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 |
|---|---|---|---|---|---|
/**
* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent project.
*
* iotagent is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with iotagent. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with iot_support at tid dot es
*/
#include <iostream>
#include <time.h>
#include <algorithm>
#include "store_const.h"
#include "service_collection.h"
iota::ServiceCollection::ServiceCollection()
: Collection(iota::store::types::SERVICE_TABLE){};
iota::ServiceCollection::ServiceCollection(ServiceCollection& dc)
: Collection(dc){};
iota::ServiceCollection::~ServiceCollection(){};
void iota::ServiceCollection::addServicePath(const std::string& data,
mongo::BSONObjBuilder& obj) {
if (data.empty()) {
obj.append(iota::store::types::SERVICE_PATH,
iota::types::FIWARE_SERVICEPATH_DEFAULT);
} else if (data.compare("/*") != 0 && data.compare("/#") != 0) {
obj.append(iota::store::types::SERVICE_PATH, data);
}
}
/*void iota::ServiceCollection::fillSharKey(mongo::BSONObjBuilder &obj)
{
// CLAVE DE SHARD service, name
if (_m_device._name.empty())
{
throw std::runtime_error("ServiceCollection::fillSharKey name is needed
as shardKey");
}
obj.append("name", _m_device._name);
if (_m_device._service.empty())
{
throw std::runtime_error("ServiceCollection::fillSharKey service is
needed as shardKey");
}
obj.append("service", _m_device._service);
}*/
const std::string& iota::ServiceCollection::get_resource_name() {
return iota::store::types::RESOURCE;
}
int iota::ServiceCollection::fill_all_resources(
const std::string& service, const std::string& service_path,
std::vector<std::string>& resources) {
int result = 0;
mongo::BSONObj query =
BSON(iota::store::types::SERVICE
<< service << iota::store::types::SERVICE_PATH << service_path);
mongo::BSONObjBuilder field_return;
field_return.append(iota::store::types::RESOURCE, 1);
find(query, field_return);
mongo::BSONObj obj;
std::string resource;
while (more()) {
obj = next();
resource = obj.getStringField(iota::store::types::RESOURCE);
if (!resource.empty()) {
resources.push_back(resource);
result++;
}
}
return result;
}
int iota::ServiceCollection::createTableAndIndex() {
// db.SERVICE.ensureIndex({"apikey":1, resource:1},{"unique":1})
mongo::BSONObj indexUni1 =
BSON("apikey" << 1 << "resource" << 1);
createIndex(indexUni1, true);
// db.SERVICE.ensureIndex({"service":1, service_path:1,
// resource:1},{"unique":1})
mongo::BSONObj indexUni =
BSON("service" << 1 << "service_path" << 1 << "resource" << 1);
return createIndex(indexUni, true);
}
void iota::ServiceCollection::getElementsFromBSON(
mongo::BSONObj& obj, std::vector<mongo::BSONObj>& result) {
std::vector<mongo::BSONElement> be =
obj.getField(iota::store::types::SERVICES).Array();
for (unsigned int i = 0; i < be.size(); i++) {
result.push_back(be[i].embeddedObject());
}
}
| telefonicaid/fiware-IoTAgent-Cplusplus | src/util/service_collection.cc | C++ | agpl-3.0 | 3,710 |
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.provide("erpnext.accounts");
frappe.provide("erpnext.journal_entry");
frappe.ui.form.on("Journal Entry", {
setup: function(frm) {
frm.get_field('accounts').grid.editable_fields = [
{fieldname: 'account', columns: 3},
{fieldname: 'party', columns: 4},
{fieldname: 'debit_in_account_currency', columns: 2},
{fieldname: 'credit_in_account_currency', columns: 2}
];
},
refresh: function(frm) {
erpnext.toggle_naming_series();
frm.cscript.voucher_type(frm.doc);
if(frm.doc.docstatus==1) {
frm.add_custom_button(__('Ledger'), function() {
frappe.route_options = {
"voucher_no": frm.doc.name,
"from_date": frm.doc.posting_date,
"to_date": frm.doc.posting_date,
"company": frm.doc.company,
group_by_voucher: 0
};
frappe.set_route("query-report", "General Ledger");
}, "icon-table");
}
if (frm.doc.__islocal) {
frm.add_custom_button(__('Quick Entry'), function() {
return erpnext.journal_entry.quick_entry(frm);
});
}
// hide /unhide fields based on currency
erpnext.journal_entry.toggle_fields_based_on_currency(frm);
},
multi_currency: function(frm) {
erpnext.journal_entry.toggle_fields_based_on_currency(frm);
}
})
erpnext.accounts.JournalEntry = frappe.ui.form.Controller.extend({
onload: function() {
this.load_defaults();
this.setup_queries();
this.setup_balance_formatter();
},
onload_post_render: function() {
cur_frm.get_field("accounts").grid.set_multiple_add("account");
},
load_defaults: function() {
//this.frm.show_print_first = true;
if(this.frm.doc.__islocal && this.frm.doc.company) {
frappe.model.set_default_values(this.frm.doc);
$.each(this.frm.doc.accounts || [], function(i, jvd) {
frappe.model.set_default_values(jvd);
}
);
if(!this.frm.doc.amended_from) this.frm.doc.posting_date = this.frm.posting_date || get_today();
}
},
setup_queries: function() {
var me = this;
me.frm.set_query("account", "accounts", function(doc, cdt, cdn) {
return erpnext.journal_entry.account_query(me.frm);
});
me.frm.set_query("cost_center", "accounts", function(doc, cdt, cdn) {
return {
filters: {
company: me.frm.doc.company,
is_group: 0
}
};
});
me.frm.set_query("party_type", "accounts", function(doc, cdt, cdn) {
return {
filters: {"name": ["in", ["Customer", "Supplier"]]}
}
});
me.frm.set_query("reference_name", "accounts", function(doc, cdt, cdn) {
var jvd = frappe.get_doc(cdt, cdn);
// expense claim
if(jvd.reference_type==="Expense Claim") {
return {};
}
// journal entry
if(jvd.reference_type==="Journal Entry") {
frappe.model.validate_missing(jvd, "account");
return {
query: "erpnext.accounts.doctype.journal_entry.journal_entry.get_against_jv",
filters: {
account: jvd.account,
party: jvd.party
}
};
}
var out = {
filters: [
[jvd.reference_type, "docstatus", "=", 1]
]
};
if(in_list(["Sales Invoice", "Purchase Invoice"], jvd.reference_type)) {
out.filters.push([jvd.reference_type, "outstanding_amount", "!=", 0]);
// account filter
frappe.model.validate_missing(jvd, "account");
party_account_field = jvd.reference_type==="Sales Invoice" ? "debit_to": "credit_to";
out.filters.push([jvd.reference_type, party_account_field, "=", jvd.account]);
} else {
// party_type and party mandatory
frappe.model.validate_missing(jvd, "party_type");
frappe.model.validate_missing(jvd, "party");
out.filters.push([jvd.reference_type, "per_billed", "<", 100]);
}
if(jvd.party_type && jvd.party) {
out.filters.push([jvd.reference_type,
(jvd.reference_type.indexOf("Sales")===0 ? "customer" : "supplier"), "=", jvd.party]);
}
return out;
});
},
setup_balance_formatter: function() {
var me = this;
$.each(["balance", "party_balance"], function(i, field) {
var df = frappe.meta.get_docfield("Journal Entry Account", field, me.frm.doc.name);
df.formatter = function(value, df, options, doc) {
var currency = frappe.meta.get_field_currency(df, doc);
var dr_or_cr = value ? ('<label>' + (value > 0.0 ? __("Dr") : __("Cr")) + '</label>') : "";
return "<div style='text-align: right'>"
+ ((value==null || value==="") ? "" : format_currency(Math.abs(value), currency))
+ " " + dr_or_cr
+ "</div>";
}
})
},
reference_name: function(doc, cdt, cdn) {
var d = frappe.get_doc(cdt, cdn);
if(d.reference_name) {
if (d.reference_type==="Purchase Invoice" && !flt(d.debit)) {
this.get_outstanding('Purchase Invoice', d.reference_name, doc.company, d);
}
if (d.reference_type==="Sales Invoice" && !flt(d.credit)) {
this.get_outstanding('Sales Invoice', d.reference_name, doc.company, d);
}
if (d.reference_type==="Journal Entry" && !flt(d.credit) && !flt(d.debit)) {
this.get_outstanding('Journal Entry', d.reference_name, doc.company, d);
}
}
},
get_outstanding: function(doctype, docname, company, child) {
var me = this;
var args = {
"doctype": doctype,
"docname": docname,
"party": child.party,
"account": child.account,
"account_currency": child.account_currency,
"company": company
}
return frappe.call({
method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_outstanding",
args: { args: args},
callback: function(r) {
if(r.message) {
$.each(r.message, function(field, value) {
frappe.model.set_value(child.doctype, child.name, field, value);
})
}
}
});
},
accounts_add: function(doc, cdt, cdn) {
var row = frappe.get_doc(cdt, cdn);
$.each(doc.accounts, function(i, d) {
if(d.account && d.party && d.party_type) {
row.account = d.account;
row.party = d.party;
row.party_type = d.party_type;
}
});
// set difference
if(doc.difference) {
if(doc.difference > 0) {
row.credit_in_account_currency = doc.difference;
row.credit = doc.difference;
} else {
row.debit_in_account_currency = -doc.difference;
row.debit = -doc.difference;
}
}
cur_frm.cscript.update_totals(doc);
},
});
cur_frm.script_manager.make(erpnext.accounts.JournalEntry);
cur_frm.cscript.update_totals = function(doc) {
var td=0.0; var tc =0.0;
var accounts = doc.accounts || [];
for(var i in accounts) {
td += flt(accounts[i].debit, precision("debit", accounts[i]));
tc += flt(accounts[i].credit, precision("credit", accounts[i]));
}
var doc = locals[doc.doctype][doc.name];
doc.total_debit = td;
doc.total_credit = tc;
doc.difference = flt((td - tc), precision("difference"));
refresh_many(['total_debit','total_credit','difference']);
}
cur_frm.cscript.get_balance = function(doc,dt,dn) {
cur_frm.cscript.update_totals(doc);
return $c_obj(cur_frm.doc, 'get_balance', '', function(r, rt){
cur_frm.refresh();
});
}
cur_frm.cscript.validate = function(doc,cdt,cdn) {
cur_frm.cscript.update_totals(doc);
}
cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
if(doc.select_print_heading){
// print heading
cur_frm.pformat.print_heading = doc.select_print_heading;
}
else
cur_frm.pformat.print_heading = __("Journal Entry");
}
cur_frm.cscript.voucher_type = function(doc, cdt, cdn) {
cur_frm.set_df_property("cheque_no", "reqd", doc.voucher_type=="Bank Entry");
cur_frm.set_df_property("cheque_date", "reqd", doc.voucher_type=="Bank Entry");
if(!doc.company) return;
var update_jv_details = function(doc, r) {
var jvdetail = frappe.model.add_child(doc, "Journal Entry Account", "accounts");
$.each(r, function(i, d) {
var row = frappe.model.add_child(doc, "Journal Entry Account", "accounts");
row.account = d.account;
row.balance = d.balance;
});
refresh_field("accounts");
}
if(!(doc.accounts || []).length) {
if(in_list(["Bank Entry", "Cash Entry"], doc.voucher_type)) {
return frappe.call({
type: "GET",
method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_default_bank_cash_account",
args: {
"account_type": (doc.voucher_type=="Bank Entry" ?
"Bank" : (doc.voucher_type=="Cash" ? "Cash" : null)),
"company": doc.company
},
callback: function(r) {
if(r.message) {
update_jv_details(doc, [r.message]);
}
}
})
} else if(doc.voucher_type=="Opening Entry") {
return frappe.call({
type:"GET",
method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_opening_accounts",
args: {
"company": doc.company
},
callback: function(r) {
frappe.model.clear_table(doc, "accounts");
if(r.message) {
update_jv_details(doc, r.message);
}
cur_frm.set_value("is_opening", "Yes")
}
})
}
}
}
frappe.ui.form.on("Journal Entry Account", {
party: function(frm, cdt, cdn) {
var d = frappe.get_doc(cdt, cdn);
if(!d.account && d.party_type && d.party) {
if(!frm.doc.company) frappe.throw(__("Please select Company"));
return frm.call({
method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_party_account_and_balance",
child: d,
args: {
company: frm.doc.company,
party_type: d.party_type,
party: d.party
}
});
}
},
account: function(frm, dt, dn) {
var d = locals[dt][dn];
if(d.account) {
if(!frm.doc.company) frappe.throw(__("Please select Company first"));
if(!frm.doc.posting_date) frappe.throw(__("Please select Posting Date first"));
return frappe.call({
method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_account_balance_and_party_type",
args: {
account: d.account,
date: frm.doc.posting_date,
company: frm.doc.company,
debit: flt(d.debit_in_account_currency),
credit: flt(d.credit_in_account_currency),
exchange_rate: d.exchange_rate
},
callback: function(r) {
if(r.message) {
$.extend(d, r.message);
erpnext.journal_entry.set_debit_credit_in_company_currency(frm, dt, dn);
refresh_field('accounts');
}
}
});
}
},
debit_in_account_currency: function(frm, cdt, cdn) {
erpnext.journal_entry.set_exchange_rate(frm, cdt, cdn);
},
credit_in_account_currency: function(frm, cdt, cdn) {
erpnext.journal_entry.set_exchange_rate(frm, cdt, cdn);
},
debit: function(frm, dt, dn) {
cur_frm.cscript.update_totals(frm.doc);
},
credit: function(frm, dt, dn) {
cur_frm.cscript.update_totals(frm.doc);
},
exchange_rate: function(frm, cdt, cdn) {
var company_currency = frappe.get_doc(":Company", frm.doc.company).default_currency;
var row = locals[cdt][cdn];
if(row.account_currency == company_currency || !frm.doc.multi_currency) {
frappe.model.set_value(cdt, cdn, "exchange_rate", 1);
}
erpnext.journal_entry.set_debit_credit_in_company_currency(frm, cdt, cdn);
}
})
frappe.ui.form.on("Journal Entry Account", "accounts_remove", function(frm) {
cur_frm.cscript.update_totals(frm.doc);
});
$.extend(erpnext.journal_entry, {
toggle_fields_based_on_currency: function(frm) {
var fields = ["currency_section", "account_currency", "exchange_rate", "debit", "credit"];
var grid = frm.get_field("accounts").grid;
if(grid) grid.set_column_disp(fields, frm.doc.multi_currency);
// dynamic label
var field_label_map = {
"debit_in_account_currency": "Debit",
"credit_in_account_currency": "Credit"
};
$.each(field_label_map, function (fieldname, label) {
var df = frappe.meta.get_docfield("Journal Entry Account", fieldname, frm.doc.name);
df.label = frm.doc.multi_currency ? (label + " in Account Currency") : label;
})
},
set_debit_credit_in_company_currency: function(frm, cdt, cdn) {
var row = locals[cdt][cdn];
frappe.model.set_value(cdt, cdn, "debit",
flt(flt(row.debit_in_account_currency)*row.exchange_rate, precision("debit", row)));
frappe.model.set_value(cdt, cdn, "credit",
flt(flt(row.credit_in_account_currency)*row.exchange_rate, precision("credit", row)));
cur_frm.cscript.update_totals(frm.doc);
},
set_exchange_rate: function(frm, cdt, cdn) {
var company_currency = frappe.get_doc(":Company", frm.doc.company).default_currency;
var row = locals[cdt][cdn];
if(row.account_currency == company_currency || !frm.doc.multi_currency) {
row.exchange_rate = 1;
erpnext.journal_entry.set_debit_credit_in_company_currency(frm, cdt, cdn);
} else if (!row.exchange_rate || row.exchange_rate == 1 || row.account_type == "Bank") {
frappe.call({
method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_exchange_rate",
args: {
account: row.account,
account_currency: row.account_currency,
company: frm.doc.company,
reference_type: cstr(row.reference_type),
reference_name: cstr(row.reference_name),
debit: flt(row.debit_in_account_currency),
credit: flt(row.credit_in_account_currency),
exchange_rate: row.exchange_rate
},
callback: function(r) {
if(r.message) {
row.exchange_rate = r.message;
erpnext.journal_entry.set_debit_credit_in_company_currency(frm, cdt, cdn);
}
}
})
} else {
erpnext.journal_entry.set_debit_credit_in_company_currency(frm, cdt, cdn);
}
refresh_field("exchange_rate", cdn, "accounts");
},
quick_entry: function(frm) {
var naming_series_options = frm.fields_dict.naming_series.df.options;
var naming_series_default = frm.fields_dict.naming_series.df.default || naming_series_options.split("\n")[0];
var dialog = new frappe.ui.Dialog({
title: __("Quick Journal Entry"),
fields: [
{fieldtype: "Currency", fieldname: "debit", label: __("Amount"), reqd: 1},
{fieldtype: "Link", fieldname: "debit_account", label: __("Debit Account"), reqd: 1,
options: "Account",
get_query: function() {
return erpnext.journal_entry.account_query(frm);
}
},
{fieldtype: "Link", fieldname: "credit_account", label: __("Credit Account"), reqd: 1,
options: "Account",
get_query: function() {
return erpnext.journal_entry.account_query(frm);
}
},
{fieldtype: "Date", fieldname: "posting_date", label: __("Date"), reqd: 1,
default: frm.doc.posting_date},
{fieldtype: "Small Text", fieldname: "user_remark", label: __("User Remark"), reqd: 1},
{fieldtype: "Select", fieldname: "naming_series", label: __("Series"), reqd: 1,
options: naming_series_options, default: naming_series_default},
]
});
dialog.set_primary_action(__("Save"), function() {
var btn = this;
var values = dialog.get_values();
frm.set_value("posting_date", values.posting_date);
frm.set_value("user_remark", values.user_remark);
frm.set_value("naming_series", values.naming_series);
// clear table is used because there might've been an error while adding child
// and cleanup didn't happen
frm.clear_table("accounts");
// using grid.add_new_row() to add a row in UI as well as locals
// this is required because triggers try to refresh the grid
var debit_row = frm.fields_dict.accounts.grid.add_new_row();
frappe.model.set_value(debit_row.doctype, debit_row.name, "account", values.debit_account);
frappe.model.set_value(debit_row.doctype, debit_row.name, "debit_in_account_currency", values.debit);
var credit_row = frm.fields_dict.accounts.grid.add_new_row();
frappe.model.set_value(credit_row.doctype, credit_row.name, "account", values.credit_account);
frappe.model.set_value(credit_row.doctype, credit_row.name, "credit_in_account_currency", values.debit);
frm.save();
dialog.hide();
});
dialog.show();
},
account_query: function(frm) {
var filters = {
company: frm.doc.company,
is_group: 0
};
if(!frm.doc.multi_currency) {
$.extend(filters, {
account_currency: frappe.get_doc(":Company", frm.doc.company).default_currency
});
}
return { filters: filters };
}
});
| anandpdoshi/erpnext | erpnext/accounts/doctype/journal_entry/journal_entry.js | JavaScript | agpl-3.0 | 15,981 |
/**
* Created by
* Pratish Shrestha <pratishshrestha@lftechnology.com>
* on 4/19/16.
*/
var jsdom = require('jsdom').jsdom;
var exposedProperties = ['window', 'navigator', 'document', 'localStorage'];
global.document = jsdom('');
global.window = document.defaultView;
global.localStorage = {getItem: ()=>{}, setItem: ()=>{}};
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property);
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js'
};
//for jQuery
global.jQuery = require('jquery');
global.$ = global.jQuery;
global.window.jQuery = global.jQuery;
global.window.$ = global.jQuery;
//for jQuery plugins
require('jquery-confirm');
require('../src/custom-ui/bootstrap-colorselector'); | leapfrogtechnology/vyaguta-resource | frontend/test/setup.js | JavaScript | agpl-3.0 | 850 |
package roart.db.thread;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import org.apache.commons.lang3.tuple.Pair;
import org.hibernate.query.Query;
import roart.db.model.HibernateUtil;
public class Queues {
public static final Deque<Object> queue = new ConcurrentLinkedDeque<Object>();
public static final Deque<String> queuedelete = new ConcurrentLinkedDeque<>();
public static final Deque<Pair<HibernateUtil, Query>> queuedeleteq = new ConcurrentLinkedDeque<>();
}
| rroart/stockstat | common/db/src/main/java/roart/db/thread/Queues.java | Java | agpl-3.0 | 513 |
import analytics
import anyjson
from channels import Group
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from lily.accounts.api.serializers import RelatedAccountSerializer
from lily.api.fields import SanitizedHtmlCharField
from lily.api.nested.mixins import RelatedSerializerMixin
from lily.api.nested.serializers import WritableNestedSerializer
from lily.api.serializers import ContentTypeSerializer
from lily.contacts.api.serializers import RelatedContactSerializer
from lily.contacts.models import Function
from lily.users.api.serializers import RelatedLilyUserSerializer, RelatedTeamSerializer
from lily.utils.api.serializers import RelatedTagSerializer
from lily.utils.request import is_external_referer
from ..models import Case, CaseStatus, CaseType
class CaseStatusSerializer(serializers.ModelSerializer):
"""
Serializer for case status model.
"""
class Meta:
model = CaseStatus
fields = (
'id',
'name',
)
class RelatedCaseStatusSerializer(RelatedSerializerMixin, CaseStatusSerializer):
pass
class CaseTypeSerializer(serializers.ModelSerializer):
"""
Serializer for case type model.
"""
class Meta:
model = CaseType
fields = (
'id',
'is_archived',
'name',
'use_as_filter',
)
class RelatedCaseTypeSerializer(RelatedSerializerMixin, CaseTypeSerializer):
pass
class CaseSerializer(WritableNestedSerializer):
"""
Serializer for the case model.
"""
# Set non mutable fields.
created_by = RelatedLilyUserSerializer(read_only=True)
content_type = ContentTypeSerializer(
read_only=True,
help_text='This is what the object is identified as in the back-end.',
)
# Related fields.
account = RelatedAccountSerializer(
required=False,
allow_null=True,
help_text='Account for which the case is being created.',
)
contact = RelatedContactSerializer(
required=False,
allow_null=True,
help_text='Contact for which the case is being created.',
)
assigned_to = RelatedLilyUserSerializer(
required=False,
allow_null=True,
assign_only=True,
help_text='Person which the case is assigned to.',
)
assigned_to_teams = RelatedTeamSerializer(
many=True,
required=False,
assign_only=True,
help_text='List of teams the case is assigned to.',
)
type = RelatedCaseTypeSerializer(
assign_only=True,
help_text='The type of case.',
)
status = RelatedCaseStatusSerializer(
assign_only=True,
help_text='Status of the case.',
)
tags = RelatedTagSerializer(
many=True,
required=False,
create_only=True,
help_text='Any tags used to further categorize the case.',
)
description = SanitizedHtmlCharField(
help_text='Any extra text to describe the case (supports Markdown).',
)
# Show string versions of fields.
priority_display = serializers.CharField(
source='get_priority_display',
read_only=True,
help_text='Human readable value of the case\'s priority.',
)
def validate(self, data):
contact_id = data.get('contact', {})
if isinstance(contact_id, dict):
contact_id = contact_id.get('id')
account_id = data.get('account', {})
if isinstance(account_id, dict):
account_id = account_id.get('id')
if contact_id and account_id:
if not Function.objects.filter(contact_id=contact_id, account_id=account_id).exists():
raise serializers.ValidationError({'contact': _('Given contact must work at the account.')})
# Check if we are related and if we only passed in the id, which means user just wants new reference.
errors = {
'account': _('Please enter an account and/or contact.'),
'contact': _('Please enter an account and/or contact.'),
}
if not self.partial:
# For POST or PUT we always want to check if either is set.
if not (account_id or contact_id):
raise serializers.ValidationError(errors)
else:
# For PATCH only check the data if both account and contact are passed.
if ('account' in data and 'contact' in data) and not (account_id or contact_id):
raise serializers.ValidationError(errors)
return super(CaseSerializer, self).validate(data)
def create(self, validated_data):
user = self.context.get('request').user
assigned_to = validated_data.get('assigned_to')
validated_data.update({
'created_by_id': user.pk,
})
if assigned_to:
Group('tenant-%s' % user.tenant.id).send({
'text': anyjson.dumps({
'event': 'case-assigned',
}),
})
if assigned_to.get('id') != user.pk:
validated_data.update({
'newly_assigned': True,
})
else:
Group('tenant-%s' % user.tenant.id).send({
'text': anyjson.dumps({
'event': 'case-unassigned',
}),
})
instance = super(CaseSerializer, self).create(validated_data)
# Track newly ceated accounts in segment.
if not settings.TESTING:
analytics.track(
user.id,
'case-created', {
'expires': instance.expires,
'assigned_to_id': instance.assigned_to_id if instance.assigned_to else '',
'creation_type': 'automatic' if is_external_referer(self.context.get('request')) else 'manual',
},
)
return instance
def update(self, instance, validated_data):
user = self.context.get('request').user
status_id = validated_data.get('status', instance.status_id)
assigned_to = validated_data.get('assigned_to')
if assigned_to:
assigned_to = assigned_to.get('id')
if isinstance(status_id, dict):
status_id = status_id.get('id')
status = CaseStatus.objects.get(pk=status_id)
# Automatically archive the case if the status is set to 'Closed'.
if status.name == 'Closed' and 'is_archived' not in validated_data:
validated_data.update({
'is_archived': True
})
# Check if the case being reassigned. If so we want to notify that user.
if assigned_to and assigned_to != user.pk:
validated_data.update({
'newly_assigned': True,
})
elif 'assigned_to' in validated_data and not assigned_to:
# Case is unassigned, so clear newly assigned flag.
validated_data.update({
'newly_assigned': False,
})
if (('status' in validated_data and status.name == 'Open') or
('is_archived' in validated_data and not validated_data.get('is_archived'))):
# Case is reopened or unarchived, so we want to notify the user again.
validated_data.update({
'newly_assigned': True,
})
if 'assigned_to' in validated_data or instance.assigned_to_id:
Group('tenant-%s' % user.tenant.id).send({
'text': anyjson.serialize({
'event': 'case-assigned',
}),
})
if (not instance.assigned_to_id or
instance.assigned_to_id and
'assigned_to' in validated_data and
not validated_data.get('assigned_to')):
Group('tenant-%s' % user.tenant.id).send({
'text': anyjson.serialize({
'event': 'case-unassigned',
}),
})
return super(CaseSerializer, self).update(instance, validated_data)
class Meta:
model = Case
fields = (
'id',
'account',
'assigned_to',
'assigned_to_teams',
'contact',
'content_type',
'created',
'created_by',
'description',
'expires',
'is_archived',
'modified',
'newly_assigned',
'priority',
'priority_display',
'status',
'tags',
'subject',
'type',
)
extra_kwargs = {
'created': {
'help_text': 'Shows the date and time when the deal was created.',
},
'expires': {
'help_text': 'Shows the date and time for when the case should be completed.',
},
'modified': {
'help_text': 'Shows the date and time when the case was last modified.',
},
'newly_assigned': {
'help_text': 'True if the assignee was changed and that person hasn\'t accepted yet.',
},
'subject': {
'help_text': 'A short description of the case.',
},
}
class RelatedCaseSerializer(RelatedSerializerMixin, CaseSerializer):
"""
Serializer for the case model when used as a relation.
"""
class Meta:
model = Case
# Override the fields because we don't want related fields in this serializer.
fields = (
'id',
'assigned_to',
'assigned_to_teams',
'created',
'created_by',
'description',
'expires',
'is_archived',
'modified',
'priority',
'priority_display',
'subject',
)
| HelloLily/hellolily | lily/cases/api/serializers.py | Python | agpl-3.0 | 9,977 |
<?php
/**
* Copyright 2015-2018 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
return [
'match' => [
'beatmap-deleted' => 'smazaná mapa',
'difference' => 'o :difference',
'failed' => 'SELHAL',
'header' => 'Multiplayer zápasy',
'in-progress' => '(zápas probíhá)',
'in_progress_spinner_label' => 'probíhá zápas',
'loading-events' => 'Načítání událostí...',
'winner' => ':team vyhrává',
'events' => [
'player-left' => ':user opustil zápas',
'player-joined' => ':user se připojil',
'player-kicked' => ':user byl vyhozen ze zápasu',
'match-created' => ':user vytvořil zápas',
'match-disbanded' => 'zápas byl zrušen',
'host-changed' => ':user se stal hostitelem zápasu',
'player-left-no-user' => 'hráč opustil zápas',
'player-joined-no-user' => 'hráč se připojil k zápasu',
'player-kicked-no-user' => 'hráč byl ze zápasu vyhozen',
'match-created-no-user' => 'zápas byl vytvořen',
'match-disbanded-no-user' => 'zápas byl zrušen',
'host-changed-no-user' => 'hostitel byl změněn',
],
'score' => [
'stats' => [
'accuracy' => 'Přesnost',
'combo' => 'Combo',
'score' => 'Skóre',
],
],
'team-types' => [
'head-to-head' => 'Head-to-head',
'tag-coop' => 'Tag Co-op',
'team-vs' => 'Team VS',
'tag-team-vs' => 'Tag Team VS',
],
'teams' => [
'blue' => 'Modrý tým',
'red' => 'Červený tým',
],
],
'game' => [
'scoring-type' => [
'score' => 'Nejvyšší skóre',
'accuracy' => 'Nejvyšší přesnost',
'combo' => 'Nejvyšší combo',
'scorev2' => 'Score V2',
],
],
];
| kj415j45/osu-web | resources/lang/cs/multiplayer.php | PHP | agpl-3.0 | 2,698 |
/*
Bacula® - The Network Backup Solution
Copyright (C) 2006-2014 Free Software Foundation Europe e.V.
The main author of Bacula is Kern Sibbald, with contributions from many
others, a complete list can be found in the file AUTHORS.
You may use this file and others of this release according to the
license defined in the LICENSE file, which includes the Affero General
Public License, v3.0 ("AGPLv3") and some additional permissions and
terms pursuant to its AGPLv3 Section 7.
Bacula® is a registered trademark of Kern Sibbald.
*/
/*
* Implement routines to determine drive type (Windows specific).
*
* Written by Robert Nelson, June 2006
*
* Version $Id$
*/
#ifndef TEST_PROGRAM
#include "bacula.h"
#include "find.h"
#else /* Set up for testing a stand alone program */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SUPPORTEDOSES \
"HAVE_WIN32\n"
#define false 0
#define true 1
#define bstrncpy strncpy
#define Dmsg0(n,s) fprintf(stderr, s)
#define Dmsg1(n,s,a1) fprintf(stderr, s, a1)
#define Dmsg2(n,s,a1,a2) fprintf(stderr, s, a1, a2)
#endif
/*
* These functions should be implemented for each OS
*
* bool drivetype(const char *fname, char *dt, int dtlen);
*/
#if defined (HAVE_WIN32)
/* Windows */
bool drivetype(const char *fname, char *dt, int dtlen)
{
CHAR rootpath[4];
UINT type;
/* Copy Drive Letter, colon, and backslash to rootpath */
bstrncpy(rootpath, fname, 3);
rootpath[3] = '\0';
type = GetDriveType(rootpath);
switch (type) {
case DRIVE_REMOVABLE: bstrncpy(dt, "removable", dtlen); return true;
case DRIVE_FIXED: bstrncpy(dt, "fixed", dtlen); return true;
case DRIVE_REMOTE: bstrncpy(dt, "remote", dtlen); return true;
case DRIVE_CDROM: bstrncpy(dt, "cdrom", dtlen); return true;
case DRIVE_RAMDISK: bstrncpy(dt, "ramdisk", dtlen); return true;
case DRIVE_UNKNOWN:
case DRIVE_NO_ROOT_DIR:
default:
return false;
}
}
/* Windows */
#else /* No recognised OS */
bool drivetype(const char *fname, char *dt, int dtlen)
{
Dmsg0(10, "!!! drivetype() not implemented for this OS. !!!\n");
#ifdef TEST_PROGRAM
Dmsg1(10, "Please define one of the following when compiling:\n\n%s\n",
SUPPORTEDOSES);
exit(EXIT_FAILURE);
#endif
return false;
}
#endif
#ifdef TEST_PROGRAM
int main(int argc, char **argv)
{
char *p;
char dt[1000];
int status = 0;
if (argc < 2) {
p = (argc < 1) ? "drivetype" : argv[0];
printf("usage:\t%s path ...\n"
"\t%s prints the drive type and pathname of the paths.\n",
p, p);
return EXIT_FAILURE;
}
while (*++argv) {
if (!drivetype(*argv, dt, sizeof(dt))) {
status = EXIT_FAILURE;
} else {
printf("%s\t%s\n", dt, *argv);
}
}
return status;
}
#endif
| rkorzeniewski/bacula | bacula/src/findlib/drivetype.c | C | agpl-3.0 | 2,948 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.protocols.ss7.map.api.smstpdu;
import java.io.Serializable;
/**
*
* @author sergey vetyutnev
*
*/
public interface ValidityEnhancedFormatData extends Serializable {
byte[] getData();
}
| RestComm/jss7 | map/map-api/src/main/java/org/restcomm/protocols/ss7/map/api/smstpdu/ValidityEnhancedFormatData.java | Java | agpl-3.0 | 1,222 |
<script src="./dist/runtime.bundle.js?v=4454171a3629744946c7"></script><script src="./dist/main_ui.bundle.js?v=70aaa5b585f983f6b592"></script> | aydancoskun/timetrex-community-edition | interface/html5/dist/_js.main_ui.template.html | HTML | agpl-3.0 | 142 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2008-2013 AvanzOSC S.L. All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
##############################################################################
from openerp.osv import orm, fields
from openerp.tools.translate import _
class create_extra_documentation(orm.TransientModel):
_name = 'module.doc.create'
def create_documentation(self, cr, uid, ids, context=None):
doc_obj = self.pool.get('module.doc')
mod_obj = self.pool.get('ir.module.module')
for id in ids:
search_ids = doc_obj.search(cr, uid, [('module_id', '=', id)],
context=context)
if not search_ids:
created_id = doc_obj.create(cr, uid, {'module_id': id},
context=context)
name = doc_obj.onchange_module_id(cr, uid, [created_id], id,
context=context)['value']['name']
doc_obj.write(cr, uid, created_id, {'name': name},
context=context)
mod_obj.write(cr, uid, id, {'doc_id': created_id},
context=context)
else:
for search_id in search_ids:
doc_obj.write(cr, uid, search_id, {'has_info': True},
context=context)
mod_obj.write(cr, uid, id, {'doc_id': search_id},
context=context)
return {
'name': _('Extra documentation'),
'view_type': 'form',
'view_mode': 'tree,form',
'res_model': 'module.doc',
'type': 'ir.actions.act_window',
}
def create_documentation_all(self, cr, uid, ids, context):
mod_obj = self.pool.get('ir.module.module')
all_ids = mod_obj.search(cr, uid, [])
return self.create_documentation(cr, uid, all_ids, context)
def create_documentation_installed(self, cr, uid, ids, context):
mod_obj = self.pool.get('ir.module.module')
installed_ids = mod_obj.search(cr, uid, [('state', '=', 'installed')])
return self.create_documentation(cr, uid, installed_ids, context)
| Daniel-CA/odoo-addons | __unported__/avanzosc_module_doc/wizard/create_module_documentation.py | Python | agpl-3.0 | 3,050 |
#pragma once
#include "../Interface/Thread.h"
#include "../Interface/Database.h"
#include "../Interface/Query.h"
#include "../Interface/Pipe.h"
#include "../Interface/File.h"
#include "../urbackupcommon/os_functions.h"
#include "ChunkPatcher.h"
#include "server_prepare_hash.h"
#include "FileIndex.h"
#include "dao/ServerFilesDao.h"
#include <vector>
#include <map>
#include "../urbackupcommon/chunk_hasher.h"
#include "server_log.h"
#include "../urbackupcommon/ExtentIterator.h"
class FileMetadata;
class MaxFileId;
const int64 link_file_min_size = 2048;
struct STmpFile
{
STmpFile(int backupid, std::string fp, std::string hashpath)
: backupid(backupid), fp(fp), hashpath(hashpath)
{
}
STmpFile(void) {}
int backupid;
std::string fp;
std::string hashpath;
};
class BackupServerHash : public IThread, public INotEnoughSpaceCallback, public IChunkPatcherCallback
{
public:
enum EAction
{
EAction_LinkOrCopy,
EAction_Copy
};
BackupServerHash(IPipe *pPipe, int pClientid, bool use_snapshots, bool use_reflink,
bool use_tmpfiles, logid_t logid, bool snapshot_file_inplace, MaxFileId& max_file_id);
~BackupServerHash(void);
void operator()(void);
bool isWorking(void);
bool hasError(void);
virtual bool handle_not_enough_space(const std::string &path);
virtual void next_chunk_patcher_bytes(const char *buf, size_t bsize, bool changed, bool* is_sparse);
virtual void next_sparse_extent_bytes(const char *buf, size_t bsize);
virtual int64 chunk_patcher_pos();
void setupDatabase(void);
void deinitDatabase(void);
bool findFileAndLink(const std::string &tfn, IFile *tf, std::string hash_fn, const std::string &sha2, _i64 t_filesize, const std::string &hashoutput_fn,
bool copy_from_hardlink_if_failed, bool &tries_once, std::string &ff_last, bool &hardlink_limit, bool &copied_file, int64& entryid, int& entryclientid, int64& rsize, int64& next_entry,
FileMetadata& metadata, bool datch_dbs, ExtentIterator* extent_iterator);
void addFileSQL(int backupid, int clientid, int incremental, const std::string &fp, const std::string &hash_path,
const std::string &shahash, _i64 filesize, _i64 rsize, int64 prev_entry, int64 prev_entry_clientid, int64 next_entry, bool update_fileindex);
static void addFileSQL(ServerFilesDao& filesdao, FileIndex& fileindex, int backupid, int clientid, int incremental, const std::string &fp,
const std::string &hash_path, const std::string &shahash, _i64 filesize, _i64 rsize, int64 prev_entry, int64 prev_entry_clientid,
int64 next_entry, bool update_fileindex);
static void deleteFileSQL(ServerFilesDao& filesdao, FileIndex& fileindex, int64 id);
struct SInMemCorrection
{
std::map<int64, int64> next_entries;
std::map<int64, int64> prev_entries;
std::map<int64, int> pointed_to;
int64 max_correct;
int64 min_correct;
bool needs_correction(int64 id)
{
return id >= min_correct && id <= max_correct;
}
};
static void deleteFileSQL(ServerFilesDao& filesdao, FileIndex& fileindex, const char* pHash, _i64 filesize, _i64 rsize, int clientid, int backupid, int incremental, int64 id, int64 prev_id, int64 next_id, int pointed_to,
bool use_transaction, bool del_entry, bool detach_dbs, bool with_backupstat, SInMemCorrection* correction);
private:
void addFile(int backupid, int incremental, IFile *tf, const std::string &tfn,
std::string hash_fn, const std::string &sha2, const std::string &orig_fn, const std::string &hashoutput_fn, int64 t_filesize,
FileMetadata& metadata, bool with_hashes, ExtentIterator* extent_iterator, int64 fileid);
struct SFindState
{
SFindState()
: state(0) {}
int state;
int64 orig_prev;
ServerFilesDao::SFindFileEntry prev;
std::map<int, int64> entryids;
std::map<int, int64>::iterator client;
};
ServerFilesDao::SFindFileEntry findFileHash(const std::string &pHash, _i64 filesize, int clientid, SFindState& state);
bool copyFile(IFile *tf, const std::string &dest, ExtentIterator* extent_iterator);
bool copyFileWithHashoutput(IFile *tf, const std::string &dest, const std::string hash_dest, ExtentIterator* extent_iterator);
bool freeSpace(int64 fs, const std::string &fp);
int countFilesInTmp(void);
IFsFile* openFileRetry(const std::string &dest, int mode, std::string& errstr);
bool patchFile(IFile *patch, const std::string &source, const std::string &dest, const std::string hash_output, const std::string hash_dest,
_i64 tfilesize, ExtentIterator* extent_iterator);
bool replaceFile(IFile *tf, const std::string &dest, const std::string &orig_fn, ExtentIterator* extent_iterator);
bool replaceFileWithHashoutput(IFile *tf, const std::string &dest, const std::string hash_dest, const std::string &orig_fn, ExtentIterator* extent_iterator);
bool renameFileWithHashoutput(IFile *tf, const std::string &dest, const std::string hash_dest, ExtentIterator* extent_iterator);
bool renameFile(IFile *tf, const std::string &dest, bool log_info=true);
bool correctPath(std::string& ff, std::string& f_hashpath);
bool correctClientName(const std::string& backupfolder, std::string& ff, std::string& f_hashpath);
bool punchHoleOrZero(IFile *tf, int64 offset, int64 size);
std::map<std::pair<std::string, _i64>, std::vector<STmpFile> > files_tmp;
ServerFilesDao* filesdao;
IPipe *pipe;
IDatabase *db;
int link_logcnt;
int space_logcnt;
int clientid;
volatile bool working;
volatile bool has_error;
IFsFile *chunk_output_fn;
ChunkPatcher chunk_patcher;
bool chunk_patcher_has_error;
bool use_snapshots;
bool use_reflink;
bool use_tmpfiles;
bool has_reflink;
_i64 chunk_patch_pos;
_i64 cow_filesize;
FileIndex *fileindex;
std::string backupfolder;
bool old_backupfolders_loaded;
std::vector<std::string> old_backupfolders;
std::map<std::string, std::vector<std::string> > client_moved_to;
logid_t logid;
bool enabled_sparse;
bool snapshot_file_inplace;
MaxFileId& max_file_id;
};
| uroni/urbackup_backend | urbackupserver/server_hash.h | C | agpl-3.0 | 6,101 |
package org.cmdbuild.common.utils;
import org.apache.commons.lang3.ArrayUtils;
public class Arrays {
private Arrays() {
// prevents instantiation
}
@SuppressWarnings("unchecked")
public static <T> T[] append(final T[] original, final T element) {
return (T[]) ArrayUtils.add(original, element);
}
public static <T> T[] addDistinct(final T[] original, final T element) {
if (element == null) {
return original;
}
for (final T origElement : original) {
if (element.equals(origElement)) {
return original;
}
}
return append(original, element);
}
}
| jzinedine/CMDBuild | cmdbuild-commons/src/main/java/org/cmdbuild/common/utils/Arrays.java | Java | agpl-3.0 | 585 |
# --
# Kernel/Output/HTML/HeaderMetaTicketSearch.pm
# Copyright (C) 2001-2012 OTRS AG, http://otrs.org/
# --
# $Id: HeaderMetaTicketSearch.pm,v 1.13 2012-11-20 14:58:36 mh Exp $
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (AGPL). If you
# did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
# --
package Kernel::Output::HTML::HeaderMetaTicketSearch;
use strict;
use warnings;
use vars qw($VERSION);
$VERSION = qw($Revision: 1.13 $) [1];
sub new {
my ( $Type, %Param ) = @_;
# allocate new hash for object
my $Self = {};
bless( $Self, $Type );
# get needed objects
for (qw(ConfigObject LogObject LayoutObject TimeObject)) {
$Self->{$_} = $Param{$_} || die "Got no $_!";
}
return $Self;
}
sub Run {
my ( $Self, %Param ) = @_;
my $Session = '';
if ( !$Self->{LayoutObject}->{SessionIDCookie} ) {
$Session = ';' . $Self->{LayoutObject}->{SessionName} . '='
. $Self->{LayoutObject}->{SessionID};
}
my $Title = $Self->{ConfigObject}->Get('ProductName');
$Title .= ' (' . $Self->{ConfigObject}->Get('Ticket::Hook') . ')';
$Self->{LayoutObject}->Block(
Name => 'MetaLink',
Data => {
Rel => 'search',
Type => 'application/opensearchdescription+xml',
Title => $Title,
Href => '$Env{"Baselink"}Action=' . $Param{Config}->{Action}
. ';Subaction=OpenSearchDescriptionTicketNumber' . $Session,
},
);
my $Fulltext = $Self->{LayoutObject}->{LanguageObject}->Get('Fulltext');
$Title = $Self->{ConfigObject}->Get('ProductName');
$Title .= ' (' . $Fulltext . ')';
$Self->{LayoutObject}->Block(
Name => 'MetaLink',
Data => {
Rel => 'search',
Type => 'application/opensearchdescription+xml',
Title => $Title,
Href => '$Env{"Baselink"}Action=' . $Param{Config}->{Action}
. ';Subaction=OpenSearchDescriptionFulltext' . $Session,
},
);
return 1;
}
1;
| djoudi/otrs-gitimport-test | Kernel/Output/HTML/HeaderMetaTicketSearch.pm | Perl | agpl-3.0 | 2,136 |
{% extends "base.html" %}
{% import "projects/_helpers.html" as helper %}
{% import "account/_helpers.html" as account_helper %}
{% block content %}
<div class="banner">
<div class="container">
<div class="row">
<div class="col-md-4">
<h1>{{ brand }}</h1>
{% include ['custom/front_page_text.html', 'home/_pybossa_text.html'] ignore missing %}
</div>
<div class="col-md-8">
<div class="row">
{% for f in categories_projects['featured'] %}
<div class="col-xs-4 col-sm-2">
<a href="{{ url_for('project.details', short_name=f.short_name)}}">
{{ helper.render_project_thumbnail(f, upload_method) }}
<h3>{{f.name}}</h3>
<span class="label label-info">{{ _('Info') }}</span>
</a>
</div>
{% endfor %}
{% for number in range(18 - categories_projects['featured']|count) %}
<div class="col-xs-4 col-sm-2">
<div class="featured"></div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid grey">
<section class="get-started container">
<div class="row">
<div class="col-md-4">
<h2><i class="glyphicon glyphicon-play-circle"></i> {{ _('Get Started') }}</h2>
<p>{{ _('It\'s really simple to start contributing.') }}</p>
</div>
<div class="col-md-8">
<div class="row">
<div class="col-sm-6">
<div class="get-started-call">
<a href="{{url_for('project.index')}}" class="btn btn-info btn-lg btn-block"><i class="glyphicon glyphicon-ok-sign"></i>{{ _(' Start Contributing') }}</a>
</div>
</div>
<div class="col-sm-6">
<div class="get-started-call">
<a href="{{url_for('project.new')}}" class="btn btn-primary btn-lg btn-block"><i class="glyphicon glyphicon-plus-sign"></i> {{ _('Create a Project') }}</a>
</div>
</div>
</div>
</div>
</section>
</div>
<section class="container">
<h2><i class="glyphicon glyphicon-th"></i> {{ _('Most Active Projects') }}</h2>
<div class="row">
{% for project in top_projects %}
<div class="col-xs-6 col-sm-3">
<div class="text-center">
{% if project.info.thumbnail %}
<a href="{{url_for('project.details', short_name=project.short_name)}}" class="image" style="background-image:url({{helper.render_url_thumbnail(project, upload_method)}})"></a>
{% else %}
<a href="{{url_for('project.details', short_name=project.short_name)}}" class="image" style="background-image:url({{url_for('static',filename='img/placeholder.project.png')}})"></a>
{% endif %}
<h3>{{project.name | truncate(20, true)}}</h3>
<p>{{project.description | truncate(32, true)}}</p>
<p><a href="{{url_for('project.details',short_name=project.short_name)}}" class="btn btn-xs btn-info">Info</a> <a href="{{url_for('project.presenter',short_name=project.short_name)}}" class="btn btn-xs btn-primary">{{ _('Start') }}</a></p>
</div>
</div>
{% endfor %}
{% for i in range(4-top_projects|count)%}
<div class="col-xs-6 col-md-3">
<div class="text-center">
<a href="#" class="image" style="background-image:url({{url_for('static',filename='img/placeholder.project.png')}})"></a>
<h3>{{ _('Your project') }}</h3>
<p>{{ _('could be here!') }}</p>
<p><a href="{{url_for('project.new')}}" class="btn btn-xs btn-primary">{{ _('Create a project') }}</a></p>
</div>
</div>
{% endfor %}
</div>
</section>
{% if top_users %}
<div class="container-fluid grey">
<section id="top_users" class="container">
<h2><i class="glyphicon glyphicon-user"></i>{{ _('Most Active Volunteers') }}</h2>
<div class="row">
{% for user in top_users %}
<div class="col-xs-4 col-sm-4 col-md-3 col-lg-2">
<a href="{{url_for('account.profile', name=user.name)}}" data-content="
<strong>{{_('Joined')}}:</strong> {{user.created[0:10]}}
<br/>
<strong>{{_('Submitted Tasks')}}:</strong> {{user.task_runs}}
" rel="popover" data-original-title="<strong>{{user.fullname}}</strong>">
{{ account_helper.render_user_thumbnail(user, upload_method, style="width:100%;") }}
</a>
<p class="text-center"><span class="label label-success">{{user.score}}</span> <small>{{_('Tasks')}}</small></p>
</div>
{% endfor %}
</div>
</section>
</div>
{% endif %}
<script>
$("a[rel=popover]").popover({
html: true,
animation: true,
trigger: 'hover',
placement: 'top'
});
</script>
{{ helper.broken_image() }}
{% endblock %}
| jeffersonrpn/pybossa-contribua-theme | templates/home/index.html | HTML | agpl-3.0 | 5,494 |
<%! from django.utils.translation import ugettext as _ %>
<%! from django.core.urlresolvers import reverse %>
<%inherit file="../main.html" />
<%namespace name='static' file='/static_content.html'/>
<%block name="bodyclass">register verification-process step-photos</%block>
<%block name="title"><title>${_("Register for {} | Verification").format(course_name)}</title></%block>
<%block name="js_extra">
<script src="${static.url('js/vendor/responsive-carousel/responsive-carousel.js')}"></script>
<script src="${static.url('js/vendor/responsive-carousel/responsive-carousel.keybd.js')}"></script>
<script src="${static.url('js/verify_student/photocapture.js')}"></script>
</%block>
<%block name="content">
<div class="container">
<section class="wrapper">
<%include file="_verification_header.html" args="course_name=course_name" />
<div class="wrapper-progress">
<section class="progress">
<h3 class="sr title">${_("Your Progress")}</h3>
<!-- FIXME: Move the "Current Step: " text to the right DOM element -->
<ol class="progress-steps">
<li class="progress-step is-completed" id="progress-step0">
<span class="wrapper-step-number"><span class="step-number">0</span></span>
<span class="step-name">${_("Intro")}</span>
</li>
<li class="progress-step is-current" id="progress-step1">
<span class="wrapper-step-number"><span class="step-number">1</span></span>
<span class="step-name"><span class="sr">${_("Current Step: ")}</span>${_("Take Photo")}</span>
</li>
<li class="progress-step" id="progress-step2">
<span class="wrapper-step-number"><span class="step-number">2</span></span>
<span class="step-name">${_("Take ID Photo")}</span>
</li>
<li class="progress-step" id="progress-step3">
<span class="wrapper-step-number"><span class="step-number">3</span></span>
<span class="step-name">${_("Review")}</span>
</li>
<li class="progress-step" id="progress-step4">
<span class="wrapper-step-number"><span class="step-number">4</span></span>
<span class="step-name">${_("Make Payment")}</span>
</li>
<li class="progress-step progress-step-icon" id="progress-step5">
<span class="wrapper-step-number"><span class="step-number">
<i class="icon-ok"></i>
</span></span>
<span class="step-name">${_("Confirmation")}</span>
</li>
</ol>
<span class="progress-sts">
<span class="progress-sts-value"></span>
</span>
</section>
</div>
<div class="wrapper-content-main">
<article class="content-main">
<section class="wrapper carousel" data-transition="slide">
<div id="wrapper-facephoto" class="wrapper-view block-photo">
<div class="facephoto view">
<h3 class="title">${_("Take Your Photo")}</h3>
<div class="instruction">
<p>${_("Use your webcam to take a picture of your face so we can match it with the picture on your ID.")}</p>
</div>
<div class="wrapper-task">
<div id="facecam" class="task cam">
<div class="placeholder-cam" id="face_capture_div">
<div class="placeholder-art">
<p class="copy">${_("Don't see your picture? Make sure to allow your browser to use your camera when it asks for permission. <br />Still not working? You can {a_start} audit the course {a_end} without verifying.").format(a_start='<a rel="external" href="/course_modes/choose/' + course_id + '">', a_end="</a>")}</p>
</div>
<video id="face_video" autoplay></video><br/>
<canvas id="face_canvas" style="display:none;" width="640" height="480"></canvas>
</div>
<div class="controls photo-controls">
<ul class="list-controls">
<li class="control control-redo" id="face_reset_button">
<a class="action action-redo" href="">
<i class="icon-undo"></i> <span class="sr">${_("Retake")}</span>
</a>
</li>
<li class="control control-do" id="face_capture_button">
<a class="action action-do" href="">
<i class="icon-camera"></i><span class="sr">${_("Take photo")}</span>
</a>
</li>
<li class="control control-approve" id="face_approve_button">
<a class="action action-approve" href="">
<i class="icon-ok"></i> <span class="sr">${_("Looks good")}</span>
</a>
</li>
</ul>
</div>
</div>
<div class="wrapper-help">
<div class="help help-task photo-tips facetips">
<h4 class="title">${_("Tips on taking a successful photo")}</h4>
<div class="copy">
<ul class="list-help">
<li class="help-item">${_("Make sure your face is well-lit")}</li>
<li class="help-item">${_("Be sure your entire face is inside the frame")}</li>
<li class="help-item">${_("Can we match the photo you took with the one on your ID?")}</li>
<li class="help-item">${_("Click the checkmark once you are happy with the photo")}</li>
</ul>
</div>
</div>
<div class="help help-faq facefaq">
<h4 class="sr title">${_("Common Questions")}</h4>
<div class="copy">
<dl class="list-faq">
<dt class="faq-question">${_("Why do you need my photo?")}</dt>
<dd class="faq-answer">${_("As part of the verification process, we need your photo to confirm that you are you.")}</dd>
<dt class="faq-question">${_("What do you do with this picture?")}</dt>
<dd class="faq-answer">${_("We only use it to verify your identity. It is not displayed anywhere.")}</dd>
</dl>
</div>
</div>
</div>
</div>
<nav class="nav-wizard"> <!-- FIXME: Additional class is-ready, is-not-ready -->
<span class="help help-inline">${_("Once you verify your photo looks good, you can move on to step 2.")}</span>
<ol class="wizard-steps">
<li class="wizard-step">
<a class="next action-primary" id="face_next_button" href="#next" aria-hidden="true" title="Next">${_("Go to Step 2: Take ID Photo")}</a>
</li>
</ol>
</nav>
</div> <!-- /view -->
</div> <!-- /wrapper-view -->
<div id="wrapper-idphoto" class="wrapper-view block-photo">
<div class="idphoto view">
<h3 class="title">${_("Show Us Your ID")}</h3>
<div class="instruction">
<p>${_("Use your webcam to take a picture of your ID so we can match it with your photo and the name on your account.")}</p>
</div>
<div class="wrapper-task">
<div id="idcam" class="task cam">
<div class="placeholder-cam" id="photo_id_capture_div">
<div class="placeholder-art">
<p class="copy">${_("Don't see your picture? Make sure to allow your browser to use your camera when it asks for permission. Still not working? You can {a_start} audit the course {a_end} without verifying.").format(a_start='<a rel="external" href="/course_modes/choose/' + course_id + '">', a_end="</a>")}</p>
</div>
<video id="photo_id_video" autoplay></video><br/>
<canvas id="photo_id_canvas" style="display:none;" width="640" height="480"></canvas>
</div>
<div class="controls photo-controls">
<ul class="list-controls">
<li class="control control-redo" id="photo_id_reset_button">
<a class="action action-redo" href="">
<i class="icon-undo"></i> <span class="sr">${_("Retake")}</span>
</a>
</li>
<li class="control control-do" id="photo_id_capture_button">
<a class="action action-do" href="">
<i class="icon-camera"></i> <span class="sr">${_("Take photo")}</span>
</a>
</li>
<li class="control control-approve" id="photo_id_approve_button">
<a class="action action-approve" href="">
<i class="icon-ok"></i> <span class="sr">${_("Looks good")}</span>
</a>
</li>
</ul>
</div>
</div>
<div class="wrapper-help">
<div class="help help-task photo-tips idtips">
<h4 class="title">${_("Tips on taking a successful photo")}</h4>
<div class="copy">
<ul class="list-help">
<li class="help-item">${_("Make sure your ID is well-lit")}</li>
<li class="help-item">${_("Check that there isn't any glare")}</li>
<li class="help-item">${_("Ensure that you can see your photo and read your name")}</li>
<li class="help-item">${_("Try to keep your fingers at the edge to avoid covering important information")}</li>
<li class="help-item">${_("Acceptable IDs include drivers licenses, passports, or other goverment-issued IDs that include your name and photo")}</li>
<li class="help-item">${_("Click the checkmark once you are happy with the photo")}</li>
</ul>
</div>
</div>
<div class="help help-faq facefaq">
<h4 class="sr title">${_("Common Questions")}</h4>
<div class="copy">
<dl class="list-faq">
<dt class="faq-question">${_("Why do you need a photo of my ID?")}</dt>
<dd class="faq-answer">${_("We need to match your ID with your photo and name to confirm that you are you.")}</dd>
<dt class="faq-question">${_("What do you do with this picture?")}</dt>
<dd class="faq-answer">${_("We encrypt it and send it to our secure authorization service for review. We use the highest levels of security and do not save the photo or information anywhere once the match has been completed.")}</dd>
</dl>
</div>
</div>
</div>
</div>
<nav class="nav-wizard">
<span class="help help-inline">${_("Once you verify your ID photo looks good, you can move on to step 3.")}</span>
<ol class="wizard-steps">
<li class="wizard-step">
<a class="next action-primary" id="photo_id_next_button" href="#next" aria-hidden="true" title="Next">${_("Go to Step 3: Review Your Info")}</a>
</li>
</ol>
</nav>
</div> <!-- /view -->
</div> <!-- /wrapper-view -->
<div id="wrapper-review" class="wrapper-view">
<div class="review view">
<h3 class="title">${_("Verify Your Submission")}</h3>
<div class="instruction">
<p>${_("Make sure we can verify your identity with the photos and information below.")}</p>
</div>
<div class="wrapper-task">
<ol class="review-tasks">
<li class="review-task review-task-name">
<h4 class="title">${_("Check Your Name")}</h4>
<div class="copy">
<p>${_("Make sure your full name on your edX account ({full_name}) matches your ID. We will also use this as the name on your certificate.").format(full_name="<span id='full-name'>" + user_full_name + "</span>")}</p>
</div>
<ul class="list-actions">
<li class="action action-editname">
<a class="edit-name" rel="leanModal" href="#edit-name">${_("Edit your name")}</a>
</li>
</ul>
</li>
<li class="review-task review-task-photos">
<h4 class="title">${_("Review the Photos You've Taken")}</h4>
<div class="copy">
<p>${_("Please review the photos and verify that they meet the requirements listed below.")}</p>
</div>
<ol class="wrapper-photos">
<li class="wrapper-photo">
<div class="placeholder-photo">
<img id="face_image" src=""/>
</div>
<div class="help-tips">
<h5 class="title">${_("The photo above needs to meet the following requirements:")}</h5>
<ul class="list-help list-tips copy">
<li class="tip">${_("Be well lit")}</li>
<li class="tip">${_("Show your whole face")}</li>
<li class="tip">${_("The photo on your ID must match the photo of your face")}</li>
</ul>
</div>
</li>
<li class="wrapper-photo">
<div class="placeholder-photo">
<img id="photo_id_image" src=""/>
</div>
<div class="help-tips">
<h5 class="title">${_("The photo above needs to meet the following requirements:")}</h5>
<ul class="list-help list-tips copy">
<li class="tip">${_("Be readable (not too far away, no glare)")}</li>
<li class="tip">${_("The photo on your ID must match the photo of your face")}</li>
<li class="tip">${_("The name on your ID must match the name on your account above")}</li>
</ul>
</div>
</li>
</ol>
<div class="msg msg-retake msg-followup">
<div class="copy">
<p>${_("Photos don't meet the requirements?")}</p>
</div>
<ul class="list-actions">
<li class="action action-retakephotos">
<a class="retake-photos" href="javascript:void(0);" onclick="document.location.reload(true);">${_("Retake Your Photos")}</a>
</li>
</ul>
</div>
</li>
<li class="review-task review-task-contribution">
<h4 class="title">${_("Check Your Contribution Level")}</h4>
<div class="copy">
<p>${_("Please confirm your contribution for this course (min. $")} ${min_price} <span class="denomination-name">${currency}</span>${_("):")}</p>
</div>
<%include file="/course_modes/_contribution.html" args="suggested_prices=suggested_prices, currency=currency, chosen_price=chosen_price, min_price=min_price"/>
</li>
</ol>
</div>
<nav class="nav-wizard">
<span class="help help-inline">${_("Once you verify your details match the requirements, you can move on to step 4, payment on our secure server.")}</span>
<ol class="wizard-steps">
<li class="wizard-step step-match">
<input type="checkbox" name="match" id="confirm_pics_good" />
<label for="confirm_pics_good">${_("Yes! My details all match.")}</label>
</li>
<li class="wizard-step step-proceed">
<form id="pay_form" method="post" action="${purchase_endpoint}">
<input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }">
<input type="hidden" name="course_id" value="${course_id | h}" />
<input class="action-primary disabled" type="button" id="pay_button" value="Go to Step 4: Secure Payment" name="payment">
</form>
</li>
</ol>
</nav>
</div> <!-- /view -->
</div> <!-- /wrapper-view -->
</section>
</article>
</div> <!-- /wrapper-content-main -->
<%include file="_verification_support.html" />
</section>
</div>
<%include file="_modal_editname.html" />
</%block>
| praveen-pal/edx-platform | lms/templates/verify_student/photo_verification.html | HTML | agpl-3.0 | 17,751 |
namespace Kcsara.Database.Api
{
using System.Web.Http.Filters;
using log4net;
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
LogManager.GetLogger("Kcsara.Database.Api").Error(context.Request.RequestUri.AbsoluteUri, context.Exception);
base.OnException(context);
}
}
}
| mcosand/KCSARA-Database | src/website-api/ExceptionFilter.cs | C# | agpl-3.0 | 401 |
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2013 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2013. All rights reserved".
********************************************************************************/
class WorkflowTriggersUtilBaseTest extends WorkflowBaseTest
{
public $freeze = false;
public function setup()
{
parent::setUp();
$freeze = false;
if (RedBeanDatabase::isFrozen())
{
RedBeanDatabase::unfreeze();
$freeze = true;
}
$this->freeze = $freeze;
}
public function teardown()
{
if ($this->freeze)
{
RedBeanDatabase::freeze();
}
parent::teardown();
}
public static function makeOnSaveWorkflowAndTriggerWithoutValueType($attributeIndexOrDerivedType, $operator,
$value,
$moduleClassName = 'WorkflowsTestModule',
$modelClassName = 'WorkflowModelTestItem',
$secondValue = null)
{
assert('is_string($attributeIndexOrDerivedType)'); // Not Coding Standard
assert('is_string($operator)'); // Not Coding Standard
assert('is_string($moduleClassName)'); // Not Coding Standard
assert('is_string($modelClassName)'); // Not Coding Standard
$workflow = new Workflow();
$workflow->setType(Workflow::TYPE_ON_SAVE);
$workflow->setTriggersStructure('1');
$trigger = new TriggerForWorkflowForm($moduleClassName, $modelClassName, $workflow->getType());
$trigger->attributeIndexOrDerivedType = $attributeIndexOrDerivedType;
$trigger->value = $value;
$trigger->secondValue = $secondValue;
$trigger->operator = $operator;
$workflow->addTrigger($trigger);
return $workflow;
}
public static function makeOnSaveWorkflowAndTimeTriggerWithoutValueType($attributeIndexOrDerivedType, $operator,
$value,
$durationSeconds = 0,
$moduleClassName = 'WorkflowsTestModule',
$modelClassName = 'WorkflowModelTestItem',
$secondValue = null)
{
assert('is_string($attributeIndexOrDerivedType)'); // Not Coding Standard
assert('is_string($operator)'); // Not Coding Standard
assert('is_int($durationSeconds)'); // Not Coding Standard
assert('is_string($moduleClassName)'); // Not Coding Standard
assert('is_string($modelClassName)'); // Not Coding Standard
$workflow = new Workflow();
$workflow->setType(Workflow::TYPE_BY_TIME);
$workflow->setTriggersStructure('1');
$trigger = new TimeTriggerForWorkflowForm($moduleClassName, $modelClassName, $workflow->getType());
$trigger->attributeIndexOrDerivedType = $attributeIndexOrDerivedType;
$trigger->value = $value;
$trigger->secondValue = $secondValue;
$trigger->operator = $operator;
$trigger->durationSeconds = $durationSeconds;
$workflow->setTimeTrigger($trigger);
return $workflow;
}
public static function makeOnSaveWorkflowAndTriggerForDateOrDateTime($attributeIndexOrDerivedType, $valueType,
$value,
$moduleClassName = 'WorkflowsTestModule',
$modelClassName = 'WorkflowModelTestItem',
$secondValue = null)
{
assert('is_string($attributeIndexOrDerivedType)'); // Not Coding Standard
assert('is_string($valueType)'); // Not Coding Standard
assert('is_string($moduleClassName)'); // Not Coding Standard
assert('is_string($modelClassName)'); // Not Coding Standard
$workflow = new Workflow();
$workflow->setType(Workflow::TYPE_ON_SAVE);
$workflow->setTriggersStructure('1');
$trigger = new TriggerForWorkflowForm($moduleClassName, $modelClassName, $workflow->getType());
$trigger->attributeIndexOrDerivedType = $attributeIndexOrDerivedType;
$trigger->valueType = $valueType;
$trigger->value = $value;
$trigger->secondValue = $secondValue;
$workflow->addTrigger($trigger);
return $workflow;
}
public static function makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime($attributeIndexOrDerivedType, $valueType,
$value,
$durationSeconds = 0,
$moduleClassName = 'WorkflowsTestModule',
$modelClassName = 'WorkflowModelTestItem',
$secondValue = null)
{
assert('is_string($attributeIndexOrDerivedType)'); // Not Coding Standard
assert('is_string($valueType)'); // Not Coding Standard
assert('is_int($durationSeconds)'); // Not Coding Standard
assert('is_string($moduleClassName)'); // Not Coding Standard
assert('is_string($modelClassName)'); // Not Coding Standard
$workflow = new Workflow();
$workflow->setType(Workflow::TYPE_BY_TIME);
$workflow->setTriggersStructure('1');
$trigger = new TimeTriggerForWorkflowForm($moduleClassName, $modelClassName, $workflow->getType());
$trigger->attributeIndexOrDerivedType = $attributeIndexOrDerivedType;
$trigger->valueType = $valueType;
$trigger->value = $value;
$trigger->secondValue = $secondValue;
$trigger->durationSeconds = $durationSeconds;
$workflow->setTimeTrigger($trigger);
return $workflow;
}
public static function saveAndReloadModel(RedBeanModel $model)
{
$saved = $model->save();
if (!$saved)
{
throw new FailedToSaveModelException();
}
$modelId = $model->id;
$modelClassName = get_class($model);
$model->forget();
unset($model);
return $modelClassName::getById($modelId);
}
}
?> | sandeep1027/zurmo_ | app/protected/modules/workflows/tests/unit/WorkflowTriggersUtilBaseTest.php | PHP | agpl-3.0 | 9,793 |
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
knife_donkuwah = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/weapon/melee/knife/knife_donkuwah.iff",
craftingValues = {
{"mindamage",14,26,0},
{"maxdamage",32,62,0},
{"attackspeed",3.9,2.7,1},
{"woundchance",6,12,0},
{"hitpoints",750,1500,0},
{"zerorangemod",17,33,0},
{"maxrangemod",17,33,0},
{"midrange",3,3,0},
{"midrangemod",17,33,0},
{"maxrange",7,7,0},
{"attackhealthcost",8,4,0},
{"attackactioncost",38,20,0},
{"attackmindcost",8,4,0},
},
customizationStringNames = {},
customizationValues = {},
-- randomDotChance: The chance of this weapon object dropping with a random dot on it. Higher number means less chance. Set to 0 to always have a random dot.
randomDotChance = 600,
-- staticDotChance: The chance of this weapon object dropping with a static dot on it. Higher number means less chance. Set to 0 to always have a static dot.
staticDotChance = 0,
-- staticDotType: 1 = Poison, 2 = Disease, 3 = Fire, 4 = Bleed
staticDotType = 1,
-- staticDotValues: Object map that can randomly or statically generate a dot (used for weapon objects.)
staticDotValues = {
{"attribute", 3, 3}, -- See CreatureAttributes.h in src for numbers.
{"strength", 70, 70},
{"duration", 120, 120},
{"potency", 60, 60},
{"uses", 500, 500}
},
junkDealerTypeNeeded = JUNKWEAPONS,
junkMinValue = 20,
junkMaxValue = 60
}
addLootItemTemplate("knife_donkuwah", knife_donkuwah)
| Tatwi/legend-of-hondo | MMOCoreORB/bin/scripts/loot/items/weapon/knife_donkuwah.lua | Lua | agpl-3.0 | 1,535 |
<!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" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jqCouch :: Tests</title>
<link rel="stylesheet" type="text/css" href="css/testsuite.css" />
<script type="text/javascript" src="js/jquery-1.2.1.js"></script>
<script type="text/javascript" src="js/testrunner.js"></script>
<script type="text/javascript" src="../jqcouch.src.js"></script>
<script type="text/javascript" src="tests/jqcouch.js"></script>
</head>
<body id="body">
<h2 id="userAgent"></h2>
<h1>jqCouch testsuite</h1>
<div id="main" style="display: none;">
</div>
<ol id="tests"></ol>
</body>
<script type="text/javascript">
runTest();
</script>
</html> | thepug/Speeqe | speeqeweb/webroot/scripts/jqcouch/testsuite/main.html | HTML | agpl-3.0 | 900 |
<?php
/**
* Base class that represents a row from the 'log' table.
*
*
*
* @package propel.generator.atica.om
*/
abstract class BaseLog extends BaseObject implements Persistent
{
/**
* Peer class name
*/
const PEER = 'LogPeer';
/**
* The Peer class.
* Instance provides a convenient way of calling static methods on a class
* that calling code may not be able to identify.
* @var LogPeer
*/
protected static $peer;
/**
* The flag var to prevent infinit loop in deep copy
* @var boolean
*/
protected $startCopy = false;
/**
* The value for the id field.
* @var int
*/
protected $id;
/**
* The value for the ip field.
* @var string
*/
protected $ip;
/**
* The value for the when field.
* @var string
*/
protected $when;
/**
* The value for the person_id field.
* @var int
*/
protected $person_id;
/**
* The value for the organization_id field.
* @var int
*/
protected $organization_id;
/**
* The value for the category_id field.
* @var int
*/
protected $category_id;
/**
* The value for the grouping_id field.
* @var int
*/
protected $grouping_id;
/**
* The value for the activity_id field.
* @var int
*/
protected $activity_id;
/**
* The value for the event_id field.
* @var int
*/
protected $event_id;
/**
* The value for the folder_id field.
* @var int
*/
protected $folder_id;
/**
* The value for the delivery_id field.
* @var int
*/
protected $delivery_id;
/**
* The value for the revision_id field.
* @var int
*/
protected $revision_id;
/**
* The value for the document_id field.
* @var int
*/
protected $document_id;
/**
* The value for the kind field.
* @var string
*/
protected $kind;
/**
* The value for the detail field.
* @var string
*/
protected $detail;
/**
* Flag to prevent endless save loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInSave = false;
/**
* Flag to prevent endless validation loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInValidation = false;
/**
* Get the [id] column value.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Get the [ip] column value.
*
* @return string
*/
public function getIp()
{
return $this->ip;
}
/**
* Get the [optionally formatted] temporal [when] column value.
*
*
* @param string $format The date/time format string (either date()-style or strftime()-style).
* If format is null, then the raw DateTime object will be returned.
* @return mixed Formatted date/time value as string or DateTime object (if format is null), null if column is null, and 0 if column value is 0000-00-00 00:00:00
* @throws PropelException - if unable to parse/validate the date/time value.
*/
public function getWhen($format = 'Y-m-d H:i:s')
{
if ($this->when === null) {
return null;
}
if ($this->when === '0000-00-00 00:00:00') {
// while technically this is not a default value of null,
// this seems to be closest in meaning.
return null;
} else {
try {
$dt = new DateTime($this->when);
} catch (Exception $x) {
throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->when, true), $x);
}
}
if ($format === null) {
// Because propel.useDateTimeClass is true, we return a DateTime object.
return $dt;
} elseif (strpos($format, '%') !== false) {
return strftime($format, $dt->format('U'));
} else {
return $dt->format($format);
}
}
/**
* Get the [person_id] column value.
*
* @return int
*/
public function getPersonId()
{
return $this->person_id;
}
/**
* Get the [organization_id] column value.
*
* @return int
*/
public function getOrganizationId()
{
return $this->organization_id;
}
/**
* Get the [category_id] column value.
*
* @return int
*/
public function getCategoryId()
{
return $this->category_id;
}
/**
* Get the [grouping_id] column value.
*
* @return int
*/
public function getGroupingId()
{
return $this->grouping_id;
}
/**
* Get the [activity_id] column value.
*
* @return int
*/
public function getActivityId()
{
return $this->activity_id;
}
/**
* Get the [event_id] column value.
*
* @return int
*/
public function getEventId()
{
return $this->event_id;
}
/**
* Get the [folder_id] column value.
*
* @return int
*/
public function getFolderId()
{
return $this->folder_id;
}
/**
* Get the [delivery_id] column value.
*
* @return int
*/
public function getDeliveryId()
{
return $this->delivery_id;
}
/**
* Get the [revision_id] column value.
*
* @return int
*/
public function getRevisionId()
{
return $this->revision_id;
}
/**
* Get the [document_id] column value.
*
* @return int
*/
public function getDocumentId()
{
return $this->document_id;
}
/**
* Get the [kind] column value.
*
* @return string
*/
public function getKind()
{
return $this->kind;
}
/**
* Get the [detail] column value.
*
* @return string
*/
public function getDetail()
{
return $this->detail;
}
/**
* Set the value of [id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->id !== $v) {
$this->id = $v;
$this->modifiedColumns[] = LogPeer::ID;
}
return $this;
} // setId()
/**
* Set the value of [ip] column.
*
* @param string $v new value
* @return Log The current object (for fluent API support)
*/
public function setIp($v)
{
if ($v !== null) {
$v = (string) $v;
}
if ($this->ip !== $v) {
$this->ip = $v;
$this->modifiedColumns[] = LogPeer::IP;
}
return $this;
} // setIp()
/**
* Sets the value of [when] column to a normalized version of the date/time value specified.
*
* @param mixed $v string, integer (timestamp), or DateTime value.
* Empty strings are treated as null.
* @return Log The current object (for fluent API support)
*/
public function setWhen($v)
{
$dt = PropelDateTime::newInstance($v, null, 'DateTime');
if ($this->when !== null || $dt !== null) {
$currentDateAsString = ($this->when !== null && $tmpDt = new DateTime($this->when)) ? $tmpDt->format('Y-m-d H:i:s') : null;
$newDateAsString = $dt ? $dt->format('Y-m-d H:i:s') : null;
if ($currentDateAsString !== $newDateAsString) {
$this->when = $newDateAsString;
$this->modifiedColumns[] = LogPeer::WHEN;
}
} // if either are not null
return $this;
} // setWhen()
/**
* Set the value of [person_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setPersonId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->person_id !== $v) {
$this->person_id = $v;
$this->modifiedColumns[] = LogPeer::PERSON_ID;
}
return $this;
} // setPersonId()
/**
* Set the value of [organization_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setOrganizationId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->organization_id !== $v) {
$this->organization_id = $v;
$this->modifiedColumns[] = LogPeer::ORGANIZATION_ID;
}
return $this;
} // setOrganizationId()
/**
* Set the value of [category_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setCategoryId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->category_id !== $v) {
$this->category_id = $v;
$this->modifiedColumns[] = LogPeer::CATEGORY_ID;
}
return $this;
} // setCategoryId()
/**
* Set the value of [grouping_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setGroupingId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->grouping_id !== $v) {
$this->grouping_id = $v;
$this->modifiedColumns[] = LogPeer::GROUPING_ID;
}
return $this;
} // setGroupingId()
/**
* Set the value of [activity_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setActivityId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->activity_id !== $v) {
$this->activity_id = $v;
$this->modifiedColumns[] = LogPeer::ACTIVITY_ID;
}
return $this;
} // setActivityId()
/**
* Set the value of [event_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setEventId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->event_id !== $v) {
$this->event_id = $v;
$this->modifiedColumns[] = LogPeer::EVENT_ID;
}
return $this;
} // setEventId()
/**
* Set the value of [folder_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setFolderId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->folder_id !== $v) {
$this->folder_id = $v;
$this->modifiedColumns[] = LogPeer::FOLDER_ID;
}
return $this;
} // setFolderId()
/**
* Set the value of [delivery_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setDeliveryId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->delivery_id !== $v) {
$this->delivery_id = $v;
$this->modifiedColumns[] = LogPeer::DELIVERY_ID;
}
return $this;
} // setDeliveryId()
/**
* Set the value of [revision_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setRevisionId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->revision_id !== $v) {
$this->revision_id = $v;
$this->modifiedColumns[] = LogPeer::REVISION_ID;
}
return $this;
} // setRevisionId()
/**
* Set the value of [document_id] column.
*
* @param int $v new value
* @return Log The current object (for fluent API support)
*/
public function setDocumentId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->document_id !== $v) {
$this->document_id = $v;
$this->modifiedColumns[] = LogPeer::DOCUMENT_ID;
}
return $this;
} // setDocumentId()
/**
* Set the value of [kind] column.
*
* @param string $v new value
* @return Log The current object (for fluent API support)
*/
public function setKind($v)
{
if ($v !== null) {
$v = (string) $v;
}
if ($this->kind !== $v) {
$this->kind = $v;
$this->modifiedColumns[] = LogPeer::KIND;
}
return $this;
} // setKind()
/**
* Set the value of [detail] column.
*
* @param string $v new value
* @return Log The current object (for fluent API support)
*/
public function setDetail($v)
{
if ($v !== null) {
$v = (string) $v;
}
if ($this->detail !== $v) {
$this->detail = $v;
$this->modifiedColumns[] = LogPeer::DETAIL;
}
return $this;
} // setDetail()
/**
* Indicates whether the columns in this object are only set to default values.
*
* This method can be used in conjunction with isModified() to indicate whether an object is both
* modified _and_ has some values set which are non-default.
*
* @return boolean Whether the columns in this object are only been set with default values.
*/
public function hasOnlyDefaultValues()
{
// otherwise, everything was equal, so return true
return true;
} // hasOnlyDefaultValues()
/**
* Hydrates (populates) the object variables with values from the database resultset.
*
* An offset (0-based "start column") is specified so that objects can be hydrated
* with a subset of the columns in the resultset rows. This is needed, for example,
* for results of JOIN queries where the resultset row includes columns from two or
* more tables.
*
* @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM)
* @param int $startcol 0-based offset column which indicates which restultset column to start with.
* @param boolean $rehydrate Whether this object is being re-hydrated from the database.
* @return int next starting column
* @throws PropelException - Any caught Exception will be rewrapped as a PropelException.
*/
public function hydrate($row, $startcol = 0, $rehydrate = false)
{
try {
$this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null;
$this->ip = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null;
$this->when = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null;
$this->person_id = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null;
$this->organization_id = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null;
$this->category_id = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null;
$this->grouping_id = ($row[$startcol + 6] !== null) ? (int) $row[$startcol + 6] : null;
$this->activity_id = ($row[$startcol + 7] !== null) ? (int) $row[$startcol + 7] : null;
$this->event_id = ($row[$startcol + 8] !== null) ? (int) $row[$startcol + 8] : null;
$this->folder_id = ($row[$startcol + 9] !== null) ? (int) $row[$startcol + 9] : null;
$this->delivery_id = ($row[$startcol + 10] !== null) ? (int) $row[$startcol + 10] : null;
$this->revision_id = ($row[$startcol + 11] !== null) ? (int) $row[$startcol + 11] : null;
$this->document_id = ($row[$startcol + 12] !== null) ? (int) $row[$startcol + 12] : null;
$this->kind = ($row[$startcol + 13] !== null) ? (string) $row[$startcol + 13] : null;
$this->detail = ($row[$startcol + 14] !== null) ? (string) $row[$startcol + 14] : null;
$this->resetModified();
$this->setNew(false);
if ($rehydrate) {
$this->ensureConsistency();
}
return $startcol + 15; // 15 = LogPeer::NUM_HYDRATE_COLUMNS.
} catch (Exception $e) {
throw new PropelException("Error populating Log object", $e);
}
}
/**
* Checks and repairs the internal consistency of the object.
*
* This method is executed after an already-instantiated object is re-hydrated
* from the database. It exists to check any foreign keys to make sure that
* the objects related to the current object are correct based on foreign key.
*
* You can override this method in the stub class, but you should always invoke
* the base method from the overridden method (i.e. parent::ensureConsistency()),
* in case your model changes.
*
* @throws PropelException
*/
public function ensureConsistency()
{
} // ensureConsistency
/**
* Reloads this object from datastore based on primary key and (optionally) resets all associated objects.
*
* This will only work if the object has been saved and has a valid primary key set.
*
* @param boolean $deep (optional) Whether to also de-associated any related objects.
* @param PropelPDO $con (optional) The PropelPDO connection to use.
* @return void
* @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db
*/
public function reload($deep = false, PropelPDO $con = null)
{
if ($this->isDeleted()) {
throw new PropelException("Cannot reload a deleted object.");
}
if ($this->isNew()) {
throw new PropelException("Cannot reload an unsaved object.");
}
if ($con === null) {
$con = Propel::getConnection(LogPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
// We don't need to alter the object instance pool; we're just modifying this instance
// already in the pool.
$stmt = LogPeer::doSelectStmt($this->buildPkeyCriteria(), $con);
$row = $stmt->fetch(PDO::FETCH_NUM);
$stmt->closeCursor();
if (!$row) {
throw new PropelException('Cannot find matching row in the database to reload object values.');
}
$this->hydrate($row, 0, true); // rehydrate
if ($deep) { // also de-associate any related objects?
} // if (deep)
}
/**
* Removes this object from datastore and sets delete attribute.
*
* @param PropelPDO $con
* @return void
* @throws PropelException
* @throws Exception
* @see BaseObject::setDeleted()
* @see BaseObject::isDeleted()
*/
public function delete(PropelPDO $con = null)
{
if ($this->isDeleted()) {
throw new PropelException("This object has already been deleted.");
}
if ($con === null) {
$con = Propel::getConnection(LogPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$con->beginTransaction();
try {
$deleteQuery = LogQuery::create()
->filterByPrimaryKey($this->getPrimaryKey());
$ret = $this->preDelete($con);
if ($ret) {
$deleteQuery->delete($con);
$this->postDelete($con);
$con->commit();
$this->setDeleted(true);
} else {
$con->commit();
}
} catch (Exception $e) {
$con->rollBack();
throw $e;
}
}
/**
* Persists this object to the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All modified related objects will also be persisted in the doSave()
* method. This method wraps all precipitate database operations in a
* single transaction.
*
* @param PropelPDO $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @throws Exception
* @see doSave()
*/
public function save(PropelPDO $con = null)
{
if ($this->isDeleted()) {
throw new PropelException("You cannot save an object that has been deleted.");
}
if ($con === null) {
$con = Propel::getConnection(LogPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$con->beginTransaction();
$isInsert = $this->isNew();
try {
$ret = $this->preSave($con);
if ($isInsert) {
$ret = $ret && $this->preInsert($con);
} else {
$ret = $ret && $this->preUpdate($con);
}
if ($ret) {
$affectedRows = $this->doSave($con);
if ($isInsert) {
$this->postInsert($con);
} else {
$this->postUpdate($con);
}
$this->postSave($con);
LogPeer::addInstanceToPool($this);
} else {
$affectedRows = 0;
}
$con->commit();
return $affectedRows;
} catch (Exception $e) {
$con->rollBack();
throw $e;
}
}
/**
* Performs the work of inserting or updating the row in the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All related objects are also updated in this method.
*
* @param PropelPDO $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see save()
*/
protected function doSave(PropelPDO $con)
{
$affectedRows = 0; // initialize var to track total num of affected rows
if (!$this->alreadyInSave) {
$this->alreadyInSave = true;
if ($this->isNew() || $this->isModified()) {
// persist changes
if ($this->isNew()) {
$this->doInsert($con);
} else {
$this->doUpdate($con);
}
$affectedRows += 1;
$this->resetModified();
}
$this->alreadyInSave = false;
}
return $affectedRows;
} // doSave()
/**
* Insert the row in the database.
*
* @param PropelPDO $con
*
* @throws PropelException
* @see doSave()
*/
protected function doInsert(PropelPDO $con)
{
$modifiedColumns = array();
$index = 0;
$this->modifiedColumns[] = LogPeer::ID;
if (null !== $this->id) {
throw new PropelException('Cannot insert a value for auto-increment primary key (' . LogPeer::ID . ')');
}
// check the columns in natural order for more readable SQL queries
if ($this->isColumnModified(LogPeer::ID)) {
$modifiedColumns[':p' . $index++] = '`ID`';
}
if ($this->isColumnModified(LogPeer::IP)) {
$modifiedColumns[':p' . $index++] = '`IP`';
}
if ($this->isColumnModified(LogPeer::WHEN)) {
$modifiedColumns[':p' . $index++] = '`WHEN`';
}
if ($this->isColumnModified(LogPeer::PERSON_ID)) {
$modifiedColumns[':p' . $index++] = '`PERSON_ID`';
}
if ($this->isColumnModified(LogPeer::ORGANIZATION_ID)) {
$modifiedColumns[':p' . $index++] = '`ORGANIZATION_ID`';
}
if ($this->isColumnModified(LogPeer::CATEGORY_ID)) {
$modifiedColumns[':p' . $index++] = '`CATEGORY_ID`';
}
if ($this->isColumnModified(LogPeer::GROUPING_ID)) {
$modifiedColumns[':p' . $index++] = '`GROUPING_ID`';
}
if ($this->isColumnModified(LogPeer::ACTIVITY_ID)) {
$modifiedColumns[':p' . $index++] = '`ACTIVITY_ID`';
}
if ($this->isColumnModified(LogPeer::EVENT_ID)) {
$modifiedColumns[':p' . $index++] = '`EVENT_ID`';
}
if ($this->isColumnModified(LogPeer::FOLDER_ID)) {
$modifiedColumns[':p' . $index++] = '`FOLDER_ID`';
}
if ($this->isColumnModified(LogPeer::DELIVERY_ID)) {
$modifiedColumns[':p' . $index++] = '`DELIVERY_ID`';
}
if ($this->isColumnModified(LogPeer::REVISION_ID)) {
$modifiedColumns[':p' . $index++] = '`REVISION_ID`';
}
if ($this->isColumnModified(LogPeer::DOCUMENT_ID)) {
$modifiedColumns[':p' . $index++] = '`DOCUMENT_ID`';
}
if ($this->isColumnModified(LogPeer::KIND)) {
$modifiedColumns[':p' . $index++] = '`KIND`';
}
if ($this->isColumnModified(LogPeer::DETAIL)) {
$modifiedColumns[':p' . $index++] = '`DETAIL`';
}
$sql = sprintf(
'INSERT INTO `log` (%s) VALUES (%s)',
implode(', ', $modifiedColumns),
implode(', ', array_keys($modifiedColumns))
);
try {
$stmt = $con->prepare($sql);
foreach ($modifiedColumns as $identifier => $columnName) {
switch ($columnName) {
case '`ID`':
$stmt->bindValue($identifier, $this->id, PDO::PARAM_INT);
break;
case '`IP`':
$stmt->bindValue($identifier, $this->ip, PDO::PARAM_STR);
break;
case '`WHEN`':
$stmt->bindValue($identifier, $this->when, PDO::PARAM_STR);
break;
case '`PERSON_ID`':
$stmt->bindValue($identifier, $this->person_id, PDO::PARAM_INT);
break;
case '`ORGANIZATION_ID`':
$stmt->bindValue($identifier, $this->organization_id, PDO::PARAM_INT);
break;
case '`CATEGORY_ID`':
$stmt->bindValue($identifier, $this->category_id, PDO::PARAM_INT);
break;
case '`GROUPING_ID`':
$stmt->bindValue($identifier, $this->grouping_id, PDO::PARAM_INT);
break;
case '`ACTIVITY_ID`':
$stmt->bindValue($identifier, $this->activity_id, PDO::PARAM_INT);
break;
case '`EVENT_ID`':
$stmt->bindValue($identifier, $this->event_id, PDO::PARAM_INT);
break;
case '`FOLDER_ID`':
$stmt->bindValue($identifier, $this->folder_id, PDO::PARAM_INT);
break;
case '`DELIVERY_ID`':
$stmt->bindValue($identifier, $this->delivery_id, PDO::PARAM_INT);
break;
case '`REVISION_ID`':
$stmt->bindValue($identifier, $this->revision_id, PDO::PARAM_INT);
break;
case '`DOCUMENT_ID`':
$stmt->bindValue($identifier, $this->document_id, PDO::PARAM_INT);
break;
case '`KIND`':
$stmt->bindValue($identifier, $this->kind, PDO::PARAM_STR);
break;
case '`DETAIL`':
$stmt->bindValue($identifier, $this->detail, PDO::PARAM_STR);
break;
}
}
$stmt->execute();
} catch (Exception $e) {
Propel::log($e->getMessage(), Propel::LOG_ERR);
throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), $e);
}
try {
$pk = $con->lastInsertId();
} catch (Exception $e) {
throw new PropelException('Unable to get autoincrement id.', $e);
}
$this->setId($pk);
$this->setNew(false);
}
/**
* Update the row in the database.
*
* @param PropelPDO $con
*
* @see doSave()
*/
protected function doUpdate(PropelPDO $con)
{
$selectCriteria = $this->buildPkeyCriteria();
$valuesCriteria = $this->buildCriteria();
BasePeer::doUpdate($selectCriteria, $valuesCriteria, $con);
}
/**
* Array of ValidationFailed objects.
* @var array ValidationFailed[]
*/
protected $validationFailures = array();
/**
* Gets any ValidationFailed objects that resulted from last call to validate().
*
*
* @return array ValidationFailed[]
* @see validate()
*/
public function getValidationFailures()
{
return $this->validationFailures;
}
/**
* Validates the objects modified field values and all objects related to this table.
*
* If $columns is either a column name or an array of column names
* only those columns are validated.
*
* @param mixed $columns Column name or an array of column names.
* @return boolean Whether all columns pass validation.
* @see doValidate()
* @see getValidationFailures()
*/
public function validate($columns = null)
{
$res = $this->doValidate($columns);
if ($res === true) {
$this->validationFailures = array();
return true;
} else {
$this->validationFailures = $res;
return false;
}
}
/**
* This function performs the validation work for complex object models.
*
* In addition to checking the current object, all related objects will
* also be validated. If all pass then <code>true</code> is returned; otherwise
* an aggreagated array of ValidationFailed objects will be returned.
*
* @param array $columns Array of column names to validate.
* @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise.
*/
protected function doValidate($columns = null)
{
if (!$this->alreadyInValidation) {
$this->alreadyInValidation = true;
$retval = null;
$failureMap = array();
if (($retval = LogPeer::doValidate($this, $columns)) !== true) {
$failureMap = array_merge($failureMap, $retval);
}
$this->alreadyInValidation = false;
}
return (!empty($failureMap) ? $failureMap : true);
}
/**
* Retrieves a field from the object by name passed in as a string.
*
* @param string $name name
* @param string $type The type of fieldname the $name is of:
* one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
* Defaults to BasePeer::TYPE_PHPNAME
* @return mixed Value of field.
*/
public function getByName($name, $type = BasePeer::TYPE_PHPNAME)
{
$pos = LogPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
$field = $this->getByPosition($pos);
return $field;
}
/**
* Retrieves a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @return mixed Value of field at $pos
*/
public function getByPosition($pos)
{
switch ($pos) {
case 0:
return $this->getId();
break;
case 1:
return $this->getIp();
break;
case 2:
return $this->getWhen();
break;
case 3:
return $this->getPersonId();
break;
case 4:
return $this->getOrganizationId();
break;
case 5:
return $this->getCategoryId();
break;
case 6:
return $this->getGroupingId();
break;
case 7:
return $this->getActivityId();
break;
case 8:
return $this->getEventId();
break;
case 9:
return $this->getFolderId();
break;
case 10:
return $this->getDeliveryId();
break;
case 11:
return $this->getRevisionId();
break;
case 12:
return $this->getDocumentId();
break;
case 13:
return $this->getKind();
break;
case 14:
return $this->getDetail();
break;
default:
return null;
break;
} // switch()
}
/**
* Exports the object as an array.
*
* You can specify the key type of the array by passing one of the class
* type constants.
*
* @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
* Defaults to BasePeer::TYPE_PHPNAME.
* @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to true.
* @param array $alreadyDumpedObjects List of objects to skip to avoid recursion
*
* @return array an associative array containing the field names (as keys) and field values
*/
public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array())
{
if (isset($alreadyDumpedObjects['Log'][$this->getPrimaryKey()])) {
return '*RECURSION*';
}
$alreadyDumpedObjects['Log'][$this->getPrimaryKey()] = true;
$keys = LogPeer::getFieldNames($keyType);
$result = array(
$keys[0] => $this->getId(),
$keys[1] => $this->getIp(),
$keys[2] => $this->getWhen(),
$keys[3] => $this->getPersonId(),
$keys[4] => $this->getOrganizationId(),
$keys[5] => $this->getCategoryId(),
$keys[6] => $this->getGroupingId(),
$keys[7] => $this->getActivityId(),
$keys[8] => $this->getEventId(),
$keys[9] => $this->getFolderId(),
$keys[10] => $this->getDeliveryId(),
$keys[11] => $this->getRevisionId(),
$keys[12] => $this->getDocumentId(),
$keys[13] => $this->getKind(),
$keys[14] => $this->getDetail(),
);
return $result;
}
/**
* Sets a field from the object by name passed in as a string.
*
* @param string $name peer name
* @param mixed $value field value
* @param string $type The type of fieldname the $name is of:
* one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
* Defaults to BasePeer::TYPE_PHPNAME
* @return void
*/
public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME)
{
$pos = LogPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
$this->setByPosition($pos, $value);
}
/**
* Sets a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @param mixed $value field value
* @return void
*/
public function setByPosition($pos, $value)
{
switch ($pos) {
case 0:
$this->setId($value);
break;
case 1:
$this->setIp($value);
break;
case 2:
$this->setWhen($value);
break;
case 3:
$this->setPersonId($value);
break;
case 4:
$this->setOrganizationId($value);
break;
case 5:
$this->setCategoryId($value);
break;
case 6:
$this->setGroupingId($value);
break;
case 7:
$this->setActivityId($value);
break;
case 8:
$this->setEventId($value);
break;
case 9:
$this->setFolderId($value);
break;
case 10:
$this->setDeliveryId($value);
break;
case 11:
$this->setRevisionId($value);
break;
case 12:
$this->setDocumentId($value);
break;
case 13:
$this->setKind($value);
break;
case 14:
$this->setDetail($value);
break;
} // switch()
}
/**
* Populates the object using an array.
*
* This is particularly useful when populating an object from one of the
* request arrays (e.g. $_POST). This method goes through the column
* names, checking to see whether a matching key exists in populated
* array. If so the setByName() method is called for that column.
*
* You can specify the key type of the array by additionally passing one
* of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
* The default key type is the column's BasePeer::TYPE_PHPNAME
*
* @param array $arr An array to populate the object from.
* @param string $keyType The type of keys the array uses.
* @return void
*/
public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
{
$keys = LogPeer::getFieldNames($keyType);
if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]);
if (array_key_exists($keys[1], $arr)) $this->setIp($arr[$keys[1]]);
if (array_key_exists($keys[2], $arr)) $this->setWhen($arr[$keys[2]]);
if (array_key_exists($keys[3], $arr)) $this->setPersonId($arr[$keys[3]]);
if (array_key_exists($keys[4], $arr)) $this->setOrganizationId($arr[$keys[4]]);
if (array_key_exists($keys[5], $arr)) $this->setCategoryId($arr[$keys[5]]);
if (array_key_exists($keys[6], $arr)) $this->setGroupingId($arr[$keys[6]]);
if (array_key_exists($keys[7], $arr)) $this->setActivityId($arr[$keys[7]]);
if (array_key_exists($keys[8], $arr)) $this->setEventId($arr[$keys[8]]);
if (array_key_exists($keys[9], $arr)) $this->setFolderId($arr[$keys[9]]);
if (array_key_exists($keys[10], $arr)) $this->setDeliveryId($arr[$keys[10]]);
if (array_key_exists($keys[11], $arr)) $this->setRevisionId($arr[$keys[11]]);
if (array_key_exists($keys[12], $arr)) $this->setDocumentId($arr[$keys[12]]);
if (array_key_exists($keys[13], $arr)) $this->setKind($arr[$keys[13]]);
if (array_key_exists($keys[14], $arr)) $this->setDetail($arr[$keys[14]]);
}
/**
* Build a Criteria object containing the values of all modified columns in this object.
*
* @return Criteria The Criteria object containing all modified values.
*/
public function buildCriteria()
{
$criteria = new Criteria(LogPeer::DATABASE_NAME);
if ($this->isColumnModified(LogPeer::ID)) $criteria->add(LogPeer::ID, $this->id);
if ($this->isColumnModified(LogPeer::IP)) $criteria->add(LogPeer::IP, $this->ip);
if ($this->isColumnModified(LogPeer::WHEN)) $criteria->add(LogPeer::WHEN, $this->when);
if ($this->isColumnModified(LogPeer::PERSON_ID)) $criteria->add(LogPeer::PERSON_ID, $this->person_id);
if ($this->isColumnModified(LogPeer::ORGANIZATION_ID)) $criteria->add(LogPeer::ORGANIZATION_ID, $this->organization_id);
if ($this->isColumnModified(LogPeer::CATEGORY_ID)) $criteria->add(LogPeer::CATEGORY_ID, $this->category_id);
if ($this->isColumnModified(LogPeer::GROUPING_ID)) $criteria->add(LogPeer::GROUPING_ID, $this->grouping_id);
if ($this->isColumnModified(LogPeer::ACTIVITY_ID)) $criteria->add(LogPeer::ACTIVITY_ID, $this->activity_id);
if ($this->isColumnModified(LogPeer::EVENT_ID)) $criteria->add(LogPeer::EVENT_ID, $this->event_id);
if ($this->isColumnModified(LogPeer::FOLDER_ID)) $criteria->add(LogPeer::FOLDER_ID, $this->folder_id);
if ($this->isColumnModified(LogPeer::DELIVERY_ID)) $criteria->add(LogPeer::DELIVERY_ID, $this->delivery_id);
if ($this->isColumnModified(LogPeer::REVISION_ID)) $criteria->add(LogPeer::REVISION_ID, $this->revision_id);
if ($this->isColumnModified(LogPeer::DOCUMENT_ID)) $criteria->add(LogPeer::DOCUMENT_ID, $this->document_id);
if ($this->isColumnModified(LogPeer::KIND)) $criteria->add(LogPeer::KIND, $this->kind);
if ($this->isColumnModified(LogPeer::DETAIL)) $criteria->add(LogPeer::DETAIL, $this->detail);
return $criteria;
}
/**
* Builds a Criteria object containing the primary key for this object.
*
* Unlike buildCriteria() this method includes the primary key values regardless
* of whether or not they have been modified.
*
* @return Criteria The Criteria object containing value(s) for primary key(s).
*/
public function buildPkeyCriteria()
{
$criteria = new Criteria(LogPeer::DATABASE_NAME);
$criteria->add(LogPeer::ID, $this->id);
return $criteria;
}
/**
* Returns the primary key for this object (row).
* @return int
*/
public function getPrimaryKey()
{
return $this->getId();
}
/**
* Generic method to set the primary key (id column).
*
* @param int $key Primary key.
* @return void
*/
public function setPrimaryKey($key)
{
$this->setId($key);
}
/**
* Returns true if the primary key for this object is null.
* @return boolean
*/
public function isPrimaryKeyNull()
{
return null === $this->getId();
}
/**
* Sets contents of passed object to values from current object.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param object $copyObj An object of Log (or compatible) type.
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @param boolean $makeNew Whether to reset autoincrement PKs and make the object new.
* @throws PropelException
*/
public function copyInto($copyObj, $deepCopy = false, $makeNew = true)
{
$copyObj->setIp($this->getIp());
$copyObj->setWhen($this->getWhen());
$copyObj->setPersonId($this->getPersonId());
$copyObj->setOrganizationId($this->getOrganizationId());
$copyObj->setCategoryId($this->getCategoryId());
$copyObj->setGroupingId($this->getGroupingId());
$copyObj->setActivityId($this->getActivityId());
$copyObj->setEventId($this->getEventId());
$copyObj->setFolderId($this->getFolderId());
$copyObj->setDeliveryId($this->getDeliveryId());
$copyObj->setRevisionId($this->getRevisionId());
$copyObj->setDocumentId($this->getDocumentId());
$copyObj->setKind($this->getKind());
$copyObj->setDetail($this->getDetail());
if ($makeNew) {
$copyObj->setNew(true);
$copyObj->setId(NULL); // this is a auto-increment column, so set to default value
}
}
/**
* Makes a copy of this object that will be inserted as a new row in table when saved.
* It creates a new object filling in the simple attributes, but skipping any primary
* keys that are defined for the table.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @return Log Clone of current object.
* @throws PropelException
*/
public function copy($deepCopy = false)
{
// we use get_class(), because this might be a subclass
$clazz = get_class($this);
$copyObj = new $clazz();
$this->copyInto($copyObj, $deepCopy);
return $copyObj;
}
/**
* Returns a peer instance associated with this om.
*
* Since Peer classes are not to have any instance attributes, this method returns the
* same instance for all member of this class. The method could therefore
* be static, but this would prevent one from overriding the behavior.
*
* @return LogPeer
*/
public function getPeer()
{
if (self::$peer === null) {
self::$peer = new LogPeer();
}
return self::$peer;
}
/**
* Clears the current object and sets all attributes to their default values
*/
public function clear()
{
$this->id = null;
$this->ip = null;
$this->when = null;
$this->person_id = null;
$this->organization_id = null;
$this->category_id = null;
$this->grouping_id = null;
$this->activity_id = null;
$this->event_id = null;
$this->folder_id = null;
$this->delivery_id = null;
$this->revision_id = null;
$this->document_id = null;
$this->kind = null;
$this->detail = null;
$this->alreadyInSave = false;
$this->alreadyInValidation = false;
$this->clearAllReferences();
$this->resetModified();
$this->setNew(true);
$this->setDeleted(false);
}
/**
* Resets all references to other model objects or collections of model objects.
*
* This method is a user-space workaround for PHP's inability to garbage collect
* objects with circular references (even in PHP 5.3). This is currently necessary
* when using Propel in certain daemon or large-volumne/high-memory operations.
*
* @param boolean $deep Whether to also clear the references on all referrer objects.
*/
public function clearAllReferences($deep = false)
{
if ($deep) {
} // if ($deep)
}
/**
* return the string representation of this object
*
* @return string The value of the 'detail' column
*/
public function __toString()
{
return (string) $this->getDetail();
}
/**
* return true is the object is in saving state
*
* @return boolean
*/
public function isAlreadyInSave()
{
return $this->alreadyInSave;
}
}
| iesoretania/atica.old | server/build/classes/atica/om/BaseLog.php | PHP | agpl-3.0 | 48,207 |
<?php
/* Project: EQdkp-Plus
* Package: EQdkp-plus
* Link: http://eqdkp-plus.eu
*
* Copyright (C) 2006-2016 EQdkp-Plus Developer Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if ( !defined('EQDKP_INC') ){
header('HTTP/1.0 404 Not Found');exit;
}
class tinyMCE extends gen_class {
protected $tinymce_version = '4.9.6';
protected $language = 'en';
protected $trigger = array(
'bbcode' => false,
'normal' => false
);
protected $skin = 'lightgray';
protected $theme = 'modern';
public function __construct($nojsinclude=false){
if(!$nojsinclude) $this->tpl->js_file($this->server_path.'libraries/tinyMCE/tinymce/jquery.tinymce.min.js');
$this->language = $this->user->lang('XML_LANG');
$this->tpl->add_js('var tinymce_eqdkp_lightbox_thumbnailsize = '.(($this->config->get('thumbnail_defaultsize')) ? $this->config->get('thumbnail_defaultsize') : 400).';');
if($this->user->style['editor_theme'] != ""){
$this->skin = $this->user->style['editor_theme'];
}
}
public function editor_bbcode($settings=false){
if(!$this->trigger['bbcode']){
//Language
$lang = ( !isset($settings['language']) ) ? $this->language : $settings['language'];
if (is_file($this->root_path.'libraries/tinyMCE/tinymce/langs/'.$lang.'.js')){
$this->language = ( !isset($settings['language']) ) ? $this->language : $settings['language'];
} else $this->language = 'en';
$arrHooks = (($this->hooks->isRegistered('tinymce_bbcode_setup')) ? $this->hooks->process('tinymce_bbcode_setup', array('js' => '', 'env' => $this->env), true): array());
$strHooks = isset($arrHooks['js']) ? $arrHooks['js'] : '';
$strHooksPlugin = isset($arrHooks['plugins']) ? $arrHooks['plugins'] : '';
$strHooksToolbar = isset($arrHooks['toolbar']) ? $arrHooks['toolbar'] : '';
$mention = (isset($settings['mention']) && $settings['mention']) ? ' mention' : '';
$autolink = ($this->config->get('enable_embedly')) ? '' : ' autolink';
$this->tpl->add_js('
function initialize_bbcode_editor(){
$(".mceEditor_bbcode").tinymce({
// Location of TinyMCE script
script_url : "'.$this->server_path.'libraries/tinyMCE/tinymce/tinymce.min.js",
// General options
plugins: [
"bbcode link image charmap paste",
"searchreplace visualblocks code fullscreen",
"media textcolor '.$mention.$strHooksPlugin.$autolink.'"
],
language : "'.$this->language.'",
branding: false,
theme : "'.$this->theme.'",
skin : "'.$this->skin.'",
paste_as_text: true,
browser_spellcheck: true,
mentions: {
source: function(query, process, delimiter){
$.getJSON("'.$this->server_path.'libraries/tinyMCE/tinymce/plugins/mention/users.php", function (data) {
process(data);
});
},
insert: function(item) {
return "@\'" + item.name + "\'";
}
},
setup: function(editor){
editor.on("init", function(evt){
$(editor.getBody().parentNode).bind("dragover dragenter dragend drag drop", function(event){
event.stopPropagation();
event.preventDefault();
});
$(editor.getDoc()).bind("draggesture", function(event){
event.stopPropagation();
event.preventDefault();
});
});
'.$strHooks.'
},
// Theme options
entity_encoding : "raw",
add_unload_trigger : false,
remove_linebreaks : false,
inline_styles : false,
convert_fonts_to_spans : false,
force_p_newlines : false,
menubar: false,
relative_urls : false,
remove_script_host : false,
toolbar: "undo redo | bold italic underline | fontsizeselect forecolor | blockquote image link'.$strHooksToolbar.'",
statusbar : false,
});
}
initialize_bbcode_editor();
', 'docready');
$this->trigger['bbcode'] = true;
}
}
public function editor_normal($settings=false){
if(!$this->trigger['normal']){
//Language
$lang = (!isset($settings['language']) || !$settings['language'] ) ? $this->language : $settings['language'];
if (is_file($this->root_path.'libraries/tinyMCE/tinymce/langs/'.$lang.'.js')){
$this->language = (!isset($settings['language']) || !$settings['language'] ) ? $this->language : $settings['language'];
} else $this->language = 'en';
$autoresize = (isset($settings['autoresize']) && $settings['autoresize']) ? ' autoresize' : '';
$pageobjects = (isset($settings['pageobjects']) && $settings['pageobjects']) ? ' eqdkp_pageobject' : '';
$readmore = (isset($settings['readmore']) && !$settings['readmore']) ? '' : ' eqdkp_pagebreak_readmore';
$gallery = (isset($settings['gallery']) && $settings['gallery']) ? ' eqdkp_gallery' : '';
$raidloot = (isset($settings['raidloot']) && $settings['raidloot'] && !$this->config->get('disable_guild_features')) ? ' eqdkp_raidloot eqdkp_chars' : '';
$relative_url = (isset($settings['relative_urls']) && $settings['relative_urls'] == false) ? 'relative_urls : false,' : '';
$removeHost = (isset($settings['remove_host']) && $settings['remove_host'] == false) ? 'remove_script_host : false,' : 'remove_script_host : true, convert_urls : true,';
$image_upload = (isset($settings['image_upload']) && $settings['image_upload'] == true) ? 'paste_data_images: true, images_upload_credentials: true, images_upload_url: "'.$this->server_path.'libraries/tinyMCE/imageUploader.php'.$this->SID.'",' : '';
$item_plugin = (!$this->config->get('disable_guild_features')) ? ' eqdkp_item' : '';
$link_list = '';
if (isset($settings['link_list'])){
//Articles & Categories
$arrCategoryIDs = $this->pdh->sort($this->pdh->get('article_categories', 'id_list', array()), 'article_categories', 'sort_id', 'asc');
foreach($arrCategoryIDs as $cid){
if (!$this->pdh->get('article_categories', 'published', array($cid))) continue;
if ($cid != 1) $arrCategories[] = array('text' => $this->pdh->get('article_categories', 'name', array($cid)), 'id' => $cid);
$arrArticles = $this->pdh->get('articles', 'id_list', array($cid));
foreach($arrArticles as $articleID){
if (!$this->pdh->get('articles', 'published', array($articleID))) continue;
$arrItems[$cid][] = array('text' => $this->pdh->get('articles', 'title', array( $articleID)), 'id' => $articleID);
}
}
$link_list = '
link_list : [{text: "'.$this->user->lang('articles').'", value: "", menu: [';
foreach($arrCategories as $val){
$link_list .= '{text: "'.$val['text'].'", value: "{{category_url_plain::'.$val['id'].'}}", menu: [';
if(!isset($arrItems[$val['id']])) $arrItems[$val['id']] = array();
$link_list .= '{text: "'.$val['text'].'", value: "{{category_url_plain::'.$val['id'].'}}"},';
foreach($arrItems[$val['id']] as $value){
$link_list .= '{text: "'.$this->jquery->sanitize($value['text'], true).'", value: "{{article_url_plain::'.$value['id'].'}}"},';
}
$link_list .= ']},';
}
//$link_list .= '{}';
$link_list .= '
]}],';
}
$arrHooks = (($this->hooks->isRegistered('tinymce_normal_setup')) ? $this->hooks->process('tinymce_normal_setup', array('js' => '', 'env' => $this->env), true): array());
$strHooks = isset($arrHooks['js']) ? $arrHooks['js'] : '';
$strHooksPlugin = isset($arrHooks['plugins']) ? $arrHooks['plugins'] : '';
$strHooksToolbar = isset($arrHooks['toolbar']) ? $arrHooks['toolbar'] : '';
$autolink = ($this->config->get('enable_embedly')) ? '' : ' autolink';
$this->tpl->add_js('
$(".mceEditor").tinymce({
// Location of TinyMCE script
script_url : "'.$this->server_path.'libraries/tinyMCE/tinymce/tinymce.min.js",
document_base_url : "'.$this->env->link.'",
// General options
theme : "'.$this->theme.'",
skin : "'.$this->skin.'",
image_advtab: true,
verify_html: false,
branding: false,
mobile: { theme: "mobile" },
toolbar: "code | insertfile undo redo | fullscreen | styleselect | fontselect | fontsizeselect | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist | link image media emoticons eqdkp_lightbox eqdkp_filebrowser | eqdkp_readmore eqdkp_pagebreak eqdkp_pageobject | eqdkp_item eqdkp_gallery eqdkp_raidloot eqdkp_chars | custom_buttons '.$strHooksToolbar.'",
language : "'.$this->language.'",
plugins: [
"advlist lists link image imagetools charmap preview anchor eqdkp_lightbox eqdkp_filebrowser eqdkp_easyinsert",
"searchreplace visualblocks code fullscreen colorpicker",
"media table contextmenu paste textcolor emoticons'.$autolink.$item_plugin.$autoresize.$pageobjects.$readmore.$gallery.$raidloot.$strHooksPlugin.'"
],
browser_spellcheck: true,
images_upload_credentials: true,
images_upload_url: "'.$this->server_path.'libraries/tinyMCE/imageUploader.php'.$this->SID.'",
entity_encoding : "raw",
rel_list: [{value:"", text: "" }, {value:"lightbox", text: "Lightbox" }, {value:"nofollow", text: "nofollow" }],
extended_valid_elements: "p[class|id|style|data-sort|data-folder|data-id|title],script[type|lang|src]",
setup: function(editor){
'.$strHooks.'
},
'.$link_list.'
file_picker_callback: function(callback, value, meta) {
var elfinder_url = "'.$this->env->link.'libraries/elfinder/elfinder.php'.$this->SID.'"; // use an absolute path!
var cmsURL = elfinder_url; // script URL - use an absolute path!
var type = meta.filetype;
if (cmsURL.indexOf("?") < 0) {
//add the type as the only query parameter
cmsURL = cmsURL + "?editor=tiny&type=" + type + "&field=_callback";
}
else {
//add the type as an additional query parameter
// (PHP session ID is now included if there is one at all)
cmsURL = cmsURL + "&editor=tiny&type=" + type + "&field=_callback";
}
var mycallback = callback;
tinyMCE.activeEditor.windowManager.open({
file : cmsURL,
title : "File Browser",
width : 900,
height : 450,
resizable : "yes",
inline : "yes", // This parameter only has an effect if you use the inlinepopups plugin!
popup_css : false, // Disable TinyMCEs default popup CSS
close_previous : "no"
}, {
oninsert: function (url, objVals) {
callback(url, objVals);
},
param_meta: meta,
param_value: value,
});
return false;
},
'.$relative_url.$removeHost.$image_upload.'
});
', 'docready');
$this->trigger['normal'] = true;
}
}
public function inline_editor_simple($selector, $settings=array()){
if(!isset($this->trigger['inline_simple.'.$selector])){
//Language
$lang = ( !isset($settings['language']) || (isset($settings['language']) && !$settings['language']) ) ? $this->language : $settings['language'];
if (is_file($this->root_path.'libraries/tinyMCE/tinymce/langs/'.$lang.'.js')){
$this->language = ( !isset($settings['language']) || (isset($settings['language']) && !$settings['language']) ) ? $this->language : $settings['language'];
} else $this->language = 'en';
$strSetup = (isset($settings['setup'])) ? $settings['setup'] : '';
$strAutofocus = (isset($settings['autofocus']) && $settings['autofocus']) ? 'true' : 'false';
$blnStart = (isset($settings['start_onload'])) ? $settings['start_onload'] : true;
//Hooks
$arrHooks = (($this->hooks->isRegistered('tinymce_inline_simple_setup')) ? $this->hooks->process('tinymce_inline_simple_setup', array('js' => '', 'selector' => $selector, 'env' => $this->env), true): array());
$strHooks = isset($arrHooks['js']) ? $arrHooks['js'] : '';
$strHooksPlugin = isset($arrHooks['plugins']) ? $arrHooks['plugins'] : '';
$strHooksToolbar = isset($arrHooks['toolbar']) ? $arrHooks['toolbar'] : '';
$tinyid = md5($selector);
$this->tpl->add_js('
function tinyinlinesimple_'.$tinyid.'() {
$("'.$selector.'").tinymce({
// Location of TinyMCE script
script_url : "'.$this->server_path.'libraries/tinyMCE/tinymce/tinymce.min.js",
document_base_url : "'.$this->env->link.'",
// General options
language : "'.$this->language.'",
theme : "'.$this->theme.'",
skin : "'.$this->skin.'",
inline: true,
toolbar: "undo redo '.$strHooksToolbar.'",
menubar: false,
plugins: ["save '.$strHooksPlugin.'"],
browser_spellcheck: true,
setup: function(editor) {
'.$strSetup.$strHooks.'
},
entity_encoding : "raw",
relative_urls : false,
remove_script_host : false,
auto_focus: '.$strAutofocus.'
});
}
'.(($blnStart) ? 'tinyinlinesimple_'.$tinyid.'()' : '').'
', 'docready');
$this->trigger['inline_simple.'.$selector] = true;
}
}
public function inline_editor($selector, $settings=false, $blnStart=true){
if(!isset($this->trigger['inline.'.$selector])){
//Language
$lang = ( !isset($settings['language']) || (isset($settings['language']) && !$settings['language']) ) ? $this->language : $settings['language'];
if (is_file($this->root_path.'libraries/tinyMCE/tinymce/langs/'.$lang.'.js')){
$this->language = ( !isset($settings['language']) || (isset($settings['language']) && !$settings['language']) ) ? $this->language : $settings['language'];
} else $this->language = 'en';
$autoresize = (isset($settings['autoresize']) && $settings['autoresize']) ? ' autoresize' : '';
$pageobjects = (isset($settings['pageobjects']) && $settings['pageobjects']) ? ' eqdkp_pageobject' : '';
$readmore = (isset($settings['readmore']) && !$settings['readmore']) ? '' : ' eqdkp_pagebreak_readmore';
$gallery = (isset($settings['gallery']) && $settings['gallery']) ? ' eqdkp_gallery' : '';
$raidloot = (isset($settings['raidloot']) && $settings['raidloot'] && !$this->config->get('disable_guild_features')) ? ' eqdkp_raidloot eqdkp_chars' : '';
$relative_url = (isset($settings['relative_urls']) && $settings['relative_urls'] == false) ? 'relative_urls : false,' : '';
$removeHost = (isset($settings['remove_host']) && $settings['remove_host'] == false) ? 'remove_script_host : false,' : 'remove_script_host : true, convert_urls : true,';
$image_upload = (isset($settings['image_upload']) && $settings['image_upload'] == true) ? 'paste_data_images: true, images_upload_credentials: true, images_upload_url: "'.$this->server_path.'libraries/tinyMCE/imageUploader.php'.$this->SID.'",' : '';
$item_plugin = (!$this->config->get('disable_guild_features')) ? ' eqdkp_item' : '';
$strSetup = (isset($settings['setup'])) ? $settings['setup'] : '';
$strAutofocus = (isset($settings['autofocus']) && $settings['autofocus']) ? 'true' : 'false';
$blnStart = (isset($settings['start_onload'])) ? $settings['start_onload'] : true;
$link_list = '';
if (isset($settings['link_list'])){
//Articles & Categories
$arrCategoryIDs = $this->pdh->sort($this->pdh->get('article_categories', 'id_list', array()), 'article_categories', 'sort_id', 'asc');
foreach($arrCategoryIDs as $cid){
if (!$this->pdh->get('article_categories', 'published', array($cid))) continue;
if ($cid != 1) $arrCategories[] = array('text' => $this->pdh->get('article_categories', 'name', array($cid)), 'id' => $cid);
$arrArticles = $this->pdh->get('articles', 'id_list', array($cid));
foreach($arrArticles as $articleID){
if (!$this->pdh->get('articles', 'published', array($articleID))) continue;
$arrItems[$cid][] = array('text' => $this->pdh->get('articles', 'title', array( $articleID)), 'id' => $articleID);
}
}
$link_list = '
link_list : [{text: "'.$this->user->lang('articles').'", value: "", menu: [';
foreach($arrCategories as $val){
$link_list .= '{text: "'.$val['text'].'", value: "{{category_url::'.$val['id'].'}}", menu: [';
if(!isset($arrItems[$val['id']])) $arrItems[$val['id']] = array();
$link_list .= '{text: "'.$val['text'].'", value: "{{category_url::'.$val['id'].'}}"},';
foreach($arrItems[$val['id']] as $value){
$link_list .= '{text: "'.$this->jquery->sanitize($value['text'], true).'", value: "{{article_url::'.$value['id'].'}}"},';
}
$link_list .= ']},';
}
//$link_list .= '{}';
$link_list .= '
]}],';
}
$arrHooks = (($this->hooks->isRegistered('tinymce_inline_setup')) ? $this->hooks->process('tinymce_inline_setup', array('js' => '', 'selector' => $selector, 'env' => $this->env), true): array());
$strHooks = isset($arrHooks['js']) ? $arrHooks['js'] : '';
$strHooksPlugin = isset($arrHooks['plugins']) ? $arrHooks['plugins'] : '';
$strHooksToolbar = isset($arrHooks['toolbar']) ? $arrHooks['toolbar'] : '';
$autolink = ($this->config->get('enable_embedly')) ? '' : ' autolink';
$tinyid = md5($selector);
$this->tpl->add_js('
function tinyinline_'.$tinyid.'(){
$("'.$selector.'").tinymce({
// Location of TinyMCE script
script_url : "'.$this->server_path.'libraries/tinyMCE/tinymce/tinymce.min.js",
document_base_url : "'.$this->env->link.'",
// General options
inline: true,
theme : "'.$this->theme.'",
skin : "'.$this->skin.'",
image_advtab: true,
verify_html: false,
toolbar: "insertfile undo redo | fullscreen | styleselect | fontselect | fontsizeselect | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist | link image media emoticons eqdkp_lightbox eqdkp_filebrowser | eqdkp_readmore eqdkp_pagebreak eqdkp_pageobject | eqdkp_item eqdkp_gallery eqdkp_raidloot eqdkp_chars | custom_buttons '.$strHooksToolbar.'",
language : "'.$this->language.'",
plugins: [
"advlist lists link image imagetools charmap preview anchor eqdkp_lightbox eqdkp_filebrowser eqdkp_easyinsert",
"searchreplace visualblocks code fullscreen",
"save media table contextmenu paste textcolor emoticons'.$item_plugin.$autoresize.$pageobjects.$readmore.$gallery.$raidloot.$strHooksPlugin.'"
],
browser_spellcheck: true,
entity_encoding : "raw",
rel_list: [{value:"", text: "" }, {value:"lightbox", text: "Lightbox" }, {value:"nofollow", text: "nofollow" }],
extended_valid_elements : "p[class|id|style|data-sort|data-folder|data-id|title],script[type|lang|src]",
'.$link_list.'
file_browser_callback : function(field_name, url, type, win){
var elfinder_url = "'.$this->env->link.'libraries/elfinder/elfinder.php'.$this->SID.'"; // use an absolute path!
var cmsURL = elfinder_url; // script URL - use an absolute path!
if (cmsURL.indexOf("?") < 0) {
//add the type as the only query parameter
cmsURL = cmsURL + "?editor=tiny&type=" + type + "&field=_callback";
}
else {
//add the type as an additional query parameter
// (PHP session ID is now included if there is one at all)
cmsURL = cmsURL + "&editor=tiny&type=" + type + "&field=_callback";
}
tinyMCE.activeEditor.windowManager.open({
file : cmsURL,
title : "File Browser",
width : 900,
height : 450,
resizable : "yes",
inline : "yes", // This parameter only has an effect if you use the inlinepopups plugin!
popup_css : false, // Disable TinyMCEs default popup CSS
close_previous : "no"
}, {
oninsert: function (url, objVals) {
callback(url, objVals);
},
param_meta: meta,
param_value: value,
});
return false;
},
setup: function(editor) {
'.$strSetup.$strHooks.'
},
save_onsavecallback: function() {
},
auto_focus: '.$strAutofocus.',
'.$relative_url.$removeHost.$image_upload.'
});
}
'.(($blnStart) ? 'tinyinline_'.$tinyid.'()' : '').'
', 'docready');
$this->trigger['inline.'.$selector] = true;
}
}
public function textbox($input, $settings){
$text_cols = ( !$settings['textbox_cols'] ) ? "85" : $settings['textbox_cols'];
$text_rows = ( !$settings['textbox_rows'] ) ? "15" : $settings['textbox_rows'];
$textbox = ( !$settings['textbox_name'] ) ? "content" :$settings['textbox_name'];
return '<textarea name="'.$textbox.'" class="mceEditor" cols="'.$text_cols.'" rows="'.$text_rows.'">'.$input.'</textarea>';
}
public function encode($input){
return addslashes(htmlentities($input));
}
public function decode($input){
return html_entity_decode(stripslashes($input));
}
public function getAvailableSkins(){
$arrSkins = sdir($this->root_path.'libraries/tinyMCE/tinymce/skins');
$arrOut = array();
foreach($arrSkins as $val){
$arrOut[$val] = ucfirst($val);
}
return $arrOut;
}
}
| EQdkpPlus/core | libraries/tinyMCE/tinyMCE.class.php | PHP | agpl-3.0 | 21,374 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.ar.businessobject.lookup;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.kns.lookup.HtmlData;
import org.kuali.kfs.kns.lookup.HtmlData.AnchorHtmlData;
import org.kuali.kfs.kns.lookup.KualiLookupableHelperServiceImpl;
import org.kuali.kfs.kns.web.struts.form.LookupForm;
import org.kuali.kfs.kns.web.ui.ResultRow;
import org.kuali.kfs.krad.util.GlobalVariables;
import org.kuali.kfs.krad.util.KRADConstants;
import org.kuali.kfs.krad.util.UrlFactory;
import org.kuali.kfs.module.ar.ArConstants;
import org.kuali.kfs.module.ar.ArKeyConstants;
import org.kuali.kfs.module.ar.ArPropertyConstants;
import org.kuali.kfs.module.ar.businessobject.Customer;
import org.kuali.kfs.module.ar.businessobject.CustomerOpenItemReportDetail;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.krad.bo.BusinessObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
public class CustomerLookupableHelperServiceImpl extends KualiLookupableHelperServiceImpl {
/***
* This method was overridden to remove the COPY link from the actions and to add in the REPORT link.
*
* @see org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#getCustomActionUrls(org.kuali.rice.krad.bo.BusinessObject, java.util.List)
*/
@Override
public List<HtmlData> getCustomActionUrls(BusinessObject businessObject, List pkNames) {
List<HtmlData> htmlDataList = new ArrayList<HtmlData>();
if (StringUtils.isNotBlank(getMaintenanceDocumentTypeName()) && allowsMaintenanceEditAction(businessObject)) {
htmlDataList.add(getUrlData(businessObject, KRADConstants.MAINTENANCE_EDIT_METHOD_TO_CALL, pkNames));
}
htmlDataList.add(getCustomerOpenItemReportUrl(businessObject));
return htmlDataList;
}
/**
* This method...
*
* @param bo
* @return
*/
protected AnchorHtmlData getCustomerOpenItemReportUrl(BusinessObject bo) {
Customer customer = (Customer) bo;
Properties params = new Properties();
params.put(KFSConstants.BUSINESS_OBJECT_CLASS_ATTRIBUTE, CustomerOpenItemReportDetail.class.getName());
params.put(KFSConstants.RETURN_LOCATION_PARAMETER, StringUtils.EMPTY);
params.put(KFSConstants.LOOKUPABLE_IMPL_ATTRIBUTE_NAME, ArConstants.CUSTOMER_OPEN_ITEM_REPORT_LOOKUPABLE_IMPL);
params.put(KFSConstants.DISPATCH_REQUEST_PARAMETER, KFSConstants.SEARCH_METHOD);
params.put(ArPropertyConstants.CustomerFields.CUSTOMER_NUMBER, customer.getCustomerNumber());
params.put(KFSConstants.CustomerOpenItemReport.REPORT_NAME, KFSConstants.CustomerOpenItemReport.HISTORY_REPORT_NAME);
params.put(ArPropertyConstants.CustomerFields.CUSTOMER_NAME, customer.getCustomerName());
params.put(KFSConstants.DOC_FORM_KEY, "88888888");
String href = UrlFactory.parameterizeUrl(getKualiConfigurationService().getPropertyValueAsString(KRADConstants.APPLICATION_URL_KEY) + "/" + ArConstants.UrlActions.CUSTOMER_OPEN_ITEM_REPORT_LOOKUP, params);
return new AnchorHtmlData(href, KFSConstants.SEARCH_METHOD, ArKeyConstants.CustomerConstants.ACTIONS_REPORT);
}
/**
* This method was overridden to set force the actions to show up even if the user does not have permission to initiate a CUS document.
*/
@Override
public Collection<? extends BusinessObject> performLookup(LookupForm lookupForm, Collection<ResultRow> resultTable, boolean bounded) {
boolean isAuthorized = KimApiServiceLocator.getPermissionService().isAuthorized(GlobalVariables.getUserSession().getPerson().getPrincipalId(), ArConstants.AR_NAMESPACE_CODE, ArConstants.PermissionNames.REPORT, new HashMap<String, String>());
if (isAuthorized) {
lookupForm.setSuppressActions(false);
}
return super.performLookup(lookupForm, resultTable, bounded);
}
}
| quikkian-ua-devops/will-financials | kfs-ar/src/main/java/org/kuali/kfs/module/ar/businessobject/lookup/CustomerLookupableHelperServiceImpl.java | Java | agpl-3.0 | 4,861 |
# -*- coding: utf-8 -*-
import traceback
from ckan.lib.helpers import json
from ckanext.harvest.model import HarvestObject, HarvestObjectExtra
from ckanext.harvest.harvesters import HarvesterBase
from ckanext.geocat.utils import search_utils, csw_processor, ogdch_map_utils, csw_mapping # noqa
from ckanext.geocat.utils.vocabulary_utils import \
(VALID_TERMS_OF_USE, DEFAULT_TERMS_OF_USE)
from ckan.logic.schema import default_update_package_schema,\
default_create_package_schema
from ckan.lib.navl.validators import ignore
import ckan.plugins.toolkit as tk
from ckan import model
from ckan.model import Session
import uuid
import logging
log = logging.getLogger(__name__)
DEFAULT_PERMA_LINK_URL = 'https://www.geocat.ch/geonetwork/srv/ger/md.viewer#/full_view/' # noqa
DEFAULT_PERMA_LINK_LABEL = 'geocat.ch Permalink'
HARVEST_USER = 'harvest'
class GeocatHarvester(HarvesterBase):
'''
The harvester for geocat
'''
def info(self):
return {
'name': 'geocat_harvester',
'title': 'Geocat harvester',
'description': (
'Harvests metadata from geocat (CSW)'
),
'form_config_interface': 'Text'
}
def validate_config(self, config):
if not config:
return config
try:
config_obj = json.loads(config)
except Exception as e:
raise ValueError(
'Configuration could not be parsed. An error {} occured'
.format(e)
)
if 'delete_missing_datasets' in config_obj:
if not isinstance(config_obj['delete_missing_datasets'], bool):
raise ValueError('delete_missing_dataset must be boolean')
if 'rights' in config_obj:
if not config_obj['rights'] in VALID_TERMS_OF_USE:
raise ValueError('{} is not valid as terms of use'
.format(config_obj['rights']))
return config
def _set_config(self, config_str, harvest_source_id):
if config_str:
self.config = json.loads(config_str)
else:
self.config = {}
self.config['rights'] = self.config.get('rights', DEFAULT_TERMS_OF_USE)
if not self.config['rights'] in VALID_TERMS_OF_USE:
self.config['rights'] = DEFAULT_TERMS_OF_USE
self.config['delete_missing_datasets'] = \
self.config.get('delete_missing_datasets', False)
self.config['geocat_perma_link_label'] = \
tk.config.get('ckanext.geocat.permalink_title',
DEFAULT_PERMA_LINK_LABEL)
self.config['geocat_perma_link_url'] = \
self.config.get('geocat_perma_link_url',
tk.config.get('geocat_perma_link_url',
DEFAULT_PERMA_LINK_URL))
self.config['legal_basis_url'] = \
self.config.get('legal_basis_url', None)
organization_slug = \
search_utils.get_organization_slug_for_harvest_source(
harvest_source_id)
self.config['organization'] = organization_slug
log.debug('Using config: %r' % self.config)
def gather_stage(self, harvest_job):
log.debug('In GeocatHarvester gather_stage')
self._set_config(harvest_job.source.config, harvest_job.source.id)
csw_url = harvest_job.source.url
try:
csw_data = csw_processor.GeocatCatalogueServiceWeb(url=csw_url)
gathered_geocat_identifiers = csw_data.get_geocat_id_from_csw()
except Exception as e:
self._save_gather_error(
'Unable to get content for URL: %s: %s / %s'
% (csw_url, str(e), traceback.format_exc()),
harvest_job
)
return []
existing_dataset_infos = \
search_utils.get_dataset_infos_for_organization(
organization_name=self.config['organization'],
harvest_source_id=harvest_job.source_id,
)
gathered_ogdch_identifiers = \
[ogdch_map_utils.map_geocat_to_ogdch_identifier(
geocat_identifier=geocat_identifier,
organization_slug=self.config['organization'])
for geocat_identifier in gathered_geocat_identifiers]
all_ogdch_identifiers = \
set(gathered_ogdch_identifiers + existing_dataset_infos.keys())
packages_to_delete = search_utils.get_packages_to_delete(
existing_dataset_infos=existing_dataset_infos,
gathered_ogdch_identifiers=gathered_ogdch_identifiers,
)
csw_map = csw_mapping.GeoMetadataMapping(
organization_slug=self.config['organization'],
geocat_perma_link=self.config['geocat_perma_link_url'],
geocat_perma_label=self.config['geocat_perma_link_label'],
legal_basis_url=self.config['legal_basis_url'],
default_rights=self.config['rights'],
valid_identifiers=all_ogdch_identifiers,
)
harvest_obj_ids = self.map_geocat_dataset(
csw_data,
csw_map,
gathered_geocat_identifiers,
gathered_ogdch_identifiers,
harvest_job)
log.debug('IDs: %r' % harvest_obj_ids)
if self.config['delete_missing_datasets']:
delete_harvest_object_ids = \
self.delete_geocat_ids(
harvest_job,
harvest_obj_ids,
packages_to_delete
)
harvest_obj_ids.extend(delete_harvest_object_ids)
return harvest_obj_ids
def delete_geocat_ids(self,
harvest_job,
harvest_obj_ids,
packages_to_delete):
delete_harvest_obj_ids = []
for package_info in packages_to_delete:
obj = HarvestObject(
guid=package_info[1].name,
job=harvest_job,
extras=[HarvestObjectExtra(key='import_action',
value='delete')])
obj.save()
delete_harvest_obj_ids.append(obj.id)
return delete_harvest_obj_ids
def map_geocat_dataset(self,
csw_data,
csw_map,
gathered_geocat_identifiers,
gathered_ogdch_identifiers,
harvest_job):
mapped_harvest_obj_ids = []
for geocat_id in gathered_geocat_identifiers:
ogdch_identifier = ogdch_map_utils.map_geocat_to_ogdch_identifier(
geocat_identifier=geocat_id,
organization_slug=self.config['organization'])
if ogdch_identifier in gathered_ogdch_identifiers:
try:
csw_record_as_string = csw_data.get_record_by_id(geocat_id)
except Exception as e:
self._save_gather_error(
'Error when reading csw record form source: %s %r / %s'
% (ogdch_identifier, e, traceback.format_exc()),
harvest_job)
continue
try:
dataset_dict = csw_map.get_metadata(csw_record_as_string,
geocat_id)
except Exception as e:
self._save_gather_error(
'Error when mapping csw data to dcat: %s %r / %s'
% (ogdch_identifier, e, traceback.format_exc()),
harvest_job)
continue
try:
harvest_obj = \
HarvestObject(guid=ogdch_identifier,
job=harvest_job,
content=json.dumps(dataset_dict))
harvest_obj.save()
except Exception as e:
self._save_gather_error(
'Error when processsing dataset: %s %r / %s'
% (ogdch_identifier, e, traceback.format_exc()),
harvest_job)
continue
else:
mapped_harvest_obj_ids.append(harvest_obj.id)
return mapped_harvest_obj_ids
def fetch_stage(self, harvest_object):
return True
def import_stage(self, harvest_object): # noqa
log.debug('In GeocatHarvester import_stage')
if not harvest_object:
log.error('No harvest object received')
self._save_object_error(
'No harvest object received',
harvest_object
)
return False
import_action = \
search_utils.get_value_from_object_extra(harvest_object.extras,
'import_action')
if import_action and import_action == 'delete':
log.debug('import action: %s' % import_action)
harvest_object.current = False
return self._delete_dataset({'id': harvest_object.guid})
if harvest_object.content is None:
self._save_object_error('Empty content for object %s' %
harvest_object.id,
harvest_object, 'Import')
return False
try:
pkg_dict = json.loads(harvest_object.content)
except ValueError:
self._save_object_error('Could not parse content for object {0}'
.format(harvest_object.id), harvest_object, 'Import') # noqa
return False
pkg_info = \
search_utils.find_package_for_identifier(harvest_object.guid)
context = {
'ignore_auth': True,
'user': HARVEST_USER,
}
try:
if pkg_info:
# Change default schema to ignore lists of dicts, which
# are stored in the '__junk' field
schema = default_update_package_schema()
context['schema'] = schema
schema['__junk'] = [ignore]
pkg_dict['name'] = pkg_info.name
pkg_dict['id'] = pkg_info.package_id
search_utils.map_resources_to_ids(pkg_dict, pkg_info)
updated_pkg = \
tk.get_action('package_update')(context, pkg_dict)
harvest_object.current = True
harvest_object.package_id = updated_pkg['id']
harvest_object.save()
log.debug("Updated PKG: %s" % updated_pkg)
else:
flat_title = _derive_flat_title(pkg_dict['title'])
if not flat_title:
self._save_object_error(
'Unable to derive name from title %s'
% pkg_dict['title'], harvest_object, 'Import')
return False
pkg_dict['name'] = self._gen_new_name(flat_title)
schema = default_create_package_schema()
context['schema'] = schema
schema['__junk'] = [ignore]
log.debug("No package found, create a new one!")
# generate an id to reference it in the harvest_object
pkg_dict['id'] = unicode(uuid.uuid4())
log.info('Package with GUID %s does not exist, '
'let\'s create it' % harvest_object.guid)
harvest_object.current = True
harvest_object.package_id = pkg_dict['id']
harvest_object.add()
model.Session.execute(
'SET CONSTRAINTS harvest_object_package_id_fkey DEFERRED')
model.Session.flush()
created_pkg = \
tk.get_action('package_create')(context, pkg_dict)
log.debug("Created PKG: %s" % created_pkg)
Session.commit()
return True
except Exception as e:
self._save_object_error(
('Exception in import stage: %r / %s'
% (e, traceback.format_exc())), harvest_object)
return False
def _create_new_context(self):
# get the site user
site_user = tk.get_action('get_site_user')(
{'model': model, 'ignore_auth': True}, {})
context = {
'model': model,
'session': Session,
'user': site_user['name'],
}
return context
def _delete_dataset(self, package_dict):
log.debug('deleting dataset %s' % package_dict['id'])
context = self._create_new_context()
tk.get_action('dataset_purge')(
context.copy(),
package_dict
)
return True
def _get_geocat_permalink_relation(self, geocat_pkg_id):
return {'url': self.config['geocat_perma_link_url'] + geocat_pkg_id,
'label': self.config['geocat_perma_link_label']}
class GeocatConfigError(Exception):
pass
def _derive_flat_title(title_dict):
"""localizes language dict if no language is specified"""
return title_dict.get('de') or title_dict.get('fr') or title_dict.get('en') or title_dict.get('it') or "" # noqa
| opendata-swiss/ckanext-geocat | ckanext/geocat/harvester.py | Python | agpl-3.0 | 13,479 |
require File.dirname(__FILE__) + '/../test_helper'
class NotifyActivityToProfilesJobTest < ActiveSupport::TestCase
should 'notify just the community in tracker with add_member_in_community verb' do
person = fast_create(Person)
community = fast_create(Community)
action_tracker = fast_create(ActionTracker::Record, :user_type => 'Profile', :user_id => person.id, :target_type => 'Profile', :target_id => community.id, :verb => 'add_member_in_community')
assert NotifyActivityToProfilesJob::NOTIFY_ONLY_COMMUNITY.include?(action_tracker.verb)
p1, p2, m1, m2 = fast_create(Person), fast_create(Person), fast_create(Person), fast_create(Person)
fast_create(Friendship, :person_id => person.id, :friend_id => p1.id)
fast_create(Friendship, :person_id => person.id, :friend_id => p2.id)
fast_create(RoleAssignment, :accessor_id => m1.id, :role_id => 3, :resource_id => community.id)
fast_create(RoleAssignment, :accessor_id => m2.id, :role_id => 3, :resource_id => community.id)
ActionTrackerNotification.delete_all
job = NotifyActivityToProfilesJob.new(action_tracker.id)
job.perform
process_delayed_job_queue
assert_equal 1, ActionTrackerNotification.count
[community].each do |profile|
notification = ActionTrackerNotification.find_by_profile_id profile.id
assert_equal action_tracker, notification.action_tracker
end
end
should 'notify just the community in tracker with remove_member_in_community verb' do
person = fast_create(Person)
community = fast_create(Community)
action_tracker = fast_create(ActionTracker::Record, :user_type => 'Profile', :user_id => person.id, :target_type => 'Profile', :target_id => community.id, :verb => 'remove_member_in_community')
assert NotifyActivityToProfilesJob::NOTIFY_ONLY_COMMUNITY.include?(action_tracker.verb)
p1, p2, m1, m2 = fast_create(Person), fast_create(Person), fast_create(Person), fast_create(Person)
fast_create(Friendship, :person_id => person.id, :friend_id => p1.id)
fast_create(Friendship, :person_id => person.id, :friend_id => p2.id)
fast_create(RoleAssignment, :accessor_id => m1.id, :role_id => 3, :resource_id => community.id)
fast_create(RoleAssignment, :accessor_id => m2.id, :role_id => 3, :resource_id => community.id)
ActionTrackerNotification.delete_all
job = NotifyActivityToProfilesJob.new(action_tracker.id)
job.perform
process_delayed_job_queue
assert_equal 1, ActionTrackerNotification.count
[community].each do |profile|
notification = ActionTrackerNotification.find_by_profile_id profile.id
assert_equal action_tracker, notification.action_tracker
end
end
should 'notify just the users and his friends tracking user actions' do
person = fast_create(Person)
community = fast_create(Community)
action_tracker = fast_create(ActionTracker::Record, :user_type => 'Profile', :user_id => person.id, :target_type => 'Profile', :verb => 'create_article')
assert !NotifyActivityToProfilesJob::NOTIFY_ONLY_COMMUNITY.include?(action_tracker.verb)
p1, p2, m1, m2 = fast_create(Person), fast_create(Person), fast_create(Person), fast_create(Person)
fast_create(Friendship, :person_id => person.id, :friend_id => p1.id)
fast_create(Friendship, :person_id => person.id, :friend_id => p2.id)
fast_create(Friendship, :person_id => p1.id, :friend_id => m1.id)
fast_create(RoleAssignment, :accessor_id => m2.id, :role_id => 3, :resource_id => community.id)
ActionTrackerNotification.delete_all
job = NotifyActivityToProfilesJob.new(action_tracker.id)
job.perform
process_delayed_job_queue
assert_equal 3, ActionTrackerNotification.count
[person, p1, p2].each do |profile|
notification = ActionTrackerNotification.find_by_profile_id profile.id
assert_equal action_tracker, notification.action_tracker
end
end
should 'not notify the communities members' do
person = fast_create(Person)
community = fast_create(Community)
action_tracker = fast_create(ActionTracker::Record, :user_type => 'Profile', :user_id => person.id, :target_type => 'Profile', :target_id => community.id, :verb => 'create_article')
assert !NotifyActivityToProfilesJob::NOTIFY_ONLY_COMMUNITY.include?(action_tracker.verb)
m1, m2 = fast_create(Person), fast_create(Person), fast_create(Person), fast_create(Person)
fast_create(RoleAssignment, :accessor_id => m1.id, :role_id => 3, :resource_id => community.id)
fast_create(RoleAssignment, :accessor_id => m2.id, :role_id => 3, :resource_id => community.id)
ActionTrackerNotification.delete_all
job = NotifyActivityToProfilesJob.new(action_tracker.id)
job.perform
process_delayed_job_queue
assert_equal 4, ActionTrackerNotification.count
[person, community, m1, m2].each do |profile|
notification = ActionTrackerNotification.find_by_profile_id profile.id
assert_equal action_tracker, notification.action_tracker
end
end
should 'notify users its friends, the community and its members' do
person = fast_create(Person)
community = fast_create(Community)
action_tracker = fast_create(ActionTracker::Record, :user_type => 'Profile', :user_id => person.id, :target_type => 'Profile', :target_id => community.id, :verb => 'create_article')
assert !NotifyActivityToProfilesJob::NOTIFY_ONLY_COMMUNITY.include?(action_tracker.verb)
p1, p2, m1, m2 = fast_create(Person), fast_create(Person), fast_create(Person), fast_create(Person)
fast_create(Friendship, :person_id => person.id, :friend_id => p1.id)
fast_create(Friendship, :person_id => person.id, :friend_id => p2.id)
fast_create(RoleAssignment, :accessor_id => m1.id, :role_id => 3, :resource_id => community.id)
fast_create(RoleAssignment, :accessor_id => m2.id, :role_id => 3, :resource_id => community.id)
ActionTrackerNotification.delete_all
job = NotifyActivityToProfilesJob.new(action_tracker.id)
job.perform
process_delayed_job_queue
assert_equal 6, ActionTrackerNotification.count
[person, community, p1, p2, m1, m2].each do |profile|
notification = ActionTrackerNotification.find_by_profile_id profile.id
assert_equal action_tracker, notification.action_tracker
end
end
should 'not notify the community tracking join_community verb' do
person = fast_create(Person)
community = fast_create(Community)
action_tracker = fast_create(ActionTracker::Record, :user_type => 'Profile', :user_id => person.id, :target_type => 'Profile', :target_id => community.id, :verb => 'join_community')
assert !NotifyActivityToProfilesJob::NOTIFY_ONLY_COMMUNITY.include?(action_tracker.verb)
p1, p2, m1, m2 = fast_create(Person), fast_create(Person), fast_create(Person), fast_create(Person)
fast_create(Friendship, :person_id => person.id, :friend_id => p1.id)
fast_create(Friendship, :person_id => person.id, :friend_id => p2.id)
fast_create(RoleAssignment, :accessor_id => m1.id, :role_id => 3, :resource_id => community.id)
fast_create(RoleAssignment, :accessor_id => m2.id, :role_id => 3, :resource_id => community.id)
ActionTrackerNotification.delete_all
job = NotifyActivityToProfilesJob.new(action_tracker.id)
job.perform
process_delayed_job_queue
assert_equal 5, ActionTrackerNotification.count
[person, p1, p2, m1, m2].each do |profile|
notification = ActionTrackerNotification.find_by_profile_id profile.id
assert_equal action_tracker, notification.action_tracker
end
end
should 'not notify the community tracking leave_community verb' do
person = fast_create(Person)
community = fast_create(Community)
action_tracker = fast_create(ActionTracker::Record, :user_type => 'Profile', :user_id => person.id, :target_type => 'Profile', :target_id => community.id, :verb => 'leave_community')
assert !NotifyActivityToProfilesJob::NOTIFY_ONLY_COMMUNITY.include?(action_tracker.verb)
p1, p2, m1, m2 = fast_create(Person), fast_create(Person), fast_create(Person), fast_create(Person)
fast_create(Friendship, :person_id => person.id, :friend_id => p1.id)
fast_create(Friendship, :person_id => person.id, :friend_id => p2.id)
fast_create(RoleAssignment, :accessor_id => m1.id, :role_id => 3, :resource_id => community.id)
fast_create(RoleAssignment, :accessor_id => m2.id, :role_id => 3, :resource_id => community.id)
ActionTrackerNotification.delete_all
job = NotifyActivityToProfilesJob.new(action_tracker.id)
job.perform
process_delayed_job_queue
assert_equal 5, ActionTrackerNotification.count
[person, p1, p2, m1, m2].each do |profile|
notification = ActionTrackerNotification.find_by_profile_id profile.id
assert_equal action_tracker, notification.action_tracker
end
end
should "the NOTIFY_ONLY_COMMUNITY constant has all the verbs tested" do
notify_community_verbs = ['add_member_in_community', 'remove_member_in_community']
assert_equal [], notify_community_verbs - NotifyActivityToProfilesJob::NOTIFY_ONLY_COMMUNITY
assert_equal [], NotifyActivityToProfilesJob::NOTIFY_ONLY_COMMUNITY - notify_community_verbs
end
should "the NOT_NOTIFY_COMMUNITY constant has all the verbs tested" do
not_notify_community_verbs = ['join_community', 'leave_community']
assert_equal [], not_notify_community_verbs - NotifyActivityToProfilesJob::NOT_NOTIFY_COMMUNITY
assert_equal [], NotifyActivityToProfilesJob::NOT_NOTIFY_COMMUNITY - not_notify_community_verbs
end
should 'cancel notify when target no more exists' do
person = fast_create(Person)
friend = fast_create(Person)
fast_create(Friendship, :person_id => person.id, :friend_id => friend.id)
action_tracker = fast_create(ActionTracker::Record, :user_type => 'Profile', :user_id => person.id, :target_type => 'Profile', :verb => 'create_article')
ActionTrackerNotification.delete_all
job = NotifyActivityToProfilesJob.new(action_tracker.id)
person.destroy
job.perform
process_delayed_job_queue
assert_equal 0, ActionTrackerNotification.count
end
end
| joenio/noosfero | test/unit/notify_activity_to_profiles_job_test.rb | Ruby | agpl-3.0 | 10,155 |
class AddStartFinishToRound < ActiveRecord::Migration
def change
add_column :rounds, :started_at, :datetime
add_column :rounds, :finished_at, :datetime
end
end
| bschmeck/two_sixes | db/migrate/20140728171953_add_start_finish_to_round.rb | Ruby | agpl-3.0 | 172 |
/*
Copyright 2015 Daniel Nichter
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package ticker
import (
"testing"
"time"
)
var nowNano int64
func mockNowNanoFunc() int64 {
return nowNano
}
var nowUnix int64
func mockNowUnixFunc() int64 {
return nowUnix
}
var slept time.Duration
func mockSleepFunc(t time.Duration) {
slept = t
return
}
func init() {
useMockFuncs()
}
func useMockFuncs() {
nowNanoFunc = mockNowNanoFunc
nowUnixFunc = mockNowUnixFunc
sleepFunc = mockSleepFunc
}
func TestFake2sTicker(t *testing.T) {
// To align ticks, we must first sleep N number of nanoseconds until
// the next interval. So we specify the curren time (now) in
// nanoseconds, and an interval time (2), and then we know how long
// the syncer should sleep to wait from now until the next interval
// time.
// Fri Sep 27 18:11:37.385120 -0700 PDT 2013 =
nowNano = int64(1380330697385120263)
// Start a 2s, aligned ticker.
tkr := NewTimeTicker(2, true)
defer tkr.Stop()
// Subscribe the 2s ticker.
c := tkr.Subscribe()
defer tkr.Remove(c)
// Wait for the first tick, which should be 0.61488 seconds away
// because now is ^ so the next interval 2s interval, 18:11:38.000.
<-c
// Check how long ticker slept.
got := slept.Nanoseconds()
expect := int64(614879744) // 0.61488s
if got != expect {
t.Errorf("Slept %d, expected %d\n", got, expect)
}
// Next (time to next tick) should be reported as the same: 0.614880s
d := tkr.Next()
if d < 0.614 || d > 0.615 {
t.Errorf("Next %f, expected 0.61488\n", d)
}
}
func TestFake60sTicker(t *testing.T) {
// Fri Sep 27 18:11:37.385120 -0700 PDT 2013 =
nowNano = int64(1380330697385120263)
tkr := NewTimeTicker(60, true)
defer tkr.Stop()
c := tkr.Subscribe()
defer tkr.Remove(c)
<-c
got := slept.Nanoseconds()
expect := int64(614879744 + (22 * time.Second))
if got != expect {
t.Errorf("Slept %d, expected %d\n", got, expect)
}
}
func TestReal2sTicker(t *testing.T) {
// Use real time functions for this test.
nowNanoFunc = time.Now().UnixNano
nowUnixFunc = time.Now().Unix
sleepFunc = time.Sleep
defer useMockFuncs() // restore mock time functions
// The ticker returned by the syncer should tick at this given interval,
// 2s in this case. We test this by ensuring that the current time at
// a couple of ticks is divisible by 2, and that the fractional seconds
// part is < ~1 millisecond, e.g.:
// 00:00:02.000123456 OK
// 00:00:04.000123456 OK
// 00:00:06.001987654 BAD
// This may fail on slow test machines.
// Start a 2s, aligned ticker.
tkr := NewTimeTicker(2, true)
defer tkr.Stop()
// Subscribe the 2s ticker.
c1 := tkr.Subscribe()
defer tkr.Remove(c1)
c2 := tkr.Subscribe()
defer tkr.Remove(c2)
// Get 2 ticks but only on c1. "Time waits for nobody" and neither does
// the ticker, so c2 not receiving should not affect c1.
maxDelay := 8900000 // 8.9ms
var lastTick time.Time
for i := 0; i < 2; i++ {
select {
case tick := <-c1:
sec := tick.Second()
if sec%2 > 0 {
t.Errorf("Tick %d not 2s interval: %d", i, sec)
}
nano := tick.Nanosecond()
if nano > maxDelay {
t.Errorf("Tick %d too slow: %d >= %d: %s", i, nano, maxDelay, tick)
}
lastTick = tick
}
}
// Remove c1 and recv on c2 now. Even though c2 missed previous 2 ticks,
// it should be able to start receiving new ticks. By contrast, c1 should
// not receive the tick.
tkr.Remove(c1)
timeout := time.After(2500 * time.Millisecond)
var c2Tick time.Time
TICK_LOOP:
for {
select {
case tick := <-c2:
if !c2Tick.IsZero() {
t.Error("c2 gets only 1 tick")
} else {
c2Tick = tick
}
case <-c1:
t.Error("c1 does not get current tick")
case <-timeout:
break TICK_LOOP
}
}
if c2Tick == lastTick || c2Tick.Before(lastTick) {
t.Error("c2 gets current tick")
}
}
func TestStopTicker(t *testing.T) {
// Use real time functions for this test.
nowNanoFunc = time.Now().UnixNano
nowUnixFunc = time.Now().Unix
sleepFunc = time.Sleep
defer useMockFuncs() // restore mock time functions
// Start a 2s, aligned ticker.
tkr := NewTimeTicker(1, false)
defer tkr.Stop()
// Subscribe the 2s ticker.
c := tkr.Subscribe()
ticked := make(chan bool, 1)
stopped := make(chan bool, 1)
go func() {
for _ = range c {
ticked <- true
}
stopped <- true
}()
// Wait for a tick to make sure it's alive.
select {
case <-ticked:
case <-time.After(2 * time.Second):
t.Fatal("Didn't get tick after 2s")
}
// Stop the ticker which should stop and close all the watcher chans.
tkr.Stop()
select {
case <-stopped:
case <-time.After(1 * time.Second):
t.Fatal("Ticker didn't stop after 1s")
}
// Stopping should be idempotent.
tkr.Stop()
}
func TestCurrent(t *testing.T) {
// 5m ticker
tkr := NewTimeTicker(300, true)
defer tkr.Stop()
var began time.Time
// between intervals
nowUnix = 1388577750 // 2014-01-01 12:02:30
began = tkr.Current()
if began.Unix() != int64(1388577600) { // 2014-01-01 12:00:00
t.Error("Got %d, expected 1388577600\n", began.Unix())
}
// 1s before next interval
nowUnix = 1388577899 // 2014-01-01 12:04:59
began = tkr.Current()
if began.Unix() != int64(1388577600) { // 2014-01-01 12:00:00
t.Error("Got %d, expected 1388577600\n", began.Unix())
}
// at interval
nowUnix = 1388577900 // 2014-01-01 12:05:00
began = tkr.Current()
if began.Unix() != int64(1388577900) { // 2014-01-01 12:05:00
t.Error("Got %d, expected 1388577900\n", began.Unix())
}
}
| daniel-nichter/ticker | ticker_test.go | GO | agpl-3.0 | 6,115 |
DELETE FROM `weenie` WHERE `class_Id` = 12509;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (12509, 'portallakeblessedcottages', 7, '2019-02-10 00:00:00') /* Portal */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (12509, 1, 65536) /* ItemType - Portal */
, (12509, 16, 32) /* ItemUseable - Remote */
, (12509, 93, 3084) /* PhysicsState - Ethereal, ReportCollisions, Gravity, LightingOn */
, (12509, 111, 1) /* PortalBitmask - Unrestricted */
, (12509, 133, 4) /* ShowableOnRadar - ShowAlways */
, (12509, 8007, 0) /* PCAPRecordedAutonomousMovement */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (12509, 1, True ) /* Stuck */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (12509, 54, -0.1) /* UseRadius */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (12509, 1, 'Lake Blessed Cottages Portal') /* Name */
, (12509, 8006, 'AAA9AAAAAAA=') /* PCAPRecordedCurrentMotionState */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (12509, 1, 33554867) /* Setup */
, (12509, 2, 150994947) /* MotionTable */
, (12509, 8, 100667499) /* Icon */
, (12509, 8001, 8388656) /* PCAPRecordedWeenieHeader - Usable, UseRadius, RadarBehavior */
, (12509, 8003, 262164) /* PCAPRecordedObjectDesc - Stuck, Attackable, Portal */
, (12509, 8005, 98307) /* PCAPRecordedPhysicsDesc - CSetup, MTable, Position, Movement */;
INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (12509, 8040, 3432316939, 45.2177, 59, 21.02033, 0.6177728, 0, 0, 0.7863567) /* PCAPRecordedLocation */
/* @teleloc 0xCC95000B [45.217700 59.000000 21.020330] 0.617773 0.000000 0.000000 0.786357 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (12509, 8000, 2093568002) /* PCAPRecordedObjectIID */;
| LtRipley36706/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/Portal/Portal/12509 Lake Blessed Cottages Portal.sql | SQL | agpl-3.0 | 2,135 |
# -*- coding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'l10n_ar_account_check_sale',
'version': '1.0',
'summary': 'Venta de cheques de terceros',
'description': """
Cheques
==================================
Venta de cheques de terceros.
""",
'author': 'OPENPYME S.R.L.',
'website': 'http://www.openpyme.com.ar',
'category': 'Accounting',
'depends': [
'l10n_ar_account_check',
],
'data': [
'data/sold_check_data.xml',
'views/account_third_check_view.xml',
'views/account_sold_check_view.xml',
'wizard/wizard_sell_check_view.xml',
'security/ir.model.access.csv',
'data/security.xml',
],
'active': False,
'application': True,
'installable': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| odoo-arg/odoo_l10n_ar | l10n_ar_account_check_sale/__manifest__.py | Python | agpl-3.0 | 1,674 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
********************************************************************************/
$dictionary['Campaign'] = array ('audited'=>true,
'comment' => 'Campaigns are a series of operations undertaken to accomplish a purpose, usually acquiring leads',
'table' => 'campaigns',
'unified_search' => true,
'fields' => array (
'tracker_key' => array (
'name' => 'tracker_key',
'vname' => 'LBL_TRACKER_KEY',
'type' => 'int',
'required' => true,
'studio' => array('editview' => false),
'len' => '11',
'auto_increment' => true,
'comment' => 'The internal ID of the tracker used in a campaign; no longer used as of 4.2 (see campaign_trkrs)'
),
'tracker_count' => array (
'name' => 'tracker_count',
'vname' => 'LBL_TRACKER_COUNT',
'type' => 'int',
'len' => '11',
'default' => '0',
'comment' => 'The number of accesses made to the tracker URL; no longer used as of 4.2 (see campaign_trkrs)'
),
'name' => array (
'name' => 'name',
'vname' => 'LBL_CAMPAIGN_NAME',
'dbType' => 'varchar',
'type' => 'name',
'len' => '50',
'comment' => 'The name of the campaign',
'importable' => 'required',
'required' => true,
'unified_search' => true,
),
'refer_url' => array (
'name' => 'refer_url',
'vname' => 'LBL_REFER_URL',
'type' => 'varchar',
'len' => '255',
'default' => 'http://',
'comment' => 'The URL referenced in the tracker URL; no longer used as of 4.2 (see campaign_trkrs)'
),
'description'=>array('name'=>'description','type'=>'none', 'comment'=>'inhertied but not used', 'source'=>'non-db'),
'tracker_text' => array (
'name' => 'tracker_text',
'vname' => 'LBL_TRACKER_TEXT',
'type' => 'varchar',
'len' => '255',
'comment' => 'The text that appears in the tracker URL; no longer used as of 4.2 (see campaign_trkrs)'
),
'start_date' => array (
'name' => 'start_date',
'vname' => 'LBL_CAMPAIGN_START_DATE',
'type' => 'date',
'audited'=>true,
'comment' => 'Starting date of the campaign',
'validation' => array ('type' => 'isbefore', 'compareto' => 'end_date'),
'enable_range_search' => true,
'options' => 'date_range_search_dom',
),
'end_date' => array (
'name' => 'end_date',
'vname' => 'LBL_CAMPAIGN_END_DATE',
'type' => 'date',
'audited'=>true,
'comment' => 'Ending date of the campaign',
'importable' => 'required',
'required' => true,
'enable_range_search' => true,
'options' => 'date_range_search_dom',
),
'status' => array (
'name' => 'status',
'vname' => 'LBL_CAMPAIGN_STATUS',
'type' => 'enum',
'options' => 'campaign_status_dom',
'len' => 100,
'audited'=>true,
'comment' => 'Status of the campaign',
'importable' => 'required',
'required' => true,
),
'impressions' => array (
'name' => 'impressions',
'vname' => 'LBL_CAMPAIGN_IMPRESSIONS',
'type' => 'int',
'default'=>0,
'reportable'=>true,
'comment' => 'Expected Click throughs manually entered by Campaign Manager'
),
'currency_id' =>
array (
'name' => 'currency_id',
'vname' => 'LBL_CURRENCY',
'type' => 'id',
'group'=>'currency_id',
'function'=>array('name'=>'getCurrencyDropDown', 'returns'=>'html'),
'required'=>false,
'do_report'=>false,
'reportable'=>false,
'comment' => 'Currency in use for the campaign'
),
'budget' => array (
'name' => 'budget',
'vname' => 'LBL_CAMPAIGN_BUDGET',
'type' => 'currency',
'dbType' => 'double',
'comment' => 'Budgeted amount for the campaign'
),
'expected_cost' => array (
'name' => 'expected_cost',
'vname' => 'LBL_CAMPAIGN_EXPECTED_COST',
'type' => 'currency',
'dbType' => 'double',
'comment' => 'Expected cost of the campaign'
),
'actual_cost' => array (
'name' => 'actual_cost',
'vname' => 'LBL_CAMPAIGN_ACTUAL_COST',
'type' => 'currency',
'dbType' => 'double',
'comment' => 'Actual cost of the campaign'
),
'expected_revenue' => array (
'name' => 'expected_revenue',
'vname' => 'LBL_CAMPAIGN_EXPECTED_REVENUE',
'type' => 'currency',
'dbType' => 'double',
'comment' => 'Expected revenue stemming from the campaign'
),
'campaign_type' => array (
'name' => 'campaign_type',
'vname' => 'LBL_CAMPAIGN_TYPE',
'type' => 'enum',
'options' => 'campaign_type_dom',
'len' => 100,
'audited'=>true,
'comment' => 'The type of campaign',
'importable' => 'required',
'required' => true,
),
'objective' => array (
'name' => 'objective',
'vname' => 'LBL_CAMPAIGN_OBJECTIVE',
'type' => 'text',
'comment' => 'The objective of the campaign'
),
'content' => array (
'name' => 'content',
'vname' => 'LBL_CAMPAIGN_CONTENT',
'type' => 'text',
'comment' => 'The campaign description'
),
'prospectlists'=> array (
'name' => 'prospectlists',
'type' => 'link',
'relationship' => 'prospect_list_campaigns',
'source'=>'non-db',
),
'emailmarketing'=> array (
'name' => 'emailmarketing',
'type' => 'link',
'relationship' => 'campaign_email_marketing',
'source'=>'non-db',
),
'queueitems'=> array (
'name' => 'queueitems',
'type' => 'link',
'relationship' => 'campaign_emailman',
'source'=>'non-db',
),
'log_entries'=> array (
'name' => 'log_entries',
'type' => 'link',
'relationship' => 'campaign_campaignlog',
'source'=>'non-db',
'vname' => 'LBL_LOG_ENTRIES',
),
'tracked_urls' => array (
'name' => 'tracked_urls',
'type' => 'link',
'relationship' => 'campaign_campaigntrakers',
'source'=>'non-db',
'vname'=>'LBL_TRACKED_URLS',
),
'frequency' => array (
'name' => 'frequency',
'vname' => 'LBL_CAMPAIGN_FREQUENCY',
'type' => 'enum',
//'options' => 'campaign_status_dom',
'len' => 100,
'comment' => 'Frequency of the campaign',
'options' => 'newsletter_frequency_dom',
'len' => 100,
),
'leads'=> array (
'name' => 'leads',
'type' => 'link',
'relationship' => 'campaign_leads',
'source'=>'non-db',
'vname' => 'LBL_LEADS',
),
'opportunities'=> array (
'name' => 'opportunities',
'type' => 'link',
'relationship' => 'campaign_opportunities',
'source'=>'non-db',
'vname' => 'LBL_OPPORTUNITIES',
),
'contacts'=> array (
'name' => 'contacts',
'type' => 'link',
'relationship' => 'campaign_contacts',
'source'=>'non-db',
'vname' => 'LBL_CONTACTS',
),
'accounts'=> array (
'name' => 'accounts',
'type' => 'link',
'relationship' => 'campaign_accounts',
'source'=>'non-db',
'vname' => 'LBL_ACCOUNTS',
),
),
'indices' => array (
array (
'name' => 'camp_auto_tracker_key' ,
'type'=>'index' ,
'fields'=>array('tracker_key')
),
array (
'name' =>'idx_campaign_name',
'type' =>'index',
'fields'=>array('name')
),
),
'relationships' => array (
'campaign_accounts' => array('lhs_module'=> 'Campaigns', 'lhs_table'=> 'campaigns', 'lhs_key' => 'id',
'rhs_module'=> 'Accounts', 'rhs_table'=> 'accounts', 'rhs_key' => 'campaign_id',
'relationship_type'=>'one-to-many'),
'campaign_contacts' => array('lhs_module'=> 'Campaigns', 'lhs_table'=> 'campaigns', 'lhs_key' => 'id',
'rhs_module'=> 'Contacts', 'rhs_table'=> 'contacts', 'rhs_key' => 'campaign_id',
'relationship_type'=>'one-to-many'),
'campaign_leads' => array('lhs_module'=> 'Campaigns', 'lhs_table'=> 'campaigns', 'lhs_key' => 'id',
'rhs_module'=> 'Leads', 'rhs_table'=> 'leads', 'rhs_key' => 'campaign_id',
'relationship_type'=>'one-to-many'),
'campaign_prospects' => array('lhs_module'=> 'Campaigns', 'lhs_table'=> 'campaigns', 'lhs_key' => 'id',
'rhs_module'=> 'Prospects', 'rhs_table'=> 'prospects', 'rhs_key' => 'campaign_id',
'relationship_type'=>'one-to-many'),
'campaign_opportunities' => array('lhs_module'=> 'Campaigns', 'lhs_table'=> 'campaigns', 'lhs_key' => 'id',
'rhs_module'=> 'Opportunities', 'rhs_table'=> 'opportunities', 'rhs_key' => 'campaign_id',
'relationship_type'=>'one-to-many'),
'campaign_email_marketing' => array('lhs_module'=> 'Campaigns', 'lhs_table'=> 'campaigns', 'lhs_key' => 'id',
'rhs_module'=> 'EmailMarketing', 'rhs_table'=> 'email_marketing', 'rhs_key' => 'campaign_id',
'relationship_type'=>'one-to-many'),
'campaign_emailman' => array('lhs_module'=> 'Campaigns', 'lhs_table'=> 'campaigns', 'lhs_key' => 'id',
'rhs_module'=> 'EmailMan', 'rhs_table'=> 'emailman', 'rhs_key' => 'campaign_id',
'relationship_type'=>'one-to-many'),
'campaign_campaignlog' => array('lhs_module'=> 'Campaigns', 'lhs_table'=> 'campaigns', 'lhs_key' => 'id',
'rhs_module'=> 'CampaignLog', 'rhs_table'=> 'campaign_log', 'rhs_key' => 'campaign_id',
'relationship_type'=>'one-to-many'),
'campaign_assigned_user' => array('lhs_module'=> 'Users', 'lhs_table'=> 'users', 'lhs_key' => 'id',
'rhs_module'=> 'Campaigns', 'rhs_table'=> 'campaigns', 'rhs_key' => 'assigned_user_id',
'relationship_type'=>'one-to-many'),
'campaign_modified_user' => array('lhs_module'=> 'Users', 'lhs_table'=> 'users', 'lhs_key' => 'id',
'rhs_module'=> 'Campaigns', 'rhs_table'=> 'campaigns', 'rhs_key' => 'modified_user_id',
'relationship_type'=>'one-to-many'),
)
);
VardefManager::createVardef('Campaigns','Campaign', array('default', 'assignable',
'team_security',
));
?> | harish-patel/ecrm | modules/Campaigns/vardefs.php | PHP | agpl-3.0 | 11,710 |
/*
* This program is part of the ForLAB software.
* Copyright © 2010 Clinton Health Access Initiative(CHAI)
*
* The ForLAB software was made possible in part through the support of the President's Emergency Plan for AIDS Relief (PEPFAR) through the U.S. Agency for International Development (USAID) under the Supply Chain Management System (SCMS) Project CONTRACT # GPO-1-00-05-00032-00; CFDA/AWARD# 98.001.
*
* The U.S. Government is not liable for any disclosure, use, or reproduction of the ForLAB software.
*
*/
namespace LQT.GUI.MorbidityUserCtr
{
partial class FrmImportCPN
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtFilename = new System.Windows.Forms.TextBox();
this.butSave = new System.Windows.Forms.Button();
this.lvImport = new System.Windows.Forms.ListView();
this.colNo = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colRegion = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colSite = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader12 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader13 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader6 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader7 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader8 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader9 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader10 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader11 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.butImport = new System.Windows.Forms.Button();
this.butBrowse = new System.Windows.Forms.Button();
this.panel2 = new System.Windows.Forms.Panel();
this.butClear = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// txtFilename
//
this.txtFilename.BackColor = System.Drawing.SystemColors.ButtonHighlight;
this.txtFilename.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtFilename.Location = new System.Drawing.Point(7, 10);
this.txtFilename.MinimumSize = new System.Drawing.Size(250, 25);
this.txtFilename.Name = "txtFilename";
this.txtFilename.ReadOnly = true;
this.txtFilename.Size = new System.Drawing.Size(472, 20);
this.txtFilename.TabIndex = 0;
this.txtFilename.WordWrap = false;
//
// butSave
//
this.butSave.Enabled = false;
this.butSave.Location = new System.Drawing.Point(830, 6);
this.butSave.Name = "butSave";
this.butSave.Size = new System.Drawing.Size(65, 30);
this.butSave.TabIndex = 4;
this.butSave.Text = "Save";
this.butSave.UseVisualStyleBackColor = true;
this.butSave.Click += new System.EventHandler(this.butSave_Click);
//
// lvImport
//
this.lvImport.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colNo,
this.colRegion,
this.colSite,
this.columnHeader4,
this.columnHeader3,
this.columnHeader12,
this.columnHeader13,
this.columnHeader5,
this.columnHeader6,
this.columnHeader7,
this.columnHeader8,
this.columnHeader9,
this.columnHeader10,
this.columnHeader11,
this.columnHeader1,
this.columnHeader2});
this.lvImport.Dock = System.Windows.Forms.DockStyle.Fill;
this.lvImport.FullRowSelect = true;
this.lvImport.GridLines = true;
this.lvImport.Location = new System.Drawing.Point(0, 44);
this.lvImport.Name = "lvImport";
this.lvImport.Size = new System.Drawing.Size(941, 528);
this.lvImport.TabIndex = 5;
this.lvImport.UseCompatibleStateImageBehavior = false;
this.lvImport.View = System.Windows.Forms.View.Details;
//
// colNo
//
this.colNo.Text = "No";
this.colNo.Width = 27;
//
// colRegion
//
this.colRegion.Text = "Category/Region";
this.colRegion.Width = 112;
//
// colSite
//
this.colSite.Text = "ART Sites";
this.colSite.Width = 124;
//
// columnHeader4
//
this.columnHeader4.Text = "CURRENT P.T";
this.columnHeader4.Width = 96;
//
// columnHeader3
//
this.columnHeader3.Text = "CURRENT P.Pre-T";
this.columnHeader3.Width = 115;
//
// columnHeader12
//
this.columnHeader12.Text = "EVER STARTED P.T";
this.columnHeader12.Width = 123;
//
// columnHeader13
//
this.columnHeader13.Text = "EVER STARTED P.Pre-T";
this.columnHeader13.Width = 140;
//
// columnHeader5
//
this.columnHeader5.Text = "VCT";
this.columnHeader5.Width = 34;
//
// columnHeader6
//
this.columnHeader6.Text = "CD4";
this.columnHeader6.Width = 34;
//
// columnHeader7
//
this.columnHeader7.Text = "Chemistry";
this.columnHeader7.Width = 58;
//
// columnHeader8
//
this.columnHeader8.Text = "Hematology";
this.columnHeader8.Width = 76;
//
// columnHeader9
//
this.columnHeader9.Text = "Viral Load";
this.columnHeader9.Width = 65;
//
// columnHeader10
//
this.columnHeader10.Text = "Other Tests";
this.columnHeader10.Width = 69;
//
// columnHeader11
//
this.columnHeader11.Text = "Consummables";
this.columnHeader11.Width = 91;
//
// columnHeader1
//
this.columnHeader1.Text = "Exist";
this.columnHeader1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.columnHeader1.Width = 47;
//
// columnHeader2
//
this.columnHeader2.Text = "Remarks";
this.columnHeader2.Width = 172;
//
// butImport
//
this.butImport.Location = new System.Drawing.Point(553, 6);
this.butImport.Name = "butImport";
this.butImport.Size = new System.Drawing.Size(61, 30);
this.butImport.TabIndex = 2;
this.butImport.Text = "Import";
this.butImport.UseVisualStyleBackColor = true;
this.butImport.Click += new System.EventHandler(this.butImport_Click);
//
// butBrowse
//
this.butBrowse.Location = new System.Drawing.Point(482, 6);
this.butBrowse.Name = "butBrowse";
this.butBrowse.Size = new System.Drawing.Size(61, 30);
this.butBrowse.TabIndex = 1;
this.butBrowse.Text = "Browse...";
this.butBrowse.UseVisualStyleBackColor = true;
this.butBrowse.Click += new System.EventHandler(this.butBrowse_Click);
//
// panel2
//
this.panel2.Controls.Add(this.butClear);
this.panel2.Controls.Add(this.txtFilename);
this.panel2.Controls.Add(this.butSave);
this.panel2.Controls.Add(this.butImport);
this.panel2.Controls.Add(this.butBrowse);
this.panel2.Dock = System.Windows.Forms.DockStyle.Top;
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(941, 44);
this.panel2.TabIndex = 35;
//
// butClear
//
this.butClear.Enabled = false;
this.butClear.Location = new System.Drawing.Point(624, 6);
this.butClear.Name = "butClear";
this.butClear.Size = new System.Drawing.Size(61, 30);
this.butClear.TabIndex = 3;
this.butClear.Text = "Clear";
this.butClear.UseVisualStyleBackColor = true;
this.butClear.Click += new System.EventHandler(this.butClear_Click);
//
// openFileDialog1
//
this.openFileDialog1.DefaultExt = "xls";
this.openFileDialog1.Filter = "Excel files|*.xls";
//
// FrmImportCPN
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(941, 572);
this.Controls.Add(this.lvImport);
this.Controls.Add(this.panel2);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MinimizeBox = false;
this.Name = "FrmImportCPN";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Import Current Patient Numbers, EVER STARTED Patient Numbers and Forecast supply " +
"for the site";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TextBox txtFilename;
private System.Windows.Forms.Button butSave;
private System.Windows.Forms.ListView lvImport;
private System.Windows.Forms.ColumnHeader colNo;
private System.Windows.Forms.ColumnHeader colRegion;
private System.Windows.Forms.ColumnHeader colSite;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.Button butImport;
private System.Windows.Forms.Button butBrowse;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Button butClear;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.ColumnHeader columnHeader5;
private System.Windows.Forms.ColumnHeader columnHeader6;
private System.Windows.Forms.ColumnHeader columnHeader7;
private System.Windows.Forms.ColumnHeader columnHeader8;
private System.Windows.Forms.ColumnHeader columnHeader9;
private System.Windows.Forms.ColumnHeader columnHeader10;
private System.Windows.Forms.ColumnHeader columnHeader11;
private System.Windows.Forms.ColumnHeader columnHeader12;
private System.Windows.Forms.ColumnHeader columnHeader13;
}
}
| forlab/ForLAB | LQT.GUI/MorbidityUserCtr/FrmImportCPN.Designer.cs | C# | agpl-3.0 | 13,431 |
/*
* Copyright (c) 2014 Villu Ruusmann
*
* This file is part of JPMML-Evaluator
*
* JPMML-Evaluator is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JPMML-Evaluator 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with JPMML-Evaluator. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpmml.evaluator.regression;
import java.util.Map;
import org.jpmml.evaluator.Deltas;
import org.jpmml.evaluator.ModelEvaluator;
import org.jpmml.evaluator.ModelEvaluatorTest;
import org.jpmml.evaluator.ProbabilityDistribution;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class EmptyTargetCategoryTest extends ModelEvaluatorTest implements Deltas {
@Test
public void evaluate() throws Exception {
ModelEvaluator<?> evaluator = createModelEvaluator();
Map<String, ?> arguments = createArguments("x1", 3d, "x2", 3d);
Map<String, ?> results = evaluator.evaluate(arguments);
ProbabilityDistribution<?> targetValue = (ProbabilityDistribution<?>)results.get(evaluator.getTargetName());
assertEquals("yes", targetValue.getResult());
double value = (3d * -28.6617384d + 3d * -20.42027426d + 125.56601826d);
assertEquals(Math.exp(0d) / (Math.exp(0d) + Math.exp(value)), targetValue.getProbability("yes"), DOUBLE_EXACT);
assertEquals(Math.exp(value) / (Math.exp(0d) + Math.exp(value)), targetValue.getProbability("no"), DOUBLE_EXACT);
assertNull(targetValue.getPredictionReport());
}
} | jpmml/jpmml-evaluator | pmml-evaluator/src/test/java/org/jpmml/evaluator/regression/EmptyTargetCategoryTest.java | Java | agpl-3.0 | 1,959 |
/*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Top-level react component for editing MediaWiki documents
*/
import { createEditor } from "../frame-tree/editor";
import { aux_file } from "../frame-tree/util";
import { set } from "smc-util/misc2";
import { IFrameHTML } from "../html-editor/iframe-html";
import { CodemirrorEditor } from "../code-editor/codemirror-editor";
import { SETTINGS_SPEC } from "../settings/editor";
import { terminal } from "../terminal-editor/editor";
import { time_travel } from "../time-travel-editor/editor";
const EDITOR_SPEC = {
cm: {
short: "Code",
name: "Source Code",
icon: "code",
component: CodemirrorEditor,
buttons: set([
"print",
"decrease_font_size",
"increase_font_size",
"save",
"time_travel",
"replace",
"find",
"goto_line",
"cut",
"paste",
"copy",
"undo",
"redo",
"reload",
]),
},
html: {
short: "HTML",
name: "Rendered HTML (pandoc)",
icon: "html5",
component: IFrameHTML,
buttons: set([
"print",
"decrease_font_size",
"increase_font_size",
"save",
"time_travel",
"reload",
]),
path(path) {
return aux_file(path, "html");
},
fullscreen_style: {
// set via jquery
"max-width": "900px",
margin: "auto",
},
},
terminal,
settings: SETTINGS_SPEC,
time_travel,
};
export const Editor = createEditor({
format_bar: true,
editor_spec: EDITOR_SPEC,
display_name: "WikiEditor",
});
| tscholl2/smc | src/smc-webapp/frame-editors/wiki-editor/editor.ts | TypeScript | agpl-3.0 | 1,654 |
<?php /* Smarty version Smarty-3.1.12, created on 2015-11-10 01:10:50
compiled from "/home/gam/themes/Backend/ExtJs/backend/base/component/Shopware.DragAndDropSelector.js" */ ?>
<?php /*%%SmartyHeaderCode:16345463015641360a29c610-70602129%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'509b22d314bafb4e224fdd533479988e42d56279' =>
array (
0 => '/home/gam/themes/Backend/ExtJs/backend/base/component/Shopware.DragAndDropSelector.js',
1 => 1445520152,
2 => 'file',
),
),
'nocache_hash' => '16345463015641360a29c610-70602129',
'function' =>
array (
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.12',
'unifunc' => 'content_5641360a2f2bb6_85489887',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_5641360a2f2bb6_85489887')) {function content_5641360a2f2bb6_85489887($_smarty_tpl) {?>/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* 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 Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*
* @category Shopware
* @package Base
* @subpackage Component
* @version $Id$
* @author shopware AG
*/
/**
* Shopware UI - DragAndDropSelector Panel
*
* todo@all: Documentation
*
*
* @example
* Ext.create('Shopware.panel.DragAndDropSelector', {
* name: 'supplierIds',
* fromTitle: 'Supplier Available',
* toTitle: 'Supplier Chosen',
* fromStore:this.supplierStore,
* buttons:[ 'add','remove' ],
* gridHeight: 270,
* selectedItems: me.getStore('Something'),
* buttonsText: {
* add: "Add",
* remove: "Remove"
* }
* });
*/
Ext.define('Shopware.DragAndDropSelector',
{
/**
* Based on Ext.panel.Panel
*/
extend:'Ext.container.Container',
/**
* List of short aliases for class names. Most useful for defining xtypes for widgets
* @array
*/
alias: [ 'widget.draganddropselector', 'widget.ddselector' ],
/**
* From-Store which holds the Available Data
*
* @default null
* @object
*/
fromStore: null,
/**
* To-Store which holds the Selected Data
*
* @default null
* @object
*/
toStore: null,
/**
* Grid on the left side
*
* @default null
* @object
*/
fromField: null,
/**
* DockedItems for the grid on the left side
*
* @default null
* @object
*/
fromFieldDockedItems: null,
/**
* Grid on the right side
*
* @default null
* @object
*/
toField: null,
/**
* DockedItems for the grid on the right side
*
* @default null
* @object
*/
toFieldDockedItems: null,
/**
* Recordset with all selected items
*
* @default null
* @object
*/
selectedItems: null,
/**
* FromTitle which holds Title on the Left Side
*
* @string
*/
fromTitle: '',
/**
* toTitle which holds Title on the Right Side
*
* @string
*/
toTitle: '',
/**
* default columns for the from grid
*/
fromColumns :[{
text: 'name',
flex: 1,
dataIndex: 'name'
}],
/**
* default columns for the to grid
*/
toColumns :[{
text: 'name',
flex: 1,
dataIndex: 'name'
}],
/**
* hides the header of the grids
*/
hideHeaders: true,
/**
* height of the grid panel
*
* @integer
*/
gridHeight: null,
/**
* standard layout
*/
layout:{
type:'hbox',
align: 'stretch'
},
/**
* available buttons
*
* @object
*/
buttons: ['top', 'up', 'add', 'remove', 'down', 'bottom'],
/**
* default button texts
*
* @object
*/
buttonsText: {
top: "Move to Top",
up: "Move Up",
add: "Add to Selected",
remove: "Remove from Selected",
down: "Move Down",
bottom: "Move to Bottom"
},
/**
* Init the component
*/
initComponent : function() {
var me = this;
me.toStore = me.selectedItems;
//to set the usedIds to the store
me.refreshStore();
me.fromStore.load();
me.fromField = me.createGrid({
title: me.fromTitle,
store: me.fromStore,
columns :me.fromColumns,
dockedItems: me.fromFieldDockedItems,
border: false,
viewConfig: {
plugins: {
ptype: 'gridviewdragdrop',
dragGroup: 'firstGridDDGroup',
dropGroup: 'secondGridDDGroup'
},
listeners: {
drop: function() {
me.refreshStore();
}
}
}
});
me.toField = me.createGrid({
title : me.toTitle,
store : me.toStore,
columns : me.toColumns,
dockedItems: me.toFieldDockedItems,
border: false,
viewConfig: {
plugins: {
ptype: 'gridviewdragdrop',
dragGroup: 'secondGridDDGroup',
dropGroup: 'firstGridDDGroup'
},
listeners: {
drop: function() {
me.refreshStore();
}
}
}
});
// Create the view
me.items = [
me.fromField,
me.getMiddleButtons(),
me.toField
];
me.callParent(arguments);
},
/**
* The two grids are separated by a container which contains to buttons.
* One button is used to move the selection from the left side to the right side and the second button does this vice-versa.
*
* @return Ext.container.Container
*/
getMiddleButtons : function() {
var me = this;
return Ext.create('Ext.container.Container',{
margins: '0 4',
width: 22,
layout: {
type: 'vbox',
pack: 'center'
},
items: me.createButtons()
});
},
/**
* Creates all adjusted buttons
*
* @return Ext.Button
*/
createButtons: function(){
var me = this,
buttons = [];
Ext.Array.forEach(me.buttons, function(name) {
var button = Ext.create('Ext.Button', {
tooltip: me.buttonsText[name],
cls: Ext.baseCSSPrefix + 'form-itemselector-btn',
iconCls: Ext.baseCSSPrefix + 'form-itemselector-' + name,
navBtn: true,
margin: '4 0 0 0'
});
button.addListener('click', me['on' + Ext.String.capitalize(name) + 'BtnClick'], me);
buttons.push(button);
});
return buttons;
},
/**
* Creates a grid with the adjusted config
*
* @return Ext.grid.Panel
*/
createGrid: function(config) {
var me = this;
var defaultConfig = {
stripeRows : true,
multiSelect: true,
hideHeaders: me.hideHeaders,
height: me.gridHeight,
flex: 1
};
defaultConfig = Ext.apply(defaultConfig, config);
var gridPanel = Ext.create('Ext.grid.Panel', defaultConfig);
gridPanel.addListener('itemdblclick', me.onItemDblClick, me);
return gridPanel;
},
/**
* Event listener on item double click
* Moves the selected Items from grid to grid
*
* @param view
* @param rec
*/
onItemDblClick: function(view, rec){
var me = this,
from = me.fromStore,
to = me.toStore,
current,
destination;
if (view.store === me.fromField.store) {
current = from;
destination = to;
} else {
current = to;
destination = from;
}
current.remove(rec);
destination.add(rec);
me.refreshStore();
},
/**
* Event listener on add button click
* Moves the selected Items from grid to grid
*/
onAddBtnClick : function() {
var me = this,
fromList = me.fromField,
selected = this.getSelections(fromList);
//performance fix because ext js is slow in removing single things
var storeItems = me.fromStore.data.items;
me.fromStore.removeAll();
//storeItems contains now an array of Ext.data.Model
storeItems = me.fastRemoveStoreItems(storeItems, selected);
me.fromStore.add(storeItems);
me.toStore.add(selected);
me.refreshStore();
},
/**
* Event listener on Remove button click
* Moves the selected Items from grid to grid
*/
onRemoveBtnClick : function() {
var me = this,
toList = me.toField,
selected = me.getSelections(toList);
//performance fix because ext js is slow in removing single things
var storeItems = me.toStore.data.items;
me.toStore.removeAll();
//storeItems contains now an array of Ext.data.Model
storeItems = me.fastRemoveStoreItems(storeItems, selected);
me.toStore.add(storeItems);
me.fromStore.add(selected);
me.refreshStore();
},
/**
* Returns the selected Items
*
* @return Ext.Array
*/
getSelections: function(list){
var store = list.getStore(),
selections = list.getSelectionModel().getSelection();
return Ext.Array.sort(selections, function(a, b){
a = store.indexOf(a);
b = store.indexOf(b);
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
});
},
/**
* Refreshes the Store so send the latest selected items with the search
*/
refreshStore: function() {
var me = this,
ids = [];
if(me.toStore != null) {
me.selectedItems = me.toStore;
}
if(me.selectedItems != null){
me.selectedItems.each(function(element) {
ids.push(element.get('id'));
});
}
me.fromStore.getProxy().extraParams = {
'usedIds[]': ids
};
},
/**
* removes the selectedItems from the storeItems
*/
fastRemoveStoreItems: function(storeItems, selected) {
var toRemove = [];
//performance fix because ext js is slow in removing single things
for(var i in storeItems) {
var select = storeItems[i];
Ext.each(selected, function(item) {
if(select.get('id') === item.get('id')) {
toRemove.unshift(i);
}
});
}
Ext.each(toRemove, function(index) {
Ext.Array.erase(storeItems, index, 1);
});
return storeItems;
},
/**
* Destroys the DragAndDropSelector panel
*
* @public
* @return void
*/
destroy: function() {
this.fromStore = null;
Ext.destroyMembers(this, 'fromField', 'toField');
this.callParent();
}
});
<?php }} ?> | gamchantoi/AgroSHop-UTUAWARDS | var/cache/production_201510221322/templates/backend_en_GB_a0ba8/50/9b/22/509b22d314bafb4e224fdd533479988e42d56279.snippet.Shopware.DragAndDropSelector.js.php | PHP | agpl-3.0 | 12,293 |
var mongoose = require('mongoose');
var es = require('event-stream');
var config = require('../lib/config/config');
var _ = require('lodash');
require('../lib/config/mongoose')(mongoose, config);
var Situation = mongoose.model('Situation');
Situation.find({ status: 'test' }).stream()
.pipe(es.map(function (situation, done) {
var isSituationUpdated = false;
hasConjoint = _.find(situation.individus, { role: 'conjoint' });
hasEnfant = _.find(situation.individus, { role: 'enfant' });
if (hasEnfant && ! hasConjoint) {
situation.individus[0].isolementRecent = true;
isSituationUpdated = true;
}
situation.save(function (err) {
if (err) {
console.log('Cannot save migrated situation %s', situation.id);
console.trace(err);
}
else if (isSituationUpdated)
console.log('Situation migrée');
done();
});
}))
.on('end', function() {
console.log('Terminé');
process.exit();
})
.on('error', function(err) {
console.trace(err);
process.exit();
})
.resume();
| sgmap/mes-aides-api | migrations/rsa-isolement.js | JavaScript | agpl-3.0 | 1,192 |
# == Schema Information
#
# Table name: homepages
#
# id :integer not null, primary key
# movement_id :integer
# draft :boolean default(FALSE)
#
class Homepage < ActiveRecord::Base
include ActsAsClickableFromEmail
belongs_to :movement
has_many :homepage_contents, dependent: :destroy
has_many :featured_content_collections, as: :featurable, dependent: :destroy
has_many :featured_content_modules, through: :featured_content_collections
class << self
def clean_drafts!
Homepage.where(draft: true).find_in_batches {|grp| grp.each{|homepage| homepage.destroy}}
end
end
def duplicate_for_preview(attrs = {})
config = {include: [:homepage_contents, {featured_content_collections: [:featured_content_modules]}]}
self.dup(config) do |original, clone|
clone.assign_attributes(attrs[:homepage_content][clone.iso_code]) if clone.is_a?(HomepageContent) && attrs[:homepage_content]
clone.assign_attributes(attrs[:featured_content_modules][original.id]) if clone.is_a?(FeaturedContentModule) && attrs[:featured_content_modules]
end.tap{|cloned_homepage| cloned_homepage.update_attributes(draft: true)}
end
def build_content_for_all_languages
movement.languages.collect { |l| build_content(l) }
end
def build_content(language)
homepage_contents.find_or_initialize_by_language_id(language.id)
end
def name
'Homepage'
end
end
| PurposeOpen/Platform | app/models/homepage.rb | Ruby | agpl-3.0 | 1,433 |
/*
* Copyright 2017 the Isard-vdi project authors:
* Josep Maria Viñolas Auquer
* Alberto Larraz Dalmases
* License: AGPLv3
*/
var href = location.href;
url=href.match(/([^\/]*)\/*$/)[1];
if (url!="Desktops") {
kind='template'
} else {
$('#global_actions').css('display','block');
kind='desktop'
}
columns= [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": '<button class="btn btn-xs btn-info" type="button" data-placement="top" ><i class="fa fa-plus"></i></button>'
},
{ "data": "icon" },
{ "data": "server", "width": "10px"},
{ "data": "hyp_started", "width": "100px"},
{ "data": "name"},
{ "data": "description"},
{ "data": null},
{ "data": "status"},
{ "data": "username"},
{ "data": "category"},
{ "data": "group"},
{ "data": "accessed",
'defaultContent': ''},
{
"className": 'text-center',
"data": null,
"orderable": false,
"defaultContent": '<input type="checkbox" class="form-check-input"></input>'
}
]
columnDefs = [
{
"targets": 1,
"render": function ( data, type, full, meta ) {
url = location.protocol+'//' + document.domain + ':' + location.port + full.image.url
return "<img src='"+url+"' width='50px'>"
}
},{
"targets": 2,
"render": function (data, type, full, meta) {
if('server' in full['create_dict']){
return full['create_dict']['server']
}else{
return false;
}
}
},{
"targets": 3,
"render": function (data, type, full, meta) {
return renderHypStarted(full)
}
},{
"targets": 6,
"width": "100px",
"render": function (data, type, full, meta) {
return renderAction(full) + renderDisplay(full)
}
},{
"targets": 7,
"render": function (data, type, full, meta) {
return renderStatus(full)
}
},{
"targets": 11,
"render": function (data, type, full, meta) {
if ( type === 'display' || type === 'filter' ) {
return moment.unix(full.accessed).fromNow()
}
return full.accessed
}
}
]
if(url!="Desktops"){
columns.splice(12, 1)
columns.splice(
11,
0,
{
"data": 'enabled',
"className": 'text-center',
"data": null,
"orderable": false,
"defaultContent": '<input type="checkbox" class="form-check-input" checked></input>'
},
{"data": "derivates"},
{"defaultContent": '<button id="btn-alloweds" class="btn btn-xs" type="button" data-placement="top" ><i class="fa fa-users" style="color:darkblue"></i></button>'},
);
columns.splice(6, 2)
columnDefs.splice(3, 2)
columnDefs[3]["targets"]=12
columnDefs[4]={
"targets": 9,
"render": function ( data, type, full, meta ) {
if( full.enabled ){
return '<input id="chk-enabled" type="checkbox" class="form-check-input" checked></input>'
}else{
return '<input id="chk-enabled" type="checkbox" class="form-check-input"></input>'
}
}
}
}
$(document).ready(function() {
$('.admin-status').show()
$template_domain = $(".template-detail-domain");
$admin_template_domain = $(".admin-template-detail-domain");
var stopping_timer=null
modal_add_desktops = $('#modal_add_desktops').DataTable()
initalize_modal_all_desktops_events()
$('.btn-add-desktop').on('click', function () {
$('#allowed-title').html('')
$('#alloweds_panel').css('display','block');
setAlloweds_add('#alloweds-block');
if ($('meta[id=user_data]').attr('data-role') == 'manager'){
$('#categories_pannel').hide();
$('#roles_pannel').hide();
}
$("#modalAddDesktop #send-block").unbind('click');
$("#modalAddDesktop #send-block").on('click', function(e){
var form = $('#modalAdd');
form.parsley().validate();
if (form.parsley().isValid()){
template=$('#modalAddDesktop #template').val();
if (template !=''){
data=$('#modalAdd').serializeObject();
data=replaceAlloweds_arrays('#modalAddDesktop #alloweds-block',data)
socket.emit('domain_add',data)
}else{
$('#modal_add_desktops').closest('.x_panel').addClass('datatables-error');
$('#modalAddDesktop #datatables-error-status').html('No template selected').addClass('my-error');
}
}
});
if($('.limits-desktops-bar').attr('aria-valuenow') >=100){
new PNotify({
title: "Quota for creating desktops full.",
text: "Can't create another desktop, category quota full.",
hide: true,
delay: 3000,
icon: 'fa fa-alert-sign',
opacity: 1,
type: 'error'
});
}else{
setHardwareOptions('#modalAddDesktop');
$("#modalAdd")[0].reset();
$('#modalAddDesktop').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
$('#modalAddDesktop #hardware-block').hide();
$('#modalAdd').parsley();
modal_add_desktop_datatables();
}
});
$("#modalTemplateDesktop #send").on('click', function(e){
var form = $('#modalTemplateDesktopForm');
form.parsley().validate();
if (form.parsley().isValid()){
desktop_id=$('#modalTemplateDesktopForm #id').val();
if (desktop_id !=''){
data=$('#modalTemplateDesktopForm').serializeObject();
data=replaceMedia_arrays('#modalTemplateDesktopForm',data);
data=replaceAlloweds_arrays('#modalTemplateDesktopForm #alloweds-add',data)
socket.emit('domain_template_add',data)
}else{
$('#modal_add_desktops').closest('.x_panel').addClass('datatables-error');
$('#modalAddDesktop #datatables-error-status').html('No template selected').addClass('my-error');
}
}
});
$("#modalDeleteTemplate #send").on('click', function(e){
selected = $("#modalDeleteTemplate .tree_template_delete").fancytree('getTree').getSelectedNodes();
todelete = []
selected.forEach(function (item) {
todelete.push({"id":item.data.id, "title":item.title, "kind":item.data.kind, "status":item.data.status})
});
//id=$('#modalDeleteTemplate #id').val();
api.ajax('/isard-admin/admin/items/delete','POST',todelete).done(function(data) {
data=JSON.parse(data);
if( data == true ){
new PNotify({
title: "Deleting",
text: "Deleting all templates and desktops",
hide: true,
delay: 4000,
icon: 'fa fa-success',
opacity: 1,
type: 'success'
});
}else{
new PNotify({
title: "Error deleting",
text: "Unable to delete templates and desktops: "+data,
hide: true,
delay: 4000,
icon: 'fa fa-warning',
opacity: 1,
type: 'error'
});
}
domains_table.ajax.reload()
$("#modalDeleteTemplate").modal('hide');
});
});
// Setup - add a text input to each footer cell
$('#domains tfoot th').each( function () {
var title = $(this).text();
if (['','Icon','Hypervisor','Action', 'Enabled'].indexOf(title) == -1){
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
}
} );
domains_table= $('#domains').DataTable({
"ajax": {
"url": "/admin/domains",
"type": "GET",
"dataSrc":'',
"data": { 'kind': kind }
},
"language": {
"loadingRecords": '<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading...</span>'
},
"rowId": "id",
"deferRender": true,
"columns": columns,
"order": [[7, 'asc']],
"columnDefs": columnDefs,
"rowCallback": function (row, data) {
if('server' in data['create_dict']){
if(data['create_dict']['server'] == true){
$(row).css("background-color", "#f7eac6");
}else{
$(row).css("background-color", "#ffffff");
}
}
}
} );
// Apply the search
domains_table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
domains_table.on( 'click', 'tr', function () {
if (kind =='desktop') {
$(this).toggleClass('active');
if ($(this).hasClass('active')) {
$(this).find('input').prop('checked', true);
} else {
$(this).find('input').prop('checked', false);
}
}
} );
$('#mactions').on('change', function () {
action=$(this).val();
names=''
ids=[]
if(domains_table.rows('.active').data().length){
$.each(domains_table.rows('.active').data(),function(key, value){
names+=value['name']+'\n';
ids.push(value['id']);
});
var text = "You are about to "+action+" these desktops:\n\n "+names
}else{
$.each(domains_table.rows({filter: 'applied'}).data(),function(key, value){
ids.push(value['id']);
});
var text = "You are about to "+action+" "+domains_table.rows({filter: 'applied'}).data().length+" desktops!\n All the desktops in list!"
}
new PNotify({
title: 'Warning!',
text: text,
hide: false,
opacity: 0.9,
confirm: {
confirm: true
},
buttons: {
closer: false,
sticker: false
},
history: {
history: false
},
addclass: 'pnotify-center'
}).get().on('pnotify.confirm', function() {
api.ajax(
'/isard-admin/admin/mdomains',
'POST',
{'ids': ids, 'action': action}
).done(function(data) {
notify(data)
}).fail(function(jqXHR) {
notify(jqXHR.responseJSON)
}).always(function() {
$('#mactions option[value="none"]').prop("selected", true);
})
}).on('pnotify.cancel', function() {
$('#mactions option[value="none"]').prop("selected",true);
});
} );
$('#domains').find('tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = domains_table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Close other rows
if ( domains_table.row( '.shown' ).length ) {
$('.details-control', domains_table.row( '.shown' ).node()).click();
}
if (row.data().status=='Creating'){
//In this case better not to open detail as ajax snippets will fail
//Maybe needs to be blocked also on other -ing's
new PNotify({
title: "Domain is being created",
text: "Wait till domain ["+row.data().name+"] creation completes to view details",
hide: true,
delay: 3000,
icon: 'fa fa-alert-sign',
opacity: 1,
type: 'error'
});
}else{
// Open this row
row.child( addDomainDetailPannel(row.data()) ).show();
tr.addClass('shown');
$('#status-detail-'+row.data().id).html(row.data().detail);
actionsDomainDetail();
setDomainDetailButtonsStatus(row.data().id,row.data().status)
//if(row.data().status=='Stopped' || row.data().status=='Started' || row.data().status=='Failed'){
//~ setDomainGenealogy(row.data().id);
setDomainHotplug(row.data().id, row.data());
setHardwareDomainDefaults_viewer('#hardware-'+row.data().id,row.data());
if(url!="Desktops"){
setAlloweds_viewer('#alloweds-'+row.data().id,row.data().id);
//~ setDomainDerivates(row.data().id);
}
//}
}
}
} );
$('#domains').find(' tbody').on( 'click', 'input', function () {
var pk=domains_table.row( $(this).parents('tr') ).id();
switch($(this).attr('id')){
case 'chk-enabled':
if ($(this).is(":checked")){
enabled=true
}else{
enabled=false
}
api.ajax('/isard-admin/template',
'PUT',
{'id':pk,
'enabled':enabled})
.fail(function(jqXHR) {
new PNotify({
title: "Template enable/disable",
text: "Could not update!",
hide: true,
delay: 3000,
icon: 'fa fa-alert-sign',
opacity: 1,
type: 'error'
});
domains_table.ajax.reload()
});
break;
}
})
// DataTable buttons
$('#domains tbody').on( 'click', 'button', function () {
var data = domains_table.row( $(this).parents('tr') ).data();
switch($(this).attr('id')){
case 'btn-play':
if($('.quota-play .perc').text() >=100){
new PNotify({
title: "Quota for running desktops full.",
text: "Can't start another desktop, quota full.",
hide: true,
delay: 3000,
icon: 'fa fa-alert-sign',
opacity: 1,
type: 'error'
});
}else{
socket.emit('domain_update',{'pk':data['id'],'name':'status','value':'Starting'})
//~ api.ajax('/isard-admin/domains/update','POST',{'pk':data['id'],'name':'status','value':'Starting'}).done(function(data) {
//~ });
}
break;
case 'btn-stop':
if(data['status']=='Shutting-down'){
socket.emit('domain_update',{'pk':data['id'],'name':'status','value':'Stopping'})
}else{
socket.emit('domain_update',{'pk':data['id'],'name':'status','value':'Shutting-down'})
}
break;
case 'btn-display':
new PNotify({
title: 'Connect to user viewer!',
text: "By connecting to desktop "+ name+" you will disconnect and gain access to that user current desktop.\n\n \
Please, think twice before doing this as it could be illegal depending on your relation with the user. \n\n ",
hide: false,
opacity: 0.9,
confirm: {
confirm: true
},
buttons: {
closer: false,
sticker: false
},
history: {
history: false
},
addclass: 'pnotify-center'
}).get().on('pnotify.confirm', function() {
setViewerButtons(data,socket);
if('viewer' in data && 'guest_ip' in data['viewer']){
viewerButtonsIP(data['viewer']['guest_ip'])
}
$('#modalOpenViewer').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
}).on('pnotify.cancel', function() {
});
break;
case 'btn-alloweds':
modalAllowedsFormShow('domains',data)
break;
}
});
// SocketIO
socket = io.connect(location.protocol+'//' + document.domain + ':' + location.port+'/isard-admin/sio_admins', {
'path': '/isard-admin/socket.io/',
'transports': ['websocket']
});
socket.on('connect', function() {
connection_done();
socket.emit('join_rooms',['domains'])
console.log('Listening admins namespace');
});
socket.on('connect_error', function(data) {
connection_lost();
});
startClientVpnSocket(socket)
socket.on('user_quota', function(data) {
console.log('Quota update')
var data = JSON.parse(data);
drawUserQuota(data);
});
socket.on(kind+'_data', function(data){
var data = JSON.parse(data);
if(data.status =='Started' && 'viewer' in data && 'guest_ip' in data['viewer']){
if(!('viewer' in domains_table.row('#'+data.id).data()) || !('guest_ip' in domains_table.row('#'+data.id).data())){
//console.log('NEW IP ARRIVED!: '+data['viewer']['guest_ip'])
viewerButtonsIP(data['viewer']['guest_ip'])
}
}
dtUpdateInsert(domains_table,data,false);
setDomainDetailButtonsStatus(data.id, data.status);
});
socket.on(kind+'_delete', function(data){
var data = JSON.parse(data);
var row = domains_table.row('#'+data.id).remove().draw();
new PNotify({
title: kind+" deleted",
text: kind+" "+data.name+" has been deleted",
hide: true,
delay: 4000,
icon: 'fa fa-success',
opacity: 1,
type: 'success'
});
});
socket.on ('result', function (data) {
var data = JSON.parse(data);
if(data.result){
$('.modal').modal('hide');
}
new PNotify({
title: data.title,
text: data.text,
hide: true,
delay: 4000,
icon: 'fa fa-'+data.icon,
opacity: 1,
type: data.type
});
});
socket.on('add_form_result', function (data) {
var data = JSON.parse(data);
if(data.result){
$("#modalAddFromBuilder #modalAdd")[0].reset();
$("#modalAddFromBuilder").modal('hide');
$("#modalAddFromMedia #modalAdd")[0].reset();
$("#modalAddFromMedia").modal('hide');
$("#modalTemplateDesktop #modalTemplateDesktopForm")[0].reset();
$("#modalTemplateDesktop").modal('hide');
}
new PNotify({
title: data.title,
text: data.text,
hide: true,
delay: 4000,
icon: 'fa fa-'+data.icon,
opacity: 1,
type: data.type
});
});
socket.on('adds_form_result', function (data) {
var data = JSON.parse(data);
if(data.result){
$("#modalAddDesktop #modalAdd")[0].reset();
$("#modalAddDesktop").modal('hide');
}
new PNotify({
title: data.title,
text: data.text,
hide: true,
delay: 4000,
icon: 'fa fa-'+data.icon,
opacity: 1,
type: data.type
});
});
socket.on('edit_form_result', function (data) {
var data = JSON.parse(data);
if(data.result){
$("#modalEdit")[0].reset();
$("#modalEditDesktop").modal('hide');
$("#modalBulkEditForm")[0].reset();
$("#modalBulkEdit").modal('hide');
}
new PNotify({
title: data.title,
text: data.text,
hide: true,
delay: 4000,
icon: 'fa fa-'+data.icon,
opacity: 1,
type: data.type
});
});
});
function actionsDomainDetail(){
$('.btn-edit').on('click', function () {
var pk=$(this).closest("[data-pk]").attr("data-pk");
setHardwareOptions('#modalEditDesktop');
setHardwareDomainDefaults('#modalEditDesktop',pk);
$("#modalEdit")[0].reset();
$('#modalEditDesktop').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
$('#hardware-block').hide();
$('#modalEdit').parsley();
modal_edit_desktop_datatables(pk);
setDomainMediaDefaults('#modalEditDesktop',pk);
setMedia_add('#modalEditDesktop #media-block')
});
$('.btn-xml').on('click', function () {
var pk=$(this).closest("[data-pk]").attr("data-pk");
$("#modalEditXmlForm")[0].reset();
$('#modalEditXml').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
$('#modalEditXmlForm #id').val(pk);
$.ajax({
type: "GET",
url:"/isard-admin/admin/domains/xml/" + pk,
success: function(data)
{
$('#modalEditXmlForm #xml').val(data);
}
});
//~ $('#modalEdit').parsley();
//~ modal_edit_desktop_datatables(pk);
});
$('.btn-server').on('click', function () {
var pk=$(this).closest("[data-pk]").attr("data-pk");
$("#modalServerForm")[0].reset();
$('#modalServer').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
$('#modalServerForm #id').val(pk);
$.ajax({
type: "GET",
url:"/isard-admin/admin/domains/server/" + pk,
success: function(data)
{
if(data == true){
$('#modalServerForm #create_dict-server').iCheck('check').iCheck('update');
}else{
$('#modalServerForm #create_dict-server').iCheck('unckeck').iCheck('update');
}
}
});
//~ $('#modalEdit').parsley();
//~ modal_edit_desktop_datatables(pk);
});
if(url=="Desktops"){
$('.btn-delete-template').remove()
$('.btn-template').on('click', function () {
if($('.quota-templates .perc').text() >=100){
new PNotify({
title: "Quota for creating templates full.",
text: "Can't create another template, quota full.",
hide: true,
delay: 3000,
icon: 'fa fa-alert-sign',
opacity: 1,
type: 'error'
});
}else{
var pk=$(this).closest("[data-pk]").attr("data-pk");
setDefaultsTemplate(pk);
setHardwareOptions('#modalTemplateDesktop');
setHardwareDomainDefaults('#modalTemplateDesktop',pk);
$('#modalTemplateDesktop').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
setDomainMediaDefaults('#modalTemplateDesktop',pk);
setMedia_add('#modalTemplateDesktop #media-block')
setAlloweds_add('#modalTemplateDesktop #alloweds-add');
}
});
$('.btn-delete').on('click', function () {
var pk=$(this).closest("[data-pk]").attr("data-pk");
var name=$(this).closest("[data-pk]").attr("data-name");
new PNotify({
title: 'Confirmation Needed',
text: "Are you sure you want to delete virtual machine: "+name+"?",
hide: false,
opacity: 0.9,
confirm: {
confirm: true
},
buttons: {
closer: false,
sticker: false
},
history: {
history: false
},
addclass: 'pnotify-center'
}).get().on('pnotify.confirm', function() {
socket.emit('domain_update',{'pk':pk,'name':'status','value':'Deleting'})
}).on('pnotify.cancel', function() {
});
});
}else{
$('.btn-delete').remove()
$('.btn-template').remove()
$('.btn-delete-template').on('click', function () {
var pk = $(this).closest("[data-pk]").attr("data-pk")
$('#modalDeleteTemplate').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
populate_tree_template_delete(pk);
});
}
$('.btn-jumperurl').on('click', function () {
var pk=$(this).closest("[data-pk]").attr("data-pk");
$("#modalJumperurlForm")[0].reset();
$('#modalJumperurlForm #id').val(pk);
$('#modalJumperurl').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
// setModalUser()
// setQuotaTableDefaults('#edit-users-quota','users',pk)
api.ajax('/isard-admin/admin/domains/jumperurl/'+pk,'GET',{}).done(function(data) {
if(data.jumperurl != false){
$('#jumperurl').show();
$('.btn-copy-jumperurl').show();
//NOTE: With this it will fire ifChecked event, and generate new key
// and we don't want it now as we are just setting de initial state
// and don't want to reset de key again if already exists!
//$('#jumperurl-check').iCheck('check');
$('#jumperurl-check').prop('checked',true).iCheck('update');
$('#jumperurl').val(location.protocol + '//' + location.host+'/vw/'+data.jumperurl);
}else{
$('#jumperurl-check').iCheck('update')[0].unchecked;
$('#jumperurl').hide();
$('.btn-copy-jumperurl').hide();
}
});
});
$('#jumperurl-check').unbind('ifChecked').on('ifChecked', function(event){
if($('#jumperurl').val()==''){
pk=$('#modalJumperurlForm #id').val();
api.ajax('/isard-admin/admin/domains/jumperurl_reset/'+pk,'GET',{}).done(function(data) {
$('#jumperurl').val(location.protocol + '//' + location.host+'/vw/'+data);
});
$('#jumperurl').show();
$('.btn-copy-jumperurl').show();
}
});
$('#jumperurl-check').unbind('ifUnchecked').on('ifUnchecked', function(event){
pk=$('#modalJumperurlForm #id').val();
new PNotify({
title: 'Confirmation Needed',
text: "Are you sure you want to delete direct viewer access url?",
hide: false,
opacity: 0.9,
confirm: {
confirm: true
},
buttons: {
closer: false,
sticker: false
},
history: {
history: false
},
addclass: 'pnotify-center'
}).get().on('pnotify.confirm', function() {
pk=$('#modalJumperurlForm #id').val();
api.ajax('/isard-admin/admin/domains/jumperurl_disable/'+pk,'GET',{}).done(function(data) {
$('#jumperurl').val('');
});
$('#jumperurl').hide();
$('.btn-copy-jumperurl').hide();
}).on('pnotify.cancel', function() {
$('#jumperurl-check').iCheck('check');
$('#jumperurl').show();
$('.btn-copy-jumperurl').show();
});
});
$('.btn-copy-jumperurl').on('click', function () {
$('#jumperurl').prop('disabled',false).select().prop('disabled',true);
document.execCommand("copy");
});
$('.btn-forcedhyp').on('click', function () {
var pk=$(this).closest("[data-pk]").attr("data-pk");
$("#modalForcedhypForm")[0].reset();
$('#modalForcedhypForm #id').val(pk);
$('#modalForcedhyp').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
api.ajax('/isard-admin/admin/load/domains/post','POST',{'id':pk,'pluck':['id','forced_hyp']}).done(function(data) {
if('forced_hyp' in data && data.forced_hyp != false && data.forced_hyp != []){
HypervisorsDropdown(data.forced_hyp[0]);
$('#modalForcedhypForm #forced_hyp').show();
//NOTE: With this it will fire ifChecked event, and generate new key
// and we don't want it now as we are just setting de initial state
// and don't want to reset de key again if already exists!
//$('#jumperurl-check').iCheck('check');
$('#forcedhyp-check').prop('checked',true).iCheck('update');
}else{
$('#forcedhyp-check').iCheck('update')[0].unchecked;
$('#modalForcedhypForm #forced_hyp').hide();
}
});
});
$('#forcedhyp-check').unbind('ifChecked').on('ifChecked', function(event){
if($('#forced_hyp').val()==''){
pk=$('#modalForcedhypForm #id').val();
api.ajax('/isard-admin/admin/load/domains/post','POST',{'id':pk,'pluck':['id','forced_hyp']}).done(function(data) {
if('forced_hyp' in data && data.forced_hyp != false && data.forced_hyp != []){
HypervisorsDropdown(data.forced_hyp[0]);
}else{
HypervisorsDropdown('');
}
});
$('#modalForcedhypForm #forced_hyp').show();
}
});
$('#forcedhyp-check').unbind('ifUnchecked').on('ifUnchecked', function(event){
pk=$('#modalForcedhypForm #id').val();
$('#modalForcedhypForm #forced_hyp').hide();
$("#modalForcedhypForm #forced_hyp").empty()
});
$("#modalForcedhyp #send").on('click', function(e){
data=$('#modalForcedhypForm').serializeObject();
if('forced_hyp' in data){
socket.emit('forcedhyp_update',{'id':data.id,'forced_hyp':[data.forced_hyp]})
}else{
socket.emit('forcedhyp_update',{'id':data.id,'forced_hyp':false})
}
});
$("#modalServer #send").on('click', function(e){
data=$('#modalServerForm').serializeObject();
if('create_dict-server' in data){
socket.emit('create_dict-server',{'id':data.id,'create_dict-server':true})
}else{
socket.emit('create_dict-server',{'id':data.id,'create_dict-server':false})
}
});
}
function HypervisorsDropdown(selected) {
$("#modalForcedhypForm #forced_hyp").empty();
api.ajax('/isard-admin/admin/load/hypervisors/post','POST',{'pluck':['id','hostname']}).done(function(data) {
data.forEach(function(hypervisor){
$("#modalForcedhypForm #forced_hyp").append('<option value=' + hypervisor.id + '>' + hypervisor.id+' ('+hypervisor.hostname+')' + '</option>');
if(hypervisor.id == selected){
$('#modalForcedhypForm #forced_hyp option[value="'+hypervisor.id+'"]').prop("selected",true);
}
});
});
}
function setDefaultsTemplate(id) {
$.ajax({
type: "GET",
url:"/isard-admin/desktops/templateUpdate/" + id,
success: function(data)
{
$('.template-id').val(id);
$('.template-id').attr('data-pk', id);
$('.template-name').val('Template '+data.name);
$('.template-description').val(data.description);
}
});
}
//~ RENDER DATATABLE
function addDomainDetailPannel ( d ) {
$newPanel = $template_domain.clone();
if(kind=='desktop'){
$newPanel = $template_domain.clone();
$newPanel.find('#derivates-d\\.id').remove();
}else{
$newPanel = $admin_template_domain.clone();
}
$newPanel.html(function(i, oldHtml){
return oldHtml.replace(/d.id/g, d.id).replace(/d.name/g, d.name);
});
return $newPanel
}
function setDomainDetailButtonsStatus(id,status){
if(status=='Started' || status=='Starting'){
$('#actions-'+id+' *[class^="btn"]').prop('disabled', true);
$('#actions-'+id+' .btn-jumperurl').prop('disabled', false);
}else{
$('#actions-'+id+' *[class^="btn"]').prop('disabled', false);
}
$('#actions-'+id+' .btn-server').prop('disabled', false);
}
function icon(data){
viewer=""
viewerIP="'No client viewer'"
if(data['viewer-client_since']){viewer=" style='color:green' ";viewerIP="'Viewer client from IP: "+data['viewer-client_addr']+"'";}
if(data.icon=='windows' || data.icon=='linux'){
return "<i class='fa fa-"+data.icon+" fa-2x ' "+viewer+" title="+viewerIP+"></i>";
}else{
return "<span class='fl-"+data.icon+" fa-2x' "+viewer+" title="+viewerIP+"></span>";
}
}
function renderDisplay(data){
if(['Started', 'Shutting-down', 'Stopping'].includes(data.status)){
return '<button type="button" id="btn-display" class="btn btn-pill-right btn-success btn-xs"> \
<i class="fa fa-desktop"></i> Show</button>';
}
return ''
}
function renderStatus(data){
return data.status;
//To return the guest ip
if('viewer' in data && 'guest_ip' in data['viewer']){
return data['viewer']['guest_ip']
}else{
return 'No ip'
}
}
function renderHypStarted(data){
res=''
if('forced_hyp' in data && data.forced_hyp != false && data.forced_hyp != []){
res='<b>F: </b>'+data.forced_hyp[0]
}
if('hyp_started' in data && data.hyp_started != ''){ res=res+'<br><b>S: </b>'+ data.hyp_started;}
return res
}
function renderAction(data){
status=data.status;
if(status=='Stopped' || status=='Failed'){
return '<button type="button" id="btn-play" class="btn btn-pill-right btn-success btn-xs"><i class="fa fa-play"></i> Start</button>';
}
if(status=='Started'){
return '<button type="button" id="btn-stop" class="btn btn-pill-left btn-danger btn-xs"><i class="fa fa-stop"></i> Stop</button>';
}
if(status=='Shutting-down'){
return '<button type="button" id="btn-stop" class="btn btn-pill-left btn-danger btn-xs"><i class="fa fa-spinner fa-pulse fa-fw"></i> Force stop</button>';
}
if(status=='Crashed'){
return '<div class="Change"> <i class="fa fa-thumbs-o-down fa-2x"></i> </div>';
}
if(status=='Disabled'){
return '<i class="fa fa-times fa-2x"></i>';
}
return '<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>';
}
function populate_tree_template_delete(id){
$("#modalDeleteTemplate .tree_template_delete").fancytree({
extensions: ["table"],
table: {
indentation: 20, // indent 20px per node level
nodeColumnIdx: 2, // render the node title into the 2nd column
checkboxColumnIdx: 0 // render the checkboxes into the 1st column
},
source: {url: "/isard-admin/admin/domains/tree_list/" + id,
cache: false},
lazyLoad: function(event, data){
data.result = $.ajax({
url: "/isard-admin/admin/domains/tree_list/" + id,
dataType: "json"
});
},
checkbox: true,
selectMode: 3,
renderColumns: function(event, data) {
var node = data.node,
$tdList = $(node.tr).find(">td");
// (index #0 is rendered by fancytree by adding the checkbox)
$tdList.eq(1).text(node.getIndexHier());
// (index #2 is rendered by fancytree)
if(node.unselectable){
$tdList.eq(3).html('<i class="fa fa-exclamation-triangle"></i> '+node.data.user);
}else{
$tdList.eq(3).text(node.data.user);
}
if(node.data.kind != "desktop"){
$tdList.eq(4).html('<p style="color:black">'+node.data.kind+'</p>');
$tdList.eq(5).html('<p style="color:black">'+node.data.category+'</p>');
$tdList.eq(6).html('<p style="color:black">'+node.data.group+'</p>');
}else{
$tdList.eq(4).text(node.data.kind);
$tdList.eq(5).text(node.data.category);
$tdList.eq(6).text(node.data.group);
}
// Rendered by row template:
// $tdList.eq(4).html("<input type='checkbox' name='like' value='" + node.key + "'>");
}
});
}
function delete_templates(id){
//~ var pk=$(this).closest("[data-pk]").attr("data-pk");
$('#modalDeleteTemplate #id').val(id);
modal_delete_templates = $('#modal_delete_templates').DataTable({
"ajax": {
"url": "/isard-admin/admin/domains/todelete/"+id,
"dataSrc": ""
},
"scrollY": "125px",
"scrollCollapse": true,
"paging": false,
"language": {
"loadingRecords": '<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading...</span>',
"zeroRecords": "No matching templates found",
"info": "Showing _START_ to _END_ of _TOTAL_ templates",
"infoEmpty": "Showing 0 to 0 of 0 templates",
"infoFiltered": "(filtered from _MAX_ total templates)"
},
"rowId": "id",
"deferRender": true,
"columns": [
{ "data": "kind"},
{ "data": "user"},
{ "data": "status"},
{ "data": "name"},
],
//~ "order": [[0, 'asc']],
"pageLength": 10,
"destroy" : true
} );
}
// MODAL EDIT DESKTOP
function modal_edit_desktop_datatables(id){
$.ajax({
type: "GET",
url:"/isard-admin/desktops/templateUpdate/" + id,
success: function(data)
{
$('#modalEditDesktop #name_hidden').val(data.name);
$('#modalEditDesktop #name').val(data.name);
$('#modalEditDesktop #description').val(data.description);
$('#modalEditDesktop #id').val(data.id);
setHardwareDomainDefaults('#modalEditDesktop', id);
if(data['options-viewers-spice-fullscreen']){
$('#modalEditDesktop #options-viewers-spice-fullscreen').iCheck('check');
}
}
});
}
$("#modalEditDesktop #send").on('click', function(e){
var form = $('#modalEdit');
form.parsley().validate();
if (form.parsley().isValid()){
data=$('#modalEdit').serializeObject();
data=replaceMedia_arrays('#modalEditDesktop',data);
socket.emit('domain_edit',data)
}
});
$("#modalEditXml #send").on('click', function(e){
var form = $('#modalEditXmlForm');
//~ form.parsley().validate();
//~ if (form.parsley().isValid()){
id=$('#modalEditXmlForm #id').val();
xml=$('#modalEditXmlForm #xml').val();
api.ajax('/isard-admin/admin/domains/xml/'+id,'POST',{'xml':xml}).done(function(data) {
$("#modalEditXmlForm")[0].reset();
$("#modalEditXml").modal('hide');
});
//~ }
});
//~ }
| isard-vdi/isard | webapp/webapp/webapp/static/admin/js/domains.js | JavaScript | agpl-3.0 | 41,015 |
class AddSourceBeforeToMigrationLog < ActiveRecord::Migration
def change
add_column :migration_logs, :source_before, :text
end
end
| draknor/migro | db/migrate/20150502160325_add_source_before_to_migration_log.rb | Ruby | agpl-3.0 | 139 |
<?php
include_once ("../config.php");
if ( nbt_get_privileges_for_userid ( $_SESSION[INSTALL_HASH . '_nbt_userid'] ) == 4 ) {
nbt_remove_table_data_column ( $_POST['element'], $_POST['column'] );
}
$tableelementid = $_POST['element'];
include ('./tabledata.php');
?> | bgcarlisle/Numbat | forms/removetabledatacolumn.php | PHP | agpl-3.0 | 276 |
##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2021 Université catholique de Louvain (http://www.uclouvain.be)
#
# 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.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
from ddd.logic.learning_unit.builder.effective_class_identity_builder import EffectiveClassIdentityBuilder
from ddd.logic.learning_unit.commands import GetEffectiveClassCommand
from ddd.logic.learning_unit.domain.model.effective_class import EffectiveClass
from ddd.logic.learning_unit.repository.i_effective_class import IEffectiveClassRepository
# FIXME :: à tester unitairement + renvoyer EffectiveClassFromRepositoryDTO au lieu de l'objet du domaine
def get_effective_class(
cmd: 'GetEffectiveClassCommand',
effective_class_repository: 'IEffectiveClassRepository'
) -> 'EffectiveClass':
effective_class_identity = EffectiveClassIdentityBuilder.build_from_code_and_learning_unit_identity_data(
class_code=cmd.class_code,
learning_unit_code=cmd.learning_unit_code,
learning_unit_year=cmd.learning_unit_year
)
return effective_class_repository.get(entity_id=effective_class_identity)
| uclouvain/osis | ddd/logic/learning_unit/use_case/read/get_effective_class_service.py | Python | agpl-3.0 | 2,220 |
import React from 'react'
import PropTypes from 'prop-types'
import { ToastContainer } from 'react-toastify'
import { createBrowserHistory } from 'history'
import { Router, Redirect, Switch, Route, useLocation } from 'react-router'
import { BondeSessionProvider, BondeSessionUI } from 'bonde-core-tools'
import { Loading } from 'bonde-components'
import { ProviderRedux } from 'services/redux'
// Routes
// import Dashboard from './scenes/Dashboard'
// import { Root as AuthRoot } from './scenes/Auth'
import HomePage from 'scenes/HomePage'
import ChatbotPage from 'scenes/ChatbotPage/page'
import CommunityPage from 'scenes/CommunityPage'
// import SettingsPage from './scenes/Dashboard/scenes/Settings'
// import TagsPage from './scenes/Dashboard/scenes/Tags'
// import InvitationsPage from './scenes/Dashboard/scenes/Invitations'
import { NotFound } from 'components'
// Styles
import 'react-toastify/dist/ReactToastify.css'
const PagesRoute = () => {
const location = useLocation()
return (
<BondeSessionUI
indexRoute='/'
disableNavigation={location.pathname === '/'}
>
<ToastContainer
className='BondeToastify'
hideProgressBar={true}
/>
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/chatbot' component={ChatbotPage} />
<Route path='/community' component={CommunityPage} />
<Redirect from='/admin' to='/' />
<Route component={NotFound} />
</Switch>
</BondeSessionUI>
)
}
const TextLoading = ({ fetching }) => {
const messages = {
session: 'Carregando sessão...',
user: 'Carregando usuário...',
communities: 'Carregando communities...',
redirect: 'Redirecionando para autenticação...',
module: 'Redirecionando para módulo...'
}
return <Loading fullsize message={messages[fetching]} />
}
TextLoading.propTypes = {
fetching: PropTypes.string.isRequired
}
BondeSessionProvider.displayName = 'BondeSessionProvider'
const history = createBrowserHistory()
const Root = () => (
<BondeSessionProvider
fetchData
environment={process.env.REACT_APP_ENVIRONMENT || 'development'}
loading={TextLoading}
>
<ProviderRedux>
<Router history={history}>
<PagesRoute />
</Router>
</ProviderRedux>
</BondeSessionProvider>
)
export default Root
| nossas/bonde-client | packages/bonde-admin-canary/src/Root/index.js | JavaScript | agpl-3.0 | 2,346 |
/*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2016 Tanaguru.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.rgaa32016;
import org.tanaguru.entity.audit.ProcessResult;
import org.tanaguru.entity.audit.TestSolution;
import org.tanaguru.rules.rgaa32016.test.Rgaa32016RuleImplementationTestCase;
import org.tanaguru.rules.keystore.HtmlElementStore;
import org.tanaguru.rules.keystore.RemarkMessageStore;
/**
* Unit test class for the implementation of the rule 13-2-3 of the referential Rgaa 3-2016.
*
* @author jkowalczyk
*/
public class Rgaa32016Rule130203Test extends Rgaa32016RuleImplementationTestCase {
/**
* Default constructor
* @param testName
*/
public Rgaa32016Rule130203Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName("org.tanaguru.rules.rgaa32016.Rgaa32016Rule130203");
}
@Override
protected void setUpWebResourceMap() {
addWebResource("Rgaa32016.Test.13.02.03-3NMI-01");
addWebResource("Rgaa32016.Test.13.02.03-3NMI-02");
addWebResource("Rgaa32016.Test.13.02.03-3NMI-03");
addWebResource("Rgaa32016.Test.13.02.03-3NMI-04");
addWebResource("Rgaa32016.Test.13.02.03-3NMI-05");
addWebResource("Rgaa32016.Test.13.02.03-4NA-01");
}
@Override
protected void setProcess() {
//----------------------------------------------------------------------
//------------------------------3NMI-01---------------------------------
//----------------------------------------------------------------------
ProcessResult processResult = processPageTest("Rgaa32016.Test.13.02.03-3NMI-01");
checkResultIsPreQualified(processResult, 1, 1);
checkRemarkIsPresent(
processResult,
TestSolution.NEED_MORE_INFO,
RemarkMessageStore.CHECK_USER_IS_WARNED_IN_CASE_OF_NEW_WINDOW_MSG,
HtmlElementStore.FORM_ELEMENT,
1);
//----------------------------------------------------------------------
//------------------------------3NMI-02---------------------------------
//----------------------------------------------------------------------
processResult = processPageTest("Rgaa32016.Test.13.02.03-3NMI-02");
checkResultIsPreQualified(processResult, 1, 1);
checkRemarkIsPresent(
processResult,
TestSolution.NEED_MORE_INFO,
RemarkMessageStore.CHECK_USER_IS_WARNED_IN_CASE_OF_NEW_WINDOW_MSG,
HtmlElementStore.SELECT_ELEMENT,
1);
//----------------------------------------------------------------------
//------------------------------3NMI-03---------------------------------
//----------------------------------------------------------------------
processResult = processPageTest("Rgaa32016.Test.13.02.03-3NMI-03");
checkResultIsPreQualified(processResult, 1, 1);
checkRemarkIsPresent(
processResult,
TestSolution.NEED_MORE_INFO,
RemarkMessageStore.CHECK_USER_IS_WARNED_IN_CASE_OF_NEW_WINDOW_MSG,
HtmlElementStore.INPUT_ELEMENT,
1);
//----------------------------------------------------------------------
//------------------------------3NMI-04---------------------------------
//----------------------------------------------------------------------
processResult = processPageTest("Rgaa32016.Test.13.02.03-3NMI-04");
checkResultIsPreQualified(processResult, 1, 1);
checkRemarkIsPresent(
processResult,
TestSolution.NEED_MORE_INFO,
RemarkMessageStore.CHECK_USER_IS_WARNED_IN_CASE_OF_NEW_WINDOW_MSG,
HtmlElementStore.TEXTAREA_ELEMENT,
1);
//----------------------------------------------------------------------
//------------------------------3NMI-05---------------------------------
//----------------------------------------------------------------------
processResult = processPageTest("Rgaa32016.Test.13.02.03-3NMI-05");
checkResultIsPreQualified(processResult, 1, 1);
checkRemarkIsPresent(
processResult,
TestSolution.NEED_MORE_INFO,
RemarkMessageStore.CHECK_USER_IS_WARNED_IN_CASE_OF_NEW_WINDOW_MSG,
HtmlElementStore.BUTTON_ELEMENT,
1);
//----------------------------------------------------------------------
//------------------------------4NA-01----------------------------------
//----------------------------------------------------------------------
checkResultIsNotApplicable(processPageTest("Rgaa32016.Test.13.02.03-4NA-01"));
}
}
| Tanaguru/Tanaguru | rules/rgaa3-2016/src/test/java/org/tanaguru/rules/rgaa32016/Rgaa32016Rule130203Test.java | Java | agpl-3.0 | 5,725 |
<?php
/*
* Xibo - Digital Signage - http://www.xibo.org.uk
* Copyright (C) 2011-13 Daniel Garner
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Xibo 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Xibo. If not, see <http://www.gnu.org/licenses/>.
*/
defined('XIBO') or die("Sorry, you are not allowed to directly access this page.<br /> Please press the back button in your browser.");
class DataSet extends Data
{
public function hasData($dataSetId)
{
try {
$dbh = PDOConnect::init();
// First check to see if we have any data
$sth = $dbh->prepare('SELECT * FROM `datasetdata` INNER JOIN `datasetcolumn` ON datasetcolumn.DataSetColumnID = datasetdata.DataSetColumnID WHERE datasetcolumn.DataSetID = :datasetid');
$sth->execute(array(
'datasetid' => $dataSetId
));
return ($sth->fetch());
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage(), get_class(), __FUNCTION__);
if (!$this->IsError())
$this->SetError(1, __('Unknown Error'));
return false;
}
}
/**
* Add a data set
* @param <type> $dataSet
* @param <type> $description
* @param <type> $userId
* @return <type>
*/
public function Add($dataSet, $description, $userId)
{
try {
$dbh = PDOConnect::init();
// Validation
if (strlen($dataSet) > 50 || strlen($dataSet) < 1)
return $this->SetError(25001, __("Name must be between 1 and 50 characters"));
if (strlen($description) > 254)
return $this->SetError(25002, __("Description can not be longer than 254 characters"));
// Ensure there are no layouts with the same name
$sth = $dbh->prepare('SELECT DataSet FROM dataset WHERE DataSet = :dataset');
$sth->execute(array(
'dataset' => $dataSet
));
if ($row = $sth->fetch())
return $this->SetError(25004, sprintf(__("There is already dataset called '%s'. Please choose another name."), $dataSet));
// End Validation
$SQL = "INSERT INTO dataset (DataSet, Description, UserID) ";
$SQL .= " VALUES (:dataset, :description, :userid) ";
// Insert the data set
$sth = $dbh->prepare($SQL);
$sth->execute(array(
'dataset' => $dataSet,
'description' => $description,
'userid' => $userId
));
$id = $dbh->lastInsertId();
Debug::LogEntry('audit', 'Complete', 'DataSet', 'Add');
return $id;
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
return $this->SetError(25005, __('Could not add DataSet'));
}
}
/**
* Edit a DataSet
* @param <type> $dataSetId
* @param <type> $dataSet
* @param <type> $description
*/
public function Edit($dataSetId, $dataSet, $description)
{
try {
$dbh = PDOConnect::init();
// Validation
if (strlen($dataSet) > 50 || strlen($dataSet) < 1)
{
$this->SetError(25001, __("Name must be between 1 and 50 characters"));
return false;
}
if (strlen($description) > 254)
{
$this->SetError(25002, __("Description can not be longer than 254 characters"));
return false;
}
// Ensure there are no layouts with the same name
$sth = $dbh->prepare('SELECT DataSet FROM dataset WHERE DataSet = :dataset AND DataSetID <> :datasetid');
$sth->execute(array(
'dataset' => $dataSet,
'datasetid' => $dataSetId
));
if ($row = $sth->fetch())
return $this->SetError(25004, sprintf(__("There is already dataset called '%s'. Please choose another name."), $dataSet));
// End Validation
// Update the data set
$sth = $dbh->prepare('UPDATE dataset SET DataSet = :dataset, Description = :description WHERE DataSetID = :datasetid');
$sth->execute(array(
'dataset' => $dataSet,
'description' => $description,
'datasetid' => $dataSetId
));
return true;
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
return $this->SetError(25005, sprintf(__('Cannot edit dataset %s'), $dataSet));
}
}
/**
* Delete DataSet
* @param <type> $dataSetId
*/
public function Delete($dataSetId)
{
try {
$dbh = PDOConnect::init();
// Delete the Data
$data = new DataSetData();
$data->DeleteAll($dataSetId);
// Delete security
$security = new DataSetGroupSecurity($this->db);
$security->UnlinkAll($dataSetId);
// Delete columns
$dataSetObject = new DataSetColumn($this->db);
if (!$dataSetObject->DeleteAll($dataSetId))
return $this->SetError(25005, __('Cannot delete dataset, columns could not be deleted.'));
// Delete data set
$sth = $dbh->prepare('DELETE FROM dataset WHERE DataSetID = :datasetid');
$sth->execute(array(
'datasetid' => $dataSetId
));
return true;
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
if (!$this->IsError())
$this->SetError(25005, sprintf(__('Cannot edit dataset %s'), $dataSet));
return false;
}
}
public function LinkLayout($dataSetId, $layoutId, $regionId, $mediaId) {
try {
$dbh = PDOConnect::init();
$sth = $dbh->prepare('INSERT INTO `lkdatasetlayout` (DataSetID, LayoutID, RegionID, MediaID) VALUES (:datasetid, :layoutid, :regionid, :mediaid)');
$sth->execute(array(
'datasetid' => $dataSetId,
'layoutid' => $layoutId,
'regionid' => $regionId,
'mediaid' => $mediaId
));
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
if (!$this->IsError())
$this->SetError(1, __('Unknown Error'));
return false;
}
}
public function UnlinkLayout($dataSetId, $layoutId, $regionId, $mediaId) {
try {
$dbh = PDOConnect::init();
$sth = $dbh->prepare('DELETE FROM `lkdatasetlayout` WHERE DataSetID = :datasetid AND LayoutID = :layoutid AND RegionID = :regionid AND MediaID = :mediaid');
$sth->execute(array(
'datasetid' => $dataSetId,
'layoutid' => $layoutId,
'regionid' => $regionId,
'mediaid' => $mediaId
));
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
if (!$this->IsError())
$this->SetError(1, __('Unknown Error'));
return false;
}
}
public function GetDataSetFromLayout($layoutId, $regionId, $mediaId) {
try {
$dbh = PDOConnect::init();
$sth = $dbh->prepare('SELECT `dataset`.* FROM `lkdatasetlayout` INNER JOIN `dataset` ON lkdatasetlayout.DataSetId = dataset.DataSetID WHERE LayoutID = :layoutid AND RegionID = :regionid AND MediaID = :mediaid');
$sth->execute(array(
'layoutid' => $layoutId,
'regionid' => $regionId,
'mediaid' => $mediaId
));
return $sth->fetchAll();
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
if (!$this->IsError())
$this->SetError(1, __('Unknown Error'));
return false;
}
}
public function GetCampaignsForDataSet($dataSetId) {
try {
$dbh = PDOConnect::init();
$sth = $dbh->prepare('SELECT DISTINCT `lkcampaignlayout`.CampaignID FROM `lkdatasetlayout` INNER JOIN `lkcampaignlayout` ON `lkcampaignlayout`.LayoutID = `lkdatasetlayout`.LayoutID WHERE DataSetID = :datasetid');
$sth->execute(array(
'datasetid' => $dataSetId
));
$ids = array();
foreach ($sth->fetchAll() as $id)
$ids[] = $id['CampaignID'];
return $ids;
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
if (!$this->IsError())
$this->SetError(1, __('Unknown Error'));
return false;
}
}
public function GetLastDataEditTime($dataSetId) {
try {
$dbh = PDOConnect::init();
$sth = $dbh->prepare('SELECT LastDataEdit FROM `dataset` WHERE DataSetID = :dataset_id');
$sth->execute(array(
'dataset_id' => $dataSetId
));
$updateDate = $sth->fetchColumn(0);
Debug::LogEntry('audit', sprintf('Returning update date %s for DataSetId %d', $updateDate, $dataSetId), 'dataset', 'GetLastDataEditTime');
return $updateDate;
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
if (!$this->IsError())
$this->SetError(1, __('Unknown Error'));
return false;
}
}
/**
* Data Set Results
* @param <type> $dataSetId
* @param <type> $columnIds
* @param <type> $filter
* @param <type> $ordering
* @param <type> $lowerLimit
* @param <type> $upperLimit
* @return <type>
*/
public function DataSetResults($dataSetId, $columnIds, $filter = '', $ordering = '', $lowerLimit = 0, $upperLimit = 0, $displayId = 0)
{
$blackList = array(';', 'INSERT', 'UPDATE', 'SELECT', 'DELETE', 'TRUNCATE', 'TABLE', 'FROM', 'WHERE');
try {
$dbh = PDOConnect::init();
PDOConnect::setTimeZone($dbh, date('P'));
$params = array('dataSetId' => $dataSetId);
$selectSQL = '';
$outserSelect = '';
$finalSelect = '';
$results = array();
$headings = array();
$allowedOrderCols = array();
$filter = str_replace($blackList, '', $filter);
$filter = str_replace('[DisplayId]', $displayId, $filter);
$columns = explode(',', $columnIds);
// Get the Latitude and Longitude ( might be used in a formula )
if ($displayId == 0) {
$defaultLat = Config::GetSetting('DEFAULT_LAT');
$defaultLong = Config::GetSetting('DEFAULT_LONG');
$displayGeoLocation = "GEOMFROMTEXT('POINT(" . $defaultLat . " " . $defaultLong . ")')";
}
else
$displayGeoLocation = sprintf("(SELECT GeoLocation FROM `display` WHERE DisplayID = %d)", $displayId);
// Get all columns for the cross tab
$sth = $dbh->prepare('SELECT DataSetColumnID, Heading, DataSetColumnTypeID, Formula, DataTypeID FROM datasetcolumn WHERE DataSetID = :dataSetId');
$sth->execute(array('dataSetId' => $dataSetId));
$allColumns = $sth->fetchAll();
foreach($allColumns as $col)
{
$heading = $col;
$heading['Text'] = $heading['Heading'];
$allowedOrderCols[] = $heading['Heading'];
$formula = str_replace($blackList, '', htmlspecialchars_decode($col['Formula'], ENT_QUOTES));
// Is this column a formula column or a value column?
if ($col['DataSetColumnTypeID'] == 2) {
// Formula
$formula = str_replace('[DisplayGeoLocation]', $displayGeoLocation, $formula);
$formula = str_replace('[DisplayId]', $displayId, $formula);
$heading['Heading'] = $formula . ' AS \'' . $heading['Heading'] . '\'';
}
else {
// Value
$selectSQL .= sprintf("MAX(CASE WHEN DataSetColumnID = %d THEN `Value` ELSE null END) AS '%s', ", $col['DataSetColumnID'], $heading['Heading']);
}
$headings[] = $heading;
}
// Build our select statement including formulas
foreach($headings as $heading)
{
if ($heading['DataSetColumnTypeID'] == 2)
// This is a formula, so the heading has been morphed into some SQL to run
$outserSelect .= ' ' . $heading['Heading'] . ',';
else
$outserSelect .= sprintf(' `%s`,', $heading['Heading']);
}
$outserSelect = rtrim($outserSelect, ',');
// For each heading, put it in the correct order (according to $columns)
foreach($columns as $visibleColumn)
{
foreach($headings as $heading)
{
if ($heading['DataSetColumnID'] == $visibleColumn)
{
$finalSelect .= sprintf(' `%s`,', $heading['Text']);
$results['Columns'][] = $heading;
}
}
}
$finalSelect = rtrim($finalSelect, ',');
// We are ready to build the select and from part of the SQL
$SQL = "SELECT $finalSelect ";
$SQL .= " FROM ( ";
$SQL .= " SELECT $outserSelect ,";
$SQL .= " RowNumber ";
$SQL .= " FROM ( ";
$SQL .= " SELECT $selectSQL ";
$SQL .= " RowNumber ";
$SQL .= " FROM (";
$SQL .= " SELECT datasetcolumn.DataSetColumnID, datasetdata.RowNumber, datasetdata.`Value` ";
$SQL .= " FROM datasetdata ";
$SQL .= " INNER JOIN datasetcolumn ";
$SQL .= " ON datasetcolumn.DataSetColumnID = datasetdata.DataSetColumnID ";
$SQL .= " WHERE datasetcolumn.DataSetID = :dataSetId ";
$SQL .= " ) datasetdatainner ";
$SQL .= " GROUP BY RowNumber ";
$SQL .= " ) datasetdata ";
if ($filter != '')
{
$SQL .= ' WHERE ' . $filter;
}
$SQL .= ' ) finalselect ';
if ($ordering != '')
{
$order = ' ORDER BY ';
$ordering = explode(',', $ordering);
foreach ($ordering as $orderPair)
{
// Sanitize the clause
$sanitized = str_replace(' ASC', '', str_replace(' DESC', '', $orderPair));
// Check allowable
if (!in_array($sanitized, $allowedOrderCols)) {
Debug::Info('Disallowed column: ' . $sanitized);
continue;
}
// Substitute
if (strripos($orderPair, ' DESC')) {
$order .= sprintf(' `%s` DESC,', $sanitized);
}
else if (strripos($orderPair, ' ASC')) {
$order .= sprintf(' `%s` ASC,', $sanitized);
}
else {
$order .= sprintf(' `%s`,', $sanitized);
}
}
$SQL .= trim($order, ',');
}
else
{
$SQL .= " ORDER BY RowNumber ";
}
if ($lowerLimit != 0 || $upperLimit != 0)
{
// Lower limit should be 0 based
if ($lowerLimit != 0)
$lowerLimit = $lowerLimit - 1;
// Upper limit should be the distance between upper and lower
$upperLimit = $upperLimit - $lowerLimit;
// Substitute in
$SQL .= sprintf(' LIMIT %d, %d ', $lowerLimit, $upperLimit);
}
Debug::Audit($SQL . ' ' . var_export($params, true));
$sth = $dbh->prepare($SQL);
//$sth->debugDumpParams();
$sth->execute($params);
$results['Rows'] = $sth->fetchAll();
return $results;
}
catch (Exception $e) {
Debug::Error($e->getMessage());
if (!$this->IsError())
$this->SetError(1, __('Unknown Error'));
return false;
}
}
public function GetDataTypes() {
try {
$dbh = PDOConnect::init();
$sth = $dbh->prepare('SELECT datatypeid, datatype FROM datatype');
$sth->execute();
return $sth->fetchAll();
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
if (!$this->IsError())
$this->SetError(1, __('Unknown Error'));
return false;
}
}
public function GetDataSetColumnTypes() {
try {
$dbh = PDOConnect::init();
$sth = $dbh->prepare('SELECT datasetcolumntypeid, datasetcolumntype FROM datasetcolumntype');
$sth->execute();
return $sth->fetchAll();
}
catch (Exception $e) {
Debug::LogEntry('error', $e->getMessage());
if (!$this->IsError())
$this->SetError(1, __('Unknown Error'));
return false;
}
}
}
?>
| gractor/xibo-cms | lib/data/dataset.data.class.php | PHP | agpl-3.0 | 19,090 |
/*
* Copyright (C) 1998, 2000-2007, 2010, 2011, 2012, 2013 SINTEF ICT,
* Applied Mathematics, Norway.
*
* Contact information: E-mail: tor.dokken@sintef.no
* SINTEF ICT, Department of Applied Mathematics,
* P.O. Box 124 Blindern,
* 0314 Oslo, Norway.
*
* This file is part of GoTools.
*
* GoTools is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* GoTools 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with GoTools. If not, see
* <http://www.gnu.org/licenses/>.
*
* In accordance with Section 7(b) of the GNU Affero General Public
* License, a covered work must retain the producer line in every data
* file that is created or manipulated using GoTools.
*
* Other Usage
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the GoTools library without
* disclosing the source code of your own applications.
*
* This file may be used in accordance with the terms contained in a
* written agreement between you and SINTEF ICT.
*/
#ifndef COMPLETEEDGENET_H
#define COMPLETEEDGENET_H
#include "GoTools/compositemodel/SurfaceModel.h"
namespace Go
{
/// \brief Complete the edge net of a SurfaceModel. Fetches the wire
/// frame model corresponding to a surface model, and extends it such
/// that the extended wire frame will become the wire frame model corresponding
/// to a volume model have the given surface model as its outer boundary.
/// The extension to the wireframe is represented as pairs of vertices where
/// these vertices lie at the endpoints of the missing edges.
/// NB! This solution is currently not expected to handle all configurations.
class CompleteEdgeNet
{
public:
/// Constructor. The method is applied on a SurfaceModel
/// \param sfmodel Pointer to a SurfaceModel
CompleteEdgeNet(shared_ptr<SurfaceModel> sfmodel,
bool perform_step2, bool smooth_connections);
/// Destructor
~CompleteEdgeNet();
/// Apply algorithm for completing the edge net and create
/// a starting ground for a block structured model of solids
/// \return Whether the edge net was completed or not.
bool perform(std::vector<std::pair<Point,Point> >& corr_vx_pts);
/// Fetch modified model (after regularization)
/// \return Pointer to the modified model
shared_ptr<SurfaceModel> getRegularizedModel()
{
return model_;
}
/// Fetch new edges represented by their end vertices
/// \return Vector of pointers to end vertices of the edges
std::vector<std::pair<shared_ptr<Vertex>, shared_ptr<Vertex> > >
getMissingEdges()
{
return missing_edges_;
}
private:
shared_ptr<SurfaceModel> model_;
std::vector<std::pair<shared_ptr<Vertex>, shared_ptr<Vertex> > > missing_edges_;
bool perform_step2_;
bool smooth_connections_;
/// Given a regular solid, add the edges required to make a block
/// structured model
void addMissingEdges();
void identifyVertexConnection(std::vector<shared_ptr<Vertex> > vxs,
size_t ki1, size_t ki2,
int& ix1, int& ix2);
void traverseEdges(std::vector<ftEdge*>& edges,
std::vector<ftEdge*>& curr_path,
std::vector<int>& curr_idx,
ftEdge *curr_edge,
shared_ptr<Vertex> vx,
bool search_end);
ftEdge* fetchNextEdge(ftEdge *curr_edge,
shared_ptr<Vertex> vx,
int& next_idx);
bool regularizeEdgeLoop(std::vector<ftEdge*>& edges);
void splitLoop(std::vector<ftEdge*>& edges,
std::vector<shared_ptr<Vertex> >& vxs,
bool to_add_edges,
std::vector<std::vector<ftEdge*> >& split_loops,
std::vector<std::vector<shared_ptr<Vertex> > >& split_vxs,
std::vector<bool>& add_edges_split);
bool regularizeCurrLoop(std::vector<ftEdge*>& edges,
std::vector<shared_ptr<Vertex> >& vxs,
bool to_add_edges);
double getVertexAngle(ftEdge *edge1, ftEdge *edge2);
void addRemainingEdges();
bool vertexInfo(shared_ptr<Vertex> vx, double& angle, Point& centre);
void writePath(std::vector<ftEdge*>& edges, shared_ptr<Vertex> vx);
std::vector<ftEdge*> getStartEdges();
void addIdentifiedEdges(std::vector<std::pair<Point,Point> >& corr_vx_pts);
bool betterConnectionInFace(shared_ptr<Vertex> source, Body *bd,
ftEdge* edg1, ftEdge *edg2, shared_ptr<Vertex> dest);
};
} // namespace Go
#endif // COMPLETEEDGENET_H
| akva2/GoTools | compositemodel/include/GoTools/compositemodel/CompleteEdgeNet.h | C | agpl-3.0 | 5,154 |
<?php
$GLOBALS["dictionary"]["Employee"]=array (
'table' => 'users',
'fields' =>
array (
'id' =>
array (
'name' => 'id',
'vname' => 'LBL_ID',
'type' => 'id',
'required' => true,
),
'user_name' =>
array (
'name' => 'user_name',
'vname' => 'LBL_USER_NAME',
'type' => 'user_name',
'dbType' => 'varchar',
'len' => '60',
'importable' => 'required',
'required' => true,
'studio' =>
array (
'no_duplicate' => true,
'editview' => false,
'detailview' => true,
'quickcreate' => false,
'basic_search' => false,
'advanced_search' => false,
'wirelesseditview' => false,
'wirelessdetailview' => true,
'wirelesslistview' => false,
'wireless_basic_search' => false,
'wireless_advanced_search' => false,
'rollup' => false,
),
),
'user_hash' =>
array (
'name' => 'user_hash',
'vname' => 'LBL_USER_HASH',
'type' => 'varchar',
'len' => '255',
'reportable' => false,
'importable' => 'false',
'studio' =>
array (
'no_duplicate' => true,
'listview' => false,
'searchview' => false,
),
),
'system_generated_password' =>
array (
'name' => 'system_generated_password',
'vname' => 'LBL_SYSTEM_GENERATED_PASSWORD',
'type' => 'bool',
'required' => true,
'reportable' => false,
'massupdate' => false,
'studio' =>
array (
'listview' => false,
'searchview' => false,
'editview' => false,
'quickcreate' => false,
'wirelesseditview' => false,
),
),
'pwd_last_changed' =>
array (
'name' => 'pwd_last_changed',
'vname' => 'LBL_PSW_MODIFIED',
'type' => 'datetime',
'required' => false,
'massupdate' => false,
'studio' =>
array (
'formula' => false,
),
),
'authenticate_id' =>
array (
'name' => 'authenticate_id',
'vname' => 'LBL_AUTHENTICATE_ID',
'type' => 'varchar',
'len' => '100',
'reportable' => false,
'importable' => 'false',
'studio' =>
array (
'listview' => false,
'searchview' => false,
'related' => false,
),
),
'sugar_login' =>
array (
'name' => 'sugar_login',
'vname' => 'LBL_SUGAR_LOGIN',
'type' => 'bool',
'default' => '1',
'reportable' => false,
'massupdate' => false,
'importable' => false,
'studio' =>
array (
'listview' => false,
'searchview' => false,
'formula' => false,
),
),
'first_name' =>
array (
'name' => 'first_name',
'vname' => 'LBL_FIRST_NAME',
'dbType' => 'varchar',
'type' => 'name',
'len' => '30',
),
'last_name' =>
array (
'name' => 'last_name',
'vname' => 'LBL_LAST_NAME',
'dbType' => 'varchar',
'type' => 'name',
'len' => '30',
'importable' => 'required',
'required' => true,
),
'full_name' =>
array (
'name' => 'full_name',
'rname' => 'full_name',
'vname' => 'LBL_NAME',
'type' => 'name',
'fields' =>
array (
0 => 'first_name',
1 => 'last_name',
),
'source' => 'non-db',
'sort_on' => 'last_name',
'sort_on2' => 'first_name',
'db_concat_fields' =>
array (
0 => 'first_name',
1 => 'last_name',
),
'len' => '510',
'studio' =>
array (
'formula' => false,
),
),
'name' =>
array (
'name' => 'name',
'rname' => 'name',
'vname' => 'LBL_NAME',
'type' => 'varchar',
'source' => 'non-db',
'len' => '510',
'db_concat_fields' =>
array (
0 => 'first_name',
1 => 'last_name',
),
'importable' => 'false',
),
'is_admin' =>
array (
'name' => 'is_admin',
'vname' => 'LBL_IS_ADMIN',
'type' => 'bool',
'default' => '0',
'studio' =>
array (
'listview' => false,
'searchview' => false,
'related' => false,
),
'massupdate' => false,
),
'external_auth_only' =>
array (
'name' => 'external_auth_only',
'vname' => 'LBL_EXT_AUTHENTICATE',
'type' => 'bool',
'reportable' => false,
'massupdate' => false,
'default' => '0',
'studio' =>
array (
'listview' => false,
'searchview' => false,
'related' => false,
),
),
'receive_notifications' =>
array (
'name' => 'receive_notifications',
'vname' => 'LBL_RECEIVE_NOTIFICATIONS',
'type' => 'bool',
'default' => '1',
'massupdate' => false,
'studio' => false,
),
'description' =>
array (
'name' => 'description',
'vname' => 'LBL_DESCRIPTION',
'type' => 'text',
),
'date_entered' =>
array (
'name' => 'date_entered',
'vname' => 'LBL_DATE_ENTERED',
'type' => 'datetime',
'required' => true,
'studio' =>
array (
'editview' => false,
'quickcreate' => false,
'wirelesseditview' => false,
),
),
'date_modified' =>
array (
'name' => 'date_modified',
'vname' => 'LBL_DATE_MODIFIED',
'type' => 'datetime',
'required' => true,
'studio' =>
array (
'editview' => false,
'quickcreate' => false,
'wirelesseditview' => false,
),
),
'modified_user_id' =>
array (
'name' => 'modified_user_id',
'rname' => 'user_name',
'id_name' => 'modified_user_id',
'vname' => 'LBL_MODIFIED_BY_ID',
'type' => 'assigned_user_name',
'table' => 'users',
'isnull' => 'false',
'dbType' => 'id',
),
'modified_by_name' =>
array (
'name' => 'modified_by_name',
'vname' => 'LBL_MODIFIED_BY',
'type' => 'varchar',
'source' => 'non-db',
'studio' => false,
),
'created_by' =>
array (
'name' => 'created_by',
'rname' => 'user_name',
'id_name' => 'modified_user_id',
'vname' => 'LBL_ASSIGNED_TO',
'type' => 'assigned_user_name',
'table' => 'users',
'isnull' => 'false',
'dbType' => 'id',
'studio' => false,
),
'created_by_name' =>
array (
'name' => 'created_by_name',
'vname' => 'LBL_CREATED_BY_NAME',
'type' => 'varchar',
'source' => 'non-db',
'importable' => 'false',
),
'title' =>
array (
'name' => 'title',
'vname' => 'LBL_TITLE',
'type' => 'varchar',
'len' => '50',
),
'department' =>
array (
'name' => 'department',
'vname' => 'LBL_DEPARTMENT',
'type' => 'varchar',
'len' => '50',
),
'phone_home' =>
array (
'name' => 'phone_home',
'vname' => 'LBL_HOME_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => '50',
),
'phone_mobile' =>
array (
'name' => 'phone_mobile',
'vname' => 'LBL_MOBILE_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => '50',
),
'phone_work' =>
array (
'name' => 'phone_work',
'vname' => 'LBL_WORK_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => '50',
),
'phone_other' =>
array (
'name' => 'phone_other',
'vname' => 'LBL_OTHER_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => '50',
),
'phone_fax' =>
array (
'name' => 'phone_fax',
'vname' => 'LBL_FAX_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => '50',
),
'status' =>
array (
'name' => 'status',
'vname' => 'LBL_STATUS',
'type' => 'enum',
'len' => 100,
'options' => 'user_status_dom',
'importable' => 'required',
'required' => false,
'massupdate' => false,
'studio' => false,
),
'address_street' =>
array (
'name' => 'address_street',
'vname' => 'LBL_ADDRESS_STREET',
'type' => 'varchar',
'len' => '150',
),
'address_city' =>
array (
'name' => 'address_city',
'vname' => 'LBL_ADDRESS_CITY',
'type' => 'varchar',
'len' => '100',
),
'address_state' =>
array (
'name' => 'address_state',
'vname' => 'LBL_ADDRESS_STATE',
'type' => 'varchar',
'len' => '100',
),
'address_country' =>
array (
'name' => 'address_country',
'vname' => 'LBL_ADDRESS_COUNTRY',
'type' => 'varchar',
'len' => 100,
),
'address_postalcode' =>
array (
'name' => 'address_postalcode',
'vname' => 'LBL_ADDRESS_POSTALCODE',
'type' => 'varchar',
'len' => '20',
),
'UserType' =>
array (
'name' => 'UserType',
'vname' => 'LBL_USER_TYPE',
'type' => 'enum',
'len' => 50,
'options' => 'user_type_dom',
'source' => 'non-db',
'import' => false,
'reportable' => false,
'studio' =>
array (
'formula' => false,
),
'massupdate' => false,
),
'deleted' =>
array (
'name' => 'deleted',
'vname' => 'LBL_DELETED',
'type' => 'bool',
'required' => false,
'reportable' => false,
),
'portal_only' =>
array (
'name' => 'portal_only',
'vname' => 'LBL_PORTAL_ONLY_USER',
'type' => 'bool',
'massupdate' => false,
'default' => '0',
'studio' =>
array (
'listview' => false,
'searchview' => false,
'formula' => false,
),
),
'show_on_employees' =>
array (
'name' => 'show_on_employees',
'vname' => 'LBL_SHOW_ON_EMPLOYEES',
'type' => 'bool',
'massupdate' => true,
'importable' => true,
'default' => true,
'studio' =>
array (
'formula' => false,
),
),
'employee_status' =>
array (
'name' => 'employee_status',
'vname' => 'LBL_EMPLOYEE_STATUS',
'type' => 'varchar',
'function' =>
array (
'name' => 'getEmployeeStatusOptions',
'returns' => 'html',
'include' => 'modules/Employees/EmployeeStatus.php',
),
'len' => 100,
),
'messenger_id' =>
array (
'name' => 'messenger_id',
'vname' => 'LBL_MESSENGER_ID',
'type' => 'varchar',
'len' => 100,
),
'messenger_type' =>
array (
'name' => 'messenger_type',
'vname' => 'LBL_MESSENGER_TYPE',
'type' => 'enum',
'options' => 'messenger_type_dom',
'len' => 100,
'massupdate' => false,
),
'calls' =>
array (
'name' => 'calls',
'type' => 'link',
'relationship' => 'calls_users',
'source' => 'non-db',
'vname' => 'LBL_CALLS',
),
'meetings' =>
array (
'name' => 'meetings',
'type' => 'link',
'relationship' => 'meetings_users',
'source' => 'non-db',
'vname' => 'LBL_MEETINGS',
),
'contacts_sync' =>
array (
'name' => 'contacts_sync',
'type' => 'link',
'relationship' => 'contacts_users',
'source' => 'non-db',
'vname' => 'LBL_CONTACTS_SYNC',
'reportable' => false,
),
'reports_to_id' =>
array (
'name' => 'reports_to_id',
'vname' => 'LBL_REPORTS_TO_ID',
'type' => 'id',
'required' => false,
),
'reports_to_name' =>
array (
'name' => 'reports_to_name',
'rname' => 'last_name',
'id_name' => 'reports_to_id',
'vname' => 'LBL_REPORTS_TO_NAME',
'type' => 'relate',
'isnull' => 'true',
'module' => 'Users',
'table' => 'users',
'link' => 'reports_to_link',
'reportable' => false,
'source' => 'non-db',
'duplicate_merge' => 'disabled',
'side' => 'right',
),
'reports_to_link' =>
array (
'name' => 'reports_to_link',
'type' => 'link',
'relationship' => 'user_direct_reports',
'link_type' => 'one',
'side' => 'right',
'source' => 'non-db',
'vname' => 'LBL_REPORTS_TO',
),
'reportees' =>
array (
'name' => 'reportees',
'type' => 'link',
'relationship' => 'user_direct_reports',
'link_type' => 'many',
'side' => 'left',
'source' => 'non-db',
'vname' => 'LBL_REPORTS_TO',
'reportable' => false,
),
'email1' =>
array (
'name' => 'email1',
'vname' => 'LBL_EMAIL',
'type' => 'varchar',
'function' =>
array (
'name' => 'getEmailAddressWidget',
'returns' => 'html',
),
'source' => 'non-db',
'group' => 'email1',
'merge_filter' => 'enabled',
'required' => false,
),
'email_addresses' =>
array (
'name' => 'email_addresses',
'type' => 'link',
'relationship' => 'users_email_addresses',
'module' => 'EmailAddress',
'bean_name' => 'EmailAddress',
'source' => 'non-db',
'vname' => 'LBL_EMAIL_ADDRESSES',
'reportable' => false,
'required' => false,
),
'email_addresses_primary' =>
array (
'name' => 'email_addresses_primary',
'type' => 'link',
'relationship' => 'users_email_addresses_primary',
'source' => 'non-db',
'vname' => 'LBL_EMAIL_ADDRESS_PRIMARY',
'duplicate_merge' => 'disabled',
'required' => false,
),
'email_link_type' =>
array (
'name' => 'email_link_type',
'vname' => 'LBL_EMAIL_LINK_TYPE',
'type' => 'enum',
'options' => 'dom_email_link_type',
'importable' => false,
'reportable' => false,
'source' => 'non-db',
'studio' => false,
'massupdate' => false,
),
'aclroles' =>
array (
'name' => 'aclroles',
'type' => 'link',
'relationship' => 'acl_roles_users',
'source' => 'non-db',
'side' => 'right',
'vname' => 'LBL_ROLES',
),
'is_group' =>
array (
'name' => 'is_group',
'vname' => 'LBL_GROUP_USER',
'type' => 'bool',
'massupdate' => false,
'studio' =>
array (
'listview' => false,
'searchview' => false,
'formula' => false,
),
),
'c_accept_status_fields' =>
array (
'name' => 'c_accept_status_fields',
'rname' => 'id',
'relationship_fields' =>
array (
'id' => 'accept_status_id',
'accept_status' => 'accept_status_name',
),
'vname' => 'LBL_LIST_ACCEPT_STATUS',
'type' => 'relate',
'link' => 'calls',
'link_type' => 'relationship_info',
'source' => 'non-db',
'importable' => 'false',
'studio' =>
array (
'listview' => false,
'searchview' => false,
'formula' => false,
),
),
'm_accept_status_fields' =>
array (
'name' => 'm_accept_status_fields',
'rname' => 'id',
'relationship_fields' =>
array (
'id' => 'accept_status_id',
'accept_status' => 'accept_status_name',
),
'vname' => 'LBL_LIST_ACCEPT_STATUS',
'type' => 'relate',
'link' => 'meetings',
'link_type' => 'relationship_info',
'source' => 'non-db',
'importable' => 'false',
'studio' =>
array (
'listview' => false,
'searchview' => false,
'formula' => false,
),
),
'accept_status_id' =>
array (
'name' => 'accept_status_id',
'type' => 'varchar',
'source' => 'non-db',
'vname' => 'LBL_LIST_ACCEPT_STATUS',
'importable' => 'false',
'studio' =>
array (
'listview' => false,
'searchview' => false,
'formula' => false,
),
),
'accept_status_name' =>
array (
'name' => 'accept_status_name',
'type' => 'enum',
'source' => 'non-db',
'vname' => 'LBL_LIST_ACCEPT_STATUS',
'options' => 'dom_meeting_accept_status',
'massupdate' => false,
'studio' =>
array (
'listview' => false,
'searchview' => false,
'formula' => false,
),
),
'prospect_lists' =>
array (
'name' => 'prospect_lists',
'type' => 'link',
'relationship' => 'prospect_list_users',
'module' => 'ProspectLists',
'source' => 'non-db',
'vname' => 'LBL_PROSPECT_LIST',
),
'emails_users' =>
array (
'name' => 'emails_users',
'type' => 'link',
'relationship' => 'emails_users_rel',
'module' => 'Emails',
'source' => 'non-db',
'vname' => 'LBL_EMAILS',
),
'holidays' =>
array (
'name' => 'holidays',
'type' => 'link',
'relationship' => 'users_holidays',
'source' => 'non-db',
'side' => 'right',
'vname' => 'LBL_HOLIDAYS',
),
'eapm' =>
array (
'name' => 'eapm',
'type' => 'link',
'relationship' => 'eapm_assigned_user',
'vname' => 'LBL_ASSIGNED_TO_USER',
'source' => 'non-db',
),
'oauth_tokens' =>
array (
'name' => 'oauth_tokens',
'type' => 'link',
'relationship' => 'oauthtokens_assigned_user',
'vname' => 'LBL_OAUTH_TOKENS',
'link_type' => 'one',
'module' => 'OAuthTokens',
'bean_name' => 'OAuthToken',
'source' => 'non-db',
'side' => 'left',
),
'project_resource' =>
array (
'name' => 'project_resource',
'type' => 'link',
'relationship' => 'projects_users_resources',
'source' => 'non-db',
'vname' => 'LBL_PROJECTS',
),
),
'indices' =>
array (
0 =>
array (
'name' => 'userspk',
'type' => 'primary',
'fields' =>
array (
0 => 'id',
),
),
1 =>
array (
'name' => 'idx_user_name',
'type' => 'index',
'fields' =>
array (
0 => 'user_name',
1 => 'is_group',
2 => 'status',
3 => 'last_name',
4 => 'first_name',
5 => 'id',
),
),
),
'relationships' =>
array (
'user_direct_reports' =>
array (
'lhs_module' => 'Users',
'lhs_table' => 'users',
'lhs_key' => 'id',
'rhs_module' => 'Users',
'rhs_table' => 'users',
'rhs_key' => 'reports_to_id',
'relationship_type' => 'one-to-many',
),
'users_users_signatures' =>
array (
'lhs_module' => 'Users',
'lhs_table' => 'users',
'lhs_key' => 'id',
'rhs_module' => 'UserSignature',
'rhs_table' => 'users_signatures',
'rhs_key' => 'user_id',
'relationship_type' => 'one-to-many',
),
'users_email_addresses' =>
array (
'lhs_module' => 'Users',
'lhs_table' => 'users',
'lhs_key' => 'id',
'rhs_module' => 'EmailAddresses',
'rhs_table' => 'email_addresses',
'rhs_key' => 'id',
'relationship_type' => 'many-to-many',
'join_table' => 'email_addr_bean_rel',
'join_key_lhs' => 'bean_id',
'join_key_rhs' => 'email_address_id',
'relationship_role_column' => 'bean_module',
'relationship_role_column_value' => 'Users',
),
'users_email_addresses_primary' =>
array (
'lhs_module' => 'Users',
'lhs_table' => 'users',
'lhs_key' => 'id',
'rhs_module' => 'EmailAddresses',
'rhs_table' => 'email_addresses',
'rhs_key' => 'id',
'relationship_type' => 'many-to-many',
'join_table' => 'email_addr_bean_rel',
'join_key_lhs' => 'bean_id',
'join_key_rhs' => 'email_address_id',
'relationship_role_column' => 'primary_address',
'relationship_role_column_value' => '1',
),
),
'custom_fields' => false,
); | bupendra/Fieldtrip | cache/modules/Employees/Employeevardefs.php | PHP | agpl-3.0 | 19,988 |
/* Theme LESS assets */
/* Fonts */
/* Responsive */
/* Grid */
/* Navigation */
.nav-pills-active-bg-color {
border-radius: 15px;
}
.inputs-style:focus {
box-shadow: none;
}
.flex {
display: flex;
}
.nav-item-before-reset {
height: auto;
width: auto;
background-image: none;
}
.hero {
background-size: cover;
background-position: center;
}
.hero-search {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
position: relative;
}
.hero-search .image-credit {
position: absolute;
text-align: center;
display: block;
padding: 7.5px;
bottom: -10px;
font-size: x-small;
}
.hero-search .image-credit a {
color: currentColor;
text-decoration: underline;
}
.hero-search-symbol {
max-width: 120px;
margin: 0 30px 15px;
}
@media (min-width: 1200px) {
.container {
width: 1140px;
}
.span9 {
width: 880px;
}
}
.wrapper {
border: none;
box-shadow: none;
margin-top: 30px;
margin-bottom: 30px;
}
@media (max-width: 768px) {
.wrapper {
margin: 0;
}
}
/* Required for IE 11 because of this bug: https://goo.gl/LdrTn4 */
_:-ms-fullscreen,
:root [role=main].hero-search {
height: 350px;
}
#content .wrapper {
background: transparent;
}
textarea:focus,
input[type="text"]:focus,
input[type="password"]:focus,
input[type="datetime"]:focus,
input[type="datetime-local"]:focus,
input[type="date"]:focus,
input[type="month"]:focus,
input[type="time"]:focus,
input[type="week"]:focus,
input[type="number"]:focus,
input[type="email"]:focus,
input[type="url"]:focus,
input[type="search"]:focus,
input[type="tel"]:focus,
input[type="color"]:focus,
.uneditable-input:focus {
box-shadow: none;
}
.list-wide li:not(:first-child) {
margin-left: 10px;
}
.list-wide li:not(:last-child) {
margin-right: 10px;
}
@media (min-width: 768px) {
.span9 .page-header {
margin-left: 0;
}
}
.visually-hidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
.account-masthead .account ul li {
border-left: transparent;
}
.masthead {
color: inherit;
padding-top: 30px;
padding-bottom: 30px;
min-height: auto;
}
.masthead .logo {
display: inline-block;
max-width: 270px;
}
@media (max-width: 768px) {
.masthead .container-fluid {
padding-left: 20px;
padding-right: 20px;
}
}
.masthead .btn-navbar,
.masthead .btn-navbar:hover,
.masthead .btn-navbar:focus {
margin-top: 0;
}
.masthead input[type="text"]:focus {
box-shadow: none;
}
.masthead .twitter {
display: none;
}
@media (min-width: 1200px) {
.masthead .twitter {
display: inline-block;
margin-top: 3px;
}
.masthead .twitter + .site-search {
margin-left: 30px;
}
}
.masthead .twitter a {
color: #1DA1F2;
}
.masthead .twitter img {
position: relative;
bottom: 3px;
margin-right: 5px;
}
.language-picker {
list-style: none;
display: inline-block;
margin: 0 0 0 30px;
padding: 0;
}
@media (max-width: 980px) {
.language-picker {
position: absolute;
top: 153px;
right: 30px;
}
}
@media (max-width: 768px) {
.language-picker {
right: 50px;
}
}
@media (max-width: 360px) {
.language-picker {
display: none;
}
}
.language-picker li {
display: inline;
float: left;
}
.language-picker li.active a {
font-weight: 700;
}
.language-picker li a {
display: inline-block;
padding: 10px 15px;
}
.language-picker li a:hover {
text-decoration: none;
}
.header-text-logo h1 {
margin: 0;
}
.btn {
background-image: none;
border-color: transparent;
box-shadow: none;
border-radius: 15px;
}
@media (max-width: 768px) {
.nav-main .nav-collapse .nav {
margin-bottom: 30px;
}
}
.nav-main .nav-collapse .nav > li a {
text-transform: uppercase;
font-size: 16px;
font-weight: 700;
}
@media (max-width: 768px) {
.nav-main .nav-collapse .nav > li a {
margin: 0 15px;
}
}
.nav-main .nav {
margin-top: 15px;
margin-bottom: 15px;
}
.nav-main .nav a {
margin: 0;
padding: 7.5px 15px;
}
@media (min-width: 1200px) {
.nav-main .nav > li:not(:first-child) {
margin-left: 7.5px;
}
}
.nav-simple .nav-item .active {
border-radius: 30px 0 0 30px;
}
.nav-item.active a:before,
.nav-aside.active a:before {
height: auto;
width: auto;
background-image: none;
}
/* All modules */
.module:first-child .module-heading {
border-radius: 15px;
border: none;
overflow: auto;
}
.module:first-child .module-heading .fa:last-child {
margin-right: 3px;
}
.module div.module-content:first-child {
padding-top: 0;
}
.module-shallow .module-content:first-child {
padding-top: 0;
}
.module-shallow .module-content:last-child {
padding-bottom: 0;
}
.context-info .module-content:first-child {
padding-top: 0;
}
.module-heading {
border-radius: 15px;
border: none;
overflow: auto;
}
.module-resource {
margin-bottom: 30px;
}
.module-narrow .nav-item > a {
border-top-left-radius: 15px;
border-bottom-left-radius: 15px;
}
.module-narrow .nav-item > a:hover {
border-radius: 15px;
}
.module-narrow .nav-item.active a:hover {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.module-narrow .nav-aside li a {
border-top-left-radius: 15px;
border-bottom-left-radius: 15px;
}
.module-narrow .nav-aside li a:hover {
border-radius: 15px;
}
/* Search */
.module-hero-search {
width: 50%;
padding: 0;
}
@media (min-width: 1200px) {
.module-hero-search {
width: 35%;
}
}
@media (max-width: 768px) {
.module-hero-search {
width: 80%;
}
}
.module-hero-search:last-child {
margin: 0;
}
.module-hero-search .search-form {
border: none;
margin-bottom: 0;
}
.module-hero-search .search-input {
margin-bottom: 0;
}
.module-hero-search .search-input input {
border-width: 3px;
}
.search-form .search-input.search-giant button {
margin-top: -15px;
}
/* Topics */
.module-topics:last-child {
margin-bottom: 0;
}
.module-topics-list {
margin: 0;
list-style: none;
text-align: center;
}
.module-topics-list .topic {
padding: 15px;
display: block;
font-weight: 700;
}
.module-topics-list .topic-title {
margin-top: 10px;
display: block;
text-transform: uppercase;
}
.module-topics-list li {
max-width: 126px;
text-align: center;
vertical-align: middle;
display: inline-block;
}
.span9 div.module-content {
padding-left: 25px;
}
.toolbar .breadcrumb {
font-size: 14px;
}
.toolbar .breadcrumb li {
margin-right: 6px;
}
.toolbar .breadcrumb li:after {
margin-left: 6px;
}
.toolbar .breadcrumb a {
font-weight: 400;
}
.news {
margin: 15px 0;
}
.news-header {
padding: 6px 15px;
display: flex;
align-items: center;
justify-content: center;
}
.news-header-title {
text-transform: uppercase;
flex-grow: 2;
}
.news-items-container {
display: flex;
flex-direction: column;
}
@media (min-width: 980px) {
.news-items-container {
flex-direction: row;
}
}
.news-item {
display: flex;
overflow: hidden;
flex-direction: column;
justify-content: flex-start;
transition: 200ms padding-top ease-in-out 20ms;
}
@media (max-width: 980px) {
.news-item {
margin-top: 20px;
}
.news-item .news-item-photo img {
min-width: 100%;
max-width: 0;
}
}
@media (min-width: 980px) {
.news-item {
max-width: 33.33%;
margin: 20px 0 0 15px;
}
.news-item:first-child {
margin-left: 0;
}
}
.news-item:hover,
.news-item:focus {
transition: 200ms box-shadow ease-in-out 10ms;
text-decoration: none;
}
.news-item-title {
position: relative;
font-size: 18px;
font-weight: 700;
display: block;
margin-top: 20px;
}
.news-item-description {
position: relative;
display: block;
margin: 15px 0;
}
.news-item-title,
.news-item-description {
margin-left: 15px;
margin-right: 15px;
}
.news-item-photo {
display: flex;
margin: 0;
align-items: center;
justify-content: center;
max-height: 150px;
overflow: hidden;
}
.news-item-photo img {
min-height: 150px;
min-width: inherit;
max-width: inherit;
}
.add-dataset-modal {
position: fixed;
left: 50%;
top: 20%;
transform: translateX(-50%);
z-index: 1050;
display: none;
}
.add-dataset-modal-box {
display: table-cell;
background-color: #ffffff;
border: 1px solid #999;
border-radius: 6px;
box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
background-clip: padding-box;
outline: none;
text-align: center;
}
.add-dataset-modal-description {
margin-top: 30px;
}
.add-dataset-modal-description p {
font-weight: bold;
}
.add-dataset-modal-description ul {
text-align: left;
}
.add-dataset-modal .close {
font-size: 35px;
color: white;
position: relative;
top: -32px;
}
.add-dataset-modal-backdrop {
display: none;
}
#dataset-resources {
border: 1px solid #dddddd;
padding: 15px;
margin-bottom: 10px;
border-radius: 10px;
}
#dataset-resources h3,
#dataset-resources .search-form {
display: inline;
}
.resource-list {
margin-top: 15px;
}
.validate-resource li {
width: 33.333333%;
}
.validate-resource-report-header {
margin-bottom: 30px;
}
.validate-resource-report-error-count {
margin-bottom: 20px;
}
.search {
font-family: inherit;
}
.control-order-by select {
border-radius: 15px;
}
.module-content .search-form .search-input {
margin-bottom: 40px;
}
.search-giant {
padding: 0;
border: 0;
}
.search-giant.search-input input {
border-radius: 30px;
}
#field-user-search,
#field-sitewide-search {
border-radius: 15px;
}
.organization-logos {
padding: 15px 0;
}
.organization-logos .container {
display: flex;
align-items: center;
justify-content: center;
}
@media (max-width: 1200px) {
.organization-logos .container {
flex-direction: column;
}
}
.organization-logos figure {
margin: 15px 30px;
min-width: 150px;
text-align: center;
}
.organization-logos figure img {
max-width: 100%;
max-height: 90px;
}
.organization-logos figure figcaption {
display: none;
margin: 15px 0;
}
.js .image-upload input[type=file] {
cursor: pointer;
position: absolute;
z-index: 1;
opacity: 0;
}
.nav-tabs .fa:last-child,
.module-heading .fa:last-child,
.btn .fa:last-child {
margin-right: 3px;
}
.media-grid {
margin: 0;
}
.media-item {
width: 159px;
}
.resource-tracking-summary {
margin-top: -20px !important;
border-top: none !important;
}
| ViderumGlobal/ckanext-tayside | ckanext/tayside/fanstatic/css/tayside.css | CSS | agpl-3.0 | 10,288 |
# Copyright (C) 2020 Shannon M. Hauck, http://www.smhauck.com
#
# This file is part of Project Useful.
#
# Project Useful is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Project Useful 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Project Useful. If not, see <http://www.gnu.org/licenses/>.
require 'test_helper'
class PagesControllerTest < ActionController::TestCase
test "should get license" do
get :license
assert_response :success
end
test "should get technology" do
get :technology
assert_response :success
end
end
| wbhauck/ProjectUseful | test/controllers/pages_controller_test.rb | Ruby | agpl-3.0 | 1,028 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@Deprecated
package org.kuali.kfs.kns.kim.permission;
| quikkian-ua-devops/will-financials | kfs-kns/src/main/java/org/kuali/kfs/kns/kim/permission/package-info.java | Java | agpl-3.0 | 866 |
+++
title = "Release notes for Grafana 7.3.10"
[_build]
list = false
+++
<!-- Auto generated by update changelog github action -->
# Release notes for Grafana 7.3.10
### Bug fixes
- **Security**: Fix API permissions issues related to team-sync CVE-2021-28146, CVE-2021-28147. (Enterprise)
- **Security**: Usage insights requires signed in users CVE-2021-28148. (Enterprise)
| grafana/grafana | docs/sources/release-notes/release-notes-7-3-10.md | Markdown | agpl-3.0 | 378 |
/*
* core.css
*
* Copyright (c) 2004 David Holroyd, and contributors
* See the file 'COPYING' for terms of use
*
* Part of the Docbook-CSS stylesheet
* http://www.badgers-in-foil.co.uk/projects/docbook-css/
*/
/* Generated 2002-12-12 */
abbrev, accel, acronym, action, application, artpagenums, authorinitials,
bibliocoverage, biblioid, bibliomisc, bibliorelation, bibliosource, citation,
citebiblioid, citerefentry, citetitle, city, classname, co, command,
computeroutput, constant, coref, country, database, date, email, emphasis,
envar, errorcode, errorname, errortext, errortype, exceptionname, fax,
filename, firstname, firstterm, funcdef, funcparams, function, group,
guibutton, guiicon, guilabel, guimenu, guimenuitem, guisubmenu, hardware,
honorific, initializer, inlineequation, inlinegraphic, inlinemediaobject,
interface, interfacename, invpartnumber, isbn, issn, keycap, keycode,
keycombo, keysym, lineage, lineannotation, link, literal, markup, medialabel,
member, menuchoice, methodname, methodparam, modifier, mousebutton, olink,
ooclass, ooexception, oointerface, option, optional, orgdiv, orgname,
otheraddr, othername, pagenums, paramdef, parameter, phone, phrase, pob,
postcode, productname, productnumber, prompt, property, pubdate, pubsnumber,
quote, refpurpose, replaceable, returnvalue, revnumber, seriesvolnums,
sgmltag, shortcut, state, street, structfield, structname, subscript,
superscript, surname, symbol, systemitem, token, trademark, type, ulink,
userinput, varname, volumenum, wordasword, year {
display:inline;
}
abstract, ackno, address, answer, appendix, article, attribution, authorblurb,
bibliodiv, biblioentry, bibliography, bibliomixed, bibliomset, biblioset,
blockquote, book, callout, calloutlist, caption, caution, chapter,
cmdsynopsis, colophon, constraintdef, dedication, epigraph, equation, example,
figure, formalpara, glossary, glossdef, glossdiv, glossentry, glosslist,
graphic, graphicco, highlights, imagedata, imageobjectco, important, index,
indexdiv, indexentry, informalequation, informalexample, informalfigure,
informaltable, itemizedlist, legalnotice, listitem, lot, lotentry,
mediaobject, mediaobjectco, msg, msgentry, msgexplan, msgmain, msgset, note,
orderedlist, para, part, partintro, personblurb, preface, primaryie,
printhistory, procedure, productionset, programlistingco, qandadiv, qandaentry,
qandaset, question, refentry, refentrytitle, reference, refnamediv, refsect1,
refsect2, refsect3, refsection, refsynopsisdiv, revhistory, screenco,
screenshot, secondaryie, sect2, sect3, sect4, sect5, section, seealsoie, seeie,
set, setindex, sidebar, simpara, simplemsgentry, simplesect, step, substeps,
subtitle, synopfragment, synopfragmentref, table, term, tertiaryie, tip,
title, toc, tocback, tocchap, tocentry, tocfront, toclevel1, toclevel2,
toclevel3, toclevel4, toclevel5, tocpart, variablelist, varlistentry, warning,
sect1 {
display:block;
}
appendixinfo, area, areaset, areaspec, articleinfo, bibliographyinfo,
blockinfo, bookinfo, chapterinfo, colspec, glossaryinfo, indexinfo, indexterm,
itermset, modespec, objectinfo, partinfo, prefaceinfo, primary, refentryinfo,
referenceinfo, refmeta, refsect1info, refsect2info, refsect3info,
refsectioninfo, refsynopsisdivinfo, screeninfo, secondary, sect1info,
sect2info, sect3info, sect4info, sect5info, sectioninfo, see, seealso,
setindexinfo, setinfo, sidebarinfo, spanspec, tertiary {
display:none;
}
classsynopsisinfo, funcsynopsisinfo, literallayout, programlisting, screen,
synopsis {
white-space:pre;
font-family:monospace;
display:block;
}
| RajkumarSelvaraju/FixNix_CRM | erp/xmlrpc/doc/docbook-css/core.css | CSS | agpl-3.0 | 3,689 |
import logging
from lxml import etree
from pkg_resources import resource_string
from xmodule.raw_module import RawDescriptor
from .x_module import XModule
from xblock.core import Integer, Scope, String, List, Float, Boolean
from xmodule.open_ended_grading_classes.combined_open_ended_modulev1 import CombinedOpenEndedV1Module, CombinedOpenEndedV1Descriptor
from collections import namedtuple
from .fields import Date, Timedelta
import textwrap
log = logging.getLogger("mitx.courseware")
V1_SETTINGS_ATTRIBUTES = [
"display_name", "max_attempts", "graded", "accept_file_upload",
"skip_spelling_checks", "due", "graceperiod", "weight", "min_to_calibrate",
"max_to_calibrate", "peer_grader_count", "required_peer_grading",
]
V1_STUDENT_ATTRIBUTES = ["current_task_number", "task_states", "state",
"student_attempts", "ready_to_reset", "old_task_states"]
V1_ATTRIBUTES = V1_SETTINGS_ATTRIBUTES + V1_STUDENT_ATTRIBUTES
VersionTuple = namedtuple('VersionTuple', ['descriptor', 'module', 'settings_attributes', 'student_attributes'])
VERSION_TUPLES = {
1: VersionTuple(CombinedOpenEndedV1Descriptor, CombinedOpenEndedV1Module, V1_SETTINGS_ATTRIBUTES,
V1_STUDENT_ATTRIBUTES),
}
DEFAULT_VERSION = 1
DEFAULT_DATA = textwrap.dedent("""\
<combinedopenended>
<prompt>
<h3>Censorship in the Libraries</h3>
<p>'All of us can think of a book that we hope none of our children or any other children have taken off the shelf. But if I have the right to remove that book from the shelf -- that work I abhor -- then you also have exactly the same right and so does everyone else. And then we have no books left on the shelf for any of us.' --Katherine Paterson, Author
</p>
<p>
Write a persuasive essay to a newspaper reflecting your views on censorship in libraries. Do you believe that certain materials, such as books, music, movies, magazines, etc., should be removed from the shelves if they are found offensive? Support your position with convincing arguments from your own experience, observations, and/or reading.
</p>
</prompt>
<rubric>
<rubric>
<category>
<description>
Ideas
</description>
<option>
Difficult for the reader to discern the main idea. Too brief or too repetitive to establish or maintain a focus.
</option>
<option>
Attempts a main idea. Sometimes loses focus or ineffectively displays focus.
</option>
<option>
Presents a unifying theme or main idea, but may include minor tangents. Stays somewhat focused on topic and task.
</option>
<option>
Presents a unifying theme or main idea without going off on tangents. Stays completely focused on topic and task.
</option>
</category>
<category>
<description>
Content
</description>
<option>
Includes little information with few or no details or unrelated details. Unsuccessful in attempts to explore any facets of the topic.
</option>
<option>
Includes little information and few or no details. Explores only one or two facets of the topic.
</option>
<option>
Includes sufficient information and supporting details. (Details may not be fully developed; ideas may be listed.) Explores some facets of the topic.
</option>
<option>
Includes in-depth information and exceptional supporting details that are fully developed. Explores all facets of the topic.
</option>
</category>
<category>
<description>
Organization
</description>
<option>
Ideas organized illogically, transitions weak, and response difficult to follow.
</option>
<option>
Attempts to logically organize ideas. Attempts to progress in an order that enhances meaning, and demonstrates use of transitions.
</option>
<option>
Ideas organized logically. Progresses in an order that enhances meaning. Includes smooth transitions.
</option>
</category>
<category>
<description>
Style
</description>
<option>
Contains limited vocabulary, with many words used incorrectly. Demonstrates problems with sentence patterns.
</option>
<option>
Contains basic vocabulary, with words that are predictable and common. Contains mostly simple sentences (although there may be an attempt at more varied sentence patterns).
</option>
<option>
Includes vocabulary to make explanations detailed and precise. Includes varied sentence patterns, including complex sentences.
</option>
</category>
<category>
<description>
Voice
</description>
<option>
Demonstrates language and tone that may be inappropriate to task and reader.
</option>
<option>
Demonstrates an attempt to adjust language and tone to task and reader.
</option>
<option>
Demonstrates effective adjustment of language and tone to task and reader.
</option>
</category>
</rubric>
</rubric>
<task>
<selfassessment/></task>
<task>
<openended min_score_to_attempt="4" max_score_to_attempt="12" >
<openendedparam>
<initial_display>Enter essay here.</initial_display>
<answer_display>This is the answer.</answer_display>
<grader_payload>{"grader_settings" : "ml_grading.conf", "problem_id" : "6.002x/Welcome/OETest"}</grader_payload>
</openendedparam>
</openended>
</task>
<task>
<openended min_score_to_attempt="9" max_score_to_attempt="12" >
<openendedparam>
<initial_display>Enter essay here.</initial_display>
<answer_display>This is the answer.</answer_display>
<grader_payload>{"grader_settings" : "peer_grading.conf", "problem_id" : "6.002x/Welcome/OETest"}</grader_payload>
</openendedparam>
</openended>
</task>
</combinedopenended>
""")
class VersionInteger(Integer):
"""
A model type that converts from strings to integers when reading from json.
Also does error checking to see if version is correct or not.
"""
def from_json(self, value):
try:
value = int(value)
if value not in VERSION_TUPLES:
version_error_string = "Could not find version {0}, using version {1} instead"
log.error(version_error_string.format(value, DEFAULT_VERSION))
value = DEFAULT_VERSION
except:
value = DEFAULT_VERSION
return value
class CombinedOpenEndedFields(object):
display_name = String(
display_name="Display Name",
help="This name appears in the horizontal navigation at the top of the page.",
default="Open Response Assessment",
scope=Scope.settings
)
current_task_number = Integer(
help="Current task that the student is on.",
default=0,
scope=Scope.user_state
)
old_task_states = List(
help=("A list of lists of state dictionaries for student states that are saved."
"This field is only populated if the instructor changes tasks after"
"the module is created and students have attempted it (for example changes a self assessed problem to "
"self and peer assessed."),
scope = Scope.user_state
)
task_states = List(
help="List of state dictionaries of each task within this module.",
scope=Scope.user_state
)
state = String(
help="Which step within the current task that the student is on.",
default="initial",
scope=Scope.user_state
)
graded = Boolean(
display_name="Graded",
help='Defines whether the student gets credit for grading this problem.',
default=False,
scope=Scope.settings
)
student_attempts = Integer(
help="Number of attempts taken by the student on this problem",
default=0,
scope=Scope.user_state
)
ready_to_reset = Boolean(
help="If the problem is ready to be reset or not.",
default=False,
scope=Scope.user_state
)
max_attempts = Integer(
display_name="Maximum Attempts",
help="The number of times the student can try to answer this problem.",
default=1,
scope=Scope.settings,
values={"min": 1 }
)
accept_file_upload = Boolean(
display_name="Allow File Uploads",
help="Whether or not the student can submit files as a response.",
default=False,
scope=Scope.settings
)
skip_spelling_checks = Boolean(
display_name="Disable Quality Filter",
help="If False, the Quality Filter is enabled and submissions with poor spelling, short length, or poor grammar will not be peer reviewed.",
default=False,
scope=Scope.settings
)
due = Date(
help="Date that this problem is due by",
scope=Scope.settings
)
graceperiod = Timedelta(
help="Amount of time after the due date that submissions will be accepted",
scope=Scope.settings
)
version = VersionInteger(help="Current version number", default=DEFAULT_VERSION, scope=Scope.settings)
data = String(help="XML data for the problem", scope=Scope.content,
default=DEFAULT_DATA)
weight = Float(
display_name="Problem Weight",
help="Defines the number of points each problem is worth. If the value is not set, each problem is worth one point.",
scope=Scope.settings,
values={"min": 0, "step": ".1"},
default=1
)
min_to_calibrate = Integer(
display_name="Minimum Peer Grading Calibrations",
help="The minimum number of calibration essays each student will need to complete for peer grading.",
default=3,
scope=Scope.settings,
values={"min": 1, "max": 20, "step": "1"}
)
max_to_calibrate = Integer(
display_name="Maximum Peer Grading Calibrations",
help="The maximum number of calibration essays each student will need to complete for peer grading.",
default=6,
scope=Scope.settings,
values={"min": 1, "max": 20, "step": "1"}
)
peer_grader_count = Integer(
display_name="Peer Graders per Response",
help="The number of peers who will grade each submission.",
default=3,
scope=Scope.settings,
values={"min": 1, "step": "1", "max": 5}
)
required_peer_grading = Integer(
display_name="Required Peer Grading",
help="The number of other students each student making a submission will have to grade.",
default=3,
scope=Scope.settings,
values={"min": 1, "step": "1", "max": 5}
)
markdown = String(
help="Markdown source of this module",
default=textwrap.dedent("""\
[prompt]
<h3>Censorship in the Libraries</h3>
<p>'All of us can think of a book that we hope none of our children or any other children have taken off the shelf. But if I have the right to remove that book from the shelf -- that work I abhor -- then you also have exactly the same right and so does everyone else. And then we have no books left on the shelf for any of us.' --Katherine Paterson, Author
</p>
<p>
Write a persuasive essay to a newspaper reflecting your vies on censorship in libraries. Do you believe that certain materials, such as books, music, movies, magazines, etc., should be removed from the shelves if they are found offensive? Support your position with convincing arguments from your own experience, observations, and/or reading.
</p>
[prompt]
[rubric]
+ Ideas
- Difficult for the reader to discern the main idea. Too brief or too repetitive to establish or maintain a focus.
- Attempts a main idea. Sometimes loses focus or ineffectively displays focus.
- Presents a unifying theme or main idea, but may include minor tangents. Stays somewhat focused on topic and task.
- Presents a unifying theme or main idea without going off on tangents. Stays completely focused on topic and task.
+ Content
- Includes little information with few or no details or unrelated details. Unsuccessful in attempts to explore any facets of the topic.
- Includes little information and few or no details. Explores only one or two facets of the topic.
- Includes sufficient information and supporting details. (Details may not be fully developed; ideas may be listed.) Explores some facets of the topic.
- Includes in-depth information and exceptional supporting details that are fully developed. Explores all facets of the topic.
+ Organization
- Ideas organized illogically, transitions weak, and response difficult to follow.
- Attempts to logically organize ideas. Attempts to progress in an order that enhances meaning, and demonstrates use of transitions.
- Ideas organized logically. Progresses in an order that enhances meaning. Includes smooth transitions.
+ Style
- Contains limited vocabulary, with many words used incorrectly. Demonstrates problems with sentence patterns.
- Contains basic vocabulary, with words that are predictable and common. Contains mostly simple sentences (although there may be an attempt at more varied sentence patterns).
- Includes vocabulary to make explanations detailed and precise. Includes varied sentence patterns, including complex sentences.
+ Voice
- Demonstrates language and tone that may be inappropriate to task and reader.
- Demonstrates an attempt to adjust language and tone to task and reader.
- Demonstrates effective adjustment of language and tone to task and reader.
[rubric]
[tasks]
(Self), ({4-12}AI), ({9-12}Peer)
[tasks]
"""),
scope=Scope.settings
)
class CombinedOpenEndedModule(CombinedOpenEndedFields, XModule):
"""
This is a module that encapsulates all open ended grading (self assessment, peer assessment, etc).
It transitions between problems, and support arbitrary ordering.
Each combined open ended module contains one or multiple "child" modules.
Child modules track their own state, and can transition between states. They also implement get_html and
handle_ajax.
The combined open ended module transitions between child modules as appropriate, tracks its own state, and passess
ajax requests from the browser to the child module or handles them itself (in the cases of reset and next problem)
ajax actions implemented by all children are:
'save_answer' -- Saves the student answer
'save_assessment' -- Saves the student assessment (or external grader assessment)
'save_post_assessment' -- saves a post assessment (hint, feedback on feedback, etc)
ajax actions implemented by combined open ended module are:
'reset' -- resets the whole combined open ended module and returns to the first child module
'next_problem' -- moves to the next child module
'get_results' -- gets results from a given child module
Types of children. Task is synonymous with child module, so each combined open ended module
incorporates multiple children (tasks):
openendedmodule
selfassessmentmodule
CombinedOpenEndedModule.__init__ takes the same arguments as xmodule.x_module:XModule.__init__
"""
STATE_VERSION = 1
# states
INITIAL = 'initial'
ASSESSING = 'assessing'
INTERMEDIATE_DONE = 'intermediate_done'
DONE = 'done'
icon_class = 'problem'
js = {
'coffee':
[
resource_string(__name__, 'js/src/combinedopenended/display.coffee'),
resource_string(__name__, 'js/src/collapsible.coffee'),
resource_string(__name__, 'js/src/javascript_loader.coffee'),
]
}
js_module_name = "CombinedOpenEnded"
css = {'scss': [resource_string(__name__, 'css/combinedopenended/display.scss')]}
def __init__(self, *args, **kwargs):
"""
Definition file should have one or many task blocks, a rubric block, and a prompt block.
See DEFAULT_DATA for a sample.
"""
XModule.__init__(self, *args, **kwargs)
self.system.set('location', self.location)
if self.task_states is None:
self.task_states = []
if self.old_task_states is None:
self.old_task_states = []
version_tuple = VERSION_TUPLES[self.version]
self.student_attributes = version_tuple.student_attributes
self.settings_attributes = version_tuple.settings_attributes
attributes = self.student_attributes + self.settings_attributes
static_data = {}
instance_state = {k: getattr(self, k) for k in attributes}
self.child_descriptor = version_tuple.descriptor(self.system)
self.child_definition = version_tuple.descriptor.definition_from_xml(etree.fromstring(self.data), self.system)
self.child_module = version_tuple.module(self.system, self.location, self.child_definition, self.child_descriptor,
instance_state=instance_state, static_data=static_data,
attributes=attributes)
self.save_instance_data()
def get_html(self):
self.save_instance_data()
return_value = self.child_module.get_html()
return return_value
def handle_ajax(self, dispatch, data):
self.save_instance_data()
return_value = self.child_module.handle_ajax(dispatch, data)
self.save_instance_data()
return return_value
def get_instance_state(self):
return self.child_module.get_instance_state()
def get_score(self):
return self.child_module.get_score()
def max_score(self):
return self.child_module.max_score()
def get_progress(self):
return self.child_module.get_progress()
@property
def due_date(self):
return self.child_module.due_date
def save_instance_data(self):
for attribute in self.student_attributes:
setattr(self, attribute, getattr(self.child_module, attribute))
class CombinedOpenEndedDescriptor(CombinedOpenEndedFields, RawDescriptor):
"""
Module for adding combined open ended questions
"""
mako_template = "widgets/open-ended-edit.html"
module_class = CombinedOpenEndedModule
has_score = True
always_recalculate_grades = True
template_dir_name = "combinedopenended"
#Specify whether or not to pass in S3 interface
needs_s3_interface = True
#Specify whether or not to pass in open ended interface
needs_open_ended_interface = True
metadata_attributes = RawDescriptor.metadata_attributes
js = {'coffee': [resource_string(__name__, 'js/src/combinedopenended/edit.coffee')]}
js_module_name = "OpenEndedMarkdownEditingDescriptor"
css = {'scss': [resource_string(__name__, 'css/editor/edit.scss'), resource_string(__name__, 'css/combinedopenended/edit.scss')]}
metadata_translations = {
'is_graded': 'graded',
'attempts': 'max_attempts',
}
def get_context(self):
_context = RawDescriptor.get_context(self)
_context.update({'markdown': self.markdown,
'enable_markdown': self.markdown is not None})
return _context
@property
def non_editable_metadata_fields(self):
non_editable_fields = super(CombinedOpenEndedDescriptor, self).non_editable_metadata_fields
non_editable_fields.extend([CombinedOpenEndedDescriptor.due, CombinedOpenEndedDescriptor.graceperiod,
CombinedOpenEndedDescriptor.markdown, CombinedOpenEndedDescriptor.version])
return non_editable_fields
| pdehaye/theming-edx-platform | common/lib/xmodule/xmodule/combined_open_ended_module.py | Python | agpl-3.0 | 21,389 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_seq_packet_socket::close (1 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../close.html" title="basic_seq_packet_socket::close">
<link rel="prev" href="../close.html" title="basic_seq_packet_socket::close">
<link rel="next" href="overload2.html" title="basic_seq_packet_socket::close (2 of 2 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../close.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../close.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_asio.reference.basic_seq_packet_socket.close.overload1"></a><a class="link" href="overload1.html" title="basic_seq_packet_socket::close (1 of 2 overloads)">basic_seq_packet_socket::close
(1 of 2 overloads)</a>
</h5></div></div></div>
<p>
<span class="emphasis"><em>Inherited from basic_socket.</em></span>
</p>
<p>
Close the socket.
</p>
<pre class="programlisting"><span class="keyword">void</span> <span class="identifier">close</span><span class="special">();</span>
</pre>
<p>
This function is used to close the socket. Any asynchronous send, receive
or connect operations will be cancelled immediately, and will complete
with the <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">operation_aborted</span></code> error.
</p>
<h6>
<a name="boost_asio.reference.basic_seq_packet_socket.close.overload1.h0"></a>
<span class="phrase"><a name="boost_asio.reference.basic_seq_packet_socket.close.overload1.exceptions"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_seq_packet_socket.close.overload1.exceptions">Exceptions</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl class="variablelist">
<dt><span class="term">boost::system::system_error</span></dt>
<dd><p>
Thrown on failure. Note that, even if the function indicates an
error, the underlying descriptor is closed.
</p></dd>
</dl>
</div>
<h6>
<a name="boost_asio.reference.basic_seq_packet_socket.close.overload1.h1"></a>
<span class="phrase"><a name="boost_asio.reference.basic_seq_packet_socket.close.overload1.remarks"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_seq_packet_socket.close.overload1.remarks">Remarks</a>
</h6>
<p>
For portable behaviour with respect to graceful closure of a connected
socket, call <code class="computeroutput"><span class="identifier">shutdown</span><span class="special">()</span></code> before closing the socket.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2017 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../close.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../close.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| cris-iisc/mpc-primitives | crislib/libscapi/lib/boost_1_64_0/doc/html/boost_asio/reference/basic_seq_packet_socket/close/overload1.html | HTML | agpl-3.0 | 5,147 |
/**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.classifieds.servlets;
import com.silverpeas.classifieds.control.ClassifiedsRole;
import com.silverpeas.classifieds.control.ClassifiedsSessionController;
import com.silverpeas.classifieds.servlets.handler.HandlerProvider;
import com.silverpeas.look.LookHelper;
import com.stratelia.silverpeas.peasCore.ComponentContext;
import com.stratelia.silverpeas.peasCore.MainSessionController;
import com.stratelia.silverpeas.peasCore.servlets.ComponentRequestRouter;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import org.silverpeas.servlet.HttpRequest;
import javax.servlet.http.HttpServletRequest;
public class ClassifiedsRequestRouter extends ComponentRequestRouter<ClassifiedsSessionController> {
private static final long serialVersionUID = -4872776979680116068L;
/**
* This method has to be implemented in the component request rooter class. returns the session
* control bean name to be put in the request object ex : for almanach, returns "almanach"
*/
@Override
public String getSessionControlBeanName() {
return "classifieds";
}
/**
* Method declaration
*
* @param mainSessionCtrl
* @param componentContext
* @return
* @see
*/
@Override
public ClassifiedsSessionController createComponentSessionController(
MainSessionController mainSessionCtrl, ComponentContext componentContext) {
return new ClassifiedsSessionController(mainSessionCtrl, componentContext);
}
/**
* This method has to be implemented by the component request rooter it has to compute a
* destination page
*
*
* @param function The entering request function (ex : "Main.jsp")
* @param classifiedsSC The component Session Control, build and initialised.
* @param request
* @return The complete destination URL for a forward (ex : "/almanach/jsp/almanach.jsp?flag=user")
*/
@Override
public String getDestination(String function, ClassifiedsSessionController classifiedsSC,
HttpRequest request) {
String destination = "";
String rootDest = "/classifieds/jsp/";
SilverTrace.info("classifieds", "classifiedsRequestRouter.getDestination()",
"root.MSG_GEN_PARAM_VALUE", "User=" + classifiedsSC.getUserId() + " Function=" + function);
// Common parameters
ClassifiedsRole highestRole = (isAnonymousAccess(request)) ? ClassifiedsRole.ANONYMOUS :
ClassifiedsRole.getRole(classifiedsSC.getUserRoles());
String userId = classifiedsSC.getUserId();
// Store them in request as attributes
request.setAttribute("Profile", highestRole);
request.setAttribute("UserId", userId);
request.setAttribute("InstanceId", classifiedsSC.getComponentId());
request.setAttribute("Language", classifiedsSC.getLanguage());
request.setAttribute("isWysiwygHeaderEnabled", classifiedsSC.isWysiwygHeaderEnabled());
SilverTrace.debug("classifieds", "classifiedsRequestRouter.getDestination()",
"root.MSG_GEN_PARAM_VALUE", "Profile=" + highestRole);
try {
// Delegate to specific Handler
FunctionHandler handler = HandlerProvider.getHandler(function);
if (handler != null) {
destination = handler.computeDestination(classifiedsSC, request);
} else {
destination = rootDest + function;
}
} catch (Exception e) {
request.setAttribute("javax.servlet.jsp.jspException", e);
return "/admin/jsp/errorpageMain.jsp";
}
SilverTrace.info("classifieds", "classifiedsRequestRouter.getDestination()",
"root.MSG_GEN_PARAM_VALUE", "Destination=" + destination);
return destination;
}
private boolean isAnonymousAccess(HttpServletRequest request) {
LookHelper lookHelper = (LookHelper) request.getSession().getAttribute(LookHelper.SESSION_ATT);
if (lookHelper != null) {
return lookHelper.isAnonymousAccess();
}
return false;
}
} | CecileBONIN/Silverpeas-Components | classifieds/classifieds-war/src/main/java/com/silverpeas/classifieds/servlets/ClassifiedsRequestRouter.java | Java | agpl-3.0 | 5,037 |
class Api::StatsController < Api::ApiController
def show
unless params[:events].present? || params[:visits].present?
return render json: {}, status: :bad_request
end
ds = Ahoy::DataSource.new
if params[:events].present?
event_types = params[:events].split ','
event_types.each do |event|
ds.add event.titleize, Ahoy::Event.where(name: event).group_by_day(:time).count
end
end
if params[:visits].present?
ds.add "Visits", Visit.group_by_day(:started_at).count
end
render json: ds.build
end
end
| eloy/participacion | app/controllers/api/stats_controller.rb | Ruby | agpl-3.0 | 571 |
/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#pragma once
#ifndef OOX_EXTERNAL_INCLUDE_H_
#define OOX_EXTERNAL_INCLUDE_H_
#include "../File.h"
#include "../FileTypes.h"
namespace OOX
{
class External : public File
{
public:
External(OOX::Document* pMain) : File(pMain)
{
}
External(OOX::Document* pMain, const CPath& uri) : File(pMain)
{
read(uri);
}
~External()
{
}
virtual void read(const CPath& uri)
{
m_uri = uri;
}
virtual void write(const CPath& filename, const CPath& directory, CContentTypes& content) const
{
}
CPath Uri() const
{
return m_uri;
}
void set_Uri(CPath & file_path)
{
m_uri = file_path;
m_sOutputFilename = file_path.GetFilename();
}
protected:
CPath m_uri;
};
} // namespace OOX
#endif // OOX_EXTERNAL_INCLUDE_H_
| ONLYOFFICE/core | Common/DocxFormat/Source/DocxFormat/External/External.h | C | agpl-3.0 | 2,393 |
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key`
# by default. You can change it below and use your own secret key.
config.secret_key = '486ed5e25dcabac12a62c72a26e8057cfc2b822dd46c8b593a77aa95479bac481c3d70d5e5ee88a04aac3cf9b40e592575ca7674e248ff747f5afcdf3a320969'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [:email]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# encryptor), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = '43d5d80fc0a95d9aa618ca138b747b1d7623020544249e2672bf3a19846fa47baa29117cba30c9edcd3fcd10d379cd65c485a3f931a7a19efb3a794796828432'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 8..72
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| eloy/participacion | config/initializers/devise.rb | Ruby | agpl-3.0 | 13,108 |
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_TEST_MAIN
#define BOOST_TEST_IGNORE_SIGCHLD
#include <boost/test/included/unit_test.hpp>
#include <boost/process/exe.hpp>
#include <boost/process/args.hpp>
#include <boost/process/cmd.hpp>
#include <boost/process/io.hpp>
#include <boost/process/error.hpp>
#include <boost/process/child.hpp>
#include <boost/algorithm/string/predicate.hpp>
namespace bp = boost::process;
BOOST_AUTO_TEST_CASE(args, *boost::unit_test::timeout(2))
{
using boost::unit_test::framework::master_test_suite;
bp::ipstream is;
std::error_code ec;
bp::child c(
master_test_suite().argv[1],
L"test", "--echo-argv", L"hello thingy", "\"stuff\"", static_cast<const wchar_t*>(L" spa ce "),
bp::std_out>is,
ec
);
if (ec)
std::cout << "EC: " << ec.message() << std::endl;
BOOST_REQUIRE(!ec);
return ;
std::string s;
std::getline(is, s);
s.resize(4);
BOOST_CHECK_EQUAL(s, "test");
std::getline(is, s);
s.resize(11);
BOOST_CHECK_EQUAL(s, "--echo-argv");
std::getline(is, s);
s.resize(12);
BOOST_CHECK_EQUAL(s, "hello thingy");
std::getline(is, s);
s.resize(7);
BOOST_CHECK_EQUAL(s, "\"stuff\"");
std::getline(is, s);
s.resize(10);
BOOST_CHECK_EQUAL(s, " spa ce ");
}
BOOST_AUTO_TEST_CASE(cmd, *boost::unit_test::timeout(2))
{
using boost::unit_test::framework::master_test_suite;
bp::ipstream is;
std::error_code ec;
std::wstring cmd =
bp::detail::convert(master_test_suite().argv[1]);
cmd+= L" test --echo-argv \"hello thingy\" \\\"stuff\\\" \" spa ce \"";
bp::child c(cmd,
bp::std_out>is,
ec
);
BOOST_REQUIRE(!ec);
return ;
std::string s;
std::getline(is, s);
s.resize(4);
BOOST_CHECK_EQUAL(s, "test");
std::getline(is, s);
s.resize(11);
BOOST_CHECK_EQUAL(s, "--echo-argv");
std::getline(is, s);
s.resize(12);
BOOST_CHECK_EQUAL(s, "hello thingy");
std::getline(is, s);
s.resize(7);
BOOST_CHECK_EQUAL(s, "\"stuff\"");
std::getline(is, s);
s.resize(10);
BOOST_CHECK_EQUAL(s, " spa ce ");
}
| cris-iisc/mpc-primitives | crislib/libscapi/lib/boost_1_64_0/libs/process/test/wargs_cmd.cpp | C++ | agpl-3.0 | 2,661 |
.synopsis, .classsynopsis
{
background: #eeeeee;
border: solid 1px #aaaaaa;
padding: 0.5em;
}
.programlisting
{
background: #eeeeff;
border: solid 1px #aaaaff;
padding: 0.5em;
}
.variablelist
{
padding: 4px;
margin-left: 3em;
}
.variablelist td:first-child
{
vertical-align: top;
}
table.navigation
{
background: #ffeeee;
border: solid 1px #ffaaaa;
margin-top: 0.5em;
margin-bottom: 0.5em;
}
.navigation a
{
color: #770000;
}
.navigation a:visited
{
color: #550000;
}
.navigation .title
{
font-size: 200%;
}
div.refnamediv
{
margin-top: 2em;
}
div.gallery-float
{
float: left;
padding: 10px;
}
div.gallery-float img
{
border-style: none;
}
div.gallery-spacer
{
clear: both;
}
a
{
text-decoration: none;
}
a:hover
{
text-decoration: underline;
color: #FF0000;
}
| ONLYOFFICE/core | DesktopEditor/xml/libxml2/doc/devhelp/style.css | CSS | agpl-3.0 | 886 |
package android.support.v7.view.menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
public final class h extends BaseAdapter {
final /* synthetic */ g a;
private int b = -1;
public h(g gVar) {
this.a = gVar;
a();
}
private void a() {
m mVar = this.a.c.j;
if (mVar != null) {
ArrayList j = this.a.c.j();
int size = j.size();
for (int i = 0; i < size; i++) {
if (((m) j.get(i)) == mVar) {
this.b = i;
return;
}
}
}
this.b = -1;
}
public final m a(int i) {
ArrayList j = this.a.c.j();
int a = this.a.i + i;
if (this.b >= 0 && a >= this.b) {
a++;
}
return (m) j.get(a);
}
public final int getCount() {
int size = this.a.c.j().size() - this.a.i;
return this.b < 0 ? size : size - 1;
}
public final /* synthetic */ Object getItem(int i) {
return a(i);
}
public final long getItemId(int i) {
return (long) i;
}
public final View getView(int i, View view, ViewGroup viewGroup) {
View inflate = view == null ? this.a.b.inflate(this.a.f, viewGroup, false) : view;
((aa) inflate).a(a(i));
return inflate;
}
public final void notifyDataSetChanged() {
a();
super.notifyDataSetChanged();
}
}
| WenbinHou/PKUAutoGateway.Android | Reference/IPGWAndroid/android/support/v7/view/menu/h.java | Java | agpl-3.0 | 1,526 |
<!-- | template to change password -->
<?php
// deny direct access
defined('TS_INIT') OR die('Access denied!');
?>
<h1><?php $this->set('SHOWSETLOGIN__H1'); ?></h1>
<p>
<?php $this->set('SHOWSETLOGIN__INFOTEXT'); ?>
</p>
<form action="?event=setLogin" method="post" class="ts_form">
<fieldset>
<legend><?php echo $this->set('SHOWSETLOGIN__LEGEND'); ?></legend>
<label for="system_users__formLogin__password"><?php echo $this->set('SHOWSETLOGIN__PASSWORD'); ?></label>
<input type="password" name="pass" />
<div style="clear:both;"></div>
</fieldset>
<input type="submit" class="ts_submit" value="<?php echo $this->set('SHOWSETLOGIN__SUBMIT'); ?>" />
</form>
| nfrickler/tsunic | admin/templates/showSetLogin.tpl.php | PHP | agpl-3.0 | 678 |
<?php
// created: 2015-03-22 17:52:16
$dictionary["yo_Sales"]["fields"]["yo_amortizationschedule_yo_sales"] = array (
'name' => 'yo_amortizationschedule_yo_sales',
'type' => 'link',
'relationship' => 'yo_amortizationschedule_yo_sales',
'source' => 'non-db',
'module' => 'yo_AmortizationSchedule',
'bean_name' => false,
'side' => 'right',
'vname' => 'LBL_YO_AMORTIZATIONSCHEDULE_YO_SALES_FROM_YO_AMORTIZATIONSCHEDULE_TITLE',
);
| shoaib-fazal16/yourown | custom/Extension/modules/yo_Sales/Ext/Vardefs/yo_amortizationschedule_yo_sales_yo_Sales.php | PHP | agpl-3.0 | 443 |
package de.static_interface.sinkcity.database.rows;
import de.static_interface.sinkcity.database.tables.CityTable;
import de.static_interface.sinklibrary.database.Row;
import de.static_interface.sinklibrary.database.annotation.Column;
import de.static_interface.sinklibrary.database.annotation.ForeignKey;
public class CityRankRow implements Row {
@Column(keyLength = 36)
@ForeignKey(table = CityTable.class, column = "cityId")
public String cityId;
@Column(primaryKey = true, autoIncrement = true)
public Integer rankId;
@Column
public String rankName;
}
| Static-Interface/SinkCity | src/main/java/de/static_interface/sinkcity/database/rows/CityRankRow.java | Java | agpl-3.0 | 590 |
# Copyright 2020 Tecnativa - Alexandre Díaz
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from copy import deepcopy
from xml.sax.saxutils import escape
from lxml import etree as ElementTree
from odoo import SUPERUSER_ID, api
def _merge_views(env, xmlids):
old_view_ids = env["ir.ui.view"].search(
[("key", "in", xmlids), ("active", "=", True)]
)
# Get only the edited version of the views (if has it)
old_view_ids_edited = old_view_ids.filtered("website_id")
old_view_ids_edited_keys = old_view_ids_edited.mapped("key")
views_to_discard = env["ir.ui.view"]
for old_view in old_view_ids:
if not old_view.website_id and old_view.key in old_view_ids_edited_keys:
views_to_discard |= old_view
old_view_ids -= views_to_discard
new_website_page = env.ref("website_legal_page.legal_page_page")
new_view_id = env.ref("website_legal_page.legal_page")
# 'Dolly' separator element
separator = ElementTree.fromstring(
"<div class='s_hr text-left pt32 pb32' data-name='Separator'>"
+ "<hr class='s_hr_1px s_hr_solid border-600 w-100 mx-auto'/></div>"
)
# Replace new content with the old one per website
website_ids = old_view_ids.mapped("website_id")
for website_id in website_ids:
new_xml = ElementTree.fromstring(new_view_id.arch)
table_content_list = new_xml.xpath("//div[@id='section_list']/ul")[0]
sections_content = new_xml.xpath("//div[@id='section_content']")[0]
has_views_edited = any(
old_view_ids_edited.filtered(lambda x: x.website_id == website_id)
)
# Remove 'IS A SAMPLE' alert
if has_views_edited:
alert = new_xml.xpath(
"//section[@data-name='Title']//div[@data-name='Alert']"
)[0]
alert.find("..").remove(alert)
# Remove unused content
for child in table_content_list.getchildren():
table_content_list.remove(child)
for child in sections_content.getchildren():
sections_content.remove(child)
views_done = env["ir.ui.view"]
for old_view_id in old_view_ids:
if old_view_id.website_id != website_id:
continue
anchor_name = old_view_id.key.split(".")[1]
# Insert item in table content list
list_item = ElementTree.fromstring(
"<li><p><a href='#{}'>{}</a></p></li>".format(
anchor_name, escape(old_view_id.name)
)
)
table_content_list.append(list_item)
# Insert section content
old_xml = ElementTree.fromstring(old_view_id.arch)
old_content = old_xml.xpath("//div[@id='wrap']")[0]
sections_content.append(deepcopy(separator))
sections_content.append(
ElementTree.fromstring(
"<a class='legal_anchor' id='%s'/>" % anchor_name
)
)
for children in old_content.getchildren():
sections_content.append(children)
views_done |= old_view_id
old_view_ids -= views_done
# Create a new page with the changes
view_id = env["ir.ui.view"].create(
{
"arch": ElementTree.tostring(new_xml, encoding="unicode"),
"website_id": website_id.id,
"key": new_view_id.key,
"name": new_view_id.name,
"type": "qweb",
}
)
env["website.page"].create(
{
"name": new_website_page.name,
"url": new_website_page.url,
"view_id": view_id.id,
"is_published": True,
"website_id": website_id.id,
"website_indexed": True,
"website_published": True,
}
)
def post_init_hook(cr, registry):
with api.Environment.manage():
env = api.Environment(cr, SUPERUSER_ID, {})
is_website_sale_installed = (
env["ir.module.module"].search_count(
[("name", "=", "website_sale"), ("state", "=", "installed")]
)
> 0
)
if is_website_sale_installed:
_merge_views(env, ["website_sale.terms"])
| OCA/website | website_legal_page/hooks.py | Python | agpl-3.0 | 4,340 |
using System.Collections;
using System.Collections.Generic;
using GameRunTests;
using NaughtyAttributes;
using UnityEngine;
public partial class TestAction
{
public bool ShowSetTile => SpecifiedAction == ActionType.SetTile;
[AllowNesting] [ShowIf(nameof(ShowSetTile))] public SetTile SetTileData;
[System.Serializable]
public class SetTile
{
public Vector3 WorldPosition;
public LayerTile LayerTile;
public string MatrixName;
public LayerType tileLayerRemove;
// public Matrix4x4 matrix; //has terrible inspector and Defaults to invalid Option
// public Color Colour; // Defaults to bad option
public bool Initiate(TestRunSO TestRunSO)
{
MatrixInfo _Magix = UsefulFunctions.GetCorrectMatrix(MatrixName, WorldPosition);
if (LayerTile == null)
{
_Magix.Matrix.MetaTileMap.RemoveTileWithlayer(WorldPosition.ToLocal(_Magix).RoundToInt(), tileLayerRemove);
}
else
{
_Magix.Matrix.MetaTileMap.SetTile(WorldPosition.ToLocal(_Magix).RoundToInt(), LayerTile, Matrix4x4.identity,
Color.white);
}
return true;
}
}
public bool InitiateSetTile(TestRunSO TestRunSO)
{
return SetTileData.Initiate(TestRunSO);
}
} | unitystation/unitystation | UnityProject/Assets/Tests/PlayModeTests/RunTests/ActionTypes/ActionSetTile.cs | C# | agpl-3.0 | 1,178 |
/*
**********************************************************************
* Copyright (C) 1997-2015, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*
* File USCRIPT.H
*
* Modification History:
*
* Date Name Description
* 07/06/2001 Ram Creation.
******************************************************************************
*/
#ifndef USCRIPT_H
#define USCRIPT_H
#include "unicode/utypes.h"
/**
* \file
* \brief C API: Unicode Script Information
*/
/**
* Constants for ISO 15924 script codes.
*
* The current set of script code constants supports at least all scripts
* that are encoded in the version of Unicode which ICU currently supports.
* The names of the constants are usually derived from the
* Unicode script property value aliases.
* See UAX #24 Unicode Script Property (http://www.unicode.org/reports/tr24/)
* and http://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt .
*
* Starting with ICU 3.6, constants for most ISO 15924 script codes
* are included, for use with language tags, CLDR data, and similar.
* Some of those codes are not used in the Unicode Character Database (UCD).
* For example, there are no characters that have a UCD script property value of
* Hans or Hant. All Han ideographs have the Hani script property value in Unicode.
*
* Private-use codes Qaaa..Qabx are not included.
*
* Starting with ICU 55, script codes are only added when their scripts
* have been or will certainly be encoded in Unicode,
* and have been assigned Unicode script property value aliases,
* to ensure that their script names are stable and match the names of the constants.
* Script codes like Latf and Aran that are not subject to separate encoding
* may be added at any time.
*
* @stable ICU 2.2
*/
typedef enum UScriptCode {
/*
* Note: UScriptCode constants and their ISO script code comments
* are parsed by preparseucd.py.
* It matches lines like
* USCRIPT_<Unicode Script value name> = <integer>, / * <ISO script code> * /
*/
/** @stable ICU 2.2 */
USCRIPT_INVALID_CODE = -1,
/** @stable ICU 2.2 */
USCRIPT_COMMON = 0, /* Zyyy */
/** @stable ICU 2.2 */
USCRIPT_INHERITED = 1, /* Zinh */ /* "Code for inherited script", for non-spacing combining marks; also Qaai */
/** @stable ICU 2.2 */
USCRIPT_ARABIC = 2, /* Arab */
/** @stable ICU 2.2 */
USCRIPT_ARMENIAN = 3, /* Armn */
/** @stable ICU 2.2 */
USCRIPT_BENGALI = 4, /* Beng */
/** @stable ICU 2.2 */
USCRIPT_BOPOMOFO = 5, /* Bopo */
/** @stable ICU 2.2 */
USCRIPT_CHEROKEE = 6, /* Cher */
/** @stable ICU 2.2 */
USCRIPT_COPTIC = 7, /* Copt */
/** @stable ICU 2.2 */
USCRIPT_CYRILLIC = 8, /* Cyrl */
/** @stable ICU 2.2 */
USCRIPT_DESERET = 9, /* Dsrt */
/** @stable ICU 2.2 */
USCRIPT_DEVANAGARI = 10, /* Deva */
/** @stable ICU 2.2 */
USCRIPT_ETHIOPIC = 11, /* Ethi */
/** @stable ICU 2.2 */
USCRIPT_GEORGIAN = 12, /* Geor */
/** @stable ICU 2.2 */
USCRIPT_GOTHIC = 13, /* Goth */
/** @stable ICU 2.2 */
USCRIPT_GREEK = 14, /* Grek */
/** @stable ICU 2.2 */
USCRIPT_GUJARATI = 15, /* Gujr */
/** @stable ICU 2.2 */
USCRIPT_GURMUKHI = 16, /* Guru */
/** @stable ICU 2.2 */
USCRIPT_HAN = 17, /* Hani */
/** @stable ICU 2.2 */
USCRIPT_HANGUL = 18, /* Hang */
/** @stable ICU 2.2 */
USCRIPT_HEBREW = 19, /* Hebr */
/** @stable ICU 2.2 */
USCRIPT_HIRAGANA = 20, /* Hira */
/** @stable ICU 2.2 */
USCRIPT_KANNADA = 21, /* Knda */
/** @stable ICU 2.2 */
USCRIPT_KATAKANA = 22, /* Kana */
/** @stable ICU 2.2 */
USCRIPT_KHMER = 23, /* Khmr */
/** @stable ICU 2.2 */
USCRIPT_LAO = 24, /* Laoo */
/** @stable ICU 2.2 */
USCRIPT_LATIN = 25, /* Latn */
/** @stable ICU 2.2 */
USCRIPT_MALAYALAM = 26, /* Mlym */
/** @stable ICU 2.2 */
USCRIPT_MONGOLIAN = 27, /* Mong */
/** @stable ICU 2.2 */
USCRIPT_MYANMAR = 28, /* Mymr */
/** @stable ICU 2.2 */
USCRIPT_OGHAM = 29, /* Ogam */
/** @stable ICU 2.2 */
USCRIPT_OLD_ITALIC = 30, /* Ital */
/** @stable ICU 2.2 */
USCRIPT_ORIYA = 31, /* Orya */
/** @stable ICU 2.2 */
USCRIPT_RUNIC = 32, /* Runr */
/** @stable ICU 2.2 */
USCRIPT_SINHALA = 33, /* Sinh */
/** @stable ICU 2.2 */
USCRIPT_SYRIAC = 34, /* Syrc */
/** @stable ICU 2.2 */
USCRIPT_TAMIL = 35, /* Taml */
/** @stable ICU 2.2 */
USCRIPT_TELUGU = 36, /* Telu */
/** @stable ICU 2.2 */
USCRIPT_THAANA = 37, /* Thaa */
/** @stable ICU 2.2 */
USCRIPT_THAI = 38, /* Thai */
/** @stable ICU 2.2 */
USCRIPT_TIBETAN = 39, /* Tibt */
/** Canadian_Aboriginal script. @stable ICU 2.6 */
USCRIPT_CANADIAN_ABORIGINAL = 40, /* Cans */
/** Canadian_Aboriginal script (alias). @stable ICU 2.2 */
USCRIPT_UCAS = USCRIPT_CANADIAN_ABORIGINAL,
/** @stable ICU 2.2 */
USCRIPT_YI = 41, /* Yiii */
/* New scripts in Unicode 3.2 */
/** @stable ICU 2.2 */
USCRIPT_TAGALOG = 42, /* Tglg */
/** @stable ICU 2.2 */
USCRIPT_HANUNOO = 43, /* Hano */
/** @stable ICU 2.2 */
USCRIPT_BUHID = 44, /* Buhd */
/** @stable ICU 2.2 */
USCRIPT_TAGBANWA = 45, /* Tagb */
/* New scripts in Unicode 4 */
/** @stable ICU 2.6 */
USCRIPT_BRAILLE = 46, /* Brai */
/** @stable ICU 2.6 */
USCRIPT_CYPRIOT = 47, /* Cprt */
/** @stable ICU 2.6 */
USCRIPT_LIMBU = 48, /* Limb */
/** @stable ICU 2.6 */
USCRIPT_LINEAR_B = 49, /* Linb */
/** @stable ICU 2.6 */
USCRIPT_OSMANYA = 50, /* Osma */
/** @stable ICU 2.6 */
USCRIPT_SHAVIAN = 51, /* Shaw */
/** @stable ICU 2.6 */
USCRIPT_TAI_LE = 52, /* Tale */
/** @stable ICU 2.6 */
USCRIPT_UGARITIC = 53, /* Ugar */
/** New script code in Unicode 4.0.1 @stable ICU 3.0 */
USCRIPT_KATAKANA_OR_HIRAGANA = 54,/*Hrkt */
/* New scripts in Unicode 4.1 */
/** @stable ICU 3.4 */
USCRIPT_BUGINESE = 55, /* Bugi */
/** @stable ICU 3.4 */
USCRIPT_GLAGOLITIC = 56, /* Glag */
/** @stable ICU 3.4 */
USCRIPT_KHAROSHTHI = 57, /* Khar */
/** @stable ICU 3.4 */
USCRIPT_SYLOTI_NAGRI = 58, /* Sylo */
/** @stable ICU 3.4 */
USCRIPT_NEW_TAI_LUE = 59, /* Talu */
/** @stable ICU 3.4 */
USCRIPT_TIFINAGH = 60, /* Tfng */
/** @stable ICU 3.4 */
USCRIPT_OLD_PERSIAN = 61, /* Xpeo */
/* New script codes from Unicode and ISO 15924 */
/** @stable ICU 3.6 */
USCRIPT_BALINESE = 62, /* Bali */
/** @stable ICU 3.6 */
USCRIPT_BATAK = 63, /* Batk */
/** @stable ICU 3.6 */
USCRIPT_BLISSYMBOLS = 64, /* Blis */
/** @stable ICU 3.6 */
USCRIPT_BRAHMI = 65, /* Brah */
/** @stable ICU 3.6 */
USCRIPT_CHAM = 66, /* Cham */
/** @stable ICU 3.6 */
USCRIPT_CIRTH = 67, /* Cirt */
/** @stable ICU 3.6 */
USCRIPT_OLD_CHURCH_SLAVONIC_CYRILLIC = 68, /* Cyrs */
/** @stable ICU 3.6 */
USCRIPT_DEMOTIC_EGYPTIAN = 69, /* Egyd */
/** @stable ICU 3.6 */
USCRIPT_HIERATIC_EGYPTIAN = 70, /* Egyh */
/** @stable ICU 3.6 */
USCRIPT_EGYPTIAN_HIEROGLYPHS = 71, /* Egyp */
/** @stable ICU 3.6 */
USCRIPT_KHUTSURI = 72, /* Geok */
/** @stable ICU 3.6 */
USCRIPT_SIMPLIFIED_HAN = 73, /* Hans */
/** @stable ICU 3.6 */
USCRIPT_TRADITIONAL_HAN = 74, /* Hant */
/** @stable ICU 3.6 */
USCRIPT_PAHAWH_HMONG = 75, /* Hmng */
/** @stable ICU 3.6 */
USCRIPT_OLD_HUNGARIAN = 76, /* Hung */
/** @stable ICU 3.6 */
USCRIPT_HARAPPAN_INDUS = 77, /* Inds */
/** @stable ICU 3.6 */
USCRIPT_JAVANESE = 78, /* Java */
/** @stable ICU 3.6 */
USCRIPT_KAYAH_LI = 79, /* Kali */
/** @stable ICU 3.6 */
USCRIPT_LATIN_FRAKTUR = 80, /* Latf */
/** @stable ICU 3.6 */
USCRIPT_LATIN_GAELIC = 81, /* Latg */
/** @stable ICU 3.6 */
USCRIPT_LEPCHA = 82, /* Lepc */
/** @stable ICU 3.6 */
USCRIPT_LINEAR_A = 83, /* Lina */
/** @stable ICU 4.6 */
USCRIPT_MANDAIC = 84, /* Mand */
/** @stable ICU 3.6 */
USCRIPT_MANDAEAN = USCRIPT_MANDAIC,
/** @stable ICU 3.6 */
USCRIPT_MAYAN_HIEROGLYPHS = 85, /* Maya */
/** @stable ICU 4.6 */
USCRIPT_MEROITIC_HIEROGLYPHS = 86, /* Mero */
/** @stable ICU 3.6 */
USCRIPT_MEROITIC = USCRIPT_MEROITIC_HIEROGLYPHS,
/** @stable ICU 3.6 */
USCRIPT_NKO = 87, /* Nkoo */
/** @stable ICU 3.6 */
USCRIPT_ORKHON = 88, /* Orkh */
/** @stable ICU 3.6 */
USCRIPT_OLD_PERMIC = 89, /* Perm */
/** @stable ICU 3.6 */
USCRIPT_PHAGS_PA = 90, /* Phag */
/** @stable ICU 3.6 */
USCRIPT_PHOENICIAN = 91, /* Phnx */
/** @stable ICU 52 */
USCRIPT_MIAO = 92, /* Plrd */
/** @stable ICU 3.6 */
USCRIPT_PHONETIC_POLLARD = USCRIPT_MIAO,
/** @stable ICU 3.6 */
USCRIPT_RONGORONGO = 93, /* Roro */
/** @stable ICU 3.6 */
USCRIPT_SARATI = 94, /* Sara */
/** @stable ICU 3.6 */
USCRIPT_ESTRANGELO_SYRIAC = 95, /* Syre */
/** @stable ICU 3.6 */
USCRIPT_WESTERN_SYRIAC = 96, /* Syrj */
/** @stable ICU 3.6 */
USCRIPT_EASTERN_SYRIAC = 97, /* Syrn */
/** @stable ICU 3.6 */
USCRIPT_TENGWAR = 98, /* Teng */
/** @stable ICU 3.6 */
USCRIPT_VAI = 99, /* Vaii */
/** @stable ICU 3.6 */
USCRIPT_VISIBLE_SPEECH = 100,/* Visp */
/** @stable ICU 3.6 */
USCRIPT_CUNEIFORM = 101,/* Xsux */
/** @stable ICU 3.6 */
USCRIPT_UNWRITTEN_LANGUAGES = 102,/* Zxxx */
/** @stable ICU 3.6 */
USCRIPT_UNKNOWN = 103,/* Zzzz */ /* Unknown="Code for uncoded script", for unassigned code points */
/** @stable ICU 3.8 */
USCRIPT_CARIAN = 104,/* Cari */
/** @stable ICU 3.8 */
USCRIPT_JAPANESE = 105,/* Jpan */
/** @stable ICU 3.8 */
USCRIPT_LANNA = 106,/* Lana */
/** @stable ICU 3.8 */
USCRIPT_LYCIAN = 107,/* Lyci */
/** @stable ICU 3.8 */
USCRIPT_LYDIAN = 108,/* Lydi */
/** @stable ICU 3.8 */
USCRIPT_OL_CHIKI = 109,/* Olck */
/** @stable ICU 3.8 */
USCRIPT_REJANG = 110,/* Rjng */
/** @stable ICU 3.8 */
USCRIPT_SAURASHTRA = 111,/* Saur */
/** Sutton SignWriting @stable ICU 3.8 */
USCRIPT_SIGN_WRITING = 112,/* Sgnw */
/** @stable ICU 3.8 */
USCRIPT_SUNDANESE = 113,/* Sund */
/** @stable ICU 3.8 */
USCRIPT_MOON = 114,/* Moon */
/** @stable ICU 3.8 */
USCRIPT_MEITEI_MAYEK = 115,/* Mtei */
/** @stable ICU 4.0 */
USCRIPT_IMPERIAL_ARAMAIC = 116,/* Armi */
/** @stable ICU 4.0 */
USCRIPT_AVESTAN = 117,/* Avst */
/** @stable ICU 4.0 */
USCRIPT_CHAKMA = 118,/* Cakm */
/** @stable ICU 4.0 */
USCRIPT_KOREAN = 119,/* Kore */
/** @stable ICU 4.0 */
USCRIPT_KAITHI = 120,/* Kthi */
/** @stable ICU 4.0 */
USCRIPT_MANICHAEAN = 121,/* Mani */
/** @stable ICU 4.0 */
USCRIPT_INSCRIPTIONAL_PAHLAVI = 122,/* Phli */
/** @stable ICU 4.0 */
USCRIPT_PSALTER_PAHLAVI = 123,/* Phlp */
/** @stable ICU 4.0 */
USCRIPT_BOOK_PAHLAVI = 124,/* Phlv */
/** @stable ICU 4.0 */
USCRIPT_INSCRIPTIONAL_PARTHIAN = 125,/* Prti */
/** @stable ICU 4.0 */
USCRIPT_SAMARITAN = 126,/* Samr */
/** @stable ICU 4.0 */
USCRIPT_TAI_VIET = 127,/* Tavt */
/** @stable ICU 4.0 */
USCRIPT_MATHEMATICAL_NOTATION = 128,/* Zmth */
/** @stable ICU 4.0 */
USCRIPT_SYMBOLS = 129,/* Zsym */
/** @stable ICU 4.4 */
USCRIPT_BAMUM = 130,/* Bamu */
/** @stable ICU 4.4 */
USCRIPT_LISU = 131,/* Lisu */
/** @stable ICU 4.4 */
USCRIPT_NAKHI_GEBA = 132,/* Nkgb */
/** @stable ICU 4.4 */
USCRIPT_OLD_SOUTH_ARABIAN = 133,/* Sarb */
/** @stable ICU 4.6 */
USCRIPT_BASSA_VAH = 134,/* Bass */
/** @stable ICU 54 */
USCRIPT_DUPLOYAN = 135,/* Dupl */
#ifndef U_HIDE_DEPRECATED_API
/** @deprecated ICU 54 Typo, use USCRIPT_DUPLOYAN */
USCRIPT_DUPLOYAN_SHORTAND = USCRIPT_DUPLOYAN,
#endif /* U_HIDE_DEPRECATED_API */
/** @stable ICU 4.6 */
USCRIPT_ELBASAN = 136,/* Elba */
/** @stable ICU 4.6 */
USCRIPT_GRANTHA = 137,/* Gran */
/** @stable ICU 4.6 */
USCRIPT_KPELLE = 138,/* Kpel */
/** @stable ICU 4.6 */
USCRIPT_LOMA = 139,/* Loma */
/** Mende Kikakui @stable ICU 4.6 */
USCRIPT_MENDE = 140,/* Mend */
/** @stable ICU 4.6 */
USCRIPT_MEROITIC_CURSIVE = 141,/* Merc */
/** @stable ICU 4.6 */
USCRIPT_OLD_NORTH_ARABIAN = 142,/* Narb */
/** @stable ICU 4.6 */
USCRIPT_NABATAEAN = 143,/* Nbat */
/** @stable ICU 4.6 */
USCRIPT_PALMYRENE = 144,/* Palm */
/** @stable ICU 54 */
USCRIPT_KHUDAWADI = 145,/* Sind */
/** @stable ICU 4.6 */
USCRIPT_SINDHI = USCRIPT_KHUDAWADI,
/** @stable ICU 4.6 */
USCRIPT_WARANG_CITI = 146,/* Wara */
/** @stable ICU 4.8 */
USCRIPT_AFAKA = 147,/* Afak */
/** @stable ICU 4.8 */
USCRIPT_JURCHEN = 148,/* Jurc */
/** @stable ICU 4.8 */
USCRIPT_MRO = 149,/* Mroo */
/** @stable ICU 4.8 */
USCRIPT_NUSHU = 150,/* Nshu */
/** @stable ICU 4.8 */
USCRIPT_SHARADA = 151,/* Shrd */
/** @stable ICU 4.8 */
USCRIPT_SORA_SOMPENG = 152,/* Sora */
/** @stable ICU 4.8 */
USCRIPT_TAKRI = 153,/* Takr */
/** @stable ICU 4.8 */
USCRIPT_TANGUT = 154,/* Tang */
/** @stable ICU 4.8 */
USCRIPT_WOLEAI = 155,/* Wole */
/** @stable ICU 49 */
USCRIPT_ANATOLIAN_HIEROGLYPHS = 156,/* Hluw */
/** @stable ICU 49 */
USCRIPT_KHOJKI = 157,/* Khoj */
/** @stable ICU 49 */
USCRIPT_TIRHUTA = 158,/* Tirh */
/** @stable ICU 52 */
USCRIPT_CAUCASIAN_ALBANIAN = 159,/* Aghb */
/** @stable ICU 52 */
USCRIPT_MAHAJANI = 160,/* Mahj */
/** @stable ICU 54 */
USCRIPT_AHOM = 161,/* Ahom */
/** @stable ICU 54 */
USCRIPT_HATRAN = 162,/* Hatr */
/** @stable ICU 54 */
USCRIPT_MODI = 163,/* Modi */
/** @stable ICU 54 */
USCRIPT_MULTANI = 164,/* Mult */
/** @stable ICU 54 */
USCRIPT_PAU_CIN_HAU = 165,/* Pauc */
/** @stable ICU 54 */
USCRIPT_SIDDHAM = 166,/* Sidd */
/**
* One higher than the last script code constant.
* This value increases as constants for script codes are added.
*
* There are constants for Unicode 7 script property values.
* There are constants for ISO 15924 script codes assigned on or before 2013-10-12.
* There are no constants for private use codes from Qaaa - Qabx
* except as used in the UCD.
*
* @stable ICU 2.2
*/
USCRIPT_CODE_LIMIT = 167
} UScriptCode;
/**
* Gets the script codes associated with the given locale or ISO 15924 abbreviation or name.
* Fills in USCRIPT_MALAYALAM given "Malayam" OR "Mlym".
* Fills in USCRIPT_LATIN given "en" OR "en_US"
* If the required capacity is greater than the capacity of the destination buffer,
* then the error code is set to U_BUFFER_OVERFLOW_ERROR and the required capacity is returned.
*
* <p>Note: To search by short or long script alias only, use
* u_getPropertyValueEnum(UCHAR_SCRIPT, alias) instead. That does
* a fast lookup with no access of the locale data.
*
* @param nameOrAbbrOrLocale name of the script, as given in
* PropertyValueAliases.txt, or ISO 15924 code or locale
* @param fillIn the UScriptCode buffer to fill in the script code
* @param capacity the capacity (size) fo UScriptCode buffer passed in.
* @param err the error status code.
* @return The number of script codes filled in the buffer passed in
* @stable ICU 2.4
*/
U_STABLE int32_t U_EXPORT2
uscript_getCode(const char* nameOrAbbrOrLocale,UScriptCode* fillIn,int32_t capacity,UErrorCode *err);
/**
* Returns the long Unicode script name, if there is one.
* Otherwise returns the 4-letter ISO 15924 script code.
* Returns "Malayam" given USCRIPT_MALAYALAM.
*
* @param scriptCode UScriptCode enum
* @return long script name as given in PropertyValueAliases.txt, or the 4-letter code,
* or NULL if scriptCode is invalid
* @stable ICU 2.4
*/
U_STABLE const char* U_EXPORT2
uscript_getName(UScriptCode scriptCode);
/**
* Returns the 4-letter ISO 15924 script code,
* which is the same as the short Unicode script name if Unicode has names for the script.
* Returns "Mlym" given USCRIPT_MALAYALAM.
*
* @param scriptCode UScriptCode enum
* @return short script name (4-letter code), or NULL if scriptCode is invalid
* @stable ICU 2.4
*/
U_STABLE const char* U_EXPORT2
uscript_getShortName(UScriptCode scriptCode);
/**
* Gets the script code associated with the given codepoint.
* Returns USCRIPT_MALAYALAM given 0x0D02
* @param codepoint UChar32 codepoint
* @param err the error status code.
* @return The UScriptCode, or 0 if codepoint is invalid
* @stable ICU 2.4
*/
U_STABLE UScriptCode U_EXPORT2
uscript_getScript(UChar32 codepoint, UErrorCode *err);
/**
* Do the Script_Extensions of code point c contain script sc?
* If c does not have explicit Script_Extensions, then this tests whether
* c has the Script property value sc.
*
* Some characters are commonly used in multiple scripts.
* For more information, see UAX #24: http://www.unicode.org/reports/tr24/.
*
* The Script_Extensions property is provisional. It may be modified or removed
* in future versions of the Unicode Standard, and thus in ICU.
* @param c code point
* @param sc script code
* @return TRUE if sc is in Script_Extensions(c)
* @stable ICU 49
*/
U_STABLE UBool U_EXPORT2
uscript_hasScript(UChar32 c, UScriptCode sc);
/**
* Writes code point c's Script_Extensions as a list of UScriptCode values
* to the output scripts array and returns the number of script codes.
* - If c does have Script_Extensions, then the Script property value
* (normally Common or Inherited) is not included.
* - If c does not have Script_Extensions, then the one Script code is written to the output array.
* - If c is not a valid code point, then the one USCRIPT_UNKNOWN code is written.
* In other words, if the return value is 1,
* then the output array contains exactly c's single Script code.
* If the return value is n>=2, then the output array contains c's n Script_Extensions script codes.
*
* Some characters are commonly used in multiple scripts.
* For more information, see UAX #24: http://www.unicode.org/reports/tr24/.
*
* If there are more than capacity script codes to be written, then
* U_BUFFER_OVERFLOW_ERROR is set and the number of Script_Extensions is returned.
* (Usual ICU buffer handling behavior.)
*
* The Script_Extensions property is provisional. It may be modified or removed
* in future versions of the Unicode Standard, and thus in ICU.
* @param c code point
* @param scripts output script code array
* @param capacity capacity of the scripts array
* @param errorCode Standard ICU error code. Its input value must
* pass the U_SUCCESS() test, or else the function returns
* immediately. Check for U_FAILURE() on output or use with
* function chaining. (See User Guide for details.)
* @return number of script codes in c's Script_Extensions, or 1 for the single Script value,
* written to scripts unless U_BUFFER_OVERFLOW_ERROR indicates insufficient capacity
* @stable ICU 49
*/
U_STABLE int32_t U_EXPORT2
uscript_getScriptExtensions(UChar32 c,
UScriptCode *scripts, int32_t capacity,
UErrorCode *errorCode);
/**
* Script usage constants.
* See UAX #31 Unicode Identifier and Pattern Syntax.
* http://www.unicode.org/reports/tr31/#Table_Candidate_Characters_for_Exclusion_from_Identifiers
*
* @stable ICU 51
*/
typedef enum UScriptUsage {
/** Not encoded in Unicode. @stable ICU 51 */
USCRIPT_USAGE_NOT_ENCODED,
/** Unknown script usage. @stable ICU 51 */
USCRIPT_USAGE_UNKNOWN,
/** Candidate for Exclusion from Identifiers. @stable ICU 51 */
USCRIPT_USAGE_EXCLUDED,
/** Limited Use script. @stable ICU 51 */
USCRIPT_USAGE_LIMITED_USE,
/** Aspirational Use script. @stable ICU 51 */
USCRIPT_USAGE_ASPIRATIONAL,
/** Recommended script. @stable ICU 51 */
USCRIPT_USAGE_RECOMMENDED
} UScriptUsage;
/**
* Writes the script sample character string.
* This string normally consists of one code point but might be longer.
* The string is empty if the script is not encoded.
*
* @param script script code
* @param dest output string array
* @param capacity number of UChars in the dest array
* @param pErrorCode standard ICU in/out error code, must pass U_SUCCESS() on input
* @return the string length, even if U_BUFFER_OVERFLOW_ERROR
* @stable ICU 51
*/
U_STABLE int32_t U_EXPORT2
uscript_getSampleString(UScriptCode script, UChar *dest, int32_t capacity, UErrorCode *pErrorCode);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
class UnicodeString;
U_NAMESPACE_END
/**
* Returns the script sample character string.
* This string normally consists of one code point but might be longer.
* The string is empty if the script is not encoded.
*
* @param script script code
* @return the sample character string
* @stable ICU 51
*/
U_COMMON_API icu::UnicodeString U_EXPORT2
uscript_getSampleUnicodeString(UScriptCode script);
#endif
/**
* Returns the script usage according to UAX #31 Unicode Identifier and Pattern Syntax.
* Returns USCRIPT_USAGE_NOT_ENCODED if the script is not encoded in Unicode.
*
* @param script script code
* @return script usage
* @see UScriptUsage
* @stable ICU 51
*/
U_STABLE UScriptUsage U_EXPORT2
uscript_getUsage(UScriptCode script);
/**
* Returns TRUE if the script is written right-to-left.
* For example, Arab and Hebr.
*
* @param script script code
* @return TRUE if the script is right-to-left
* @stable ICU 51
*/
U_STABLE UBool U_EXPORT2
uscript_isRightToLeft(UScriptCode script);
/**
* Returns TRUE if the script allows line breaks between letters (excluding hyphenation).
* Such a script typically requires dictionary-based line breaking.
* For example, Hani and Thai.
*
* @param script script code
* @return TRUE if the script allows line breaks between letters
* @stable ICU 51
*/
U_STABLE UBool U_EXPORT2
uscript_breaksBetweenLetters(UScriptCode script);
/**
* Returns TRUE if in modern (or most recent) usage of the script case distinctions are customary.
* For example, Latn and Cyrl.
*
* @param script script code
* @return TRUE if the script is cased
* @stable ICU 51
*/
U_STABLE UBool U_EXPORT2
uscript_isCased(UScriptCode script);
#endif
| ONLYOFFICE/core | UnicodeConverter/icubuilds-mac/icu/unicode/uscript.h | C | agpl-3.0 | 25,849 |
/**
* Created with IntelliJ IDEA.
* User: issa
* Date: 3/16/14
* Time: 9:08 PM
* To change this template use File | Settings | File Templates.
*/
function DistrictStockedOutController($scope,$location,$routeParams,dashboardMenuService,messageService,StockedOutFacilitiesByDistrict) {
$scope.filterObject = {};
$scope.formFilter = {};
$scope.formPanel = {openPanel:true};
$scope.startYears = [];
$scope.showProductsFilter = true;
$scope.$parent.currentTab = 'DISTRICT-STOCK-OUT';
$scope.productSelectOption = {maximumSelectionSize : 1};
$scope.stockedOutPieChartOption = {
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 2 / 3,
formatter: function (label, series) {
return '<div style="font-size:8pt;text-align:center;padding:2px;color:black;">' + Math.round(series.percent) + '%</div>';
},
threshold: 0.1
}
}
},
legend: {
container:$("#stockedOutReportLegend"),
noColumns: 0,
labelBoxBorderColor: "none"
},
grid:{
hoverable: true,
clickable: true,
borderWidth: 1,
borderColor: "#d6d6d6",
backgroundColor: {
colors: ["#FFF", "#CCC"]
}
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s",
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$scope.$on('$viewContentLoaded', function () {
$scope.filterObject = $routeParams;
if(!isUndefined($routeParams.programId) &&
!isUndefined($routeParams.periodId) &&
!isUndefined($routeParams.productId) &&
!isUndefined($routeParams.zoneId)){
StockedOutFacilitiesByDistrict.get({
periodId: $routeParams.periodId,
programId: $routeParams.programId,
productId: $routeParams.productId,
zoneId: $routeParams.zoneId
},function(stockData){
$scope.totalStockOuts = 0;
if(!isUndefined(stockData.stockOut)){
$scope.totalStockOuts = stockData.stockOut.length;
var suppliedInPast = _.filter(stockData.stockOut, function(stock){ if(stock.suppliedInPast === true){return stock;}});
$scope.product = _.pluck(stockData.stockOut,'product')[0];
$scope.location = _.pluck(stockData.stockOut,'location')[0];
$scope.datarows = [{label:messageService.get('label.facility.supplied.in.past'),
total: suppliedInPast.length,
color: "#F47900"
},
{label:messageService.get('label.facility.not.supplied.in.past'),
total: $scope.totalStockOuts - suppliedInPast.length,
color:"#CC0505"
}];
$scope.stockedOutPieChartData = [];
for (var i = 0; i < $scope.datarows.length; i++) {
$scope.stockedOutPieChartData[i] = {
label: $scope.datarows[i].label,
data: $scope.datarows[i].total,
color: $scope.datarows[i].color
};
}
bindChartEvent("#stocked-out-reporting","plotclick",$scope.stockedOutChartClickHandler);
bindChartEvent("#stocked-out-reporting","plothover",flotChartHoverCursorHandler);
}else{
$scope.resetStockedOutData();
}
});
} else{
$scope.resetStockedOutData();
}
// };
});
$scope.stockedOutChartClickHandler = function (event, pos, item){
if(item){
var districtStockOutPath = '/stock-out-detail/'+$scope.filterObject.programId+'/'+$scope.filterObject.periodId+'/'+$scope.filterObject.zoneId+'/'+$scope.filterObject.productId;
dashboardMenuService.addTab('menu.header.dashboard.stocked.out.district.detail','/public/pages/dashboard/index.html#'+districtStockOutPath,'DISTRICT-STOCK-OUT-DETAIL',true, 5);
$location.path(districtStockOutPath);
$scope.$apply();
}
};
$scope.resetStockedOutData = function(){
$scope.stockedOutPieChartData = null;
$scope.datarows = null;
$scope.stockedOutDetails = null;
};
function flotChartHoverCursorHandler(event,pos,item){
if (item && !isUndefined(item.dataIndex)) {
$(event.target).css('cursor','pointer');
} else {
$(event.target).css('cursor','auto');
}
}
function bindChartEvent(elementSelector, eventType, callback){
$(elementSelector).bind(eventType, callback);
}
$scope.getFacilityStockOutPercent = function(value){
return Math.round((value/$scope.totalStockOuts)*100) +'%';
};
} | vimsvarcode/elmis | modules/openlmis-web/src/main/webapp/public/js/dashboard/controller/district-stocked-out-controller.js | JavaScript | agpl-3.0 | 5,612 |
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#ifndef ABSTRACTNODEINSTANCEVIEW_H
#define ABSTRACTNODEINSTANCEVIEW_H
#include "corelib_global.h"
#include "abstractview.h"
#include <QtGui/QWidget>
#include <QtCore/QHash>
#include <QtScript/QScriptEngine>
#include <QWeakPointer>
#include <QtCore/QHash>
#include <modelnode.h>
#include <nodeinstance.h>
QT_BEGIN_NAMESPACE
class QDeclarativeEngine;
class QGraphicsScene;
class QGraphicsView;
QT_END_NAMESPACE
namespace QmlDesigner {
namespace Internal {
class ChildrenChangeEventFilter;
}
class CORESHARED_EXPORT NodeInstanceView : public AbstractView
{
Q_OBJECT
friend class NodeInstance;
friend class Internal::ObjectNodeInstance;
public:
typedef QWeakPointer<NodeInstanceView> Pointer;
NodeInstanceView(QObject *parent = 0);
~NodeInstanceView();
void modelAttached(Model *model);
void modelAboutToBeDetached(Model *model);
void nodeCreated(const ModelNode &createdNode);
void nodeAboutToBeRemoved(const ModelNode &removedNode);
void nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange);
void propertiesAdded(const ModelNode &node, const QList<AbstractProperty>& propertyList);
void propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList);
void propertiesRemoved(const QList<AbstractProperty>& propertyList);
void variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange);
void bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags propertyChange);
void nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange);
void rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion);
void fileUrlChanged(const QUrl &oldUrl, const QUrl &newUrl);
void nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId);
void modelStateAboutToBeRemoved(const ModelState &modelState);
void modelStateAdded(const ModelState &modelState);
void nodeStatesAboutToBeRemoved(const QList<ModelNode> &nodeStateList);
void nodeStatesAdded(const QList<ModelNode> &nodeStateList);
void nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int oldIndex);
NodeInstance rootNodeInstance() const;
NodeInstance viewNodeInstance() const;
void selectedNodesChanged(const QList<ModelNode> &selectedNodeList, const QList<ModelNode> &lastSelectedNodeList);
QList<NodeInstance> instances() const;
NodeInstance instanceForNode(const ModelNode &node);
bool hasInstanceForNode(const ModelNode &node);
NodeInstance instanceForObject(QObject *object);
bool hasInstanceForObject(QObject *object);
void anchorsChanged(const ModelNode &nodeState);
void render(QPainter *painter, const QRectF &target=QRectF(), const QRectF &source=QRect(), Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio);
QRectF boundingRect() const;
QRectF sceneRect() const;
void setBlockChangeSignal(bool block);
void notifyPropertyChange(const ModelNode &modelNode, const QString &propertyName);
void setQmlModelView(QmlModelView *qmlModelView);
QmlModelView *qmlModelView() const ;
void setBlockStatePropertyChanges(bool block);
signals:
void instanceRemoved(const NodeInstance &nodeInstance);
private slots:
void emitParentChanged(QObject *child);
private: // functions
NodeInstance loadNode(const ModelNode &rootNode, QObject *objectToBeWrapped = 0);
void loadModel(Model *model);
void loadNodes(const QList<ModelNode> &nodeList);
void removeAllInstanceNodeRelationships();
void removeRecursiveChildRelationship(const ModelNode &removedNode);
void insertInstanceNodeRelationship(const ModelNode &node, const NodeInstance &instance);
void removeInstanceNodeRelationship(const ModelNode &node);
QDeclarativeEngine *engine() const;
Internal::ChildrenChangeEventFilter *childrenChangeEventFilter();
void removeInstanceAndSubInstances(const ModelNode &node);
private: //variables
NodeInstance m_rootNodeInstance;
QScopedPointer<QGraphicsView> m_graphicsView;
QHash<ModelNode, NodeInstance> m_nodeInstanceHash;
QHash<QObject*, NodeInstance> m_objectInstanceHash; // This is purely internal. Might contain dangling pointers!
QWeakPointer<QDeclarativeEngine> m_engine;
QWeakPointer<Internal::ChildrenChangeEventFilter> m_childrenChangeEventFilter;
QWeakPointer<QmlModelView> m_qmlModelView;
bool m_blockChangeSignal;
bool m_blockStatePropertyChanges;
};
}
#endif // ABSTRACTNODEINSTANCEVIEW_H
| enricoros/k-qt-creator-inspector | src/plugins/qmldesigner/core/include/nodeinstanceview.h | C | lgpl-2.1 | 6,001 |
/*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2010-2016 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary 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.
*
* Zongsoft.CoreLibrary 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.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
namespace Zongsoft.Services
{
/// <summary>
/// 提供实现<see cref="ICommand"/>接口功能的基类,建议需要完成<see cref="ICommand"/>接口功能的实现者从此类继承。
/// </summary>
/// <typeparam name="TContext">指定命令的执行上下文类型。</typeparam>
public abstract class CommandBase<TContext> : CommandBase, ICommand<TContext>, IPredication<TContext> where TContext : CommandContext
{
#region 构造函数
protected CommandBase() : base(null, true)
{
}
protected CommandBase(string name) : base(name, true)
{
}
protected CommandBase(string name, bool enabled) : base(name, enabled)
{
}
#endregion
#region 公共方法
/// <summary>
/// 判断命令是否可被执行。
/// </summary>
/// <param name="context">判断命令是否可被执行的上下文对象。</param>
/// <returns>如果返回真(true)则表示命令可被执行,否则表示不可执行。</returns>
/// <remarks>
/// <para>本方法为虚拟方法,可由子类更改基类的默认实现方式。</para>
/// <para>如果<seealso cref="CommandBase.Predication"/>属性为空(null),则返回<seealso cref="CommandBase.Enabled"/>属性值;否则返回由<seealso cref="CommandBase.Predication"/>属性指定的断言对象的断言方法的值。</para>
/// </remarks>
public virtual bool CanExecute(TContext context)
{
return base.CanExecute(context);
}
/// <summary>
/// 执行命令。
/// </summary>
/// <param name="context">执行命令的上下文对象。</param>
/// <returns>返回执行的返回结果。</returns>
/// <remarks>
/// <para>本方法的实现中首先调用<seealso cref="CommandBase.CanExecute"/>方法,以确保阻止非法的调用。</para>
/// </remarks>
public object Execute(TContext context)
{
return base.Execute(context);
}
#endregion
#region 抽象方法
protected virtual TContext CreateContext(object parameter)
{
return parameter as TContext;
}
protected abstract object OnExecute(TContext context);
#endregion
#region 重写方法
protected override bool CanExecute(object parameter)
{
var context = parameter as TContext;
if(context == null)
context = this.CreateContext(parameter);
return this.CanExecute(context);
}
protected override object OnExecute(object parameter)
{
var context = parameter as TContext;
if(context == null)
context = this.CreateContext(parameter);
//执行具体的命令操作
return this.OnExecute(context);
}
#endregion
#region 显式实现
bool IPredication<TContext>.Predicate(TContext context)
{
return this.CanExecute(context);
}
#endregion
}
}
| Zongsoft/Zongsoft.CoreLibrary | src/Services/CommandBase`1.cs | C# | lgpl-2.1 | 3,855 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- qitemselectionmodel.cpp -->
<title>Qt 4.8: List of All Members for QItemSelectionRange</title>
<link rel="stylesheet" type="text/css" href="style/offline.css" />
</head>
<body>
<div class="header" id="qtdocheader">
<div class="content">
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
</div>
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
<li><a href="modules.html">Modules</a></li>
<li><a href="qtgui.html">QtGui</a></li>
<li>QItemSelectionRange</li>
</ul>
</div>
</div>
<div class="content mainContent">
<h1 class="title">List of All Members for QItemSelectionRange</h1>
<p>This is the complete list of members for <a href="qitemselectionrange.html">QItemSelectionRange</a>, including inherited members.</p>
<table class="propsummary">
<tr><td class="topAlign"><ul>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#QItemSelectionRange">QItemSelectionRange</a></b></span> ()</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#QItemSelectionRange-2">QItemSelectionRange</a></b></span> ( const QItemSelectionRange & )</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#QItemSelectionRange-3">QItemSelectionRange</a></b></span> ( const QModelIndex &, const QModelIndex & )</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#QItemSelectionRange-4">QItemSelectionRange</a></b></span> ( const QModelIndex & )</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#bottom">bottom</a></b></span> () const : int</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#bottomRight">bottomRight</a></b></span> () const : QModelIndex</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#contains">contains</a></b></span> ( const QModelIndex & ) const : bool</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#contains-2">contains</a></b></span> ( int, int, const QModelIndex & ) const : bool</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#height">height</a></b></span> () const : int</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#indexes">indexes</a></b></span> () const : QModelIndexList</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#intersected">intersected</a></b></span> ( const QItemSelectionRange & ) const : QItemSelectionRange</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#intersects">intersects</a></b></span> ( const QItemSelectionRange & ) const : bool</li>
</ul></td><td class="topAlign"><ul>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#isEmpty">isEmpty</a></b></span> () const : bool</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#isValid">isValid</a></b></span> () const : bool</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#left">left</a></b></span> () const : int</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#model">model</a></b></span> () const : const QAbstractItemModel *</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#parent">parent</a></b></span> () const : QModelIndex</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#right">right</a></b></span> () const : int</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#top">top</a></b></span> () const : int</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#topLeft">topLeft</a></b></span> () const : QModelIndex</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#width">width</a></b></span> () const : int</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#operator-not-eq">operator!=</a></b></span> ( const QItemSelectionRange & ) const : bool</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#operator-lt">operator<</a></b></span> ( const QItemSelectionRange & ) const : bool</li>
<li class="fn"><span class="name"><b><a href="qitemselectionrange.html#operator-eq-eq">operator==</a></b></span> ( const QItemSelectionRange & ) const : bool</li>
</ul>
</td></tr>
</table>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2008-2011 Nokia Corporation and/or its
subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation
in Finland and/or other countries worldwide.</p>
<p>
All other trademarks are property of their respective owners. <a title="Privacy Policy"
href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p>
<br />
<p>
Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p>
<p>
Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU
Free Documentation License version 1.3</a>
as published by the Free Software Foundation.</p>
</div>
</body>
</html>
| kobolabs/qt-everywhere-4.8.0 | doc/html/qitemselectionrange-members.html | HTML | lgpl-2.1 | 5,753 |
/*
* 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 bean;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* @author Matthew
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
| adrienelium/Projet-DAD-Exia | J2EE/JSFWithEntityClass/src/java/bean/AbstractFacade.java | Java | lgpl-2.1 | 1,964 |
/*
This file is part of libmicrohttpd
Copyright (C) 2006-2017 Christian Grothoff (and other contributing authors)
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
*/
/**
* @file microhttpd.h
* @brief public interface to libmicrohttpd
* @author Christian Grothoff
* @author Karlson2k (Evgeny Grin)
* @author Chris GauthierDickey
*
* All symbols defined in this header start with MHD. MHD is a small
* HTTP daemon library. As such, it does not have any API for logging
* errors (you can only enable or disable logging to stderr). Also,
* it may not support all of the HTTP features directly, where
* applicable, portions of HTTP may have to be handled by clients of
* the library.
*
* The library is supposed to handle everything that it must handle
* (because the API would not allow clients to do this), such as basic
* connection management; however, detailed interpretations of headers
* -- such as range requests -- and HTTP methods are left to clients.
* The library does understand HEAD and will only send the headers of
* the response and not the body, even if the client supplied a body.
* The library also understands headers that control connection
* management (specifically, "Connection: close" and "Expect: 100
* continue" are understood and handled automatically).
*
* MHD understands POST data and is able to decode certain formats
* (at the moment only "application/x-www-form-urlencoded" and
* "mulitpart/formdata"). Unsupported encodings and large POST
* submissions may require the application to manually process
* the stream, which is provided to the main application (and thus can be
* processed, just not conveniently by MHD).
*
* The header file defines various constants used by the HTTP protocol.
* This does not mean that MHD actually interprets all of these
* values. The provided constants are exported as a convenience
* for users of the library. MHD does not verify that transmitted
* HTTP headers are part of the standard specification; users of the
* library are free to define their own extensions of the HTTP
* standard and use those with MHD.
*
* All functions are guaranteed to be completely reentrant and
* thread-safe (with the exception of #MHD_set_connection_value,
* which must only be used in a particular context).
*
*
* @defgroup event event-loop control
* MHD API to start and stop the HTTP server and manage the event loop.
* @defgroup response generation of responses
* MHD API used to generate responses.
* @defgroup request handling of requests
* MHD API used to access information about requests.
* @defgroup authentication HTTP authentication
* MHD API related to basic and digest HTTP authentication.
* @defgroup logging logging
* MHD API to mange logging and error handling
* @defgroup specialized misc. specialized functions
* This group includes functions that do not fit into any particular
* category and that are rarely used.
*/
#ifndef MHD_MICROHTTPD_H
#define MHD_MICROHTTPD_H
#ifdef __cplusplus
extern "C"
{
#if 0 /* keep Emacsens' auto-indent happy */
}
#endif
#endif
/* While we generally would like users to use a configure-driven
build process which detects which headers are present and
hence works on any platform, we use "standard" includes here
to build out-of-the-box for beginning users on common systems.
If generic headers don't work on your platform, include headers
which define 'va_list', 'size_t', 'ssize_t', 'intptr_t',
'uint16_t', 'uint32_t', 'uint64_t', 'off_t', 'struct sockaddr',
'socklen_t', 'fd_set' and "#define MHD_PLATFORM_H" before
including "microhttpd.h". Then the following "standard"
includes won't be used (which might be a good idea, especially
on platforms where they do not exist).
*/
#ifndef MHD_PLATFORM_H
#include <stdarg.h>
#include <stdint.h>
#include <sys/types.h>
#if defined(_WIN32) && !defined(__CYGWIN__)
#include <ws2tcpip.h>
#if defined(_MSC_FULL_VER) && !defined (_SSIZE_T_DEFINED)
#define _SSIZE_T_DEFINED
typedef intptr_t ssize_t;
#endif /* !_SSIZE_T_DEFINED */
#else
#include <unistd.h>
#include <sys/time.h>
#include <sys/socket.h>
#endif
#endif
#if defined(__CYGWIN__) && !defined(_SYS_TYPES_FD_SET)
/* Do not define __USE_W32_SOCKETS under Cygwin! */
#error Cygwin with winsock fd_set is not supported
#endif
/**
* Current version of the library.
* 0x01093001 = 1.9.30-1.
*/
#define MHD_VERSION 0x00095502
/**
* MHD-internal return code for "YES".
*/
#define MHD_YES 1
/**
* MHD-internal return code for "NO".
*/
#define MHD_NO 0
/**
* MHD digest auth internal code for an invalid nonce.
*/
#define MHD_INVALID_NONCE -1
/**
* Constant used to indicate unknown size (use when
* creating a response).
*/
#ifdef UINT64_MAX
#define MHD_SIZE_UNKNOWN UINT64_MAX
#else
#define MHD_SIZE_UNKNOWN ((uint64_t) -1LL)
#endif
#ifdef SIZE_MAX
#define MHD_CONTENT_READER_END_OF_STREAM SIZE_MAX
#define MHD_CONTENT_READER_END_WITH_ERROR (SIZE_MAX - 1)
#else
#define MHD_CONTENT_READER_END_OF_STREAM ((size_t) -1LL)
#define MHD_CONTENT_READER_END_WITH_ERROR (((size_t) -1LL) - 1)
#endif
#ifndef _MHD_EXTERN
#if defined(_WIN32) && defined(MHD_W32LIB)
#define _MHD_EXTERN extern
#elif defined (_WIN32) && defined(MHD_W32DLL)
/* Define MHD_W32DLL when using MHD as W32 .DLL to speed up linker a little */
#define _MHD_EXTERN __declspec(dllimport)
#else
#define _MHD_EXTERN extern
#endif
#endif
#ifndef MHD_SOCKET_DEFINED
/**
* MHD_socket is type for socket FDs
*/
#if !defined(_WIN32) || defined(_SYS_TYPES_FD_SET)
#define MHD_POSIX_SOCKETS 1
typedef int MHD_socket;
#define MHD_INVALID_SOCKET (-1)
#else /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */
#define MHD_WINSOCK_SOCKETS 1
#include <winsock2.h>
typedef SOCKET MHD_socket;
#define MHD_INVALID_SOCKET (INVALID_SOCKET)
#endif /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */
#define MHD_SOCKET_DEFINED 1
#endif /* MHD_SOCKET_DEFINED */
/**
* Define MHD_NO_DEPRECATION before including "microhttpd.h" to disable deprecation messages
*/
#ifdef MHD_NO_DEPRECATION
#define _MHD_DEPR_MACRO(msg)
#define _MHD_NO_DEPR_IN_MACRO 1
#define _MHD_DEPR_IN_MACRO(msg)
#define _MHD_NO_DEPR_FUNC 1
#define _MHD_DEPR_FUNC(msg)
#endif /* MHD_NO_DEPRECATION */
#ifndef _MHD_DEPR_MACRO
#if defined(_MSC_FULL_VER) && _MSC_VER+0 >= 1500
/* VS 2008 or later */
/* Stringify macros */
#define _MHD_INSTRMACRO(a) #a
#define _MHD_STRMACRO(a) _MHD_INSTRMACRO(a)
/* deprecation message */
#define _MHD_DEPR_MACRO(msg) __pragma(message(__FILE__ "(" _MHD_STRMACRO(__LINE__)"): warning: " msg))
#define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO(msg)
#elif defined(__clang__) || defined (__GNUC_PATCHLEVEL__)
/* clang or GCC since 3.0 */
#define _MHD_GCC_PRAG(x) _Pragma (#x)
#if __clang_major__+0 >= 5 || \
(!defined(__apple_build_version__) && (__clang_major__+0 > 3 || (__clang_major__+0 == 3 && __clang_minor__ >= 3))) || \
__GNUC__+0 > 4 || (__GNUC__+0 == 4 && __GNUC_MINOR__+0 >= 8)
/* clang >= 3.3 (or XCode's clang >= 5.0) or
GCC >= 4.8 */
#define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG(GCC warning msg)
#define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO(msg)
#else /* older clang or GCC */
/* clang < 3.3, XCode's clang < 5.0, 3.0 <= GCC < 4.8 */
#define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG(message msg)
#if (__clang_major__+0 > 2 || (__clang_major__+0 == 2 && __clang_minor__ >= 9)) /* FIXME: clang >= 2.9, earlier versions not tested */
/* clang handles inline pragmas better than GCC */
#define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO(msg)
#endif /* clang >= 2.9 */
#endif /* older clang or GCC */
/* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */
#endif /* clang || GCC >= 3.0 */
#endif /* !_MHD_DEPR_MACRO */
#ifndef _MHD_DEPR_MACRO
#define _MHD_DEPR_MACRO(msg)
#endif /* !_MHD_DEPR_MACRO */
#ifndef _MHD_DEPR_IN_MACRO
#define _MHD_NO_DEPR_IN_MACRO 1
#define _MHD_DEPR_IN_MACRO(msg)
#endif /* !_MHD_DEPR_IN_MACRO */
#ifndef _MHD_DEPR_FUNC
#if defined(_MSC_FULL_VER) && _MSC_VER+0 >= 1400
/* VS 2005 or later */
#define _MHD_DEPR_FUNC(msg) __declspec(deprecated(msg))
#elif defined(_MSC_FULL_VER) && _MSC_VER+0 >= 1310
/* VS .NET 2003 deprecation do not support custom messages */
#define _MHD_DEPR_FUNC(msg) __declspec(deprecated)
#elif (__GNUC__+0 >= 5) || (defined (__clang__) && \
(__clang_major__+0 > 2 || (__clang_major__+0 == 2 && __clang_minor__ >= 9))) /* FIXME: earlier versions not tested */
/* GCC >= 5.0 or clang >= 2.9 */
#define _MHD_DEPR_FUNC(msg) __attribute__((deprecated(msg)))
#elif defined (__clang__) || __GNUC__+0 > 3 || (__GNUC__+0 == 3 && __GNUC_MINOR__+0 >= 1)
/* 3.1 <= GCC < 5.0 or clang < 2.9 */
/* old GCC-style deprecation do not support custom messages */
#define _MHD_DEPR_FUNC(msg) __attribute__((__deprecated__))
/* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */
#endif /* clang < 2.9 || GCC >= 3.1 */
#endif /* !_MHD_DEPR_FUNC */
#ifndef _MHD_DEPR_FUNC
#define _MHD_NO_DEPR_FUNC 1
#define _MHD_DEPR_FUNC(msg)
#endif /* !_MHD_DEPR_FUNC */
/**
* Not all architectures and `printf()`'s support the `long long` type.
* This gives the ability to replace `long long` with just a `long`,
* standard `int` or a `short`.
*/
#ifndef MHD_LONG_LONG
/**
* @deprecated use #MHD_UNSIGNED_LONG_LONG instead!
*/
#define MHD_LONG_LONG long long
#define MHD_UNSIGNED_LONG_LONG unsigned long long
#else /* MHD_LONG_LONG */
_MHD_DEPR_MACRO("Macro MHD_LONG_LONG is deprecated, use MHD_UNSIGNED_LONG_LONG")
#endif
/**
* Format string for printing a variable of type #MHD_LONG_LONG.
* You should only redefine this if you also define #MHD_LONG_LONG.
*/
#ifndef MHD_LONG_LONG_PRINTF
/**
* @deprecated use #MHD_UNSIGNED_LONG_LONG_PRINTF instead!
*/
#define MHD_LONG_LONG_PRINTF "ll"
#define MHD_UNSIGNED_LONG_LONG_PRINTF "%llu"
#else /* MHD_LONG_LONG_PRINTF */
_MHD_DEPR_MACRO("Macro MHD_LONG_LONG_PRINTF is deprecated, use MHD_UNSIGNED_LONG_LONG_PRINTF")
#endif
/**
* @defgroup httpcode HTTP response codes.
* These are the status codes defined for HTTP responses.
* @{
*/
/* See http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml */
#define MHD_HTTP_CONTINUE 100
#define MHD_HTTP_SWITCHING_PROTOCOLS 101
#define MHD_HTTP_PROCESSING 102
#define MHD_HTTP_OK 200
#define MHD_HTTP_CREATED 201
#define MHD_HTTP_ACCEPTED 202
#define MHD_HTTP_NON_AUTHORITATIVE_INFORMATION 203
#define MHD_HTTP_NO_CONTENT 204
#define MHD_HTTP_RESET_CONTENT 205
#define MHD_HTTP_PARTIAL_CONTENT 206
#define MHD_HTTP_MULTI_STATUS 207
#define MHD_HTTP_ALREADY_REPORTED 208
#define MHD_HTTP_IM_USED 226
#define MHD_HTTP_MULTIPLE_CHOICES 300
#define MHD_HTTP_MOVED_PERMANENTLY 301
#define MHD_HTTP_FOUND 302
#define MHD_HTTP_SEE_OTHER 303
#define MHD_HTTP_NOT_MODIFIED 304
#define MHD_HTTP_USE_PROXY 305
#define MHD_HTTP_SWITCH_PROXY 306
#define MHD_HTTP_TEMPORARY_REDIRECT 307
#define MHD_HTTP_PERMANENT_REDIRECT 308
#define MHD_HTTP_BAD_REQUEST 400
#define MHD_HTTP_UNAUTHORIZED 401
#define MHD_HTTP_PAYMENT_REQUIRED 402
#define MHD_HTTP_FORBIDDEN 403
#define MHD_HTTP_NOT_FOUND 404
#define MHD_HTTP_METHOD_NOT_ALLOWED 405
#define MHD_HTTP_NOT_ACCEPTABLE 406
/** @deprecated */
#define MHD_HTTP_METHOD_NOT_ACCEPTABLE \
_MHD_DEPR_IN_MACRO("Value MHD_HTTP_METHOD_NOT_ACCEPTABLE is deprecated, use MHD_HTTP_NOT_ACCEPTABLE") 406
#define MHD_HTTP_PROXY_AUTHENTICATION_REQUIRED 407
#define MHD_HTTP_REQUEST_TIMEOUT 408
#define MHD_HTTP_CONFLICT 409
#define MHD_HTTP_GONE 410
#define MHD_HTTP_LENGTH_REQUIRED 411
#define MHD_HTTP_PRECONDITION_FAILED 412
#define MHD_HTTP_PAYLOAD_TOO_LARGE 413
/** @deprecated */
#define MHD_HTTP_REQUEST_ENTITY_TOO_LARGE \
_MHD_DEPR_IN_MACRO("Value MHD_HTTP_REQUEST_ENTITY_TOO_LARGE is deprecated, use MHD_HTTP_PAYLOAD_TOO_LARGE") 413
#define MHD_HTTP_URI_TOO_LONG 414
/** @deprecated */
#define MHD_HTTP_REQUEST_URI_TOO_LONG \
_MHD_DEPR_IN_MACRO("Value MHD_HTTP_REQUEST_URI_TOO_LONG is deprecated, use MHD_HTTP_URI_TOO_LONG") 414
#define MHD_HTTP_UNSUPPORTED_MEDIA_TYPE 415
#define MHD_HTTP_RANGE_NOT_SATISFIABLE 416
/** @deprecated */
#define MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE \
_MHD_DEPR_IN_MACRO("Value MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE is deprecated, use MHD_HTTP_RANGE_NOT_SATISFIABLE") 416
#define MHD_HTTP_EXPECTATION_FAILED 417
#define MHD_HTTP_MISDIRECTED_REQUEST 421
#define MHD_HTTP_UNPROCESSABLE_ENTITY 422
#define MHD_HTTP_LOCKED 423
#define MHD_HTTP_FAILED_DEPENDENCY 424
#define MHD_HTTP_UNORDERED_COLLECTION 425
#define MHD_HTTP_UPGRADE_REQUIRED 426
#define MHD_HTTP_PRECONDITION_REQUIRED 428
#define MHD_HTTP_TOO_MANY_REQUESTS 429
#define MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE 431
#define MHD_HTTP_NO_RESPONSE 444
#define MHD_HTTP_RETRY_WITH 449
#define MHD_HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS 450
#define MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS 451
#define MHD_HTTP_INTERNAL_SERVER_ERROR 500
#define MHD_HTTP_NOT_IMPLEMENTED 501
#define MHD_HTTP_BAD_GATEWAY 502
#define MHD_HTTP_SERVICE_UNAVAILABLE 503
#define MHD_HTTP_GATEWAY_TIMEOUT 504
#define MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED 505
#define MHD_HTTP_VARIANT_ALSO_NEGOTIATES 506
#define MHD_HTTP_INSUFFICIENT_STORAGE 507
#define MHD_HTTP_LOOP_DETECTED 508
#define MHD_HTTP_BANDWIDTH_LIMIT_EXCEEDED 509
#define MHD_HTTP_NOT_EXTENDED 510
#define MHD_HTTP_NETWORK_AUTHENTICATION_REQUIRED 511
/** @} */ /* end of group httpcode */
/**
* Returns the string reason phrase for a response code.
*
* If we don't have a string for a status code, we give the first
* message in that status code class.
*/
_MHD_EXTERN const char *
MHD_get_reason_phrase_for (unsigned int code);
/**
* Flag to be or-ed with MHD_HTTP status code for
* SHOUTcast. This will cause the response to begin
* with the SHOUTcast "ICY" line instad of "HTTP".
* @ingroup specialized
*/
#define MHD_ICY_FLAG ((uint32_t)(((uint32_t)1) << 31))
/**
* @defgroup headers HTTP headers
* These are the standard headers found in HTTP requests and responses.
* See: http://www.iana.org/assignments/message-headers/message-headers.xml
* Registry Version 2017-01-27
* @{
*/
/* Main HTTP headers. */
/* Standard. RFC7231, Section 5.3.2 */
#define MHD_HTTP_HEADER_ACCEPT "Accept"
/* Standard. RFC7231, Section 5.3.3 */
#define MHD_HTTP_HEADER_ACCEPT_CHARSET "Accept-Charset"
/* Standard. RFC7231, Section 5.3.4; RFC7694, Section 3 */
#define MHD_HTTP_HEADER_ACCEPT_ENCODING "Accept-Encoding"
/* Standard. RFC7231, Section 5.3.5 */
#define MHD_HTTP_HEADER_ACCEPT_LANGUAGE "Accept-Language"
/* Standard. RFC7233, Section 2.3 */
#define MHD_HTTP_HEADER_ACCEPT_RANGES "Accept-Ranges"
/* Standard. RFC7234, Section 5.1 */
#define MHD_HTTP_HEADER_AGE "Age"
/* Standard. RFC7231, Section 7.4.1 */
#define MHD_HTTP_HEADER_ALLOW "Allow"
/* Standard. RFC7235, Section 4.2 */
#define MHD_HTTP_HEADER_AUTHORIZATION "Authorization"
/* Standard. RFC7234, Section 5.2 */
#define MHD_HTTP_HEADER_CACHE_CONTROL "Cache-Control"
/* Reserved. RFC7230, Section 8.1 */
#define MHD_HTTP_HEADER_CLOSE "Close"
/* Standard. RFC7230, Section 6.1 */
#define MHD_HTTP_HEADER_CONNECTION "Connection"
/* Standard. RFC7231, Section 3.1.2.2 */
#define MHD_HTTP_HEADER_CONTENT_ENCODING "Content-Encoding"
/* Standard. RFC7231, Section 3.1.3.2 */
#define MHD_HTTP_HEADER_CONTENT_LANGUAGE "Content-Language"
/* Standard. RFC7230, Section 3.3.2 */
#define MHD_HTTP_HEADER_CONTENT_LENGTH "Content-Length"
/* Standard. RFC7231, Section 3.1.4.2 */
#define MHD_HTTP_HEADER_CONTENT_LOCATION "Content-Location"
/* Standard. RFC7233, Section 4.2 */
#define MHD_HTTP_HEADER_CONTENT_RANGE "Content-Range"
/* Standard. RFC7231, Section 3.1.1.5 */
#define MHD_HTTP_HEADER_CONTENT_TYPE "Content-Type"
/* Standard. RFC7231, Section 7.1.1.2 */
#define MHD_HTTP_HEADER_DATE "Date"
/* Standard. RFC7232, Section 2.3 */
#define MHD_HTTP_HEADER_ETAG "ETag"
/* Standard. RFC7231, Section 5.1.1 */
#define MHD_HTTP_HEADER_EXPECT "Expect"
/* Standard. RFC7234, Section 5.3 */
#define MHD_HTTP_HEADER_EXPIRES "Expires"
/* Standard. RFC7231, Section 5.5.1 */
#define MHD_HTTP_HEADER_FROM "From"
/* Standard. RFC7230, Section 5.4 */
#define MHD_HTTP_HEADER_HOST "Host"
/* Standard. RFC7232, Section 3.1 */
#define MHD_HTTP_HEADER_IF_MATCH "If-Match"
/* Standard. RFC7232, Section 3.3 */
#define MHD_HTTP_HEADER_IF_MODIFIED_SINCE "If-Modified-Since"
/* Standard. RFC7232, Section 3.2 */
#define MHD_HTTP_HEADER_IF_NONE_MATCH "If-None-Match"
/* Standard. RFC7233, Section 3.2 */
#define MHD_HTTP_HEADER_IF_RANGE "If-Range"
/* Standard. RFC7232, Section 3.4 */
#define MHD_HTTP_HEADER_IF_UNMODIFIED_SINCE "If-Unmodified-Since"
/* Standard. RFC7232, Section 2.2 */
#define MHD_HTTP_HEADER_LAST_MODIFIED "Last-Modified"
/* Standard. RFC7231, Section 7.1.2 */
#define MHD_HTTP_HEADER_LOCATION "Location"
/* Standard. RFC7231, Section 5.1.2 */
#define MHD_HTTP_HEADER_MAX_FORWARDS "Max-Forwards"
/* Standard. RFC7231, Appendix A.1 */
#define MHD_HTTP_HEADER_MIME_VERSION "MIME-Version"
/* Standard. RFC7234, Section 5.4 */
#define MHD_HTTP_HEADER_PRAGMA "Pragma"
/* Standard. RFC7235, Section 4.3 */
#define MHD_HTTP_HEADER_PROXY_AUTHENTICATE "Proxy-Authenticate"
/* Standard. RFC7235, Section 4.4 */
#define MHD_HTTP_HEADER_PROXY_AUTHORIZATION "Proxy-Authorization"
/* Standard. RFC7233, Section 3.1 */
#define MHD_HTTP_HEADER_RANGE "Range"
/* Standard. RFC7231, Section 5.5.2 */
#define MHD_HTTP_HEADER_REFERER "Referer"
/* Standard. RFC7231, Section 7.1.3 */
#define MHD_HTTP_HEADER_RETRY_AFTER "Retry-After"
/* Standard. RFC7231, Section 7.4.2 */
#define MHD_HTTP_HEADER_SERVER "Server"
/* Standard. RFC7230, Section 4.3 */
#define MHD_HTTP_HEADER_TE "TE"
/* Standard. RFC7230, Section 4.4 */
#define MHD_HTTP_HEADER_TRAILER "Trailer"
/* Standard. RFC7230, Section 3.3.1 */
#define MHD_HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding"
/* Standard. RFC7230, Section 6.7 */
#define MHD_HTTP_HEADER_UPGRADE "Upgrade"
/* Standard. RFC7231, Section 5.5.3 */
#define MHD_HTTP_HEADER_USER_AGENT "User-Agent"
/* Standard. RFC7231, Section 7.1.4 */
#define MHD_HTTP_HEADER_VARY "Vary"
/* Standard. RFC7230, Section 5.7.1 */
#define MHD_HTTP_HEADER_VIA "Via"
/* Standard. RFC7235, Section 4.1 */
#define MHD_HTTP_HEADER_WWW_AUTHENTICATE "WWW-Authenticate"
/* Standard. RFC7234, Section 5.5 */
#define MHD_HTTP_HEADER_WARNING "Warning"
/* Additional HTTP headers. */
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_A_IM "A-IM"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_ACCEPT_ADDITIONS "Accept-Additions"
/* Informational. RFC7089 */
#define MHD_HTTP_HEADER_ACCEPT_DATETIME "Accept-Datetime"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_ACCEPT_FEATURES "Accept-Features"
/* No category. RFC5789 */
#define MHD_HTTP_HEADER_ACCEPT_PATCH "Accept-Patch"
/* Standard. RFC7639, Section 2 */
#define MHD_HTTP_HEADER_ALPN "ALPN"
/* Standard. RFC7838 */
#define MHD_HTTP_HEADER_ALT_SVC "Alt-Svc"
/* Standard. RFC7838 */
#define MHD_HTTP_HEADER_ALT_USED "Alt-Used"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_ALTERNATES "Alternates"
/* No category. RFC4437 */
#define MHD_HTTP_HEADER_APPLY_TO_REDIRECT_REF "Apply-To-Redirect-Ref"
/* Experimental. RFC8053, Section 4 */
#define MHD_HTTP_HEADER_AUTHENTICATION_CONTROL "Authentication-Control"
/* Standard. RFC7615, Section 3 */
#define MHD_HTTP_HEADER_AUTHENTICATION_INFO "Authentication-Info"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_C_EXT "C-Ext"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_C_MAN "C-Man"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_C_OPT "C-Opt"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_C_PEP "C-PEP"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_C_PEP_INFO "C-PEP-Info"
/* Standard. RFC7809, Section 7.1 */
#define MHD_HTTP_HEADER_CALDAV_TIMEZONES "CalDAV-Timezones"
/* Obsoleted. RFC2068; RFC2616 */
#define MHD_HTTP_HEADER_CONTENT_BASE "Content-Base"
/* Standard. RFC6266 */
#define MHD_HTTP_HEADER_CONTENT_DISPOSITION "Content-Disposition"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_CONTENT_ID "Content-ID"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_CONTENT_MD5 "Content-MD5"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_CONTENT_SCRIPT_TYPE "Content-Script-Type"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_CONTENT_STYLE_TYPE "Content-Style-Type"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_CONTENT_VERSION "Content-Version"
/* Standard. RFC6265 */
#define MHD_HTTP_HEADER_COOKIE "Cookie"
/* Obsoleted. RFC2965; RFC6265 */
#define MHD_HTTP_HEADER_COOKIE2 "Cookie2"
/* Standard. RFC5323 */
#define MHD_HTTP_HEADER_DASL "DASL"
/* Standard. RFC4918 */
#define MHD_HTTP_HEADER_DAV "DAV"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_DEFAULT_STYLE "Default-Style"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_DELTA_BASE "Delta-Base"
/* Standard. RFC4918 */
#define MHD_HTTP_HEADER_DEPTH "Depth"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_DERIVED_FROM "Derived-From"
/* Standard. RFC4918 */
#define MHD_HTTP_HEADER_DESTINATION "Destination"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_DIFFERENTIAL_ID "Differential-ID"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_DIGEST "Digest"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_EXT "Ext"
/* Standard. RFC7239 */
#define MHD_HTTP_HEADER_FORWARDED "Forwarded"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_GETPROFILE "GetProfile"
/* Experimental. RFC7486, Section 6.1.1 */
#define MHD_HTTP_HEADER_HOBAREG "Hobareg"
/* Standard. RFC7540, Section 3.2.1 */
#define MHD_HTTP_HEADER_HTTP2_SETTINGS "HTTP2-Settings"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_IM "IM"
/* Standard. RFC4918 */
#define MHD_HTTP_HEADER_IF "If"
/* Standard. RFC6638 */
#define MHD_HTTP_HEADER_IF_SCHEDULE_TAG_MATCH "If-Schedule-Tag-Match"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_KEEP_ALIVE "Keep-Alive"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_LABEL "Label"
/* No category. RFC5988 */
#define MHD_HTTP_HEADER_LINK "Link"
/* Standard. RFC4918 */
#define MHD_HTTP_HEADER_LOCK_TOKEN "Lock-Token"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_MAN "Man"
/* Informational. RFC7089 */
#define MHD_HTTP_HEADER_MEMENTO_DATETIME "Memento-Datetime"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_METER "Meter"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_NEGOTIATE "Negotiate"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_OPT "Opt"
/* Experimental. RFC8053, Section 3 */
#define MHD_HTTP_HEADER_OPTIONAL_WWW_AUTHENTICATE "Optional-WWW-Authenticate"
/* Standard. RFC4229 */
#define MHD_HTTP_HEADER_ORDERING_TYPE "Ordering-Type"
/* Standard. RFC6454 */
#define MHD_HTTP_HEADER_ORIGIN "Origin"
/* Standard. RFC4918 */
#define MHD_HTTP_HEADER_OVERWRITE "Overwrite"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_P3P "P3P"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PEP "PEP"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PICS_LABEL "PICS-Label"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PEP_INFO "Pep-Info"
/* Standard. RFC4229 */
#define MHD_HTTP_HEADER_POSITION "Position"
/* Standard. RFC7240 */
#define MHD_HTTP_HEADER_PREFER "Prefer"
/* Standard. RFC7240 */
#define MHD_HTTP_HEADER_PREFERENCE_APPLIED "Preference-Applied"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PROFILEOBJECT "ProfileObject"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PROTOCOL "Protocol"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PROTOCOL_INFO "Protocol-Info"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PROTOCOL_QUERY "Protocol-Query"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PROTOCOL_REQUEST "Protocol-Request"
/* Standard. RFC7615, Section 4 */
#define MHD_HTTP_HEADER_PROXY_AUTHENTICATION_INFO "Proxy-Authentication-Info"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PROXY_FEATURES "Proxy-Features"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PROXY_INSTRUCTION "Proxy-Instruction"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_PUBLIC "Public"
/* Standard. RFC7469 */
#define MHD_HTTP_HEADER_PUBLIC_KEY_PINS "Public-Key-Pins"
/* Standard. RFC7469 */
#define MHD_HTTP_HEADER_PUBLIC_KEY_PINS_REPORT_ONLY "Public-Key-Pins-Report-Only"
/* No category. RFC4437 */
#define MHD_HTTP_HEADER_REDIRECT_REF "Redirect-Ref"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_SAFE "Safe"
/* Standard. RFC6638 */
#define MHD_HTTP_HEADER_SCHEDULE_REPLY "Schedule-Reply"
/* Standard. RFC6638 */
#define MHD_HTTP_HEADER_SCHEDULE_TAG "Schedule-Tag"
/* Standard. RFC6455 */
#define MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT "Sec-WebSocket-Accept"
/* Standard. RFC6455 */
#define MHD_HTTP_HEADER_SEC_WEBSOCKET_EXTENSIONS "Sec-WebSocket-Extensions"
/* Standard. RFC6455 */
#define MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY "Sec-WebSocket-Key"
/* Standard. RFC6455 */
#define MHD_HTTP_HEADER_SEC_WEBSOCKET_PROTOCOL "Sec-WebSocket-Protocol"
/* Standard. RFC6455 */
#define MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_SECURITY_SCHEME "Security-Scheme"
/* Standard. RFC6265 */
#define MHD_HTTP_HEADER_SET_COOKIE "Set-Cookie"
/* Obsoleted. RFC2965; RFC6265 */
#define MHD_HTTP_HEADER_SET_COOKIE2 "Set-Cookie2"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_SETPROFILE "SetProfile"
/* Standard. RFC5023 */
#define MHD_HTTP_HEADER_SLUG "SLUG"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_SOAPACTION "SoapAction"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_STATUS_URI "Status-URI"
/* Standard. RFC6797 */
#define MHD_HTTP_HEADER_STRICT_TRANSPORT_SECURITY "Strict-Transport-Security"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_SURROGATE_CAPABILITY "Surrogate-Capability"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_SURROGATE_CONTROL "Surrogate-Control"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_TCN "TCN"
/* Standard. RFC4918 */
#define MHD_HTTP_HEADER_TIMEOUT "Timeout"
/* Standard. RFC8030, Section 5.4 */
#define MHD_HTTP_HEADER_TOPIC "Topic"
/* Standard. RFC8030, Section 5.2 */
#define MHD_HTTP_HEADER_TTL "TTL"
/* Standard. RFC8030, Section 5.3 */
#define MHD_HTTP_HEADER_URGENCY "Urgency"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_URI "URI"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_VARIANT_VARY "Variant-Vary"
/* No category. RFC4229 */
#define MHD_HTTP_HEADER_WANT_DIGEST "Want-Digest"
/* Informational. RFC7034 */
#define MHD_HTTP_HEADER_X_FRAME_OPTIONS "X-Frame-Options"
/* Some provisional headers. */
#define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN "Access-Control-Allow-Origin"
/** @} */ /* end of group headers */
/**
* @defgroup versions HTTP versions
* These strings should be used to match against the first line of the
* HTTP header.
* @{
*/
#define MHD_HTTP_VERSION_1_0 "HTTP/1.0"
#define MHD_HTTP_VERSION_1_1 "HTTP/1.1"
/** @} */ /* end of group versions */
/**
* @defgroup methods HTTP methods
* HTTP methods (as strings).
* See: http://www.iana.org/assignments/http-methods/http-methods.xml
* Registry Version 2015-05-19
* @{
*/
/* Main HTTP methods. */
/* Not safe. Not idempotent. RFC7231, Section 4.3.6. */
#define MHD_HTTP_METHOD_CONNECT "CONNECT"
/* Not safe. Idempotent. RFC7231, Section 4.3.5. */
#define MHD_HTTP_METHOD_DELETE "DELETE"
/* Safe. Idempotent. RFC7231, Section 4.3.1. */
#define MHD_HTTP_METHOD_GET "GET"
/* Safe. Idempotent. RFC7231, Section 4.3.2. */
#define MHD_HTTP_METHOD_HEAD "HEAD"
/* Safe. Idempotent. RFC7231, Section 4.3.7. */
#define MHD_HTTP_METHOD_OPTIONS "OPTIONS"
/* Not safe. Not idempotent. RFC7231, Section 4.3.3. */
#define MHD_HTTP_METHOD_POST "POST"
/* Not safe. Idempotent. RFC7231, Section 4.3.4. */
#define MHD_HTTP_METHOD_PUT "PUT"
/* Safe. Idempotent. RFC7231, Section 4.3.8. */
#define MHD_HTTP_METHOD_TRACE "TRACE"
/* Additional HTTP methods. */
/* Not safe. Idempotent. RFC3744, Section 8.1. */
#define MHD_HTTP_METHOD_ACL "ACL"
/* Not safe. Idempotent. RFC3253, Section 12.6. */
#define MHD_HTTP_METHOD_BASELINE_CONTROL "BASELINE-CONTROL"
/* Not safe. Idempotent. RFC5842, Section 4. */
#define MHD_HTTP_METHOD_BIND "BIND"
/* Not safe. Idempotent. RFC3253, Section 4.4, Section 9.4. */
#define MHD_HTTP_METHOD_CHECKIN "CHECKIN"
/* Not safe. Idempotent. RFC3253, Section 4.3, Section 8.8. */
#define MHD_HTTP_METHOD_CHECKOUT "CHECKOUT"
/* Not safe. Idempotent. RFC4918, Section 9.8. */
#define MHD_HTTP_METHOD_COPY "COPY"
/* Not safe. Idempotent. RFC3253, Section 8.2. */
#define MHD_HTTP_METHOD_LABEL "LABEL"
/* Not safe. Idempotent. RFC2068, Section 19.6.1.2. */
#define MHD_HTTP_METHOD_LINK "LINK"
/* Not safe. Not idempotent. RFC4918, Section 9.10. */
#define MHD_HTTP_METHOD_LOCK "LOCK"
/* Not safe. Idempotent. RFC3253, Section 11.2. */
#define MHD_HTTP_METHOD_MERGE "MERGE"
/* Not safe. Idempotent. RFC3253, Section 13.5. */
#define MHD_HTTP_METHOD_MKACTIVITY "MKACTIVITY"
/* Not safe. Idempotent. RFC4791, Section 5.3.1. */
#define MHD_HTTP_METHOD_MKCALENDAR "MKCALENDAR"
/* Not safe. Idempotent. RFC4918, Section 9.3. */
#define MHD_HTTP_METHOD_MKCOL "MKCOL"
/* Not safe. Idempotent. RFC4437, Section 6. */
#define MHD_HTTP_METHOD_MKREDIRECTREF "MKREDIRECTREF"
/* Not safe. Idempotent. RFC3253, Section 6.3. */
#define MHD_HTTP_METHOD_MKWORKSPACE "MKWORKSPACE"
/* Not safe. Idempotent. RFC4918, Section 9.9. */
#define MHD_HTTP_METHOD_MOVE "MOVE"
/* Not safe. Idempotent. RFC3648, Section 7. */
#define MHD_HTTP_METHOD_ORDERPATCH "ORDERPATCH"
/* Not safe. Not idempotent. RFC5789, Section 2. */
#define MHD_HTTP_METHOD_PATCH "PATCH"
/* Safe. Idempotent. RFC7540, Section 3.5. */
#define MHD_HTTP_METHOD_PRI "PRI"
/* Safe. Idempotent. RFC4918, Section 9.1. */
#define MHD_HTTP_METHOD_PROPFIND "PROPFIND"
/* Not safe. Idempotent. RFC4918, Section 9.2. */
#define MHD_HTTP_METHOD_PROPPATCH "PROPPATCH"
/* Not safe. Idempotent. RFC5842, Section 6. */
#define MHD_HTTP_METHOD_REBIND "REBIND"
/* Safe. Idempotent. RFC3253, Section 3.6. */
#define MHD_HTTP_METHOD_REPORT "REPORT"
/* Safe. Idempotent. RFC5323, Section 2. */
#define MHD_HTTP_METHOD_SEARCH "SEARCH"
/* Not safe. Idempotent. RFC5842, Section 5. */
#define MHD_HTTP_METHOD_UNBIND "UNBIND"
/* Not safe. Idempotent. RFC3253, Section 4.5. */
#define MHD_HTTP_METHOD_UNCHECKOUT "UNCHECKOUT"
/* Not safe. Idempotent. RFC2068, Section 19.6.1.3. */
#define MHD_HTTP_METHOD_UNLINK "UNLINK"
/* Not safe. Idempotent. RFC4918, Section 9.11. */
#define MHD_HTTP_METHOD_UNLOCK "UNLOCK"
/* Not safe. Idempotent. RFC3253, Section 7.1. */
#define MHD_HTTP_METHOD_UPDATE "UPDATE"
/* Not safe. Idempotent. RFC4437, Section 7. */
#define MHD_HTTP_METHOD_UPDATEREDIRECTREF "UPDATEREDIRECTREF"
/* Not safe. Idempotent. RFC3253, Section 3.5. */
#define MHD_HTTP_METHOD_VERSION_CONTROL "VERSION-CONTROL"
/** @} */ /* end of group methods */
/**
* @defgroup postenc HTTP POST encodings
* See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
* @{
*/
#define MHD_HTTP_POST_ENCODING_FORM_URLENCODED "application/x-www-form-urlencoded"
#define MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA "multipart/form-data"
/** @} */ /* end of group postenc */
/**
* @brief Handle for the daemon (listening on a socket for HTTP traffic).
* @ingroup event
*/
struct MHD_Daemon;
/**
* @brief Handle for a connection / HTTP request.
*
* With HTTP/1.1, multiple requests can be run over the same
* connection. However, MHD will only show one request per TCP
* connection to the client at any given time.
* @ingroup request
*/
struct MHD_Connection;
/**
* @brief Handle for a response.
* @ingroup response
*/
struct MHD_Response;
/**
* @brief Handle for POST processing.
* @ingroup response
*/
struct MHD_PostProcessor;
/**
* @brief Flags for the `struct MHD_Daemon`.
*
* Note that MHD will run automatically in background thread(s) only
* if #MHD_USE_INTERNAL_POLLING_THREAD is used. Otherwise caller (application)
* must use #MHD_run() or #MHD_run_from_select() to have MHD processed
* network connections and data.
*
* Starting the daemon may also fail if a particular option is not
* implemented or not supported on the target platform (i.e. no
* support for TLS, epoll or IPv6).
*/
enum MHD_FLAG
{
/**
* No options selected.
*/
MHD_NO_FLAG = 0,
/**
* Print errors messages to custom error logger or to `stderr` if
* custom error logger is not set.
* @sa ::MHD_OPTION_EXTERNAL_LOGGER
*/
MHD_USE_ERROR_LOG = 1,
/**
* Run in debug mode. If this flag is used, the library should
* print error messages and warnings to `stderr`.
*/
MHD_USE_DEBUG = 1,
/**
* Run in HTTPS mode. The modern protocol is called TLS.
*/
MHD_USE_TLS = 2,
/** @deprecated */
MHD_USE_SSL = 2,
#if 0
/* let's do this later once versions that define MHD_USE_TLS a more widely deployed. */
#define MHD_USE_SSL \
_MHD_DEPR_IN_MACRO("Value MHD_USE_SSL is deprecated, use MHD_USE_TLS") \
MHD_USE_TLS
#endif
/**
* Run using one thread per connection.
* Must be used only with #MHD_USE_INTERNAL_POLLING_THREAD.
*/
MHD_USE_THREAD_PER_CONNECTION = 4,
/**
* Run using an internal thread (or thread pool) for sockets sending
* and receiving and data processing. Without this flag MHD will not
* run automatically in background thread(s).
* If this flag is set, #MHD_run() and #MHD_run_from_select() couldn't
* be used.
* This flag is set explicitly by #MHD_USE_POLL_INTERNAL_THREAD and
* by #MHD_USE_EPOLL_INTERNAL_THREAD.
*/
MHD_USE_INTERNAL_POLLING_THREAD = 8,
/** @deprecated */
MHD_USE_SELECT_INTERNALLY = 8,
#if 0 /* Will be marked for real deprecation later. */
#define MHD_USE_SELECT_INTERNALLY \
_MHD_DEPR_IN_MACRO("Value MHD_USE_SELECT_INTERNALLY is deprecated, use MHD_USE_INTERNAL_POLLING_THREAD instead") \
MHD_USE_INTERNAL_POLLING_THREAD
#endif /* 0 */
/**
* Run using the IPv6 protocol (otherwise, MHD will just support
* IPv4). If you want MHD to support IPv4 and IPv6 using a single
* socket, pass #MHD_USE_DUAL_STACK, otherwise, if you only pass
* this option, MHD will try to bind to IPv6-only (resulting in
* no IPv4 support).
*/
MHD_USE_IPv6 = 16,
/**
* Be pedantic about the protocol (as opposed to as tolerant as
* possible). Specifically, at the moment, this flag causes MHD to
* reject HTTP 1.1 connections without a "Host" header. This is
* required by the standard, but of course in violation of the "be
* as liberal as possible in what you accept" norm. It is
* recommended to turn this ON if you are testing clients against
* MHD, and OFF in production.
*/
MHD_USE_PEDANTIC_CHECKS = 32,
#if 0 /* Will be marked for real deprecation later. */
#define MHD_USE_PEDANTIC_CHECKS \
_MHD_DEPR_IN_MACRO("Flag MHD_USE_PEDANTIC_CHECKS is deprecated, use option MHD_OPTION_STRICT_FOR_CLIENT instead") \
32
#endif /* 0 */
/**
* Use `poll()` instead of `select()`. This allows sockets with `fd >=
* FD_SETSIZE`. This option is not compatible with using an
* 'external' polling mode (as there is no API to get the file
* descriptors for the external poll() from MHD) and must also not
* be used in combination with #MHD_USE_EPOLL.
* @sa ::MHD_FEATURE_POLL, #MHD_USE_POLL_INTERNAL_THREAD
*/
MHD_USE_POLL = 64,
/**
* Run using an internal thread (or thread pool) doing `poll()`.
* @sa ::MHD_FEATURE_POLL, #MHD_USE_POLL, #MHD_USE_INTERNAL_POLLING_THREAD
*/
MHD_USE_POLL_INTERNAL_THREAD = MHD_USE_POLL | MHD_USE_INTERNAL_POLLING_THREAD,
/** @deprecated */
MHD_USE_POLL_INTERNALLY = MHD_USE_POLL | MHD_USE_INTERNAL_POLLING_THREAD,
#if 0 /* Will be marked for real deprecation later. */
#define MHD_USE_POLL_INTERNALLY \
_MHD_DEPR_IN_MACRO("Value MHD_USE_POLL_INTERNALLY is deprecated, use MHD_USE_POLL_INTERNAL_THREAD instead") \
MHD_USE_POLL_INTERNAL_THREAD
#endif /* 0 */
/**
* Suppress (automatically) adding the 'Date:' header to HTTP responses.
* This option should ONLY be used on systems that do not have a clock
* and that DO provide other mechanisms for cache control. See also
* RFC 2616, section 14.18 (exception 3).
*/
MHD_USE_SUPPRESS_DATE_NO_CLOCK = 128,
/** @deprecated */
MHD_SUPPRESS_DATE_NO_CLOCK = 128,
#if 0 /* Will be marked for real deprecation later. */
#define MHD_SUPPRESS_DATE_NO_CLOCK \
_MHD_DEPR_IN_MACRO("Value MHD_SUPPRESS_DATE_NO_CLOCK is deprecated, use MHD_USE_SUPPRESS_DATE_NO_CLOCK instead") \
MHD_USE_SUPPRESS_DATE_NO_CLOCK
#endif /* 0 */
/**
* Run without a listen socket. This option only makes sense if
* #MHD_add_connection is to be used exclusively to connect HTTP
* clients to the HTTP server. This option is incompatible with
* using a thread pool; if it is used, #MHD_OPTION_THREAD_POOL_SIZE
* is ignored.
*/
MHD_USE_NO_LISTEN_SOCKET = 256,
/**
* Use `epoll()` instead of `select()` or `poll()` for the event loop.
* This option is only available on some systems; using the option on
* systems without epoll will cause #MHD_start_daemon to fail. Using
* this option is not supported with #MHD_USE_THREAD_PER_CONNECTION.
* @sa ::MHD_FEATURE_EPOLL
*/
MHD_USE_EPOLL = 512,
/** @deprecated */
MHD_USE_EPOLL_LINUX_ONLY = 512,
#if 0 /* Will be marked for real deprecation later. */
#define MHD_USE_EPOLL_LINUX_ONLY \
_MHD_DEPR_IN_MACRO("Value MHD_USE_EPOLL_LINUX_ONLY is deprecated, use MHD_USE_EPOLL") \
MHD_USE_EPOLL
#endif /* 0 */
/**
* Run using an internal thread (or thread pool) doing `epoll()`.
* This option is only available on certain platforms; using the option on
* platform without `epoll` support will cause #MHD_start_daemon to fail.
* @sa ::MHD_FEATURE_EPOLL, #MHD_USE_EPOLL, #MHD_USE_INTERNAL_POLLING_THREAD
*/
MHD_USE_EPOLL_INTERNAL_THREAD = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD,
/** @deprecated */
MHD_USE_EPOLL_INTERNALLY = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD,
/** @deprecated */
MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD,
#if 0 /* Will be marked for real deprecation later. */
#define MHD_USE_EPOLL_INTERNALLY \
_MHD_DEPR_IN_MACRO("Value MHD_USE_EPOLL_INTERNALLY is deprecated, use MHD_USE_EPOLL_INTERNAL_THREAD") \
MHD_USE_EPOLL_INTERNAL_THREAD
/** @deprecated */
#define MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY \
_MHD_DEPR_IN_MACRO("Value MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY is deprecated, use MHD_USE_EPOLL_INTERNAL_THREAD") \
MHD_USE_EPOLL_INTERNAL_THREAD
#endif /* 0 */
/**
* Use inter-thread communication channel.
* #MHD_USE_ITC can be used with #MHD_USE_INTERNAL_POLLING_THREAD
* and is ignored with any "external" mode.
* It's required for use of #MHD_quiesce_daemon
* or #MHD_add_connection.
* This option is enforced by #MHD_ALLOW_SUSPEND_RESUME or
* #MHD_USE_NO_LISTEN_SOCKET.
* #MHD_USE_ITC is always used automatically on platforms
* where select()/poll()/other ignore shutdown of listen
* socket.
*/
MHD_USE_ITC = 1024,
/** @deprecated */
MHD_USE_PIPE_FOR_SHUTDOWN = 1024,
#if 0 /* Will be marked for real deprecation later. */
#define MHD_USE_PIPE_FOR_SHUTDOWN \
_MHD_DEPR_IN_MACRO("Value MHD_USE_PIPE_FOR_SHUTDOWN is deprecated, use MHD_USE_ITC") \
MHD_USE_ITC
#endif /* 0 */
/**
* Use a single socket for IPv4 and IPv6.
*/
MHD_USE_DUAL_STACK = MHD_USE_IPv6 | 2048,
/**
* Enable `turbo`. Disables certain calls to `shutdown()`,
* enables aggressive non-blocking optimistic reads and
* other potentially unsafe optimizations.
* Most effects only happen with #MHD_USE_EPOLL.
*/
MHD_USE_TURBO = 4096,
/** @deprecated */
MHD_USE_EPOLL_TURBO = 4096,
#if 0 /* Will be marked for real deprecation later. */
#define MHD_USE_EPOLL_TURBO \
_MHD_DEPR_IN_MACRO("Value MHD_USE_EPOLL_TURBO is deprecated, use MHD_USE_TURBO") \
MHD_USE_TURBO
#endif /* 0 */
/**
* Enable suspend/resume functions, which also implies setting up
* ITC to signal resume.
*/
MHD_ALLOW_SUSPEND_RESUME = 8192 | MHD_USE_ITC,
/** @deprecated */
MHD_USE_SUSPEND_RESUME = 8192 | MHD_USE_ITC,
#if 0 /* Will be marked for real deprecation later. */
#define MHD_USE_SUSPEND_RESUME \
_MHD_DEPR_IN_MACRO("Value MHD_USE_SUSPEND_RESUME is deprecated, use MHD_ALLOW_SUSPEND_RESUME instead") \
MHD_ALLOW_SUSPEND_RESUME
#endif /* 0 */
/**
* Enable TCP_FASTOPEN option. This option is only available on Linux with a
* kernel >= 3.6. On other systems, using this option cases #MHD_start_daemon
* to fail.
*/
MHD_USE_TCP_FASTOPEN = 16384,
/**
* You need to set this option if you want to use HTTP "Upgrade".
* "Upgrade" may require usage of additional internal resources,
* which we do not want to use unless necessary.
*/
MHD_ALLOW_UPGRADE = 32768,
/**
* Automatically use best available polling function.
* Choice of polling function is also depend on other daemon options.
* If #MHD_USE_INTERNAL_POLLING_THREAD is specified then epoll, poll() or
* select() will be used (listed in decreasing preference order, first
* function available on system will be used).
* If #MHD_USE_THREAD_PER_CONNECTION is specified then poll() or select()
* will be used.
* If those flags are not specified then epoll or select() will be
* used (as the only suitable for MHD_get_fdset())
*/
MHD_USE_AUTO = 65536,
/**
* Run using an internal thread (or thread pool) with best available on
* system polling function.
* This is combination of #MHD_USE_AUTO and #MHD_USE_INTERNAL_POLLING_THREAD
* flags.
*/
MHD_USE_AUTO_INTERNAL_THREAD = MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD
};
/**
* Type of a callback function used for logging by MHD.
*
* @param cls closure
* @param fm format string (`printf()`-style)
* @param ap arguments to @a fm
* @ingroup logging
*/
typedef void
(*MHD_LogCallback)(void *cls,
const char *fm,
va_list ap);
/**
* @brief MHD options.
*
* Passed in the varargs portion of #MHD_start_daemon.
*/
enum MHD_OPTION
{
/**
* No more options / last option. This is used
* to terminate the VARARGs list.
*/
MHD_OPTION_END = 0,
/**
* Maximum memory size per connection (followed by a `size_t`).
* Default is 32 kb (#MHD_POOL_SIZE_DEFAULT).
* Values above 128k are unlikely to result in much benefit, as half
* of the memory will be typically used for IO, and TCP buffers are
* unlikely to support window sizes above 64k on most systems.
*/
MHD_OPTION_CONNECTION_MEMORY_LIMIT = 1,
/**
* Maximum number of concurrent connections to
* accept (followed by an `unsigned int`).
*/
MHD_OPTION_CONNECTION_LIMIT = 2,
/**
* After how many seconds of inactivity should a
* connection automatically be timed out? (followed
* by an `unsigned int`; use zero for no timeout).
*/
MHD_OPTION_CONNECTION_TIMEOUT = 3,
/**
* Register a function that should be called whenever a request has
* been completed (this can be used for application-specific clean
* up). Requests that have never been presented to the application
* (via #MHD_AccessHandlerCallback) will not result in
* notifications.
*
* This option should be followed by TWO pointers. First a pointer
* to a function of type #MHD_RequestCompletedCallback and second a
* pointer to a closure to pass to the request completed callback.
* The second pointer maybe NULL.
*/
MHD_OPTION_NOTIFY_COMPLETED = 4,
/**
* Limit on the number of (concurrent) connections made to the
* server from the same IP address. Can be used to prevent one
* IP from taking over all of the allowed connections. If the
* same IP tries to establish more than the specified number of
* connections, they will be immediately rejected. The option
* should be followed by an `unsigned int`. The default is
* zero, which means no limit on the number of connections
* from the same IP address.
*/
MHD_OPTION_PER_IP_CONNECTION_LIMIT = 5,
/**
* Bind daemon to the supplied `struct sockaddr`. This option should
* be followed by a `struct sockaddr *`. If #MHD_USE_IPv6 is
* specified, the `struct sockaddr*` should point to a `struct
* sockaddr_in6`, otherwise to a `struct sockaddr_in`.
*/
MHD_OPTION_SOCK_ADDR = 6,
/**
* Specify a function that should be called before parsing the URI from
* the client. The specified callback function can be used for processing
* the URI (including the options) before it is parsed. The URI after
* parsing will no longer contain the options, which maybe inconvenient for
* logging. This option should be followed by two arguments, the first
* one must be of the form
*
* void * my_logger(void *cls, const char *uri, struct MHD_Connection *con)
*
* where the return value will be passed as
* (`* con_cls`) in calls to the #MHD_AccessHandlerCallback
* when this request is processed later; returning a
* value of NULL has no special significance (however,
* note that if you return non-NULL, you can no longer
* rely on the first call to the access handler having
* `NULL == *con_cls` on entry;)
* "cls" will be set to the second argument following
* #MHD_OPTION_URI_LOG_CALLBACK. Finally, uri will
* be the 0-terminated URI of the request.
*
* Note that during the time of this call, most of the connection's
* state is not initialized (as we have not yet parsed the headers).
* However, information about the connecting client (IP, socket)
* is available.
*
* The specified function is called only once per request, therefore some
* programmers may use it to instantiate their own request objects, freeing
* them in the notifier #MHD_OPTION_NOTIFY_COMPLETED.
*/
MHD_OPTION_URI_LOG_CALLBACK = 7,
/**
* Memory pointer for the private key (key.pem) to be used by the
* HTTPS daemon. This option should be followed by a
* `const char *` argument.
* This should be used in conjunction with #MHD_OPTION_HTTPS_MEM_CERT.
*/
MHD_OPTION_HTTPS_MEM_KEY = 8,
/**
* Memory pointer for the certificate (cert.pem) to be used by the
* HTTPS daemon. This option should be followed by a
* `const char *` argument.
* This should be used in conjunction with #MHD_OPTION_HTTPS_MEM_KEY.
*/
MHD_OPTION_HTTPS_MEM_CERT = 9,
/**
* Daemon credentials type.
* Followed by an argument of type
* `gnutls_credentials_type_t`.
*/
MHD_OPTION_HTTPS_CRED_TYPE = 10,
/**
* Memory pointer to a `const char *` specifying the
* cipher algorithm (default: "NORMAL").
*/
MHD_OPTION_HTTPS_PRIORITIES = 11,
/**
* Pass a listen socket for MHD to use (systemd-style). If this
* option is used, MHD will not open its own listen socket(s). The
* argument passed must be of type `MHD_socket` and refer to an
* existing socket that has been bound to a port and is listening.
*/
MHD_OPTION_LISTEN_SOCKET = 12,
/**
* Use the given function for logging error messages. This option
* must be followed by two arguments; the first must be a pointer to
* a function of type #MHD_LogCallback and the second a pointer
* `void *` which will be passed as the first argument to the log
* callback.
*
* Note that MHD will not generate any log messages
* if it was compiled without the "--enable-messages"
* flag being set.
*/
MHD_OPTION_EXTERNAL_LOGGER = 13,
/**
* Number (`unsigned int`) of threads in thread pool. Enable
* thread pooling by setting this value to to something
* greater than 1. Currently, thread model must be
* #MHD_USE_INTERNAL_POLLING_THREAD if thread pooling is enabled
* (#MHD_start_daemon returns NULL for an unsupported thread
* model).
*/
MHD_OPTION_THREAD_POOL_SIZE = 14,
/**
* Additional options given in an array of `struct MHD_OptionItem`.
* The array must be terminated with an entry `{MHD_OPTION_END, 0, NULL}`.
* An example for code using #MHD_OPTION_ARRAY is:
*
* struct MHD_OptionItem ops[] = {
* { MHD_OPTION_CONNECTION_LIMIT, 100, NULL },
* { MHD_OPTION_CONNECTION_TIMEOUT, 10, NULL },
* { MHD_OPTION_END, 0, NULL }
* };
* d = MHD_start_daemon (0, 8080, NULL, NULL, dh, NULL,
* MHD_OPTION_ARRAY, ops,
* MHD_OPTION_END);
*
* For options that expect a single pointer argument, the
* second member of the `struct MHD_OptionItem` is ignored.
* For options that expect two pointer arguments, the first
* argument must be cast to `intptr_t`.
*/
MHD_OPTION_ARRAY = 15,
/**
* Specify a function that should be called for unescaping escape
* sequences in URIs and URI arguments. Note that this function
* will NOT be used by the `struct MHD_PostProcessor`. If this
* option is not specified, the default method will be used which
* decodes escape sequences of the form "%HH". This option should
* be followed by two arguments, the first one must be of the form
*
* size_t my_unescaper(void *cls,
* struct MHD_Connection *c,
* char *s)
*
* where the return value must be "strlen(s)" and "s" should be
* updated. Note that the unescape function must not lengthen "s"
* (the result must be shorter than the input and still be
* 0-terminated). "cls" will be set to the second argument
* following #MHD_OPTION_UNESCAPE_CALLBACK.
*/
MHD_OPTION_UNESCAPE_CALLBACK = 16,
/**
* Memory pointer for the random values to be used by the Digest
* Auth module. This option should be followed by two arguments.
* First an integer of type `size_t` which specifies the size
* of the buffer pointed to by the second argument in bytes.
* Note that the application must ensure that the buffer of the
* second argument remains allocated and unmodified while the
* deamon is running.
*/
MHD_OPTION_DIGEST_AUTH_RANDOM = 17,
/**
* Size of the internal array holding the map of the nonce and
* the nonce counter. This option should be followed by an `unsigend int`
* argument.
*/
MHD_OPTION_NONCE_NC_SIZE = 18,
/**
* Desired size of the stack for threads created by MHD. Followed
* by an argument of type `size_t`. Use 0 for system default.
*/
MHD_OPTION_THREAD_STACK_SIZE = 19,
/**
* Memory pointer for the certificate (ca.pem) to be used by the
* HTTPS daemon for client authentification.
* This option should be followed by a `const char *` argument.
*/
MHD_OPTION_HTTPS_MEM_TRUST = 20,
/**
* Increment to use for growing the read buffer (followed by a
* `size_t`). Must fit within #MHD_OPTION_CONNECTION_MEMORY_LIMIT.
*/
MHD_OPTION_CONNECTION_MEMORY_INCREMENT = 21,
/**
* Use a callback to determine which X.509 certificate should be
* used for a given HTTPS connection. This option should be
* followed by a argument of type `gnutls_certificate_retrieve_function2 *`.
* This option provides an
* alternative to #MHD_OPTION_HTTPS_MEM_KEY,
* #MHD_OPTION_HTTPS_MEM_CERT. You must use this version if
* multiple domains are to be hosted at the same IP address using
* TLS's Server Name Indication (SNI) extension. In this case,
* the callback is expected to select the correct certificate
* based on the SNI information provided. The callback is expected
* to access the SNI data using `gnutls_server_name_get()`.
* Using this option requires GnuTLS 3.0 or higher.
*/
MHD_OPTION_HTTPS_CERT_CALLBACK = 22,
/**
* When using #MHD_USE_TCP_FASTOPEN, this option changes the default TCP
* fastopen queue length of 50. Note that having a larger queue size can
* cause resource exhaustion attack as the TCP stack has to now allocate
* resources for the SYN packet along with its DATA. This option should be
* followed by an `unsigned int` argument.
*/
MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE = 23,
/**
* Memory pointer for the Diffie-Hellman parameters (dh.pem) to be used by the
* HTTPS daemon for key exchange.
* This option must be followed by a `const char *` argument.
*/
MHD_OPTION_HTTPS_MEM_DHPARAMS = 24,
/**
* If present and set to true, allow reusing address:port socket
* (by using SO_REUSEPORT on most platform, or platform-specific ways).
* If present and set to false, disallow reusing address:port socket
* (does nothing on most plaform, but uses SO_EXCLUSIVEADDRUSE on Windows).
* This option must be followed by a `unsigned int` argument.
*/
MHD_OPTION_LISTENING_ADDRESS_REUSE = 25,
/**
* Memory pointer for a password that decrypts the private key (key.pem)
* to be used by the HTTPS daemon. This option should be followed by a
* `const char *` argument.
* This should be used in conjunction with #MHD_OPTION_HTTPS_MEM_KEY.
* @sa ::MHD_FEATURE_HTTPS_KEY_PASSWORD
*/
MHD_OPTION_HTTPS_KEY_PASSWORD = 26,
/**
* Register a function that should be called whenever a connection is
* started or closed.
*
* This option should be followed by TWO pointers. First a pointer
* to a function of type #MHD_NotifyConnectionCallback and second a
* pointer to a closure to pass to the request completed callback.
* The second pointer maybe NULL.
*/
MHD_OPTION_NOTIFY_CONNECTION = 27,
/**
* Allow to change maximum length of the queue of pending connections on
* listen socket. If not present than default platform-specific SOMAXCONN
* value is used. This option should be followed by an `unsigned int`
* argument.
*/
MHD_OPTION_LISTEN_BACKLOG_SIZE = 28,
/**
* If set to 1 - be strict about the protocol (as opposed to as
* tolerant as possible). Specifically, at the moment, this flag
* causes MHD to reject HTTP 1.1 connections without a "Host" header.
* This is required by the standard, but of course in violation of
* the "be as liberal as possible in what you accept" norm. It is
* recommended to set this to 1 if you are testing clients against
* MHD, and 0 in production.
* This option should be followed by an `int` argument.
*/
MHD_OPTION_STRICT_FOR_CLIENT = 29
};
/**
* Entry in an #MHD_OPTION_ARRAY.
*/
struct MHD_OptionItem
{
/**
* Which option is being given. Use #MHD_OPTION_END
* to terminate the array.
*/
enum MHD_OPTION option;
/**
* Option value (for integer arguments, and for options requiring
* two pointer arguments); should be 0 for options that take no
* arguments or only a single pointer argument.
*/
intptr_t value;
/**
* Pointer option value (use NULL for options taking no arguments
* or only an integer option).
*/
void *ptr_value;
};
/**
* The `enum MHD_ValueKind` specifies the source of
* the key-value pairs in the HTTP protocol.
*/
enum MHD_ValueKind
{
/**
* Response header
* @deprecated
*/
MHD_RESPONSE_HEADER_KIND = 0,
#define MHD_RESPONSE_HEADER_KIND \
_MHD_DEPR_IN_MACRO("Value MHD_RESPONSE_HEADER_KIND is deprecated and not used") \
MHD_RESPONSE_HEADER_KIND
/**
* HTTP header (request/response).
*/
MHD_HEADER_KIND = 1,
/**
* Cookies. Note that the original HTTP header containing
* the cookie(s) will still be available and intact.
*/
MHD_COOKIE_KIND = 2,
/**
* POST data. This is available only if a content encoding
* supported by MHD is used (currently only URL encoding),
* and only if the posted content fits within the available
* memory pool. Note that in that case, the upload data
* given to the #MHD_AccessHandlerCallback will be
* empty (since it has already been processed).
*/
MHD_POSTDATA_KIND = 4,
/**
* GET (URI) arguments.
*/
MHD_GET_ARGUMENT_KIND = 8,
/**
* HTTP footer (only for HTTP 1.1 chunked encodings).
*/
MHD_FOOTER_KIND = 16
};
/**
* The `enum MHD_RequestTerminationCode` specifies reasons
* why a request has been terminated (or completed).
* @ingroup request
*/
enum MHD_RequestTerminationCode
{
/**
* We finished sending the response.
* @ingroup request
*/
MHD_REQUEST_TERMINATED_COMPLETED_OK = 0,
/**
* Error handling the connection (resources
* exhausted, other side closed connection,
* application error accepting request, etc.)
* @ingroup request
*/
MHD_REQUEST_TERMINATED_WITH_ERROR = 1,
/**
* No activity on the connection for the number
* of seconds specified using
* #MHD_OPTION_CONNECTION_TIMEOUT.
* @ingroup request
*/
MHD_REQUEST_TERMINATED_TIMEOUT_REACHED = 2,
/**
* We had to close the session since MHD was being
* shut down.
* @ingroup request
*/
MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN = 3,
/**
* We tried to read additional data, but the other side closed the
* connection. This error is similar to
* #MHD_REQUEST_TERMINATED_WITH_ERROR, but specific to the case where
* the connection died because the other side did not send expected
* data.
* @ingroup request
*/
MHD_REQUEST_TERMINATED_READ_ERROR = 4,
/**
* The client terminated the connection by closing the socket
* for writing (TCP half-closed); MHD aborted sending the
* response according to RFC 2616, section 8.1.4.
* @ingroup request
*/
MHD_REQUEST_TERMINATED_CLIENT_ABORT = 5
};
/**
* The `enum MHD_ConnectionNotificationCode` specifies types
* of connection notifications.
* @ingroup request
*/
enum MHD_ConnectionNotificationCode
{
/**
* A new connection has been started.
* @ingroup request
*/
MHD_CONNECTION_NOTIFY_STARTED = 0,
/**
* A connection is closed.
* @ingroup request
*/
MHD_CONNECTION_NOTIFY_CLOSED = 1
};
/**
* Information about a connection.
*/
union MHD_ConnectionInfo
{
/**
* Cipher algorithm used, of type "enum gnutls_cipher_algorithm".
*/
int /* enum gnutls_cipher_algorithm */ cipher_algorithm;
/**
* Protocol used, of type "enum gnutls_protocol".
*/
int /* enum gnutls_protocol */ protocol;
/**
* The suspended status of a connection.
*/
int /* MHD_YES or MHD_NO */ suspended;
/**
* Amount of second that connection could spend in idle state
* before automatically disconnected.
* Zero for no timeout (unlimited idle time).
*/
unsigned int connection_timeout;
/**
* Connect socket
*/
MHD_socket connect_fd;
/**
* Size of the client's HTTP header.
*/
size_t header_size;
/**
* GNUtls session handle, of type "gnutls_session_t".
*/
void * /* gnutls_session_t */ tls_session;
/**
* GNUtls client certificate handle, of type "gnutls_x509_crt_t".
*/
void * /* gnutls_x509_crt_t */ client_cert;
/**
* Address information for the client.
*/
struct sockaddr *client_addr;
/**
* Which daemon manages this connection (useful in case there are many
* daemons running).
*/
struct MHD_Daemon *daemon;
/**
* Socket-specific client context. Points to the same address as
* the "socket_context" of the #MHD_NotifyConnectionCallback.
*/
void *socket_context;
};
/**
* Values of this enum are used to specify what
* information about a connection is desired.
* @ingroup request
*/
enum MHD_ConnectionInfoType
{
/**
* What cipher algorithm is being used.
* Takes no extra arguments.
* @ingroup request
*/
MHD_CONNECTION_INFO_CIPHER_ALGO,
/**
*
* Takes no extra arguments.
* @ingroup request
*/
MHD_CONNECTION_INFO_PROTOCOL,
/**
* Obtain IP address of the client. Takes no extra arguments.
* Returns essentially a `struct sockaddr **` (since the API returns
* a `union MHD_ConnectionInfo *` and that union contains a `struct
* sockaddr *`).
* @ingroup request
*/
MHD_CONNECTION_INFO_CLIENT_ADDRESS,
/**
* Get the gnuTLS session handle.
* @ingroup request
*/
MHD_CONNECTION_INFO_GNUTLS_SESSION,
/**
* Get the gnuTLS client certificate handle. Dysfunctional (never
* implemented, deprecated). Use #MHD_CONNECTION_INFO_GNUTLS_SESSION
* to get the `gnutls_session_t` and then call
* gnutls_certificate_get_peers().
*/
MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT,
/**
* Get the `struct MHD_Daemon *` responsible for managing this connection.
* @ingroup request
*/
MHD_CONNECTION_INFO_DAEMON,
/**
* Request the file descriptor for the connection socket.
* No extra arguments should be passed.
* @ingroup request
*/
MHD_CONNECTION_INFO_CONNECTION_FD,
/**
* Returns the client-specific pointer to a `void *` that was (possibly)
* set during a #MHD_NotifyConnectionCallback when the socket was
* first accepted. Note that this is NOT the same as the "con_cls"
* argument of the #MHD_AccessHandlerCallback. The "con_cls" is
* fresh for each HTTP request, while the "socket_context" is fresh
* for each socket.
*/
MHD_CONNECTION_INFO_SOCKET_CONTEXT,
/**
* Check whether the connection is suspended.
* @ingroup request
*/
MHD_CONNECTION_INFO_CONNECTION_SUSPENDED,
/**
* Get connection timeout
* @ingroup request
*/
MHD_CONNECTION_INFO_CONNECTION_TIMEOUT,
/**
* Return length of the client's HTTP request header.
* @ingroup request
*/
MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE
};
/**
* Values of this enum are used to specify what
* information about a deamon is desired.
*/
enum MHD_DaemonInfoType
{
/**
* No longer supported (will return NULL).
*/
MHD_DAEMON_INFO_KEY_SIZE,
/**
* No longer supported (will return NULL).
*/
MHD_DAEMON_INFO_MAC_KEY_SIZE,
/**
* Request the file descriptor for the listening socket.
* No extra arguments should be passed.
*/
MHD_DAEMON_INFO_LISTEN_FD,
/**
* Request the file descriptor for the external epoll.
* No extra arguments should be passed.
* Waiting on epoll FD must not block longer than value
* returned by #MHD_get_timeout().
*/
MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY,
MHD_DAEMON_INFO_EPOLL_FD = MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY,
/**
* Request the number of current connections handled by the daemon.
* No extra arguments should be passed.
* Note: when using MHD in external polling mode, this type of request
* could be used only when #MHD_run()/#MHD_run_from_select is not
* working in other thread at the same time.
*/
MHD_DAEMON_INFO_CURRENT_CONNECTIONS,
/**
* Request the daemon flags.
* No extra arguments should be passed.
* Note: flags may differ from original 'flags' specified for
* daemon, especially if #MHD_USE_AUTO was set.
*/
MHD_DAEMON_INFO_FLAGS,
/**
* Request the port number of daemon's listen socket.
* No extra arguments should be passed.
* Note: if port '0' was specified for #MHD_start_daemon(), returned
* value will be real port number.
*/
MHD_DAEMON_INFO_BIND_PORT
};
/**
* Callback for serious error condition. The default action is to print
* an error message and `abort()`.
*
* @param cls user specified value
* @param file where the error occured
* @param line where the error occured
* @param reason error detail, may be NULL
* @ingroup logging
*/
typedef void
(*MHD_PanicCallback) (void *cls,
const char *file,
unsigned int line,
const char *reason);
/**
* Allow or deny a client to connect.
*
* @param cls closure
* @param addr address information from the client
* @param addrlen length of @a addr
* @return #MHD_YES if connection is allowed, #MHD_NO if not
*/
typedef int
(*MHD_AcceptPolicyCallback) (void *cls,
const struct sockaddr *addr,
socklen_t addrlen);
/**
* A client has requested the given url using the given method
* (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT,
* #MHD_HTTP_METHOD_DELETE, #MHD_HTTP_METHOD_POST, etc). The callback
* must call MHD callbacks to provide content to give back to the
* client and return an HTTP status code (i.e. #MHD_HTTP_OK,
* #MHD_HTTP_NOT_FOUND, etc.).
*
* @param cls argument given together with the function
* pointer when the handler was registered with MHD
* @param url the requested url
* @param method the HTTP method used (#MHD_HTTP_METHOD_GET,
* #MHD_HTTP_METHOD_PUT, etc.)
* @param version the HTTP version string (i.e.
* #MHD_HTTP_VERSION_1_1)
* @param upload_data the data being uploaded (excluding HEADERS,
* for a POST that fits into memory and that is encoded
* with a supported encoding, the POST data will NOT be
* given in upload_data and is instead available as
* part of #MHD_get_connection_values; very large POST
* data *will* be made available incrementally in
* @a upload_data)
* @param[in,out] upload_data_size set initially to the size of the
* @a upload_data provided; the method must update this
* value to the number of bytes NOT processed;
* @param[in,out] con_cls pointer that the callback can set to some
* address and that will be preserved by MHD for future
* calls for this request; since the access handler may
* be called many times (i.e., for a PUT/POST operation
* with plenty of upload data) this allows the application
* to easily associate some request-specific state.
* If necessary, this state can be cleaned up in the
* global #MHD_RequestCompletedCallback (which
* can be set with the #MHD_OPTION_NOTIFY_COMPLETED).
* Initially, `*con_cls` will be NULL.
* @return #MHD_YES if the connection was handled successfully,
* #MHD_NO if the socket must be closed due to a serios
* error while handling the request
*/
typedef int
(*MHD_AccessHandlerCallback) (void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method,
const char *version,
const char *upload_data,
size_t *upload_data_size,
void **con_cls);
/**
* Signature of the callback used by MHD to notify the
* application about completed requests.
*
* @param cls client-defined closure
* @param connection connection handle
* @param con_cls value as set by the last call to
* the #MHD_AccessHandlerCallback
* @param toe reason for request termination
* @see #MHD_OPTION_NOTIFY_COMPLETED
* @ingroup request
*/
typedef void
(*MHD_RequestCompletedCallback) (void *cls,
struct MHD_Connection *connection,
void **con_cls,
enum MHD_RequestTerminationCode toe);
/**
* Signature of the callback used by MHD to notify the
* application about started/stopped connections
*
* @param cls client-defined closure
* @param connection connection handle
* @param socket_context socket-specific pointer where the
* client can associate some state specific
* to the TCP connection; note that this is
* different from the "con_cls" which is per
* HTTP request. The client can initialize
* during #MHD_CONNECTION_NOTIFY_STARTED and
* cleanup during #MHD_CONNECTION_NOTIFY_CLOSED
* and access in the meantime using
* #MHD_CONNECTION_INFO_SOCKET_CONTEXT.
* @param toe reason for connection notification
* @see #MHD_OPTION_NOTIFY_CONNECTION
* @ingroup request
*/
typedef void
(*MHD_NotifyConnectionCallback) (void *cls,
struct MHD_Connection *connection,
void **socket_context,
enum MHD_ConnectionNotificationCode toe);
/**
* Iterator over key-value pairs. This iterator
* can be used to iterate over all of the cookies,
* headers, or POST-data fields of a request, and
* also to iterate over the headers that have been
* added to a response.
*
* @param cls closure
* @param kind kind of the header we are looking at
* @param key key for the value, can be an empty string
* @param value corresponding value, can be NULL
* @return #MHD_YES to continue iterating,
* #MHD_NO to abort the iteration
* @ingroup request
*/
typedef int
(*MHD_KeyValueIterator) (void *cls,
enum MHD_ValueKind kind,
const char *key,
const char *value);
/**
* Callback used by libmicrohttpd in order to obtain content. The
* callback is to copy at most @a max bytes of content into @a buf. The
* total number of bytes that has been placed into @a buf should be
* returned.
*
* Note that returning zero will cause libmicrohttpd to try again.
* Thus, returning zero should only be used in conjunction
* with MHD_suspend_connection() to avoid busy waiting.
*
* @param cls extra argument to the callback
* @param pos position in the datastream to access;
* note that if a `struct MHD_Response` object is re-used,
* it is possible for the same content reader to
* be queried multiple times for the same data;
* however, if a `struct MHD_Response` is not re-used,
* libmicrohttpd guarantees that "pos" will be
* the sum of all non-negative return values
* obtained from the content reader so far.
* @param buf where to copy the data
* @param max maximum number of bytes to copy to @a buf (size of @a buf)
* @return number of bytes written to @a buf;
* 0 is legal unless we are running in internal select mode (since
* this would cause busy-waiting); 0 in external select mode
* will cause this function to be called again once the external
* select calls MHD again;
* #MHD_CONTENT_READER_END_OF_STREAM (-1) for the regular
* end of transmission (with chunked encoding, MHD will then
* terminate the chunk and send any HTTP footers that might be
* present; without chunked encoding and given an unknown
* response size, MHD will simply close the connection; note
* that while returning #MHD_CONTENT_READER_END_OF_STREAM is not technically
* legal if a response size was specified, MHD accepts this
* and treats it just as #MHD_CONTENT_READER_END_WITH_ERROR;
* #MHD_CONTENT_READER_END_WITH_ERROR (-2) to indicate a server
* error generating the response; this will cause MHD to simply
* close the connection immediately. If a response size was
* given or if chunked encoding is in use, this will indicate
* an error to the client. Note, however, that if the client
* does not know a response size and chunked encoding is not in
* use, then clients will not be able to tell the difference between
* #MHD_CONTENT_READER_END_WITH_ERROR and #MHD_CONTENT_READER_END_OF_STREAM.
* This is not a limitation of MHD but rather of the HTTP protocol.
*/
typedef ssize_t
(*MHD_ContentReaderCallback) (void *cls,
uint64_t pos,
char *buf,
size_t max);
/**
* This method is called by libmicrohttpd if we
* are done with a content reader. It should
* be used to free resources associated with the
* content reader.
*
* @param cls closure
* @ingroup response
*/
typedef void
(*MHD_ContentReaderFreeCallback) (void *cls);
/**
* Iterator over key-value pairs where the value
* maybe made available in increments and/or may
* not be zero-terminated. Used for processing
* POST data.
*
* @param cls user-specified closure
* @param kind type of the value, always #MHD_POSTDATA_KIND when called from MHD
* @param key 0-terminated key for the value
* @param filename name of the uploaded file, NULL if not known
* @param content_type mime-type of the data, NULL if not known
* @param transfer_encoding encoding of the data, NULL if not known
* @param data pointer to @a size bytes of data at the
* specified offset
* @param off offset of data in the overall value
* @param size number of bytes in @a data available
* @return #MHD_YES to continue iterating,
* #MHD_NO to abort the iteration
*/
typedef int
(*MHD_PostDataIterator) (void *cls,
enum MHD_ValueKind kind,
const char *key,
const char *filename,
const char *content_type,
const char *transfer_encoding,
const char *data,
uint64_t off,
size_t size);
/* **************** Daemon handling functions ***************** */
/**
* Start a webserver on the given port.
*
* @param flags combination of `enum MHD_FLAG` values
* @param port port to bind to (in host byte order),
* use '0' to bind to random free port,
* ignored if MHD_OPTION_SOCK_ADDR or
* MHD_OPTION_LISTEN_SOCKET is provided
* or MHD_USE_NO_LISTEN_SOCKET is specified
* @param apc callback to call to check which clients
* will be allowed to connect; you can pass NULL
* in which case connections from any IP will be
* accepted
* @param apc_cls extra argument to apc
* @param dh handler called for all requests (repeatedly)
* @param dh_cls extra argument to @a dh
* @param ap list of options (type-value pairs,
* terminated with #MHD_OPTION_END).
* @return NULL on error, handle to daemon on success
* @ingroup event
*/
_MHD_EXTERN struct MHD_Daemon *
MHD_start_daemon_va (unsigned int flags,
uint16_t port,
MHD_AcceptPolicyCallback apc, void *apc_cls,
MHD_AccessHandlerCallback dh, void *dh_cls,
va_list ap);
/**
* Start a webserver on the given port. Variadic version of
* #MHD_start_daemon_va.
*
* @param flags combination of `enum MHD_FLAG` values
* @param port port to bind to (in host byte order),
* use '0' to bind to random free port,
* ignored if MHD_OPTION_SOCK_ADDR or
* MHD_OPTION_LISTEN_SOCKET is provided
* or MHD_USE_NO_LISTEN_SOCKET is specified
* @param apc callback to call to check which clients
* will be allowed to connect; you can pass NULL
* in which case connections from any IP will be
* accepted
* @param apc_cls extra argument to apc
* @param dh handler called for all requests (repeatedly)
* @param dh_cls extra argument to @a dh
* @return NULL on error, handle to daemon on success
* @ingroup event
*/
_MHD_EXTERN struct MHD_Daemon *
MHD_start_daemon (unsigned int flags,
uint16_t port,
MHD_AcceptPolicyCallback apc, void *apc_cls,
MHD_AccessHandlerCallback dh, void *dh_cls,
...);
/**
* Stop accepting connections from the listening socket. Allows
* clients to continue processing, but stops accepting new
* connections. Note that the caller is responsible for closing the
* returned socket; however, if MHD is run using threads (anything but
* external select mode), it must not be closed until AFTER
* #MHD_stop_daemon has been called (as it is theoretically possible
* that an existing thread is still using it).
*
* Note that some thread modes require the caller to have passed
* #MHD_USE_ITC when using this API. If this daemon is
* in one of those modes and this option was not given to
* #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET.
*
* @param daemon daemon to stop accepting new connections for
* @return old listen socket on success, #MHD_INVALID_SOCKET if
* the daemon was already not listening anymore
* @ingroup specialized
*/
_MHD_EXTERN MHD_socket
MHD_quiesce_daemon (struct MHD_Daemon *daemon);
/**
* Shutdown an HTTP daemon.
*
* @param daemon daemon to stop
* @ingroup event
*/
_MHD_EXTERN void
MHD_stop_daemon (struct MHD_Daemon *daemon);
/**
* Add another client connection to the set of connections managed by
* MHD. This API is usually not needed (since MHD will accept inbound
* connections on the server socket). Use this API in special cases,
* for example if your HTTP server is behind NAT and needs to connect
* out to the HTTP client, or if you are building a proxy.
*
* If you use this API in conjunction with a internal select or a
* thread pool, you must set the option
* #MHD_USE_ITC to ensure that the freshly added
* connection is immediately processed by MHD.
*
* The given client socket will be managed (and closed!) by MHD after
* this call and must no longer be used directly by the application
* afterwards.
*
* @param daemon daemon that manages the connection
* @param client_socket socket to manage (MHD will expect
* to receive an HTTP request from this socket next).
* @param addr IP address of the client
* @param addrlen number of bytes in @a addr
* @return #MHD_YES on success, #MHD_NO if this daemon could
* not handle the connection (i.e. `malloc()` failed, etc).
* The socket will be closed in any case; `errno` is
* set to indicate further details about the error.
* @ingroup specialized
*/
_MHD_EXTERN int
MHD_add_connection (struct MHD_Daemon *daemon,
MHD_socket client_socket,
const struct sockaddr *addr,
socklen_t addrlen);
/**
* Obtain the `select()` sets for this daemon.
* Daemon's FDs will be added to fd_sets. To get only
* daemon FDs in fd_sets, call FD_ZERO for each fd_set
* before calling this function. FD_SETSIZE is assumed
* to be platform's default.
*
* This function should only be called in when MHD is configured to
* use external select with @code{select()} or with @code{epoll()}.
* In the latter case, it will only add the single @code{epoll()} file
* descriptor used by MHD to the sets.
* It's necessary to use #MHD_get_timeout() in combination with
* this function.
*
* This function must be called only for daemon started
* without #MHD_USE_INTERNAL_POLLING_THREAD flag.
*
* @param daemon daemon to get sets from
* @param read_fd_set read set
* @param write_fd_set write set
* @param except_fd_set except set
* @param max_fd increased to largest FD added (if larger
* than existing value); can be NULL
* @return #MHD_YES on success, #MHD_NO if this
* daemon was not started with the right
* options for this call or any FD didn't
* fit fd_set.
* @ingroup event
*/
_MHD_EXTERN int
MHD_get_fdset (struct MHD_Daemon *daemon,
fd_set *read_fd_set,
fd_set *write_fd_set,
fd_set *except_fd_set,
MHD_socket *max_fd);
/**
* Obtain the `select()` sets for this daemon.
* Daemon's FDs will be added to fd_sets. To get only
* daemon FDs in fd_sets, call FD_ZERO for each fd_set
* before calling this function.
*
* Passing custom FD_SETSIZE as @a fd_setsize allow usage of
* larger/smaller than platform's default fd_sets.
*
* This function should only be called in when MHD is configured to
* use external select with @code{select()} or with @code{epoll()}.
* In the latter case, it will only add the single @code{epoll()} file
* descriptor used by MHD to the sets.
* It's necessary to use #MHD_get_timeout() in combination with
* this function.
*
* This function must be called only for daemon started
* without #MHD_USE_INTERNAL_POLLING_THREAD flag.
*
* @param daemon daemon to get sets from
* @param read_fd_set read set
* @param write_fd_set write set
* @param except_fd_set except set
* @param max_fd increased to largest FD added (if larger
* than existing value); can be NULL
* @param fd_setsize value of FD_SETSIZE
* @return #MHD_YES on success, #MHD_NO if this
* daemon was not started with the right
* options for this call or any FD didn't
* fit fd_set.
* @ingroup event
*/
_MHD_EXTERN int
MHD_get_fdset2 (struct MHD_Daemon *daemon,
fd_set *read_fd_set,
fd_set *write_fd_set,
fd_set *except_fd_set,
MHD_socket *max_fd,
unsigned int fd_setsize);
/**
* Obtain the `select()` sets for this daemon.
* Daemon's FDs will be added to fd_sets. To get only
* daemon FDs in fd_sets, call FD_ZERO for each fd_set
* before calling this function. Size of fd_set is
* determined by current value of FD_SETSIZE.
* It's necessary to use #MHD_get_timeout() in combination with
* this function.
*
* This function could be called only for daemon started
* without #MHD_USE_INTERNAL_POLLING_THREAD flag.
*
* @param daemon daemon to get sets from
* @param read_fd_set read set
* @param write_fd_set write set
* @param except_fd_set except set
* @param max_fd increased to largest FD added (if larger
* than existing value); can be NULL
* @return #MHD_YES on success, #MHD_NO if this
* daemon was not started with the right
* options for this call or any FD didn't
* fit fd_set.
* @ingroup event
*/
#define MHD_get_fdset(daemon,read_fd_set,write_fd_set,except_fd_set,max_fd) \
MHD_get_fdset2((daemon),(read_fd_set),(write_fd_set),(except_fd_set),(max_fd),FD_SETSIZE)
/**
* Obtain timeout value for polling function for this daemon.
* This function set value to amount of milliseconds for which polling
* function (`select()` or `poll()`) should at most block, not the
* timeout value set for connections.
* It is important to always use this function, even if connection
* timeout is not set, as in some cases MHD may already have more
* data to process on next turn (data pending in TLS buffers,
* connections are already ready with epoll etc.) and returned timeout
* will be zero.
*
* @param daemon daemon to query for timeout
* @param timeout set to the timeout (in milliseconds)
* @return #MHD_YES on success, #MHD_NO if timeouts are
* not used (or no connections exist that would
* necessitate the use of a timeout right now).
* @ingroup event
*/
_MHD_EXTERN int
MHD_get_timeout (struct MHD_Daemon *daemon,
MHD_UNSIGNED_LONG_LONG *timeout);
/**
* Run webserver operations (without blocking unless in client
* callbacks). This method should be called by clients in combination
* with #MHD_get_fdset if the client-controlled select method is used and
* #MHD_get_timeout().
*
* This function is a convenience method, which is useful if the
* fd_sets from #MHD_get_fdset were not directly passed to `select()`;
* with this function, MHD will internally do the appropriate `select()`
* call itself again. While it is always safe to call #MHD_run (if
* #MHD_USE_INTERNAL_POLLING_THREAD is not set), you should call
* #MHD_run_from_select if performance is important (as it saves an
* expensive call to `select()`).
*
* @param daemon daemon to run
* @return #MHD_YES on success, #MHD_NO if this
* daemon was not started with the right
* options for this call.
* @ingroup event
*/
_MHD_EXTERN int
MHD_run (struct MHD_Daemon *daemon);
/**
* Run webserver operations. This method should be called by clients
* in combination with #MHD_get_fdset and #MHD_get_timeout() if the
* client-controlled select method is used.
*
* You can use this function instead of #MHD_run if you called
* `select()` on the result from #MHD_get_fdset. File descriptors in
* the sets that are not controlled by MHD will be ignored. Calling
* this function instead of #MHD_run is more efficient as MHD will
* not have to call `select()` again to determine which operations are
* ready.
*
* This function cannot be used with daemon started with
* #MHD_USE_INTERNAL_POLLING_THREAD flag.
*
* @param daemon daemon to run select loop for
* @param read_fd_set read set
* @param write_fd_set write set
* @param except_fd_set except set
* @return #MHD_NO on serious errors, #MHD_YES on success
* @ingroup event
*/
_MHD_EXTERN int
MHD_run_from_select (struct MHD_Daemon *daemon,
const fd_set *read_fd_set,
const fd_set *write_fd_set,
const fd_set *except_fd_set);
/* **************** Connection handling functions ***************** */
/**
* Get all of the headers from the request.
*
* @param connection connection to get values from
* @param kind types of values to iterate over, can be a bitmask
* @param iterator callback to call on each header;
* maybe NULL (then just count headers)
* @param iterator_cls extra argument to @a iterator
* @return number of entries iterated over
* @ingroup request
*/
_MHD_EXTERN int
MHD_get_connection_values (struct MHD_Connection *connection,
enum MHD_ValueKind kind,
MHD_KeyValueIterator iterator,
void *iterator_cls);
/**
* This function can be used to add an entry to the HTTP headers of a
* connection (so that the #MHD_get_connection_values function will
* return them -- and the `struct MHD_PostProcessor` will also see
* them). This maybe required in certain situations (see Mantis
* #1399) where (broken) HTTP implementations fail to supply values
* needed by the post processor (or other parts of the application).
*
* This function MUST only be called from within the
* #MHD_AccessHandlerCallback (otherwise, access maybe improperly
* synchronized). Furthermore, the client must guarantee that the key
* and value arguments are 0-terminated strings that are NOT freed
* until the connection is closed. (The easiest way to do this is by
* passing only arguments to permanently allocated strings.).
*
* @param connection the connection for which a
* value should be set
* @param kind kind of the value
* @param key key for the value
* @param value the value itself
* @return #MHD_NO if the operation could not be
* performed due to insufficient memory;
* #MHD_YES on success
* @ingroup request
*/
_MHD_EXTERN int
MHD_set_connection_value (struct MHD_Connection *connection,
enum MHD_ValueKind kind,
const char *key,
const char *value);
/**
* Sets the global error handler to a different implementation. @a cb
* will only be called in the case of typically fatal, serious
* internal consistency issues. These issues should only arise in the
* case of serious memory corruption or similar problems with the
* architecture. While @a cb is allowed to return and MHD will then
* try to continue, this is never safe.
*
* The default implementation that is used if no panic function is set
* simply prints an error message and calls `abort()`. Alternative
* implementations might call `exit()` or other similar functions.
*
* @param cb new error handler
* @param cls passed to @a cb
* @ingroup logging
*/
_MHD_EXTERN void
MHD_set_panic_func (MHD_PanicCallback cb, void *cls);
/**
* Process escape sequences ('%HH') Updates val in place; the
* result should be UTF-8 encoded and cannot be larger than the input.
* The result must also still be 0-terminated.
*
* @param val value to unescape (modified in the process)
* @return length of the resulting val (`strlen(val)` may be
* shorter afterwards due to elimination of escape sequences)
*/
_MHD_EXTERN size_t
MHD_http_unescape (char *val);
/**
* Get a particular header value. If multiple
* values match the kind, return any one of them.
*
* @param connection connection to get values from
* @param kind what kind of value are we looking for
* @param key the header to look for, NULL to lookup 'trailing' value without a key
* @return NULL if no such item was found
* @ingroup request
*/
_MHD_EXTERN const char *
MHD_lookup_connection_value (struct MHD_Connection *connection,
enum MHD_ValueKind kind,
const char *key);
/**
* Queue a response to be transmitted to the client (as soon as
* possible but after #MHD_AccessHandlerCallback returns).
*
* @param connection the connection identifying the client
* @param status_code HTTP status code (i.e. #MHD_HTTP_OK)
* @param response response to transmit
* @return #MHD_NO on error (i.e. reply already sent),
* #MHD_YES on success or if message has been queued
* @ingroup response
*/
_MHD_EXTERN int
MHD_queue_response (struct MHD_Connection *connection,
unsigned int status_code,
struct MHD_Response *response);
/**
* Suspend handling of network data for a given connection. This can
* be used to dequeue a connection from MHD's event loop for a while.
*
* If you use this API in conjunction with a internal select or a
* thread pool, you must set the option #MHD_USE_ITC to
* ensure that a resumed connection is immediately processed by MHD.
*
* Suspended connections continue to count against the total number of
* connections allowed (per daemon, as well as per IP, if such limits
* are set). Suspended connections will NOT time out; timeouts will
* restart when the connection handling is resumed. While a
* connection is suspended, MHD will not detect disconnects by the
* client.
*
* The only safe time to suspend a connection is from the
* #MHD_AccessHandlerCallback.
*
* Finally, it is an API violation to call #MHD_stop_daemon while
* having suspended connections (this will at least create memory and
* socket leaks or lead to undefined behavior). You must explicitly
* resume all connections before stopping the daemon.
*
* @param connection the connection to suspend
*/
_MHD_EXTERN void
MHD_suspend_connection (struct MHD_Connection *connection);
/**
* Resume handling of network data for suspended connection. It is
* safe to resume a suspended connection at any time. Calling this
* function on a connection that was not previously suspended will
* result in undefined behavior.
*
* If you are using this function in ``external'' select mode, you must
* make sure to run #MHD_run() afterwards (before again calling
* #MHD_get_fdset(), as otherwise the change may not be reflected in
* the set returned by #MHD_get_fdset() and you may end up with a
* connection that is stuck until the next network activity.
*
* @param connection the connection to resume
*/
_MHD_EXTERN void
MHD_resume_connection (struct MHD_Connection *connection);
/* **************** Response manipulation functions ***************** */
/**
* Flags for special handling of responses.
*/
enum MHD_ResponseFlags
{
/**
* Default: no special flags.
*/
MHD_RF_NONE = 0,
/**
* Only respond in conservative HTTP 1.0-mode. In particular,
* do not (automatically) sent "Connection" headers and always
* close the connection after generating the response.
*/
MHD_RF_HTTP_VERSION_1_0_ONLY = 1
};
/**
* MHD options (for future extensions).
*/
enum MHD_ResponseOptions
{
/**
* End of the list of options.
*/
MHD_RO_END = 0
};
/**
* Set special flags and options for a response.
*
* @param response the response to modify
* @param flags to set for the response
* @param ... #MHD_RO_END terminated list of options
* @return #MHD_YES on success, #MHD_NO on error
*/
_MHD_EXTERN int
MHD_set_response_options (struct MHD_Response *response,
enum MHD_ResponseFlags flags,
...);
/**
* Create a response object. The response object can be extended with
* header information and then be used any number of times.
*
* @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown
* @param block_size preferred block size for querying crc (advisory only,
* MHD may still call @a crc using smaller chunks); this
* is essentially the buffer size used for IO, clients
* should pick a value that is appropriate for IO and
* memory performance requirements
* @param crc callback to use to obtain response data
* @param crc_cls extra argument to @a crc
* @param crfc callback to call to free @a crc_cls resources
* @return NULL on error (i.e. invalid arguments, out of memory)
* @ingroup response
*/
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_callback (uint64_t size,
size_t block_size,
MHD_ContentReaderCallback crc, void *crc_cls,
MHD_ContentReaderFreeCallback crfc);
/**
* Create a response object. The response object can be extended with
* header information and then be used any number of times.
*
* @param size size of the @a data portion of the response
* @param data the data itself
* @param must_free libmicrohttpd should free data when done
* @param must_copy libmicrohttpd must make a copy of @a data
* right away, the data maybe released anytime after
* this call returns
* @return NULL on error (i.e. invalid arguments, out of memory)
* @deprecated use #MHD_create_response_from_buffer instead
* @ingroup response
*/
_MHD_DEPR_FUNC("MHD_create_response_from_data() is deprecated, use MHD_create_response_from_buffer()") \
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_data (size_t size,
void *data,
int must_free,
int must_copy);
/**
* Specification for how MHD should treat the memory buffer
* given for the response.
* @ingroup response
*/
enum MHD_ResponseMemoryMode
{
/**
* Buffer is a persistent (static/global) buffer that won't change
* for at least the lifetime of the response, MHD should just use
* it, not free it, not copy it, just keep an alias to it.
* @ingroup response
*/
MHD_RESPMEM_PERSISTENT,
/**
* Buffer is heap-allocated with `malloc()` (or equivalent) and
* should be freed by MHD after processing the response has
* concluded (response reference counter reaches zero).
* @ingroup response
*/
MHD_RESPMEM_MUST_FREE,
/**
* Buffer is in transient memory, but not on the heap (for example,
* on the stack or non-`malloc()` allocated) and only valid during the
* call to #MHD_create_response_from_buffer. MHD must make its
* own private copy of the data for processing.
* @ingroup response
*/
MHD_RESPMEM_MUST_COPY
};
/**
* Create a response object. The response object can be extended with
* header information and then be used any number of times.
*
* @param size size of the data portion of the response
* @param buffer size bytes containing the response's data portion
* @param mode flags for buffer management
* @return NULL on error (i.e. invalid arguments, out of memory)
* @ingroup response
*/
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_buffer (size_t size,
void *buffer,
enum MHD_ResponseMemoryMode mode);
/**
* Create a response object. The response object can be extended with
* header information and then be used any number of times.
*
* @param size size of the data portion of the response
* @param fd file descriptor referring to a file on disk with the
* data; will be closed when response is destroyed;
* fd should be in 'blocking' mode
* @return NULL on error (i.e. invalid arguments, out of memory)
* @ingroup response
*/
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_fd (size_t size,
int fd);
/**
* Create a response object. The response object can be extended with
* header information and then be used any number of times.
*
* @param size size of the data portion of the response;
* sizes larger than 2 GiB may be not supported by OS or
* MHD build; see ::MHD_FEATURE_LARGE_FILE
* @param fd file descriptor referring to a file on disk with the
* data; will be closed when response is destroyed;
* fd should be in 'blocking' mode
* @return NULL on error (i.e. invalid arguments, out of memory)
* @ingroup response
*/
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_fd64 (uint64_t size,
int fd);
/**
* Create a response object. The response object can be extended with
* header information and then be used any number of times.
*
* @param size size of the data portion of the response
* @param fd file descriptor referring to a file on disk with the
* data; will be closed when response is destroyed;
* fd should be in 'blocking' mode
* @param offset offset to start reading from in the file;
* Be careful! `off_t` may have been compiled to be a
* 64-bit variable for MHD, in which case your application
* also has to be compiled using the same options! Read
* the MHD manual for more details.
* @return NULL on error (i.e. invalid arguments, out of memory)
* @ingroup response
*/
_MHD_DEPR_FUNC("Function MHD_create_response_from_fd_at_offset() is deprecated, use MHD_create_response_from_fd_at_offset64()") \
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_fd_at_offset (size_t size,
int fd,
off_t offset);
#if !defined(_MHD_NO_DEPR_IN_MACRO) || defined(_MHD_NO_DEPR_FUNC)
/* Substitute MHD_create_response_from_fd_at_offset64() instead of MHD_create_response_from_fd_at_offset()
to minimize potential problems with different off_t sizes */
#define MHD_create_response_from_fd_at_offset(size,fd,offset) \
_MHD_DEPR_IN_MACRO("Usage of MHD_create_response_from_fd_at_offset() is deprecated, use MHD_create_response_from_fd_at_offset64()") \
MHD_create_response_from_fd_at_offset64((size),(fd),(offset))
#endif /* !_MHD_NO_DEPR_IN_MACRO || _MHD_NO_DEPR_FUNC */
/**
* Create a response object. The response object can be extended with
* header information and then be used any number of times.
*
* @param size size of the data portion of the response;
* sizes larger than 2 GiB may be not supported by OS or
* MHD build; see ::MHD_FEATURE_LARGE_FILE
* @param fd file descriptor referring to a file on disk with the
* data; will be closed when response is destroyed;
* fd should be in 'blocking' mode
* @param offset offset to start reading from in the file;
* reading file beyond 2 GiB may be not supported by OS or
* MHD build; see ::MHD_FEATURE_LARGE_FILE
* @return NULL on error (i.e. invalid arguments, out of memory)
* @ingroup response
*/
_MHD_EXTERN struct MHD_Response *
MHD_create_response_from_fd_at_offset64 (uint64_t size,
int fd,
uint64_t offset);
/**
* Enumeration for actions MHD should perform on the underlying socket
* of the upgrade. This API is not finalized, and in particular
* the final set of actions is yet to be decided. This is just an
* idea for what we might want.
*/
enum MHD_UpgradeAction
{
/**
* Close the socket, the application is done with it.
*
* Takes no extra arguments.
*/
MHD_UPGRADE_ACTION_CLOSE = 0
};
/**
* Handle given to the application to manage special
* actions relating to MHD responses that "upgrade"
* the HTTP protocol (i.e. to WebSockets).
*/
struct MHD_UpgradeResponseHandle;
/**
* This connection-specific callback is provided by MHD to
* applications (unusual) during the #MHD_UpgradeHandler.
* It allows applications to perform 'special' actions on
* the underlying socket from the upgrade.
*
* @param urh the handle identifying the connection to perform
* the upgrade @a action on.
* @param action which action should be performed
* @param ... arguments to the action (depends on the action)
* @return #MHD_NO on error, #MHD_YES on success
*/
_MHD_EXTERN int
MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh,
enum MHD_UpgradeAction action,
...);
/**
* Function called after a protocol "upgrade" response was sent
* successfully and the socket should now be controlled by some
* protocol other than HTTP.
*
* Any data already received on the socket will be made available in
* @e extra_in. This can happen if the application sent extra data
* before MHD send the upgrade response. The application should
* treat data from @a extra_in as if it had read it from the socket.
*
* Note that the application must not close() @a sock directly,
* but instead use #MHD_upgrade_action() for special operations
* on @a sock.
*
* Data forwarding to "upgraded" @a sock will be started as soon
* as this function return.
*
* Except when in 'thread-per-connection' mode, implementations
* of this function should never block (as it will still be called
* from within the main event loop).
*
* @param cls closure, whatever was given to #MHD_create_response_for_upgrade().
* @param connection original HTTP connection handle,
* giving the function a last chance
* to inspect the original HTTP request
* @param con_cls last value left in `con_cls` of the `MHD_AccessHandlerCallback`
* @param extra_in if we happened to have read bytes after the
* HTTP header already (because the client sent
* more than the HTTP header of the request before
* we sent the upgrade response),
* these are the extra bytes already read from @a sock
* by MHD. The application should treat these as if
* it had read them from @a sock.
* @param extra_in_size number of bytes in @a extra_in
* @param sock socket to use for bi-directional communication
* with the client. For HTTPS, this may not be a socket
* that is directly connected to the client and thus certain
* operations (TCP-specific setsockopt(), getsockopt(), etc.)
* may not work as expected (as the socket could be from a
* socketpair() or a TCP-loopback). The application is expected
* to perform read()/recv() and write()/send() calls on the socket.
* The application may also call shutdown(), but must not call
* close() directly.
* @param urh argument for #MHD_upgrade_action()s on this @a connection.
* Applications must eventually use this callback to (indirectly)
* perform the close() action on the @a sock.
*/
typedef void
(*MHD_UpgradeHandler)(void *cls,
struct MHD_Connection *connection,
void *con_cls,
const char *extra_in,
size_t extra_in_size,
MHD_socket sock,
struct MHD_UpgradeResponseHandle *urh);
/**
* Create a response object that can be used for 101 UPGRADE
* responses, for example to implement WebSockets. After sending the
* response, control over the data stream is given to the callback (which
* can then, for example, start some bi-directional communication).
* If the response is queued for multiple connections, the callback
* will be called for each connection. The callback
* will ONLY be called after the response header was successfully passed
* to the OS; if there are communication errors before, the usual MHD
* connection error handling code will be performed.
*
* Setting the correct HTTP code (i.e. MHD_HTTP_SWITCHING_PROTOCOLS)
* and setting correct HTTP headers for the upgrade must be done
* manually (this way, it is possible to implement most existing
* WebSocket versions using this API; in fact, this API might be useful
* for any protocol switch, not just WebSockets). Note that
* draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this
* way as the header "HTTP/1.1 101 WebSocket Protocol Handshake"
* cannot be generated; instead, MHD will always produce "HTTP/1.1 101
* Switching Protocols" (if the response code 101 is used).
*
* As usual, the response object can be extended with header
* information and then be used any number of times (as long as the
* header information is not connection-specific).
*
* @param upgrade_handler function to call with the "upgraded" socket
* @param upgrade_handler_cls closure for @a upgrade_handler
* @return NULL on error (i.e. invalid arguments, out of memory)
*/
_MHD_EXTERN struct MHD_Response *
MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler,
void *upgrade_handler_cls);
/**
* Destroy a response object and associated resources. Note that
* libmicrohttpd may keep some of the resources around if the response
* is still in the queue for some clients, so the memory may not
* necessarily be freed immediatley.
*
* @param response response to destroy
* @ingroup response
*/
_MHD_EXTERN void
MHD_destroy_response (struct MHD_Response *response);
/**
* Add a header line to the response.
*
* @param response response to add a header to
* @param header the header to add
* @param content value to add
* @return #MHD_NO on error (i.e. invalid header or content format),
* or out of memory
* @ingroup response
*/
_MHD_EXTERN int
MHD_add_response_header (struct MHD_Response *response,
const char *header,
const char *content);
/**
* Add a footer line to the response.
*
* @param response response to remove a header from
* @param footer the footer to delete
* @param content value to delete
* @return #MHD_NO on error (i.e. invalid footer or content format).
* @ingroup response
*/
_MHD_EXTERN int
MHD_add_response_footer (struct MHD_Response *response,
const char *footer,
const char *content);
/**
* Delete a header (or footer) line from the response.
*
* @param response response to remove a header from
* @param header the header to delete
* @param content value to delete
* @return #MHD_NO on error (no such header known)
* @ingroup response
*/
_MHD_EXTERN int
MHD_del_response_header (struct MHD_Response *response,
const char *header,
const char *content);
/**
* Get all of the headers (and footers) added to a response.
*
* @param response response to query
* @param iterator callback to call on each header;
* maybe NULL (then just count headers)
* @param iterator_cls extra argument to @a iterator
* @return number of entries iterated over
* @ingroup response
*/
_MHD_EXTERN int
MHD_get_response_headers (struct MHD_Response *response,
MHD_KeyValueIterator iterator, void *iterator_cls);
/**
* Get a particular header (or footer) from the response.
*
* @param response response to query
* @param key which header to get
* @return NULL if header does not exist
* @ingroup response
*/
_MHD_EXTERN const char *
MHD_get_response_header (struct MHD_Response *response,
const char *key);
/* ********************** PostProcessor functions ********************** */
/**
* Create a `struct MHD_PostProcessor`.
*
* A `struct MHD_PostProcessor` can be used to (incrementally) parse
* the data portion of a POST request. Note that some buggy browsers
* fail to set the encoding type. If you want to support those, you
* may have to call #MHD_set_connection_value with the proper encoding
* type before creating a post processor (if no supported encoding
* type is set, this function will fail).
*
* @param connection the connection on which the POST is
* happening (used to determine the POST format)
* @param buffer_size maximum number of bytes to use for
* internal buffering (used only for the parsing,
* specifically the parsing of the keys). A
* tiny value (256-1024) should be sufficient.
* Do NOT use a value smaller than 256. For good
* performance, use 32 or 64k (i.e. 65536).
* @param iter iterator to be called with the parsed data,
* Must NOT be NULL.
* @param iter_cls first argument to @a iter
* @return NULL on error (out of memory, unsupported encoding),
* otherwise a PP handle
* @ingroup request
*/
_MHD_EXTERN struct MHD_PostProcessor *
MHD_create_post_processor (struct MHD_Connection *connection,
size_t buffer_size,
MHD_PostDataIterator iter, void *iter_cls);
/**
* Parse and process POST data. Call this function when POST data is
* available (usually during an #MHD_AccessHandlerCallback) with the
* "upload_data" and "upload_data_size". Whenever possible, this will
* then cause calls to the #MHD_PostDataIterator.
*
* @param pp the post processor
* @param post_data @a post_data_len bytes of POST data
* @param post_data_len length of @a post_data
* @return #MHD_YES on success, #MHD_NO on error
* (out-of-memory, iterator aborted, parse error)
* @ingroup request
*/
_MHD_EXTERN int
MHD_post_process (struct MHD_PostProcessor *pp,
const char *post_data, size_t post_data_len);
/**
* Release PostProcessor resources.
*
* @param pp the PostProcessor to destroy
* @return #MHD_YES if processing completed nicely,
* #MHD_NO if there were spurious characters / formatting
* problems; it is common to ignore the return
* value of this function
* @ingroup request
*/
_MHD_EXTERN int
MHD_destroy_post_processor (struct MHD_PostProcessor *pp);
/* ********************* Digest Authentication functions *************** */
/**
* Constant to indicate that the nonce of the provided
* authentication code was wrong.
* @ingroup authentication
*/
#define MHD_INVALID_NONCE -1
/**
* Get the username from the authorization header sent by the client
*
* @param connection The MHD connection structure
* @return NULL if no username could be found, a pointer
* to the username if found, free using #MHD_free().
* @ingroup authentication
*/
_MHD_EXTERN char *
MHD_digest_auth_get_username (struct MHD_Connection *connection);
/**
* Free the memory given by @a ptr. Calls "free(ptr)". This function
* should be used to free the username returned by
* #MHD_digest_auth_get_username().
*
* @param ptr pointer to free.
*/
_MHD_EXTERN void
MHD_free (void *ptr);
/**
* Authenticates the authorization header sent by the client
*
* @param connection The MHD connection structure
* @param realm The realm presented to the client
* @param username The username needs to be authenticated
* @param password The password used in the authentication
* @param nonce_timeout The amount of time for a nonce to be
* invalid in seconds
* @return #MHD_YES if authenticated, #MHD_NO if not,
* #MHD_INVALID_NONCE if nonce is invalid
* @ingroup authentication
*/
_MHD_EXTERN int
MHD_digest_auth_check (struct MHD_Connection *connection,
const char *realm,
const char *username,
const char *password,
unsigned int nonce_timeout);
/**
* Queues a response to request authentication from the client
*
* @param connection The MHD connection structure
* @param realm The realm presented to the client
* @param opaque string to user for opaque value
* @param response reply to send; should contain the "access denied"
* body; note that this function will set the "WWW Authenticate"
* header and that the caller should not do this
* @param signal_stale #MHD_YES if the nonce is invalid to add
* 'stale=true' to the authentication header
* @return #MHD_YES on success, #MHD_NO otherwise
* @ingroup authentication
*/
_MHD_EXTERN int
MHD_queue_auth_fail_response (struct MHD_Connection *connection,
const char *realm,
const char *opaque,
struct MHD_Response *response,
int signal_stale);
/**
* Get the username and password from the basic authorization header sent by the client
*
* @param connection The MHD connection structure
* @param[out] password a pointer for the password, free using #MHD_free().
* @return NULL if no username could be found, a pointer
* to the username if found, free using #MHD_free().
* @ingroup authentication
*/
_MHD_EXTERN char *
MHD_basic_auth_get_username_password (struct MHD_Connection *connection,
char** password);
/**
* Queues a response to request basic authentication from the client
* The given response object is expected to include the payload for
* the response; the "WWW-Authenticate" header will be added and the
* response queued with the 'UNAUTHORIZED' status code.
*
* @param connection The MHD connection structure
* @param realm the realm presented to the client
* @param response response object to modify and queue
* @return #MHD_YES on success, #MHD_NO otherwise
* @ingroup authentication
*/
_MHD_EXTERN int
MHD_queue_basic_auth_fail_response (struct MHD_Connection *connection,
const char *realm,
struct MHD_Response *response);
/* ********************** generic query functions ********************** */
/**
* Obtain information about the given connection.
*
* @param connection what connection to get information about
* @param info_type what information is desired?
* @param ... depends on @a info_type
* @return NULL if this information is not available
* (or if the @a info_type is unknown)
* @ingroup specialized
*/
_MHD_EXTERN const union MHD_ConnectionInfo *
MHD_get_connection_info (struct MHD_Connection *connection,
enum MHD_ConnectionInfoType info_type,
...);
/**
* MHD connection options. Given to #MHD_set_connection_option to
* set custom options for a particular connection.
*/
enum MHD_CONNECTION_OPTION
{
/**
* Set a custom timeout for the given connection. Specified
* as the number of seconds, given as an `unsigned int`. Use
* zero for no timeout.
* If timeout was set to zero (or unset) before, setup of new value by
* MHD_set_connection_option() will reset timeout timer.
*/
MHD_CONNECTION_OPTION_TIMEOUT
};
/**
* Set a custom option for the given connection, overriding defaults.
*
* @param connection connection to modify
* @param option option to set
* @param ... arguments to the option, depending on the option type
* @return #MHD_YES on success, #MHD_NO if setting the option failed
* @ingroup specialized
*/
_MHD_EXTERN int
MHD_set_connection_option (struct MHD_Connection *connection,
enum MHD_CONNECTION_OPTION option,
...);
/**
* Information about an MHD daemon.
*/
union MHD_DaemonInfo
{
/**
* Size of the key, no longer supported.
* @deprecated
*/
size_t key_size;
/**
* Size of the mac key, no longer supported.
* @deprecated
*/
size_t mac_key_size;
/**
* Socket, returned for #MHD_DAEMON_INFO_LISTEN_FD.
*/
MHD_socket listen_fd;
/**
* Bind port number, returned for #MHD_DAEMON_INFO_BIND_PORT.
*/
uint16_t port;
/**
* epoll FD, returned for #MHD_DAEMON_INFO_EPOLL_FD.
*/
int epoll_fd;
/**
* Number of active connections, for #MHD_DAEMON_INFO_CURRENT_CONNECTIONS.
*/
unsigned int num_connections;
/**
* Combination of #MHD_FLAG values, for #MHD_DAEMON_INFO_FLAGS.
* This value is actually a bitfield.
* Note: flags may differ from original 'flags' specified for
* daemon, especially if #MHD_USE_AUTO was set.
*/
enum MHD_FLAG flags;
};
/**
* Obtain information about the given daemon
* (not fully implemented!).
*
* @param daemon what daemon to get information about
* @param info_type what information is desired?
* @param ... depends on @a info_type
* @return NULL if this information is not available
* (or if the @a info_type is unknown)
* @ingroup specialized
*/
_MHD_EXTERN const union MHD_DaemonInfo *
MHD_get_daemon_info (struct MHD_Daemon *daemon,
enum MHD_DaemonInfoType info_type,
...);
/**
* Obtain the version of this library
*
* @return static version string, e.g. "0.9.9"
* @ingroup specialized
*/
_MHD_EXTERN const char*
MHD_get_version (void);
/**
* Types of information about MHD features,
* used by #MHD_is_feature_supported().
*/
enum MHD_FEATURE
{
/**
* Get whether messages are supported. If supported then in debug
* mode messages can be printed to stderr or to external logger.
*/
MHD_FEATURE_MESSAGES = 1,
/**
* Get whether HTTPS is supported. If supported then flag
* #MHD_USE_TLS and options #MHD_OPTION_HTTPS_MEM_KEY,
* #MHD_OPTION_HTTPS_MEM_CERT, #MHD_OPTION_HTTPS_MEM_TRUST,
* #MHD_OPTION_HTTPS_MEM_DHPARAMS, #MHD_OPTION_HTTPS_CRED_TYPE,
* #MHD_OPTION_HTTPS_PRIORITIES can be used.
*/
MHD_FEATURE_TLS = 2,
MHD_FEATURE_SSL = 2,
/**
* Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK is
* supported.
*/
MHD_FEATURE_HTTPS_CERT_CALLBACK = 3,
/**
* Get whether IPv6 is supported. If supported then flag
* #MHD_USE_IPv6 can be used.
*/
MHD_FEATURE_IPv6 = 4,
/**
* Get whether IPv6 without IPv4 is supported. If not supported
* then IPv4 is always enabled in IPv6 sockets and
* flag #MHD_USE_DUAL_STACK if always used when #MHD_USE_IPv6 is
* specified.
*/
MHD_FEATURE_IPv6_ONLY = 5,
/**
* Get whether `poll()` is supported. If supported then flag
* #MHD_USE_POLL can be used.
*/
MHD_FEATURE_POLL = 6,
/**
* Get whether `epoll()` is supported. If supported then Flags
* #MHD_USE_EPOLL and
* #MHD_USE_EPOLL_INTERNAL_THREAD can be used.
*/
MHD_FEATURE_EPOLL = 7,
/**
* Get whether shutdown on listen socket to signal other
* threads is supported. If not supported flag
* #MHD_USE_ITC is automatically forced.
*/
MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET = 8,
/**
* Get whether socketpair is used internally instead of pipe to
* signal other threads.
*/
MHD_FEATURE_SOCKETPAIR = 9,
/**
* Get whether TCP Fast Open is supported. If supported then
* flag #MHD_USE_TCP_FASTOPEN and option
* #MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE can be used.
*/
MHD_FEATURE_TCP_FASTOPEN = 10,
/**
* Get whether HTTP Basic authorization is supported. If supported
* then functions #MHD_basic_auth_get_username_password and
* #MHD_queue_basic_auth_fail_response can be used.
*/
MHD_FEATURE_BASIC_AUTH = 11,
/**
* Get whether HTTP Digest authorization is supported. If
* supported then options #MHD_OPTION_DIGEST_AUTH_RANDOM,
* #MHD_OPTION_NONCE_NC_SIZE and
* #MHD_digest_auth_check() can be used.
*/
MHD_FEATURE_DIGEST_AUTH = 12,
/**
* Get whether postprocessor is supported. If supported then
* functions #MHD_create_post_processor(), #MHD_post_process() and
* #MHD_destroy_post_processor() can
* be used.
*/
MHD_FEATURE_POSTPROCESSOR = 13,
/**
* Get whether password encrypted private key for HTTPS daemon is
* supported. If supported then option
* ::MHD_OPTION_HTTPS_KEY_PASSWORD can be used.
*/
MHD_FEATURE_HTTPS_KEY_PASSWORD = 14,
/**
* Get whether reading files beyond 2 GiB boundary is supported.
* If supported then #MHD_create_response_from_fd(),
* #MHD_create_response_from_fd64 #MHD_create_response_from_fd_at_offset()
* and #MHD_create_response_from_fd_at_offset64() can be used with sizes and
* offsets larger than 2 GiB. If not supported value of size+offset is
* limited to 2 GiB.
*/
MHD_FEATURE_LARGE_FILE = 15,
/**
* Get whether MHD set names on generated threads.
*/
MHD_FEATURE_THREAD_NAMES = 16,
MHD_THREAD_NAMES = 16,
/**
* Get whether HTTP "Upgrade" is supported.
* If supported then #MHD_ALLOW_UPGRADE, #MHD_upgrade_action() and
* #MHD_create_response_for_upgrade() can be used.
*/
MHD_FEATURE_UPGRADE = 17,
/**
* Get whether it's safe to use same FD for multiple calls of
* #MHD_create_response_from_fd() and whether it's safe to use single
* response generated by #MHD_create_response_from_fd() with multiple
* connections at same time.
* If #MHD_is_feature_supported() return #MHD_NO for this feature then
* usage of responses with same file FD in multiple parallel threads may
* results in incorrect data sent to remote client.
* It's always safe to use same file FD in multiple responses if MHD
* is run in any single thread mode.
*/
MHD_FEATURE_RESPONSES_SHARED_FD = 18,
/**
* Get whether MHD support automatic detection of bind port number.
* @sa #MHD_DAEMON_INFO_BIND_PORT
*/
MHD_FEATURE_AUTODETECT_BIND_PORT = 19,
/**
* Get whether MHD support SIGPIPE suppression.
* If SIGPIPE suppression is not supported, application must handle
* SIGPIPE signal by itself.
*/
MHD_FEATURE_AUTOSUPPRESS_SIGPIPE = 20
};
/**
* Get information about supported MHD features.
* Indicate that MHD was compiled with or without support for
* particular feature. Some features require additional support
* by kernel. Kernel support is not checked by this function.
*
* @param feature type of requested information
* @return #MHD_YES if feature is supported by MHD, #MHD_NO if
* feature is not supported or feature is unknown.
* @ingroup specialized
*/
_MHD_EXTERN int
MHD_is_feature_supported (enum MHD_FEATURE feature);
#if 0 /* keep Emacsens' auto-indent happy */
{
#endif
#ifdef __cplusplus
}
#endif
#endif
| ghaderer/libmicrohttpd | src/include/microhttpd.h | C | lgpl-2.1 | 122,270 |
// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ Includes -----------------------------------
// Local Includes -----------------------------------
#include "libmesh/libmesh_config.h"
#include "libmesh/mesh_base.h"
#include "libmesh/parallel.h" // also includes mpi.h
#include "libmesh/mesh_serializer.h"
#include "libmesh/mesh_tools.h"
#include "libmesh/mesh_communication.h"
#include "libmesh/parmetis_partitioner.h"
#include "libmesh/metis_partitioner.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/elem.h"
#include "libmesh/parmetis_helper.h"
// Include the ParMETIS header file.
#ifdef LIBMESH_HAVE_PARMETIS
namespace Parmetis {
extern "C" {
# include "libmesh/ignore_warnings.h"
# include "parmetis.h"
# include "libmesh/restore_warnings.h"
}
}
#endif
// Hash maps for interior->boundary element lookups
#include LIBMESH_INCLUDE_UNORDERED_MULTIMAP
#include LIBMESH_INCLUDE_HASH
LIBMESH_DEFINE_HASH_POINTERS
namespace libMesh
{
// Minimum elements on each processor required for us to choose
// Parmetis over Metis.
#ifdef LIBMESH_HAVE_PARMETIS
const unsigned int MIN_ELEM_PER_PROC = 4;
#endif
// ------------------------------------------------------------
// ParmetisPartitioner implementation
ParmetisPartitioner::ParmetisPartitioner()
#ifdef LIBMESH_HAVE_PARMETIS
: _pmetis(new ParmetisHelper)
#endif
{}
ParmetisPartitioner::~ParmetisPartitioner()
{
#ifdef LIBMESH_HAVE_PARMETIS
delete _pmetis;
#endif
}
void ParmetisPartitioner::_do_partition (MeshBase & mesh,
const unsigned int n_sbdmns)
{
this->_do_repartition (mesh, n_sbdmns);
}
void ParmetisPartitioner::_do_repartition (MeshBase & mesh,
const unsigned int n_sbdmns)
{
libmesh_assert_greater (n_sbdmns, 0);
// Check for an easy return
if (n_sbdmns == 1)
{
this->single_partition(mesh);
return;
}
// This function must be run on all processors at once
libmesh_parallel_only(mesh.comm());
// What to do if the Parmetis library IS NOT present
#ifndef LIBMESH_HAVE_PARMETIS
libmesh_here();
libMesh::err << "ERROR: The library has been built without" << std::endl
<< "Parmetis support. Using a Metis" << std::endl
<< "partitioner instead!" << std::endl;
MetisPartitioner mp;
mp.partition (mesh, n_sbdmns);
// What to do if the Parmetis library IS present
#else
// Revert to METIS on one processor.
if (mesh.n_processors() == 1)
{
MetisPartitioner mp;
mp.partition (mesh, n_sbdmns);
return;
}
START_LOG("repartition()", "ParmetisPartitioner");
// Initialize the data structures required by ParMETIS
this->initialize (mesh, n_sbdmns);
// Make sure all processors have enough active local elements.
// Parmetis tends to crash when it's given only a couple elements
// per partition.
{
bool all_have_enough_elements = true;
for (processor_id_type pid=0; pid<_n_active_elem_on_proc.size(); pid++)
if (_n_active_elem_on_proc[pid] < MIN_ELEM_PER_PROC)
all_have_enough_elements = false;
// Parmetis will not work unless each processor has some
// elements. Specifically, it will abort when passed a NULL
// partition array on *any* of the processors.
if (!all_have_enough_elements)
{
// FIXME: revert to METIS, although this requires a serial mesh
MeshSerializer serialize(mesh);
STOP_LOG ("repartition()", "ParmetisPartitioner");
MetisPartitioner mp;
mp.partition (mesh, n_sbdmns);
return;
}
}
// build the graph corresponding to the mesh
this->build_graph (mesh);
// Partition the graph
std::vector<Parmetis::idx_t> vsize(_pmetis->vwgt.size(), 1);
Parmetis::real_t itr = 1000000.0;
MPI_Comm mpi_comm = mesh.comm().get();
// Call the ParMETIS adaptive repartitioning method. This respects the
// original partitioning when computing the new partitioning so as to
// minimize the required data redistribution.
Parmetis::ParMETIS_V3_AdaptiveRepart(_pmetis->vtxdist.empty() ? NULL : &_pmetis->vtxdist[0],
_pmetis->xadj.empty() ? NULL : &_pmetis->xadj[0],
_pmetis->adjncy.empty() ? NULL : &_pmetis->adjncy[0],
_pmetis->vwgt.empty() ? NULL : &_pmetis->vwgt[0],
vsize.empty() ? NULL : &vsize[0],
NULL,
&_pmetis->wgtflag,
&_pmetis->numflag,
&_pmetis->ncon,
&_pmetis->nparts,
_pmetis->tpwgts.empty() ? NULL : &_pmetis->tpwgts[0],
_pmetis->ubvec.empty() ? NULL : &_pmetis->ubvec[0],
&itr,
&_pmetis->options[0],
&_pmetis->edgecut,
_pmetis->part.empty() ? NULL : &_pmetis->part[0],
&mpi_comm);
// Assign the returned processor ids
this->assign_partitioning (mesh);
STOP_LOG ("repartition()", "ParmetisPartitioner");
#endif // #ifndef LIBMESH_HAVE_PARMETIS ... else ...
}
// Only need to compile these methods if ParMETIS is present
#ifdef LIBMESH_HAVE_PARMETIS
void ParmetisPartitioner::initialize (const MeshBase & mesh,
const unsigned int n_sbdmns)
{
const dof_id_type n_active_local_elem = mesh.n_active_local_elem();
// Set parameters.
_pmetis->wgtflag = 2; // weights on vertices only
_pmetis->ncon = 1; // one weight per vertex
_pmetis->numflag = 0; // C-style 0-based numbering
_pmetis->nparts = static_cast<Parmetis::idx_t>(n_sbdmns); // number of subdomains to create
_pmetis->edgecut = 0; // the numbers of edges cut by the
// partition
// Initialize data structures for ParMETIS
_pmetis->vtxdist.resize (mesh.n_processors()+1); std::fill (_pmetis->vtxdist.begin(), _pmetis->vtxdist.end(), 0);
_pmetis->tpwgts.resize (_pmetis->nparts); std::fill (_pmetis->tpwgts.begin(), _pmetis->tpwgts.end(), 1./_pmetis->nparts);
_pmetis->ubvec.resize (_pmetis->ncon); std::fill (_pmetis->ubvec.begin(), _pmetis->ubvec.end(), 1.05);
_pmetis->part.resize (n_active_local_elem); std::fill (_pmetis->part.begin(), _pmetis->part.end(), 0);
_pmetis->options.resize (5);
_pmetis->vwgt.resize (n_active_local_elem);
// Set the options
_pmetis->options[0] = 1; // don't use default options
_pmetis->options[1] = 0; // default (level of timing)
_pmetis->options[2] = 15; // random seed (default)
_pmetis->options[3] = 2; // processor distribution and subdomain distribution are decoupled
// Find the number of active elements on each processor. We cannot use
// mesh.n_active_elem_on_proc(pid) since that only returns the number of
// elements assigned to pid which are currently stored on the calling
// processor. This will not in general be correct for parallel meshes
// when (pid!=mesh.processor_id()).
_n_active_elem_on_proc.resize(mesh.n_processors());
mesh.comm().allgather(n_active_local_elem, _n_active_elem_on_proc);
// count the total number of active elements in the mesh. Note we cannot
// use mesh.n_active_elem() in general since this only returns the number
// of active elements which are stored on the calling processor.
// We should not use n_active_elem for any allocation because that will
// be inheritly unscalable, but it can be useful for libmesh_assertions.
dof_id_type n_active_elem=0;
// Set up the vtxdist array. This will be the same on each processor.
// ***** Consult the Parmetis documentation. *****
libmesh_assert_equal_to (_pmetis->vtxdist.size(),
cast_int<std::size_t>(mesh.n_processors()+1));
libmesh_assert_equal_to (_pmetis->vtxdist[0], 0);
for (processor_id_type pid=0; pid<mesh.n_processors(); pid++)
{
_pmetis->vtxdist[pid+1] = _pmetis->vtxdist[pid] + _n_active_elem_on_proc[pid];
n_active_elem += _n_active_elem_on_proc[pid];
}
libmesh_assert_equal_to (_pmetis->vtxdist.back(), static_cast<Parmetis::idx_t>(n_active_elem));
// ParMetis expects the elements to be numbered in contiguous blocks
// by processor, i.e. [0, ne0), [ne0, ne0+ne1), ...
// Since we only partition active elements we should have no expectation
// that we currently have such a distribution. So we need to create it.
// Also, at the same time we are going to map all the active elements into a globally
// unique range [0,n_active_elem) which is *independent* of the current partitioning.
// This can be fed to ParMetis as the initial partitioning of the subdomains (decoupled
// from the partitioning of the objects themselves). This allows us to get the same
// resultant partitioning independed of the input partitioning.
MeshTools::BoundingBox bbox =
MeshTools::bounding_box(mesh);
_global_index_by_pid_map.clear();
// Maps active element ids into a contiguous range independent of partitioning.
// (only needs local scope)
vectormap<dof_id_type, dof_id_type> global_index_map;
{
std::vector<dof_id_type> global_index;
// create the mapping which is contiguous by processor
dof_id_type pid_offset=0;
for (processor_id_type pid=0; pid<mesh.n_processors(); pid++)
{
MeshBase::const_element_iterator it = mesh.active_pid_elements_begin(pid);
const MeshBase::const_element_iterator end = mesh.active_pid_elements_end(pid);
// note that we may not have all (or any!) the active elements which belong on this processor,
// but by calling this on all processors a unique range in [0,_n_active_elem_on_proc[pid])
// is constructed. Only the indices for the elements we pass in are returned in the array.
MeshCommunication().find_global_indices (mesh.comm(),
bbox, it, end,
global_index);
for (dof_id_type cnt=0; it != end; ++it)
{
const Elem * elem = *it;
libmesh_assert (!_global_index_by_pid_map.count(elem->id()));
libmesh_assert_less (cnt, global_index.size());
libmesh_assert_less (global_index[cnt], _n_active_elem_on_proc[pid]);
_global_index_by_pid_map.insert(std::make_pair(elem->id(), global_index[cnt++] + pid_offset));
}
pid_offset += _n_active_elem_on_proc[pid];
}
// create the unique mapping for all active elements independent of partitioning
{
MeshBase::const_element_iterator it = mesh.active_elements_begin();
const MeshBase::const_element_iterator end = mesh.active_elements_end();
// Calling this on all processors a unique range in [0,n_active_elem) is constructed.
// Only the indices for the elements we pass in are returned in the array.
MeshCommunication().find_global_indices (mesh.comm(),
bbox, it, end,
global_index);
for (dof_id_type cnt=0; it != end; ++it)
{
const Elem * elem = *it;
libmesh_assert (!global_index_map.count(elem->id()));
libmesh_assert_less (cnt, global_index.size());
libmesh_assert_less (global_index[cnt], n_active_elem);
global_index_map.insert(std::make_pair(elem->id(), global_index[cnt++]));
}
}
// really, shouldn't be close!
libmesh_assert_less_equal (global_index_map.size(), n_active_elem);
libmesh_assert_less_equal (_global_index_by_pid_map.size(), n_active_elem);
// At this point the two maps should be the same size. If they are not
// then the number of active elements is not the same as the sum over all
// processors of the number of active elements per processor, which means
// there must be some unpartitioned objects out there.
if (global_index_map.size() != _global_index_by_pid_map.size())
libmesh_error_msg("ERROR: ParmetisPartitioner cannot handle unpartitioned objects!");
}
// Finally, we need to initialize the vertex (partition) weights and the initial subdomain
// mapping. The subdomain mapping will be independent of the processor mapping, and is
// defined by a simple mapping of the global indices we just found.
{
std::vector<dof_id_type> subdomain_bounds(mesh.n_processors());
const dof_id_type first_local_elem = _pmetis->vtxdist[mesh.processor_id()];
for (processor_id_type pid=0; pid<mesh.n_processors(); pid++)
{
dof_id_type tgt_subdomain_size = 0;
// watch out for the case that n_subdomains < n_processors
if (pid < static_cast<unsigned int>(_pmetis->nparts))
{
tgt_subdomain_size = n_active_elem/std::min
(cast_int<Parmetis::idx_t>(mesh.n_processors()), _pmetis->nparts);
if (pid < n_active_elem%_pmetis->nparts)
tgt_subdomain_size++;
}
if (pid == 0)
subdomain_bounds[0] = tgt_subdomain_size;
else
subdomain_bounds[pid] = subdomain_bounds[pid-1] + tgt_subdomain_size;
}
libmesh_assert_equal_to (subdomain_bounds.back(), n_active_elem);
MeshBase::const_element_iterator elem_it = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
const Elem * elem = *elem_it;
libmesh_assert (_global_index_by_pid_map.count(elem->id()));
const dof_id_type global_index_by_pid =
_global_index_by_pid_map[elem->id()];
libmesh_assert_less (global_index_by_pid, n_active_elem);
const dof_id_type local_index =
global_index_by_pid - first_local_elem;
libmesh_assert_less (local_index, n_active_local_elem);
libmesh_assert_less (local_index, _pmetis->vwgt.size());
// TODO:[BSK] maybe there is a better weight?
_pmetis->vwgt[local_index] = elem->n_nodes();
// find the subdomain this element belongs in
libmesh_assert (global_index_map.count(elem->id()));
const dof_id_type global_index =
global_index_map[elem->id()];
libmesh_assert_less (global_index, subdomain_bounds.back());
const unsigned int subdomain_id =
std::distance(subdomain_bounds.begin(),
std::lower_bound(subdomain_bounds.begin(),
subdomain_bounds.end(),
global_index));
libmesh_assert_less (subdomain_id, static_cast<unsigned int>(_pmetis->nparts));
libmesh_assert_less (local_index, _pmetis->part.size());
_pmetis->part[local_index] = subdomain_id;
}
}
}
void ParmetisPartitioner::build_graph (const MeshBase & mesh)
{
// build the graph in distributed CSR format. Note that
// the edges in the graph will correspond to
// face neighbors
const dof_id_type n_active_local_elem = mesh.n_active_local_elem();
// If we have boundary elements in this mesh, we want to account for
// the connectivity between them and interior elements. We can find
// interior elements from boundary elements, but we need to build up
// a lookup map to do the reverse.
typedef LIBMESH_BEST_UNORDERED_MULTIMAP<const Elem *, const Elem *>
map_type;
map_type interior_to_boundary_map;
{
MeshBase::const_element_iterator elem_it = mesh.active_elements_begin();
const MeshBase::const_element_iterator elem_end = mesh.active_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
const Elem * elem = *elem_it;
// If we don't have an interior_parent then there's nothing to look us
// up.
if ((elem->dim() >= LIBMESH_DIM) ||
!elem->interior_parent())
continue;
// get all relevant interior elements
std::set<const Elem *> neighbor_set;
elem->find_interior_neighbors(neighbor_set);
std::set<const Elem *>::iterator n_it = neighbor_set.begin();
for (; n_it != neighbor_set.end(); ++n_it)
{
// FIXME - non-const versions of the Elem set methods
// would be nice
Elem * neighbor = const_cast<Elem *>(*n_it);
#if defined(LIBMESH_HAVE_UNORDERED_MULTIMAP) || \
defined(LIBMESH_HAVE_TR1_UNORDERED_MAP) || \
defined(LIBMESH_HAVE_HASH_MAP) || \
defined(LIBMESH_HAVE_EXT_HASH_MAP)
interior_to_boundary_map.insert
(std::make_pair(neighbor, elem));
#else
interior_to_boundary_map.insert
(interior_to_boundary_map.begin(),
std::make_pair(neighbor, elem));
#endif
}
}
}
#ifdef LIBMESH_ENABLE_AMR
std::vector<const Elem *> neighbors_offspring;
#endif
std::vector<std::vector<dof_id_type> > graph(n_active_local_elem);
dof_id_type graph_size=0;
const dof_id_type first_local_elem = _pmetis->vtxdist[mesh.processor_id()];
MeshBase::const_element_iterator elem_it = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
const Elem * elem = *elem_it;
libmesh_assert (_global_index_by_pid_map.count(elem->id()));
const dof_id_type global_index_by_pid =
_global_index_by_pid_map[elem->id()];
const dof_id_type local_index =
global_index_by_pid - first_local_elem;
libmesh_assert_less (local_index, n_active_local_elem);
std::vector<dof_id_type> & graph_row = graph[local_index];
// Loop over the element's neighbors. An element
// adjacency corresponds to a face neighbor
for (unsigned int ms=0; ms<elem->n_neighbors(); ms++)
{
const Elem * neighbor = elem->neighbor(ms);
if (neighbor != NULL)
{
// If the neighbor is active treat it
// as a connection
if (neighbor->active())
{
libmesh_assert(_global_index_by_pid_map.count(neighbor->id()));
const dof_id_type neighbor_global_index_by_pid =
_global_index_by_pid_map[neighbor->id()];
graph_row.push_back(neighbor_global_index_by_pid);
graph_size++;
}
#ifdef LIBMESH_ENABLE_AMR
// Otherwise we need to find all of the
// neighbor's children that are connected to
// us and add them
else
{
// The side of the neighbor to which
// we are connected
const unsigned int ns =
neighbor->which_neighbor_am_i (elem);
libmesh_assert_less (ns, neighbor->n_neighbors());
// Get all the active children (& grandchildren, etc...)
// of the neighbor
// FIXME - this is the wrong thing, since we
// should be getting the active family tree on
// our side only. But adding too many graph
// links may cause hanging nodes to tend to be
// on partition interiors, which would reduce
// communication overhead for constraint
// equations, so we'll leave it.
neighbor->active_family_tree (neighbors_offspring);
// Get all the neighbor's children that
// live on that side and are thus connected
// to us
for (unsigned int nc=0; nc<neighbors_offspring.size(); nc++)
{
const Elem * child =
neighbors_offspring[nc];
// This does not assume a level-1 mesh.
// Note that since children have sides numbered
// coincident with the parent then this is a sufficient test.
if (child->neighbor(ns) == elem)
{
libmesh_assert (child->active());
libmesh_assert (_global_index_by_pid_map.count(child->id()));
const dof_id_type child_global_index_by_pid =
_global_index_by_pid_map[child->id()];
graph_row.push_back(child_global_index_by_pid);
graph_size++;
}
}
}
#endif /* ifdef LIBMESH_ENABLE_AMR */
}
}
if ((elem->dim() < LIBMESH_DIM) &&
elem->interior_parent())
{
// get all relevant interior elements
std::set<const Elem *> neighbor_set;
elem->find_interior_neighbors(neighbor_set);
std::set<const Elem *>::iterator n_it = neighbor_set.begin();
for (; n_it != neighbor_set.end(); ++n_it)
{
// FIXME - non-const versions of the Elem set methods
// would be nice
Elem * neighbor = const_cast<Elem *>(*n_it);
const dof_id_type neighbor_global_index_by_pid =
_global_index_by_pid_map[neighbor->id()];
graph_row.push_back(neighbor_global_index_by_pid);
graph_size++;
}
}
// Check for any boundary neighbors
typedef map_type::iterator map_it_type;
std::pair<map_it_type, map_it_type>
bounds = interior_to_boundary_map.equal_range(elem);
for (map_it_type it = bounds.first; it != bounds.second; ++it)
{
const Elem * neighbor = it->second;
const dof_id_type neighbor_global_index_by_pid =
_global_index_by_pid_map[neighbor->id()];
graph_row.push_back(neighbor_global_index_by_pid);
graph_size++;
}
}
// Reserve space in the adjacency array
_pmetis->xadj.clear();
_pmetis->xadj.reserve (n_active_local_elem + 1);
_pmetis->adjncy.clear();
_pmetis->adjncy.reserve (graph_size);
for (std::size_t r=0; r<graph.size(); r++)
{
_pmetis->xadj.push_back(_pmetis->adjncy.size());
std::vector<dof_id_type> graph_row; // build this emtpy
graph_row.swap(graph[r]); // this will deallocate at the end of scope
_pmetis->adjncy.insert(_pmetis->adjncy.end(),
graph_row.begin(),
graph_row.end());
}
// The end of the adjacency array for the last elem
_pmetis->xadj.push_back(_pmetis->adjncy.size());
libmesh_assert_equal_to (_pmetis->xadj.size(), n_active_local_elem+1);
libmesh_assert_equal_to (_pmetis->adjncy.size(), graph_size);
}
void ParmetisPartitioner::assign_partitioning (MeshBase & mesh)
{
// This function must be run on all processors at once
libmesh_parallel_only(mesh.comm());
const dof_id_type
first_local_elem = _pmetis->vtxdist[mesh.processor_id()];
std::vector<std::vector<dof_id_type> >
requested_ids(mesh.n_processors()),
requests_to_fill(mesh.n_processors());
MeshBase::element_iterator elem_it = mesh.active_elements_begin();
MeshBase::element_iterator elem_end = mesh.active_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
Elem * elem = *elem_it;
// we need to get the index from the owning processor
// (note we cannot assign it now -- we are iterating
// over elements again and this will be bad!)
libmesh_assert_less (elem->processor_id(), requested_ids.size());
requested_ids[elem->processor_id()].push_back(elem->id());
}
// Trade with all processors (including self) to get their indices
for (processor_id_type pid=0; pid<mesh.n_processors(); pid++)
{
// Trade my requests with processor procup and procdown
const processor_id_type procup = (mesh.processor_id() + pid) % mesh.n_processors();
const processor_id_type procdown = (mesh.n_processors() +
mesh.processor_id() - pid) % mesh.n_processors();
mesh.comm().send_receive (procup, requested_ids[procup],
procdown, requests_to_fill[procdown]);
// we can overwrite these requested ids in-place.
for (std::size_t i=0; i<requests_to_fill[procdown].size(); i++)
{
const dof_id_type requested_elem_index =
requests_to_fill[procdown][i];
libmesh_assert(_global_index_by_pid_map.count(requested_elem_index));
const dof_id_type global_index_by_pid =
_global_index_by_pid_map[requested_elem_index];
const dof_id_type local_index =
global_index_by_pid - first_local_elem;
libmesh_assert_less (local_index, _pmetis->part.size());
libmesh_assert_less (local_index, mesh.n_active_local_elem());
const unsigned int elem_procid =
static_cast<unsigned int>(_pmetis->part[local_index]);
libmesh_assert_less (elem_procid, static_cast<unsigned int>(_pmetis->nparts));
requests_to_fill[procdown][i] = elem_procid;
}
// Trade back
mesh.comm().send_receive (procdown, requests_to_fill[procdown],
procup, requested_ids[procup]);
}
// and finally assign the partitioning.
// note we are iterating in exactly the same order
// used to build up the request, so we can expect the
// required entries to be in the proper sequence.
elem_it = mesh.active_elements_begin();
elem_end = mesh.active_elements_end();
for (std::vector<unsigned int> counters(mesh.n_processors(), 0);
elem_it != elem_end; ++elem_it)
{
Elem * elem = *elem_it;
const processor_id_type current_pid = elem->processor_id();
libmesh_assert_less (counters[current_pid], requested_ids[current_pid].size());
const processor_id_type elem_procid =
requested_ids[current_pid][counters[current_pid]++];
libmesh_assert_less (elem_procid, static_cast<unsigned int>(_pmetis->nparts));
elem->processor_id() = elem_procid;
}
}
#endif // #ifdef LIBMESH_HAVE_PARMETIS
} // namespace libMesh
| dknez/libmesh | src/partitioning/parmetis_partitioner.C | C++ | lgpl-2.1 | 27,749 |
package horse.ponecraft.pegasus;
import horse.ponecraft.pegasus.items.ItemGemShard;
import horse.ponecraft.pegasus.tinkers.PegasusToolEvents;
import horse.ponecraft.pegasus.tinkers.PegasusToolMod;
import horse.ponecraft.pegasus.tinkers.TConstructIMC;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import tconstruct.library.TConstructRegistry;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
@Mod(modid = Pegasus.MODID, version = Pegasus.VERSION, name = "Ponecraft Pegasus", dependencies = "after:ProjRed|Core;after:TConstruct")
public class Pegasus
{
public static final String MODID = "horse.ponecraft.pegasus";
public static final String VERSION = "1.0";
public static final String FlightPermissionName = "horse.ponecraft.pegasus.flight";
public static final ItemGemShard rubyShard = new ItemGemShard("rubyShard");
public static final ItemGemShard sapphireShard = new ItemGemShard("sapphireShard");
public static final ItemGemShard peridotShard = new ItemGemShard("peridotShard");
public static final int RubyMaterial = 1001;
public static final int SapphireMaterial = 1002;
public static final int PeridotMaterial = 1003;
// public static final Potion pacify = new PotionPacify();
public static List<ItemStack> allowableFlightArmor;
private String[] allowedFlightArmorNames = new String[]
{
"betterstorage:backpack",
"betterstorage:cardboardBoots",
"betterstorage:cardboardChestplate",
"betterstorage:cardboardHelmet",
"betterstorage:cardboardLeggings",
"betterstorage:drinkingHelmet",
"betterstorage:enderBackpack",
"betterstorage:thaumcraftBackpack",
"BiblioCraft:item.BiblioGlasses",
"BiblioCraft:item.BiblioGlasses#1",
"BiblioCraft:item.BiblioGlasses#2",
"ExtraUtilities:sonar_goggles",
"minecraft:chainmail_boots",
"minecraft:chainmail_chestplate",
"minecraft:chainmail_helmet",
"minecraft:chainmail_leggings",
"minecraft:leather_boots",
"minecraft:leather_chestplate",
"minecraft:leather_helmet",
"minecraft:leather_leggings",
"Natura:natura.armor.impboots",
"Natura:natura.armor.imphelmet",
"Natura:natura.armor.impjerkin",
"Natura:natura.armor.impleggings",
"Railcraft:armor.goggles",
"Railcraft:armor.overalls",
"witchery:hunterboots",
"witchery:hunterbootssilvered",
"witchery:huntercoat",
"witchery:huntercoatsilvered",
"witchery:hunterhat",
"witchery:hunterhatsilvered",
"witchery:hunterlegs",
"witchery:hunterlegssilvered",
};
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
Configuration config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
allowedFlightArmorNames = config.getStringList("allowedFlightArmorNames", "flight", allowedFlightArmorNames, "A list of item names of armor that can be worn without preventing flight.");
config.save();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
MinecraftForge.EVENT_BUS.register(new PegasusEvents());
MinecraftForge.EVENT_BUS.register(new PegasusToolEvents());
TConstructRegistry.activeModifiers.add(new PegasusToolMod());
TConstructIMC.addMaterial(RubyMaterial, "Ruby", 2, 400, 800, 1, 0.8f, 0, 0, 0, EnumChatFormatting.RED, 180, 72, 72, 1, 1, 1, 1);
TConstructIMC.addMaterial(SapphireMaterial, "Sapphire", 2, 400, 800, 1, 0.8f, 0, 0, 0, EnumChatFormatting.BLUE, 72, 112, 208, 1, 1, 1, 1);
TConstructIMC.addMaterial(PeridotMaterial, "Peridot", 2, 400, 800, 1, 0.8f, 0, 0, 0, EnumChatFormatting.GREEN, 88, 164, 44, 1, 1, 1, 1);
ItemStack rubyGem = new ItemStack((Item)Item.itemRegistry.getObject("ProjRed|Core:projectred.core.part"), 1, 37);
ItemStack sapphireGem = new ItemStack((Item)Item.itemRegistry.getObject("ProjRed|Core:projectred.core.part"), 1, 38);
ItemStack peridotGem = new ItemStack((Item)Item.itemRegistry.getObject("ProjRed|Core:projectred.core.part"), 1, 39);
GameRegistry.registerItem(rubyShard, "rubyShard");
GameRegistry.registerItem(sapphireShard, "sapphireShard");
GameRegistry.registerItem(peridotShard, "peridotShard");
TConstructIMC.addMaterialItem(1001, 1, rubyGem);
TConstructIMC.addMaterialItem(1002, 1, sapphireGem);
TConstructIMC.addMaterialItem(1003, 1, peridotGem);
TConstructIMC.addPartBuilderMaterial(1001, rubyGem, new ItemStack(rubyShard), 2);
TConstructIMC.addPartBuilderMaterial(1002, sapphireGem, new ItemStack(sapphireShard), 2);
TConstructIMC.addPartBuilderMaterial(1003, peridotGem, new ItemStack(peridotShard), 2);
allowableFlightArmor = new ArrayList<ItemStack>();
for (String name : allowedFlightArmorNames)
{
int meta = 0;
if (name.contains("#"))
{
meta = Integer.parseInt(name.substring(name.indexOf("#") + 1));
name = name.substring(0, name.indexOf("#"));
}
Item armorItem = (Item)Item.itemRegistry.getObject(name);
if (armorItem != null)
{
allowableFlightArmor.add(new ItemStack(armorItem, 1, meta));
}
}
}
} | EmptyAudio/horse.ponecraft | src/main/java/horse/ponecraft/pegasus/Pegasus.java | Java | lgpl-2.1 | 5,795 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html401/loose.dtd">
<html>
<!-- Created by texi2html 1.76 -->
<!--
Written by: Lionel Cons <Lionel.Cons@cern.ch> (original author)
Karl Berry <karl@freefriends.org>
Olaf Bachmann <obachman@mathematik.uni-kl.de>
and many others.
Maintained by: Many creative people <dev@texi2html.cvshome.org>
Send bugs and suggestions to <users@texi2html.cvshome.org>
-->
<head>
<title>Crystal Space 2.1.0: 4.16.2.1 Getting the Plugin and Intro</title>
<meta name="description" content="Crystal Space 2.1.0: 4.16.2.1 Getting the Plugin and Intro">
<meta name="keywords" content="Crystal Space 2.1.0: 4.16.2.1 Getting the Plugin and Intro">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2html 1.76">
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
pre.display {font-family: serif}
pre.format {font-family: serif}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: serif; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: serif; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.sansserif {font-family:sans-serif; font-weight:normal;}
ul.toc {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="XMLServices-Intro"></a>
<a name="0"></a>
<table cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="XML-Syntax-Services.html#0" title="Previous section in reading order"> < </a>]</td>
<td valign="middle" align="left">[<a href="XMLServices-Mixmode.html#0" title="Next section in reading order"> > </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="Using-Crystal-Space.html#0" title="Beginning of this chapter or previous chapter"> << </a>]</td>
<td valign="middle" align="left">[<a href="XML-Syntax-Services.html#0" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[<a href="Working-with-Engine-Content.html#0" title="Next chapter"> >> </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="index.html#SEC_Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="cs_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[<a href="cs_Index.html#0" title="Index">Index</a>]</td>
<td valign="middle" align="left">[<a href="cs_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<hr size="1">
<h4 class="subsubsection"> 4.16.2.1 Getting the Plugin and Intro </h4>
<a name="1"></a>
<h4 class="subsubheading"> Getting the Plugin </h4>
<p>This plugin has <samp>‘crystalspace.syntax.loader.service.text’</samp> as plugin id.
Usually this plugin is already loaded if you also use the main loader plugin.
In that case you can get this plugin from the object registry by doing:
</p>
<table><tr><td> </td><td><pre class="example">csRef<iSyntaxService> services = csQueryRegistry<iSyntaxService> (object_reg);
</pre></td></tr></table>
<p>If you need to load the plugin yourselves then the following code would
work. This code will first check if the plugin is already loaded. If not
it will load it:
</p>
<table><tr><td> </td><td><pre class="example">csRef<iSyntaxService> services = csLoadPluginCheck<iSyntaxService> (
object_reg, "crystalspace.syntax.loader.service.text");
</pre></td></tr></table>
<a name="2"></a>
<h4 class="subsubheading"> Introduction </h4>
<p>This plugin implements the <code>iSyntaxService</code> interface. The definition
of this interface can be found in <tt>‘imap/services.h’</tt>. There are
basically three kinds of functions in this interface:
</p>
<ul>
<li> <samp>‘Reporting Helpers’</samp>
These are functions that make it easier for a plugin writer to report
an error to the user.
</li><li> <samp>‘Parsing Helpers’</samp>
These functions are the main part of this plugin. They all start with
<samp>‘Parse’</samp> and help with parsing a small part of the <small>XML</small> format.
They all expect a node (<code>iDocumentNode</code>) to be parsed as the input
and they return the parsed result or an error.
</li><li> <samp>‘Writing Helpers’</samp>
These functions create <small>XML</small> (in the given <code>iDocumentNode</code> parameter)
for some basic Crystal Space object. They are useful if you ware making
a plugin that saves <small>XML</small>.
</li></ul>
<p>In this document we explain a few of the more important parsing functions
present in this plugin.
</p>
<hr size="1">
<p>
<font size="-1">
This document was generated using <a href="http://texi2html.cvshome.org/"><em>texi2html 1.76</em></a>.
</font>
<br>
</p>
</body>
</html>
| baoboa/Crystal-Space | docs/html/manual/XMLServices-Intro.html | HTML | lgpl-2.1 | 5,283 |
<?php
namespace wcf\system\devtools;
use wcf\system\SingletonFactory;
use wcf\util\FileUtil;
use wcf\util\JSON;
/**
* Enables the rapid deployment of new installations using a central configuration file
* in the document root. Requires the developer mode to work.
*
* @author Alexander Ebert
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Devtools\Package
* @since 3.1
*/
class DevtoolsSetup extends SingletonFactory {
/**
* configuration file in the server's document root
* @var string
*/
const CONFIGURATION_FILE = 'wsc-dev-config-52.json';
/**
* configuration data
* @var array
*/
protected $configuration = [];
/**
* @inheritDoc
*/
protected function init() {
if (empty($_SERVER['DOCUMENT_ROOT'])) return;
$docRoot = FileUtil::addTrailingSlash(FileUtil::unifyDirSeparator($_SERVER['DOCUMENT_ROOT']));
if (!file_exists($docRoot . self::CONFIGURATION_FILE)) return;
$contents = file_get_contents($docRoot . self::CONFIGURATION_FILE);
// allow the exception to go rampage
$this->configuration = JSON::decode($contents);
}
/**
* Returns the database configuration.
*
* @return array|null
*/
public function getDatabaseConfig() {
if (!isset($this->configuration['setup']) || !isset($this->configuration['setup']['database'])) return null;
// dirname return a single backslash on Windows if there are no parent directories
$dir = dirname($_SERVER['SCRIPT_NAME']);
$dir = ($dir === '\\') ? '/' : FileUtil::addTrailingSlash($dir);
if ($dir === '/') throw new \RuntimeException("Refusing to install in the document root.");
$dir = FileUtil::removeLeadingSlash(FileUtil::removeTrailingSlash($dir));
$dbName = implode('_', explode('/', $dir));
$dbConfig = $this->configuration['setup']['database'];
return [
'auto' => $dbConfig['auto'],
'host' => $dbConfig['host'],
'password' => $dbConfig['password'],
'username' => $dbConfig['username'],
'dbName' => $dbName,
'dbNumber' => $dbConfig['dbNumber']
];
}
/**
* Returns true if the suggested default paths for the Core and, if exists,
* the bundled app should be used.
*
* @return boolean
*/
public function useDefaultInstallPath() {
return (isset($this->configuration['setup']) && isset($this->configuration['setup']['useDefaultInstallPath']) && $this->configuration['setup']['useDefaultInstallPath'] === true);
}
/**
* Returns true if a static cookie prefix should be used, instead of the randomized
* value used for non-dev-mode installations.
*
* @return boolean
*/
public function forceStaticCookiePrefix() {
return (isset($this->configuration['setup']) && isset($this->configuration['setup']['forceStaticCookiePrefix']) && $this->configuration['setup']['forceStaticCookiePrefix'] === true);
}
/**
* List of option values that will be set after the setup has completed.
*
* @return string[]
*/
public function getOptionOverrides() {
if (!isset($this->configuration['configuration']) || empty($this->configuration['configuration']['option'])) return [];
if (isset($this->configuration['configuration']['option']['cookie_prefix'])) {
throw new \DomainException("The 'cookie_prefix' option cannot be set during the setup, consider using the 'forceStaticCookiePrefix' setting instead.");
}
return $this->configuration['configuration']['option'];
}
/**
* Returns a list of users that should be automatically created during setup.
*
* @return array|\Generator
*/
public function getUsers() {
if (empty($this->configuration['user'])) return;
foreach ($this->configuration['user'] as $user) {
if ($user['username'] === 'root') throw new \LogicException("The 'root' user is automatically created.");
yield [
'username' => $user['username'],
'password' => $user['password'],
'email' => $user['email']
];
}
}
/**
* Returns the base path for projects that should be automatically imported.
*
* @return string
*/
public function getDevtoolsImportPath() {
return (isset($this->configuration['configuration']['devtools']) && !empty($this->configuration['configuration']['devtools']['importFromPath'])) ? $this->configuration['configuration']['devtools']['importFromPath'] : '';
}
/**
* Returns the raw configuration data.
*
* @return array
*/
public function getRawConfiguration() {
return $this->configuration;
}
}
| MenesesEvandro/WCF | wcfsetup/install/files/lib/system/devtools/DevtoolsSetup.class.php | PHP | lgpl-2.1 | 4,565 |
/**
* @file element_compare.c
* @brief element.h implementation
* @author Aleix Conchillo Flaque <aconchillo@gmail.com>
* @date Thu Aug 27, 2009 01:38
*
* @if copyright
*
* Copyright (C) 2009 Aleix Conchillo Flaque
*
* SCEW 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.
*
* SCEW 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.
*
* @endif
*/
#include "xelement.h"
#include "attribute.h"
#include "str.h"
#include <assert.h>
/* Private */
static scew_bool compare_element_ (scew_element const *a,
scew_element const *b);
static scew_bool compare_children_ (scew_element const *a,
scew_element const *b,
scew_element_cmp_hook hook);
static scew_bool compare_attributes_ (scew_element const *a,
scew_element const *b);
/* Public */
scew_bool
scew_element_compare (scew_element const *a,
scew_element const *b,
scew_element_cmp_hook hook)
{
scew_element_cmp_hook cmp_hook = NULL;
assert (a != NULL);
assert (b != NULL);
cmp_hook = (NULL == hook) ? compare_element_ : hook;
return (cmp_hook (a, b) && compare_children_ (a, b, cmp_hook));
}
/* Private */
scew_bool
compare_element_ (scew_element const *a, scew_element const *b)
{
scew_bool equal = SCEW_FALSE;
assert (a != NULL);
assert (b != NULL);
equal = (scew_strcmp (a->name, b->name) == 0)
&& (scew_strcmp (a->contents, b->contents) == 0)
&& compare_attributes_ (a, b);
return equal;
}
scew_bool
compare_attributes_ (scew_element const *a, scew_element const *b)
{
scew_bool equal = SCEW_TRUE;
scew_list *list_a = NULL;
scew_list *list_b = NULL;
assert (a != NULL);
assert (b != NULL);
equal = (a->n_attributes == b->n_attributes);
list_a = a->attributes;
list_b = b->attributes;
while (equal && (list_a != NULL) && (list_b != NULL))
{
scew_attribute *attr_a = scew_list_data (list_a);
scew_attribute *attr_b = scew_list_data (list_b);
equal = scew_attribute_compare (attr_a, attr_b);
list_a = scew_list_next (list_a);
list_b = scew_list_next (list_b);
}
return equal;
}
scew_bool
compare_children_ (scew_element const *a,
scew_element const *b,
scew_element_cmp_hook hook)
{
scew_bool equal = SCEW_TRUE;
scew_list *list_a = NULL;
scew_list *list_b = NULL;
assert (a != NULL);
assert (b != NULL);
equal = (a->n_children == b->n_children);
list_a = a->children;
list_b = b->children;
while (equal && (list_a != NULL) && (list_b != NULL))
{
scew_element *child_a = scew_list_data (list_a);
scew_element *child_b = scew_list_data (list_b);
equal = scew_element_compare (child_a, child_b, hook);
list_a = scew_list_next (list_a);
list_b = scew_list_next (list_b);
}
return equal;
}
| aconchillo/scew | scew/element_compare.c | C | lgpl-2.1 | 3,575 |
/*
* This file is part of ofono-qt
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Alexander Kanavin <alex.kanavin@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* 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 St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#ifndef OFONOMODEMMANAGER_H
#define OFONOMODEMMANAGER_H
#include <QtCore/QObject>
#include <QVariant>
#include <QDBusObjectPath>
#include <QStringList>
#include "libofono-qt_global.h"
//! Provides access to the list of available modems and changes in that list.
class OFONO_QT_EXPORT OfonoModemManager : public QObject {
Q_OBJECT
public:
OfonoModemManager(QObject *parent=0);
~OfonoModemManager();
//! Returns a list of d-bus object paths that represent available modems
Q_INVOKABLE QStringList modems() const;
signals:
//! Issued when a modem has been added
void modemAdded(const QString &modemPath);
//! Issued when a modem has been removed
void modemRemoved(const QString &modemPath);
private slots:
void onModemAdded(const QDBusObjectPath &path, const QVariantMap &map);
void onModemRemoved(const QDBusObjectPath &path);
private:
QStringList m_modems;
};
#endif
| nemomobile-graveyard/libofono-qt | lib/ofonomodemmanager.h | C | lgpl-2.1 | 1,776 |
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain Version 0.8.0
// The SmartSoft Toolchain has been developed by:
//
// ZAFH Servicerobotic Ulm
// Christian Schlegel (schlegel@hs-ulm.de)
// University of Applied Sciences
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// smart-robotics.sourceforge.net
//
// This file is generated once. Modify this file to your needs.
// If you want the toolchain to re-generate this file, please
// delete it before running the code generator.
//--------------------------------------------------------------------------
//------------------------------------------------------------------------
//
// Copyright (C) 2010 Manuel Wopfner
//
// wopfner@hs-ulm.de
//
// Christian Schlegel (schlegel@hs-ulm.de)
// University of Applied Sciences
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//--------------------------------------------------------------------------
#ifndef _BASESTATETASK_HH
#define _BASESTATETASK_HH
#include "gen/BaseStateTaskCore.hh"
#include <CommBasicObjects/commBaseState.hh>
class BaseStateTask: public BaseStateTaskCore
{
public:
CHS::SmartMutex base_mutex;
CommBasicObjects::CommBaseState base_state;
BaseStateTask();
int svc();
};
#endif
| carlos22/SmartSoftCorba | src/components/SmartPTUServer/src/BaseStateTask.hh | C++ | lgpl-2.1 | 2,133 |
#############################################################################
##
## Copyright (C) 2017 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of the test suite of PySide2.
##
## $QT_BEGIN_LICENSE:GPL-EXCEPT$
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and The Qt Company. For licensing terms
## and conditions see https://www.qt.io/terms-conditions. For further
## information use the contact form at https://www.qt.io/contact-us.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 3 as published by the Free Software
## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
## included in the packaging of this file. Please review the following
## information to ensure the GNU General Public License requirements will
## be met: https://www.gnu.org/licenses/gpl-3.0.html.
##
## $QT_END_LICENSE$
##
#############################################################################
'''Test cases for QtMultimediaWidgets'''
import unittest
from helper import UsesQApplication
from PySide2.QtMultimediaWidgets import QGraphicsVideoItem, QVideoWidget
from PySide2.QtWidgets import QGraphicsScene, QGraphicsView, QVBoxLayout, QWidget
from PySide2.QtCore import QTimer
class MyWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
layout = QVBoxLayout(self)
layout.addWidget(QVideoWidget())
graphicsScene = QGraphicsScene()
graphicsView = QGraphicsView(graphicsScene)
graphicsScene.addItem(QGraphicsVideoItem())
layout.addWidget(graphicsView)
class QMultimediaWidgetsTest(UsesQApplication):
def testMultimediaWidgets(self):
w = MyWidget()
w.show()
timer = QTimer.singleShot(100, self.app.quit)
self.app.exec_()
if __name__ == '__main__':
unittest.main()
| qtproject/pyside-pyside | tests/QtMultimediaWidgets/qmultimediawidgets.py | Python | lgpl-2.1 | 2,146 |
#!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# This file is part of libgpiod.
#
# Copyright (C) 2017-2018 Bartosz Golaszewski <bartekgola@gmail.com>
#
'''Simplified reimplementation of the gpioset tool in Python.'''
import gpiod
import sys
if __name__ == '__main__':
if len(sys.argv) < 3:
raise TypeError('usage: gpioset.py <gpiochip> <offset1>=<value1> ...')
with gpiod.Chip(sys.argv[1]) as chip:
offsets = []
values = []
for arg in sys.argv[2:]:
arg = arg.split('=')
offsets.append(int(arg[0]))
values.append(int(arg[1]))
lines = chip.get_lines(offsets)
lines.request(consumer=sys.argv[0], type=gpiod.LINE_REQ_DIR_OUT)
lines.set_values(values)
input()
| brgl/libgpiod | bindings/python/examples/gpioset.py | Python | lgpl-2.1 | 793 |
/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
copyright : (C) 2006 by Aaron VonderHaar
email : avh4@users.sourceforge.net
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* 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 *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include "../../../toolkit/tdebug.h"
#include "generalencapsulatedobjectframe.h"
using namespace TagLib;
using namespace ID3v2;
class GeneralEncapsulatedObjectFrame::GeneralEncapsulatedObjectFramePrivate
{
public:
GeneralEncapsulatedObjectFramePrivate() : textEncoding(String::Latin1) {}
String::Type textEncoding;
String mimeType;
String fileName;
String description;
ByteVector data;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
GeneralEncapsulatedObjectFrame::GeneralEncapsulatedObjectFrame() : Frame("GEOB")
{
d = new GeneralEncapsulatedObjectFramePrivate;
}
GeneralEncapsulatedObjectFrame::GeneralEncapsulatedObjectFrame(const ByteVector &data) : Frame(data)
{
d = new GeneralEncapsulatedObjectFramePrivate;
setData(data);
}
GeneralEncapsulatedObjectFrame::~GeneralEncapsulatedObjectFrame()
{
delete d;
}
String GeneralEncapsulatedObjectFrame::toString() const
{
String text = "[" + d->mimeType + "]";
if(!d->fileName.isEmpty())
text += " " + d->fileName;
if(!d->description.isEmpty())
text += " \"" + d->description + "\"";
return text;
}
String::Type GeneralEncapsulatedObjectFrame::textEncoding() const
{
return d->textEncoding;
}
void GeneralEncapsulatedObjectFrame::setTextEncoding(String::Type encoding)
{
d->textEncoding = encoding;
}
String GeneralEncapsulatedObjectFrame::mimeType() const
{
return d->mimeType;
}
void GeneralEncapsulatedObjectFrame::setMimeType(const String &type)
{
d->mimeType = type;
}
String GeneralEncapsulatedObjectFrame::fileName() const
{
return d->fileName;
}
void GeneralEncapsulatedObjectFrame::setFileName(const String &name)
{
d->fileName = name;
}
String GeneralEncapsulatedObjectFrame::description() const
{
return d->description;
}
void GeneralEncapsulatedObjectFrame::setDescription(const String &desc)
{
d->description = desc;
}
ByteVector GeneralEncapsulatedObjectFrame::object() const
{
return d->data;
}
void GeneralEncapsulatedObjectFrame::setObject(const ByteVector &data)
{
d->data = data;
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
void GeneralEncapsulatedObjectFrame::parseFields(const ByteVector &data)
{
if(data.size() < 4) {
debug("An object frame must contain at least 4 bytes.");
return;
}
d->textEncoding = String::Type(data[0]);
int pos = 1;
d->mimeType = readStringField(data, String::Latin1, &pos);
d->fileName = readStringField(data, d->textEncoding, &pos);
d->description = readStringField(data, d->textEncoding, &pos);
d->data = data.mid(pos);
}
ByteVector GeneralEncapsulatedObjectFrame::renderFields() const
{
ByteVector data;
data.append(char(d->textEncoding));
data.append(d->mimeType.data(String::Latin1));
data.append(textDelimiter(String::Latin1));
data.append(d->fileName.data(d->textEncoding));
data.append(textDelimiter(d->textEncoding));
data.append(d->description.data(d->textEncoding));
data.append(textDelimiter(d->textEncoding));
data.append(d->data);
return data;
}
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////
GeneralEncapsulatedObjectFrame::GeneralEncapsulatedObjectFrame(const ByteVector &data, Header *h) : Frame(h)
{
d = new GeneralEncapsulatedObjectFramePrivate;
parseFields(fieldData(data));
}
| epik/wAMP | plugin/src/taglib/mpeg/id3v2/frames/generalencapsulatedobjectframe.cpp | C++ | lgpl-2.1 | 5,475 |
import { FieldSchema, ValueSchema } from '@ephox/boulder';
import { Fun, Optional, Result } from '@ephox/katamari';
export interface SidebarInstanceApi {
element: () => HTMLElement;
}
export interface SidebarSpec {
icon?: string;
tooltip?: string;
onShow?: (api: SidebarInstanceApi) => void;
onSetup?: (api: SidebarInstanceApi) => (api: SidebarInstanceApi) => void;
onHide?: (api: SidebarInstanceApi) => void;
}
export interface Sidebar {
icon: Optional<string>;
tooltip: Optional<string>;
onShow: (api: SidebarInstanceApi) => void;
onSetup: (api: SidebarInstanceApi) => (api: SidebarInstanceApi) => void;
onHide: (api: SidebarInstanceApi) => void;
}
export const sidebarSchema = ValueSchema.objOf([
FieldSchema.optionString('icon'),
FieldSchema.optionString('tooltip'),
FieldSchema.defaultedFunction('onShow', Fun.noop),
FieldSchema.defaultedFunction('onHide', Fun.noop),
FieldSchema.defaultedFunction('onSetup', () => Fun.noop)
]);
export const createSidebar = (spec: SidebarSpec): Result<Sidebar, ValueSchema.SchemaError<any>> => ValueSchema.asRaw('sidebar', sidebarSchema, spec);
| TeamupCom/tinymce | modules/bridge/src/main/ts/ephox/bridge/components/sidebar/Sidebar.ts | TypeScript | lgpl-2.1 | 1,121 |
/*
LV2 UI Extension
Copyright 2009-2014 David Robillard <d@drobilla.net>
Copyright 2006-2011 Lars Luthman <lars.luthman@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
@file ui.h User Interface API.
For high-level documentation, see <http://lv2plug.in/ns/extensions/ui>.
*/
#ifndef LV2_UI_H
#define LV2_UI_H
#include <stdint.h>
#include "lv2.h"
#define LV2_UI_URI "http://lv2plug.in/ns/extensions/ui"
#define LV2_UI_PREFIX LV2_UI_URI "#"
#define LV2_UI__CocoaUI LV2_UI_PREFIX "CocoaUI"
#define LV2_UI__Gtk3UI LV2_UI_PREFIX "Gtk3UI"
#define LV2_UI__GtkUI LV2_UI_PREFIX "GtkUI"
#define LV2_UI__PortNotification LV2_UI_PREFIX "PortNotification"
#define LV2_UI__Qt4UI LV2_UI_PREFIX "Qt4UI"
#define LV2_UI__UI LV2_UI_PREFIX "UI"
#define LV2_UI__WindowsUI LV2_UI_PREFIX "WindowsUI"
#define LV2_UI__X11UI LV2_UI_PREFIX "X11UI"
#define LV2_UI__binary LV2_UI_PREFIX "binary"
#define LV2_UI__fixedSize LV2_UI_PREFIX "fixedSize"
#define LV2_UI__idleInterface LV2_UI_PREFIX "idleInterface"
#define LV2_UI__noUserResize LV2_UI_PREFIX "noUserResize"
#define LV2_UI__notifyType LV2_UI_PREFIX "notifyType"
#define LV2_UI__parent LV2_UI_PREFIX "parent"
#define LV2_UI__plugin LV2_UI_PREFIX "plugin"
#define LV2_UI__portIndex LV2_UI_PREFIX "portIndex"
#define LV2_UI__portMap LV2_UI_PREFIX "portMap"
#define LV2_UI__portNotification LV2_UI_PREFIX "portNotification"
#define LV2_UI__portSubscribe LV2_UI_PREFIX "portSubscribe"
#define LV2_UI__resize LV2_UI_PREFIX "resize"
#define LV2_UI__showInterface LV2_UI_PREFIX "showInterface"
#define LV2_UI__touch LV2_UI_PREFIX "touch"
#define LV2_UI__ui LV2_UI_PREFIX "ui"
#define LV2_UI__updateRate LV2_UI_PREFIX "updateRate"
#define LV2_UI__windowTitle LV2_UI_PREFIX "windowTitle"
/**
The index returned by LV2_UI_Port_Port::port_index() for unknown ports.
*/
#define LV2UI_INVALID_PORT_INDEX ((uint32_t)-1)
#ifdef __cplusplus
extern "C" {
#else
# include <stdbool.h>
#endif
/**
A pointer to some widget or other type of UI handle.
The actual type is defined by the type of the UI.
*/
typedef void* LV2UI_Widget;
/**
A pointer to UI instance internals.
The host may compare this to NULL, but otherwise MUST NOT interpret it.
*/
typedef void* LV2UI_Handle;
/**
A pointer to a controller provided by the host.
The UI may compare this to NULL, but otherwise MUST NOT interpret it.
*/
typedef void* LV2UI_Controller;
/**
A pointer to opaque data for a feature.
*/
typedef void* LV2UI_Feature_Handle;
/**
A host-provided function that sends data to a plugin's input ports.
The @p buffer parameter must point to a block of data, @p buffer_size bytes
large. The format of this data and how the host should use it is defined by
the @p port_protocol. This buffer is owned by the UI and is only valid for
the duration of this call.
The @p port_protocol parameter should either be 0 or the URID for a
ui:PortProtocol. If it is 0, the protocol is implicitly ui:floatProtocol,
the port MUST be an lv2:ControlPort input, @p buffer MUST point to a single
float value, and @p buffer_size MUST be sizeof(float).
The UI SHOULD NOT use a protocol not supported by the host, but the host
MUST gracefully ignore any protocol it does not understand.
*/
typedef void (*LV2UI_Write_Function)(LV2UI_Controller controller,
uint32_t port_index,
uint32_t buffer_size,
uint32_t port_protocol,
const void* buffer);
/**
A plugin UI.
A pointer to an object of this type is returned by the lv2ui_descriptor()
function.
*/
typedef struct _LV2UI_Descriptor {
/**
The URI for this UI (not for the plugin it controls).
*/
const char* URI;
/**
Create a new UI and return a handle to it. This function works
similarly to LV2_Descriptor::instantiate().
@param descriptor The descriptor for the UI to instantiate.
@param plugin_uri The URI of the plugin that this UI will control.
@param bundle_path The path to the bundle containing this UI, including
the trailing directory separator.
@param write_function A function that the UI can use to send data to the
plugin's input ports.
@param controller A handle for the plugin instance to be passed as the
first parameter of UI methods.
@param widget (output) widget pointer. The UI points this at its main
widget, which has the type defined by the UI type in the data file.
@param features An array of LV2_Feature pointers. The host must pass
all feature URIs that it and the UI supports and any additional data, as
in LV2_Descriptor::instantiate(). Note that UI features and plugin
features are not necessarily the same.
*/
LV2UI_Handle (*instantiate)(const struct _LV2UI_Descriptor* descriptor,
const char* plugin_uri,
const char* bundle_path,
LV2UI_Write_Function write_function,
LV2UI_Controller controller,
LV2UI_Widget* widget,
const LV2_Feature* const* features);
/**
Destroy the UI. The host must not try to access the widget after
calling this function.
*/
void (*cleanup)(LV2UI_Handle ui);
/**
Tell the UI that something interesting has happened at a plugin port.
What is "interesting" and how it is written to @p buffer is defined by
@p format, which has the same meaning as in LV2UI_Write_Function().
Format 0 is a special case for lv2:ControlPort, where this function
should be called when the port value changes (but not necessarily for
every change), @p buffer_size must be sizeof(float), and @p buffer
points to a single IEEE-754 float.
By default, the host should only call this function for lv2:ControlPort
inputs. However, the UI can request updates for other ports statically
with ui:portNotification or dynamicaly with ui:portSubscribe.
The UI MUST NOT retain any reference to @p buffer after this function
returns, it is only valid for the duration of the call.
This member may be NULL if the UI is not interested in any port events.
*/
void (*port_event)(LV2UI_Handle ui,
uint32_t port_index,
uint32_t buffer_size,
uint32_t format,
const void* buffer);
/**
Return a data structure associated with an extension URI, typically an
interface struct with additional function pointers
This member may be set to NULL if the UI is not interested in supporting
any extensions. This is similar to LV2_Descriptor::extension_data().
*/
const void* (*extension_data)(const char* uri);
} LV2UI_Descriptor;
/**
Feature/interface for resizable UIs (LV2_UI__resize).
This structure is used in two ways: as a feature passed by the host via
LV2UI_Descriptor::instantiate(), or as an interface provided by a UI via
LV2UI_Descriptor::extension_data()).
*/
typedef struct _LV2UI_Resize {
/**
Pointer to opaque data which must be passed to ui_resize().
*/
LV2UI_Feature_Handle handle;
/**
Request/advertise a size change.
When provided by the host, the UI may call this function to inform the
host about the size of the UI.
When provided by the UI, the host may call this function to notify the
UI that it should change its size accordingly.
@return 0 on success.
*/
int (*ui_resize)(LV2UI_Feature_Handle handle, int width, int height);
} LV2UI_Resize;
/**
Feature to map port symbols to UIs.
This can be used by the UI to get the index for a port with the given
symbol. This makes it possible to implement and distribute a UI separately
from the plugin (since symbol, unlike index, is a stable port identifier).
*/
typedef struct _LV2UI_Port_Map {
/**
Pointer to opaque data which must be passed to port_index().
*/
LV2UI_Feature_Handle handle;
/**
Get the index for the port with the given @p symbol.
@return The index of the port, or LV2UI_INVALID_PORT_INDEX if no such
port is found.
*/
uint32_t (*port_index)(LV2UI_Feature_Handle handle, const char* symbol);
} LV2UI_Port_Map;
/**
Feature to subscribe to port updates (LV2_UI__portSubscribe).
*/
typedef struct _LV2UI_Port_Subscribe {
/**
Pointer to opaque data which must be passed to subscribe() and
unsubscribe().
*/
LV2UI_Feature_Handle handle;
/**
Subscribe to updates for a port.
This means that the host will call the UI's port_event() function when
the port value changes (as defined by protocol).
Calling this function with the same @p port_index and @p port_protocol
as an already active subscription has no effect.
@param handle The handle field of this struct.
@param port_index The index of the port.
@param port_protocol The URID of the ui:PortProtocol.
@param features Features for this subscription.
@return 0 on success.
*/
uint32_t (*subscribe)(LV2UI_Feature_Handle handle,
uint32_t port_index,
uint32_t port_protocol,
const LV2_Feature* const* features);
/**
Unsubscribe from updates for a port.
This means that the host will cease calling calling port_event() when
the port value changes.
Calling this function with a @p port_index and @p port_protocol that
does not refer to an active port subscription has no effect.
@param handle The handle field of this struct.
@param port_index The index of the port.
@param port_protocol The URID of the ui:PortProtocol.
@param features Features for this subscription.
@return 0 on success.
*/
uint32_t (*unsubscribe)(LV2UI_Feature_Handle handle,
uint32_t port_index,
uint32_t port_protocol,
const LV2_Feature* const* features);
} LV2UI_Port_Subscribe;
/**
A feature to notify the host that the user has grabbed a UI control.
*/
typedef struct _LV2UI_Touch {
/**
Pointer to opaque data which must be passed to ui_resize().
*/
LV2UI_Feature_Handle handle;
/**
Notify the host that a control has been grabbed or released.
The host should cease automating the port or otherwise manipulating the
port value until the control has been ungrabbed.
@param handle The handle field of this struct.
@param port_index The index of the port associated with the control.
@param grabbed If true, the control has been grabbed, otherwise the
control has been released.
*/
void (*touch)(LV2UI_Feature_Handle handle,
uint32_t port_index,
bool grabbed);
} LV2UI_Touch;
/**
UI Idle Interface (LV2_UI__idleInterface)
UIs can provide this interface to have an idle() callback called by the host
rapidly to update the UI.
*/
typedef struct _LV2UI_Idle_Interface {
/**
Run a single iteration of the UI's idle loop.
This will be called rapidly in the UI thread at a rate appropriate
for a toolkit main loop. There are no precise timing guarantees, but
the host should attempt to call idle() at a high enough rate for smooth
animation, at least 30Hz.
@return non-zero if the UI has been closed, in which case the host
should stop calling idle(), and can either completely destroy the UI, or
re-show it and resume calling idle().
*/
int (*idle)(LV2UI_Handle ui);
} LV2UI_Idle_Interface;
/**
UI Show Interface (LV2_UI__showInterface)
UIs can provide this interface to show and hide a window, which allows them
to function in hosts unable to embed their widget. This allows any UI to
provide a fallback for embedding that works in any host.
If used:
- The host MUST use LV2UI_Idle_Interface to drive the UI.
- The UI MUST return non-zero from LV2UI_Idle_Interface::idle() when it has been closed.
- If idle() returns non-zero, the host MUST call hide() and stop calling
idle(). It MAY later call show() then resume calling idle().
*/
typedef struct _LV2UI_Show_Interface {
/**
Show a window for this UI.
The window title MAY have been passed by the host to
LV2UI_Descriptor::instantiate() as an LV2_Options_Option with key
LV2_UI__windowTitle.
@return 0 on success, or anything else to stop being called.
*/
int (*show)(LV2UI_Handle ui);
/**
Hide the window for this UI.
@return 0 on success, or anything else to stop being called.
*/
int (*hide)(LV2UI_Handle ui);
} LV2UI_Show_Interface;
/**
Peak data for a slice of time, the update format for ui:peakProtocol.
*/
typedef struct _LV2UI_Peak_Data {
/**
The start of the measurement period. This is just a running counter
that is only meaningful in comparison to previous values and must not be
interpreted as an absolute time.
*/
uint32_t period_start;
/**
The size of the measurement period, in the same units as period_start.
*/
uint32_t period_size;
/**
The peak value for the measurement period. This should be the maximal
value for abs(sample) over all the samples in the period.
*/
float peak;
} LV2UI_Peak_Data;
/**
Prototype for UI accessor function.
This is the entry point to a UI library, which works in the same way as
lv2_descriptor() but for UIs rather than plugins.
*/
LV2_SYMBOL_EXPORT
const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index);
/**
The type of the lv2ui_descriptor() function.
*/
typedef const LV2UI_Descriptor* (*LV2UI_DescriptorFunction)(uint32_t index);
#ifdef __cplusplus
}
#endif
#endif /* LV2_UI_H */
| jnetterf/calf | src/calf/lv2_ui.h | C | lgpl-2.1 | 14,989 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<!-- <script src="http://use.edgefonts.net/source-sans-pro;source-code-pro.js"></script> -->
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic|Source+Code+Pro:300,400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="../assets/css/bootstrap.css">
<link rel="stylesheet" href="../assets/css/jquery.bonsai.css">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/icons.css">
<script type="text/javascript" src="../assets/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.js"></script>
<script type="text/javascript" src="../assets/js/jquery.bonsai.js"></script>
<!-- <script type="text/javascript" src="../assets/js/main.js"></script> -->
</head>
<body>
<div>
<!-- Name Title -->
<h1>(unnamed)</h1>
<!-- Type and Stereotype -->
<section style="margin-top: .5em;">
<span class="alert alert-info">
<span class="node-icon _icon-UMLParameter"></span>
UMLParameter
</span>
</section>
<!-- Path -->
<section style="margin-top: 10px">
<span class="label label-info"><a href='cf9c8b720f3815adeccaf3ef6e48c6c4.html'><span class='node-icon _icon-Project'></span>Untitled</a></span>
<span>::</span>
<span class="label label-info"><a href='6550300e57d7fc770bd2e9afbcdb3ecb.html'><span class='node-icon _icon-UMLModel'></span>JavaReverse</a></span>
<span>::</span>
<span class="label label-info"><a href='7ff2d96ca3eb7f62f48c1a30b3c7c990.html'><span class='node-icon _icon-UMLPackage'></span>net</a></span>
<span>::</span>
<span class="label label-info"><a href='7adc4be4f2e4859086f068fc27512d85.html'><span class='node-icon _icon-UMLPackage'></span>gleamynode</a></span>
<span>::</span>
<span class="label label-info"><a href='bb15307bdbbaf31bfef4f71be74150ae.html'><span class='node-icon _icon-UMLPackage'></span>netty</a></span>
<span>::</span>
<span class="label label-info"><a href='7b76f92b4b514580a4bcf746956f6d64.html'><span class='node-icon _icon-UMLPackage'></span>handler</a></span>
<span>::</span>
<span class="label label-info"><a href='53c2cb4d5fd869407ef4d8594cde3ec4.html'><span class='node-icon _icon-UMLPackage'></span>codec</a></span>
<span>::</span>
<span class="label label-info"><a href='d73a22ab5aed412637935820137ae402.html'><span class='node-icon _icon-UMLPackage'></span>replay</a></span>
<span>::</span>
<span class="label label-info"><a href='50e9b48de9a049a5b71488377984d97f.html'><span class='node-icon _icon-UMLClass'></span>ReplayingDecoder</a></span>
<span>::</span>
<span class="label label-info"><a href='c461c0da561478e7e0746a0769062dd5.html'><span class='node-icon _icon-UMLOperation'></span>checkpoint</a></span>
<span>::</span>
<span class="label label-info"><a href='9da407eeeff5d884dffc718318681c24.html'><span class='node-icon _icon-UMLParameter'></span>(Parameter)</a></span>
</section>
<!-- Diagram -->
<!-- Description -->
<section>
<h3>Description</h3>
<div>
<span class="label label-info">none</span>
</div>
</section>
<!-- Specification -->
<!-- Directed Relationship -->
<!-- Undirected Relationship -->
<!-- Classifier -->
<!-- Interface -->
<!-- Component -->
<!-- Node -->
<!-- Actor -->
<!-- Use Case -->
<!-- Template Parameters -->
<!-- Literals -->
<!-- Attributes -->
<!-- Operations -->
<!-- Receptions -->
<!-- Extension Points -->
<!-- Parameters -->
<!-- Diagrams -->
<!-- Behavior -->
<!-- Action -->
<!-- Interaction -->
<!-- CombinedFragment -->
<!-- Activity -->
<!-- State Machine -->
<!-- State Machine -->
<!-- State -->
<!-- Vertex -->
<!-- Transition -->
<!-- Properties -->
<section>
<h3>Properties</h3>
<table class="table table-striped table-bordered">
<tr>
<th width="50%">Name</th>
<th width="50%">Value</th>
</tr>
<tr>
<td>name</td>
<td></td>
</tr>
<tr>
<td>stereotype</td>
<td><span class='label label-info'>null</span></td>
</tr>
<tr>
<td>visibility</td>
<td>public</td>
</tr>
<tr>
<td>isStatic</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isLeaf</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>type</td>
<td>void</td>
</tr>
<tr>
<td>multiplicity</td>
<td></td>
</tr>
<tr>
<td>isReadOnly</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isOrdered</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isUnique</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>defaultValue</td>
<td></td>
</tr>
<tr>
<td>direction</td>
<td>return</td>
</tr>
</table>
</section>
<!-- Tags -->
<!-- Constraints, Dependencies, Dependants -->
<!-- Relationships -->
<!-- Owned Elements -->
</div>
</body>
</html>
| jiangbo212/netty-init | html-docs/contents/9da407eeeff5d884dffc718318681c24.html | HTML | lgpl-2.1 | 7,620 |
/******************************************************************************
JUserNotification.h
Interface for the JUserNotification class.
Copyright © 1994-96 by John Lindal. All rights reserved.
******************************************************************************/
#ifndef _H_JUserNotification
#define _H_JUserNotification
#if !defined _J_UNIX && !defined ACE_LACKS_PRAGMA_ONCE
#pragma once
#endif
#include <jTypes.h>
class JUserNotification
{
public:
enum CloseAction
{
kSaveData,
kDiscardData,
kDontClose
};
public:
JUserNotification();
virtual ~JUserNotification();
virtual void DisplayMessage(const JCharacter* message) = 0;
virtual void ReportError(const JCharacter* message) = 0;
virtual JBoolean AskUserYes(const JCharacter* message) = 0;
virtual JBoolean AskUserNo(const JCharacter* message) = 0;
virtual CloseAction OKToClose(const JCharacter* message) = 0;
virtual JBoolean AcceptLicense() = 0;
// control of Message and Error display
JBoolean IsSilent() const;
void SetSilent(const JBoolean beQuiet);
private:
JBoolean itsSilenceFlag;
private:
// not allowed
JUserNotification(const JUserNotification& source);
const JUserNotification& operator=(const JUserNotification& source);
};
/******************************************************************************
Silence
******************************************************************************/
inline JBoolean
JUserNotification::IsSilent()
const
{
return itsSilenceFlag;
}
inline void
JUserNotification::SetSilent
(
const JBoolean beQuiet
)
{
itsSilenceFlag = beQuiet;
}
#endif
| mbert/mulberry-lib-jx | libjcore/code/JUserNotification.h | C | lgpl-2.1 | 1,627 |
using MaxBootstrap.Core.View;
namespace MaxBootstrap.UI.Views.Error
{
public interface IErrorViewmodel : IViewmodel
{
string ErrorMessageText { get; }
}
}
| Frogman7/MaxBootstrap | Source/MaxBootstrap.UI/Views/Error/IErrorViewmodel.cs | C# | lgpl-2.1 | 179 |
<?php
/**
* @package tikiwiki
*/
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
require_once('tiki-setup.php');
if ($prefs['feature_jquery'] != 'y' || $prefs['feature_jquery_validation'] != 'y') {
echo '{}';
exit;
}
if (empty($_REQUEST['validator']) || empty($_REQUEST["input"]) && $_REQUEST["input"] != '0') {
echo '{}';
exit;
}
if (empty($_REQUEST["parameter"])) {
$_REQUEST["parameter"] = '';
}
if (empty($_REQUEST["message"])) {
$_REQUEST["message"] = '';
}
$validatorslib = TikiLib::lib('validators');
if (! in_array($_REQUEST['validator'], $validatorslib->available)) {
echo '{}';
exit;
}
$validatorslib->setInput($_REQUEST["input"]);
$result = $validatorslib->validateInput($_REQUEST["validator"], $_REQUEST["parameter"], $_REQUEST["message"]);
header('Content-Type: application/json');
echo json_encode($result);
| tikiorg/tiki | validate-ajax.php | PHP | lgpl-2.1 | 1,053 |
# Makefile.in generated by automake 1.11.1 from Makefile.am.
# docs/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation,
# Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
#
#
pkgdatadir = $(datadir)/curl
pkgincludedir = $(includedir)/curl
pkglibdir = $(libdir)/curl
pkglibexecdir = $(libexecdir)/curl
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = x86_64-unknown-linux-gnu
host_triplet = arm-unknown-linux-androideabi
subdir = docs
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in INSTALL \
THANKS TODO
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/curl-compilers.m4 \
$(top_srcdir)/m4/curl-confopts.m4 \
$(top_srcdir)/m4/curl-functions.m4 \
$(top_srcdir)/m4/curl-override.m4 \
$(top_srcdir)/m4/curl-reentrant.m4 \
$(top_srcdir)/m4/curl-system.m4 $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs
CONFIG_HEADER = $(top_builddir)/lib/curl_config.h \
$(top_builddir)/src/curl_config.h \
$(top_builddir)/include/curl/curlbuild.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
depcomp =
am__depfiles_maybe =
SOURCES =
DIST_SOURCES =
RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
html-recursive info-recursive install-data-recursive \
install-dvi-recursive install-exec-recursive \
install-html-recursive install-info-recursive \
install-pdf-recursive install-ps-recursive install-recursive \
installcheck-recursive installdirs-recursive pdf-recursive \
ps-recursive uninstall-recursive
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
$(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
*) f=$$p;; \
esac;
am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
am__install_max = 40
am__nobase_strip_setup = \
srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
am__nobase_strip = \
for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
am__nobase_list = $(am__nobase_strip_setup); \
for p in $$list; do echo "$$p $$p"; done | \
sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
$(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
if (++n[$$2] == $(am__install_max)) \
{ print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
END { for (dir in files) print dir, files[dir] }'
am__base_list = \
sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
man1dir = $(mandir)/man1
am__installdirs = "$(DESTDIR)$(man1dir)"
MANS = $(man_MANS)
RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \
distclean-recursive maintainer-clean-recursive
AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \
$(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \
distdir
ETAGS = etags
CTAGS = ctags
DIST_SUBDIRS = $(SUBDIRS)
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
am__relativize = \
dir0=`pwd`; \
sed_first='s,^\([^/]*\)/.*$$,\1,'; \
sed_rest='s,^[^/]*/*,,'; \
sed_last='s,^.*/\([^/]*\)$$,\1,'; \
sed_butlast='s,/*[^/]*$$,,'; \
while test -n "$$dir1"; do \
first=`echo "$$dir1" | sed -e "$$sed_first"`; \
if test "$$first" != "."; then \
if test "$$first" = ".."; then \
dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
else \
first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
if test "$$first2" = "$$first"; then \
dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
else \
dir2="../$$dir2"; \
fi; \
dir0="$$dir0"/"$$first"; \
fi; \
fi; \
dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
done; \
reldir="$$dir2"
ACLOCAL = ${SHELL} "/home/jorizci/librerias/curl/wk_curl/missing" --run aclocal-1.11
AMTAR = ${SHELL} "/home/jorizci/librerias/curl/wk_curl/missing" --run tar
AR = /home/jorizci/android_develop/ndkr5b-toolchain/android-5/bin//arm-linux-androideabi-ar
AS = as
AUTOCONF = ${SHELL} "/home/jorizci/librerias/curl/wk_curl/missing" --run autoconf
AUTOHEADER = ${SHELL} "/home/jorizci/librerias/curl/wk_curl/missing" --run autoheader
AUTOMAKE = ${SHELL} "/home/jorizci/librerias/curl/wk_curl/missing" --run automake-1.11
AWK = mawk
CC = arm-linux-androideabi-gcc
CCDEPMODE = depmode=gcc3
CFLAGS = -g0 -O2 -Wno-system-headers
CONFIGURE_OPTIONS = " '--host=arm-linux-androideabi' '--disable-tftp' '--disable-sspi' '--disable-ipv6' '--disable-ldaps' '--disable-ldap' '--disable-telnet' '--disable-ftp' '--without-ssl' '--disable-imap' '--disable-smtp' '--disable-pop3' '--disable-rtsp' '--disable-ares' '--without-ca-bundle' '--disable-warnings' '--disable-manual' '--without-nss' '--enable-shared' '--without-zlib' '--without-random' 'host_alias=arm-linux-androideabi'"
CPP = arm-linux-androideabi-gcc -E
CPPFLAGS =
CURL_CA_BUNDLE =
CURL_DISABLE_DICT =
CURL_DISABLE_FILE =
CURL_DISABLE_FTP = 1
CURL_DISABLE_HTTP =
CURL_DISABLE_IMAP = 1
CURL_DISABLE_LDAP = 1
CURL_DISABLE_LDAPS = 1
CURL_DISABLE_POP3 = 1
CURL_DISABLE_PROXY =
CURL_DISABLE_RTSP = 1
CURL_DISABLE_SMTP = 1
CURL_DISABLE_TELNET = 1
CURL_DISABLE_TFTP = 1
CURL_LIBS =
CYGPATH_W = echo
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
DLLTOOL = dlltool
DSYMUTIL =
DUMPBIN =
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /bin/grep -E
EXEEXT =
FGREP = /bin/grep -F
GREP = /bin/grep
HAVE_LIBZ =
HAVE_PK11_CREATEGENERICOBJECT =
IDN_ENABLED =
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
IPV6_ENABLED =
KRB4_ENABLED =
LD = /home/jorizci/android_develop/ndkr5b-toolchain/android-5/arm-linux-androideabi/bin/ld
LDFLAGS =
LIBCURL_LIBS =
LIBOBJS =
LIBS =
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LIPO =
LN_S = ln -s
LTLIBOBJS =
MAINT = #
MAKEINFO = ${SHELL} "/home/jorizci/librerias/curl/wk_curl/missing" --run makeinfo
MANOPT = -man
MKDIR_P = /bin/mkdir -p
NM = /home/jorizci/android_develop/ndkr5b-toolchain/android-5/bin//arm-linux-androideabi-nm -B
NMEDIT =
NROFF = /usr/bin/nroff
OBJDUMP = objdump
OBJEXT = o
OTOOL =
OTOOL64 =
PACKAGE = curl
PACKAGE_BUGREPORT = a suitable curl mailing list => http://curl.haxx.se/mail/
PACKAGE_NAME = curl
PACKAGE_STRING = curl -
PACKAGE_TARNAME = curl
PACKAGE_URL =
PACKAGE_VERSION = -
PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/jorizci/android_develop/sdk/tools/:/home/jorizci/android_develop/sdk/platform-tools/:/home/jorizci/android_develop/ndkr5b-toolchain/android-5/bin/:/home/jorizci/android_develop/ndkr5b-toolchain/android-5/
PATH_SEPARATOR = :
PERL = /usr/bin/perl
PKGADD_NAME = cURL - a client that groks URLs
PKGADD_PKG = HAXXcurl
PKGADD_VENDOR = curl.haxx.se
PKGCONFIG =
RANDOM_FILE =
RANLIB = arm-linux-androideabi-ranlib
REQUIRE_LIB_DEPS = no
SED = /bin/sed
SET_MAKE =
SHELL = /bin/bash
SSL_ENABLED =
STRIP = arm-linux-androideabi-strip
SUPPORT_FEATURES =
SUPPORT_PROTOCOLS = DICT FILE HTTP
TEST_SERVER_LIBS =
USE_ARES =
USE_GNUTLS =
USE_LIBSSH2 =
USE_NSS =
USE_SSLEAY =
USE_WINDOWS_SSPI =
VERSION = 7.20.1-DEV
VERSIONNUM = 071401
abs_builddir = /home/jorizci/librerias/curl/wk_curl/docs
abs_srcdir = /home/jorizci/librerias/curl/wk_curl/docs
abs_top_builddir = /home/jorizci/librerias/curl/wk_curl
abs_top_srcdir = /home/jorizci/librerias/curl/wk_curl
ac_ct_CC =
ac_ct_DUMPBIN =
am__include = include
am__leading_dot = .
am__quote =
am__tar = ${AMTAR} chof - "$$tardir"
am__untar = ${AMTAR} xf -
bindir = ${exec_prefix}/bin
build = x86_64-unknown-linux-gnu
build_alias =
build_cpu = x86_64
build_os = linux-gnu
build_vendor = unknown
builddir = .
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = arm-unknown-linux-androideabi
host_alias = arm-linux-androideabi
host_cpu = arm
host_os = linux-androideabi
host_vendor = unknown
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = ${SHELL} /home/jorizci/librerias/curl/wk_curl/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
libext = a
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
lt_ECHO = echo
mandir = ${datarootdir}/man
mkdir_p = /bin/mkdir -p
oldincludedir = /usr/include
pdfdir = ${docdir}
prefix = /usr/local
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
subdirs =
sysconfdir = ${prefix}/etc
target_alias =
top_build_prefix = ../
top_builddir = ..
top_srcdir = ..
AUTOMAKE_OPTIONS = foreign no-dependencies
man_MANS = curl.1 curl-config.1
GENHTMLPAGES = curl.html curl-config.html
PDFPAGES = curl.pdf curl-config.pdf
HTMLPAGES = $(GENHTMLPAGES) index.html
SUBDIRS = examples libcurl
CLEANFILES = $(GENHTMLPAGES) $(PDFPAGES)
EXTRA_DIST = MANUAL BUGS CONTRIBUTE FAQ FEATURES INTERNALS SSLCERTS \
README.win32 RESOURCES TODO TheArtOfHttpScripting THANKS VERSIONS \
KNOWN_BUGS BINDINGS $(man_MANS) $(HTMLPAGES) HISTORY INSTALL \
$(PDFPAGES) LICENSE-MIXING README.netware DISTRO-DILEMMA INSTALL.devcpp
MAN2HTML = roffit < $< >$@
SUFFIXES = .1 .html .pdf
all: all-recursive
.SUFFIXES:
.SUFFIXES: .1 .html .pdf
$(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign docs/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign docs/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: # $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): # $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
install-man1: $(man_MANS)
@$(NORMAL_INSTALL)
test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
@list=''; test -n "$(man1dir)" || exit 0; \
{ for i in $$list; do echo "$$i"; done; \
l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
sed -n '/\.1[a-z]*$$/p'; \
} | while read p; do \
if test -f $$p; then d=; else d="$(srcdir)/"; fi; \
echo "$$d$$p"; echo "$$p"; \
done | \
sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
-e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
sed 'N;N;s,\n, ,g' | { \
list=; while read file base inst; do \
if test "$$base" = "$$inst"; then list="$$list $$file"; else \
echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
$(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
fi; \
done; \
for i in $$list; do echo "$$i"; done | $(am__base_list) | \
while read files; do \
test -z "$$files" || { \
echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
$(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
done; }
uninstall-man1:
@$(NORMAL_UNINSTALL)
@list=''; test -n "$(man1dir)" || exit 0; \
files=`{ for i in $$list; do echo "$$i"; done; \
l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
sed -n '/\.1[a-z]*$$/p'; \
} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
-e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
test -z "$$files" || { \
echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
# This directory's subdirectories are mostly independent; you can cd
# into them and run `make' without going through this Makefile.
# To change the values of `make' variables: instead of editing Makefiles,
# (1) if the variable is set in `config.status', edit `config.status'
# (which will cause the Makefiles to be regenerated when you run `make');
# (2) otherwise, pass the desired values on the `make' command line.
$(RECURSIVE_TARGETS):
@fail= failcom='exit 1'; \
for f in x $$MAKEFLAGS; do \
case $$f in \
*=* | --[!k]*);; \
*k*) failcom='fail=yes';; \
esac; \
done; \
dot_seen=no; \
target=`echo $@ | sed s/-recursive//`; \
list='$(SUBDIRS)'; for subdir in $$list; do \
echo "Making $$target in $$subdir"; \
if test "$$subdir" = "."; then \
dot_seen=yes; \
local_target="$$target-am"; \
else \
local_target="$$target"; \
fi; \
($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
|| eval $$failcom; \
done; \
if test "$$dot_seen" = "no"; then \
$(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
fi; test -z "$$fail"
$(RECURSIVE_CLEAN_TARGETS):
@fail= failcom='exit 1'; \
for f in x $$MAKEFLAGS; do \
case $$f in \
*=* | --[!k]*);; \
*k*) failcom='fail=yes';; \
esac; \
done; \
dot_seen=no; \
case "$@" in \
distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
*) list='$(SUBDIRS)' ;; \
esac; \
rev=''; for subdir in $$list; do \
if test "$$subdir" = "."; then :; else \
rev="$$subdir $$rev"; \
fi; \
done; \
rev="$$rev ."; \
target=`echo $@ | sed s/-recursive//`; \
for subdir in $$rev; do \
echo "Making $$target in $$subdir"; \
if test "$$subdir" = "."; then \
local_target="$$target-am"; \
else \
local_target="$$target"; \
fi; \
($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
|| eval $$failcom; \
done && test -z "$$fail"
tags-recursive:
list='$(SUBDIRS)'; for subdir in $$list; do \
test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
done
ctags-recursive:
list='$(SUBDIRS)'; for subdir in $$list; do \
test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
done
ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
mkid -fID $$unique
tags: TAGS
TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
set x; \
here=`pwd`; \
if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
include_option=--etags-include; \
empty_fix=.; \
else \
include_option=--include; \
empty_fix=; \
fi; \
list='$(SUBDIRS)'; for subdir in $$list; do \
if test "$$subdir" = .; then :; else \
test ! -f $$subdir/TAGS || \
set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
fi; \
done; \
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: CTAGS
CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(DISTFILES)
@list='$(MANS)'; if test -n "$$list"; then \
list=`for p in $$list; do \
if test -f $$p; then d=; else d="$(srcdir)/"; fi; \
if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
if test -n "$$list" && \
grep 'ab help2man is required to generate this page' $$list >/dev/null; then \
echo "error: found man pages containing the \`missing help2man' replacement text:" >&2; \
grep -l 'ab help2man is required to generate this page' $$list | sed 's/^/ /' >&2; \
echo " to fix them, install help2man, remove and regenerate the man pages;" >&2; \
echo " typically \`make maintainer-clean' will remove them" >&2; \
exit 1; \
else :; fi; \
else :; fi
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
if test "$$subdir" = .; then :; else \
test -d "$(distdir)/$$subdir" \
|| $(MKDIR_P) "$(distdir)/$$subdir" \
|| exit 1; \
fi; \
done
@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
if test "$$subdir" = .; then :; else \
dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
$(am__relativize); \
new_distdir=$$reldir; \
dir1=$$subdir; dir2="$(top_distdir)"; \
$(am__relativize); \
new_top_distdir=$$reldir; \
echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
($(am__cd) $$subdir && \
$(MAKE) $(AM_MAKEFLAGS) \
top_distdir="$$new_top_distdir" \
distdir="$$new_distdir" \
am__remove_distdir=: \
am__skip_length_check=: \
am__skip_mode_fix=: \
distdir) \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-recursive
all-am: Makefile $(MANS)
installdirs: installdirs-recursive
installdirs-am:
for dir in "$(DESTDIR)$(man1dir)"; do \
test -z "$$dir" || $(MKDIR_P) "$$dir"; \
done
install: install-recursive
install-exec: install-exec-recursive
install-data: install-data-recursive
uninstall: uninstall-recursive
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-recursive
install-strip:
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
`test -z '$(STRIP)' || \
echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:
clean-generic:
-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-recursive
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-recursive
-rm -f Makefile
distclean-am: clean-am distclean-generic distclean-tags
dvi: dvi-recursive
dvi-am:
html-am:
info: info-recursive
info-am:
install-data-am: install-man
install-dvi: install-dvi-recursive
install-dvi-am:
install-exec-am:
install-html: install-html-recursive
install-html-am:
install-info: install-info-recursive
install-info-am:
install-man: install-man1
install-pdf: install-pdf-recursive
install-pdf-am:
install-ps: install-ps-recursive
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-recursive
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-recursive
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf-am:
ps: ps-recursive
ps-am:
uninstall-am: uninstall-man
uninstall-man: uninstall-man1
.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \
install-am install-strip tags-recursive
.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
all all-am check check-am clean clean-generic clean-libtool \
ctags ctags-recursive distclean distclean-generic \
distclean-libtool distclean-tags distdir dvi dvi-am html \
html-am info info-am install install-am install-data \
install-data-am install-dvi install-dvi-am install-exec \
install-exec-am install-html install-html-am install-info \
install-info-am install-man install-man1 install-pdf \
install-pdf-am install-ps install-ps-am install-strip \
installcheck installcheck-am installdirs installdirs-am \
maintainer-clean maintainer-clean-generic mostlyclean \
mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
tags tags-recursive uninstall uninstall-am uninstall-man \
uninstall-man1
html: $(HTMLPAGES)
cd libcurl; make html
pdf: $(PDFPAGES)
cd libcurl; make pdf
.1.html:
$(MAN2HTML)
.1.pdf:
@(foo=`echo $@ | sed -e 's/\.[0-9]$$//g'`; \
groff -Tps -man $< >$$foo.ps; \
ps2pdf $$foo.ps $@; \
rm $$foo.ps; \
echo "converted $< to $@")
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
| thahemp/osg-android | 3rdparty/curl/docs/Makefile | Makefile | lgpl-2.1 | 23,854 |
/***
Copyright (c) 2013 Hércules S. S. José
Este arquivo é parte do programa EncontreAquiPeças.
EncontreAquiPeças é um software livre; você pode redistribui-lo e/ou
modificá-lo dentro dos termos da Licença Pública Geral Menor GNU como
publicada pela Fundação do Software Livre (FSF); na versão 2.1 da
Licença.
Este programa é distribuído na esperança que possa ser útil,
mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÂO a
qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública
Geral Menor GNU em português para maiores detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral Menor GNU sob o
nome de "LICENSE.TXT" junto com este programa, se não, acesse o site HSlife
no endereco www.hslife.com.br ou escreva para a Fundação do Software
Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
Para mais informações sobre o programa EncontreAquiPeças e seu autor acesse o
endereço www.hslife.com.br, pelo e-mail contato@hslife.com.br ou escreva para
Hércules S. S. José, Av. Ministro Lafaeyte de Andrade, 1683 - Bl. 3 Apt 404,
Marco II - Nova Iguaçu, RJ, Brasil.
*/
package br.com.hslife.encontreaquipecas.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="auditoriadados")
public class AuditoriaDados {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(nullable=false)
private String nomeAtributo;
@Column(nullable=false)
private String valorAtributo;
@Column(nullable=false)
private String situacaoOperacao; //BEFORE, AFTER
public AuditoriaDados() {
}
public AuditoriaDados(String valor, String atributo, String operacao) {
this.nomeAtributo = atributo;
this.valorAtributo = valor;
this.situacaoOperacao = operacao;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNomeAtributo() {
return nomeAtributo;
}
public void setNomeAtributo(String nomeAtributo) {
this.nomeAtributo = nomeAtributo;
}
public String getValorAtributo() {
return valorAtributo;
}
public void setValorAtributo(String valorAtributo) {
this.valorAtributo = valorAtributo;
}
public String getSituacaoOperacao() {
return situacaoOperacao;
}
public void setSituacaoOperacao(String situacaoOperacao) {
this.situacaoOperacao = situacaoOperacao;
}
}
| herculeshssj/encontreaquipecas | src/br/com/hslife/encontreaquipecas/entity/AuditoriaDados.java | Java | lgpl-2.1 | 2,693 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>bufferPool</title>
<!-- <script src="http://use.edgefonts.net/source-sans-pro;source-code-pro.js"></script> -->
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic|Source+Code+Pro:300,400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="../assets/css/bootstrap.css">
<link rel="stylesheet" href="../assets/css/jquery.bonsai.css">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/icons.css">
<script type="text/javascript" src="../assets/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.js"></script>
<script type="text/javascript" src="../assets/js/jquery.bonsai.js"></script>
<!-- <script type="text/javascript" src="../assets/js/main.js"></script> -->
</head>
<body>
<div>
<!-- Name Title -->
<h1>bufferPool</h1>
<!-- Type and Stereotype -->
<section style="margin-top: .5em;">
<span class="alert alert-info">
<span class="node-icon _icon-UMLParameter"></span>
UMLParameter
</span>
</section>
<!-- Path -->
<section style="margin-top: 10px">
<span class="label label-info"><a href='cf9c8b720f3815adeccaf3ef6e48c6c4.html'><span class='node-icon _icon-Project'></span>Untitled</a></span>
<span>::</span>
<span class="label label-info"><a href='6550300e57d7fc770bd2e9afbcdb3ecb.html'><span class='node-icon _icon-UMLModel'></span>JavaReverse</a></span>
<span>::</span>
<span class="label label-info"><a href='7ff2d96ca3eb7f62f48c1a30b3c7c990.html'><span class='node-icon _icon-UMLPackage'></span>net</a></span>
<span>::</span>
<span class="label label-info"><a href='7adc4be4f2e4859086f068fc27512d85.html'><span class='node-icon _icon-UMLPackage'></span>gleamynode</a></span>
<span>::</span>
<span class="label label-info"><a href='bb15307bdbbaf31bfef4f71be74150ae.html'><span class='node-icon _icon-UMLPackage'></span>netty</a></span>
<span>::</span>
<span class="label label-info"><a href='7b76f92b4b514580a4bcf746956f6d64.html'><span class='node-icon _icon-UMLPackage'></span>handler</a></span>
<span>::</span>
<span class="label label-info"><a href='f4ff7d19df693e81f51ef48c77403ab0.html'><span class='node-icon _icon-UMLPackage'></span>ssl</a></span>
<span>::</span>
<span class="label label-info"><a href='26ed8e4c8e33915b126df76cfc9661ce.html'><span class='node-icon _icon-UMLClass'></span>SslHandler</a></span>
<span>::</span>
<span class="label label-info"><a href='eda5ca0a49e91c9ed984f5ea5dd7b3c4.html'><span class='node-icon _icon-UMLOperation'></span>«constructor»SslHandler</a></span>
<span>::</span>
<span class="label label-info"><a href='2d53f0aa53d93769b62c018cae522d87.html'><span class='node-icon _icon-UMLParameter'></span>bufferPool</a></span>
</section>
<!-- Diagram -->
<!-- Description -->
<section>
<h3>Description</h3>
<div>
<span class="label label-info">none</span>
</div>
</section>
<!-- Specification -->
<!-- Directed Relationship -->
<!-- Undirected Relationship -->
<!-- Classifier -->
<!-- Interface -->
<!-- Component -->
<!-- Node -->
<!-- Actor -->
<!-- Use Case -->
<!-- Template Parameters -->
<!-- Literals -->
<!-- Attributes -->
<!-- Operations -->
<!-- Receptions -->
<!-- Extension Points -->
<!-- Parameters -->
<!-- Diagrams -->
<!-- Behavior -->
<!-- Action -->
<!-- Interaction -->
<!-- CombinedFragment -->
<!-- Activity -->
<!-- State Machine -->
<!-- State Machine -->
<!-- State -->
<!-- Vertex -->
<!-- Transition -->
<!-- Properties -->
<section>
<h3>Properties</h3>
<table class="table table-striped table-bordered">
<tr>
<th width="50%">Name</th>
<th width="50%">Value</th>
</tr>
<tr>
<td>name</td>
<td>bufferPool</td>
</tr>
<tr>
<td>stereotype</td>
<td><span class='label label-info'>null</span></td>
</tr>
<tr>
<td>visibility</td>
<td>public</td>
</tr>
<tr>
<td>isStatic</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isLeaf</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>type</td>
<td><a href='bf4d7b6ba93c684cb406e333c34358f5.html'><span class='node-icon _icon-UMLClass'></span>SslBufferPool</a></td>
</tr>
<tr>
<td>multiplicity</td>
<td></td>
</tr>
<tr>
<td>isReadOnly</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isOrdered</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isUnique</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>defaultValue</td>
<td></td>
</tr>
<tr>
<td>direction</td>
<td>in</td>
</tr>
</table>
</section>
<!-- Tags -->
<!-- Constraints, Dependencies, Dependants -->
<!-- Relationships -->
<!-- Owned Elements -->
</div>
</body>
</html>
| jiangbo212/netty-init | html-docs/contents/2d53f0aa53d93769b62c018cae522d87.html | HTML | lgpl-2.1 | 7,532 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_07) on Tue Jul 29 17:23:27 CEST 2008 -->
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Uses of Class org.fosstrak.reader.rprm.core.mgmt.agent.snmp.table.RowObjectContainerTest (reader 0.5.1-SNAPSHOT Test API)
</TITLE>
<META NAME="date" CONTENT="2008-07-29">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.fosstrak.reader.rprm.core.mgmt.agent.snmp.table.RowObjectContainerTest (reader 0.5.1-SNAPSHOT Test API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../org/fosstrak/reader/rprm/core/mgmt/agent/snmp/table/RowObjectContainerTest.html" title="class in org.fosstrak.reader.rprm.core.mgmt.agent.snmp.table"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../../../../index.html?org/fosstrak/reader/rprm/core/mgmt/agent/snmp/table/\class-useRowObjectContainerTest.html" target="_top"><B>FRAMES</B></A>
<A HREF="RowObjectContainerTest.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.fosstrak.reader.rprm.core.mgmt.agent.snmp.table.RowObjectContainerTest</B></H2>
</CENTER>
No usage of org.fosstrak.reader.rprm.core.mgmt.agent.snmp.table.RowObjectContainerTest
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../org/fosstrak/reader/rprm/core/mgmt/agent/snmp/table/RowObjectContainerTest.html" title="class in org.fosstrak.reader.rprm.core.mgmt.agent.snmp.table"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../../../../index.html?org/fosstrak/reader/rprm/core/mgmt/agent/snmp/table/\class-useRowObjectContainerTest.html" target="_top"><B>FRAMES</B></A>
<A HREF="RowObjectContainerTest.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2008. All Rights Reserved.
</BODY>
</HTML>
| Fosstrak/fosstrak.github.io | reader/testapidocs/org/fosstrak/reader/rprm/core/mgmt/agent/snmp/table/class-use/RowObjectContainerTest.html | HTML | lgpl-2.1 | 6,847 |
#region netDxf library licensed under the MIT License
//
// netDxf library
// Copyright (c) 2019-2021 Daniel Carvajal (haplokuon@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
namespace netDxf
{
/// <summary>
/// Represent a cubic bezier curve.
/// </summary>
public class BezierCurveCubic :
BezierCurve
{
#region constructors
/// <summary>
/// Initializes a new instance of the <c>BezierCurve</c> class.
/// </summary>
/// <param name="controlPoints">A list of four control points.</param>
/// <remarks>
/// The list must contain four control points.
/// The first index represents the start point or anchor,
/// the second represents the first control point,
/// the third the second control point,
/// and the last the end point.
/// </remarks>
public BezierCurveCubic(IEnumerable<Vector3> controlPoints)
: base(controlPoints)
{
}
/// <summary>
/// Initializes a new instance of the <c>BezierCurve</c> class.
/// </summary>
/// <param name="startPoint">Start anchor point.</param>
/// <param name="firstControlPoint">First control point.</param>
/// <param name="secondControlPoint">Second control point.</param>
/// <param name="endPoint">End anchor point.</param>
public BezierCurveCubic(Vector3 startPoint, Vector3 firstControlPoint, Vector3 secondControlPoint, Vector3 endPoint)
: base(new[]{startPoint, firstControlPoint, secondControlPoint, endPoint})
{
}
#endregion
#region public properties
/// <summary>
/// Gets or sets the curve start point.
/// </summary>
public Vector3 StartPoint
{
get { return this.controlPoints[0]; }
set { this.controlPoints[0] = value; }
}
/// <summary>
/// Gets or sets the first control point.
/// </summary>
public Vector3 FirstControlPoint
{
get { return this.controlPoints[1]; }
set { this.controlPoints[1] = value; }
}
/// <summary>
/// Gets or sets the second control point.
/// </summary>
public Vector3 SecondControlPoint
{
get { return this.controlPoints[2]; }
set { this.controlPoints[2] = value; }
}
/// <summary>
/// Gets or sets the curve end point.
/// </summary>
public Vector3 EndPoint
{
get { return this.controlPoints[3]; }
set { this.controlPoints[3] = value; }
}
#endregion
#region public methods
/// <summary>
/// Obtains a point along the curve at parameter t.
/// </summary>
/// <param name="t">Parameter t, between 0.0 and 1.0.</param>
/// <returns>A point along the curve.</returns>
public Vector3 CalculatePoint(double t)
{
if (t < 0.0 || t > 1.0)
{
throw new ArgumentOutOfRangeException(nameof(t), t, "The parameter t must be between 0.0 and 1.0.");
}
double c = 1.0 - t;
double c2 = c * c;
double c3 = c2 * c;
double t2 = t * t;
double t3 = t2 * t;
Vector3 point = new Vector3
{
X = this.StartPoint.X * c3 + this.FirstControlPoint.X * 3 * t * c2 + this.SecondControlPoint.X * 3 * t2 * c + this.EndPoint.X * t3,
Y = this.StartPoint.Y * c3 + this.FirstControlPoint.Y * 3 * t * c2 + this.SecondControlPoint.Y * 3 * t2 * c + this.EndPoint.Y * t3,
Z = this.StartPoint.Z * c3 + this.FirstControlPoint.Z * 3 * t * c2 + this.SecondControlPoint.Z * 3 * t2 * c + this.EndPoint.Z * t3
};
return point;
}
/// <summary>
/// Splits the actual bezier curve in two at parameter t.
/// </summary>
/// <param name="t">Parameter t, between 0.0 and 1.0.</param>
/// <returns>The two curves result of dividing the actual curve at parameter t.</returns>
public BezierCurveCubic[] Split(double t)
{
if (t < 0.0 || t > 1.0)
{
throw new ArgumentOutOfRangeException(nameof(t), t, "The parameter t must be between 0.0 and 1.0.");
}
Vector3 p12 = (this.FirstControlPoint - this.StartPoint) * t + this.StartPoint;
Vector3 p23 = (this.SecondControlPoint - this.FirstControlPoint) * t + this.FirstControlPoint;
Vector3 p123 = (p23 - p12) * t + p12;
Vector3 p34 = (this.EndPoint - this.SecondControlPoint) * t + this.SecondControlPoint;
Vector3 p234 = (p34 - p23) * t + p23;
Vector3 breakPoint = (p234 - p123) * t + p123;
return new[]
{
new BezierCurveCubic(this.StartPoint, p12, p123, breakPoint),
new BezierCurveCubic(breakPoint, p234, p34, this.EndPoint)
};
}
/// <summary>
/// Switch the bezier curve direction.
/// </summary>
public void Reverse()
{
Array.Reverse(this.controlPoints);
}
/// <summary>
/// Converts the bezier curve in a list of vertexes.
/// </summary>
/// <param name="precision">Number of vertexes generated.</param>
/// <returns>A list vertexes that represents the bezier curve.</returns>
public List<Vector3> PolygonalVertexes(int precision)
{
if (precision < 2)
{
throw new ArgumentOutOfRangeException(nameof(precision), precision, "The precision must be equal or greater than two.");
}
List<Vector3> vertexes = new List<Vector3>();
double delta = 1.0 / (precision - 1);
for (int i = 0; i < precision; i++)
{
double t = delta * i;
vertexes.Add(this.CalculatePoint(t));
}
return vertexes;
}
/// <summary>
/// Generate a list of continuous cubic bezier curves that passes through a set of points.
/// </summary>
/// <param name="fitPoints">List of points.</param>
/// <returns>A list of cubic bezier curves.</returns>
/// <returns>
/// Original https://www.codeproject.com/Articles/31859/Draw-a-Smooth-Curve-through-a-Set-of-2D-Points-wit by Oleg V. Polikarpotchkin and Peter Lee.
/// Modified to allow the use of 3D points, and other minor changes to accomodate the existing classes of this library.<br />
/// The total number of curves returned will be equal to the number of fit points minus 1,
/// therefore this method is not suitable to use over large number of fit points,
/// where other, more computational heavy methods, like the least-squares bezier curve fitting would return a less amount of curves.
/// In such cases, it is advisable to perform some method to reduce the number of points and to avoid duplicates or very close points.
/// </returns>
public static List<BezierCurveCubic> CreateFromFitPoints(IEnumerable<Vector3> fitPoints)
{
if (fitPoints == null)
{
throw new ArgumentNullException(nameof(fitPoints));
}
Vector3[] points = fitPoints.ToArray();
int numFitPoints = points.Length;
if (numFitPoints < 2)
{
throw new ArgumentOutOfRangeException(nameof(fitPoints), numFitPoints, "At least two fit points required.");
}
int n = numFitPoints - 1;
List<BezierCurveCubic> curves = new List<BezierCurveCubic>();
Vector3 firstControlPoint;
Vector3 secondControlPoint;
if (n == 1)
{
// Special case: Bezier curve should be a straight line.
firstControlPoint = points[0] + (points[1] - points[0]) / 3;
secondControlPoint = points[1] + (points[0] - points[1]) / 3;
curves.Add(new BezierCurveCubic(points[0], firstControlPoint, secondControlPoint, points[1]));
return curves;
}
// Calculate first Bezier control points
// Right hand side vector
double[] rhs = new double[n];
// Set right hand side X values
for (int i = 1; i < n - 1; i++)
{
rhs[i] = 4.0 * points[i].X + 2.0 * points[i + 1].X;
}
rhs[0] = points[0].X + 2.0 * points[1].X;
rhs[n - 1] = (8.0 * points[n - 1].X + points[n].X) / 2.0;
// Get first control points X-values
double[] x = GetFirstControlPoints(rhs);
// Set right hand side Y values
for (int i = 1; i < n - 1; i++)
{
rhs[i] = 4.0 * points[i].Y + 2.0 * points[i + 1].Y;
}
rhs[0] = points[0].Y + 2 * points[1].Y;
rhs[n - 1] = (8.0 * points[n - 1].Y + points[n].Y) / 2.0;
// Get first control points Y-values
double[] y = GetFirstControlPoints(rhs);
// Set right hand side Y values
for (int i = 1; i < n - 1; i++)
{
rhs[i] = 4.0 * points[i].Z + 2.0 * points[i + 1].Z;
}
rhs[0] = points[0].Z + 2 * points[1].Z;
rhs[n - 1] = (8.0 * points[n - 1].Z + points[n].Z) / 2.0;
// Get first control points Z-values
double[] z = GetFirstControlPoints(rhs);
// create the curves
for (int i = 0; i < n; i++)
{
// First control point
firstControlPoint = new Vector3(x[i], y[i], z[i]);
// Second control point
if (i < n - 1)
{
secondControlPoint = new Vector3(
2 * points[i + 1].X - x[i + 1],
2 * points[i + 1].Y - y[i + 1],
2 * points[i + 1].Z - z[i + 1]);
}
else
{
secondControlPoint = new Vector3(
(points[n].X + x[n - 1]) / 2.0,
(points[n].Y + y[n - 1]) / 2.0,
(points[n].Z + z[n - 1]) / 2.0);
}
curves.Add(new BezierCurveCubic(points[i], firstControlPoint, secondControlPoint, points[i+1]));
}
return curves;
}
#endregion
#region private methods
/// <summary>
/// Solves a tri-diagonal system for one of coordinates (X, Y, or Z) of first Bezier control points.
/// </summary>
/// <param name="rhs">Right hand side vector.</param>
/// <returns>Solution vector.</returns>
private static double[] GetFirstControlPoints(double[] rhs)
{
int n = rhs.Length;
double[] x = new double[n]; // Solution vector.
double[] tmp = new double[n]; // Temp workspace.
double b = 2.0;
x[0] = rhs[0] / b;
for (int i = 1; i < n; i++) // Decomposition and forward substitution.
{
tmp[i] = 1 / b;
b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
x[i] = (rhs[i] - x[i - 1]) / b;
}
for (int i = 1; i < n; i++)
{
x[n - i - 1] -= tmp[n - i] * x[n - i]; // Back substitution.
}
return x;
}
#endregion
}
} | haplokuon/netDxf | netDxf/BezierCurveCubic.cs | C# | lgpl-2.1 | 12,917 |
// -*- C++ -*-
/* GG is a GUI for SDL and OpenGL.
Copyright (C) 2003-2008 T. Zachary Laine
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., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
If you do not wish to comply with the terms of the LGPL please
contact the author as other terms are available for a fee.
Zach Laine
whatwasthataddress@gmail.com */
/** \file MultiEditFwd.h \brief Contains forward declaration of the MultiEdit
class, and the MultiEditStyle flags. */
#ifndef _GG_MultiEditFwd_h_
#define _GG_MultiEditFwd_h_
#include <GG/Flags.h>
namespace GG {
class MultiEdit;
/** The styles of display and interaction for a MultiEdit. */
GG_FLAG_TYPE(MultiEditStyle);
extern GG_API const MultiEditStyle MULTI_NONE; ///< Default style selected.
extern GG_API const MultiEditStyle MULTI_WORDBREAK; ///< Breaks words. Lines are automatically broken between words if a word would extend past the edge of the control's bounding rectangle. (As always, a '\\n' also breaks the line.)
extern GG_API const MultiEditStyle MULTI_LINEWRAP; ///< Lines are automatically broken when the next character (or space) would be drawn outside the the text rectangle.
extern GG_API const MultiEditStyle MULTI_VCENTER; ///< Vertically centers text.
extern GG_API const MultiEditStyle MULTI_TOP; ///< Aligns text to the top.
extern GG_API const MultiEditStyle MULTI_BOTTOM; ///< Aligns text to the bottom.
extern GG_API const MultiEditStyle MULTI_CENTER; ///< Centers text.
extern GG_API const MultiEditStyle MULTI_LEFT; ///< Aligns text to the left.
extern GG_API const MultiEditStyle MULTI_RIGHT; ///< Aligns text to the right.
extern GG_API const MultiEditStyle MULTI_READ_ONLY; ///< The control is not user-interactive, only used to display text. Text can still be programmatically altered and selected.
extern GG_API const MultiEditStyle MULTI_TERMINAL_STYLE; ///< The text in the control is displayed so that the bottom is visible, instead of the top.
extern GG_API const MultiEditStyle MULTI_INTEGRAL_HEIGHT; ///< The height of the control will always be a multiple of the height of one row (fractions rounded down).
extern GG_API const MultiEditStyle MULTI_NO_VSCROLL; ///< Vertical scrolling is not available, and there is no vertical scroll bar.
extern GG_API const MultiEditStyle MULTI_NO_HSCROLL; ///< Horizontal scrolling is not available, and there is no horizontal scroll bar.
extern GG_API const Flags<MultiEditStyle> MULTI_NO_SCROLL; ///< Scrolls are not used for this control.
}
#endif
| tzlaine/GG | GG/MultiEditFwd.h | C | lgpl-2.1 | 3,284 |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- q3asciicache.qdoc -->
<head>
<title>Qt 4.6: Q3AsciiCache Class Reference</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<a name="//apple_ref/cpp/cl//Q3AsciiCache"></a>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://qt.nokia.com/"><img src="images/qt-logo.png" align="left" border="0" /></a></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="functions.html"><font color="#004faf">All Functions</font></a> · <a href="overviews.html"><font color="#004faf">Overviews</font></a></td></tr></table><h1 class="title">Q3AsciiCache Class Reference<br /><span class="small-subtitle">[<a href="qt3support.html">Qt3Support</a> module]</span>
</h1>
<p>The Q3AsciiCache class is a template class that provides a cache based on char* keys. <a href="#details">More...</a></p>
<pre> #include <Q3AsciiCache></pre><p><b>This class is part of the Qt 3 support library.</b> It is provided to keep old source code working. We strongly advise against using it in new code. See <a href="porting4.html">Porting to Qt 4</a> for more information.</p>
<p>Inherits <a href="q3ptrcollection.html">Q3PtrCollection</a>.</p>
<ul>
<li><a href="q3asciicache-members.html">List of all members, including inherited members</a></li>
</ul>
<hr />
<a name="public-functions"></a>
<h2>Public Functions</h2>
<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#Q3AsciiCache">Q3AsciiCache</a></b> ( int <i>maxCost</i> = 100, int <i>size</i> = 17, bool <i>caseSensitive</i> = true, bool <i>copyKeys</i> = true )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#dtor.Q3AsciiCache">~Q3AsciiCache</a></b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">type * </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#find">find</a></b> ( const char * <i>k</i>, bool <i>ref</i> = true ) const</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#insert">insert</a></b> ( const char * <i>k</i>, const type * <i>d</i>, int <i>c</i> = 1, int <i>p</i> = 0 )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#isEmpty">isEmpty</a></b> () const</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#maxCost">maxCost</a></b> () const</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#remove">remove</a></b> ( const char * <i>k</i> )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#setMaxCost">setMaxCost</a></b> ( int <i>m</i> )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">uint </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#size">size</a></b> () const</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#statistics">statistics</a></b> () const</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">type * </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#take">take</a></b> ( const char * <i>k</i> )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#totalCost">totalCost</a></b> () const</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">type * </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#operator-5b-5d">operator[]</a></b> ( const char * <i>k</i> ) const</td></tr>
</table>
<hr />
<a name="reimplemented-public-functions"></a>
<h2>Reimplemented Public Functions</h2>
<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#clear">clear</a></b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual uint </td><td class="memItemRight" valign="bottom"><b><a href="q3asciicache.html#count">count</a></b> () const</td></tr>
</table>
<ul>
<li><div bar="2" class="fn"></div>4 public functions inherited from <a href="q3ptrcollection.html#public-functions">Q3PtrCollection</a></li>
</ul>
<h3>Additional Inherited Members</h3>
<ul>
<li><div class="fn"></div>2 protected functions inherited from <a href="q3ptrcollection.html#protected-functions">Q3PtrCollection</a></li>
</ul>
<a name="details"></a>
<hr />
<h2>Detailed Description</h2>
<p>The Q3AsciiCache class is a template class that provides a cache based on char* keys.</p>
<p>Q3AsciiCache is implemented as a template class. Define a template instance Q3AsciiCache<X> to create a cache that operates on pointers to X (X*).</p>
<p>A cache is a least recently used (LRU) list of cache items. The cache items are accessed via <tt>char*</tt> keys. For Unicode keys use the <a href="q3cache.html">Q3Cache</a> template instead, which uses <a href="qstring.html">QString</a> keys. A <a href="q3cache.html">Q3Cache</a> has the same performace as a Q3AsciiCache.</p>
<p>Each cache item has a cost. The sum of item costs, <a href="q3asciicache.html#totalCost">totalCost</a>(), will not exceed the maximum cache cost, <a href="q3asciicache.html#maxCost">maxCost</a>(). If inserting a new item would cause the total cost to exceed the maximum cost, the least recently used items in the cache are removed.</p>
<p>Apart from <a href="q3asciicache.html#insert">insert</a>(), by far the most important function is <a href="q3asciicache.html#find">find</a>() (which also exists as operator[]()). This function looks up an item, returns it, and by default marks it as being the most recently used item.</p>
<p>There are also methods to <a href="q3asciicache.html#remove">remove</a>() or <a href="q3asciicache.html#take">take</a>() an object from the cache. Calling <a href="q3ptrcollection.html#setAutoDelete">setAutoDelete(TRUE)</a> tells the cache to delete items that are removed. The default is to not delete items when then are removed (i.e., <a href="q3asciicache.html#remove">remove</a>() and <a href="q3asciicache.html#take">take</a>() are equivalent).</p>
<p>When inserting an item into the cache, only the pointer is copied, not the item itself. This is called a shallow copy. It is possible to make the cache copy all of the item's data (known as a deep copy) when an item is inserted. <a href="q3asciicache.html#insert">insert</a>() calls the virtual function <a href="q3ptrcollection.html#newItem">Q3PtrCollection::newItem</a>() for the item to be inserted. Inherit a cache and reimplement <a href="q3ptrcollection.html#newItem">newItem</a>() if you want deep copies.</p>
<p>When removing a cache item the virtual function <a href="q3ptrcollection.html#deleteItem">Q3PtrCollection::deleteItem</a>() is called. Its default implementation in Q3AsciiCache is to delete the item if <a href="q3ptrcollection.html#setAutoDelete">auto-deletion</a> is enabled.</p>
<p>There is a <a href="q3asciicacheiterator.html">Q3AsciiCacheIterator</a> which may be used to traverse the items in the cache in arbitrary order.</p>
<p>See also <a href="q3asciicacheiterator.html">Q3AsciiCacheIterator</a>, <a href="q3cache.html">Q3Cache</a>, and <a href="q3intcache.html">Q3IntCache</a>.</p>
<hr />
<h2>Member Function Documentation</h2>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/Q3AsciiCache"></a>
<h3 class="fn"><a name="Q3AsciiCache"></a>Q3AsciiCache::Q3AsciiCache ( int <i>maxCost</i> = 100, int <i>size</i> = 17, bool <i>caseSensitive</i> = true, bool <i>copyKeys</i> = true )</h3>
<p>Constructs a cache whose contents will never have a total cost greater than <i>maxCost</i> and which is expected to contain less than <i>size</i> items.</p>
<p><i>size</i> is actually the size of an internal hash array; it's usually best to make it prime and at least 50% bigger than the largest expected number of items in the cache.</p>
<p>Each inserted item has an associated cost. When inserting a new item, if the total cost of all items in the cache will exceed <i>maxCost</i>, the cache will start throwing out the older (least recently used) items until there is enough room for the new item to be inserted.</p>
<p>If <i>caseSensitive</i> is TRUE (the default), the cache keys are case sensitive; if it is FALSE, they are case-insensitive. Case-insensitive comparison only affects the 26 letters in US-ASCII. If <i>copyKeys</i> is TRUE (the default), <a href="q3asciicache.html" class="compat">Q3AsciiCache</a> makes a copy of the cache keys, otherwise it copies just the const char * pointer - slightly faster if you can guarantee that the keys will never change, but very risky.</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/~Q3AsciiCache"></a>
<h3 class="fn"><a name="dtor.Q3AsciiCache"></a>Q3AsciiCache::~Q3AsciiCache ()</h3>
<p>Removes all items from the cache and destroys it. All iterators that access this cache will be reset.</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/clear"></a>
<h3 class="fn"><a name="clear"></a>void Q3AsciiCache::clear () <tt> [virtual]</tt></h3>
<p>Reimplemented from <a href="q3ptrcollection.html#clear">Q3PtrCollection::clear</a>().</p>
<p>Removes all items from the cache, and deletes them if <a href="q3ptrcollection.html#setAutoDelete">auto-deletion</a> has been enabled.</p>
<p>All cache iterators that operate on this cache are reset.</p>
<p>See also <a href="q3asciicache.html#remove">remove</a>() and <a href="q3asciicache.html#take">take</a>().</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/count"></a>
<h3 class="fn"><a name="count"></a><a href="qtglobal.html#uint-typedef">uint</a> Q3AsciiCache::count () const <tt> [virtual]</tt></h3>
<p>Reimplemented from <a href="q3ptrcollection.html#count">Q3PtrCollection::count</a>().</p>
<p>Returns the number of items in the cache.</p>
<p>See also <a href="q3asciicache.html#totalCost">totalCost</a>() and <a href="q3asciicache.html#size">size</a>().</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/find"></a>
<h3 class="fn"><a name="find"></a>type * Q3AsciiCache::find ( const char * <i>k</i>, bool <i>ref</i> = true ) const</h3>
<p>Returns the item with key <i>k</i>, or 0 if the key does not exist in the cache. If <i>ref</i> is TRUE (the default), the item is moved to the front of the least recently used list.</p>
<p>If there are two or more items with equal keys, the one that was inserted last is returned.</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/insert"></a>
<h3 class="fn"><a name="insert"></a>bool Q3AsciiCache::insert ( const char * <i>k</i>, const type * <i>d</i>, int <i>c</i> = 1, int <i>p</i> = 0 )</h3>
<p>Inserts the item <i>d</i> into the cache using key <i>k</i>, and with an associated cost of <i>c</i>. Returns TRUE if the item is successfully inserted. Returns FALSE if the item is not inserted, for example, if the cost of the item exceeds <a href="q3asciicache.html#maxCost">maxCost</a>().</p>
<p>The cache's size is limited, and if the total cost is too high, <a href="q3asciicache.html" class="compat">Q3AsciiCache</a> will remove old, least recently used items until there is room for this new item.</p>
<p>Items with duplicate keys can be inserted.</p>
<p>The parameter <i>p</i> is internal and should be left at the default value (0).</p>
<p><b>Warning:</b> If this function returns FALSE, you must delete <i>d</i> yourself. Additionally, be very careful about using <i>d</i> after calling this function, because any other insertions into the cache, from anywhere in the application or within Qt itself, could cause the object to be discarded from the cache and the pointer to become invalid.</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/isEmpty"></a>
<h3 class="fn"><a name="isEmpty"></a>bool Q3AsciiCache::isEmpty () const</h3>
<p>Returns TRUE if the cache is empty; otherwise returns FALSE.</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/maxCost"></a>
<h3 class="fn"><a name="maxCost"></a>int Q3AsciiCache::maxCost () const</h3>
<p>Returns the maximum allowed total cost of the cache.</p>
<p>See also <a href="q3asciicache.html#setMaxCost">setMaxCost</a>() and <a href="q3asciicache.html#totalCost">totalCost</a>().</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/remove"></a>
<h3 class="fn"><a name="remove"></a>bool Q3AsciiCache::remove ( const char * <i>k</i> )</h3>
<p>Removes the item with key <i>k</i> and returns TRUE if the item was present in the cache; otherwise returns FALSE.</p>
<p>The item is deleted if auto-deletion has been enabled, i.e., if you have called <a href="q3ptrcollection.html#setAutoDelete">setAutoDelete(TRUE)</a>.</p>
<p>If there are two or more items with equal keys, the one that was inserted last is removed.</p>
<p>All iterators that refer to the removed item are set to point to the next item in the cache's traversal order.</p>
<p>See also <a href="q3asciicache.html#take">take</a>() and <a href="q3asciicache.html#clear">clear</a>().</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/setMaxCost"></a>
<h3 class="fn"><a name="setMaxCost"></a>void Q3AsciiCache::setMaxCost ( int <i>m</i> )</h3>
<p>Sets the maximum allowed total cost of the cache to <i>m</i>. If the current total cost is greater than <i>m</i>, some items are removed immediately.</p>
<p>See also <a href="q3asciicache.html#maxCost">maxCost</a>() and <a href="q3asciicache.html#totalCost">totalCost</a>().</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/size"></a>
<h3 class="fn"><a name="size"></a><a href="qtglobal.html#uint-typedef">uint</a> Q3AsciiCache::size () const</h3>
<p>Returns the size of the hash array used to implement the cache. This should be a bit bigger than <a href="q3asciicache.html#count">count</a>() is likely to be.</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/statistics"></a>
<h3 class="fn"><a name="statistics"></a>void Q3AsciiCache::statistics () const</h3>
<p>A debug-only utility function. Prints out cache usage, hit/miss, and distribution information using <a href="qtglobal.html#qDebug">qDebug</a>(). This function does nothing in the release library.</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/take"></a>
<h3 class="fn"><a name="take"></a>type * Q3AsciiCache::take ( const char * <i>k</i> )</h3>
<p>Takes the item associated with <i>k</i> out of the cache without deleting it and returns a pointer to the item taken out, or 0 if the key does not exist in the cache.</p>
<p>If there are two or more items with equal keys, the one that was inserted last is taken.</p>
<p>All iterators that refer to the taken item are set to point to the next item in the cache's traversal order.</p>
<p>See also <a href="q3asciicache.html#remove">remove</a>() and <a href="q3asciicache.html#clear">clear</a>().</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/totalCost"></a>
<h3 class="fn"><a name="totalCost"></a>int Q3AsciiCache::totalCost () const</h3>
<p>Returns the total cost of the items in the cache. This is an integer in the range 0 to <a href="q3asciicache.html#maxCost">maxCost</a>().</p>
<p>See also <a href="q3asciicache.html#setMaxCost">setMaxCost</a>().</p>
<a name="//apple_ref/cpp/instm/Q3AsciiCache/operator[]"></a>
<h3 class="fn"><a name="operator-5b-5d"></a>type * Q3AsciiCache::operator[] ( const char * <i>k</i> ) const</h3>
<p>Returns the item with key <i>k</i>, or 0 if <i>k</i> does not exist in the cache, and moves the item to the front of the least recently used list.</p>
<p>If there are two or more items with equal keys, the one that was inserted last is returned.</p>
<p>This is the same as find( k, TRUE ).</p>
<p>See also <a href="q3asciicache.html#find">find</a>().</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="40%" align="left">Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
<td width="20%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="40%" align="right"><div align="right">Qt 4.6.2</div></td>
</tr></table></div></address></body>
</html>
| kobolabs/qt-everywhere-opensource-src-4.6.2 | doc/html/q3asciicache.html | HTML | lgpl-2.1 | 17,007 |
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_line3d.h Interface for the GLC_Line3d class.
#ifndef GLC_LINE3D_H_
#define GLC_LINE3D_H_
#include <QMetaType>
#include "glc_vector3d.h"
#include "../glc_config.h"
//////////////////////////////////////////////////////////////////////
//! \class GLC_Line3d
/*! \brief GLC_Line3d : Math 3d line representation */
/*! GLC_Line3d is definined by a 3d point and a vector*/
//////////////////////////////////////////////////////////////////////
class GLC_LIB_EXPORT GLC_Line3d
{
//////////////////////////////////////////////////////////////////////
/*! @name Constructor / Destructor */
//@{
//////////////////////////////////////////////////////////////////////
public:
//! Default constructor
GLC_Line3d();
//! Construct a 3d line with the given 3d point and vector
GLC_Line3d(const GLC_Point3d& point, const GLC_Vector3d& vector);
//! Construct a 3d line with the given 3d line
GLC_Line3d(const GLC_Line3d& line);
//! Destructor
~GLC_Line3d();
//@}
//////////////////////////////////////////////////////////////////////
/*! \name Get Functions*/
//@{
//////////////////////////////////////////////////////////////////////
public:
//! Return the starting 3d point of this line
inline GLC_Point3d startingPoint() const
{return m_Point;}
//! Return the direction vector of this line
inline GLC_Vector3d direction() const
{return m_Vector;}
//@}
//////////////////////////////////////////////////////////////////////
/*! \name Set Functions*/
//@{
//////////////////////////////////////////////////////////////////////
public:
//! Set the starting point of this 3d line
inline void setStartingPoint(const GLC_Point3d& point)
{m_Point= point;}
//! Set the direction vector of this line
inline void setDirection(const GLC_Vector3d& direction)
{m_Vector= direction;}
//@}
//////////////////////////////////////////////////////////////////////
// Private Member
//////////////////////////////////////////////////////////////////////
private:
//! Starting point of the 3d line
GLC_Point3d m_Point;
//! Vector of the line
GLC_Vector3d m_Vector;
};
Q_DECLARE_METATYPE(GLC_Line3d)
#endif /* GLC_LINE3D_H_ */
| laumaya/GLC_lib | src/lib/maths/glc_line3d.h | C | lgpl-2.1 | 3,157 |
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qscreendriverfactory_qws.h"
#include "qscreen_qws.h"
#include "qapplication.h"
#include "qscreenlinuxfb_qws.h"
#include "qscreentransformed_qws.h"
#include "qscreenvfb_qws.h"
#include "qscreenmulti_qws_p.h"
#include "qscreenqnx_qws.h"
#include "qscreenintegrityfb_qws.h"
#include <stdlib.h>
#include "private/qfactoryloader_p.h"
#include "qscreendriverplugin_qws.h"
#ifndef QT_NO_QWS_DIRECTFB
#include "qdirectfbscreen.h"
#endif
#ifndef QT_NO_QWS_VNC
#include "qscreenvnc_qws.h"
#endif
QT_BEGIN_NAMESPACE
#if !defined(Q_OS_WIN32) || defined(QT_MAKEDLL)
#ifndef QT_NO_LIBRARY
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
(QScreenDriverFactoryInterface_iid,
QLatin1String("/gfxdrivers"), Qt::CaseInsensitive))
#endif //QT_NO_LIBRARY
#endif //QT_MAKEDLL
/*!
\class QScreenDriverFactory
\ingroup qws
\brief The QScreenDriverFactory class creates screen drivers in
Qt for Embedded Linux.
Note that this class is only available in \l{Qt for Embedded Linux}.
QScreenDriverFactory is used to detect and instantiate the
available screen drivers, allowing \l{Qt for Embedded Linux} to load the
preferred driver into the server application at runtime. The
create() function returns a QScreen object representing the screen
driver identified by a given key. The valid keys (i.e. the
supported drivers) can be retrieved using the keys() function.
\l{Qt for Embedded Linux} provides several built-in screen drivers. In
addition, custom screen drivers can be added using Qt's plugin
mechanism, i.e. by subclassing the QScreen class and creating a
screen driver plugin (QScreenDriverPlugin). See the
\l{Qt for Embedded Linux Display Management}{display management}
documentation for details.
\sa QScreen, QScreenDriverPlugin
*/
/*!
Creates the screen driver specified by the given \a key, using the
display specified by the given \a displayId.
Note that the keys are case-insensitive.
\sa keys()
*/
QScreen *QScreenDriverFactory::create(const QString& key, int displayId)
{
QString driver = key.toLower();
#if defined(Q_OS_QNX) && !defined(QT_NO_QWS_QNX)
if (driver == QLatin1String("qnx") || driver.isEmpty())
return new QQnxScreen(displayId);
#endif
#if defined(Q_OS_INTEGRITY) && !defined(QT_NO_QWS_INTEGRITY)
if (driver == QLatin1String("integrityfb") || driver.isEmpty())
return new QIntfbScreen(displayId);
#endif
#ifndef QT_NO_QWS_QVFB
if (driver == QLatin1String("qvfb") || driver.isEmpty())
return new QVFbScreen(displayId);
#endif
#ifndef QT_NO_QWS_LINUXFB
if (driver == QLatin1String("linuxfb") || driver.isEmpty())
return new QLinuxFbScreen(displayId);
#endif
#ifndef QT_NO_QWS_DIRECTFB
if (driver == QLatin1String("directfb") || driver.isEmpty())
return new QDirectFBScreen(displayId);
#endif
#ifndef QT_NO_QWS_TRANSFORMED
if (driver == QLatin1String("transformed"))
return new QTransformedScreen(displayId);
#endif
#ifndef QT_NO_QWS_VNC
if (driver == QLatin1String("vnc"))
return new QVNCScreen(displayId);
#endif
#ifndef QT_NO_QWS_MULTISCREEN
if (driver == QLatin1String("multi"))
return new QMultiScreen(displayId);
#endif
#if !defined(Q_OS_WIN32) || defined(QT_MAKEDLL)
#ifndef QT_NO_LIBRARY
if (QScreenDriverFactoryInterface *factory = qobject_cast<QScreenDriverFactoryInterface*>(loader()->instance(key)))
return factory->create(driver, displayId);
#endif
#endif
return 0;
}
/*!
Returns the list of valid keys, i.e. the available screen drivers.
\sa create()
*/
QStringList QScreenDriverFactory::keys()
{
QStringList list;
#if defined(Q_OS_QNX) && !defined(QT_NO_QWS_QNX)
list << QLatin1String("QNX");
#endif
#if defined(Q_OS_INTEGRITY) && !defined(QT_NO_QWS_INTEGRITY)
list << QLatin1String("INTEGRITYFB");
#endif
#ifndef QT_NO_QWS_QVFB
list << QLatin1String("QVFb");
#endif
#ifndef QT_NO_QWS_LINUXFB
list << QLatin1String("LinuxFb");
#endif
#ifndef QT_NO_QWS_TRANSFORMED
list << QLatin1String("Transformed");
#endif
#ifndef QT_NO_QWS_VNC
list << QLatin1String("VNC");
#endif
#ifndef QT_NO_QWS_MULTISCREEN
list << QLatin1String("Multi");
#endif
#if !defined(Q_OS_WIN32) || defined(QT_MAKEDLL)
#ifndef QT_NO_LIBRARY
QStringList plugins = loader()->keys();
for (int i = 0; i < plugins.size(); ++i) {
# ifdef QT_NO_QWS_QVFB
// give QVFb top priority for autodetection
if (plugins.at(i) == QLatin1String("QVFb"))
list.prepend(plugins.at(i));
else
# endif
if (!list.contains(plugins.at(i)))
list += plugins.at(i);
}
#endif //QT_NO_LIBRARY
#endif //QT_MAKEDLL
return list;
}
QT_END_NAMESPACE
| xkfz007/vlc | build/win32/include/qt4/src/gui/embedded/qscreendriverfactory_qws.cpp | C++ | lgpl-2.1 | 6,673 |
/*
* pkcs15.h: OpenSC PKCS#15 header file
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _OPENSC_PKCS15_H
#define _OPENSC_PKCS15_H
#ifdef __cplusplus
extern "C" {
#endif
#include "libopensc/opensc.h"
#define SC_PKCS15_CACHE_DIR ".eid"
#define SC_PKCS15_PIN_MAGIC 0x31415926
#define SC_PKCS15_MAX_PINS 8
#define SC_PKCS15_MAX_LABEL_SIZE 255
#define SC_PKCS15_MAX_ID_SIZE 255
/* When changing this value, change also initialisation of the
* static ASN1 variables, that use this macro,
* like for example, 'c_asn1_access_control_rules'
* in src/libopensc/asn1.c */
#define SC_PKCS15_MAX_ACCESS_RULES 8
struct sc_pkcs15_id {
u8 value[SC_PKCS15_MAX_ID_SIZE];
size_t len;
};
typedef struct sc_pkcs15_id sc_pkcs15_id_t;
#define SC_PKCS15_CO_FLAG_PRIVATE 0x00000001
#define SC_PKCS15_CO_FLAG_MODIFIABLE 0x00000002
#define SC_PKCS15_CO_FLAG_OBJECT_SEEN 0x80000000 /* for PKCS #11 module */
#define SC_PKCS15_PIN_FLAG_CASE_SENSITIVE 0x0001
#define SC_PKCS15_PIN_FLAG_LOCAL 0x0002
#define SC_PKCS15_PIN_FLAG_CHANGE_DISABLED 0x0004
#define SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED 0x0008
#define SC_PKCS15_PIN_FLAG_INITIALIZED 0x0010
#define SC_PKCS15_PIN_FLAG_NEEDS_PADDING 0x0020
#define SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN 0x0040
#define SC_PKCS15_PIN_FLAG_SO_PIN 0x0080
#define SC_PKCS15_PIN_FLAG_DISABLE_ALLOW 0x0100
#define SC_PKCS15_PIN_FLAG_INTEGRITY_PROTECTED 0x0200
#define SC_PKCS15_PIN_FLAG_CONFIDENTIALITY_PROTECTED 0x0400
#define SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA 0x0800
#define SC_PKCS15_PIN_TYPE_FLAGS_MASK \
( SC_PKCS15_PIN_FLAG_LOCAL | SC_PKCS15_PIN_FLAG_INITIALIZED \
| SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN | SC_PKCS15_PIN_FLAG_SO_PIN )
#define SC_PKCS15_PIN_TYPE_FLAGS_SOPIN \
( SC_PKCS15_PIN_FLAG_SO_PIN | SC_PKCS15_PIN_FLAG_INITIALIZED )
#define SC_PKCS15_PIN_TYPE_FLAGS_PIN_GLOBAL \
( SC_PKCS15_PIN_FLAG_INITIALIZED )
#define SC_PKCS15_PIN_TYPE_FLAGS_PIN_LOCAL \
( SC_PKCS15_PIN_FLAG_INITIALIZED | SC_PKCS15_PIN_FLAG_LOCAL)
#define SC_PKCS15_PIN_TYPE_FLAGS_PUK_GLOBAL \
( SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN \
| SC_PKCS15_PIN_FLAG_INITIALIZED )
#define SC_PKCS15_PIN_TYPE_FLAGS_PUK_LOCAL \
( SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN \
| SC_PKCS15_PIN_FLAG_INITIALIZED | SC_PKCS15_PIN_FLAG_LOCAL)
#define SC_PKCS15_PIN_TYPE_BCD 0
#define SC_PKCS15_PIN_TYPE_ASCII_NUMERIC 1
#define SC_PKCS15_PIN_TYPE_UTF8 2
#define SC_PKCS15_PIN_TYPE_HALFNIBBLE_BCD 3
#define SC_PKCS15_PIN_TYPE_ISO9564_1 4
#define SC_PKCS15_PIN_AUTH_TYPE_PIN 0
#define SC_PKCS15_PIN_AUTH_TYPE_BIOMETRIC 1
#define SC_PKCS15_PIN_AUTH_TYPE_AUTH_KEY 2
#define SC_PKCS15_PIN_AUTH_TYPE_SM_KEY 3
/* PinAttributes as they defined in PKCS#15 v1.1 for PIN authentication object */
struct sc_pkcs15_pin_attributes {
unsigned int flags, type;
size_t min_length, stored_length, max_length;
int reference;
u8 pad_char;
};
/* AuthKeyAttributes of the authKey authentication object */
struct sc_pkcs15_authkey_attributes {
int derived;
struct sc_pkcs15_id skey_id;
};
/* BiometricAttributes of the biometricTemplate authentication object */
struct sc_pkcs15_biometric_attributes {
unsigned int flags;
struct sc_object_id template_id;
/* ... */
};
struct sc_pkcs15_auth_info {
/* CommonAuthenticationObjectAttributes */
struct sc_pkcs15_id auth_id;
/* AuthObjectAttributes */
struct sc_path path;
unsigned auth_type;
union {
struct sc_pkcs15_pin_attributes pin;
struct sc_pkcs15_biometric_attributes bio;
struct sc_pkcs15_authkey_attributes authkey;
} attrs;
/* authentication method: CHV, SEN, SYMBOLIC, ... */
unsigned int auth_method;
int tries_left, max_tries;
int max_unlocks;
};
typedef struct sc_pkcs15_auth_info sc_pkcs15_auth_info_t;
#define SC_PKCS15_ALGO_OP_COMPUTE_CHECKSUM 0x01
#define SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE 0x02
#define SC_PKCS15_ALGO_OP_VERIFY_CHECKSUM 0x04
#define SC_PKCS15_ALGO_OP_VERIFY_SIGNATURE 0x08
#define SC_PKCS15_ALGO_OP_ENCIPHER 0x10
#define SC_PKCS15_ALGO_OP_DECIPHER 0x20
#define SC_PKCS15_ALGO_OP_HASH 0x40
#define SC_PKCS15_ALGO_OP_GENERATE_KEY 0x80
/* A large integer, big endian notation */
struct sc_pkcs15_bignum {
u8 * data;
size_t len;
};
typedef struct sc_pkcs15_bignum sc_pkcs15_bignum_t;
struct sc_pkcs15_der {
u8 * value;
size_t len;
};
typedef struct sc_pkcs15_der sc_pkcs15_der_t;
struct sc_pkcs15_u8 {
u8 * value;
size_t len;
};
typedef struct sc_pkcs15_u8 sc_pkcs15_u8_t;
struct sc_pkcs15_pubkey_rsa {
sc_pkcs15_bignum_t modulus;
sc_pkcs15_bignum_t exponent;
};
struct sc_pkcs15_prkey_rsa {
/* public components */
sc_pkcs15_bignum_t modulus;
sc_pkcs15_bignum_t exponent;
/* private components */
sc_pkcs15_bignum_t d;
sc_pkcs15_bignum_t p;
sc_pkcs15_bignum_t q;
/* optional CRT elements */
sc_pkcs15_bignum_t iqmp;
sc_pkcs15_bignum_t dmp1;
sc_pkcs15_bignum_t dmq1;
};
struct sc_pkcs15_pubkey_dsa {
sc_pkcs15_bignum_t pub;
sc_pkcs15_bignum_t p;
sc_pkcs15_bignum_t q;
sc_pkcs15_bignum_t g;
};
struct sc_pkcs15_prkey_dsa {
/* public components */
sc_pkcs15_bignum_t pub;
sc_pkcs15_bignum_t p;
sc_pkcs15_bignum_t q;
sc_pkcs15_bignum_t g;
/* private key */
sc_pkcs15_bignum_t priv;
};
/*
* The ecParameters can be presented as
* - named curve;
* - OID of named curve;
* - implicit parameters.
*/
struct sc_pkcs15_ec_parameters {
char *named_curve;
struct sc_object_id id;
struct sc_pkcs15_der der;
size_t field_length; /* in bits */
};
struct sc_pkcs15_gost_parameters {
struct sc_object_id key;
struct sc_object_id hash;
struct sc_object_id cipher;
};
struct sc_pkcs15_pubkey_ec {
struct sc_pkcs15_ec_parameters params;
struct sc_pkcs15_u8 ecpointQ; /* This is NOT DER, just value and length */
};
struct sc_pkcs15_prkey_ec {
struct sc_pkcs15_ec_parameters params;
sc_pkcs15_bignum_t privateD; /* note this is bignum */
struct sc_pkcs15_u8 ecpointQ; /* This is NOT DER, just value and length */
};
struct sc_pkcs15_pubkey_gostr3410 {
struct sc_pkcs15_gost_parameters params;
sc_pkcs15_bignum_t xy;
};
struct sc_pkcs15_prkey_gostr3410 {
struct sc_pkcs15_gost_parameters params;
sc_pkcs15_bignum_t d;
};
struct sc_pkcs15_pubkey {
int algorithm;
struct sc_algorithm_id * alg_id;
/* Decoded key */
union {
struct sc_pkcs15_pubkey_rsa rsa;
struct sc_pkcs15_pubkey_dsa dsa;
struct sc_pkcs15_pubkey_ec ec;
struct sc_pkcs15_pubkey_gostr3410 gostr3410;
} u;
};
typedef struct sc_pkcs15_pubkey sc_pkcs15_pubkey_t;
struct sc_pkcs15_prkey {
unsigned int algorithm;
/* TODO do we need: struct sc_algorithm_id * alg_id; */
union {
struct sc_pkcs15_prkey_rsa rsa;
struct sc_pkcs15_prkey_dsa dsa;
struct sc_pkcs15_prkey_ec ec;
struct sc_pkcs15_prkey_gostr3410 gostr3410;
} u;
};
typedef struct sc_pkcs15_prkey sc_pkcs15_prkey_t;
/* Enveloped objects can be used to provide additional
* protection to non-native private keys */
struct sc_pkcs15_enveloped_data {
/* recipient info */
sc_pkcs15_id_t id; /* key ID */
struct sc_algorithm_id ke_alg; /* key-encryption algo */
u8 *key; /* encrypted key */
size_t key_len;
struct sc_algorithm_id ce_alg; /* content-encryption algo */
u8 *content; /* encrypted content */
size_t content_len;
};
struct sc_pkcs15_cert {
int version;
u8 *serial;
size_t serial_len;
u8 *issuer;
size_t issuer_len;
u8 *subject;
size_t subject_len;
u8 *crl;
size_t crl_len;
struct sc_pkcs15_pubkey * key;
/* DER encoded raw cert */
struct sc_pkcs15_der data;
};
typedef struct sc_pkcs15_cert sc_pkcs15_cert_t;
struct sc_pkcs15_cert_info {
struct sc_pkcs15_id id; /* correlates to private key id */
int authority; /* boolean */
/* identifiers [2] SEQUENCE OF CredentialIdentifier{{KeyIdentifiers}} */
struct sc_path path;
struct sc_pkcs15_der value;
};
typedef struct sc_pkcs15_cert_info sc_pkcs15_cert_info_t;
struct sc_pkcs15_data {
u8 *data; /* DER encoded raw data object */
size_t data_len;
};
typedef struct sc_pkcs15_data sc_pkcs15_data_t;
struct sc_pkcs15_data_info {
/* FIXME: there is no pkcs15 ID in DataType */
struct sc_pkcs15_id id;
/* Identify the application:
* either or both may be set */
char app_label[SC_PKCS15_MAX_LABEL_SIZE];
struct sc_object_id app_oid;
struct sc_path path;
struct sc_pkcs15_der data;
};
typedef struct sc_pkcs15_data_info sc_pkcs15_data_info_t;
/* keyUsageFlags are the same for all key types */
#define SC_PKCS15_PRKEY_USAGE_ENCRYPT 0x01
#define SC_PKCS15_PRKEY_USAGE_DECRYPT 0x02
#define SC_PKCS15_PRKEY_USAGE_SIGN 0x04
#define SC_PKCS15_PRKEY_USAGE_SIGNRECOVER 0x08
#define SC_PKCS15_PRKEY_USAGE_WRAP 0x10
#define SC_PKCS15_PRKEY_USAGE_UNWRAP 0x20
#define SC_PKCS15_PRKEY_USAGE_VERIFY 0x40
#define SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER 0x80
#define SC_PKCS15_PRKEY_USAGE_DERIVE 0x100
#define SC_PKCS15_PRKEY_USAGE_NONREPUDIATION 0x200
#define SC_PKCS15_PRKEY_ACCESS_SENSITIVE 0x01
#define SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE 0x02
#define SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE 0x04
#define SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE 0x08
#define SC_PKCS15_PRKEY_ACCESS_LOCAL 0x10
#define SC_PKCS15_PARAMSET_GOSTR3410_A 1
#define SC_PKCS15_PARAMSET_GOSTR3410_B 2
#define SC_PKCS15_PARAMSET_GOSTR3410_C 3
#define SC_PKCS15_GOSTR3410_KEYSIZE 256
struct sc_pkcs15_keyinfo_gostparams
{
unsigned int gostr3410, gostr3411, gost28147;
};
/* AccessMode bit definitions specified in PKCS#15 v1.1
* and extended by IAS/ECC v1.0.1 specification. */
#define SC_PKCS15_ACCESS_RULE_MODE_READ 0x01
#define SC_PKCS15_ACCESS_RULE_MODE_UPDATE 0x02
#define SC_PKCS15_ACCESS_RULE_MODE_EXECUTE 0x04
#define SC_PKCS15_ACCESS_RULE_MODE_DELETE 0x08
#define SC_PKCS15_ACCESS_RULE_MODE_ATTRIBUTE 0x10
#define SC_PKCS15_ACCESS_RULE_MODE_PSO_CDS 0x20
#define SC_PKCS15_ACCESS_RULE_MODE_PSO_VERIFY 0x40
#define SC_PKCS15_ACCESS_RULE_MODE_PSO_DECRYPT 0x80
#define SC_PKCS15_ACCESS_RULE_MODE_PSO_ENCRYPT 0x100
#define SC_PKCS15_ACCESS_RULE_MODE_INT_AUTH 0x200
#define SC_PKCS15_ACCESS_RULE_MODE_EXT_AUTH 0x400
struct sc_pkcs15_accessrule {
unsigned access_mode;
struct sc_pkcs15_id auth_id;
};
typedef struct sc_pkcs15_accessrule sc_pkcs15_accessrule_t;
struct sc_pkcs15_key_params {
void *data;
size_t len;
void (*free_params)(void *);
};
/* From Windows Smart Card Minidriver Specification
* Version 7.06
*
* #define MAX_CONTAINER_NAME_LEN 39
* #define CONTAINER_MAP_VALID_CONTAINER 1
* #define CONTAINER_MAP_DEFAULT_CONTAINER 2
* typedef struct _CONTAINER_MAP_RECORD
* {
* WCHAR wszGuid [MAX_CONTAINER_NAME_LEN + 1];
* BYTE bFlags;
* BYTE bReserved;
* WORD wSigKeySizeBits;
* WORD wKeyExchangeKeySizeBits;
* } CONTAINER_MAP_RECORD, *PCONTAINER_MAP_RECORD;
*/
#define SC_MD_MAX_CONTAINER_NAME_LEN 39
#define SC_MD_CONTAINER_MAP_VALID_CONTAINER 0x01
#define SC_MD_CONTAINER_MAP_DEFAULT_CONTAINER 0x02
struct sc_md_cmap_record {
unsigned char *guid;
size_t guid_len;
unsigned flags;
unsigned keysize_sign;
unsigned keysize_keyexchange;
};
/* From Windows Smart Card Minidriver Specification
* Version 7.06
*
* typedef struct _CARD_CACHE_FILE_FORMAT
* {
* BYTE bVersion; // Cache version
* BYTE bPinsFreshness; // Card PIN
* WORD wContainersFreshness;
* WORD wFilesFreshness;
* } CARD_CACHE_FILE_FORMAT, *PCARD_CACHE_FILE_FORMAT;
*/
struct sc_md_cardcf {
unsigned char version;
unsigned char pin_freshness;
unsigned cont_freshness;
unsigned files_freshness;
};
struct sc_md_data {
struct sc_md_cardcf cardcf;
void *prop_data;
};
struct sc_pkcs15_prkey_info {
struct sc_pkcs15_id id; /* correlates to public certificate id */
unsigned int usage, access_flags;
int native, key_reference;
/* convert to union if other types are supported */
size_t modulus_length; /* RSA */
size_t field_length; /* EC in bits */
unsigned int algo_refs[SC_MAX_SUPPORTED_ALGORITHMS];
struct sc_pkcs15_der subject;
struct sc_pkcs15_key_params params;
struct sc_path path;
/* Used by minidriver and its on-card support */
struct sc_md_cmap_record cmap_record;
};
typedef struct sc_pkcs15_prkey_info sc_pkcs15_prkey_info_t;
struct sc_pkcs15_pubkey_info {
struct sc_pkcs15_id id; /* correlates to private key id */
unsigned int usage, access_flags;
int native, key_reference;
/* convert to union if other types are supported */
size_t modulus_length; /* RSA */
size_t field_length; /* EC in bits */
unsigned int algo_refs[SC_MAX_SUPPORTED_ALGORITHMS];
struct sc_pkcs15_der subject;
struct sc_pkcs15_key_params params;
struct sc_path path;
struct {
struct sc_pkcs15_der raw;
struct sc_pkcs15_der spki;
} direct;
};
typedef struct sc_pkcs15_pubkey_info sc_pkcs15_pubkey_info_t;
struct sc_pkcs15_skey_info {
struct sc_pkcs15_id id;
unsigned int usage, access_flags;
int native, key_reference;
size_t value_len;
unsigned long key_type;
int algo_refs[SC_MAX_SUPPORTED_ALGORITHMS];
struct sc_path path; /* if on card */
struct sc_pkcs15_der data;
};
typedef struct sc_pkcs15_skey_info sc_pkcs15_skey_info_t;
#define sc_pkcs15_skey sc_pkcs15_data
#define sc_pkcs15_skey_t sc_pkcs15_data_t
#define SC_PKCS15_TYPE_CLASS_MASK 0xF00
#define SC_PKCS15_TYPE_PRKEY 0x100
#define SC_PKCS15_TYPE_PRKEY_RSA 0x101
#define SC_PKCS15_TYPE_PRKEY_DSA 0x102
#define SC_PKCS15_TYPE_PRKEY_GOSTR3410 0x103
#define SC_PKCS15_TYPE_PRKEY_EC 0x104
#define SC_PKCS15_TYPE_PUBKEY 0x200
#define SC_PKCS15_TYPE_PUBKEY_RSA 0x201
#define SC_PKCS15_TYPE_PUBKEY_DSA 0x202
#define SC_PKCS15_TYPE_PUBKEY_GOSTR3410 0x203
#define SC_PKCS15_TYPE_PUBKEY_EC 0x204
#define SC_PKCS15_TYPE_SKEY 0x300
#define SC_PKCS15_TYPE_SKEY_GENERIC 0x301
#define SC_PKCS15_TYPE_SKEY_DES 0x302
#define SC_PKCS15_TYPE_SKEY_2DES 0x303
#define SC_PKCS15_TYPE_SKEY_3DES 0x304
#define SC_PKCS15_TYPE_CERT 0x400
#define SC_PKCS15_TYPE_CERT_X509 0x401
#define SC_PKCS15_TYPE_CERT_SPKI 0x402
#define SC_PKCS15_TYPE_DATA_OBJECT 0x500
#define SC_PKCS15_TYPE_AUTH 0x600
#define SC_PKCS15_TYPE_AUTH_PIN 0x601
#define SC_PKCS15_TYPE_AUTH_BIO 0x602
#define SC_PKCS15_TYPE_AUTH_AUTHKEY 0x603
#define SC_PKCS15_TYPE_TO_CLASS(t) (1 << ((t) >> 8))
#define SC_PKCS15_SEARCH_CLASS_PRKEY 0x0002U
#define SC_PKCS15_SEARCH_CLASS_PUBKEY 0x0004U
#define SC_PKCS15_SEARCH_CLASS_SKEY 0x0008U
#define SC_PKCS15_SEARCH_CLASS_CERT 0x0010U
#define SC_PKCS15_SEARCH_CLASS_DATA 0x0020U
#define SC_PKCS15_SEARCH_CLASS_AUTH 0x0040U
struct sc_pkcs15_object {
unsigned int type;
/* CommonObjectAttributes */
char label[SC_PKCS15_MAX_LABEL_SIZE]; /* zero terminated */
unsigned int flags;
struct sc_pkcs15_id auth_id;
int usage_counter;
int user_consent;
struct sc_pkcs15_accessrule access_rules[SC_PKCS15_MAX_ACCESS_RULES];
/* Object type specific data */
void *data;
/* emulated object pointer */
void *emulated;
struct sc_pkcs15_df *df; /* can be NULL, if object is 'floating' */
struct sc_pkcs15_object *next, *prev; /* used only internally */
struct sc_pkcs15_der content;
};
typedef struct sc_pkcs15_object sc_pkcs15_object_t;
/* PKCS #15 DF types */
#define SC_PKCS15_PRKDF 0
#define SC_PKCS15_PUKDF 1
#define SC_PKCS15_PUKDF_TRUSTED 2
#define SC_PKCS15_SKDF 3
#define SC_PKCS15_CDF 4
#define SC_PKCS15_CDF_TRUSTED 5
#define SC_PKCS15_CDF_USEFUL 6
#define SC_PKCS15_DODF 7
#define SC_PKCS15_AODF 8
#define SC_PKCS15_DF_TYPE_COUNT 9
struct sc_pkcs15_card;
struct sc_pkcs15_df {
struct sc_path path;
int record_length;
unsigned int type;
int enumerated;
struct sc_pkcs15_df *next, *prev;
};
typedef struct sc_pkcs15_df sc_pkcs15_df_t;
struct sc_pkcs15_unusedspace {
sc_path_t path;
sc_pkcs15_id_t auth_id;
struct sc_pkcs15_unusedspace *next, *prev;
};
typedef struct sc_pkcs15_unusedspace sc_pkcs15_unusedspace_t;
#define SC_PKCS15_CARD_MAGIC 0x10203040
typedef struct sc_pkcs15_sec_env_info {
int se;
struct sc_object_id owner;
struct sc_aid aid;
} sc_pkcs15_sec_env_info_t;
typedef struct sc_pkcs15_last_update {
char *gtime;
struct sc_path path;
} sc_pkcs15_last_update_t;
typedef struct sc_pkcs15_profile_indication {
struct sc_object_id oid;
char *name;
} sc_pkcs15_profile_indication_t;
typedef struct sc_pkcs15_tokeninfo {
unsigned int version;
unsigned int flags;
char *label;
char *serial_number;
char *manufacturer_id;
struct sc_pkcs15_last_update last_update;
struct sc_pkcs15_profile_indication profile_indication;
char *preferred_language;
sc_pkcs15_sec_env_info_t **seInfo;
size_t num_seInfo;
struct sc_supported_algo_info supported_algos[SC_MAX_SUPPORTED_ALGORITHMS];
} sc_pkcs15_tokeninfo_t;
struct sc_pkcs15_operations {
int (*parse_df)(struct sc_pkcs15_card *, struct sc_pkcs15_df *);
void (*clear)(struct sc_pkcs15_card *);
int (*get_guid)(struct sc_pkcs15_card *, const struct sc_pkcs15_object *,
unsigned char *, size_t *);
};
typedef struct sc_pkcs15_card {
sc_card_t *card;
unsigned int flags;
struct sc_app_info *app;
sc_file_t *file_app;
sc_file_t *file_tokeninfo, *file_odf, *file_unusedspace;
struct sc_pkcs15_df *df_list;
struct sc_pkcs15_object *obj_list;
sc_pkcs15_tokeninfo_t *tokeninfo;
sc_pkcs15_unusedspace_t *unusedspace_list;
int unusedspace_read;
struct sc_pkcs15_card_opts {
int use_file_cache;
int use_pin_cache;
int pin_cache_counter;
int pin_cache_ignore_user_consent;
} opts;
unsigned int magic;
void *dll_handle; /* shared lib for emulated cards */
struct sc_md_data *md_data; /* minidriver specific data */
struct sc_pkcs15_operations ops;
} sc_pkcs15_card_t;
/* flags suitable for sc_pkcs15_tokeninfo_t */
#define SC_PKCS15_TOKEN_READONLY 0x01
#define SC_PKCS15_TOKEN_LOGIN_REQUIRED 0x02 /* Don't use */
#define SC_PKCS15_TOKEN_PRN_GENERATION 0x04
#define SC_PKCS15_TOKEN_EID_COMPLIANT 0x08
/* flags suitable for struct sc_pkcs15_card */
#define SC_PKCS15_CARD_FLAG_EMULATED 0x02000000
/* sc_pkcs15_bind: Binds a card object to a PKCS #15 card object
* and initializes a new PKCS #15 card object. Will return
* SC_ERROR_PKCS15_APP_NOT_FOUND, if the card hasn't got a
* valid PKCS #15 file structure. */
int sc_pkcs15_bind(struct sc_card *card, struct sc_aid *aid,
struct sc_pkcs15_card **pkcs15_card);
/* sc_pkcs15_unbind: Releases a PKCS #15 card object, and frees any
* memory allocations done on the card object. */
int sc_pkcs15_unbind(struct sc_pkcs15_card *card);
int sc_pkcs15_get_objects(struct sc_pkcs15_card *card, unsigned int type,
struct sc_pkcs15_object **ret, size_t ret_count);
int sc_pkcs15_get_objects_cond(struct sc_pkcs15_card *card, unsigned int type,
int (* func)(struct sc_pkcs15_object *, void *),
void *func_arg,
struct sc_pkcs15_object **ret, size_t ret_count);
int sc_pkcs15_find_object_by_id(struct sc_pkcs15_card *, unsigned int,
const sc_pkcs15_id_t *,
struct sc_pkcs15_object **);
struct sc_pkcs15_card * sc_pkcs15_card_new(void);
void sc_pkcs15_card_free(struct sc_pkcs15_card *p15card);
void sc_pkcs15_card_clear(struct sc_pkcs15_card *p15card);
int sc_pkcs15_decipher(struct sc_pkcs15_card *p15card,
const struct sc_pkcs15_object *prkey_obj,
unsigned long flags,
const u8 *in, size_t inlen, u8 *out, size_t outlen);
int sc_pkcs15_derive(struct sc_pkcs15_card *p15card,
const struct sc_pkcs15_object *prkey_obj,
unsigned long flags,
const u8 *in, size_t inlen, u8 *out, unsigned long *poutlen);
int sc_pkcs15_compute_signature(struct sc_pkcs15_card *p15card,
const struct sc_pkcs15_object *prkey_obj,
unsigned long alg_flags, const u8 *in,
size_t inlen, u8 *out, size_t outlen);
int sc_pkcs15_read_pubkey(struct sc_pkcs15_card *,
const struct sc_pkcs15_object *, struct sc_pkcs15_pubkey **);
int sc_pkcs15_decode_pubkey_rsa(struct sc_context *,
struct sc_pkcs15_pubkey_rsa *, const u8 *, size_t);
int sc_pkcs15_encode_pubkey_rsa(struct sc_context *,
struct sc_pkcs15_pubkey_rsa *, u8 **, size_t *);
int sc_pkcs15_decode_pubkey_dsa(struct sc_context *,
struct sc_pkcs15_pubkey_dsa *, const u8 *, size_t);
int sc_pkcs15_encode_pubkey_dsa(struct sc_context *,
struct sc_pkcs15_pubkey_dsa *, u8 **, size_t *);
int sc_pkcs15_decode_pubkey_gostr3410(struct sc_context *,
struct sc_pkcs15_pubkey_gostr3410 *, const u8 *, size_t);
int sc_pkcs15_encode_pubkey_gostr3410(struct sc_context *,
struct sc_pkcs15_pubkey_gostr3410 *, u8 **, size_t *);
int sc_pkcs15_decode_pubkey_ec(struct sc_context *,
struct sc_pkcs15_pubkey_ec *, const u8 *, size_t);
int sc_pkcs15_encode_pubkey_ec(struct sc_context *,
struct sc_pkcs15_pubkey_ec *, u8 **, size_t *);
int sc_pkcs15_decode_pubkey(struct sc_context *,
struct sc_pkcs15_pubkey *, const u8 *, size_t);
int sc_pkcs15_encode_pubkey(struct sc_context *,
struct sc_pkcs15_pubkey *, u8 **, size_t *);
int sc_pkcs15_encode_pubkey_as_spki(struct sc_context *,
struct sc_pkcs15_pubkey *, u8 **, size_t *);
void sc_pkcs15_erase_pubkey(struct sc_pkcs15_pubkey *);
void sc_pkcs15_free_pubkey(struct sc_pkcs15_pubkey *);
int sc_pkcs15_pubkey_from_prvkey(struct sc_context *, struct sc_pkcs15_prkey *,
struct sc_pkcs15_pubkey **);
int sc_pkcs15_pubkey_from_cert(struct sc_context *, struct sc_pkcs15_der *,
struct sc_pkcs15_pubkey **);
int sc_pkcs15_pubkey_from_spki_file(struct sc_context *,
char *, struct sc_pkcs15_pubkey ** );
int sc_pkcs15_pubkey_from_spki_fields(struct sc_context *,
struct sc_pkcs15_pubkey **, u8 *, size_t, int);
int sc_pkcs15_encode_prkey(struct sc_context *,
struct sc_pkcs15_prkey *, u8 **, size_t *);
void sc_pkcs15_free_prkey(struct sc_pkcs15_prkey *prkey);
void sc_pkcs15_free_key_params(struct sc_pkcs15_key_params *params);
int sc_pkcs15_read_data_object(struct sc_pkcs15_card *p15card,
const struct sc_pkcs15_data_info *info,
struct sc_pkcs15_data **data_object_out);
int sc_pkcs15_find_data_object_by_id(struct sc_pkcs15_card *p15card,
const struct sc_pkcs15_id *id,
struct sc_pkcs15_object **out);
int sc_pkcs15_find_data_object_by_app_oid(struct sc_pkcs15_card *p15card,
const struct sc_object_id *app_oid,
struct sc_pkcs15_object **out);
int sc_pkcs15_find_data_object_by_name(struct sc_pkcs15_card *p15card,
const char *app_label,
const char *label,
struct sc_pkcs15_object **out);
void sc_pkcs15_free_data_object(struct sc_pkcs15_data *data_object);
int sc_pkcs15_read_certificate(struct sc_pkcs15_card *card,
const struct sc_pkcs15_cert_info *info,
struct sc_pkcs15_cert **cert);
void sc_pkcs15_free_certificate(struct sc_pkcs15_cert *cert);
int sc_pkcs15_find_cert_by_id(struct sc_pkcs15_card *card,
const struct sc_pkcs15_id *id,
struct sc_pkcs15_object **out);
/* sc_pkcs15_create_cdf: Creates a new certificate DF on a card pointed
* by <card>. Information about the file, such as the file ID, is read
* from <file>. <certs> has to be NULL-terminated. */
int sc_pkcs15_create_cdf(struct sc_pkcs15_card *card,
struct sc_file *file,
const struct sc_pkcs15_cert_info **certs);
int sc_pkcs15_create(struct sc_pkcs15_card *p15card, struct sc_card *card);
int sc_pkcs15_find_prkey_by_id(struct sc_pkcs15_card *card,
const struct sc_pkcs15_id *id,
struct sc_pkcs15_object **out);
int sc_pkcs15_find_prkey_by_id_usage(struct sc_pkcs15_card *card,
const struct sc_pkcs15_id *id,
unsigned int usage,
struct sc_pkcs15_object **out);
int sc_pkcs15_find_prkey_by_reference(struct sc_pkcs15_card *,
const sc_path_t *, int,
struct sc_pkcs15_object **);
int sc_pkcs15_find_pubkey_by_id(struct sc_pkcs15_card *card,
const struct sc_pkcs15_id *id,
struct sc_pkcs15_object **out);
int sc_pkcs15_find_skey_by_id(struct sc_pkcs15_card *card,
const struct sc_pkcs15_id *id,
struct sc_pkcs15_object **out);
int sc_pkcs15_verify_pin(struct sc_pkcs15_card *card,
struct sc_pkcs15_object *pin_obj,
const u8 *pincode, size_t pinlen);
int sc_pkcs15_change_pin(struct sc_pkcs15_card *card,
struct sc_pkcs15_object *pin_obj,
const u8 *oldpincode, size_t oldpinlen,
const u8 *newpincode, size_t newpinlen);
int sc_pkcs15_unblock_pin(struct sc_pkcs15_card *card,
struct sc_pkcs15_object *pin_obj,
const u8 *puk, size_t puklen,
const u8 *newpin, size_t newpinlen);
int sc_pkcs15_find_pin_by_auth_id(struct sc_pkcs15_card *card,
const struct sc_pkcs15_id *id,
struct sc_pkcs15_object **out);
int sc_pkcs15_find_pin_by_reference(struct sc_pkcs15_card *card,
const sc_path_t *path, int reference,
struct sc_pkcs15_object **out);
int sc_pkcs15_find_pin_by_type_and_reference(struct sc_pkcs15_card *card,
const sc_path_t *path, unsigned auth_method,
int reference,
struct sc_pkcs15_object **out);
int sc_pkcs15_find_so_pin(struct sc_pkcs15_card *card,
struct sc_pkcs15_object **out);
int sc_pkcs15_find_pin_by_flags(struct sc_pkcs15_card *p15card,
unsigned flags, unsigned mask, int *index,
struct sc_pkcs15_object **out);
void sc_pkcs15_pincache_add(struct sc_pkcs15_card *, struct sc_pkcs15_object *,
const u8 *, size_t);
int sc_pkcs15_pincache_revalidate(struct sc_pkcs15_card *p15card,
const struct sc_pkcs15_object *obj);
void sc_pkcs15_pincache_clear(struct sc_pkcs15_card *p15card);
int sc_pkcs15_encode_dir(struct sc_context *ctx,
struct sc_pkcs15_card *card,
u8 **buf, size_t *buflen);
int sc_pkcs15_parse_tokeninfo(struct sc_context *ctx,
sc_pkcs15_tokeninfo_t *ti,
const u8 *buf, size_t blen);
int sc_pkcs15_encode_tokeninfo(struct sc_context *ctx,
sc_pkcs15_tokeninfo_t *ti,
u8 **buf, size_t *buflen);
int sc_pkcs15_encode_odf(struct sc_context *ctx,
struct sc_pkcs15_card *card,
u8 **buf, size_t *buflen);
int sc_pkcs15_encode_df(struct sc_context *ctx,
struct sc_pkcs15_card *p15card,
struct sc_pkcs15_df *df,
u8 **buf, size_t *bufsize);
int sc_pkcs15_encode_cdf_entry(struct sc_context *ctx,
const struct sc_pkcs15_object *obj, u8 **buf,
size_t *bufsize);
int sc_pkcs15_encode_prkdf_entry(struct sc_context *ctx,
const struct sc_pkcs15_object *obj, u8 **buf,
size_t *bufsize);
int sc_pkcs15_encode_pukdf_entry(struct sc_context *ctx,
const struct sc_pkcs15_object *obj, u8 **buf,
size_t *bufsize);
int sc_pkcs15_encode_dodf_entry(struct sc_context *ctx,
const struct sc_pkcs15_object *obj, u8 **buf,
size_t *bufsize);
int sc_pkcs15_encode_aodf_entry(struct sc_context *ctx,
const struct sc_pkcs15_object *obj, u8 **buf,
size_t *bufsize);
int sc_pkcs15_parse_df(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_df *df);
int sc_pkcs15_read_df(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_df *df);
int sc_pkcs15_decode_cdf_entry(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj,
const u8 **buf, size_t *bufsize);
int sc_pkcs15_decode_dodf_entry(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj,
const u8 **buf, size_t *bufsize);
int sc_pkcs15_decode_aodf_entry(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj,
const u8 **buf, size_t *bufsize);
int sc_pkcs15_decode_prkdf_entry(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj,
const u8 **buf, size_t *bufsize);
int sc_pkcs15_decode_pukdf_entry(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj,
const u8 **buf, size_t *bufsize);
int sc_pkcs15_decode_skdf_entry(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj,
const u8 **buf, size_t *bufsize);
int sc_pkcs15_decode_enveloped_data(struct sc_context *ctx,
struct sc_pkcs15_enveloped_data *result,
const u8 *buf, size_t buflen);
int sc_pkcs15_encode_enveloped_data(struct sc_context *ctx,
struct sc_pkcs15_enveloped_data *data,
u8 **buf, size_t *buflen);
int sc_pkcs15_add_object(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj);
void sc_pkcs15_remove_object(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj);
int sc_pkcs15_add_df(struct sc_pkcs15_card *, unsigned int, const sc_path_t *);
int sc_pkcs15_add_unusedspace(struct sc_pkcs15_card *p15card,
const sc_path_t *path, const sc_pkcs15_id_t *auth_id);
int sc_pkcs15_parse_unusedspace(const u8 * buf, size_t buflen,
struct sc_pkcs15_card *card);
int sc_pkcs15_encode_unusedspace(struct sc_context *ctx,
struct sc_pkcs15_card *p15card,
u8 **buf, size_t *buflen);
/* Deduce private key attributes from cerresponding certificate */
int sc_pkcs15_prkey_attrs_from_cert(struct sc_pkcs15_card *, struct sc_pkcs15_object *,
struct sc_pkcs15_object **);
void sc_pkcs15_free_prkey_info(sc_pkcs15_prkey_info_t *key);
void sc_pkcs15_free_pubkey_info(sc_pkcs15_pubkey_info_t *key);
void sc_pkcs15_free_cert_info(sc_pkcs15_cert_info_t *cert);
void sc_pkcs15_free_data_info(sc_pkcs15_data_info_t *data);
void sc_pkcs15_free_auth_info(sc_pkcs15_auth_info_t *auth_info);
void sc_pkcs15_free_object(struct sc_pkcs15_object *obj);
/* Generic file i/o */
int sc_pkcs15_read_file(struct sc_pkcs15_card *p15card,
const struct sc_path *path,
u8 **buf, size_t *buflen);
/* Caching functions */
int sc_pkcs15_read_cached_file(struct sc_pkcs15_card *p15card,
const struct sc_path *path,
u8 **buf, size_t *bufsize);
int sc_pkcs15_cache_file(struct sc_pkcs15_card *p15card,
const struct sc_path *path,
const u8 *buf, size_t bufsize);
/* PKCS #15 ID handling functions */
int sc_pkcs15_compare_id(const struct sc_pkcs15_id *id1,
const struct sc_pkcs15_id *id2);
const char *sc_pkcs15_print_id(const struct sc_pkcs15_id *id);
void sc_pkcs15_format_id(const char *id_in, struct sc_pkcs15_id *id_out);
int sc_pkcs15_hex_string_to_id(const char *in, struct sc_pkcs15_id *out);
int sc_der_copy(struct sc_pkcs15_der *, const struct sc_pkcs15_der *);
int sc_pkcs15_get_object_id(const struct sc_pkcs15_object *, struct sc_pkcs15_id *);
int sc_pkcs15_get_object_guid(struct sc_pkcs15_card *, const struct sc_pkcs15_object *, unsigned,
unsigned char *, size_t *);
int sc_pkcs15_serialize_guid(unsigned char *, size_t, unsigned, char *, size_t);
int sc_encode_oid (struct sc_context *, struct sc_object_id *,
unsigned char **, size_t *);
/* Get application by type: 'protected', 'generic' */
struct sc_app_info *sc_pkcs15_get_application_by_type(struct sc_card *, char *);
/* Prepend 'parent' to 'child' in case 'child' is a relative path */
int sc_pkcs15_make_absolute_path(const sc_path_t *parent, sc_path_t *child);
/* Clean and free object content */
void sc_pkcs15_free_object_content(struct sc_pkcs15_object *);
/* Allocate and set object content */
int sc_pkcs15_allocate_object_content(struct sc_context *, struct sc_pkcs15_object *,
const unsigned char *, size_t);
struct sc_supported_algo_info *sc_pkcs15_get_supported_algo(struct sc_pkcs15_card *,
unsigned, unsigned);
int sc_pkcs15_add_supported_algo_ref(struct sc_pkcs15_object *,
struct sc_supported_algo_info *);
int sc_pkcs15_fix_ec_parameters(struct sc_context *, struct sc_pkcs15_ec_parameters *);
/* Convert the OpenSSL key data type into the OpenSC key */
int sc_pkcs15_convert_bignum(sc_pkcs15_bignum_t *dst, const void *bignum);
int sc_pkcs15_convert_prkey(struct sc_pkcs15_prkey *key, void *evp_key);
int sc_pkcs15_convert_pubkey(struct sc_pkcs15_pubkey *key, void *evp_key);
/* Get 'LastUpdate' string */
char *sc_pkcs15_get_lastupdate(struct sc_pkcs15_card *p15card);
/* Allocate generalized time string */
int sc_pkcs15_get_generalized_time(struct sc_context *ctx, char **out);
/* New object search API.
* More complex, but also more powerful.
*/
typedef struct sc_pkcs15_search_key {
unsigned int class_mask;
unsigned int type;
const sc_pkcs15_id_t * id;
const struct sc_object_id *app_oid;
const sc_path_t * path;
unsigned int usage_mask, usage_value;
unsigned int flags_mask, flags_value;
unsigned int match_reference : 1;
int reference;
const char * app_label;
const char * label;
} sc_pkcs15_search_key_t;
int sc_pkcs15_search_objects(struct sc_pkcs15_card *, sc_pkcs15_search_key_t *,
struct sc_pkcs15_object **, size_t);
/* This structure is passed to the new sc_pkcs15emu_*_init functions */
typedef struct sc_pkcs15emu_opt {
scconf_block *blk;
unsigned int flags;
} sc_pkcs15emu_opt_t;
#define SC_PKCS15EMU_FLAGS_NO_CHECK 0x00000001
extern int sc_pkcs15_bind_synthetic(struct sc_pkcs15_card *);
extern int sc_pkcs15_is_emulation_only(sc_card_t *);
int sc_pkcs15emu_object_add(struct sc_pkcs15_card *, unsigned int,
const struct sc_pkcs15_object *, const void *);
/* some wrapper functions for sc_pkcs15emu_object_add */
int sc_pkcs15emu_add_pin_obj(struct sc_pkcs15_card *,
const struct sc_pkcs15_object *, const sc_pkcs15_auth_info_t *);
int sc_pkcs15emu_add_rsa_prkey(struct sc_pkcs15_card *,
const struct sc_pkcs15_object *, const sc_pkcs15_prkey_info_t *);
int sc_pkcs15emu_add_rsa_pubkey(struct sc_pkcs15_card *,
const struct sc_pkcs15_object *, const sc_pkcs15_pubkey_info_t *);
int sc_pkcs15emu_add_ec_prkey(struct sc_pkcs15_card *,
const struct sc_pkcs15_object *, const sc_pkcs15_prkey_info_t *);
int sc_pkcs15emu_add_ec_pubkey(struct sc_pkcs15_card *,
const struct sc_pkcs15_object *, const sc_pkcs15_pubkey_info_t *);
int sc_pkcs15emu_add_x509_cert(struct sc_pkcs15_card *,
const struct sc_pkcs15_object *, const sc_pkcs15_cert_info_t *);
int sc_pkcs15emu_add_data_object(struct sc_pkcs15_card *,
const struct sc_pkcs15_object *, const sc_pkcs15_data_info_t *);
#ifdef __cplusplus
}
#endif
#endif
| puccia/OpenSC | src/libopensc/pkcs15.h | C | lgpl-2.1 | 34,394 |
/*
* libvirt-host.h
* Summary: APIs for management of hosts
* Description: Provides APIs for the management of hosts
*
* Copyright (C) 2006-2014 Red Hat, Inc.
*
* 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, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef LIBVIRT_HOST_H
# define LIBVIRT_HOST_H
# ifndef __VIR_LIBVIRT_H_INCLUDES__
# error "Don't include this file directly, only use libvirt/libvirt.h"
# endif
/**
* virConnect:
*
* a virConnect is a private structure representing a connection to
* the Hypervisor.
*/
typedef struct _virConnect virConnect;
/**
* virConnectPtr:
*
* a virConnectPtr is pointer to a virConnect private structure, this is the
* type used to reference a connection to the Hypervisor in the API.
*/
typedef virConnect *virConnectPtr;
/**
* virNodeSuspendTarget:
*
* Flags to indicate which system-wide sleep state the host must be
* transitioned to.
*/
typedef enum {
VIR_NODE_SUSPEND_TARGET_MEM = 0,
VIR_NODE_SUSPEND_TARGET_DISK = 1,
VIR_NODE_SUSPEND_TARGET_HYBRID = 2,
# ifdef VIR_ENUM_SENTINELS
VIR_NODE_SUSPEND_TARGET_LAST /* This constant is subject to change */
# endif
} virNodeSuspendTarget;
/**
* virStream:
*
* a virStream is a private structure representing a data stream.
*/
typedef struct _virStream virStream;
/**
* virStreamPtr:
*
* a virStreamPtr is pointer to a virStream private structure, this is the
* type used to reference a data stream in the API.
*/
typedef virStream *virStreamPtr;
/**
* VIR_SECURITY_LABEL_BUFLEN:
*
* Macro providing the maximum length of the virSecurityLabel label string.
* Note that this value is based on that used by Labeled NFS.
*/
# define VIR_SECURITY_LABEL_BUFLEN (4096 + 1)
/**
* virSecurityLabel:
*
* a virSecurityLabel is a structure filled by virDomainGetSecurityLabel(),
* providing the security label and associated attributes for the specified
* domain.
*/
typedef struct _virSecurityLabel virSecurityLabel;
struct _virSecurityLabel {
char label[VIR_SECURITY_LABEL_BUFLEN]; /* security label string */
int enforcing; /* 1 if security policy is being enforced for domain */
};
/**
* virSecurityLabelPtr:
*
* a virSecurityLabelPtr is a pointer to a virSecurityLabel.
*/
typedef virSecurityLabel *virSecurityLabelPtr;
/**
* VIR_SECURITY_MODEL_BUFLEN:
*
* Macro providing the maximum length of the virSecurityModel model string.
*/
# define VIR_SECURITY_MODEL_BUFLEN (256 + 1)
/**
* VIR_SECURITY_DOI_BUFLEN:
*
* Macro providing the maximum length of the virSecurityModel doi string.
*/
# define VIR_SECURITY_DOI_BUFLEN (256 + 1)
/**
* virSecurityModel:
*
* a virSecurityModel is a structure filled by virNodeGetSecurityModel(),
* providing the per-hypervisor security model and DOI attributes for the
* specified domain.
*/
typedef struct _virSecurityModel virSecurityModel;
struct _virSecurityModel {
char model[VIR_SECURITY_MODEL_BUFLEN]; /* security model string */
char doi[VIR_SECURITY_DOI_BUFLEN]; /* domain of interpretation */
};
/**
* virSecurityModelPtr:
*
* a virSecurityModelPtr is a pointer to a virSecurityModel.
*/
typedef virSecurityModel *virSecurityModelPtr;
/* data types related to virNodePtr */
/**
* virNodeInfoPtr:
*
* a virNodeInfo is a structure filled by virNodeGetInfo() and providing
* the information for the Node.
*/
typedef struct _virNodeInfo virNodeInfo;
struct _virNodeInfo {
char model[32]; /* string indicating the CPU model */
unsigned long memory; /* memory size in kilobytes */
unsigned int cpus; /* the number of active CPUs */
unsigned int mhz; /* expected CPU frequency, 0 if not known or
on unusual architectures */
unsigned int nodes; /* the number of NUMA cell, 1 for unusual NUMA
topologies or uniform memory access; check
capabilities XML for the actual NUMA topology */
unsigned int sockets; /* number of CPU sockets per node if nodes > 1,
1 in case of unusual NUMA topology */
unsigned int cores; /* number of cores per socket, total number of
processors in case of unusual NUMA topology*/
unsigned int threads; /* number of threads per core, 1 in case of
unusual numa topology */
};
/**
* VIR_NODE_CPU_STATS_FIELD_LENGTH:
*
* Macro providing the field length of virNodeCPUStats
*/
# define VIR_NODE_CPU_STATS_FIELD_LENGTH 80
/**
* VIR_NODE_CPU_STATS_ALL_CPUS:
*
* Value for specifying request for the total CPU time/utilization
*/
typedef enum {
VIR_NODE_CPU_STATS_ALL_CPUS = -1,
} virNodeGetCPUStatsAllCPUs;
/**
* VIR_NODE_CPU_STATS_KERNEL:
*
* Macro for the cumulative CPU time which was spent by the kernel,
* since the node booting up (in nanoseconds).
*/
# define VIR_NODE_CPU_STATS_KERNEL "kernel"
/**
* VIR_NODE_CPU_STATS_USER:
*
* The cumulative CPU time which was spent by user processes,
* since the node booting up (in nanoseconds).
*/
# define VIR_NODE_CPU_STATS_USER "user"
/**
* VIR_NODE_CPU_STATS_IDLE:
*
* The cumulative idle CPU time,
* since the node booting up (in nanoseconds).
*/
# define VIR_NODE_CPU_STATS_IDLE "idle"
/**
* VIR_NODE_CPU_STATS_IOWAIT:
*
* The cumulative I/O wait CPU time,
* since the node booting up (in nanoseconds).
*/
# define VIR_NODE_CPU_STATS_IOWAIT "iowait"
/**
* VIR_NODE_CPU_STATS_INTR:
*
* The cumulative interrupt CPU time,
* since the node booting up (in nanoseconds).
*/
# define VIR_NODE_CPU_STATS_INTR "intr"
/**
* VIR_NODE_CPU_STATS_UTILIZATION:
*
* The CPU utilization of a node.
* The usage value is in percent and 100% represents all CPUs of
* the node.
*/
# define VIR_NODE_CPU_STATS_UTILIZATION "utilization"
/**
* virNodeCPUStats:
*
* a virNodeCPUStats is a structure filled by virNodeGetCPUStats()
* providing information about the CPU stats of the node.
*/
typedef struct _virNodeCPUStats virNodeCPUStats;
struct _virNodeCPUStats {
char field[VIR_NODE_CPU_STATS_FIELD_LENGTH];
unsigned long long value;
};
/**
* VIR_NODE_MEMORY_STATS_FIELD_LENGTH:
*
* Macro providing the field length of virNodeMemoryStats
*/
# define VIR_NODE_MEMORY_STATS_FIELD_LENGTH 80
/**
* VIR_NODE_MEMORY_STATS_ALL_CELLS:
*
* Value for specifying request for the total memory of all cells.
*/
typedef enum {
VIR_NODE_MEMORY_STATS_ALL_CELLS = -1,
} virNodeGetMemoryStatsAllCells;
/**
* VIR_NODE_MEMORY_STATS_TOTAL:
*
* Macro for the total memory of specified cell:
* it represents the maximum memory.
*/
# define VIR_NODE_MEMORY_STATS_TOTAL "total"
/**
* VIR_NODE_MEMORY_STATS_FREE:
*
* Macro for the free memory of specified cell:
* On Linux, it includes buffer and cached memory, in case of
* VIR_NODE_MEMORY_STATS_ALL_CELLS.
*/
# define VIR_NODE_MEMORY_STATS_FREE "free"
/**
* VIR_NODE_MEMORY_STATS_BUFFERS:
*
* Macro for the buffer memory: On Linux, it is only returned in case of
* VIR_NODE_MEMORY_STATS_ALL_CELLS.
*/
# define VIR_NODE_MEMORY_STATS_BUFFERS "buffers"
/**
* VIR_NODE_MEMORY_STATS_CACHED:
*
* Macro for the cached memory: On Linux, it is only returned in case of
* VIR_NODE_MEMORY_STATS_ALL_CELLS.
*/
# define VIR_NODE_MEMORY_STATS_CACHED "cached"
/**
* virNodeMemoryStats:
*
* a virNodeMemoryStats is a structure filled by virNodeGetMemoryStats()
* providing information about the memory of the node.
*/
typedef struct _virNodeMemoryStats virNodeMemoryStats;
struct _virNodeMemoryStats {
char field[VIR_NODE_MEMORY_STATS_FIELD_LENGTH];
unsigned long long value;
};
/*
* VIR_NODE_MEMORY_SHARED_PAGES_TO_SCAN:
*
* Macro for typed parameter that represents how many present pages
* to scan before the shared memory service goes to sleep.
*/
# define VIR_NODE_MEMORY_SHARED_PAGES_TO_SCAN "shm_pages_to_scan"
/*
* VIR_NODE_MEMORY_SHARED_SLEEP_MILLISECS:
*
* Macro for typed parameter that represents how many milliseconds
* the shared memory service should sleep before next scan.
*/
# define VIR_NODE_MEMORY_SHARED_SLEEP_MILLISECS "shm_sleep_millisecs"
/*
* VIR_NODE_MEMORY_SHARED_PAGES_SHARED:
*
* Macro for typed parameter that represents how many the shared
* memory pages are being used.
*/
# define VIR_NODE_MEMORY_SHARED_PAGES_SHARED "shm_pages_shared"
/*
* VIR_NODE_MEMORY_SHARED_PAGES_SHARING:
*
* Macro for typed parameter that represents how many sites are
* sharing the pages i.e. how much saved.
*/
# define VIR_NODE_MEMORY_SHARED_PAGES_SHARING "shm_pages_sharing"
/*
* VIR_NODE_MEMORY_SHARED_PAGES_UNSHARED:
*
* Macro for typed parameter that represents how many pages unique
* but repeatedly checked for merging.
*/
# define VIR_NODE_MEMORY_SHARED_PAGES_UNSHARED "shm_pages_unshared"
/*
* VIR_NODE_MEMORY_SHARED_PAGES_VOLATILE:
*
* Macro for typed parameter that represents how many pages changing
* too fast to be placed in a tree.
*/
# define VIR_NODE_MEMORY_SHARED_PAGES_VOLATILE "shm_pages_volatile"
/*
* VIR_NODE_MEMORY_SHARED_FULL_SCANS:
*
* Macro for typed parameter that represents how many times all
* mergeable areas have been scanned.
*/
# define VIR_NODE_MEMORY_SHARED_FULL_SCANS "shm_full_scans"
/*
* VIR_NODE_MEMORY_SHARED_MERGE_ACROSS_NODES:
*
* Macro for typed parameter that represents whether pages from
* different NUMA nodes can be merged. The parameter has type int,
* when its value is 0, only pages which physically reside in the
* memory area of same NUMA node are merged; When its value is 1,
* pages from all nodes can be merged. Other values are reserved
* for future use.
*/
# define VIR_NODE_MEMORY_SHARED_MERGE_ACROSS_NODES "shm_merge_across_nodes"
int virNodeGetMemoryParameters(virConnectPtr conn,
virTypedParameterPtr params,
int *nparams,
unsigned int flags);
int virNodeSetMemoryParameters(virConnectPtr conn,
virTypedParameterPtr params,
int nparams,
unsigned int flags);
/*
* node CPU map
*/
int virNodeGetCPUMap(virConnectPtr conn,
unsigned char **cpumap,
unsigned int *online,
unsigned int flags);
/**
* VIR_NODEINFO_MAXCPUS:
* @nodeinfo: virNodeInfo instance
*
* This macro is to calculate the total number of CPUs supported
* but not necessary active in the host.
*/
# define VIR_NODEINFO_MAXCPUS(nodeinfo) ((nodeinfo).nodes*(nodeinfo).sockets*(nodeinfo).cores*(nodeinfo).threads)
/**
* virNodeInfoPtr:
*
* a virNodeInfoPtr is a pointer to a virNodeInfo structure.
*/
typedef virNodeInfo *virNodeInfoPtr;
/**
* virNodeCPUStatsPtr:
*
* a virNodeCPUStatsPtr is a pointer to a virNodeCPUStats structure.
*/
typedef virNodeCPUStats *virNodeCPUStatsPtr;
/**
* virNodeMemoryStatsPtr:
*
* a virNodeMemoryStatsPtr is a pointer to a virNodeMemoryStats structure.
*/
typedef virNodeMemoryStats *virNodeMemoryStatsPtr;
/**
*
* SEV Parameters
*/
/**
* VIR_NODE_SEV_PDH:
*
* Macro represents the Platform Diffie-Hellman key, as VIR_TYPED_PARAMS_STRING.
*/
# define VIR_NODE_SEV_PDH "pdh"
/**
* VIR_NODE_SEV_CERT_CHAIN:
*
* Macro represents the platform certificate chain that includes the platform
* endorsement key (PEK), owner certificate authority (OCD) and chip
* endorsement key (CEK), as VIR_TYPED_PARAMS_STRING.
*/
# define VIR_NODE_SEV_CERT_CHAIN "cert-chain"
/**
* VIR_NODE_SEV_CBITPOS:
*
* Macro represents the CBit Position used by hypervisor when SEV is enabled.
*/
# define VIR_NODE_SEV_CBITPOS "cbitpos"
/**
* VIR_NODE_SEV_REDUCED_PHYS_BITS:
*
* Macro represents the number of bits we lose in physical address space
* when SEV is enabled in the guest.
*/
# define VIR_NODE_SEV_REDUCED_PHYS_BITS "reduced-phys-bits"
int virNodeGetSEVInfo (virConnectPtr conn,
virTypedParameterPtr *params,
int *nparams,
unsigned int flags);
/**
* virConnectFlags
*
* Flags when opening a connection to a hypervisor
*/
typedef enum {
VIR_CONNECT_RO = (1 << 0), /* A readonly connection */
VIR_CONNECT_NO_ALIASES = (1 << 1), /* Don't try to resolve URI aliases */
} virConnectFlags;
typedef enum {
VIR_CRED_USERNAME = 1, /* Identity to act as */
VIR_CRED_AUTHNAME = 2, /* Identify to authorize as */
VIR_CRED_LANGUAGE = 3, /* RFC 1766 languages, comma separated */
VIR_CRED_CNONCE = 4, /* client supplies a nonce */
VIR_CRED_PASSPHRASE = 5, /* Passphrase secret */
VIR_CRED_ECHOPROMPT = 6, /* Challenge response */
VIR_CRED_NOECHOPROMPT = 7, /* Challenge response */
VIR_CRED_REALM = 8, /* Authentication realm */
VIR_CRED_EXTERNAL = 9, /* Externally managed credential */
# ifdef VIR_ENUM_SENTINELS
VIR_CRED_LAST /* More may be added - expect the unexpected */
# endif
} virConnectCredentialType;
struct _virConnectCredential {
int type; /* One of virConnectCredentialType constants */
const char *prompt; /* Prompt to show to user */
const char *challenge; /* Additional challenge to show */
const char *defresult; /* Optional default result */
char *result; /* Result to be filled with user response (or defresult) */
unsigned int resultlen; /* Length of the result */
};
typedef struct _virConnectCredential virConnectCredential;
typedef virConnectCredential *virConnectCredentialPtr;
/**
* virConnectAuthCallbackPtr:
* @cred: list of virConnectCredential object to fetch from user
* @ncred: size of cred list
* @cbdata: opaque data passed to virConnectOpenAuth
*
* When authentication requires one or more interactions, this callback
* is invoked. For each interaction supplied, data must be gathered
* from the user and filled in to the 'result' and 'resultlen' fields.
* If an interaction cannot be filled, fill in NULL and 0.
*
* Returns 0 if all interactions were filled, or -1 upon error
*/
typedef int (*virConnectAuthCallbackPtr)(virConnectCredentialPtr cred,
unsigned int ncred,
void *cbdata);
struct _virConnectAuth {
int *credtype; /* List of supported virConnectCredentialType values */
unsigned int ncredtype;
virConnectAuthCallbackPtr cb; /* Callback used to collect credentials */
void *cbdata;
};
typedef struct _virConnectAuth virConnectAuth;
typedef virConnectAuth *virConnectAuthPtr;
VIR_EXPORT_VAR virConnectAuthPtr virConnectAuthPtrDefault;
/**
* VIR_UUID_BUFLEN:
*
* This macro provides the length of the buffer required
* for virDomainGetUUID()
*/
# define VIR_UUID_BUFLEN (16)
/**
* VIR_UUID_STRING_BUFLEN:
*
* This macro provides the length of the buffer required
* for virDomainGetUUIDString()
*/
# define VIR_UUID_STRING_BUFLEN (36+1)
int virGetVersion (unsigned long *libVer,
const char *type,
unsigned long *typeVer);
/*
* Connection and disconnections to the Hypervisor
*/
int virInitialize (void);
virConnectPtr virConnectOpen (const char *name);
virConnectPtr virConnectOpenReadOnly (const char *name);
virConnectPtr virConnectOpenAuth (const char *name,
virConnectAuthPtr auth,
unsigned int flags);
int virConnectRef (virConnectPtr conn);
int virConnectClose (virConnectPtr conn);
/**
* VIR_CONNECT_IDENTITY_USER_NAME:
*
* The operating system user name as VIR_TYPED_PARAM_STRING.
*/
# define VIR_CONNECT_IDENTITY_USER_NAME "user-name"
/**
* VIR_CONNECT_IDENTITY_UNIX_USER_ID:
*
* The UNIX user ID as VIR_TYPED_PARAM_ULLONG.
*/
# define VIR_CONNECT_IDENTITY_UNIX_USER_ID "unix-user-id"
/**
* VIR_CONNECT_IDENTITY_GROUP_NAME:
*
* The operating system group name as VIR_TYPED_PARAM_STRING.
*/
# define VIR_CONNECT_IDENTITY_GROUP_NAME "group-name"
/**
* VIR_CONNECT_IDENTITY_UNIX_GROUP_ID:
*
* The UNIX group ID as VIR_TYPED_PARAM_ULLONG.
*/
# define VIR_CONNECT_IDENTITY_UNIX_GROUP_ID "unix-group-id"
/**
* VIR_CONNECT_IDENTITY_PROCESS_ID:
*
* The operating system process ID as VIR_TYPED_PARAM_LLONG.
*/
# define VIR_CONNECT_IDENTITY_PROCESS_ID "process-id"
/**
* VIR_CONNECT_IDENTITY_PROCESS_TIME:
*
* The operating system process start time as VIR_TYPED_PARAM_ULLONG.
*
* The units the time is measured in vary according to the
* host operating system. On Linux this is usually clock
* ticks (as reported in /proc/$PID/stat field 22).
*/
# define VIR_CONNECT_IDENTITY_PROCESS_TIME "process-time"
/**
* VIR_CONNECT_IDENTITY_SASL_USER_NAME:
*
* The SASL authenticated username as VIR_TYPED_PARAM_STRING
*/
# define VIR_CONNECT_IDENTITY_SASL_USER_NAME "sasl-user-name"
/**
* VIR_CONNECT_IDENTITY_X509_DISTINGUISHED_NAME:
*
* The TLS x509 certificate distinguished named as VIR_TYPED_PARAM_STRING
*/
# define VIR_CONNECT_IDENTITY_X509_DISTINGUISHED_NAME "x509-distinguished-name"
/**
* VIR_CONNECT_IDENTITY_SELINUX_CONTEXT:
*
* The application's SELinux context as VIR_TYPED_PARAM_STRING.
*/
# define VIR_CONNECT_IDENTITY_SELINUX_CONTEXT "selinux-context"
int virConnectSetIdentity (virConnectPtr conn,
virTypedParameterPtr params,
int nparams,
unsigned int flags);
const char * virConnectGetType (virConnectPtr conn);
int virConnectGetVersion (virConnectPtr conn,
unsigned long *hvVer);
int virConnectGetLibVersion (virConnectPtr conn,
unsigned long *libVer);
char * virConnectGetHostname (virConnectPtr conn);
char * virConnectGetURI (virConnectPtr conn);
char * virConnectGetSysinfo (virConnectPtr conn,
unsigned int flags);
int virConnectSetKeepAlive(virConnectPtr conn,
int interval,
unsigned int count);
/**
* virConnectCloseFunc:
* @conn: virConnect connection
* @reason: reason why the connection was closed (one of virConnectCloseReason)
* @opaque: opaque user data
*
* A callback function to be registered, and called when the connection
* is closed.
*/
typedef void (*virConnectCloseFunc)(virConnectPtr conn,
int reason,
void *opaque);
int virConnectRegisterCloseCallback(virConnectPtr conn,
virConnectCloseFunc cb,
void *opaque,
virFreeCallback freecb);
int virConnectUnregisterCloseCallback(virConnectPtr conn,
virConnectCloseFunc cb);
/*
* Capabilities of the connection / driver.
*/
int virConnectGetMaxVcpus (virConnectPtr conn,
const char *type);
int virNodeGetInfo (virConnectPtr conn,
virNodeInfoPtr info);
char * virConnectGetCapabilities (virConnectPtr conn);
int virNodeGetCPUStats (virConnectPtr conn,
int cpuNum,
virNodeCPUStatsPtr params,
int *nparams,
unsigned int flags);
int virNodeGetMemoryStats (virConnectPtr conn,
int cellNum,
virNodeMemoryStatsPtr params,
int *nparams,
unsigned int flags);
unsigned long long virNodeGetFreeMemory (virConnectPtr conn);
int virNodeGetSecurityModel (virConnectPtr conn,
virSecurityModelPtr secmodel);
int virNodeSuspendForDuration (virConnectPtr conn,
unsigned int target,
unsigned long long duration,
unsigned int flags);
/*
* NUMA support
*/
int virNodeGetCellsFreeMemory(virConnectPtr conn,
unsigned long long *freeMems,
int startCell,
int maxCells);
int virConnectIsEncrypted(virConnectPtr conn);
int virConnectIsSecure(virConnectPtr conn);
int virConnectIsAlive(virConnectPtr conn);
/*
* CPU specification API
*/
typedef enum {
VIR_CPU_COMPARE_ERROR = -1,
VIR_CPU_COMPARE_INCOMPATIBLE = 0,
VIR_CPU_COMPARE_IDENTICAL = 1,
VIR_CPU_COMPARE_SUPERSET = 2,
# ifdef VIR_ENUM_SENTINELS
VIR_CPU_COMPARE_LAST
# endif
} virCPUCompareResult;
typedef enum {
VIR_CONNECT_COMPARE_CPU_FAIL_INCOMPATIBLE = (1 << 0), /* treat incompatible
CPUs as failure */
} virConnectCompareCPUFlags;
int virConnectCompareCPU(virConnectPtr conn,
const char *xmlDesc,
unsigned int flags);
int virConnectCompareHypervisorCPU(virConnectPtr conn,
const char *emulator,
const char *arch,
const char *machine,
const char *virttype,
const char *xmlCPU,
unsigned int flags);
int virConnectGetCPUModelNames(virConnectPtr conn,
const char *arch,
char ***models,
unsigned int flags);
/**
* virConnectBaselineCPUFlags
*
* Flags when getting XML description of a computed CPU
*/
typedef enum {
VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES = (1 << 0), /* show all features */
VIR_CONNECT_BASELINE_CPU_MIGRATABLE = (1 << 1), /* filter out non-migratable features */
} virConnectBaselineCPUFlags;
char *virConnectBaselineCPU(virConnectPtr conn,
const char **xmlCPUs,
unsigned int ncpus,
unsigned int flags);
char *virConnectBaselineHypervisorCPU(virConnectPtr conn,
const char *emulator,
const char *arch,
const char *machine,
const char *virttype,
const char **xmlCPUs,
unsigned int ncpus,
unsigned int flags);
int virNodeGetFreePages(virConnectPtr conn,
unsigned int npages,
unsigned int *pages,
int startcell,
unsigned int cellcount,
unsigned long long *counts,
unsigned int flags);
typedef enum {
VIR_NODE_ALLOC_PAGES_ADD = 0, /* Add @pageCounts to the pages pool. This
can be used only to size up the pool. */
VIR_NODE_ALLOC_PAGES_SET = (1 << 0), /* Don't add @pageCounts, instead set
passed number of pages. This can be
used to free allocated pages. */
} virNodeAllocPagesFlags;
int virNodeAllocPages(virConnectPtr conn,
unsigned int npages,
unsigned int *pageSizes,
unsigned long long *pageCounts,
int startCell,
unsigned int cellCount,
unsigned int flags);
#endif /* LIBVIRT_HOST_H */
| andreabolognani/libvirt | include/libvirt/libvirt-host.h | C | lgpl-2.1 | 25,314 |
/* dlvhex -- Answer-Set Programming with external interfaces.
* Copyright (C) 2005-2007 Roman Schindlauer
* Copyright (C) 2006-2015 Thomas Krennwallner
* Copyright (C) 2009-2016 Peter Schüller
* Copyright (C) 2011-2016 Christoph Redl
* Copyright (C) 2015-2016 Tobias Kaminski
* Copyright (C) 2015-2016 Antonius Weinzierl
*
* This file is part of dlvhex.
*
* dlvhex 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.
*
* dlvhex 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 dlvhex; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
/**
* @file PluginContainer.h
* @author Roman Schindlauer
* @author Peter Schueller
* @date Thu Sep 1 17:21:53 2005
*
* @brief Container class for plugins.
*
*
*/
#if !defined(_DLVHEX_PLUGINCONTAINER_H)
#define _DLVHEX_PLUGINCONTAINER_H
#include "dlvhex2/PlatformDefinitions.h"
#include "dlvhex2/fwd.h"
#include "dlvhex2/PluginInterface.h"
#include <string>
#include <vector>
#include <boost/shared_ptr.hpp>
DLVHEX_NAMESPACE_BEGIN
/**
* @brief Collects and administrates all available plugins.
*
* The PluginContainer loads and manages dynamically loaded and internal plugins.
* It is not aware of the configuration or usage of plugins or plugin atoms in a
* ProgramCtx.
*
* Important: memory allocation policy:
* * PluginInterface objects are passed by pointer from the extern "C" plugin
* import function, they are wrapped in a non-deleting smart pointer by the
* PluginContainer and must be deallocated by the library itself.
* * PluginAtom objects are created by PluginInterface::getAtoms and
* then owned by a smart pointer in the PluginContainer. These smart pointers
* must contain a "deleter" compiled into the library.
*/
class DLVHEX_EXPORT PluginContainer
{
private:
/** \brief Copy-constructor.
*
* Must not be used, would duplicate library unloads.
* @param c Other PluginContainer.
*/
PluginContainer(const PluginContainer& p);
public:
/** \brief Constructor. */
PluginContainer();
/** \brief Destructor.
*
* Unloads shared libraries (if shared_ptr reference counts are ok). */
~PluginContainer();
//
// loading and accessing
//
/** \brief Search for plugins in searchpath and open those that are plugins.
*
* May be called multiple times with different paths.
* Paths may be separated by ":" just like LD_LIBRARY_PATH.
* @param searchpath Path(es) to search. */
void loadPlugins(const std::string& searchpath="");
/** \brief Add a PluginInterface to the container.
*
* The smart pointer will not be reconfigured, so if you need to use a
* custom "deleter", do it before you call this method.
* @param plugin Pointer to an internal plugin. */
void addInternalPlugin(PluginInterfacePtr plugin);
/** \brief Get container with plugins loaded so far.
* @return Vector of plugins loaded so far. */
const std::vector<PluginInterfacePtr>& getPlugins() const
{ return pluginInterfaces; }
//
// batch operations on all plugins
//
/** \brief Calls printUsage for each loaded plugin.
* @param o Stream to print the output to. */
void printUsage(std::ostream& o);
public:
struct LoadedPlugin;
typedef boost::shared_ptr<LoadedPlugin> LoadedPluginPtr;
typedef std::vector<LoadedPluginPtr> LoadedPluginVector;
typedef std::vector<PluginInterfacePtr> PluginInterfaceVector;
private:
/** \brief Add loaded plugin (do not extract plugin atoms).
* @param lplugin Pointer to the loaded plugin. */
void addInternalPlugin(LoadedPluginPtr lplugin);
/** \brief Current search path. */
std::string searchPath;
/** \brief Loaded plugins. */
LoadedPluginVector plugins;
/** \brief Loaded plugins (interface ptrs). */
PluginInterfaceVector pluginInterfaces;
};
typedef boost::shared_ptr<PluginContainer> PluginContainerPtr;
DLVHEX_NAMESPACE_END
#endif /* _DLVHEX_PLUGINCONTAINER_H */
// vim:expandtab:ts=4:sw=4:
// mode: C++
// End:
| hexhex/core | include/dlvhex2/PluginContainer.h | C | lgpl-2.1 | 4,832 |
"""LDAP protocol proxy server"""
from twisted.internet import reactor, defer
from ldaptor.protocols.ldap import ldapserver, ldapconnector, ldapclient
from ldaptor.protocols import pureldap
class Proxy(ldapserver.BaseLDAPServer):
protocol = ldapclient.LDAPClient
client = None
waitingConnect = []
unbound = False
def __init__(self, config):
"""
Initialize the object.
@param config: The configuration.
@type config: ldaptor.interfaces.ILDAPConfig
"""
ldapserver.BaseLDAPServer.__init__(self)
self.config = config
def _whenConnected(self, fn, *a, **kw):
if self.client is None:
d = defer.Deferred()
self.waitingConnect.append((d, fn, a, kw))
return d
else:
return defer.maybeDeferred(fn, *a, **kw)
def _cbConnectionMade(self, proto):
self.client = proto
while self.waitingConnect:
d, fn, a, kw = self.waitingConnect.pop(0)
d2 = defer.maybeDeferred(fn, *a, **kw)
d2.chainDeferred(d)
def _clientQueue(self, request, controls, reply):
# TODO controls
if request.needs_answer:
d = self.client.send_multiResponse(request, self._gotResponse, reply)
# TODO handle d errbacks
else:
self.client.send_noResponse(request)
def _gotResponse(self, response, reply):
reply(response)
# TODO this is ugly
return isinstance(response, (
pureldap.LDAPSearchResultDone,
pureldap.LDAPBindResponse,
))
def _failConnection(self, reason):
#TODO self.loseConnection()
return reason # TODO
def connectionMade(self):
clientCreator = ldapconnector.LDAPClientCreator(
reactor, self.protocol)
d = clientCreator.connect(
dn='',
overrides=self.config.getServiceLocationOverrides())
d.addCallback(self._cbConnectionMade)
d.addErrback(self._failConnection)
ldapserver.BaseLDAPServer.connectionMade(self)
def connectionLost(self, reason):
assert self.client is not None
if self.client.connected:
if not self.unbound:
self.client.unbind()
self.unbound = True
else:
self.client.transport.loseConnection()
self.client = None
ldapserver.BaseLDAPServer.connectionLost(self, reason)
def _handleUnknown(self, request, controls, reply):
self._whenConnected(self._clientQueue, request, controls, reply)
return None
def handleUnknown(self, request, controls, reply):
d = defer.succeed(request)
d.addCallback(self._handleUnknown, controls, reply)
return d
def handle_LDAPUnbindRequest(self, request, controls, reply):
self.unbound = True
self.handleUnknown(request, controls, reply)
if __name__ == '__main__':
"""
Demonstration LDAP proxy; passes all requests to localhost:389.
"""
from twisted.internet import protocol
from twisted.python import log
import sys
log.startLogging(sys.stderr)
factory = protocol.ServerFactory()
factory.protocol = lambda : Proxy(overrides={
'': ('localhost', 389),
})
reactor.listenTCP(10389, factory)
reactor.run()
| antong/ldaptor | ldaptor/protocols/ldap/proxy.py | Python | lgpl-2.1 | 3,381 |
// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#ifndef __tecplot_io_h__
#define __tecplot_io_h__
// Local includes
#include "libmesh_common.h"
#include "mesh_output.h"
// C++ Includes
#include <cstddef>
namespace libMesh
{
// Forward declarations
class MeshBase;
/**
* This class implements writing meshes in the Tecplot format.
*
* @author Benjamin S. Kirk, 2004
*/
// ------------------------------------------------------------
// TecplotIO class definition
class TecplotIO : public MeshOutput<MeshBase>
{
public:
/**
* Constructor. Takes a reference to a constant mesh object.
* This constructor will only allow us to write the mesh.
* The optional parameter \p binary can be used to switch
* between ASCII (\p false, the default) or binary (\p true)
* output files.
*/
explicit
TecplotIO (const MeshBase&, const bool binary=false);
/**
* This method implements writing a mesh to a specified file.
*/
virtual void write (const std::string& );
/**
* This method implements writing a mesh with nodal data to a
* specified file where the nodal data and variable names are provided.
*/
virtual void write_nodal_data (const std::string&,
const std::vector<Number>&,
const std::vector<std::string>&);
/**
* Flag indicating whether or not to write a binary file
* (if the tecio.a library was found by \p configure).
*/
bool & binary ();
private:
/**
* This method implements writing a mesh with nodal data to a
* specified file where the nodal data and variable names are optionally
* provided. This will write an ASCII file.
*/
void write_ascii (const std::string&,
const std::vector<Number>* = NULL,
const std::vector<std::string>* = NULL);
/**
* This method implements writing a mesh with nodal data to a
* specified file where the nodal data and variable names are optionally
* provided. This will write a binary file if the tecio.a library was
* found at compile time, otherwise a warning message will be printed and
* an ASCII file will be created.
*/
void write_binary (const std::string&,
const std::vector<Number>* = NULL,
const std::vector<std::string>* = NULL);
//---------------------------------------------------------------------------
// local data
/**
* Flag to write binary data.
*/
bool _binary;
};
// ------------------------------------------------------------
// TecplotIO inline members
inline
TecplotIO::TecplotIO (const MeshBase& mesh, const bool binary) :
MeshOutput<MeshBase> (mesh),
_binary (binary)
{
}
inline
bool & TecplotIO::binary ()
{
return _binary;
}
} // namespace libMesh
#endif // #define __tecplot_io_h__
| certik/libmesh | include/mesh/tecplot_io.h | C | lgpl-2.1 | 3,538 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.