code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
package org.opendatafoundation.data.spss;
/*
* Author(s): Pascal Heus (pheus@opendatafoundation.org)
*
* This product has been developed with the financial and
* technical support of the UK Data Archive Data Exchange Tools
* project (http://www.data-archive.ac.uk/dext/) and the
* Open Data Foundation (http://www.opendatafoundation.org)
*
* Copyright 2007 University of Essex (http://www.esds.ac.uk)
*
* This program 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 2.1 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 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, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
* The full text of the license is also available on the Internet at
* http://www.gnu.org/copyleft/lesser.html
*
*/
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import org.opendatafoundation.data.FileFormatInfo;
import org.opendatafoundation.data.Utils;
import org.opendatafoundation.data.ValidationReportElement;
/**
* SPSS numeric variable
*
* @author Pascal Heus (pheus@opendatafoundation.org)
*/
public class SPSSNumericVariable extends SPSSVariable {
/** a list of data values used to load the file into memory */
public List<Double> data;
/** a single data value used when reading data from disk */
public double value;
// summary statistics
public double min = Double.MAX_VALUE;
public double max = Double.MIN_VALUE;
public double mean = 0.0;
public double min_wgt = Double.MAX_VALUE;
public double max_wgt = Double.MIN_VALUE;
public double mean_wgt = 0.0;
/**
* Class constructor
*/
public SPSSNumericVariable(SPSSFile file, boolean validateEncoding,
boolean correctEncoding, List<ValidationReportElement> reportList) {
super(file, validateEncoding, correctEncoding, reportList);
data = new ArrayList<Double>();
type = VariableType.NUMERIC;
}
/**
* Adds a category to the variable based on a byte[8] value
*
* @throws SPSSFileException
*/
public SPSSVariableCategory addCategory(boolean missing, byte[] byteValue,
String label) throws SPSSFileException {
double value = SPSSUtils.byte8ToDouble(byteValue);
return (addCategory(missing, value, label));
}
/**
* Adds a category to the variable based on a double value
*
* @throws SPSSFileException
*/
public SPSSVariableCategory addCategory(boolean missing, double value,
String label) throws SPSSFileException {
Map<String, SPSSVariableCategory> map = null;
SPSSVariableCategory cat;
String strValue = valueToString(value).trim();
// add code to codeList
codeList.add(strValue);
// add cat to categoryMap indexed by code
if (missing) {
map = missingCategoryMap;
} else {
map = categoryMap;
}
cat = (SPSSVariableCategory) map.get(strValue);
if (cat == null) {
// create and add to the map
cat = new SPSSVariableCategory();
map.put(strValue, cat);
map.entrySet();
}
cat.value = value;
cat.strValue = strValue;
cat.label = label;
return (cat);
}
/**
* Gets a category for this variable based on a byte[8] value
*
* @throws SPSSFileException
*/
public SPSSVariableCategory getCategory(byte[] byteValue)
throws SPSSFileException {
double value = SPSSUtils.byte8ToDouble(byteValue);
return (getCategory(value));
}
/**
* Gets a category for this variable based on a double value
*
* @throws SPSSFileException
*/
public SPSSVariableCategory getCategory(double value)
throws SPSSFileException {
return (categoryMap.get(valueToString(value)));
}
/**
* @return A string representing variable in SPSS syntax
*/
public String getSPSSFormat() {
int width = getLength();
String formatStr = null;
switch (this.variableRecord.writeFormatType) {
case 3: // comma
formatStr = "Comma" + getLength() + "." + getDecimals();
break;
case 4: // dollar
formatStr = "Dollar" + getLength() + "." + getDecimals();
break;
case 5: // fixed format (default)
if (getDecimals() > 0) {
formatStr = "real";
} else {
formatStr = "integer";
}
// spss format
// formatStr = "F" + width + "." + getDecimals();
break;
case 17: // scientific notation
formatStr = "E" + getLength() + "." + getDecimals();
break;
case 20: // Date dd-mmm-yyyy or dd-mmm-yy
formatStr = defineSPSSFormat(width, new String[] { "hh:mm",
"dd-mmm-yyyy", "dd-mmm-yy" }, "Date" + width);
break;
case 21: // Time in hh:mm, hh:mm:ss or hh:mm:ss.ss
formatStr = defineSPSSFormat(width, new String[] { "hh:mm",
"hh:mm:ss", "hh:mm:ss.ss" }, "Time" + width + "."
+ getDecimals());
break;
case 22: // DateTime in dd-mmm-yyyy hh:mm, dd-mmm-yyyy hh:mm:ss or
// dd-mmm-yyyy hh:mm:ss.ss
formatStr = defineSPSSFormat(width, new String[] {
"dd-mmm-yyyy hh:mm", "dd-mmm-yyyy hh:mm:ss",
"dd-mmm-yyyy hh:mm:ss.ss" }, "DateTime" + width + "."
+ getDecimals());
break;
case 23: // American date
// Date in mm/dd/yy or mm/dd/yyyy
formatStr = defineSPSSFormat(width, new String[] { "mm/dd/yyyy",
"mm/dd/yy" }, "ATime" + width);
break;
case 24: // Julian date
// Date in yyyyddd or yyddd
formatStr = defineSPSSFormat(width, new String[] { "yyyyddd",
"yyddd" }, "JDate" + width);
break;
case 25: // days ad time
// DateTime in ddd:hh:mm, ddd:hh:mm:ss or ddd:hh:mm:ss.ss
formatStr = defineSPSSFormat(width, new String[] { "ddd:hh:mm",
"ddd:hh:mm:ss", "ddd:hh:mm:ss.ss" }, "DTime" + width + "."
+ getDecimals());
break;
case 26: // Date as day of the week, full name or 3-letter
formatStr = "WkDay" + getLength();
break;
case 27: // Date 3-letter month
// formatStr = "Month" + getLength();
formatStr = "mmm";
break;
case 28: // Date in mmm yyyy or mmm yy
formatStr = defineSPSSFormat(width, new String[] { "mmm yyyy",
"mmm yy" }, "Moyr" + width);
break;
case 29: // Date in q Q yyyy or q Q yy
// TODO look into W3C XML Schema's xs:dateTime datatype Duration
formatStr = "QYr" + getLength();
break;
case 30: // Week and year
// Date in wkWKyyyy or wkWKyy
formatStr = defineSPSSFormat(width, new String[] { "wkWKyyyy",
"wkWKyy" }, "Wkyr" + width);
break;
case 32: // dot
formatStr = "Dot" + getLength() + "." + getDecimals();
break;
case 33: // Custom currency A
formatStr = "Cca" + getLength() + "." + getDecimals();
break;
case 34: // Custom currency B
formatStr = "Ccb" + getLength() + "." + getDecimals();
break;
case 35: // Custom currency C
formatStr = "Ccc" + getLength() + "." + getDecimals();
break;
case 36: // Custom currency D
formatStr = "Ccd" + getLength() + "." + getDecimals();
break;
case 37: // Custom currency E
formatStr = "Cce" + getLength() + "." + getDecimals();
break;
case 38: // European date
// Date in dd.mm.yy or dd.mm.yyyy
formatStr = defineSPSSFormat(width, new String[] { "dd.mm.yy",
"dd.mm.yyyy" }, "EDate" + width);
break;
case 39: // Sorted date
// Date in yyyy/mm/dd or yy/mm/dd (?)
formatStr = defineSPSSFormat(width, new String[] { "yyyy/mm/dd",
"yy/mm/dd" }, "SDate" + width);
break;
default:
formatStr = "other";
}
return (formatStr);
}
private String defineSPSSFormat(int width, String[] options,
String defaultFormatStr) {
for (int i = 0; i < options.length; i++) {
if (width == options[i].length()) {
return options[i];
}
}
return defaultFormatStr;
}
/**
* Returns an observation value as a string based on the specified data ad
* variable format. The specified record number is used to determine which
* value is read. If a nthe observation umber is between 1 and the number of
* observation in the file is specifed and asusming the data has been loaded
* in memory, the relevant record number value is returned. If the
* observation number is 0, the variable value is retrned instead.
*
* @param obsNumber
* the record. Either 0 or between 1 and the nukber of
* observations
* @param dataFormat
* the file format
* @throws SPSSFileException
*/
public String getValueAsString(int obsNumber, FileFormatInfo dataFormat)
throws SPSSFileException {
String strValue;
double val;
// check range
if (obsNumber < 0 || obsNumber > this.data.size()) {
throw new SPSSFileException("Invalid observation number ["
+ obsNumber + ". Range is 1 to " + this.data.size()
+ "] or 0.");
}
// init value to convert
if (obsNumber == 0)
val = this.value;
else if (obsNumber > 0 && this.data.size() == 0)
throw new SPSSFileException("No data availble");
else
val = data.get(obsNumber - 1);
// convert
strValue = valueToString(val);
// format output
// length
if (dataFormat.asciiFormat == FileFormatInfo.ASCIIFormat.FIXED) {
// fixed length formats
if (strValue.equals("."))
strValue = Utils.leftPad("", this.getLength()); // replace
// missing
// values with
// spaces
else if (strValue.length() < getLength())
strValue = Utils.leftPad(strValue, this.getLength()); // left
// pad
else if (strValue.length() > getLength()) { // this value is too
// long to fit in the
// allocate space
// for fixed format, see if we can truncate the decimals (this
// is the same for SPSS fixed export)
if (this.variableRecord.writeFormatType == 5
&& this.getDecimals() > 0) {
int dotPosition = strValue.lastIndexOf(".");
// TODO: when a value is less between 1 and -1 (0.1234),
// SPSS also removes the leading zero
if (dotPosition + 2 <= getLength()) { // we can fit at least
// one decimal
strValue = String.format(
Locale.US,
"%" + this.getLength() + "."
+ (this.getLength() - dotPosition - 1)
+ "f", value);
} else if (dotPosition <= getLength()) { // we can fit the
// non-decimal
// protion
strValue = Utils.leftPad(
strValue.substring(1, dotPosition - 1),
this.getLength());
} else
strValue = Utils.leftPad("", getLength(), '*');
} else
strValue = Utils.leftPad("", getLength(), '*'); // this
// overflows
// the
// allocated
// width,
// return a
// string of
// '*'
}
} else {
// variable length formats
strValue = strValue.trim();
}
// some number formats may contain a comma
if (dataFormat.format == FileFormatInfo.Format.ASCII) {
if (dataFormat.asciiFormat == FileFormatInfo.ASCIIFormat.CSV) {
// apply numeric delimiter setting
Matcher matcher = this.spssFile.numericDelimiterPattern
.matcher(strValue);
if (matcher.find()) {
strValue = strValue.replace(
this.spssFile.numericSearchDelimiter,
this.spssFile.numericDelimiter);
}
// apply csv encoding rules
if (strValue.contains(",") || strValue.contains("\"")
|| strValue.contains("\n")) {
strValue = "\"" + strValue + "\"";
}
}
}
return (strValue);
}
/**
* Converts a numeric value (float) into a string representation based on
* the variable formnatting.
*
* @param value
* the value to format
* @return the string containing the formatted value
* @throws SPSSFileException
* if an unknown write fromat type is found
*/
public String valueToString(double value) throws SPSSFileException {
String strFormat = "";
String strValue;
int nDecimals;
GregorianCalendar calendar;
if (new Double(value).isNaN()) {
strValue = ".";
} else {
switch (this.variableRecord.writeFormatType) {
case 3: // Comma
strFormat += "%,." + this.getDecimals() + "f";
strValue = String.format(Locale.US, strFormat, value);
break;
case 4: // dollar
strFormat += "$%." + this.getDecimals() + "f";
strValue = String.format(Locale.US, strFormat, value);
break;
case 5: // fixed format (default)
strFormat += "%" + this.getLength() + "." + this.getDecimals()
+ "f";
strValue = String.format(Locale.US, strFormat, value);
break;
case 17: // scientific notation
nDecimals = this.getDecimals();
if (nDecimals > 0)
nDecimals--; // remove one decimal for the sign
strFormat += "% " + this.getLength() + "." + nDecimals + "E";
strValue = String.format(Locale.US, strFormat, value);
break;
case 20: // Date dd-mmm-yyyy or dd-mmm-yy
calendar = SPSSUtils.numericToCalendar(value);
if (this.getLength() == 11)
strFormat += "%1$td-%1$tb-%1$tY";
else
strFormat += "%1$td-%1$tb-%1$ty";
strValue = String.format(Locale.US, strFormat, calendar)
.toUpperCase();
break;
case 21: // Time in hh:mm, hh:mm:ss or hh:mm:ss.ss
calendar = SPSSUtils.numericToCalendar(value);
strFormat += "%1$tH:%1$tM";
if (this.getLength() >= 8)
strFormat += ":%1$tS";
if (this.getLength() == 11)
strFormat += ".%2$2d"; // we add the 2-digit for 1/100 sec
// as extra parameter (Formatter and
// Calendar use 3 digits
// milliseconds)
// TODO: add .ss for width=11
strValue = String.format(Locale.US, strFormat, calendar,
calendar.get(Calendar.MILLISECOND) / 10).toUpperCase();
break;
case 22: // DateTime in dd-mmm-yyyy hh:mm, dd-mmm-yyyy hh:mm:ss or
// dd-mmm-yyyy hh:mm:ss.ss
calendar = SPSSUtils.numericToCalendar(value);
strFormat += "%1$td-%1$tb-%1$tY %1$tH:%1$tM";
if (this.getLength() >= 20)
strFormat += ":%1$tS";
if (this.getLength() == 23)
strFormat += ".%2$2d";
strValue = String.format(Locale.US, strFormat, calendar,
calendar.get(Calendar.MILLISECOND) / 10).toUpperCase();
break;
case 23: // Date in mm/dd/yy or mm/dd/yyyy
calendar = SPSSUtils.numericToCalendar(value);
if (this.getLength() == 10)
strFormat += "%1$tm/%1$td/%1$tY";
else
strFormat += "%1$tm/%1$td/%1$ty";
strValue = String.format(Locale.US, strFormat, calendar);
break;
case 24: // Date in yyyyddd or yyddd
calendar = SPSSUtils.numericToCalendar(value);
if (this.getLength() == 7)
strFormat += "%1$tY%1$tj";
else
strFormat += "%1$ty%1$tj";
strValue = String.format(Locale.US, strFormat, calendar);
break;
case 25: // DateTime in ddd:hh:mm, ddd:hh:mm:ss or ddd:hh:mm:ss.ss
calendar = SPSSUtils.numericToCalendar(value);
strFormat += "%1$tj:%1$tH:%1$tM";
if (this.getLength() >= 12)
strFormat += ":%1$tS";
if (this.getLength() == 15)
strFormat += ".%2$2d";
strValue = String.format(Locale.US, strFormat, calendar,
calendar.get(Calendar.MILLISECOND) / 10);
break;
case 26: // Date as day of the week, full name or 3-letter
calendar = new GregorianCalendar();
calendar.set(Calendar.DAY_OF_WEEK, (int) value);
if (this.getLength() == 9)
strFormat += "%1$tA";
else
strFormat += "%1$ta";
strValue = String.format(Locale.US, strFormat, calendar)
.toUpperCase(); // upper case to match SPSS export
break;
case 27: // Date 3-letter month
calendar = new GregorianCalendar();
calendar.set(Calendar.MONTH, (int) value - 1); // January is 0
// in Java
strFormat += "%1$tb";
strValue = String.format(Locale.US, strFormat, calendar)
.toUpperCase(); // upper case to match SPSS export
break;
case 28: // Date in mmm yyyy or mmm yy
calendar = SPSSUtils.numericToCalendar(value);
if (this.getLength() == 8)
strFormat += "%1$tb %1$tY";
else
strFormat += "%1$tb %1$ty";
strValue = String.format(Locale.US, strFormat, calendar)
.toUpperCase();
break;
case 29: // Date in q Q yyyy or q Q yy
calendar = SPSSUtils.numericToCalendar(value);
if (calendar.get(Calendar.MONTH) <= 3)
strFormat += "1 Q ";
else if (calendar.get(Calendar.MONTH) <= 6)
strFormat += "2 Q ";
else if (calendar.get(Calendar.MONTH) <= 9)
strFormat += "3 Q ";
else
strFormat += "4 Q";
if (this.getLength() == 8)
strFormat += "%1$tY";
else
strFormat += "%1$ty";
strValue = String.format(Locale.US, strFormat, calendar);
break;
case 30: // Date in wk WK yyyy or wk WK yy
calendar = SPSSUtils.numericToCalendar(value);
if (this.getLength() == 10)
strFormat += "%1$2d WK %2$tY";
else
strFormat += "%1$2d WK %2$ty";
strValue = String.format(Locale.US, strFormat,
calendar.get(Calendar.WEEK_OF_YEAR), calendar);
break;
case 32: // Dot (use Germany locale, for some reasonm french does
// not display the dot thousand separator)
strFormat += "%,." + this.getDecimals() + "f";
strValue = String.format(Locale.GERMANY, strFormat, value);
break;
case 33: // custom currency A
case 34: // custom currency B
case 35: // custom currency C
case 36: // custom currency D
case 37: // custom currency E
strFormat += "%" + this.getLength() + "." + this.getDecimals()
+ "f";
strValue = String.format(Locale.US, strFormat, value);
break;
case 38: // Date in dd.mm.yy or dd.mm.yyyy
calendar = SPSSUtils.numericToCalendar(value);
if (this.getLength() == 10)
strFormat += "%1$td.%1$tm.%1$tY";
else
strFormat += "%1$td.%1$tm.%1$ty";
strValue = String.format(Locale.US, strFormat, calendar);
break;
case 39: // Date in yy/mm/dd or yyyy/mm/dd
calendar = SPSSUtils.numericToCalendar(value);
if (this.getLength() == 10)
strFormat += "%1$tY/%1$tm/%1$td";
else
strFormat += "%1$ty/%1$tm/%1$td";
strValue = String.format(Locale.US, strFormat, calendar);
break;
default:
throw new SPSSFileException("Unknown write format type ["
+ this.variableRecord.writeFormatType + "]");
}
}
return (strValue);
}
@Override
public byte[] getValueAsByteArray(int recordNumber,
FileFormatInfo dataFormat) throws SPSSFileException {
return getValueAsString(0, dataFormat).replaceAll("\\s+", "")
.getBytes();
}
}
|
DdiEditor/ddieditor-spss
|
src/org/opendatafoundation/data/spss/SPSSNumericVariable.java
|
Java
|
lgpl-3.0
| 19,392
|
/*--------------------------------------------------------------------
(C) Copyright 2006-2013 Barcelona Supercomputing Center
Centro Nacional de Supercomputacion
This file is part of Mercurium C/C++ source-to-source compiler.
See AUTHORS file in the top level directory for information
regarding developers and contributors.
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.
Mercurium C/C++ source-to-source compiler 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 Mercurium C/C++ source-to-source compiler; if
not, write to the Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA.
--------------------------------------------------------------------*/
#include "codegen-cxx.hpp"
#include "codegen-prune.hpp"
#include "tl-objectlist.hpp"
#include "tl-type.hpp"
#include "cxx-cexpr.h"
#include "cxx-entrylist.h"
#include "string_utils.h"
#include "tl-compilerpipeline.hpp"
#include <iomanip>
#ifdef HAVE_QUADMATH_H
MCXX_BEGIN_DECLS
#include <quadmath.h>
MCXX_END_DECLS
#endif
#include "cxx-printscope.h"
namespace Codegen {
std::string CxxBase::codegen(const Nodecl::NodeclBase &n)
{
if (n.is_null())
return "";
// Keep the state and reset it
State old_state = state;
state = State();
state.nontype_template_argument_needs_parentheses =
old_state.nontype_template_argument_needs_parentheses;
decl_context_t decl_context = this->get_current_scope().get_decl_context();
state.global_namespace = decl_context.global_scope->related_entry;
state.opened_namespace = decl_context.namespace_scope->related_entry;
state.emit_declarations = this->is_file_output() ? State::EMIT_ALL_DECLARATIONS : State::EMIT_NO_DECLARATIONS;
std::string old_file = file.str();
file.clear();
file.str("");
walk(n);
// Make sure the starting namespace is closed
codegen_move_namespace_from_to(state.opened_namespace, decl_context.namespace_scope->related_entry);
std::string result = file.str();
// Restore previous state
state = old_state;
file.str(old_file);
file.seekp(0, std::ios_base::end);
return result;
}
void CxxBase::push_scope(TL::Scope sc)
{
_scope_stack.push_back(sc);
}
void CxxBase::pop_scope()
{
_scope_stack.pop_back();
}
void CxxBase::codegen_cleanup()
{
// In some cases, we use the same codegen object to compile one or more
// sources (for example, it happens in ompss transformation). For this
// reason, we need to restore the codegen status of every symbol.
_codegen_status.clear();
}
void CxxBase::handle_parameter(int n, void* data)
{
switch (n)
{
case CODEGEN_PARAM_NONTYPE_TEMPLATE_ARGUMENT:
{
ERROR_CONDITION(data == NULL, "data cannot be NULL\n", 0);
state.nontype_template_argument_needs_parentheses = *((char *)data);
break;
};
default:
{
internal_error("undefined codegen parameter\n", 0);
break;
};
}
}
TL::Scope CxxBase::get_current_scope() const
{
return _scope_stack.back();
}
#define OPERATOR_TABLE \
PREFIX_UNARY_EXPRESSION(Plus, " +") \
PREFIX_UNARY_EXPRESSION(Neg, " -") \
PREFIX_UNARY_EXPRESSION(LogicalNot, "!") \
PREFIX_UNARY_EXPRESSION(BitwiseNot, "~") \
PREFIX_UNARY_EXPRESSION(Dereference, "*") \
PREFIX_UNARY_EXPRESSION(Preincrement, "++") \
PREFIX_UNARY_EXPRESSION(Predecrement, "--") \
PREFIX_UNARY_EXPRESSION(Delete, "delete ") \
PREFIX_UNARY_EXPRESSION(DeleteArray, "delete[] ") \
PREFIX_UNARY_EXPRESSION(RealPart, "__real__ ") \
PREFIX_UNARY_EXPRESSION(ImagPart, "__imag__ ") \
POSTFIX_UNARY_EXPRESSION(Postincrement, "++") \
POSTFIX_UNARY_EXPRESSION(Postdecrement, "--") \
BINARY_EXPRESSION(Add, " + ") \
BINARY_EXPRESSION(Mul, " * ") \
BINARY_EXPRESSION(Div, " / ") \
BINARY_EXPRESSION(Mod, " % ") \
BINARY_EXPRESSION(Minus, " - ") \
BINARY_EXPRESSION(Equal, " == ") \
BINARY_EXPRESSION(Different, " != ") \
BINARY_EXPRESSION(LowerThan, " < ") \
BINARY_EXPRESSION(LowerOrEqualThan, " <= ") \
BINARY_EXPRESSION_EX(GreaterThan, " > ") \
BINARY_EXPRESSION_EX(GreaterOrEqualThan, " >= ") \
BINARY_EXPRESSION(LogicalAnd, " && ") \
BINARY_EXPRESSION(LogicalOr, " || ") \
BINARY_EXPRESSION(BitwiseAnd, " & ") \
BINARY_EXPRESSION(BitwiseOr, " | ") \
BINARY_EXPRESSION(BitwiseXor, " ^ ") \
BINARY_EXPRESSION(BitwiseShl, " << ") \
BINARY_EXPRESSION_EX(BitwiseShr, " >> ") \
BINARY_EXPRESSION_EX(ArithmeticShr, " >> ") \
BINARY_EXPRESSION_ASSIG(Assignment, " = ") \
BINARY_EXPRESSION_ASSIG(MulAssignment, " *= ") \
BINARY_EXPRESSION_ASSIG(DivAssignment, " /= ") \
BINARY_EXPRESSION_ASSIG(AddAssignment, " += ") \
BINARY_EXPRESSION_ASSIG(MinusAssignment, " -= ") \
BINARY_EXPRESSION_ASSIG(BitwiseShlAssignment, " <<= ") \
BINARY_EXPRESSION_ASSIG_EX(BitwiseShrAssignment, " >>= ") \
BINARY_EXPRESSION_ASSIG_EX(ArithmeticShrAssignment, " >>= ") \
BINARY_EXPRESSION_ASSIG(BitwiseAndAssignment, " &= ") \
BINARY_EXPRESSION_ASSIG(BitwiseOrAssignment, " |= ") \
BINARY_EXPRESSION_ASSIG(BitwiseXorAssignment, " ^= ") \
BINARY_EXPRESSION_ASSIG(ModAssignment, " %= ") \
BINARY_EXPRESSION(Offset, ".*") \
BINARY_EXPRESSION(CxxDotPtrMember, ".*") \
BINARY_EXPRESSION(CxxArrowPtrMember, "->*") \
#define PREFIX_UNARY_EXPRESSION(_name, _operand) \
void CxxBase::visit(const Nodecl::_name &node) \
{ \
Nodecl::NodeclBase rhs = node.children()[0]; \
char needs_parentheses = operand_has_lower_priority(node, rhs); \
file << _operand; \
if (needs_parentheses) \
{ \
file << "("; \
} \
walk(rhs); \
if (needs_parentheses) \
{ \
file << ")"; \
} \
}
bool CxxBase::is_non_language_reference_type(TL::Type type)
{
return this->is_file_output()
&& ((IS_C_LANGUAGE && type.is_any_reference())
|| (IS_CXX_LANGUAGE && type.is_rebindable_reference()));
}
bool CxxBase::is_non_language_reference_variable(TL::Symbol sym)
{
return is_non_language_reference_type(sym.get_type());
}
bool CxxBase::is_non_language_reference_variable(const Nodecl::NodeclBase &n)
{
if (n.get_symbol().is_valid())
{
return is_non_language_reference_variable(n.get_symbol());
}
return false;
}
void CxxBase::visit(const Nodecl::Reference &node)
{
Nodecl::NodeclBase rhs = node.get_rhs();
char needs_parentheses = operand_has_lower_priority(node, rhs);
bool old_do_not_derref_rebindable_ref = state.do_not_derref_rebindable_reference;
if (rhs.get_type().is_rebindable_reference())
{
state.do_not_derref_rebindable_reference = true;
}
else if (is_non_language_reference_variable(rhs))
{
state.do_not_derref_rebindable_reference = true;
// Emit a casting here
file << "(" << this->get_declaration(node.get_type(), this->get_current_scope(), "") << ") ";
}
else
{
file << "&";
}
if (needs_parentheses)
{
file << "(";
}
walk(rhs);
if (needs_parentheses)
{
file << ")";
}
state.do_not_derref_rebindable_reference = old_do_not_derref_rebindable_ref;
}
#define POSTFIX_UNARY_EXPRESSION(_name, _operand) \
void CxxBase::visit(const Nodecl::_name& node) \
{ \
Nodecl::NodeclBase rhs = node.children()[0]; \
char needs_parentheses = operand_has_lower_priority(node, rhs); \
if (needs_parentheses) \
{ \
file << "("; \
} \
walk(rhs); \
if (needs_parentheses) \
{ \
file << ")"; \
} \
file << _operand; \
}
#define BINARY_EXPRESSION(_name, _operand) \
void CxxBase::visit(const Nodecl::_name& node) \
{ \
BINARY_EXPRESSION_IMPL(_name, _operand) \
}
#define BINARY_EXPRESSION_IMPL(_name, _operand) \
Nodecl::NodeclBase lhs = node.children()[0]; \
Nodecl::NodeclBase rhs = node.children()[1]; \
char needs_parentheses = operand_has_lower_priority(node, lhs); \
if (needs_parentheses) \
{ \
file << "("; \
} \
walk(lhs); \
if (needs_parentheses) \
{ \
file << ")"; \
} \
file << _operand; \
needs_parentheses = operand_has_lower_priority(node, rhs) || same_operation(node, rhs); \
if (needs_parentheses) \
{ \
file << "("; \
} \
walk(rhs); \
if (needs_parentheses) \
{ \
file << ")"; \
}
// In some cases (i. e. when the operator of a binary expression contains the
// character '>') nontype template arguments may need an extra parentheses
// Example:
// template < bool b>
// struct A {};
// A < (3 > 2) > a;
#define BINARY_EXPRESSION_EX(_name, _operand) \
void CxxBase::visit(const Nodecl::_name& node) \
{ \
if (state.nontype_template_argument_needs_parentheses) \
{\
file << "("; \
}\
BINARY_EXPRESSION_IMPL(_name, _operand) \
if (state.nontype_template_argument_needs_parentheses) \
{\
file << ")"; \
}\
}
#define BINARY_EXPRESSION_ASSIG(_name, _operand) \
void CxxBase::visit(const Nodecl::_name& node) \
{ \
BINARY_EXPRESSION_ASSIG_IMPL(_name, _operand) \
}
#define BINARY_EXPRESSION_ASSIG_IMPL(_name, _operand) \
Nodecl::NodeclBase lhs = node.children()[0]; \
Nodecl::NodeclBase rhs = node.children()[1]; \
if (state.in_condition && state.condition_top == node) \
{ \
file << "("; \
} \
char needs_parentheses = operand_has_lower_priority(node, lhs) || same_operation(node, lhs); \
if (needs_parentheses) \
{ \
file << "("; \
} \
walk(lhs); \
if (needs_parentheses) \
{ \
file << ")"; \
} \
file << _operand; \
needs_parentheses = operand_has_lower_priority(node, rhs); \
if (needs_parentheses) \
{ \
file << "("; \
} \
walk(rhs); \
if (needs_parentheses) \
{ \
file << ")"; \
} \
if (state.in_condition && state.condition_top == node) \
{ \
file << ")"; \
} \
// In some cases (i. e. when the operator of a binary expression assignment
// contains the character '>') nontype template arguments may need an extra
// parentheses
#define BINARY_EXPRESSION_ASSIG_EX(_name, _operand) \
void CxxBase::visit(const Nodecl::_name& node) \
{ \
if (state.nontype_template_argument_needs_parentheses) \
{\
file << "("; \
}\
BINARY_EXPRESSION_ASSIG_IMPL(_name, _operand) \
if (state.nontype_template_argument_needs_parentheses) \
{\
file << ")"; \
}\
}
OPERATOR_TABLE
#undef POSTFIX_UNARY_EXPRESSION
#undef PREFIX_UNARY_EXPRESSION
#undef BINARY_EXPRESSION
#undef BINARY_EXPRESSION_IMPL
#undef BINARY_EXPRESSION_EX
#undef BINARY_EXPRESSION_ASSIG
#undef BINARY_EXPRESSION_ASSIG_IMPL
#undef BINARY_EXPRESSION_ASSIG_EX
CxxBase::Ret CxxBase::visit(const Nodecl::ArraySubscript& node)
{
Nodecl::NodeclBase subscripted = node.get_subscripted();
Nodecl::List subscript = node.get_subscripts().as<Nodecl::List>();
if (operand_has_lower_priority(node, subscripted))
{
file << "(";
}
walk(subscripted);
if (operand_has_lower_priority(node, subscripted))
{
file << ")";
}
// We keep a list instead of a single dimension for multidimensional arrays
// alla Fortran
for(Nodecl::List::iterator it = subscript.begin();
it != subscript.end();
it++)
{
file << "[";
walk(*it);
file << "]";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::BooleanLiteral& node)
{
const_value_t* val = nodecl_get_constant(node.get_internal_nodecl());
if (const_value_is_zero(val))
{
file << "false";
}
else
{
file << "true";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::BreakStatement& node)
{
indent();
file << "break;\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::C99DesignatedInitializer& node)
{
walk(node.get_designation());
file << " = ";
walk(node.get_init());
}
CxxBase::Ret CxxBase::visit(const Nodecl::C99FieldDesignator& node)
{
file << ".";
walk(node.get_name());
}
CxxBase::Ret CxxBase::visit(const Nodecl::C99IndexDesignator& node)
{
file << "[";
walk(node.get_expr());
file << "]";
}
CxxBase::Ret CxxBase::visit(const Nodecl::CaseStatement& node)
{
Nodecl::NodeclBase expression = node.get_case();
Nodecl::NodeclBase statement = node.get_statement();
indent();
file << "case ";
walk(expression);
file << " :\n";
walk(statement);
}
CxxBase::Ret CxxBase::visit(const Nodecl::Cast& node)
{
std::string cast_kind = node.get_text();
TL::Type t = fix_references(node.get_type());
Nodecl::NodeclBase nest = node.get_rhs();
if (IS_C_LANGUAGE
|| cast_kind == "C")
{
bool is_non_ref = is_non_language_reference_type(node.get_type());
if (is_non_ref)
{
if (node.get_type().no_ref().is_array())
{
// Special case for arrays, themselves are an address
file << "(";
}
else
{
file << "(*";
}
// This avoids a warning in some compilers which complain on (T* const)e
t = t.get_unqualified_type();
}
file << "(" << this->get_declaration(t, this->get_current_scope(), "") << ")";
if (is_non_ref)
{
file << "&(";
}
char needs_parentheses = operand_has_lower_priority(node, nest);
if (needs_parentheses)
{
file << "(";
}
walk(nest);
if (needs_parentheses)
{
file << ")";
}
if (is_non_ref)
{
file << "))";
}
}
else
{
std::string decl = this->get_declaration(t, this->get_current_scope(), "");
if (decl[0] == ':')
{
decl = " " + decl;
}
file << cast_kind << "<" << decl << ">(";
walk(nest);
file << ")";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::CatchHandler& node)
{
Nodecl::NodeclBase name = node.get_name();
Nodecl::NodeclBase statement = node.get_statement();
TL::Type type = node.get_type();
indent();
file << "catch (";
if (name.is_null())
{
// FIXME: Is this always safe?
file << this->get_declaration(type, this->get_current_scope(), "");
}
else
{
int old_condition = state.in_condition;
Nodecl::NodeclBase old_condition_top = state.condition_top;
int old_indent = get_indent_level();
set_indent_level(0);
state.in_condition = 1;
state.condition_top = name;
walk(name);
set_indent_level(old_indent);
state.condition_top = old_condition_top;
state.in_condition = old_condition;
}
file << ")\n";
walk(statement);
}
CxxBase::Ret CxxBase::visit(const Nodecl::ClassMemberAccess& node)
{
Nodecl::NodeclBase lhs = node.get_lhs();
Nodecl::NodeclBase rhs = node.get_member();
Nodecl::NodeclBase member_form = node.get_member_form();
TL::Symbol sym = rhs.get_symbol();
/*
* .
* / \
* . c
* / \
* a <<anon>>
*
* We want a.<<anon>>.c become a.c
*/
bool is_anonymous_union_accessor = sym.is_valid()
&& sym.get_type().is_named_class()
&& sym.get_type().get_symbol().is_anonymous_union();
bool must_derref_all = (sym.is_valid()
&& is_non_language_reference_variable(sym)
&& !sym.get_type().references_to().is_array()
&& !state.do_not_derref_rebindable_reference);
bool old_do_not_derref_rebindable_ref = state.do_not_derref_rebindable_reference;
if (must_derref_all)
{
file << "(*";
}
char needs_parentheses = operand_has_lower_priority(node, lhs);
if (needs_parentheses)
{
file << "(";
}
// Left hand side does not care about the top level reference status
state.do_not_derref_rebindable_reference = false;
walk(lhs);
if (needs_parentheses)
{
file << ")";
}
if (!is_anonymous_union_accessor)
{
// Right part can be a reference but we do not want to derref it
state.do_not_derref_rebindable_reference = true;
file << "."
<< /* template tag if needed */ node.get_text();
needs_parentheses = operand_has_lower_priority(node, rhs);
if (needs_parentheses)
{
file << "(";
}
// This will only emit the unqualified name
TL::Symbol rhs_symbol = rhs.get_symbol();
if (!rhs_symbol.is_valid()
|| (!member_form.is_null()
&& member_form.is<Nodecl::CxxMemberFormQualified>()))
{
// This will print the qualified name
walk(rhs);
}
else
{
// Simply print the name
file << rhs_symbol.get_name();
}
if (needs_parentheses)
{
file << ")";
}
state.do_not_derref_rebindable_reference = old_do_not_derref_rebindable_ref;
}
if (must_derref_all)
{
file << ")";
}
}
void CxxBase::visit(const Nodecl::Comma & node)
{
file << "(";
Nodecl::NodeclBase lhs = node.children()[0];
Nodecl::NodeclBase rhs = node.children()[1];
if (state.in_condition && state.condition_top == node)
{
file << "(";
}
char needs_parentheses = operand_has_lower_priority(node, lhs) || same_operation(node, lhs);
if (needs_parentheses)
{
file << "(";
}
walk(lhs);
if (needs_parentheses)
{
file << ")";
}
file << ", ";
needs_parentheses = operand_has_lower_priority(node, rhs);
if (needs_parentheses)
{
file << "(";
}
walk(rhs);
if (needs_parentheses)
{
file << ")";
}
if (state.in_condition && state.condition_top == node)
{
file << ")";
}
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::ComplexLiteral& node)
{
const_value_t* cval = node.get_constant();
const_value_t* real_part = const_value_complex_get_real_part(cval);
const_value_t* imag_part = const_value_complex_get_imag_part(cval);
ERROR_CONDITION(!const_value_is_zero(real_part), "Invalid complex constant in C with nonzero real component", 0);
if (const_value_is_integer(imag_part))
{
emit_integer_constant(imag_part, node.get_type().complex_get_base_type());
}
else if (const_value_is_floating(imag_part))
{
emit_floating_constant(imag_part, node.get_type().complex_get_base_type());
}
else
{
internal_error("Code unreachable", 0);
}
file << "i";
}
CxxBase::Ret CxxBase::visit(const Nodecl::CompoundExpression& node)
{
file << " (";
Nodecl::Context context = node.get_nest().as<Nodecl::Context>();
Nodecl::List statements = context.get_in_context().as<Nodecl::List>();
this->push_scope(context.retrieve_context());
file << "{\n";
inc_indent();
State::EmitDeclarations emit_declarations = state.emit_declarations;
if (state.emit_declarations == State::EMIT_NO_DECLARATIONS)
state.emit_declarations = State::EMIT_CURRENT_SCOPE_DECLARATIONS;
bool in_condition = state.in_condition;
state.in_condition = 0;
ERROR_CONDITION(statements.size() != 1, "In C/C++ blocks only have one statement", 0);
ERROR_CONDITION(!statements[0].is<Nodecl::CompoundStatement>(), "Invalid statement", 0);
Nodecl::NodeclBase statement_seq = statements[0].as<Nodecl::CompoundStatement>().get_statements();
define_local_entities_in_trees(statement_seq);
walk(statement_seq);
state.in_condition = in_condition;
state.emit_declarations = emit_declarations;
dec_indent();
indent();
file << "}";
this->pop_scope();
file << ") ";
}
CxxBase::Ret CxxBase::visit(const Nodecl::CompoundStatement& node)
{
indent();
file << "{\n";
inc_indent();
State::EmitDeclarations emit_declarations = state.emit_declarations;
if (state.emit_declarations == State::EMIT_NO_DECLARATIONS)
state.emit_declarations = State::EMIT_CURRENT_SCOPE_DECLARATIONS;
Nodecl::NodeclBase statement_seq = node.get_statements();
define_local_entities_in_trees(statement_seq);
walk(statement_seq);
state.emit_declarations = emit_declarations;
dec_indent();
indent();
file << "}\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::ConditionalExpression& node)
{
Nodecl::NodeclBase cond = node.get_condition();
Nodecl::NodeclBase then = node.get_true();
Nodecl::NodeclBase _else = node.get_false();
if (get_rank(cond) < get_rank_kind(NODECL_LOGICAL_OR, ""))
{
// This expression is a logical-or-expression, so an assignment (or comma)
// needs parentheses
file << "(";
}
walk(cond);
if (get_rank(cond) < get_rank_kind(NODECL_LOGICAL_OR, ""))
{
file << ")";
}
file << " ? ";
// This is a top level expression, no parentheses should be required
walk(then);
file << " : ";
if (get_rank(cond) < get_rank_kind(NODECL_ASSIGNMENT, ""))
{
// Only comma operator could get here actually
file << "(";
}
walk(_else);
if (get_rank(cond) < get_rank_kind(NODECL_ASSIGNMENT, ""))
{
file << ")";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::Context& node)
{
this->push_scope(node.retrieve_context());
walk(node.get_in_context());
this->pop_scope();
}
CxxBase::Ret CxxBase::visit(const Nodecl::ContinueStatement& node)
{
indent();
file << "continue;\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::Conversion& node)
{
// Do nothing
walk(node.get_nest());
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxArrow& node)
{
Nodecl::NodeclBase lhs = node.get_lhs();
Nodecl::NodeclBase rhs = node.get_member();
char needs_parentheses = operand_has_lower_priority(node, lhs);
if (needs_parentheses)
{
file << "(";
}
walk(lhs);
if (needs_parentheses)
{
file << ")";
}
file << "->"
<< /* template tag if needed */ node.get_text();
needs_parentheses = operand_has_lower_priority(node, rhs);
if (needs_parentheses)
{
file << "(";
}
walk(rhs);
if (needs_parentheses)
{
file << ")";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxBracedInitializer& node)
{
file << "{ ";
if (!node.get_init().is_null())
{
walk_list(node.get_init().as<Nodecl::List>(), ", ");
}
file << " }";
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxDepGlobalNameNested& node)
{
file << "::";
visit(node.as<Nodecl::CxxDepNameNested>());
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxDepNameConversion& node)
{
file << "operator " << this->get_declaration(node.get_type(), this->get_current_scope(), "");
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxDepNameNested& node)
{
walk_list(node.get_items().as<Nodecl::List>(), "::");
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxDepNameSimple& node)
{
file << node.get_text();
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxDepTemplateId& node)
{
file << node.get_text();
walk(node.get_name());
TL::TemplateParameters tpl = node.get_template_parameters();
file << ::template_arguments_to_str(
tpl.get_internal_template_parameter_list(),
/* first_template_argument_to_be_printed */ 0,
/* print_first_level_bracket */ 1,
this->get_current_scope().get_decl_context());
// The function 'template_arguments_to_str' does not print anything when
// template arguments are empty. For this reason, we add the empty list '<>'
if (tpl.get_num_parameters() == 0)
{
file << "<>";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxInitializer& node)
{
walk(node.get_init());
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxEqualInitializer& node)
{
file << " = ";
walk(node.get_init());
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxMemberInit& node)
{
walk(node.get_name());
walk(node.get_initializer());
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxExplicitTypeCast& node)
{
TL::Type t = node.get_type();
file << this->get_declaration(t, this->get_current_scope(), "");
walk(node.get_init_list());
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxParenthesizedInitializer& node)
{
file << "(";
if (!node.get_init().is_null())
{
walk_expression_list(node.get_init().as<Nodecl::List>());
}
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxAlignof& node)
{
if (IS_CXX1X_LANGUAGE)
{
file << "alignof(";
}
else
{
file << "__alignof__(";
}
walk(node.get_expr());
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxSizeof& node)
{
file << "sizeof(";
walk(node.get_expr());
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::DefaultArgument& node)
{
internal_error("Code unreachable", 0);
}
CxxBase::Ret CxxBase::visit(const Nodecl::DefaultStatement& node)
{
Nodecl::NodeclBase statement = node.get_statement();
indent();
file << "default :\n";
walk(statement);
}
CxxBase::Ret CxxBase::visit(const Nodecl::DoStatement& node)
{
Nodecl::NodeclBase statement = node.get_statement();
Nodecl::NodeclBase condition = node.get_condition();
indent();
file << "do\n";
inc_indent();
walk(statement);
dec_indent();
indent();
file << "while (";
walk(condition);
file << ");\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::EmptyStatement& node)
{
indent();
file << ";\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::ErrExpr& node)
{
if (!this->is_file_output())
{
file << "<<error expression>>";
}
else
{
internal_error("%s: error: <<error expression>> found when the output is a file",
node.get_locus_str().c_str());
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::ExpressionStatement& node)
{
Nodecl::NodeclBase expression = node.get_nest();
indent();
walk(expression);
file << ";\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::FieldDesignator& node)
{
Nodecl::NodeclBase field = node.get_field();
Nodecl::NodeclBase next = node.get_next();
if (IS_CXX_LANGUAGE)
{
file << " /* ";
}
file << ".";
walk(field);
if (!next.is<Nodecl::FieldDesignator>()
&& !next.is<Nodecl::IndexDesignator>())
{
file << " = ";
}
if (IS_CXX_LANGUAGE)
{
file << " */ ";
}
walk(next);
}
void CxxBase::emit_floating_constant(const_value_t* cval, TL::Type t)
{
int precision = floating_type_get_info(t.get_internal_type())->p + 1;
// FIXME - We are relying on a (really handy) GNU extension
if (const_value_is_float(cval))
{
const char* floating = NULL;
uniquestr_sprintf(&floating, "%.*ef", precision, const_value_cast_to_float(cval));
file << floating;
}
else if (const_value_is_double(cval))
{
const char* floating = NULL;
uniquestr_sprintf(&floating, "%.*e", precision, const_value_cast_to_double(cval));
file << floating;
}
else if (const_value_is_long_double(cval))
{
const char* floating = NULL;
uniquestr_sprintf(&floating, "%.*LeL", precision, const_value_cast_to_long_double(cval));
file << floating;
}
#ifdef HAVE_QUADMATH_H
else if (const_value_is_float128(cval))
{
__float128 f128 = const_value_cast_to_float128(cval);
int n = quadmath_snprintf (NULL, 0, "%.*Qe", precision, f128);
char *c = new char[n + 1];
quadmath_snprintf (c, n, "%.*Qe", precision, f128);
c[n] = '\0';
file << c << "Q";
delete[] c;
}
#endif
}
CxxBase::Ret CxxBase::visit(const Nodecl::FloatingLiteral& node)
{
const_value_t* value = nodecl_get_constant(node.get_internal_nodecl());
ERROR_CONDITION(value == NULL, "Invalid value", 0);
emit_floating_constant(value, nodecl_get_type(node.get_internal_nodecl()));
}
void CxxBase::emit_range_loop_header(
Nodecl::RangeLoopControl lc,
Nodecl::NodeclBase statement,
const std::string& rel_op)
{
TL::Symbol ind_var = lc.get_induction_variable().get_symbol();
std::string ind_var_name = this->get_qualified_name(ind_var);
indent();
file << "for (";
// I = L
file << ind_var_name;
file << " = ";
walk(lc.get_lower());
file << "; ";
// I <= L (or I >= L)
file << ind_var_name << rel_op;
walk(lc.get_upper());
file << "; ";
// I += S
file << ind_var_name << " += ";
if (!lc.get_step().is_null())
walk(lc.get_step());
else
file << "1";
file << ")\n";
inc_indent();
walk(statement);
dec_indent();
}
CxxBase::Ret CxxBase::visit(const Nodecl::ForStatement& node)
{
Nodecl::NodeclBase loop_control = node.get_loop_header();
Nodecl::NodeclBase statement = node.get_statement();
if (loop_control.is<Nodecl::LoopControl>())
{
indent();
file << "for (";
walk(loop_control);
file << ")\n";
inc_indent();
walk(statement);
dec_indent();
}
else if (loop_control.is<Nodecl::UnboundedLoopControl>())
{
// This only happens for DO without loop-control
indent();
file << "for (;;)\n";
inc_indent();
walk(statement);
dec_indent();
}
else if (loop_control.is<Nodecl::RangeLoopControl>())
{
Nodecl::RangeLoopControl lc = loop_control.as<Nodecl::RangeLoopControl>();
Nodecl::NodeclBase lower = lc.get_lower();
Nodecl::NodeclBase upper = lc.get_upper();
Nodecl::NodeclBase step = lc.get_step();
if (step.is_null()
|| step.is_constant())
{
std::string rel_op = " <= ";
const_value_t* v = NULL;
if (step.is_null())
{
v = const_value_get_signed_int(1);
}
else
{
v = step.get_constant();
}
if (const_value_is_negative(v))
{
rel_op = " >= ";
}
emit_range_loop_header(lc, statement, rel_op);
}
else
{
indent();
file << "if (";
walk(step);
file << "> 0)\n;";
inc_indent();
indent();
file << "{\n";
inc_indent();
emit_range_loop_header(lc, statement, " <= ");
dec_indent();
indent();
file << "}\n";
dec_indent();
indent();
file << "else\n";
inc_indent();
indent();
file << "{\n";
inc_indent();
emit_range_loop_header(lc, statement, " >= ");
dec_indent();
indent();
file << "}\n";
dec_indent();
}
}
else
{
internal_error("Code unreachable", 0);
}
}
template <typename Iterator>
CxxBase::Ret CxxBase::codegen_function_call_arguments(
Iterator begin,
Iterator end,
TL::Type function_type,
int ignore_n_first)
{
bool has_ellipsis = 0;
TL::ObjectList<TL::Type> parameters_type = function_type.parameters(has_ellipsis);
TL::ObjectList<TL::Type>::iterator type_it = parameters_type.begin();
TL::ObjectList<TL::Type>::iterator type_end = parameters_type.end();
Iterator arg_it = begin;
while (arg_it != end
&& ignore_n_first > 0)
{
arg_it++;
if (type_it != type_end)
type_it++;
ignore_n_first--;
}
// Update begin if we have ignored any argument
begin = arg_it;
bool default_arguments = false;
while (arg_it != end)
{
Nodecl::NodeclBase actual_arg = *arg_it;
if (actual_arg.is<Nodecl::DefaultArgument>())
{
// Default arguments are printed in a comment
if (!default_arguments)
{
file << "/* ";
default_arguments = true;
}
actual_arg = actual_arg.as<Nodecl::DefaultArgument>().get_argument();
}
if (arg_it != begin)
{
file << ", ";
}
bool old_do_not_derref_rebindable_ref = state.do_not_derref_rebindable_reference;
state.do_not_derref_rebindable_reference = false;
bool do_reference = false;
if (type_it != type_end
&& type_it->is_valid())
{
while (actual_arg.is<Nodecl::Conversion>())
{
actual_arg = actual_arg.as<Nodecl::Conversion>().get_nest();
}
bool param_is_ref = is_non_language_reference_type(*type_it);
bool arg_is_ref = is_non_language_reference_variable(actual_arg);
if (param_is_ref && !arg_is_ref)
{
if (actual_arg.is<Nodecl::Dereference>())
{
// Consider this case [ Emitted C ]
// void f(int (&v)[10]) -> void f(int * const v)
// {
// }
//
// void g() void g()
// { {
// int (*k)[10]; int (*k)[10];
// f(*k); f(*k); // Emitting f(k) would be wrong
// } }
//
// Note that "*k" has type "int[10]" but then it gets converted into "int*"
// conversely "k" is just "int(*)[10]" but this cannot be converted into "int*"
bool is_array_argument =
(actual_arg.get_type().is_array()
|| (actual_arg.get_type().is_any_reference()
&& actual_arg.get_type().references_to().is_array()));
if (!is_array_argument)
{
actual_arg = actual_arg.as<Nodecl::Dereference>().get_rhs();
}
}
else if (type_it->references_to().is_array()
&& actual_arg.get_type().is_valid()
&& actual_arg.get_type().no_ref().is_array())
{
// Consider this case [ Emitted C ]
// void f(int (&v)[10]) -> void f(int * const v)
// {
// }
//
// void g() void g()
// { {
// int k[10]; int k[10];
// f(k); f(k); // Emitting f(&k) would yield a wrong
// // type (with the proper value, though)
// } }
//
// Note that "k" has type "int[10]" (not a reference)
}
else
{
do_reference = true;
}
}
else if (!param_is_ref && arg_is_ref)
{
// Do nothing
}
else if (param_is_ref && arg_is_ref)
{
state.do_not_derref_rebindable_reference = true;
}
else if (!param_is_ref && !arg_is_ref)
{
// Do nothing
}
}
if (do_reference)
{
file << "&(";
}
walk(actual_arg);
if (do_reference)
{
file << ")";
}
if (type_it != type_end)
type_it++;
arg_it++;
state.do_not_derref_rebindable_reference = old_do_not_derref_rebindable_ref;
}
// Close the comment if needed
if (default_arguments)
file << " */";
}
template <typename Node>
void CxxBase::visit_function_call_form_template_id(const Node& node)
{
Nodecl::NodeclBase function_form = node.get_function_form();
TL::Symbol called_symbol = node.get_called().get_symbol();
if (!function_form.is_null()
&& function_form.is<Nodecl::CxxFunctionFormTemplateId>())
{
TL::TemplateParameters template_args = function_form.get_template_parameters();
TL::TemplateParameters deduced_template_args =
called_symbol.get_type().template_specialized_type_get_template_arguments();
if (template_args.get_num_parameters() == deduced_template_args.get_num_parameters())
{
// First case: the user's code specifies all template arguments
file << ::template_arguments_to_str(
template_args.get_internal_template_parameter_list(),
/* first_template_argument_to_be_printed */ 0,
/* print_first_level_bracket */ 1,
called_symbol.get_scope().get_decl_context());
}
else
{
// Second case: the user's code specifies some template arguments but not all
std::string template_args_str =
::template_arguments_to_str(
template_args.get_internal_template_parameter_list(),
/* first_template_argument_to_be_printed */ 0,
/* print_first_level_bracket */ 0,
called_symbol.get_scope().get_decl_context());
std::string deduced_template_args_str =
::template_arguments_to_str(
deduced_template_args.get_internal_template_parameter_list(),
/* first_template_argument_to_be_printed */ template_args.get_num_parameters(),
/* print_first_level_bracket */ 1,
called_symbol.get_scope().get_decl_context());
// Reason of this: A<::B> it's not legal
if (template_args_str.length() != 0 && template_args_str[0] == ':')
{
file << "< ";
}
else
{
file << "<";
}
file << template_args_str << "/*, " << deduced_template_args_str <<"*/>";
}
}
else
{
// Third case: the user's code does not specify any template argument
// We generate a comment with the deduced template arguments
if (called_symbol != NULL
&& called_symbol.get_type().is_template_specialized_type())
{
TL::TemplateParameters deduced_template_args =
called_symbol.get_type().template_specialized_type_get_template_arguments();
file << "/*";
file << ::template_arguments_to_str(
deduced_template_args.get_internal_template_parameter_list(),
/* first_template_argument_to_be_printed */ 0,
/* print_first_level_bracket */ 1,
called_symbol.get_scope().get_decl_context());
file << "*/";
}
}
}
// Explicit specialitzation for Nodecl::CxxDepFunctionCall because this kind of node has not a function form
template <>
void CxxBase::visit_function_call_form_template_id<Nodecl::CxxDepFunctionCall>(const Nodecl::CxxDepFunctionCall& node)
{
}
template <typename Node>
bool CxxBase::is_implicit_function_call(const Node& node) const
{
return (!node.get_function_form().is_null()
&& node.get_function_form().template is<Nodecl::CxxFunctionFormImplicit>());
}
// Explicit specialitzation for Nodecl::CxxDepFunctionCall because this kind of node has not a function form
template <>
bool CxxBase::is_implicit_function_call<Nodecl::CxxDepFunctionCall>(const Nodecl::CxxDepFunctionCall& node) const
{
return 0;
}
template <typename Node>
bool CxxBase::is_binary_infix_operator_function_call(const Node& node)
{
return (!node.get_function_form().is_null()
&& node.get_function_form().template is<Nodecl::CxxFunctionFormBinaryInfix>());
}
// Explicit specialitzation for Nodecl::CxxDepFunctionCall because this kind of node has not a function form
template <>
bool CxxBase::is_binary_infix_operator_function_call<Nodecl::CxxDepFunctionCall>(const Nodecl::CxxDepFunctionCall& node)
{
return 0;
}
template <typename Node>
bool CxxBase::is_unary_prefix_operator_function_call(const Node& node)
{
return (!node.get_function_form().is_null()
&& node.get_function_form().template is<Nodecl::CxxFunctionFormUnaryPrefix>());
}
// Explicit specialitzation for Nodecl::CxxDepFunctionCall because this kind of node has not a function form
template <>
bool CxxBase::is_unary_prefix_operator_function_call<Nodecl::CxxDepFunctionCall>(const Nodecl::CxxDepFunctionCall& node)
{
return 0;
}
template <typename Node>
bool CxxBase::is_unary_postfix_operator_function_call(const Node& node)
{
return (!node.get_function_form().is_null()
&& node.get_function_form().template is<Nodecl::CxxFunctionFormUnaryPostfix>());
}
// Explicit specialitzation for Nodecl::CxxDepFunctionCall because this kind of node has not a function form
template <>
bool CxxBase::is_unary_postfix_operator_function_call<Nodecl::CxxDepFunctionCall>(const Nodecl::CxxDepFunctionCall& node)
{
return 0;
}
template <typename Node>
bool CxxBase::is_operator_function_call(const Node& node)
{
return (is_unary_prefix_operator_function_call(node)
|| is_unary_postfix_operator_function_call(node)
|| is_binary_infix_operator_function_call(node));
}
template <typename Node>
CxxBase::Ret CxxBase::visit_function_call(const Node& node, bool is_virtual_call)
{
Nodecl::NodeclBase called_entity = node.get_called();
if (is_implicit_function_call(node))
{
// We don't want to generate the current function call because It has
// been added by the compiler. We should ignore it!
if (!node.get_arguments().is_null())
{
walk(node.get_arguments().template as<Nodecl::List>()[0]);
}
return;
}
TL::Symbol called_symbol = called_entity.get_symbol();
Nodecl::List arguments = node.get_arguments().template as<Nodecl::List>();
TL::Type function_type(NULL);
if (called_entity.is<Nodecl::Symbol>())
{
function_type = called_entity.as<Nodecl::Symbol>().get_symbol().get_type();
}
else
{
function_type = called_entity.get_type();
}
if (function_type.is_any_reference())
function_type = function_type.references_to();
if (function_type.is_pointer())
function_type = function_type.points_to();
// There are a lot of cases!
if (!function_type.is_function())
{
char needs_parentheses = operand_has_lower_priority(node, called_entity);
if (needs_parentheses)
{
file << "(";
}
walk(called_entity);
if (needs_parentheses)
{
file << ")";
}
file << "(";
walk_expression_list(arguments);
file << ")";
return;
}
enum call_kind
{
INVALID_CALL = 0,
ORDINARY_CALL,
NONSTATIC_MEMBER_CALL,
STATIC_MEMBER_CALL,
CONSTRUCTOR_INITIALIZATION,
BINARY_INFIX_OPERATOR,
UNARY_PREFIX_OPERATOR,
UNARY_POSTFIX_OPERATOR
} kind = ORDINARY_CALL;
if (called_symbol.is_valid())
{
if (is_unary_prefix_operator_function_call(node))
{
kind = UNARY_PREFIX_OPERATOR;
}
else if (is_unary_postfix_operator_function_call(node))
{
kind = UNARY_POSTFIX_OPERATOR;
}
else if (is_binary_infix_operator_function_call(node))
{
kind = BINARY_INFIX_OPERATOR;
}
else if (called_symbol.is_function()
&& called_symbol.is_member())
{
if (called_symbol.is_constructor())
{
kind = CONSTRUCTOR_INITIALIZATION;
}
else if (!called_symbol.is_static())
{
kind = NONSTATIC_MEMBER_CALL;
}
else
{
kind = STATIC_MEMBER_CALL;
}
}
}
bool is_non_language_ref = is_non_language_reference_type(function_type.returns());
if (is_non_language_ref)
file << "(*(";
bool old_visiting_called_entity_of_function_call =
state.visiting_called_entity_of_function_call;
// We are going to visit the called entity of the current function call.
// The template arguments of this function (if any) will be printed by the
// function 'visit_function_call_form_template_id' and not by the visitor
// of the symbol
state.visiting_called_entity_of_function_call = true;
int ignore_n_first_arguments;
switch (kind)
{
case ORDINARY_CALL:
case STATIC_MEMBER_CALL:
{
bool needs_parentheses = operand_has_lower_priority(node, called_entity);
if (needs_parentheses)
file << "(";
walk(called_entity);
if (needs_parentheses)
file << ")";
ignore_n_first_arguments = 0;
break;
}
case NONSTATIC_MEMBER_CALL:
{
ERROR_CONDITION(!(arguments.size() >= 1), "A nonstatic member call lacks the implicit argument", 0);
bool needs_parentheses = (get_rank(arguments[0]) < get_rank_kind(NODECL_CLASS_MEMBER_ACCESS, ""));
if (needs_parentheses)
file << "(";
walk(arguments[0]);
if (needs_parentheses)
file << ")";
file << ".";
if (is_virtual_call)
{
ERROR_CONDITION(!called_symbol.is_valid(), "Virtual call lacks called symbol", 0);
file << unmangle_symbol_name(called_symbol);
}
else
{
walk(called_entity);
}
ignore_n_first_arguments = 1;
break;
}
case CONSTRUCTOR_INITIALIZATION:
{
TL::Symbol class_symbol = called_symbol.get_class_type().get_symbol();
file << this->get_qualified_name(class_symbol);
ignore_n_first_arguments = 0;
break;
}
case UNARY_PREFIX_OPERATOR:
{
std::string called_operator = called_symbol.get_name().substr(std::string("operator ").size());
state.visiting_called_entity_of_function_call =
old_visiting_called_entity_of_function_call;
// We need this to avoid - - 1 to become --1
file << " " << called_operator;
bool needs_parentheses = operand_has_lower_priority(node, arguments[0]);
if (needs_parentheses)
file << "(";
walk(arguments[0]);
if (needs_parentheses)
file << ")";
if (is_non_language_ref)
file << "))";
return;
}
case UNARY_POSTFIX_OPERATOR:
{
std::string called_operator = called_symbol.get_name().substr(std::string("operator ").size());
state.visiting_called_entity_of_function_call =
old_visiting_called_entity_of_function_call;
bool needs_parentheses = operand_has_lower_priority(node, arguments[0]);
if (needs_parentheses)
file << "(";
walk(arguments[0]);
if (needs_parentheses)
file << ")";
file << called_operator;
if (is_non_language_ref)
file << "))";
return;
}
case BINARY_INFIX_OPERATOR:
{
std::string called_operator = called_symbol.get_name().substr(std::string("operator ").size());
state.visiting_called_entity_of_function_call =
old_visiting_called_entity_of_function_call;
bool needs_parentheses = operand_has_lower_priority(node, arguments[0]);
if (needs_parentheses)
file << "(";
walk(arguments[0]);
if (needs_parentheses)
file << ")";
file << " " << called_operator << " ";
needs_parentheses = operand_has_lower_priority(node, arguments[1]);
if (needs_parentheses)
file << "(";
walk(arguments[1]);
if (needs_parentheses)
file << ")";
if (is_non_language_ref)
file << "))";
return;
}
default:
{
internal_error("Unhandled function call kind", 0);
}
}
visit_function_call_form_template_id(node);
file << "(";
state.visiting_called_entity_of_function_call = old_visiting_called_entity_of_function_call;
codegen_function_call_arguments(arguments.begin(), arguments.end(), function_type, ignore_n_first_arguments);
file << ")";
if (is_non_language_ref)
file << "))";
}
CxxBase::Ret CxxBase::visit(const Nodecl::FunctionCall& node)
{
visit_function_call(node, /* is_virtual_call */ false);
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxDepFunctionCall& node)
{
visit_function_call(node, /* is_virtual_call */ false);
}
// Bug in GCC 4.4
template CxxBase::Ret CxxBase::visit_function_call<Nodecl::FunctionCall>(const Nodecl::FunctionCall& node, bool is_virtual_call);
template CxxBase::Ret CxxBase::visit_function_call<Nodecl::CxxDepFunctionCall>(const Nodecl::CxxDepFunctionCall& node, bool is_virtual_call);
CxxBase::Ret CxxBase::visit(const Nodecl::TemplateFunctionCode& node)
{
// We are going to generate dependent code
state.in_dependent_template_function_code = true;
Nodecl::Context context = node.get_statements().as<Nodecl::Context>();
Nodecl::List statement_seq = context.get_in_context().as<Nodecl::List>();
Nodecl::NodeclBase initializers = node.get_initializers();
if (statement_seq.size() != 1)
{
internal_error("C/C++ functions only have one statement", 0);
}
Nodecl::NodeclBase statement = statement_seq[0];
TL::Symbol symbol = node.get_symbol();
// We don't define twice a symbol
if (get_codegen_status(symbol) == CODEGEN_STATUS_DEFINED)
return;
// Two return cases for C++:
// - The symbol is defined inside a certain class and we are not defining this class yet
// - The symbol is not defined inside a class and, currently, we are defining one or more
if (IS_CXX_LANGUAGE
&& ((symbol.is_defined_inside_class()
&& (state.classes_being_defined.empty()
|| state.classes_being_defined.back() != symbol.get_class_type().get_symbol()))
|| (!symbol.is_defined_inside_class()
&& !state.classes_being_defined.empty())))
return;
TL::Type symbol_type = symbol.get_type();
TL::Scope function_scope = context.retrieve_context();
ERROR_CONDITION(!symbol.is_function()
&& !symbol.is_dependent_friend_function(), "Invalid symbol", 0);
if (!symbol.is_friend())
{
if (symbol.is_member())
{
TL::Symbol class_symbol = symbol.get_class_type().get_symbol();
do_define_symbol(class_symbol,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
else
{
if (symbol_type.is_template_specialized_type())
{
TL::Type template_type = symbol_type.get_related_template_type();
TL::Type primary_type = template_type.get_primary_template();
TL::Symbol primary_symbol = primary_type.get_symbol();
do_declare_symbol(primary_symbol,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
}
}
state.current_symbol = symbol;
int num_parameters = symbol.get_related_symbols().size();
TL::ObjectList<std::string> parameter_names(num_parameters);
TL::ObjectList<std::string> parameter_attributes(num_parameters);
fill_parameter_names_and_parameter_attributes(symbol, parameter_names, parameter_attributes);
std::string decl_spec_seq;
if (symbol.is_friend()
// The function is friend of a class
&& symbol.is_defined_inside_class()
// The friend function is defined within this class
&& !state.classes_being_defined.empty()
&& state.classes_being_defined.back() == symbol.get_class_type().get_symbol())
// The friend function is defined in the current being defined class
{
decl_spec_seq += "friend ";
}
if (symbol.is_static()
&& (!symbol.is_member()
|| (!state.classes_being_defined.empty()
&& state.classes_being_defined.back() == symbol.get_class_type().get_symbol())))
{
decl_spec_seq += "static ";
}
if (symbol.is_extern() && symbol.get_value().is_null())
{
decl_spec_seq += "extern ";
}
if (symbol.is_inline())
{
C_LANGUAGE()
{
decl_spec_seq += "__inline ";
}
CXX_LANGUAGE()
{
decl_spec_seq += "inline ";
}
}
if (symbol.is_explicit_constructor()
&& symbol.is_defined_inside_class())
{
decl_spec_seq += "explicit ";
}
std::string gcc_attributes;
if (symbol.has_gcc_attributes())
{
gcc_attributes = gcc_attributes_to_str(symbol) + " ";
}
std::string gcc_extension;
if (symbol.has_gcc_extension())
{
gcc_extension = "__extension__ ";
}
std::string asm_specification = gcc_asm_specifier_to_str(symbol);
std::string declarator_name;
if (!symbol.is_defined_inside_class())
{
declarator_name = symbol.get_class_qualification(function_scope, /* without_template */ true);
}
else
{
declarator_name = unmangle_symbol_name(symbol);
}
TL::Type real_type = symbol_type;
if (symbol.is_conversion_function()
|| symbol.is_destructor())
{
// FIXME - Use TL::Type to build this type
real_type = ::get_new_function_type(NULL, NULL, 0);
if (symbol.is_conversion_function())
{
if (symbol.get_type().is_const())
{
real_type = real_type.get_const_type();
}
}
}
std::string declarator;
declarator = this->get_declaration_with_parameters(real_type, function_scope, declarator_name, parameter_names, parameter_attributes);
std::string exception_spec = exception_specifier_to_str(symbol);
move_to_namespace_of_symbol(symbol);
TL::TemplateParameters template_parameters = function_scope.get_template_parameters();
if (symbol.is_defined_inside_class())
{
TL::Symbol class_sym = symbol.get_class_type().get_symbol();
codegen_template_headers_bounded(
template_parameters,
class_sym.get_scope().get_template_parameters(),
/*show default variables*/ false);
}
else
{
codegen_template_headers_all_levels(
template_parameters,
/*show default values*/ false);
}
bool requires_extern_linkage = (!symbol.is_member()
&& symbol.has_nondefault_linkage());
if (requires_extern_linkage)
{
file << "extern " + symbol.get_linkage() + "\n";
indent();
file << "{\n";
inc_indent();
}
if (!symbol.is_member()
&& asm_specification != "")
{
// gcc does not like asm specifications appear in the
// function-definition so emit a declaration before the definition
indent();
file << gcc_extension << decl_spec_seq << gcc_attributes << declarator << exception_spec << asm_specification << ";\n";
}
indent();
file << gcc_extension << decl_spec_seq << gcc_attributes << declarator << exception_spec << "\n";
set_codegen_status(symbol, CODEGEN_STATUS_DEFINED);
if (!initializers.is_null())
{
push_scope(function_scope);
inc_indent();
indent();
file << ": ";
walk_list(initializers.as<Nodecl::List>(), ", ");
dec_indent();
file << "\n";
pop_scope();
}
this->walk(context);
if (requires_extern_linkage)
{
dec_indent();
indent();
file << "}\n";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::FunctionCode& node)
{
if (_prune_saved_variables)
{
PruneVLAVisitor prune_vla;
prune_vla.walk(node);
}
//Only independent code
Nodecl::Context context = node.get_statements().as<Nodecl::Context>();
Nodecl::List statement_seq = context.get_in_context().as<Nodecl::List>();
Nodecl::NodeclBase initializers = node.get_initializers();
if (statement_seq.size() != 1)
{
internal_error("C/C++ functions only have one statement", 0);
}
Nodecl::NodeclBase statement = statement_seq[0];
TL::Symbol symbol = node.get_symbol();
// We don't define twice a symbol
if (get_codegen_status(symbol) == CODEGEN_STATUS_DEFINED)
return;
// Two return cases for C++:
// - The symbol is defined inside a certain class and we are not defining this class yet
// - The symbol is not defined inside a class and, currently, we are defining one or more
if (IS_CXX_LANGUAGE
&& ((symbol.is_defined_inside_class()
&& (state.classes_being_defined.empty()
|| state.classes_being_defined.back() != symbol.get_class_type().get_symbol()))
|| (!symbol.is_defined_inside_class()
&& !state.classes_being_defined.empty())))
return;
TL::Type symbol_type = symbol.get_type();
C_LANGUAGE()
{
walk_type_for_symbols(
symbol_type,
&CxxBase::declare_symbol_if_nonlocal_nonprototype,
&CxxBase::define_symbol_if_nonlocal_nonprototype,
&CxxBase::define_nonlocal_nonprototype_entities_in_trees);
}
TL::Scope symbol_scope = symbol.get_scope();
ERROR_CONDITION(!symbol.is_function()
&& !symbol.is_dependent_friend_function(), "Invalid symbol", 0);
bool is_template_specialized = symbol_type.is_template_specialized_type();
if(!symbol.is_friend())
{
if (symbol.is_member())
{
TL::Symbol class_symbol = symbol.get_class_type().get_symbol();
do_define_symbol(class_symbol,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
else
{
if (is_template_specialized)
{
TL::Type template_type = symbol_type.get_related_template_type();
TL::Type primary_type = template_type.get_primary_template();
TL::Symbol primary_symbol = primary_type.get_symbol();
do_declare_symbol(primary_symbol,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
}
}
state.current_symbol = symbol;
// At this point, we mark the function as defined. It must be done here to
// avoid the useless declaration of the function being defined and other
// related problems.
set_codegen_status(symbol, CODEGEN_STATUS_DEFINED);
C_LANGUAGE()
{
bool has_ellipsis = false;
TL::ObjectList<TL::Type> parameter_list = symbol_type.parameters(has_ellipsis);
for (TL::ObjectList<TL::Type>::iterator it = parameter_list.begin();
it != parameter_list.end();
it++)
{
walk_type_for_symbols(*it,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always,
&CxxBase::define_nonlocal_nonprototype_entities_in_trees);
}
define_nonlocal_nonprototype_entities_in_trees(statement);
}
int num_parameters = symbol.get_related_symbols().size();
TL::ObjectList<std::string> parameter_names(num_parameters);
TL::ObjectList<std::string> parameter_attributes(num_parameters);
fill_parameter_names_and_parameter_attributes(symbol, parameter_names, parameter_attributes);
std::string decl_spec_seq;
if (symbol.is_friend()
// The function is friend of a class
&& symbol.is_defined_inside_class()
// The friend function is defined within this class
&& !state.classes_being_defined.empty()
&& state.classes_being_defined.back() == symbol.get_class_type().get_symbol())
// The friend function is defined in the current being defined class
{
decl_spec_seq += "friend ";
}
if (symbol.is_static()
&& (!symbol.is_member()
|| (!state.classes_being_defined.empty()
&& state.classes_being_defined.back() == symbol.get_class_type().get_symbol())))
{
decl_spec_seq += "static ";
}
if (symbol.is_extern() && symbol.get_value().is_null())
{
decl_spec_seq += "extern ";
}
if (symbol.is_inline())
{
C_LANGUAGE()
{
decl_spec_seq += "__inline ";
}
CXX_LANGUAGE()
{
decl_spec_seq += "inline ";
}
}
if (symbol.is_explicit_constructor()
&& symbol.is_defined_inside_class())
{
decl_spec_seq += "explicit ";
}
std::string gcc_attributes;
if (symbol.has_gcc_attributes())
{
gcc_attributes = gcc_attributes_to_str(symbol) + " ";
}
std::string gcc_extension;
if (symbol.has_gcc_extension())
{
gcc_extension = "__extension__ ";
}
std::string asm_specification = gcc_asm_specifier_to_str(symbol);
std::string declarator_name;
if (IS_C_LANGUAGE)
{
declarator_name = unmangle_symbol_name(symbol);
}
else
{
if (!symbol.is_defined_inside_class())
{
declarator_name = symbol.get_class_qualification(symbol_scope, /* without_template */ true);
}
else
{
declarator_name = unmangle_symbol_name(symbol);
}
}
if (is_template_specialized
&& !symbol.is_conversion_function())
{
declarator_name += template_arguments_to_str(symbol);
}
TL::Type real_type = symbol_type;
if (symbol.is_conversion_function()
|| symbol.is_destructor())
{
// FIXME - Use TL::Type to build this type
real_type = ::get_new_function_type(NULL, NULL, 0);
if (symbol.is_conversion_function())
{
if (symbol.get_type().is_const())
{
real_type = real_type.get_const_type();
}
}
}
std::string declarator = this->get_declaration_with_parameters(
real_type, symbol_scope, declarator_name, parameter_names, parameter_attributes);
std::string exception_spec = exception_specifier_to_str(symbol);
move_to_namespace_of_symbol(symbol);
// We may need zero or more empty template headers
TL::TemplateParameters tpl = symbol_scope.get_template_parameters();
while (tpl.is_valid())
{
// We should ignore some 'fake' empty template headers
if (tpl.get_num_parameters() > 0 || tpl.get_is_explicit_specialization())
{
indent();
file << "template <>\n";
}
tpl = tpl.get_enclosing_parameters();
}
bool requires_extern_linkage = false;
if (IS_CXX_LANGUAGE
|| cuda_emit_always_extern_linkage())
{
requires_extern_linkage = (!symbol.is_member()
&& symbol.has_nondefault_linkage());
if (requires_extern_linkage)
{
file << "extern " + symbol.get_linkage() + "\n";
indent();
file << "{\n";
inc_indent();
}
}
if (!symbol.is_member()
&& asm_specification != "")
{
// gcc does not like asm specifications appear in the
// function-definition so emit a declaration before the definition
indent();
file << gcc_extension << decl_spec_seq << gcc_attributes << declarator << exception_spec << asm_specification << ";\n";
}
indent();
file << gcc_extension << decl_spec_seq << gcc_attributes << declarator << exception_spec << "\n";
if (!initializers.is_null())
{
push_scope(symbol_scope);
inc_indent();
indent();
file << ": ";
walk_list(initializers.as<Nodecl::List>(), ", ");
dec_indent();
file << "\n";
pop_scope();
}
this->walk(context);
if (IS_CXX_LANGUAGE
|| cuda_emit_always_extern_linkage())
{
if (requires_extern_linkage)
{
dec_indent();
indent();
file << "}\n";
}
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::GotoStatement& node)
{
TL::Symbol label_sym = node.get_symbol();
indent();
file << "goto " << label_sym.get_name() << ";\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::IfElseStatement& node)
{
Nodecl::NodeclBase condition = node.get_condition();
Nodecl::NodeclBase then = node.get_then();
Nodecl::NodeclBase _else = node.get_else();
indent();
file << "if (";
int old_condition = state.in_condition;
int old_indent = get_indent_level();
Nodecl::NodeclBase old_condition_top = state.condition_top;
set_indent_level(0);
state.in_condition = 1;
state.condition_top = condition;
walk(condition);
set_indent_level(old_indent);
state.in_condition = old_condition;
state.condition_top = old_condition_top;
file << ")\n";
inc_indent();
walk(then);
dec_indent();
if (!_else.is_null())
{
indent();
file << "else\n";
inc_indent();
walk(_else);
dec_indent();
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::IndexDesignator& node)
{
Nodecl::NodeclBase _index = node.get_index();
Nodecl::NodeclBase next = node.get_next();
if (IS_CXX_LANGUAGE)
{
file << " /* ";
}
file << "[";
walk(_index);
file << "]";
if (!next.is<Nodecl::FieldDesignator>()
&& !next.is<Nodecl::IndexDesignator>())
{
file << " = ";
}
if (IS_CXX_LANGUAGE)
{
file << " */ ";
}
walk(next);
}
void CxxBase::emit_integer_constant(const_value_t* cval, TL::Type t)
{
unsigned long long int v = const_value_cast_to_8(cval);
// Since we may be representing data with too many bits, let's discard
// uppermost bits for unsigned values
if (!const_value_is_signed(cval))
{
int bits = 8 * t.get_size();
unsigned long long int mask = 0;
if (bits < 64)
mask = ((~0ULL) << bits);
v &= ~mask;
}
if (t.is_signed_int())
{
file << *(signed long long*)&v;
}
else if (t.is_unsigned_int())
{
file << (unsigned long long)v << "U";
}
else if (t.is_signed_long_int())
{
file << *(signed long long*)&v << "L";
}
else if (t.is_unsigned_long_int())
{
file << (unsigned long long)v << "LU";
}
else if (t.is_signed_long_long_int())
{
file << *(signed long long*)&v << "LL";
}
else if (t.is_unsigned_long_long_int())
{
file << (unsigned long long)v << "LLU";
}
else
{
// Remaining integers like 'short'
if (const_value_is_signed(cval))
{
file << *(signed long long*)&v;
}
else
{
file << (unsigned long long)v;
}
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::IntegerLiteral& node)
{
const_value_t* value = nodecl_get_constant(node.get_internal_nodecl());
ERROR_CONDITION(value == NULL, "Invalid value", 0);
TL::Type t = node.get_type();
if (t.is_char())
{
unsigned char b = const_value_cast_to_1(value);
switch (b)
{
case '\'' : { file << "'\\''"; break; }
case '\\': { file << "'\\\\'"; break; }
case '\a' : { file << "'\\a'"; break; }
case '\b' : { file << "'\\b'"; break; }
case '\e' : { file << "'\\e'"; break; } // GCC extension
case '\f' : { file << "'\\f'"; break; }
case '\n' : { file << "'\\n'"; break; }
case '\r' : { file << "'\\r'"; break; }
case '\t' : { file << "'\\t'"; break; }
case '\v' : { file << "'\\v'"; break; }
case '\"' : { file << "'\\\"'"; break; }
default: {
if (isprint(b))
{
if (t.is_signed_char())
{
file << "'" << (signed char) b << "'";
}
else
{
file << "'" << (unsigned char) b << "'";
}
}
else
{
file << "'\\"
<< std::oct << std::setfill('0') << std::setw(3)
<< (unsigned int)b
<< std::dec << std::setw(0) << "'";
}
}
}
}
else if (IS_CXX_LANGUAGE && t.is_wchar_t())
{
unsigned int mb = const_value_cast_to_4(value);
file << "L'\\x"
<< std::hex << std::setfill('0') << std::setw(4)
<< mb
<< std::dec << std::setw(0) << "'";
}
else
{
emit_integer_constant(value, t);
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::LabeledStatement& node)
{
TL::Symbol label_sym = node.get_symbol();
Nodecl::NodeclBase statement = node.get_statement();
indent();
file << label_sym.get_name() << " : ";
int old = get_indent_level();
set_indent_level(0);
walk(statement);
set_indent_level(old);
}
CxxBase::Ret CxxBase::visit(const Nodecl::LoopControl& node)
{
Nodecl::NodeclBase init = node.get_init();
Nodecl::NodeclBase cond = node.get_cond();
Nodecl::NodeclBase next = node.get_next();
// No condition top as "for((i=0); ...)" looks unnecessary ugly
int old = state.in_condition;
state.in_condition = 1;
Nodecl::List init_list = init.as<Nodecl::List>();
if (!init_list.empty())
{
Nodecl::List::iterator it = init_list.begin();
if(!it->is<Nodecl::ObjectInit>())
{
walk(init);
}
else
{
TL::ObjectList<TL::Symbol> object_init_symbols;
for(; it != init_list.end(); ++it)
{
ERROR_CONDITION(!it->is<Nodecl::ObjectInit>(),
"unexpected node '%s'", ast_print_node_type(it->get_kind()));
object_init_symbols.append(it->as<Nodecl::ObjectInit>().get_symbol());
}
define_or_declare_variables(object_init_symbols, /* is definition */ true);
}
}
file << "; ";
Nodecl::NodeclBase old_condition_top = state.condition_top;
state.condition_top = cond;
// But it is desirable for the condition in "for( ... ; (i = x) ; ...)"
walk(cond);
file << "; ";
state.condition_top = old_condition_top;
// Here we do not care about parentheses "for ( ... ; ... ; i = i + 1)"
walk(next);
state.in_condition = old;
}
CxxBase::Ret CxxBase::visit(const Nodecl::MemberInit& node)
{
TL::Symbol entry = node.get_symbol();
Nodecl::NodeclBase init_expr = node.get_init_expr();
if (entry.is_class())
{
// Use the qualified name, do not rely on class-scope unqualified lookup
file << entry.get_qualified_name() << "(";
}
else
{
// Otherwise the name must not be qualified
file << entry.get_name() << "(";
}
TL::Type type = entry.get_type();
if (entry.is_class())
{
type = entry.get_user_defined_type();
}
if (nodecl_calls_to_constructor(init_expr, type))
{
// Ignore top level constructor
walk_expression_list(init_expr.as<Nodecl::FunctionCall>().get_arguments().as<Nodecl::List>());
}
else if (init_expr.is<Nodecl::StructuredValue>())
{
walk_expression_list(init_expr.as<Nodecl::StructuredValue>().get_items().as<Nodecl::List>());
}
else
{
walk(init_expr);
}
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::New& node)
{
Nodecl::NodeclBase initializer = node.get_init();
ERROR_CONDITION(initializer.is_null(), "New lacks initializer", 0);
Nodecl::NodeclBase placement = node.get_placement();
// Nodecl::NodeclBase operator_new = nodecl_get_child(node, 2);
if (node.get_text() == "global")
file << "::";
file << "new ";
if (!placement.is_null())
{
file << "(";
walk_expression_list(placement.as<Nodecl::List>());
file << ")";
}
Nodecl::NodeclBase type = node.get_init_real_type();
TL::Type init_real_type = type.get_type();
file << "(" << this->get_declaration(init_real_type, this->get_current_scope(), "") << ")";
// new[] cannot have an initializer, so just print the init_real_type
if (init_real_type.is_array())
return;
if (initializer.is<Nodecl::CxxEqualInitializer>()
|| initializer.is<Nodecl::CxxBracedInitializer>()
|| initializer.is<Nodecl::CxxParenthesizedInitializer>())
{
// Dependent cases are always printed verbatim
walk(initializer);
}
else if (IS_CXX03_LANGUAGE
&& init_real_type.is_aggregate()
&& initializer.is<Nodecl::StructuredValue>())
{
// int a[] = { 1, 2, 3 };
// struct foo { int x; int y; } a = {1, 2};
//
// Note that C++11 allows struct foo { int x; int y; } a{1,2};
file << " = ";
bool old = state.inside_structured_value;
state.inside_structured_value = true;
walk(initializer);
state.inside_structured_value = old;
}
else if (init_real_type.is_array()
&& !initializer.is<Nodecl::StructuredValue>())
{
// Only for char and wchar_t
// const char c[] = "1234";
file << " = ";
walk(initializer);
}
else if (init_real_type.is_array()
&& initializer.is<Nodecl::StructuredValue>())
{
// char c = { 'a' };
// int x = { 1 };
file << " = ";
bool old = state.inside_structured_value;
state.inside_structured_value = true;
walk(initializer);
state.inside_structured_value = old;
}
else if (state.in_condition)
{
// This is something like if (bool foo = expression)
file << " = ";
walk(initializer);
}
else
{
file << "(";
// A a; we cannot emmit it as A a(); since this would declare a function () returning A
if (nodecl_calls_to_constructor(initializer, init_real_type))
{
Nodecl::List constructor_args = initializer.as<Nodecl::FunctionCall>().get_arguments().as<Nodecl::List>();
// Here we add extra parentheses lest the direct-initialization looked like
// as a function declarator (faced with this ambiguity, C++ chooses the latter!)
//
// A x( (A()) ); cannot become A x( A() ); because it would declare 'x' as a
// "function (pointer to function() returning A) returning A"
// [extra blanks added for clarity in the example above]
walk_list(constructor_args, ", ", /* parenthesize_elements */ true);
}
else
{
walk(initializer);
}
file << ")";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxDepNew& node)
{
Nodecl::NodeclBase initializer = node.get_init();
ERROR_CONDITION(initializer.is_null(), "Dependent new lacks initializer", 0);
if (node.get_text() == "global")
file << "::";
file << "new ";
Nodecl::NodeclBase placement = node.get_placement();
if (!placement.is_null())
{
file << "(";
walk_expression_list(placement.as<Nodecl::List>());
file << ")";
}
Nodecl::NodeclBase type = node.get_init_real_type();
TL::Type init_real_type = type.get_type();
file << this->get_declaration(init_real_type, this->get_current_scope(), "");
// new[] cannot have an initializer, so just print the type
if (init_real_type.is_array())
return;
walk(initializer);
}
CxxBase::Ret CxxBase::visit(const Nodecl::ObjectInit& node)
{
TL::Symbol sym = node.get_symbol();
C_LANGUAGE()
{
walk_type_for_symbols(sym.get_type(),
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always,
&CxxBase::define_all_entities_in_trees);
}
state.must_be_object_init.erase(sym);
do_define_symbol(sym,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
CxxBase::Ret CxxBase::visit(const Nodecl::Offsetof& node)
{
file << "__builtin_offsetof(";
walk(node.get_offset_type());
file << ", ";
// Except for the first, the remaining must be printed as usual
Nodecl::List designator = node.get_designator().as<Nodecl::List>();
for (Nodecl::List::iterator it = designator.begin();
it != designator.end();
it++)
{
if (it == designator.begin())
{
ERROR_CONDITION(!it->is<Nodecl::C99FieldDesignator>(), "Invalid node", 0);
walk(it->as<Nodecl::C99FieldDesignator>().get_name());
}
else
{
walk(*it);
}
}
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::ParenthesizedExpression& node)
{
Nodecl::NodeclBase nest = node.get_nest();
file << "(";
walk(nest);
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::PointerToMember& node)
{
TL::Symbol symbol = node.get_symbol();
file << "&" << this->get_qualified_name(symbol);
}
CxxBase::Ret CxxBase::visit(const Nodecl::PragmaClauseArg& node)
{
file << node.get_text();
}
CxxBase::Ret CxxBase::visit(const Nodecl::PragmaCustomClause& node)
{
Nodecl::NodeclBase arguments = node.get_arguments();
file << node.get_text();
if (!arguments.is_null())
{
file << "(";
walk_list(arguments.as<Nodecl::List>(), ", ");
file << ")";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::PragmaCustomDeclaration& node)
{
Nodecl::NodeclBase pragma_line = node.get_pragma_line();
Nodecl::NodeclBase nested_pragma = node.get_nested_pragma();
TL::Symbol symbol = node.get_symbol();
indent();
// FIXME parallel|for must be printed as parallel for
file << "/* decl: #pragma " << node.get_text() << " ";
walk(pragma_line);
file << "' " << this->get_qualified_name(symbol) << "' */\n";
walk(nested_pragma);
}
CxxBase::Ret CxxBase::visit(const Nodecl::PragmaCustomDirective& node)
{
Nodecl::NodeclBase pragma_line = node.get_pragma_line();
indent();
file << "#pragma " << node.get_text() << " ";
walk(pragma_line);
file << "\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::PragmaCustomLine& node)
{
Nodecl::NodeclBase parameters = node.get_parameters();
Nodecl::NodeclBase clauses = node.get_clauses();
file << node.get_text();
if (!parameters.is_null())
{
file << "(";
walk_list(parameters.as<Nodecl::List>(), ", ");
file << ")";
}
else
{
file << " ";
}
walk_list(clauses.as<Nodecl::List>(), " ");
}
CxxBase::Ret CxxBase::visit(const Nodecl::PragmaCustomStatement& node)
{
Nodecl::NodeclBase pragma_line = node.get_pragma_line();
Nodecl::NodeclBase statement = node.get_statements();
indent();
// FIXME parallel|for must be printed as parallel for
file << "#pragma " << node.get_text() << " ";
walk(pragma_line);
file << "\n";
walk(statement);
}
CxxBase::Ret CxxBase::visit(const Nodecl::PseudoDestructorName& node)
{
Nodecl::NodeclBase lhs = node.get_accessed();
Nodecl::NodeclBase rhs = node.get_destructor_name();
char needs_parentheses = operand_has_lower_priority(node, lhs);
if (needs_parentheses)
{
file << "(";
}
walk(lhs);
if (needs_parentheses)
{
file << ")";
}
file << ".";
walk(rhs);
}
CxxBase::Ret CxxBase::visit(const Nodecl::Range& node)
{
Nodecl::NodeclBase lb_expr = node.get_lower();
Nodecl::NodeclBase ub_expr = node.get_upper();
Nodecl::NodeclBase step_expr = node.get_stride();
walk(lb_expr);
file << ":";
walk(ub_expr);
// Do not emit stride 1 because it looks weird in C
if (!step_expr.is_constant()
|| (const_value_cast_to_signed_int(step_expr.get_constant()) != 1))
{
file << ":";
walk(step_expr);
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::ReturnStatement& node)
{
Nodecl::NodeclBase expression = node.get_value();
indent();
file << "return ";
walk(expression);
file << ";\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::Shaping& node)
{
Nodecl::NodeclBase postfix = node.get_postfix();
Nodecl::List seq_exp = node.get_shape().as<Nodecl::List>();
for (Nodecl::List::iterator it = seq_exp.begin();
it != seq_exp.end();
it++)
{
file << "[";
walk(*it);
file << "]";
}
file << " ";
walk(postfix);
}
CxxBase::Ret CxxBase::visit(const Nodecl::Sizeof& node)
{
TL::Type t = node.get_size_type().get_type();
file << "sizeof(" << this->get_declaration(t, this->get_current_scope(), "") << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::Alignof& node)
{
TL::Type t = node.get_align_type().get_type();
file << "__alignof__(" << this->get_declaration(t, this->get_current_scope(), "") << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::StringLiteral& node)
{
const_value_t* v = nodecl_get_constant(node.get_internal_nodecl());
int *bytes = NULL;
int length = 0;
const_value_string_unpack_to_int(v, &bytes, &length);
type_t* element_type = array_type_get_element_type(no_ref(nodecl_get_type(node.get_internal_nodecl())));
char is_wchar = !is_unsigned_char_type(element_type)
&& !is_signed_char_type(element_type);
file << quote_c_string(bytes, length, is_wchar);
::xfree(bytes);
}
CxxBase::Ret CxxBase::visit(const Nodecl::StructuredValue& node)
{
Nodecl::List items = node.get_items().as<Nodecl::List>();
TL::Type type = node.get_type();
enum structured_value_kind
{
INVALID = 0,
// (T) { expr-list }
GCC_POSTFIX,
// T(single-expression)
CXX03_EXPLICIT,
// T{expr-list}
CXX1X_EXPLICIT,
} kind = INVALID;
if (IS_C_LANGUAGE)
{
kind = GCC_POSTFIX;
}
else if (IS_CXX03_LANGUAGE)
{
if ((items.empty()
|| ((items.size() == 1)
&& (type.is_named()
|| type.no_ref().is_builtin())))
&& !(type.is_class()
&& type.is_aggregate()))
{
kind = CXX03_EXPLICIT;
}
else
{
kind = GCC_POSTFIX;
}
}
else if (IS_CXX1X_LANGUAGE)
{
if (type.no_ref().is_vector())
{
// This is nonstandard, lets fallback to gcc
kind = GCC_POSTFIX;
}
else if (type.is_named())
{
kind = CXX1X_EXPLICIT;
}
else
{
// If this is not a named type fallback to gcc
kind = GCC_POSTFIX;
}
}
else
{
internal_error("Code unreachable", 0);
}
if (state.inside_structured_value)
{
kind = GCC_POSTFIX;
}
switch (kind)
{
// (T) { expr-list }
case GCC_POSTFIX:
{
if (!state.inside_structured_value)
{
file << "(" << this->get_declaration(type, this->get_current_scope(), "") << ")";
}
char inside_structured_value = state.inside_structured_value;
state.inside_structured_value = 1;
file << "{ ";
walk_expression_list(items);
file << " }";
state.inside_structured_value = inside_structured_value;
break;
}
// T(expr-list)
case CXX03_EXPLICIT:
{
// Special cases that are not valid here
// short int
// long int
// unsigned int
// signed int
if (type.is_signed_short_int())
{
file << "short";
}
else if (type.is_signed_long_int())
{
file << "long";
}
else if (type.is_unsigned_int())
{
file << "unsigned";
}
else
{
// No effort done for invalid cases that the syntax does not allow
file << this->get_declaration(type, this->get_current_scope(), "");
}
if (items.empty())
{
file << "()";
}
else
{
file << "(";
char inside_structured_value = state.inside_structured_value;
state.inside_structured_value = 0;
walk_expression_list(items);
state.inside_structured_value = inside_structured_value;
file << ")";
}
break;
}
// T{expr-list}
case CXX1X_EXPLICIT:
{
if (type.is_signed_short_int())
{
file << "short";
}
else if (type.is_signed_long_int())
{
file << "long";
}
else if (type.is_unsigned_int())
{
file << "unsigned";
}
else
{
// No effort done for invalid cases that the syntax does not allow
file << this->get_declaration(type, this->get_current_scope(), "");
}
char inside_structured_value = state.inside_structured_value;
state.inside_structured_value = 1;
file << "{ ";
walk_expression_list(items);
file << " }";
state.inside_structured_value = inside_structured_value;
break;
}
default:
{
internal_error("Code unreachable", 0);
}
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::SwitchStatement& node)
{
Nodecl::NodeclBase expression = node.get_switch();
Nodecl::NodeclBase statement = node.get_statement();
indent();
file << "switch (";
Nodecl::NodeclBase old_condition_top = state.condition_top;
int old_condition = state.in_condition;
int old_indent = get_indent_level();
set_indent_level(0);
state.in_condition = 1;
state.condition_top = expression;
walk(expression);
set_indent_level(old_indent);
state.in_condition = old_condition;
state.condition_top = old_condition_top;
file << ")\n";
inc_indent(2);
walk(statement);
dec_indent(2);
}
CxxBase::Ret CxxBase::visit(const Nodecl::Symbol& node)
{
TL::Symbol entry = node.get_symbol();
C_LANGUAGE()
{
if (entry.is_member())
{
do_define_symbol(entry.get_class_type().get_symbol(),
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
}
bool must_derref = is_non_language_reference_variable(entry)
&& !entry.get_type().references_to().is_array()
&& !state.do_not_derref_rebindable_reference;
if (must_derref)
{
file << "(*";
}
C_LANGUAGE()
{
file << entry.get_name();
}
CXX_LANGUAGE()
{
if (entry.is_builtin()
// Builtins cannot be qualified
|| (entry.is_function() && entry.is_friend_declared()))
{
file << entry.get_name();
}
else if (entry.is_function())
{
if (node.get_type().is_valid()
&& node.get_type().is_unresolved_overload())
{
file << this->get_qualified_name(entry,
this->get_current_scope().get_decl_context(),
/* without_template_id */ true);
TL::TemplateParameters template_arguments =
node.get_type().unresolved_overloaded_type_get_explicit_template_arguments();
if (template_arguments.is_valid())
{
file << ::template_arguments_to_str(
template_arguments.get_internal_template_parameter_list(),
/* first_template_argument_to_be_printed */ 0,
/* print_first_level_bracket */ 1,
this->get_current_scope().get_decl_context());
}
}
else
{
// If we are visiting the called entity of a function call, the template arguments
// (if any) will be added by 'visit_function_call_form_template_id' function
file << this->get_qualified_name(entry,
this->get_current_scope(),
/* without template id */ state.visiting_called_entity_of_function_call);
}
}
else if (!entry.is_dependent_entity())
{
file << this->get_qualified_name(entry, this->get_current_scope());
}
else
{
ERROR_CONDITION(entry.get_value().is_null(), "A dependent entity must have a tree of its name!", 0);
walk(entry.get_value());
}
}
if (must_derref)
{
file << ")";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::Text& node)
{
file << node.get_text();
}
CxxBase::Ret CxxBase::visit(const Nodecl::Throw& node)
{
Nodecl::NodeclBase expr = node.get_rhs();
file << "throw";
if (!expr.is_null())
{
file << " ";
if (get_rank(expr) < get_rank_kind(NODECL_ASSIGNMENT, ""))
{
// A comma operator could slip in
file << "(";
}
walk(expr);
if (get_rank(expr) < get_rank_kind(NODECL_ASSIGNMENT, ""))
{
file << ")";
}
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::TopLevel& node)
{
walk(node.get_top_level());
}
CxxBase::Ret CxxBase::visit(const Nodecl::TryBlock& node)
{
Nodecl::NodeclBase statement = node.get_statement();
Nodecl::NodeclBase catch_handlers = node.get_catch_handlers();
Nodecl::NodeclBase any_catch_handler = node.get_any();
indent();
file << "try\n";
walk(statement);
walk(catch_handlers);
if (!any_catch_handler.is_null())
{
indent();
file << "catch (...)\n";
walk(any_catch_handler);
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::Type& node)
{
TL::Type type = node.get_type();
file << this->get_declaration(type, this->get_current_scope(), "");
}
CxxBase::Ret CxxBase::visit(const Nodecl::Typeid& node)
{
Nodecl::NodeclBase expr = node.get_arg();
file << "typeid(";
walk(expr);
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::VirtualFunctionCall& node)
{
visit_function_call(node, /* is_virtual_call */ true);
}
// Bug in GCC 4.4
template CxxBase::Ret CxxBase::visit_function_call<Nodecl::VirtualFunctionCall>(const Nodecl::VirtualFunctionCall& node, bool is_virtual_call);
CxxBase::Ret CxxBase::visit(const Nodecl::WhileStatement& node)
{
Nodecl::NodeclBase condition = node.get_condition();
Nodecl::NodeclBase statement = node.get_statement();
indent();
file << "while (";
int old = state.in_condition;
Nodecl::NodeclBase old_condition_top = state.condition_top;
int old_indent = get_indent_level();
set_indent_level(0);
state.in_condition = 1;
state.condition_top = condition;
walk(condition);
set_indent_level(old_indent);
state.in_condition = old;
state.condition_top = old_condition_top;
file << ")\n";
inc_indent();
walk(statement);
dec_indent();
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxDecl& node)
{
TL::Symbol sym = node.get_symbol();
TL::Scope* context_of_declaration = NULL;
TL::Scope context;
Nodecl::NodeclBase nodecl_context = node.get_context();
if (!nodecl_context.is_null())
{
context = nodecl_context.as<Nodecl::Context>().retrieve_context();
context_of_declaration = &context;
}
state.must_be_object_init.erase(sym);
do_declare_symbol(sym,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always,
context_of_declaration);
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxDef& node)
{
TL::Symbol sym = node.get_symbol();
state.must_be_object_init.erase(sym);
TL::Scope* context_of_declaration = NULL;
TL::Scope context;
Nodecl::NodeclBase nodecl_context = node.get_context();
if (!nodecl_context.is_null())
{
context = nodecl_context.as<Nodecl::Context>().retrieve_context();
context_of_declaration = &context;
}
do_define_symbol(sym,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always,
context_of_declaration);
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxUsingDecl& node)
{
TL::Scope context = node.get_context().retrieve_context();
TL::Symbol sym = node.get_symbol();
if (context.is_namespace_scope())
{
// We define de namespace if it has not been defined yet.
// C++ only allows the definition of a namespace inside an other
// namespace or in the global scope
do_define_symbol(sym,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
move_to_namespace(context.get_related_symbol());
}
indent();
file << "using " << this->get_qualified_name(sym) << ";\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxUsingNamespace & node)
{
TL::Scope context = node.get_context().retrieve_context();
TL::Symbol sym = node.get_symbol();
ERROR_CONDITION(!sym.is_namespace(),
"This symbol '%s' is not a namespace",
sym.get_name().c_str());
if (context.is_namespace_scope())
{
// We define de namespace if it has not been defined yet.
// C++ only allows the definition of a namespace inside an other
// namespace or in the global scope
do_define_symbol(sym,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
move_to_namespace(context.get_related_symbol());
}
indent();
file << "using namespace " << this->get_qualified_name(sym) << ";\n";
}
void CxxBase::codegen_explicit_instantiation(TL::Symbol sym,
const Nodecl::NodeclBase & declarator_name,
const Nodecl::NodeclBase & context,
bool is_extern)
{
if (sym.is_class())
{
std::string class_key;
switch (sym.get_type().class_type_get_class_kind())
{
case TT_CLASS:
class_key = "class";
break;
case TT_STRUCT:
class_key = "struct";
break;
case TT_UNION:
class_key = "union";
break;
default:
internal_error("Invalid class kind", 0);
}
if (is_extern)
file << "extern ";
file << "template " << class_key << " " << this->get_qualified_name(sym, sym.get_scope()) << ";\n";
}
else if (sym.is_function())
{
decl_context_t decl_context = context.retrieve_context().get_decl_context();
move_to_namespace(decl_context.namespace_scope->related_entry);
if (is_extern)
file << "extern ";
std::string original_declarator_name = codegen(declarator_name);
file << "template " << this->get_declaration(sym.get_type(), sym.get_scope(), original_declarator_name) << ";\n";
}
else
{
internal_error("Invalid symbol", 0);
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxExplicitInstantiation& node)
{
TL::Symbol sym = node.get_symbol();
Nodecl::NodeclBase declarator_name = node.get_declarator_name();
Nodecl::NodeclBase context = node.get_context();
state.must_be_object_init.erase(sym);
codegen_explicit_instantiation(sym, declarator_name, context);
}
CxxBase::Ret CxxBase::visit(const Nodecl::CxxExternExplicitInstantiation& node)
{
TL::Symbol sym = node.get_symbol();
Nodecl::NodeclBase declarator_name = node.get_declarator_name();
Nodecl::NodeclBase context = node.get_context();
state.must_be_object_init.erase(sym);
codegen_explicit_instantiation(sym, declarator_name, context, /* is_extern */ true);
}
CxxBase::Ret CxxBase::visit(const Nodecl::Verbatim& node)
{
file << node.get_text();
}
CxxBase::Ret CxxBase::visit(const Nodecl::VlaWildcard& node)
{
file << "*";
}
CxxBase::Ret CxxBase::visit(const Nodecl::UnknownPragma& node)
{
move_to_namespace(node.retrieve_context().get_decl_context().namespace_scope->related_entry);
file << "#pragma " << node.get_text() << "\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::GxxTrait& node)
{
Nodecl::NodeclBase lhs = node.get_lhs();
Nodecl::NodeclBase rhs = node.get_rhs();
file << node.get_text() << "(";
walk(lhs);
if (!rhs.is_null())
{
file << ", ";
walk(rhs);
}
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::AsmDefinition& node)
{
indent();
file << "asm(";
walk(node.get_asm_text());
file << ");\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::GccAsmDefinition& node)
{
Nodecl::NodeclBase op0 = node.get_operands0();
Nodecl::NodeclBase op1 = node.get_operands1();
Nodecl::NodeclBase op2 = node.get_operands2();
Nodecl::NodeclBase specs = node.get_specs();
indent();
file << "__asm__ ";
walk_list(specs.as<Nodecl::List>(), ", ");
file << "(";
file << node.get_text();
file << " : ";
walk_list(op0.as<Nodecl::List>(), ", ");
file << " : ";
walk_list(op1.as<Nodecl::List>(), ", ");
if (!op2.is_null())
{
file << " : ";
walk_list(op2.as<Nodecl::List>(), ", ");
}
file << ");\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::GccAsmOperand& node)
{
Nodecl::NodeclBase identifier = node.get_identifier();
Nodecl::NodeclBase constraint = node.get_constraint();
Nodecl::NodeclBase expr = node.get_expr();
if (!identifier.is_null())
{
file << "[" << identifier.get_text() << "]";
}
walk(constraint);
if (!expr.is_null())
{
file << "(";
walk(expr);
file << ")";
}
}
CxxBase::Ret CxxBase::visit(const Nodecl::GccAsmSpec& node)
{
file << " __asm(" << node.get_text() << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::GccBuiltinVaArg& node)
{
file << "__builtin_va_arg(";
walk(node.get_expr());
file << ", ";
walk(node.get_va_type());
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::UpcSyncStatement& node)
{
file << node.get_text() << "(";
walk(node.get_expr());
file << ")";
}
CxxBase::Ret CxxBase::visit(const Nodecl::SourceComment& node)
{
indent();
file << "/* " << node.get_text() << " */\n";
}
CxxBase::Ret CxxBase::visit(const Nodecl::PreprocessorLine& node)
{
file << node.get_text() << "\n";
}
bool CxxBase::symbol_is_same_or_nested_in(TL::Symbol symbol, TL::Symbol class_sym)
{
if (symbol == class_sym)
{
return true;
}
else
{
if (symbol.is_member())
{
return symbol_is_same_or_nested_in(
symbol.get_class_type().get_symbol(),
class_sym);
}
else
{
return false;
}
}
}
bool CxxBase::symbol_is_nested_in_defined_classes(TL::Symbol symbol)
{
for (TL::ObjectList<TL::Symbol>::iterator it = state.classes_being_defined.begin();
it != state.classes_being_defined.end();
it++)
{
// If the symbol we are going to define is nested in one of
// the classes being defined, do not define now. It will be defined later
if (symbol_is_same_or_nested_in(symbol, *it))
{
return true;
}
}
return false;
}
bool CxxBase::symbol_or_its_bases_are_nested_in_defined_classes(TL::Symbol symbol)
{
if (symbol_is_nested_in_defined_classes(symbol))
{
return true;
}
if (symbol.is_class())
{
TL::ObjectList<TL::Symbol> bases = symbol.get_type().get_bases_class_symbol_list();
for (TL::ObjectList<TL::Symbol>::iterator it = bases.begin();
it != bases.end();
it++)
{
if (symbol_is_nested_in_defined_classes(*it))
{
return true;
}
}
}
return false;
}
// This function is only for C
TL::ObjectList<TL::Symbol> CxxBase::define_required_before_class(TL::Symbol symbol,
void (CxxBase::*decl_sym_fun)(TL::Symbol symbol),
void (CxxBase::*def_sym_fun)(TL::Symbol symbol))
{
state.pending_nested_types_to_define.clear();
if (state.being_checked_for_required.find(symbol) != state.being_checked_for_required.end())
return TL::ObjectList<TL::Symbol>();
state.being_checked_for_required.insert(symbol);
if (symbol.is_class())
{
TL::ObjectList<TL::Symbol> members = symbol.get_type().get_all_members();
for (TL::ObjectList<TL::Symbol>::iterator it = members.begin();
it != members.end();
it++)
{
TL::Symbol &member(*it);
if (member.is_class()
&& !member.is_defined_inside_class())
continue;
if (member.is_enum())
{
TL::ObjectList<TL::Symbol> enumerators = member.get_type().enum_get_enumerators();
for (TL::ObjectList<TL::Symbol>::iterator it2 = enumerators.begin();
it2 != enumerators.end();
it2++)
{
TL::Symbol &enumerator(*it2);
define_nonnested_entities_in_trees(enumerator.get_value());
}
}
else if(member.is_class())
{
walk_type_for_symbols(
member.get_type(),
&CxxBase::declare_symbol_if_nonnested,
&CxxBase::define_symbol_if_nonnested,
&CxxBase::define_nonnested_entities_in_trees);
}
else
{
if (member.is_variable()
&& member.is_static()
&& !member.get_value().is_null())
{
define_nonnested_entities_in_trees(member.get_value());
}
walk_type_for_symbols(
member.get_type(),
&CxxBase::declare_symbol_if_nonnested,
&CxxBase::define_symbol_if_nonnested,
&CxxBase::define_nonnested_entities_in_trees);
if (member.is_function())
{
// Define the types used by the function parameters
TL::ObjectList<TL::Type> parameters = member.get_type().parameters();
for (TL::ObjectList<TL::Type>::iterator it2 = parameters.begin();
it2 != parameters.end();
it2++)
{
TL::Type current_parameter(*it2);
walk_type_for_symbols(
current_parameter,
&CxxBase::declare_symbol_if_nonnested,
&CxxBase::define_symbol_if_nonnested,
&CxxBase::define_nonnested_entities_in_trees);
}
// Define the return type
walk_type_for_symbols(
member.get_type().returns(),
&CxxBase::declare_symbol_if_nonnested,
&CxxBase::define_symbol_if_nonnested,
&CxxBase::define_nonnested_entities_in_trees);
}
}
}
}
else if (symbol.is_enum()
|| symbol.is_enumerator()
|| symbol.is_variable())
{
walk_type_for_symbols(
symbol.get_type(),
&CxxBase::declare_symbol_if_nonnested,
&CxxBase::define_symbol_if_nonnested,
&CxxBase::define_nonnested_entities_in_trees);
}
else
{
internal_error("Unexpected symbol kind %s\n", symbol_kind_name(symbol.get_internal_symbol()));
}
// Here state.pending_nested_types_to_define has all the types that must be
// defined inside the current class, so we review them, lest they required
// something to be declared before the current class
TL::ObjectList<TL::Symbol> result(state.pending_nested_types_to_define.begin(), state.pending_nested_types_to_define.end());
// Remove current class if it appears
TL::ObjectList<TL::Symbol>::iterator it = std::find(result.begin(), result.end(), symbol);
if (it != result.end())
result.erase(it);
// Clear pending now as we are going to call define_required_before_class again
state.pending_nested_types_to_define.clear();
TL::ObjectList<TL::Symbol> must_be_defined_inside_class = result;
for (it = must_be_defined_inside_class.begin();
it != must_be_defined_inside_class.end();
it++)
{
TL::Symbol& entry(*it);
// This indirectly fills state.pending_nested_types_to_define
TL::ObjectList<TL::Symbol> pending_symbols =
define_required_before_class(entry, decl_sym_fun, def_sym_fun);
result.insert(pending_symbols);
}
state.being_checked_for_required.erase(symbol);
return result;
}
void CxxBase::define_class_symbol_aux(TL::Symbol symbol,
TL::ObjectList<TL::Symbol> symbols_defined_inside_class,
int level,
TL::Scope* scope)
{
set_codegen_status(symbol, CODEGEN_STATUS_DEFINED);
access_specifier_t default_access_spec = AS_UNKNOWN;
std::string class_key;
switch (symbol.get_type().class_type_get_class_kind())
{
case TT_CLASS:
class_key = "class";
default_access_spec = AS_PRIVATE;
break;
case TT_STRUCT:
class_key = "struct";
default_access_spec = AS_PUBLIC;
break;
case TT_UNION:
class_key = "union";
default_access_spec = AS_PUBLIC;
break;
default:
internal_error("Invalid class kind", 0);
}
std::string gcc_attributes;
if (symbol.has_gcc_attributes())
{
gcc_attributes = gcc_attributes_to_str(symbol) + " ";
}
std::string gcc_extension;
if (symbol.has_gcc_extension())
{
gcc_extension = "__extension__ ";
}
// 1. Declaration of the class key part
C_LANGUAGE()
{
indent();
// We generate the gcc attributes at this point (and not at the end of
// the class definition) because the attribute "visibility" is a bit
// special and needs to be placed here.
file << gcc_extension << class_key << " " << gcc_attributes << ms_attributes_to_str(symbol);
if (!symbol.is_anonymous_union())
{
// The symbol is called 'struct/union X' in C. We should ignore the
// class key because it has been already printed.
file << " " << symbol.get_name().substr(class_key.length() + 1);
}
file << "\n";
indent();
file << "{\n";
}
TL::Type symbol_type = symbol.get_type();
ERROR_CONDITION(::is_incomplete_type(symbol_type.get_internal_type()), "An incomplete class cannot be defined", 0);
CXX_LANGUAGE()
{
char is_template_specialized = 0;
char is_primary_template = 0;
char defined_inside_class = symbol.is_defined_inside_class();
TL::Type template_type(NULL);
TL::Type primary_template(NULL);
TL::Symbol primary_symbol(NULL);
if (symbol_type.is_template_specialized_type())
{
is_template_specialized = 1;
template_type = symbol_type.get_related_template_type();
primary_template = template_type.get_primary_template();
primary_symbol = primary_template.get_symbol();
if (primary_symbol == symbol)
{
is_primary_template = 1;
}
}
// *** From here everything required should have been declared ***
move_to_namespace_of_symbol(symbol);
if (!is_local_symbol(symbol))
{
if (is_template_specialized)
{
TL::TemplateParameters template_parameters =
(scope != NULL) ? scope->get_template_parameters() : symbol.get_scope().get_template_parameters();
if (!(symbol_type.class_type_is_complete_independent()
|| symbol_type.class_type_is_incomplete_independent()))
{
if (defined_inside_class)
{
// We only want the template header related to the current class
TL::Symbol enclosing_class = symbol.get_class_type().get_symbol();
codegen_template_headers_bounded(template_parameters,
enclosing_class.get_scope().get_template_parameters(),
/* show_default_values */ true);
}
else
{
// We want all template headers
codegen_template_headers_all_levels(template_parameters, /* show_default_values */ true);
}
}
else
{
while (template_parameters.is_valid() &&
template_parameters.get_is_explicit_specialization())
{
indent();
file << "template <>\n";
template_parameters = template_parameters.get_enclosing_parameters();
}
}
}
else
{
if (!defined_inside_class)
{
// A special case: a class declaration or definition is inside an other template class
TL::Symbol related_symbol = symbol.get_scope().get_related_symbol();
TL::Type type_related_symbol = related_symbol.get_type();
if (type_related_symbol.is_template_specialized_type())
{
// If the symbol is an anonymous union then it must be defined in the enclosing class definition.
// Otherwise, this symbol must be defined in its namespace and we should generate all template headers.
if (!symbol.is_anonymous_union())
{
TL::TemplateParameters template_parameters = symbol.get_scope().get_template_parameters();
codegen_template_headers_all_levels(template_parameters, /* show_default_values */ true);
}
}
}
}
}
indent();
std::string qualified_name;
if (level == 0)
{
qualified_name = symbol.get_class_qualification(/* without_template_id */ true);
}
else
{
qualified_name = symbol.get_name();
}
if (is_template_specialized
&& !is_primary_template)
{
qualified_name += get_template_arguments_str(symbol.get_internal_symbol(), symbol.get_scope().get_decl_context());
}
// We generate the gcc attributes at this point (and not at the end of
// the class definition) because the attribute "visibility" is a bit
// special and needs to be placed here.
file << gcc_extension << class_key << " " << gcc_attributes << ms_attributes_to_str(symbol);
if (!symbol.is_anonymous_union())
{
file << " " << qualified_name;
}
TL::ObjectList<TL::Type::BaseInfo> bases = symbol_type.get_bases();
if (!bases.empty())
{
file << " : " ;
for (TL::ObjectList<TL::Type::BaseInfo>::iterator it = bases.begin();
it != bases.end();
it++)
{
if (it != bases.begin())
{
file << ", ";
}
TL::Symbol &base(it->base);
bool is_virtual(it->is_virtual);
access_specifier_t current_access_spec(it->access_specifier);
if (is_virtual)
{
file << "virtual ";
}
if (current_access_spec != default_access_spec)
{
if (current_access_spec == AS_PUBLIC)
{
file << "public ";
}
else if (current_access_spec == AS_PRIVATE)
{
file << "private ";
}
else if (current_access_spec == AS_PROTECTED)
{
file << "protected ";
}
else
{
internal_error("Unreachable code", 0);
}
}
file << this->get_qualified_name(base, symbol.get_scope());
}
}
file << "\n";
indent();
file << "{\n";
}
// 2. Now declare members:
// 2.1 We need to forward declare all member classes (only for C++) because
// the member list does not contain enough information to decide in what
// order we should generate the members
TL::ObjectList<TL::Symbol> members = symbol_type.get_all_members();
access_specifier_t current_access_spec = default_access_spec;
CXX_LANGUAGE()
{
state.in_forwarded_member_declaration = true;
for (TL::ObjectList<TL::Symbol>::iterator it = members.begin();
it != members.end();
it++)
{
TL::Symbol &member(*it);
if (!member.is_class())
continue;
if (!member.is_defined_inside_class())
continue;
CXX_LANGUAGE()
{
access_specifier_t access_spec = member.get_access_specifier();
inc_indent();
if (current_access_spec != access_spec)
{
current_access_spec = access_spec;
indent();
if (current_access_spec == AS_PUBLIC)
{
file << "public:\n";
}
else if (current_access_spec == AS_PRIVATE)
{
file << "private:\n";
}
else if (current_access_spec == AS_PROTECTED)
{
file << "protected:\n";
}
else
{
internal_error("Unreachable code", 0);
}
}
}
inc_indent();
char old_in_member_declaration = state.in_member_declaration;
state.in_member_declaration = 1;
do_declare_symbol(member,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
state.in_member_declaration = old_in_member_declaration;
dec_indent();
dec_indent();
}
state.in_forwarded_member_declaration = false;
}
// 2.2 Declare members as usual
for (TL::ObjectList<TL::Symbol>::iterator it = members.begin();
it != members.end();
it++)
{
TL::Symbol &member(*it);
access_specifier_t access_spec = member.get_access_specifier();
CXX_LANGUAGE()
{
inc_indent();
if (current_access_spec != access_spec)
{
current_access_spec = access_spec;
indent();
if (current_access_spec == AS_PUBLIC)
{
file << "public:\n";
}
else if (current_access_spec == AS_PRIVATE)
{
file << "private:\n";
}
else if (current_access_spec == AS_PROTECTED)
{
file << "protected:\n";
}
else
{
internal_error("Unreachable code", 0);
}
}
}
inc_indent();
char old_in_member_declaration = state.in_member_declaration;
state.in_member_declaration = 1;
C_LANGUAGE()
{
if (member.get_type().is_named_class()
&& member.get_type().get_symbol().is_anonymous_union())
{
TL::Symbol class_sym = member.get_type().get_symbol();
state.classes_being_defined.push_back(class_sym);
define_class_symbol_aux(class_sym, symbols_defined_inside_class, level + 1, scope);
state.classes_being_defined.pop_back();
}
else
{
do_define_symbol(member,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
set_codegen_status(member, CODEGEN_STATUS_DEFINED);
}
CXX_LANGUAGE()
{
if (member.is_class())
{
if (member.get_type().is_template_specialized_type())
{
// We should declare all user template specializations
if (member.is_user_declared())
{
// Could this specialization be defined?
if (member.is_defined_inside_class() &&
is_complete_type(member.get_type().get_internal_type()))
{
state.classes_being_defined.push_back(member);
define_class_symbol_aux(member, symbols_defined_inside_class, level + 1);
state.classes_being_defined.pop_back();
}
else
{
do_declare_symbol(member,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
set_codegen_status(member, CODEGEN_STATUS_DECLARED);
}
}
else
{
// Do not emit anything but mark the symbols
if (symbols_defined_inside_class.contains(member))
{
set_codegen_status(member, CODEGEN_STATUS_DEFINED);
}
else
{
set_codegen_status(member, CODEGEN_STATUS_DECLARED);
}
}
}
else
{
if (member.is_defined_inside_class() || symbols_defined_inside_class.contains(member))
{
state.classes_being_defined.push_back(member);
define_class_symbol_aux(member, symbols_defined_inside_class, level + 1);
state.classes_being_defined.pop_back();
}
else
{
do_declare_symbol(member,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
set_codegen_status(member, CODEGEN_STATUS_DECLARED);
}
}
}
else if (member.is_using_symbol()
|| member.is_using_typename_symbol())
{
indent();
ERROR_CONDITION(!member.get_type().is_unresolved_overload(), "Invalid SK_USING symbol\n", 0);
TL::ObjectList<TL::Symbol> unresolved = member.get_type().get_unresolved_overload_set();
TL::Symbol entry = unresolved[0];
file << "using ";
if (member.is_using_typename_symbol())
file << "typename ";
file << this->get_qualified_name(entry, /* without_template */ 1) << ";\n";
}
else if (member.is_enum()
|| member.is_typedef())
{
do_define_symbol(member,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
set_codegen_status(member, CODEGEN_STATUS_DEFINED);
}
else if (member.is_function())
{
if (!member.get_function_code().is_null() &&
member.is_defined_inside_class())
{
walk(member.get_function_code());
}
else
{
do_declare_symbol(member,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
}
else
{
bool member_declaration_does_define = true;
// If we are declaring a static member it is not a definition
// unless it has been declared inside the class
if (member.is_variable()
&& member.is_static())
{
member_declaration_does_define = member.is_defined_inside_class();
}
if (member_declaration_does_define)
{
do_define_symbol(member,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
set_codegen_status(member, CODEGEN_STATUS_DEFINED);
}
else
{
do_declare_symbol(member,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
set_codegen_status(member, CODEGEN_STATUS_DECLARED);
}
}
}
state.in_member_declaration = old_in_member_declaration;
dec_indent();
CXX_LANGUAGE()
{
dec_indent();
}
}
// 3. Declare friends
TL::ObjectList<TL::Symbol> friends = symbol_type.class_get_friends();
for (TL::ObjectList<TL::Symbol>::iterator it = friends.begin();
it != friends.end();
it++)
{
TL::Symbol &_friend(*it);
inc_indent();
if ((_friend.is_function() || _friend.is_dependent_friend_function())
&& !_friend.get_function_code().is_null()
&& _friend.is_defined_inside_class())
{
walk(_friend.get_function_code());
}
else
{
declare_friend_symbol(*it, symbol);
}
dec_indent();
}
indent();
file << "};\n";
}
void CxxBase::define_class_symbol(TL::Symbol symbol,
void (CxxBase::*decl_sym_fun)(TL::Symbol symbol),
void (CxxBase::*def_sym_fun)(TL::Symbol symbol),
TL::Scope *scope)
{
if (symbol.is_anonymous_union() && !symbol.is_user_declared())
{
// This anonymous already union has been defined in a class scope
return;
}
std::set<TL::Symbol> current_pending = state.pending_nested_types_to_define;
state.classes_being_defined.push_back(symbol);
// This indirectly fills state.pending_nested_types_to_define
TL::ObjectList<TL::Symbol> symbols_defined_inside_class;
C_LANGUAGE()
{
symbols_defined_inside_class =
define_required_before_class(symbol, decl_sym_fun, def_sym_fun);
}
define_class_symbol_aux(symbol, symbols_defined_inside_class, /* level */ 0, scope);
state.classes_being_defined.pop_back();
state.pending_nested_types_to_define = current_pending;
}
void CxxBase::declare_friend_symbol(TL::Symbol friend_symbol, TL::Symbol class_symbol)
{
ERROR_CONDITION(!friend_symbol.is_friend(), "This symbol must be a friend", 0);
bool is_template_friend_declaration = false;
if (friend_symbol.is_template())
{
is_template_friend_declaration = true;
TL::Type primary_template = friend_symbol.get_type().get_primary_template();
TL::Symbol primary_symbol = primary_template.get_symbol();
friend_symbol = primary_symbol;
}
TL::Type friend_type = friend_symbol.get_type();
// A. Generate a template header if this friend declaration has one
if (friend_symbol.is_dependent_friend_class() && friend_symbol.has_alias_to())
{
// It's a special case: friend_symbol contains the right context
// of the template friend declaration and an alias to the real friend symbol
TL::Symbol pointed_symbol = friend_symbol.get_alias_to();
if (pointed_symbol.is_template())
{
is_template_friend_declaration = true;
TL::Type primary_template = pointed_symbol.get_type().get_primary_template();
TL::Symbol primary_symbol = primary_template.get_symbol();
pointed_symbol = primary_symbol;
}
codegen_template_headers_bounded(
friend_symbol.get_scope().get_template_parameters(),
class_symbol.get_scope().get_template_parameters(),
/* show default values */ false);
// Now, we should change the fake friend symbol by the real pointed symbol
friend_symbol = pointed_symbol;
friend_type = pointed_symbol.get_type();
}
else if (friend_type.is_template_specialized_type())
{
TL::Type template_type = friend_type.get_related_template_type();
TL::Type primary_template = template_type.get_primary_template();
TL::Symbol primary_symbol = primary_template.get_symbol();
if (friend_type.is_dependent())
{
TL::TemplateParameters template_parameters =
friend_symbol.get_scope().get_template_parameters();
codegen_template_headers_bounded(
template_parameters,
class_symbol.get_scope().get_template_parameters(),
/* show default values */ false);
}
}
// B. Generate the function or class declaration
indent();
file << "friend ";
if (friend_symbol.is_class())
{
std::string friend_class_key;
switch (friend_type.class_type_get_class_kind())
{
case TT_CLASS:
friend_class_key = "class";
break;
case TT_STRUCT:
friend_class_key = "struct";
break;
case TT_UNION:
friend_class_key = "union";
break;
default:
internal_error("Invalid class kind", 0);
}
file << friend_class_key << " ";
if ((!friend_type.is_template_specialized_type()
&& get_codegen_status(friend_symbol) == CODEGEN_STATUS_NONE)
|| (friend_type.is_template_specialized_type()
&& get_codegen_status(friend_type
.get_related_template_type()
.get_primary_template()
.get_symbol()) == CODEGEN_STATUS_NONE))
{
// The class_symbol has not been declared or defined before this friend declaration
// We cannot print its qualified
file << friend_symbol.get_name();
}
else
{
file << this->get_qualified_name(
friend_symbol,
class_symbol.get_scope(),
/*without template id */ is_template_friend_declaration);
}
}
else if(friend_symbol.is_dependent_friend_class())
{
enum type_tag_t class_key_tag;
if (friend_type.is_dependent_typename())
{
class_key_tag = get_dependent_entry_kind(friend_type.get_internal_type());
}
else
{
class_key_tag = friend_type.class_type_get_class_kind();
}
std::string friend_class_key;
switch (class_key_tag)
{
case TT_CLASS:
friend_class_key = "class";
break;
case TT_STRUCT:
friend_class_key = "struct";
break;
case TT_UNION:
friend_class_key = "union";
break;
default:
internal_error("Invalid class kind", 0);
}
file << this->get_declaration(friend_type, friend_symbol.get_scope(), "");
}
else if (friend_symbol.is_function()
|| friend_symbol.is_dependent_friend_function())
{
std::string exception_spec = exception_specifier_to_str(friend_symbol);
TL::Type real_type = friend_type;
if (class_symbol.is_conversion_function())
{
real_type = get_new_function_type(NULL, NULL, 0);
}
std::string function_name;
if (friend_type.is_template_specialized_type()
&& !friend_type.is_dependent())
{
function_name = this->get_qualified_name(
friend_symbol,
class_symbol.get_scope(),
/* without template id */ false);
}
else if(get_codegen_status(friend_symbol) == CODEGEN_STATUS_NONE)
{
function_name = friend_symbol.get_name();
}
else
{
function_name = this->get_qualified_name(
friend_symbol,
class_symbol.get_scope(),
/* without template id */ true);
}
// Dirty trick to remove the firsts two colons if the name of the function has them
if (function_name.size() >= 2 &&
function_name[0] == ':' &&
function_name[1] == ':')
{
function_name = function_name.substr(2);
}
file << this->get_declaration(real_type, friend_symbol.get_scope(), function_name) << exception_spec;
}
else if (friend_symbol.is_dependent_friend_function())
{
std::string exception_spec = exception_specifier_to_str(friend_symbol);
TL::Type real_type = friend_type;
if (class_symbol.is_conversion_function())
{
real_type = get_new_function_type(NULL, NULL, 0);
}
std::string function_name;
TL::ObjectList<TL::Symbol> candidates_set = friend_symbol.get_related_symbols();
if (candidates_set.size() == 1 &&
(get_codegen_status(candidates_set[0]) == CODEGEN_STATUS_DECLARED ||
get_codegen_status(candidates_set[0]) == CODEGEN_STATUS_DEFINED))
{
function_name = this->get_qualified_name(
friend_symbol,
candidates_set[0].get_scope(),
/* without template id */ (friend_type.is_template_specialized_type()));
}
else
{
function_name = friend_symbol.get_name();
}
file << this->get_declaration(real_type, friend_symbol.get_scope(), function_name) << exception_spec;
}
else
{
internal_error("Invalid friend class_symbol kind '%s'\n", symbol_kind_name(friend_symbol.get_internal_symbol()));
}
file << ";\n";
}
bool CxxBase::is_local_symbol(TL::Symbol entry)
{
return entry.is_valid()
&& (entry.get_scope().is_block_scope()
|| entry.get_scope().is_function_scope()
|| (entry.is_member() && is_local_symbol(entry.get_class_type().get_symbol())));
}
bool CxxBase::is_local_symbol_but_local_class(TL::Symbol entry)
{
return is_local_symbol(entry)
// C++ local classes are not considered here
&& !(IS_CXX_LANGUAGE && entry.is_class() && entry.get_scope().is_block_scope());
}
// Note: is_nonlocal_symbol_but_local_class is NOT EQUIVALENT to !is_local_symbol_but_local_class
bool CxxBase::is_nonlocal_symbol_but_local_class(TL::Symbol entry)
{
return !is_local_symbol(entry)
// C++ Local classes are obiously non local
&& !(IS_CXX_LANGUAGE && entry.is_class() && entry.get_scope().is_block_scope());
}
bool CxxBase::is_prototype_symbol(TL::Symbol entry)
{
return entry.is_valid()
&& entry.get_scope().is_prototype_scope();
}
bool CxxBase::all_enclosing_classes_are_user_declared(TL::Symbol entry)
{
bool result = true;
TL::Symbol class_entry = entry;
while (result && class_entry.is_member())
{
class_entry = class_entry.get_class_type().get_symbol();
result = class_entry.is_user_declared();
}
return result;
}
void CxxBase::define_symbol_always(TL::Symbol symbol)
{
do_define_symbol(symbol,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
void CxxBase::declare_symbol_always(TL::Symbol symbol)
{
do_declare_symbol(symbol,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always);
}
void CxxBase::define_symbol_if_local(TL::Symbol symbol)
{
if (is_local_symbol_but_local_class(symbol))
{
do_define_symbol(symbol,
&CxxBase::declare_symbol_if_local,
&CxxBase::define_symbol_if_local);
}
}
void CxxBase::declare_symbol_if_local(TL::Symbol symbol)
{
if (is_local_symbol_but_local_class(symbol))
{
do_declare_symbol(symbol,
&CxxBase::declare_symbol_if_local,
&CxxBase::define_symbol_if_local);
}
}
void CxxBase::define_symbol_if_nonlocal(TL::Symbol symbol)
{
if (is_nonlocal_symbol_but_local_class(symbol))
{
do_define_symbol(symbol,
&CxxBase::declare_symbol_if_nonlocal,
&CxxBase::define_symbol_if_nonlocal);
}
}
void CxxBase::declare_symbol_if_nonlocal(TL::Symbol symbol)
{
if (is_nonlocal_symbol_but_local_class(symbol))
{
do_declare_symbol(symbol,
&CxxBase::declare_symbol_if_nonlocal,
&CxxBase::define_symbol_if_nonlocal);
}
}
void CxxBase::define_symbol_if_nonlocal_nonprototype(TL::Symbol symbol)
{
if (is_nonlocal_symbol_but_local_class(symbol)
&& !is_prototype_symbol(symbol))
{
do_define_symbol(symbol,
&CxxBase::declare_symbol_if_nonlocal_nonprototype,
&CxxBase::define_symbol_if_nonlocal_nonprototype);
}
}
void CxxBase::declare_symbol_if_nonlocal_nonprototype(TL::Symbol symbol)
{
if (is_nonlocal_symbol_but_local_class(symbol)
&& !is_prototype_symbol(symbol))
{
do_declare_symbol(symbol,
&CxxBase::declare_symbol_if_nonlocal_nonprototype,
&CxxBase::define_symbol_if_nonlocal_nonprototype);
}
}
void CxxBase::define_symbol_if_nonprototype(TL::Symbol symbol)
{
if (!is_prototype_symbol(symbol))
{
do_define_symbol(symbol,
&CxxBase::declare_symbol_if_nonprototype,
&CxxBase::define_symbol_if_nonprototype);
}
}
void CxxBase::declare_symbol_if_nonprototype(TL::Symbol symbol)
{
if (!is_prototype_symbol(symbol))
{
do_define_symbol(symbol,
&CxxBase::declare_symbol_if_nonprototype,
&CxxBase::define_symbol_if_nonprototype);
}
}
void CxxBase::define_symbol_if_nonnested(TL::Symbol symbol)
{
if (!symbol_or_its_bases_are_nested_in_defined_classes(symbol))
{
do_define_symbol(symbol,
&CxxBase::declare_symbol_if_nonnested,
&CxxBase::define_symbol_if_nonnested);
}
else
{
// This symbol is nested in a defined class
// We cannot define it now, so we keep it
state.pending_nested_types_to_define.insert(symbol);
}
}
void CxxBase::declare_symbol_if_nonnested(TL::Symbol symbol)
{
if (!symbol_or_its_bases_are_nested_in_defined_classes(symbol)
|| !symbol.is_member())
{
do_declare_symbol(symbol,
&CxxBase::declare_symbol_if_nonnested,
&CxxBase::define_symbol_if_nonnested);
}
}
void CxxBase::define_nonnested_entities_in_trees(Nodecl::NodeclBase const& node)
{
define_generic_entities(node,
&CxxBase::declare_symbol_if_nonnested,
&CxxBase::define_symbol_if_nonnested,
&CxxBase::define_nonnested_entities_in_trees,
&CxxBase::entry_just_define);
}
void CxxBase::define_or_declare_if_complete(TL::Symbol sym,
void (CxxBase::* symbol_to_declare)(TL::Symbol),
void (CxxBase::* symbol_to_define)(TL::Symbol))
{
if ((sym.is_class()
|| sym.is_enum())
&& ( ::is_incomplete_type(sym.get_type().get_internal_type())
|| symbol_or_its_bases_are_nested_in_defined_classes(sym)))
{
(this->*symbol_to_declare)(sym);
}
else
{
(this->*symbol_to_define)(sym);
}
}
void CxxBase::define_or_declare_variable_emit_initializer(TL::Symbol& symbol, bool is_definition)
{
// Emit the initializer for nonmembers and nonstatic members in
// non member declarations or member declarations if they have
// integral or enum type
char emit_initializer = 0;
if (!symbol.get_value().is_null()
&& (!symbol.is_member()
|| (state.in_member_declaration == symbol.is_defined_inside_class())))
{
emit_initializer = 1;
}
// Initializer
if (emit_initializer)
{
push_scope(symbol.get_scope());
// We try to always emit direct-initialization syntax
// except when infelicities in the syntax prevent us to do that
Nodecl::NodeclBase init = symbol.get_value();
if (is_definition)
{
C_LANGUAGE()
{
file << " = ";
bool old = state.inside_structured_value;
if (init.is<Nodecl::StructuredValue>())
{
state.inside_structured_value = true;
}
walk(init);
state.inside_structured_value = old;
}
CXX_LANGUAGE()
{
if (init.is<Nodecl::CxxEqualInitializer>()
|| init.is<Nodecl::CxxBracedInitializer>()
|| init.is<Nodecl::CxxParenthesizedInitializer>())
{
// Dependent cases are always printed verbatim
walk(init);
}
else if (IS_CXX03_LANGUAGE
&& symbol.get_type().is_aggregate()
&& init.is<Nodecl::StructuredValue>())
{
// int a[] = { 1, 2, 3 };
// struct foo { int x; int y; } a = {1, 2};
//
// Note that C++11 allows struct foo { int x; int y; } a{1,2};
file << " = ";
bool old = state.inside_structured_value;
state.inside_structured_value = true;
walk(init);
state.inside_structured_value = old;
}
else if (symbol.get_type().is_array()
&& !init.is<Nodecl::StructuredValue>())
{
// Only for char and wchar_t
// const char c[] = "1234";
file << " = ";
walk(init);
}
else if (!symbol.get_type().is_array()
&& init.is<Nodecl::StructuredValue>())
{
// char c = { 'a' };
// int x = { 1 };
file << " = ";
bool old = state.inside_structured_value;
state.inside_structured_value = true;
walk(init);
state.inside_structured_value = old;
}
else if (symbol.is_member()
&& symbol.is_static()
&& state.in_member_declaration)
{
// This is an in member declaration initialization
file << " = ";
walk(init);
}
else if (state.in_condition)
{
// This is something like if (bool foo = expression)
file << " = ";
walk(init);
}
// Workaround for g++ <=4.5, >=4.7 (4.6 seems to work fine, but we'll do it anyways)
else if (nodecl_expr_is_value_dependent(init.get_internal_nodecl())
&& symbol.get_type().is_integral_type())
{
file << " = ";
walk(init);
}
else
{
file << "(";
// A a; we cannot emmit it as A a(); since this would declare a function () returning A
if (nodecl_calls_to_constructor(init, symbol.get_type()))
{
Nodecl::List constructor_args = init.as<Nodecl::FunctionCall>().get_arguments().as<Nodecl::List>();
// Here we add extra parentheses lest the direct-initialization looked like
// as a function declarator (faced with this ambiguity, C++ chooses the latter!)
//
// A x( (A()) ); cannot become A x( A() ); because it would declare 'x' as a
// "function (pointer to function() returning A) returning A"
// [extra blanks added for clarity in the example above]
walk_list(constructor_args, ", ", /* parenthesize_elements */ true);
}
else
{
walk(init);
}
file << ")";
}
}
}
pop_scope();
}
}
std::string CxxBase::define_or_declare_variable_get_name_variable(TL::Symbol& symbol)
{
bool has_been_declared = (get_codegen_status(symbol) == CODEGEN_STATUS_DECLARED
|| get_codegen_status(symbol) == CODEGEN_STATUS_DEFINED);
std::string variable_name;
if (!has_been_declared)
{
variable_name = symbol.get_name();
}
else
{
variable_name = symbol.get_class_qualification(symbol.get_scope(),
/* without_template */ false);
}
return variable_name;
}
void CxxBase::emit_declarations_of_initializer(TL::Symbol symbol)
{
if (!symbol.get_value().is_null()
&& (!symbol.is_member()
|| ((symbol.is_static()
&& (!state.in_member_declaration
|| ((symbol.get_type().is_integral_type()
|| symbol.get_type().is_enum())
&& symbol.get_type().is_const())))
|| symbol.is_defined_inside_class())))
{
if (symbol.is_member()
// FIXME -> || !is_local_symbol_but_local_class(symbol))
|| (!symbol.get_scope().is_block_scope()
&& !symbol.get_scope().is_function_scope()))
{
// This is a member or nonlocal symbol
define_nonnested_entities_in_trees(symbol.get_value());
}
else
{
// This is a local symbol
define_local_entities_in_trees(symbol.get_value());
}
}
}
void CxxBase::define_or_declare_variables(TL::ObjectList<TL::Symbol>& symbols, bool is_definition)
{
codegen_status_t codegen_status =
(is_definition) ? CODEGEN_STATUS_DEFINED : CODEGEN_STATUS_DECLARED;
for (TL::ObjectList<TL::Symbol>::iterator it = symbols.begin();
it != symbols.end();
it++)
{
TL::Symbol &symbol (*it);
emit_declarations_of_initializer(symbol);
}
define_or_declare_variable(symbols[0], is_definition);
// We ignore the first symbol as it has been already declared
for (TL::ObjectList<TL::Symbol>::iterator it = (symbols.begin() + 1);
it != symbols.end();
it++)
{
TL::Symbol &symbol (*it);
std::string variable_name =
define_or_declare_variable_get_name_variable(symbol);
std::string declarator = this->get_declaration_only_declarator(symbol.get_type(),
symbol.get_scope(),
variable_name);
set_codegen_status(symbol, codegen_status);
file << ", " << declarator;
define_or_declare_variable_emit_initializer(symbol, is_definition);
}
}
void CxxBase::define_or_declare_variable(TL::Symbol symbol, bool is_definition)
{
ERROR_CONDITION(!symbol.is_variable(), "must be a variable", 0);
// Builtins, anonymous unions and non-user declared varibles are not printed
if ((symbol.is_builtin()
|| (symbol.get_type().is_named_class()
&& symbol.get_type().get_symbol().is_anonymous_union())))
{
set_codegen_status(symbol, CODEGEN_STATUS_DECLARED);
return;
}
std::string decl_specifiers;
std::string gcc_attributes;
std::string declarator;
std::string bit_field;
bool requires_extern_linkage = false;
if (IS_CXX_LANGUAGE
|| cuda_emit_always_extern_linkage())
{
requires_extern_linkage = (!symbol.is_member()
&& symbol.has_nondefault_linkage());
if (requires_extern_linkage)
{
file << "extern " + symbol.get_linkage() + "\n";
indent();
file << "{\n";
inc_indent();
}
}
if (symbol.is_static()
&& (!symbol.is_member()
|| (!state.classes_being_defined.empty()
&& state.classes_being_defined.back() == symbol.get_class_type().get_symbol())))
{
decl_specifiers += "static ";
}
else if (symbol.is_extern() || !is_definition)
{
decl_specifiers += "extern ";
}
if (symbol.is_thread())
{
decl_specifiers += "__thread ";
}
if (symbol.is_mutable())
{
decl_specifiers += "mutable ";
}
if (symbol.is_register())
{
decl_specifiers += "register ";
}
if (symbol.is_bitfield())
{
unsigned int bits_of_bitfield = const_value_cast_to_4(
nodecl_get_constant(symbol.get_bitfield_size().get_internal_nodecl()));
std::stringstream ss;
ss << ":" << bits_of_bitfield;
bit_field = ss.str();
}
std::string variable_name = define_or_declare_variable_get_name_variable(symbol);
if (is_definition)
{
set_codegen_status(symbol, CODEGEN_STATUS_DEFINED);
}
else
{
set_codegen_status(symbol, CODEGEN_STATUS_DECLARED);
}
emit_declarations_of_initializer(symbol);
move_to_namespace_of_symbol(symbol);
// Generate the template headers if needed
CXX_LANGUAGE()
{
if (symbol.is_member()
&& !symbol.is_defined_inside_class()
&& state.classes_being_defined.empty())
{
TL::TemplateParameters template_parameters = symbol.get_scope().get_template_parameters();
codegen_template_headers_all_levels(template_parameters, false);
}
}
declarator = this->get_declaration(symbol.get_type(),
symbol.get_scope(),
variable_name);
if (symbol.has_gcc_attributes())
{
gcc_attributes = gcc_attributes_to_str(symbol) + " ";
}
std::string gcc_extension;
if (symbol.has_gcc_extension())
{
gcc_extension = "__extension__ ";
}
if (!state.in_condition)
indent();
if (_emit_saved_variables_as_unused
&& symbol.is_saved_expression())
{
gcc_attributes += "__attribute__((unused)) ";
}
file << gcc_extension << decl_specifiers << gcc_attributes << declarator << bit_field;
define_or_declare_variable_emit_initializer(symbol, is_definition);
if (!state.in_condition)
{
file << ";\n";
}
if (IS_CXX_LANGUAGE
|| cuda_emit_always_extern_linkage())
{
if (requires_extern_linkage)
{
dec_indent();
indent();
file << "}\n";
}
}
}
void CxxBase::do_define_symbol(TL::Symbol symbol,
void (CxxBase::*decl_sym_fun)(TL::Symbol symbol),
void (CxxBase::*def_sym_fun)(TL::Symbol symbol),
TL::Scope* scope)
{
if (state.emit_declarations == State::EMIT_NO_DECLARATIONS)
return;
if (state.emit_declarations == State::EMIT_CURRENT_SCOPE_DECLARATIONS)
{
if (this->get_current_scope().get_decl_context().current_scope != symbol.get_scope().get_decl_context().current_scope)
return;
}
if (symbol.not_to_be_printed())
return;
if (symbol.is_injected_class_name())
symbol = symbol.get_class_type().get_symbol();
if (symbol.get_type().is_template_specialized_type()
&& !symbol.is_user_declared())
return;
if (symbol.is_dependent_entity())
{
TL::Symbol entry(NULL);
Nodecl::NodeclBase n = Nodecl::NodeclBase::null();
symbol.get_type().dependent_typename_get_components(entry, n);
define_symbol_if_nonnested(entry);
return;
}
if (symbol.is_member())
{
TL::Symbol class_entry = symbol.get_class_type().get_symbol();
if (!symbol_or_its_bases_are_nested_in_defined_classes(class_entry))
{
define_symbol_if_nonnested(class_entry);
}
}
// Do nothing if already defined
if (get_codegen_status(symbol) == CODEGEN_STATUS_DEFINED
// It is a symbol that will be object-inited
|| state.must_be_object_init.find(symbol) != state.must_be_object_init.end())
return;
// We only generate user declared code
if (!symbol.is_user_declared())
return;
if (symbol.is_variable())
{
define_or_declare_variable(symbol, /* is definition */ true);
}
else if (symbol.is_typedef())
{
// Template parameters are not to be defined, ever
if (!symbol.is_template_parameter())
{
std::string gcc_attributes;
if (symbol.has_gcc_attributes())
{
gcc_attributes = gcc_attributes_to_str(symbol) + " ";
}
std::string gcc_extension;
if (symbol.has_gcc_extension())
{
gcc_extension = "__extension__ ";
}
move_to_namespace_of_symbol(symbol);
indent();
file << gcc_extension
<< "typedef "
<< gcc_attributes
<< this->get_declaration(symbol.get_type(),
symbol.get_scope(),
symbol.get_name())
<< ";\n";
}
}
else if (symbol.is_enumerator())
{
(this->*def_sym_fun)(symbol.get_type().get_symbol());
}
else if (symbol.is_enum())
{
move_to_namespace_of_symbol(symbol);
C_LANGUAGE()
{
// the symbol will be already called 'enum X' in C
indent();
file << symbol.get_name() << "\n";
indent();
file << "{\n";
}
CXX_LANGUAGE()
{
indent();
file << "enum " << symbol.get_name() << "\n";
indent();
file << "{\n";
}
inc_indent();
TL::ObjectList<TL::Symbol> enumerators = symbol.get_type().enum_get_enumerators();
for (TL::ObjectList<TL::Symbol>::iterator it = enumerators.begin();
it != enumerators.end();
it++)
{
TL::Symbol &enumerator(*it);
push_scope(enumerator.get_scope());
if (it != enumerators.begin())
{
file << ",\n";
}
indent();
file << enumerator.get_name();
if (!enumerator.get_value().is_null())
{
file << " = ";
walk(enumerator.get_value());
}
pop_scope();
}
dec_indent();
file << "\n";
indent();
file << "};\n";
}
else if (symbol.is_class())
{
define_class_symbol(symbol, decl_sym_fun, def_sym_fun, scope);
}
else if (symbol.is_function())
{
(this->*decl_sym_fun)(symbol);
// Functions are not defined but only declared
// We early return here otherwise this function would be marked as defined
return;
}
else if (symbol.is_namespace())
{
move_to_namespace_of_symbol(symbol);
indent();
file << "namespace " << symbol.get_name() << " { }\n";
}
else if (symbol.is_template_parameter())
{
// Do nothing
}
else
{
internal_error("I do not know how to define a %s\n", symbol_kind_name(symbol.get_internal_symbol()));
}
set_codegen_status(symbol, CODEGEN_STATUS_DEFINED);
}
void CxxBase::do_declare_symbol(TL::Symbol symbol,
void (CxxBase::*decl_sym_fun)(TL::Symbol symbol),
void (CxxBase::*def_sym_fun)(TL::Symbol symbol),
TL::Scope* scope)
{
if (state.emit_declarations == State::EMIT_NO_DECLARATIONS)
return;
if (state.emit_declarations == State::EMIT_CURRENT_SCOPE_DECLARATIONS)
{
if (this->get_current_scope().get_decl_context().current_scope != symbol.get_scope().get_decl_context().current_scope)
return;
}
if (symbol.is_injected_class_name())
symbol = symbol.get_class_type().get_symbol();
if (symbol.not_to_be_printed())
return;
if (symbol.is_member())
{
TL::Symbol class_entry = symbol.get_class_type().get_symbol();
if (!symbol_or_its_bases_are_nested_in_defined_classes(class_entry))
{
define_symbol_if_nonnested(class_entry);
}
// If the member symbol has been defined inside a class and
// and this class is not currently being defined we do nothing
if (symbol.is_defined_inside_class() &&
(state.classes_being_defined.empty()
|| (state.classes_being_defined.back() != class_entry)))
return;
}
// We only generate user declared code
if (!symbol.is_user_declared())
return;
// Do nothing if:
// - The symbol has been declared or defined and
// - It is not a template specialized class
if ((get_codegen_status(symbol) == CODEGEN_STATUS_DEFINED
|| get_codegen_status(symbol) == CODEGEN_STATUS_DECLARED)
&& !(symbol.is_class()
&& symbol.get_type().is_template_specialized_type()))
return;
// It is a symbol that will be object-inited
if (state.must_be_object_init.find(symbol) != state.must_be_object_init.end())
return;
if (symbol.is_variable())
{
define_or_declare_variable(symbol, /* is definition */ false);
return;
}
// If the symbol is already defined we should not change its codegen status
if (get_codegen_status(symbol) == CODEGEN_STATUS_NONE)
set_codegen_status(symbol, CODEGEN_STATUS_DECLARED);
if (symbol.is_class())
{
C_LANGUAGE()
{
// the symbol will be already called 'struct/union X' in C
indent();
file << symbol.get_name() << ";\n";
}
CXX_LANGUAGE()
{
if (symbol.is_member())
{
// A nested symbol can be declared only if we are
// defining its immediate enclosing class, otherwise request for a definition of the enclosing class
if (state.classes_being_defined.empty()
|| (state.classes_being_defined.back() !=
symbol.get_class_type().get_symbol()))
{
(this->*def_sym_fun)(symbol.get_class_type().get_symbol());
return;
}
}
char is_template_specialized = 0;
char is_primary_template = 0;
TL::Type template_type(NULL);
TL::Type primary_template(NULL);
TL::Symbol primary_symbol(NULL);
if (symbol.get_type().is_template_specialized_type())
{
is_template_specialized = 1;
template_type = symbol.get_type().get_related_template_type();
primary_template = template_type.get_primary_template();
primary_symbol = primary_template.get_symbol();
if (primary_symbol != symbol)
{
// Before the declaration of this specialization we should ensure
// that the primary specialization has been defined
(this->*decl_sym_fun)(primary_symbol);
}
else
{
is_primary_template = 1;
}
}
std::string class_key;
switch (symbol.get_type().class_type_get_class_kind())
{
case TT_CLASS:
class_key = "class";
break;
case TT_STRUCT:
class_key = "struct";
break;
case TT_UNION:
class_key = "union";
break;
default:
internal_error("Invalid class kind", 0);
}
move_to_namespace_of_symbol(symbol);
if (is_template_specialized)
{
if (symbol.get_type().class_type_is_complete_independent()
|| symbol.get_type().class_type_is_incomplete_independent())
{
indent();
file << "template <>\n";
}
else
{
ERROR_CONDITION(!symbol.is_user_declared(),
"Only user declared template specializations are allowed "
"as a dependent template specialized type!\n", 0);
TL::TemplateParameters template_parameters(NULL);
if (scope != NULL)
{
template_parameters = scope->get_template_parameters();
}
else
{
template_parameters = is_primary_template ?
template_type.get_related_template_symbol().get_type().template_type_get_template_parameters()
: symbol.get_type().template_specialized_type_get_template_parameters();
}
codegen_template_header(template_parameters,
/* show_default_values */ !state.in_forwarded_member_declaration);
}
}
// A union inside a class must be defined if its not a forward
// member declaration
if (class_key == "union"
&& symbol.get_scope().is_class_scope()
&& !state.in_forwarded_member_declaration)
{
(this->*def_sym_fun)(symbol);
return;
}
if (!symbol.is_anonymous_union())
{
indent();
file << class_key << " " << symbol.get_name();
if (is_template_specialized
&& !is_primary_template)
{
file << get_template_arguments_str(symbol.get_internal_symbol(), symbol.get_scope().get_decl_context());
}
file << ";\n";
}
}
}
else if (symbol.is_enumerator())
{
(this->*decl_sym_fun)(symbol.get_type().get_symbol());
}
else if (symbol.is_enum())
{
// Enums cannot be only declared but defined
(this->*def_sym_fun)(symbol);
}
else if (symbol.is_typedef())
{
// Typedefs can't be simply declared
(this->*def_sym_fun)(symbol);
}
else if (symbol.is_function())
{
// The user did not declare it, ignore it
if (symbol.is_friend_declared())
return;
C_LANGUAGE()
{
walk_type_for_symbols(
symbol.get_type(),
&CxxBase::declare_symbol_if_nonlocal_nonprototype,
&CxxBase::define_symbol_if_nonlocal_nonprototype,
&CxxBase::define_nonlocal_nonprototype_entities_in_trees);
}
char is_primary_template = 0;
bool requires_extern_linkage = false;
if (IS_CXX_LANGUAGE
|| cuda_emit_always_extern_linkage())
{
move_to_namespace_of_symbol(symbol);
requires_extern_linkage = (!symbol.is_member()
&& symbol.has_nondefault_linkage());
if (requires_extern_linkage)
{
file << "extern " + symbol.get_linkage() + "\n";
indent();
file << "{\n";
inc_indent();
}
}
CXX_LANGUAGE()
{
if (symbol.get_type().is_template_specialized_type())
{
TL::Type template_type = symbol.get_type().get_related_template_type();
TL::Type primary_template = template_type.get_primary_template();
TL::Symbol primary_symbol = primary_template.get_symbol();
(this->*decl_sym_fun)(primary_symbol);
if (primary_symbol != symbol)
{
indent();
file << "template <>\n";
}
else
{
TL::TemplateParameters template_parameters = template_type.template_type_get_template_parameters();
codegen_template_header(template_parameters,
/*show default values*/ false);
is_primary_template = 1;
}
}
}
int num_parameters = symbol.get_related_symbols().size();
TL::ObjectList<std::string> parameter_names(num_parameters);
TL::ObjectList<std::string> parameter_attributes(num_parameters);
fill_parameter_names_and_parameter_attributes(symbol, parameter_names, parameter_attributes);
std::string decl_spec_seq;
if (symbol.is_static()
&& (!symbol.is_member()
|| (!state.classes_being_defined.empty()
&& state.classes_being_defined.back() == symbol.get_class_type().get_symbol())))
{
decl_spec_seq += "static ";
}
if (symbol.is_extern())
{
decl_spec_seq += "extern ";
}
if (symbol.is_virtual())
{
decl_spec_seq += "virtual ";
}
if (symbol.is_inline())
{
C_LANGUAGE()
{
decl_spec_seq += "__inline ";
}
CXX_LANGUAGE()
{
decl_spec_seq += "inline ";
}
}
if (symbol.is_explicit_constructor()
&& symbol.is_defined_inside_class())
{
decl_spec_seq += "explicit ";
}
if (symbol.is_nested_function())
{
decl_spec_seq += "auto ";
}
std::string gcc_attributes = gcc_attributes_to_str(symbol);
std::string asm_specification = gcc_asm_specifier_to_str(symbol);
TL::Type real_type = symbol.get_type();
if (symbol.is_conversion_function()
|| symbol.is_destructor())
{
// FIXME
real_type = get_new_function_type(NULL, NULL, 0);
if (symbol.is_conversion_function())
{
if (symbol.get_type().is_const())
{
real_type = real_type.get_const_type();
}
}
}
std::string function_name = unmangle_symbol_name(symbol);
if (symbol.get_type().is_template_specialized_type()
// Conversions do not allow templates
&& !is_primary_template
&& !symbol.is_conversion_function())
{
function_name += template_arguments_to_str(symbol);
}
std::string declarator = "";
std::string pure_spec = "";
if (!real_type.lacks_prototype())
{
declarator = this->get_declaration_with_parameters(real_type, symbol.get_scope(),
function_name,
parameter_names,
parameter_attributes);
if (symbol.is_virtual()
&& symbol.is_pure())
{
pure_spec += " = 0 ";
}
}
else
{
declarator = this->get_declaration(
real_type.returns(),
symbol.get_scope(),
function_name);
declarator += "(";
TL::ObjectList<TL::Symbol> args = symbol.get_related_symbols();
for (TL::ObjectList<TL::Symbol>::iterator it = args.begin();
it != args.end();
it++)
{
if (it != args.begin())
declarator += ", ";
declarator += it->get_name();
}
bool has_ellipsis = false;
real_type.parameters(has_ellipsis);
if (has_ellipsis)
{
if (!args.empty())
{
declarator += ", ";
}
declarator += "...";
}
declarator += ")";
}
std::string exception_spec = exception_specifier_to_str(symbol);
indent();
file << decl_spec_seq << declarator << exception_spec << pure_spec << asm_specification << gcc_attributes << ";\n";
if (IS_CXX_LANGUAGE
|| cuda_emit_always_extern_linkage())
{
if (requires_extern_linkage)
{
dec_indent();
indent();
file << "}\n";
}
}
}
else if (symbol.is_template_parameter())
{
// Do nothing
}
else if (symbol.is_dependent_entity())
{
TL::Symbol entry(NULL);
Nodecl::NodeclBase n = Nodecl::NodeclBase::null();
symbol.get_type().dependent_typename_get_components(entry, n);
(this->*decl_sym_fun)(entry);
}
else if(symbol.get_type().is_dependent_typename() || symbol.is_dependent_friend_function())
{
// Do nothing
}
else
{
internal_error("Do not know how to declare a %s\n", symbol_kind_name(symbol.get_internal_symbol()));
}
}
bool CxxBase::is_pointer_arithmetic_add_helper(TL::Type op1, TL::Type op2)
{
if (op1.is_lvalue_reference())
op1 = op1.references_to();
if (op2.is_lvalue_reference())
op2 = op2.references_to();
return (op1.is_pointer() && op2.is_integral_type());
}
bool CxxBase::is_pointer_arithmetic_add(const Nodecl::Add &node, TL::Type &pointer_type)
{
Nodecl::NodeclBase lhs = node.get_lhs();
Nodecl::NodeclBase rhs = node.get_rhs();
if ( is_pointer_arithmetic_add_helper(lhs.get_type(), rhs.get_type()))
{
pointer_type = lhs.get_type();
}
else if (is_pointer_arithmetic_add_helper(rhs.get_type(), lhs.get_type()))
{
pointer_type = rhs.get_type();
}
else
{
return false;
}
if (pointer_type.is_lvalue_reference())
pointer_type = pointer_type.references_to();
return true;
}
void CxxBase::define_generic_entities(Nodecl::NodeclBase node,
void (CxxBase::*decl_sym_fun)(TL::Symbol symbol),
void (CxxBase::*def_sym_fun)(TL::Symbol symbol),
void (CxxBase::*define_entities_fun)(const Nodecl::NodeclBase& node),
void (CxxBase::*define_entry_fun)(
const Nodecl::NodeclBase &node, TL::Symbol entry,
void (CxxBase::*def_sym_fun_2)(TL::Symbol symbol))
)
{
if (node.is_null())
return;
if (node.is<Nodecl::List>())
{
Nodecl::List l = node.as<Nodecl::List>();
for (Nodecl::List::iterator it = l.begin();
it != l.end();
it++)
{
define_generic_entities(
*it,
decl_sym_fun,
def_sym_fun,
define_entities_fun,
define_entry_fun
);
}
}
else
{
TL::ObjectList<Nodecl::NodeclBase> children = node.children();
for (TL::ObjectList<Nodecl::NodeclBase>::iterator it = children.begin();
it != children.end();
it++)
{
define_generic_entities(
*it,
decl_sym_fun,
def_sym_fun,
define_entities_fun,
define_entry_fun
);
}
TL::Symbol entry = node.get_symbol();
if (entry.is_valid()
&& entry.get_type().is_valid()
&& state.walked_symbols.find(entry) == state.walked_symbols.end())
{
state.walked_symbols.insert(entry);
C_LANGUAGE()
{
walk_type_for_symbols(entry.get_type(),
decl_sym_fun,
def_sym_fun,
define_entities_fun
);
(this->*define_entry_fun)(node, entry, def_sym_fun);
}
define_generic_entities(entry.get_value(),
decl_sym_fun,
def_sym_fun,
define_entities_fun,
define_entry_fun
);
state.walked_symbols.erase(entry);
}
C_LANGUAGE()
{
TL::Type type = node.get_type();
if (type.is_valid())
{
walk_type_for_symbols(
type,
decl_sym_fun,
def_sym_fun,
define_entities_fun);
}
// Special case for pointer arithmetic
if (node.is<Nodecl::Add>())
{
Nodecl::Add add = node.as<Nodecl::Add>();
TL::Type pointer_type;
if (is_pointer_arithmetic_add(add, /* out */ pointer_type))
{
walk_type_for_symbols(
pointer_type.points_to(),
decl_sym_fun,
def_sym_fun,
define_entities_fun);
}
}
}
}
}
void CxxBase::entry_just_define(
const Nodecl::NodeclBase&,
TL::Symbol entry,
void (CxxBase::*def_sym_fun)(TL::Symbol))
{
(this->*def_sym_fun)(entry);
}
void CxxBase::entry_local_definition(
const Nodecl::NodeclBase& node,
TL::Symbol entry,
void (CxxBase::*def_sym_fun)(TL::Symbol))
{
// FIXME - Improve this
if (this->get_current_scope().get_decl_context().current_scope
== entry.get_scope().get_decl_context().current_scope)
{
if (node.is<Nodecl::ObjectInit>()
|| node.is<Nodecl::CxxDecl>()
|| node.is<Nodecl::CxxDef>())
{
// If this is an object init (and the traversal ensures that
// they will be seen first) we assume it's already been defined
state.must_be_object_init.insert(entry);
}
else
{
(this->*def_sym_fun)(entry);
}
}
}
void CxxBase::define_all_entities_in_trees(const Nodecl::NodeclBase& node)
{
define_generic_entities(node,
&CxxBase::declare_symbol_always,
&CxxBase::define_symbol_always,
&CxxBase::define_all_entities_in_trees,
&CxxBase::entry_just_define);
}
void CxxBase::define_nonlocal_entities_in_trees(const Nodecl::NodeclBase& node)
{
define_generic_entities(node,
&CxxBase::declare_symbol_if_nonlocal,
&CxxBase::define_symbol_if_nonlocal,
&CxxBase::define_nonlocal_entities_in_trees,
&CxxBase::entry_just_define);
}
void CxxBase::define_nonprototype_entities_in_trees(const Nodecl::NodeclBase& node)
{
define_generic_entities(node,
&CxxBase::declare_symbol_if_nonprototype,
&CxxBase::define_symbol_if_nonprototype,
&CxxBase::define_nonprototype_entities_in_trees,
&CxxBase::entry_just_define);
}
void CxxBase::define_nonlocal_nonprototype_entities_in_trees(const Nodecl::NodeclBase& node)
{
define_generic_entities(node,
&CxxBase::declare_symbol_if_nonlocal_nonprototype,
&CxxBase::define_symbol_if_nonlocal_nonprototype,
&CxxBase::define_nonlocal_nonprototype_entities_in_trees,
&CxxBase::entry_just_define);
}
void CxxBase::define_local_entities_in_trees(const Nodecl::NodeclBase& node)
{
define_generic_entities(node,
&CxxBase::declare_symbol_if_local,
&CxxBase::define_symbol_if_local,
&CxxBase::define_local_entities_in_trees,
&CxxBase::entry_local_definition);
}
// This function is only for C
// Do not call it in C++
void CxxBase::walk_type_for_symbols(TL::Type t,
void (CxxBase::* symbol_to_declare)(TL::Symbol),
void (CxxBase::* symbol_to_define)(TL::Symbol),
void (CxxBase::* define_entities_in_tree)(const Nodecl::NodeclBase&),
bool needs_definition)
{
if (!t.is_valid())
return;
// This effectively poisons return, do not return from this function
#define return 1=1;
// This must be checked first since all query functions ignore typedefs
if (t.is_named()
&& t.get_symbol().is_typedef())
{
walk_type_for_symbols(
t.get_symbol().get_type(),
symbol_to_declare,
symbol_to_define,
define_entities_in_tree,
needs_definition);
(this->*symbol_to_define)(t.get_symbol());
}
else if (t.is_indirect())
{
walk_type_for_symbols(
t.get_symbol().get_type(),
symbol_to_declare,
symbol_to_define,
define_entities_in_tree,
needs_definition);
}
else if (t.is_pointer())
{
walk_type_for_symbols(t.points_to(), symbol_to_declare, symbol_to_define,
define_entities_in_tree,
/* needs_definition */ false);
}
else if (t.is_pointer_to_member())
{
walk_type_for_symbols(t.pointed_class(), symbol_to_declare, symbol_to_define,
define_entities_in_tree, /* needs_definition */ false);
walk_type_for_symbols(t.points_to(), symbol_to_declare, symbol_to_define,
define_entities_in_tree, /* needs_definition */ false);
}
else if (t.is_array())
{
(this->*define_entities_in_tree)(t.array_get_size());
walk_type_for_symbols(t.array_element(),
symbol_to_declare, symbol_to_define,
define_entities_in_tree);
}
else if (t.is_lvalue_reference()
|| t.is_rvalue_reference())
{
walk_type_for_symbols(t.references_to(),
symbol_to_declare, symbol_to_define,
define_entities_in_tree);
}
else if (t.is_function())
{
walk_type_for_symbols(t.returns(),
symbol_to_declare, symbol_to_define, define_entities_in_tree);
TL::ObjectList<TL::Type> params = t.parameters();
for (TL::ObjectList<TL::Type>::iterator it = params.begin();
it != params.end();
it++)
{
walk_type_for_symbols(*it,
symbol_to_declare,
symbol_to_define,
define_entities_in_tree);
}
TL::ObjectList<TL::Type> nonadjusted_params = t.nonadjusted_parameters();
for (TL::ObjectList<TL::Type>::iterator it = nonadjusted_params.begin();
it != nonadjusted_params.end();
it++)
{
walk_type_for_symbols(*it,
symbol_to_declare,
symbol_to_define,
define_entities_in_tree);
}
}
else if (t.is_vector())
{
walk_type_for_symbols(t.vector_element(), symbol_to_declare, symbol_to_define, define_entities_in_tree);
}
else if (t.is_named_class())
{
TL::Symbol class_entry = t.get_symbol();
if (needs_definition)
{
define_or_declare_if_complete(class_entry, symbol_to_declare, symbol_to_define);
}
else
{
(this->*symbol_to_declare)(class_entry);
}
}
else if (t.is_unnamed_class())
{
// Special case for nested members
// Bases
TL::ObjectList<TL::Type::BaseInfo> bases = t.get_bases();
for (TL::ObjectList<TL::Type::BaseInfo>::iterator it = bases.begin();
it != bases.end();
it++)
{
TL::Symbol &base_class(it->base);
define_or_declare_if_complete(base_class, symbol_to_declare, symbol_to_define);
}
// Members
TL::ObjectList<TL::Symbol> members = t.get_all_members();
for (TL::ObjectList<TL::Symbol>::iterator it = members.begin();
it != members.end();
it++)
{
walk_type_for_symbols(it->get_type(), symbol_to_declare, symbol_to_define, define_entities_in_tree);
}
}
else if (t.is_unnamed_enum())
{
TL::ObjectList<TL::Symbol> enumerators = t.enum_get_enumerators();
for (TL::ObjectList<TL::Symbol>::iterator it = enumerators.begin();
it != enumerators.end();
it++)
{
TL::Symbol &enumerator(*it);
(this->*define_entities_in_tree)(enumerator.get_value());
}
}
else if (t.is_named_enum())
{
TL::Symbol enum_entry = t.get_symbol();
// Only walk the enumerators if not already defined
if (get_codegen_status(enum_entry) != CODEGEN_STATUS_DEFINED)
{
walk_type_for_symbols(enum_entry.get_type(), symbol_to_declare, symbol_to_define, define_entities_in_tree);
}
define_or_declare_if_complete(enum_entry, symbol_to_declare, symbol_to_define);
}
else if (t.is_unresolved_overload())
{
TL::ObjectList<TL::Symbol> unresolved_set = t.get_unresolved_overload_set();
for (TL::ObjectList<TL::Symbol>::iterator it = unresolved_set.begin();
it != unresolved_set.end();
it++)
{
(this->*symbol_to_define)(*it);
}
}
else if (t.is_dependent_typename())
{
Nodecl::NodeclBase nodecl_parts = Nodecl::NodeclBase::null();
TL::Symbol dependent_entry(NULL);
t.dependent_typename_get_components(dependent_entry, nodecl_parts);
if (!(dependent_entry.is_class()
&& ::is_incomplete_type(dependent_entry.get_type().get_internal_type())))
{
(this->*symbol_to_define)(dependent_entry);
}
else
{
(this->*symbol_to_declare)(dependent_entry);
}
}
else
{
// Do nothing as it should be a builtin type
}
#undef return
}
void CxxBase::set_codegen_status(TL::Symbol sym, codegen_status_t status)
{
_codegen_status[sym] = status;
}
codegen_status_t CxxBase::get_codegen_status(TL::Symbol sym)
{
std::map<TL::Symbol, codegen_status_t>::iterator it = _codegen_status.find(sym);
if (it == _codegen_status.end())
{
return CODEGEN_STATUS_NONE;
}
else
{
return it->second;
}
}
void CxxBase::codegen_fill_namespace_list_rec(
scope_entry_t* namespace_sym,
scope_entry_t** list,
int* position)
{
ERROR_CONDITION(namespace_sym == NULL, "Invalid symbol", 0);
ERROR_CONDITION(namespace_sym->kind != SK_NAMESPACE, "Symbol '%s' is not a namespace", namespace_sym->symbol_name);
if (namespace_sym == state.global_namespace.get_internal_symbol())
{
*position = 0;
}
else
{
codegen_fill_namespace_list_rec(
namespace_sym->decl_context.current_scope->related_entry,
list,
position);
ERROR_CONDITION(*position == MCXX_MAX_SCOPES_NESTING, "Too many scopes", 0);
list[*position] = namespace_sym;
(*position)++;
}
}
void CxxBase::codegen_move_namespace_from_to(TL::Symbol from, TL::Symbol to)
{
scope_entry_t* namespace_nesting_from[MCXX_MAX_SCOPES_NESTING] = { 0 };
scope_entry_t* namespace_nesting_to[MCXX_MAX_SCOPES_NESTING] = { 0 };
int num_from = 0;
codegen_fill_namespace_list_rec(from.get_internal_symbol(), namespace_nesting_from, &num_from);
int num_to = 0;
codegen_fill_namespace_list_rec(to.get_internal_symbol(), namespace_nesting_to, &num_to);
// We only have to close and open the noncommon suffixes
int common;
for (common = 0;
(common < num_from)
&& (common < num_to)
&& (namespace_nesting_from[common] == namespace_nesting_to[common]);
common++)
{
// Empty body
}
int i;
for (i = common; i < num_from; i++)
{
dec_indent();
indent();
file << "}\n";
}
for (i = common; i < num_to; i++)
{
std::string real_name = namespace_nesting_to[i]->symbol_name;
set_codegen_status(namespace_nesting_to[i], CODEGEN_STATUS_DEFINED);
// Anonymous namespace has special properties that we want to preserve
if (real_name == "(unnamed)")
{
real_name = "/* anonymous */";
}
std::string gcc_attributes = "";
if (namespace_nesting_to[i]->entity_specs.num_gcc_attributes > 0)
{
gcc_attributes =
" " + gcc_attributes_to_str(namespace_nesting_to[i]);
}
indent();
file << "namespace " << real_name << gcc_attributes << " {\n";
if ((i + 1) < num_from)
{
file << " ";
}
inc_indent();
}
}
void CxxBase::move_to_namespace_of_symbol(TL::Symbol symbol)
{
C_LANGUAGE()
{
return;
}
// Get the namespace where this symbol has been declared
scope_t* enclosing_namespace = symbol.get_internal_symbol()->decl_context.namespace_scope;
scope_entry_t* namespace_sym = enclosing_namespace->related_entry;
// First close the namespaces
codegen_move_namespace_from_to(state.opened_namespace, namespace_sym);
state.opened_namespace = namespace_sym;
}
void CxxBase::move_to_namespace(TL::Symbol namespace_sym)
{
C_LANGUAGE()
{
return;
}
ERROR_CONDITION(!namespace_sym.is_namespace(), "This is not a namespace", 0);
// First close the namespaces
codegen_move_namespace_from_to(state.opened_namespace, namespace_sym.get_internal_symbol());
state.opened_namespace = namespace_sym.get_internal_symbol();
}
void CxxBase::indent()
{
for (int i = 0; i < state._indent_level; i++)
{
file << " ";
}
}
void CxxBase::inc_indent(int n)
{
state._indent_level += n;
}
void CxxBase::dec_indent(int n)
{
state._indent_level -= n;
}
int CxxBase::get_indent_level()
{
return state._indent_level;
}
void CxxBase::set_indent_level(int n)
{
state._indent_level = n;
}
void CxxBase::walk_list(const Nodecl::List& list, const std::string& separator, bool parenthesize_elements)
{
Nodecl::List::const_iterator it = list.begin(), begin = it;
bool default_argument = false;
while (it != list.end())
{
Nodecl::NodeclBase current_node = *it;
if (current_node.is<Nodecl::DefaultArgument>())
{
if (!default_argument)
{
default_argument = true;
file << "/* ";
}
current_node = current_node.as<Nodecl::DefaultArgument>().get_argument();
}
if (it != begin)
file << separator;
if (parenthesize_elements)
file << "(";
walk(current_node);
if (parenthesize_elements)
file << ")";
it++;
}
if (default_argument)
file << " */";
}
void CxxBase::walk_expression_list(const Nodecl::List& node)
{
walk_list(node, ", ");
}
template <typename Iterator>
void CxxBase::walk_expression_unpacked_list(Iterator begin, Iterator end)
{
Iterator it = begin;
while (it != end)
{
if (it != begin)
{
file << ", ";
}
walk(*it);
it++;
}
}
template < typename Node>
node_t CxxBase::get_kind_of_operator_function_call(const Node & node)
{
ERROR_CONDITION(!is_operator_function_call(node), "This function is not an operator\n", 0);
TL::Symbol called_sym = node.get_called().get_symbol();
std::string operator_name = called_sym.get_name().substr(std::string("operator ").size());
if (is_binary_infix_operator_function_call(node))
{
if (operator_name == "->*") return NODECL_CXX_ARROW_PTR_MEMBER;
else if (operator_name == ".*") return NODECL_CXX_DOT_PTR_MEMBER;
else if (operator_name == "*") return NODECL_MUL;
else if (operator_name == "/") return NODECL_DIV;
else if (operator_name == "%") return NODECL_MOD;
else if (operator_name == "+") return NODECL_ADD;
else if (operator_name == "-") return NODECL_MINUS;
else if (operator_name == "<<") return NODECL_BITWISE_SHL;
else if (operator_name == ">>") return NODECL_BITWISE_SHR;
else if (operator_name == "<") return NODECL_LOWER_THAN;
else if (operator_name == "<=") return NODECL_LOWER_OR_EQUAL_THAN;
else if (operator_name == ">") return NODECL_GREATER_THAN;
else if (operator_name == ">=") return NODECL_GREATER_OR_EQUAL_THAN;
else if (operator_name == "==") return NODECL_EQUAL;
else if (operator_name == "!=") return NODECL_DIFFERENT;
else if (operator_name == "&") return NODECL_BITWISE_AND;
else if (operator_name == "^") return NODECL_BITWISE_XOR;
else if (operator_name == "|") return NODECL_BITWISE_OR;
else if (operator_name == "&&") return NODECL_LOGICAL_AND;
else if (operator_name == "||") return NODECL_LOGICAL_OR;
else if (operator_name == "?") return NODECL_CONDITIONAL_EXPRESSION;
else if (operator_name == "=") return NODECL_ASSIGNMENT;
else if (operator_name == "*=") return NODECL_MUL_ASSIGNMENT;
else if (operator_name == "/=") return NODECL_DIV_ASSIGNMENT;
else if (operator_name == "%=") return NODECL_MOD_ASSIGNMENT;
else if (operator_name == "+=") return NODECL_ADD_ASSIGNMENT;
else if (operator_name == "-=") return NODECL_MINUS_ASSIGNMENT;
else if (operator_name == "<<=") return NODECL_BITWISE_SHL_ASSIGNMENT;
else if (operator_name == ">>=") return NODECL_BITWISE_SHR_ASSIGNMENT;
else if (operator_name == "&=") return NODECL_BITWISE_AND;
else if (operator_name == "|=") return NODECL_BITWISE_OR;
else if (operator_name == "^=") return NODECL_BITWISE_XOR;
else if (operator_name == ",") return NODECL_COMMA;
}
else
{
if (operator_name == "&") return NODECL_REFERENCE;
else if (operator_name == "*") return NODECL_DEREFERENCE;
else if (operator_name == "+") return NODECL_PLUS;
else if (operator_name == "-") return NODECL_NEG;
else if (operator_name == "!") return NODECL_LOGICAL_NOT;
else if (operator_name == "~") return NODECL_BITWISE_NOT;
else if (operator_name == "++" && is_unary_prefix_operator_function_call(node)) return NODECL_PREINCREMENT;
else if (operator_name == "++" && is_unary_postfix_operator_function_call(node)) return NODECL_POSTINCREMENT;
else if (operator_name == "--" && is_unary_prefix_operator_function_call(node)) return NODECL_PREDECREMENT;
else if (operator_name == "--" && is_unary_postfix_operator_function_call(node)) return NODECL_POSTDECREMENT;
}
internal_error("function operator '%s' is not supported yet\n", called_sym.get_name().c_str());
}
int CxxBase::get_rank_kind(node_t n, const std::string& text)
{
switch (n)
{
case NODECL_SYMBOL:
case NODECL_STRING_LITERAL:
case NODECL_INTEGER_LITERAL:
case NODECL_FLOATING_LITERAL:
case NODECL_BOOLEAN_LITERAL:
case NODECL_STRUCTURED_VALUE:
case NODECL_PARENTHESIZED_EXPRESSION:
case NODECL_COMPOUND_EXPRESSION:
case NODECL_CXX_DEP_NAME_SIMPLE:
case NODECL_CXX_DEP_NAME_NESTED:
case NODECL_CXX_DEP_GLOBAL_NAME_NESTED:
case NODECL_CXX_DEP_TEMPLATE_ID:
{
return -1;
}
case NODECL_ARRAY_SUBSCRIPT:
case NODECL_FUNCTION_CALL:
case NODECL_VIRTUAL_FUNCTION_CALL:
case NODECL_CLASS_MEMBER_ACCESS:
case NODECL_PSEUDO_DESTRUCTOR_NAME:
case NODECL_TYPEID:
case NODECL_POSTINCREMENT:
case NODECL_POSTDECREMENT:
case NODECL_CXX_ARROW:
case NODECL_CXX_POSTFIX_INITIALIZER:
case NODECL_CXX_ARRAY_SECTION_RANGE:
case NODECL_CXX_ARRAY_SECTION_SIZE:
case NODECL_CXX_EXPLICIT_TYPE_CAST:
case NODECL_CXX_DEP_FUNCTION_CALL:
{
return -2;
}
case NODECL_REFERENCE:
case NODECL_DEREFERENCE:
case NODECL_PLUS:
case NODECL_NEG:
case NODECL_LOGICAL_NOT:
case NODECL_BITWISE_NOT:
case NODECL_SIZEOF:
case NODECL_NEW:
case NODECL_DELETE:
case NODECL_DELETE_ARRAY:
case NODECL_PREINCREMENT:
case NODECL_PREDECREMENT:
case NODECL_REAL_PART:
case NODECL_IMAG_PART:
// FIXME: Missing GCC nodes
// FIXME: Do we want them or we can use builtins?
// case NODECL_ALIGNOF
// case NODECL_LABEL_ADDR
case NODECL_CXX_SIZEOF:
case NODECL_CXX_ALIGNOF:
{
return -3;
}
// This one is special as we keep several casts in a single node
case NODECL_CAST:
{
if (IS_C_LANGUAGE
|| (text == "C"))
{
return -4;
}
else
{
// These casts are postfix expressions actually
// static_cast, dynamic_cast, reinterpret_cast, const_cast
return -2;
}
}
// This is a pointer to member
case NODECL_OFFSET:
case NODECL_CXX_ARROW_PTR_MEMBER:
case NODECL_CXX_DOT_PTR_MEMBER:
return -5;
case NODECL_MUL:
case NODECL_DIV:
case NODECL_MOD:
return -6;
case NODECL_ADD:
case NODECL_MINUS:
return -7;
case NODECL_BITWISE_SHL:
case NODECL_BITWISE_SHR:
case NODECL_ARITHMETIC_SHR:
return -8;
case NODECL_LOWER_THAN:
case NODECL_LOWER_OR_EQUAL_THAN:
case NODECL_GREATER_THAN:
case NODECL_GREATER_OR_EQUAL_THAN:
return -9;
case NODECL_EQUAL:
case NODECL_DIFFERENT:
return -10;
case NODECL_BITWISE_AND:
return -11;
case NODECL_BITWISE_XOR:
return -12;
case NODECL_BITWISE_OR:
return -13;
case NODECL_LOGICAL_AND:
return -14;
case NODECL_LOGICAL_OR:
return -15;
case NODECL_CONDITIONAL_EXPRESSION:
case NODECL_ASSIGNMENT:
case NODECL_MUL_ASSIGNMENT:
case NODECL_DIV_ASSIGNMENT:
case NODECL_MOD_ASSIGNMENT:
case NODECL_ADD_ASSIGNMENT:
case NODECL_MINUS_ASSIGNMENT:
case NODECL_BITWISE_SHL_ASSIGNMENT:
case NODECL_BITWISE_SHR_ASSIGNMENT:
case NODECL_ARITHMETIC_SHR_ASSIGNMENT:
case NODECL_BITWISE_AND_ASSIGNMENT:
case NODECL_BITWISE_OR_ASSIGNMENT:
case NODECL_BITWISE_XOR_ASSIGNMENT:
case NODECL_THROW:
return -16;
case NODECL_COMMA:
return -17;
default:
// Lowest priority possible. This is a conservative approach that
// will work always albeit it will introduce some unnecessary
// parentheses for unknown expressions
return -1000;
}
return -1000;
}
int CxxBase::get_rank(const Nodecl::NodeclBase &n)
{
if (n.is<Nodecl::Conversion>())
{
return get_rank(n.as<Nodecl::Conversion>().get_nest());
}
else
{
node_t kind;
if (n.is<Nodecl::FunctionCall>()
&& is_operator_function_call(n.as<Nodecl::FunctionCall>()))
{
kind = get_kind_of_operator_function_call(n.as<Nodecl::FunctionCall>());
}
else if (n.is<Nodecl::VirtualFunctionCall>()
&& is_operator_function_call(n.as<Nodecl::VirtualFunctionCall>()))
{
kind = get_kind_of_operator_function_call(n.as<Nodecl::VirtualFunctionCall>());
}
else
{
kind = n.get_kind();
}
return get_rank_kind(kind, n.get_text());
}
}
static char is_bitwise_bin_operator(node_t n)
{
return n == NODECL_BITWISE_AND
|| n == NODECL_BITWISE_OR
|| n == NODECL_BITWISE_XOR;
}
static char is_logical_bin_operator(node_t n)
{
return n == NODECL_LOGICAL_AND
|| n == NODECL_LOGICAL_OR;
}
static char is_shift_bin_operator(node_t n)
{
return n == NODECL_BITWISE_SHL
|| n == NODECL_BITWISE_SHR
|| n == NODECL_ARITHMETIC_SHR;
}
static char is_additive_bin_operator(node_t n)
{
return n == NODECL_ADD
|| n == NODECL_MINUS;
}
bool CxxBase::same_operation(Nodecl::NodeclBase current_operator, Nodecl::NodeclBase operand)
{
if (current_operator.is<Nodecl::Conversion>())
{
current_operator = current_operator.as<Nodecl::Conversion>().get_nest();
}
if (operand.is<Nodecl::Conversion>())
{
operand = operand.as<Nodecl::Conversion>().get_nest();
}
int rank_current = get_rank(current_operator);
int rank_operand = get_rank(operand);
return (current_operator.get_kind() == operand.get_kind())
|| (rank_current == rank_operand);
}
bool CxxBase::operand_has_lower_priority(Nodecl::NodeclBase current_operator, Nodecl::NodeclBase operand)
{
if (current_operator.is<Nodecl::Conversion>())
{
current_operator = current_operator.as<Nodecl::Conversion>().get_nest();
}
if (operand.is<Nodecl::Conversion>())
{
operand = operand.as<Nodecl::Conversion>().get_nest();
}
int rank_current = get_rank(current_operator);
int rank_operand = get_rank(operand);
node_t current_kind = current_operator.get_kind();
node_t operand_kind = operand.get_kind();
// For the sake of clarity and to avoid warnings emitted by gcc
if (0
// a || b && c -> a || (b && c)
|| (is_logical_bin_operator(current_kind) && is_logical_bin_operator(operand_kind))
// a | b & c -> a | (b & c)
|| (is_bitwise_bin_operator(current_kind) && is_bitwise_bin_operator(operand_kind))
// a << b - c -> a << (b - c)
|| (is_shift_bin_operator(current_kind) && is_additive_bin_operator(operand_kind))
// a + b & c -> (a + b) & c
|| (is_bitwise_bin_operator(current_kind) && is_additive_bin_operator(operand_kind))
)
{
return 1;
}
return rank_operand < rank_current;
}
std::string CxxBase::quote_c_string(int* c, int length, char is_wchar)
{
std::string result;
if (is_wchar)
{
result += "L";
}
result += "\"";
int i;
for (i = 0; i < length; i++)
{
int current = c[i];
if (current == '\n')
{
result += "\\n";
}
else if (current == '\'')
{
result += "\\\'";
}
else if (current == '"')
{
result += "\\\"";
}
else if (current == '?')
{
result += "\\?";
}
else if (current == '\\')
{
result += "\\\\";
}
else if (current == '\a')
{
result += "\\a";
}
else if (current == '\b')
{
result += "\\b";
}
else if (current == '\f')
{
result += "\\f";
}
else if (current == '\n')
{
result += "\\n";
}
else if (current == '\r')
{
result += "\\r";
}
else if (current == '\t')
{
result += "\\t";
}
else if (current == '\v')
{
result += "\\v";
}
else if (isprint(current))
{
std::string str(1, (char)current);
result += str;
}
// Best effort
else
{
std::stringstream ss;
if (!is_wchar
|| (current < 255))
{
ss << "\\"
<< std::oct << std::setw(3) << std::setfill('0')
<< (unsigned int) current
<< std::setw(0) << std::dec;
result += ss.str();
}
else
{
ss << "\\U"
<< std::hex << std::setw(8) << std::setfill('0')
<< current
<< std::dec << std::setw(0);
result += ss.str();
}
}
}
result += "\"";
return result;
}
bool CxxBase::nodecl_calls_to_constructor(const Nodecl::NodeclBase& node, TL::Type t)
{
if (node.is<Nodecl::FunctionCall>())
{
TL::Symbol called_sym = node.as<Nodecl::FunctionCall>().get_called().get_symbol();
if (called_sym.is_valid()
&& called_sym.is_constructor())
{
return (!t.is_valid())
|| (t.no_ref()
.get_unqualified_type()
.is_same_type(called_sym.get_class_type().get_unqualified_type()));
}
}
return 0;
}
bool CxxBase::nodecl_is_zero_args_call_to_constructor(Nodecl::NodeclBase node)
{
return (nodecl_calls_to_constructor(node, TL::Type(NULL))
&& node.as<Nodecl::FunctionCall>().get_arguments().as<Nodecl::List>().empty());
}
bool CxxBase::nodecl_is_zero_args_structured_value(Nodecl::NodeclBase node)
{
return (node.is<Nodecl::StructuredValue>()
&& (node.as<Nodecl::StructuredValue>().get_items().is_null()
|| node.as<Nodecl::StructuredValue>().get_items().as<Nodecl::List>().empty()));
}
std::string CxxBase::unmangle_symbol_name(TL::Symbol symbol)
{
return ::unmangle_symbol_name(symbol.get_internal_symbol());
}
void CxxBase::codegen_template_headers_bounded(
TL::TemplateParameters template_parameters,
TL::TemplateParameters lim,
bool show_default_values)
{
if (!template_parameters.is_valid())
return;
if (template_parameters != lim)
{
if (template_parameters.has_enclosing_parameters())
{
TL::TemplateParameters enclosing_template_parameters =
template_parameters.get_enclosing_parameters();
// We only print the default arguments of the innermost template header.
// For this reason we set show_default_values to false
codegen_template_headers_bounded(
enclosing_template_parameters, lim,
/* show_default_values */ false);
}
codegen_template_header(template_parameters, show_default_values);
}
}
void CxxBase::codegen_template_headers_all_levels(
TL::TemplateParameters template_parameters,
bool show_default_values)
{
if (!template_parameters.is_valid())
return;
if (template_parameters.has_enclosing_parameters())
{
TL::TemplateParameters enclosing_template_parameters =
template_parameters.get_enclosing_parameters();
// We only print the default arguments of the innermost template header
// For this reason we set show_default_values to false
codegen_template_headers_all_levels(
enclosing_template_parameters,
/* show_default_values */ false);
}
codegen_template_header(template_parameters, show_default_values);
}
void CxxBase::codegen_template_header(
TL::TemplateParameters template_parameters,
bool show_default_values,
bool endline)
{
if (!template_parameters.is_valid())
return;
indent();
if (template_parameters.get_is_explicit_specialization())
{
file << "template <>";
if (endline)
file << "\n";
return;
}
file << "template < ";
for (int i = 0; i < template_parameters.get_num_parameters(); i++)
{
std::pair<TL::Symbol,
TL::TemplateParameters::TemplateParameterKind>
tpl_param = template_parameters.get_parameter_num(i);
TL::Symbol symbol = tpl_param.first;
if (i != 0)
{
file << ", ";
}
switch (tpl_param.second)
{
case TPK_TYPE:
{
file << "typename " << symbol.get_name();
break;
}
case TPK_NONTYPE:
{
std::string declaration = this->get_declaration(symbol.get_type(),
symbol.get_scope(),
symbol.get_name());
file << declaration;
break;
}
case TPK_TEMPLATE:
{
TL::Type template_type = symbol.get_type();
codegen_template_header(
symbol.get_type().template_type_get_template_parameters(),
show_default_values,
/* endline */ false);
file << " class " << symbol.get_name();
break;
}
default:
{
internal_error("Invalid template parameter kind", 0);
}
}
// Has this template parameter a default value?
if (show_default_values &&
template_parameters.has_argument(i))
{
TL::TemplateArgument temp_arg = template_parameters.get_argument_num(i);
if (temp_arg.is_default())
{
file << " = ";
switch (tpl_param.second)
{
case TPK_TYPE:
case TPK_TEMPLATE:
{
TL::Type temp_arg_type = temp_arg.get_type();
file <<
this->print_type_str(
temp_arg_type.get_internal_type(),
symbol.get_scope().get_decl_context(),
/* we need to store the current codegen */ (void*) this);
break;
}
case TPK_NONTYPE:
{
push_scope(symbol.get_scope());
walk(temp_arg.get_value());
pop_scope();
break;
}
default:
{
internal_error("code unreachable", 0);
}
}
}
}
}
file << " >";
if (endline)
file << "\n";
}
std::string CxxBase::gcc_attributes_to_str(TL::Symbol symbol)
{
std::string result;
TL::ObjectList<TL::GCCAttribute> gcc_attr_list = symbol.get_gcc_attributes();
int attributes_counter = 0;
bool print_cuda_attributes = cuda_print_special_attributes();
for (TL::ObjectList<TL::GCCAttribute>::iterator it = gcc_attr_list.begin();
it != gcc_attr_list.end();
it++)
{
if (attributes_counter > 0)
result += " ";
if (!print_cuda_attributes
&& (it->get_attribute_name() == "host"
|| it->get_attribute_name() == "device"
|| it->get_attribute_name() == "shared"
|| it->get_attribute_name() == "constant"
|| it->get_attribute_name() == "global"))
continue;
if (it->get_expression_list().is_null())
{
result += "__attribute__((" + it->get_attribute_name() + "))";
}
else
{
result += "__attribute__((" + it->get_attribute_name() + "(";
std::string old_str = file.str();
file.clear();
file.str("");
walk_expression_list(it->get_expression_list().as<Nodecl::List>());
result += file.str();
file.clear();
file.str(old_str);
// Go to the end of the stream...
file.seekp(0, std::ios_base::end);
result += ")))";
}
attributes_counter++;
}
return result;
}
std::string CxxBase::ms_attributes_to_str(TL::Symbol symbol)
{
std::string result;
TL::ObjectList<TL::MSAttribute> ms_attr_list = symbol.get_ms_attributes();
int attributes_counter = 0;
for (TL::ObjectList<TL::MSAttribute>::iterator it = ms_attr_list.begin();
it != ms_attr_list.end();
it++)
{
if (attributes_counter > 0)
result += " ";
if (it->get_expression_list().is_null())
{
result += "__declspec(" + it->get_attribute_name() + ")";
}
else
{
result += "__declspec(" + it->get_attribute_name() + "(";
std::string old_str = file.str();
file.clear();
file.str("");
walk_expression_list(it->get_expression_list().as<Nodecl::List>());
result += file.str();
file.clear();
file.str(old_str);
// Go to the end of the stream...
file.seekp(0, std::ios_base::end);
result += "))";
}
attributes_counter++;
}
return result;
}
std::string CxxBase::gcc_asm_specifier_to_str(TL::Symbol symbol)
{
std::string result;
if (!symbol.get_asm_specification().is_null())
{
std::string old_str = file.str();
file.clear();
file.str("");
walk(symbol.get_asm_specification());
result = file.str();
file.clear();
file.str(old_str);
// Go to the end of the stream...
file.seekp(0, std::ios_base::end);
}
return result;
}
std::string CxxBase::exception_specifier_to_str(TL::Symbol symbol)
{
std::string exception_spec;
CXX_LANGUAGE()
{
if (!symbol.function_throws_any_exception())
{
exception_spec += " throw(";
TL::ObjectList<TL::Type> exceptions = symbol.get_thrown_exceptions();
for (TL::ObjectList<TL::Type>::iterator it = exceptions.begin();
it != exceptions.end();
it++)
{
if (it != exceptions.begin())
{
exception_spec += ", ";
}
exception_spec += this->get_declaration(*it, symbol.get_scope(), "");
}
exception_spec += ")";
}
}
return exception_spec;
}
std::string CxxBase::template_arguments_to_str(TL::Symbol symbol)
{
return ::get_template_arguments_str(symbol.get_internal_symbol(), symbol.get_scope().get_decl_context());
}
CxxBase::Ret CxxBase::unhandled_node(const Nodecl::NodeclBase & n)
{
indent();
file << "/* >>> " << ast_print_node_type(n.get_kind()) << " >>> */\n";
inc_indent();
TL::ObjectList<Nodecl::NodeclBase> children = n.children();
int i = 0;
for (TL::ObjectList<Nodecl::NodeclBase>::iterator it = children.begin();
it != children.end();
it++, i++)
{
indent();
file << "/* Children " << i << " */\n";
walk(*it);
}
dec_indent();
indent();
file << "/* <<< " << ast_print_node_type(n.get_kind()) << " <<< */\n";
}
const char* CxxBase::print_name_str(scope_entry_t* sym, decl_context_t decl_context, void *data)
{
// We obtain the current codegen from the data
CxxBase* _this = (CxxBase*) data;
// The variable data must contain a valid pointer to the current codegen
ERROR_CONDITION(_this == NULL, "Invalid this", 0);
ERROR_CONDITION(sym == NULL, "Invalid symbol", 0);
const char* result = NULL;
if (IS_CXX_LANGUAGE
&& _this->get_codegen_status(sym) == CODEGEN_STATUS_NONE
&& ((sym->kind == SK_CLASS && !is_template_specialized_type(sym->type_information))
|| sym->kind == SK_ENUM))
{
result = sym->symbol_name;
if (sym->kind == SK_ENUM)
{
result = strappend("enum ", result);
}
else if (sym->kind == SK_CLASS)
{
switch (class_type_get_class_kind(sym->type_information))
{
case TT_UNION:
result = strappend("union ", result); break;
case TT_STRUCT:
result = strappend("struct ", result); break;
case TT_CLASS:
result = strappend("class ", result); break;
default:
internal_error("Code unreachable", 0);
}
}
}
else
{
char is_dependent = 0;
int max_level = 0;
result =
get_fully_qualified_symbol_name_ex(sym,
decl_context, &is_dependent, &max_level,
/* no_templates */ 0, /* only_classes */ 0,
/* do_not_emit_template_keywords */ 0,
print_type_str,
data);
// If is a dependent name and it is qualified then it can be
// given a "typename" keyword (in some cases one must do that)
if (is_dependent && max_level > 0)
{
result = strappend("typename ", result);
}
if (IS_CXX_LANGUAGE
&& (sym->kind == SK_CLASS
|| sym->kind == SK_ENUM))
{
// It may happen that a function is hiding our typename in this scope
scope_entry_list_t* entry_list = query_in_scope_str(sym->decl_context, sym->symbol_name);
entry_list = filter_symbol_using_predicate(entry_list,
is_function_or_template_function_name_or_extern_variable, NULL);
// It seems somebody is hiding our name in this scope
if (entry_list != NULL)
{
if (sym->kind == SK_ENUM)
{
result = strappend("enum ", result);
}
else if (sym->kind == SK_CLASS)
{
switch (class_type_get_class_kind(sym->type_information))
{
case TT_UNION:
result = strappend("union ", result); break;
case TT_STRUCT:
result = strappend("struct ", result); break;
case TT_CLASS:
result = strappend("class ", result); break;
default:
internal_error("Code unreachable", 0);
}
}
}
entry_list_free(entry_list);
}
}
return result;
}
const char* CxxBase::print_type_str(type_t* t, decl_context_t decl_context, void *data)
{
const char* result = NULL;
if (t == NULL)
{
result = uniquestr("< unknown type >");
}
else
{
result = get_declaration_string_ex(t,
decl_context, /* symbol_name */"",
/* initializer */ "",
/* semicolon */ 0,
/* num_parameter_names */ 0,
/* parameter_names */ NULL,
/* parameter_attributes */ NULL,
/* is_parameter */ 0,
print_name_str,
data);
}
return result;
}
std::string CxxBase::get_declaration(TL::Type t, TL::Scope scope, const std::string& name)
{
t = fix_references(t);
return get_declaration_string_ex(t.get_internal_type(), scope.get_decl_context(),
name.c_str(), "", 0, 0, NULL, NULL, /* is_parameter */ 0, print_name_str,
/* we need to store the current codegen */ (void*) this);
}
std::string CxxBase::get_declaration_only_declarator(TL::Type t, TL::Scope scope, const std::string& name)
{
t = fix_references(t);
return get_declarator_name_string_ex(
scope.get_decl_context(),
t.get_internal_type(),
name.c_str(),
/* num_parameter_names */ 0,
/* parameter_names */ NULL,
/* parameter_attributes */ NULL,
/* is_parameter */ 0,
print_name_str,
/* we need to store the current codegen */ (void*) this);
}
std::string CxxBase::get_qualified_name(TL::Symbol sym, bool without_template_id) const
{
return this->get_qualified_name(sym, sym.get_scope(), without_template_id);
}
std::string CxxBase::get_qualified_name(TL::Symbol sym, TL::Scope sc, bool without_template_id) const
{
if (sym.get_internal_symbol()->symbol_name == NULL)
{
return std::string("");
}
else
{
const char* result = NULL;
int max_level = 0;
char is_dependent = 0;
if (without_template_id)
{
result = get_fully_qualified_symbol_name_ex(sym.get_internal_symbol(),
sc.get_decl_context(), &is_dependent, &max_level,
/* no_templates */ 1, /* only_classes */ 0,
/* do_not_emit_template_keywords */ 0,
print_type_str,
/* we need to store the current codegen */ (void*) this);
}
else
{
result = get_fully_qualified_symbol_name_ex(sym.get_internal_symbol(),
sc.get_decl_context(), &is_dependent, &max_level,
/* no_templates */ 0, /* only_classes */ 0,
/* do_not_emit_template_keywords */ 0,
print_type_str,
/* we need to store the current codegen */ (void*) this);
}
return std::string(result);
}
}
void CxxBase::fill_parameter_names_and_parameter_attributes(TL::Symbol symbol,
TL::ObjectList<std::string>& parameter_names,
TL::ObjectList<std::string>& parameter_attributes)
{
ERROR_CONDITION(!symbol.is_function()
&& !symbol.is_dependent_friend_function(), "This symbol should be a function\n", -1);
int i = 0;
TL::ObjectList<TL::Symbol> related_symbols = symbol.get_related_symbols();
for (TL::ObjectList<TL::Symbol>::iterator it = related_symbols.begin();
it != related_symbols.end();
it++, i++)
{
TL::Symbol current_param = *it;
if (current_param.is_valid())
{
if(!current_param.not_to_be_printed())
{
parameter_names[i] = current_param.get_name();
}
if (current_param.has_gcc_attributes())
{
parameter_attributes[i] = gcc_attributes_to_str(current_param);
}
if (get_codegen_status(current_param) != CODEGEN_STATUS_DEFINED
&& symbol.has_default_argument_num(i))
{
parameter_attributes[i] += " = " + codegen(symbol.get_default_argument_num(i));
}
set_codegen_status(current_param, CODEGEN_STATUS_DEFINED);
}
}
}
std::string CxxBase::get_declaration_with_parameters(TL::Type t,
TL::Scope scope,
const std::string& symbol_name,
TL::ObjectList<std::string>& parameters,
TL::ObjectList<std::string>& parameter_attributes)
{
t = fix_references(t);
int num_parameters = t.parameters().size();
const char** parameter_names = new const char*[num_parameters + 1];
const char** param_attributes = new const char*[num_parameters + 1];
for (int i = 0; i < num_parameters; i++)
{
parameter_names[i] = NULL;
param_attributes[i] = NULL;
}
int orig_size = parameters.size();
for (int i = 0; i < orig_size; i++)
{
parameter_names[i] = uniquestr(parameters[i].c_str());
param_attributes[i] = uniquestr(parameter_attributes[i].c_str());
}
const char* result = get_declaration_string_ex(t.get_internal_type(),
scope.get_decl_context(), symbol_name.c_str(), "", 0,
num_parameters, parameter_names, param_attributes,
/* is_parameter */ 1, print_name_str,
/* we need to store the current codegen */ (void*) this);
for (int i = 0; i < num_parameters; i++)
{
if (i < orig_size)
{
parameters[i] = parameter_names[i];
}
else
{
if (parameter_names[i] != NULL)
parameters.append(parameter_names[i]);
else
parameters.append("");
}
}
delete[] parameter_names;
delete[] param_attributes;
return result;
}
TL::Type CxxBase::fix_references(TL::Type t)
{
if (is_non_language_reference_type(t))
{
TL::Type ref = t.references_to();
if (ref.is_array())
{
// T (&a)[10] -> T * const
// T (&a)[10][20] -> T (* const)[20]
ref = ref.array_element();
}
// T &a -> T * const a
TL::Type ptr = ref.get_pointer_to();
if (!t.is_rebindable_reference())
{
ptr = ptr.get_const_type();
}
return ptr;
}
else if (t.is_array())
{
if (t.array_is_region())
{
Nodecl::NodeclBase lb, reg_lb, ub, reg_ub;
t.array_get_bounds(lb, ub);
t.array_get_region_bounds(reg_lb, reg_ub);
TL::Scope sc = array_type_get_region_size_expr_context(t.get_internal_type());
return fix_references(t.array_element()).get_array_to_with_region(lb, ub, reg_lb, reg_ub, sc);
}
else
{
Nodecl::NodeclBase size = t.array_get_size();
TL::Scope sc = array_type_get_array_size_expr_context(t.get_internal_type());
return fix_references(t.array_element()).get_array_to(size, sc);
}
}
else if (t.is_pointer())
{
TL::Type fixed = fix_references(t.points_to()).get_pointer_to();
fixed = ::get_cv_qualified_type(fixed.get_internal_type(),
get_cv_qualifier(t.get_internal_type()));
return fixed;
}
else if (t.is_function())
{
// Do not fix unprototyped functions
if (t.lacks_prototype())
return t;
cv_qualifier_t cv_qualif = get_cv_qualifier(t.get_internal_type());
TL::Type fixed_result = fix_references(t.returns());
bool has_ellipsis = 0;
TL::ObjectList<TL::Type> fixed_parameters = t.parameters(has_ellipsis);
for (TL::ObjectList<TL::Type>::iterator it = fixed_parameters.begin();
it != fixed_parameters.end();
it++)
{
*it = fix_references(*it);
}
TL::ObjectList<TL::Type> nonadjusted_fixed_parameters = t.nonadjusted_parameters();
for (TL::ObjectList<TL::Type>::iterator it = nonadjusted_fixed_parameters.begin();
it != nonadjusted_fixed_parameters.end();
it++)
{
*it = fix_references(*it);
}
TL::Type fixed_function = fixed_result.get_function_returning(
fixed_parameters,
nonadjusted_fixed_parameters,
has_ellipsis);
fixed_function = TL::Type(get_cv_qualified_type(fixed_function.get_internal_type(), cv_qualif));
return fixed_function;
}
// Note: we are not fixing classes
else
{
// Anything else must be left untouched
return t;
}
}
bool CxxBase::cuda_print_special_attributes()
{
return false;
}
bool CxxBase::cuda_emit_always_extern_linkage()
{
return false;
}
CxxBase::CxxBase()
{
set_phase_name("C/C++ codegen");
set_phase_description("This phase emits in C/C++ the intermediate representation of the compiler");
_emit_saved_variables_as_unused = false;
register_parameter("emit_saved_variables_as_unused",
"Emits saved-expression variables as __attribute__((unused))",
_emit_saved_variables_as_unused_str,
"0").connect(functor(&CxxBase::set_emit_saved_variables_as_unused, *this));
_prune_saved_variables = true;
register_parameter("prune_saved_variables",
"Disables removal of unused saved-expression variables. If you need to enable this, please report a ticket",
_prune_saved_variables_str,
"1").connect(functor(&CxxBase::set_prune_saved_variables, *this));
}
void CxxBase::set_emit_saved_variables_as_unused(const std::string& str)
{
TL::parse_boolean_option("emit_saved_variables_as_unused", str, _emit_saved_variables_as_unused, "Assuming false.");
}
void CxxBase::set_prune_saved_variables(const std::string& str)
{
TL::parse_boolean_option("prune_saved_variables", str, _prune_saved_variables, "Assuming true.");
}
} // Codegen
EXPORT_PHASE(Codegen::CxxBase)
|
drpicox/mcxx
|
src/tl/codegen/base/cxx/codegen-cxx.cpp
|
C++
|
lgpl-3.0
| 228,310
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>pulsesink</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="index.html" title="GStreamer Good Plugins 0.10 Plugins Reference Manual">
<link rel="up" href="ch01.html" title="gst-plugins-good Elements">
<link rel="prev" href="gst-plugins-good-plugins-progressreport.html" title="progressreport">
<link rel="next" href="gst-plugins-good-plugins-pulsesrc.html" title="pulsesrc">
<meta name="generator" content="GTK-Doc V1.15 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="2">
<tr valign="middle">
<td><a accesskey="p" href="gst-plugins-good-plugins-progressreport.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td>
<td><a accesskey="u" href="ch01.html"><img src="up.png" width="24" height="24" border="0" alt="Up"></a></td>
<td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td>
<th width="100%" align="center">GStreamer Good Plugins 0.10 Plugins Reference Manual</th>
<td><a accesskey="n" href="gst-plugins-good-plugins-pulsesrc.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td>
</tr>
<tr><td colspan="5" class="shortcuts">
<a href="#gst-plugins-good-plugins-pulsesink.synopsis" class="shortcut">Top</a>
|
<a href="#gst-plugins-good-plugins-pulsesink.description" class="shortcut">Description</a>
|
<a href="#gst-plugins-good-plugins-pulsesink.object-hierarchy" class="shortcut">Object Hierarchy</a>
|
<a href="#gst-plugins-good-plugins-pulsesink.implemented-interfaces" class="shortcut">Implemented Interfaces</a>
|
<a href="#gst-plugins-good-plugins-pulsesink.properties" class="shortcut">Properties</a>
</td></tr>
</table>
<div class="refentry" title="pulsesink">
<a name="gst-plugins-good-plugins-pulsesink"></a><div class="titlepage"></div>
<div class="refnamediv"><table width="100%"><tr>
<td valign="top">
<h2><span class="refentrytitle"><a name="gst-plugins-good-plugins-pulsesink.top_of_page"></a>pulsesink</span></h2>
<p>pulsesink — Plays audio to a PulseAudio server</p>
</td>
<td valign="top" align="right"></td>
</tr></table></div>
<div class="refsynopsisdiv" title="Synopsis">
<a name="gst-plugins-good-plugins-pulsesink.synopsis"></a><h2>Synopsis</h2>
<a name="GstPulseSink"></a><pre class="synopsis"> <a class="link" href="gst-plugins-good-plugins-pulsesink.html#GstPulseSink-struct" title="GstPulseSink">GstPulseSink</a>;
</pre>
</div>
<div class="refsect1" title="Object Hierarchy">
<a name="gst-plugins-good-plugins-pulsesink.object-hierarchy"></a><h2>Object Hierarchy</h2>
<pre class="synopsis">
<a href="/usr/share/gtk-doc/html/gobject/gobject-The-Base-Object-Type.html#GObject">GObject</a>
+----<a href="/usr/share/gtk-doc/html/gstreamer-0.10/GstObject.html">GstObject</a>
+----<a href="/usr/share/gtk-doc/html/gstreamer-0.10/GstElement.html">GstElement</a>
+----<a href="/usr/share/gtk-doc/html/gstreamer-libs-0.10/GstBaseSink.html">GstBaseSink</a>
+----<a href="/usr/share/gtk-doc/html/gst-plugins-base-libs-0.10/gst-plugins-base-libs-gstbaseaudiosink.html#GstBaseAudioSink">GstBaseAudioSink</a>
+----GstPulseSink
</pre>
</div>
<div class="refsect1" title="Implemented Interfaces">
<a name="gst-plugins-good-plugins-pulsesink.implemented-interfaces"></a><h2>Implemented Interfaces</h2>
<p>
GstPulseSink implements
<a href="/usr/share/gtk-doc/html/gst-plugins-base-libs-0.10/gst-plugins-base-libs-gststreamvolume.html#GstStreamVolume">GstStreamVolume</a>, <a href="/usr/share/gtk-doc/html/gstreamer-0.10/GstImplementsInterface.html">GstImplementsInterface</a> and <a href="/usr/share/gtk-doc/html/gst-plugins-base-libs-0.10/gst-plugins-base-libs-gstpropertyprobe.html#GstPropertyProbe">GstPropertyProbe</a>.</p>
</div>
<div class="refsect1" title="Properties">
<a name="gst-plugins-good-plugins-pulsesink.properties"></a><h2>Properties</h2>
<pre class="synopsis">
"<a class="link" href="gst-plugins-good-plugins-pulsesink.html#GstPulseSink--device" title='The "device" property'>device</a>" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a>* : Read / Write
"<a class="link" href="gst-plugins-good-plugins-pulsesink.html#GstPulseSink--server" title='The "server" property'>server</a>" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a>* : Read / Write
"<a class="link" href="gst-plugins-good-plugins-pulsesink.html#GstPulseSink--device-name" title='The "device-name" property'>device-name</a>" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a>* : Read
"<a class="link" href="gst-plugins-good-plugins-pulsesink.html#GstPulseSink--volume" title='The "volume" property'>volume</a>" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gdouble"><span class="type">gdouble</span></a> : Read / Write
"<a class="link" href="gst-plugins-good-plugins-pulsesink.html#GstPulseSink--mute" title='The "mute" property'>mute</a>" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gboolean"><span class="type">gboolean</span></a> : Read / Write
</pre>
</div>
<div class="refsect1" title="Description">
<a name="gst-plugins-good-plugins-pulsesink.description"></a><h2>Description</h2>
<p>
This element outputs audio to a
<a class="ulink" href="" target="_top">PulseAudio sound server</a>.
</p>
<div class="refsect2" title="Example pipelines">
<a name="id588943"></a><h3>Example pipelines</h3>
<div class="informalexample">
<table class="listing_frame" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td class="listing_lines" align="right"><pre>1</pre></td>
<td class="listing_code"><pre class="programlisting">gst<span class="symbol">-</span>launch <span class="symbol">-</span>v filesrc location<span class="symbol">=</span>sine<span class="symbol">.</span>ogg <span class="symbol">!</span> oggdemux <span class="symbol">!</span> vorbisdec <span class="symbol">!</span> audioconvert <span class="symbol">!</span> audioresample <span class="symbol">!</span> pulsesink</pre></td>
</tr>
</tbody>
</table>
</div>
Play an Ogg/Vorbis file.
<div class="informalexample">
<table class="listing_frame" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td class="listing_lines" align="right"><pre>1</pre></td>
<td class="listing_code"><pre class="programlisting">gst<span class="symbol">-</span>launch <span class="symbol">-</span>v audiotestsrc <span class="symbol">!</span> audioconvert <span class="symbol">!</span> volume volume<span class="symbol">=</span><span class="number">0.4</span> <span class="symbol">!</span> pulsesink</pre></td>
</tr>
</tbody>
</table>
</div>
Play a 440Hz sine wave.
</div>
</div>
<div class="refsect1" title="Details">
<a name="gst-plugins-good-plugins-pulsesink.details"></a><h2>Details</h2>
<div class="refsect2" title="GstPulseSink">
<a name="GstPulseSink-struct"></a><h3>GstPulseSink</h3>
<pre class="programlisting">typedef struct _GstPulseSink GstPulseSink;</pre>
<p>
</p>
</div>
</div>
<div class="refsect1" title="Property Details">
<a name="gst-plugins-good-plugins-pulsesink.property-details"></a><h2>Property Details</h2>
<div class="refsect2" title='The "device" property'>
<a name="GstPulseSink--device"></a><h3>The <code class="literal">"device"</code> property</h3>
<pre class="programlisting"> "device" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a>* : Read / Write</pre>
<p>The PulseAudio sink device to connect to.</p>
<p>Default value: NULL</p>
</div>
<hr>
<div class="refsect2" title='The "server" property'>
<a name="GstPulseSink--server"></a><h3>The <code class="literal">"server"</code> property</h3>
<pre class="programlisting"> "server" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a>* : Read / Write</pre>
<p>The PulseAudio server to connect to.</p>
<p>Default value: NULL</p>
</div>
<hr>
<div class="refsect2" title='The "device-name" property'>
<a name="GstPulseSink--device-name"></a><h3>The <code class="literal">"device-name"</code> property</h3>
<pre class="programlisting"> "device-name" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a>* : Read</pre>
<p>Human-readable name of the sound device.</p>
<p>Default value: NULL</p>
</div>
<hr>
<div class="refsect2" title='The "volume" property'>
<a name="GstPulseSink--volume"></a><h3>The <code class="literal">"volume"</code> property</h3>
<pre class="programlisting"> "volume" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gdouble"><span class="type">gdouble</span></a> : Read / Write</pre>
<p>Linear volume of this stream, 1.0=100%.</p>
<p>Allowed values: [0,10]</p>
<p>Default value: 1</p>
</div>
<hr>
<div class="refsect2" title='The "mute" property'>
<a name="GstPulseSink--mute"></a><h3>The <code class="literal">"mute"</code> property</h3>
<pre class="programlisting"> "mute" <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gboolean"><span class="type">gboolean</span></a> : Read / Write</pre>
<p>Mute state of this stream.</p>
<p>Default value: FALSE</p>
</div>
</div>
<div class="refsect1" title="See Also">
<a name="gst-plugins-good-plugins-pulsesink.see-also"></a><h2>See Also</h2>
pulsesrc, pulsemixer
</div>
</div>
<div class="footer">
<hr>
Generated by GTK-Doc V1.15</div>
</body>
</html>
|
cpopescu/whispermedialib
|
third-party/gstreamer/gst-plugins-good-0.10.23/docs/plugins/html/gst-plugins-good-plugins-pulsesink.html
|
HTML
|
lgpl-3.0
| 10,417
|
// <copyright file="RemoveCmsServerCmslet.cs" company="Chris Crutchfield">
// Copyright (C) 2017 Chris Crutchfield
//
// 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>
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using CMS.SiteProvider;
using CMS.Synchronization;
using ImpromptuInterface;
using PoshKentico.Business.Configuration.Staging;
using PoshKentico.Core.Services.Configuration.Staging;
using AliasAttribute = System.Management.Automation.AliasAttribute;
namespace PoshKentico.Cmdlets.Configuration.Staging
{
/// <summary>
/// <para type="synopsis">Removes the servers selected by the provided input.</para>
/// <para type="description">Removes the servers selected by the provided input. This command automatically initializes the connection to Kentico if not already initialized.</para>
/// <example>
/// <para>Remove a server.</para>
/// <code>$server | Remove-CMSServer</code>
/// </example>
/// <example>
/// <para>Remove all servers with a display name "basic", or server name "basic".</para>
/// <code>Remove-CMSServer basic </code>
/// </example>
/// <example>
/// <para>Remove all servers with a site id 5, and a display name "basic" or server name "basic".</para>
/// <code>Remove-CMSServer -SiteID 5 -ServerName "basic"</code>
/// </example>
/// <example>
/// <para>Remove all servers associalted with site $site with a display name "basic", or server name "basic"</para>
/// <code>$site | Remove-CMSServer basic</code>
/// </example>
/// <example>
/// <para>Remove all servers with a display name "*basic*", or server name "*basic*"</para>
/// <code>Remove-CMSServer *basic* -RegularExpression</code>
/// </example>
/// <example>
/// <para>Remove all servers with a site id 5, and a display name "*basic*" or server name "*basic*"</para>
/// <code>Remove-CMSServer 5 *basic* -RegularExpression</code>
/// </example>
/// <example>
/// <para>Remove all servers associalted with site $site with a display name "*basic*", or server name "*basic*"</para>
/// <code>$site | Remove-CMSServer *basic* -RegularExpression</code>
/// </example>
/// <example>
/// <para>Remove all the servers with the specified IDs.</para>
/// <code>Remove-CMSServer -ID 5,304,5</code>
/// </example>
/// </summary>
[ExcludeFromCodeCoverage]
[Cmdlet(VerbsCommon.Remove, "CMSServer", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)]
[Alias("rserver")]
public class RemoveCmsServerCmslet : GetCmsServerCmdlet
{
#region Constants
private const string SERVEROBJECTSET = "Object";
#endregion
#region Properties
/// <summary>
/// <para type="description">A reference to the site to remove.</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, Position = 0, ParameterSetName = SERVEROBJECTSET)]
[Alias("Server")]
public ServerInfo ServerToRemove { get; set; }
/// <summary>
/// Gets or sets the Business layer for this server. Populated by MEF.
/// </summary>
[Import]
public RemoveCmsServerBusiness RemoveBusinessLayer { get; set; }
#endregion
#region Methods
/// <inheritdoc />
protected override void ProcessRecord()
{
if (this.ParameterSetName == SERVEROBJECTSET)
{
this.ActOnObject(this.ServerToRemove.ActLike<IServer>());
}
else
{
base.ProcessRecord();
}
}
/// <inheritdoc />
protected override void ActOnObject(IServer server)
{
if (server == null)
{
return;
}
this.RemoveBusinessLayer.Remove(server);
}
#endregion
}
}
|
clcrutch/posh-kentico
|
src/PoshKentico/Cmdlets/Configuration/Staging/RemoveCmsServerCmslet.cs
|
C#
|
lgpl-3.0
| 4,668
|
/* libpharmmlcpp - Library to handle PharmML
* Copyright (C) 2016 Rikard Nordgren and Gunnar Yngman
*
* 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.
*
* his 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 PHARMMLCPP_DATASET_H_
#define PHARMMLCPP_DATASET_H_
#include <xml/xml.h>
#include <PharmML/PharmMLReader.h>
#include <PharmML/PharmMLSection.h>
#include <AST/AstNode.h>
#include <visitors/AstNodeVisitor.h>
#include <visitors/XMLAstVisitor.h>
#include <AST/Scalar.h>
namespace pharmmlcpp
{
// Class HeaderDefinition (single header specification of dataset)
class HeaderDefinition
{
public:
HeaderDefinition(PharmMLReader &reader, xml::Node node);
void parse(PharmMLReader &reader, xml::Node node);
xml::Node xml();
void addHeaderRow(xml::Node node);
std::string getName();
int getRowNumber();
private:
std::string name;
int rowNumber;
};
// Class ColumnDefinition (single column specification of dataset)
class ColumnDefinition
{
public:
ColumnDefinition(PharmMLReader &reader, xml::Node node);
void parse(PharmMLReader &reader, xml::Node node);
xml::Node xml();
std::string getId();
std::string getType();
std::string getLevel();
std::string getValueType();
int getNum();
private:
std::string id;
std::string type;
std::string level;
std::string valueType;
int num;
};
// Class DatasetDefinition (header/column specifications of dataset)
class DatasetDefinition
{
public:
DatasetDefinition(PharmMLReader &reader, xml::Node node);
void parse(PharmMLReader &reader, xml::Node node);
xml::Node xml();
ColumnDefinition *getColumnDefinition(int colNum);
std::vector<ColumnDefinition *> getColumnDefinitions();
int getNumColumns();
private:
std::vector<HeaderDefinition *> headers;
std::vector<ColumnDefinition *> columns;
std::shared_ptr<AstNode> ignoreCondition;
std::string ignoreSymbols; // 1 to 5 non-whitespace characters
};
// class ExternalFile (data is stored externally)
class ExternalFile
{
public:
ExternalFile(PharmMLReader &reader, xml::Node node);
void parse(PharmMLReader &reader, xml::Node node);
std::string getOid();
std::string getPath();
std::string getFormat();
std::string getDelimiter();
void accept(PharmMLVisitor *visitor);
private:
std::string oid;
std::string path;
std::string format;
std::string delimiter;
// TODO: Support MissingDataMapType
};
// Class DataColumn (single column with its definition)
class DataColumn
{
public:
DataColumn(PharmMLReader &reader, xml::Node table_node, ColumnDefinition *definition);
void parse(PharmMLReader &reader, xml::Node table_node);
std::vector<std::shared_ptr<AstNode>> getData();
ColumnDefinition *getDefinition();
std::shared_ptr<AstNode> getElement(int row);
int getNumRows();
void accept(PharmMLVisitor *visitor);
private:
ColumnDefinition *definition;
std::vector<std::shared_ptr<AstNode>> column;
int numRows;
};
// Class Dataset (top-level of above)
class Dataset : public PharmMLSection
{
public:
Dataset(PharmMLReader &reader, xml::Node node);
void parse(PharmMLReader &reader, xml::Node node);
xml::Node xml();
std::string getOid();
DatasetDefinition *getDefinition();
bool isExternal();
ExternalFile *getExternal();
std::vector<DataColumn *> getColumns();
DataColumn *getColumnFromType(std::string columnType);
DataColumn *getIdvColumn();
void setName(std::string name);
std::string getName();
void accept(PharmMLVisitor *visitor);
private:
std::string oid;
DatasetDefinition *definition = nullptr;
ExternalFile *externalFile = nullptr;
std::vector<DataColumn *> columns;
std::string name;
};
}
#endif
|
rikardn/libpharmmlcpp
|
libpharmmlcpp/PharmML/Dataset.h
|
C
|
lgpl-3.0
| 5,118
|
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef QTAWS_UPDATEJOBSTATUSREQUEST_H
#define QTAWS_UPDATEJOBSTATUSREQUEST_H
#include "s3controlrequest.h"
namespace QtAws {
namespace S3Control {
class UpdateJobStatusRequestPrivate;
class QTAWSS3CONTROL_EXPORT UpdateJobStatusRequest : public S3ControlRequest {
public:
UpdateJobStatusRequest(const UpdateJobStatusRequest &other);
UpdateJobStatusRequest();
virtual bool isValid() const Q_DECL_OVERRIDE;
protected:
virtual QtAws::Core::AwsAbstractResponse * response(QNetworkReply * const reply) const Q_DECL_OVERRIDE;
private:
Q_DECLARE_PRIVATE(UpdateJobStatusRequest)
};
} // namespace S3Control
} // namespace QtAws
#endif
|
pcolby/libqtaws
|
src/s3control/updatejobstatusrequest.h
|
C
|
lgpl-3.0
| 1,391
|
package org.areasy.common.parser.html.engine.filters;
/*
* Copyright (c) 2007-2020 AREasy Runtime
*
* This library, AREasy Runtime and API for BMC Remedy AR System, is free software ("Licensed 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 2.1 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;
* including but not limited to, the implied warranty of MERCHANTABILITY, NONINFRINGEMENT,
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
import org.areasy.common.parser.html.engine.Node;
import org.areasy.common.parser.html.engine.NodeFilter;
/**
* This class accepts all nodes not acceptable to the filter.
*/
public class NotFilter implements NodeFilter
{
/**
* The filter to gainsay.
*/
protected NodeFilter mFilter;
/**
* Creates a new instance of NotFilter that accepts nodes not acceptable to the filter.
*
* @param filter The filter to consult.
*/
public NotFilter(NodeFilter filter)
{
mFilter = filter;
}
/**
* Accept nodes that are not acceptable to the filter.
*
* @param node The node to check.
*/
public boolean accept(Node node)
{
return (!mFilter.accept(node));
}
}
|
stefandmn/AREasy
|
src/java/org/areasy/common/parser/html/engine/filters/NotFilter.java
|
Java
|
lgpl-3.0
| 1,411
|
package uk.ac.manchester.cs.owl.owlapi;/**
* Author: Matthew Horridge<br>
* Stanford University<br>
* Bio-Medical Informatics Research Group<br>
* Date: 20/11/2013
*/
import com.google.gwt.user.client.rpc.CustomFieldSerializer;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import org.semanticweb.owlapi.model.OWLDataPropertyExpression;
import org.semanticweb.owlapi.model.OWLLiteral;
/**
* A server side implementation of CustomFieldSerilizer for serializing {@link uk.ac.manchester.cs.owl.owlapi.OWLDataHasValueImpl}
* objects.
*/
public class OWLDataHasValueImpl_CustomFieldSerializer extends CustomFieldSerializer<OWLDataHasValueImpl> {
/**
* @return <code>true</code> if a specialist {@link #instantiateInstance} is
* implemented; <code>false</code> otherwise
*/
@Override
public boolean hasCustomInstantiateInstance() {
return true;
}
/**
* Instantiates an object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
* <p/>
* Most of the time, this can be left unimplemented and the framework
* will instantiate the instance itself. This is typically used when the
* object being deserialized is immutable, hence it has to be created with
* its state already set.
* <p/>
* If this is overridden, the {@link #hasCustomInstantiateInstance} method
* must return <code>true</code> in order for the framework to know to call
* it.
*
* @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
* object's content from
* @return an object that has been loaded from the
* {@link com.google.gwt.user.client.rpc.SerializationStreamReader}
* @throws com.google.gwt.user.client.rpc.SerializationException
* if the instantiation operation is not
* successful
*/
@Override
public OWLDataHasValueImpl instantiateInstance(SerializationStreamReader streamReader) throws SerializationException {
return instantiate(streamReader);
}
public static OWLDataHasValueImpl instantiate(SerializationStreamReader streamReader) throws SerializationException {
OWLDataPropertyExpression property = (OWLDataPropertyExpression) streamReader.readObject();
OWLLiteral value = (OWLLiteral) streamReader.readObject();
return new OWLDataHasValueImpl(property, value);
}
/**
* Serializes the content of the object into the
* {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
*
* @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
* object's content to
* @param instance the object instance to serialize
* @throws com.google.gwt.user.client.rpc.SerializationException
* if the serialization operation is not
* successful
*/
@Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataHasValueImpl instance) throws SerializationException {
serialize(streamWriter, instance);
}
public static void serialize(SerializationStreamWriter streamWriter, OWLDataHasValueImpl instance) throws SerializationException {
streamWriter.writeObject(instance.getProperty());
streamWriter.writeObject(instance.getValue());
}
/**
* Deserializes the content of the object from the
* {@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
*
* @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
* object's content from
* @param instance the object instance to deserialize
* @throws com.google.gwt.user.client.rpc.SerializationException
* if the deserialization operation is not
* successful
*/
@Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLDataHasValueImpl instance) throws SerializationException {
deserialize(streamReader, instance);
}
public static void deserialize(SerializationStreamReader streamReader, OWLDataHasValueImpl instance) throws SerializationException {
}
}
|
matthewhorridge/owlapi-gwt
|
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataHasValueImpl_CustomFieldSerializer.java
|
Java
|
lgpl-3.0
| 4,451
|
/*
* Copyright 2014 by Heiko Schäfer <heiko@rangun.de>
*
* This file is part of NetMauMau.
*
* NetMauMau 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.
*
* NetMauMau 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 NetMauMau. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file
* @brief The main class of a client
* @author Heiko Schäfer <heiko@rangun.de>
*
* @mainpage %NetMauMau Client API
*
* The %NetMauMau Client API is for developers of clients for %NetMauMau.
* It handles the connection to a server and provides callbacks via pure virtual functions.
*
* To use the @b %NetMauMau @b Client @b API please read at first how to implement
* NetMauMau::Client::AbstractClient. @n Useful functions you'll find in NetMauMau::Common.
*
* Link your client against @c -lnetmaumauclient and @c -lnetmaumaucommon
*
* Get the lastest code via git: `git clone https://github.com/velnias75/NetMauMau.git`
*
* @htmlinclude README.md
*/
#ifndef NETMAUMAU_ABSTRACTCLIENT_H
#define NETMAUMAU_ABSTRACTCLIENT_H
#include <vector>
#include "iplayerpiclistener.h"
#include "clientconnection.h"
#include "icard.h"
namespace NetMauMau {
/// @brief Classes and functions used by clients only
namespace Client {
class AbstractClientV05Impl;
/**
* @brief %Client interface to communicate with the server
*/
class _EXPORT AbstractClientV05 : protected IPlayerPicListener {
DISALLOW_COPY_AND_ASSIGN(AbstractClientV05)
friend class AbstractClientV05Impl;
friend class AbstractClientV07;
friend class AbstractClientV08;
public:
/// @copydoc Connection::CAPABILITIES
typedef Connection::CAPABILITIES CAPABILITIES;
/// @copydoc Connection::PLAYERLIST
typedef Connection::PLAYERLIST PLAYERLIST;
/// @copydoc Connection::PLAYERINFOS
typedef Connection::PLAYERINFOS PLAYERINFOS;
/**
* @brief A vector of @c Common::ICard pointers
*/
typedef std::vector<Common::ICard *> CARDS;
/**
* @brief Statistics entry about the other player's card count
*/
typedef struct {
std::string playerName; ///< the player's name
std::size_t cardCount; ///< the player's card count
} STAT;
/**
* @brief A vector with statistics about the other player's card count
* @see STAT
*/
typedef std::vector<STAT> STATS;
virtual ~AbstractClientV05();
/**
* @brief Attempt to start a game on the servers
*
* @param timeout the time to wait for a connection, if @c NULL there will be no timeout
*
* @throw Common::Exception::SocketException if the connection failed
* @throw Client::Exception::TimeoutException if the connection attempt timed out
* @throw Client::Exception::ProtocolErrorException if there was a aprotocol error
* @throw Client::Exception::ConnectionRejectedException if the connection got rejected
* @throw Client::Exception::NoNetMauMauServerException
* if the remote host is no %NetMauMau server
* @throw Client::Exception::ShutdownException if the server is shutting down
* @throw Client::Exception::VersionMismatchException if the client is not supported
*/
void play(timeval *timeout = NULL) throw(NetMauMau::Common::Exception::SocketException);
/**
* @brief Disconnects the client from the server
*/
void disconnect();
/**
* @name Server query methods
* @{
*/
/**
* @brief Returns the server capabilities
*
* @param timeout the time to wait for a connection, if @c NULL there will be no timeout
*
* @throw Common::Exception::SocketException if the connection failed
* @throw Client::Exception::CapabilitiesException if the capabilities cannot get retrieved
* @throw Client::Exception::TimeoutException if the connection attempt timed out
*
* @return the server capabilities
*/
CAPABILITIES capabilities(timeval *timeout = NULL)
throw(NetMauMau::Common::Exception::SocketException);
/**
* @brief Returns the list of currently registered player names
*
* @note The image data returned in @c NetMauMau::Client::AbstractClient::PLAYERLIST must
* be freed by the user @code delete [] x->pngData @endcode
*
* @param playerPNG @c true if the player images should get retrieved
* @param timeout the time to wait for a connection, if @c NULL there will be no timeout
*
* @throw Common::Exception::SocketException if the connection failed
* @throw Client::Exception::PlayerlistException if the player list cannot get retrieved
* @throw Client::Exception::TimeoutException if the connection attempt timed out
*
* @return the list of currently registered player names
*
* @since 0.4
*/
PLAYERINFOS playerList(bool playerPNG, timeval *timeout = NULL)
throw(NetMauMau::Common::Exception::SocketException);
/**
* @brief Returns the list of currently registered player names
*
* It does not retrieve the player images
*
* @overload
*/
PLAYERLIST playerList(timeval *timeout = NULL)
throw(NetMauMau::Common::Exception::SocketException);
/**
* @ingroup util
* @brief Returns the version of the client's implemented protocol version
*
* You can retrieve major and minor version as following: @code
* uint16_t major = static_cast<uint16_t>(AbstractClient::getClientProtocolVersion() >> 16);
* uint16_t minor = static_cast<uint16_t>(AbstractClient::getClientProtocolVersion());
* @endcode
*
* @return the protocol version
*/
static uint32_t getClientProtocolVersion() _CONST;
/**
* @ingroup util
* @brief Parses a version string and returns the resulting protocol version
*
* @param version the protocol version as string
* @return the protocol version
*
* @since 0.3
*/
static uint32_t parseProtocolVersion(const std::string &version);
/**
* @ingroup util
* @brief Checks if an player image is uploadable to the server
*
* @note it is possible that the server rejects the image anyway if configured to use
* a different (smaller) maximum file size than this client
*
* @param pngData the image data
* @param pngDataLen length of the image data
* @return @c true if the file will most probably accepted by the server, @c false otherwise
*
* @since 0.5
*/
static bool isPlayerImageUploadable(const unsigned char *pngData, std::size_t pngDataLen);
/**
* @ingroup util
* @brief Gets the default port of the server
*
* @return the default port of the server
*/
static uint16_t getDefaultPort() _CONST;
/**
* @brief Gets the player's name
*
* @return the player's name
*/
std::string getPlayerName() const;
/**
* @ingroup util
* @brief Gets the compiled in default AI player name
*
* @return the compiled in default AI player name
*/
static const char *getDefaultAIName() _CONST;
/// @}
protected:
/**
* @brief Creates an @c AbstractClientV05 instance
*
* Sets up all information to connect to a server
*
* @see play
*
* @param player the player's name
* @param server the server to connect to
* @param port the server port to connect to
*/
AbstractClientV05(const std::string &player, const std::string &server, uint16_t port);
/**
* @brief Creates an @c AbstractClientV05 instance
*
* Sets up all information to connect to a server. Additionally a player picture can be
* submitted
*
* @see play
*
* @param player the player's name
* @param pngData pointer to a buffer containg PNG image data or @c NULL
* @param pngDataLen length of the data in the buffer pointed to by @c pngData
* @param server the server to connect to
* @param port the server port to connect to
*
* @since 0.4
*/
AbstractClientV05(const std::string &player, const unsigned char *pngData,
std::size_t pngDataLen, const std::string &server, uint16_t port);
/**
* @name Server requests
* @{
*/
/**
* @brief The server requests a card to play
*
* @note If the client send an <em>illegal card</em> the client will be requsted to
* choose a card again. Before the client will receive the amount of extra cards
* to take by played out SEVEN rank cards.
*
* @see Common::getIllegalCard
*
* @param cards playable cards, which will get accepted by the server
* @return the card the player wants to play or @c NULL if the player cannot play a
* card and/or suspends the turn or the <em>illegal card</em>
*/
virtual Common::ICard *playCard(const CARDS &cards) const = 0;
/**
* @brief Gets the current Jack suit
*
* @return the current Jack suit
*/
virtual Common::ICard::SUIT getJackSuitChoice() const = 0;
//@}
/**
* @name Sever events
* @{
*/
/**
* @brief The server send a general message
*
* @param msg the general message
*/
virtual void message(const std::string &msg) const = 0;
/**
* @brief The server send a error message
*
* @param msg the error message
*/
virtual void error(const std::string &msg) const = 0;
/**
* @brief A new turn has started
*
* @param turn number of the current turn
*/
virtual void turn(std::size_t turn) const = 0;
/**
* @brief The server sent statistics about the other player's card count
*
* @param stats the statistics about the other player's card count
*/
virtual void stats(const STATS &stats) const = 0;
/**
* @brief The server announced the game is over
*/
virtual void gameOver() const = 0;
/**
* @brief A new player joined the game
*
* Transmits a PNG picture of the player if available
*
* @param player the new player's name
* @param pngData PNG data of the players picture or @c 0L
* @param pngDataLen length of the PNG data
*/
virtual void playerJoined(const std::string &player, const unsigned char *pngData,
std::size_t len) const = 0;
/**
* @brief A player got rejected to join the game
*
* @param player the rejected player's name
*/
virtual void playerRejected(const std::string &player) const = 0;
/**
* @brief A player suspends this turn
*
* @param player the suspending player's name
*/
virtual void playerSuspends(const std::string &player) const = 0;
/**
* @brief A player played a card
*
* @param player the player's name
* @param card the card the player played
*/
virtual void playedCard(const std::string &player, const Common::ICard *card) const = 0;
/**
* @brief A player has won the game
*
* @param player the player's name
* @param turn the number of the turn the player has won
*/
virtual void playerWins(const std::string &player, std::size_t turn) const = 0;
/**
* @brief A player has lost the game
*
* @param player the player's name
* @param turn the number of the turn the player has lost
* @param points the points the loosing player had in hand
*/
virtual void playerLost(const std::string &player, std::size_t turn,
std::size_t points) const = 0;
/**
* @brief A player picks up a card
*
* @note The card is @c NULL if the player is a remote player
*
* @param player the player's name
* @param card the card the player picked up
*/
virtual void playerPicksCard(const std::string &player, const Common::ICard *card) const = 0;
/**
* @brief A player picks up an amount of cards
*
* @param player the player's name
* @param count the count of picked up cards
*/
virtual void playerPicksCard(const std::string &player, std::size_t count) const = 0;
/**
* @brief Name of the next player
*
* @param player the next player's name
*/
virtual void nextPlayer(const std::string &player) const = 0;
/**
* @brief Notes if suspending and taking a card possible
*
* If there are no more cards on the talon, except the open card, suspending and
* taking card a is not possible
*
* @param enable @c true if it is possible to take a card, @c false otherwise
*/
virtual void enableSuspend(bool enable) const = 0;
/**
* @brief The card set distributed to the player, or if the
* player picked up cards off the talon
*
* @param cards the card set given to the player
*/
virtual void cardSet(const CARDS &cards) const = 0;
/**
* @brief The initial card
*
* @param card the initial card
*/
virtual void initialCard(const Common::ICard *card) const = 0;
/**
* @brief The current open card
*
* If there is a suit chosen by a Jack the jackSuit contains it and can get converted to
* @c NetMauMau::Common::ICard::SUIT by NetMauMau::Common::symbolToSuit, else it will be
* a empty string.
*
* @see NetMauMau::Common::symbolToSuit
*
* @param card the current open card
* @param jackSuit the current jack suit
*/
virtual void openCard(const Common::ICard *card, const std::string &jackSuit) const = 0;
/**
* @brief The talon was empty and shuffled anew
*
* All played cards, except the open top card are shuffled and added to the Talon.
*
* This event can be used for displaying an shuffle animation.
*
*/
virtual void talonShuffled() const = 0;
/**
* @brief The player's played card got rejected
*
* @param player the player's name
* @param card the rejected card
*/
virtual void cardRejected(const std::string &player, const Common::ICard *card) const = 0;
/**
* @brief The player's played card got accepted
*
* @param card the accepted card
*/
virtual void cardAccepted(const Common::ICard *card) const = 0;
/**
* @brief The server announces a Jack suit
*
* @param suit the current Jack suit
*/
virtual void jackSuit(Common::ICard::SUIT suit) const = 0;
// @}
/**
* @name Player image notifications
*
* The notifications can be overloaded if the client is interested in events
* regarding the player pictures.
*
* This functions all do nothing at default.
*
* @{
*/
/**
* @brief A download of a player image has started
*
* @param player the player the image is downloaded for
*
* @since 0.4
*/
virtual void beginReceivePlayerPicture(const std::string &player) const throw() _CONST;
/**
* @brief A download of a player image has ended
*
* @param player the player the image is downloaded for
*
* @since 0.4
*/
virtual void endReceivePlayerPicture(const std::string &player) const throw() _CONST;
/**
* @brief The upload of the player image has succeded
*
* @param player the player the image is uploaded for
*
* @since 0.4
*/
virtual void uploadSucceded(const std::string &player) const throw() _CONST;
/**
* @brief The upload of the player image has failed
*
* @param player the player the image is uploaded for
*
* @since 0.4
*/
virtual void uploadFailed(const std::string &player) const throw() _CONST;
/// @}
/**
* @brief The server sent a message not understood by the client
*
* @param message the unknown message
*/
virtual void unknownServerMessage(const std::string &msg) const = 0;
private:
typedef enum { OK, NOT_UNDERSTOOD, BREAK } PIRET;
virtual PIRET playInternal(std::string &msg, std::size_t *cturn, bool *initCardShown,
std::string &cjackSuit,
const NetMauMau::Common::ICard **lastPlayedCard)
throw(NetMauMau::Common::Exception::SocketException);
private:
AbstractClientV05Impl *const _pimpl;
};
/**
* @brief %Client interface to communicate with the server
*
* @since 0.7
*/
class _EXPORT AbstractClientV07 : public AbstractClientV05 {
DISALLOW_COPY_AND_ASSIGN(AbstractClientV07)
friend class AbstractClientV08;
protected:
/**
* @brief Creates an @c AbstractClientV07 instance
*
* @copydetails AbstractClientV05(const std::string &, const std::string &, uint16_t)
*/
AbstractClientV07(const std::string &player, const std::string &server, uint16_t port);
/**
* @brief Creates an @c AbstractClientV07 instance
*
* @copydetails AbstractClientV05(const std::string &, const unsigned char *,
* std::size_t, const std::string &, uint16_t)
*/
AbstractClientV07(const std::string &player, const unsigned char *pngData,
std::size_t pngDataLen, const std::string &server, uint16_t port);
/**
* @name Server requests
*
* This requests require a %client of at least version 0.7
*
* @{
*/
/**
* @brief Gets the choice if an ace round should be started
* @return @c true to start an ace round, @c false otherwise
* @since 0.7
*/
virtual bool getAceRoundChoice() const = 0;
/// @}
/**
* @name Server events
*
* This events require a %client of at least version 0.7
*
* @{
*/
/**
* @brief An ace round was started by a player
*
* @param player the player starting the ace round
* @since 0.7
*/
virtual void aceRoundStarted(const std::string &player) const = 0;
/**
* @brief An ace round was ended by a player
*
* @param player the player ending the ace round
* @since 0.7
*/
virtual void aceRoundEnded(const std::string &player) const = 0;
/// @}
public:
virtual ~AbstractClientV07();
private:
using AbstractClientV05::playInternal;
virtual AbstractClientV05::PIRET playInternal(std::string &msg, std::size_t *cturn,
bool *initCardShown, std::string &cjackSuit, const Common::ICard **lastPlayedCard)
throw(NetMauMau::Common::Exception::SocketException);
};
/**
* @brief %Client interface to communicate with the server
*
* @since 0.8
*/
class _EXPORT AbstractClientV08 : public AbstractClientV07 {
DISALLOW_COPY_AND_ASSIGN(AbstractClientV08)
protected:
using AbstractClientV07::playCard;
/**
* @brief Creates an @c AbstractClientV08 instance
*
* @copydetails AbstractClientV07(const std::string &, const std::string &, uint16_t)
*
* @param clientVersion the protocol version the client understands
*
* @since 0.8
*/
AbstractClientV08(const std::string &player, const std::string &server, uint16_t port,
uint32_t clientVersion);
/**
* @brief Creates an @c AbstractClientV08 instance
*
* @copydetails AbstractClientV07(const std::string &, const unsigned char *,
* std::size_t, const std::string &, uint16_t)
*
* @param clientVersion the protocol version the client understands
*
* @since 0.8
*/
AbstractClientV08(const std::string &player, const unsigned char *pngData,
std::size_t pngDataLen, const std::string &server, uint16_t port,
uint32_t clientVersion);
virtual Common::ICard *playCard(const CARDS &cards) const;
/**
* @name Server requests
* @{
*/
/**
* @brief The server requests a card to play
*
* @copydetails AbstractClientV05::playCard(const CARDS &cards)
*
* If @c takeCount is > @c 0 the client can use @c Common::getIllegalCard to retrive the
* cards first
*
* @param takeCount the amount of cards the player has to take
*/
virtual Common::ICard *playCard(const CARDS &cards, std::size_t takeCount) const = 0;
/// @}
virtual ~AbstractClientV08();
private:
virtual PIRET playInternal(std::string &msg, std::size_t *cturn, bool *initCardShown,
std::string &cjackSuit,
const NetMauMau::Common::ICard **lastPlayedCard)
throw(NetMauMau::Common::Exception::SocketException);
};
/**
* @brief Alias to the current client interface to communicate with the server
*
* In your client subclass @c AbstractClient and implement all pure virtual methods. In the
* constructor @c AbstractClient you can setup the connection.\n
* To actually join the game you need to call @c play(). The pure virtual functions are
* translated events and requests of the server, which your client has to handle accordingly.\n
* If you just want to query the player list, you can call @c playerList() and to get the
* servers capabilities you can call @c capabilities()
*
* A complete proof of concept client can be obtained via git:
* `git clone https://github.com/velnias75/NetMauMau-Qt-Client.git`
*
* @note All data is transferred as UTF-8 encoded byte strings
* @note Starting with version 0.6 and with *libmagic* enabled, the server checks if the player
* images are really in the PNG format
*
* @see AbstractClientV08
*
*/
typedef AbstractClientV08 AbstractClient;
}
}
#endif /* NETMAUMAU_ABSTRACTCLIENT_H */
// kate: indent-mode cstyle; indent-width 4; replace-tabs off; tab-width 4;
|
gonzoid/NetMauMau
|
src/include/abstractclient.h
|
C
|
lgpl-3.0
| 20,441
|
-- different ways to generate primes
ps :: Int -> [Int]
ps 2 = [2]
ps n =
let pn1 = ps (n-1) in
if any (==0) $ map (rem n) pn1
then pn1
else pn1 ++ [n]
isqrt :: Integral a => a -> a
isqrt = ceiling . sqrt . fromIntegral
ispm :: Int -> Bool
ispm 1 = True
ispm 2 = True
ispm n = null [q | q <- [x | x <- [2..(isqrt n)], ispm x], rem n q == 0]
|
ekalosak/haskell-practice
|
Primes.hs
|
Haskell
|
lgpl-3.0
| 360
|
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.plugins.ws;
import com.google.common.base.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import org.sonar.server.ws.WsTester;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.Release;
import static com.google.common.collect.ImmutableList.of;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.when;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonar.updatecenter.common.PluginUpdate.Status.COMPATIBLE;
import static org.sonar.updatecenter.common.PluginUpdate.Status.DEPENDENCIES_REQUIRE_SONAR_UPGRADE;
import static org.sonar.updatecenter.common.PluginUpdate.Status.INCOMPATIBLE;
import static org.sonar.updatecenter.common.PluginUpdate.Status.REQUIRE_SONAR_UPGRADE;
public class AvailableActionTest extends AbstractUpdateCenterBasedPluginsWsActionTest {
private static final Plugin FULL_PROPERTIES_PLUGIN = Plugin.factory("pkey")
.setName("p_name")
.setCategory("p_category")
.setDescription("p_description")
.setLicense("p_license")
.setOrganization("p_orga_name")
.setOrganizationUrl("p_orga_url")
.setHomepageUrl("p_homepage_url")
.setIssueTrackerUrl("p_issue_url")
.setTermsConditionsUrl("p_t_and_c_url");
private static final Release FULL_PROPERTIES_PLUGIN_RELEASE = release(FULL_PROPERTIES_PLUGIN, "1.12.1")
.setDate(DateUtils.parseDate("2015-04-16"))
.setDownloadUrl("http://p_file.jar")
.addOutgoingDependency(release(PLUGIN_1, "0.3.6"))
.addOutgoingDependency(release(PLUGIN_2, "1.0.0"));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public ExpectedException expectedException = ExpectedException.none();
private AvailableAction underTest = new AvailableAction(userSession, updateCenterFactory);
@Test
public void action_available_is_defined() {
logInAsSystemAdministrator();
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
underTest.define(newController);
newController.done();
WebService.Controller controller = wsTester.controller(DUMMY_CONTROLLER_KEY);
assertThat(controller.actions()).extracting("key").containsExactly("available");
WebService.Action action = controller.actions().iterator().next();
assertThat(action.isPost()).isFalse();
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExample()).isNotNull();
}
@Test
public void verify_example() throws Exception {
logInAsSystemAdministrator();
when(updateCenter.findAvailablePlugins()).thenReturn(of(
pluginUpdate(release(Plugin.factory("abap")
.setName("ABAP")
.setCategory("Languages")
.setDescription("Enable analysis and reporting on ABAP projects")
.setLicense("Commercial")
.setOrganization("SonarSource")
.setOrganizationUrl("http://www.sonarsource.com")
.setTermsConditionsUrl("http://dist.sonarsource.com/SonarSource_Terms_And_Conditions.pdf"),
"3.2")
.setDate(DateUtils.parseDate("2015-03-10")),
COMPATIBLE),
pluginUpdate(release(Plugin.factory("android")
.setName("Android")
.setCategory("Languages")
.setDescription("Import Android Lint reports.")
.setLicense("GNU LGPL 3")
.setOrganization("SonarSource and Jerome Van Der Linden, Stephane Nicolas, Florian Roncari, Thomas Bores")
.setOrganizationUrl("http://www.sonarsource.com"),
"1.0")
.setDate(DateUtils.parseDate("2014-03-31"))
.addOutgoingDependency(release(Plugin.factory("java").setName("Java").setDescription("SonarQube rule engine."), "0.3.6")),
COMPATIBLE)));
underTest.handle(request, response);
WsActionTester actionTester = new WsActionTester(underTest);
assertJson(response.outputAsString()).isSimilarTo(actionTester.getDef().responseExampleAsString());
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() throws Exception {
expectedException.expect(ForbiddenException.class);
underTest.handle(request, response);
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception {
userSession.logIn().setNonSystemAdministrator();
expectedException.expect(ForbiddenException.class);
underTest.handle(request, response);
}
@Test
public void empty_array_is_returned_when_there_is_no_plugin_available() throws Exception {
logInAsSystemAdministrator();
underTest.handle(request, response);
assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST);
}
@Test
public void empty_array_is_returned_when_update_center_is_not_accessible() throws Exception {
logInAsSystemAdministrator();
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.absent());
underTest.handle(request, response);
assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST);
}
@Test
public void verify_properties_displayed_in_json_per_plugin() throws Exception {
logInAsSystemAdministrator();
when(updateCenter.findAvailablePlugins()).thenReturn(of(
pluginUpdate(FULL_PROPERTIES_PLUGIN_RELEASE, COMPATIBLE)));
underTest.handle(request, response);
assertJson(response.outputAsString())
.isSimilarTo(
"{" +
" \"plugins\": [" +
" {" +
" \"key\": \"pkey\"," +
" \"name\": \"p_name\"," +
" \"category\": \"p_category\"," +
" \"description\": \"p_description\"," +
" \"license\": \"p_license\"," +
" \"termsAndConditionsUrl\": \"p_t_and_c_url\"," +
" \"organizationName\": \"p_orga_name\"," +
" \"organizationUrl\": \"p_orga_url\"," +
" \"homepageUrl\": \"p_homepage_url\"," +
" \"issueTrackerUrl\": \"p_issue_url\"," +
" \"release\": {" +
" \"version\": \"1.12.1\"," +
" \"date\": \"2015-04-16\"" +
" }," +
" \"update\": {" +
" \"status\": \"COMPATIBLE\"," +
" \"requires\": [" +
" {" +
" \"key\": \"pkey1\"," +
" \"name\": \"p_name_1\"" +
" }," +
" {" +
" \"key\": \"pkey2\"," +
" \"name\": \"p_name_2\"," +
" \"description\": \"p_desc_2\"" +
" }" +
" ]" +
" }" +
" }" +
" ]," +
" \"updateCenterRefresh\": \"2015-04-24T16:08:36+0200\"" +
"}");
}
@Test
public void status_COMPATIBLE_is_displayed_COMPATIBLE_in_JSON() throws Exception {
logInAsSystemAdministrator();
checkStatusDisplayedInJson(COMPATIBLE, "COMPATIBLE");
}
@Test
public void status_INCOMPATIBLE_is_displayed_INCOMPATIBLE_in_JSON() throws Exception {
logInAsSystemAdministrator();
checkStatusDisplayedInJson(INCOMPATIBLE, "INCOMPATIBLE");
}
@Test
public void status_REQUIRE_SONAR_UPGRADE_is_displayed_REQUIRES_SYSTEM_UPGRADE_in_JSON() throws Exception {
logInAsSystemAdministrator();
checkStatusDisplayedInJson(REQUIRE_SONAR_UPGRADE, "REQUIRES_SYSTEM_UPGRADE");
}
@Test
public void status_DEPENDENCIES_REQUIRE_SONAR_UPGRADE_is_displayed_DEPS_REQUIRE_SYSTEM_UPGRADE_in_JSON() throws Exception {
logInAsSystemAdministrator();
checkStatusDisplayedInJson(DEPENDENCIES_REQUIRE_SONAR_UPGRADE, "DEPS_REQUIRE_SYSTEM_UPGRADE");
}
private void checkStatusDisplayedInJson(PluginUpdate.Status status, String expectedValue) throws Exception {
when(updateCenter.findAvailablePlugins()).thenReturn(of(
pluginUpdate(release(PLUGIN_1, "1.0.0"), status)));
underTest.handle(request, response);
assertJson(response.outputAsString()).isSimilarTo(
"{" +
" \"plugins\": [" +
" {" +
" \"update\": {" +
" \"status\": \"" + expectedValue + "\"" +
" }" +
" }" +
" ]" +
"}");
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
}
|
Godin/sonar
|
server/sonar-server/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.java
|
Java
|
lgpl-3.0
| 9,689
|
'''
Puck: FreeBSD virtualization guest configuration server
Copyright (C) 2011 The Hotel Communication Network inc.
This program 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 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 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/>.
'''
import os.path
import cherrypy
from libs.controller import *
import models
from models import Users
class RootController(Controller):
crumbs = [Crumb("/", "Home")]
def __init__(self, lookup):
Controller.__init__(self, lookup)
self._lookup = lookup
self._routes = {}
@cherrypy.expose
@cherrypy.tools.myauth()
def index(self):
return self.render("index.html", self.crumbs[:-1])
@cherrypy.expose
def login(self, **post):
if post:
self._login(post)
return self.render("login.html", self.crumbs[:-1])
@cherrypy.expose
def logout(self, **post):
cherrypy.session.delete()
raise cherrypy.HTTPRedirect("/login")
def add(self, route, cls):
self._routes[route] = cls
def load(self):
[setattr(self, route, self._routes[route](self._lookup)) for route in self._routes]
def _login(self, post):
fields = ['user.username', 'user.password']
for f in fields:
if not f in post:
cherrypy.session['flash'] = "Invalid form data."
return False
hash_password = Users.hash_password(post['user.password'])
user = Users.first(username=post['user.username'], password=hash_password)
if not user:
cherrypy.session['flash'] = 'Invalid username or password.'
return False
creds = user.generate_auth()
cherrypy.session['user.id'] = user.id
cherrypy.session['user.group'] = user.user_group
cherrypy.session['credentials'] = creds
raise cherrypy.HTTPRedirect('/index')
|
masom/Puck
|
server/controllers/root.py
|
Python
|
lgpl-3.0
| 2,450
|
public class StmEscape {
public void unmangleIds( int stage ) {
super.unmangleIds( stage-1 );
}
}
|
SergiyKolesnikov/fuji
|
examples/AHEAD/unmixinbaseAst/StmEscape.java
|
Java
|
lgpl-3.0
| 123
|
# SCAI
Starcraft AI
|
KertanLeGnome/SCAI
|
README.md
|
Markdown
|
lgpl-3.0
| 20
|
<?php
/**
* BBBx
*
* Copyright 2016 by goldsky <goldsky@virtudraft.com>
*
* This file is part of BBBx, a BigBlueButton and MODX integration add on.
*
* BBBx 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 version 3,
*
* BBBx 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
* BBBx; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
* @package bbbx
* @subpackage abstract class
*/
class BigBlueButton
{
/**
* @var string
*/
private $securitySalt;
/**
* @var string
*/
private $bbbServerBaseUrl;
/**
* @var array
*/
private $queries = array();
/**
* @var array
*/
private $meta = array();
/**
*
* @var string
*/
private $contentType = 'application/xml';
public function __construct($bbbServerBaseUrl, $securitySalt)
{
$this->bbbServerBaseUrl = $bbbServerBaseUrl;
$this->securitySalt = $securitySalt;
}
public function getApiVersion()
{
return $this->processXmlResponseArray($this->buildUrl());
}
public function getMeetings($limit = 0, $start = 0)
{
return $this->processXmlResponseArray($this->buildUrl(__FUNCTION__));
}
public function getJoinMeetingURL(array $params)
{
$this->resetQueries();
foreach ($params as $k => $v) {
$this->setQuery($k, $v);
}
return $this->buildUrl('join', $this->getHTTPQuery());
}
/**
* @param $params
* @param array $meta
*
* @return string
*/
public function getCreateMeetingUrl(array $params, array $meta = array())
{
$this->resetQueries();
foreach ($params as $k => $v) {
$this->setQuery($k, $v);
}
$this->resetMeta();
foreach ($meta as $k => $v) {
$this->setMeta($k, $v);
}
return $this->buildUrl('create', $this->getHTTPQuery());
}
public function createMeeting(array $params, array $meta = array(), $postFields = '')
{
return $this->processXmlResponseArray($this->getCreateMeetingURL($params, $meta), $postFields);
}
/**
* @param $params
*
* @return string
*/
public function getEndMeetingURL(array $params)
{
$this->resetQueries();
foreach ($params as $k => $v) {
$this->setQuery($k, $v);
}
return $this->buildUrl('end', $this->getHTTPQuery());
}
/**
* @param $params
*
* @return array
*/
public function endMeeting(array $params)
{
return $this->processXmlResponseArray($this->getEndMeetingURL($params));
}
/**
* @param $meetingID
* @return string
*/
public function getIsMeetingRunningUrl($meetingID)
{
$this->resetQueries();
$this->setQuery('meetingID', $meetingID);
return $this->buildUrl('isMeetingRunning', $this->getHTTPQuery());
}
/**
* @param $meetingID
* @throws \Exception
*/
public function isMeetingRunning($meetingID)
{
return $this->processXmlResponseArray($this->getIsMeetingRunningUrl($meetingID));
}
/**
* @param $params
* @return string
*/
public function getMeetingInfoUrl(array $params)
{
$this->resetQueries();
foreach ($params as $k => $v) {
$this->setQuery($k, $v);
}
return $this->buildUrl('getMeetingInfo', $this->getHTTPQuery());
}
/**
* @param $params
* @return GetMeetingInfoResponse
*/
public function getMeetingInfo(array $params)
{
return $this->processXmlResponseArray($this->getMeetingInfoUrl($params));
}
/* __________________ BBB RECORDING METHODS _________________ */
/* The methods in the following section support the following categories of the BBB API:
-- getRecordings
-- publishRecordings
-- deleteRecordings
*/
/**
* @param $params
* @return string
*/
public function getRecordingsUrl(array $params)
{
$this->resetQueries();
foreach ($params as $k => $v) {
$this->setQuery($k, $v);
}
return $this->buildUrl('getRecordings', $this->getHTTPQuery());
}
public function getRecordings(array $params)
{
return $this->processXmlResponseArray($this->getRecordingsUrl($params));
}
/**
* @param $params
* @return string
*/
public function getPublishRecordingsUrl(array $params)
{
$this->resetQueries();
foreach ($params as $k => $v) {
$this->setQuery($k, $v);
}
return $this->buildUrl('publishRecordings', $this->getHTTPQuery());
}
public function publishRecordings(array $params)
{
return $this->processXmlResponseArray($this->getPublishRecordingsUrl($params));
}
/**
* @param $params
* @return string
*/
public function getDeleteRecordingsUrl(array $params)
{
$this->resetQueries();
foreach ($params as $k => $v) {
$this->setQuery($k, $v);
}
return $this->buildUrl('deleteRecordings', $this->getHTTPQuery());
}
public function deleteRecordings(array $params)
{
return $this->processXmlResponseArray($this->getDeleteRecordingsUrl($params));
}
/**
* @return string
*/
public function getDefaultConfigXMLUrl()
{
return $this->buildUrl('getDefaultConfigXML', $this->getHTTPQuery());
}
public function getDefaultConfigXML()
{
return $this->processXmlResponseArray($this->getDefaultConfigXMLUrl());
}
/**
* @param $params
* @return string
*/
public function setConfigXMLUrl(array $params)
{
return $this->buildUrl('setConfigXML', $this->buildHTTPQuery($params));
}
public function setConfigXML(array $params)
{
$postFields = array_merge($params, array(
'checksum' => sha1('setConfigXML'.$this->buildHTTPQuery($params).$this->securitySalt)
));
return $this->processXmlResponseArray($this->setConfigXMLUrl($params), $postFields);
}
/**
* @param string $key
*
* @return mixed
*/
public function getQuery($key)
{
return $this->queries[$key];
}
/**
* @param string $key
* @param mixed $val
*
* @return BigBlueButton
*/
public function setQuery($key, $val = '')
{
$this->queries[$key] = $val;
return $this;
}
/**
* @param string $key
*
* @return BigBlueButton
*/
public function unsetQuery($key)
{
unset($this->queries[$key]);
if (!isset($this->queries)) {
$this->queries = array();
}
return $this;
}
/**
* @return BigBlueButton
*/
public function resetQueries()
{
$this->queries = array();
return $this;
}
/**
* @return string
*/
public function getMeta($key)
{
return $this->meta[$key];
}
/**
* @param string $key
* @param string $value
*
* @return CreateMeetingParameters
*/
public function setMeta($key, $value)
{
/**
* Remove prefix to assure the standard
*/
$key = preg_replace('/^meta_/', '', $key);
$this->meta[$key] = $value;
return $this;
}
/**
* @param string $key
*
* @return BigBlueButton
*/
public function unsetMeta($key)
{
unset($this->meta[$key]);
if (!isset($this->meta)) {
$this->meta = array();
}
return $this;
}
/**
* @return BigBlueButton
*/
public function resetMeta()
{
$this->meta = array();
return $this;
}
/**
* @param string $key
*
* @return string
*/
public function getContentType()
{
return $this->contentType;
}
/**
* @param string $key
* @param mixed $val
*
* @return BigBlueButton
*/
public function setContentType($contentType)
{
$this->contentType = $contentType;
return $this;
}
/**
* @return string
*/
public function getHTTPQuery()
{
$queries = $this->queries;
if (!empty($this->meta)) {
foreach ($this->meta as $k => $v) {
/**
* Append prefix to apply the standard
*/
$queries['meta_'.strtolower($k)] = $v;
}
}
return $this->buildHTTPQuery($queries);
}
/**
* @param $array
*
* @return string
*/
public function buildHTTPQuery($array)
{
return http_build_query(array_filter($array));
}
/**
* Builds an API method URL and generates its checksum.
*
* @param string $method
* @param string $params
*
* @return string
*/
public function buildUrl($method = '', $params = '')
{
return $this->bbbServerBaseUrl.'api/'.$method.'?'.$params.'&checksum='.sha1($method.$params.$this->securitySalt);
}
public function processXmlResponse($url, $postFields = '')
{
/*
A private utility method used by other public methods to process XML responses.
*/
if (extension_loaded('curl')) {
$ch = curl_init() or die(curl_error());
$timeout = 10;
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
if (!empty($postFields)) {
if (is_array($postFields)) {
$postFields = http_build_query($postFields);
}
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-type: '.$this->contentType,
'Content-length: '.strlen($postFields),
]);
}
$data = curl_exec($ch);
curl_close($ch);
if ($data) {
return new SimpleXMLElement($data);
} else {
return false;
}
}
if (!empty($postFields)) {
throw new \Exception('Set xml, but curl does not installed.');
}
return simplexml_load_file($url);
}
public function processXmlResponseArray($url, $postFields = '')
{
$xml = $this->processXmlResponse($url, $postFields);
return json_decode(json_encode($xml), true);
}
}
|
virtudraft/bbbx
|
core/components/bbbx/model/bigbluebutton.class.php
|
PHP
|
lgpl-3.0
| 11,466
|
package com.git.opengds.generalization.dbManager;
import java.util.HashMap;
import com.git.gdsbuilder.generalization.rep.DTGeneralReport;
import com.git.gdsbuilder.generalization.rep.DTGeneralReport.DTGeneralReportNumsType;
public class GenResultDBQueryManager {
public HashMap<String, Object> getInsertGenResultQuery(String collectionName, String layerName, String genTbName,
DTGeneralReport resultReport) {
String tableName = "\"" + "shp_layercollection_gen_result" + "\"";
String insertQuery = "insert into " + tableName
+ "(collection_name, before_features_count, after_features_count, before_points_count, after_points_count, layer_name, gen_layer_tb_name) values("
+ "'" + collectionName + "',"
+ resultReport.getDTGeneralReportNums(DTGeneralReportNumsType.ENTITY).getPreNum() + ", "
+ resultReport.getDTGeneralReportNums(DTGeneralReportNumsType.ENTITY).getAfNum() + ", "
+ resultReport.getDTGeneralReportNums(DTGeneralReportNumsType.POINT).getPreNum() + ", "
+ resultReport.getDTGeneralReportNums(DTGeneralReportNumsType.POINT).getAfNum() + ", '" + layerName
+ "', " + "'" + genTbName + "')";
HashMap<String, Object> insertMap = new HashMap<>();
insertMap.put("insertQuery", insertQuery);
return insertMap;
}
}
|
ODTBuilder/Builder-v1.0
|
OpenGDS_2017/src/main/java/com/git/opengds/generalization/dbManager/GenResultDBQueryManager.java
|
Java
|
lgpl-3.0
| 1,267
|
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.List;
import java.util.Locale;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.sonar.api.i18n.I18n;
import org.sonar.api.issue.internal.FieldDiffs;
import org.sonar.api.utils.Duration;
import org.sonar.api.utils.Durations;
import org.sonar.server.tester.UserSessionRule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class IssueChangelogFormatterTest {
private static final Locale DEFAULT_LOCALE = Locale.getDefault();
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Mock
private I18n i18n;
@Mock
private Durations durations;
private IssueChangelogFormatter formatter;
@Before
public void before() {
formatter = new IssueChangelogFormatter(i18n, durations, userSessionRule);
}
@Test
public void format_field_diffs_with_new_and_old_value() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("severity", "BLOCKER", "INFO");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.field.severity", null)).thenReturn("Severity");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.changed_to", null, "Severity", "INFO")).thenReturn("Severity changed to INFO");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.was", null, "BLOCKER")).thenReturn("was BLOCKER");
List<String> result = formatter.format(DEFAULT_LOCALE, diffs);
assertThat(result).hasSize(1);
String message = result.get(0);
assertThat(message).isEqualTo("Severity changed to INFO (was BLOCKER)");
}
@Test
public void format_field_diffs_with_only_new_value() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("severity", null, "INFO");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.field.severity", null)).thenReturn("Severity");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.changed_to", null, "Severity", "INFO")).thenReturn("Severity changed to INFO");
List<String> result = formatter.format(DEFAULT_LOCALE, diffs);
assertThat(result).hasSize(1);
String message = result.get(0);
assertThat(message).isEqualTo("Severity changed to INFO");
}
@Test
public void format_field_diffs_with_only_old_value() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("severity", "BLOCKER", null);
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.field.severity", null)).thenReturn("Severity");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.removed", null, "Severity")).thenReturn("Severity removed");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.was", null, "BLOCKER")).thenReturn("was BLOCKER");
List<String> result = formatter.format(DEFAULT_LOCALE, diffs);
assertThat(result).hasSize(1);
String message = result.get(0);
assertThat(message).isEqualTo("Severity removed (was BLOCKER)");
}
@Test
public void format_field_diffs_without_value() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("severity", null, null);
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.field.severity", null)).thenReturn("Severity");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.removed", null, "Severity")).thenReturn("Severity removed");
List<String> result = formatter.format(DEFAULT_LOCALE, diffs);
assertThat(result).hasSize(1);
String message = result.get(0);
assertThat(message).isEqualTo("Severity removed");
}
@Test
public void format_field_diffs_with_empty_old_value() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("severity", "", null);
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.field.severity", null)).thenReturn("Severity");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.removed", null, "Severity")).thenReturn("Severity removed");
List<String> result = formatter.format(DEFAULT_LOCALE, diffs);
assertThat(result).hasSize(1);
String message = result.get(0);
assertThat(message).isEqualTo("Severity removed");
}
@Test
public void format_technical_debt_with_old_and_new_value() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("technicalDebt", "18000", "28800");
when(durations.format(any(Locale.class), eq(Duration.create(18000L)), eq(Durations.DurationFormat.SHORT))).thenReturn("5 hours");
when(durations.format(any(Locale.class), eq(Duration.create(28800L)), eq(Durations.DurationFormat.SHORT))).thenReturn("1 days");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.field.technicalDebt", null)).thenReturn("Technical Debt");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.changed_to", null, "Technical Debt", "1 days")).thenReturn("Technical Debt changed to 1 days");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.was", null, "5 hours")).thenReturn("was 5 hours");
List<String> result = formatter.format(DEFAULT_LOCALE, diffs);
assertThat(result).hasSize(1);
String message = result.get(0);
assertThat(message).isEqualTo("Technical Debt changed to 1 days (was 5 hours)");
}
@Test
public void format_technical_debt_with_new_value_only() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("technicalDebt", null, "28800");
when(durations.format(any(Locale.class), eq(Duration.create(28800L)), eq(Durations.DurationFormat.SHORT))).thenReturn("1 days");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.field.technicalDebt", null)).thenReturn("Technical Debt");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.changed_to", null, "Technical Debt", "1 days")).thenReturn("Technical Debt changed to 1 days");
List<String> result = formatter.format(DEFAULT_LOCALE, diffs);
assertThat(result).hasSize(1);
String message = result.get(0);
assertThat(message).isEqualTo("Technical Debt changed to 1 days");
}
@Test
public void format_technical_debt_without_value() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("technicalDebt", null, null);
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.field.technicalDebt", null)).thenReturn("Technical Debt");
when(i18n.message(DEFAULT_LOCALE, "issue.changelog.removed", null, "Technical Debt")).thenReturn("Technical Debt removed");
List<String> result = formatter.format(DEFAULT_LOCALE, diffs);
assertThat(result).hasSize(1);
String message = result.get(0);
assertThat(message).isEqualTo("Technical Debt removed");
}
}
|
jblievremont/sonarqube
|
server/sonar-server/src/test/java/org/sonar/server/issue/IssueChangelogFormatterTest.java
|
Java
|
lgpl-3.0
| 7,544
|
// Created file "Lib\src\PortableDeviceGuids\X64\guids"
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(WPD_CONTENT_TYPE_AUDIO_ALBUM, 0xaa18737e, 0x5009, 0x48fa, 0xae, 0x21, 0x85, 0xf2, 0x43, 0x83, 0xb4, 0xe6);
|
Frankie-PellesC/fSDK
|
Lib/src/PortableDeviceGuids/X64/guids000000AE.c
|
C
|
lgpl-3.0
| 477
|
/*
Copyright 2011 PODO.
This file is part of PODO.
PODO 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.
PODO 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 PODO. If not, see <http://www.gnu.org/licenses/>.
*/
#include "PDLang.h"
#include "PDApp.h"
#include "../base/PDFile.h"
#include "../base/PDIniFile.h"
#include "PDLang_p.hpp"
namespace PD
{
Lang::Lang()
{
d = new LangPrivate;
}
Lang::~Lang()
{
d = new LangPrivate;
}
CountryCode Lang::countryCode() { return d->countryCode; }
void Lang::setLanguage(const char* fileName)
{
if( fileName == NULL || !PD::File::exists(fileName) ||
d->language.read(fileName) == -1 )
{
printf("App::setLanguage() language file not loading!\n");
d->languageCheck = false;
d->countryCode = CountryCodeEN;
theApp->setLanguage(this);
return;
}
d->languageCheck = true;
d->countryCode = d->CountryCodeToEnum(
d->language.readEntry("CountryCode", "Code"));
theApp->setLanguage(this);
}
std::string Lang::tr(const std::string& group, const std::string& key)
{
if( d->countryCode == CountryCodeEN )
return key;
if( d->languageCheck )
{
std::string tempKey = key;
tempKey = PD::String::trim(tempKey);
std::string temp = d->language.readEntry(group, tempKey);
temp = PD::String::trim(temp);
if( temp == "" )
return key;
else
{
String::replace(temp, "\\n", "\n");
return temp;
}
}
return key;
}
}
|
ktd2004/podo
|
src/gui/PDLang.cpp
|
C++
|
lgpl-3.0
| 1,902
|
// Created file "Lib\src\sensorsapi\sensorsapi"
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(GUID_PROCESSOR_CORE_PARKING_INCREASE_TIME, 0x2ddd5a84, 0x5a71, 0x437e, 0x91, 0x2a, 0xdb, 0x0b, 0x8c, 0x78, 0x87, 0x32);
|
Frankie-PellesC/fSDK
|
Lib/src/sensorsapi/sensorsapi00000058.c
|
C
|
lgpl-3.0
| 482
|
<?php
namespace Google\AdsApi\Dfp\v201708;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class SamSessionError extends \Google\AdsApi\Dfp\v201708\ApiError
{
/**
* @var string $reason
*/
protected $reason = null;
/**
* @param string $fieldPath
* @param \Google\AdsApi\Dfp\v201708\FieldPathElement[] $fieldPathElements
* @param string $trigger
* @param string $errorString
* @param string $reason
*/
public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null)
{
parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString);
$this->reason = $reason;
}
/**
* @return string
*/
public function getReason()
{
return $this->reason;
}
/**
* @param string $reason
* @return \Google\AdsApi\Dfp\v201708\SamSessionError
*/
public function setReason($reason)
{
$this->reason = $reason;
return $this;
}
}
|
advanced-online-marketing/AOM
|
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201708/SamSessionError.php
|
PHP
|
lgpl-3.0
| 1,052
|
package stripedash
import (
"fmt"
"strconv"
)
func Uint64ToDollars(i uint64) string {
d := []byte(strconv.FormatUint(i, 10))
// Cents only
if len(d) < 3 {
return fmt.Sprintf("0.%s", d)
}
// Dollars and cents
centStart := len(d) - 2
dollars := d[0:centStart]
cents := d[centStart:len(d)]
return fmt.Sprintf("%s.%s", string(dollars), string(cents))
}
|
remkade/stripedash
|
helpers.go
|
GO
|
lgpl-3.0
| 367
|
/**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2012 Ricardo Mariaca
* http://dynamicreports.sourceforge.net
*
* This file is part of DynamicReports.
*
* DynamicReports 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.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.jasper.base;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import net.sf.dynamicreports.jasper.exception.JasperDesignException;
import net.sf.dynamicreports.report.base.style.DRBaseStyle;
import net.sf.dynamicreports.report.base.style.DRBorder;
import net.sf.dynamicreports.report.base.style.DRConditionalStyle;
import net.sf.dynamicreports.report.base.style.DRFont;
import net.sf.dynamicreports.report.base.style.DRPadding;
import net.sf.dynamicreports.report.base.style.DRParagraph;
import net.sf.dynamicreports.report.base.style.DRPen;
import net.sf.dynamicreports.report.base.style.DRStyle;
import net.sf.dynamicreports.report.base.style.DRTabStop;
import net.sf.dynamicreports.report.builder.expression.Expressions;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.constant.ImageScale;
import net.sf.dynamicreports.report.constant.LineSpacing;
import net.sf.dynamicreports.report.constant.LineStyle;
import net.sf.dynamicreports.report.constant.Markup;
import net.sf.dynamicreports.report.constant.Rotation;
import net.sf.dynamicreports.report.constant.TabStopAlignment;
import net.sf.dynamicreports.report.constant.VerticalAlignment;
import net.sf.dynamicreports.report.definition.expression.DRIExpression;
import net.sf.dynamicreports.report.definition.style.DRIStyle;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRConditionalStyle;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRLineBox;
import net.sf.jasperreports.engine.JRParagraph;
import net.sf.jasperreports.engine.JRPen;
import net.sf.jasperreports.engine.JRStyle;
import net.sf.jasperreports.engine.JRTemplate;
import net.sf.jasperreports.engine.TabStop;
import net.sf.jasperreports.engine.type.HorizontalAlignEnum;
import net.sf.jasperreports.engine.type.LineSpacingEnum;
import net.sf.jasperreports.engine.type.LineStyleEnum;
import net.sf.jasperreports.engine.type.RotationEnum;
import net.sf.jasperreports.engine.type.ScaleImageEnum;
import net.sf.jasperreports.engine.type.TabStopAlignEnum;
import net.sf.jasperreports.engine.type.VerticalAlignEnum;
import net.sf.jasperreports.engine.xml.JRXmlTemplateLoader;
import org.apache.commons.lang3.Validate;
/**
* @author Ricardo Mariaca (dynamicreports@gmail.com)
*/
public class JasperTemplateStyleLoader {
public static DRIStyle[] loadStyles(File file) {
Validate.notNull(file, "file must not be null");
return loadStyles(JRXmlTemplateLoader.load(file));
}
public static DRIStyle[] loadStyles(String fileName) throws DRException {
Validate.notNull(fileName, "fileName must not be null");
try {
return loadStyles(JRXmlTemplateLoader.load(fileName));
} catch (JRException e) {
throw new DRException(e);
}
}
public static DRIStyle[] loadStyles(InputStream inputStream) {
Validate.notNull(inputStream, "inputStream must not be null");
return loadStyles(JRXmlTemplateLoader.load(inputStream));
}
public static DRIStyle[] loadStyles(URL url) {
Validate.notNull(url, "url must not be null");
return loadStyles(JRXmlTemplateLoader.load(url));
}
private static DRIStyle[] loadStyles(JRTemplate template) {
Validate.notNull(template, "template must not be null");
JRStyle[] jrStyles = template.getStyles();
DRIStyle[] styles = new DRIStyle[jrStyles.length];
for (int i = 0; i < jrStyles.length; i++) {
JRStyle jrStyle = jrStyles[i];
styles[i] = convertStyle(jrStyle);
}
return styles;
}
private static DRStyle convertStyle(JRStyle jrStyle) {
DRStyle style = new DRStyle();
abstractStyle(jrStyle, style);
style.setName(jrStyle.getName());
JRStyle jrParentStyle = jrStyle.getStyle();
if (jrParentStyle != null) {
style.setParentStyle(convertStyle(jrParentStyle));
}
for (JRConditionalStyle jrConditionalStyle : jrStyle.getConditionalStyles()) {
style.addConditionalStyle(conditionalStyle(jrConditionalStyle));
}
return style;
}
private static DRConditionalStyle conditionalStyle(JRConditionalStyle jrConditionalStyle) {
DRIExpression<Boolean> expression = Expressions.jasperSyntax(jrConditionalStyle.getConditionExpression().getText(), Boolean.class);
DRConditionalStyle conditionalStyle = new DRConditionalStyle(expression);
abstractStyle(jrConditionalStyle, conditionalStyle);
return conditionalStyle;
}
private static void abstractStyle(JRStyle jrStyle, DRBaseStyle style) {
style.setForegroundColor(jrStyle.getOwnForecolor());
style.setBackgroundColor(jrStyle.getOwnBackcolor());
style.setRadius(jrStyle.getOwnRadius());
style.setImageScale(imageScale(jrStyle.getOwnScaleImageValue()));
style.setHorizontalAlignment(horizontalAlignment(jrStyle.getOwnHorizontalAlignmentValue()));
style.setVerticalAlignment(verticalAlignment(jrStyle.getOwnVerticalAlignmentValue()));
border(jrStyle.getLineBox(), style.getBorder());
padding(jrStyle.getLineBox(), style.getPadding());
font(jrStyle, style.getFont());
style.setRotation(rotation(jrStyle.getOwnRotationValue()));
style.setPattern(jrStyle.getOwnPattern());
style.setMarkup(markup(jrStyle.getOwnMarkup()));
paragraph(jrStyle.getParagraph(), style.getParagraph());
pen(jrStyle.getLinePen(), style.getLinePen());
}
private static void paragraph(JRParagraph jrParagraph, DRParagraph paragraph) {
paragraph.setLineSpacing(lineSpacing(jrParagraph.getOwnLineSpacing()));
paragraph.setLineSpacingSize(jrParagraph.getOwnLineSpacingSize());
paragraph.setFirstLineIndent(jrParagraph.getOwnFirstLineIndent());
paragraph.setLeftIndent(jrParagraph.getOwnLeftIndent());
paragraph.setRightIndent(jrParagraph.getOwnRightIndent());
paragraph.setSpacingBefore(jrParagraph.getOwnSpacingBefore());
paragraph.setSpacingAfter(jrParagraph.getOwnSpacingAfter());
paragraph.setTabStopWidth(jrParagraph.getOwnTabStopWidth());
if (jrParagraph.getOwnTabStops() != null) {
for (TabStop jrTabStop : jrParagraph.getOwnTabStops()) {
DRTabStop tabStop = new DRTabStop();
tabStop.setPosition(jrTabStop.getPosition());
tabStop.setAlignment(tabStopAlignment(jrTabStop.getAlignment()));
paragraph.getTabStops().add(tabStop);
}
}
}
protected static void pen(JRPen jrPen, DRPen pen) {
pen.setLineColor(jrPen.getOwnLineColor());
pen.setLineStyle(lineStyle(jrPen.getOwnLineStyleValue()));
pen.setLineWidth(jrPen.getOwnLineWidth());
}
private static void border(JRLineBox jrLineBox, DRBorder border) {
pen(jrLineBox.getLeftPen(), border.getLeftPen());
pen(jrLineBox.getRightPen(), border.getRightPen());
pen(jrLineBox.getTopPen(), border.getTopPen());
pen(jrLineBox.getBottomPen(), border.getBottomPen());
}
private static void padding(JRLineBox jrLineBox, DRPadding padding) {
padding.setLeft(jrLineBox.getOwnLeftPadding());
padding.setRight(jrLineBox.getOwnRightPadding());
padding.setTop(jrLineBox.getOwnTopPadding());
padding.setBottom(jrLineBox.getOwnBottomPadding());
}
@SuppressWarnings("deprecation")
private static void font(JRStyle jrStyle, DRFont font) {
font.setFontName(jrStyle.getOwnFontName());
font.setBold(jrStyle.isOwnBold());
font.setItalic(jrStyle.isOwnItalic());
font.setFontSize(jrStyle.getOwnFontSize());
font.setStrikeThrough(jrStyle.isOwnStrikeThrough());
font.setUnderline(jrStyle.isOwnUnderline());
font.setPdfFontName(jrStyle.getOwnPdfFontName());
font.setPdfEncoding(jrStyle.getOwnPdfEncoding());
font.setPdfEmbedded(jrStyle.isOwnPdfEmbedded());
}
private static LineStyle lineStyle(LineStyleEnum lineStyle) {
if (lineStyle == null) {
return null;
}
switch (lineStyle) {
case SOLID:
return LineStyle.SOLID;
case DASHED:
return LineStyle.DASHED;
case DOTTED:
return LineStyle.DOTTED;
case DOUBLE:
return LineStyle.DOUBLE;
default:
throw new JasperDesignException("Line style " + lineStyle.name() + " not supported");
}
}
private static ImageScale imageScale(ScaleImageEnum imageScale) {
if (imageScale == null) {
return null;
}
switch (imageScale) {
case CLIP:
return ImageScale.NO_RESIZE;
case FILL_FRAME:
return ImageScale.FILL;
case RETAIN_SHAPE:
return ImageScale.FILL_PROPORTIONALLY;
default:
throw new JasperDesignException("Image scale " + imageScale.name() + " not supported");
}
}
private static HorizontalAlignment horizontalAlignment(HorizontalAlignEnum horizontalAlignment) {
if (horizontalAlignment == null) {
return null;
}
switch (horizontalAlignment) {
case LEFT:
return HorizontalAlignment.LEFT;
case CENTER:
return HorizontalAlignment.CENTER;
case RIGHT:
return HorizontalAlignment.RIGHT;
case JUSTIFIED:
return HorizontalAlignment.JUSTIFIED;
default:
throw new JasperDesignException("Horizontal alignment " + horizontalAlignment.name() + " not supported");
}
}
private static VerticalAlignment verticalAlignment(VerticalAlignEnum verticalAlignment) {
if (verticalAlignment == null) {
return null;
}
switch (verticalAlignment) {
case TOP:
return VerticalAlignment.TOP;
case MIDDLE:
return VerticalAlignment.MIDDLE;
case BOTTOM:
return VerticalAlignment.BOTTOM;
case JUSTIFIED:
return VerticalAlignment.JUSTIFIED;
default:
throw new JasperDesignException("Vertical alignment " + verticalAlignment.name() + " not supported");
}
}
private static Markup markup(String markup) {
if (markup == null) {
return null;
}
if (markup.equals("none")) {
return Markup.NONE;
}
if (markup.equals("styled")) {
return Markup.STYLED;
}
if (markup.equals("rtf")) {
return Markup.RTF;
}
if (markup.equals("html")) {
return Markup.HTML;
}
throw new JasperDesignException("Markup " + markup + " not supported");
}
private static LineSpacing lineSpacing(LineSpacingEnum lineSpacing) {
if (lineSpacing == null) {
return null;
}
switch (lineSpacing) {
case SINGLE:
return LineSpacing.SINGLE;
case ONE_AND_HALF:
return LineSpacing.ONE_AND_HALF;
case DOUBLE:
return LineSpacing.DOUBLE;
case AT_LEAST:
return LineSpacing.AT_LEAST;
case FIXED:
return LineSpacing.FIXED;
case PROPORTIONAL:
return LineSpacing.PROPORTIONAL;
default:
throw new JasperDesignException("LineSpacing " + lineSpacing.name() + " not supported");
}
}
protected static Rotation rotation(RotationEnum rotation) {
if (rotation == null) {
return null;
}
switch (rotation) {
case NONE:
return Rotation.NONE;
case LEFT:
return Rotation.LEFT;
case RIGHT:
return Rotation.RIGHT;
case UPSIDE_DOWN:
return Rotation.UPSIDE_DOWN;
default:
throw new JasperDesignException("Rotation " + rotation.name() + " not supported");
}
}
private static TabStopAlignment tabStopAlignment(TabStopAlignEnum alignment) {
switch (alignment) {
case LEFT:
return TabStopAlignment.LEFT;
case CENTER:
return TabStopAlignment.CENTER;
case RIGHT:
return TabStopAlignment.RIGHT;
default:
throw new JasperDesignException("TabStopAlignment " + alignment.name() + " not supported");
}
}
}
|
robcowell/dynamicreports
|
dynamicreports-core/src/main/java/net/sf/dynamicreports/jasper/base/JasperTemplateStyleLoader.java
|
Java
|
lgpl-3.0
| 11,989
|
import { HistoryOptions, History } from '../index';
export default function createHashHistory(options?: HistoryOptions): History;
|
solaimanjdn/framework
|
Signum.React/node_modules/@types/history/lib/createHashHistory.d.ts
|
TypeScript
|
lgpl-3.0
| 130
|
// -*- C++ -*-
/*
* Simple MultimEdia LiTerator(SMELT)
* by Chris Xiong 2015
* SFX dumb implementation
* This dumb implementation has everything stubbed, useful if you don't
* use the audio routines here.
*
* WARNING: This library is in development and interfaces would be very
* unstable.
*
*/
#include "smelt_internal.hpp"
static const char* SFX_SDL_SRCFN="smelt/sdl/sfx_dumb.cpp";
SMSFX SMELT_IMPL::smSFXLoad(const char *path)
{return 0;}
SMSFX SMELT_IMPL::smSFXLoadFromMemory(const char *ptr,DWORD size)
{return 0;}
SMCHN SMELT_IMPL::smSFXPlay(SMSFX fx,int vol,int pan,float pitch,bool loop)
{return 0;}
float SMELT_IMPL::smSFXGetLengthf(SMSFX fx)
{return 0.0;}
DWORD SMELT_IMPL::smSFXGetLengthd(SMSFX fx)
{return -1;}
void SMELT_IMPL::smSFXSetLoopPoint(SMSFX fx,DWORD l,DWORD r)
{}
void SMELT_IMPL::smSFXFree(SMSFX fx)
{}
void SMELT_IMPL::smChannelVol(SMCHN chn,int vol)
{}
void SMELT_IMPL::smChannelPan(SMCHN chn,int pan)
{}
void SMELT_IMPL::smChannelPitch(SMCHN chn,float pitch)
{}
void SMELT_IMPL::smChannelPause(SMCHN chn)
{}
void SMELT_IMPL::smChannelResume(SMCHN chn)
{}
void SMELT_IMPL::smChannelStop(SMCHN chn)
{}
void SMELT_IMPL::smChannelPauseAll()
{}
void SMELT_IMPL::smChannelResumeAll()
{}
void SMELT_IMPL::smChannelStopAll()
{}
bool SMELT_IMPL::smChannelIsPlaying(SMCHN chn)
{return false;}
float SMELT_IMPL::smChannelGetPosf(SMCHN chn)
{return -1.;}
void SMELT_IMPL::smChannelSetPosf(SMCHN chn,float pos)
{}
int SMELT_IMPL::smChannelGetPosd(SMCHN chn)
{return -1;}
void SMELT_IMPL::smChannelSetPosd(SMCHN chn,int pos)
{}
ALuint SMELT_IMPL::getSource()
{return 0;}
bool SMELT_IMPL::initOAL()
{
smLog("%s:" SLINE ": I'm dumb!\n",SFX_SDL_SRCFN);
pOpenALDevice=(void*)1;
return true;
}
void SMELT_IMPL::finiOAL()
{
if(pOpenALDevice)
{
pOpenALDevice=NULL;
}
}
|
BearKidsTeam/SMELT
|
smelt/w32/sfx_dumb.cpp
|
C++
|
lgpl-3.0
| 1,796
|
/*
* Copyright (c) 2009 Thierry FOURNIER
*
* This file is part of MySAC.
*
* MySAC 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
*
* MySAC 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 MySAC. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file */
#ifndef __MYSAC_H__
#define __MYSAC_H__
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <mysql/errmsg.h>
#include <mysql/mysql.h>
/* def imported from: linux-2.6.24/include/linux/stddef.h */
#define mysac_offset_of(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
/**
* container_of - cast a member of a structure out to the containing structure
*
* def imported from: linux-2.6.24/include/linux/kernel.h
*
* @param ptr the pointer to the member.
* @param type the type of the container struct this is embedded in.
* @param member the name of the member within the struct.
*
*/
#define mysac_container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - mysac_offset_of(type,member) );})
/**
* Simple doubly linked list implementation.
*
* def imported from: linux-2.6.24/include/linux/list.h
*
* Some of the internal functions ("__xxx") are useful when
* manipulating whole lists rather than single entries, as
* sometimes we already know the next/prev entries and we can
* generate better code by using them directly rather than
* using the generic single-entry routines.
*/
struct mysac_list_head {
struct mysac_list_head *next, *prev;
};
/**
* list_entry - get the struct for this entry
*
* def imported from: linux-2.6.24/include/linux/list.h
*
* @param ptr: the &struct list_head pointer.
* @param type: the type of the struct this is embedded in.
* @param member: the name of the list_struct within the struct.
*/
#define mysac_list_entry(ptr, type, member) \
mysac_container_of(ptr, type, member)
/**
* list_first_entry - get the first element from a list
*
* def imported from: linux-2.6.24/include/linux/list.h
* @param ptr the list head to take the element from.
* @param type the type of the struct this is embedded in.
* @param member the name of the list_struct within the struct.
*
* Note, that list is expected to be not empty.
*/
#define mysac_list_first_entry(ptr, type, member) \
mysac_list_entry((ptr)->next, type, member)
#define mysac_list_next_entry(ptr, type, member) \
mysac_list_first_entry(ptr, type, member);
enum my_query_st {
MYSAC_START,
MYSAC_CONN_CHECK,
MYSAC_READ_GREATINGS,
MYSAC_SEND_AUTH_1,
MYSAC_RECV_AUTH_1,
MYSAC_SEND_AUTH_2,
MYSAC_SEND_QUERY,
MYSAC_RECV_QUERY_COLNUM,
MYSAC_RECV_QUERY_COLDESC1,
MYSAC_RECV_QUERY_COLDESC2,
MYSAC_RECV_QUERY_EOF1,
MYSAC_RECV_QUERY_EOF2,
MYSAC_RECV_QUERY_DATA,
MYSAC_SEND_INIT_DB,
MYSAC_RECV_INIT_DB,
MYSAC_SEND_STMT_QUERY,
MYSAC_RECV_STMT_QUERY,
MYSAC_SEND_STMT_EXECUTE,
MYSAC_RECV_STMT_EXECUTE,
MYSAC_READ_NUM,
MYSAC_READ_HEADER,
MYSAC_READ_LINE
};
#define MYSAC_COL_MAX_LEN 50
#define MYSAC_COL_MAX_NUN 100
/* errors */
enum {
MYERR_PROTOCOL_ERROR = 1,
MYERR_BUFFER_OVERSIZE,
MYERR_PACKET_CORRUPT,
MYERR_WANT_READ,
MYERR_WANT_WRITE,
MYERR_UNKNOWN_ERROR,
MYERR_MYSQL_ERROR,
MYERR_SERVER_LOST,
MYERR_BAD_PORT,
MYERR_BAD_STATE,
MYERR_RESOLV_HOST,
MYERR_SYSTEM,
MYERR_CANT_CONNECT,
MYERR_BUFFER_TOO_SMALL,
MYERR_UNEXPECT_R_STATE,
MYERR_STRFIELD_CORRUPT,
MYERR_BINFIELD_CORRUPT,
MYERR_BAD_LCB,
MYERR_LEN_OVER_BUFFER,
MYERR_CONVLONG,
MYERR_CONVLONGLONG,
MYERR_CONVFLOAT,
MYERR_CONVDOUBLE,
MYERR_CONVTIME,
MYERR_CONVTIMESTAMP,
MYERR_CONVDATE
};
extern const char *mysac_type[];
extern const char *mysac_errors[];
/**
* This is union containing all c type matching mysql types
*/
typedef union {
signed char stiny; /* MYSQL_TYPE_TINY TINYINT */
unsigned char utiny; /* MYSQL_TYPE_TINY TINYINT */
unsigned char mbool; /* MYSQL_TYPE_TINY TINYINT */
short ssmall; /* MYSQL_TYPE_SHORT SMALLINT */
unsigned short small; /* MYSQL_TYPE_SHORT SMALLINT */
int sint; /* MYSQL_TYPE_LONG INT */
unsigned int uint; /* MYSQL_TYPE_LONG INT */
long long sbigint; /* MYSQL_TYPE_LONGLONG BIGINT */
unsigned long long ubigint; /* MYSQL_TYPE_LONGLONG BIGINT */
float mfloat; /* MYSQL_TYPE_FLOAT FLOAT */
double mdouble; /* MYSQL_TYPE_DOUBLE DOUBLE */
struct timeval tv; /* MYSQL_TYPE_TIME TIME */
struct tm *tm; /* MYSQL_TYPE_DATE DATE
MYSQL_TYPE_DATETIME DATETIME
MYSQL_TYPE_TIMESTAMP TIMESTAMP */
char *string; /* MYSQL_TYPE_STRING TEXT,CHAR,VARCHAR */
char *blob; /* MYSQL_TYPE_BLOB BLOB,BINARY,VARBINARY */
void *ptr; /* generic pointer */
} MYSAC_ROW;
/**
* This is chained element. contain pointer to each elements of one row
*/
typedef struct {
struct mysac_list_head link;
unsigned long *lengths;
MYSAC_ROW *data;
} MYSAC_ROWS;
/**
* This contain the complete result of one request
*/
typedef struct {
char *buffer;
int buffer_len;
int nb_cols;
int nb_lines;
int nb_time;
int extend_bloc_size;
int max_len;
int do_free;
MYSQL_FIELD *cols;
struct mysac_list_head data;
MYSAC_ROWS *cr;
} MYSAC_RES;
/**
* This contain list of values for statement binding
*/
typedef struct mysac_bind {
enum enum_field_types type;
void *value;
int value_len;
char is_null;
} MYSAC_BIND;
/**
* This contain the necessary for one mysql connection
*/
typedef struct mysac {
int len;
char *read;
int read_len;
char *send;
int readst;
unsigned int packet_length;
unsigned int packet_number;
/* mysac */
char free_it;
int fd;
int (*call_it)(/* MYSAC * */ struct mysac *);
/*defconnect */
unsigned int protocol;
char *version;
unsigned int threadid;
char salt[SCRAMBLE_LENGTH + 1];
unsigned int options;
unsigned int charset;
unsigned int status;
unsigned long affected_rows;
unsigned int warnings;
unsigned int errorcode;
unsigned long insert_id;
char *mysql_code;
char *mysql_error;
char eof;
/* user */
const char *addr;
const char *login;
const char *password;
const char *database;
const char *query;
unsigned int flags;
/* query */
enum my_query_st qst;
int read_id;
MYSAC_RES *res;
unsigned long *stmt_id;
/* the buffer */
unsigned int bufsize;
char *buf;
/* special stmt */
int nb_cols; /* number of columns in response */
int nb_plhold; /* number of placeholders in request */
} MYSAC;
/**
* Allocates and initializes a MYSQL object.
* If mysql is a NULL pointer, the function allocates, initializes, and
* returns a new object. Otherwise, the object is initialized and the address
* of the object is returned. If mysql_init() allocates a new object, it is
* freed when mysql_close() is called to close the connection.
*
* @param buffsize is the size of the buffer
*
* @return An initialized MYSAC* handle. NULL if there was insufficient memory
* to allocate a new object.
*/
MYSAC *mysac_new(int buffsize);
/**
* Initializes a MYSQL object.
* If mysql is a NULL pointer, the function allocates, initializes, and
* returns a new object. Otherwise, the object is initialized and the address
* of the object is returned. If mysql_init() allocates a new object, it is
* freed when mysql_close() is called to close the connection.
*
* @param mysac Should be the address of an existing MYSAC structure.
* @param buffer is ptr on the pre-allocated buffer
* @param buffsize is the size of the buffer
*/
void mysac_init(MYSAC *mysac, char *buffer, unsigned int buffsize);
/**
* mysac_connect() attempts to establish a connection to a MySQL database engine
* running on host. mysql_real_connect() must complete successfully before you
* can execute any other API functions that require a valid MYSQL connection
* handle structure.
*
* @param mysac The first parameter should be the address of an existing MYSQL
* structure. Before calling mysql_real_connect() you must call
* mysql_init() to initialize the MYSQL structure. You can change a lot
* of connect options with the mysql_options() call.
*
* @param my_addr like "<ipv4>:<port>" "<ipv6>:<port>", "socket_unix_file" or
* NULL. If NULL, bind is set to socket 0
*
* @param user The user parameter contains the user's MySQL login ID. If user
* is NULL or the empty string "", the current user is assumed.
*
* @param passwd The passwd parameter contains the password for user. If passwd
* is NULL, only entries in the user table for the user that have a blank
* (empty) password field are checked for a match.
*
* @param db is the database name. If db is not NULL, the connection sets the
* default database to this value.
*
* @param client_flag The value of client_flag is usually 0, but can be set to a
* combination of the following flags to enable certain features:
*
* Flag Name Flag Description
* CLIENT_COMPRESS Use compression protocol.
* CLIENT_FOUND_ROWS Return the number of found (matched) rows,
* not the number of changed rows.
* CLIENT_IGNORE_SPACE Allow spaces after function names. Makes all
* functions names reserved words.
*/
void mysac_setup(MYSAC *mysac, const char *my_addr, const char *user,
const char *passwd, const char *db,
unsigned long client_flag);
/**
* Run network connexion and mysql authentication
*
* @param mysac Should be the address of an existing MYSQL structure.
*
* @return
* MYERR_WANT_READ : want read socket
* MYERR_WANT_WRITE : want write socket
* CR_CONN_HOST_ERROR : Failed to connect to the MySQL server.
* CR_CONNECTION_ERROR : Failed to connect to the local MySQL server.
* CR_IPSOCK_ERROR : Failed to create an IP socket.
* CR_OUT_OF_MEMORY : Out of memory.
* CR_SOCKET_CREATE_ERROR : Failed to create a Unix socket.
* CR_UNKNOWN_HOST : Failed to find the IP address for the hostname.
* CR_VERSION_ERROR : A protocol mismatch resulted from attempting to
* connect to a server with a client library that
* uses a different protocol version.
* CR_SERVER_LOST : If connect_timeout > 0 and it took longer than
* connect_timeout seconds to connect to the server
* or if the server died while executing the
* init-command.
*/
int mysac_connect(MYSAC *mysac);
/**
* Closes a previously opened connection. mysql_close() also deallocates the
* connection handle pointed to by mysql if the handle was allocated
* automatically by mysql_init() or mysql_connect().
*
* @param mysac Should be the address of an existing MYSQL structure.
*/
void mysac_close(MYSAC *mysac);
/**
* This function return the mysql filedescriptor used for connection
* to the mysql server
*
* @param mysac Should be the address of an existing MYSAC structure.
*
* @return mysql filedescriptor
*/
int mysac_get_fd(MYSAC *mysac);
/**
* this function call the io function associated with the current
* command. (mysac_send_database, mysac_send_query and mysac_connect)
*
* @param mysac Should be the address of an existing MYSAC structure.
*
* @return 0 is ok, or all errors associated with functions
* mysac_send_database, mysac_send_query and mysac_connect or
* MYERR_BAD_STATE : the function does nothing to do (is an error)
*/
int mysac_io(MYSAC *mysac);
/**
* Build use database message
*
* @param mysac Should be the address of an existing MYSQL structure.
* @param database is the database name
*/
int mysac_set_database(MYSAC *mysac, const char *database);
/**
* This send use database command
*
* @param mysac Should be the address of an existing MYSQL structure.
*
* @return
* 0 => ok
* MYSAC_WANT_READ
* MYSAC_WANT_WRITE
* ...
*/
int mysac_send_database(MYSAC *mysac);
/**
* Initialize MYSAC_RES structur
* This function can not allocate memory, just use your buffer.
*
* @param buffer this buffer must contain all the sql response.
* this size is:
* sizeof(MYSAC_RES) +
* ( sizeof(MYSQL_FIELD) * nb_field ) +
* ( different fields names )
*
* and for each row:
* sizeof(MYSAC_ROWS) +
* ( sizeof(MYSAC_ROW) * nb_field ) +
* ( sizeof(unsigned long) * nb_field ) +
* ( sizeof(struct tm) for differents date fields of the request ) +
* ( differents strings returned by the request ) +
*
* @param len is the len of the buffer
*
* @return MYSAC_RES. this function cannot be fail
*/
MYSAC_RES *mysac_init_res(char *buffer, int len);
/**
* Create new MYSAC_RES structur
* This function allocate memory
*
* WARNING: If extend is set, you must use the function mysac_get_res
* for retrieving the resource pointer after each call att
* mysac_send_query.
*
* @param chunk_size is the size allocated for the bloc
* @param extend if is true, the block is extended if the initial
* memory does not enough. the extension size is the size
* of chunk_size
*/
MYSAC_RES *mysac_new_res(int chunk_size, int extend);
/**
* Destroy MYSAC_RES structur
* This function free memory
*/
void mysac_free_res(MYSAC_RES *r);
/**
* Initialize query
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param res Should be the address of an existing MYSAC_RES structur.
* @param fmt is the output format with the printf style
*
* @return 0: ok, -1 nok
*/
int mysac_set_query(MYSAC *mysac, MYSAC_RES *res, const char *fmt, ...);
/**
* Initialize query
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param res Should be the address of an existing MYSAC_RES structur.
* @param fmt is the output format with the printf style
* @param ap is the argument list on format vprintf
*
* @return 0: ok, -1 nok
*/
int mysac_v_set_query(MYSAC *mysac, MYSAC_RES *res, const char *fmt, va_list ap);
/**
* Initialize query
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param res Should be the address of an existing MYSAC_RES structur.
* @param query is a string (terminated by \0) containing the query
*
* @return 0: ok, -1 nok
*/
int mysac_s_set_query(MYSAC *mysac, MYSAC_RES *res, const char *query);
/**
* Initialize query
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param res Should be the address of an existing MYSAC_RES structur.
* @param query is a string containing the query
* @param len is the len of the query
*
* @return 0: ok, -1 nok
*/
int mysac_b_set_query(MYSAC *mysac, MYSAC_RES *res, const char *query, int len);
/**
* This function return the mysql response pointer
*
* @param mysac Should be the address of an existing MYSAC structure.
*
* @return mysql response pointer
*/
MYSAC_RES *mysac_get_res(MYSAC *mysac);
/**
* Send sql query command
*
* @param mysac Should be the address of an existing MYSAC structur.
*
* @return
* 0 => ok
* MYSAC_WANT_READ
* MYSAC_WANT_WRITE
* ...
*/
int mysac_send_query(MYSAC *mysac);
/**
* Prepare statement
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param stmt_id is the receiver of the statement id
* @param fmt is the output format with the printf style
*
* @return 0: ok, -1 nok
*/
int mysac_set_stmt_prepare(MYSAC *mysac, unsigned long *stmt_id, const char *fmt, ...);
/**
* Prepare statement
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param stmt_id is the receiver of the statement id
* @param fmt is the output format with the printf style
* @param ap is the argument list on format vprintf
*
* @return 0: ok, -1 nok
*/
int mysac_v_set_stmt_prepare(MYSAC *mysac, unsigned long *stmt_id, const char *fmt, va_list ap);
/**
* Prepare statement
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param stmt_id is the receiver of the statement id
* @param query is a string (terminated by \0) containing the query
*
* @return 0: ok, -1 nok
*/
int mysac_s_set_stmt_prepare(MYSAC *mysac, unsigned long *stmt_id, const char *request);
/**
* Prepare statement
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param stmt_id is the receiver of the statement id
* @param request is a string containing the query
* @param len is the len of the query
*
* @return 0: ok, -1 nok
*/
int mysac_b_set_stmt_prepare(MYSAC *mysac, unsigned long *stmt_id, const char *request, int len);
/**
* Send sql query command
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param stmt_id is pointer for storing the statement id
*
* @return
* 0 => ok
* MYSAC_WANT_READ
* MYSAC_WANT_WRITE
* ...
*/
int mysac_send_stmt_prepare(MYSAC *mysac);
/**
* Execute statement
*
* @param mysac Should be the address of an existing MYSAC structur.
* @param res Should be the address of an existing MYSAC_RES structur.
* @param stmt_id the statement id
* @param values is array of values send for the request
* @param nb is number of values
*
* @return 0: ok, -1 nok
*/
int mysac_set_stmt_execute(MYSAC *mysac, MYSAC_RES *res, unsigned long stmt_id,
MYSAC_BIND *values, int nb);
/**
* send stmt execute command
*
* @param mysac Should be the address of an existing MYSQL structure.
*
* @return
*/
int mysac_send_stmt_execute(MYSAC *mysac);
/**
* After executing a statement with mysql_query() returns the number of rows
* changed (for UPDATE), deleted (for DELETE), orinserted (for INSERT). For
* SELECT statements, mysql_affected_rows() works like mysql_num_rows().
*
* @param mysac Should be the address of an existing MYSQL structure.
*
* @return An integer greater than zero indicates the number of rows affected
* or retrieved. Zero indicates that no records were updated for an
* UPDATE statement, no rows matched the WHERE clause in the query or
* that no query has yet been executed. -1 indicates that the query
* returned an error or that, for a SELECT query, mysql_affected_rows()
* was called prior to calling mysql_store_result(). Because
* mysql_affected_rows() returns an unsigned value, you can check for -1
* by comparing the return value to (my_ulonglong)-1 (or to
* (my_ulonglong)~0, which is equivalent).
*/
int mysac_affected_rows(MYSAC *mysac);
/**
* Returns the number of columns for the most recent query on the connection.
*
* @param res Should be the address of an existing MYSAC_RES structure.
*
* @return number of columns
*/
unsigned int mysac_field_count(MYSAC_RES *res);
/**
* Returns the number of rows in the result set.
*
* mysql_num_rows() is intended for use with statements that return a result
* set, such as SELECT. For statements such as INSERT, UPDATE, or DELETE, the
* number of affected rows can be obtained with mysql_affected_rows().
*
* @param res Should be the address of an existing MYSAC_RES structure.
*
* @return The number of rows in the result set.
*/
unsigned long mysac_num_rows(MYSAC_RES *res);
/**
* Retrieves the next row of a result set. mysql_fetch_row() returns NULL when
* there are no more rows to retrieve or if an error occurred.
*
* The number of values in the row is given by mysql_num_fields(result).
*
* The lengths of the field values in the row may be obtained by calling
* mysql_fetch_lengths(). Empty fields and fields containing NULL both have
* length 0; you can distinguish these by checking the pointer for the field
* value. If the pointer is NULL, the field is NULL; otherwise, the field is
* empty.
*
* @param res Should be the address of an existing MYSAC_RES structure.
*
* @return A MYSAC_ROW structure for the next row. NULL if there are no more
* rows to retrieve or if an error occurred.
*/
MYSAC_ROW *mysac_fetch_row(MYSAC_RES *res);
/**
* Set pointer on the first row, you can exec mysac_fetch_row, return it the
* first row;
*/
void mysac_first_row(MYSAC_RES *res);
/**
* Get current row, dont touch row ptr
*/
MYSAC_ROW *mysac_cur_row(MYSAC_RES *res);
/**
* Returns the value generated for an AUTO_INCREMENT column by the previous
* INSERT or UPDATE statement. Use this function after you have performed an
* INSERT statement into a table that contains an AUTO_INCREMENT field
*
* http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html
*
* @param m Should be the address of an existing MYSQL structure.
*
* @return the value generated for an AUTO_INCREMENT column
*/
unsigned long mysac_insert_id(MYSAC *m);
#if 0
mysql_fetch_fields() /*Returns an array of all field structures*/
mysql_fetch_field() /*Returns the type of the next table field*/
mysql_fetch_lengths() /*Returns the lengths of all columns in the current row*/
#endif
/**
* Changes the user and causes the database specified by db to become the
* default (current) database on the connection specified by mysql. In
* subsequent queries, this database is the default for table references that
* do not include an explicit database specifier.
*
* mysql_change_user() fails if the connected user cannot be authenticated or
* doesn't have permission to use the database. In this case, the user and
* database are not changed
*
* This command resets the state as if one had done a new connect. It always
* performs a ROLLBACK of any active transactions, closes and drops all
* temporary tables, and unlocks all locked tables. Session system variables
* are reset to the values of the corresponding global system variables.
* Prepared statements are released and HANDLER variables are closed. Locks
* acquired with GET_LOCK() are released. These effects occur even if the user
* didn't change.
*
* @param mysac Should be the address of an existing MYSQL structure.
*
* @param user The user parameter contains the user's MySQL login ID. If user
* is NULL or the empty string "", the current user is assumed.
*
* @param passwd The passwd parameter contains the password for user. If passwd
* is NULL, only entries in the user table for the user that have a blank
* (empty) password field are checked for a match.
*
* @param db The db parameter may be set to NULL if you don't want to have a
* default database.
*
* @return
* CR_COMMANDS_OUT_OF_SYNC : Commands were executed in an improper order.
* CR_SERVER_GONE_ERROR : The MySQL server has gone away.
* CR_SERVER_LOST : The connection to the server was lost during
* the query.
* CR_UNKNOWN_ERROR : An unknown error occurred.
* ER_UNKNOWN_COM_ERROR : The MySQL server doesn't implement this
* command (probably an old server).
* ER_ACCESS_DENIED_ERROR : The user or password was wrong.
* ER_BAD_DB_ERROR : The database didn't exist.
* ER_DBACCESS_DENIED_ERROR : The user did not have access rights to the
* database.
* ER_WRONG_DB_NAME : The database name was too long.
*/
int mysac_change_user(MYSAC *mysac, const char *user, const char *passwd,
const char *db);
/**
* Returns the default character set name for the current connection.
*
* @param mysac Should be the address of an existing MYSQL structure.
*
* @return The default character set name
*/
//const char *mysac_character_set_name(MYSAC *mysac);
/**
* For the connection specified by mysql, mysql_errno() returns the error code
* for the most recently invoked API function that can succeed or fail. A return
* value of zero means that no error occurred. Client error message numbers are
* listed in the MySQL errmsg.h header file. Server error message numbers are
* listed in mysqld_error.h. Errors also are listed at Appendix B, Errors, Error
* Codes, and Common Problems.
*
* @param mysac Should be the address of an existing MYSQL structure.
*/
unsigned int mysac_errno(MYSAC *mysac);
/**
* For the connection specified by mysql, mysql_error() returns a null-
* terminated string containing the error message for the most recently invoked
* API function that failed. If a function didn't fail, the return value of
* mysql_error() may be the previous error or an empty string to indicate no
* error.
*
* @param mysac Should be the address of an existing MYSQL structure.
*/
const char *mysac_error(MYSAC *mysac);
/**
* For the connection specified by mysql, mysql_error() returns a null-
* terminated string containing the error message for the most recently invoked
* API function that failed. If a function didn't fail, the return value of
* mysql_error() may be the previous error or an empty string to indicate no
* error.
*
* @param mysac Should be the address of an existing MYSQL structure.
*/
const char *mysac_advance_error(MYSAC *mysac);
/*
1607 ulong STDCALL
1608 mysac_escape_string(MYSQL *mysql, char *to,const char *from,
1609 ulong length)
1610 {
1611 if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
1612 return escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
1613 return escape_string_for_mysql(mysql->charset, to, 0, from, length);
1614 }
*/
#if 0
mysql_affected_rows() /*Returns the number of rows changed/deleted/inserted by the last UPDATE, DELETE, or INSERT query*/
mysql_autocommit() /*Toggles autocommit mode on/off*/
mysql_commit() /*Commits the transaction*/
mysql_create_db() /*Creates a database (this function is deprecated; use the SQL statement CREATE DATABASE instead)*/
mysql_data_seek() /*Seeks to an arbitrary row number in a query result set*/
mysql_debug() /*Does a DBUG_PUSH with the given string*/
mysql_drop_db() /*Drops a database (this function is deprecated; use the SQL statement DROP DATABASE instead)*/
mysql_dump_debug_info() /*Makes the server write debug information to the log*/
mysql_escape_string() /*Escapes special characters in a string for use in an SQL statement*/
mysql_fetch_field_direct() /*Returns the type of a table field, given a field number*/
mysql_field_seek() /*Puts the column cursor on a specified column*/
mysql_field_tell() /*Returns the position of the field cursor used for the last mysql_fetch_field()*/
mysql_free_result() /*Frees memory used by a result set*/
mysql_get_character_set_info() /*Return information about default character set*/
mysql_get_client_info() /*Returns client version information as a string*/
mysql_get_client_version() /*Returns client version information as an integer*/
mysql_get_host_info() /*Returns a string describing the connection*/
mysql_get_proto_info() /*Returns the protocol version used by the connection*/
mysql_get_server_info() /*Returns the server version number*/
mysql_get_server_version() /*Returns version number of server as an integer*/
mysql_get_ssl_cipher() /*Return current SSL cipher*/
mysql_hex_string() /*Encode string in hexadecimal format*/
mysql_info() /*Returns information about the most recently executed query*/
mysql_init() /*Gets or initializes a MYSQL structure*/
mysql_kill() /*Kills a given thread*/
mysql_library_end() /*Finalize the MySQL C API library*/
mysql_library_init() /*Initialize the MySQL C API library*/
mysql_list_dbs() /*Returns database names matching a simple regular expression*/
mysql_list_fields() /*Returns field names matching a simple regular expression*/
mysql_list_processes() /*Returns a list of the current server threads*/
mysql_list_tables() /*Returns table names matching a simple regular expression*/
mysql_more_results() /*Checks whether any more results exist*/
mysql_next_result() /*Returns/initiates the next result in multiple-statement executions*/
mysql_num_fields() /*Returns the number of columns in a result set*/
mysql_num_rows() /*Returns the number of rows in a result set*/
mysql_options() /*Sets connect options for mysql_real_connect()*/
mysql_ping() /*Checks whether the connection to the server is working, reconnecting as necessary*/
mysql_query() /*Executes an SQL query specified as a null-terminated string*/
mysql_real_connect() /*Connects to a MySQL server*/
mysql_real_escape_string() /*Escapes special characters in a string for use in an SQL statement, taking into account the current character set of the connection*/
mysql_real_query() /*Executes an SQL query specified as a counted string*/
mysql_refresh() /*Flush or reset tables and caches*/
mysql_reload() /*Tells the server to reload the grant tables*/
mysql_rollback() /*Rolls back the transaction*/
mysql_row_seek() /*Seeks to a row offset in a result set, using value returned from mysql_row_tell()*/
mysql_row_tell() /*Returns the row cursor position*/
mysql_select_db() /*Selects a database*/
mysql_server_end() /*Finalize the MySQL C API library*/
mysql_server_init() /*Initialize the MySQL C API library*/
mysql_set_character_set() /*Set default character set for current connection*/
mysql_set_local_infile_default() /*Set the LOAD DATA LOCAL INFILE handler callbacks to their default values*/
mysql_set_local_infile_handler() /*Install application-specific LOAD DATA LOCAL INFILE handler callbacks*/
mysql_set_server_option() /*Sets an option for the connection (like multi-statements)*/
mysql_sqlstate() /*Returns the SQLSTATE error code for the last error*/
mysql_shutdown() /*Shuts down the database server*/
mysql_ssl_set() /*Prepare to establish SSL connection to server*/
mysql_stat() /*Returns the server status as a string*/
mysql_store_result() /*Retrieves a complete result set to the client*/
mysql_thread_id() /*Returns the current thread ID*/
mysql_use_result() /*Initiates a row-by-row result set retrieval*/
mysql_warning_count() /*Returns the warning count for the previous SQL statement*/
#endif
#endif
|
wantim/mysac
|
mysac.h
|
C
|
lgpl-3.0
| 30,705
|
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.setting;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.sonar.api.config.Configuration;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
public class TestProjectConfigurationLoader implements ProjectConfigurationLoader {
private final Configuration config;
public TestProjectConfigurationLoader(Configuration config) {
this.config = config;
}
@Override
public Map<String, Configuration> loadProjectConfigurations(DbSession dbSession, Set<ComponentDto> projects) {
Map<String, Configuration> map = new HashMap<>();
for (ComponentDto project : projects) {
map.put(project.uuid(), config);
}
return map;
}
}
|
SonarSource/sonarqube
|
server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/TestProjectConfigurationLoader.java
|
Java
|
lgpl-3.0
| 1,576
|
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.scan;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.scanner.fs.InputModuleHierarchy;
@Immutable
public class DefaultInputModuleHierarchy implements InputModuleHierarchy {
private final DefaultInputModule root;
private final Map<DefaultInputModule, DefaultInputModule> parents;
private final Map<DefaultInputModule, List<DefaultInputModule>> children;
public DefaultInputModuleHierarchy(DefaultInputModule root) {
this.children = Collections.emptyMap();
this.parents = Collections.emptyMap();
this.root = root;
}
/**
* Map of child->parent. Neither the Keys or values can be null.
*/
public DefaultInputModuleHierarchy(DefaultInputModule root, Map<DefaultInputModule, DefaultInputModule> parents) {
Map<DefaultInputModule, List<DefaultInputModule>> childrenBuilder = new HashMap<>();
for (Map.Entry<DefaultInputModule, DefaultInputModule> e : parents.entrySet()) {
childrenBuilder.computeIfAbsent(e.getValue(), x -> new ArrayList<>()).add(e.getKey());
}
this.children = Collections.unmodifiableMap(childrenBuilder);
this.parents = Map.copyOf(parents);
this.root = root;
}
@Override
public DefaultInputModule root() {
return root;
}
@Override
public Collection<DefaultInputModule> children(DefaultInputModule component) {
return children.getOrDefault(component, Collections.emptyList());
}
@Override
public DefaultInputModule parent(DefaultInputModule component) {
return parents.get(component);
}
@Override
public boolean isRoot(DefaultInputModule module) {
return root.equals(module);
}
@Override
@CheckForNull
public String relativePath(DefaultInputModule module) {
AbstractProjectOrModule parent = parent(module);
if (parent == null) {
return "";
}
Path parentBaseDir = parent.getBaseDir();
Path moduleBaseDir = module.getBaseDir();
return PathResolver.relativize(parentBaseDir, moduleBaseDir).orElse(null);
}
public String relativePathToRoot(DefaultInputModule module) {
Path rootBaseDir = root.getBaseDir();
Path moduleBaseDir = module.getBaseDir();
return PathResolver.relativize(rootBaseDir, moduleBaseDir).orElse(null);
}
}
|
SonarSource/sonarqube
|
sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/DefaultInputModuleHierarchy.java
|
Java
|
lgpl-3.0
| 3,486
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.Math.Vector import Vector
from UM.Math.Float import Float
class Plane:
"""Plane representation using normal and distance."""
def __init__(self, normal = Vector(), distance = 0.0):
super().__init__()
self._normal = normal
self._distance = distance
@property
def normal(self):
return self._normal
@property
def distance(self):
return self._distance
def intersectsRay(self, ray):
w = ray.origin - (self._normal * self._distance)
nDotR = self._normal.dot(ray.direction)
nDotW = -self._normal.dot(w)
if Float.fuzzyCompare(nDotR, 0.0):
return False
t = nDotW / nDotR
if t < 0:
return False
return t
def __repr__(self):
return "Plane(normal = {0}, distance = {1})".format(self._normal, self._distance)
|
Ultimaker/Uranium
|
UM/Math/Plane.py
|
Python
|
lgpl-3.0
| 975
|
# WaitView
显示等待加载状态的View
[](https://jitpack.io/#imkarl/WaitView)
# Introduce
- 第二张图为`等待加载的状态`
<img src="https://raw.githubusercontent.com/ImKarl/WaitView/master/captures/layout_default.png" width="225" height="385" alt="默认状态"/> . <img src="https://raw.githubusercontent.com/ImKarl/WaitView/master/captures/layout_waitview.png" width="225" height="385" alt="等待加载的状态"/>
# Features
- `简单高效` 一行代码搞定所有控件的状态切换、恢复
- `兼容性强` 支持所有系统控件、自定义控件
- `可定制性` 自定义渲染规则,按需配置
# Usage
**Step 1.** Add the JitPack repository to your build file
```
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
```
**Step 2.** Add the dependency
```
compile 'com.github.ImKarl:WaitView:{latestVersion}'
```
# Sample
- 渲染
```
单个View
WaitViewController.from(mRootView).render();
所有子View
WaitViewController.from(mRootView).renderChilds();
```
- 移除
```
单个View
WaitViewController.from(mRootView).remove();
所有子View
WaitViewController.from(mRootView).removeChilds();
```
- 额外的可配置项
```
WaitViewController controller = WaitViewController.from(mRootView);
颜色:@ColorInt
controller.color(color);
透明度:@IntRange(from=0, to=255)
controller.alpha(alpha);
圆角半径:@Dimension
controller.radius(radius);
绘制区域:如 new Rect(0, 0, view.getWidth(), view.getHeight())
controller.drawRect(rect);
controller.drawRect(width, height);
过滤器:如 new SimpleOnWaitViewFilter()
controller.filter(filter);
```
- 更详细的案例
请查看 [sample](https://github.com/ImKarl/WaitView/blob/master/sample/src/main/java/cn/imkarl/waitview/sample/MainActivity.java)
|
ImKarl/WaitView
|
README.md
|
Markdown
|
lgpl-3.0
| 1,852
|
/**
*
* This file is part of Tulip (http://tulip.labri.fr)
*
* Authors: David Auber and the Tulip development Team
* from LaBRI, University of Bordeaux
*
* Tulip 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.
*
* Tulip 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.
*
*/
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include <ctime>
#include <tulip/ExportModule.h>
#include <tulip/Graph.h>
#include <tulip/GraphProperty.h>
#include <tulip/TlpTools.h>
#include <tulip/MutableContainer.h>
#include <tulip/StringCollection.h>
#include <tulip/TulipRelease.h>
#include <tulip/PropertyTypes.h>
#include <tulip/StableIterator.h>
#define TLP_FILE_VERSION "2.3"
using namespace std;
using namespace tlp;
static string convert(const string &tmp) {
string newStr;
for (unsigned int i = 0; i < tmp.length(); ++i) {
if (tmp[i] == '\"')
newStr += "\\\"";
else if (tmp[i] == '\n')
newStr += "\\n";
else if (tmp[i] == '\\')
newStr += "\\\\";
else
newStr += tmp[i];
}
return newStr;
}
static const char *paramHelp[] = {
// name
"Name of the graph being exported.",
// author
"Authors",
// comments
"Description of the graph."};
namespace tlp {
/**
* This plugin records a Tulip graph structure in a file using the TLP format.
* TLP is the Tulip Software Graph Format.
* See 'Tulip-Software.org->Docs->TLP File Format' for description.
*/
class TLPExport : public ExportModule {
public:
PLUGININFORMATION("TLP Export", "Auber David", "31/07/2001",
"<p>Supported extensions: tlp, tlpz (compressed), tlp.gz "
"(compressed)</p><p>Exports a graph in a file using the TLP format (Tulip "
"Software Graph Format).<br/>See <b>http://tulip.labri.fr->Framework->TLP File "
"Format</b> for more details.</p>",
"1.1", "File")
string fileExtension() const override {
return "tlp";
}
list<string> gzipFileExtensions() const override {
list<string> ext;
ext.push_back("tlp.gz");
ext.push_back("tlpz");
return ext;
}
DataSet controller;
int progress;
TLPExport(tlp::PluginContext *context) : ExportModule(context), progress(0) {
addInParameter<string>("name", paramHelp[0], "");
addInParameter<string>("author", paramHelp[1], "");
addInParameter<string>("text::comments", paramHelp[2], "This file was generated by Tulip.");
}
//=====================================================
~TLPExport() override {}
//=====================================================
std::string icon() const override {
return ":/tulip/gui/icons/logo32x32.png";
}
//====================================================
inline node getNode(node n) {
return node(graph->nodePos(n));
}
//====================================================
inline edge getEdge(edge e) {
return edge(graph->edgePos(e));
}
//=====================================================
void saveGraphElements(ostream &os, Graph *g) {
pluginProgress->setComment("Saving Graph Elements");
pluginProgress->progress(progress, g->numberOfEdges() + g->numberOfNodes());
if (g->getSuperGraph() != g) {
os << "(cluster " << g->getId() << endl;
if (inGuiTestingMode())
g->sortElts();
const std::vector<node> &nodes = g->nodes();
unsigned int nbNodes = nodes.size();
const std::vector<edge> &edges = g->edges();
unsigned int nbEdges = edges.size();
node beginNode, previousNode;
unsigned int progupdate = 1 + (nbNodes + nbEdges) / 100;
if (nbNodes) {
os << "(nodes";
for (unsigned int i = 0; i < nbNodes; ++i) {
if (progress % progupdate == 0)
pluginProgress->progress(progress, nbNodes + nbEdges);
++progress;
node current = getNode(nodes[i]);
if (!beginNode.isValid()) {
beginNode = previousNode = current;
os << " " << beginNode.id;
} else {
if (current.id == previousNode.id + 1) {
previousNode = current;
if (i == nbNodes - 1)
os << ".." << current.id;
} else {
if (previousNode != beginNode) {
os << ".." << previousNode.id;
}
os << " " << current.id;
beginNode = previousNode = current;
}
}
}
os << ")" << endl;
}
edge beginEdge, previousEdge;
if (nbEdges) {
os << "(edges";
for (unsigned int i = 0; i < nbEdges; ++i) {
if (progress % progupdate == 0)
pluginProgress->progress(progress, nbNodes + nbEdges);
++progress;
edge current = getEdge(edges[i]);
if (!beginEdge.isValid()) {
beginEdge = previousEdge = current;
os << " " << beginEdge.id;
} else {
if (current.id == previousEdge.id + 1) {
previousEdge = current;
if (i == nbEdges - 1)
os << ".." << current.id;
} else {
if (previousEdge != beginEdge) {
os << ".." << previousEdge.id;
}
os << " " << current.id;
beginEdge = previousEdge = current;
}
}
}
os << ")" << endl;
}
} else {
unsigned int nbElts = g->numberOfNodes();
os << "(nb_nodes " << nbElts << ")" << endl;
os << ";(nodes <node_id> <node_id> ...)" << endl;
switch (nbElts) {
case 0:
os << "(nodes)" << endl;
break;
case 1:
os << "(nodes 0)" << endl;
break;
case 2:
os << "(nodes 0 1)" << endl;
break;
default:
os << "(nodes 0.." << nbElts - 1 << ")" << endl;
}
nbElts = g->numberOfEdges();
os << "(nb_edges " << nbElts << ")" << endl;
os << ";(edge <edge_id> <source_id> <target_id>)" << endl;
unsigned int progupdate = 1 + nbElts / 100;
const std::vector<edge> &edges = g->edges();
for (unsigned i = 0; i < nbElts; ++i) {
if (progress % progupdate == 0)
pluginProgress->progress(progress, nbElts);
++progress;
edge e = edges[i];
const pair<node, node> &ends = g->ends(e);
os << "(edge " << i << " " << getNode(ends.first).id << " " << getNode(ends.second).id
<< ")";
if (i != nbElts - 1)
os << endl;
}
os << endl;
}
for (Graph *sg : g->getSubGraphs())
saveGraphElements(os, sg);
if (g->getSuperGraph() != g)
os << ")" << endl;
}
//=====================================================
void saveLocalProperties(ostream &os, Graph *g) {
pluginProgress->setComment("Saving Graph Properties");
progress = 0;
Iterator<PropertyInterface *> *itP = nullptr;
if (g->getSuperGraph() == g) {
itP = g->getObjectProperties();
} else {
itP = g->getLocalObjectProperties();
}
int nonDefaultvaluatedElementCount = 1;
for (PropertyInterface *prop : itP) {
nonDefaultvaluatedElementCount += prop->numberOfNonDefaultValuatedNodes();
nonDefaultvaluatedElementCount += prop->numberOfNonDefaultValuatedEdges();
}
if (g->getSuperGraph() == g) {
itP = g->getObjectProperties();
} else {
itP = g->getLocalObjectProperties();
}
for (PropertyInterface *prop : itP) {
stringstream tmp;
tmp << "Saving Property [" << prop->getName() << "]";
pluginProgress->setComment(tmp.str());
if (g->getSuperGraph() == g) {
os << "(property "
<< " 0 " << prop->getTypename() << " ";
} else {
os << "(property "
<< " " << g->getId() << " " << prop->getTypename() << " ";
}
os << "\"" << convert(prop->getName()) << "\"" << endl;
string nDefault = prop->getNodeDefaultStringValue();
string eDefault = prop->getEdgeDefaultStringValue();
bool isPathViewProp =
(prop->getName() == string("viewFont") || prop->getName() == string("viewTexture"));
// replace real path with symbolic one using TulipBitmapDir
if (isPathViewProp && !TulipBitmapDir.empty()) {
size_t pos = nDefault.find(TulipBitmapDir);
if (pos != string::npos)
nDefault.replace(pos, TulipBitmapDir.size(), "TulipBitmapDir/");
pos = eDefault.find(TulipBitmapDir);
if (pos != string::npos)
eDefault.replace(pos, TulipBitmapDir.size(), "TulipBitmapDir/");
}
os << "(default \"" << convert(nDefault) << "\" \"" << convert(eDefault) << "\")" << endl;
Iterator<node> *itN = prop->getNonDefaultValuatedNodes(g);
if (inGuiTestingMode())
// sort nodes to ensure a predictable ordering of the ouput
itN = new StableIterator<node>(itN, 0, true, true);
while (itN->hasNext()) {
auto itn = itN->next();
if (progress % (1 + nonDefaultvaluatedElementCount / 100) == 0)
pluginProgress->progress(progress, nonDefaultvaluatedElementCount);
++progress;
string tmp = prop->getNodeStringValue(itn);
// replace real path with symbolic one using TulipBitmapDir
if (isPathViewProp && !TulipBitmapDir.empty()) {
size_t pos = tmp.find(TulipBitmapDir);
if (pos != string::npos)
tmp.replace(pos, TulipBitmapDir.size(), "TulipBitmapDir/");
} else if (g->getId() != 0 && // if it is not the real root graph
prop->getTypename() == GraphProperty::propertyTypename) {
unsigned int id = strtoul(tmp.c_str(), nullptr, 10);
// we must check if the pointed subgraph
// is a descendant of the currently export graph
if (!graph->getDescendantGraph(id))
continue;
}
os << "(node " << getNode(itn).id << " \"" << convert(tmp) << "\")" << endl;
}
delete itN;
Iterator<edge> *itE = prop->getNonDefaultValuatedEdges(g);
if (inGuiTestingMode())
// sort edges to ensure a predictable ordering of the ouput
itE = new StableIterator<edge>(itE, 0, true, true);
if (prop->getTypename() == GraphProperty::propertyTypename) {
while (itE->hasNext()) {
auto ite = itE->next();
if (progress % (1 + nonDefaultvaluatedElementCount / 100) == 0)
pluginProgress->progress(progress, nonDefaultvaluatedElementCount);
++progress;
// for GraphProperty we must ensure the reindexing
// of embedded edges
const set<edge> &edges = static_cast<GraphProperty *>(prop)->getEdgeValue(ite);
set<edge> rEdges;
set<edge>::const_iterator its;
for (its = edges.begin(); its != edges.end(); ++its) {
rEdges.insert(getEdge(*its));
}
// finally save the vector
os << "(edge " << getEdge(ite).id << " \"";
EdgeSetType::write(os, rEdges);
os << "\")" << endl;
}
} else {
while (itE->hasNext()) {
auto ite = itE->next();
if (progress % (1 + nonDefaultvaluatedElementCount / 100) == 0)
pluginProgress->progress(progress, nonDefaultvaluatedElementCount);
++progress;
// replace real path with symbolic one using TulipBitmapDir
string tmp = prop->getEdgeStringValue(ite);
if (isPathViewProp && !TulipBitmapDir.empty()) {
size_t pos = tmp.find(TulipBitmapDir);
if (pos != string::npos)
tmp.replace(pos, TulipBitmapDir.size(), "TulipBitmapDir/");
}
os << "(edge " << getEdge(ite).id << " \"" << convert(tmp) << "\")" << endl;
}
}
delete itE;
os << ")" << endl;
}
}
//=====================================================
void saveProperties(ostream &os, Graph *g) {
saveLocalProperties(os, g);
for (Graph *sg : g->getSubGraphs())
saveProperties(os, sg);
}
//=====================================================
void saveAttributes(ostream &os, Graph *g) {
const DataSet &attributes = g->getAttributes();
if (!attributes.empty()) {
// If nodes and edges are stored as graph attributes
// we need to update their id before serializing them
// as nodes and edges have been reindexed
for (const pair<string, DataType *> &attribute : attributes.getValues()) {
if (attribute.second->getTypeName() == string(typeid(node).name())) {
node *n = static_cast<node *>(attribute.second->value);
n->id = getNode(*n).id;
} else if (attribute.second->getTypeName() == string(typeid(edge).name())) {
edge *e = static_cast<edge *>(attribute.second->value);
e->id = getEdge(*e).id;
} else if (attribute.second->getTypeName() == string(typeid(vector<node>).name())) {
vector<node> *vn = static_cast<vector<node> *>(attribute.second->value);
for (size_t i = 0; i < vn->size(); ++i) {
(*vn)[i].id = getNode((*vn)[i]).id;
}
} else if (attribute.second->getTypeName() == string(typeid(vector<edge>).name())) {
vector<edge> *ve = static_cast<vector<edge> *>(attribute.second->value);
for (size_t i = 0; i < ve->size(); ++i) {
(*ve)[i].id = getEdge((*ve)[i]).id;
}
}
}
if (g->getSuperGraph() == g) {
os << "(graph_attributes 0 ";
} else {
os << "(graph_attributes " << g->getId() << " ";
}
DataSet::write(os, attributes);
os << ")" << endl;
}
// save subgraph attributes
for (Graph *sg : g->getSubGraphs())
saveAttributes(os, sg);
}
//=====================================================
void saveController(ostream &os, DataSet &data) {
os << "(controller ";
DataSet::write(os, data);
os << ")" << endl;
}
bool exportGraph(ostream &os) override {
// change graph parent in hierarchy temporarily to itself as
// it will be the new root of the exported hierarchy
Graph *superGraph = graph->getSuperGraph();
graph->setSuperGraph(graph);
string format(TLP_FILE_VERSION);
string name;
string author;
string comments = "This file was generated by Tulip.";
if (dataSet != nullptr) {
dataSet->get("name", name);
dataSet->get("author", author);
dataSet->get("text::comments", comments);
}
if (name.length() > 0)
graph->setAttribute("name", name);
// get ostime
time_t ostime = time(nullptr);
// get local time
struct tm *currTime = localtime(&ostime);
// format date
char currDate[32];
strftime(currDate, 32, "%m-%d-%Y", currTime);
// output tlp format version
os << "(tlp \"" << format.c_str() << '"' << endl;
// current date
os << "(date \"" << currDate << "\")" << endl;
// author
if (author.length() > 0)
os << "(author \"" << author << "\")" << endl;
// comments
os << "(comments \"" << comments << "\")" << endl;
saveGraphElements(os, graph);
saveProperties(os, graph);
saveAttributes(os, graph);
// Save views
if (dataSet != nullptr && dataSet->get<DataSet>("controller", controller))
saveController(os, controller);
os << ')' << endl; // end of (tlp ...
// restore original parent in hierarchy
graph->setSuperGraph(superGraph);
return true;
}
};
PLUGIN(TLPExport)
} // namespace tlp
|
tulip5/tulip
|
library/tulip-core/src/TLPExport.cpp
|
C++
|
lgpl-3.0
| 16,016
|
#pragma once
#ifndef SAMPLE2_H
#define SAMPLE2_H
#include "WireApplication.h"
namespace Wire
{
class Sample2 : public WIREAPPLICATION
{
WIRE_DECLARE_INITIALIZE;
typedef WIREAPPLICATION Parent;
public:
Sample2();
virtual Bool OnInitialize();
virtual void OnIdle();
private:
Node* CreateHelicopter();
RenderObject* CreateCube(ColorRGBA top, ColorRGBA bottom);
CameraPtr mspCamera;
Culler mCuller;
Float mAngle;
Double mLastTime;
NodePtr mspRoot;
NodePtr mspTopRotor;
NodePtr mspRearRotor;
};
WIRE_REGISTER_INITIALIZE(Sample2);
}
#endif
|
rrath/Wire3D
|
Samples/Sample2/src/Sample2.h
|
C
|
lgpl-3.0
| 561
|
package org.areasy.common.parser.excel.biff;
/*
* Copyright (c) 2007-2020 AREasy Runtime
*
* This library, AREasy Runtime and API for BMC Remedy AR System, is free software ("Licensed 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 2.1 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;
* including but not limited to, the implied warranty of MERCHANTABILITY, NONINFRINGEMENT,
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
import org.areasy.common.logger.Logger;
import org.areasy.common.logger.LoggerFactory;
import org.areasy.common.parser.excel.CellReferenceHelper;
import org.areasy.common.parser.excel.Range;
import org.areasy.common.parser.excel.biff.drawing.ComboBox;
import org.areasy.common.parser.excel.biff.drawing.Comment;
import org.areasy.common.parser.excel.common.Assert;
import org.areasy.common.parser.excel.write.biff.CellValue;
import java.util.Collection;
/**
* Container for any additional cell features
*/
public class BaseCellFeatures
{
/**
* The logger
*/
public static Logger logger = LoggerFactory.getLog(BaseCellFeatures.class);
/**
* The comment
*/
private String comment;
/**
* The comment width in cells
*/
private double commentWidth;
/**
* The comment height in cells
*/
private double commentHeight;
/**
* A handle to the drawing object
*/
private Comment commentDrawing;
/**
* A handle to the combo box object
*/
private ComboBox comboBox;
/**
* The data validation settings
*/
private DataValiditySettingsRecord validationSettings;
/**
* The DV Parser used to contain the validation details
*/
private DVParser dvParser;
/**
* Indicates whether a drop down is required
*/
private boolean dropDown;
/**
* Indicates whether this cell features has data validation
*/
private boolean dataValidation;
/**
* The cell to which this is attached, and which may need to be notified
*/
private CellValue writableCell;
// Constants
private final static double defaultCommentWidth = 3;
private final static double defaultCommentHeight = 4;
// Validation conditions
protected static class ValidationCondition
{
private DVParser.Condition condition;
private static ValidationCondition[] types = new ValidationCondition[0];
ValidationCondition(DVParser.Condition c)
{
condition = c;
ValidationCondition[] oldtypes = types;
types = new ValidationCondition[oldtypes.length + 1];
System.arraycopy(oldtypes, 0, types, 0, oldtypes.length);
types[oldtypes.length] = this;
}
public DVParser.Condition getCondition()
{
return condition;
}
}
public static final ValidationCondition BETWEEN =
new ValidationCondition(DVParser.BETWEEN);
public static final ValidationCondition NOT_BETWEEN =
new ValidationCondition(DVParser.NOT_BETWEEN);
public static final ValidationCondition EQUAL =
new ValidationCondition(DVParser.EQUAL);
public static final ValidationCondition NOT_EQUAL =
new ValidationCondition(DVParser.NOT_EQUAL);
public static final ValidationCondition GREATER_THAN =
new ValidationCondition(DVParser.GREATER_THAN);
public static final ValidationCondition LESS_THAN =
new ValidationCondition(DVParser.LESS_THAN);
public static final ValidationCondition GREATER_EQUAL =
new ValidationCondition(DVParser.GREATER_EQUAL);
public static final ValidationCondition LESS_EQUAL =
new ValidationCondition(DVParser.LESS_EQUAL);
/**
* Constructor
*/
protected BaseCellFeatures()
{
}
/**
* Copy constructor
*
* @param cf cell to copy
*/
public BaseCellFeatures(BaseCellFeatures cf)
{
// The comment stuff
comment = cf.comment;
commentWidth = cf.commentWidth;
commentHeight = cf.commentHeight;
// The data validation stuff.
dropDown = cf.dropDown;
dataValidation = cf.dataValidation;
validationSettings = cf.validationSettings; // ?
if (cf.dvParser != null)
{
dvParser = new DVParser(cf.dvParser);
}
}
/**
* Accessor for the cell comment
*/
protected String getComment()
{
return comment;
}
/**
* Accessor for the comment width
*/
public double getCommentWidth()
{
return commentWidth;
}
/**
* Accessor for the comment height
*/
public double getCommentHeight()
{
return commentHeight;
}
/**
* Called by the cell when the features are added
*
* @param wc the writable cell
*/
public final void setWritableCell(CellValue wc)
{
writableCell = wc;
}
/**
* Internal method to set the cell comment. Used when reading
*/
public void setReadComment(String s, double w, double h)
{
comment = s;
commentWidth = w;
commentHeight = h;
}
/**
* Internal method to set the data validation. Used when reading
*/
public void setValidationSettings(DataValiditySettingsRecord dvsr)
{
Assert.verify(dvsr != null);
validationSettings = dvsr;
dataValidation = true;
}
/**
* Sets the cell comment
*
* @param s the comment
*/
public void setComment(String s)
{
setComment(s, defaultCommentWidth, defaultCommentHeight);
}
/**
* Sets the cell comment
*
* @param s the comment
* @param height the height of the comment box in cells
* @param width the width of the comment box in cells
*/
public void setComment(String s, double width, double height)
{
comment = s;
commentWidth = width;
commentHeight = height;
if (commentDrawing != null)
{
commentDrawing.setCommentText(s);
commentDrawing.setWidth(width);
commentDrawing.setWidth(height);
// commentDrawing is set up when trying to modify a copied cell
}
}
/**
* Removes the cell comment, if present
*/
public void removeComment()
{
// Set the comment string to be empty
comment = null;
// Remove the drawing from the drawing group
if (commentDrawing != null)
{
// do not call DrawingGroup.remove() because comments are not present
// on the Workbook DrawingGroup record
writableCell.removeComment(commentDrawing);
commentDrawing = null;
}
}
/**
* Public function which removes any data validation, if present
*/
public void removeDataValidation()
{
if (!dataValidation)
{
return;
}
// If the data validation is shared, then generate a warning
DVParser dvp = getDVParser();
if (dvp.extendedCellsValidation())
{
logger.warn("Cannot remove data validation from " +
CellReferenceHelper.getCellReference(writableCell) +
" as it is part of the shared reference " +
CellReferenceHelper.getCellReference(dvp.getFirstColumn(),
dvp.getFirstRow()) +
"-" +
CellReferenceHelper.getCellReference(dvp.getLastColumn(),
dvp.getLastRow()));
return;
}
// Remove the validation from the WritableSheet object if present
writableCell.removeDataValidation();
clearValidationSettings();
}
/**
* Internal function which removes any data validation, including
* shared ones, if present. This is called from DefaultWritableSheet
* in response to a call to removeDataValidation
*/
public void removeSharedDataValidation()
{
if (!dataValidation)
{
return;
}
// Remove the validation from the WritableSheet object if present
writableCell.removeDataValidation();
clearValidationSettings();
}
/**
* Sets the comment drawing object
*/
public final void setCommentDrawing(Comment c)
{
commentDrawing = c;
}
/**
* Accessor for the comment drawing
*/
public final Comment getCommentDrawing()
{
return commentDrawing;
}
/**
* Gets the data validation list as a formula. Used only when reading
*
* @return the validation formula as a list
*/
public String getDataValidationList()
{
if (validationSettings == null)
{
return null;
}
return validationSettings.getValidationFormula();
}
/**
* The list of items to validate for this cell. For each object in the
* collection, the toString() method will be called and the data entered
* will be validated against that string
*
* @param c the list of valid values
*/
public void setDataValidationList(Collection c)
{
if (dataValidation && getDVParser().extendedCellsValidation())
{
logger.warn("Cannot set data validation on " +
CellReferenceHelper.getCellReference(writableCell) +
" as it is part of a shared data validation");
return;
}
clearValidationSettings();
dvParser = new DVParser(c);
dropDown = true;
dataValidation = true;
}
/**
* The list of items to validate for this cell in the form of a cell range.
*/
public void setDataValidationRange(int col1, int r1, int col2, int r2)
{
if (dataValidation && getDVParser().extendedCellsValidation())
{
logger.warn("Cannot set data validation on " +
CellReferenceHelper.getCellReference(writableCell) +
" as it is part of a shared data validation");
return;
}
clearValidationSettings();
dvParser = new DVParser(col1, r1, col2, r2);
dropDown = true;
dataValidation = true;
}
/**
* Sets the data validation based upon a named range
*/
public void setDataValidationRange(String namedRange)
{
if (dataValidation && getDVParser().extendedCellsValidation())
{
logger.warn("Cannot set data validation on " +
CellReferenceHelper.getCellReference(writableCell) +
" as it is part of a shared data validation");
return;
}
clearValidationSettings();
dvParser = new DVParser(namedRange);
dropDown = true;
dataValidation = true;
}
/**
* Sets the data validation based upon a numerical condition
*/
public void setNumberValidation(double val, ValidationCondition c)
{
if (dataValidation && getDVParser().extendedCellsValidation())
{
logger.warn("Cannot set data validation on " +
CellReferenceHelper.getCellReference(writableCell) +
" as it is part of a shared data validation");
return;
}
clearValidationSettings();
dvParser = new DVParser(val, Double.NaN, c.getCondition());
dropDown = false;
dataValidation = true;
}
public void setNumberValidation(double val1, double val2,
ValidationCondition c)
{
if (dataValidation && getDVParser().extendedCellsValidation())
{
logger.warn("Cannot set data validation on " +
org.areasy.common.parser.excel.CellReferenceHelper.getCellReference(writableCell) +
" as it is part of a shared data validation");
return;
}
clearValidationSettings();
dvParser = new DVParser(val1, val2, c.getCondition());
dropDown = false;
dataValidation = true;
}
/**
* Accessor for the data validation
*
* @return TRUE if this has a data validation associated with it,
* FALSE otherwise
*/
public boolean hasDataValidation()
{
return dataValidation;
}
/**
* Clears out any existing validation settings
*/
private void clearValidationSettings()
{
validationSettings = null;
dvParser = null;
dropDown = false;
comboBox = null;
dataValidation = false;
}
/**
* Accessor for whether a drop down is required
*
* @return TRUE if this requires a drop down, FALSE otherwise
*/
public boolean hasDropDown()
{
return dropDown;
}
/**
* Sets the combo box drawing object for list validations
*
* @param cb the combo box
*/
public void setComboBox(ComboBox cb)
{
comboBox = cb;
}
/**
* Gets the dv parser
*/
public DVParser getDVParser()
{
// straightforward - this was created as a writable cell
if (dvParser != null)
{
return dvParser;
}
// this was copied from a readable cell, and then copied again
if (validationSettings != null)
{
dvParser = new DVParser(validationSettings.getDVParser());
return dvParser;
}
return null; // keep the compiler happy
}
/**
* Use the same data validation logic as the specified cell features
*
* @param source the data validation to reuse
*/
public void shareDataValidation(BaseCellFeatures source)
{
if (dataValidation)
{
logger.warn("Attempting to share a data validation on cell " +
CellReferenceHelper.getCellReference(writableCell) +
" which already has a data validation");
return;
}
clearValidationSettings();
dvParser = source.getDVParser();
validationSettings = null;
dataValidation = true;
dropDown = source.dropDown;
comboBox = source.comboBox;
}
/**
* Gets the range of cells to which the data validation applies. If the
* validation applies to just this cell, this will be reflected in the
* returned range
*
* @return the range to which the same validation extends, or NULL if this
* cell doesn't have a validation
*/
public Range getSharedDataValidationRange()
{
if (!dataValidation)
{
return null;
}
DVParser dvp = getDVParser();
return new DefaultSheetRange(writableCell.getSheet(),
dvp.getFirstColumn(),
dvp.getFirstRow(),
dvp.getLastColumn(),
dvp.getLastRow());
}
}
|
stefandmn/AREasy
|
src/java/org/areasy/common/parser/excel/biff/BaseCellFeatures.java
|
Java
|
lgpl-3.0
| 13,067
|
#include "BaconBox/Display/Color.h"
#include <cmath>
#include <map>
#include <vector>
#include <utility>
#include "BaconBox/Helper/Serialization/Value.h"
#include "BaconBox/Helper/Serialization/DefaultSerializer.h"
#include "BaconBox/Helper/Serialization/Serializer.h"
#include "BaconBox/Helper/StringHelper.h"
#include "BaconBox/Helper/Serialization/Object.h"
namespace BaconBox {
const Color Color::BLACK(0, 0, 0);
const Color Color::SILVER(192, 192, 192);
const Color Color::GRAY(128, 128, 128);
const Color Color::WHITE(255, 255, 255);
const Color Color::MAROON(128, 0, 0);
const Color Color::RED(255, 0, 0);
const Color Color::PURPLE(128, 0, 128);
const Color Color::FUCHSIA(255, 0, 255);
const Color Color::GREEN(0, 128, 0);
const Color Color::LIME(0, 255, 0);
const Color Color::OLIVE(128, 128, 0);
const Color Color::YELLOW(255, 255, 0);
const Color Color::NAVY(0, 0, 128);
const Color Color::BLUE(0, 0, 255);
const Color Color::TEAL(0, 128, 128);
const Color Color::AQUA(0, 255, 255);
const Color Color::TRANSPARENT(0, 0, 0, 0);
uint8_t Color::getWithinRange(int32_t component) {
return static_cast<uint8_t>((component < 0) ? (0) : ((component > MAX_COMPONENT_VALUE_32) ? (MAX_COMPONENT_VALUE) : (component)));
}
Color::Color() {
operator=(WHITE);
}
Color::Color(int32_t red, int32_t green, int32_t blue, int32_t alpha) {
setRGBA(red, green, blue, alpha);
}
Color::Color(uint32_t rgba) {
setRGBA(rgba);
}
Color::Color(const std::string &colorString) {
operator=(WHITE);
setRGBA(colorString);
}
Color::Color(const Color &src) {
if (this != &src) {
setRGBA(src.getRed(), src.getGreen(), src.getBlue(), src.getAlpha());
}
}
Color &Color::operator=(const Color &src) {
if (this != &src) {
setRGBA(src.getRed(), src.getGreen(), src.getBlue(), src.getAlpha());
}
return *this;
}
bool Color::operator==(const Color &other) {
return colors[R] == other.colors[R] && colors[G] == other.colors[G] &&
colors[B] == other.colors[B] && colors[A] == other.colors[A];
}
bool Color::operator!=(const Color &other) {
return !operator==(other);
}
Color::operator uint32_t() const {
unsigned int result = static_cast<uint32_t>(colors[R]) << 24;
result |= static_cast<uint32_t>(colors[G]) << 16;
result |= static_cast<uint32_t>(colors[B]) << 8;
result |= static_cast<uint32_t>(colors[A]);
return result;
}
uint8_t Color::getRed() const {
return colors[R];
}
uint8_t Color::getGreen() const {
return colors[G];
}
uint8_t Color::getBlue() const {
return colors[B];
}
uint8_t Color::getAlpha() const {
return colors[A];
}
void Color::setRed(int32_t red) {
colors[R] = getWithinRange(red);
}
void Color::setGreen(int32_t green) {
colors[G] = getWithinRange(green);
}
void Color::setBlue(int32_t blue) {
colors[B] = getWithinRange(blue);
}
void Color::setAlpha(int32_t alpha) {
colors[A] = getWithinRange(alpha);
}
void Color::setRGB(int32_t red, int32_t green, int32_t blue) {
setRed(red);
setGreen(green);
setBlue(blue);
}
void Color::setRGB(uint32_t rgb) {
setRGB(static_cast<uint8_t>((rgb & 0xff0000) >> 16),
static_cast<uint8_t>((rgb & 0x00ff00) >> 8),
static_cast<uint8_t>(rgb & 0x0000ff));
}
void Color::setRGBA(int32_t red, int32_t green, int32_t blue, int32_t alpha) {
setRGB(red, green, blue);
setAlpha(alpha);
}
void Color::setRGBA(uint32_t rgba) {
setRGBA(static_cast<uint8_t>((rgba & 0xff000000) >> 24),
static_cast<uint8_t>((rgba & 0x00ff0000) >> 16),
static_cast<uint8_t>((rgba & 0x0000ff00) >> 8),
static_cast<uint8_t>(rgba & 0x000000ff));
}
std::map<std::string, Color> createCssColorMap();
void Color::setRGBA(const std::string &colorString) {
static const std::map<std::string, Color> cssColorMap = createCssColorMap();
// We remove the whitespaces.
std::string tmp(StringHelper::toLower(colorString));
StringHelper::trim(tmp);
// We make sure the string is not empty.
if (!tmp.empty()) {
// If it's in hexadecimal.
if (tmp[0] == '#') {
// We remove the '#'.
tmp.erase(0, 1);
// We make sure it has a valid size.
if (tmp.size() == 3) {
// We convert it to the 6 char format.
tmp.reserve(8);
tmp.resize(6, tmp[2]);
tmp[3] = tmp[2] = tmp[1];
tmp[1] = tmp[0];
}
if (tmp.size() == 6) {
// We append the alpha value.
tmp.append("ff");
// We convert it to an int.
uint32_t rgba;
if (StringHelper::fromString(tmp, rgba, std::hex)) {
setRGBA(rgba);
}
}
} else if (tmp[0] == 'r') {
// It's either for the color "red", rgb or rgba.
if (tmp == std::string("red")) {
operator=(RED);
} else {
// We check if the color is in rgba format.
bool rgba = tmp.size() >= 13 &&
(tmp.substr(0, 5) == std::string("rgba(")) &&
*tmp.rbegin() == ')';
if (rgba) {
tmp.erase(0, 5);
tmp.erase(tmp.size() - 1, 1);
} else if (tmp.size() >= 10 &&
tmp.substr(0, 4) == std::string("rgb(") &&
*tmp.rbegin() == ')') {
tmp.erase(0, 4);
tmp.erase(tmp.size() - 1, 1);
}
std::vector<std::string> componentList;
componentList.reserve(4);
StringHelper::tokenize(tmp, componentList, ",");
if ((rgba && componentList.size() == 4) ||
(!rgba && componentList.size() == 3)) {
// We re-use the rgba variable.
rgba = true;
// We check if the rgb components use percentages.
int r, g, b, a;
// We make sure the rgb components are not empty.
if (!componentList[0].empty() &&
!componentList[1].empty() &&
!componentList[2].empty()) {
if (*componentList[0].rbegin() == '%' &&
*componentList[1].rbegin() == '%' &&
*componentList[2].rbegin() == '%') {
// We remove the percentage signs.
componentList[0].erase(componentList[0].size() - 1, 1);
componentList[1].erase(componentList[1].size() - 1, 1);
componentList[2].erase(componentList[2].size() - 1, 1);
// We convert the percentages to floats.
float fr, fg, fb;
if (StringHelper::fromString(componentList[0], fr) &&
StringHelper::fromString(componentList[1], fg) &&
StringHelper::fromString(componentList[2], fb)) {
r = static_cast<int>(fr * 2.55f);
g = static_cast<int>(fg * 2.55f);
b = static_cast<int>(fb * 2.55f);
} else {
rgba = false;
}
} else if (*componentList[0].rbegin() != '%' &&
*componentList[1].rbegin() != '%' &&
*componentList[2].rbegin() != '%') {
// We read the rgb values.
if (!(StringHelper::fromString(componentList[0], r) &&
StringHelper::fromString(componentList[1], g) &&
StringHelper::fromString(componentList[2], b))) {
rgba = false;
}
} else {
rgba = false;
}
} else {
rgba = false;
}
// If the rgb components were valid.
if (rgba) {
if (componentList.size() == 4) {
// We make sure the alpha value is not empty.
if (!componentList[3].empty()) {
// We check if the alpha value is in percentage.
if (*componentList[3].rbegin() == '%') {
// We remove the percentage sign.
componentList[3].erase(componentList[3].size() - 1, 1);
// We convert the percentage.
float fa;
if (StringHelper::fromString(componentList[3], fa)) {
a = static_cast<int>(fa * 2.55f);
} else {
rgba = false;
}
} else {
float fa;
if (StringHelper::fromString(componentList[3], fa)) {
a = static_cast<int>(fa * 255.0f);
} else {
rgba = false;
}
}
} else {
rgba = false;
}
} else {
a = 255;
}
}
if (rgba) {
setRGBA(r, g, b, a);
}
}
}
} else {
// It's either for a color keyword or invalid.
std::map<std::string, Color>::const_iterator colorFound = cssColorMap.find(tmp);
if (colorFound != cssColorMap.end()) {
operator=(colorFound->second);
}
}
}
}
std::map<std::string, Color> createCssColorMap() {
std::map<std::string, Color> result;
result.insert(std::make_pair(std::string("black"), Color::BLACK));
result.insert(std::make_pair(std::string("silver"), Color::SILVER));
result.insert(std::make_pair(std::string("gray"), Color::GRAY));
result.insert(std::make_pair(std::string("white"), Color::WHITE));
result.insert(std::make_pair(std::string("maroon"), Color::MAROON));
result.insert(std::make_pair(std::string("purple"), Color::PURPLE));
result.insert(std::make_pair(std::string("fuchsia"), Color::FUCHSIA));
result.insert(std::make_pair(std::string("green"), Color::GREEN));
result.insert(std::make_pair(std::string("lime"), Color::LIME));
result.insert(std::make_pair(std::string("olive"), Color::OLIVE));
result.insert(std::make_pair(std::string("yellow"), Color::YELLOW));
result.insert(std::make_pair(std::string("navy"), Color::NAVY));
result.insert(std::make_pair(std::string("blue"), Color::BLUE));
result.insert(std::make_pair(std::string("teal"), Color::TEAL));
result.insert(std::make_pair(std::string("aqua"), Color::AQUA));
result.insert(std::make_pair(std::string("transparent"), Color::TRANSPARENT));
return result;
}
const uint8_t *Color::getComponents() const {
return colors;
}
Color::HSV Color::getHSV() const {
Color::HSV thisColor;
// Sets the default saturation
thisColor.S = 0;
// Sets the hue
thisColor.H = this->getHue();
// Colors as percentage
float red = static_cast<float>(colors[R]) / 255.0f;
float green = static_cast<float>(colors[G]) / 255.0f;
float blue = static_cast<float>(colors[B]) / 255.0f;
// Find the max color
float maxColor = std::max(red, std::max(green, blue));
float minColor = std::min(red, std::min(green, blue));
float delta = maxColor - minColor;
// Sets the found value
thisColor.V = maxColor;
// When there is a saturation
if (maxColor != 0) {
// Sets the right saturation
thisColor.S = delta / maxColor;
}
return thisColor;
}
void Color::setHSV(Color::HSV hsvColor) {
// http://www.cs.rit.edu/~ncs/color/t_convert.html#RGB to HSV & HSV to RGB
int i;
if (hsvColor.V > 1.0f) {
hsvColor.V = 1.0f;
} else if (hsvColor.V < 0.0f) {
hsvColor.V = 0.0f;
}
if (hsvColor.S > 1.0f) {
hsvColor.S = 1.0f;
} else if (hsvColor.S < 0.0f) {
hsvColor.S = 0.0f;
}
float hueRemainder;
float p;
float q;
float t;
if (hsvColor.S == 0) {
// achromatic (grey)
colors[R] = static_cast<float>(hsvColor.V * 255.0f);
colors[G] = static_cast<float>(hsvColor.V * 255.0f);
colors[B] = static_cast<float>(hsvColor.V * 255.0f);
return;
}
hsvColor.H /= 60; // Gives the sector of the HSV hexagon
i = floor(hsvColor.H);
hueRemainder = hsvColor.H - i;
p = hsvColor.V * (1 - hsvColor.S);
q = hsvColor.V * (1 - hsvColor.S * hueRemainder);
t = hsvColor.V * (1 - hsvColor.S * (1 - hueRemainder));
switch (i) {
case 0:
this->colors[R] = static_cast<float>((hsvColor.V) * 255.0f);
this->colors[G] = static_cast<float>((t) * 255.0f);
this->colors[B] = static_cast<float>((p) * 255.0f);
break;
case 1:
this->colors[R] = static_cast<float>((q) * 255.0f);
this->colors[G] = static_cast<float>((hsvColor.V) * 255.0f);
this->colors[B] = static_cast<float>((p) * 255.0f);
break;
case 2:
this->colors[R] = static_cast<float>((p) * 255.0f);
this->colors[G] = static_cast<float>((hsvColor.V) * 255.0f);
this->colors[B] = static_cast<float>((t) * 255.0f);
break;
case 3:
this->colors[R] = static_cast<float>((p) * 255.0f);
this->colors[G] = static_cast<float>((q) * 255.0f);
this->colors[B] = static_cast<float>((hsvColor.V) * 255.0f);
break;
case 4:
this->colors[R] = static_cast<float>((t) * 255.0f);
this->colors[G] = static_cast<float>((p) * 255.0f);
this->colors[B] = static_cast<float>((hsvColor.V) * 255.0f);
break;
default: // case 5:
this->colors[R] = static_cast<float>((hsvColor.V) * 255.0f);
this->colors[G] = static_cast<float>((p) * 255.0f);
this->colors[B] = static_cast<float>((q) * 255.0f);
break;
}
}
float Color::getHue() const {
// If this color is a shade of pure gray, black or white.
if (colors[R] == colors[B] && colors[R] == colors[G]) {
// Hue is returned as 0, as usual with almost every implementation.
// In reality, Hue is undefined, though.
return 0;
}
// Find dominant color
float maxColor = static_cast<float>(std::max(colors[R], std::max(colors[G], colors[B])));
float minColor = static_cast<float>(std::min(colors[R], std::min(colors[G], colors[B])));
float hue;
// Red is max
if (maxColor == colors[R]) {
hue = static_cast<float>(colors[G] - colors[B]) / (maxColor - minColor);
}
// Green is max
else if (maxColor == colors[G]) {
hue = static_cast<float>(colors[B] - colors[R]) / (maxColor - minColor) + 2.0f;
}
// Blue is max
else {
hue = static_cast<float>(colors[R] - colors[G]) / (maxColor - minColor) + 4.0f;
}
// Gets it up to 360 degrees.
hue *= 60.0f;
// Shifts it back to positive if negative.
if (hue < 0) {
hue += 360.0f;
}
return hue;
}
float Color::getSaturation() const {
return getHSV().S;
}
float Color::getValue() const {
return getHSV().V;
}
void Color::setHue(float hue) {
Color::HSV color = getHSV();
color.H = hue;
setHSV(color);
}
void Color::setSaturation(float saturation) {
Color::HSV color = getHSV();
color.S = saturation;
setHSV(color);
}
void Color::setValue(float value) {
Color::HSV color = getHSV();
color.V = value;
setHSV(color);
}
void Color::serialize(Value &node, bool setName) const {
if (setName) {
node.setName("Color");
}
// We set the value's attributes.
node["red"].setInt(getRed());
node["red"].setAttribute(true);
node["green"].setInt(getGreen());
node["green"].setAttribute(true);
node["blue"].setInt(getBlue());
node["blue"].setAttribute(true);
node["alpha"].setInt(getAlpha());
node["alpha"].setAttribute(true);
}
bool Color::deserialize(const Value &node) {
bool result = true;
Object::const_iterator itRed = node.getObject().find("red");
Object::const_iterator itGreen = node.getObject().find("green");
Object::const_iterator itBlue = node.getObject().find("blue");
Object::const_iterator itAlpha = node.getObject().find("alpha");
if (itRed != node.getObject().end() &&
itGreen != node.getObject().end() &&
itBlue != node.getObject().end() &&
itAlpha != node.getObject().end() &&
itRed->second.isNumeric() &&
itGreen->second.isNumeric() &&
itBlue->second.isNumeric() &&
itAlpha->second.isNumeric()) {
setRGBA(itRed->second.getInt(), itGreen->second.getInt(),
itBlue->second.getInt(), itAlpha->second.getInt());
} else {
result = false;
}
return result;
}
bool Color::isValidValue(const Value &node) {
Object::const_iterator itRed = node.getObject().find("red");
Object::const_iterator itGreen = node.getObject().find("green");
Object::const_iterator itBlue = node.getObject().find("blue");
Object::const_iterator itAlpha = node.getObject().find("alpha");
return itRed != node.getObject().end() &&
itGreen != node.getObject().end() &&
itBlue != node.getObject().end() &&
itAlpha != node.getObject().end() &&
itRed->second.isNumeric() &&
itGreen->second.isNumeric() &&
itBlue->second.isNumeric() &&
itAlpha->second.isNumeric();
}
std::ostream &operator<<(std::ostream &output, const Color &color) {
Value tmpValue;
DefaultSerializer::serialize(color, tmpValue);
DefaultSerializer::getDefaultSerializer().writeToStream(output, tmpValue);
return output;
}
}
|
anhero/BaconBox-OLD
|
BaconBox/BaconBox/Display/Color.cpp
|
C++
|
lgpl-3.0
| 16,153
|
<html><head><title>o2tab_fkey_setoff</title><link rel='stylesheet' type='text/css' href='jxdoc.css'></head><body><center><br><small><a href='index.html#o2tab_fkey_setoff'>Index</a></small><hr></center><p>(table)</p><h3>o2tab_fkey_setoff</h3><code><i>boolean</i> o2tab_fkey_setoff(<i>string</i> $table_name, <i>string</i> $fkey_name)</code><p>Deactivates an active foreign key by name <br />
<br />
<br />
</p><fieldset><legend>Parameters:</legend><ol><li><b>$table_name</b></li> <li><b>$fkey_name</b></li> </ol></fieldset><fieldset><legend>Related functions:</legend><p><a href="o2tab_fkey_seton.html">o2tab_fkey_seton</a></p><p><a href="o2tab_fkeys_setoff.html">o2tab_fkeys_setoff</a></p><p><a href="o2tab_fkeys_list.html">o2tab_fkeys_list</a></p></fieldset></body></html>
|
tvannini/janox
|
doc/reference/o2tab_fkey_setoff.html
|
HTML
|
lgpl-3.0
| 773
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Copyright © 2006-2010 Travis Robinson. All rights reserved.
// Copyright © 2011-2018 LibUsbDotNet contributors. All rights reserved.
//
// website: http://github.com/libusbdotnet/libusbdotnet
//
// 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 2 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. or
// visit www.gnu.org.
//
//
using System;
namespace LibUsbDotNet
{
/// <summary>
/// Since version 1.0.16,
/// Hotplug events
/// </summary>
[Flags]
public enum HotplugEvent : byte
{
/// <summary>
/// A device has been plugged in and is ready to use
/// </summary>
DeviceArrived = 0x1,
DeviceLeft = 0x2,
}
}
|
LibUsbDotNet/LibUsbDotNet
|
src/LibUsbDotNet/Generated/HotplugEvent.cs
|
C#
|
lgpl-3.0
| 1,678
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Extent.cs" company="Allors bvba">
// Copyright 2002-2016 Allors bvba.
// Dual Licensed under
// a) the Lesser General Public Licence v3 (LGPL)
// b) the Allors License
// The LGPL License is included in the file lgpl.txt.
// The Allors License is an addendum to your contract.
// Allors Platform 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.
// For more information visit http://www.allors.com/legal
// </copyright>
// <summary>
// Defines the AllorsExtentMemory type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using Allors;
namespace Allors.Adapters.Memory
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Allors.Meta;
public abstract class Extent : Allors.Extent
{
private readonly Session session;
private IObject[] defaultObjectArray;
private Extent parent;
private ExtentSort sorter;
private List<Strategy> strategies;
protected Extent(Session session)
{
this.session = session;
}
public override int Count
{
get
{
this.Evaluate();
return this.strategies.Count;
}
}
public override IObject First
{
get
{
this.Evaluate();
return (from Strategy strategy in this.Strategies select strategy.GetObject()).FirstOrDefault();
}
}
public Extent Parent
{
get
{
return this.parent;
}
set
{
if (this.parent != null)
{
throw new ArgumentException("Extent has already a parent");
}
this.parent = value;
}
}
internal Session Session
{
get { return this.session; }
}
internal ExtentSort Sorter
{
get { return this.sorter; }
}
protected List<Strategy> Strategies
{
get { return this.strategies; }
set { this.strategies = value; }
}
public override Allors.Extent AddSort(IRoleType roleType)
{
return this.AddSort(roleType, SortDirection.Ascending);
}
public override Allors.Extent AddSort(IRoleType roleType, SortDirection direction)
{
if (this.sorter == null)
{
this.sorter = new ExtentSort(roleType, direction);
}
else
{
this.sorter.AddSort(roleType, direction);
}
this.Invalidate();
return this;
}
public override bool Contains(object value)
{
return this.IndexOf(value) >= 0;
}
public override void CopyTo(Array array, int index)
{
this.Evaluate();
var i = index;
foreach (var strategy in this.strategies)
{
array.SetValue(strategy.GetObject(), i);
++i;
}
}
public override IEnumerator GetEnumerator()
{
this.Evaluate();
return new ExtentEnumerator(this.strategies.GetEnumerator());
}
public override int IndexOf(object value)
{
this.Evaluate();
var containedObject = (IObject)value;
var i = 0;
foreach (var strategy in this.strategies)
{
if (strategy.ObjectId.Equals(containedObject.Strategy.ObjectId))
{
return i;
}
++i;
}
return -1;
}
public override IObject[] ToArray()
{
this.Evaluate();
var clrType = this.Session.GetTypeForObjectType(this.ObjectType);
if (this.strategies.Count > 0)
{
var objects = (IObject[])Array.CreateInstance(clrType, this.strategies.Count);
var i = 0;
foreach (var strategy in this.strategies)
{
objects[i] = strategy.GetObject();
++i;
}
return objects;
}
return this.defaultObjectArray ?? (this.defaultObjectArray = (IObject[])Array.CreateInstance(clrType, 0));
}
public override IObject[] ToArray(Type type)
{
this.Evaluate();
if (this.strategies.Count > 0)
{
var objects = (IObject[])Array.CreateInstance(type, this.strategies.Count);
var i = 0;
foreach (var strategy in this.strategies)
{
objects[i] = strategy.GetObject();
++i;
}
return objects;
}
return (IObject[])Array.CreateInstance(type, 0);
}
internal bool ContainsStrategy(Strategy strategy)
{
this.Evaluate();
return this.strategies.Contains(strategy);
}
internal List<Strategy> GetEvaluatedStrategies()
{
this.Evaluate();
return this.strategies;
}
internal void Invalidate()
{
this.strategies = null;
if (this.parent != null)
{
this.parent.Invalidate();
}
}
protected abstract void Evaluate();
protected override IObject GetItem(int index)
{
this.Evaluate();
return this.strategies[index].GetObject();
}
}
}
|
Allors/allors1
|
Adapters/Allors.Adapters.Memory/Extent.cs
|
C#
|
lgpl-3.0
| 6,198
|
# EnableGameStream
This small program should patch GeForce Experience to enable GameStream on GT Devices
The idea is based upon the work of others, I used the manual from p1gl3t, as posted on [xda-developers here](http://forum.xda-developers.com/showpost.php?p=58240849&postcount=123)
I really liked the idea of using my laptop (using a NVidia GT 750M) in combination with Moonlight running on an Amazon Fire TV, and I got it working.
One thing I didn't like about the solution, and that is one needs to install Python and also need to do a lot of manual steps.
This is why I wrote this little tool.
What it currently does:
* Find your graphics card ID
* Find the service
* Find the files to patch
* Stop the service
* Patch the files
* Start the service
What this doesn't:
* Enable frame buffer capture. I could by including the NvFBCEnable.exe, but I don't want issues with NVidia. Unless someone has information on how this works... or if this is still needed? you can find the download in the link on [xda-developers here](http://forum.xda-developers.com/showpost.php?p=58240849&postcount=123)
* Patch the HTTP(S) communication between GeForce-Experience and the site, this could be done by installing my application temporarily as a Proxy (using Fiddler). [Here on xda-developers](http://forum.xda-developers.com/showpost.php?p=62867011&postcount=158) is an example on what the proxy needs to do.
Downloads can be found under the [releases](https://github.com/Lakritzator/EnableGameStream/releases) tab of this repository.
Last, an important notice:
**There is a reason that NVidia didn't enable this functionality, as the power of the GT graphics cards is limited you will have issues streaming when a lot of stuff is going on!!!! I tried it with Alan Wake, video sequences were streaming fine to Moonlight but while playing I had about one frame per 3-4 seconds. Local display on the laptop had no lag at all. I had to reduce the details and resolution before it was somewhat playable in Moonlight.**
**DISCLAIMER**
EnableGameStream 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.
|
Lakritzator/EnableGameStream
|
README.md
|
Markdown
|
lgpl-3.0
| 2,271
|
package io.github.albertus82.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import io.github.albertus82.util.logging.LoggerFactory;
public class BrotliAdapterTest {
private static final Logger log = LoggerFactory.getLogger(BrotliAdapterTest.class);
private static final int JOBS_COUNT = 50;
private static final int CONCURRENT_THREADS = 4;
private static final String CHARSET_NAME = "UTF-8";
// @formatter:off
private static final String[] testStrings = {
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a scelerisque tortor. Fusce vehicula tellus quam, dictum ornare dolor placerat sed. Cras varius vulputate lorem, eu dignissim dolor imperdiet ut. Sed rutrum nisi eu metus porta semper. Etiam pharetra mauris dolor, vel mattis arcu rhoncus quis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent non facilisis nulla. Curabitur placerat, quam vitae semper ultrices, augue dui scelerisque nunc, sagittis viverra sem nisi quis elit. Nunc rhoncus efficitur est. Nullam non libero et augue ultricies commodo. Fusce eleifend in risus at sagittis. Praesent nec nunc sollicitudin libero varius tempor. Phasellus interdum et est nec cursus.",
"Quisque nec ultrices eros, eu interdum mi. Pellentesque lorem elit, placerat id nisi non, posuere vulputate libero. Duis tincidunt tortor ligula, non rhoncus urna vestibulum vitae. Vestibulum posuere magna ut nunc molestie dignissim. Donec nec mollis nibh. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc tincidunt malesuada elit. Phasellus sollicitudin consectetur malesuada. Maecenas convallis leo sit amet justo tincidunt finibus.",
"Etiam consectetur pellentesque imperdiet. Pellentesque urna justo, tincidunt a risus in, mollis consectetur nunc. Ut eu sem congue, tincidunt est gravida, congue risus. Vestibulum lobortis nisl non placerat dictum. Sed erat orci, molestie id nunc non, commodo placerat sapien. Aenean luctus fringilla dolor, sed tempus nibh consectetur vitae. Ut in auctor eros, sit amet malesuada est. Vestibulum leo ante, vulputate sed ornare a, dictum nec est. Suspendisse quis sodales felis. Aenean ac nisi quis est pulvinar tincidunt. Etiam commodo egestas ante in pellentesque. Duis euismod urna et felis accumsan tempus. Ut ultricies nisl sit amet mauris finibus sodales. Proin semper sed enim a tincidunt. Aenean euismod ante massa. Donec nec nisl nisl.",
"Donec in consectetur nisl, sed euismod erat. Maecenas mattis laoreet hendrerit. In commodo nunc mi, ac efficitur lacus luctus vel. Pellentesque nulla justo, consequat eget finibus in, pharetra sit amet sapien. In at augue libero. Sed suscipit, ipsum vitae sagittis interdum, libero erat dictum massa, ut tempus urna mauris a risus. Cras ultricies mauris vel sem pulvinar, vel faucibus felis mattis. Phasellus quis posuere risus. Donec ligula odio, pharetra et nulla eget, vestibulum pharetra tortor. Sed lacinia nibh tincidunt velit interdum tempus. In vel malesuada dolor, id rhoncus libero. Cras felis mauris, accumsan vel rhoncus quis, blandit vitae sem. Fusce porta faucibus ex, at lacinia nibh imperdiet ac." };
// @formatter:on
private static BrotliAdapter instance;
@BeforeClass
public static void init() {
instance = new BrotliAdapter();
}
@Test
public void testArraySingleThread() throws IOException {
final int i = new Random().nextInt(4);
final byte[] original = testStrings[i].getBytes(CHARSET_NAME);
final byte[] compressed = instance.compress(original, 2);
final byte[] decompressed = instance.decompress(compressed);
Assert.assertArrayEquals(original, decompressed);
Assert.assertEquals(testStrings[i], new String(decompressed, CHARSET_NAME));
}
@Test
public void testArrayMultiThread() throws IOException, InterruptedException {
final Random random = new Random();
for (int i = 0; i < JOBS_COUNT; i++) {
final List<CompressDecompressThread> threads = new ArrayList<CompressDecompressThread>();
for (int j = 0; j < CONCURRENT_THREADS; j++) {
final CompressDecompressThread thread = new CompressDecompressThread(testStrings[random.nextInt(4)]);
threads.add(thread);
thread.start();
}
for (final Thread thread : threads) {
thread.join();
}
for (final CompressDecompressThread thread : threads) {
Assert.assertArrayEquals(thread.original.getBytes(CHARSET_NAME), thread.decompressed);
Assert.assertEquals(thread.original, new String(thread.decompressed, CHARSET_NAME));
}
System.out.println('.');
}
}
private class CompressDecompressThread extends Thread {
private final String original;
private byte[] decompressed;
public CompressDecompressThread(final String original) {
this.original = original;
}
@Override
public void run() {
try {
final long t0 = System.nanoTime();
final byte[] compressed = instance.compress(original.getBytes(CHARSET_NAME), 2);
final long t1 = System.nanoTime();
log.log(Level.INFO, "Brotli compressed in {0,number,#} ms.", TimeUnit.NANOSECONDS.toMillis(t1 - t0));
final long t2 = System.nanoTime();
decompressed = instance.decompress(compressed);
final long t3 = System.nanoTime();
log.log(Level.INFO, "Brotli decompressed in {0} ms.", Double.toString(TimeUnit.NANOSECONDS.toMicros(t3 - t2) / 1000d));
}
catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
}
|
Albertus82/JFaceUtils
|
src/test/java/io/github/albertus82/util/BrotliAdapterTest.java
|
Java
|
lgpl-3.0
| 5,842
|
package org.molgenis.data.elasticsearch.request;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.mockito.ArgumentCaptor;
import org.molgenis.data.Entity;
import org.molgenis.data.Query;
import org.molgenis.data.Sort;
import org.molgenis.data.elasticsearch.util.DocumentIdGenerator;
import org.molgenis.data.meta.model.Attribute;
import org.molgenis.data.meta.model.EntityType;
import org.molgenis.data.support.QueryImpl;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import static org.mockito.Mockito.*;
import static org.molgenis.data.meta.AttributeType.INT;
import static org.molgenis.data.meta.AttributeType.STRING;
import static org.testng.Assert.assertEquals;
public class SortGeneratorTest
{
private SortGenerator sortGenerator;
private SearchRequestBuilder searchRequestBuilder;
private EntityType entityType;
@BeforeMethod
public void beforeMethod()
{
DocumentIdGenerator documentIdGenerator = mock(DocumentIdGenerator.class);
when(documentIdGenerator.generateId(any(Attribute.class)))
.thenAnswer(invocation -> ((Attribute) invocation.getArguments()[0]).getName());
sortGenerator = new SortGenerator(documentIdGenerator);
searchRequestBuilder = mock(SearchRequestBuilder.class);
EntityType entityType = when(mock(EntityType.class).getFullyQualifiedName()).thenReturn("entity").getMock();
Attribute intAttr = when(mock(Attribute.class).getName()).thenReturn("int").getMock();
when(intAttr.getDataType()).thenReturn(INT);
when(entityType.getAttribute("int")).thenReturn(intAttr);
Attribute stringAttr = when(mock(Attribute.class).getName()).thenReturn("string").getMock();
when(stringAttr.getDataType()).thenReturn(STRING);
when(entityType.getAttribute("string")).thenReturn(stringAttr);
this.entityType = entityType;
}
@Test
public void testGenerateNoSort()
{
QueryImpl<Entity> query = new QueryImpl<>();
sortGenerator.generate(searchRequestBuilder, query, entityType);
verifyZeroInteractions(searchRequestBuilder);
}
@Test
public void testGenerateAsc()
{
Query<Entity> query = new QueryImpl<>().sort(new Sort("int", Sort.Direction.ASC));
sortGenerator.generate(searchRequestBuilder, query, entityType);
ArgumentCaptor<FieldSortBuilder> argument = ArgumentCaptor.forClass(FieldSortBuilder.class);
verify(searchRequestBuilder).addSort(argument.capture());
FieldSortBuilder sortBuilder = argument.getValue();
assertEquals(sortBuilder.toString().replaceAll("\\s", ""), "\"int\"{\"order\":\"asc\",\"mode\":\"min\"}");
}
@Test
public void testGenerateAscRaw()
{
Query<Entity> query = new QueryImpl<>().sort(new Sort("string", Sort.Direction.ASC));
sortGenerator.generate(searchRequestBuilder, query, entityType);
ArgumentCaptor<FieldSortBuilder> argument = ArgumentCaptor.forClass(FieldSortBuilder.class);
verify(searchRequestBuilder).addSort(argument.capture());
FieldSortBuilder sortBuilder = argument.getValue();
assertEquals(sortBuilder.toString().replaceAll("\\s", ""),
"\"string.raw\"{\"order\":\"asc\",\"mode\":\"min\"}");
}
@Test
public void testGenerateDesc()
{
Query<Entity> query = new QueryImpl<>().sort(new Sort("int", Sort.Direction.DESC));
sortGenerator.generate(searchRequestBuilder, query, entityType);
ArgumentCaptor<FieldSortBuilder> argument = ArgumentCaptor.forClass(FieldSortBuilder.class);
verify(searchRequestBuilder).addSort(argument.capture());
FieldSortBuilder sortBuilder = argument.getValue();
assertEquals(sortBuilder.toString().replaceAll("\\s", ""), "\"int\"{\"order\":\"desc\",\"mode\":\"min\"}");
}
@Test
public void testGenerateDescRaw()
{
Query<Entity> query = new QueryImpl<>().sort(new Sort("string", Sort.Direction.DESC));
sortGenerator.generate(searchRequestBuilder, query, entityType);
ArgumentCaptor<FieldSortBuilder> argument = ArgumentCaptor.forClass(FieldSortBuilder.class);
verify(searchRequestBuilder).addSort(argument.capture());
FieldSortBuilder sortBuilder = argument.getValue();
assertEquals(sortBuilder.toString().replaceAll("\\s", ""),
"\"string.raw\"{\"order\":\"desc\",\"mode\":\"min\"}");
}
@Test
public void testGenerateDescAscRaw()
{
Query<Entity> query = new QueryImpl<>()
.sort(new Sort().on("int", Sort.Direction.DESC).on("string", Sort.Direction.ASC));
sortGenerator.generate(searchRequestBuilder, query, entityType);
ArgumentCaptor<FieldSortBuilder> argument = ArgumentCaptor.forClass(FieldSortBuilder.class);
verify(searchRequestBuilder, times(2)).addSort(argument.capture());
List<FieldSortBuilder> sortBuilder = argument.getAllValues();
assertEquals(sortBuilder.size(), 2);
assertEquals(sortBuilder.get(0).toString().replaceAll("\\s", ""),
"\"int\"{\"order\":\"desc\",\"mode\":\"min\"}");
assertEquals(sortBuilder.get(1).toString().replaceAll("\\s", ""),
"\"string.raw\"{\"order\":\"asc\",\"mode\":\"min\"}");
}
}
|
marissaDubbelaar/GOAD3.1.1
|
molgenis-data-elasticsearch/src/test/java/org/molgenis/data/elasticsearch/request/SortGeneratorTest.java
|
Java
|
lgpl-3.0
| 4,980
|
<?php
/*
* EZCAST EZplayer
*
* Copyright (C) 2016 Université libre de Bruxelles
*
* Written by Michel Jansens <mjansens@ulb.ac.be>
* Arnaud Wijns <awijns@ulb.ac.be>
* Carlos Avidmadjessi
* UI Design by Julien Di Pietrantonio
*
* This software 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
?>
<?php
include_once 'lib_print.php';
?>
<h2><b style="text-transform:uppercase;"><?php echo suffix_remove($album); ?></b> // <?php echo get_album_title($album); ?></h2>
<?php if (isset($asset_meta['title'])){ ?>
<h3><?php echo $asset_meta['title']; ?></h3>
<?php } ?>
<br/><p>Sélectionnez les signets que vous souhaitez supprimer. Cette opération est irréversible.</p>
<a class="close-reveal-modal" href="javascript:close_popup();">×</a>
<br/>
<?php if (isset($bookmarks) && count($bookmarks) > 0){ ?>
<form action="index.php?action=bookmarks_delete" method="post" id="select_delete_bookmark_form" name="delete_bookmarks_form" onsubmit="return false">
<input type="hidden" name="album" id="delete_album" value="<?php echo $album; ?>"/>
<input type="hidden" name="asset" id="delete_asset" value="<?php echo $asset_meta['record_date']; ?>"/>
<input type="hidden" name="target" id="delete_target" value="<?php echo $tab; ?>"/><br/>
<ul>
<li style="border-bottom: solid 1px #cccccc;"><input type="checkbox" onclick="toggle_checkboxes(this, 'delete_selection[]')" name="check_all"/><span class="<?php echo (($tab == 'custom') ? 'blue-title' : 'orange-title'); ?>"><b>Date</b></span><span class="<?php echo (($tab == 'custom') ? 'blue-title' : 'orange-title'); ?>"><b>Signet</b></span></li>
<?php foreach ($bookmarks as $index => $bookmark){ ?>
<li>
<input style="float: left;" type="checkbox" name="delete_selection[]" value="<?php echo $index ?>"/>
<div style="display: inline-block; width: 457px; padding-left: 8px;">
<span style="padding-left: 0px;"><b><?php print_info(substr(get_user_friendly_date($bookmark['asset'], '/', false, get_lang(), false), 0, 10)); ?></b></span>
<?php echo get_asset_title($bookmark['album'], $bookmark['asset']); ?>
<div class="right-arrow"></div>
<?php print_bookmark_title($bookmark['title']); ?>
</div>
</li>
<?php } ?>
</ul><br/>
<a href="#" onclick="bookmarks_delete_form_submit('<?php echo $source; ?>');" id="delete_button" class="delete-button-confirm" title="Supprimer les signets sélectionnés">Supprimer</a>
<a class="close-reveal-modal-button" href="javascript:close_popup();">Annuler</a>
</form>
<?php } else { ?>
Il n'y a aucun signet à afficher.
<?php } ?>
|
lmondry/ezcast
|
ezplayer/tmpl/fr/popup_bookmarks_delete.php
|
PHP
|
lgpl-3.0
| 3,491
|
namespace libMBIN.Models.Structs
{
public class GcBuildingCostPartCount : NMSTemplate
{
[NMS(Size = 0x10)]
public string Id;
public int Count;
}
}
|
theFisher86/MBINCompiler
|
libMBIN/Source/Models/Structs/GcBuildingCostPartCount.cs
|
C#
|
lgpl-3.0
| 186
|
namespace LinFu.AOP.Interfaces
{
/// <summary>
/// Represents a class that can instantiate object instances.
/// </summary>
/// <typeparam name="TContext">
/// The type that describes the context of the object instantiation.
/// </typeparam>
public interface IActivator<TContext>
where TContext : IActivationContext
{
/// <summary>
/// Creates an object instance.
/// </summary>
/// <param name="context">The context that describes the request to instantiate the target type.</param>
/// <returns>A valid object instance.</returns>
object CreateInstance(TContext context);
}
}
|
philiplaureano/LinFu
|
src/LinFu.AOP.Interfaces/IActivator.cs
|
C#
|
lgpl-3.0
| 683
|
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.java.ast.visitor;
import java.util.Arrays;
import java.util.List;
import org.sonar.squid.api.SourceClass;
import org.sonar.squid.api.SourcePackage;
import org.sonar.squid.measures.Metric;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
public class ClassVisitor extends JavaAstVisitor {
public static final List<Integer> WANTED_TOKENS = Arrays.asList(TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.ENUM_DEF,
TokenTypes.ANNOTATION_DEF);
@Override
public List<Integer> getWantedTokens() {
return WANTED_TOKENS;
}
@Override
public void visitToken(DetailAST ast) {
String className = ast.findFirstToken(TokenTypes.IDENT).getText();
SourceClass unit;
if (peekSourceCode().isType(SourceClass.class)) {
unit = createSourceClass((SourceClass) peekSourceCode(), className);
} else {
unit = createSourceClass(peekParentPackage(), className);
}
addSourceCode(unit);
unit.setStartAtLine(ast.getLineNo());
unit.setMeasure(Metric.CLASSES, 1);
if (isInterface(ast.getType())) {
unit.setMeasure(Metric.INTERFACES, 1);
}
if (isAbstract(ast)) {
unit.setMeasure(Metric.ABSTRACT_CLASSES, 1);
}
unit.setSuppressWarnings(SuppressWarningsAnnotationUtils.isSuppressAllWarnings(ast));
}
@Override
public void leaveToken(DetailAST ast) {
popSourceCode();
}
private boolean isAbstract(DetailAST ast) {
final DetailAST abstractAST = ast.findFirstToken(TokenTypes.MODIFIERS).findFirstToken(TokenTypes.ABSTRACT);
return abstractAST != null;
}
private boolean isInterface(int type) {
return type == TokenTypes.INTERFACE_DEF;
}
static SourceClass createSourceClass(SourcePackage parentPackage, String className) {
StringBuilder key = new StringBuilder();
if (parentPackage != null && !"".equals(parentPackage.getKey())) {
key.append(parentPackage.getKey());
key.append("/");
}
key.append(className);
return new SourceClass(key.toString(), className);
}
static SourceClass createSourceClass(SourceClass parentClass, String innerClassName) {
return new SourceClass(parentClass.getKey() + "$" + innerClassName, innerClassName);
}
}
|
leodmurillo/sonar
|
plugins/sonar-squid-java-plugin/src/main/java/org/sonar/java/ast/visitor/ClassVisitor.java
|
Java
|
lgpl-3.0
| 3,126
|
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program 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.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\item;
use pocketmine\block\Block;
use pocketmine\entity\EnderCrystal;
use pocketmine\entity\Entity;
use pocketmine\level\Level;
use pocketmine\math\Vector3;
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\DoubleTag;
use pocketmine\nbt\tag\FloatTag;
use pocketmine\nbt\tag\ListTag;
use pocketmine\nbt\tag\StringTag;
use pocketmine\Player;
class EndCrystal extends Item{
public function __construct(int $meta = 0){
parent::__construct(self::END_CRYSTAL, $meta, "End Crystal");
}
public function onActivate(Level $level, Player $player, Block $block, Block $target, int $face, Vector3 $facePos): bool{
$nbt = new CompoundTag("", [
new ListTag("Pos", [
new DoubleTag("", $block->getX() + 0.5),
new DoubleTag("", $block->getY()),
new DoubleTag("", $block->getZ() + 0.5)
]),
new ListTag("Motion", [
new DoubleTag("", 0),
new DoubleTag("", 0),
new DoubleTag("", 0)
]),
new ListTag("Rotation", [
new FloatTag("", lcg_value() * 360),
new FloatTag("", 0)
]),
]);
if ($this->hasCustomName()){
$nbt->CustomName = new StringTag("CustomName", $this->getCustomName());
}
$entity = Entity::createEntity(EnderCrystal::NETWORK_ID, $level, $nbt);
if ($entity instanceof Entity){
if ($player->isSurvival()){
--$this->count;
}
$entity->spawnToAll();
return true;
}
return false;
}
}
|
ClearSkyTeam/PocketMine-MP
|
src/pocketmine/item/EndCrystal.php
|
PHP
|
lgpl-3.0
| 2,197
|
/*****************************************************************************
Copyright (c) 2010, Intel Corp.
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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************
* Contents: Native high-level C interface to LAPACK function ssteqr
* Author: Intel Corporation
* Generated October, 2010
*****************************************************************************/
#include "lapacke.h"
#include "lapacke_utils.h"
lapack_int LAPACKE_ssteqr( int matrix_order, char compz, lapack_int n, float* d,
float* e, float* z, lapack_int ldz )
{
lapack_int info = 0;
/* Additional scalars declarations for work arrays */
lapack_int lwork;
float* work = NULL;
if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_ssteqr", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
/* Optionally check input matrices for NaNs */
if( LAPACKE_s_nancheck( n, d, 1 ) ) {
return -4;
}
if( LAPACKE_s_nancheck( n-1, e, 1 ) ) {
return -5;
}
if( LAPACKE_lsame( compz, 'i' ) || LAPACKE_lsame( compz, 'v' ) ) {
if( LAPACKE_sge_nancheck( matrix_order, n, n, z, ldz ) ) {
return -6;
}
}
#endif
/* Additional scalars initializations for work arrays */
if( LAPACKE_lsame( compz, 'n' ) ) {
lwork = 1;
} else {
lwork = MAX(1,2*n-2);
}
/* Allocate memory for working array(s) */
work = (float*)LAPACKE_malloc( sizeof(float) * lwork );
if( work == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
/* Call middle-level interface */
info = LAPACKE_ssteqr_work( matrix_order, compz, n, d, e, z, ldz, work );
/* Release memory and exit */
LAPACKE_free( work );
exit_level_0:
if( info == LAPACK_WORK_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_ssteqr", info );
}
return info;
}
|
mfine/libswiftnav
|
lapacke/src/lapacke_ssteqr.c
|
C
|
lgpl-3.0
| 3,473
|
#include "UDPEchoServer.h"
#include "SocketAddress.h"
#include "base/Time/Timespan.h"
#include <iostream>
namespace pi {
UDPEchoServer::UDPEchoServer():
_thread("UDPEchoServer"),
_stop(false)
{
_socket.bind(SocketAddress(), true);
_thread.start(this);
_ready.wait();
}
UDPEchoServer::UDPEchoServer(const SocketAddress& sa):
_thread("UDPEchoServer"),
_stop(false)
{
_socket.bind(sa, true);
_thread.start(this);
_ready.wait();
}
UDPEchoServer::~UDPEchoServer()
{
_stop = true;
_thread.join();
}
UInt16 UDPEchoServer::port() const
{
return _socket.address().port();
}
void UDPEchoServer::run()
{
Timespan span(250000);
while (!_stop)
{
_ready.set();
if (_socket.poll(span, Socket::SELECT_READ))
{
try
{
char buffer[256];
SocketAddress sender;
int n = _socket.receiveFrom(buffer, sizeof(buffer), sender);
n = _socket.sendTo(buffer, n, sender);
}
catch (Exception& exc)
{
std::cerr << "UDPEchoServer: " << exc.displayText() << std::endl;
}
}
}
}
SocketAddress UDPEchoServer::address() const
{
return _socket.address();
}
}
|
zdzhaoyong/PIL2
|
src/network/UDPEchoServer.cpp
|
C++
|
lgpl-3.0
| 1,288
|
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "untagresourcerequest.h"
#include "untagresourcerequest_p.h"
#include "untagresourceresponse.h"
#include "wafv2request_p.h"
namespace QtAws {
namespace WAFV2 {
/*!
* \class QtAws::WAFV2::UntagResourceRequest
* \brief The UntagResourceRequest class provides an interface for WAFV2 UntagResource requests.
*
* \inmodule QtAwsWAFV2
*
* <note>
*
* This is the latest version of the <b>AWS WAF</b> API, released in November, 2019. The names of the entities that you use
* to access this API, like endpoints and namespaces, all have the versioning information added, like "V2" or "v2", to
* distinguish from the prior version. We recommend migrating your resources to this version, because it has a number of
* significant
*
* improvements>
*
* If you used AWS WAF prior to this release, you can't use this AWS WAFV2 API to access any AWS WAF resources that you
* created before. You can access your old rules, web ACLs, and other AWS WAF resources only through the AWS WAF Classic
* APIs. The AWS WAF Classic APIs have retained the prior names, endpoints, and namespaces.
*
* </p
*
* For information, including how to migrate your AWS WAF resources to this version, see the <a
* href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">AWS WAF Developer Guide</a>.
*
* </p </note>
*
* AWS WAF is a web application firewall that lets you monitor the HTTP and HTTPS requests that are forwarded to Amazon
* CloudFront, an Amazon API Gateway REST API, an Application Load Balancer, or an AWS AppSync GraphQL API. AWS WAF also
* lets you control access to your content. Based on conditions that you specify, such as the IP addresses that requests
* originate from or the values of query strings, the API Gateway REST API, CloudFront distribution, the Application Load
* Balancer, or the AWS AppSync GraphQL API responds to requests either with the requested content or with an HTTP 403
* status code (Forbidden). You also can configure CloudFront to return a custom error page when a request is
*
* blocked>
*
* This API guide is for developers who need detailed information about AWS WAF API actions, data types, and errors. For
* detailed information about AWS WAF features and an overview of how to use AWS WAF, see the <a
* href="https://docs.aws.amazon.com/waf/latest/developerguide/">AWS WAF Developer
*
* Guide</a>>
*
* You can make calls using the endpoints listed in <a
* href="https://docs.aws.amazon.com/general/latest/gr/rande.html#waf_region">AWS Service Endpoints for AWS WAF</a>.
*
* </p <ul> <li>
*
* For regional applications, you can use any of the endpoints in the list. A regional application can be an Application
* Load Balancer (ALB), an API Gateway REST API, or an AppSync GraphQL API.
*
* </p </li> <li>
*
* For AWS CloudFront applications, you must use the API endpoint listed for US East (N. Virginia):
*
* us-east-1> </li> </ul>
*
* Alternatively, you can use one of the AWS SDKs to access an API that's tailored to the programming language or platform
* that you're using. For more information, see <a href="http://aws.amazon.com/tools/#SDKs">AWS
*
* SDKs</a>>
*
* We currently provide two versions of the AWS WAF API: this API and the prior versions, the classic AWS WAF APIs. This
* new API provides the same functionality as the older versions, with the following major
*
* improvements> <ul> <li>
*
* You use one API for both global and regional applications. Where you need to distinguish the scope, you specify a
* <code>Scope</code> parameter and set it to <code>CLOUDFRONT</code> or <code>REGIONAL</code>.
*
* </p </li> <li>
*
* You can define a Web ACL or rule group with a single call, and update it with a single call. You define all rule
* specifications in JSON format, and pass them to your rule group or Web ACL
*
* calls> </li> <li>
*
* The limits AWS WAF places on the use of rules more closely reflects the cost of running each type of rule. Rule groups
* include capacity settings, so you know the maximum cost of a rule group when you use
*
* \sa Wafv2Client::untagResource
*/
/*!
* Constructs a copy of \a other.
*/
UntagResourceRequest::UntagResourceRequest(const UntagResourceRequest &other)
: Wafv2Request(new UntagResourceRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a UntagResourceRequest object.
*/
UntagResourceRequest::UntagResourceRequest()
: Wafv2Request(new UntagResourceRequestPrivate(Wafv2Request::UntagResourceAction, this))
{
}
/*!
* \reimp
*/
bool UntagResourceRequest::isValid() const
{
return false;
}
/*!
* Returns a UntagResourceResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * UntagResourceRequest::response(QNetworkReply * const reply) const
{
return new UntagResourceResponse(*this, reply);
}
/*!
* \class QtAws::WAFV2::UntagResourceRequestPrivate
* \brief The UntagResourceRequestPrivate class provides private implementation for UntagResourceRequest.
* \internal
*
* \inmodule QtAwsWAFV2
*/
/*!
* Constructs a UntagResourceRequestPrivate object for Wafv2 \a action,
* with public implementation \a q.
*/
UntagResourceRequestPrivate::UntagResourceRequestPrivate(
const Wafv2Request::Action action, UntagResourceRequest * const q)
: Wafv2RequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the UntagResourceRequest
* class' copy constructor.
*/
UntagResourceRequestPrivate::UntagResourceRequestPrivate(
const UntagResourceRequestPrivate &other, UntagResourceRequest * const q)
: Wafv2RequestPrivate(other, q)
{
}
} // namespace WAFV2
} // namespace QtAws
|
pcolby/libqtaws
|
src/wafv2/untagresourcerequest.cpp
|
C++
|
lgpl-3.0
| 6,592
|
package com.github.steveice10.mc.protocol.packet.ingame.server.entity;
import com.electronwill.utils.Vec3d;
import com.github.steveice10.mc.protocol.util.ReflectionToString;
import com.github.steveice10.packetlib.io.NetInput;
import com.github.steveice10.packetlib.io.NetOutput;
import com.github.steveice10.packetlib.packet.Packet;
import java.io.IOException;
public class ServerEntityPositionPacket implements Packet {
private int entityId;
private Vec3d relativeMove;
private boolean onGround;
private ServerEntityPositionPacket() {}
public ServerEntityPositionPacket(int entityId, Vec3d relativeMove, boolean onGround) {
this.entityId = entityId;
this.relativeMove = relativeMove;
this.onGround = onGround;
}
@Override
public void read(NetInput in) throws IOException {
entityId = in.readVarInt();
double moveX = in.readShort() / 4096.0;
double moveY = in.readShort() / 4096.0;
double moveZ = in.readShort() / 4096.0;
relativeMove = new Vec3d(moveX, moveY, moveZ);
onGround = in.readBoolean();
}
@Override
public void write(NetOutput out) throws IOException {
out.writeVarInt(entityId);
out.writeShort((int)(relativeMove.x() * 4096.0));
out.writeShort((int)(relativeMove.y() * 4096.0));
out.writeShort((int)(relativeMove.z() * 4096.0));
out.writeBoolean(onGround);
}
@Override
public boolean isPriority() {
return false;
}
@Override
public String toString() {
return ReflectionToString.toString(this);
}
}
|
mcphoton/Photon-ProtocolLib
|
src/main/java/com/github/steveice10/mc/protocol/packet/ingame/server/entity/ServerEntityPositionPacket.java
|
Java
|
lgpl-3.0
| 1,617
|
from __future__ import absolute_import
import logging
import os
import sys
import datetime
import psutil
from six import StringIO
from twisted.web import http, resource
from Tribler.Core.Utilities.instrumentation import WatchDog
import Tribler.Core.Utilities.json_util as json
HAS_MELIAE = True
try:
from meliae import scanner
except ImportError:
HAS_MELIAE = False
class MemoryDumpBuffer(StringIO):
"""
Meliae expects its file handle to support write(), flush() and __call__().
The StringIO class does not support __call__(), therefore we provide this subclass.
"""
def __call__(self, s):
StringIO.write(self, s)
class DebugEndpoint(resource.Resource):
"""
This endpoint is responsible for handing requests regarding debug information in Tribler.
"""
def __init__(self, session):
resource.Resource.__init__(self)
child_handler_dict = {"circuits": DebugCircuitsEndpoint, "open_files": DebugOpenFilesEndpoint,
"open_sockets": DebugOpenSocketsEndpoint, "threads": DebugThreadsEndpoint,
"cpu": DebugCPUEndpoint, "memory": DebugMemoryEndpoint,
"log": DebugLogEndpoint, "profiler": DebugProfilerEndpoint}
for path, child_cls in child_handler_dict.iteritems():
self.putChild(path, child_cls(session))
class DebugCircuitsEndpoint(resource.Resource):
"""
This class handles requests regarding the tunnel community debug information.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
self.putChild("slots", DebugCircuitSlotsEndpoint(session))
def render_GET(self, request):
"""
.. http:get:: /debug/circuits
A GET request to this endpoint returns information about the built circuits in the tunnel community.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/circuits
**Example response**:
.. sourcecode:: javascript
{
"circuits": [{
"id": 1234,
"state": "EXTENDING",
"goal_hops": 4,
"bytes_up": 45,
"bytes_down": 49,
"created": 1468176257,
"hops": [{
"host": "unknown"
}, {
"host": "39.95.147.20:8965"
}],
...
}, ...]
}
"""
tunnel_community = self.session.lm.tunnel_community
if not tunnel_community:
request.setResponseCode(http.NOT_FOUND)
return json.dumps({"error": "tunnel community not found"})
circuits_json = []
for circuit_id, circuit in tunnel_community.circuits.iteritems():
item = {'id': circuit_id, 'state': str(circuit.state), 'goal_hops': circuit.goal_hops,
'bytes_up': circuit.bytes_up, 'bytes_down': circuit.bytes_down, 'created': circuit.creation_time}
hops_array = []
for hop in circuit.hops:
hops_array.append({'host': 'unknown' if 'UNKNOWN HOST' in hop.host else '%s:%s' % (hop.host, hop.port)})
item['hops'] = hops_array
circuits_json.append(item)
return json.dumps({'circuits': circuits_json})
class DebugCircuitSlotsEndpoint(resource.Resource):
"""
This class handles requests for information about slots in the tunnel overlay.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/circuits/slots
A GET request to this endpoint returns information about the slots in the tunnel overlay.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/circuits/slots
**Example response**:
.. sourcecode:: javascript
{
"open_files": [{
"path": "path/to/open/file.txt",
"fd": 33,
}, ...]
}
"""
return json.dumps({
"slots": {
"random": self.session.lm.tunnel_community.random_slots,
"competing": self.session.lm.tunnel_community.competing_slots
}
})
class DebugOpenFilesEndpoint(resource.Resource):
"""
This class handles request for information about open files.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/open_files
A GET request to this endpoint returns information about files opened by Tribler.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/open_files
**Example response**:
.. sourcecode:: javascript
{
"open_files": [{
"path": "path/to/open/file.txt",
"fd": 33,
}, ...]
}
"""
my_process = psutil.Process()
return json.dumps({
"open_files": [{"path": open_file.path, "fd": open_file.fd} for open_file in my_process.open_files()]})
class DebugOpenSocketsEndpoint(resource.Resource):
"""
This class handles request for information about open sockets.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/open_sockets
A GET request to this endpoint returns information about open sockets.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/openfiles
**Example response**:
.. sourcecode:: javascript
{
"open_sockets": [{
"family": 2,
"status": "ESTABLISHED",
"laddr": "0.0.0.0:0",
"raddr": "0.0.0.0:0",
"type": 30
}, ...]
}
"""
my_process = psutil.Process()
sockets = []
for open_socket in my_process.connections():
sockets.append({
"family": open_socket.family,
"status": open_socket.status,
"laddr": ("%s:%d" % open_socket.laddr) if open_socket.laddr else "-",
"raddr": ("%s:%d" % open_socket.raddr) if open_socket.raddr else "-",
"type": open_socket.type
})
return json.dumps({"open_sockets": sockets})
class DebugThreadsEndpoint(resource.Resource):
"""
This class handles request for information about threads.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/threads
A GET request to this endpoint returns information about running threads.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/threads
**Example response**:
.. sourcecode:: javascript
{
"threads": [{
"thread_id": 123456,
"thread_name": "my_thread",
"frames": ["my_frame", ...]
}, ...]
}
"""
watchdog = WatchDog()
return json.dumps({"threads": watchdog.get_threads_info()})
class DebugCPUEndpoint(resource.Resource):
"""
This class handles request for information about CPU.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.putChild("history", DebugCPUHistoryEndpoint(session))
class DebugCPUHistoryEndpoint(resource.Resource):
"""
This class handles request for information about CPU usage history.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/cpu/history
A GET request to this endpoint returns information about CPU usage history in the form of a list.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/cpu/history
**Example response**:
.. sourcecode:: javascript
{
"cpu_history": [{
"time": 1504015291214,
"cpu": 3.4,
}, ...]
}
"""
history = self.session.lm.resource_monitor.get_cpu_history_dict() if self.session.lm.resource_monitor else {}
return json.dumps({"cpu_history": history})
class DebugMemoryEndpoint(resource.Resource):
"""
This class handles request for information about memory.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.putChild("history", DebugMemoryHistoryEndpoint(session))
if HAS_MELIAE:
self.putChild("dump", DebugMemoryDumpEndpoint(session))
class DebugMemoryHistoryEndpoint(resource.Resource):
"""
This class handles request for information about memory usage history.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/memory/history
A GET request to this endpoint returns information about memory usage history in the form of a list.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/memory/history
**Example response**:
.. sourcecode:: javascript
{
"memory_history": [{
"time": 1504015291214,
"mem": 324324,
}, ...]
}
"""
history = self.session.lm.resource_monitor.get_memory_history_dict() if self.session.lm.resource_monitor else {}
return json.dumps({"memory_history": history})
class DebugMemoryDumpEndpoint(resource.Resource):
"""
This class handles request for dumping memory contents.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/memory/dump
A GET request to this endpoint returns a Meliae-compatible dump of the memory contents.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/memory/dump
**Example response**:
The content of the memory dump file.
"""
content = ""
if sys.platform == "win32":
# On Windows meliae (especially older versions) segfault on writing to file
dump_buffer = MemoryDumpBuffer()
try:
scanner.dump_all_objects(dump_buffer)
except OverflowError as e:
# https://bugs.launchpad.net/meliae/+bug/569947
logging.error("meliae dump failed (your version may be too old): %s", str(e))
content = dump_buffer.getvalue()
dump_buffer.close()
else:
# On other platforms, simply writing to file is much faster
dump_file_path = os.path.join(self.session.config.get_state_dir(), 'memory_dump.json')
scanner.dump_all_objects(dump_file_path)
with open(dump_file_path, 'r') as dump_file:
content = dump_file.read()
date_str = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
request.setHeader(b'content-type', 'application/json')
request.setHeader(b'Content-Disposition', 'attachment; filename=tribler_memory_dump_%s.json' % date_str)
return content
class DebugLogEndpoint(resource.Resource):
"""
This class handles the request for displaying the logs.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/log?process=<core|gui>&max_lines=<max_lines>
A GET request to this endpoint returns a json with content of core or gui log file & max_lines requested
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/log?process=core&max_lines=5
**Example response**:
A JSON with content of the log file & max_lines requested, for eg.
{
"max_lines" : 5,
"content" :"INFO 1506675301.76 sqlitecachedb:181 Reading database version...
INFO 1506675301.76 sqlitecachedb:185 Current database version is 29
INFO 1506675301.76 sqlitecachedb:203 Beginning the first transaction...
INFO 1506675301.76 upgrade:93 tribler is in the latest version,...
INFO 1506675302.08 LaunchManyCore:254 lmc: Starting Dispersy..."
}
"""
# First, flush all the logs to make sure it is written to file
for handler in logging.getLogger().handlers:
handler.flush()
# Get the location of log file
param_process = request.args['process'][0] if request.args['process'] else 'core'
log_file_name = os.path.join(self.session.config.get_log_dir(), 'tribler-%s-info.log' % param_process)
# Default response
response = {'content': '', 'max_lines': 0}
# Check if log file exists and return last requested 'max_lines' of log
if os.path.exists(log_file_name):
try:
max_lines = int(request.args['max_lines'][0])
with open(log_file_name, 'r') as log_file:
response['content'] = self.tail(log_file, max_lines)
response['max_lines'] = max_lines
except ValueError:
with open(log_file_name, 'r') as log_file:
response['content'] = self.tail(log_file, 100) # default 100 lines
response['max_lines'] = 0
return json.dumps(response)
def tail(self, file_handler, lines=1):
"""Tail a file and get X lines from the end"""
# place holder for the lines found
lines_found = []
byte_buffer = 1024
# block counter will be multiplied by buffer
# to get the block size from the end
block_counter = -1
# loop until we find X lines
while len(lines_found) < lines:
try:
file_handler.seek(block_counter * byte_buffer, os.SEEK_END)
except IOError: # either file is too small, or too many lines requested
file_handler.seek(0)
lines_found = file_handler.readlines()
break
lines_found = file_handler.readlines()
# we found enough lines, get out
if len(lines_found) > lines:
break
# decrement the block counter to get the
# next X bytes
block_counter -= 1
return ''.join(lines_found[-lines:])
class DebugProfilerEndpoint(resource.Resource):
"""
This class handles requests for the profiler.
"""
def __init__(self, session):
resource.Resource.__init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/profiler
A GET request to this endpoint returns information about the state of the profiler.
This state is either STARTED or STOPPED.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/debug/profiler
**Example response**:
.. sourcecode:: javascript
{
"state": "STARTED"
}
"""
monitor_enabled = self.session.config.get_resource_monitor_enabled()
state = "STARTED" if (monitor_enabled and self.session.lm.resource_monitor.profiler_running) else "STOPPED"
return json.dumps({"state": state})
def render_PUT(self, request):
"""
.. http:put:: /debug/profiler
A PUT request to this endpoint starts the profiler.
**Example request**:
.. sourcecode:: none
curl -X PUT http://localhost:8085/debug/profiler
**Example response**:
.. sourcecode:: javascript
{
"success": "true"
}
"""
self.session.lm.resource_monitor.start_profiler()
return json.dumps({"success": True})
def render_DELETE(self, request):
"""
.. http:delete:: /debug/profiler
A PUT request to this endpoint stops the profiler.
**Example request**:
.. sourcecode:: none
curl -X DELETE http://localhost:8085/debug/profiler
**Example response**:
.. sourcecode:: javascript
{
"success": "true"
}
"""
file_path = self.session.lm.resource_monitor.stop_profiler()
return json.dumps({"success": True, "profiler_file": file_path})
|
Captain-Coder/tribler
|
Tribler/Core/Modules/restapi/debug_endpoint.py
|
Python
|
lgpl-3.0
| 18,160
|
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import * as React from 'react';
import HomePageSelect from '../../../components/controls/HomePageSelect';
import DocTooltip from '../../../components/docs/DocTooltip';
import { translate } from '../../../helpers/l10n';
import { isSonarCloud } from '../../../helpers/system';
import { hasPrivateAccess, isPaidOrganization } from '../../../helpers/organizations';
interface Props {
currentUser: T.CurrentUser;
organization: T.Organization;
userOrganizations: T.Organization[];
}
export default function OrganizationNavigationMeta({
currentUser,
organization,
userOrganizations
}: Props) {
const onSonarCloud = isSonarCloud();
return (
<div className="navbar-context-meta">
{organization.url != null && (
<a
className="spacer-right text-limited"
href={organization.url}
rel="nofollow"
title={organization.url}>
{organization.url}
</a>
)}
{onSonarCloud &&
isPaidOrganization(organization) &&
hasPrivateAccess(currentUser, organization, userOrganizations) && (
<DocTooltip
className="spacer-right"
doc={import(/* webpackMode: "eager" */ 'Docs/tooltips/organizations/subscription-paid-plan.md')}>
<div className="outline-badge">{translate('organization.paid_plan.badge')}</div>
</DocTooltip>
)}
<div className="text-muted">
<strong>{translate('organization.key')}:</strong> {organization.key}
</div>
{onSonarCloud && (
<div className="navbar-context-meta-secondary">
<HomePageSelect currentPage={{ type: 'ORGANIZATION', organization: organization.key }} />
</div>
)}
</div>
);
}
|
Godin/sonar
|
server/sonar-web/src/main/js/apps/organizations/navigation/OrganizationNavigationMeta.tsx
|
TypeScript
|
lgpl-3.0
| 2,566
|
#ifndef SQLTABLEMODEL_H
#define SQLTABLEMODEL_H
#include <QSqlTableModel>
//------------------------------------------------------------------------------
namespace Patient {
// Table name:
extern const QString TableName;
// Field names:
extern const QString Id;
extern const QString LastName;
extern const QString FirstName;
extern const QString MiddleName;
extern const QString BirthDate;
extern const QString Sex;
extern const QString Addresses;
extern const QString Phones;
extern const QString Job;
extern const QString Post;
extern const QString PassportSeries;
extern const QString PassportNumber;
extern const QString PassportIssueDate;
extern const QString PassportIssuingAuthority;
extern const QString PassportPersonalNumber;
extern const QString AdditionalInformation;
}
//------------------------------------------------------------------------------
namespace ReadablePatient {
// Readable field names:
extern const char *LastName;
extern const char *FirstName;
extern const char *MiddleName;
}
//------------------------------------------------------------------------------
class SqlTableModel : public QSqlTableModel
{
Q_OBJECT
public:
//-explicit SqlTableModel(QObject *parent = 0);
explicit SqlTableModel(const QString &tableName,
QObject *parent = 0); //-! 2 explicit - это нормально?
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class PatientSqlTableModel : public SqlTableModel
{
Q_OBJECT
public:
explicit PatientSqlTableModel(QObject *parent = 0);
/*-explicit PatientSqlTableModel(const QString &tableName,
QObject *parent = 0);-*/
};
//------------------------------------------------------------------------------
#endif // SQLTABLEMODEL_H
|
IvanKosik/LA
|
Sources/SqlTableModel.h
|
C
|
lgpl-3.0
| 1,999
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cz.milik.nmcalc;
import cz.milik.nmcalc.utils.IMonad;
import java.util.Objects;
/**
*
* @author jan
*/
public class SymbolValue extends StringValue {
public SymbolValue(String value) {
super(value);
}
@Override
public boolean isSymbol() {
return true;
}
@Override
public String getRepr(ReprContext ctx) {
if (isIdent()) {
return "'" + getValue();
}
return "'$" + getValue();
}
@Override
public String getExprRepr(ReprContext ctx) {
if (isIdent()) {
return getValue();
}
return "$" + getValue();
}
@Override
public <T, U> T visit(ICalcValueVisitor<T, U> visitor, U context) {
return visitor.visitSymbol(this, context);
}
@Override
public Context eval(Context ctx) {
IMonad<ICalcValue> value = ctx.getVariable(getValue());
value.orValue(
() -> ErrorValue.formatted("Undefined variable: %s.", getValue())
).bind(val -> {
ctx.setReturnedValue(val);
});
return ctx;
}
@Override
protected Context unapplyInner(Context ctx, ICalcValue value) throws NMCalcException {
if (Objects.equals(getValue(), "_")) {
ctx.setReturnedValue(CalcValue.some(CalcValue.list()));
return ctx;
}
ICalcValue varValue = ctx.getVariable(getValue()).unwrap();
if (varValue == null) {
ctx.setVariable(getValue(), value);
ctx.setReturnedValue(CalcValue.some(CalcValue.list()));
return ctx;
}
return varValue.unapply(ctx, value);
}
public boolean isIdent() {
if (isKeyword()) {
return false;
}
return getValue().codePoints().allMatch(c -> Character.isJavaIdentifierPart(c));
}
}
|
nnen/nmcalc
|
src/main/java/cz/milik/nmcalc/SymbolValue.java
|
Java
|
lgpl-3.0
| 2,092
|
///<reference path='../definitions/JQuery.d.ts'/>
///<reference path='GetNextFreeId.ts'/>
///<reference path='IEntity.ts'/>
///<reference path='IWalkableList.ts'/>
///<reference path='IObservableRepository.ts'/>
module VjsPluginComponents {
//This Walkable list implementation includes everything stored in the underlying repository.
export class WalkableList implements IWalkableList {
_objects: IEntity[];
_index: number;
_repository: IObservableRepository;
_sortFunction: (a, b) => number;
_filterFunction: (a: any) => boolean;
constructor(sortFunction: (a, b) => number, filterFunction: (a: any) => boolean, repository: IObservableRepository) {
this._index = 0;
this._objects = [];
this._repository = repository;
this._sortFunction = sortFunction;
this._filterFunction = filterFunction;
this.updateLocalArray();
this._repository.on("create", () => {
this.updateLocalArray();
});
this._repository.on("remove", () => {
this.updateLocalArray();
});
}
updateLocalArray() {
this._objects = jQuery.grep(this._repository.toList(),this._filterFunction).sort(this._sortFunction);
}
getCurrent() {
return this._objects[this._index];
}
moveNext() {
this._index++;
}
hasNext() {
return (this._index < this._objects.length)
}
isFinished() {
return (this._index >= this._objects.length)
}
/**
* resets the list to the first point upon which the condition is met.
* @param {function(object:any) => number} condition
* @param {(args) => void} handler
* @param {string} boundaryType describes when the event should be triggered.
* Valid inputs are: "point","approach" and "depart". "point"
* triggers whenever the time is played. "approach" only
* triggers when the time up to that point is played.
* "depart" only triggers when the time after the point is
* played.
* @param {integer} maxCallCount
*/
reset(condition: (object) => boolean) {
this._index = 0;
while (this.hasNext() && !condition(this._objects[this._index])) {
this.moveNext();
}
}
add(object: IEntity) {
return this._repository.create(object);
}
removeCurrent() {
this._repository.remove(this._objects[this._index].id)
}
update(object: IEntity) {
this._repository.update(object);
}
remove(id: number) {
return this._repository.remove(id);
}
/* Look into using this instead of general updates if performance is slow.
As always, code optization later.
private insertSingleEvent(event: ISinglePointEvent) {
this._handlersToTrigger = this.insert(event,
this._handlersToTrigger,
(a, b) => {
//A appears after B when positive
if ((a.time - b.time) == 0) {
return this.getBoundaryOrdering(a.boundaryType) - this.getBoundaryOrdering(b.boundaryType);
} else {
return a.time - b.time;
}
});
}
private getBoundaryOrdering(boundaryType: string): number {
switch(boundaryType.toLowerCase()) {
case "approach":
return 0;
case "point":
return 1;
case "depart":
return 2;
default:
throw Error("Invalid boundary type entered: " + boundaryType);
}
}
private insert(element, array, comparer) {
array.splice(this.locationOf(element, array, comparer), 0, element);
return array;
}
private locationOf(element, array, comparer, start?: number = 0, end?: number): number {
if (typeof (end) === 'undefined') {
end = array.length - 1;
}
var pivot: number = Math.floor(start + (end - start) / 2);
if (!(array[pivot]) || comparer(element, array[pivot]) == 0) return pivot;
if (comparer(element, array[pivot]) > 0) {
if (pivot == end) return (pivot + 1);
return this.locationOf(element, array, comparer, pivot + 1, end);
} else {
if (pivot == start) return (pivot);
return this.locationOf(element, array, comparer, start, pivot - 1);
}
} */
}
}
|
Axonn/videojs-plugin-components
|
src/ts/WalkableList.ts
|
TypeScript
|
lgpl-3.0
| 4,738
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns='http://www.w3.org/1999/xhtml' lang='he' dir='rtl'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=windows-1255' />
<meta http-equiv='Content-Script-Type' content='text/javascript' />
<meta http-equiv='revisit-after' content='15 days' />
<link rel='stylesheet' href='../../../_script/klli.css' />
<link rel='stylesheet' href='../../_themes/klli.css' />
<title>úîø áú ãåã</title>
<meta name='author' content="øòðï" />
<meta name='receiver' content="" />
<meta name='jmQovc' content="tnk1/dmut/dmut/783" />
<meta name='tvnit' content="tnk_dmut" />
<meta name='description' lang='he' content="úîø áú ãåã" />
<meta name='description' lang='en' content="this page is in Hebrew" />
<meta name='keywords' lang='he' content="úîø (áú ãåã),úîø áú ãåã" />
</head><body class="dmwt"><div class="pnim">
<script type='text/javascript' src='../../../_script/vars.js'></script>
<!--NiwutElyon0-->
<div class="NiwutElyon">
<div class="NiwutElyon"><a href='../../index.html'>øàùé</a>><a href='../../dmut/index.html'>ãîåéåú úðëéåú</a>><a href='../../dmut/ToknLfiDmutHkl.html'>ëì äãîåéåú</a>><a href='../../dmut/jm/tmr.html'>úîø</a>></div>
</div>
<!--NiwutElyon1-->
<h1 id='h1'>úîø áú ãåã</h1>
<div style='display:none'>
<p>îàú: øòðï
<p>÷åã: úîø (áú ãåã)
</div>
<script type='text/javascript'>kotrt()</script>
<!--tosft0--><div id='tosft'>
<p>
<ol>
<li>ùî"á éâ 1: åéäé àçøé ëï åìàáùìåí áï ãåã àçåú éôä åùîä úîø åéàäáä àîðåï áï ãåã. </ol>
<p>
<q class="psuq">äòøä: </q>úîø äéà áúå ùì ãåã, ùäøé äéà ð÷øàú àçåúå ùì àîðåï áï ãåã (ôñ' 5, 6, 7, 8, 10, 11, 12, 20), åëï ð÷øàú "áú äîìê" (ôñ' 18).
<p>
<q class="psuq">àá: </q>
<a href='692.html'>ãåã </a>
<p>
<q class="psuq">àí: </q>
<a href='701.html'>îòëä </a>
<p>
<q class="psuq">àçéí îàá åàí: </q>
<a href='702.html'>àáùìåí </a>
</div><!--tosft--><!--tosft1-->
<ul id='ulbnim' style='display:none'>
<li>îàîø: <a href='../../messages/nvir_jmuelb_amnon_wtmr_2_0.html' class="mamr">äàí áäëøç àðñ àîðåï àú úîø?<small> / ùéøé -> shiri-21 @ bezeqint.net</small></a>
<li>îàîø: <a href='../../nvir/jmuelb/amnon_wtmr.html' class="mamr">äàí úîø àäáä àú àîðåï?<small> / éãéãéä öå÷øîï, àøàì -> ôå"ñ 8</small></a>
<li>îàîø: <a href='../../nvir/jmuelb/amnon_wtmr_2.html' class="mamr">äéôéí åäúðëééí - àîðåï åúîø<small> / òéãéú -> ëôéú ùáè ñà</small></a>
<li>îàîø: <a href='../../../axrimpl/hydepark/709713_1.html' class='mamr' target='_blank'>ùåøù ùðàú àîðåï ìúîø åöòøä<small> / îçáøéí ùåðéí -> "òöåø ëàï çåùáéí"</small></a>
</ul><!--end-->
<script type='text/javascript'>
var theBnim = document.getElementById('ulbnim');
var theBnimArray = theBnim.innerHTML.split(/<li>/i);
var theWrittenBnim = new Array(theBnimArray.length);
</script>
<div class='awsp_mpwrt'>
<div class="noseim">
<script type='text/javascript'>ktov_bnim('<h2>ñôøéí</h2> <ol class="TableSublists"> ', 'ñôø:', ' </ol> ')</script>
<script type='text/javascript'>ktov_bnim('<h2>ðåùàéí</h2> <ol class="TableSublists"> ', 'àåñó:', ' </ol> ')</script>
</div>
<script type='text/javascript'>ktov_bnim('<div class="omnutiim"> <h2>îàîøéí ãîéåðééí åàîðåúééí</h2> <ol class="TableSublists"> ', '(îàîø ãîéåðé|ñéôåø|ùéø|öéåø):', ' </ol> </div>')</script>
<script type='text/javascript'>ktov_bnim('<div class="jelot"> <h2>ùàìåú åîàîøéí ìà âîåøéí</h2> <ol class="TableSublists"> ', '(îàîø ìà âîåø|îàîø ùìà ôåøñí|ùàìä):', ' </ol> </div>')</script>
<script type='text/javascript'>ktov_bnim('<div class="mamrim"> <h2>îàîøéí</h2> <ol class="TableSublists"> ', '(àúø|äáãìéí|îàîø|îáðä|îöâú|÷åáõ|ëìì|äâãøä):', ' </ol> </div>')</script>
</div>
<br style='clear:all'>
<h2 id='tguvot'>úåñôåú åúâåáåú</h2>
<ul class="tablesublists">
<script type='text/javascript'>ktov_bnim_axrim()</script>
</ul>
<script type='text/javascript'>tguva(); txtit()</script>
</div><!--pnim-->
</body></html>
|
erelsgl/erel-sites
|
tnk1/dmut/dmut/783.html
|
HTML
|
lgpl-3.0
| 3,950
|
package cn.basics.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* @ClassName: RedisUtil
* @Description: TODO(Redis连接池工具)
* @author zhiqiang94@vip.qq.com (苟志强)
* @date 2017-8-23 下午5:11:57
*/
public class RedisUtil {
/**私有构造函数 使类禁止实例化*/
private RedisUtil(){}
/**Redis服务器IP*/
private static final String redis_path = "localhost";
/**Redis端口号*/
private static final int redis_port = 6379;
/**Redis访问密码*/
// private static final String redis_pwd = "";
/**连接实例的最大数目*/ //可用连接实例的最大数目,默认值为8;如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static final int max_total = 300;
/**最大空闲实例*/ //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static final int max_idle = 100;
/**等待可用连接的最大时间*/ //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
private static final int max_wait = 10000;
/**Redis对象实例关闭时间*/
private static int out_time = 10000;
//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean test_on_borrow = true;
/**Redis连接池*/
private static JedisPool jedisPool = null;
/**初始化Redis连接池*/
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(max_total);
config.setMaxIdle(max_idle);
config.setMaxWaitMillis(max_wait);
config.setTestOnBorrow(test_on_borrow);
//需要访问密码的
// jedisPool = new JedisPool(config, redis_path, redis_port, out_time,redis_pwd);
jedisPool = new JedisPool(config, redis_path, redis_port, out_time);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Title: getJedis
* @Description: TODO(获取Jedis实例)
* @author zhiqiang94@vip.qq.com (苟志强)
* @date 2017-8-23 下午4:49:04
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
System.out.println("【Redis/Jedis】获取Jedis实例成功!");
return resource;
}
} catch (Exception e) {
System.out.println("【Redis/Jedis】"+e.toString());
}
System.out.println("【Redis/Jedis】获取Jedis实例失败!");
return null;
}
/**
* @Title: returnResource
* @Description: TODO(释放jedis)
* @author zhiqiang94@vip.qq.com (苟志强)
* @date 2017-8-23 下午4:49:11
* @param jedis
*/
public static void close(final Jedis jedis) {
jedis.close();
System.out.println("【Redis/Jedis】释放Jedis。");
}
public static void main(String[] args) {
RedisUtil.getJedis().set("a", "abc321");
RedisUtil.getJedis().set("newname", "中文测试");
System.out.println(RedisUtil.getJedis().get("a"));
System.out.println(RedisUtil.getJedis().get("newname"));
System.out.println(RedisUtil.getJedis().get("mykey"));
}
}
|
zhiqiang94/BasicsProject
|
src/main/java/cn/basics/util/RedisUtil.java
|
Java
|
lgpl-3.0
| 3,261
|
<?php
namespace pocketmine\entity\monster\walking;
use pocketmine\entity\monster\WalkingMonster;
use pocketmine\entity\Entity;
use pocketmine\item\GoldSword;
use pocketmine\nbt\tag\IntTag;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\entity\EntityDamageByEntityEvent;
use pocketmine\item\Item;
use pocketmine\entity\Creature;
use pocketmine\network\protocol\MobEquipmentPacket;
use pocketmine\Player;
class PigZombie extends WalkingMonster{
const NETWORK_ID = 36;
private $angry = 0;
public $width = 0.72;
public $height = 1.8;
public $eyeHeight = 1.62;
public function getSpeed(){
return 1.15;
}
public function initEntity(){
parent::initEntity();
if(isset($this->namedtag->Angry)){
$this->angry = (int) $this->namedtag["Angry"];
}
$this->fireProof = true;
$this->setDamage([0, 5, 9, 13]);
}
public function saveNBT(){
parent::saveNBT();
$this->namedtag->Angry = new IntTag("Angry", $this->angry);
}
public function getName(){
return "PigZombie";
}
public function isAngry(){
return $this->angry > 0;
}
public function setAngry(int $val){
$this->angry = $val;
}
public function targetOption(Creature $creature, float $distance){
return $this->isAngry() && parent::targetOption($creature, $distance);
}
public function attack($damage, EntityDamageEvent $source){
parent::attack($damage, $source);
if(!$source->isCancelled()){
$this->setAngry(1000);
}
}
public function spawnTo(Player $player){
parent::spawnTo($player);
$pk = new MobEquipmentPacket();
$pk->eid = $this->getId();
$pk->item = new GoldSword();
$pk->slot = 10;
$pk->selectedSlot = 10;
$player->dataPacket($pk);
}
public function attackEntity(Entity $player){
if($this->attackDelay > 10 && $this->distanceSquared($player) < 1.44){
$this->attackDelay = 0;
$ev = new EntityDamageByEntityEvent($this, $player, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $this->getDamage());
$player->attack($ev->getFinalDamage(), $ev);
}
}
public function getDrops(){
$drops = [];
if($this->lastDamageCause instanceof EntityDamageByEntityEvent){
switch(mt_rand(0, 2)){
case 0:
$drops[] = Item::get(Item::FLINT, 0, 1);
break;
case 1:
$drops[] = Item::get(Item::GUNPOWDER, 0, 1);
break;
case 2:
$drops[] = Item::get(Item::REDSTONE_DUST, 0, 1);
break;
}
}
return $drops;
}
}
|
Apollo-SoftwareTeam/Apollo-Legacy
|
src/pocketmine/entity/monster/walking/PigZombie.php
|
PHP
|
lgpl-3.0
| 2,402
|
--- @type RCLootCouncil
local addon = select(2, ...)
local name = "IconBordered"
local Object = {}
-- varargs: texture
function Object:New(parent, name, texture)
local b = addon.UI.CreateFrame("Button", name, parent, "BackdropTemplate")
b:SetSize(40,40)
b:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")
b:GetHighlightTexture():SetBlendMode("ADD")
b:SetNormalTexture(texture or "Interface\\InventoryItems\\WoWUnknownItem01")
b:GetNormalTexture():SetDrawLayer("BACKGROUND")
b:GetNormalTexture():SetVertexColor(1,1,1)
b:SetBackdrop({
bgFile = "",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
edgeSize = 18,
})
b:SetScript("OnLeave", addon.UI.HideTooltip)
b:EnableMouse(true)
b:RegisterForClicks("AnyUp")
b.SetBorderColor = self.SetBorderColor
b.Desaturate = self.Desaturate
return b
end
function Object:SetBorderColor(color)
if color == "green" then
self:SetBackdropBorderColor(0,1,0,1) -- green
self:GetNormalTexture():SetVertexColor(0.8,0.8,0.8)
elseif color == "yellow" then
self:SetBackdropBorderColor(1,1,0,1) -- yellow
self:GetNormalTexture():SetVertexColor(1,1,1)
elseif color == "grey" or color == "gray" then
self:SetBackdropBorderColor(0.75,0.75,0.75,1)
self:GetNormalTexture():SetVertexColor(1,1,1)
elseif color == "red" then
self:SetBackdropBorderColor(1,0,0,1)
self:GetNormalTexture():SetVertexColor(1,1,1)
elseif color == "purple" then
self:SetBackdropBorderColor(0.65,0.4,1,1)
self:GetNormalTexture():SetVertexColor(1,1,1)
else -- Default to white
self:SetBackdropBorderColor(1,1,1,1) -- white
self:GetNormalTexture():SetVertexColor(0.5,0.5,0.5)
end
end
function Object:Desaturate()
return self:GetNormalTexture():SetDesaturated(true)
end
addon.UI:RegisterElement(Object, name)
|
evil-morfar/RCLootCouncil2
|
UI/Widgets/IconBordered.lua
|
Lua
|
lgpl-3.0
| 1,869
|
/**
* Kopernicus Planetary System Modifier
* ====================================
* Created by: BryceSchroeder and Teknoman117 (aka. Nathaniel R. Lewis)
* Maintained by: Thomas P., NathanKell and KillAshley
* Additional Content by: Gravitasi, aftokino, KCreator, Padishar, Kragrathea, OvenProofMars, zengei, MrHappyFace, Sigma88
* -------------------------------------------------------------
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*
* This library is intended to be used as a plugin for Kerbal Space Program
* which is copyright 2011-2015 Squad. Your usage of Kerbal Space Program
* itself is governed by the terms of its EULA, not the license above.
*
* https://kerbalspaceprogram.com
*/
using System;
using UnityEngine;
namespace Kopernicus
{
namespace Configuration
{
namespace ModLoader
{
[RequireConfigType(ConfigType.Node)]
public class VertexSimplexMultiChromatic : ModLoader<PQSMod_VertexSimplexMultiChromatic>
{
// The frequency of the alpha noise
[ParserTarget("alphaFrequency")]
public NumericParser<double> alphaFrequency
{
get { return mod.alphaFrequency; }
set { mod.alphaFrequency = value; }
}
// Octaves of the alpha noise
[ParserTarget("alphaOctaves")]
public NumericParser<double> alphaOctaves
{
get { return mod.alphaOctaves; }
set { mod.alphaOctaves = value; }
}
// Persistence of the alpha noise
[ParserTarget("alphaPersistence")]
public NumericParser<double> alphaPersistence
{
get { return mod.alphaPersistence; }
set { mod.alphaPersistence = value; }
}
// The seed of the alpha noise
[ParserTarget("alphaSeed")]
public NumericParser<int> alphaSeed
{
get { return mod.alphaSeed; }
set { mod.alphaSeed = value; }
}
// Amount of color that will be applied
[ParserTarget("blend")]
public NumericParser<float> blend
{
get { return mod.blend; }
set { mod.blend = value; }
}
// The frequency of the blue noise
[ParserTarget("blueFrequency")]
public NumericParser<double> blueFrequency
{
get { return mod.blueFrequency; }
set { mod.blueFrequency = value; }
}
// Octaves of the blue noise
[ParserTarget("blueOctaves")]
public NumericParser<double> blueOctaves
{
get { return mod.blueOctaves; }
set { mod.blueOctaves = value; }
}
// Persistence of the blue noise
[ParserTarget("bluePersistence")]
public NumericParser<double> bluePersistence
{
get { return mod.bluePersistence; }
set { mod.bluePersistence = value; }
}
// The seed of the blue noise
[ParserTarget("blueSeed")]
public NumericParser<int> blueSeed
{
get { return mod.blueSeed; }
set { mod.blueSeed = value; }
}
// The frequency of the green noise
[ParserTarget("greenFrequency")]
public NumericParser<double> greenFrequency
{
get { return mod.greenFrequency; }
set { mod.greenFrequency = value; }
}
// Octaves of the green noise
[ParserTarget("greenOctaves")]
public NumericParser<double> greenOctaves
{
get { return mod.greenOctaves; }
set { mod.greenOctaves = value; }
}
// Persistence of the green noise
[ParserTarget("greenPersistence")]
public NumericParser<double> greenPersistence
{
get { return mod.greenPersistence; }
set { mod.greenPersistence = value; }
}
// The seed of the green noise
[ParserTarget("greenSeed")]
public NumericParser<int> greenSeed
{
get { return mod.greenSeed; }
set { mod.greenSeed = value; }
}
// The frequency of the red noise
[ParserTarget("redFrequency")]
public NumericParser<double> redFrequency
{
get { return mod.redFrequency; }
set { mod.redFrequency = value; }
}
// Octaves of the red noise
[ParserTarget("redOctaves")]
public NumericParser<double> redOctaves
{
get { return mod.redOctaves; }
set { mod.redOctaves = value; }
}
// Persistence of the red noise
[ParserTarget("redPersistence")]
public NumericParser<double> redPersistence
{
get { return mod.redPersistence; }
set { mod.redPersistence = value; }
}
// The seed of the red noise
[ParserTarget("redSeed")]
public NumericParser<int> redSeed
{
get { return mod.redSeed; }
set { mod.redSeed = value; }
}
}
}
}
}
|
Kerbas-ad-astra/Kopernicus
|
Kopernicus/Kopernicus/Configuration/ModLoader/VertexSimplexMultiChromatic.cs
|
C#
|
lgpl-3.0
| 6,753
|
\hypertarget{celltriang_8h}{}\subsection{celltriang.\+h File Reference}
\label{celltriang_8h}\index{celltriang.\+h@{celltriang.\+h}}
Background cells for integration.
{\ttfamily \#include \char`\"{}L\+M\+X/cofe\+\_\+\+Tensor\+Rank2.\+h\char`\"{}}\\*
{\ttfamily \#include \char`\"{}cell.\+h\char`\"{}}\\*
Include dependency graph for celltriang.\+h\+:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=350pt]{d5/d0e/celltriang_8h__incl}
\end{center}
\end{figure}
This graph shows which files directly or indirectly include this file\+:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=317pt]{d3/d7d/celltriang_8h__dep__incl}
\end{center}
\end{figure}
\subsubsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{classmknix_1_1_cell_triang}{mknix\+::\+Cell\+Triang}
\end{DoxyCompactItemize}
\subsubsection*{Namespaces}
\begin{DoxyCompactItemize}
\item
\hyperlink{namespacemknix}{mknix}
\end{DoxyCompactItemize}
\subsubsection{Detailed Description}
Background cells for integration.
\begin{DoxyAuthor}{Author}
Daniel Iglesias
\end{DoxyAuthor}
|
daniel-iglesias/mknix
|
doc/latex/dc/d6a/celltriang_8h.tex
|
TeX
|
lgpl-3.0
| 1,129
|
<?php
/*
*
* _____ _ _____
* / ____| (_) | __ \
*| | __ ___ _ __ _ ___ _ _ ___| |__) | __ ___
*| | |_ |/ _ \ '_ \| / __| | | / __| ___/ '__/ _ \
*| |__| | __/ | | | \__ \ |_| \__ \ | | | | (_) |
* \_____|\___|_| |_|_|___/\__, |___/_| |_| \___/
* __/ |
* |___/
*
* This program 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.
*
* @author GenisysPro
* @link https://github.com/GenisysPro/GenisysPro
*
*
*/
namespace pocketmine\entity;
use pocketmine\network\mcpe\protocol\AddEntityPacket;
use pocketmine\Player;
class Vex extends Monster {
const NETWORK_ID = 105;
public $width = 0.6;
public $length = 0.6;
public $height = 0;
public $dropExp = [5, 5];
/**
* @return string
*/
public function getName(){
return "Vex";
}
public function initEntity(){
$this->setMaxHealth(14);
parent::initEntity();
}
/**
* @param Player $player
*/
public function spawnTo(Player $player){
$pk = new AddEntityPacket();
$pk->eid = $this->getId();
$pk->type = Vex::NETWORK_ID;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->speedX = $this->motionX;
$pk->speedY = $this->motionY;
$pk->speedZ = $this->motionZ;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$pk->metadata = $this->dataProperties;
$player->dataPacket($pk);
parent::spawnTo($player);
}
}
|
Nekiechan/NekoMine-MP
|
src/pocketmine/entity/Vex.php
|
PHP
|
lgpl-3.0
| 1,697
|
<?php
// field labels
$fieldLabelsvw_feedspec = array();
$fieldLabelsvw_feedspec["English"]=array();
$fieldLabelsvw_feedspec["English"]["FeedID"] = "Feed ID";
$fieldLabelsvw_feedspec["English"]["Technology"] = "Technology";
$fieldLabelsvw_feedspec["English"]["Stage"] = "Stage";
$fieldLabelsvw_feedspec["English"]["FCountryID"] = "FCountry ID";
$fieldLabelsvw_feedspec["English"]["FIDSourceID"] = "FIDSource ID";
$fieldLabelsvw_feedspec["English"]["FeedTypeID"] = "Feed Type ID";
$fieldLabelsvw_feedspec["English"]["SpeciesID"] = "Species ID";
$fieldLabelsvw_feedspec["English"]["Hybrid"] = "Hybrid";
$fieldLabelsvw_feedspec["English"]["Variety"] = "Variety";
$fieldLabelsvw_feedspec["English"]["Family"] = "Family";
$fieldLabelsvw_feedspec["English"]["Group"] = "Group";
$fieldLabelsvw_feedspec["English"]["Genus"] = "Genus";
$fieldLabelsvw_feedspec["English"]["Environment"] = "Environment";
$fieldLabelsvw_feedspec["English"]["Country"] = "Country";
$fieldLabelsvw_feedspec["English"]["Feed"] = "Feed Name";
$fieldLabelsvw_feedspec["English"]["Brand"] = "Brand";
$fieldLabelsvw_feedspec["English"]["Feed_Year"] = "Feed Year";
$fieldLabelsvw_feedspec["English"]["Country_Origin"] = "Country Origin";
$fieldLabelsvw_feedspec["English"]["Details"] = "Details";
$fieldLabelsvw_feedspec["English"]["Data_Source"] = "Data Source";
$fieldLabelsvw_feedspec["English"]["Type"] = "Feed Type";
$fieldLabelsvw_feedspec["English"]["Species_Name"] = "Species Name";
$fieldLabelsvw_feedspec["English"]["Common_Name"] = "Common Name";
$fieldLabelsvw_feedspec["English"]["Habit"] = "Feeding Habit";
$fieldLabelsvw_feedspec["English"]["Species_Year"] = "Species Year";
$tdatavw_feedspec=array();
$tdatavw_feedspec[".NumberOfChars"]=80;
$tdatavw_feedspec[".ShortName"]="vw_feedspec";
$tdatavw_feedspec[".OwnerID"]="";
$tdatavw_feedspec[".OriginalTable"]="vw_feedspec";
$keys=array();
$keys[]="FeedID";
$tdatavw_feedspec[".Keys"]=$keys;
// FeedID
$fdata = array();
$fdata["Label"]="Feed ID";
$fdata["FieldType"]= 3;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "FeedID";
$fdata["FullName"]= "FeedID";
$fdata["Index"]= 1;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["FeedID"]=$fdata;
// Feed
$fdata = array();
$fdata["Label"]="Feed Name";
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Lookup wizard";
$fdata["ViewFormat"]= "";
$fdata["LookupType"]=1;
$fdata["LinkField"]="`FName`";
$fdata["LinkFieldType"]=200;
$fdata["DisplayField"]="`FName`";
$fdata["LookupTable"]="vw_feedspec";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Feed";
$fdata["FullName"]= "FName";
$fdata["Index"]= 2;
$fdata["FieldPermissions"]=true;
$fdata["ListPage"]=true;
$tdatavw_feedspec["Feed"]=$fdata;
// Brand
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Brand";
$fdata["FullName"]= "BrandName";
$fdata["Index"]= 3;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Brand"]=$fdata;
// Technology
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Technology";
$fdata["FullName"]= "Technology";
$fdata["Index"]= 4;
$fdata["EditParams"]="";
$fdata["EditParams"].= " maxlength=200";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Technology"]=$fdata;
// Feed Year
$fdata = array();
$fdata["FieldType"]= 3;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Feed_Year";
$fdata["FullName"]= "FeedYear";
$fdata["Index"]= 5;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Feed Year"]=$fdata;
// Stage
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Stage";
$fdata["FullName"]= "Stage";
$fdata["Index"]= 6;
$fdata["EditParams"]="";
$fdata["EditParams"].= " maxlength=200";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Stage"]=$fdata;
// FCountryID
$fdata = array();
$fdata["Label"]="FCountry ID";
$fdata["FieldType"]= 3;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "FCountryID";
$fdata["FullName"]= "FCountryID";
$fdata["Index"]= 7;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["FCountryID"]=$fdata;
// Country Origin
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Country_Origin";
$fdata["FullName"]= "CountryOrigin";
$fdata["Index"]= 8;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$fdata["ListPage"]=true;
$tdatavw_feedspec["Country Origin"]=$fdata;
// FIDSourceID
$fdata = array();
$fdata["Label"]="FIDSource ID";
$fdata["FieldType"]= 3;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "FIDSourceID";
$fdata["FullName"]= "FIDSourceID";
$fdata["Index"]= 9;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["FIDSourceID"]=$fdata;
// Details
$fdata = array();
$fdata["FieldType"]= 13;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Details";
$fdata["FullName"]= "FisDetail";
$fdata["Index"]= 10;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Details"]=$fdata;
// Data Source
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Data_Source";
$fdata["FullName"]= "FDataSource";
$fdata["Index"]= 11;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$fdata["ListPage"]=true;
$tdatavw_feedspec["Data Source"]=$fdata;
// FeedTypeID
$fdata = array();
$fdata["Label"]="Feed Type ID";
$fdata["FieldType"]= 3;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "FeedTypeID";
$fdata["FullName"]= "FeedTypeID";
$fdata["Index"]= 12;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["FeedTypeID"]=$fdata;
// Type
$fdata = array();
$fdata["Label"]="Feed Type";
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Type";
$fdata["FullName"]= "FeedType";
$fdata["Index"]= 13;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$fdata["ListPage"]=true;
$tdatavw_feedspec["Type"]=$fdata;
// SpeciesID
$fdata = array();
$fdata["Label"]="Species ID";
$fdata["FieldType"]= 3;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "SpeciesID";
$fdata["FullName"]= "SpeciesID";
$fdata["Index"]= 14;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["SpeciesID"]=$fdata;
// Species Name
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Lookup wizard";
$fdata["ViewFormat"]= "";
$fdata["LookupType"]=1;
$fdata["LinkField"]="`SpecName`";
$fdata["LinkFieldType"]=200;
$fdata["DisplayField"]="`SpecName`";
$fdata["LookupTable"]="vw_feedspec";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Species_Name";
$fdata["FullName"]= "SpecName";
$fdata["Index"]= 15;
$fdata["FieldPermissions"]=true;
$fdata["ListPage"]=true;
$tdatavw_feedspec["Species Name"]=$fdata;
// Common Name
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Common_Name";
$fdata["FullName"]= "CommonName";
$fdata["Index"]= 16;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Common Name"]=$fdata;
// Hybrid
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Hybrid";
$fdata["FullName"]= "Hybrid";
$fdata["Index"]= 17;
$fdata["EditParams"]="";
$fdata["EditParams"].= " maxlength=200";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Hybrid"]=$fdata;
// Variety
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Variety";
$fdata["FullName"]= "Variety";
$fdata["Index"]= 18;
$fdata["EditParams"]="";
$fdata["EditParams"].= " maxlength=200";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Variety"]=$fdata;
// Family
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Family";
$fdata["FullName"]= "Family";
$fdata["Index"]= 19;
$fdata["EditParams"]="";
$fdata["EditParams"].= " maxlength=200";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Family"]=$fdata;
// Group
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Group";
$fdata["FullName"]= "`Group`";
$fdata["Index"]= 20;
$fdata["EditParams"]="";
$fdata["EditParams"].= " maxlength=200";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Group"]=$fdata;
// Genus
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Genus";
$fdata["FullName"]= "Genus";
$fdata["Index"]= 21;
$fdata["EditParams"]="";
$fdata["EditParams"].= " maxlength=200";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Genus"]=$fdata;
// Environment
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Environment";
$fdata["FullName"]= "Environment";
$fdata["Index"]= 22;
$fdata["EditParams"]="";
$fdata["EditParams"].= " maxlength=200";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Environment"]=$fdata;
// Habit
$fdata = array();
$fdata["Label"]="Feeding Habit";
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Habit";
$fdata["FullName"]= "FeedHabit";
$fdata["Index"]= 23;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Habit"]=$fdata;
// Country
$fdata = array();
$fdata["FieldType"]= 200;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Country";
$fdata["FullName"]= "Country";
$fdata["Index"]= 24;
$fdata["EditParams"]="";
$fdata["EditParams"].= " maxlength=45";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Country"]=$fdata;
// Species Year
$fdata = array();
$fdata["FieldType"]= 3;
$fdata["EditFormat"]= "Text field";
$fdata["ViewFormat"]= "";
$fdata["NeedEncode"]=true;
$fdata["GoodName"]= "Species_Year";
$fdata["FullName"]= "SpecYear";
$fdata["Index"]= 25;
$fdata["EditParams"]="";
$fdata["FieldPermissions"]=true;
$tdatavw_feedspec["Species Year"]=$fdata;
$tables_data["vw_feedspec"]=&$tdatavw_feedspec;
$field_labels["vw_feedspec"] = &$fieldLabelsvw_feedspec;
?>
|
openfigis/affris
|
AFFRIS/affris/faofeed/include/vw_feedspec_settings.php
|
PHP
|
lgpl-3.0
| 12,558
|
package tv.superawesome.lib.sawebplayer;
import android.graphics.Bitmap;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class SAWebClient extends WebViewClient {
private Listener listener;
SAWebClient(Listener listener) {
this.listener = listener;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
listener.onPageStarted(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
listener.onPageFinished(view);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return listener.shouldOverrideUrlLoading(view, url);
}
interface Listener {
void onPageStarted (WebView view, String url);
void onPageFinished (WebView view);
boolean shouldOverrideUrlLoading (WebView webView, String url);
}
}
|
SuperAwesomeLTD/sa-mobile-lib-android-webplayer
|
sawebplayer/src/main/java/tv/superawesome/lib/sawebplayer/SAWebClient.java
|
Java
|
lgpl-3.0
| 1,008
|
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.rule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.assertj.core.groups.Tuple;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.DateUtils;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class ActiveRulesProviderTest {
private ActiveRulesProvider provider;
@Mock
private DefaultActiveRulesLoader loader;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
provider = new ActiveRulesProvider();
}
@Test
public void testCombinationOfRules() {
LoadedActiveRule r1 = mockRule("rule1");
LoadedActiveRule r2 = mockRule("rule2");
LoadedActiveRule r3 = mockRule("rule3");
List<LoadedActiveRule> qp1Rules = ImmutableList.of(r1, r2);
List<LoadedActiveRule> qp2Rules = ImmutableList.of(r2, r3);
List<LoadedActiveRule> qp3Rules = ImmutableList.of(r1, r3);
when(loader.load(eq("qp1"))).thenReturn(qp1Rules);
when(loader.load(eq("qp2"))).thenReturn(qp2Rules);
when(loader.load(eq("qp3"))).thenReturn(qp3Rules);
QualityProfiles profiles = mockProfiles("qp1", "qp2", "qp3");
ActiveRules activeRules = provider.provide(loader, profiles);
assertThat(activeRules.findAll()).hasSize(3);
assertThat(activeRules.findAll()).extracting("ruleKey").containsOnly(
RuleKey.of("rule1", "rule1"), RuleKey.of("rule2", "rule2"), RuleKey.of("rule3", "rule3"));
verify(loader).load(eq("qp1"));
verify(loader).load(eq("qp2"));
verify(loader).load(eq("qp3"));
verifyNoMoreInteractions(loader);
}
@Test
public void testParamsAreTransformed() {
LoadedActiveRule r1 = mockRule("rule1");
LoadedActiveRule r2 = mockRule("rule2");
r2.setParams(ImmutableMap.of("foo1", "bar1", "foo2", "bar2"));
List<LoadedActiveRule> qpRules = ImmutableList.of(r1, r2);
when(loader.load(eq("qp"))).thenReturn(qpRules);
QualityProfiles profiles = mockProfiles("qp");
ActiveRules activeRules = provider.provide(loader, profiles);
assertThat(activeRules.findAll()).hasSize(2);
assertThat(activeRules.findAll()).extracting("ruleKey", "params").containsOnly(
Tuple.tuple(RuleKey.of("rule1", "rule1"), ImmutableMap.of()),
Tuple.tuple(RuleKey.of("rule2", "rule2"), ImmutableMap.of("foo1", "bar1", "foo2", "bar2")));
verify(loader).load(eq("qp"));
verifyNoMoreInteractions(loader);
}
private static QualityProfiles mockProfiles(String... keys) {
List<QualityProfile> profiles = new LinkedList<>();
for (String k : keys) {
QualityProfile p = QualityProfile.newBuilder().setKey(k).setLanguage(k).setRulesUpdatedAt(DateUtils.formatDateTime(new Date())).build();
profiles.add(p);
}
return new QualityProfiles(profiles);
}
private static LoadedActiveRule mockRule(String name) {
LoadedActiveRule r = new LoadedActiveRule();
r.setName(name);
r.setRuleKey(RuleKey.of(name, name));
return r;
}
}
|
Godin/sonar
|
sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/ActiveRulesProviderTest.java
|
Java
|
lgpl-3.0
| 4,322
|
/*****************************************************************************
Copyright (c) 2010, Intel Corp.
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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************
* Contents: Native middle-level C interface to LAPACK function cgesvd
* Author: Intel Corporation
* Generated October, 2010
*****************************************************************************/
#include "lapacke.h"
#include "lapacke_utils.h"
lapack_int LAPACKE_cgesvd_work( int matrix_order, char jobu, char jobvt,
lapack_int m, lapack_int n,
lapack_complex_float* a, lapack_int lda,
float* s, lapack_complex_float* u,
lapack_int ldu, lapack_complex_float* vt,
lapack_int ldvt, lapack_complex_float* work,
lapack_int lwork, float* rwork )
{
lapack_int info = 0;
if( matrix_order == LAPACK_COL_MAJOR ) {
/* Call LAPACK function and adjust info */
LAPACK_cgesvd( &jobu, &jobvt, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt,
work, &lwork, rwork, &info );
if( info < 0 ) {
info = info - 1;
}
} else if( matrix_order == LAPACK_ROW_MAJOR ) {
lapack_int nrows_u = ( LAPACKE_lsame( jobu, 'a' ) ||
LAPACKE_lsame( jobu, 's' ) ) ? m : 1;
lapack_int ncols_u = LAPACKE_lsame( jobu, 'a' ) ? m :
( LAPACKE_lsame( jobu, 's' ) ? MIN(m,n) : 1);
lapack_int nrows_vt = LAPACKE_lsame( jobvt, 'a' ) ? n :
( LAPACKE_lsame( jobvt, 's' ) ? MIN(m,n) : 1);
lapack_int lda_t = MAX(1,m);
lapack_int ldu_t = MAX(1,nrows_u);
lapack_int ldvt_t = MAX(1,nrows_vt);
lapack_complex_float* a_t = NULL;
lapack_complex_float* u_t = NULL;
lapack_complex_float* vt_t = NULL;
/* Check leading dimension(s) */
if( lda < n ) {
info = -7;
LAPACKE_xerbla( "LAPACKE_cgesvd_work", info );
return info;
}
if( ldu < ncols_u ) {
info = -10;
LAPACKE_xerbla( "LAPACKE_cgesvd_work", info );
return info;
}
if( ldvt < n ) {
info = -12;
LAPACKE_xerbla( "LAPACKE_cgesvd_work", info );
return info;
}
/* Query optimal working array(s) size if requested */
if( lwork == -1 ) {
LAPACK_cgesvd( &jobu, &jobvt, &m, &n, a, &lda_t, s, u, &ldu_t, vt,
&ldvt_t, work, &lwork, rwork, &info );
return (info < 0) ? (info - 1) : info;
}
/* Allocate memory for temporary array(s) */
a_t = (lapack_complex_float*)
LAPACKE_malloc( sizeof(lapack_complex_float) * lda_t * MAX(1,n) );
if( a_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_0;
}
if( LAPACKE_lsame( jobu, 'a' ) || LAPACKE_lsame( jobu, 's' ) ) {
u_t = (lapack_complex_float*)
LAPACKE_malloc( sizeof(lapack_complex_float) *
ldu_t * MAX(1,ncols_u) );
if( u_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_1;
}
}
if( LAPACKE_lsame( jobvt, 'a' ) || LAPACKE_lsame( jobvt, 's' ) ) {
vt_t = (lapack_complex_float*)
LAPACKE_malloc( sizeof(lapack_complex_float) *
ldvt_t * MAX(1,n) );
if( vt_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_2;
}
}
/* Transpose input matrices */
LAPACKE_cge_trans( matrix_order, m, n, a, lda, a_t, lda_t );
/* Call LAPACK function and adjust info */
LAPACK_cgesvd( &jobu, &jobvt, &m, &n, a_t, &lda_t, s, u_t, &ldu_t, vt_t,
&ldvt_t, work, &lwork, rwork, &info );
if( info < 0 ) {
info = info - 1;
}
/* Transpose output matrices */
LAPACKE_cge_trans( LAPACK_COL_MAJOR, m, n, a_t, lda_t, a, lda );
if( LAPACKE_lsame( jobu, 'a' ) || LAPACKE_lsame( jobu, 's' ) ) {
LAPACKE_cge_trans( LAPACK_COL_MAJOR, nrows_u, ncols_u, u_t, ldu_t,
u, ldu );
}
if( LAPACKE_lsame( jobvt, 'a' ) || LAPACKE_lsame( jobvt, 's' ) ) {
LAPACKE_cge_trans( LAPACK_COL_MAJOR, nrows_vt, n, vt_t, ldvt_t, vt,
ldvt );
}
/* Release memory and exit */
if( LAPACKE_lsame( jobvt, 'a' ) || LAPACKE_lsame( jobvt, 's' ) ) {
LAPACKE_free( vt_t );
}
exit_level_2:
if( LAPACKE_lsame( jobu, 'a' ) || LAPACKE_lsame( jobu, 's' ) ) {
LAPACKE_free( u_t );
}
exit_level_1:
LAPACKE_free( a_t );
exit_level_0:
if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_cgesvd_work", info );
}
} else {
info = -1;
LAPACKE_xerbla( "LAPACKE_cgesvd_work", info );
}
return info;
}
|
mfine/libswiftnav
|
lapacke/src/lapacke_cgesvd_work.c
|
C
|
lgpl-3.0
| 6,758
|
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef QTAWS_LISTCHANNELMEMBERSHIPSFORAPPINSTANCEUSERREQUEST_P_H
#define QTAWS_LISTCHANNELMEMBERSHIPSFORAPPINSTANCEUSERREQUEST_P_H
#include "chimerequest_p.h"
#include "listchannelmembershipsforappinstanceuserrequest.h"
namespace QtAws {
namespace Chime {
class ListChannelMembershipsForAppInstanceUserRequest;
class ListChannelMembershipsForAppInstanceUserRequestPrivate : public ChimeRequestPrivate {
public:
ListChannelMembershipsForAppInstanceUserRequestPrivate(const ChimeRequest::Action action,
ListChannelMembershipsForAppInstanceUserRequest * const q);
ListChannelMembershipsForAppInstanceUserRequestPrivate(const ListChannelMembershipsForAppInstanceUserRequestPrivate &other,
ListChannelMembershipsForAppInstanceUserRequest * const q);
private:
Q_DECLARE_PUBLIC(ListChannelMembershipsForAppInstanceUserRequest)
};
} // namespace Chime
} // namespace QtAws
#endif
|
pcolby/libqtaws
|
src/chime/listchannelmembershipsforappinstanceuserrequest_p.h
|
C
|
lgpl-3.0
| 1,696
|
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*-
/*
* URIHandler.hpp
* Copyright (C) INCHRON GmbH 2018 <soeren.henning@inchron.com>
*
* EMF4CPP 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.
*
* EMF4CPP 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/>.
*/
#ifndef URIHandler_HPP
#define URIHandler_HPP
#include "../dllEcorecpp.hpp"
#include <list>
#include <memory>
namespace ecore {
class EObject;
}
class QUrl;
namespace ecorecpp {
namespace resource {
class URIHandler;
using URIHandler_ptr = std::shared_ptr<URIHandler>;
/** A class for uri type handling. This class is used by the URIConverter.
*
* The base class (URIHandler) implementation can only handle local
* file uris. For all other types of uris (e.g. https://, ftp://, svn://)
* specialized derived classes must be implemented.
*/
class EXPORT_ECORECPP_DLL URIHandler {
public:
using URIHandlerList = std::list<URIHandler_ptr>;
static const URIHandlerList DEFAULT_HANDLERS;
URIHandler();
virtual ~URIHandler();
/** Returns true, if this handler can handle uris of the given form.*/
virtual bool canHandle(const QUrl&) const;
/** Returns input stream for uri, may return a null pointer,
* if the given uri can not be handled*/
virtual std::shared_ptr<std::istream> createInputStream(const QUrl&) const;
/** Returns output stream for uri, may return a null pointer,
* if the given uri can not be handled*/
virtual std::shared_ptr<std::ostream> createOutputStream(const QUrl&) const;
/** Remove uri resource. Does nothing, if the given uri can
* not be handled.*/
virtual void remove(const QUrl&) const;
/** Check existence of uri resource. Return 'false',
* if the given uri can not be handled.*/
virtual bool exists(const QUrl&) const;
};
} // resource
} // ecorecpp
#endif
|
catedrasaes-umu/emf4cpp
|
emf4cpp/ecorecpp/resource/URIHandler.hpp
|
C++
|
lgpl-3.0
| 2,340
|
<?php
namespace Google\AdsApi\Dfp\v201711;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class OrderService extends \Google\AdsApi\Common\AdsSoapClient
{
/**
* @var array $classmap The defined classes
*/
private static $classmap = array (
'ObjectValue' => 'Google\\AdsApi\\Dfp\\v201711\\ObjectValue',
'ApiError' => 'Google\\AdsApi\\Dfp\\v201711\\ApiError',
'ApiException' => 'Google\\AdsApi\\Dfp\\v201711\\ApiException',
'ApiVersionError' => 'Google\\AdsApi\\Dfp\\v201711\\ApiVersionError',
'ApplicationException' => 'Google\\AdsApi\\Dfp\\v201711\\ApplicationException',
'AppliedLabel' => 'Google\\AdsApi\\Dfp\\v201711\\AppliedLabel',
'ApproveAndOverbookOrders' => 'Google\\AdsApi\\Dfp\\v201711\\ApproveAndOverbookOrders',
'ApproveOrders' => 'Google\\AdsApi\\Dfp\\v201711\\ApproveOrders',
'ApproveOrdersWithoutReservationChanges' => 'Google\\AdsApi\\Dfp\\v201711\\ApproveOrdersWithoutReservationChanges',
'ArchiveOrders' => 'Google\\AdsApi\\Dfp\\v201711\\ArchiveOrders',
'AudienceExtensionError' => 'Google\\AdsApi\\Dfp\\v201711\\AudienceExtensionError',
'AuthenticationError' => 'Google\\AdsApi\\Dfp\\v201711\\AuthenticationError',
'BaseCustomFieldValue' => 'Google\\AdsApi\\Dfp\\v201711\\BaseCustomFieldValue',
'BooleanValue' => 'Google\\AdsApi\\Dfp\\v201711\\BooleanValue',
'ClickTrackingLineItemError' => 'Google\\AdsApi\\Dfp\\v201711\\ClickTrackingLineItemError',
'CollectionSizeError' => 'Google\\AdsApi\\Dfp\\v201711\\CollectionSizeError',
'CommonError' => 'Google\\AdsApi\\Dfp\\v201711\\CommonError',
'CompanyCreditStatusError' => 'Google\\AdsApi\\Dfp\\v201711\\CompanyCreditStatusError',
'ContentMetadataTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\ContentMetadataTargetingError',
'CreativeError' => 'Google\\AdsApi\\Dfp\\v201711\\CreativeError',
'CrossSellError' => 'Google\\AdsApi\\Dfp\\v201711\\CrossSellError',
'CustomFieldValue' => 'Google\\AdsApi\\Dfp\\v201711\\CustomFieldValue',
'CustomFieldValueError' => 'Google\\AdsApi\\Dfp\\v201711\\CustomFieldValueError',
'CustomTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\CustomTargetingError',
'Date' => 'Google\\AdsApi\\Dfp\\v201711\\Date',
'DateTime' => 'Google\\AdsApi\\Dfp\\v201711\\DateTime',
'DateTimeRangeTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\DateTimeRangeTargetingError',
'DateTimeValue' => 'Google\\AdsApi\\Dfp\\v201711\\DateTimeValue',
'DateValue' => 'Google\\AdsApi\\Dfp\\v201711\\DateValue',
'DayPartTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\DayPartTargetingError',
'DeleteOrders' => 'Google\\AdsApi\\Dfp\\v201711\\DeleteOrders',
'DisapproveOrders' => 'Google\\AdsApi\\Dfp\\v201711\\DisapproveOrders',
'DisapproveOrdersWithoutReservationChanges' => 'Google\\AdsApi\\Dfp\\v201711\\DisapproveOrdersWithoutReservationChanges',
'DropDownCustomFieldValue' => 'Google\\AdsApi\\Dfp\\v201711\\DropDownCustomFieldValue',
'EntityChildrenLimitReachedError' => 'Google\\AdsApi\\Dfp\\v201711\\EntityChildrenLimitReachedError',
'EntityLimitReachedError' => 'Google\\AdsApi\\Dfp\\v201711\\EntityLimitReachedError',
'FeatureError' => 'Google\\AdsApi\\Dfp\\v201711\\FeatureError',
'FieldPathElement' => 'Google\\AdsApi\\Dfp\\v201711\\FieldPathElement',
'ForecastError' => 'Google\\AdsApi\\Dfp\\v201711\\ForecastError',
'FrequencyCapError' => 'Google\\AdsApi\\Dfp\\v201711\\FrequencyCapError',
'GenericTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\GenericTargetingError',
'GeoTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\GeoTargetingError',
'GrpSettingsError' => 'Google\\AdsApi\\Dfp\\v201711\\GrpSettingsError',
'ImageError' => 'Google\\AdsApi\\Dfp\\v201711\\ImageError',
'InternalApiError' => 'Google\\AdsApi\\Dfp\\v201711\\InternalApiError',
'InvalidEmailError' => 'Google\\AdsApi\\Dfp\\v201711\\InvalidEmailError',
'InvalidUrlError' => 'Google\\AdsApi\\Dfp\\v201711\\InvalidUrlError',
'InventoryTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\InventoryTargetingError',
'LabelEntityAssociationError' => 'Google\\AdsApi\\Dfp\\v201711\\LabelEntityAssociationError',
'LineItemActivityAssociationError' => 'Google\\AdsApi\\Dfp\\v201711\\LineItemActivityAssociationError',
'LineItemCreativeAssociationError' => 'Google\\AdsApi\\Dfp\\v201711\\LineItemCreativeAssociationError',
'LineItemError' => 'Google\\AdsApi\\Dfp\\v201711\\LineItemError',
'LineItemFlightDateError' => 'Google\\AdsApi\\Dfp\\v201711\\LineItemFlightDateError',
'LineItemOperationError' => 'Google\\AdsApi\\Dfp\\v201711\\LineItemOperationError',
'Money' => 'Google\\AdsApi\\Dfp\\v201711\\Money',
'NotNullError' => 'Google\\AdsApi\\Dfp\\v201711\\NotNullError',
'NullError' => 'Google\\AdsApi\\Dfp\\v201711\\NullError',
'NumberValue' => 'Google\\AdsApi\\Dfp\\v201711\\NumberValue',
'OrderAction' => 'Google\\AdsApi\\Dfp\\v201711\\OrderAction',
'OrderActionError' => 'Google\\AdsApi\\Dfp\\v201711\\OrderActionError',
'Order' => 'Google\\AdsApi\\Dfp\\v201711\\Order',
'OrderError' => 'Google\\AdsApi\\Dfp\\v201711\\OrderError',
'OrderPage' => 'Google\\AdsApi\\Dfp\\v201711\\OrderPage',
'ParseError' => 'Google\\AdsApi\\Dfp\\v201711\\ParseError',
'PauseOrders' => 'Google\\AdsApi\\Dfp\\v201711\\PauseOrders',
'PermissionError' => 'Google\\AdsApi\\Dfp\\v201711\\PermissionError',
'ProgrammaticError' => 'Google\\AdsApi\\Dfp\\v201711\\ProgrammaticError',
'PublisherQueryLanguageContextError' => 'Google\\AdsApi\\Dfp\\v201711\\PublisherQueryLanguageContextError',
'PublisherQueryLanguageSyntaxError' => 'Google\\AdsApi\\Dfp\\v201711\\PublisherQueryLanguageSyntaxError',
'QuotaError' => 'Google\\AdsApi\\Dfp\\v201711\\QuotaError',
'RangeError' => 'Google\\AdsApi\\Dfp\\v201711\\RangeError',
'RegExError' => 'Google\\AdsApi\\Dfp\\v201711\\RegExError',
'RequiredCollectionError' => 'Google\\AdsApi\\Dfp\\v201711\\RequiredCollectionError',
'RequiredError' => 'Google\\AdsApi\\Dfp\\v201711\\RequiredError',
'RequiredNumberError' => 'Google\\AdsApi\\Dfp\\v201711\\RequiredNumberError',
'RequiredSizeError' => 'Google\\AdsApi\\Dfp\\v201711\\RequiredSizeError',
'ReservationDetailsError' => 'Google\\AdsApi\\Dfp\\v201711\\ReservationDetailsError',
'ResumeAndOverbookOrders' => 'Google\\AdsApi\\Dfp\\v201711\\ResumeAndOverbookOrders',
'ResumeOrders' => 'Google\\AdsApi\\Dfp\\v201711\\ResumeOrders',
'RetractOrders' => 'Google\\AdsApi\\Dfp\\v201711\\RetractOrders',
'RetractOrdersWithoutReservationChanges' => 'Google\\AdsApi\\Dfp\\v201711\\RetractOrdersWithoutReservationChanges',
'AudienceSegmentError' => 'Google\\AdsApi\\Dfp\\v201711\\AudienceSegmentError',
'ServerError' => 'Google\\AdsApi\\Dfp\\v201711\\ServerError',
'SetTopBoxLineItemError' => 'Google\\AdsApi\\Dfp\\v201711\\SetTopBoxLineItemError',
'SetValue' => 'Google\\AdsApi\\Dfp\\v201711\\SetValue',
'SoapRequestHeader' => 'Google\\AdsApi\\Dfp\\v201711\\SoapRequestHeader',
'SoapResponseHeader' => 'Google\\AdsApi\\Dfp\\v201711\\SoapResponseHeader',
'Statement' => 'Google\\AdsApi\\Dfp\\v201711\\Statement',
'StatementError' => 'Google\\AdsApi\\Dfp\\v201711\\StatementError',
'StringFormatError' => 'Google\\AdsApi\\Dfp\\v201711\\StringFormatError',
'StringLengthError' => 'Google\\AdsApi\\Dfp\\v201711\\StringLengthError',
'String_ValueMapEntry' => 'Google\\AdsApi\\Dfp\\v201711\\String_ValueMapEntry',
'SubmitOrdersForApproval' => 'Google\\AdsApi\\Dfp\\v201711\\SubmitOrdersForApproval',
'SubmitOrdersForApprovalAndOverbook' => 'Google\\AdsApi\\Dfp\\v201711\\SubmitOrdersForApprovalAndOverbook',
'SubmitOrdersForApprovalWithoutReservationChanges' => 'Google\\AdsApi\\Dfp\\v201711\\SubmitOrdersForApprovalWithoutReservationChanges',
'TeamError' => 'Google\\AdsApi\\Dfp\\v201711\\TeamError',
'TechnologyTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\TechnologyTargetingError',
'TemplateInstantiatedCreativeError' => 'Google\\AdsApi\\Dfp\\v201711\\TemplateInstantiatedCreativeError',
'TextValue' => 'Google\\AdsApi\\Dfp\\v201711\\TextValue',
'TimeZoneError' => 'Google\\AdsApi\\Dfp\\v201711\\TimeZoneError',
'TypeError' => 'Google\\AdsApi\\Dfp\\v201711\\TypeError',
'UnarchiveOrders' => 'Google\\AdsApi\\Dfp\\v201711\\UnarchiveOrders',
'UniqueError' => 'Google\\AdsApi\\Dfp\\v201711\\UniqueError',
'UpdateResult' => 'Google\\AdsApi\\Dfp\\v201711\\UpdateResult',
'UserDomainTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\UserDomainTargetingError',
'Value' => 'Google\\AdsApi\\Dfp\\v201711\\Value',
'VideoPositionTargetingError' => 'Google\\AdsApi\\Dfp\\v201711\\VideoPositionTargetingError',
'createOrdersResponse' => 'Google\\AdsApi\\Dfp\\v201711\\createOrdersResponse',
'getOrdersByStatementResponse' => 'Google\\AdsApi\\Dfp\\v201711\\getOrdersByStatementResponse',
'performOrderActionResponse' => 'Google\\AdsApi\\Dfp\\v201711\\performOrderActionResponse',
'updateOrdersResponse' => 'Google\\AdsApi\\Dfp\\v201711\\updateOrdersResponse',
);
/**
* @param array $options A array of config values
* @param string $wsdl The wsdl file to use
*/
public function __construct(array $options = array(),
$wsdl = 'https://ads.google.com/apis/ads/publisher/v201711/OrderService?wsdl')
{
foreach (self::$classmap as $key => $value) {
if (!isset($options['classmap'][$key])) {
$options['classmap'][$key] = $value;
}
}
$options = array_merge(array (
'features' => 1,
), $options);
parent::__construct($wsdl, $options);
}
/**
* Creates new {@link Order} objects.
*
* @param \Google\AdsApi\Dfp\v201711\Order[] $orders
* @return \Google\AdsApi\Dfp\v201711\Order[]
* @throws \Google\AdsApi\Dfp\v201711\ApiException
*/
public function createOrders(array $orders)
{
return $this->__soapCall('createOrders', array(array('orders' => $orders)))->getRval();
}
/**
* Gets an {@link OrderPage} of {@link Order} objects that satisfy the given
* {@link Statement#query}. The following fields are supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code advertiserId}</td>
* <td>{@link Order#advertiserId}</td>
* </tr>
* <tr>
* <td>{@code endDateTime}</td>
* <td>{@link Order#endDateTime}</td>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link Order#id}</td>
* </tr>
* <tr>
* <td>{@code name}</td>
* <td>{@link Order#name}</td>
* </tr>
* <tr>
* <td>{@code salespersonId}</td>
* <td>{@link Order#salespersonId}</td>
* </tr>
* <tr>
* <td>{@code startDateTime}</td>
* <td>{@link Order#startDateTime}</td>
* </tr>
* <tr>
* <td>{@code status}</td>
* <td>{@link Order#status}</td>
* </tr>
* <tr>
* <td>{@code traffickerId}</td>
* <td>{@link Order#traffickerId}</td>
* </tr>
* <tr>
* <td>{@code lastModifiedDateTime}</td>
* <td>{@link Order#lastModifiedDateTime}</td>
* </tr>
* </table>
*
* a set of orders
*
* @param \Google\AdsApi\Dfp\v201711\Statement $filterStatement
* @return \Google\AdsApi\Dfp\v201711\OrderPage
* @throws \Google\AdsApi\Dfp\v201711\ApiException
*/
public function getOrdersByStatement(\Google\AdsApi\Dfp\v201711\Statement $filterStatement)
{
return $this->__soapCall('getOrdersByStatement', array(array('filterStatement' => $filterStatement)))->getRval();
}
/**
* Performs actions on {@link Order} objects that match the given
* {@link Statement#query}.
*
* a set of orders
*
* @param \Google\AdsApi\Dfp\v201711\OrderAction $orderAction
* @param \Google\AdsApi\Dfp\v201711\Statement $filterStatement
* @return \Google\AdsApi\Dfp\v201711\UpdateResult
* @throws \Google\AdsApi\Dfp\v201711\ApiException
*/
public function performOrderAction(\Google\AdsApi\Dfp\v201711\OrderAction $orderAction, \Google\AdsApi\Dfp\v201711\Statement $filterStatement)
{
return $this->__soapCall('performOrderAction', array(array('orderAction' => $orderAction, 'filterStatement' => $filterStatement)))->getRval();
}
/**
* Updates the specified {@link Order} objects.
*
* @param \Google\AdsApi\Dfp\v201711\Order[] $orders
* @return \Google\AdsApi\Dfp\v201711\Order[]
* @throws \Google\AdsApi\Dfp\v201711\ApiException
*/
public function updateOrders(array $orders)
{
return $this->__soapCall('updateOrders', array(array('orders' => $orders)))->getRval();
}
}
|
advanced-online-marketing/AOM
|
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201711/OrderService.php
|
PHP
|
lgpl-3.0
| 13,091
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class MainForm
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.label8 = New System.Windows.Forms.Label()
Me.button8 = New System.Windows.Forms.Button()
Me.label1 = New System.Windows.Forms.Label()
Me.button1 = New System.Windows.Forms.Button()
Me.label16 = New System.Windows.Forms.Label()
Me.button16 = New System.Windows.Forms.Button()
Me.label15 = New System.Windows.Forms.Label()
Me.button15 = New System.Windows.Forms.Button()
Me.Label2 = New System.Windows.Forms.Label()
Me.Button2 = New System.Windows.Forms.Button()
Me.SuspendLayout()
'
'label8
'
Me.label8.Location = New System.Drawing.Point(0, 41)
Me.label8.Name = "label8"
Me.label8.Size = New System.Drawing.Size(208, 41)
Me.label8.TabIndex = 19
Me.label8.Text = "Autocomplete sample. This example shows simplest way to create autocomplete funct" & _
"ionality."
Me.label8.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'button8
'
Me.button8.Location = New System.Drawing.Point(214, 52)
Me.button8.Name = "button8"
Me.button8.Size = New System.Drawing.Size(75, 23)
Me.button8.TabIndex = 18
Me.button8.Text = "Show"
Me.button8.UseVisualStyleBackColor = True
'
'label1
'
Me.label1.Location = New System.Drawing.Point(0, 4)
Me.label1.Name = "label1"
Me.label1.Size = New System.Drawing.Size(208, 34)
Me.label1.TabIndex = 17
Me.label1.Text = "Powerful sample. It shows syntax highlighting and many features."
Me.label1.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'button1
'
Me.button1.Location = New System.Drawing.Point(214, 3)
Me.button1.Name = "button1"
Me.button1.Size = New System.Drawing.Size(75, 23)
Me.button1.TabIndex = 16
Me.button1.Text = "Show"
Me.button1.UseVisualStyleBackColor = True
'
'label16
'
Me.label16.Location = New System.Drawing.Point(0, 157)
Me.label16.Name = "label16"
Me.label16.Size = New System.Drawing.Size(208, 23)
Me.label16.TabIndex = 33
Me.label16.Text = "Bookmarks sample"
Me.label16.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'button16
'
Me.button16.Location = New System.Drawing.Point(214, 152)
Me.button16.Name = "button16"
Me.button16.Size = New System.Drawing.Size(75, 23)
Me.button16.TabIndex = 32
Me.button16.Text = "Show"
Me.button16.UseVisualStyleBackColor = True
'
'label15
'
Me.label15.Location = New System.Drawing.Point(0, 206)
Me.label15.Name = "label15"
Me.label15.Size = New System.Drawing.Size(208, 23)
Me.label15.TabIndex = 35
Me.label15.Text = "AutoIndent sample"
Me.label15.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'button15
'
Me.button15.Location = New System.Drawing.Point(214, 201)
Me.button15.Name = "button15"
Me.button15.Size = New System.Drawing.Size(75, 23)
Me.button15.TabIndex = 34
Me.button15.Text = "Show"
Me.button15.UseVisualStyleBackColor = True
'
'Label2
'
Me.Label2.Location = New System.Drawing.Point(0, 91)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(208, 48)
Me.Label2.TabIndex = 37
Me.Label2.Text = "Autocomplete sample 2." & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "This example demonstrates more flexible variant of Autoco" & _
"mpleteMenu using."
Me.Label2.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'Button2
'
Me.Button2.Location = New System.Drawing.Point(214, 102)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(75, 23)
Me.Button2.TabIndex = 36
Me.Button2.Text = "Show"
Me.Button2.UseVisualStyleBackColor = True
'
'MainForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(315, 254)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.label15)
Me.Controls.Add(Me.button15)
Me.Controls.Add(Me.label16)
Me.Controls.Add(Me.button16)
Me.Controls.Add(Me.label8)
Me.Controls.Add(Me.button8)
Me.Controls.Add(Me.label1)
Me.Controls.Add(Me.button1)
Me.Name = "MainForm"
Me.Text = "MenuForm"
Me.ResumeLayout(False)
End Sub
Private WithEvents label8 As System.Windows.Forms.Label
Private WithEvents button8 As System.Windows.Forms.Button
Private WithEvents label1 As System.Windows.Forms.Label
Private WithEvents button1 As System.Windows.Forms.Button
Private WithEvents label16 As System.Windows.Forms.Label
Private WithEvents button16 As System.Windows.Forms.Button
Private WithEvents label15 As System.Windows.Forms.Label
Private WithEvents button15 As System.Windows.Forms.Button
Private WithEvents Label2 As System.Windows.Forms.Label
Private WithEvents Button2 As System.Windows.Forms.Button
End Class
|
collenirwin/BoinEdit
|
BoinEdit/bin/Debug/FastColoredTextBox/FastColoredTextBox-master/TesterVB/MainForm.Designer.vb
|
Visual Basic
|
lgpl-3.0
| 6,379
|
/* Copyright 2015, Eric Pernia.
* All rights reserved.
*
* This file is part HVM4CIAA.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package ar.edu.unq.embebidos;
import minicdj.util.HashMap;
public class Device extends PeripheralLibrary {
/* Attributes */
private HashMap pins = new HashMap();
private HashMap peripherals = new HashMap();
/* Default devices */
private static Device CIAA_NXP =
new Device( 0, "CIAA-NXP" );
private static Device EDU_CIAA_NXP =
new Device( 1, "EDU-CIAA-NXP" );
private static Device TEST_DEVICE =
new Device( 1, "Test Device" );
/* Constructor */
public Device( int id, String name ) {
super( id, name);
}
/* Put a Peripheral */
public void putPeripheral( String key, Peripheral value ) {
peripherals.put( key, value );
}
/* Put a Pin */
public void putPin( String key, Pin value ) {
pins.put( key, value );
}
/* Returns a Pin with Name pinName */
public Pin getPin( String pinName ) {
return (Pin) pins.get(pinName);
}
/* Returns a Peripheral with Name periphName */
public Peripheral getPeripheral(String periphName){
return (Peripheral) peripherals.get(periphName);
}
public Peripheral get(String periphName){
return (Peripheral) peripherals.get(periphName);
}
/* Device Builders */
public static Device testDevice() {
Pin pin = new Pin( 1, "P1", TEST_DEVICE);
pin.addMode(PinMode.DI);
pin.addMode(PinMode.DO);
TEST_DEVICE.putPin(pin.getName(),pin);
pin = new Pin( 2, "P2", TEST_DEVICE);
pin.addMode(PinMode.DI);
pin.addMode(PinMode.DO);
pin.addMode(PinMode.U);
TEST_DEVICE.putPin(pin.getName(),pin);
pin = new Pin( 3, "P3", TEST_DEVICE);
pin.addMode(PinMode.DI);
pin.addMode(PinMode.DO);
pin.addMode(PinMode.U);
TEST_DEVICE.putPin(pin.getName(),pin);
pin = new Pin( 4, "P4", TEST_DEVICE);
pin.addMode(PinMode.AI);
TEST_DEVICE.putPin(pin.getName(),pin);
pin = new Pin( 5, "P5", TEST_DEVICE);
pin.addMode(PinMode.AO);
TEST_DEVICE.putPin(pin.getName(),pin);
pin = new Pin( 6, "P6", TEST_DEVICE);
pin.addMode(PinMode.DI);
pin.addMode(PinMode.DO);
pin.addMode(PinMode.AI);
TEST_DEVICE.putPin(pin.getName(),pin);
pin = new Pin( 7, "VCC", TEST_DEVICE);
pin.addMode(PinMode.X);
TEST_DEVICE.putPin(pin.getName(),pin);
pin = new Pin( 8, "GND", TEST_DEVICE);
pin.addMode(PinMode.X);
TEST_DEVICE.putPin(pin.getName(),pin);
DigitalIO periph =
new DigitalIO(0,"DIO0",TEST_DEVICE,TEST_DEVICE.getPin("P1"));
TEST_DEVICE.putPeripheral(periph.getName(),periph);
periph = new DigitalIO(1,"DIO1",TEST_DEVICE,TEST_DEVICE.getPin("P2"));
TEST_DEVICE.putPeripheral(periph.getName(),periph);
periph = new DigitalIO(2,"DIO2",TEST_DEVICE,TEST_DEVICE.getPin("P3"));
TEST_DEVICE.putPeripheral(periph.getName(),periph);
periph = new DigitalIO(3,"DIO3",TEST_DEVICE,TEST_DEVICE.getPin("P6"));
TEST_DEVICE.putPeripheral(periph.getName(),periph);
Uart periph2 = new Uart(0,"UART0", TEST_DEVICE,
TEST_DEVICE.getPin("P2"),TEST_DEVICE.getPin("P3"));
TEST_DEVICE.putPeripheral(periph2.getName(),periph2);
AnalogIO periph3 =
new AnalogIO(0,"AI0",TEST_DEVICE,TEST_DEVICE.getPin("P4"));
TEST_DEVICE.putPeripheral(periph3.getName(),periph3);
periph3 = new AnalogIO(1,"AO0",TEST_DEVICE,TEST_DEVICE.getPin("P5"));
TEST_DEVICE.putPeripheral(periph3.getName(),periph3);
periph3 = new AnalogIO(2,"AI1",TEST_DEVICE,TEST_DEVICE.getPin("P6"));
TEST_DEVICE.putPeripheral(periph3.getName(),periph3);
return TEST_DEVICE;
}
public static Device ciaaNxp() {
/* 1 to 20 */
Pin pin = new Pin( 1, "AOUT", CIAA_NXP);
pin.addMode(PinMode.AO);
CIAA_NXP.putPin(pin.getName(),pin);
AnalogIO periphA = new AnalogIO(0,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphA.getName(),periphA);
pin = new Pin( 2, "GNDA0", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin( 3, "GND0", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin( 4, "DOUT0", CIAA_NXP);
pin.addMode(PinMode.DO);
CIAA_NXP.putPin(pin.getName(),pin);
DigitalIO periphD = new DigitalIO(0,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 5, "DOUT0_C", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin( 6, "DOUT1", CIAA_NXP);
pin.addMode(PinMode.DO);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(1,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 7, "DOUT1_C", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin( 8, "DOUT2", CIAA_NXP);
pin.addMode(PinMode.DO);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(2,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 9, "DOUT2_C", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(10, "DOUT3", CIAA_NXP);
pin.addMode(PinMode.DO);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(3,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(11, "DOUT3_C", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(12, "GND1", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(13, "VOUT_24V", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(14, "DOUT4", CIAA_NXP);
pin.addMode(PinMode.DO);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(4,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(15, "DOUT5", CIAA_NXP);
pin.addMode(PinMode.DO);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(5,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(16, "DOUT6", CIAA_NXP);
pin.addMode(PinMode.DO);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(6,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(17, "DOUT7", CIAA_NXP);
pin.addMode(PinMode.DO);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(7,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(18, "NC", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(19, "VIN_24V", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(20, "GND2", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
/* 21 to 40 */
pin = new Pin(21, "RS485_A", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(22, "RS485_B", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(23, "RS485_GND2", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(24, "DIN0", CIAA_NXP);
pin.addMode(PinMode.DI);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(0,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(25, "DIN1", CIAA_NXP);
pin.addMode(PinMode.DI);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(1,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(26, "DIN2", CIAA_NXP);
pin.addMode(PinMode.DI);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(2,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(27, "DIN3", CIAA_NXP);
pin.addMode(PinMode.DI);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(3,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(28, "DIN4", CIAA_NXP);
pin.addMode(PinMode.DI);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(4,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(29, "DIN5", CIAA_NXP);
pin.addMode(PinMode.DI);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(5,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(30, "DIN6", CIAA_NXP);
pin.addMode(PinMode.DI);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(6,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(31, "DIN7", CIAA_NXP);
pin.addMode(PinMode.DI);
CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(7,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin(32, "DIN_COM", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(33, "AIN0", CIAA_NXP);
pin.addMode(PinMode.AI);
CIAA_NXP.putPin(pin.getName(),pin);
periphA = new AnalogIO(0,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphA.getName(),periphA);
pin = new Pin(34, "AIN1", CIAA_NXP);
pin.addMode(PinMode.AI);
CIAA_NXP.putPin(pin.getName(),pin);
periphA = new AnalogIO(1,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphA.getName(),periphA);
pin = new Pin(35, "AIN2", CIAA_NXP);
pin.addMode(PinMode.AI);
CIAA_NXP.putPin(pin.getName(),pin);
periphA = new AnalogIO(2,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphA.getName(),periphA);
pin = new Pin(36, "AIN3", CIAA_NXP);
pin.addMode(PinMode.AI);
CIAA_NXP.putPin(pin.getName(),pin);
periphA = new AnalogIO(3,pin.getName(), CIAA_NXP,pin);
CIAA_NXP.putPeripheral(periphA.getName(),periphA);
pin = new Pin(37, "GNDA1", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(38, "CAN_H", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(39, "CAN_L", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
pin = new Pin(40, "GND3", CIAA_NXP);
pin.addMode(PinMode.X);
CIAA_NXP.putPin(pin.getName(),pin);
return CIAA_NXP;
}
public static Device eduCiaaNxp() {
int i = 0;
Pin pin = new Pin( 0, "", EDU_CIAA_NXP);
DigitalIO periphD = new DigitalIO(0,pin.getName(), EDU_CIAA_NXP,pin);
AnalogIO periphA = new AnalogIO(0,pin.getName(), EDU_CIAA_NXP,pin);
/* Digital */
for( i=0; i<=35; i++ ){
pin = new Pin( i+1, ("DIO"+Integer.toString(i)), EDU_CIAA_NXP);
pin.addMode(PinMode.DI);
pin.addMode(PinMode.DO);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(i,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(), periphD);
}
pin = new Pin( 37, "TEC1", EDU_CIAA_NXP);
pin.addMode(PinMode.DI);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(36,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 38, "TEC2", EDU_CIAA_NXP);
pin.addMode(PinMode.DI);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(37,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 39, "TEC3", EDU_CIAA_NXP);
pin.addMode(PinMode.DI);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(38,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 40, "TEC4", EDU_CIAA_NXP);
pin.addMode(PinMode.DI);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(39,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 41, "LED1", EDU_CIAA_NXP);
pin.addMode(PinMode.DO);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(40,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 42, "LED2", EDU_CIAA_NXP);
pin.addMode(PinMode.DO);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(41,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 43, "LED3", EDU_CIAA_NXP);
pin.addMode(PinMode.DO);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(42,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 44, "LEDR", EDU_CIAA_NXP);
pin.addMode(PinMode.DO);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(43,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 45, "LEDG", EDU_CIAA_NXP);
pin.addMode(PinMode.DO);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(44,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
pin = new Pin( 46, "LEDB", EDU_CIAA_NXP);
pin.addMode(PinMode.DO);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphD = new DigitalIO(45,pin.getName(), pin.getDevice(), pin);
EDU_CIAA_NXP.putPeripheral(periphD.getName(),periphD);
/* Analog */
pin = new Pin(48, "AIN0", EDU_CIAA_NXP);
pin.addMode(PinMode.AI);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphA = new AnalogIO(0,pin.getName(), pin.getDevice(),pin);
EDU_CIAA_NXP.putPeripheral(periphA.getName(),periphA);
pin = new Pin(49, "AIN1", EDU_CIAA_NXP);
pin.addMode(PinMode.AI);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphA = new AnalogIO(1,pin.getName(), pin.getDevice(),pin);
EDU_CIAA_NXP.putPeripheral(periphA.getName(),periphA);
pin = new Pin(50, "AIN2", EDU_CIAA_NXP);
pin.addMode(PinMode.AI);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphA = new AnalogIO(2,pin.getName(), pin.getDevice(),pin);
EDU_CIAA_NXP.putPeripheral(periphA.getName(),periphA);
pin = new Pin( 47, "AOUT", EDU_CIAA_NXP);
pin.addMode(PinMode.AO);
EDU_CIAA_NXP.putPin(pin.getName(),pin);
periphA = new AnalogIO(0,pin.getName(), pin.getDevice(),pin);
EDU_CIAA_NXP.putPeripheral(periphA.getName(),periphA);
/* Uart */
return EDU_CIAA_NXP;
}
}
|
epernia/HVM
|
2016/runtime-EclipseApplication/EduCiaaPeripheral/src/ar/edu/unq/embebidos/Device.java
|
Java
|
lgpl-3.0
| 17,686
|
<!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 (1.8.0_201) on Thu Oct 01 11:57:27 EDT 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<title>Uses of Class ca.uqac.lif.ecp.statechart.atomic.AtomicStatechartRenderer.ChartStatePair (SealTest Documentation)</title>
<meta name="date" content="2020-10-01">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class ca.uqac.lif.ecp.statechart.atomic.AtomicStatechartRenderer.ChartStatePair (SealTest Documentation)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../ca/uqac/lif/ecp/statechart/atomic/AtomicStatechartRenderer.ChartStatePair.html" title="class in ca.uqac.lif.ecp.statechart.atomic">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-all.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?ca/uqac/lif/ecp/statechart/atomic/class-use/AtomicStatechartRenderer.ChartStatePair.html" target="_top">Frames</a></li>
<li><a href="AtomicStatechartRenderer.ChartStatePair.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 ca.uqac.lif.ecp.statechart.atomic.AtomicStatechartRenderer.ChartStatePair" class="title">Uses of Class<br>ca.uqac.lif.ecp.statechart.atomic.AtomicStatechartRenderer.ChartStatePair</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../ca/uqac/lif/ecp/statechart/atomic/AtomicStatechartRenderer.ChartStatePair.html" title="class in ca.uqac.lif.ecp.statechart.atomic">AtomicStatechartRenderer.ChartStatePair</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="#ca.uqac.lif.ecp.statechart.atomic">ca.uqac.lif.ecp.statechart.atomic</a></td>
<td class="colLast">
<div class="block">UML statecharts made of atomic events</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="ca.uqac.lif.ecp.statechart.atomic">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../ca/uqac/lif/ecp/statechart/atomic/AtomicStatechartRenderer.ChartStatePair.html" title="class in ca.uqac.lif.ecp.statechart.atomic">AtomicStatechartRenderer.ChartStatePair</a> in <a href="../../../../../../../ca/uqac/lif/ecp/statechart/atomic/package-summary.html">ca.uqac.lif.ecp.statechart.atomic</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../ca/uqac/lif/ecp/statechart/atomic/package-summary.html">ca.uqac.lif.ecp.statechart.atomic</a> that return <a href="../../../../../../../ca/uqac/lif/ecp/statechart/atomic/AtomicStatechartRenderer.ChartStatePair.html" title="class in ca.uqac.lif.ecp.statechart.atomic">AtomicStatechartRenderer.ChartStatePair</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>protected static <a href="../../../../../../../ca/uqac/lif/ecp/statechart/atomic/AtomicStatechartRenderer.ChartStatePair.html" title="class in ca.uqac.lif.ecp.statechart.atomic">AtomicStatechartRenderer.ChartStatePair</a></code></td>
<td class="colLast"><span class="typeNameLabel">AtomicStatechartRenderer.</span><code><span class="memberNameLink"><a href="../../../../../../../ca/uqac/lif/ecp/statechart/atomic/AtomicStatechartRenderer.html#getLastState-ca.uqac.lif.ecp.statechart.Statechart-ca.uqac.lif.ecp.statechart.Configuration-">getLastState</a></span>(<a href="../../../../../../../ca/uqac/lif/ecp/statechart/Statechart.html" title="class in ca.uqac.lif.ecp.statechart">Statechart</a><<a href="../../../../../../../ca/uqac/lif/ecp/atomic/AtomicEvent.html" title="class in ca.uqac.lif.ecp.atomic">AtomicEvent</a>> owner,
<a href="../../../../../../../ca/uqac/lif/ecp/statechart/Configuration.html" title="class in ca.uqac.lif.ecp.statechart">Configuration</a><<a href="../../../../../../../ca/uqac/lif/ecp/atomic/AtomicEvent.html" title="class in ca.uqac.lif.ecp.atomic">AtomicEvent</a>> source)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../ca/uqac/lif/ecp/statechart/atomic/AtomicStatechartRenderer.ChartStatePair.html" title="class in ca.uqac.lif.ecp.statechart.atomic">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-all.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?ca/uqac/lif/ecp/statechart/atomic/class-use/AtomicStatechartRenderer.ChartStatePair.html" target="_top">Frames</a></li>
<li><a href="AtomicStatechartRenderer.ChartStatePair.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 ======= -->
<p class="legalCopy"><small><i>Copyright © Sylvain Hallé. All Rights Reserved.</i></small></p>
</body>
</html>
|
liflab/sealtest
|
docs/doc/ca/uqac/lif/ecp/statechart/atomic/class-use/AtomicStatechartRenderer.ChartStatePair.html
|
HTML
|
lgpl-3.0
| 8,238
|
(function($) {
var cultures = $.global.cultures,
en = cultures.en,
standard = en.calendars.standard,
culture = cultures["mt-MT"] = $.extend(true, {}, en, {
name: "mt-MT",
englishName: "Maltese (Malta)",
nativeName: "Malti (Malta)",
language: "mt",
numberFormat: {
percent: {
pattern: ["-%n","%n"]
},
currency: {
pattern: ["-$n","$n"],
symbol: "€"
}
},
calendars: {
standard: $.extend(true, {}, standard, {
firstDay: 1,
days: {
names: ["Il-Ħadd","It-Tnejn","It-Tlieta","L-Erbgħa","Il-Ħamis","Il-Ġimgħa","Is-Sibt"],
namesAbbr: ["Ħad","Tne","Tli","Erb","Ħam","Ġim","Sib"],
namesShort: ["I","I","I","L","I","I","I"]
},
months: {
names: ["Jannar","Frar","Marzu","April","Mejju","Ġunju","Lulju","Awissu","Settembru","Ottubru","Novembru","Diċembru",""],
namesAbbr: ["Jan","Fra","Mar","Apr","Mej","Ġun","Lul","Awi","Set","Ott","Nov","Diċ",""]
},
patterns: {
d: "dd/MM/yyyy",
D: "dddd, d' ta\\' 'MMMM yyyy",
t: "HH:mm",
T: "HH:mm:ss",
f: "dddd, d' ta\\' 'MMMM yyyy HH:mm",
F: "dddd, d' ta\\' 'MMMM yyyy HH:mm:ss",
M: "d' ta\\' 'MMMM",
Y: "MMMM yyyy"
}
})
}
}, cultures["mt-MT"]);
culture.calendar = culture.calendars.standard;
})(jQuery);
|
Kapinko/CJAF
|
lib/jquery/global/globinfo/jquery.glob.mt-MT.js
|
JavaScript
|
lgpl-3.0
| 1,735
|
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum 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.
//
// The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
/*
Show nicely (but simple) formatted HTML error pages (or respond with JSON
if the appropriate `Accept` header is set)) for the http package.
*/
package http
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
"time"
"github.com/Lopastvertoleta/go-ethereum/log"
)
//templateMap holds a mapping of an HTTP error code to a template
var templateMap map[int]*template.Template
//parameters needed for formatting the correct HTML page
type ErrorParams struct {
Msg string
Code int
Timestamp string
template *template.Template
Details template.HTML
}
//we init the error handling right on boot time, so lookup and http response is fast
func init() {
initErrHandling()
}
func initErrHandling() {
//pages are saved as strings - get these strings
genErrPage := GetGenericErrorPage()
notFoundPage := GetNotFoundErrorPage()
//map the codes to the available pages
tnames := map[int]string{
0: genErrPage, //default
400: genErrPage,
404: notFoundPage,
500: genErrPage,
}
templateMap = make(map[int]*template.Template)
for code, tname := range tnames {
//assign formatted HTML to the code
templateMap[code] = template.Must(template.New(fmt.Sprintf("%d", code)).Parse(tname))
}
}
//ShowError is used to show an HTML error page to a client.
//If there is an `Accept` header of `application/json`, JSON will be returned instead
//The function just takes a string message which will be displayed in the error page.
//The code is used to evaluate which template will be displayed
//(and return the correct HTTP status code)
func ShowError(w http.ResponseWriter, r *http.Request, msg string, code int) {
if code == http.StatusInternalServerError {
log.Error(msg)
}
respond(w, r, &ErrorParams{
Code: code,
Msg: msg,
Timestamp: time.Now().Format(time.RFC1123),
template: getTemplate(code),
})
}
//evaluate if client accepts html or json response
func respond(w http.ResponseWriter, r *http.Request, params *ErrorParams) {
w.WriteHeader(params.Code)
if r.Header.Get("Accept") == "application/json" {
respondJson(w, params)
} else {
respondHtml(w, params)
}
}
//return a HTML page
func respondHtml(w http.ResponseWriter, params *ErrorParams) {
err := params.template.Execute(w, params)
if err != nil {
log.Error(err.Error())
}
}
//return JSON
func respondJson(w http.ResponseWriter, params *ErrorParams) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(params)
}
//get the HTML template for a given code
func getTemplate(code int) *template.Template {
if val, tmpl := templateMap[code]; tmpl {
return val
} else {
return templateMap[0]
}
}
|
Lopastvertoleta/go-ethereum
|
swarm/api/http/error.go
|
GO
|
lgpl-3.0
| 3,454
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns='http://www.w3.org/1999/xhtml' lang='he' dir='rtl'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=windows-1255' />
<meta http-equiv='Content-Script-Type' content='text/javascript' />
<meta http-equiv='revisit-after' content='15 days' />
<title>ðæç</title>
<link rel='stylesheet' type='text/css' href='../../../_script/klli.css' />
<link rel='stylesheet' type='text/css' href='../../../tnk1/_themes/klli.css' />
<meta name='author' content="" />
<meta name='receiver' content="" />
<meta name='jmQovc' content="tnk1/ljon/jorj/nzx" />
<meta name='tvnit' content="tnk_jorj" />
<meta name='description' lang='he' content="ðæç" />
<meta name='description' lang='en' content="this page is in Hebrew" />
<meta name='keywords' lang='he' content="ðæç áúð"ê,ðæç" />
</head>
<!--
PHP Programming by Erel Segal - Rent a Brain http://tora.us.fm/rentabrain
-->
<body lang='he' dir='rtl' id = 'tnk1_ljon_jorj_nzx' class='ajmz tnk_jorj'>
<div class='pnim'>
<script type='text/javascript' src='../../../_script/vars.js'></script>
<!--NiwutElyon0-->
<div class='NiwutElyon'>
<div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>><a href='../../../tnk1/ljon/index.html'>ìùåï äî÷øà</a>><a href='../../../tnk1/ljon/jorj/index.html'>ùåøùéí</a>><a href='../../../tnk1/ljon/jorj/g.html'>â</a>><a href='../../../tnk1/ljon/jorj/g=z.html'>â=æ</a>><a href='../../../tnk1/ljon/jorj/z.html'>æ</a>><a href='../../../tnk1/ljon/jorj/z=s.html'>æ=ñ</a>><a href='../../../tnk1/ljon/jorj/nzx=nsx.html'>ðæç=ðñç</a>></div>
</div>
<!--NiwutElyon1-->
<h1 id='h1'>ðæç</h1>
<div id='idfields'>
<p>÷åã: ðæç áúð"ê</p>
<p>ñåâ: àùîæ</p>
<p>îàú: </p>
<p>àì: </p>
</div>
<script type='text/javascript'>kotrt()</script>
<ul id='ulbnim'>
<li>äâãøä_ëììéú: <span class='hgdrh_kllyt dor1'>= òðéðå ëîå ðñç.<small> [ùáé"ì]</small></span> </li>
<li>ôåòì: <span class='pwel dor1'>ðæÇç (ôòì)</span>
<div class='dor2'>
<span class='hgdrh'>[ø÷ áòúéã "éÄæÌÇç"].</span>
<a href='../../../tnk1/messages/prqim_t02_0.html' class='hgdrh' title='îéìéí ùéù ø÷ áñôø ùîåú'><small>[áàä ø÷ áñôø ùîåú]</small></a>
</div><!--dor2-->
</li>
<li>öéìåí: <span class='cylwm dor1'><img src='' /></span> </li>
</ul><!--end-->
<script type='text/javascript'>
AnalyzeBnim();
ktov_bnim_jorj();
</script>
<h2 id='tguvot'>úåñôåú åúâåáåú</h2>
<script type='text/javascript'>ktov_bnim_axrim("<"+"ul>","</"+"ul>")</script>
<script type='text/javascript'>tguva(); txtit()</script>
</div><!--pnim-->
</body>
</html>
|
erelsgl/erel-sites
|
tnk1/ljon/jorj/nzx.html
|
HTML
|
lgpl-3.0
| 2,720
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="ApiGen 2.8.0" />
<title>Class tschiemer\Aspsms\Response | aspsms-php</title>
<script type="text/javascript" src="resources/combined.js?922972382"></script>
<script type="text/javascript" src="elementlist.js?1436315765"></script>
<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li><a href="namespace-None.html">None</a>
</li>
<li><a href="namespace-PHP.html">PHP</a>
</li>
<li class="active"><a href="namespace-tschiemer.html">tschiemer<span></span></a>
<ul>
<li class="active"><a href="namespace-tschiemer.Aspsms.html">Aspsms<span></span></a>
<ul>
<li><a href="namespace-tschiemer.Aspsms.Http.html">Http</a>
</li>
<li><a href="namespace-tschiemer.Aspsms.Soap.html">Soap</a>
</li>
<li><a href="namespace-tschiemer.Aspsms.Xml.html">Xml</a>
</li>
</ul></li></ul></li>
</ul>
</div>
<hr />
<div id="elements">
<h3>Classes</h3>
<ul>
<li><a href="class-tschiemer.Aspsms.AbstractClient.html">AbstractClient</a></li>
<li><a href="class-tschiemer.Aspsms.AbstractSimpleClient.html">AbstractSimpleClient</a></li>
<li><a href="class-tschiemer.Aspsms.Request.html">Request</a></li>
<li class="active"><a href="class-tschiemer.Aspsms.Response.html">Response</a></li>
<li><a href="class-tschiemer.Aspsms.SimpleClient.html">SimpleClient</a></li>
<li><a href="class-tschiemer.Aspsms.Strings.html">Strings</a></li>
</ul>
<h3>Exceptions</h3>
<ul>
<li><a href="class-tschiemer.Aspsms.ServiceException.html">ServiceException</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="text" />
<input type="submit" value="Search" />
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li>
<a href="namespace-tschiemer.Aspsms.html" title="Summary of tschiemer\Aspsms"><span>Namespace</span></a>
</li>
<li class="active">
<span>Class</span> </li>
</ul>
<ul>
<li>
<a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a>
</li>
</ul>
<ul>
</ul>
</div>
<div id="content" class="class">
<h1>Class Response</h1>
<div class="description">
<p>Shared response object used for request abstraction</p>
</div>
<div class="info">
<b>Namespace:</b> <a href="namespace-tschiemer.html">tschiemer</a>\<a href="namespace-tschiemer.Aspsms.html">Aspsms</a><br />
<b>Package:</b> aspsms<br />
<b>Copyright:</b>
2013 Philip Tschiemer, <<a
href="mailto:tschiemer@filou.se">tschiemer@<!---->filou.se</a>><br />
<b>License:</b>
<a href="LGPL">v3 http://www.gnu.org/licenses/lgpl-3.0.txt</a><br />
<b>Version:</b>
1.1.0<br />
<b>Link:</b>
<a href="https://github.com/tschiemer/aspsms-php">https://github.com/tschiemer/aspsms-php</a><br />
<b>Located at</b> <a href="source-class-tschiemer.Aspsms.Response.html#5-109" title="Go to source code">lib/tschiemer/Aspsms/Response.php</a><br />
</div>
<table class="summary" id="methods">
<caption>Methods summary</caption>
<tr data-order="__construct" id="___construct">
<td class="attributes"><code>
public
</code>
</td>
<td class="name"><div>
<a class="anchor" href="#___construct">#</a>
<code><a href="source-class-tschiemer.Aspsms.Response.html#47-62" title="Go to source code">__construct</a>( <span>Aspsms\Request,string <var>$request</var></span> )</code>
<div class="description short">
<p>Constructor</p>
</div>
<div class="description detailed hidden">
<p>Constructor</p>
<h4>Parameters</h4>
<div class="list"><dl>
<dt><var>$request</var></dt>
<dd><code>Aspsms\Request,string</code><br>$request</dd>
</dl></div>
</div>
</div></td>
</tr>
<tr data-order="requestName" id="_requestName">
<td class="attributes"><code>
public
string
</code>
</td>
<td class="name"><div>
<a class="anchor" href="#_requestName">#</a>
<code><a href="source-class-tschiemer.Aspsms.Response.html#64-71" title="Go to source code">requestName</a>( )</code>
<div class="description short">
<p>Getter</p>
</div>
<div class="description detailed hidden">
<p>Getter</p>
<h4>Returns</h4>
<div class="list">
<code>string</code><br />
</div>
</div>
</div></td>
</tr>
<tr data-order="statusCode" id="_statusCode">
<td class="attributes"><code>
public
integer
</code>
</td>
<td class="name"><div>
<a class="anchor" href="#_statusCode">#</a>
<code><a href="source-class-tschiemer.Aspsms.Response.html#73-85" title="Go to source code">statusCode</a>( <span>NULL,int <var>$code</var> = <span class="php-keyword1">NULL</span></span> )</code>
<div class="description short">
<p>Getter/setter. Sets new code iff a value is passed.</p>
</div>
<div class="description detailed hidden">
<p>Getter/setter. Sets new code iff a value is passed.</p>
<h4>Parameters</h4>
<div class="list"><dl>
<dt><var>$code</var></dt>
<dd><code>NULL,int</code><br>$code</dd>
</dl></div>
<h4>Returns</h4>
<div class="list">
<code>integer</code><br />
</div>
</div>
</div></td>
</tr>
<tr data-order="statusDescription" id="_statusDescription">
<td class="attributes"><code>
public
string
</code>
</td>
<td class="name"><div>
<a class="anchor" href="#_statusDescription">#</a>
<code><a href="source-class-tschiemer.Aspsms.Response.html#87-99" title="Go to source code">statusDescription</a>( <span>NULL,string <var>$description</var> = <span class="php-keyword1">NULL</span></span> )</code>
<div class="description short">
<p>Getter/setter. Sets new description iff a value is passed.</p>
</div>
<div class="description detailed hidden">
<p>Getter/setter. Sets new description iff a value is passed.</p>
<h4>Parameters</h4>
<div class="list"><dl>
<dt><var>$description</var></dt>
<dd><code>NULL,string</code><br>$description</dd>
</dl></div>
<h4>Returns</h4>
<div class="list">
<code>string</code><br />
</div>
</div>
</div></td>
</tr>
<tr data-order="result" id="_result">
<td class="attributes"><code>
public
mixed
</code>
</td>
<td class="name"><div>
<a class="anchor" href="#_result">#</a>
<code><a href="source-class-tschiemer.Aspsms.Response.html#101-108" title="Go to source code">result</a>( )</code>
<div class="description short">
<p>Getter</p>
</div>
<div class="description detailed hidden">
<p>Getter</p>
<h4>Returns</h4>
<div class="list">
<code>mixed</code><br />
</div>
</div>
</div></td>
</tr>
</table>
<table class="summary" id="constants">
<caption>Constants summary</caption>
<tr data-order="STAT_OK" id="STAT_OK">
<td class="attributes"><code>integer</code></td>
<td class="name"><code>
<a href="source-class-tschiemer.Aspsms.Response.html#16" title="Go to source code"><b>STAT_OK</b></a>
</code></td>
<td class="value"><code><span class="php-num">1</span></code></td>
<td class="description"><div>
<a href="#STAT_OK" class="anchor">#</a>
<div class="description short">
</div>
<div class="description detailed hidden">
</div>
</div></td>
</tr>
</table>
<table class="summary" id="properties">
<caption>Properties summary</caption>
<tr data-order="requestName" id="$requestName">
<td class="attributes"><code>
public
string
</code></td>
<td class="name">
<a href="source-class-tschiemer.Aspsms.Response.html#18-23" title="Go to source code"><var>$requestName</var></a>
</td>
<td class="value"><code><span class="php-quote">''</span></code></td>
<td class="description"><div>
<a href="#$requestName" class="anchor">#</a>
<div class="description short">
<p>Request name for which this is a response</p>
</div>
<div class="description detailed hidden">
<p>Request name for which this is a response</p>
</div>
</div></td>
</tr>
<tr data-order="statusCode" id="$statusCode">
<td class="attributes"><code>
public
integer
</code></td>
<td class="name">
<a href="source-class-tschiemer.Aspsms.Response.html#25-30" title="Go to source code"><var>$statusCode</var></a>
</td>
<td class="value"><code><span class="php-num">0</span></code></td>
<td class="description"><div>
<a href="#$statusCode" class="anchor">#</a>
<div class="description short">
<p>Status code</p>
</div>
<div class="description detailed hidden">
<p>Status code</p>
</div>
</div></td>
</tr>
<tr data-order="statusDescription" id="$statusDescription">
<td class="attributes"><code>
public
string
</code></td>
<td class="name">
<a href="source-class-tschiemer.Aspsms.Response.html#32-37" title="Go to source code"><var>$statusDescription</var></a>
</td>
<td class="value"><code><span class="php-quote">''</span></code></td>
<td class="description"><div>
<a href="#$statusDescription" class="anchor">#</a>
<div class="description short">
<p>Status Description</p>
</div>
<div class="description detailed hidden">
<p>Status Description</p>
</div>
</div></td>
</tr>
<tr data-order="result" id="$result">
<td class="attributes"><code>
public
mixed
</code></td>
<td class="name">
<a href="source-class-tschiemer.Aspsms.Response.html#40-45" title="Go to source code"><var>$result</var></a>
</td>
<td class="value"><code></code></td>
<td class="description"><div>
<a href="#$result" class="anchor">#</a>
<div class="description short">
<p>Essential request result</p>
</div>
<div class="description detailed hidden">
<p>Essential request result</p>
</div>
</div></td>
</tr>
</table>
</div>
<div id="footer">
aspsms-php API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a>
</div>
</div>
</div>
</body>
</html>
|
tschiemer/aspsms-php
|
doc/php/class-tschiemer.Aspsms.Response.html
|
HTML
|
lgpl-3.0
| 10,613
|
/*
Aseba - an event-based framework for distributed robot control
Copyright (C) 2007--2016:
Stephane Magnenat <stephane at magnenat dot net>
(http://stephane.magnenat.net)
and other contributors, see authors.txt for details
This example is based on a first work of Olivier Marti (2010 - 2011).
Stripped down & cleaned version by Florian Vaussard (2013).
This program 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, version 3 of the License.
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 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 "DashelInterface.hpp"
#include <Timer.hpp>
#include <dashel/dashel.h>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QSharedPointer>
#include <QtXml/QDomDocument>
#include <string>
#include <iterator>
#include <cstdlib>
#include <iostream>
#include <chrono>
#include <thread>
using namespace Dashel;
using namespace Aseba;
/*!
* Constructor.
*/
DashelInterface::DashelInterface() :
NodesManager(),
m_stream(nullptr),
m_dashelParams(""),
m_isRunning(false),
m_isConnected(false)
{
qRegisterMetaType<QSharedPointer<Aseba::UserMessage>>("QSharedPointer<Aseba::UserMessage>");
}
/*!
* Destructor.
*/
DashelInterface::~DashelInterface()
{
disconnectAseba();
}
/*!
* Connect to any kind of valid Dashel target (TCP, serial, CAN,...).
*/
void DashelInterface::connectAseba(const QString& dashelTarget)
{
m_dashelParams = dashelTarget;
m_isRunning = true;
start();
}
/*!
* Connect through a TCP socket.message
*/
void DashelInterface::connectAseba(const QString& ip, const QString& port)
{
connectAseba("tcp:" + ip + ";port=" + port);
}
/*!
* Cleanly disconnect.
*/
void DashelInterface::disconnectAseba()
{
stop();
wait();
}
/*!
* Loads the script via dashel.
*/
bool DashelInterface::loadScript(const QString& fileName)
{
if (!isConnected()) {
qDebug() << "There is no active connectin, use 'connectAseba'";
return false;
}
QFile file(fileName);
if (!file.open(QFile::ReadOnly))
{
qDebug() << QString("The script file %1 doesn't exist")
.arg(fileName);
return false;
}
QDomDocument document("aesl-source");
QString errorMsg;
int errorLine;
int errorColumn;
if (!document.setContent(&file, false, &errorMsg, &errorLine, &errorColumn))
{
qDebug() << QString("Error in XML source file: %0 at line %1, column %2")
.arg(errorMsg).arg(errorLine)
.arg(errorColumn);
return false;
}
commonDefinitions.events.clear();
commonDefinitions.constants.clear();
// userDefinedVariablesMap.clear();
int noNodeCount = 0;
QDomNode domNode = document.documentElement().firstChild();
// FIXME: this code depends on event and contants being before any code
bool wasError = false;
while (!domNode.isNull())
{
if (domNode.isElement())
{
QDomElement element = domNode.toElement();
if (element.tagName() == "node")
{
bool ok;
const unsigned nodeId(getNodeId(element.attribute("name").toStdWString(),
element.attribute("nodeId", 0).toUInt(), &ok));
if (ok)
{
std::wistringstream is(element.firstChild().toText().data().toStdWString());
Error error;
BytecodeVector bytecode;
unsigned allocatedVariablesCount;
Compiler compiler;
compiler.setTargetDescription(getDescription(nodeId));
compiler.setCommonDefinitions(&commonDefinitions);
bool result = compiler.compile(is, bytecode, allocatedVariablesCount, error);
if (result)
{
typedef std::vector<Message*> MessageVector;
MessageVector messages;
sendBytecode(messages, nodeId, std::vector<uint16>(bytecode.begin(), bytecode.end()));
for (MessageVector::const_iterator it = messages.begin(); it != messages.end(); ++it)
{
sendMessage(**it);
delete *it;
}
Run msg(nodeId);
sendMessage(msg);
}
else
{
qDebug() << QString::fromStdWString(error.toWString());
wasError = true;
break;
}
// // retrieve user-defined variables for use in get/set
// userDefinedVariablesMap[element.attribute("name")] = *compiler.getVariablesMap();
}
else
noNodeCount++;
}
else if (element.tagName() == "event")
{
const QString eventName(element.attribute("name"));
const unsigned eventSize(element.attribute("size").toUInt());
if (eventSize > ASEBA_MAX_EVENT_ARG_SIZE)
{
qDebug() << QString("Event %1 has a length %2 larger than maximum %3")
.arg(eventName)
.arg(eventSize)
.arg(ASEBA_MAX_EVENT_ARG_SIZE);
wasError = true;
break;
}
else
{
commonDefinitions.events.push_back(NamedValue(eventName.toStdWString(), eventSize));
}
}
else if (element.tagName() == "constant")
{
commonDefinitions.constants.push_back(NamedValue(element.attribute("name").toStdWString(), element.attribute("value").toInt()));
}
}
domNode = domNode.nextSibling();
}
// check if there was an error
if (wasError)
{
qDebug() << QString("There was an error while loading script %1")
.arg(fileName);
commonDefinitions.events.clear();
commonDefinitions.constants.clear();
// userDefinedVariablesMap.clear();
}
// check if there was some matching problem
if (noNodeCount)
{
qDebug() << QString("%1 scripts have no corresponding nodes in the "
"current network and have not been loaded.")
.arg(noNodeCount);
}
return true;
}
/*!
* From Dashel::Hub. Message coming from a node. Consider _only_ UserMessage.
* Discard other types of messages (debug, etc.)
*/
void DashelInterface::incomingData(Dashel::Stream *stream)
{
try {
Aseba::Message *message = Aseba::Message::receive(stream);
// scan this message for nodes descriptions
Aseba::NodesManager::processMessage(message);
QSharedPointer<Aseba::UserMessage> userMessage(dynamic_cast<Aseba::UserMessage *>(message));
if (userMessage)
emit messageAvailable(userMessage);
} catch (const DashelException& e) {
// if this stream has a problem, ignore it for now, and let Hub call
// connectionClosed later.
qDebug() << "error while reading message";
}
}
/*!
* Send a UserMessage with ID 'id', and optionnally some data values.
*/
void DashelInterface::sendEvent(unsigned id, const Values& values)
{
if (isConnected())
{
Aseba::UserMessage::DataVector data(values.size());
QListIterator<qint16> it(values);
unsigned i = 0;
while (it.hasNext())
data[i++] = it.next();
try {
Aseba::UserMessage(id, data).serialize(m_stream);
m_stream->flush();
} catch (const DashelException& e) {
// if this stream has a problem, ignore it for now, and let Hub call connectionClosed later.
qDebug() << "Error while writing message";
}
}
}
/*!
* Sends an named event to the robot.
*/
void DashelInterface::sendEventName(const QString& name, const Values& data)
{
size_t event;
if (commonDefinitions.events.contains(name.toStdWString(), &event))
sendEvent(event, data);
else
qDebug() << QString("No event named %1").arg(name);
}
/*!
* Dashel connection was closed.
*/
void DashelInterface::connectionClosed(Dashel::Stream* stream, bool abnormal)
{
if (abnormal)
qDebug() << QString("Abnormal connection closed to %1 : %2")
.arg(stream->getTargetName().c_str())
.arg(stream->getFailReason().c_str());
else
qDebug() << QString("Normal connection closed to %1")
.arg(stream->getTargetName().c_str());
emit dashelDisconnection();
m_isConnected = false;
m_stream = nullptr;
}
// internals
void DashelInterface::run()
{
// a timer to stop trying to connect on a timeout
Timer connectionTimer;
connectionTimer.reset();
// try to connect
while (1) {
try {
m_stream = Dashel::Hub::connect(m_dashelParams.toStdString());
emit dashelConnection();
m_isConnected = true;
break;
} catch (const Dashel::DashelException& e) {
qDebug() << "Cannot connect to target: "
<< m_dashelParams;
// if can't connect then stop
if (connectionTimer.isTimedOutSec(10)) {
qDebug() << "Stop trying to connect to target"
<< m_dashelParams;
break;
} else {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
}
if (isConnected()) {
QObject::connect(this, &DashelInterface::messageAvailable,
this, &DashelInterface::dispatchEvent);
}
while (m_isRunning)
Dashel::Hub::run();
if (m_stream) {
connectionClosed(m_stream, false);
Dashel::Hub::closeStream(m_stream);
}
}
void DashelInterface::sendMessage(const Aseba::Message& message)
{
// this is called from the GUI thread through processMessage() or
// pingNetwork(), so we must lock the Hub before sending
lock();
if (isConnected()) {
try {
message.serialize(m_stream);
m_stream->flush();
unlock();
} catch (const Dashel::DashelException& e) {
unlock();
qDebug() << "Dashel exception: " << e.what();
}
} else {
unlock();
}
}
void DashelInterface::stop()
{
m_isRunning = false;
Dashel::Hub::stop();
}
/*!
* Flag an event to listen for, and associate callback function (passed by
* pointer).
*/
void DashelInterface::connectEvent(const QString& eventName, EventCallback callback)
{
// associate callback with event name
m_callbacks.insert(std::make_pair(eventName, callback));
}
/*!
* Callback (slot) used to retrieve subscribed event information.
*/
void DashelInterface::dispatchEvent(QSharedPointer<Aseba::UserMessage> message)
{
// get name
QString eventName = QString::fromWCharArray(commonDefinitions.events[message->type].name.c_str());
// convert values
Values eventData;
for (auto& value : message->data)
eventData.append(value);
// find and trigger matching callback
if( m_callbacks.count(eventName) > 0)
{
auto eventCallbacks = m_callbacks.equal_range(eventName);
for (auto iterator = eventCallbacks.first; iterator != eventCallbacks.second; ++iterator)
(iterator->second)(eventData);
}
}
|
gribovskiy/CATS2
|
source/robot-control/interfaces/DashelInterface.cpp
|
C++
|
lgpl-3.0
| 12,643
|
// Created file "Lib\src\Uuid\functiondiscovery"
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(PKEY_DeviceDisplay_PrimaryCategory, 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57);
|
Frankie-PellesC/fSDK
|
Lib/src/Uuid/functiondiscovery0000011B.c
|
C
|
lgpl-3.0
| 476
|
/*******************************************************************************
* Title: CloudSimDisk
* Description: a module for energy aware storage simulation in CloudSim
* Author: Baptiste Louis
* Date: June 2015
*
* Address: baptiste_louis@live.fr
* Source: https://github.com/Udacity2048/CloudSimDisk
* Website: http://baptistelouis.weebly.com/projects.html
*
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
* Copyright (c) 2015, Luleå University of Technology, Sweden.
*******************************************************************************/
package org.cloudbus.cloudsimdisk.models.hdd;
/**
* Storage Model based on HGST Ultrastar C10K900 Review (HUC109090CSS600).
*
* Link: http://www.storagereview.com/hgst_ultrastar_c10k900_review
*
* @author Baptiste Louis
*/
public class StorageModelHddHGSTUltrastarHUC109090CSS600 extends StorageModelHdd {
/* (non-Javadoc)
*
* @see org.cloudbus.cloudsim.power.models.PowerModelSpecPower#getPowerData(int) */
@Override
protected Object getCharacteristic(int key) {
switch (key) {
case 0:
return "HGST Western Digital"; // Manufacturer
case 1:
return "HUC109090CSS600"; // Model Number
case 2:
return 900000; // capacity (MB)
case 3:
return 0.003; // Average Rotation Latency (s)
case 4:
return 0.004; // Average Seek Time (s)
case 5:
return 198.0; // Maximum Internal Data Transfer Rate (MB/s)
default:
return "n/a";
// SCALABILITY: add new characteristic by adding new CASE.
//
// case <KEY_NUMBER>:
// return <PARAMETER_VALUE>;
//
}
}
}
|
Udacity2048/CloudSimDisk
|
sources/org/cloudbus/cloudsimdisk/models/hdd/StorageModelHddHGSTUltrastarHUC109090CSS600.java
|
Java
|
lgpl-3.0
| 1,662
|
/*****************************************************************************
Copyright (c) 2010, Intel Corp.
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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************
* Contents: Native high-level C interface to LAPACK function ssbev
* Author: Intel Corporation
* Generated October, 2010
*****************************************************************************/
#include "lapacke.h"
#include "lapacke_utils.h"
lapack_int LAPACKE_ssbev( int matrix_order, char jobz, char uplo, lapack_int n,
lapack_int kd, float* ab, lapack_int ldab, float* w,
float* z, lapack_int ldz )
{
lapack_int info = 0;
float* work = NULL;
if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_ssbev", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
/* Optionally check input matrices for NaNs */
if( LAPACKE_ssb_nancheck( matrix_order, uplo, n, kd, ab, ldab ) ) {
return -6;
}
#endif
/* Allocate memory for working array(s) */
work = (float*)LAPACKE_malloc( sizeof(float) * MAX(1,3*n-2) );
if( work == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
/* Call middle-level interface */
info = LAPACKE_ssbev_work( matrix_order, jobz, uplo, n, kd, ab, ldab, w, z,
ldz, work );
/* Release memory and exit */
LAPACKE_free( work );
exit_level_0:
if( info == LAPACK_WORK_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_ssbev", info );
}
return info;
}
|
mfine/libswiftnav
|
lapacke/src/lapacke_ssbev.c
|
C
|
lgpl-3.0
| 3,125
|
/* cladiv.f -- translated by f2c (version 20061008).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "pnl/pnl_f2c.h"
/* Complex */ VOID cladiv_(complex * ret_val, complex *x, complex *y)
{
/* System generated locals */
float r__1, r__2, r__3, r__4;
complex q__1;
/* Builtin functions */
double r_imag(complex *);
/* Local variables */
float zi, zr;
extern int sladiv_(float *, float *, float *, float *, float *
, float *);
/* -- LAPACK auxiliary routine (version 3.2) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* CLADIV := X / Y, where X and Y are complex. The computation of X / Y */
/* will not overflow on an intermediary step unless the results */
/* overflows. */
/* Arguments */
/* ========= */
/* X (input) COMPLEX */
/* Y (input) COMPLEX */
/* The complex scalars X and Y. */
/* ===================================================================== */
/* .. Local Scalars .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
r__1 = x->r;
r__2 = r_imag(x);
r__3 = y->r;
r__4 = r_imag(y);
sladiv_(&r__1, &r__2, &r__3, &r__4, &zr, &zi);
q__1.r = zr, q__1.i = zi;
ret_val->r = q__1.r, ret_val->i = q__1.i;
return ;
/* End of CLADIV */
} /* cladiv_ */
|
pnlnum/pnl
|
src/liblapack/cladiv.c
|
C
|
lgpl-3.0
| 1,889
|
<?php
/**
* Smarty PHPunit tests loadFilter method
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for loadFilter method tests
*/
class LoadFilterTest extends PHPUnit_Framework_TestCase
{
public function setUp() {
$this->smarty = SmartyTests::$smarty;
SmartyTests::init();
}
/**
* test loadFilter method
*/
public function testLoadFilter() {
$this->smarty->loadFilter('output', 'trimwhitespace');
$this->assertTrue(is_callable($this->smarty->registered_filters['output']['smarty_outputfilter_trimwhitespace']));
}
}
|
chriseling/brainy
|
test/LoadFilterTest.php
|
PHP
|
lgpl-3.0
| 585
|
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "untagresourcerequest.h"
#include "untagresourcerequest_p.h"
#include "untagresourceresponse.h"
#include "schemasrequest_p.h"
namespace QtAws {
namespace Schemas {
/*!
* \class QtAws::Schemas::UntagResourceRequest
* \brief The UntagResourceRequest class provides an interface for Schemas UntagResource requests.
*
* \inmodule QtAwsSchemas
*
* Amazon EventBridge Schema
*
* \sa SchemasClient::untagResource
*/
/*!
* Constructs a copy of \a other.
*/
UntagResourceRequest::UntagResourceRequest(const UntagResourceRequest &other)
: SchemasRequest(new UntagResourceRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a UntagResourceRequest object.
*/
UntagResourceRequest::UntagResourceRequest()
: SchemasRequest(new UntagResourceRequestPrivate(SchemasRequest::UntagResourceAction, this))
{
}
/*!
* \reimp
*/
bool UntagResourceRequest::isValid() const
{
return false;
}
/*!
* Returns a UntagResourceResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * UntagResourceRequest::response(QNetworkReply * const reply) const
{
return new UntagResourceResponse(*this, reply);
}
/*!
* \class QtAws::Schemas::UntagResourceRequestPrivate
* \brief The UntagResourceRequestPrivate class provides private implementation for UntagResourceRequest.
* \internal
*
* \inmodule QtAwsSchemas
*/
/*!
* Constructs a UntagResourceRequestPrivate object for Schemas \a action,
* with public implementation \a q.
*/
UntagResourceRequestPrivate::UntagResourceRequestPrivate(
const SchemasRequest::Action action, UntagResourceRequest * const q)
: SchemasRequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the UntagResourceRequest
* class' copy constructor.
*/
UntagResourceRequestPrivate::UntagResourceRequestPrivate(
const UntagResourceRequestPrivate &other, UntagResourceRequest * const q)
: SchemasRequestPrivate(other, q)
{
}
} // namespace Schemas
} // namespace QtAws
|
pcolby/libqtaws
|
src/schemas/untagresourcerequest.cpp
|
C++
|
lgpl-3.0
| 2,844
|
/*
* ipsw.c
* Definitions for communicating with Apple's TSS server.
*
* Copyright (c) 2010 Joshua Hill. All Rights Reserved.
*
* 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 2.1 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef IDEVICERESTORE_TSS_H
#define IDEVICERESTORE_TSS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <plist/plist.h>
plist_t tss_send_request(plist_t request);
plist_t tss_create_request(plist_t build_identity, uint64_t ecid, unsigned char* nonce, int nonce_size, int buildno);
int tss_get_ticket(plist_t tss, unsigned char** ticket, uint32_t* tlen);
int tss_get_entry_path(plist_t tss, const char* entry, char** path);
int tss_get_blob_by_path(plist_t tss, const char* path, char** blob);
int tss_get_blob_by_name(plist_t tss, const char* entry, char** blob);
#ifdef __cplusplus
}
#endif
#endif
|
plnep00f/idevicerestore
|
src/tss.h
|
C
|
lgpl-3.0
| 1,486
|
/*
* The libcdata header wrapper
*
* Copyright (C) 2011-2022, Joachim Metz <joachim.metz@gmail.com>
*
* Refer to AUTHORS for acknowledgements.
*
* This program 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 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 Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#if !defined( _LIBSCCA_LIBCDATA_H )
#define _LIBSCCA_LIBCDATA_H
#include <common.h>
/* Define HAVE_LOCAL_LIBCDATA for local use of libcdata
*/
#if defined( HAVE_LOCAL_LIBCDATA )
#include <libcdata_array.h>
#include <libcdata_btree.h>
#include <libcdata_definitions.h>
#include <libcdata_list.h>
#include <libcdata_list_element.h>
#include <libcdata_range_list.h>
#include <libcdata_tree_node.h>
#include <libcdata_types.h>
#else
/* If libtool DLL support is enabled set LIBCDATA_DLL_IMPORT
* before including libcdata.h
*/
#if defined( _WIN32 ) && defined( DLL_IMPORT )
#define LIBCDATA_DLL_IMPORT
#endif
#include <libcdata.h>
#endif /* defined( HAVE_LOCAL_LIBCDATA ) */
#endif /* !defined( _LIBSCCA_LIBCDATA_H ) */
|
libyal/libscca
|
libscca/libscca_libcdata.h
|
C
|
lgpl-3.0
| 1,545
|
package com.beimin.eveapi.model.eve;
import java.util.ArrayList;
import java.util.Collection;
public class SkillGroup implements Comparable<SkillGroup> {
private String groupName;
private int groupID;
private final Collection<Skill> skills = new ArrayList<Skill>();
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public int getGroupID() {
return groupID;
}
public void setGroupID(int groupID) {
this.groupID = groupID;
}
public void add(Skill skill) {
skills.add(skill);
}
public Collection<Skill> getSkills() {
return skills;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(groupName).append(" (").append(skills.size()).append(" skills)\n");
for (Skill skill : skills) {
result.append("\t").append(skill).append("\n");
}
return result.toString();
}
public int compareTo(SkillGroup o) {
return groupName.compareTo(o.groupName);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + groupID;
result = prime * result + ((groupName == null) ? 0 : groupName.hashCode());
result = prime * result + ((skills == null) ? 0 : skills.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SkillGroup other = (SkillGroup) obj;
if (groupID != other.groupID)
return false;
if (groupName == null) {
if (other.groupName != null)
return false;
} else if (!groupName.equals(other.groupName))
return false;
if (skills == null) {
if (other.skills != null)
return false;
} else if (!skills.equals(other.skills))
return false;
return true;
}
}
|
stevelle/eveapi
|
src/main/java/com/beimin/eveapi/model/eve/SkillGroup.java
|
Java
|
lgpl-3.0
| 1,908
|
#ifndef __SUBSTRATE__PARALLELISM_STRUCT_H
#define __SUBSTRATE__PARALLELISM_STRUCT_H
#include <stdbool.h>
#include <stdio.h>
struct substrate_parallelism_profile
{
bool * parallelizable_loops; /*< The loops that can be parallelized (from outer to inner loop) */
unsigned int size;
};
struct substrate_parallelism_profile substrate_parallelism_profile_clone(
struct substrate_parallelism_profile * pp);
void substrate_parallelism_profile_free(
struct substrate_parallelism_profile * pp);
void substrate_parallelism_profile_dump(
FILE * output_stream,
struct substrate_parallelism_profile * pp);
void substrate_parallelism_profile_idump(
FILE * output_stream,
struct substrate_parallelism_profile * pp,
unsigned int level);
struct substrate_parallelism_profile substrate_parallelism_profile_fusion(
struct substrate_parallelism_profile * pp1,
struct substrate_parallelism_profile * pp2);
#endif
|
Haerezis/substrate
|
include/substrate/parallelism_struct.h
|
C
|
lgpl-3.0
| 976
|
<?php
/**
* This file is part of FacturaScripts
* Copyright (C) 2015-2018 Carlos Garcia Gomez <neorazorx@gmail.com>
*
* This program 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 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 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/>.
*/
require_once 'base/fs_mysql.php';
require_once 'base/fs_postgresql.php';
/**
* Clase genérica de acceso a la base de datos, ya sea MySQL o PostgreSQL.
*
* @author Carlos García Gómez <neorazorx@gmail.com>
*/
class fs_db2
{
/**
* Transacttiones automáticas activadas si o no.
* @var boolean
*/
private static $auto_transactions;
/**
* Motor utilizado, MySQL o PostgreSQL
* @var fs_mysql|fs_postgresql
*/
private static $engine;
/**
* Última lista de tablas de la base de datos.
* @var array|false
*/
private static $table_list;
public function __construct()
{
if (!isset(self::$engine)) {
if (strtolower(FS_DB_TYPE) == 'mysql') {
self::$engine = new fs_mysql();
} else {
self::$engine = new fs_postgresql();
}
self::$auto_transactions = TRUE;
self::$table_list = FALSE;
}
}
/**
* Inicia una transacción SQL.
* @return boolean
*/
public function begin_transaction()
{
return self::$engine->begin_transaction();
}
/**
* Realiza comprobaciones extra a la tabla.
* @param string $table_name
* @return boolean
*/
public function check_table_aux($table_name)
{
return self::$engine->check_table_aux($table_name);
}
/**
* Desconecta de la base de datos.
* @return boolean
*/
public function close()
{
return self::$engine->close();
}
/**
* Guarda los cambios de una transacción SQL.
* @return boolean
*/
public function commit()
{
return self::$engine->commit();
}
/**
* Compara dos arrays de columnas, devuelve una sentencia sql en caso de encontrar diferencias.
* @param string $table_name
* @param array $xml_cols
* @param array $db_cols
* @return string
*/
public function compare_columns($table_name, $xml_cols, $db_cols)
{
return self::$engine->compare_columns($table_name, $xml_cols, $db_cols);
}
/**
* Compara dos arrays de restricciones, devuelve una sentencia sql en caso de encontrar diferencias.
* @param string $table_name
* @param array $xml_cons
* @param array $db_cons
* @param boolean $delete_only
* @return string
*/
public function compare_constraints($table_name, $xml_cons, $db_cons, $delete_only = FALSE)
{
return self::$engine->compare_constraints($table_name, $xml_cons, $db_cons, $delete_only);
}
/**
* Conecta a la base de datos.
* @return boolean
*/
public function connect()
{
return self::$engine->connect();
}
/**
* Devuelve TRUE si se está conestado a la base de datos.
* @return boolean
*/
public function connected()
{
return self::$engine->connected();
}
/**
* Devuelve el estilo de fecha del motor de base de datos.
* @return string
*/
public function date_style()
{
return self::$engine->date_style();
}
/**
* Escapa las comillas de la cadena de texto.
* @param string $str
* @return string
*/
public function escape_string($str)
{
return self::$engine->escape_string($str);
}
/**
* Ejecuta sentencias SQL sobre la base de datos (inserts, updates o deletes).
* Para hacer selects, mejor usar select() o selec_limit().
* Por defecto se inicia una transacción, se ejecutan las consultas, y si todo
* sale bien, se guarda, sino se deshace.
* Se puede evitar este modo de transacción si se pone false
* en el parametro transaction, o con la función set_auto_transactions(FALSE)
* @param string $sql
* @param boolean $transaction
* @return boolean
*/
public function exec($sql, $transaction = NULL)
{
/// usamos self::$auto_transactions como valor por defecto para la función
if (is_null($transaction)) {
$transaction = self::$auto_transactions;
}
/// limpiamos la lista de tablas, ya que podría haber cambios al ejecutar este sql.
self::$table_list = FALSE;
return self::$engine->exec($sql, $transaction);
}
/**
* Devuelve la sentencia sql necesaria para crear una tabla con la estructura proporcionada.
* @param string $table_name
* @param array $xml_cols
* @param array $xml_cons
* @return string
*/
public function generate_table($table_name, $xml_cols, $xml_cons)
{
return self::$engine->generate_table($table_name, $xml_cols, $xml_cons);
}
/**
* Devuelve el valor de auto_transacions, para saber si las transacciones
* automáticas están activadas o no.
* @return boolean
*/
public function get_auto_transactions()
{
return self::$auto_transactions;
}
/**
* Devuelve un array con las columnas de una tabla dada.
* @param string $table_name
* @return array
*/
public function get_columns($table_name)
{
return self::$engine->get_columns($table_name);
}
/**
* Devuelve una array con las restricciones de una tabla dada.
* @param string $table_name
* @param boolean $extended
* @return array
*/
public function get_constraints($table_name, $extended = FALSE)
{
if ($extended) {
return self::$engine->get_constraints_extended($table_name);
}
return self::$engine->get_constraints($table_name);
}
/**
* Devuelve el historial SQL.
* @return array
*/
public function get_history()
{
return self::$engine->get_history();
}
/**
* Devuelve una array con los indices de una tabla dada.
* @param string $table_name
* @return array
*/
public function get_indexes($table_name)
{
return self::$engine->get_indexes($table_name);
}
/**
* Devuelve un array con los bloqueos de la base de datos.
* @return array
*/
public function get_locks()
{
return self::$engine->get_locks();
}
/**
* Devuelve el nº de selects a la base de datos.
* @return integer
*/
public function get_selects()
{
return self::$engine->get_selects();
}
/**
* Devuelve el nº de transacciones con la base de datos.
* @return integer
*/
public function get_transactions()
{
return self::$engine->get_transactions();
}
/**
* Devuleve el último ID asignado al hacer un INSERT en la base de datos.
* @return integer
*/
public function lastval()
{
return self::$engine->lastval();
}
/**
* Devuelve un array con los nombres de las tablas de la base de datos.
* @return array
*/
public function list_tables()
{
if (self::$table_list === FALSE) {
self::$table_list = self::$engine->list_tables();
}
return self::$table_list;
}
/**
* Deshace los cambios de una transacción SQL.
* @return boolean
*/
public function rollback()
{
return self::$engine->rollback();
}
/**
* Ejecuta una sentencia SQL de tipo select, y devuelve un array con los resultados,
* o false en caso de fallo.
* @param string $sql
* @return array|false
*/
public function select($sql)
{
return self::$engine->select($sql);
}
/**
* Ejecuta una sentencia SQL de tipo select, pero con paginación,
* y devuelve un array con los resultados o false en caso de fallo.
* Limit es el número de elementos que quieres que devuelva.
* Offset es el número de resultado desde el que quieres que empiece.
* @param string $sql
* @param integer $limit
* @param integer $offset
* @return array|false
*/
public function select_limit($sql, $limit = FS_ITEM_LIMIT, $offset = 0)
{
return self::$engine->select_limit($sql, $limit, $offset);
}
/**
* Activa/desactiva las transacciones automáticas en la función exec()
* @param boolean $value
*/
public function set_auto_transactions($value)
{
self::$auto_transactions = $value;
}
/**
* Devuelve el SQL necesario para convertir la columna a entero.
* @param string $col_name
* @return string
*/
public function sql_to_int($col_name)
{
return self::$engine->sql_to_int($col_name);
}
/**
* Devuelve TRUE si la tabla existe, FALSE en caso contrario.
* @param string $name
* @param array $list
* @return boolean
*/
public function table_exists($name, $list = FALSE)
{
$result = FALSE;
if ($list === FALSE) {
$list = $this->list_tables();
}
foreach ($list as $table) {
if ($table['name'] == $name) {
$result = TRUE;
break;
}
}
return $result;
}
/**
* Devuelve el motor de base de datos usado y la versión.
* @return string
*/
public function version()
{
return self::$engine->version();
}
}
|
NeoRazorX/facturascripts_2015
|
base/fs_db2.php
|
PHP
|
lgpl-3.0
| 10,126
|
#include <iostream>
#include <string>
#include <Graphics.h>
#include <Components.h>
using namespace Component;
int main()
{
WindowManager wm = WindowManager();
std::string name = "Blop";
if(wm.initWindow(name))
{
std::cout << "Orthogonals vectors of polygon (0,0) (1,0) (0,1) :" << std::endl;
Polygon p = Polygon::Triangle(Point(0,0), Point(1,0), Point(0,1));
std::vector<Vector> v = p.getOrthogonalsVect();
for(int i=0; i<v.size(); i++)
std::cout<< v[i] << std::endl;
}
return 0;
}
|
Klafyvel/SDL-Platformer-Engine-2D
|
examples/src/main.cpp
|
C++
|
lgpl-3.0
| 552
|
using System.Collections.Generic;
using System.IO;
using SharpCompress.Common;
using SharpCompress.Common.Rar;
using SharpCompress.Common.Rar.Headers;
using SharpCompress.IO;
namespace SharpCompress.Reader.Rar
{
public class RarReaderVolume : RarVolume
{
internal RarReaderVolume(Stream stream, Options options)
: base(StreamingMode.Streaming, stream, options)
{
}
internal override RarFilePart CreateFilePart(FileHeader fileHeader, MarkHeader markHeader)
{
return new NonSeekableStreamFilePart(markHeader, fileHeader);
}
internal override IEnumerable<RarFilePart> ReadFileParts()
{
return GetVolumeFileParts();
}
#if !PORTABLE
public override FileInfo VolumeFile
{
get
{
return null;
}
}
#endif
}
}
|
peterstevens130561/sonarlint-vs
|
its/sharpcompress_b855fd5bf0d1/SharpCompress/Reader/Rar/RarReaderVolume.cs
|
C#
|
lgpl-3.0
| 903
|
/*
* @author ucchy
* @license LGPLv3
* @copyright Copyright ucchy 2014
*/
package com.github.ucchyocean.bp.webstats;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import com.github.ucchyocean.bp.BattlePoints;
/**
* Webコネクションのスレッドクラス
* @author ucchy
*/
public class ConnectionThread extends Thread {
// 顔画像キャッシュの有効期限(1日)
private static final long FACE_EXPIRE_LIMIT = 24 * 60 * 60 * 1000;
private Socket socket;
private FileCache cache;
private BPDataSorter sorter;
/**
* コンストラクタ
* @param socket クライアントからの接続
* @param cache ファイルキャッシュ
* @param sorter BPUserDataのキャッシュ
*/
public ConnectionThread(Socket socket, FileCache cache, BPDataSorter sorter) {
this.socket = socket;
this.cache = cache;
this.sorter = sorter;
}
/**
* 接続処理
* @see java.lang.Thread#run()
*/
public void run() {
PrintStream outstream = null;
BufferedReader reader = null;
boolean isResponced = false;
// クライアントIP
String destIP = "";
// クライアントポート
int destport = -1;
// リクエストファイル
String requestFile = "";
// UserAgent
String userAgent = "";
try {
// クライアントIP
destIP = socket.getInetAddress().toString();
// クライアントポート
destport = socket.getPort();
outstream = new PrintStream(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// リクエストヘッダーの解析処理
String inline = reader.readLine();
HashMap<String, String> parameters = new HashMap<String, String>();
if ( inline != null ) {
requestFile = inline.split(" ")[1].trim();
if ( requestFile.contains("?") ) {
int index = requestFile.indexOf("?");
String[] temp = requestFile.substring(index+1).split("&");
requestFile = requestFile.substring(0, index);
for ( String t : temp ) {
index = t.indexOf("=");
if ( index == -1 ) {
continue;
}
String key = t.substring(0, index);
String value = t.substring(index+1);
parameters.put(key, value);
}
}
} else {
requestFile = "index.html";
}
if ( requestFile.endsWith("/") ) {
requestFile += "index.html";
}
while (reader.ready() && inline != null) {
inline = reader.readLine();
if ( inline != null && inline.startsWith("User-Agent:") ) {
userAgent = inline.substring("User-Agent:".length()).trim();
}
}
File file = new File(
BattlePoints.getInstance().getWebstatsContentFolder(),
requestFile);
// 顔画像のリクエストなら、更新をまず行う
if ( isFaceFile(requestFile) ) {
refreshFaceFile(requestFile, file);
}
// データファイルなら、そのままレスポンス
if ( requestFile.equals("/sort_data") ) {
String type = parameters.get("type");
String page = parameters.get("page");
String size = parameters.get("size");
String filter = parameters.get("filter");
byte[] content = sorter.getDataContents(type, page, size, filter);
int len = content.length;
isResponced = true;
outstream.println("HTTP/1.0 200 OK");
outstream.println("MIME-version: 1.0");
outstream.println("Content-Type: text/xml");
outstream.println("Content-Length: " + len);
outstream.println("");
outstream.write(content, 0, len);
WebServerLogger.write(destIP + "," + destport + ",200,"
+ requestFile + "," + userAgent);
return;
}
// レスポンス処理
if ( !file.exists() ) {
isResponced = true;
outstream.println("HTTP/1.0 404 Not Found");
outstream.println("");
WebServerLogger.write(destIP + "," + destport + ",404,"
+ requestFile + "," + userAgent);
} else {
int len = (int) file.length();
isResponced = true;
outstream.println("HTTP/1.0 200 OK");
outstream.println("MIME-version: 1.0");
outstream.println("Content-Type: " + getContentType(file.getName()));
outstream.println("Content-Length: " + len);
outstream.println("");
// ファイル転送
byte[] content = cache.readFile(requestFile, file);
outstream.write(content, 0, len);
WebServerLogger.write(destIP + "," + destport + ",200,"
+ requestFile + "," + userAgent);
}
} catch (Exception e) {
e.printStackTrace();
if ( outstream != null && !isResponced ) {
outstream.println("HTTP/1.0 500 Internal Server Error");
outstream.println("");
}
WebServerLogger.write(destIP + "," + destport + ",500,"
+ requestFile + "," + userAgent);
} finally {
if ( reader != null ) {
try {
reader.close();
} catch (IOException e) {
// do nothing.
}
}
if ( outstream != null ) {
outstream.flush();
outstream.close();
}
}
}
/**
* 指定されたファイル名が、プレイヤーフェイスかどうか
* @param name リクエストファイル名
* @return プレイヤーフェイスかどうか
*/
private boolean isFaceFile(String name) {
return (name.startsWith("/faces/") && name.endsWith(".png"));
}
/**
* プレイヤーフェイスファイルの更新を行う
* @param name リクエストファイル名
* @param file リクエストファイル
*/
private void refreshFaceFile(String name, File file) {
String playerName = name.substring("/faces/".length(), name.length() - ".png".length());
if ( !file.exists() ) {
// 顔画像が無いならダウンロード
PlayerFaceDownloader.downloadSkin(playerName, file, true);
} else {
// 顔画像が古いなら再ダウンロード
long modified = file.lastModified();
if ( (modified + FACE_EXPIRE_LIMIT) < System.currentTimeMillis() ) {
PlayerFaceDownloader.downloadSkin(playerName, file, false);
}
}
}
private static String getContentType(String name) {
if ( name.endsWith(".txt") ) {
return "text/plain";
} else if ( name.endsWith(".htm") || name.endsWith(".html") ) {
return "text/html";
} else if ( name.endsWith(".xml") ) {
return "text/xml";
} else if ( name.endsWith(".js") ) {
return "text/javascript";
} else if ( name.endsWith(".vbs") ) {
return "text/vbscript";
} else if ( name.endsWith(".css") ) {
return "text/css";
} else if ( name.endsWith(".gif") ) {
return "image/gif";
} else if ( name.endsWith(".jpg") || name.endsWith(".jpeg") ) {
return "image/jpeg";
} else if ( name.endsWith(".png") ) {
return "image/png";
} else if ( name.endsWith(".cgi") ) {
return "application/x-httpd-cgi";
} else if ( name.endsWith(".pdf") ) {
return "application/pdf";
}
return "text/plain";
}
}
|
ucchyocean/BattlePoints
|
src/main/java/com/github/ucchyocean/bp/webstats/ConnectionThread.java
|
Java
|
lgpl-3.0
| 8,839
|
var searchData=
[
['part_2ec',['part.c',['../part_8c.html',1,'']]],
['part_2eh',['part.h',['../part_8h.html',1,'']]],
['potential_2ec',['potential.c',['../potential_8c.html',1,'']]],
['potential_2eh',['potential.h',['../potential_8h.html',1,'']]],
['potential_5feval_2eh',['potential_eval.h',['../potential__eval_8h.html',1,'']]]
];
|
stephanmg/mdcore
|
doc/html/search/files_70.js
|
JavaScript
|
lgpl-3.0
| 343
|
/**************************************************************************
*
* Copyright 2011-2015 by Andrey Butok. FNET Community.
*
***************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License Version 3
* or later (the "LGPL").
*
* As a special exception, the copyright holders of the FNET project give you
* permission to link the FNET sources with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module.
* An independent module is a module which is not derived from or based
* on this library.
* If you modify the FNET sources, you may extend this exception
* to your version of the FNET sources, but you are not obligated
* to do so. If you do not wish to do so, delete this
* exception statement from your 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.
*
* You should have received a copy of the GNU General Public License
* and the GNU Lesser General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
**********************************************************************/ /*!
*
* @file fnet_os.h
*
* @author Andrey Butok
*
* @brief FNET OS API.
*
***************************************************************************/
#ifndef _FNET_OS_H_
#define _FNET_OS_H_
#include "fnet_config.h"
#if FNET_CFG_OS_MUTEX
int fnet_os_mutex_init(void);
void fnet_os_mutex_lock(void);
void fnet_os_mutex_unlock(void);
void fnet_os_mutex_release(void);
#else
#define fnet_os_mutex_init() FNET_OK
#define fnet_os_mutex_lock() do{}while(0)
#define fnet_os_mutex_unlock() do{}while(0)
#define fnet_os_mutex_release() do{}while(0)
#endif
#if FNET_CFG_OS_ISR
void fnet_os_isr(void);
#else
#define fnet_os_isr(void) do{}while(0)
#endif
#if FNET_CFG_OS_EVENT
int fnet_os_event_init(void);
void fnet_os_event_wait(void);
void fnet_os_event_raise(void);
#else
#define fnet_os_event_init() FNET_OK
#define fnet_os_event_wait() do{}while(0)
#define fnet_os_event_raise() do{}while(0)
#endif
int fnet_os_timer_init(unsigned int period_ms);
void fnet_os_timer_release(void);
#endif /* _FNET_OS_H_ */
|
EdizonTN/FNET-NXPLPC
|
fnet_stack/os/fnet_os.h
|
C
|
lgpl-3.0
| 2,714
|
/*
* libgphoto++ - modern c++ wrapper library for gphoto2
* Copyright (C) 2016 Marco Gulino <marco AT gulinux.net>
*
* This program 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 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 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/>.
*/
#ifndef LIBGPHOTO_CPP_UTILS_READ_JPEG_IMAGE_H
#define LIBGPHOTO_CPP_UTILS_READ_JPEG_IMAGE_H
#include "read_image.h"
#include "utils/dptr.h"
namespace GPhotoCPP {
class ReadJPEGImage : public ReadImage
{
public:
ReadJPEGImage();
~ReadJPEGImage();
virtual Image read(const std::string& file_path);
virtual Image read(const std::vector< uint8_t >& data, const std::string &filename);
private:
DPTR
};
}
#endif // GPHOTO_READJPEGIMAGE_H
|
GuLinux/libgphoto-cpp
|
src/utils/read_jpeg_image.h
|
C
|
lgpl-3.0
| 1,240
|
#
# OpenSSL/crypto/engine/Makefile
#
DIR= engine
TOP= ../..
CC= cc
INCLUDES= -I.. -I$(TOP) -I../../include
CFLAG=-g
MAKEFILE= Makefile
AR= ar r
CFLAGS= $(INCLUDES) $(CFLAG)
GENERAL=Makefile
TEST= enginetest.c
APPS=
LIB=$(TOP)/libcrypto.a
LIBSRC= eng_err.c eng_lib.c eng_list.c eng_init.c eng_ctrl.c \
eng_table.c eng_pkey.c eng_fat.c eng_all.c \
tb_rsa.c tb_dsa.c tb_ecdsa.c tb_dh.c tb_ecdh.c tb_rand.c tb_store.c \
tb_cipher.c tb_digest.c tb_pkmeth.c tb_asnmth.c \
eng_openssl.c eng_cnf.c eng_dyn.c eng_cryptodev.c \
eng_rdrand.c
LIBOBJ= eng_err.o eng_lib.o eng_list.o eng_init.o eng_ctrl.o \
eng_table.o eng_pkey.o eng_fat.o eng_all.o \
tb_rsa.o tb_dsa.o tb_ecdsa.o tb_dh.o tb_ecdh.o tb_rand.o tb_store.o \
tb_cipher.o tb_digest.o tb_pkmeth.o tb_asnmth.o \
eng_openssl.o eng_cnf.o eng_dyn.o eng_cryptodev.o \
eng_rdrand.o
SRC= $(LIBSRC)
EXHEADER= engine.h
HEADER= $(EXHEADER)
ALL= $(GENERAL) $(SRC) $(HEADER)
top:
(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
all: lib
lib: $(LIBOBJ)
$(AR) $(LIB) $(LIBOBJ)
$(RANLIB) $(LIB) || echo Never mind.
@touch lib
files:
$(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO
links:
@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
install:
@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
do \
(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
done;
tags:
ctags $(SRC)
tests:
lint:
lint -DLINT $(INCLUDES) $(SRC)>fluff
update: depend
depend:
@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
dclean:
$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
mv -f Makefile.new $(MAKEFILE)
clean:
rm -f *.o */*.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
# DO NOT DELETE THIS LINE -- make depend depends on it.
eng_all.o: ../../e_os.h ../../include/openssl/asn1.h
eng_all.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_all.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
eng_all.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
eng_all.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
eng_all.o: ../../include/openssl/err.h ../../include/openssl/evp.h
eng_all.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
eng_all.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
eng_all.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
eng_all.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
eng_all.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
eng_all.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
eng_all.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_all.c eng_int.h
eng_cnf.o: ../../e_os.h ../../include/openssl/asn1.h
eng_cnf.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_cnf.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
eng_cnf.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
eng_cnf.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
eng_cnf.o: ../../include/openssl/engine.h ../../include/openssl/err.h
eng_cnf.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
eng_cnf.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
eng_cnf.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
eng_cnf.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
eng_cnf.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
eng_cnf.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
eng_cnf.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
eng_cnf.o: ../cryptlib.h eng_cnf.c eng_int.h
eng_cryptodev.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h
eng_cryptodev.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h
eng_cryptodev.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
eng_cryptodev.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
eng_cryptodev.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
eng_cryptodev.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
eng_cryptodev.o: ../../include/openssl/obj_mac.h
eng_cryptodev.o: ../../include/openssl/objects.h
eng_cryptodev.o: ../../include/openssl/opensslconf.h
eng_cryptodev.o: ../../include/openssl/opensslv.h
eng_cryptodev.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
eng_cryptodev.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
eng_cryptodev.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
eng_cryptodev.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
eng_cryptodev.o: eng_cryptodev.c
eng_ctrl.o: ../../e_os.h ../../include/openssl/asn1.h
eng_ctrl.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_ctrl.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
eng_ctrl.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
eng_ctrl.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
eng_ctrl.o: ../../include/openssl/err.h ../../include/openssl/evp.h
eng_ctrl.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
eng_ctrl.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
eng_ctrl.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
eng_ctrl.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
eng_ctrl.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
eng_ctrl.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
eng_ctrl.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_ctrl.c eng_int.h
eng_dyn.o: ../../e_os.h ../../include/openssl/asn1.h
eng_dyn.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_dyn.o: ../../include/openssl/crypto.h ../../include/openssl/dso.h
eng_dyn.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
eng_dyn.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
eng_dyn.o: ../../include/openssl/engine.h ../../include/openssl/err.h
eng_dyn.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
eng_dyn.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
eng_dyn.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
eng_dyn.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
eng_dyn.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
eng_dyn.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
eng_dyn.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
eng_dyn.o: ../cryptlib.h eng_dyn.c eng_int.h
eng_err.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h
eng_err.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
eng_err.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
eng_err.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
eng_err.o: ../../include/openssl/engine.h ../../include/openssl/err.h
eng_err.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
eng_err.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
eng_err.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
eng_err.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
eng_err.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
eng_err.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
eng_err.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
eng_err.o: eng_err.c
eng_fat.o: ../../e_os.h ../../include/openssl/asn1.h
eng_fat.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_fat.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
eng_fat.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
eng_fat.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
eng_fat.o: ../../include/openssl/engine.h ../../include/openssl/err.h
eng_fat.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
eng_fat.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
eng_fat.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
eng_fat.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
eng_fat.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
eng_fat.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
eng_fat.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
eng_fat.o: ../cryptlib.h eng_fat.c eng_int.h
eng_init.o: ../../e_os.h ../../include/openssl/asn1.h
eng_init.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_init.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
eng_init.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
eng_init.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
eng_init.o: ../../include/openssl/err.h ../../include/openssl/evp.h
eng_init.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
eng_init.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
eng_init.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
eng_init.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
eng_init.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
eng_init.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
eng_init.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_init.c eng_int.h
eng_lib.o: ../../e_os.h ../../include/openssl/asn1.h
eng_lib.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_lib.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
eng_lib.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
eng_lib.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
eng_lib.o: ../../include/openssl/err.h ../../include/openssl/evp.h
eng_lib.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
eng_lib.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
eng_lib.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
eng_lib.o: ../../include/openssl/pkcs7.h ../../include/openssl/rand.h
eng_lib.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
eng_lib.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
eng_lib.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
eng_lib.o: ../cryptlib.h eng_int.h eng_lib.c
eng_list.o: ../../e_os.h ../../include/openssl/asn1.h
eng_list.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_list.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
eng_list.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
eng_list.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
eng_list.o: ../../include/openssl/err.h ../../include/openssl/evp.h
eng_list.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
eng_list.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
eng_list.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
eng_list.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
eng_list.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
eng_list.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
eng_list.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h eng_list.c
eng_openssl.o: ../../e_os.h ../../include/openssl/asn1.h
eng_openssl.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_openssl.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h
eng_openssl.o: ../../include/openssl/dsa.h ../../include/openssl/dso.h
eng_openssl.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
eng_openssl.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
eng_openssl.o: ../../include/openssl/engine.h ../../include/openssl/err.h
eng_openssl.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
eng_openssl.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
eng_openssl.o: ../../include/openssl/opensslconf.h
eng_openssl.o: ../../include/openssl/opensslv.h
eng_openssl.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pem.h
eng_openssl.o: ../../include/openssl/pem2.h ../../include/openssl/pkcs7.h
eng_openssl.o: ../../include/openssl/rand.h ../../include/openssl/rc4.h
eng_openssl.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
eng_openssl.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
eng_openssl.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
eng_openssl.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_openssl.c
eng_pkey.o: ../../e_os.h ../../include/openssl/asn1.h
eng_pkey.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_pkey.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
eng_pkey.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
eng_pkey.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
eng_pkey.o: ../../include/openssl/err.h ../../include/openssl/evp.h
eng_pkey.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
eng_pkey.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
eng_pkey.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
eng_pkey.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
eng_pkey.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
eng_pkey.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
eng_pkey.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h eng_pkey.c
eng_rdrand.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h
eng_rdrand.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
eng_rdrand.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
eng_rdrand.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
eng_rdrand.o: ../../include/openssl/engine.h ../../include/openssl/err.h
eng_rdrand.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
eng_rdrand.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
eng_rdrand.o: ../../include/openssl/opensslconf.h
eng_rdrand.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
eng_rdrand.o: ../../include/openssl/pkcs7.h ../../include/openssl/rand.h
eng_rdrand.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
eng_rdrand.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
eng_rdrand.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
eng_rdrand.o: eng_rdrand.c
eng_table.o: ../../e_os.h ../../include/openssl/asn1.h
eng_table.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
eng_table.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
eng_table.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
eng_table.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
eng_table.o: ../../include/openssl/err.h ../../include/openssl/evp.h
eng_table.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
eng_table.o: ../../include/openssl/objects.h
eng_table.o: ../../include/openssl/opensslconf.h
eng_table.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
eng_table.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
eng_table.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
eng_table.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
eng_table.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h
eng_table.o: eng_table.c
tb_asnmth.o: ../../e_os.h ../../include/openssl/asn1.h
tb_asnmth.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
tb_asnmth.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
tb_asnmth.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
tb_asnmth.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
tb_asnmth.o: ../../include/openssl/err.h ../../include/openssl/evp.h
tb_asnmth.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
tb_asnmth.o: ../../include/openssl/objects.h
tb_asnmth.o: ../../include/openssl/opensslconf.h
tb_asnmth.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
tb_asnmth.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
tb_asnmth.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
tb_asnmth.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
tb_asnmth.o: ../../include/openssl/x509_vfy.h ../asn1/asn1_locl.h ../cryptlib.h
tb_asnmth.o: eng_int.h tb_asnmth.c
tb_cipher.o: ../../e_os.h ../../include/openssl/asn1.h
tb_cipher.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
tb_cipher.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
tb_cipher.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
tb_cipher.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
tb_cipher.o: ../../include/openssl/err.h ../../include/openssl/evp.h
tb_cipher.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
tb_cipher.o: ../../include/openssl/objects.h
tb_cipher.o: ../../include/openssl/opensslconf.h
tb_cipher.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
tb_cipher.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
tb_cipher.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
tb_cipher.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
tb_cipher.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h
tb_cipher.o: tb_cipher.c
tb_dh.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h
tb_dh.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
tb_dh.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
tb_dh.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
tb_dh.o: ../../include/openssl/engine.h ../../include/openssl/err.h
tb_dh.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
tb_dh.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
tb_dh.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
tb_dh.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
tb_dh.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
tb_dh.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
tb_dh.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
tb_dh.o: ../cryptlib.h eng_int.h tb_dh.c
tb_digest.o: ../../e_os.h ../../include/openssl/asn1.h
tb_digest.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
tb_digest.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
tb_digest.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
tb_digest.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
tb_digest.o: ../../include/openssl/err.h ../../include/openssl/evp.h
tb_digest.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
tb_digest.o: ../../include/openssl/objects.h
tb_digest.o: ../../include/openssl/opensslconf.h
tb_digest.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
tb_digest.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
tb_digest.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
tb_digest.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
tb_digest.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h
tb_digest.o: tb_digest.c
tb_dsa.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h
tb_dsa.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
tb_dsa.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
tb_dsa.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
tb_dsa.o: ../../include/openssl/engine.h ../../include/openssl/err.h
tb_dsa.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
tb_dsa.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
tb_dsa.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
tb_dsa.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
tb_dsa.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
tb_dsa.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
tb_dsa.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
tb_dsa.o: ../cryptlib.h eng_int.h tb_dsa.c
tb_ecdh.o: ../../e_os.h ../../include/openssl/asn1.h
tb_ecdh.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
tb_ecdh.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
tb_ecdh.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
tb_ecdh.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
tb_ecdh.o: ../../include/openssl/err.h ../../include/openssl/evp.h
tb_ecdh.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
tb_ecdh.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
tb_ecdh.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
tb_ecdh.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
tb_ecdh.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
tb_ecdh.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
tb_ecdh.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h tb_ecdh.c
tb_ecdsa.o: ../../e_os.h ../../include/openssl/asn1.h
tb_ecdsa.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
tb_ecdsa.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
tb_ecdsa.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
tb_ecdsa.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
tb_ecdsa.o: ../../include/openssl/err.h ../../include/openssl/evp.h
tb_ecdsa.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
tb_ecdsa.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
tb_ecdsa.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
tb_ecdsa.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
tb_ecdsa.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
tb_ecdsa.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
tb_ecdsa.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h tb_ecdsa.c
tb_pkmeth.o: ../../e_os.h ../../include/openssl/asn1.h
tb_pkmeth.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
tb_pkmeth.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
tb_pkmeth.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
tb_pkmeth.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
tb_pkmeth.o: ../../include/openssl/err.h ../../include/openssl/evp.h
tb_pkmeth.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
tb_pkmeth.o: ../../include/openssl/objects.h
tb_pkmeth.o: ../../include/openssl/opensslconf.h
tb_pkmeth.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
tb_pkmeth.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
tb_pkmeth.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
tb_pkmeth.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
tb_pkmeth.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h
tb_pkmeth.o: tb_pkmeth.c
tb_rand.o: ../../e_os.h ../../include/openssl/asn1.h
tb_rand.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
tb_rand.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
tb_rand.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
tb_rand.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
tb_rand.o: ../../include/openssl/err.h ../../include/openssl/evp.h
tb_rand.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
tb_rand.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
tb_rand.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
tb_rand.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
tb_rand.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
tb_rand.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
tb_rand.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h tb_rand.c
tb_rsa.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h
tb_rsa.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
tb_rsa.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
tb_rsa.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
tb_rsa.o: ../../include/openssl/engine.h ../../include/openssl/err.h
tb_rsa.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
tb_rsa.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
tb_rsa.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
tb_rsa.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
tb_rsa.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
tb_rsa.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
tb_rsa.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
tb_rsa.o: ../cryptlib.h eng_int.h tb_rsa.c
tb_store.o: ../../e_os.h ../../include/openssl/asn1.h
tb_store.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
tb_store.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
tb_store.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
tb_store.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h
tb_store.o: ../../include/openssl/err.h ../../include/openssl/evp.h
tb_store.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
tb_store.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
tb_store.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
tb_store.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h
tb_store.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
tb_store.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
tb_store.o: ../../include/openssl/x509_vfy.h ../cryptlib.h eng_int.h tb_store.c
|
Orav/kbengine
|
kbe/src/lib/dependencies/openssl/crypto/engine/Makefile
|
Makefile
|
lgpl-3.0
| 26,573
|
/**
* AnalyzerBeans
* Copyright (C) 2014 Neopost - Customer Information Management
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.eobjects.analyzer.beans.referentialintegrity;
import org.eobjects.analyzer.beans.api.Description;
import org.eobjects.analyzer.data.InputColumn;
import org.eobjects.analyzer.result.AnnotatedRowsResult;
import org.eobjects.analyzer.storage.RowAnnotation;
import org.eobjects.analyzer.storage.RowAnnotationFactory;
@Description("Records with unresolved foreign key values")
public class ReferentialIntegrityAnalyzerResult extends AnnotatedRowsResult {
private static final long serialVersionUID = 1L;
public ReferentialIntegrityAnalyzerResult(RowAnnotation annotation, RowAnnotationFactory annotationFactory,
InputColumn<?>[] highlightedColumns) {
super(annotation, annotationFactory, highlightedColumns);
}
}
|
datacleaner/AnalyzerBeans
|
components/referential-integrity/src/main/java/org/eobjects/analyzer/beans/referentialintegrity/ReferentialIntegrityAnalyzerResult.java
|
Java
|
lgpl-3.0
| 1,570
|
/*
* SonarLint for Visual Studio
* Copyright (C) 2016-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System.Reflection;
using System.Runtime.InteropServices;
// Note: keep the version numbers in sync with the VSIX (source.extension.manifest)
[assembly: AssemblyVersion("3.6.0")]
[assembly: AssemblyFileVersion("3.6.0.0")] // This should exactly match the VSIX version
[assembly: AssemblyInformationalVersion("Version:3.6.0.0 Branch:not-set Sha1:not-set")]
[assembly: AssemblyConfiguration("")]
[assembly: ComVisible(false)]
[assembly: AssemblyProduct("SonarLint for Visual Studio")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyCompany("SonarSource")]
[assembly: AssemblyCopyright("Copyright © SonarSource SA 2016-2017")]
[assembly: AssemblyTrademark("")]
|
duncanpMS/sonarlint-visualstudio
|
src/AssemblyInfo.Shared.cs
|
C#
|
lgpl-3.0
| 1,569
|
package com.thekarura.bukkit.plugin.resorcedungeons.listener;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.scheduler.BukkitRunnable;
import com.thekarura.bukkit.plugin.resorcedungeons.ResorceDungeons;
import com.thekarura.bukkit.plugin.resorcedungeons.util.MessageFormats;
public class RDPlayerListener implements Listener {
public static final Logger log = ResorceDungeons.log;
private static final String logPrefix = ResorceDungeons.logPrefix;
private static final String msgPrefix = ResorceDungeons.msgPrefix;
// instance
private ResorceDungeons instance = ResorceDungeons.getInstance();
public RDPlayerListener(ResorceDungeons plugin) {
this.instance = plugin;
}
/**
* 自分向けのメッセージを送信
* @param event PlayerJoinEventから習得
*/
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerMoveEvent(PlayerJoinEvent event){
MessageFormats format = new MessageFormats(instance);
String auther = instance.getConfigs().getAuther();
final Player player = event.getPlayer();
final String server_name = instance.getServer().getServerName();
final String plugin_name = instance.getConfigs().getName();
final String mes = format.MessageFormat("&a \"" + server_name + "\" は " + plugin_name + "を導入しています。", player.getName());
if (player.equals(Bukkit.getPlayer(auther))){
new BukkitRunnable(){
@Override
public void run(){
player.sendMessage(msgPrefix + mes);
}
}.runTaskLater(instance, 60);
}
}
}
|
ucchyocean/ResorceDungeons
|
src/main/java/com/thekarura/bukkit/plugin/resorcedungeons/listener/RDPlayerListener.java
|
Java
|
lgpl-3.0
| 1,778
|
// Copyright (C) 2000, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#ifndef OsiSolverInterface_H
#define OsiSolverInterface_H
#include <cstdlib>
#include <string>
#include <vector>
#include "CoinMessageHandler.hpp"
#include "CoinPackedVectorBase.hpp"
#include "CoinTypes.hpp"
#include "OsiCollections.hpp"
#include "OsiSolverParameters.hpp"
class CoinPackedMatrix;
class CoinWarmStart;
class CoinSnapshot;
class CoinLpIO;
class CoinMpsIO;
class OsiCuts;
class OsiAuxInfo;
class OsiRowCut;
class OsiRowCutDebugger;
class CoinSet;
class CoinBuild;
class CoinModel;
class OsiSolverBranch;
class OsiSolverResult;
class OsiObject;
//#############################################################################
/*! \brief Abstract Base Class for describing an interface to a solver.
Many OsiSolverInterface query methods return a const pointer to the
requested read-only data. If the model data is changed or the solver
is called, these pointers may no longer be valid and should be
refreshed by invoking the member function to obtain an updated copy
of the pointer.
For example:
\code
OsiSolverInterface solverInterfacePtr ;
const double * ruBnds = solverInterfacePtr->getRowUpper();
solverInterfacePtr->applyCuts(someSetOfCuts);
// ruBnds is no longer a valid pointer and must be refreshed
ruBnds = solverInterfacePtr->getRowUpper();
\endcode
Querying a problem that has no data associated with it will result in
zeros for the number of rows and columns, and NULL pointers from
the methods that return vectors.
*/
class OsiSolverInterface {
friend void OsiSolverInterfaceCommonUnitTest(
const OsiSolverInterface* emptySi,
const std::string & mpsDir,
const std::string & netlibDir);
friend void OsiSolverInterfaceMpsUnitTest(
const std::vector<OsiSolverInterface*> & vecSiP,
const std::string & mpsDir);
public:
/// Internal class for obtaining status from the applyCuts method
class ApplyCutsReturnCode {
friend class OsiSolverInterface;
friend class OsiOslSolverInterface;
friend class OsiClpSolverInterface;
public:
///@name Constructors and desctructors
//@{
/// Default constructor
ApplyCutsReturnCode():
intInconsistent_(0),
extInconsistent_(0),
infeasible_(0),
ineffective_(0),
applied_(0) {}
/// Copy constructor
ApplyCutsReturnCode(const ApplyCutsReturnCode & rhs):
intInconsistent_(rhs.intInconsistent_),
extInconsistent_(rhs.extInconsistent_),
infeasible_(rhs.infeasible_),
ineffective_(rhs.ineffective_),
applied_(rhs.applied_) {}
/// Assignment operator
ApplyCutsReturnCode & operator=(const ApplyCutsReturnCode& rhs)
{
if (this != &rhs) {
intInconsistent_ = rhs.intInconsistent_;
extInconsistent_ = rhs.extInconsistent_;
infeasible_ = rhs.infeasible_;
ineffective_ = rhs.ineffective_;
applied_ = rhs.applied_;
}
return *this;
}
/// Destructor
~ApplyCutsReturnCode(){}
//@}
/**@name Accessing return code attributes */
//@{
/// Number of logically inconsistent cuts
inline int getNumInconsistent(){return intInconsistent_;}
/// Number of cuts inconsistent with the current model
inline int getNumInconsistentWrtIntegerModel(){return extInconsistent_;}
/// Number of cuts that cause obvious infeasibility
inline int getNumInfeasible(){return infeasible_;}
/// Number of redundant or ineffective cuts
inline int getNumIneffective(){return ineffective_;}
/// Number of cuts applied
inline int getNumApplied(){return applied_;}
//@}
private:
/**@name Private methods */
//@{
/// Increment logically inconsistent cut counter
inline void incrementInternallyInconsistent(){intInconsistent_++;}
/// Increment model-inconsistent counter
inline void incrementExternallyInconsistent(){extInconsistent_++;}
/// Increment infeasible cut counter
inline void incrementInfeasible(){infeasible_++;}
/// Increment ineffective cut counter
inline void incrementIneffective(){ineffective_++;}
/// Increment applied cut counter
inline void incrementApplied(){applied_++;}
//@}
///@name Private member data
//@{
/// Counter for logically inconsistent cuts
int intInconsistent_;
/// Counter for model-inconsistent cuts
int extInconsistent_;
/// Counter for infeasible cuts
int infeasible_;
/// Counter for ineffective cuts
int ineffective_;
/// Counter for applied cuts
int applied_;
//@}
};
//---------------------------------------------------------------------------
///@name Solve methods
//@{
/// Solve initial LP relaxation
virtual void initialSolve() = 0;
/*! \brief Resolve an LP relaxation after problem modification
Note the `re-' in `resolve'. initialSolve() should be used to solve the
problem for the first time.
*/
virtual void resolve() = 0;
/// Invoke solver's built-in enumeration algorithm
virtual void branchAndBound() = 0;
#ifdef CBC_NEXT_VERSION
/*
Would it make sense to collect all of these routines in a `MIP Helper'
section? It'd make it easier for users and implementors to find them.
*/
/**
Solve 2**N (N==depth) problems and return solutions and bases.
There are N branches each of which changes bounds on both sides
as given by branch. The user should provide an array of (empty)
results which will be filled in. See OsiSolveResult for more details
(in OsiSolveBranch.?pp) but it will include a basis and primal solution.
The order of results is left to right at feasible leaf nodes so first one
is down, down, .....
Returns number of feasible leaves. Also sets number of solves done and number
of iterations.
This is provided so a solver can do faster.
If forceBranch true then branch done even if satisfied
*/
virtual int solveBranches(int depth,const OsiSolverBranch * branch,
OsiSolverResult * result,
int & numberSolves, int & numberIterations,
bool forceBranch=false);
#endif
//@}
//---------------------------------------------------------------------------
/**@name Parameter set/get methods
The set methods return true if the parameter was set to the given value,
false otherwise. When a set method returns false, the original value (if
any) should be unchanged. There can be various reasons for failure: the
given parameter is not applicable for the solver (e.g., refactorization
frequency for the volume algorithm), the parameter is not yet
implemented for the solver or simply the value of the parameter is out
of the range the solver accepts. If a parameter setting call returns
false check the details of your solver.
The get methods return true if the given parameter is applicable for the
solver and is implemented. In this case the value of the parameter is
returned in the second argument. Otherwise they return false.
\note
There is a default implementation of the set/get
methods, namely to store/retrieve the given value using an array in the
base class. A specific solver implementation can use this feature, for
example, to store parameters that should be used later on. Implementors
of a solver interface should overload these functions to provide the
proper interface to and accurately reflect the capabilities of a
specific solver.
The format for hints is slightly different in that a boolean specifies
the sense of the hint and an enum specifies the strength of the hint.
Hints should be initialised when a solver is instantiated.
(See OsiSolverParameters.hpp for defined hint parameters and strength.)
When specifying the sense of the hint, a value of true means to work with
the hint, false to work against it. For example,
<ul>
<li> \code setHintParam(OsiDoScale,true,OsiHintTry) \endcode
is a mild suggestion to the solver to scale the constraint
system.
<li> \code setHintParam(OsiDoScale,false,OsiForceDo) \endcode
tells the solver to disable scaling, or throw an exception if
it cannot comply.
</ul>
As another example, a solver interface could use the value and strength
of the \c OsiDoReducePrint hint to adjust the amount of information
printed by the interface and/or solver. The extent to which a solver
obeys hints is left to the solver. The value and strength returned by
\c getHintParam will match the most recent call to \c setHintParam,
and will not necessarily reflect the solver's ability to comply with the
hint. If the hint strength is \c OsiForceDo, the solver is required to
throw an exception if it cannot perform the specified action.
\note
As with the other set/get methods, there is a default implementation
which maintains arrays in the base class for hint sense and strength.
The default implementation does not store the \c otherInformation
pointer, and always throws an exception for strength \c OsiForceDo.
Implementors of a solver interface should override these functions to
provide the proper interface to and accurately reflect the capabilities
of a specific solver.
*/
//@{
//! Set an integer parameter
virtual bool setIntParam(OsiIntParam key, int value) {
if (key == OsiLastIntParam) return (false) ;
intParam_[key] = value;
return true;
}
//! Set a double parameter
virtual bool setDblParam(OsiDblParam key, double value) {
if (key == OsiLastDblParam) return (false) ;
dblParam_[key] = value;
return true;
}
//! Set a string parameter
virtual bool setStrParam(OsiStrParam key, const std::string & value) {
if (key == OsiLastStrParam) return (false) ;
strParam_[key] = value;
return true;
}
/*! \brief Set a hint parameter
The \c otherInformation parameter can be used to pass in an arbitrary
block of information which is interpreted by the OSI and the underlying
solver. Users are cautioned that this hook is solver-specific.
Implementors:
The default implementation completely ignores \c otherInformation and
always throws an exception for OsiForceDo. This is almost certainly not
the behaviour you want; you really should override this method.
*/
virtual bool setHintParam(OsiHintParam key, bool yesNo=true,
OsiHintStrength strength=OsiHintTry,
void * /*otherInformation*/ = nullptr) {
if (key==OsiLastHintParam)
return false;
hintParam_[key] = yesNo;
hintStrength_[key] = strength;
if (strength == OsiForceDo)
throw CoinError("OsiForceDo illegal",
"setHintParam", "OsiSolverInterface");
return true;
}
//! Get an integer parameter
virtual bool getIntParam(OsiIntParam key, int& value) const {
if (key == OsiLastIntParam) return (false) ;
value = intParam_[key];
return true;
}
//! Get a double parameter
virtual bool getDblParam(OsiDblParam key, double& value) const {
if (key == OsiLastDblParam) return (false) ;
value = dblParam_[key];
return true;
}
//! Get a string parameter
virtual bool getStrParam(OsiStrParam key, std::string& value) const {
if (key == OsiLastStrParam) return (false) ;
value = strParam_[key];
return true;
}
/*! \brief Get a hint parameter (all information)
Return all available information for the hint: sense, strength,
and any extra information associated with the hint.
Implementors: The default implementation will always set
\c otherInformation to NULL. This is almost certainly not the
behaviour you want; you really should override this method.
*/
virtual bool getHintParam(OsiHintParam key, bool& yesNo,
OsiHintStrength& strength,
void *& otherInformation) const {
if (key==OsiLastHintParam)
return false;
yesNo = hintParam_[key];
strength = hintStrength_[key];
otherInformation=nullptr;
return true;
}
/*! \brief Get a hint parameter (sense and strength only)
Return only the sense and strength of the hint.
*/
virtual bool getHintParam(OsiHintParam key, bool& yesNo,
OsiHintStrength& strength) const {
if (key==OsiLastHintParam)
return false;
yesNo = hintParam_[key];
strength = hintStrength_[key];
return true;
}
/*! \brief Get a hint parameter (sense only)
Return only the sense (true/false) of the hint.
*/
virtual bool getHintParam(OsiHintParam key, bool& yesNo) const {
if (key==OsiLastHintParam)
return false;
yesNo = hintParam_[key];
return true;
}
/*! \brief Copy all parameters in this section from one solver to another
Note that the current implementation also copies the appData block,
message handler, and rowCutDebugger. Arguably these should have
independent copy methods.
*/
void copyParameters(OsiSolverInterface & rhs);
/** \brief Return the integrality tolerance of the underlying solver.
We should be able to get an integrality tolerance, but
until that time just use the primal tolerance
\todo
This method should be replaced; it's architecturally wrong. This
should be an honest dblParam with a keyword. Underlying solvers
that do not support integer variables should return false for set and
get on this parameter. Underlying solvers that support integrality
should add this to the parameters they support, using whatever
tolerance is appropriate. -lh, 091021-
*/
inline double getIntegerTolerance() const
{ return dblParam_[OsiPrimalTolerance];}
//@}
//---------------------------------------------------------------------------
///@name Methods returning info on how the solution process terminated
//@{
/// Are there numerical difficulties?
virtual bool isAbandoned() const = 0;
/// Is optimality proven?
virtual bool isProvenOptimal() const = 0;
/// Is primal infeasibility proven?
virtual bool isProvenPrimalInfeasible() const = 0;
/// Is dual infeasibility proven?
virtual bool isProvenDualInfeasible() const = 0;
/// Is the given primal objective limit reached?
virtual bool isPrimalObjectiveLimitReached() const;
/// Is the given dual objective limit reached?
virtual bool isDualObjectiveLimitReached() const;
/// Iteration limit reached?
virtual bool isIterationLimitReached() const = 0;
//@}
//---------------------------------------------------------------------------
/** \name Warm start methods
Note that the warm start methods return a generic CoinWarmStart object.
The precise characteristics of this object are solver-dependent. Clients
who wish to maintain a maximum degree of solver independence should take
care to avoid unnecessary assumptions about the properties of a warm start
object.
*/
//@{
/*! \brief Get an empty warm start object
This routine returns an empty warm start object. Its purpose is
to provide a way for a client to acquire a warm start object of the
appropriate type for the solver, which can then be resized and modified
as desired.
*/
virtual CoinWarmStart *getEmptyWarmStart () const = 0 ;
/** \brief Get warm start information.
Return warm start information for the current state of the solver
interface. If there is no valid warm start information, an empty warm
start object wil be returned.
*/
virtual CoinWarmStart* getWarmStart() const = 0;
/** \brief Get warm start information.
Return warm start information for the current state of the solver
interface. If there is no valid warm start information, an empty warm
start object wil be returned. This does not necessarily create an
object - may just point to one. must Delete set true if user
should delete returned object.
*/
virtual CoinWarmStart* getPointerToWarmStart(bool & mustDelete) ;
/** \brief Set warm start information.
Return true or false depending on whether the warm start information was
accepted or not.
By definition, a call to setWarmStart with a null parameter should
cause the solver interface to refresh its warm start information
from the underlying solver.
*/
virtual bool setWarmStart(const CoinWarmStart* warmstart) = 0;
//@}
//---------------------------------------------------------------------------
/**@name Hot start methods
Primarily used in strong branching. The user can create a hot start
object --- a snapshot of the optimization process --- then reoptimize
over and over again, starting from the same point.
\note
<ul>
<li> Between hot started optimizations only bound changes are allowed.
<li> The copy constructor and assignment operator should NOT copy any
hot start information.
<li> The default implementation simply extracts a warm start object in
\c markHotStart, resets to the warm start object in
\c solveFromHotStart, and deletes the warm start object in
\c unmarkHotStart.
<em>Actual solver implementations are encouraged to do better.</em>
</ul>
*/
//@{
/// Create a hot start snapshot of the optimization process.
virtual void markHotStart();
/// Optimize starting from the hot start snapshot.
virtual void solveFromHotStart();
/// Delete the hot start snapshot.
virtual void unmarkHotStart();
//@}
//---------------------------------------------------------------------------
/**@name Problem query methods
Querying a problem that has no data associated with it will result in
zeros for the number of rows and columns, and NULL pointers from the
methods that return vectors.
Const pointers returned from any data-query method are valid as long as
the data is unchanged and the solver is not called.
*/
//@{
/// Get the number of columns
virtual int getNumCols() const = 0;
/// Get the number of rows
virtual int getNumRows() const = 0;
/// Get the number of nonzero elements
virtual int getNumElements() const = 0;
/// Get the number of integer variables
virtual int getNumIntegers() const ;
/// Get a pointer to an array[getNumCols()] of column lower bounds
virtual const double * getColLower() const = 0;
/// Get a pointer to an array[getNumCols()] of column upper bounds
virtual const double * getColUpper() const = 0;
/*! \brief Get a pointer to an array[getNumRows()] of row constraint senses.
<ul>
<li>'L': <= constraint
<li>'E': = constraint
<li>'G': >= constraint
<li>'R': ranged constraint
<li>'N': free constraint
</ul>
*/
virtual const char * getRowSense() const = 0;
/*! \brief Get a pointer to an array[getNumRows()] of row right-hand sides
<ul>
<li> if getRowSense()[i] == 'L' then
getRightHandSide()[i] == getRowUpper()[i]
<li> if getRowSense()[i] == 'G' then
getRightHandSide()[i] == getRowLower()[i]
<li> if getRowSense()[i] == 'R' then
getRightHandSide()[i] == getRowUpper()[i]
<li> if getRowSense()[i] == 'N' then
getRightHandSide()[i] == 0.0
</ul>
*/
virtual const double * getRightHandSide() const = 0;
/*! \brief Get a pointer to an array[getNumRows()] of row ranges.
<ul>
<li> if getRowSense()[i] == 'R' then
getRowRange()[i] == getRowUpper()[i] - getRowLower()[i]
<li> if getRowSense()[i] != 'R' then
getRowRange()[i] is 0.0
</ul>
*/
virtual const double * getRowRange() const = 0;
/// Get a pointer to an array[getNumRows()] of row lower bounds
virtual const double * getRowLower() const = 0;
/// Get a pointer to an array[getNumRows()] of row upper bounds
virtual const double * getRowUpper() const = 0;
/*! \brief Get a pointer to an array[getNumCols()] of objective
function coefficients.
*/
virtual const double * getObjCoefficients() const = 0;
/*! \brief Get the objective function sense
- 1 for minimisation (default)
- -1 for maximisation
*/
virtual double getObjSense() const = 0;
/// Return true if the variable is continuous
virtual bool isContinuous(int colIndex) const = 0;
/// Return true if the variable is binary
virtual bool isBinary(int colIndex) const;
/*! \brief Return true if the variable is integer.
This method returns true if the variable is binary or general integer.
*/
virtual bool isInteger(int colIndex) const;
/// Return true if the variable is general integer
virtual bool isIntegerNonBinary(int colIndex) const;
/// Return true if the variable is binary and not fixed
virtual bool isFreeBinary(int colIndex) const;
/*! \brief Return an array[getNumCols()] of column types
\deprecated See #getColType
*/
inline const char *columnType(bool refresh=false) const
{ return getColType(refresh); }
/*! \brief Return an array[getNumCols()] of column types
- 0 - continuous
- 1 - binary
- 2 - general integer
If \p refresh is true, the classification of integer variables as
binary or general integer will be reevaluated. If the current bounds
are [0,1], or if the variable is fixed at 0 or 1, it will be classified
as binary, otherwise it will be classified as general integer.
*/
virtual const char * getColType(bool refresh=false) const;
/// Get a pointer to a row-wise copy of the matrix
virtual const CoinPackedMatrix * getMatrixByRow() const = 0;
/// Get a pointer to a column-wise copy of the matrix
virtual const CoinPackedMatrix * getMatrixByCol() const = 0;
/*! \brief Get a pointer to a mutable row-wise copy of the matrix.
Returns NULL if the request is not meaningful (i.e., the OSI will not
recognise any modifications to the matrix).
*/
virtual CoinPackedMatrix * getMutableMatrixByRow() const {return nullptr;}
/*! \brief Get a pointer to a mutable column-wise copy of the matrix
Returns NULL if the request is not meaningful (i.e., the OSI will not
recognise any modifications to the matrix).
*/
virtual CoinPackedMatrix * getMutableMatrixByCol() const {return nullptr;}
/// Get the solver's value for infinity
virtual double getInfinity() const = 0;
//@}
/**@name Solution query methods */
//@{
/// Get a pointer to an array[getNumCols()] of primal variable values
virtual const double * getColSolution() const = 0;
/** Get a pointer to an array[getNumCols()] of primal variable values
guaranteed to be between the column lower and upper bounds.
*/
virtual const double * getStrictColSolution();
/// Get pointer to array[getNumRows()] of dual variable values
virtual const double * getRowPrice() const = 0;
/// Get a pointer to an array[getNumCols()] of reduced costs
virtual const double * getReducedCost() const = 0;
/** Get a pointer to array[getNumRows()] of row activity levels.
The row activity for a row is the left-hand side evaluated at the
current solution.
*/
virtual const double * getRowActivity() const = 0;
/// Get the objective function value.
virtual double getObjValue() const = 0;
/** Get the number of iterations it took to solve the problem (whatever
`iteration' means to the solver).
*/
virtual int getIterationCount() const = 0;
/** Get as many dual rays as the solver can provide. In case of proven
primal infeasibility there should (with high probability) be at least
one.
The first getNumRows() ray components will always be associated with
the row duals (as returned by getRowPrice()). If \c fullRay is true,
the final getNumCols() entries will correspond to the ray components
associated with the nonbasic variables. If the full ray is requested
and the method cannot provide it, it will throw an exception.
\note
Implementors of solver interfaces note that the double pointers in
the vector should point to arrays of length getNumRows() (fullRay =
false) or (getNumRows()+getNumCols()) (fullRay = true) and they should
be allocated with new[].
\note
Clients of solver interfaces note that it is the client's
responsibility to free the double pointers in the vector using
delete[]. Clients are reminded that a problem can be dual and primal
infeasible.
*/
virtual std::vector<double*> getDualRays(int maxNumRays,
bool fullRay = false) const = 0;
/** Get as many primal rays as the solver can provide. In case of proven
dual infeasibility there should (with high probability) be at least
one.
\note
Implementors of solver interfaces note that the double pointers in
the vector should point to arrays of length getNumCols() and they
should be allocated with new[].
\note
Clients of solver interfaces note that it is the client's
responsibility to free the double pointers in the vector using
delete[]. Clients are reminded that a problem can be dual and primal
infeasible.
*/
virtual std::vector<double*> getPrimalRays(int maxNumRays) const = 0;
/** Get vector of indices of primal variables which are integer variables
but have fractional values in the current solution. */
virtual OsiVectorInt getFractionalIndices(const double etol=1.e-05)
const;
//@}
//-------------------------------------------------------------------------
/**@name Methods to modify the objective, bounds, and solution
For functions which take a set of indices as parameters
(\c setObjCoeffSet(), \c setColSetBounds(), \c setRowSetBounds(),
\c setRowSetTypes()), the parameters follow the C++ STL iterator
convention: \c indexFirst points to the first index in the
set, and \c indexLast points to a position one past the last index
in the set.
*/
//@{
/** Set an objective function coefficient */
virtual void setObjCoeff( int elementIndex, double elementValue ) = 0;
/** Set a set of objective function coefficients */
virtual void setObjCoeffSet(const int* indexFirst,
const int* indexLast,
const double* coeffList);
/** Set the objective coefficients for all columns.
array [getNumCols()] is an array of values for the objective.
This defaults to a series of set operations and is here for speed.
*/
virtual void setObjective(const double * array);
/** Set the objective function sense.
Use 1 for minimisation (default), -1 for maximisation.
\note
Implementors note that objective function sense is a parameter of
the OSI, not a property of the problem. Objective sense can be
set prior to problem load and should not be affected by loading a
new problem.
*/
virtual void setObjSense(double s) = 0;
/** Set a single column lower bound.
Use -getInfinity() for -infinity. */
virtual void setColLower( int elementIndex, double elementValue ) = 0;
/** Set the lower bounds for all columns.
array [getNumCols()] is an array of values for the lower bounds.
This defaults to a series of set operations and is here for speed.
*/
virtual void setColLower(const double * array);
/** Set a single column upper bound.
Use getInfinity() for infinity. */
virtual void setColUpper( int elementIndex, double elementValue ) = 0;
/** Set the upper bounds for all columns.
array [getNumCols()] is an array of values for the upper bounds.
This defaults to a series of set operations and is here for speed.
*/
virtual void setColUpper(const double * array);
/** Set a single column lower and upper bound.
The default implementation just invokes setColLower() and
setColUpper() */
virtual void setColBounds( int elementIndex,
double lower, double upper ) {
setColLower(elementIndex, lower);
setColUpper(elementIndex, upper);
}
/** Set the upper and lower bounds of a set of columns.
The default implementation just invokes setColBounds() over and over
again. For each column, boundList must contain both a lower and
upper bound, in that order.
*/
virtual void setColSetBounds(const int* indexFirst,
const int* indexLast,
const double* boundList);
/** Set a single row lower bound.
Use -getInfinity() for -infinity. */
virtual void setRowLower( int elementIndex, double elementValue ) = 0;
/** Set a single row upper bound.
Use getInfinity() for infinity. */
virtual void setRowUpper( int elementIndex, double elementValue ) = 0;
/** Set a single row lower and upper bound.
The default implementation just invokes setRowLower() and
setRowUpper() */
virtual void setRowBounds( int elementIndex,
double lower, double upper ) {
setRowLower(elementIndex, lower);
setRowUpper(elementIndex, upper);
}
/** Set the bounds on a set of rows.
The default implementation just invokes setRowBounds() over and over
again. For each row, boundList must contain both a lower and
upper bound, in that order.
*/
virtual void setRowSetBounds(const int* indexFirst,
const int* indexLast,
const double* boundList);
/** Set the type of a single row */
virtual void setRowType(int index, char sense, double rightHandSide,
double range) = 0;
/** Set the type of a set of rows.
The default implementation just invokes setRowType()
over and over again.
*/
virtual void setRowSetTypes(const int* indexFirst,
const int* indexLast,
const char* senseList,
const double* rhsList,
const double* rangeList);
/** Set the primal solution variable values
colsol[getNumCols()] is an array of values for the primal variables.
These values are copied to memory owned by the solver interface
object or the solver. They will be returned as the result of
getColSolution() until changed by another call to setColSolution() or
by a call to any solver routine. Whether the solver makes use of the
solution in any way is solver-dependent.
*/
virtual void setColSolution(const double *colsol) = 0;
/** Set dual solution variable values
rowprice[getNumRows()] is an array of values for the dual variables.
These values are copied to memory owned by the solver interface
object or the solver. They will be returned as the result of
getRowPrice() until changed by another call to setRowPrice() or by a
call to any solver routine. Whether the solver makes use of the
solution in any way is solver-dependent.
*/
virtual void setRowPrice(const double * rowprice) = 0;
/** Fix variables at bound based on reduced cost
For variables currently at bound, fix the variable at bound if the
reduced cost exceeds the gap. Return the number of variables fixed.
If justInteger is set to false, the routine will also fix continuous
variables, but the test still assumes a delta of 1.0.
*/
virtual int reducedCostFix(double gap, bool justInteger=true);
//@}
//-------------------------------------------------------------------------
/**@name Methods to set variable type */
//@{
/** Set the index-th variable to be a continuous variable */
virtual void setContinuous(int index) = 0;
/** Set the index-th variable to be an integer variable */
virtual void setInteger(int index) = 0;
/** Set the variables listed in indices (which is of length len) to be
continuous variables */
virtual void setContinuous(const int* indices, int len);
/** Set the variables listed in indices (which is of length len) to be
integer variables */
virtual void setInteger(const int* indices, int len);
//@}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
/*! \brief Data type for name vectors. */
typedef std::vector<std::string> OsiNameVec ;
/*! \name Methods for row and column names
Osi defines three name management disciplines: `auto names' (0), `lazy
names' (1), and `full names' (2). See the description of
#OsiNameDiscipline for details. Changing the name discipline (via
setIntParam()) will not automatically add or remove name information,
but setting the discipline to auto will make existing information
inaccessible until the discipline is reset to lazy or full.
By definition, a row index of getNumRows() (<i>i.e.</i>, one larger than
the largest valid row index) refers to the objective function.
OSI users and implementors: While the OSI base class can define an
interface and provide rudimentary support, use of names really depends
on support by the OsiXXX class to ensure that names are managed
correctly. If an OsiXXX class does not support names, it should return
false for calls to getIntParam() or setIntParam() that reference
OsiNameDiscipline.
*/
//@{
/*! \brief Generate a standard name of the form Rnnnnnnn or Cnnnnnnn
Set \p rc to 'r' for a row name, 'c' for a column name.
The `nnnnnnn' part is generated from ndx and will contain 7 digits
by default, padded with zeros if necessary. As a special case,
ndx = getNumRows() is interpreted as a request for the name of the
objective function. OBJECTIVE is returned, truncated to digits+1
characters to match the row and column names.
*/
virtual std::string dfltRowColName(char rc,
int ndx, unsigned digits = 7) const ;
/*! \brief Return the name of the objective function */
#pragma warning(suppress: 4309)
virtual std::string getObjName (unsigned maxLen = static_cast<unsigned>(std::string::npos)) const ;
/*! \brief Set the name of the objective function */
virtual inline void setObjName (std::string name)
{ objName_ = name ; }
/*! \brief Return the name of the row.
The routine will <i>always</i> return some name, regardless of the name
discipline or the level of support by an OsiXXX derived class. Use
maxLen to limit the length.
*/
virtual std::string getRowName(int rowIndex,
#pragma warning(suppress: 4309)
unsigned maxLen = static_cast<unsigned>(std::string::npos)) const ;
/*! \brief Return a pointer to a vector of row names
If the name discipline (#OsiNameDiscipline) is auto, the return value
will be a vector of length zero. If the name discipline is lazy, the
vector will contain only names supplied by the client and will be no
larger than needed to hold those names; entries not supplied will be
null strings. In particular, the objective name is <i>not</i>
included in the vector for lazy names. If the name discipline is
full, the vector will have getNumRows() names, either supplied or
generated, plus one additional entry for the objective name.
*/
virtual const OsiNameVec &getRowNames() ;
/*! \brief Set a row name
Quietly does nothing if the name discipline (#OsiNameDiscipline) is
auto. Quietly fails if the row index is invalid.
*/
virtual void setRowName(int ndx, std::string name) ;
/*! \brief Set multiple row names
The run of len entries starting at srcNames[srcStart] are installed as
row names starting at row index tgtStart. The base class implementation
makes repeated calls to setRowName.
*/
virtual void setRowNames(OsiNameVec &srcNames,
int srcStart, int len, int tgtStart) ;
/*! \brief Delete len row names starting at index tgtStart
The specified row names are removed and the remaining row names are
copied down to close the gap.
*/
virtual void deleteRowNames(int tgtStart, int len) ;
/*! \brief Return the name of the column
The routine will <i>always</i> return some name, regardless of the name
discipline or the level of support by an OsiXXX derived class. Use
maxLen to limit the length.
*/
virtual std::string getColName(int colIndex,
#pragma warning(suppress: 4309)
unsigned maxLen = static_cast<unsigned>(std::string::npos)) const ;
/*! \brief Return a pointer to a vector of column names
If the name discipline (#OsiNameDiscipline) is auto, the return value
will be a vector of length zero. If the name discipline is lazy, the
vector will contain only names supplied by the client and will be no
larger than needed to hold those names; entries not supplied will be
null strings. If the name discipline is full, the vector will have
getNumCols() names, either supplied or generated.
*/
virtual const OsiNameVec &getColNames() ;
/*! \brief Set a column name
Quietly does nothing if the name discipline (#OsiNameDiscipline) is
auto. Quietly fails if the column index is invalid.
*/
virtual void setColName(int ndx, std::string name) ;
/*! \brief Set multiple column names
The run of len entries starting at srcNames[srcStart] are installed as
column names starting at column index tgtStart. The base class
implementation makes repeated calls to setColName.
*/
virtual void setColNames(OsiNameVec &srcNames,
int srcStart, int len, int tgtStart) ;
/*! \brief Delete len column names starting at index tgtStart
The specified column names are removed and the remaining column names
are copied down to close the gap.
*/
virtual void deleteColNames(int tgtStart, int len) ;
/*! \brief Set row and column names from a CoinMpsIO object.
Also sets the name of the objective function. If the name discipline
is auto, you get what you asked for. This routine does not use
setRowName or setColName.
*/
void setRowColNames(const CoinMpsIO &mps) ;
/*! \brief Set row and column names from a CoinModel object.
If the name discipline is auto, you get what you asked for.
This routine does not use setRowName or setColName.
*/
void setRowColNames(CoinModel &mod) ;
/*! \brief Set row and column names from a CoinLpIO object.
Also sets the name of the objective function. If the name discipline is
auto, you get what you asked for. This routine does not use setRowName
or setColName.
*/
void setRowColNames(CoinLpIO &mod) ;
//@}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
/**@name Methods to modify the constraint system.
Note that new columns are added as continuous variables.
*/
//@{
/** Add a column (primal variable) to the problem. */
virtual void addCol(const CoinPackedVectorBase& vec,
const double collb, const double colub,
const double obj) = 0;
/*! \brief Add a named column (primal variable) to the problem.
The default implementation adds the column, then changes the name. This
can surely be made more efficient within an OsiXXX class.
*/
virtual void addCol(const CoinPackedVectorBase& vec,
const double collb, const double colub,
const double obj, std::string name) ;
/** Add a column (primal variable) to the problem. */
virtual void addCol(int numberElements,
const int* rows, const double* elements,
const double collb, const double colub,
const double obj) ;
/*! \brief Add a named column (primal variable) to the problem.
The default implementation adds the column, then changes the name. This
can surely be made more efficient within an OsiXXX class.
*/
virtual void addCol(int numberElements,
const int* rows, const double* elements,
const double collb, const double colub,
const double obj, std::string name) ;
/** Add a set of columns (primal variables) to the problem.
The default implementation simply makes repeated calls to
addCol().
*/
virtual void addCols(const int numcols,
const CoinPackedVectorBase * const * cols,
const double* collb, const double* colub,
const double* obj);
/** Add a set of columns (primal variables) to the problem.
The default implementation simply makes repeated calls to
addCol().
*/
virtual void addCols(const int numcols, const int* columnStarts,
const int* rows, const double* elements,
const double* collb, const double* colub,
const double* obj);
/// Add columns using a CoinBuild object
void addCols(const CoinBuild & buildObject);
/** Add columns from a model object. returns
-1 if object in bad state (i.e. has row information)
otherwise number of errors
modelObject non const as can be regularized as part of build
*/
int addCols(CoinModel & modelObject);
#if 0
/** */
virtual void addCols(const CoinPackedMatrix& matrix,
const double* collb, const double* colub,
const double* obj);
#endif
/** \brief Remove a set of columns (primal variables) from the
problem.
The solver interface for a basis-oriented solver will maintain valid
warm start information if all deleted variables are nonbasic.
*/
virtual void deleteCols(const int num, const int * colIndices) = 0;
/*! \brief Add a row (constraint) to the problem. */
virtual void addRow(const CoinPackedVectorBase& vec,
const double rowlb, const double rowub) = 0;
/*! \brief Add a named row (constraint) to the problem.
The default implementation adds the row, then changes the name. This
can surely be made more efficient within an OsiXXX class.
*/
virtual void addRow(const CoinPackedVectorBase& vec,
const double rowlb, const double rowub,
std::string name) ;
/*! \brief Add a row (constraint) to the problem. */
virtual void addRow(const CoinPackedVectorBase& vec,
const char rowsen, const double rowrhs,
const double rowrng) = 0;
/*! \brief Add a named row (constraint) to the problem.
The default implementation adds the row, then changes the name. This
can surely be made more efficient within an OsiXXX class.
*/
virtual void addRow(const CoinPackedVectorBase& vec,
const char rowsen, const double rowrhs,
const double rowrng, std::string name) ;
/*! Add a row (constraint) to the problem.
Converts to addRow(CoinPackedVectorBase&,const double,const double).
*/
virtual void addRow(int numberElements,
const int *columns, const double *element,
const double rowlb, const double rowub) ;
/*! Add a set of rows (constraints) to the problem.
The default implementation simply makes repeated calls to
addRow().
*/
virtual void addRows(const int numrows,
const CoinPackedVectorBase * const * rows,
const double* rowlb, const double* rowub);
/** Add a set of rows (constraints) to the problem.
The default implementation simply makes repeated calls to
addRow().
*/
virtual void addRows(const int numrows,
const CoinPackedVectorBase * const * rows,
const char* rowsen, const double* rowrhs,
const double* rowrng);
/** Add a set of rows (constraints) to the problem.
The default implementation simply makes repeated calls to
addRow().
*/
virtual void addRows(const int numrows, const int *rowStarts,
const int *columns, const double *element,
const double *rowlb, const double *rowub);
/// Add rows using a CoinBuild object
void addRows(const CoinBuild &buildObject);
/*! Add rows from a CoinModel object.
Returns -1 if the object is in the wrong state (<i>i.e.</i>, has
column-major information), otherwise the number of errors.
The modelObject is not const as it can be regularized as part of
the build.
*/
int addRows(CoinModel &modelObject);
#if 0
/** */
virtual void addRows(const CoinPackedMatrix& matrix,
const double* rowlb, const double* rowub);
/** */
virtual void addRows(const CoinPackedMatrix& matrix,
const char* rowsen, const double* rowrhs,
const double* rowrng);
#endif
/** \brief Delete a set of rows (constraints) from the problem.
The solver interface for a basis-oriented solver will maintain valid
warm start information if all deleted rows are loose.
*/
virtual void deleteRows(const int num, const int * rowIndices) = 0;
/** \brief Replace the constraint matrix
I (JJF) am getting annoyed because I can't just replace a matrix.
The default behavior of this is do nothing so only use where that would
not matter, e.g. strengthening a matrix for MIP.
*/
virtual void replaceMatrixOptional(const CoinPackedMatrix & ) {}
/** \brief Replace the constraint matrix
And if it does matter (not used at present)
*/
virtual void replaceMatrix(const CoinPackedMatrix & ) {abort();}
/** \brief Save a copy of the base model
If solver wants it can save a copy of "base" (continuous) model here.
*/
virtual void saveBaseModel() {}
/** \brief Reduce the constraint system to the specified number of
constraints.
If solver wants it can restore a copy of "base" (continuous) model
here.
\note
The name is somewhat misleading. Implementors should consider
the opportunity to optimise behaviour in the common case where
\p numberRows is exactly the number of original constraints. Do not,
however, neglect the possibility that \p numberRows does not equal
the number of original constraints.
*/
virtual void restoreBaseModel(int numberRows);
//-----------------------------------------------------------------------
/** Apply a collection of cuts.
Only cuts which have an <code>effectiveness >= effectivenessLb</code>
are applied.
<ul>
<li> ReturnCode.getNumineffective() -- number of cuts which were
not applied because they had an
<code>effectiveness < effectivenessLb</code>
<li> ReturnCode.getNuminconsistent() -- number of invalid cuts
<li> ReturnCode.getNuminconsistentWrtIntegerModel() -- number of
cuts that are invalid with respect to this integer model
<li> ReturnCode.getNuminfeasible() -- number of cuts that would
make this integer model infeasible
<li> ReturnCode.getNumApplied() -- number of integer cuts which
were applied to the integer model
<li> cs.size() == getNumineffective() +
getNuminconsistent() +
getNuminconsistentWrtIntegerModel() +
getNuminfeasible() +
getNumApplied()
</ul>
*/
virtual ApplyCutsReturnCode applyCuts(const OsiCuts & cs,
double effectivenessLb = 0.0);
/** Apply a collection of row cuts which are all effective.
applyCuts seems to do one at a time which seems inefficient.
Would be even more efficient to pass an array of pointers.
*/
virtual void applyRowCuts(int numberCuts, const OsiRowCut * cuts);
/** Apply a collection of row cuts which are all effective.
This is passed in as an array of pointers.
*/
virtual void applyRowCuts(int numberCuts, const OsiRowCut ** cuts);
/// Deletes branching information before columns deleted
void deleteBranchingInfo(int numberDeleted, const int * which);
//@}
//---------------------------------------------------------------------------
/**@name Methods for problem input and output */
//@{
/*! \brief Load in a problem by copying the arguments. The constraints on
the rows are given by lower and upper bounds.
If a pointer is 0 then the following values are the default:
<ul>
<li> <code>colub</code>: all columns have upper bound infinity
<li> <code>collb</code>: all columns have lower bound 0
<li> <code>rowub</code>: all rows have upper bound infinity
<li> <code>rowlb</code>: all rows have lower bound -infinity
<li> <code>obj</code>: all variables have 0 objective coefficient
</ul>
Note that the default values for rowub and rowlb produce the
constraint -infty <= ax <= infty. This is probably not what you want.
*/
virtual void loadProblem (const CoinPackedMatrix& matrix,
const double* collb, const double* colub,
const double* obj,
const double* rowlb, const double* rowub) = 0;
/*! \brief Load in a problem by assuming ownership of the arguments.
The constraints on the rows are given by lower and upper bounds.
For default argument values see the matching loadProblem method.
\warning
The arguments passed to this method will be freed using the
C++ <code>delete</code> and <code>delete[]</code> functions.
*/
virtual void assignProblem (CoinPackedMatrix*& matrix,
double*& collb, double*& colub, double*& obj,
double*& rowlb, double*& rowub) = 0;
/*! \brief Load in a problem by copying the arguments.
The constraints on the rows are given by sense/rhs/range triplets.
If a pointer is 0 then the following values are the default:
<ul>
<li> <code>colub</code>: all columns have upper bound infinity
<li> <code>collb</code>: all columns have lower bound 0
<li> <code>obj</code>: all variables have 0 objective coefficient
<li> <code>rowsen</code>: all rows are >=
<li> <code>rowrhs</code>: all right hand sides are 0
<li> <code>rowrng</code>: 0 for the ranged rows
</ul>
Note that the default values for rowsen, rowrhs, and rowrng produce the
constraint ax >= 0.
*/
virtual void loadProblem (const CoinPackedMatrix& matrix,
const double* collb, const double* colub,
const double* obj,
const char* rowsen, const double* rowrhs,
const double* rowrng) = 0;
/*! \brief Load in a problem by assuming ownership of the arguments.
The constraints on the rows are given by sense/rhs/range triplets.
For default argument values see the matching loadProblem method.
\warning
The arguments passed to this method will be freed using the
C++ <code>delete</code> and <code>delete[]</code> functions.
*/
virtual void assignProblem (CoinPackedMatrix*& matrix,
double*& collb, double*& colub, double*& obj,
char*& rowsen, double*& rowrhs,
double*& rowrng) = 0;
/*! \brief Load in a problem by copying the arguments. The constraint
matrix is is specified with standard column-major
column starts / row indices / coefficients vectors.
The constraints on the rows are given by lower and upper bounds.
The matrix vectors must be gap-free. Note that <code>start</code> must
have <code>numcols+1</code> entries so that the length of the last column
can be calculated as <code>start[numcols]-start[numcols-1]</code>.
See the previous loadProblem method using rowlb and rowub for default
argument values.
*/
virtual void loadProblem (const int numcols, const int numrows,
const CoinBigIndex * start, const int* index,
const double* value,
const double* collb, const double* colub,
const double* obj,
const double* rowlb, const double* rowub) = 0;
/*! \brief Load in a problem by copying the arguments. The constraint
matrix is is specified with standard column-major
column starts / row indices / coefficients vectors.
The constraints on the rows are given by sense/rhs/range triplets.
The matrix vectors must be gap-free. Note that <code>start</code> must
have <code>numcols+1</code> entries so that the length of the last column
can be calculated as <code>start[numcols]-start[numcols-1]</code>.
See the previous loadProblem method using sense/rhs/range for default
argument values.
*/
virtual void loadProblem (const int numcols, const int numrows,
const CoinBigIndex * start, const int* index,
const double* value,
const double* collb, const double* colub,
const double* obj,
const char* rowsen, const double* rowrhs,
const double* rowrng) = 0;
/*! \brief Load a model from a CoinModel object. Return the number of
errors encountered.
The modelObject parameter cannot be const as it may be changed as part
of process. If keepSolution is true will try and keep warmStart.
*/
virtual int loadFromCoinModel (CoinModel & modelObject,
bool keepSolution=false);
/*! \brief Read a problem in MPS format from the given filename.
The default implementation uses CoinMpsIO::readMps() to read
the MPS file and returns the number of errors encountered.
*/
virtual int readMps (const char *filename,
const char *extension = "mps") ;
/*! \brief Read a problem in MPS format from the given full filename.
This uses CoinMpsIO::readMps() to read the MPS file and returns the
number of errors encountered. It also may return an array of set
information
*/
virtual int readMps (const char *filename, const char*extension,
int & numberSets, CoinSet ** & sets);
/*! \brief Read a problem in GMPL format from the given filenames.
The default implementation uses CoinMpsIO::readGMPL(). This capability
is available only if the third-party package Glpk is installed.
*/
virtual int readGMPL (const char *filename, const char *dataname=nullptr);
/*! \brief Write the problem in MPS format to the specified file.
If objSense is non-zero, a value of -1.0 causes the problem to be
written with a maximization objective; +1.0 forces a minimization
objective. If objSense is zero, the choice is left to the implementation.
*/
virtual void writeMps (const char *filename,
const char *extension = "mps",
double objSense=0.0) const = 0;
/*! \brief Write the problem in MPS format to the specified file with
more control over the output.
Row and column names may be null.
formatType is
<ul>
<li> 0 - normal
<li> 1 - extra accuracy
<li> 2 - IEEE hex
</ul>
Returns non-zero on I/O error
*/
int writeMpsNative (const char *filename,
const char ** rowNames, const char ** columnNames,
int formatType=0,int numberAcross=2,
double objSense=0.0, int numberSOS=0,
const CoinSet * setInfo=nullptr) const ;
/***********************************************************************/
// Lp files
/** Write the problem into an Lp file of the given filename with the
specified extension.
Coefficients with value less than epsilon away from an integer value
are written as integers.
Write at most numberAcross monomials on a line.
Write non integer numbers with decimals digits after the decimal point.
The written problem is always a minimization problem.
If the current problem is a maximization problem, the
intended objective function for the written problem is the current
objective function multiplied by -1. If the current problem is a
minimization problem, the intended objective function for the
written problem is the current objective function.
If objSense < 0, the intended objective function is multiplied by -1
before writing the problem. It is left unchanged otherwise.
Write objective function name and constraint names if useRowNames is
true. This version calls writeLpNative().
*/
virtual void writeLp(const char *filename,
const char *extension = "lp",
double epsilon = 1e-5,
int numberAcross = 10,
int decimals = 5,
double objSense = 0.0,
bool useRowNames = true) const;
/** Write the problem into the file pointed to by the parameter fp.
Other parameters are similar to
those of writeLp() with first parameter filename.
*/
virtual void writeLp(FILE *fp,
double epsilon = 1e-5,
int numberAcross = 10,
int decimals = 5,
double objSense = 0.0,
bool useRowNames = true) const;
/** Write the problem into an Lp file. Parameters are similar to
those of writeLp(), but in addition row names and column names
may be given.
Parameter rowNames may be NULL, in which case default row names
are used. If rowNames is not NULL, it must have exactly one entry
per row in the problem and one additional
entry (rowNames[getNumRows()] with the objective function name.
These getNumRows()+1 entries must be distinct. If this is not the
case, default row names
are used. In addition, format restrictions are imposed on names
(see CoinLpIO::is_invalid_name() for details).
Similar remarks can be made for the parameter columnNames which
must either be NULL or have exactly getNumCols() distinct entries.
Write objective function name and constraint names if
useRowNames is true. */
int writeLpNative(const char *filename,
char const * const * const rowNames,
char const * const * const columnNames,
const double epsilon = 1.0e-5,
const int numberAcross = 10,
const int decimals = 5,
const double objSense = 0.0,
const bool useRowNames = true) const;
/** Write the problem into the file pointed to by the parameter fp.
Other parameters are similar to
those of writeLpNative() with first parameter filename.
*/
int writeLpNative(FILE *fp,
char const * const * const rowNames,
char const * const * const columnNames,
const double epsilon = 1.0e-5,
const int numberAcross = 10,
const int decimals = 5,
const double objSense = 0.0,
const bool useRowNames = true) const;
/// Read file in LP format from file with name filename.
/// See class CoinLpIO for description of this format.
virtual int readLp(const char *filename, const double epsilon = 1e-5);
/// Read file in LP format from the file pointed to by fp.
/// See class CoinLpIO for description of this format.
int readLp(FILE *fp, const double epsilon = 1e-5);
//@}
//---------------------------------------------------------------------------
/**@name Miscellaneous */
//@{
#ifdef COIN_SNAPSHOT
/// Return a CoinSnapshot
virtual CoinSnapshot * snapshot(bool createArrays=true) const;
#endif
#ifdef COIN_FACTORIZATION_INFO
/// Return number of entries in L part of current factorization
virtual CoinBigIndex getSizeL() const;
/// Return number of entries in U part of current factorization
virtual CoinBigIndex getSizeU() const;
#endif
//@}
//---------------------------------------------------------------------------
/**@name Setting/Accessing application data */
//@{
/** Set application data.
This is a pointer that the application can store into and
retrieve from the solver interface.
This field is available for the application to optionally
define and use.
*/
void setApplicationData (void * appData);
/** Create a clone of an Auxiliary Information object.
The base class just stores an application data pointer
but can be more general. Application data pointer is
designed for one user while this can be extended to cope
with more general extensions.
*/
void setAuxiliaryInfo(OsiAuxInfo * auxiliaryInfo);
/// Get application data
void * getApplicationData() const;
/// Get pointer to auxiliary info object
OsiAuxInfo * getAuxiliaryInfo() const;
//@}
//---------------------------------------------------------------------------
/**@name Message handling
See the COIN library documentation for additional information about
COIN message facilities.
*/
//@{
/** Pass in a message handler
It is the client's responsibility to destroy a message handler installed
by this routine; it will not be destroyed when the solver interface is
destroyed.
*/
virtual void passInMessageHandler(CoinMessageHandler * handler);
/// Set language
void newLanguage(CoinMessages::Language language);
inline void setLanguage(CoinMessages::Language language)
{newLanguage(language);}
/// Return a pointer to the current message handler
inline CoinMessageHandler * messageHandler() const
{return handler_;}
/// Return the current set of messages
inline CoinMessages messages()
{return messages_;}
/// Return a pointer to the current set of messages
inline CoinMessages * messagesPointer()
{return &messages_;}
/// Return true if default handler
inline bool defaultHandler() const
{ return defaultHandler_;}
//@}
//---------------------------------------------------------------------------
/**@name Methods for dealing with discontinuities other than integers.
Osi should be able to know about SOS and other types. This is an optional
section where such information can be stored.
*/
//@{
/** \brief Identify integer variables and create corresponding objects.
Record integer variables and create an OsiSimpleInteger object for each
one. All existing OsiSimpleInteger objects will be destroyed.
If justCount then no objects created and we just store numberIntegers_
*/
void findIntegers(bool justCount);
/** \brief Identify integer variables and SOS and create corresponding objects.
Record integer variables and create an OsiSimpleInteger object for each
one. All existing OsiSimpleInteger objects will be destroyed.
If the solver supports SOS then do the same for SOS.
If justCount then no objects created and we just store numberIntegers_
Returns number of SOS
*/
virtual int findIntegersAndSOS(bool justCount);
/// Get the number of objects
inline int numberObjects() const { return numberObjects_;}
/// Set the number of objects
inline void setNumberObjects(int number)
{ numberObjects_=number;}
/// Get the array of objects
inline OsiObject ** objects() const { return object_;}
/// Get the specified object
const inline OsiObject * object(int which) const { return object_[which];}
/// Get the specified object
inline OsiObject * modifiableObject(int which) const { return object_[which];}
/// Delete all object information
void deleteObjects();
/** Add in object information.
Objects are cloned; the owner can delete the originals.
*/
void addObjects(int numberObjects, OsiObject ** objects);
/** Use current solution to set bounds so current integer feasible solution will stay feasible.
Only feasible bounds will be used, even if current solution outside bounds. The amount of
such violation will be returned (and if small can be ignored)
*/
double forceFeasible();
//@}
//---------------------------------------------------------------------------
/*! @name Methods related to testing generated cuts
See the documentation for OsiRowCutDebugger for additional details.
*/
//@{
/*! \brief Activate the row cut debugger.
If \p modelName is in the set of known models then all cuts are
checked to see that they do NOT cut off the optimal solution known
to the debugger.
*/
virtual void activateRowCutDebugger (const char *modelName);
/*! \brief Activate the row cut debugger using a full solution array.
Activate the debugger for a model not included in the debugger's
internal database. Cuts will be checked to see that they do NOT
cut off the given solution.
\p solution must be a full solution vector, but only the integer
variables need to be correct. The debugger will fill in the continuous
variables by solving an lp relaxation with the integer variables
fixed as specified. If the given values for the continuous variables
should be preserved, set \p keepContinuous to true.
*/
virtual void activateRowCutDebugger(const double *solution,
bool enforceOptimality = true);
/*! \brief Get the row cut debugger provided the solution known to the
debugger is within the feasible region held in the solver.
If there is a row cut debugger object associated with model AND if
the solution known to the debugger is within the solver's current
feasible region (i.e., the column bounds held in the solver are
compatible with the known solution) then a pointer to the debugger
is returned which may be used to test validity of cuts.
Otherwise NULL is returned
*/
const OsiRowCutDebugger *getRowCutDebugger() const;
/*! \brief Get the row cut debugger object
Return the row cut debugger object if it exists. One common usage of
this method is to obtain a debugger object in order to execute
OsiRowCutDebugger::redoSolution (so that the stored solution is again
compatible with the problem held in the solver).
*/
OsiRowCutDebugger * getRowCutDebuggerAlways() const;
//@}
/*! \name OsiSimplexInterface
\brief Simplex Interface
Methods for an advanced interface to a simplex solver. The interface
comprises two groups of methods. Group 1 contains methods for tableau
access. Group 2 contains methods for dictating individual simplex pivots.
*/
//@{
/*! \brief Return the simplex implementation level.
The return codes are:
- 0: the simplex interface is not implemented.
- 1: the Group 1 (tableau access) methods are implemented.
- 2: the Group 2 (pivoting) methods are implemented
The codes are cumulative - a solver which implements Group 2 also
implements Group 1.
*/
virtual int canDoSimplexInterface() const ;
//@}
/*! \name OsiSimplex Group 1
\brief Tableau access methods.
This group of methods provides access to rows and columns of the basis
inverse and to rows and columns of the tableau.
*/
//@{
/*! \brief Prepare the solver for the use of tableau access methods.
Prepares the solver for the use of the tableau access methods, if
any such preparation is required.
The \c const attribute is required due to the places this method
may be called (e.g., within CglCutGenerator::generateCuts()).
*/
virtual void enableFactorization() const ;
/*! \brief Undo the effects of #enableFactorization. */
virtual void disableFactorization() const ;
/*! \brief Check if an optimal basis is available.
Returns true if the problem has been solved to optimality and a
basis is available. This should be used to see if the tableau access
operations are possible and meaningful.
\note
Implementors please note that this method may be called
before #enableFactorization.
*/
virtual bool basisIsAvailable() const ;
/// Synonym for #basisIsAvailable
inline bool optimalBasisIsAvailable() const { return basisIsAvailable() ; }
/*! \brief Retrieve status information for column and row variables.
This method returns status as integer codes:
<ul>
<li> 0: free
<li> 1: basic
<li> 2: nonbasic at upper bound
<li> 3: nonbasic at lower bound
</ul>
The #getWarmStart method provides essentially the same functionality
for a simplex-oriented solver, but the implementation details are very
different.
\note
Logical variables associated with rows are all assumed to have +1
coefficients, so for a <= constraint the logical will be at lower
bound if the constraint is tight.
\note
Implementors may choose to implement this method as a wrapper which
converts a CoinWarmStartBasis to the requested representation.
*/
virtual void getBasisStatus(int* cstat, int* rstat) const ;
/*! \brief Set the status of column and row variables and update
the basis factorization and solution.
Status information should be coded as documented for #getBasisStatus.
Returns 0 if all goes well, 1 if something goes wrong.
This method differs from #setWarmStart in the format of the input
and in its immediate effect. Think of it as #setWarmStart immediately
followed by #resolve, but no pivots are allowed.
\note
Implementors may choose to implement this method as a wrapper that calls
#setWarmStart and #resolve if the no pivot requirement can be satisfied.
*/
virtual int setBasisStatus(const int* cstat, const int* rstat) ;
/*! \brief Calculate duals and reduced costs for the given objective
coefficients.
The solver's objective coefficient vector is not changed.
*/
virtual void getReducedGradient(double* columnReducedCosts,
double* duals, const double* c) const ;
/*! \brief Get a row of the tableau
If \p slack is not null, it will be loaded with the coefficients for
the artificial (logical) variables (i.e., the row of the basis inverse).
*/
virtual void getBInvARow(int row, double* z, double* slack = nullptr) const ;
/*! \brief Get a row of the basis inverse */
virtual void getBInvRow(int row, double* z) const ;
/*! \brief Get a column of the tableau */
virtual void getBInvACol(int col, double* vec) const ;
/*! \brief Get a column of the basis inverse */
virtual void getBInvCol(int col, double* vec) const ;
/*! \brief Get indices of basic variables
If the logical (artificial) for row i is basic, the index should be coded
as (#getNumCols + i).
The order of indices must match the order of elements in the vectors
returned by #getBInvACol and #getBInvCol.
*/
virtual void getBasics(int* index) const ;
//@}
/*! \name OsiSimplex Group 2
\brief Pivoting methods
This group of methods provides for control of individual pivots by a
simplex solver.
*/
//@{
/**Enables normal operation of subsequent functions.
This method is supposed to ensure that all typical things (like
reduced costs, etc.) are updated when individual pivots are executed
and can be queried by other methods. says whether will be
doing primal or dual
*/
virtual void enableSimplexInterface(bool doingPrimal) ;
///Undo whatever setting changes the above method had to make
virtual void disableSimplexInterface() ;
/** Perform a pivot by substituting a colIn for colOut in the basis.
The status of the leaving variable is given in outStatus. Where
1 is to upper bound, -1 to lower bound
Return code was undefined - now for OsiClp is 0 for okay,
1 if inaccuracy forced re-factorization (should be okay) and
-1 for singular factorization
*/
virtual int pivot(int colIn, int colOut, int outStatus) ;
/** Obtain a result of the primal pivot
Outputs: colOut -- leaving column, outStatus -- its status,
t -- step size, and, if dx!=NULL, *dx -- primal ray direction.
Inputs: colIn -- entering column, sign -- direction of its change (+/-1).
Both for colIn and colOut, artificial variables are index by
the negative of the row index minus 1.
Return code (for now): 0 -- leaving variable found,
-1 -- everything else?
Clearly, more informative set of return values is required
Primal and dual solutions are updated
*/
virtual int primalPivotResult(int colIn, int sign,
int& colOut, int& outStatus,
double& t, CoinPackedVector* dx);
/** Obtain a result of the dual pivot (similar to the previous method)
Differences: entering variable and a sign of its change are now
the outputs, the leaving variable and its statuts -- the inputs
If dx!=NULL, then *dx contains dual ray
Return code: same
*/
virtual int dualPivotResult(int& colIn, int& sign,
int colOut, int outStatus,
double& t, CoinPackedVector* dx) ;
//@}
//---------------------------------------------------------------------------
///@name Constructors and destructors
//@{
/// Default Constructor
OsiSolverInterface();
/** Clone
The result of calling clone(false) is defined to be equivalent to
calling the default constructor OsiSolverInterface().
*/
virtual OsiSolverInterface * clone(bool copyData = true) const = 0;
/// Copy constructor
OsiSolverInterface(const OsiSolverInterface &);
/// Assignment operator
OsiSolverInterface & operator=(const OsiSolverInterface& rhs);
/// Destructor
virtual ~OsiSolverInterface ();
/** Reset the solver interface.
A call to reset() returns the solver interface to the same state as
it would have if it had just been constructed by calling the default
constructor OsiSolverInterface().
*/
virtual void reset();
//@}
//---------------------------------------------------------------------------
protected:
///@name Protected methods
//@{
/** Apply a row cut (append to the constraint matrix). */
virtual void applyRowCut( const OsiRowCut & rc ) = 0;
/** Apply a column cut (adjust the bounds of one or more variables). */
virtual void applyColCut( const OsiColCut & cc ) = 0;
/** A quick inlined function to convert from the lb/ub style of
constraint definition to the sense/rhs/range style */
inline void
convertBoundToSense(const double lower, const double upper,
char& sense, double& right, double& range) const;
/** A quick inlined function to convert from the sense/rhs/range style
of constraint definition to the lb/ub style */
inline void
convertSenseToBound(const char sense, const double right,
const double range,
double& lower, double& upper) const;
/** A quick inlined function to force a value to be between a minimum and
a maximum value */
template <class T> inline T
forceIntoRange(const T value, const T lower, const T upper) const {
return value < lower ? lower : (value > upper ? upper : value);
}
/** Set OsiSolverInterface object state for default constructor
This routine establishes the initial values of data fields in the
OsiSolverInterface object when the object is created using the
default constructor.
*/
void setInitialData();
//@}
///@name Protected member data
//@{
/*! \brief Pointer to row cut debugger object
Mutable so that we can update the solution held in the debugger while
maintaining const'ness for the Osi object.
*/
mutable OsiRowCutDebugger * rowCutDebugger_;
// Why not just make useful stuff protected?
/// Message handler
CoinMessageHandler * handler_;
/** Flag to say if the currrent handler is the default handler.
Indicates if the solver interface object is responsible
for destruction of the handler (true) or if the client is
responsible (false).
*/
bool defaultHandler_;
/// Messages
CoinMessages messages_;
/// Number of integers
int numberIntegers_;
/// Total number of objects
int numberObjects_;
/// Integer and ... information (integer info normally at beginning)
OsiObject ** object_;
/** Column type
0 - continuous
1 - binary (may get fixed later)
2 - general integer (may get fixed later)
*/
mutable char * columnType_;
//@}
//---------------------------------------------------------------------------
private:
///@name Private member data
//@{
/// Pointer to user-defined data structure - and more if user wants
OsiAuxInfo * appDataEtc_;
/// Array of integer parameters
int intParam_[OsiLastIntParam];
/// Array of double parameters
double dblParam_[OsiLastDblParam];
/// Array of string parameters
std::string strParam_[OsiLastStrParam];
/// Array of hint parameters
bool hintParam_[OsiLastHintParam];
/// Array of hint strengths
OsiHintStrength hintStrength_[OsiLastHintParam];
/** Warm start information used for hot starts when the default
hot start implementation is used. */
CoinWarmStart* ws_;
/// Column solution satisfying lower and upper column bounds
std::vector<double> strictColSolution_;
/// Row names
OsiNameVec rowNames_ ;
/// Column names
OsiNameVec colNames_ ;
/// Objective name
std::string objName_ ;
//@}
};
//#############################################################################
/** A quick inlined function to convert from the lb/ub style of constraint
definition to the sense/rhs/range style */
inline void
OsiSolverInterface::convertBoundToSense(const double lower, const double upper,
char& sense, double& right,
double& range) const
{
double inf = getInfinity();
range = 0.0;
if (lower > -inf) {
if (upper < inf) {
right = upper;
if (upper==lower) {
sense = 'E';
} else {
sense = 'R';
range = upper - lower;
}
} else {
sense = 'G';
right = lower;
}
} else {
if (upper < inf) {
sense = 'L';
right = upper;
} else {
sense = 'N';
right = 0.0;
}
}
}
//-----------------------------------------------------------------------------
/** A quick inlined function to convert from the sense/rhs/range style of
constraint definition to the lb/ub style */
inline void
OsiSolverInterface::convertSenseToBound(const char sense, const double right,
const double range,
double& lower, double& upper) const
{
double inf=getInfinity();
switch (sense) {
case 'E':
lower = upper = right;
break;
case 'L':
lower = -inf;
upper = right;
break;
case 'G':
lower = right;
upper = inf;
break;
case 'R':
lower = right - range;
upper = right;
break;
case 'N':
lower = -inf;
upper = inf;
break;
}
}
#endif
|
anlambert/tulip
|
thirdparty/OGDF/include/coin/OsiSolverInterface.hpp
|
C++
|
lgpl-3.0
| 78,372
|
<!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 (1.8.0_31) on Mon Apr 06 15:30:27 CEST 2015 -->
<title>Uses of Class org.cloudbus.cloudsim.distributions.ExponentialDistr</title>
<meta name="date" content="2015-04-06">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.cloudbus.cloudsim.distributions.ExponentialDistr";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/cloudbus/cloudsim/distributions/ExponentialDistr.html" title="class in org.cloudbus.cloudsim.distributions">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?org/cloudbus/cloudsim/distributions/class-use/ExponentialDistr.html" target="_top">Frames</a></li>
<li><a href="ExponentialDistr.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 org.cloudbus.cloudsim.distributions.ExponentialDistr" class="title">Uses of Class<br>org.cloudbus.cloudsim.distributions.ExponentialDistr</h2>
</div>
<div class="classUseContainer">No usage of org.cloudbus.cloudsim.distributions.ExponentialDistr</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/cloudbus/cloudsim/distributions/ExponentialDistr.html" title="class in org.cloudbus.cloudsim.distributions">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?org/cloudbus/cloudsim/distributions/class-use/ExponentialDistr.html" target="_top">Frames</a></li>
<li><a href="ExponentialDistr.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>
|
Udacity2048/CloudSimDisk
|
docs/org/cloudbus/cloudsim/distributions/class-use/ExponentialDistr.html
|
HTML
|
lgpl-3.0
| 4,677
|
<div class="psc-cms-ui-form-panel oid-form"><form method="post" action=""><input type="hidden" name="identifier" value="11605" />
<input type="hidden" name="type" value="oid" />
<input type="hidden" name="dataJSON" value="{"productId":2,"pageId":8}" />
<input type="hidden" name="productId" value="2" />
<input type="hidden" name="action" value="edit" />
<div class="psc-cms-ui-buttonset psc-cms-ui-buttonset-right" style="float: right"><button class="psc-cms-ui-button psc-cms-ui-button-left psc-cms-ui-button-save save psc-guid-4e5cb17740cd8" style="float: left">Speichern</button>
<script type="text/javascript">
jQuery('button.psc-guid-4e5cb17740cd8')
.button({icons:{primary:'ui-icon-disk'}})
</script>
<button class="psc-cms-ui-button psc-cms-ui-button-left psc-cms-ui-button-reload reload psc-guid-4e5cb1774120b" style="float: left">Neu laden</button>
<script type="text/javascript">
jQuery('button.psc-guid-4e5cb1774120b')
.button({icons:{primary:'ui-icon-refresh'}})
</script>
<button class="psc-cms-ui-button psc-cms-ui-button-left psc-cms-ui-button-save-close save-close psc-guid-4e5cb177416f8" style="float: left">Speichern und Schließen</button>
<script type="text/javascript">
jQuery('button.psc-guid-4e5cb177416f8')
.button({icons:{primary:'ui-icon-disk',secondary:'ui-icon-close'}})
</script>
</div>
<div class="clear"></div>
<input type="hidden" name="pageId" value="8" /><div class="psc-cms-ui-accordion oid-items psc-guid-oid-items-11605" id="oid-items-11605"><h3><a href="#">Sounds und Texte (<span class="fx-count text-count">0</span>)</a></h3>
<div><ul class="fx text"></ul></div>
<h3><a href="#">Matrix Aktionen</a></h3>
<div><button class="psc-cms-ui-button drop-mode-item tabs-content-item drag-item psc-guid-oid-11605-tabs-content-item-mode-1" id="oid-11605-tabs-content-item-mode-1">Modus-Wechsel zu Entdecken<input type="hidden" name="identifier" value="1" /> <input type="hidden" name="type" value="mode" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-mode-1')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button drop-mode-item tabs-content-item drag-item psc-guid-oid-11605-tabs-content-item-mode-2" id="oid-11605-tabs-content-item-mode-2">Modus-Wechsel zu Wissen<input type="hidden" name="identifier" value="2" /> <input type="hidden" name="type" value="mode" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-mode-2')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button drop-mode-item tabs-content-item drag-item psc-guid-oid-11605-tabs-content-item-mode-3" id="oid-11605-tabs-content-item-mode-3">Modus-Wechsel zu Erzählen<input type="hidden" name="identifier" value="3" /> <input type="hidden" name="type" value="mode" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-mode-3')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button drop-mode-item tabs-content-item drag-item psc-guid-oid-11605-tabs-content-item-mode-4" id="oid-11605-tabs-content-item-mode-4">Modus-Wechsel zu Game<input type="hidden" name="identifier" value="4" /> <input type="hidden" name="type" value="mode" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-mode-4')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-exitgame" id="oid-11605-tabs-content-item-doaction-exitgame">ExitGame()<input type="hidden" name="identifier" value="exitgame" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-exitgame')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game1" id="oid-11605-tabs-content-item-doaction-game1">Game(1)<input type="hidden" name="identifier" value="game1" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game1')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game2" id="oid-11605-tabs-content-item-doaction-game2">Game(2)<input type="hidden" name="identifier" value="game2" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game2')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game3" id="oid-11605-tabs-content-item-doaction-game3">Game(3)<input type="hidden" name="identifier" value="game3" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game3')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game4" id="oid-11605-tabs-content-item-doaction-game4">Game(4)<input type="hidden" name="identifier" value="game4" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game4')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game5" id="oid-11605-tabs-content-item-doaction-game5">Game(5)<input type="hidden" name="identifier" value="game5" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game5')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game6" id="oid-11605-tabs-content-item-doaction-game6">Game(6)<input type="hidden" name="identifier" value="game6" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game6')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game7" id="oid-11605-tabs-content-item-doaction-game7">Game(7)<input type="hidden" name="identifier" value="game7" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game7')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game8" id="oid-11605-tabs-content-item-doaction-game8">Game(8)<input type="hidden" name="identifier" value="game8" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game8')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game9" id="oid-11605-tabs-content-item-doaction-game9">Game(9)<input type="hidden" name="identifier" value="game9" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game9')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
<button class="psc-cms-ui-button tabs-content-item drop-doaction-item drag-item psc-guid-oid-11605-tabs-content-item-doaction-game10" id="oid-11605-tabs-content-item-doaction-game10">Game(10)<input type="hidden" name="identifier" value="game10" /> <input type="hidden" name="type" value="doaction" /> <input type="hidden" name="data" value="[]" /></button>
<script type="text/javascript">
jQuery('button.psc-guid-oid-11605-tabs-content-item-doaction-game10')
.draggable({cancel:false,revert:false,helper:'clone',scroll:true,scrollSpeed:40,appendTo:'#oid-11605'})
.button({})
</script>
<br />
</div>
<h3><a href="#">Optionen</a></h3>
<div><button class="psc-cms-ui-button add-sounds psc-guid-4e5cb17768746">Sounds / Texte hinzufügen</button>
<script type="text/javascript">
jQuery('button.psc-guid-4e5cb17768746')
.button({icons:{primary:'ui-icon-circle-plus'}})
</script>
<br />
<button class="psc-cms-ui-button template-basic-button psc-guid-4e5cb17768c6e">Template benutzen: Basic-Button</button>
<script type="text/javascript">
jQuery('button.psc-guid-4e5cb17768c6e')
.button({icons:{primary:'ui-icon-script',secondary:'ui-icon-info'}})
</script>
<br />
<button class="psc-cms-ui-button template-knowledge-button psc-guid-4e5cb177691bd">Template benutzen: Knowledge-Button</button>
<script type="text/javascript">
jQuery('button.psc-guid-4e5cb177691bd')
.button({icons:{primary:'ui-icon-script',secondary:'ui-icon-info'}})
</script>
<br />
<button class="psc-cms-ui-button template-song-button psc-guid-4e5cb177696f5">Template benutzen: Song-Button</button>
<script type="text/javascript">
jQuery('button.psc-guid-4e5cb177696f5')
.button({icons:{primary:'ui-icon-script',secondary:'ui-icon-info'}})
</script>
<br />
<button class="psc-cms-ui-button template-story-button psc-guid-4e5cb17769c73">Template benutzen: Story-Button</button>
<script type="text/javascript">
jQuery('button.psc-guid-4e5cb17769c73')
.button({icons:{primary:'ui-icon-script',secondary:'ui-icon-info'}})
</script>
<br />
<br /><br />
<button class="psc-cms-ui-button psc-guid-4e5cb1776a1ac">OID löschen</button>
<script type="text/javascript">
jQuery('button.psc-guid-4e5cb1776a1ac')
.click(function (e) {
e.preventDefault();
})
.tabsContentItem({identifier:11605,type:'oid',data:{productId:2,pageId:8},drag:false})
.button({icons:{primary:'ui-icon-trash',secondary:'ui-icon-info'}})
</script>
<br />
</div>
</div>
<script type="text/javascript">
jQuery('div.psc-guid-oid-items-11605')
.accordion({collapsible:true,autoHeight:true,active:3})
</script>
<div class="mode"><fieldset class="ui-corner-all ui-widget-content psc-cms-ui-group mode entdecken" id="oid-11605-mode-1"><legend class="collapsible">Tippreihenfolge für Entdecken</legend>
<div class="content"><input type="hidden" name="modeNum" value="1" /><input type="hidden" name="modeId" value="1" /><fieldset class="ui-corner-all ui-widget-content psc-cms-ui-group tip"><legend>1. Tippen</legend>
<div class="content transition"><input type="hidden" name="tipNum" value="1" />
<input type="hidden" name="transitionId" value="" />
<div class="action" id="action-11605-1-1-1"><input type="hidden" name="actionId" value="" />
<input type="hidden" name="actionNum" value="1" /> <label for="drop-box-11605-1-1-1" class="drop-box small-font">Act0</label> <div class="drop-box ui-widget-content ui-corner-all psc-guid-drop-box-11605-1-1-1" style="min-height: 60px" id="drop-box-11605-1-1-1"></div>
<script type="text/javascript">
jQuery('div.psc-guid-drop-box-11605-1-1-1')
.sortable({cancel:false,start:function (event,ui) {
sortable = true;
},stop:function (event,ui) {
sortable = false;
},update:function (event, ui) {
if (ui.sender == null) { // nur die empfangene drop-box triggered
$(this).trigger('unsaved');
}
},connectWith:'#oid-11605 div.drop-box'})
.droppable({hoverClass:'hover',drop:function (event, ui) {
if (sortable) return;
var elem = ui.draggable;
var item = {
oid: 11605,
identifier: elem.find('input[name=identifier]').val(),
type: elem.find('input[name=type]').val()
};
$.matrixManager('addItemToBox', $(this), item);
}})
</script>
<label class="checkbox-label" title="Wenn aktiviert, werden alle Sounds in diesem Tip zufällig abgespielt. Wenn deaktiviert werden alle Sounds in diesem Tip nach der angegebenen Reihenfolge abgespielt."><input type="checkbox" name="random" value="true" /> Random?</label></div>
<button class="psc-cms-ui-button add-action psc-guid-add-action-11605-1-1" id="add-action-11605-1-1">weitere Aktion</button>
<script type="text/javascript">
jQuery('button.psc-guid-add-action-11605-1-1')
.button({icons:{primary:'ui-icon-plusthick'}})
</script>
</div></fieldset><button class="psc-cms-ui-button psc-cms-ui-add add-tipp psc-guid-add-tip-11605-1" id="add-tip-11605-1">weiteres Tippen</button>
<script type="text/javascript">
jQuery('button.psc-guid-add-tip-11605-1')
.button({icons:{primary:'ui-icon-circle-plus'}})
</script>
</div></fieldset></div><div class="mode"><fieldset class="ui-corner-all ui-widget-content psc-cms-ui-group mode wissen" id="oid-11605-mode-2"><legend class="collapsible">Tippreihenfolge für Wissen</legend>
<div class="content"><input type="hidden" name="modeNum" value="2" /><input type="hidden" name="modeId" value="2" /><fieldset class="ui-corner-all ui-widget-content psc-cms-ui-group tip"><legend>1. Tippen</legend>
<div class="content transition"><input type="hidden" name="tipNum" value="1" />
<input type="hidden" name="transitionId" value="" />
<div class="action" id="action-11605-2-1-1"><input type="hidden" name="actionId" value="" />
<input type="hidden" name="actionNum" value="1" /> <label for="drop-box-11605-2-1-1" class="drop-box small-font">Act0</label> <div class="drop-box ui-widget-content ui-corner-all psc-guid-drop-box-11605-2-1-1" style="min-height: 60px" id="drop-box-11605-2-1-1"></div>
<script type="text/javascript">
jQuery('div.psc-guid-drop-box-11605-2-1-1')
.sortable({cancel:false,start:function (event,ui) {
sortable = true;
},stop:function (event,ui) {
sortable = false;
},update:function (event, ui) {
if (ui.sender == null) { // nur die empfangene drop-box triggered
$(this).trigger('unsaved');
}
},connectWith:'#oid-11605 div.drop-box'})
.droppable({hoverClass:'hover',drop:function (event, ui) {
if (sortable) return;
var elem = ui.draggable;
var item = {
oid: 11605,
identifier: elem.find('input[name=identifier]').val(),
type: elem.find('input[name=type]').val()
};
$.matrixManager('addItemToBox', $(this), item);
}})
</script>
<label class="checkbox-label" title="Wenn aktiviert, werden alle Sounds in diesem Tip zufällig abgespielt. Wenn deaktiviert werden alle Sounds in diesem Tip nach der angegebenen Reihenfolge abgespielt."><input type="checkbox" name="random" value="true" /> Random?</label></div>
<button class="psc-cms-ui-button add-action psc-guid-add-action-11605-2-1" id="add-action-11605-2-1">weitere Aktion</button>
<script type="text/javascript">
jQuery('button.psc-guid-add-action-11605-2-1')
.button({icons:{primary:'ui-icon-plusthick'}})
</script>
</div></fieldset><button class="psc-cms-ui-button psc-cms-ui-add add-tipp psc-guid-add-tip-11605-2" id="add-tip-11605-2">weiteres Tippen</button>
<script type="text/javascript">
jQuery('button.psc-guid-add-tip-11605-2')
.button({icons:{primary:'ui-icon-circle-plus'}})
</script>
</div></fieldset></div><div class="mode"><fieldset class="ui-corner-all ui-widget-content psc-cms-ui-group mode erzählen" id="oid-11605-mode-3"><legend class="collapsible">Tippreihenfolge für Erzählen</legend>
<div class="content"><input type="hidden" name="modeNum" value="3" /><input type="hidden" name="modeId" value="3" /><fieldset class="ui-corner-all ui-widget-content psc-cms-ui-group tip"><legend>1. Tippen</legend>
<div class="content transition"><input type="hidden" name="tipNum" value="1" />
<input type="hidden" name="transitionId" value="" />
<div class="action" id="action-11605-3-1-1"><input type="hidden" name="actionId" value="" />
<input type="hidden" name="actionNum" value="1" /> <label for="drop-box-11605-3-1-1" class="drop-box small-font">Act0</label> <div class="drop-box ui-widget-content ui-corner-all psc-guid-drop-box-11605-3-1-1" style="min-height: 60px" id="drop-box-11605-3-1-1"></div>
<script type="text/javascript">
jQuery('div.psc-guid-drop-box-11605-3-1-1')
.sortable({cancel:false,start:function (event,ui) {
sortable = true;
},stop:function (event,ui) {
sortable = false;
},update:function (event, ui) {
if (ui.sender == null) { // nur die empfangene drop-box triggered
$(this).trigger('unsaved');
}
},connectWith:'#oid-11605 div.drop-box'})
.droppable({hoverClass:'hover',drop:function (event, ui) {
if (sortable) return;
var elem = ui.draggable;
var item = {
oid: 11605,
identifier: elem.find('input[name=identifier]').val(),
type: elem.find('input[name=type]').val()
};
$.matrixManager('addItemToBox', $(this), item);
}})
</script>
<label class="checkbox-label" title="Wenn aktiviert, werden alle Sounds in diesem Tip zufällig abgespielt. Wenn deaktiviert werden alle Sounds in diesem Tip nach der angegebenen Reihenfolge abgespielt."><input type="checkbox" name="random" value="true" /> Random?</label></div>
<button class="psc-cms-ui-button add-action psc-guid-add-action-11605-3-1" id="add-action-11605-3-1">weitere Aktion</button>
<script type="text/javascript">
jQuery('button.psc-guid-add-action-11605-3-1')
.button({icons:{primary:'ui-icon-plusthick'}})
</script>
</div></fieldset><button class="psc-cms-ui-button psc-cms-ui-add add-tipp psc-guid-add-tip-11605-3" id="add-tip-11605-3">weiteres Tippen</button>
<script type="text/javascript">
jQuery('button.psc-guid-add-tip-11605-3')
.button({icons:{primary:'ui-icon-circle-plus'}})
</script>
</div></fieldset></div><div class="mode"><fieldset class="ui-corner-all ui-widget-content psc-cms-ui-group mode game" id="oid-11605-mode-4"><legend class="collapsible">Tippreihenfolge für Game</legend>
<div class="content"><input type="hidden" name="modeNum" value="4" /><input type="hidden" name="modeId" value="4" /><fieldset class="ui-corner-all ui-widget-content psc-cms-ui-group tip"><legend>1. Tippen</legend>
<div class="content transition"><input type="hidden" name="tipNum" value="1" />
<input type="hidden" name="transitionId" value="" />
<div class="action" id="action-11605-4-1-1"><input type="hidden" name="actionId" value="" />
<input type="hidden" name="actionNum" value="1" /> <label for="drop-box-11605-4-1-1" class="drop-box small-font">Act0</label> <div class="drop-box ui-widget-content ui-corner-all psc-guid-drop-box-11605-4-1-1" style="min-height: 60px" id="drop-box-11605-4-1-1"></div>
<script type="text/javascript">
jQuery('div.psc-guid-drop-box-11605-4-1-1')
.sortable({cancel:false,start:function (event,ui) {
sortable = true;
},stop:function (event,ui) {
sortable = false;
},update:function (event, ui) {
if (ui.sender == null) { // nur die empfangene drop-box triggered
$(this).trigger('unsaved');
}
},connectWith:'#oid-11605 div.drop-box'})
.droppable({hoverClass:'hover',drop:function (event, ui) {
if (sortable) return;
var elem = ui.draggable;
var item = {
oid: 11605,
identifier: elem.find('input[name=identifier]').val(),
type: elem.find('input[name=type]').val()
};
$.matrixManager('addItemToBox', $(this), item);
}})
</script>
<label class="checkbox-label" title="Wenn aktiviert, werden alle Sounds in diesem Tip zufällig abgespielt. Wenn deaktiviert werden alle Sounds in diesem Tip nach der angegebenen Reihenfolge abgespielt."><input type="checkbox" name="random" value="true" /> Random?</label></div>
<button class="psc-cms-ui-button add-action psc-guid-add-action-11605-4-1" id="add-action-11605-4-1">weitere Aktion</button>
<script type="text/javascript">
jQuery('button.psc-guid-add-action-11605-4-1')
.button({icons:{primary:'ui-icon-plusthick'}})
</script>
</div></fieldset><button class="psc-cms-ui-button psc-cms-ui-add add-tipp psc-guid-add-tip-11605-4" id="add-tip-11605-4">weiteres Tippen</button>
<script type="text/javascript">
jQuery('button.psc-guid-add-tip-11605-4')
.button({icons:{primary:'ui-icon-circle-plus'}})
</script>
</div></fieldset></div><div class="clear"></div>
</form></div>
|
webforge-labs/psc-cms
|
tests/files/htmltester.oid.out.html
|
HTML
|
lgpl-3.0
| 27,204
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.