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 |
|---|---|---|---|---|---|
initSidebarItems({"struct":[["DefaultState","A structure which is a factory for instances of `Hasher` which implement the default trait."]],"trait":[["HashState","A trait representing stateful hashes which can be used to hash keys in a `HashMap`."]]}); | susaing/doc.servo.org | std/collections/hash_state/sidebar-items.js | JavaScript | mpl-2.0 | 252 |
#form {
top: 70%;
left: 50%;
width: 60%;
}
#main-login-form {
top: 70%;
left: 50%;
width: 60%;
background-color: #FFFFFF;
border-radius: 10px;
padding: 12px 20px;
}
.fixed-form {
position: fixed;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.form-partial-container {
margin: 0 auto;
}
.centered {
text-align: center;
}
.error-message {
color: red;
margin-bottom: 10px;
}
| iamstephenliu/HiveCHI-rwm | app/assets/stylesheets/session.css | CSS | mpl-2.0 | 443 |
import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
export default createDevTools(
<DockMonitor
toggleVisibilityKey="H"
changePositionKey="Q"
>
<LogMonitor />
</DockMonitor>
)
| blockstack/blockstack-browser | app/js/components/DevTools.js | JavaScript | mpl-2.0 | 323 |
/*
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
var ExitHandlers = {
// a widget can dynamically set "do-not-exit" or "do-not-exit-once" classes on the field to indicate we should not
// exit the field. "do-not-exit-once" will be cleared after a single exit attempt.
'manual-exit': {
handleExit: function(fieldModel) {
var doNotExit = fieldModel.element.hasClass('do-not-exit') || fieldModel.element.hasClass('do-not-exit-once');
fieldModel.element.removeClass('do-not-exit-once');
return !doNotExit;
}
},
'leading-zeros': {
handleExit: function(fieldModel) {
var val = fieldModel.element.val();
if (val) { // if the field is blank, leave it alone
var maxLength = parseInt(fieldModel.element.attr('maxlength'));
if (maxLength > 0) {
while (val.length < maxLength) {
val = "0" + val;
}
fieldModel.element.val(val);
}
}
return true;
}
}
}; | yadamz/first-module | omod/src/main/webapp/resources/scripts/navigator/exitHandlers.js | JavaScript | mpl-2.0 | 1,610 |
import { Model, belongsTo } from 'ember-cli-mirage';
export default Model.extend({
parent: belongsTo('alloc-file'),
});
| hashicorp/nomad | ui/mirage/models/alloc-file.js | JavaScript | mpl-2.0 | 123 |
<?php
use Faker\Generator;
class IssueModuleCest
{
/**
* @var string $lastView helps the test skip some repeated tests in order to make the test framework run faster at the
* potential cost of being accurate and reliable
*/
protected $lastView;
/**
* @var Generator $fakeData
*/
protected $fakeData;
/**
* @var integer $fakeDataSeed
*/
protected $fakeDataSeed;
/**
* @param AcceptanceTester $I
*/
public function _before(AcceptanceTester $I)
{
if (!$this->fakeData) {
$this->fakeData = Faker\Factory::create();
$this->fakeDataSeed = rand(0, 2048);
}
$this->fakeData->seed($this->fakeDataSeed);
}
/**
* @param AcceptanceTester $I
*/
public function _after(AcceptanceTester $I)
{
}
// Tests
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\ModuleBuilder $moduleBuilder
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As an administrator I want to create and deploy a issue module so that I can test
* that the issue functionality is working. Given that I have already created a module I expect to deploy
* the module before testing.
*/
public function testScenarioCreateIssueModule(
\AcceptanceTester $I,
\Step\Acceptance\ModuleBuilder $moduleBuilder,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Create a issue module for testing');
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
$moduleBuilder->createModule(
\Page\IssueModule::$PACKAGE_NAME,
\Page\IssueModule::$NAME,
\SuiteCRM\Enumerator\SugarObjectType::issue
);
$this->lastView = 'ModuleBuilder';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to view my issue test module so that I can see if it has been
* deployed correctly.
*/
public function testScenarioViewIssueTestModule(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('View Issue Test Module');
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Navigate to module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
$this->lastView = 'ListView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\EditView $editView
* @param \Step\Acceptance\DetailView $detailView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to create a record with my issue test module so that I can test
* the standard fields.
*/
public function testScenarioCreateRecord(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\EditView $editView,
\Step\Acceptance\DetailView $detailView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Create Issue Test Module Record');
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
// Select create Issue Test Module form the current menu
$navigationBar->clickCurrentMenuItem('Create ' . \Page\IssueModule::$NAME);
// Create a record
$this->fakeData->seed($this->fakeDataSeed);
$editView->waitForEditViewVisible();
$editView->fillField('#name', $this->fakeData->name);
$editView->fillField('#description', $this->fakeData->paragraph);
$editView->clickSaveButton();
$detailView->waitForDetailViewVisible();
$this->lastView = 'DetailView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\DetailView $detailView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to view the record by selecting it in the list view
*/
public function testScenarioViewRecordFromListView(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\DetailView $detailView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Select Record from list view');
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickFilterButton();
$listView->click('Quick Filter');
$this->fakeData->seed($this->fakeDataSeed);
$listView->fillField('#name_basic', $this->fakeData->name);
$listView->click('Search', '.submitButtons');
$listView->wait(1);
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickNameLink($this->fakeData->name);
$detailView->waitForDetailViewVisible();
$this->lastView = 'DetailView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\DetailView $detailView
* @param \Step\Acceptance\EditView $editView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to edit the record by selecting it in the detail view
*/
public function testScenarioEditRecordFromDetailView(
\AcceptanceTester$I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\DetailView $detailView,
\Step\Acceptance\EditView $editView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Edit Issue Test Module Record from detail view');
if ($this->lastView !== 'DetailView') {
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
// Select record from list view
$listView->clickFilterButton();
$listView->click('Quick Filter');
$this->fakeData->seed($this->fakeDataSeed);
$listView->fillField('#name_basic', $this->fakeData->name);
$listView->click('Search', '.submitButtons');
$listView->wait(1);
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickNameLink($this->fakeData->name);
}
// Edit Record
$detailView->clickActionMenuItem('Edit');
// Save record
$editView->click('Save');
$detailView->waitForDetailViewVisible();
$this->lastView = 'DetailView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\DetailView $detailView
* @param \Step\Acceptance\EditView $editView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to duplicate the record
*/
public function testScenarioDuplicateRecordFromDetailView(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\DetailView $detailView,
\Step\Acceptance\EditView $editView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Duplicate Issue Test Module Record from detail view');
if ($this->lastView !== 'DetailView') {
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
// Select record from list view
$listView->clickFilterButton();
$listView->click('Quick Filter');
$this->fakeData->seed($this->fakeDataSeed);
$listView->fillField('#name_basic', $this->fakeData->name);
$listView->click('Search', '.submitButtons');
$listView->wait(1);
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickNameLink($this->fakeData->name);
}
// Edit Record
$detailView->clickActionMenuItem('Duplicate');
$this->fakeData->seed($this->fakeDataSeed);
$editView->fillField('#name', $this->fakeData->name . '1');
// Save record
$editView->click('Save');
$detailView->waitForDetailViewVisible();
$detailView->clickActionMenuItem('Delete');
$detailView->acceptPopup();
$listView->waitForListViewVisible();
$this->lastView = 'ListView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\DetailView $detailView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to delete the record by selecting it in the detail view
*/
public function testScenarioDeleteRecordFromDetailView(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\DetailView $detailView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Delete Issue Test Module Record from detail view');
if ($this->lastView !== 'DetailView') {
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
// Select record from list view
$listView->clickFilterButton();
$listView->click('Quick Filter');
$this->fakeData->seed($this->fakeDataSeed);
$listView->fillField('#name_basic', $this->fakeData->name);
$listView->click('Search', '.submitButtons');
$listView->wait(1);
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickNameLink($this->fakeData->name);
}
// Delete Record
$detailView->clickActionMenuItem('Delete');
$detailView->acceptPopup();
$listView->waitForListViewVisible();
$this->lastView = 'ListView';
}
}
| willrennie/SuiteCRM | tests/acceptance/Core/IssueModuleCest.php | PHP | agpl-3.0 | 11,748 |
create table layer_prevent_geom_editors (
layer number(19,0) not null,
role_name varchar2(255 char)
);
alter table layer_prevent_geom_editors
add constraint FKF2CC57D82AB24981
foreign key (layer)
references layer; | B3Partners/flamingo | viewer-config-persistence/src/main/resources/scripts/oracle-add_layer_prevent_geom_editors.sql | SQL | agpl-3.0 | 234 |
<?php
/**
* 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.
*/
namespace Shopware\Bundle\ESIndexingBundle\Product;
use Shopware\Bundle\ESIndexingBundle\LastIdQuery;
/**
* Class ProductQueryFactoryInterface
*/
interface ProductQueryFactoryInterface
{
/**
* @param int $categoryId
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createCategoryQuery($categoryId, $limit = null);
/**
* @param int[] $priceIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createPriceIdQuery($priceIds, $limit = null);
/**
* @param int[] $unitIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createUnitIdQuery($unitIds, $limit = null);
/**
* @param int[] $voteIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createVoteIdQuery($voteIds, $limit = null);
/**
* @param int[] $productIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createProductIdQuery($productIds, $limit = null);
/**
* @param int[] $variantIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createVariantIdQuery($variantIds, $limit = null);
/**
* @param int[] $taxIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createTaxQuery($taxIds, $limit = null);
/**
* @param int[] $manufacturerIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createManufacturerQuery($manufacturerIds, $limit = null);
/**
* @param int[] $categoryIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createProductCategoryQuery($categoryIds, $limit = null);
/**
* @param int[] $groupIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createPropertyGroupQuery($groupIds, $limit = null);
/**
* @param int[] $optionIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createPropertyOptionQuery($optionIds, $limit = null);
}
| wlwwt/shopware | engine/Shopware/Bundle/ESIndexingBundle/Product/ProductQueryFactoryInterface.php | PHP | agpl-3.0 | 3,161 |
/*
* This file is part of LibrePlan
*
* Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
* Copyright (C) 2010-2011 Igalia, S.L.
*
* 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.libreplan.business.resources.entities;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid;
/**
* Represents entity. It is another type of work resource.
*
* @author Javier Moran Rua <jmoran@igalia.com>
* @author Fernando Bellas Permuy <fbellas@udc.es>
*/
public class Machine extends Resource {
private final static ResourceEnum type = ResourceEnum.MACHINE;
private String name;
private String description;
private Set<MachineWorkersConfigurationUnit> configurationUnits = new HashSet<>();
@Valid
public Set<MachineWorkersConfigurationUnit> getConfigurationUnits() {
return Collections.unmodifiableSet(configurationUnits);
}
public void addMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) {
configurationUnits.add(unit);
}
public void removeMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) {
configurationUnits.remove(unit);
}
public static Machine createUnvalidated(String code, String name, String description) {
Machine machine = create(new Machine(), code);
machine.name = name;
machine.description = description;
return machine;
}
public void updateUnvalidated(String name, String description) {
if (!StringUtils.isBlank(name)) {
this.name = name;
}
if (!StringUtils.isBlank(description)) {
this.description = description;
}
}
/**
* Used by Hibernate. Do not use!
*/
protected Machine() {}
public static Machine create() {
return create(new Machine());
}
public static Machine create(String code) {
return create(new Machine(), code);
}
@NotEmpty(message = "machine name not specified")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public String getShortDescription() {
return name + " (" + getCode() + ")";
}
public void setDescription(String description) {
this.description = description;
}
@Override
protected boolean isCriterionSatisfactionOfCorrectType(CriterionSatisfaction c) {
return c.getResourceType().equals(ResourceEnum.MACHINE);
}
@Override
public ResourceEnum getType() {
return type;
}
@Override
public String toString() {
return String.format("MACHINE: %s", name);
}
@Override
public String getHumanId() {
return name;
}
}
| PaulLuchyn/libreplan | libreplan-business/src/main/java/org/libreplan/business/resources/entities/Machine.java | Java | agpl-3.0 | 3,681 |
<?php
/**
* Live media server object, represents a media server association with live stream entry
*
* @package Core
* @subpackage model
*
*/
class kLiveMediaServer
{
/**
* @var int
*/
protected $mediaServerId;
/**
* @var int
*/
protected $index;
/**
* @var int
*/
protected $dc;
/**
* @var string
*/
protected $hostname;
/**
* @var int
*/
protected $time;
/**
* @var string
*/
protected $applicationName;
public function __construct($index, $hostname, $dc = null, $id = null, $applicationName = null)
{
$this->index = $index;
$this->mediaServerId = $id;
$this->hostname = $hostname;
$this->dc = $dc;
$this->time = time();
$this->applicationName = $applicationName;
}
/**
* @return int $mediaServerId
*/
public function getMediaServerId()
{
return $this->mediaServerId;
}
/**
* @return MediaServerNode
*/
public function getMediaServer()
{
$mediaServer = ServerNodePeer::retrieveByPK($this->mediaServerId);
if($mediaServer instanceof MediaServerNode)
return $mediaServer;
return null;
}
/**
* @return int $index
*/
public function getIndex()
{
return $this->index;
}
/**
* @return int $dc
*/
public function getDc()
{
return $this->dc;
}
/**
* @return string $hostname
*/
public function getHostname()
{
return $this->hostname;
}
/**
* @return int $time
*/
public function getTime()
{
return $this->time;
}
/**
* @return the $applicationName
*/
public function getApplicationName() {
return $this->applicationName;
}
} | doubleshot/server | alpha/lib/data/live/kLiveMediaServer.php | PHP | agpl-3.0 | 1,582 |
//=============================================================================
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Library General Public License as published
// by the Free Software Foundation; either version 2 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
// Library General Public License for more details.
//
// The GNU Public License is available in the file LICENSE, or you
// can write to the Free Software Foundation, Inc., 59 Temple Place -
// Suite 330, Boston, MA 02111-1307, USA, or you can find it on the
// World Wide Web at http://www.fsf.org.
//=============================================================================
/** \file
* \author John Bridgman
*/
#ifndef PARSEBOOL_H
#define PARSEBOOL_H
#pragma once
#include <string>
/**
* \brief Parses string for a boolean value.
*
* Considers no, false, 0 and any abreviation
* like " f" to be false
* and everything else to be true (including
* the empty string).
* Ignores whitespace.
* Note "false blah" is true!
* \return true or false
* \param str the string to parse
*/
bool ParseBool(const std::string &str);
#endif
| telefonicaid/fiware-IoTAgent-Cplusplus | third_party/variant/src/ParseBool.h | C | agpl-3.0 | 1,391 |
/*
* Copyright 2007-2013 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio 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.
*
* Pydio 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 Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*
* Description : focusable component / Tab navigation
*/
Interface.create("IContextMenuable", {
setContextualMenu : function(contextMenu){}
}); | FredPassos/pydio-core | core/src/plugins/gui.ajax/res/js/ui/prototype/interfaces/class.IContextMenuable.js | JavaScript | agpl-3.0 | 964 |
module Formtastic
module Helpers
# @private
module FieldsetWrapper
protected
# Generates a fieldset and wraps the content in an ordered list. When working
# with nested attributes, it allows %i as interpolation option in :name. So you can do:
#
# f.inputs :name => 'Task #%i', :for => :tasks
#
# or the shorter equivalent:
#
# f.inputs 'Task #%i', :for => :tasks
#
# And it will generate a fieldset for each task with legend 'Task #1', 'Task #2',
# 'Task #3' and so on.
#
# Note: Special case for the inline inputs (non-block):
# f.inputs "My little legend", :title, :body, :author # Explicit legend string => "My little legend"
# f.inputs :my_little_legend, :title, :body, :author # Localized (118n) legend with I18n key => I18n.t(:my_little_legend, ...)
# f.inputs :title, :body, :author # First argument is a column => (no legend)
def field_set_and_list_wrapping(*args, &block) # @private
contents = args[-1].is_a?(::Hash) ? '' : args.pop.flatten
html_options = args.extract_options!
if block_given?
contents = if template.respond_to?(:is_haml?) && template.is_haml?
template.capture_haml(&block)
else
template.capture(&block)
end
end
# Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
contents = contents.join if contents.respond_to?(:join)
legend = field_set_legend(html_options)
fieldset = template.content_tag(:fieldset,
Formtastic::Util.html_safe(legend) << template.content_tag(:ol, Formtastic::Util.html_safe(contents)),
html_options.except(:builder, :parent, :name)
)
fieldset
end
def field_set_legend(html_options)
legend = (html_options[:name] || '').to_s
legend %= parent_child_index(html_options[:parent]) if html_options[:parent] && legend.include?('%i') # only applying if String includes '%i' avoids argument error when $DEBUG is true
legend = template.content_tag(:legend, template.content_tag(:span, Formtastic::Util.html_safe(legend))) unless legend.blank?
legend
end
# Gets the nested_child_index value from the parent builder. It returns a hash with each
# association that the parent builds.
def parent_child_index(parent) # @private
# Could be {"post[authors_attributes]"=>0} or { :authors => 0 }
duck = parent[:builder].instance_variable_get('@nested_child_index')
# Could be symbol for the association, or a model (or an array of either, I think? TODO)
child = parent[:for]
# Pull a sybol or model out of Array (TODO: check if there's an Array)
child = child.first if child.respond_to?(:first)
# If it's an object, get a symbol from the class name
child = child.class.name.underscore.to_sym unless child.is_a?(Symbol)
key = "#{parent[:builder].object_name}[#{child}_attributes]"
# TODO: One of the tests produces a scenario where duck is "0" and the test looks for a "1"
# in the legend, so if we have a number, return it with a +1 until we can verify this scenario.
return duck + 1 if duck.is_a?(Fixnum)
# First try to extract key from duck Hash, then try child
(duck[key] || duck[child]).to_i + 1
end
end
end
end
| BibNumUMontreal/DMPonline_v4 | vendor/ruby/2.1.0/gems/formtastic-3.1.4/lib/formtastic/helpers/fieldset_wrapper.rb | Ruby | agpl-3.0 | 3,480 |
// NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// 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/>.
#ifndef NL_MUTABLE_CONTAINER_H
#define NL_MUTABLE_CONTAINER_H
namespace NLMISC
{
/** Container wrapper that allow read/write access to element stored in
* a const container.
* In fact, the template only allow calling begin() and end() over
* a const container.
* This prevent the user to change the structure of the container.
* Usage :
*
* class foo
* {
* typedef TMutableContainer<vector<string> > TMyCont;
* TMyCont _MyCont;
*
* public:
* // return the container with mutable item content but const item list
* const TMyCont getContainer() const { return _MyCont; };
* }
*
*/
template <class BaseContainer>
struct TMutableContainer : public BaseContainer
{
typename BaseContainer::iterator begin() const
{
return const_cast<BaseContainer*>(static_cast<const BaseContainer*>(this))->begin();
}
typename BaseContainer::iterator end() const
{
return const_cast<BaseContainer*>(static_cast<const BaseContainer*>(this))->end();
}
};
} // namespace NLMISC
#endif // NL_MUTABLE_CONTAINER_H
| osgcc/ryzom | nel/include/nel/misc/mutable_container.h | C | agpl-3.0 | 1,844 |
## What is Runbook?
[Runbook](https://runbook.io) is an open source monitoring service that allows you to perform automated "Reactions" when issues are detected. Runbook gives you the ability to automatically resolve DevOps alerts with zero human interaction.
Simply put, Runbook is what you would get if Nagios and IFTTT had a baby.
## Open source and contributing
Runbook is 100% open source and developed using the [Assembly](https://assembly.com/runbook) platform. Runbook runs as a SaaS application, with both free and paid plans.
With the Assembly platform, all revenue from the product is funneled into the project and its contributors. After subtracting business expenses, 10% goes to Assembly as a fee and the rest is given back to project contributors based on a percentage of their contributions.
Unlike other open source products, not only do you get the satisfaction of giving back to the community as a whole but you also get a cut of the profits. To get started, simply join us on our [Assembly Project Page](https://assembly.com/runbook).
## Documentation
This page is the front page of our documentation for Runbook users and developers. Here you will find information about how Runbook works, how it is designed, and how you can contribute.
To get started, we recommend these resources:
[Quick Start guide](quick-start.md)
[Community tutorials](community-tutorials/index.md)
[Developer documentation](developers/index.md)
---
| rbramwell/runbook | docs/index.md | Markdown | agpl-3.0 | 1,455 |
<!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">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>Documentation: NexUpload.cpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="Logo.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Documentation
</div>
<div id="projectbrief">For Arduino users</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.7 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('_nex_upload_8cpp.html','');});
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">NexUpload.cpp File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>The implementation of download tft file for nextion.
<a href="#details">More...</a></p>
<div class="textblock"><code>#include "<a class="el" href="_nex_upload_8h_source.html">NexUpload.h</a>"</code><br />
<code>#include <SoftwareSerial.h></code><br />
</div>
<p><a href="_nex_upload_8cpp_source.html">Go to the source code of this file.</a></p>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>The implementation of download tft file for nextion. </p>
<dl class="section author"><dt>Author</dt><dd>Chen Zengpeng (email:<a href="#" onclick="location.href='mai'+'lto:'+'zen'+'gp'+'eng'+'.c'+'hen'+'@i'+'tea'+'d.'+'cc'; return false;">zengp<span style="display: none;">.nosp@m.</span>eng.<span style="display: none;">.nosp@m.</span>chen@<span style="display: none;">.nosp@m.</span>itea<span style="display: none;">.nosp@m.</span>d.cc</a>) </dd></dl>
<dl class="section date"><dt>Date</dt><dd>2016/3/29 </dd></dl>
<dl class="section copyright"><dt>Copyright</dt><dd>Copyright (C) 2014-2015 ITEAD Intelligent Systems Co., Ltd. <br />
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. </dd></dl>
<p>Definition in file <a class="el" href="_nex_upload_8cpp_source.html">NexUpload.cpp</a>.</p>
</div></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="_nex_upload_8cpp.html">NexUpload.cpp</a></li>
<li class="footer">Generated on Fri Jan 6 2017 14:00:38 for Documentation by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.7 </li>
</ul>
</div>
</body>
</html>
| DanyYanev/Boiler_Control | resourses/Libraries/ITEADLIB_Arduino_Nextion-master/doc/Documentation/_nex_upload_8cpp.html | HTML | agpl-3.0 | 4,665 |
@charset "UTF-8";
/*
Animate.css - http://daneden.me/animate
Licensed under the ☺ license (http://licence.visualidiot.com/)
Copyright (c) 2012 Dan Eden
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.
*/
body { /* Addresses a small issue in webkit: http://bit.ly/NEdoDq */
/* -webkit-backface-visibility: hidden;*/
}
.animated {
-webkit-animation-duration: 1s;
-moz-animation-duration: 1s;
-o-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
-moz-animation-fill-mode: both;
-o-animation-fill-mode: both;
animation-fill-mode: both;
}
.animated.hinge {
-webkit-animation-duration: 2s;
-moz-animation-duration: 2s;
-o-animation-duration: 2s;
animation-duration: 2s;
}
@-webkit-keyframes flash {
0%, 50%, 100% {opacity: 1;}
25%, 75% {opacity: 0;}
}
@-moz-keyframes flash {
0%, 50%, 100% {opacity: 1;}
25%, 75% {opacity: 0;}
}
@-o-keyframes flash {
0%, 50%, 100% {opacity: 1;}
25%, 75% {opacity: 0;}
}
@keyframes flash {
0%, 50%, 100% {opacity: 1;}
25%, 75% {opacity: 0;}
}
.flash {
-webkit-animation-name: flash;
-moz-animation-name: flash;
-o-animation-name: flash;
animation-name: flash;
}
@-webkit-keyframes shake {
0%, 100% {-webkit-transform: translateX(0);}
10%, 30%, 50%, 70%, 90% {-webkit-transform: translateX(-10px);}
20%, 40%, 60%, 80% {-webkit-transform: translateX(10px);}
}
@-moz-keyframes shake {
0%, 100% {-moz-transform: translateX(0);}
10%, 30%, 50%, 70%, 90% {-moz-transform: translateX(-10px);}
20%, 40%, 60%, 80% {-moz-transform: translateX(10px);}
}
@-o-keyframes shake {
0%, 100% {-o-transform: translateX(0);}
10%, 30%, 50%, 70%, 90% {-o-transform: translateX(-10px);}
20%, 40%, 60%, 80% {-o-transform: translateX(10px);}
}
@keyframes shake {
0%, 100% {transform: translateX(0);}
10%, 30%, 50%, 70%, 90% {transform: translateX(-10px);}
20%, 40%, 60%, 80% {transform: translateX(10px);}
}
.shake {
-webkit-animation-name: shake;
-moz-animation-name: shake;
-o-animation-name: shake;
animation-name: shake;
}
@-webkit-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-webkit-transform: translateY(0);}
40% {-webkit-transform: translateY(-30px);}
60% {-webkit-transform: translateY(-15px);}
}
@-moz-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-moz-transform: translateY(0);}
40% {-moz-transform: translateY(-30px);}
60% {-moz-transform: translateY(-15px);}
}
@-o-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-o-transform: translateY(0);}
40% {-o-transform: translateY(-30px);}
60% {-o-transform: translateY(-15px);}
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {transform: translateY(0);}
40% {transform: translateY(-30px);}
60% {transform: translateY(-15px);}
}
.bounce {
-webkit-animation-name: bounce;
-moz-animation-name: bounce;
-o-animation-name: bounce;
animation-name: bounce;
}
@-webkit-keyframes tada {
0% {-webkit-transform: scale(1);}
10%, 20% {-webkit-transform: scale(0.9) rotate(-3deg);}
30%, 50%, 70%, 90% {-webkit-transform: scale(1.1) rotate(3deg);}
40%, 60%, 80% {-webkit-transform: scale(1.1) rotate(-3deg);}
100% {-webkit-transform: scale(1) rotate(0);}
}
@-moz-keyframes tada {
0% {-moz-transform: scale(1);}
10%, 20% {-moz-transform: scale(0.9) rotate(-3deg);}
30%, 50%, 70%, 90% {-moz-transform: scale(1.1) rotate(3deg);}
40%, 60%, 80% {-moz-transform: scale(1.1) rotate(-3deg);}
100% {-moz-transform: scale(1) rotate(0);}
}
@-o-keyframes tada {
0% {-o-transform: scale(1);}
10%, 20% {-o-transform: scale(0.9) rotate(-3deg);}
30%, 50%, 70%, 90% {-o-transform: scale(1.1) rotate(3deg);}
40%, 60%, 80% {-o-transform: scale(1.1) rotate(-3deg);}
100% {-o-transform: scale(1) rotate(0);}
}
@keyframes tada {
0% {transform: scale(1);}
10%, 20% {transform: scale(0.9) rotate(-3deg);}
30%, 50%, 70%, 90% {transform: scale(1.1) rotate(3deg);}
40%, 60%, 80% {transform: scale(1.1) rotate(-3deg);}
100% {transform: scale(1) rotate(0);}
}
.tada {
-webkit-animation-name: tada;
-moz-animation-name: tada;
-o-animation-name: tada;
animation-name: tada;
}
@-webkit-keyframes swing {
20%, 40%, 60%, 80%, 100% { -webkit-transform-origin: top center; }
20% { -webkit-transform: rotate(15deg); }
40% { -webkit-transform: rotate(-10deg); }
60% { -webkit-transform: rotate(5deg); }
80% { -webkit-transform: rotate(-5deg); }
100% { -webkit-transform: rotate(0deg); }
}
@-moz-keyframes swing {
20% { -moz-transform: rotate(15deg); }
40% { -moz-transform: rotate(-10deg); }
60% { -moz-transform: rotate(5deg); }
80% { -moz-transform: rotate(-5deg); }
100% { -moz-transform: rotate(0deg); }
}
@-o-keyframes swing {
20% { -o-transform: rotate(15deg); }
40% { -o-transform: rotate(-10deg); }
60% { -o-transform: rotate(5deg); }
80% { -o-transform: rotate(-5deg); }
100% { -o-transform: rotate(0deg); }
}
@keyframes swing {
20% { transform: rotate(15deg); }
40% { transform: rotate(-10deg); }
60% { transform: rotate(5deg); }
80% { transform: rotate(-5deg); }
100% { transform: rotate(0deg); }
}
.swing {
-webkit-transform-origin: top center;
-moz-transform-origin: top center;
-o-transform-origin: top center;
transform-origin: top center;
-webkit-animation-name: swing;
-moz-animation-name: swing;
-o-animation-name: swing;
animation-name: swing;
}
/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */
@-webkit-keyframes wobble {
0% { -webkit-transform: translateX(0%); }
15% { -webkit-transform: translateX(-25%) rotate(-5deg); }
30% { -webkit-transform: translateX(20%) rotate(3deg); }
45% { -webkit-transform: translateX(-15%) rotate(-3deg); }
60% { -webkit-transform: translateX(10%) rotate(2deg); }
75% { -webkit-transform: translateX(-5%) rotate(-1deg); }
100% { -webkit-transform: translateX(0%); }
}
@-moz-keyframes wobble {
0% { -moz-transform: translateX(0%); }
15% { -moz-transform: translateX(-25%) rotate(-5deg); }
30% { -moz-transform: translateX(20%) rotate(3deg); }
45% { -moz-transform: translateX(-15%) rotate(-3deg); }
60% { -moz-transform: translateX(10%) rotate(2deg); }
75% { -moz-transform: translateX(-5%) rotate(-1deg); }
100% { -moz-transform: translateX(0%); }
}
@-o-keyframes wobble {
0% { -o-transform: translateX(0%); }
15% { -o-transform: translateX(-25%) rotate(-5deg); }
30% { -o-transform: translateX(20%) rotate(3deg); }
45% { -o-transform: translateX(-15%) rotate(-3deg); }
60% { -o-transform: translateX(10%) rotate(2deg); }
75% { -o-transform: translateX(-5%) rotate(-1deg); }
100% { -o-transform: translateX(0%); }
}
@keyframes wobble {
0% { transform: translateX(0%); }
15% { transform: translateX(-25%) rotate(-5deg); }
30% { transform: translateX(20%) rotate(3deg); }
45% { transform: translateX(-15%) rotate(-3deg); }
60% { transform: translateX(10%) rotate(2deg); }
75% { transform: translateX(-5%) rotate(-1deg); }
100% { transform: translateX(0%); }
}
.wobble {
-webkit-animation-name: wobble;
-moz-animation-name: wobble;
-o-animation-name: wobble;
animation-name: wobble;
}
/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */
@-webkit-keyframes pulse {
0% { -webkit-transform: scale(1); }
50% { -webkit-transform: scale(1.1); }
100% { -webkit-transform: scale(1); }
}
@-moz-keyframes pulse {
0% { -moz-transform: scale(1); }
50% { -moz-transform: scale(1.1); }
100% { -moz-transform: scale(1); }
}
@-o-keyframes pulse {
0% { -o-transform: scale(1); }
50% { -o-transform: scale(1.1); }
100% { -o-transform: scale(1); }
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
.pulse {
-webkit-animation-name: pulse;
-moz-animation-name: pulse;
-o-animation-name: pulse;
animation-name: pulse;
}
@-webkit-keyframes flip {
0% {
-webkit-transform: perspective(400px) rotateY(0);
-webkit-animation-timing-function: ease-out;
}
40% {
-webkit-transform: perspective(400px) translateZ(150px) rotateY(170deg);
-webkit-animation-timing-function: ease-out;
}
50% {
-webkit-transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1);
-webkit-animation-timing-function: ease-in;
}
80% {
-webkit-transform: perspective(400px) rotateY(360deg) scale(.95);
-webkit-animation-timing-function: ease-in;
}
100% {
-webkit-transform: perspective(400px) scale(1);
-webkit-animation-timing-function: ease-in;
}
}
@-moz-keyframes flip {
0% {
-moz-transform: perspective(400px) rotateY(0);
-moz-animation-timing-function: ease-out;
}
40% {
-moz-transform: perspective(400px) translateZ(150px) rotateY(170deg);
-moz-animation-timing-function: ease-out;
}
50% {
-moz-transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1);
-moz-animation-timing-function: ease-in;
}
80% {
-moz-transform: perspective(400px) rotateY(360deg) scale(.95);
-moz-animation-timing-function: ease-in;
}
100% {
-moz-transform: perspective(400px) scale(1);
-moz-animation-timing-function: ease-in;
}
}
@-o-keyframes flip {
0% {
-o-transform: perspective(400px) rotateY(0);
-o-animation-timing-function: ease-out;
}
40% {
-o-transform: perspective(400px) translateZ(150px) rotateY(170deg);
-o-animation-timing-function: ease-out;
}
50% {
-o-transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1);
-o-animation-timing-function: ease-in;
}
80% {
-o-transform: perspective(400px) rotateY(360deg) scale(.95);
-o-animation-timing-function: ease-in;
}
100% {
-o-transform: perspective(400px) scale(1);
-o-animation-timing-function: ease-in;
}
}
@keyframes flip {
0% {
transform: perspective(400px) rotateY(0);
animation-timing-function: ease-out;
}
40% {
transform: perspective(400px) translateZ(150px) rotateY(170deg);
animation-timing-function: ease-out;
}
50% {
transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1);
animation-timing-function: ease-in;
}
80% {
transform: perspective(400px) rotateY(360deg) scale(.95);
animation-timing-function: ease-in;
}
100% {
transform: perspective(400px) scale(1);
animation-timing-function: ease-in;
}
}
.flip {
-webkit-backface-visibility: visible !important;
-webkit-animation-name: flip;
-moz-backface-visibility: visible !important;
-moz-animation-name: flip;
-o-backface-visibility: visible !important;
-o-animation-name: flip;
backface-visibility: visible !important;
animation-name: flip;
}
@-webkit-keyframes flipInX {
0% {
-webkit-transform: perspective(400px) rotateX(90deg);
opacity: 0;
}
40% {
-webkit-transform: perspective(400px) rotateX(-10deg);
}
70% {
-webkit-transform: perspective(400px) rotateX(10deg);
}
100% {
-webkit-transform: perspective(400px) rotateX(0deg);
opacity: 1;
}
}
@-moz-keyframes flipInX {
0% {
-moz-transform: perspective(400px) rotateX(90deg);
opacity: 0;
}
40% {
-moz-transform: perspective(400px) rotateX(-10deg);
}
70% {
-moz-transform: perspective(400px) rotateX(10deg);
}
100% {
-moz-transform: perspective(400px) rotateX(0deg);
opacity: 1;
}
}
@-o-keyframes flipInX {
0% {
-o-transform: perspective(400px) rotateX(90deg);
opacity: 0;
}
40% {
-o-transform: perspective(400px) rotateX(-10deg);
}
70% {
-o-transform: perspective(400px) rotateX(10deg);
}
100% {
-o-transform: perspective(400px) rotateX(0deg);
opacity: 1;
}
}
@keyframes flipInX {
0% {
transform: perspective(400px) rotateX(90deg);
opacity: 0;
}
40% {
transform: perspective(400px) rotateX(-10deg);
}
70% {
transform: perspective(400px) rotateX(10deg);
}
100% {
transform: perspective(400px) rotateX(0deg);
opacity: 1;
}
}
.flipInX {
-webkit-backface-visibility: visible !important;
-webkit-animation-name: flipInX;
-moz-backface-visibility: visible !important;
-moz-animation-name: flipInX;
-o-backface-visibility: visible !important;
-o-animation-name: flipInX;
backface-visibility: visible !important;
animation-name: flipInX;
}
@-webkit-keyframes flipOutX {
0% {
-webkit-transform: perspective(400px) rotateX(0deg);
opacity: 1;
}
100% {
-webkit-transform: perspective(400px) rotateX(90deg);
opacity: 0;
}
}
@-moz-keyframes flipOutX {
0% {
-moz-transform: perspective(400px) rotateX(0deg);
opacity: 1;
}
100% {
-moz-transform: perspective(400px) rotateX(90deg);
opacity: 0;
}
}
@-o-keyframes flipOutX {
0% {
-o-transform: perspective(400px) rotateX(0deg);
opacity: 1;
}
100% {
-o-transform: perspective(400px) rotateX(90deg);
opacity: 0;
}
}
@keyframes flipOutX {
0% {
transform: perspective(400px) rotateX(0deg);
opacity: 1;
}
100% {
transform: perspective(400px) rotateX(90deg);
opacity: 0;
}
}
.flipOutX {
-webkit-animation-name: flipOutX;
-webkit-backface-visibility: visible !important;
-moz-animation-name: flipOutX;
-moz-backface-visibility: visible !important;
-o-animation-name: flipOutX;
-o-backface-visibility: visible !important;
animation-name: flipOutX;
backface-visibility: visible !important;
}
@-webkit-keyframes flipInY {
0% {
-webkit-transform: perspective(400px) rotateY(90deg);
opacity: 0;
}
40% {
-webkit-transform: perspective(400px) rotateY(-10deg);
}
70% {
-webkit-transform: perspective(400px) rotateY(10deg);
}
100% {
-webkit-transform: perspective(400px) rotateY(0deg);
opacity: 1;
}
}
@-moz-keyframes flipInY {
0% {
-moz-transform: perspective(400px) rotateY(90deg);
opacity: 0;
}
40% {
-moz-transform: perspective(400px) rotateY(-10deg);
}
70% {
-moz-transform: perspective(400px) rotateY(10deg);
}
100% {
-moz-transform: perspective(400px) rotateY(0deg);
opacity: 1;
}
}
@-o-keyframes flipInY {
0% {
-o-transform: perspective(400px) rotateY(90deg);
opacity: 0;
}
40% {
-o-transform: perspective(400px) rotateY(-10deg);
}
70% {
-o-transform: perspective(400px) rotateY(10deg);
}
100% {
-o-transform: perspective(400px) rotateY(0deg);
opacity: 1;
}
}
@keyframes flipInY {
0% {
transform: perspective(400px) rotateY(90deg);
opacity: 0;
}
40% {
transform: perspective(400px) rotateY(-10deg);
}
70% {
transform: perspective(400px) rotateY(10deg);
}
100% {
transform: perspective(400px) rotateY(0deg);
opacity: 1;
}
}
.flipInY {
-webkit-backface-visibility: visible !important;
-webkit-animation-name: flipInY;
-moz-backface-visibility: visible !important;
-moz-animation-name: flipInY;
-o-backface-visibility: visible !important;
-o-animation-name: flipInY;
backface-visibility: visible !important;
animation-name: flipInY;
}
@-webkit-keyframes flipOutY {
0% {
-webkit-transform: perspective(400px) rotateY(0deg);
opacity: 1;
}
100% {
-webkit-transform: perspective(400px) rotateY(90deg);
opacity: 0;
}
}
@-moz-keyframes flipOutY {
0% {
-moz-transform: perspective(400px) rotateY(0deg);
opacity: 1;
}
100% {
-moz-transform: perspective(400px) rotateY(90deg);
opacity: 0;
}
}
@-o-keyframes flipOutY {
0% {
-o-transform: perspective(400px) rotateY(0deg);
opacity: 1;
}
100% {
-o-transform: perspective(400px) rotateY(90deg);
opacity: 0;
}
}
@keyframes flipOutY {
0% {
transform: perspective(400px) rotateY(0deg);
opacity: 1;
}
100% {
transform: perspective(400px) rotateY(90deg);
opacity: 0;
}
}
.flipOutY {
-webkit-backface-visibility: visible !important;
-webkit-animation-name: flipOutY;
-moz-backface-visibility: visible !important;
-moz-animation-name: flipOutY;
-o-backface-visibility: visible !important;
-o-animation-name: flipOutY;
backface-visibility: visible !important;
animation-name: flipOutY;
}
@-webkit-keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
@-moz-keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
@-o-keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
@keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
.fadeIn {
-webkit-animation-name: fadeIn;
-moz-animation-name: fadeIn;
-o-animation-name: fadeIn;
animation-name: fadeIn;
}
@-webkit-keyframes fadeInUp {
0% {
opacity: 0;
-webkit-transform: translateY(20px);
}
100% {
opacity: 1;
-webkit-transform: translateY(0);
}
}
@-moz-keyframes fadeInUp {
0% {
opacity: 0;
-moz-transform: translateY(20px);
}
100% {
opacity: 1;
-moz-transform: translateY(0);
}
}
@-o-keyframes fadeInUp {
0% {
opacity: 0;
-o-transform: translateY(20px);
}
100% {
opacity: 1;
-o-transform: translateY(0);
}
}
@keyframes fadeInUp {
0% {
opacity: 0;
transform: translateY(20px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.fadeInUp {
-webkit-animation-name: fadeInUp;
-moz-animation-name: fadeInUp;
-o-animation-name: fadeInUp;
animation-name: fadeInUp;
}
@-webkit-keyframes fadeInDown {
0% {
opacity: 0;
-webkit-transform: translateY(-20px);
}
100% {
opacity: 1;
-webkit-transform: translateY(0);
}
}
@-moz-keyframes fadeInDown {
0% {
opacity: 0;
-moz-transform: translateY(-20px);
}
100% {
opacity: 1;
-moz-transform: translateY(0);
}
}
@-o-keyframes fadeInDown {
0% {
opacity: 0;
-o-transform: translateY(-20px);
}
100% {
opacity: 1;
-o-transform: translateY(0);
}
}
@keyframes fadeInDown {
0% {
opacity: 0;
transform: translateY(-20px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.fadeInDown {
-webkit-animation-name: fadeInDown;
-moz-animation-name: fadeInDown;
-o-animation-name: fadeInDown;
animation-name: fadeInDown;
}
@-webkit-keyframes fadeInLeft {
0% {
opacity: 0;
-webkit-transform: translateX(-20px);
}
100% {
opacity: 1;
-webkit-transform: translateX(0);
}
}
@-moz-keyframes fadeInLeft {
0% {
opacity: 0;
-moz-transform: translateX(-20px);
}
100% {
opacity: 1;
-moz-transform: translateX(0);
}
}
@-o-keyframes fadeInLeft {
0% {
opacity: 0;
-o-transform: translateX(-20px);
}
100% {
opacity: 1;
-o-transform: translateX(0);
}
}
@keyframes fadeInLeft {
0% {
opacity: 0;
transform: translateX(-20px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
.fadeInLeft {
-webkit-animation-name: fadeInLeft;
-moz-animation-name: fadeInLeft;
-o-animation-name: fadeInLeft;
animation-name: fadeInLeft;
}
@-webkit-keyframes fadeInRight {
0% {
opacity: 0;
-webkit-transform: translateX(20px);
}
100% {
opacity: 1;
-webkit-transform: translateX(0);
}
}
@-moz-keyframes fadeInRight {
0% {
opacity: 0;
-moz-transform: translateX(20px);
}
100% {
opacity: 1;
-moz-transform: translateX(0);
}
}
@-o-keyframes fadeInRight {
0% {
opacity: 0;
-o-transform: translateX(20px);
}
100% {
opacity: 1;
-o-transform: translateX(0);
}
}
@keyframes fadeInRight {
0% {
opacity: 0;
transform: translateX(20px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
.fadeInRight {
-webkit-animation-name: fadeInRight;
-moz-animation-name: fadeInRight;
-o-animation-name: fadeInRight;
animation-name: fadeInRight;
}
@-webkit-keyframes fadeInUpBig {
0% {
opacity: 0;
-webkit-transform: translateY(2000px);
}
100% {
opacity: 1;
-webkit-transform: translateY(0);
}
}
@-moz-keyframes fadeInUpBig {
0% {
opacity: 0;
-moz-transform: translateY(2000px);
}
100% {
opacity: 1;
-moz-transform: translateY(0);
}
}
@-o-keyframes fadeInUpBig {
0% {
opacity: 0;
-o-transform: translateY(2000px);
}
100% {
opacity: 1;
-o-transform: translateY(0);
}
}
@keyframes fadeInUpBig {
0% {
opacity: 0;
transform: translateY(2000px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.fadeInUpBig {
-webkit-animation-name: fadeInUpBig;
-moz-animation-name: fadeInUpBig;
-o-animation-name: fadeInUpBig;
animation-name: fadeInUpBig;
}
@-webkit-keyframes fadeInDownBig {
0% {
opacity: 0;
-webkit-transform: translateY(-2000px);
}
100% {
opacity: 1;
-webkit-transform: translateY(0);
}
}
@-moz-keyframes fadeInDownBig {
0% {
opacity: 0;
-moz-transform: translateY(-2000px);
}
100% {
opacity: 1;
-moz-transform: translateY(0);
}
}
@-o-keyframes fadeInDownBig {
0% {
opacity: 0;
-o-transform: translateY(-2000px);
}
100% {
opacity: 1;
-o-transform: translateY(0);
}
}
@keyframes fadeInDownBig {
0% {
opacity: 0;
transform: translateY(-2000px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.fadeInDownBig {
-webkit-animation-name: fadeInDownBig;
-moz-animation-name: fadeInDownBig;
-o-animation-name: fadeInDownBig;
animation-name: fadeInDownBig;
}
@-webkit-keyframes fadeInLeftBig {
0% {
opacity: 0;
-webkit-transform: translateX(-2000px);
}
100% {
opacity: 1;
-webkit-transform: translateX(0);
}
}
@-moz-keyframes fadeInLeftBig {
0% {
opacity: 0;
-moz-transform: translateX(-2000px);
}
100% {
opacity: 1;
-moz-transform: translateX(0);
}
}
@-o-keyframes fadeInLeftBig {
0% {
opacity: 0;
-o-transform: translateX(-2000px);
}
100% {
opacity: 1;
-o-transform: translateX(0);
}
}
@keyframes fadeInLeftBig {
0% {
opacity: 0;
transform: translateX(-2000px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
.fadeInLeftBig {
-webkit-animation-name: fadeInLeftBig;
-moz-animation-name: fadeInLeftBig;
-o-animation-name: fadeInLeftBig;
animation-name: fadeInLeftBig;
}
@-webkit-keyframes fadeInRightBig {
0% {
opacity: 0;
-webkit-transform: translateX(2000px);
}
100% {
opacity: 1;
-webkit-transform: translateX(0);
}
}
@-moz-keyframes fadeInRightBig {
0% {
opacity: 0;
-moz-transform: translateX(2000px);
}
100% {
opacity: 1;
-moz-transform: translateX(0);
}
}
@-o-keyframes fadeInRightBig {
0% {
opacity: 0;
-o-transform: translateX(2000px);
}
100% {
opacity: 1;
-o-transform: translateX(0);
}
}
@keyframes fadeInRightBig {
0% {
opacity: 0;
transform: translateX(2000px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
.fadeInRightBig {
-webkit-animation-name: fadeInRightBig;
-moz-animation-name: fadeInRightBig;
-o-animation-name: fadeInRightBig;
animation-name: fadeInRightBig;
}
@-webkit-keyframes fadeOut {
0% {opacity: 1;}
100% {opacity: 0;}
}
@-moz-keyframes fadeOut {
0% {opacity: 1;}
100% {opacity: 0;}
}
@-o-keyframes fadeOut {
0% {opacity: 1;}
100% {opacity: 0;}
}
@keyframes fadeOut {
0% {opacity: 1;}
100% {opacity: 0;}
}
.fadeOut {
-webkit-animation-name: fadeOut;
-moz-animation-name: fadeOut;
-o-animation-name: fadeOut;
animation-name: fadeOut;
}
@-webkit-keyframes fadeOutUp {
0% {
opacity: 1;
-webkit-transform: translateY(0);
}
100% {
opacity: 0;
-webkit-transform: translateY(-20px);
}
}
@-moz-keyframes fadeOutUp {
0% {
opacity: 1;
-moz-transform: translateY(0);
}
100% {
opacity: 0;
-moz-transform: translateY(-20px);
}
}
@-o-keyframes fadeOutUp {
0% {
opacity: 1;
-o-transform: translateY(0);
}
100% {
opacity: 0;
-o-transform: translateY(-20px);
}
}
@keyframes fadeOutUp {
0% {
opacity: 1;
transform: translateY(0);
}
100% {
opacity: 0;
transform: translateY(-20px);
}
}
.fadeOutUp {
-webkit-animation-name: fadeOutUp;
-moz-animation-name: fadeOutUp;
-o-animation-name: fadeOutUp;
animation-name: fadeOutUp;
}
@-webkit-keyframes fadeOutDown {
0% {
opacity: 1;
-webkit-transform: translateY(0);
}
100% {
opacity: 0;
-webkit-transform: translateY(20px);
}
}
@-moz-keyframes fadeOutDown {
0% {
opacity: 1;
-moz-transform: translateY(0);
}
100% {
opacity: 0;
-moz-transform: translateY(20px);
}
}
@-o-keyframes fadeOutDown {
0% {
opacity: 1;
-o-transform: translateY(0);
}
100% {
opacity: 0;
-o-transform: translateY(20px);
}
}
@keyframes fadeOutDown {
0% {
opacity: 1;
transform: translateY(0);
}
100% {
opacity: 0;
transform: translateY(20px);
}
}
.fadeOutDown {
-webkit-animation-name: fadeOutDown;
-moz-animation-name: fadeOutDown;
-o-animation-name: fadeOutDown;
animation-name: fadeOutDown;
}
@-webkit-keyframes fadeOutLeft {
0% {
opacity: 1;
-webkit-transform: translateX(0);
}
100% {
opacity: 0;
-webkit-transform: translateX(-20px);
}
}
@-moz-keyframes fadeOutLeft {
0% {
opacity: 1;
-moz-transform: translateX(0);
}
100% {
opacity: 0;
-moz-transform: translateX(-20px);
}
}
@-o-keyframes fadeOutLeft {
0% {
opacity: 1;
-o-transform: translateX(0);
}
100% {
opacity: 0;
-o-transform: translateX(-20px);
}
}
@keyframes fadeOutLeft {
0% {
opacity: 1;
transform: translateX(0);
}
100% {
opacity: 0;
transform: translateX(-20px);
}
}
.fadeOutLeft {
-webkit-animation-name: fadeOutLeft;
-moz-animation-name: fadeOutLeft;
-o-animation-name: fadeOutLeft;
animation-name: fadeOutLeft;
}
@-webkit-keyframes fadeOutRight {
0% {
opacity: 1;
-webkit-transform: translateX(0);
}
100% {
opacity: 0;
-webkit-transform: translateX(20px);
}
}
@-moz-keyframes fadeOutRight {
0% {
opacity: 1;
-moz-transform: translateX(0);
}
100% {
opacity: 0;
-moz-transform: translateX(20px);
}
}
@-o-keyframes fadeOutRight {
0% {
opacity: 1;
-o-transform: translateX(0);
}
100% {
opacity: 0;
-o-transform: translateX(20px);
}
}
@keyframes fadeOutRight {
0% {
opacity: 1;
transform: translateX(0);
}
100% {
opacity: 0;
transform: translateX(20px);
}
}
.fadeOutRight {
-webkit-animation-name: fadeOutRight;
-moz-animation-name: fadeOutRight;
-o-animation-name: fadeOutRight;
animation-name: fadeOutRight;
}
@-webkit-keyframes fadeOutUpBig {
0% {
opacity: 1;
-webkit-transform: translateY(0);
}
100% {
opacity: 0;
-webkit-transform: translateY(-2000px);
}
}
@-moz-keyframes fadeOutUpBig {
0% {
opacity: 1;
-moz-transform: translateY(0);
}
100% {
opacity: 0;
-moz-transform: translateY(-2000px);
}
}
@-o-keyframes fadeOutUpBig {
0% {
opacity: 1;
-o-transform: translateY(0);
}
100% {
opacity: 0;
-o-transform: translateY(-2000px);
}
}
@keyframes fadeOutUpBig {
0% {
opacity: 1;
transform: translateY(0);
}
100% {
opacity: 0;
transform: translateY(-2000px);
}
}
.fadeOutUpBig {
-webkit-animation-name: fadeOutUpBig;
-moz-animation-name: fadeOutUpBig;
-o-animation-name: fadeOutUpBig;
animation-name: fadeOutUpBig;
}
@-webkit-keyframes fadeOutDownBig {
0% {
opacity: 1;
-webkit-transform: translateY(0);
}
100% {
opacity: 0;
-webkit-transform: translateY(2000px);
}
}
@-moz-keyframes fadeOutDownBig {
0% {
opacity: 1;
-moz-transform: translateY(0);
}
100% {
opacity: 0;
-moz-transform: translateY(2000px);
}
}
@-o-keyframes fadeOutDownBig {
0% {
opacity: 1;
-o-transform: translateY(0);
}
100% {
opacity: 0;
-o-transform: translateY(2000px);
}
}
@keyframes fadeOutDownBig {
0% {
opacity: 1;
transform: translateY(0);
}
100% {
opacity: 0;
transform: translateY(2000px);
}
}
.fadeOutDownBig {
-webkit-animation-name: fadeOutDownBig;
-moz-animation-name: fadeOutDownBig;
-o-animation-name: fadeOutDownBig;
animation-name: fadeOutDownBig;
}
@-webkit-keyframes fadeOutLeftBig {
0% {
opacity: 1;
-webkit-transform: translateX(0);
}
100% {
opacity: 0;
-webkit-transform: translateX(-2000px);
}
}
@-moz-keyframes fadeOutLeftBig {
0% {
opacity: 1;
-moz-transform: translateX(0);
}
100% {
opacity: 0;
-moz-transform: translateX(-2000px);
}
}
@-o-keyframes fadeOutLeftBig {
0% {
opacity: 1;
-o-transform: translateX(0);
}
100% {
opacity: 0;
-o-transform: translateX(-2000px);
}
}
@keyframes fadeOutLeftBig {
0% {
opacity: 1;
transform: translateX(0);
}
100% {
opacity: 0;
transform: translateX(-2000px);
}
}
.fadeOutLeftBig {
-webkit-animation-name: fadeOutLeftBig;
-moz-animation-name: fadeOutLeftBig;
-o-animation-name: fadeOutLeftBig;
animation-name: fadeOutLeftBig;
}
@-webkit-keyframes fadeOutRightBig {
0% {
opacity: 1;
-webkit-transform: translateX(0);
}
100% {
opacity: 0;
-webkit-transform: translateX(2000px);
}
}
@-moz-keyframes fadeOutRightBig {
0% {
opacity: 1;
-moz-transform: translateX(0);
}
100% {
opacity: 0;
-moz-transform: translateX(2000px);
}
}
@-o-keyframes fadeOutRightBig {
0% {
opacity: 1;
-o-transform: translateX(0);
}
100% {
opacity: 0;
-o-transform: translateX(2000px);
}
}
@keyframes fadeOutRightBig {
0% {
opacity: 1;
transform: translateX(0);
}
100% {
opacity: 0;
transform: translateX(2000px);
}
}
.fadeOutRightBig {
-webkit-animation-name: fadeOutRightBig;
-moz-animation-name: fadeOutRightBig;
-o-animation-name: fadeOutRightBig;
animation-name: fadeOutRightBig;
}
@-webkit-keyframes bounceIn {
0% {
opacity: 0;
-webkit-transform: scale(.3);
}
50% {
opacity: 1;
-webkit-transform: scale(1.05);
}
70% {
-webkit-transform: scale(.9);
}
100% {
-webkit-transform: scale(1);
}
}
@-moz-keyframes bounceIn {
0% {
opacity: 0;
-moz-transform: scale(.3);
}
50% {
opacity: 1;
-moz-transform: scale(1.05);
}
70% {
-moz-transform: scale(.9);
}
100% {
-moz-transform: scale(1);
}
}
@-o-keyframes bounceIn {
0% {
opacity: 0;
-o-transform: scale(.3);
}
50% {
opacity: 1;
-o-transform: scale(1.05);
}
70% {
-o-transform: scale(.9);
}
100% {
-o-transform: scale(1);
}
}
@keyframes bounceIn {
0% {
opacity: 0;
transform: scale(.3);
}
50% {
opacity: 1;
transform: scale(1.05);
}
70% {
transform: scale(.9);
}
100% {
transform: scale(1);
}
}
.bounceIn {
-webkit-animation-name: bounceIn;
-moz-animation-name: bounceIn;
-o-animation-name: bounceIn;
animation-name: bounceIn;
}
@-webkit-keyframes bounceInUp {
0% {
opacity: 0;
-webkit-transform: translateY(2000px);
}
60% {
opacity: 1;
-webkit-transform: translateY(-30px);
}
80% {
-webkit-transform: translateY(10px);
}
100% {
-webkit-transform: translateY(0);
}
}
@-moz-keyframes bounceInUp {
0% {
opacity: 0;
-moz-transform: translateY(2000px);
}
60% {
opacity: 1;
-moz-transform: translateY(-30px);
}
80% {
-moz-transform: translateY(10px);
}
100% {
-moz-transform: translateY(0);
}
}
@-o-keyframes bounceInUp {
0% {
opacity: 0;
-o-transform: translateY(2000px);
}
60% {
opacity: 1;
-o-transform: translateY(-30px);
}
80% {
-o-transform: translateY(10px);
}
100% {
-o-transform: translateY(0);
}
}
@keyframes bounceInUp {
0% {
opacity: 0;
transform: translateY(2000px);
}
60% {
opacity: 1;
transform: translateY(-30px);
}
80% {
transform: translateY(10px);
}
100% {
transform: translateY(0);
}
}
.bounceInUp {
-webkit-animation-name: bounceInUp;
-moz-animation-name: bounceInUp;
-o-animation-name: bounceInUp;
animation-name: bounceInUp;
}
@-webkit-keyframes bounceInDown {
0% {
opacity: 0;
-webkit-transform: translateY(-2000px);
}
60% {
opacity: 1;
-webkit-transform: translateY(30px);
}
80% {
-webkit-transform: translateY(-10px);
}
100% {
-webkit-transform: translateY(0);
}
}
@-moz-keyframes bounceInDown {
0% {
opacity: 0;
-moz-transform: translateY(-2000px);
}
60% {
opacity: 1;
-moz-transform: translateY(30px);
}
80% {
-moz-transform: translateY(-10px);
}
100% {
-moz-transform: translateY(0);
}
}
@-o-keyframes bounceInDown {
0% {
opacity: 0;
-o-transform: translateY(-2000px);
}
60% {
opacity: 1;
-o-transform: translateY(30px);
}
80% {
-o-transform: translateY(-10px);
}
100% {
-o-transform: translateY(0);
}
}
@keyframes bounceInDown {
0% {
opacity: 0;
transform: translateY(-2000px);
}
60% {
opacity: 1;
transform: translateY(30px);
}
80% {
transform: translateY(-10px);
}
100% {
transform: translateY(0);
}
}
.bounceInDown {
-webkit-animation-name: bounceInDown;
-moz-animation-name: bounceInDown;
-o-animation-name: bounceInDown;
animation-name: bounceInDown;
}
@-webkit-keyframes bounceInLeft {
0% {
opacity: 0;
-webkit-transform: translateX(-2000px);
}
60% {
opacity: 1;
-webkit-transform: translateX(30px);
}
80% {
-webkit-transform: translateX(-10px);
}
100% {
-webkit-transform: translateX(0);
}
}
@-moz-keyframes bounceInLeft {
0% {
opacity: 0;
-moz-transform: translateX(-2000px);
}
60% {
opacity: 1;
-moz-transform: translateX(30px);
}
80% {
-moz-transform: translateX(-10px);
}
100% {
-moz-transform: translateX(0);
}
}
@-o-keyframes bounceInLeft {
0% {
opacity: 0;
-o-transform: translateX(-2000px);
}
60% {
opacity: 1;
-o-transform: translateX(30px);
}
80% {
-o-transform: translateX(-10px);
}
100% {
-o-transform: translateX(0);
}
}
@keyframes bounceInLeft {
0% {
opacity: 0;
transform: translateX(-2000px);
}
60% {
opacity: 1;
transform: translateX(30px);
}
80% {
transform: translateX(-10px);
}
100% {
transform: translateX(0);
}
}
.bounceInLeft {
-webkit-animation-name: bounceInLeft;
-moz-animation-name: bounceInLeft;
-o-animation-name: bounceInLeft;
animation-name: bounceInLeft;
}
@-webkit-keyframes bounceInRight {
0% {
opacity: 0;
-webkit-transform: translateX(2000px);
}
60% {
opacity: 1;
-webkit-transform: translateX(-30px);
}
80% {
-webkit-transform: translateX(10px);
}
100% {
-webkit-transform: translateX(0);
}
}
@-moz-keyframes bounceInRight {
0% {
opacity: 0;
-moz-transform: translateX(2000px);
}
60% {
opacity: 1;
-moz-transform: translateX(-30px);
}
80% {
-moz-transform: translateX(10px);
}
100% {
-moz-transform: translateX(0);
}
}
@-o-keyframes bounceInRight {
0% {
opacity: 0;
-o-transform: translateX(2000px);
}
60% {
opacity: 1;
-o-transform: translateX(-30px);
}
80% {
-o-transform: translateX(10px);
}
100% {
-o-transform: translateX(0);
}
}
@keyframes bounceInRight {
0% {
opacity: 0;
transform: translateX(2000px);
}
60% {
opacity: 1;
transform: translateX(-30px);
}
80% {
transform: translateX(10px);
}
100% {
transform: translateX(0);
}
}
.bounceInRight {
-webkit-animation-name: bounceInRight;
-moz-animation-name: bounceInRight;
-o-animation-name: bounceInRight;
animation-name: bounceInRight;
}
@-webkit-keyframes bounceOut {
0% {
-webkit-transform: scale(1);
}
25% {
-webkit-transform: scale(.95);
}
50% {
opacity: 1;
-webkit-transform: scale(1.1);
}
100% {
opacity: 0;
-webkit-transform: scale(.3);
}
}
@-moz-keyframes bounceOut {
0% {
-moz-transform: scale(1);
}
25% {
-moz-transform: scale(.95);
}
50% {
opacity: 1;
-moz-transform: scale(1.1);
}
100% {
opacity: 0;
-moz-transform: scale(.3);
}
}
@-o-keyframes bounceOut {
0% {
-o-transform: scale(1);
}
25% {
-o-transform: scale(.95);
}
50% {
opacity: 1;
-o-transform: scale(1.1);
}
100% {
opacity: 0;
-o-transform: scale(.3);
}
}
@keyframes bounceOut {
0% {
transform: scale(1);
}
25% {
transform: scale(.95);
}
50% {
opacity: 1;
transform: scale(1.1);
}
100% {
opacity: 0;
transform: scale(.3);
}
}
.bounceOut {
-webkit-animation-name: bounceOut;
-moz-animation-name: bounceOut;
-o-animation-name: bounceOut;
animation-name: bounceOut;
}
@-webkit-keyframes bounceOutUp {
0% {
-webkit-transform: translateY(0);
}
20% {
opacity: 1;
-webkit-transform: translateY(20px);
}
100% {
opacity: 0;
-webkit-transform: translateY(-2000px);
}
}
@-moz-keyframes bounceOutUp {
0% {
-moz-transform: translateY(0);
}
20% {
opacity: 1;
-moz-transform: translateY(20px);
}
100% {
opacity: 0;
-moz-transform: translateY(-2000px);
}
}
@-o-keyframes bounceOutUp {
0% {
-o-transform: translateY(0);
}
20% {
opacity: 1;
-o-transform: translateY(20px);
}
100% {
opacity: 0;
-o-transform: translateY(-2000px);
}
}
@keyframes bounceOutUp {
0% {
transform: translateY(0);
}
20% {
opacity: 1;
transform: translateY(20px);
}
100% {
opacity: 0;
transform: translateY(-2000px);
}
}
.bounceOutUp {
-webkit-animation-name: bounceOutUp;
-moz-animation-name: bounceOutUp;
-o-animation-name: bounceOutUp;
animation-name: bounceOutUp;
}
@-webkit-keyframes bounceOutDown {
0% {
-webkit-transform: translateY(0);
}
20% {
opacity: 1;
-webkit-transform: translateY(-20px);
}
100% {
opacity: 0;
-webkit-transform: translateY(2000px);
}
}
@-moz-keyframes bounceOutDown {
0% {
-moz-transform: translateY(0);
}
20% {
opacity: 1;
-moz-transform: translateY(-20px);
}
100% {
opacity: 0;
-moz-transform: translateY(2000px);
}
}
@-o-keyframes bounceOutDown {
0% {
-o-transform: translateY(0);
}
20% {
opacity: 1;
-o-transform: translateY(-20px);
}
100% {
opacity: 0;
-o-transform: translateY(2000px);
}
}
@keyframes bounceOutDown {
0% {
transform: translateY(0);
}
20% {
opacity: 1;
transform: translateY(-20px);
}
100% {
opacity: 0;
transform: translateY(2000px);
}
}
.bounceOutDown {
-webkit-animation-name: bounceOutDown;
-moz-animation-name: bounceOutDown;
-o-animation-name: bounceOutDown;
animation-name: bounceOutDown;
}
@-webkit-keyframes bounceOutLeft {
0% {
-webkit-transform: translateX(0);
}
20% {
opacity: 1;
-webkit-transform: translateX(20px);
}
100% {
opacity: 0;
-webkit-transform: translateX(-2000px);
}
}
@-moz-keyframes bounceOutLeft {
0% {
-moz-transform: translateX(0);
}
20% {
opacity: 1;
-moz-transform: translateX(20px);
}
100% {
opacity: 0;
-moz-transform: translateX(-2000px);
}
}
@-o-keyframes bounceOutLeft {
0% {
-o-transform: translateX(0);
}
20% {
opacity: 1;
-o-transform: translateX(20px);
}
100% {
opacity: 0;
-o-transform: translateX(-2000px);
}
}
@keyframes bounceOutLeft {
0% {
transform: translateX(0);
}
20% {
opacity: 1;
transform: translateX(20px);
}
100% {
opacity: 0;
transform: translateX(-2000px);
}
}
.bounceOutLeft {
-webkit-animation-name: bounceOutLeft;
-moz-animation-name: bounceOutLeft;
-o-animation-name: bounceOutLeft;
animation-name: bounceOutLeft;
}
@-webkit-keyframes bounceOutRight {
0% {
-webkit-transform: translateX(0);
}
20% {
opacity: 1;
-webkit-transform: translateX(-20px);
}
100% {
opacity: 0;
-webkit-transform: translateX(2000px);
}
}
@-moz-keyframes bounceOutRight {
0% {
-moz-transform: translateX(0);
}
20% {
opacity: 1;
-moz-transform: translateX(-20px);
}
100% {
opacity: 0;
-moz-transform: translateX(2000px);
}
}
@-o-keyframes bounceOutRight {
0% {
-o-transform: translateX(0);
}
20% {
opacity: 1;
-o-transform: translateX(-20px);
}
100% {
opacity: 0;
-o-transform: translateX(2000px);
}
}
@keyframes bounceOutRight {
0% {
transform: translateX(0);
}
20% {
opacity: 1;
transform: translateX(-20px);
}
100% {
opacity: 0;
transform: translateX(2000px);
}
}
.bounceOutRight {
-webkit-animation-name: bounceOutRight;
-moz-animation-name: bounceOutRight;
-o-animation-name: bounceOutRight;
animation-name: bounceOutRight;
}
@-webkit-keyframes rotateIn {
0% {
-webkit-transform-origin: center center;
-webkit-transform: rotate(-200deg);
opacity: 0;
}
100% {
-webkit-transform-origin: center center;
-webkit-transform: rotate(0);
opacity: 1;
}
}
@-moz-keyframes rotateIn {
0% {
-moz-transform-origin: center center;
-moz-transform: rotate(-200deg);
opacity: 0;
}
100% {
-moz-transform-origin: center center;
-moz-transform: rotate(0);
opacity: 1;
}
}
@-o-keyframes rotateIn {
0% {
-o-transform-origin: center center;
-o-transform: rotate(-200deg);
opacity: 0;
}
100% {
-o-transform-origin: center center;
-o-transform: rotate(0);
opacity: 1;
}
}
@keyframes rotateIn {
0% {
transform-origin: center center;
transform: rotate(-200deg);
opacity: 0;
}
100% {
transform-origin: center center;
transform: rotate(0);
opacity: 1;
}
}
.rotateIn {
-webkit-animation-name: rotateIn;
-moz-animation-name: rotateIn;
-o-animation-name: rotateIn;
animation-name: rotateIn;
}
@-webkit-keyframes rotateInUpLeft {
0% {
-webkit-transform-origin: left bottom;
-webkit-transform: rotate(90deg);
opacity: 0;
}
100% {
-webkit-transform-origin: left bottom;
-webkit-transform: rotate(0);
opacity: 1;
}
}
@-moz-keyframes rotateInUpLeft {
0% {
-moz-transform-origin: left bottom;
-moz-transform: rotate(90deg);
opacity: 0;
}
100% {
-moz-transform-origin: left bottom;
-moz-transform: rotate(0);
opacity: 1;
}
}
@-o-keyframes rotateInUpLeft {
0% {
-o-transform-origin: left bottom;
-o-transform: rotate(90deg);
opacity: 0;
}
100% {
-o-transform-origin: left bottom;
-o-transform: rotate(0);
opacity: 1;
}
}
@keyframes rotateInUpLeft {
0% {
transform-origin: left bottom;
transform: rotate(90deg);
opacity: 0;
}
100% {
transform-origin: left bottom;
transform: rotate(0);
opacity: 1;
}
}
.rotateInUpLeft {
-webkit-animation-name: rotateInUpLeft;
-moz-animation-name: rotateInUpLeft;
-o-animation-name: rotateInUpLeft;
animation-name: rotateInUpLeft;
}
@-webkit-keyframes rotateInDownLeft {
0% {
-webkit-transform-origin: left bottom;
-webkit-transform: rotate(-90deg);
opacity: 0;
}
100% {
-webkit-transform-origin: left bottom;
-webkit-transform: rotate(0);
opacity: 1;
}
}
@-moz-keyframes rotateInDownLeft {
0% {
-moz-transform-origin: left bottom;
-moz-transform: rotate(-90deg);
opacity: 0;
}
100% {
-moz-transform-origin: left bottom;
-moz-transform: rotate(0);
opacity: 1;
}
}
@-o-keyframes rotateInDownLeft {
0% {
-o-transform-origin: left bottom;
-o-transform: rotate(-90deg);
opacity: 0;
}
100% {
-o-transform-origin: left bottom;
-o-transform: rotate(0);
opacity: 1;
}
}
@keyframes rotateInDownLeft {
0% {
transform-origin: left bottom;
transform: rotate(-90deg);
opacity: 0;
}
100% {
transform-origin: left bottom;
transform: rotate(0);
opacity: 1;
}
}
.rotateInDownLeft {
-webkit-animation-name: rotateInDownLeft;
-moz-animation-name: rotateInDownLeft;
-o-animation-name: rotateInDownLeft;
animation-name: rotateInDownLeft;
}
@-webkit-keyframes rotateInUpRight {
0% {
-webkit-transform-origin: right bottom;
-webkit-transform: rotate(-90deg);
opacity: 0;
}
100% {
-webkit-transform-origin: right bottom;
-webkit-transform: rotate(0);
opacity: 1;
}
}
@-moz-keyframes rotateInUpRight {
0% {
-moz-transform-origin: right bottom;
-moz-transform: rotate(-90deg);
opacity: 0;
}
100% {
-moz-transform-origin: right bottom;
-moz-transform: rotate(0);
opacity: 1;
}
}
@-o-keyframes rotateInUpRight {
0% {
-o-transform-origin: right bottom;
-o-transform: rotate(-90deg);
opacity: 0;
}
100% {
-o-transform-origin: right bottom;
-o-transform: rotate(0);
opacity: 1;
}
}
@keyframes rotateInUpRight {
0% {
transform-origin: right bottom;
transform: rotate(-90deg);
opacity: 0;
}
100% {
transform-origin: right bottom;
transform: rotate(0);
opacity: 1;
}
}
.rotateInUpRight {
-webkit-animation-name: rotateInUpRight;
-moz-animation-name: rotateInUpRight;
-o-animation-name: rotateInUpRight;
animation-name: rotateInUpRight;
}
@-webkit-keyframes rotateInDownRight {
0% {
-webkit-transform-origin: right bottom;
-webkit-transform: rotate(90deg);
opacity: 0;
}
100% {
-webkit-transform-origin: right bottom;
-webkit-transform: rotate(0);
opacity: 1;
}
}
@-moz-keyframes rotateInDownRight {
0% {
-moz-transform-origin: right bottom;
-moz-transform: rotate(90deg);
opacity: 0;
}
100% {
-moz-transform-origin: right bottom;
-moz-transform: rotate(0);
opacity: 1;
}
}
@-o-keyframes rotateInDownRight {
0% {
-o-transform-origin: right bottom;
-o-transform: rotate(90deg);
opacity: 0;
}
100% {
-o-transform-origin: right bottom;
-o-transform: rotate(0);
opacity: 1;
}
}
@keyframes rotateInDownRight {
0% {
transform-origin: right bottom;
transform: rotate(90deg);
opacity: 0;
}
100% {
transform-origin: right bottom;
transform: rotate(0);
opacity: 1;
}
}
.rotateInDownRight {
-webkit-animation-name: rotateInDownRight;
-moz-animation-name: rotateInDownRight;
-o-animation-name: rotateInDownRight;
animation-name: rotateInDownRight;
}
@-webkit-keyframes rotateOut {
0% {
-webkit-transform-origin: center center;
-webkit-transform: rotate(0);
opacity: 1;
}
100% {
-webkit-transform-origin: center center;
-webkit-transform: rotate(200deg);
opacity: 0;
}
}
@-moz-keyframes rotateOut {
0% {
-moz-transform-origin: center center;
-moz-transform: rotate(0);
opacity: 1;
}
100% {
-moz-transform-origin: center center;
-moz-transform: rotate(200deg);
opacity: 0;
}
}
@-o-keyframes rotateOut {
0% {
-o-transform-origin: center center;
-o-transform: rotate(0);
opacity: 1;
}
100% {
-o-transform-origin: center center;
-o-transform: rotate(200deg);
opacity: 0;
}
}
@keyframes rotateOut {
0% {
transform-origin: center center;
transform: rotate(0);
opacity: 1;
}
100% {
transform-origin: center center;
transform: rotate(200deg);
opacity: 0;
}
}
.rotateOut {
-webkit-animation-name: rotateOut;
-moz-animation-name: rotateOut;
-o-animation-name: rotateOut;
animation-name: rotateOut;
}
@-webkit-keyframes rotateOutUpLeft {
0% {
-webkit-transform-origin: left bottom;
-webkit-transform: rotate(0);
opacity: 1;
}
100% {
-webkit-transform-origin: left bottom;
-webkit-transform: rotate(-90deg);
opacity: 0;
}
}
@-moz-keyframes rotateOutUpLeft {
0% {
-moz-transform-origin: left bottom;
-moz-transform: rotate(0);
opacity: 1;
}
100% {
-moz-transform-origin: left bottom;
-moz-transform: rotate(-90deg);
opacity: 0;
}
}
@-o-keyframes rotateOutUpLeft {
0% {
-o-transform-origin: left bottom;
-o-transform: rotate(0);
opacity: 1;
}
100% {
-o-transform-origin: left bottom;
-o-transform: rotate(-90deg);
opacity: 0;
}
}
@keyframes rotateOutUpLeft {
0% {
transform-origin: left bottom;
transform: rotate(0);
opacity: 1;
}
100% {
transform-origin: left bottom;
transform: rotate(-90deg);
opacity: 0;
}
}
.rotateOutUpLeft {
-webkit-animation-name: rotateOutUpLeft;
-moz-animation-name: rotateOutUpLeft;
-o-animation-name: rotateOutUpLeft;
animation-name: rotateOutUpLeft;
}
@-webkit-keyframes rotateOutDownLeft {
0% {
-webkit-transform-origin: left bottom;
-webkit-transform: rotate(0);
opacity: 1;
}
100% {
-webkit-transform-origin: left bottom;
-webkit-transform: rotate(90deg);
opacity: 0;
}
}
@-moz-keyframes rotateOutDownLeft {
0% {
-moz-transform-origin: left bottom;
-moz-transform: rotate(0);
opacity: 1;
}
100% {
-moz-transform-origin: left bottom;
-moz-transform: rotate(90deg);
opacity: 0;
}
}
@-o-keyframes rotateOutDownLeft {
0% {
-o-transform-origin: left bottom;
-o-transform: rotate(0);
opacity: 1;
}
100% {
-o-transform-origin: left bottom;
-o-transform: rotate(90deg);
opacity: 0;
}
}
@keyframes rotateOutDownLeft {
0% {
transform-origin: left bottom;
transform: rotate(0);
opacity: 1;
}
100% {
transform-origin: left bottom;
transform: rotate(90deg);
opacity: 0;
}
}
.rotateOutDownLeft {
-webkit-animation-name: rotateOutDownLeft;
-moz-animation-name: rotateOutDownLeft;
-o-animation-name: rotateOutDownLeft;
animation-name: rotateOutDownLeft;
}
@-webkit-keyframes rotateOutUpRight {
0% {
-webkit-transform-origin: right bottom;
-webkit-transform: rotate(0);
opacity: 1;
}
100% {
-webkit-transform-origin: right bottom;
-webkit-transform: rotate(90deg);
opacity: 0;
}
}
@-moz-keyframes rotateOutUpRight {
0% {
-moz-transform-origin: right bottom;
-moz-transform: rotate(0);
opacity: 1;
}
100% {
-moz-transform-origin: right bottom;
-moz-transform: rotate(90deg);
opacity: 0;
}
}
@-o-keyframes rotateOutUpRight {
0% {
-o-transform-origin: right bottom;
-o-transform: rotate(0);
opacity: 1;
}
100% {
-o-transform-origin: right bottom;
-o-transform: rotate(90deg);
opacity: 0;
}
}
@keyframes rotateOutUpRight {
0% {
transform-origin: right bottom;
transform: rotate(0);
opacity: 1;
}
100% {
transform-origin: right bottom;
transform: rotate(90deg);
opacity: 0;
}
}
.rotateOutUpRight {
-webkit-animation-name: rotateOutUpRight;
-moz-animation-name: rotateOutUpRight;
-o-animation-name: rotateOutUpRight;
animation-name: rotateOutUpRight;
}
@-webkit-keyframes rotateOutDownRight {
0% {
-webkit-transform-origin: right bottom;
-webkit-transform: rotate(0);
opacity: 1;
}
100% {
-webkit-transform-origin: right bottom;
-webkit-transform: rotate(-90deg);
opacity: 0;
}
}
@-moz-keyframes rotateOutDownRight {
0% {
-moz-transform-origin: right bottom;
-moz-transform: rotate(0);
opacity: 1;
}
100% {
-moz-transform-origin: right bottom;
-moz-transform: rotate(-90deg);
opacity: 0;
}
}
@-o-keyframes rotateOutDownRight {
0% {
-o-transform-origin: right bottom;
-o-transform: rotate(0);
opacity: 1;
}
100% {
-o-transform-origin: right bottom;
-o-transform: rotate(-90deg);
opacity: 0;
}
}
@keyframes rotateOutDownRight {
0% {
transform-origin: right bottom;
transform: rotate(0);
opacity: 1;
}
100% {
transform-origin: right bottom;
transform: rotate(-90deg);
opacity: 0;
}
}
.rotateOutDownRight {
-webkit-animation-name: rotateOutDownRight;
-moz-animation-name: rotateOutDownRight;
-o-animation-name: rotateOutDownRight;
animation-name: rotateOutDownRight;
}
@-webkit-keyframes hinge {
0% { -webkit-transform: rotate(0); -webkit-transform-origin: top left; -webkit-animation-timing-function: ease-in-out; }
20%, 60% { -webkit-transform: rotate(80deg); -webkit-transform-origin: top left; -webkit-animation-timing-function: ease-in-out; }
40% { -webkit-transform: rotate(60deg); -webkit-transform-origin: top left; -webkit-animation-timing-function: ease-in-out; }
80% { -webkit-transform: rotate(60deg) translateY(0); opacity: 1; -webkit-transform-origin: top left; -webkit-animation-timing-function: ease-in-out; }
100% { -webkit-transform: translateY(700px); opacity: 0; }
}
@-moz-keyframes hinge {
0% { -moz-transform: rotate(0); -moz-transform-origin: top left; -moz-animation-timing-function: ease-in-out; }
20%, 60% { -moz-transform: rotate(80deg); -moz-transform-origin: top left; -moz-animation-timing-function: ease-in-out; }
40% { -moz-transform: rotate(60deg); -moz-transform-origin: top left; -moz-animation-timing-function: ease-in-out; }
80% { -moz-transform: rotate(60deg) translateY(0); opacity: 1; -moz-transform-origin: top left; -moz-animation-timing-function: ease-in-out; }
100% { -moz-transform: translateY(700px); opacity: 0; }
}
@-o-keyframes hinge {
0% { -o-transform: rotate(0); -o-transform-origin: top left; -o-animation-timing-function: ease-in-out; }
20%, 60% { -o-transform: rotate(80deg); -o-transform-origin: top left; -o-animation-timing-function: ease-in-out; }
40% { -o-transform: rotate(60deg); -o-transform-origin: top left; -o-animation-timing-function: ease-in-out; }
80% { -o-transform: rotate(60deg) translateY(0); opacity: 1; -o-transform-origin: top left; -o-animation-timing-function: ease-in-out; }
100% { -o-transform: translateY(700px); opacity: 0; }
}
@keyframes hinge {
0% { transform: rotate(0); transform-origin: top left; animation-timing-function: ease-in-out; }
20%, 60% { transform: rotate(80deg); transform-origin: top left; animation-timing-function: ease-in-out; }
40% { transform: rotate(60deg); transform-origin: top left; animation-timing-function: ease-in-out; }
80% { transform: rotate(60deg) translateY(0); opacity: 1; transform-origin: top left; animation-timing-function: ease-in-out; }
100% { transform: translateY(700px); opacity: 0; }
}
.hinge {
-webkit-animation-name: hinge;
-moz-animation-name: hinge;
-o-animation-name: hinge;
animation-name: hinge;
}
/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */
@-webkit-keyframes rollIn {
0% { opacity: 0; -webkit-transform: translateX(-100%) rotate(-120deg); }
100% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); }
}
@-moz-keyframes rollIn {
0% { opacity: 0; -moz-transform: translateX(-100%) rotate(-120deg); }
100% { opacity: 1; -moz-transform: translateX(0px) rotate(0deg); }
}
@-o-keyframes rollIn {
0% { opacity: 0; -o-transform: translateX(-100%) rotate(-120deg); }
100% { opacity: 1; -o-transform: translateX(0px) rotate(0deg); }
}
@keyframes rollIn {
0% { opacity: 0; transform: translateX(-100%) rotate(-120deg); }
100% { opacity: 1; transform: translateX(0px) rotate(0deg); }
}
.rollIn {
-webkit-animation-name: rollIn;
-moz-animation-name: rollIn;
-o-animation-name: rollIn;
animation-name: rollIn;
}
/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */
@-webkit-keyframes rollOut {
0% {
opacity: 1;
-webkit-transform: translateX(0px) rotate(0deg);
}
100% {
opacity: 0;
-webkit-transform: translateX(100%) rotate(120deg);
}
}
@-moz-keyframes rollOut {
0% {
opacity: 1;
-moz-transform: translateX(0px) rotate(0deg);
}
100% {
opacity: 0;
-moz-transform: translateX(100%) rotate(120deg);
}
}
@-o-keyframes rollOut {
0% {
opacity: 1;
-o-transform: translateX(0px) rotate(0deg);
}
100% {
opacity: 0;
-o-transform: translateX(100%) rotate(120deg);
}
}
@keyframes rollOut {
0% {
opacity: 1;
transform: translateX(0px) rotate(0deg);
}
100% {
opacity: 0;
transform: translateX(100%) rotate(120deg);
}
}
.rollOut {
-webkit-animation-name: rollOut;
-moz-animation-name: rollOut;
-o-animation-name: rollOut;
animation-name: rollOut;
}
/* originally authored by Angelo Rohit - https://github.com/angelorohit */
@-webkit-keyframes lightSpeedIn {
0% { -webkit-transform: translateX(100%) skewX(-30deg); opacity: 0; }
60% { -webkit-transform: translateX(-20%) skewX(30deg); opacity: 1; }
80% { -webkit-transform: translateX(0%) skewX(-15deg); opacity: 1; }
100% { -webkit-transform: translateX(0%) skewX(0deg); opacity: 1; }
}
@-moz-keyframes lightSpeedIn {
0% { -moz-transform: translateX(100%) skewX(-30deg); opacity: 0; }
60% { -moz-transform: translateX(-20%) skewX(30deg); opacity: 1; }
80% { -moz-transform: translateX(0%) skewX(-15deg); opacity: 1; }
100% { -moz-transform: translateX(0%) skewX(0deg); opacity: 1; }
}
@-o-keyframes lightSpeedIn {
0% { -o-transform: translateX(100%) skewX(-30deg); opacity: 0; }
60% { -o-transform: translateX(-20%) skewX(30deg); opacity: 1; }
80% { -o-transform: translateX(0%) skewX(-15deg); opacity: 1; }
100% { -o-transform: translateX(0%) skewX(0deg); opacity: 1; }
}
@keyframes lightSpeedIn {
0% { transform: translateX(100%) skewX(-30deg); opacity: 0; }
60% { transform: translateX(-20%) skewX(30deg); opacity: 1; }
80% { transform: translateX(0%) skewX(-15deg); opacity: 1; }
100% { transform: translateX(0%) skewX(0deg); opacity: 1; }
}
.lightSpeedIn {
-webkit-animation-name: lightSpeedIn;
-moz-animation-name: lightSpeedIn;
-o-animation-name: lightSpeedIn;
animation-name: lightSpeedIn;
-webkit-animation-timing-function: ease-out;
-moz-animation-timing-function: ease-out;
-o-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
.animated.lightSpeedIn {
-webkit-animation-duration: 0.5s;
-moz-animation-duration: 0.5s;
-o-animation-duration: 0.5s;
animation-duration: 0.5s;
}
/* originally authored by Angelo Rohit - https://github.com/angelorohit */
@-webkit-keyframes lightSpeedOut {
0% { -webkit-transform: translateX(0%) skewX(0deg); opacity: 1; }
100% { -webkit-transform: translateX(100%) skewX(-30deg); opacity: 0; }
}
@-moz-keyframes lightSpeedOut {
0% { -moz-transform: translateX(0%) skewX(0deg); opacity: 1; }
100% { -moz-transform: translateX(100%) skewX(-30deg); opacity: 0; }
}
@-o-keyframes lightSpeedOut {
0% { -o-transform: translateX(0%) skewX(0deg); opacity: 1; }
100% { -o-transform: translateX(100%) skewX(-30deg); opacity: 0; }
}
@keyframes lightSpeedOut {
0% { transform: translateX(0%) skewX(0deg); opacity: 1; }
100% { transform: translateX(100%) skewX(-30deg); opacity: 0; }
}
.lightSpeedOut {
-webkit-animation-name: lightSpeedOut;
-moz-animation-name: lightSpeedOut;
-o-animation-name: lightSpeedOut;
animation-name: lightSpeedOut;
-webkit-animation-timing-function: ease-in;
-moz-animation-timing-function: ease-in;
-o-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
.animated.lightSpeedOut {
-webkit-animation-duration: 0.25s;
-moz-animation-duration: 0.25s;
-o-animation-duration: 0.25s;
animation-duration: 0.25s;
}
/* originally authored by Angelo Rohit - https://github.com/angelorohit */
@-webkit-keyframes wiggle {
0% { -webkit-transform: skewX(9deg); }
10% { -webkit-transform: skewX(-8deg); }
20% { -webkit-transform: skewX(7deg); }
30% { -webkit-transform: skewX(-6deg); }
40% { -webkit-transform: skewX(5deg); }
50% { -webkit-transform: skewX(-4deg); }
60% { -webkit-transform: skewX(3deg); }
70% { -webkit-transform: skewX(-2deg); }
80% { -webkit-transform: skewX(1deg); }
90% { -webkit-transform: skewX(0deg); }
100% { -webkit-transform: skewX(0deg); }
}
@-moz-keyframes wiggle {
0% { -moz-transform: skewX(9deg); }
10% { -moz-transform: skewX(-8deg); }
20% { -moz-transform: skewX(7deg); }
30% { -moz-transform: skewX(-6deg); }
40% { -moz-transform: skewX(5deg); }
50% { -moz-transform: skewX(-4deg); }
60% { -moz-transform: skewX(3deg); }
70% { -moz-transform: skewX(-2deg); }
80% { -moz-transform: skewX(1deg); }
90% { -moz-transform: skewX(0deg); }
100% { -moz-transform: skewX(0deg); }
}
@-o-keyframes wiggle {
0% { -o-transform: skewX(9deg); }
10% { -o-transform: skewX(-8deg); }
20% { -o-transform: skewX(7deg); }
30% { -o-transform: skewX(-6deg); }
40% { -o-transform: skewX(5deg); }
50% { -o-transform: skewX(-4deg); }
60% { -o-transform: skewX(3deg); }
70% { -o-transform: skewX(-2deg); }
80% { -o-transform: skewX(1deg); }
90% { -o-transform: skewX(0deg); }
100% { -o-transform: skewX(0deg); }
}
@keyframes wiggle {
0% { transform: skewX(9deg); }
10% { transform: skewX(-8deg); }
20% { transform: skewX(7deg); }
30% { transform: skewX(-6deg); }
40% { transform: skewX(5deg); }
50% { transform: skewX(-4deg); }
60% { transform: skewX(3deg); }
70% { transform: skewX(-2deg); }
80% { transform: skewX(1deg); }
90% { transform: skewX(0deg); }
100% { transform: skewX(0deg); }
}
.wiggle {
-webkit-animation-name: wiggle;
-moz-animation-name: wiggle;
-o-animation-name: wiggle;
animation-name: wiggle;
-webkit-animation-timing-function: ease-in;
-moz-animation-timing-function: ease-in;
-o-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
.animated.wiggle {
-webkit-animation-duration: 0.75s;
-moz-animation-duration: 0.75s;
-o-animation-duration: 0.75s;
animation-duration: 0.75s;
} | huidos22/huidos22.github.io | css/animate.css | CSS | agpl-3.0 | 61,153 |
<?php
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program 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 SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code 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 "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$app_list_strings['moduleList']['CON_Contratos'] = 'Contratos';
$app_list_strings['con_contratos_type_dom']['Administration'] = 'Administration';
$app_list_strings['con_contratos_type_dom']['Product'] = 'Product';
$app_list_strings['con_contratos_type_dom']['User'] = 'User';
$app_list_strings['con_contratos_status_dom']['New'] = 'New';
$app_list_strings['con_contratos_status_dom']['Assigned'] = 'Assigned';
$app_list_strings['con_contratos_status_dom']['Closed'] = 'Closed';
$app_list_strings['con_contratos_status_dom']['Pending Input'] = 'Pending Input';
$app_list_strings['con_contratos_status_dom']['Rejected'] = 'Rejected';
$app_list_strings['con_contratos_status_dom']['Duplicate'] = 'Duplicate';
$app_list_strings['con_contratos_priority_dom']['P1'] = 'High';
$app_list_strings['con_contratos_priority_dom']['P2'] = 'Medium';
$app_list_strings['con_contratos_priority_dom']['P3'] = 'Low';
$app_list_strings['con_contratos_resolution_dom'][''] = '';
$app_list_strings['con_contratos_resolution_dom']['Accepted'] = 'Accepted';
$app_list_strings['con_contratos_resolution_dom']['Duplicate'] = 'Duplicate';
$app_list_strings['con_contratos_resolution_dom']['Closed'] = 'Closed';
$app_list_strings['con_contratos_resolution_dom']['Out of Date'] = 'Out of Date';
$app_list_strings['con_contratos_resolution_dom']['Invalid'] = 'Invalid';
$app_list_strings['accion_list']['Alta'] = 'Alta';
$app_list_strings['accion_list']['Baja'] = 'Baja';
$app_list_strings['accion_list']['Modificacion'] = 'Modificacion';
$app_list_strings['tipo_contrato_list']['Indefinido'] = 'Indefinido';
$app_list_strings['tipo_contrato_list']['Temporal'] = 'Temporal';
$app_list_strings['tipo_contrato_list']['Obra'] = 'Obra';
$app_list_strings['tipo_contrato_list'][''] = '';
$app_list_strings['categoria_list']['Profesor'] = 'Profesor';
$app_list_strings['categoria_list']['Administrativo'] = 'Administrativo';
$app_list_strings['categoria_list'][''] = '';
$app_list_strings['_type_dom']['Administration'] = 'Administración';
$app_list_strings['_type_dom']['Product'] = 'Producto';
$app_list_strings['_type_dom']['User'] = 'Usuario';
$app_list_strings['_status_dom']['New'] = 'Nuevo';
$app_list_strings['_status_dom']['Assigned'] = 'Asignado';
$app_list_strings['_status_dom']['Closed'] = 'Cerrado';
$app_list_strings['_status_dom']['Pending Input'] = 'Pendiente de Información';
$app_list_strings['_status_dom']['Rejected'] = 'Rechazado';
$app_list_strings['_status_dom']['Duplicate'] = 'Duplicado';
$app_list_strings['_priority_dom']['P1'] = 'Alta';
$app_list_strings['_priority_dom']['P2'] = 'Media';
$app_list_strings['_priority_dom']['P3'] = 'Baja';
$app_list_strings['_resolution_dom'][''] = '';
$app_list_strings['_resolution_dom']['Accepted'] = 'Aceptado';
$app_list_strings['_resolution_dom']['Duplicate'] = 'Duplicado';
$app_list_strings['_resolution_dom']['Closed'] = 'Cerrado';
$app_list_strings['_resolution_dom']['Out of Date'] = 'Caducado';
$app_list_strings['_resolution_dom']['Invalid'] = 'No Válido';
| witxo/bonos | custom/modulebuilder/packages/Contratos/language/application/es_ES.lang.php | PHP | agpl-3.0 | 5,024 |
//
// Copyright (C) 2016 - present Instructure, Inc.
//
// This file is part of Canvas.
//
// Canvas 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, version 3 of the License.
//
// Canvas 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/>.
import _ from 'underscore'
import Depaginate from 'jsx/shared/CheatDepaginator'
const listUrl = () => ENV.ENROLLMENT_TERMS_URL
const deserializeTerms = termGroups =>
_.flatten(
_.map(termGroups, group =>
_.map(group.enrollment_terms, (term) => {
const groupID = term.grading_period_group_id
const newGroupID = _.isNumber(groupID) ? groupID.toString() : groupID
return {
id: term.id.toString(),
name: term.name,
startAt: term.start_at ? new Date(term.start_at) : null,
endAt: term.end_at ? new Date(term.end_at) : null,
createdAt: term.created_at ? new Date(term.created_at) : null,
gradingPeriodGroupId: newGroupID,
}
})
)
)
export default {
list (terms) {
return new Promise((resolve, reject) => {
Depaginate(listUrl())
.then(response => resolve(deserializeTerms(response)))
.fail(error => reject(error))
})
}
}
| venturehive/canvas-lms | app/coffeescripts/api/enrollmentTermsApi.js | JavaScript | agpl-3.0 | 1,662 |
/*======================================================
************ Pull To Refresh ************
======================================================*/
app.initPullToRefresh = function (pageContainer) {
var eventsTarget = $(pageContainer);
if (!eventsTarget.hasClass('pull-to-refresh-content')) {
eventsTarget = eventsTarget.find('.pull-to-refresh-content');
}
if (!eventsTarget || eventsTarget.length === 0) return;
var touchId, isTouched, isMoved, touchesStart = {}, isScrolling, touchesDiff, touchStartTime, container, refresh = false, useTranslate = false, startTranslate = 0, translate, scrollTop, wasScrolled, layer, triggerDistance, dynamicTriggerDistance, pullStarted;
var page = eventsTarget.hasClass('page') ? eventsTarget : eventsTarget.parents('.page');
var hasNavbar = false;
if (page.find('.navbar').length > 0 || page.parents('.navbar-fixed, .navbar-through').length > 0 || page.hasClass('navbar-fixed') || page.hasClass('navbar-through')) hasNavbar = true;
if (page.hasClass('no-navbar')) hasNavbar = false;
if (!hasNavbar) eventsTarget.addClass('pull-to-refresh-no-navbar');
container = eventsTarget;
// Define trigger distance
if (container.attr('data-ptr-distance')) {
dynamicTriggerDistance = true;
}
else {
triggerDistance = 44;
}
function handleTouchStart(e) {
if (isTouched) {
if (app.device.os === 'android') {
if ('targetTouches' in e && e.targetTouches.length > 1) return;
}
else return;
}
/*jshint validthis:true */
container = $(this);
if (container.hasClass('refreshing')) {
return;
}
isMoved = false;
pullStarted = false;
isTouched = true;
isScrolling = undefined;
wasScrolled = undefined;
if (e.type === 'touchstart') touchId = e.targetTouches[0].identifier;
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
touchStartTime = (new Date()).getTime();
}
function handleTouchMove(e) {
if (!isTouched) return;
var pageX, pageY, touch;
if (e.type === 'touchmove') {
if (touchId && e.touches) {
for (var i = 0; i < e.touches.length; i++) {
if (e.touches[i].identifier === touchId) {
touch = e.touches[i];
}
}
}
if (!touch) touch = e.targetTouches[0];
pageX = touch.pageX;
pageY = touch.pageY;
}
else {
pageX = e.pageX;
pageY = e.pageY;
}
if (!pageX || !pageY) return;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x));
}
if (!isScrolling) {
isTouched = false;
return;
}
scrollTop = container[0].scrollTop;
if (typeof wasScrolled === 'undefined' && scrollTop !== 0) wasScrolled = true;
if (!isMoved) {
/*jshint validthis:true */
container.removeClass('transitioning');
if (scrollTop > container[0].offsetHeight) {
isTouched = false;
return;
}
if (dynamicTriggerDistance) {
triggerDistance = container.attr('data-ptr-distance');
if (triggerDistance.indexOf('%') >= 0) triggerDistance = container[0].offsetHeight * parseInt(triggerDistance, 10) / 100;
}
startTranslate = container.hasClass('refreshing') ? triggerDistance : 0;
if (container[0].scrollHeight === container[0].offsetHeight || app.device.os !== 'ios') {
useTranslate = true;
}
else {
useTranslate = false;
}
}
isMoved = true;
touchesDiff = pageY - touchesStart.y;
if (touchesDiff > 0 && scrollTop <= 0 || scrollTop < 0) {
// iOS 8 fix
if (app.device.os === 'ios' && parseInt(app.device.osVersion.split('.')[0], 10) > 7 && scrollTop === 0 && !wasScrolled) useTranslate = true;
if (useTranslate) {
e.preventDefault();
translate = (Math.pow(touchesDiff, 0.85) + startTranslate);
container.transform('translate3d(0,' + translate + 'px,0)');
}
if ((useTranslate && Math.pow(touchesDiff, 0.85) > triggerDistance) || (!useTranslate && touchesDiff >= triggerDistance * 2)) {
refresh = true;
container.addClass('pull-up').removeClass('pull-down');
}
else {
refresh = false;
container.removeClass('pull-up').addClass('pull-down');
}
if (!pullStarted) {
container.trigger('pullstart');
pullStarted = true;
}
container.trigger('pullmove', {
event: e,
scrollTop: scrollTop,
translate: translate,
touchesDiff: touchesDiff
});
}
else {
pullStarted = false;
container.removeClass('pull-up pull-down');
refresh = false;
return;
}
}
function handleTouchEnd(e) {
if (e.type === 'touchend' && e.changedTouches && e.changedTouches.length > 0 && touchId) {
if (e.changedTouches[0].identifier !== touchId) return;
}
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
return;
}
if (translate) {
container.addClass('transitioning');
translate = 0;
}
container.transform('');
if (refresh) {
container.addClass('refreshing');
container.trigger('refresh', {
done: function () {
app.pullToRefreshDone(container);
}
});
}
else {
container.removeClass('pull-down');
}
isTouched = false;
isMoved = false;
if (pullStarted) container.trigger('pullend');
}
// Attach Events
var passiveListener = app.touchEvents.start === 'touchstart' && app.support.passiveListener ? {passive: true, capture: false} : false;
eventsTarget.on(app.touchEvents.start, handleTouchStart, passiveListener);
eventsTarget.on(app.touchEvents.move, handleTouchMove);
eventsTarget.on(app.touchEvents.end, handleTouchEnd, passiveListener);
// Detach Events on page remove
if (page.length === 0) return;
function destroyPullToRefresh() {
eventsTarget.off(app.touchEvents.start, handleTouchStart);
eventsTarget.off(app.touchEvents.move, handleTouchMove);
eventsTarget.off(app.touchEvents.end, handleTouchEnd);
}
eventsTarget[0].f7DestroyPullToRefresh = destroyPullToRefresh;
function detachEvents() {
destroyPullToRefresh();
page.off('pageBeforeRemove', detachEvents);
}
page.on('pageBeforeRemove', detachEvents);
};
app.pullToRefreshDone = function (container) {
container = $(container);
if (container.length === 0) container = $('.pull-to-refresh-content.refreshing');
container.removeClass('refreshing').addClass('transitioning');
container.transitionEnd(function () {
container.removeClass('transitioning pull-up pull-down');
container.trigger('refreshdone');
});
};
app.pullToRefreshTrigger = function (container) {
container = $(container);
if (container.length === 0) container = $('.pull-to-refresh-content');
if (container.hasClass('refreshing')) return;
container.addClass('transitioning refreshing');
container.trigger('refresh', {
done: function () {
app.pullToRefreshDone(container);
}
});
};
app.destroyPullToRefresh = function (pageContainer) {
pageContainer = $(pageContainer);
var pullToRefreshContent = pageContainer.hasClass('pull-to-refresh-content') ? pageContainer : pageContainer.find('.pull-to-refresh-content');
if (pullToRefreshContent.length === 0) return;
if (pullToRefreshContent[0].f7DestroyPullToRefresh) pullToRefreshContent[0].f7DestroyPullToRefresh();
};
| ayuzhin/web-apps | vendor/framework7/src/js/pull-to-refresh.js | JavaScript | agpl-3.0 | 8,596 |
/**
* Copyright © MyCollab
*
* 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 com.mycollab.vaadin.web.ui;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.themes.ValoTheme;
/**
* @author MyCollab Ltd.
* @since 3.0
*/
public class CheckBoxDecor extends CheckBox {
private static final long serialVersionUID = 1L;
public CheckBoxDecor(String title, boolean value) {
super(title, value);
this.addStyleName(ValoTheme.CHECKBOX_SMALL);
}
}
| aglne/mycollab | mycollab-web/src/main/java/com/mycollab/vaadin/web/ui/CheckBoxDecor.java | Java | agpl-3.0 | 1,104 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2016-2016 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.poller.remote.metadata;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.opennms.netmgt.poller.remote.metadata.MetadataField.Validator;
public class EmailValidatorTest {
private Validator m_validator;
@Before
public void setUp() {
m_validator = new EmailValidator();
}
@Test
public void testValid() {
assertTrue(m_validator.isValid("ranger@opennms.org"));
assertTrue(m_validator.isValid("ranger@monkey.esophagus"));
assertTrue(m_validator.isValid("ranger@giant.list.of.sub.domains.com"));
}
@Test
public void testInvalid() {
assertFalse(m_validator.isValid("ranger@opennms"));
assertFalse(m_validator.isValid("ranger.monkey.esophagus"));
assertFalse(m_validator.isValid("ranger@"));
assertFalse(m_validator.isValid("@foo.com"));
assertFalse(m_validator.isValid("@foo.com."));
assertFalse(m_validator.isValid("@foo.com"));
assertFalse(m_validator.isValid(".@foo.com"));
assertFalse(m_validator.isValid(".e@foo.com"));
}
}
| aihua/opennms | features/poller/remote/src/test/java/org/opennms/netmgt/poller/remote/metadata/EmailValidatorTest.java | Java | agpl-3.0 | 2,394 |
/*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library 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: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.objectweb.proactive.core.jmx.mbean;
import java.io.Serializable;
/**
* This interface is used to add a class loader to the MBean Server repository.
* See JMX Specification, version 1.4 ; Chap 8.4.1 : 'A class loader is added to the repository if it is registered as an MBean'.
* @author The ProActive Team
*/
public interface JMXClassLoaderMBean extends Serializable {
}
| paraita/programming | programming-core/src/main/java/org/objectweb/proactive/core/jmx/mbean/JMXClassLoaderMBean.java | Java | agpl-3.0 | 1,413 |
<?php
/**
* Copyright (C) 2020 Xibo Signage Ltd
*
* Xibo - Digital Signage - http://www.xibo.org.uk
*
* 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/>.
*/
namespace Xibo\Widget;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
/**
* Class TwitterBase
* @package Xibo\Widget
*/
abstract class TwitterBase extends ModuleWidget
{
/**
* Get a auth token
* @return bool|mixed
*/
protected function getToken()
{
// Prepare the URL
$url = 'https://api.twitter.com/oauth2/token';
// Prepare the consumer key and secret
$key = base64_encode(urlencode($this->getSetting('apiKey')) . ':' . urlencode($this->getSetting('apiSecret')));
// Check to see if we have the bearer token already cached
$cache = $this->getPool()->getItem($this->makeCacheKey('bearer_' . $key));
$token = $cache->get();
if ($cache->isHit()) {
$this->getLog()->debug('Bearer Token served from cache');
return $token;
}
// We can take up to 30 seconds to request a new token
$cache->lock(30);
$this->getLog()->debug('Bearer Token served from API');
$client = new Client($this->getConfig()->getGuzzleProxy());
try {
$response = $client->request('POST', $url, [
'form_params' => [
'grant_type' => 'client_credentials'
],
'headers' => [
'Authorization' => 'Basic ' . $key
]
]);
$result = json_decode($response->getBody()->getContents());
if ($result->token_type !== 'bearer') {
$this->getLog()->error('Twitter API returned OK, but without a bearer token. ' . var_export($result, true));
return false;
}
// It is, so lets cache it
// long times...
$cache->set($result->access_token);
$cache->expiresAfter(100000);
$this->getPool()->saveDeferred($cache);
return $result->access_token;
} catch (RequestException $requestException) {
$this->getLog()->error('Twitter API returned ' . $requestException->getMessage() . ' status. Unable to proceed.');
return false;
}
}
/**
* Search the twitter API
* @param $token
* @param $term
* @param $language
* @param string $resultType
* @param string $geoCode
* @param int $count
* @return bool|mixed
* @throws \GuzzleHttp\Exception\GuzzleException
*/
protected function searchApi($token, $term, $language = '', $resultType = 'mixed', $geoCode = '', $count = 15)
{
$client = new Client($this->getConfig()->getGuzzleProxy());
$query = [
'q' => trim($term),
'result_type' => $resultType,
'count' => $count,
'include_entities' => true,
'tweet_mode' => 'extended'
];
if ($geoCode != '')
$query['geocode'] = $geoCode;
if ($language != '')
$query['lang'] = $language;
$this->getLog()->debug('Query is: ' . json_encode($query));
try {
$request = $client->request('GET', 'https://api.twitter.com/1.1/search/tweets.json', [
'headers' => [
'Authorization' => 'Bearer ' . $token
],
'query' => $query
]);
return json_decode($request->getBody()->getContents());
} catch (RequestException $requestException) {
$this->getLog()->error('Unable to reach twitter api. ' . $requestException->getMessage());
return false;
}
}
} | xibosignage/xibo-cms | lib/Widget/TwitterBase.php | PHP | agpl-3.0 | 4,380 |
/*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2016 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.coeus.propdev.impl.action;
import org.apache.commons.lang3.StringUtils;
import org.kuali.coeus.sys.framework.rule.KcTransactionalDocumentRuleBase;
import org.kuali.rice.core.api.util.RiceKeyConstants;
public class ProposalDevelopmentRejectionRule extends KcTransactionalDocumentRuleBase {
private static final String ACTION_REASON = "proposalDevelopmentRejectionBean.actionReason";
public boolean proccessProposalDevelopmentRejection(ProposalDevelopmentActionBean bean) {
boolean valid = true;
if (StringUtils.isEmpty(bean.getActionReason())) {
valid = false;
String errorParams = "";
reportError(ACTION_REASON, RiceKeyConstants.ERROR_REQUIRED, errorParams);
}
return valid;
}
}
| kuali/kc | coeus-impl/src/main/java/org/kuali/coeus/propdev/impl/action/ProposalDevelopmentRejectionRule.java | Java | agpl-3.0 | 1,586 |
# lint-amnesty, pylint: disable=missing-module-docstring
from unittest.mock import patch
from django.test import TestCase
from common.djangoapps.track.backends.mongodb import MongoBackend
class TestMongoBackend(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def setUp(self):
super().setUp()
self.mongo_patcher = patch('common.djangoapps.track.backends.mongodb.MongoClient')
self.mongo_patcher.start()
self.addCleanup(self.mongo_patcher.stop)
self.backend = MongoBackend()
def test_mongo_backend(self):
events = [{'test': 1}, {'test': 2}]
self.backend.send(events[0])
self.backend.send(events[1])
# Check if we inserted events into the database
calls = self.backend.collection.insert.mock_calls
assert len(calls) == 2
# Unpack the arguments and check if the events were used
# as the first argument to collection.insert
def first_argument(call):
_, args, _ = call
return args[0]
assert events[0] == first_argument(calls[0])
assert events[1] == first_argument(calls[1])
| eduNEXT/edx-platform | common/djangoapps/track/backends/tests/test_mongodb.py | Python | agpl-3.0 | 1,162 |
## Institutional Proposal Persons [/instprop/api/v1/institutional-proposal-persons/]
### Get Institutional Proposal Persons by Key [GET /instprop/api/v1/institutional-proposal-persons/(key)]
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 200
+ Headers
Content-Type: application/json;charset=UTF-8
+ Body
{"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"}
### Get All Institutional Proposal Persons [GET /instprop/api/v1/institutional-proposal-persons/]
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 200
+ Headers
Content-Type: application/json;charset=UTF-8
+ Body
[
{"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"},
{"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"}
]
### Get All Institutional Proposal Persons with Filtering [GET /instprop/api/v1/institutional-proposal-persons/]
+ Parameters
+ institutionalProposalContactId (optional) - InstitutionalProposal Contact ID. Maximum length is 8.
+ personId (optional) -
+ rolodexId (optional) -
+ fullName (optional) - Full Name. Maximum length is 90.
+ academicYearEffort (optional) - Academic Year Effort. Maximum length is 7.
+ calendarYearEffort (optional) - Calendar Year Effort. Maximum length is 7.
+ summerEffort (optional) - Summer Effort. Maximum length is 7.
+ totalEffort (optional) - Total Effort. Maximum length is 7.
+ faculty (optional) - Faculty flag. Maximum length is 1.
+ roleCode (optional) -
+ keyPersonRole (optional) - Project Role. Maximum length is 60.
+ proposalNumber (optional) - Institutional Proposal Number. Maximum length is 8.
+ sequenceNumber (optional) - Sequence Number. Maximum length is 4.
+ institutionalProposal.proposalId (optional) -
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 200
+ Headers
Content-Type: application/json;charset=UTF-8
+ Body
[
{"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"},
{"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"}
]
### Get Schema for Institutional Proposal Persons [GET /instprop/api/v1/institutional-proposal-persons/]
+ Parameters
+ _schema (required) - will instruct the endpoint to return a schema data structure for the resource
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 200
+ Headers
Content-Type: application/json;charset=UTF-8
+ Body
{"columns":["institutionalProposalContactId","personId","rolodexId","fullName","academicYearEffort","calendarYearEffort","summerEffort","totalEffort","faculty","roleCode","keyPersonRole","proposalNumber","sequenceNumber","institutionalProposal.proposalId"],"primaryKey":"institutionalProposalContactId"}
### Get Blueprint API specification for Institutional Proposal Persons [GET /instprop/api/v1/institutional-proposal-persons/]
+ Parameters
+ _blueprint (required) - will instruct the endpoint to return an api blueprint markdown file for the resource
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: text/markdown
+ Response 200
+ Headers
Content-Type: text/markdown;charset=UTF-8
Content-Disposition:attachment; filename="Institutional Proposal Persons.md"
transfer-encoding:chunked
| UniversityOfHawaiiORS/kc | coeus-webapp/src/main/jsfrontend/apidocs/instprop/institutional-proposal-persons.md | Markdown | agpl-3.0 | 5,509 |
"""Capa's specialized use of codejail.safe_exec."""
import hashlib
from codejail.safe_exec import SafeExecException, json_safe
from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec
from codejail.safe_exec import safe_exec as codejail_safe_exec
from edx_django_utils.monitoring import function_trace
import six
from six import text_type
from . import lazymod
from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec
# Establish the Python environment for Capa.
# Capa assumes float-friendly division always.
# The name "random" is a properly-seeded stand-in for the random module.
CODE_PROLOG = """\
from __future__ import absolute_import, division
import os
os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456
import random2 as random_module
import sys
from six.moves import xrange
random = random_module.Random(%r)
random.Random = random_module.Random
sys.modules['random'] = random
"""
ASSUMED_IMPORTS = [
("numpy", "numpy"),
("math", "math"),
("scipy", "scipy"),
("calc", "calc"),
("eia", "eia"),
("chemcalc", "chem.chemcalc"),
("chemtools", "chem.chemtools"),
("miller", "chem.miller"),
("draganddrop", "verifiers.draganddrop"),
]
# We'll need the code from lazymod.py for use in safe_exec, so read it now.
lazymod_py_file = lazymod.__file__
if lazymod_py_file.endswith("c"):
lazymod_py_file = lazymod_py_file[:-1]
with open(lazymod_py_file) as f:
lazymod_py = f.read()
LAZY_IMPORTS = [lazymod_py]
for name, modname in ASSUMED_IMPORTS:
LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname))
LAZY_IMPORTS = "".join(LAZY_IMPORTS)
def update_hash(hasher, obj):
"""
Update a `hashlib` hasher with a nested object.
To properly cache nested structures, we need to compute a hash from the
entire structure, canonicalizing at every level.
`hasher`'s `.update()` method is called a number of times, touching all of
`obj` in the process. Only primitive JSON-safe types are supported.
"""
hasher.update(six.b(str(type(obj))))
if isinstance(obj, (tuple, list)):
for e in obj:
update_hash(hasher, e)
elif isinstance(obj, dict):
for k in sorted(obj):
update_hash(hasher, k)
update_hash(hasher, obj[k])
else:
hasher.update(six.b(repr(obj)))
@function_trace('safe_exec')
def safe_exec(
code,
globals_dict,
random_seed=None,
python_path=None,
extra_files=None,
cache=None,
limit_overrides_context=None,
slug=None,
unsafely=False,
):
"""
Execute python code safely.
`code` is the Python code to execute. It has access to the globals in `globals_dict`,
and any changes it makes to those globals are visible in `globals_dict` when this
function returns.
`random_seed` will be used to see the `random` module available to the code.
`python_path` is a list of filenames or directories to add to the Python
path before execution. If the name is not in `extra_files`, then it will
also be copied into the sandbox.
`extra_files` is a list of (filename, contents) pairs. These files are
created in the sandbox.
`cache` is an object with .get(key) and .set(key, value) methods. It will be used
to cache the execution, taking into account the code, the values of the globals,
and the random seed.
`limit_overrides_context` is an optional string to be used as a key on
the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply
context-specific overrides to the codejail execution limits.
If `limit_overrides_context` is omitted or not present in limit_overrides,
then use the default limits specified insettings.CODE_JAIL['limits'].
`slug` is an arbitrary string, a description that's meaningful to the
caller, that will be used in log messages.
If `unsafely` is true, then the code will actually be executed without sandboxing.
"""
# Check the cache for a previous result.
if cache:
safe_globals = json_safe(globals_dict)
md5er = hashlib.md5()
md5er.update(repr(code).encode('utf-8'))
update_hash(md5er, safe_globals)
key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest())
cached = cache.get(key)
if cached is not None:
# We have a cached result. The result is a pair: the exception
# message, if any, else None; and the resulting globals dictionary.
emsg, cleaned_results = cached
globals_dict.update(cleaned_results)
if emsg:
raise SafeExecException(emsg)
return
# Create the complete code we'll run.
code_prolog = CODE_PROLOG % random_seed
if is_codejail_rest_service_enabled():
data = {
"code": code_prolog + LAZY_IMPORTS + code,
"globals_dict": globals_dict,
"python_path": python_path,
"limit_overrides_context": limit_overrides_context,
"slug": slug,
"unsafely": unsafely,
"extra_files": extra_files,
}
emsg, exception = get_remote_exec(data)
else:
# Decide which code executor to use.
if unsafely:
exec_fn = codejail_not_safe_exec
else:
exec_fn = codejail_safe_exec
# Run the code! Results are side effects in globals_dict.
try:
exec_fn(
code_prolog + LAZY_IMPORTS + code,
globals_dict,
python_path=python_path,
extra_files=extra_files,
limit_overrides_context=limit_overrides_context,
slug=slug,
)
except SafeExecException as e:
# Saving SafeExecException e in exception to be used later.
exception = e
emsg = text_type(e)
else:
emsg = None
# Put the result back in the cache. This is complicated by the fact that
# the globals dict might not be entirely serializable.
if cache:
cleaned_results = json_safe(globals_dict)
cache.set(key, (emsg, cleaned_results))
# If an exception happened, raise it now.
if emsg:
raise exception
| eduNEXT/edx-platform | common/lib/capa/capa/safe_exec/safe_exec.py | Python | agpl-3.0 | 6,279 |
<?php
require_once __DIR__.'/Base.php';
use Subscriber\ProjectModificationDateSubscriber;
use Model\Project;
use Model\ProjectPermission;
use Model\User;
use Model\Task;
use Model\TaskCreation;
use Model\Acl;
use Model\Board;
use Model\Config;
use Model\Category;
class ProjectTest extends Base
{
public function testCreation()
{
$p = new Project($this->container);
$this->assertEquals(1, $p->create(array('name' => 'UnitTest')));
$project = $p->getById(1);
$this->assertNotEmpty($project);
$this->assertEquals(1, $project['is_active']);
$this->assertEquals(0, $project['is_public']);
$this->assertEquals(0, $project['is_private']);
$this->assertEquals(time(), $project['last_modified']);
$this->assertEmpty($project['token']);
}
public function testCreationWithDefaultCategories()
{
$p = new Project($this->container);
$c = new Config($this->container);
$cat = new Category($this->container);
// Multiple categories correctly formatted
$this->assertTrue($c->save(array('project_categories' => 'Test1, Test2')));
$this->assertEquals(1, $p->create(array('name' => 'UnitTest1')));
$project = $p->getById(1);
$this->assertNotEmpty($project);
$categories = $cat->getAll(1);
$this->assertNotEmpty($categories);
$this->assertEquals(2, count($categories));
$this->assertEquals('Test1', $categories[0]['name']);
$this->assertEquals('Test2', $categories[1]['name']);
// Single category
$this->assertTrue($c->save(array('project_categories' => 'Test1')));
$this->assertEquals(2, $p->create(array('name' => 'UnitTest2')));
$project = $p->getById(2);
$this->assertNotEmpty($project);
$categories = $cat->getAll(2);
$this->assertNotEmpty($categories);
$this->assertEquals(1, count($categories));
$this->assertEquals('Test1', $categories[0]['name']);
// Multiple categories badly formatted
$this->assertTrue($c->save(array('project_categories' => 'ABC, , DEF 3, ')));
$this->assertEquals(3, $p->create(array('name' => 'UnitTest3')));
$project = $p->getById(3);
$this->assertNotEmpty($project);
$categories = $cat->getAll(3);
$this->assertNotEmpty($categories);
$this->assertEquals(2, count($categories));
$this->assertEquals('ABC', $categories[0]['name']);
$this->assertEquals('DEF 3', $categories[1]['name']);
// No default categories
$this->assertTrue($c->save(array('project_categories' => ' ')));
$this->assertEquals(4, $p->create(array('name' => 'UnitTest4')));
$project = $p->getById(4);
$this->assertNotEmpty($project);
$categories = $cat->getAll(4);
$this->assertEmpty($categories);
}
public function testUpdateLastModifiedDate()
{
$p = new Project($this->container);
$this->assertEquals(1, $p->create(array('name' => 'UnitTest')));
$now = time();
$project = $p->getById(1);
$this->assertNotEmpty($project);
$this->assertEquals($now, $project['last_modified'], 'Wrong Timestamp', 1);
sleep(1);
$this->assertTrue($p->updateModificationDate(1));
$project = $p->getById(1);
$this->assertNotEmpty($project);
$this->assertGreaterThan($now, $project['last_modified']);
}
public function testIsLastModified()
{
$p = new Project($this->container);
$tc = new TaskCreation($this->container);
$now = time();
$this->assertEquals(1, $p->create(array('name' => 'UnitTest')));
$project = $p->getById(1);
$this->assertNotEmpty($project);
$this->assertEquals($now, $project['last_modified']);
sleep(1);
$listener = new ProjectModificationDateSubscriber($this->container);
$this->container['dispatcher']->addListener(Task::EVENT_CREATE_UPDATE, array($listener, 'execute'));
$this->assertEquals(1, $tc->create(array('title' => 'Task #1', 'project_id' => 1)));
$called = $this->container['dispatcher']->getCalledListeners();
$this->assertArrayHasKey(Task::EVENT_CREATE_UPDATE.'.Subscriber\ProjectModificationDateSubscriber::execute', $called);
$project = $p->getById(1);
$this->assertNotEmpty($project);
$this->assertTrue($p->isModifiedSince(1, $now));
}
public function testRemove()
{
$p = new Project($this->container);
$this->assertEquals(1, $p->create(array('name' => 'UnitTest')));
$this->assertTrue($p->remove(1));
$this->assertFalse($p->remove(1234));
}
public function testEnable()
{
$p = new Project($this->container);
$this->assertEquals(1, $p->create(array('name' => 'UnitTest')));
$this->assertTrue($p->disable(1));
$project = $p->getById(1);
$this->assertNotEmpty($project);
$this->assertEquals(0, $project['is_active']);
$this->assertFalse($p->disable(1111));
}
public function testDisable()
{
$p = new Project($this->container);
$this->assertEquals(1, $p->create(array('name' => 'UnitTest')));
$this->assertTrue($p->disable(1));
$this->assertTrue($p->enable(1));
$project = $p->getById(1);
$this->assertNotEmpty($project);
$this->assertEquals(1, $project['is_active']);
$this->assertFalse($p->enable(1234567));
}
public function testEnablePublicAccess()
{
$p = new Project($this->container);
$this->assertEquals(1, $p->create(array('name' => 'UnitTest')));
$this->assertTrue($p->enablePublicAccess(1));
$project = $p->getById(1);
$this->assertNotEmpty($project);
$this->assertEquals(1, $project['is_public']);
$this->assertNotEmpty($project['token']);
$this->assertFalse($p->enablePublicAccess(123));
}
public function testDisablePublicAccess()
{
$p = new Project($this->container);
$this->assertEquals(1, $p->create(array('name' => 'UnitTest')));
$this->assertTrue($p->enablePublicAccess(1));
$this->assertTrue($p->disablePublicAccess(1));
$project = $p->getById(1);
$this->assertNotEmpty($project);
$this->assertEquals(0, $project['is_public']);
$this->assertEmpty($project['token']);
$this->assertFalse($p->disablePublicAccess(123));
}
}
| 666/kanboard-redesign | tests/units/ProjectTest.php | PHP | agpl-3.0 | 6,581 |
from ddt import ddt, data
from django.core.urlresolvers import reverse
from django.test import TestCase
import mock
from analyticsclient.exceptions import NotFoundError
from courses.tests import SwitchMixin
from courses.tests.test_views import ViewTestMixin, DEMO_COURSE_ID, DEPRECATED_DEMO_COURSE_ID
from courses.tests.utils import convert_list_of_dicts_to_csv, get_mock_api_enrollment_geography_data, \
get_mock_api_enrollment_data, get_mock_api_course_activity, get_mock_api_enrollment_age_data, \
get_mock_api_enrollment_education_data, get_mock_api_enrollment_gender_data
@ddt
# pylint: disable=abstract-method
class CourseCSVTestMixin(ViewTestMixin):
client = None
column_headings = None
base_file_name = None
def assertIsValidCSV(self, course_id, csv_data):
response = self.client.get(self.path(course_id=course_id))
# Check content type
self.assertResponseContentType(response, 'text/csv')
# Check filename
csv_prefix = u'edX-DemoX-Demo_2014' if course_id == DEMO_COURSE_ID else u'edX-DemoX-Demo_Course'
filename = '{0}--{1}.csv'.format(csv_prefix, self.base_file_name)
self.assertResponseFilename(response, filename)
# Check data
self.assertEqual(response.content, csv_data)
def assertResponseContentType(self, response, content_type):
self.assertEqual(response['Content-Type'], content_type)
def assertResponseFilename(self, response, filename):
self.assertEqual(response['Content-Disposition'], 'attachment; filename="{0}"'.format(filename))
def _test_csv(self, course_id, csv_data):
with mock.patch(self.api_method, return_value=csv_data):
self.assertIsValidCSV(course_id, csv_data)
@data(DEMO_COURSE_ID, DEPRECATED_DEMO_COURSE_ID)
def test_response_no_data(self, course_id):
# Create an "empty" CSV that only has headers
csv_data = convert_list_of_dicts_to_csv([], self.column_headings)
self._test_csv(course_id, csv_data)
@data(DEMO_COURSE_ID, DEPRECATED_DEMO_COURSE_ID)
def test_response(self, course_id):
csv_data = self.get_mock_data(course_id)
csv_data = convert_list_of_dicts_to_csv(csv_data)
self._test_csv(course_id, csv_data)
def test_404(self):
course_id = 'fakeOrg/soFake/Fake_Course'
self.grant_permission(self.user, course_id)
path = reverse(self.viewname, kwargs={'course_id': course_id})
with mock.patch(self.api_method, side_effect=NotFoundError):
response = self.client.get(path, follow=True)
self.assertEqual(response.status_code, 404)
class CourseEnrollmentByCountryCSVViewTests(CourseCSVTestMixin, TestCase):
viewname = 'courses:csv:enrollment_geography'
column_headings = ['count', 'country', 'course_id', 'date']
base_file_name = 'enrollment-location'
api_method = 'analyticsclient.course.Course.enrollment'
def get_mock_data(self, course_id):
return get_mock_api_enrollment_geography_data(course_id)
class CourseEnrollmentCSVViewTests(CourseCSVTestMixin, TestCase):
viewname = 'courses:csv:enrollment'
column_headings = ['count', 'course_id', 'date']
base_file_name = 'enrollment'
api_method = 'analyticsclient.course.Course.enrollment'
def get_mock_data(self, course_id):
return get_mock_api_enrollment_data(course_id)
class CourseEnrollmentModeCSVViewTests(SwitchMixin, CourseCSVTestMixin, TestCase):
viewname = 'courses:csv:enrollment'
column_headings = ['count', 'course_id', 'date', 'audit', 'honor', 'professional', 'verified']
base_file_name = 'enrollment'
api_method = 'analyticsclient.course.Course.enrollment'
@classmethod
def setUpClass(cls):
cls.toggle_switch('display_verified_enrollment', True)
def get_mock_data(self, course_id):
return get_mock_api_enrollment_data(course_id)
class CourseEnrollmentDemographicsByAgeCSVViewTests(CourseCSVTestMixin, TestCase):
viewname = 'courses:csv:enrollment_demographics_age'
column_headings = ['birth_year', 'count', 'course_id', 'created', 'date']
base_file_name = 'enrollment-by-birth-year'
api_method = 'analyticsclient.course.Course.enrollment'
def get_mock_data(self, course_id):
return get_mock_api_enrollment_age_data(course_id)
class CourseEnrollmentDemographicsByEducationCSVViewTests(CourseCSVTestMixin, TestCase):
viewname = 'courses:csv:enrollment_demographics_education'
column_headings = ['count', 'course_id', 'created', 'date', 'education_level.name', 'education_level.short_name']
base_file_name = 'enrollment-by-education'
api_method = 'analyticsclient.course.Course.enrollment'
def get_mock_data(self, course_id):
return get_mock_api_enrollment_education_data(course_id)
class CourseEnrollmentByDemographicsGenderCSVViewTests(CourseCSVTestMixin, TestCase):
viewname = 'courses:csv:enrollment_demographics_gender'
column_headings = ['count', 'course_id', 'created', 'date', 'gender']
base_file_name = 'enrollment-by-gender'
api_method = 'analyticsclient.course.Course.enrollment'
def get_mock_data(self, course_id):
return get_mock_api_enrollment_gender_data(course_id)
class CourseEngagementActivityTrendCSVViewTests(CourseCSVTestMixin, TestCase):
viewname = 'courses:csv:engagement_activity_trend'
column_headings = ['any', 'attempted_problem', 'course_id', 'interval_end', 'interval_start',
'played_video', 'posted_forum']
base_file_name = 'engagement-activity'
api_method = 'analyticsclient.course.Course.activity'
def get_mock_data(self, course_id):
return get_mock_api_course_activity(course_id)
| open-craft/edx-analytics-dashboard | analytics_dashboard/courses/tests/test_views/test_csv.py | Python | agpl-3.0 | 5,748 |
<?php
$module_name='Cosib_postsale';
$subpanel_layout = array (
'top_buttons' =>
array (
0 =>
array (
'widget_class' => 'SubPanelTopCreateButton',
),
1 =>
array (
'widget_class' => 'SubPanelTopSelectButton',
'popup_module' => 'Cosib_postsale',
),
),
'where' => '',
'list_fields' =>
array (
'date_modified' =>
array (
'vname' => 'LBL_DATE_MODIFIED',
'width' => '45%',
),
'edit_button' =>
array (
'widget_class' => 'SubPanelEditButton',
'module' => 'Cosib_postsale',
'width' => '4%',
),
'remove_button' =>
array (
'widget_class' => 'SubPanelRemoveButton',
'module' => 'Cosib_postsale',
'width' => '5%',
),
),
); | yonkon/nedvig | modules/Cosib_postsale/metadata/subpanels/default.php | PHP | agpl-3.0 | 756 |
<h1>Welcome to FixMyStreet</h1>
<p>
Using this app you can report common street problems, like potholes or broken street lights, to councils throughout the UK.
</p>
<p>
It works online and offline, because we know that there isn't always a signal when you need one.
</p>
| Kagee/fixmystreet-mobile | src/templates/en/initial_help.html | HTML | agpl-3.0 | 272 |
class CreateIdentities < ActiveRecord::Migration
def change
create_table :identities do |t|
t.references :user, index: true
t.string :provider
t.string :uid
t.timestamps null: false
end
end
end
| asm-products/pay-it-forward | db/migrate/20141010013730_create_identities.rb | Ruby | agpl-3.0 | 231 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import time
from odoo import api, fields, models
class ProductProduct(models.Model):
_inherit = "product.product"
date_from = fields.Date(compute='_compute_product_margin_fields_values', string='Margin Date From')
date_to = fields.Date(compute='_compute_product_margin_fields_values', string='Margin Date To')
invoice_state = fields.Selection(compute='_compute_product_margin_fields_values',
selection=[
('paid', 'Paid'),
('open_paid', 'Open and Paid'),
('draft_open_paid', 'Draft, Open and Paid')
], string='Invoice State', readonly=True)
sale_avg_price = fields.Float(compute='_compute_product_margin_fields_values', string='Avg. Sale Unit Price',
help="Avg. Price in Customer Invoices.")
purchase_avg_price = fields.Float(compute='_compute_product_margin_fields_values', string='Avg. Purchase Unit Price',
help="Avg. Price in Vendor Bills ")
sale_num_invoiced = fields.Float(compute='_compute_product_margin_fields_values', string='# Invoiced in Sale',
help="Sum of Quantity in Customer Invoices")
purchase_num_invoiced = fields.Float(compute='_compute_product_margin_fields_values', string='# Invoiced in Purchase',
help="Sum of Quantity in Vendor Bills")
sales_gap = fields.Float(compute='_compute_product_margin_fields_values', string='Sales Gap',
help="Expected Sale - Turn Over")
purchase_gap = fields.Float(compute='_compute_product_margin_fields_values', string='Purchase Gap',
help="Normal Cost - Total Cost")
turnover = fields.Float(compute='_compute_product_margin_fields_values', string='Turnover',
help="Sum of Multiplication of Invoice price and quantity of Customer Invoices")
total_cost = fields.Float(compute='_compute_product_margin_fields_values', string='Total Cost',
help="Sum of Multiplication of Invoice price and quantity of Vendor Bills ")
sale_expected = fields.Float(compute='_compute_product_margin_fields_values', string='Expected Sale',
help="Sum of Multiplication of Sale Catalog price and quantity of Customer Invoices")
normal_cost = fields.Float(compute='_compute_product_margin_fields_values', string='Normal Cost',
help="Sum of Multiplication of Cost price and quantity of Vendor Bills")
total_margin = fields.Float(compute='_compute_product_margin_fields_values', string='Total Margin',
help="Turnover - Standard price")
expected_margin = fields.Float(compute='_compute_product_margin_fields_values', string='Expected Margin',
help="Expected Sale - Normal Cost")
total_margin_rate = fields.Float(compute='_compute_product_margin_fields_values', string='Total Margin Rate(%)',
help="Total margin * 100 / Turnover")
expected_margin_rate = fields.Float(compute='_compute_product_margin_fields_values', string='Expected Margin (%)',
help="Expected margin * 100 / Expected Sale")
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
"""
Inherit read_group to calculate the sum of the non-stored fields, as it is not automatically done anymore through the XML.
"""
res = super(ProductProduct, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
fields_list = ['turnover', 'sale_avg_price', 'sale_purchase_price', 'sale_num_invoiced', 'purchase_num_invoiced',
'sales_gap', 'purchase_gap', 'total_cost', 'sale_expected', 'normal_cost', 'total_margin',
'expected_margin', 'total_margin_rate', 'expected_margin_rate']
if any(x in fields for x in fields_list):
# Calculate first for every product in which line it needs to be applied
re_ind = 0
prod_re = {}
tot_products = self.browse([])
for re in res:
if re.get('__domain'):
products = self.search(re['__domain'])
tot_products |= products
for prod in products:
prod_re[prod.id] = re_ind
re_ind += 1
res_val = tot_products._compute_product_margin_fields_values(field_names=[x for x in fields if fields in fields_list])
for key in res_val:
for l in res_val[key]:
re = res[prod_re[key]]
if re.get(l):
re[l] += res_val[key][l]
else:
re[l] = res_val[key][l]
return res
def _compute_product_margin_fields_values(self, field_names=None):
res = {}
if field_names is None:
field_names = []
for val in self:
res[val.id] = {}
date_from = self.env.context.get('date_from', time.strftime('%Y-01-01'))
date_to = self.env.context.get('date_to', time.strftime('%Y-12-31'))
invoice_state = self.env.context.get('invoice_state', 'open_paid')
res[val.id]['date_from'] = date_from
res[val.id]['date_to'] = date_to
res[val.id]['invoice_state'] = invoice_state
states = ()
payment_states = ()
if invoice_state == 'paid':
states = ('posted',)
payment_states = ('paid',)
elif invoice_state == 'open_paid':
states = ('posted',)
payment_states = ('not_paid', 'paid')
elif invoice_state == 'draft_open_paid':
states = ('posted', 'draft')
payment_states = ('not_paid', 'paid')
company_id = self.env.company.id
#Cost price is calculated afterwards as it is a property
self.env['account.move.line'].flush(['price_unit', 'quantity', 'balance', 'product_id', 'display_type'])
self.env['account.move'].flush(['state', 'payment_state', 'move_type', 'invoice_date', 'company_id'])
self.env['product.template'].flush(['list_price'])
sqlstr = """
WITH currency_rate AS ({})
SELECT
SUM(l.price_unit / (CASE COALESCE(cr.rate, 0) WHEN 0 THEN 1.0 ELSE cr.rate END) * l.quantity) / NULLIF(SUM(l.quantity),0) AS avg_unit_price,
SUM(l.quantity * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)) AS num_qty,
SUM(ABS(l.balance) * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)) AS total,
SUM(l.quantity * pt.list_price * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)) AS sale_expected
FROM account_move_line l
LEFT JOIN account_move i ON (l.move_id = i.id)
LEFT JOIN product_product product ON (product.id=l.product_id)
LEFT JOIN product_template pt ON (pt.id = product.product_tmpl_id)
left join currency_rate cr on
(cr.currency_id = i.currency_id and
cr.company_id = i.company_id and
cr.date_start <= COALESCE(i.invoice_date, NOW()) and
(cr.date_end IS NULL OR cr.date_end > COALESCE(i.invoice_date, NOW())))
WHERE l.product_id = %s
AND i.state IN %s
AND i.payment_state IN %s
AND i.move_type IN %s
AND i.invoice_date BETWEEN %s AND %s
AND i.company_id = %s
AND l.display_type IS NULL
AND l.exclude_from_invoice_tab = false
""".format(self.env['res.currency']._select_companies_rates())
invoice_types = ('out_invoice', 'out_refund')
self.env.cr.execute(sqlstr, (val.id, states, payment_states, invoice_types, date_from, date_to, company_id))
result = self.env.cr.fetchall()[0]
res[val.id]['sale_avg_price'] = result[0] and result[0] or 0.0
res[val.id]['sale_num_invoiced'] = result[1] and result[1] or 0.0
res[val.id]['turnover'] = result[2] and result[2] or 0.0
res[val.id]['sale_expected'] = result[3] and result[3] or 0.0
res[val.id]['sales_gap'] = res[val.id]['sale_expected'] - res[val.id]['turnover']
invoice_types = ('in_invoice', 'in_refund')
self.env.cr.execute(sqlstr, (val.id, states, payment_states, invoice_types, date_from, date_to, company_id))
result = self.env.cr.fetchall()[0]
res[val.id]['purchase_avg_price'] = result[0] and result[0] or 0.0
res[val.id]['purchase_num_invoiced'] = result[1] and result[1] or 0.0
res[val.id]['total_cost'] = result[2] and result[2] or 0.0
res[val.id]['normal_cost'] = val.standard_price * res[val.id]['purchase_num_invoiced']
res[val.id]['purchase_gap'] = res[val.id]['normal_cost'] - res[val.id]['total_cost']
res[val.id]['total_margin'] = res[val.id]['turnover'] - res[val.id]['total_cost']
res[val.id]['expected_margin'] = res[val.id]['sale_expected'] - res[val.id]['normal_cost']
res[val.id]['total_margin_rate'] = res[val.id]['turnover'] and res[val.id]['total_margin'] * 100 / res[val.id]['turnover'] or 0.0
res[val.id]['expected_margin_rate'] = res[val.id]['sale_expected'] and res[val.id]['expected_margin'] * 100 / res[val.id]['sale_expected'] or 0.0
for k, v in res[val.id].items():
setattr(val, k, v)
return res
| ygol/odoo | addons/product_margin/models/product_product.py | Python | agpl-3.0 | 9,711 |
# clean sequences after alignment, criteria based on sequences
# make inline with canonical ordering (no extra gaps)
import os, datetime, time, re
from itertools import izip
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from scipy import stats
import numpy as np
class virus_clean(object):
"""docstring for virus_clean"""
def __init__(self,n_iqd = 5, **kwargs):
'''
parameters
n_std -- number of interquartile distances accepted in molecular clock filter
'''
self.n_iqd = n_iqd
def remove_insertions(self):
'''
remove all columns from the alignment in which the outgroup is gapped
'''
outgroup_ok = np.array(self.sequence_lookup[self.outgroup['strain']])!='-'
for seq in self.viruses:
seq.seq = Seq("".join(np.array(seq.seq)[outgroup_ok]).upper())
def clean_gaps(self):
'''
remove viruses with gaps -- not part of the standard pipeline
'''
self.viruses = filter(lambda x: '-' in x.seq, self.viruses)
def clean_ambiguous(self):
'''
substitute all ambiguous characters with '-',
ancestral inference will interpret this as missing data
'''
for v in self.viruses:
v.seq = Seq(re.sub(r'[BDEFHIJKLMNOPQRSUVWXYZ]', '-',str(v.seq)))
def unique_date(self):
'''
add a unique numerical date to each leaf. uniqueness is achieved adding a small number
'''
from date_util import numerical_date
og = self.sequence_lookup[self.outgroup['strain']]
if hasattr(og, 'date'):
try:
og.num_date = numerical_date(og.date)
except:
print "cannot parse date"
og.num_date="undefined";
for ii, v in enumerate(self.viruses):
if hasattr(v, 'date'):
try:
v.num_date = numerical_date(v.date, self.date_format['fields']) + 1e-7*(ii+1)
except:
print "cannot parse date"
v.num_date="undefined";
def times_from_outgroup(self):
outgroup_date = self.sequence_lookup[self.outgroup['strain']].num_date
return np.array([x.num_date-outgroup_date for x in self.viruses if x.strain])
def distance_from_outgroup(self):
from seq_util import hamming_distance
outgroup_seq = self.sequence_lookup[self.outgroup['strain']].seq
return np.array([hamming_distance(x.seq, outgroup_seq) for x in self.viruses if x.strain])
def clean_distances(self):
"""Remove viruses that don't follow a loose clock """
times = self.times_from_outgroup()
distances = self.distance_from_outgroup()
slope, intercept, r_value, p_value, std_err = stats.linregress(times, distances)
residuals = slope*times + intercept - distances
r_iqd = stats.scoreatpercentile(residuals,75) - stats.scoreatpercentile(residuals,25)
if self.verbose:
print "\tslope: " + str(slope)
print "\tr: " + str(r_value)
print "\tresiduals iqd: " + str(r_iqd)
new_viruses = []
for (v,r) in izip(self.viruses,residuals):
# filter viruses more than n_std standard devitations up or down
if np.abs(r)<self.n_iqd * r_iqd or v.id == self.outgroup["strain"]:
new_viruses.append(v)
else:
if self.verbose>1:
print "\t\tresidual:", r, "\nremoved ",v.strain
self.viruses = MultipleSeqAlignment(new_viruses)
def clean_generic(self):
print "Number of viruses before cleaning:",len(self.viruses)
self.unique_date()
self.remove_insertions()
self.clean_ambiguous()
self.clean_distances()
self.viruses.sort(key=lambda x:x.num_date)
print "Number of viruses after outlier filtering:",len(self.viruses)
| doerlbh/Indie-nextflu | augur/src/virus_clean.py | Python | agpl-3.0 | 3,403 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>libtcod documentation | Pseudorandom number generator</title>
<script type="text/javascript" src="../js/doctcod.js"></script>
<link href="../css/style.css" rel="stylesheet" type="text/css"></head>
<link type="text/css" rel="stylesheet" href="../css/shCore.css"></link>
<link type="text/css" rel="stylesheet" href="../css/shThemeDefault.css"></link>
<script language="javascript" src="../js/shCore.js"></script>
<script language="javascript" src="../js/shBrushBash.js"></script>
<body><div class="header">
<p><span class="title1">libtcod</span><span class="title2">documentation</span></p>
</div>
<div class="breadcrumb"><div class="breadcrumbtext"><p>
you are here: <a onclick="link('../index2.html')">Index</a> > <a onclick="link('random.html')">7. Pseudorandom number generator</a><br>
<a class="prev" onclick="link('list.html')">6. All purposes container</a> | <a class="next" onclick="link('mouse.html')">8. Mouse support</a>
</p></div></div>
<div class="filter"><input type="checkbox" id="chk_c" name="chk_c" onchange="enable('c',this.checked)" checked='checked' ><label for='chk_c'> C </label><input type="checkbox" id="chk_cpp" name="chk_cpp" onchange="enable('cpp',this.checked)" checked='checked' ><label for='chk_cpp'> C++ </label><input type="checkbox" id="chk_py" name="chk_py" onchange="enable('py',this.checked)" checked='checked' ><label for='chk_py'> Py </label><input type="checkbox" id="chk_lua" name="chk_lua" onchange="enable('lua',this.checked)" disabled='disabled'><label class='disabled' for='chk_lua'> Lua </label><input type="checkbox" id="chk_cs" name="chk_cs" onchange="enable('cs',this.checked)" disabled='disabled'><label class='disabled' for='chk_cs'> C# </label></div>
<div class="main"><div class="maintext">
<h1>7. Pseudorandom number generator</h1>
<div id="toc"><ul><li><a onclick="link('random_init.html')">7.1. Creating a generator</a></li>
<li><a onclick="link('random_distro.html')">7.2. Using a generator</a></li>
<li><a onclick="link('random_use.html')">7.3. Using a generator</a></li>
</ul></div>
<p>This toolkit is an implementation of two fast and high quality pseudorandom number generators:<br />* a Mersenne twister generator,<br />* a Complementary-Multiply-With-Carry generator.<br />CMWC is faster than MT (see table below) and has a much better period (1039460 vs. 106001). It is the default algo since libtcod 1.5.0.<br /><br />Relative performances in two independent tests (lower is better) :<br /><table class="param">
<tr>
<th>Algorithm</th>
<th>Numbers generated</th>
<th>Perf (1)</th>
<th>Perf (2)</th>
</tr>
<tr class="hilite">
<td>MT</td>
<td>integer</td>
<td>62</td>
<td>50</td>
</tr>
<tr>
<td>MT</td>
<td>float</td>
<td>54</td>
<td>45</td>
</tr>
<tr class="hilite">
<td>CMWC</td>
<td>integer</td>
<td>21</td>
<td>34</td>
</tr>
<tr>
<td>CMWC</td>
<td>float</td>
<td>32</td>
<td>27</td>
</tr>
</table><br /><br /><h6>For python users:</h6><br />Python already has great builtin random generators. But some parts of the Doryen library (noise, heightmap, ...) uses RNG as parameters. If you intend to use those functions, you must provide a RNG created with the library.<br /><br /><h6>For C# users:</h6><br />.NET already has great builtin random generators. But some parts of the Doryen library (noise, heightmap, ...) uses RNG as parameters. If you intend to use those functions, you must provide a RNG created with the library.<br /> </p>
</div></div>
<div class="footer"><div class="footertext">
<p>libtcod 1.5.2, © 2008, 2009, 2010, 2012 Jice & Mingos<br>
This file has been generated by doctcod.</p>
<p><table width='100%'><tr><td><a href="http://doryen.eptalys.net/libtcod">libtcod website</a></td>
<td><a href="http://doryen.eptalys.net/forum/index.php?board=12.0">libtcod on Roguecentral forums</a></td>
<td><a href="http://doryen.eptalys.net/libtcod/tutorial">libtcod tutorials</a></td>
</tr></table></p>
</div></div>
</body>
<script>
initFilter();
SyntaxHighlighter.all();
</script>
</html>
| svifylabs/Brogue | src/libtcod-1.5.2/doc/html2/random.html | HTML | agpl-3.0 | 4,335 |
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
return [
'availability' => [
'disabled' => 'Ez a beatmap jelenleg nem letölthető.',
'parts-removed' => 'Ez a beatmap eltávolításra került a készítő vagy egy jogbirtokos harmadik fél kérésére.',
'more-info' => 'Itt találsz több információt.',
'rule_violation' => 'Ennek a map-nek néhány elemét eltávolítottuk, mert nem találtuk őket megfelelőnek az osu!-ban történő használathoz.',
],
'download' => [
'limit_exceeded' => 'Lassíts le, játssz többet.',
],
'featured_artist_badge' => [
'label' => 'Kiemelt előadó',
],
'index' => [
'title' => 'Beatmap lista',
'guest_title' => 'Beatmap-ek',
],
'panel' => [
'empty' => 'nincs beatmap',
'download' => [
'all' => 'letöltés',
'video' => 'letöltés videóval',
'no_video' => 'letöltés videó nélkül',
'direct' => 'megnyitás osu!direct-ben',
],
],
'nominate' => [
'hybrid_requires_modes' => 'Egy hibrid beatmap szettet legalább egy játékmódra nominálni kell.',
'incorrect_mode' => 'Nincs jogosultságod :mode módban nominálni',
'full_bn_required' => 'Teljes jogú nominátornak kell lenned a kvalifikálásra nomináláshoz.',
'too_many' => 'A nominálási követelmények már teljesültek.',
'dialog' => [
'confirmation' => 'Biztosan nominálni szeretnéd ezt a Beatmap-et?',
'header' => 'Beatmap Nominálása',
'hybrid_warning' => 'megjegyzés: csak egyszer nominálhatsz, ezért kérlek győződj meg róla, hogy minden játékmódra nominálsz, amire szeretnél',
'which_modes' => 'Mely módokra nominálsz?',
],
],
'nsfw_badge' => [
'label' => 'Felnőtt',
],
'show' => [
'discussion' => 'Beszélgetés',
'details' => [
'by_artist' => ':artist által',
'favourite' => 'A beatmap kedvencek közé tétele',
'favourite_login' => 'Jelentkezz be, hogy kedvencnek jelölt ezt beatmap-et',
'logged-out' => 'Beatmapek letöltéshez be kell jelentkezned!',
'mapped_by' => 'mappolva :mapper által',
'unfavourite' => 'Beatmap eltávolitása a kedvencek közül',
'updated_timeago' => 'utóljára frissítve: :timeago',
'download' => [
'_' => 'Letöltés',
'direct' => '',
'no-video' => 'Videó nélkül',
'video' => 'Videóval',
],
'login_required' => [
'bottom' => 'további funkciók eléréséhez',
'top' => 'Bejelentkezés',
],
],
'details_date' => [
'approved' => 'jóváhagyva: :timeago',
'loved' => 'szerette: :timeago',
'qualified' => 'kvalifikálva: :timeago',
'ranked' => 'rangsorolva: :timeago',
'submitted' => 'beküldve: :timeago',
'updated' => 'utolsó frissítés: :timeago',
],
'favourites' => [
'limit_reached' => 'Túl sok beatmap van a kedvenceid között! Kérlek távolíts el néhányat az újrapróbálkozás előtt.',
],
'hype' => [
'action' => 'Hype-old a beatmapet ha élvezted rajta a játékot, hogy segíthesd a <strong>Rangsorolt</strong> állapot felé jutásban.',
'current' => [
'_' => 'Ez a map :status jelenleg.',
'status' => [
'pending' => 'függőben',
'qualified' => 'kvalifikált',
'wip' => 'munkálatok alatt',
],
],
'disqualify' => [
'_' => 'Ha találsz javaslatokat, problémákat a térképpel kapcsolatban, kérlek diszkvalifikáld ezen a linken keresztül: :link',
],
'report' => [
'_' => 'Ha találsz javaslatokat, problémákat a térképpel kapcsolatban, kérlek jelentsd az alábbi linken keresztül: :link',
'button' => 'Probléma jelentése',
'link' => 'itt',
],
],
'info' => [
'description' => 'Leírás',
'genre' => 'Műfaj',
'language' => 'Nyelv',
'no_scores' => 'Az adatok még számítás alatt...',
'nsfw' => 'Felnőtt tartalom',
'points-of-failure' => 'Kibukási Alkalmak',
'source' => 'Forrás',
'storyboard' => 'Ez a beatmap storyboard-ot tartalmaz',
'success-rate' => 'Teljesítési arány',
'tags' => 'Címkék',
'video' => 'Ez a beatmap videót tartalmaz',
],
'nsfw_warning' => [
'details' => 'Ez a beatmap szókimondó, sértő vagy felkavaró tartalmú. Továbbra is meg szeretnéd tekinteni?',
'title' => 'Felnőtt tartalom',
'buttons' => [
'disable' => 'Figyelmeztetés kikapcsolása',
'listing' => 'Beatmap lista',
'show' => 'Mutassa',
],
],
'scoreboard' => [
'achieved' => 'elérve: :when',
'country' => 'Országos Ranglista',
'error' => '',
'friend' => 'Baráti Ranglista',
'global' => 'Globális Ranglista',
'supporter-link' => 'Kattints <a href=":link">ide</a>,hogy megtekinthesd azt a sok jó funkciót amit kaphatsz!',
'supporter-only' => 'Támogató kell legyél, hogy elérd a baráti és az országos ranglistát!',
'title' => 'Eredménylista',
'headers' => [
'accuracy' => 'Pontosság',
'combo' => 'Legmagasabb kombó',
'miss' => 'Miss',
'mods' => 'Modok',
'pin' => '',
'player' => 'Játékos',
'pp' => '',
'rank' => 'Rang',
'score' => 'Pontszám',
'score_total' => 'Összpontszám',
'time' => 'Idő',
],
'no_scores' => [
'country' => 'Senki sem ért még el eredményt az országodból ezen a map-en!',
'friend' => 'Senki sem ért még el eredményt a barátaid közül ezen a map-en!',
'global' => 'Egyetlen eredmény sincs. Esetleg megpróbálhatnál szerezni párat?',
'loading' => 'Eredmények betöltése...',
'unranked' => 'Rangsorolatlan beatmap.',
],
'score' => [
'first' => 'Az élen',
'own' => 'A legjobbad',
],
'supporter_link' => [
'_' => '',
'here' => '',
],
],
'stats' => [
'cs' => 'Kör nagyság',
'cs-mania' => 'Billentyűk száma',
'drain' => 'HP Vesztés',
'accuracy' => 'Pontosság',
'ar' => 'Közelítési sebesség',
'stars' => 'Nehézség',
'total_length' => 'Hossz',
'bpm' => 'BPM',
'count_circles' => 'Körök Száma',
'count_sliders' => 'Sliderek Száma',
'user-rating' => 'Felhasználói Értékelés',
'rating-spread' => 'Értékelési Szórás',
'nominations' => 'Nominálások',
'playcount' => 'Játékszám',
],
'status' => [
'ranked' => 'Rangsorolt',
'approved' => 'Jóváhagyott',
'loved' => 'Szeretett',
'qualified' => 'Kvalifikálva',
'wip' => 'Készítés alatt',
'pending' => 'Függőben',
'graveyard' => 'Temető',
],
],
];
| ppy/osu-web | resources/lang/hu/beatmapsets.php | PHP | agpl-3.0 | 8,051 |
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('contentstore.rest_api.v1.serializers', 'cms.djangoapps.contentstore.rest_api.v1.serializers')
from cms.djangoapps.contentstore.rest_api.v1.serializers import *
| eduNEXT/edunext-platform | import_shims/studio/contentstore/rest_api/v1/serializers.py | Python | agpl-3.0 | 431 |
/** \file
* \author John Bridgman
* \brief
*/
#include <Variant/Blob.h>
#include <stdlib.h>
#include <new>
#include <string.h>
#include <algorithm>
namespace libvariant {
static void MallocFree(void *ptr, void *) {
free(ptr);
}
shared_ptr<Blob> Blob::Create(void *ptr, unsigned len, BlobFreeFunc ffunc, void *context)
{
struct iovec iov = { ptr, len };
return shared_ptr<Blob>(new Blob(&iov, 1, ffunc, context));
}
BlobPtr Blob::Create(struct iovec *iov, unsigned iov_len, BlobFreeFunc ffunc, void *context) {
return BlobPtr(new Blob(iov, iov_len, ffunc, context));
}
shared_ptr<Blob> Blob::CreateCopy(const void *ptr, unsigned len) {
struct iovec iov = { (void*)ptr, len };
return CreateCopy(&iov, 1);
}
BlobPtr Blob::CreateCopy(const struct iovec *iov, unsigned iov_len) {
unsigned len = 0;
for (unsigned i = 0; i < iov_len; ++i) { len += iov[i].iov_len; }
void *data = 0;
#ifdef __APPLE__
// TODO: Remove when apple fixes this error.
if (posix_memalign(&data, 64, std::max(len, 1u)) != 0) {
throw std::bad_alloc();
}
#else
if (posix_memalign(&data, 64, len) != 0) {
throw std::bad_alloc();
}
#endif
for (unsigned i = 0, copied = 0; i < iov_len; ++i) {
memcpy((char*)data + copied, iov[i].iov_base, iov[i].iov_len);
copied += iov[i].iov_len;
}
struct iovec v = { data, len };
return shared_ptr<Blob>(new Blob(&v, 1, MallocFree, 0));
}
shared_ptr<Blob> Blob::CreateFree(void *ptr, unsigned len) {
struct iovec iov = { ptr, len };
return CreateFree(&iov, 1);
}
BlobPtr Blob::CreateFree(struct iovec *iov, unsigned iov_len) {
return shared_ptr<Blob>(new Blob(iov, iov_len, MallocFree, 0));
}
shared_ptr<Blob> Blob::CreateReferenced(void *ptr, unsigned len) {
struct iovec iov = { ptr, len };
return CreateReferenced(&iov, 1);
}
BlobPtr Blob::CreateReferenced(struct iovec *iov, unsigned iov_len) {
return shared_ptr<Blob>(new Blob(iov, iov_len, 0, 0));
}
Blob::Blob(struct iovec *v, unsigned l, BlobFreeFunc f, void *c)
: iov(v, v+l), free_func(f), ctx(c)
{
}
Blob::~Blob() {
if (free_func) {
for (unsigned i = 0; i < iov.size(); ++i) {
free_func(iov[i].iov_base, ctx);
}
}
iov.clear();
free_func = 0;
ctx = 0;
}
shared_ptr<Blob> Blob::Copy() const {
return CreateCopy(&iov[0], iov.size());
}
unsigned Blob::GetTotalLength() const {
unsigned size = 0;
for (unsigned i = 0; i < iov.size(); ++i) {
size += iov[i].iov_len;
}
return size;
}
int Blob::Compare(ConstBlobPtr other) const {
unsigned our_offset = 0;
unsigned oth_offset = 0;
unsigned i = 0, j = 0;
while (i < GetNumBuffers() && j < other->GetNumBuffers()) {
unsigned len = std::min(GetLength(i) - our_offset, other->GetLength(j) - oth_offset);
int res = memcmp((char*)(GetPtr(i)) + our_offset, (char*)(other->GetPtr(j)) + oth_offset, len);
if (res != 0) { return res; }
our_offset += len;
if (our_offset >= GetLength(i)) {
our_offset = 0;
++i;
}
oth_offset += len;
if (oth_offset >= other->GetLength(j)) {
oth_offset = 0;
++j;
}
}
return 0;
}
}
| telefonicaid/fiware-IoTAgent-Cplusplus | third_party/variant/src/Blob.cc | C++ | agpl-3.0 | 3,102 |
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2014 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. 2014. All rights reserved".
********************************************************************************/
class MergeTagGuideAjaxLinkActionElement extends AjaxLinkActionElement
{
public function getActionType()
{
return 'MergeTagGuide';
}
public function render()
{
$this->registerScript();
return parent::render();
}
public function renderMenuItem()
{
$this->registerScript();
return parent::renderMenuItem();
}
protected function getDefaultLabel()
{
return Zurmo::t('EmailTemplatesModule', 'MergeTag Guide');
}
protected function getDefaultRoute()
{
return Yii::app()->createUrl($this->moduleId . '/' . $this->controllerId . '/mergeTagGuide/');
}
protected function getAjaxOptions()
{
$parentAjaxOptions = parent::getAjaxOptions();
$modalViewAjaxOptions = ModalView::getAjaxOptionsForModalLink($this->getDefaultLabel());
if (!isset($this->params['ajaxOptions']))
{
$this->params['ajaxOptions'] = array();
}
return CMap::mergeArray($parentAjaxOptions, $modalViewAjaxOptions, $this->params['ajaxOptions']);
}
protected function getHtmlOptions()
{
$htmlOptionsInParams = parent::getHtmlOptions();
$defaultHtmlOptions = array('id' => 'mergetag-guide', 'class' => 'simple-link');
return CMap::mergeArray($defaultHtmlOptions, $htmlOptionsInParams);
}
protected function registerScript()
{
$eventHandlerName = get_class($this);
$ajaxOptions = CMap::mergeArray($this->getAjaxOptions(), array('url' => $this->route));
if (Yii::app()->clientScript->isScriptRegistered($eventHandlerName))
{
return;
}
else
{
Yii::app()->clientScript->registerScript($eventHandlerName, "
function ". $eventHandlerName ."()
{
" . ZurmoHtml::ajax($ajaxOptions)."
}
", CClientScript::POS_HEAD);
}
return $eventHandlerName;
}
}
?> | speixoto/zurmo-for-school | app/protected/modules/emailTemplates/elements/actions/MergeTagGuideAjaxLinkActionElement.php | PHP | agpl-3.0 | 4,382 |
/** \file
* \author John Bridgman
* \brief
*/
#ifndef VARIANT_GUESSFORMAT_H
#define VARIANT_GUESSFORMAT_H
#pragma once
#include <Variant/Variant.h>
#include <Variant/Parser.h>
namespace libvariant {
///
// Try to guess the format of the input without removing any
// input from the input object.
//
// Currently only looks at the first non-whitespace character
// and if it is '<' then says XMLPLIST, otherwise says YAML
// if enabled otherwise JSON.
//
SerializeType GuessFormat(ParserInput* in);
}
#endif
| telefonicaid/fiware-IoTAgent-Cplusplus | third_party/variant/include/Variant/GuessFormat.h | C | agpl-3.0 | 521 |
class AddPublicDiscussionsCount < ActiveRecord::Migration
def change
add_column :groups, :public_discussions_count, :integer, null: false, default: 0
end
end
| mhjb/loomio | db/migrate/20160301094551_add_public_discussions_count.rb | Ruby | agpl-3.0 | 166 |
endor_lantern_bird_neutral_none = Lair:new {
mobiles = {{"lantern_bird",1}},
spawnLimit = 15,
buildingsVeryEasy = {},
buildingsEasy = {},
buildingsMedium = {},
buildingsHard = {},
buildingsVeryHard = {},
buildingType = "none",
}
addLairTemplate("endor_lantern_bird_neutral_none", endor_lantern_bird_neutral_none)
| Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/lair/creature_dynamic/endor_lantern_bird_neutral_none.lua | Lua | agpl-3.0 | 322 |
<?php
use MapasCulturais\i;
$section = '';
$groups = $this->getDictGroups();
$editEntity = $this->controller->action === 'create' || $this->controller->action === 'edit';
$texts = \MapasCulturais\Themes\BaseV1\Theme::_dict();
?>
<div id="texts" class="aba-content">
<p class="alert info">
<?php i::_e('Nesta seção você configura os textos utilizados na interface do site. Cada texto tem uma explicação do local em que deverá aparecer a informação. A opção de “exibir opções avançadas” possibilita que outros campos apareçam para definição dos textos.'); ?>
</p>
<?php foreach($groups as $gname => $group): ?>
<section class="filter-section">
<header>
<?php echo $group['title']; ?>
<label class="show-all"><input class="js-exibir-todos" type="checkbox"> <?php i::_e('exibir opções avançadas'); ?></label>
</header>
<p class="help"><?php echo $group['description']; ?></p>
<?php foreach ($texts as $key => $def):
$skey = str_replace(' ', '+', $key);
$section = substr($key, 0, strpos($key, ":"));
if($section != $gname) continue; ?>
<p class="js-text-config <?php if (isset($def['required']) && $def['required']): ?> required<?php else: ?> js-optional hidden<?php endif; ?>">
<span class="label">
<?php echo $def['name'] ?><?php if ($def['description']): ?><span class="info hltip" title="<?= htmlentities($def['description']) ?>"></span><?php endif; ?>:
</span>
<span class="js-editable js-editable--subsite-text"
data-edit="<?php echo "dict:" . $skey ?>"
data-original-title="<?php echo htmlentities($def['name']) ?>"
data-emptytext="<?php echo isset($entity->dict[$key]) && !empty($entity->dict[$key])? '': 'utilizando valor padrão (clique para definir)';?>"
<?php if (isset($def['examples']) && $def['examples']): ?>data-examples="<?= htmlentities(json_encode($def['examples'])) ?>" <?php endif; ?>
data-placeholder='<?php echo isset($entity->dict[$key]) && !empty($entity->dict[$key])? $entity->dict[$key]:$def['text'] ; ?>'><?php echo isset($entity->dict[$key]) ? $entity->dict[$key] : ''; ?></span>
</p>
<?php endforeach; ?>
</section>
<?php endforeach; ?>
</div>
| secultce/mapasculturais | src/protected/application/themes/BaseV1/layouts/parts/singles/subsite-texts.php | PHP | agpl-3.0 | 2,527 |
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2014 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. 2014. All rights reserved".
********************************************************************************/
/**
* Default controller for all report actions
*/
class ReportsDefaultController extends ZurmoBaseController
{
public function filters()
{
return array_merge(parent::filters(),
array(
array(
self::getRightsFilterPath() . ' + drillDownDetails',
'moduleClassName' => 'ReportsModule',
'rightName' => ReportsModule::RIGHT_ACCESS_REPORTS,
),
array(
self::getRightsFilterPath() . ' + selectType',
'moduleClassName' => 'ReportsModule',
'rightName' => ReportsModule::RIGHT_CREATE_REPORTS,
),
array(
ZurmoModuleController::ZERO_MODELS_CHECK_FILTER_PATH . ' + list, index',
'controller' => $this,
),
)
);
}
public function actionIndex()
{
$this->actionList();
}
public function actionList()
{
$pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType(
'listPageSize', get_class($this->getModule()));
$savedReport = new SavedReport(false);
$searchForm = new ReportsSearchForm($savedReport);
$listAttributesSelector = new ListAttributesSelector('ReportsListView', get_class($this->getModule()));
$searchForm->setListAttributesSelector($listAttributesSelector);
$dataProvider = $this->resolveSearchDataProvider(
$searchForm,
$pageSize,
null,
'ReportsSearchView'
);
$title = Zurmo::t('ReportsModule', 'Reports');
$breadCrumbLinks = array(
$title,
);
if (isset($_GET['ajax']) && $_GET['ajax'] == 'list-view')
{
$mixedView = $this->makeListView(
$searchForm,
$dataProvider
);
$view = new ReportsPageView($mixedView);
}
else
{
$mixedView = $this->makeActionBarSearchAndListView($searchForm, $dataProvider,
'SecuredActionBarForReportsSearchAndListView');
$view = new ReportsPageView(ZurmoDefaultViewUtil::
makeViewWithBreadcrumbsForCurrentUser(
$this, $mixedView, $breadCrumbLinks, 'ReportBreadCrumbView'));
}
echo $view->render();
}
public function actionDetails($id)
{
$savedReport = static::getModelAndCatchNotFoundAndDisplayError('SavedReport', intval($id));
ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName);
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport);
AuditEvent::logAuditEvent('ZurmoModule', ZurmoModule::AUDIT_EVENT_ITEM_VIEWED, array(strval($savedReport), 'ReportsModule'), $savedReport);
$breadCrumbLinks = array(strval($savedReport));
$breadCrumbView = new ReportBreadCrumbView($this->getId(), $this->getModule()->getId(), $breadCrumbLinks);
$detailsAndRelationsView = $this->makeReportDetailsAndRelationsView($savedReport, Yii::app()->request->getRequestUri(),
$breadCrumbView);
$view = new ReportsPageView(ZurmoDefaultViewUtil::
makeStandardViewForCurrentUser($this, $detailsAndRelationsView));
echo $view->render();
}
public function actionSelectType()
{
$breadCrumbLinks = array(Zurmo::t('ReportsModule', 'Select Report Type'));
$view = new ReportsPageView(ZurmoDefaultViewUtil::
makeViewWithBreadcrumbsForCurrentUser(
$this,
new ReportWizardTypesGridView(),
$breadCrumbLinks,
'ReportBreadCrumbView'));
echo $view->render();
}
public function actionCreate($type = null)
{
if ($type == null)
{
$this->actionSelectType();
Yii::app()->end(0, false);
}
$breadCrumbLinks = array(Zurmo::t('Core', 'Create'));
assert('is_string($type)');
$report = new Report();
$report->setType($type);
$progressBarAndStepsView = ReportWizardViewFactory::makeStepsAndProgressBarViewFromReport($report);
$reportWizardView = ReportWizardViewFactory::makeViewFromReport($report);
$view = new ReportsPageView(ZurmoDefaultViewUtil::
makeTwoViewsWithBreadcrumbsForCurrentUser(
$this,
$progressBarAndStepsView,
$reportWizardView,
$breadCrumbLinks,
'ReportBreadCrumbView'));
echo $view->render();
}
public function actionEdit($id, $isBeingCopied = false)
{
$savedReport = SavedReport::getById((int)$id);
ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName);
if (!$isBeingCopied)
{
ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($savedReport);
}
$breadCrumbLinks = array(strval($savedReport));
$report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport);
$progressBarAndStepsView = ReportWizardViewFactory::makeStepsAndProgressBarViewFromReport($report);
$reportWizardView = ReportWizardViewFactory::makeViewFromReport($report, (bool)$isBeingCopied);
$view = new ReportsPageView(ZurmoDefaultViewUtil::
makeTwoViewsWithBreadcrumbsForCurrentUser(
$this,
$progressBarAndStepsView,
$reportWizardView,
$breadCrumbLinks,
'ReportBreadCrumbView'));
echo $view->render();
}
public function actionSave($type, $id = null, $isBeingCopied = false)
{
$postData = PostUtil::getData();
$savedReport = null;
$report = null;
$this->resolveSavedReportAndReportByPostData($postData, $savedReport, $report, $type, $id, (bool)$isBeingCopied);
$reportToWizardFormAdapter = new ReportToWizardFormAdapter($report);
$model = $reportToWizardFormAdapter->makeFormByType();
if (isset($postData['ajax']) && $postData['ajax'] === 'edit-form')
{
$errorData = ReportUtil::validateReportWizardForm($postData, $model);
echo CJSON::encode($errorData);
Yii::app()->end(0, false);
}
$explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::
resolveByPostDataAndModelThenMake($postData[get_class($model)], $savedReport);
SavedReportToReportAdapter::resolveReportToSavedReport($report, $savedReport);
if ($savedReport->id > 0)
{
ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName);
}
ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($savedReport);
if ($savedReport->save())
{
StickyReportUtil::clearDataByKey($savedReport->id);
if ($explicitReadWriteModelPermissions != null)
{
ExplicitReadWriteModelPermissionsUtil::resolveExplicitReadWriteModelPermissions($savedReport,
$explicitReadWriteModelPermissions);
}
//i can do a safety check on perms, then do flash here, on the jscript we can go to list instead and this should come up...
//make sure you add to list of things to test.
$redirectToList = $this->resolveAfterSaveHasPermissionsProblem($savedReport,
$postData[get_class($model)]['name']);
echo CJSON::encode(array('id' => $savedReport->id,
'redirectToList' => $redirectToList));
Yii::app()->end(0, false);
}
else
{
throw new FailedToSaveModelException();
}
}
public function actionRelationsAndAttributesTree($type, $treeType, $id = null, $nodeId = null, $isBeingCopied = false)
{
$postData = PostUtil::getData();
$savedReport = null;
$report = null;
$this->resolveSavedReportAndReportByPostData($postData, $savedReport, $report, $type, $id, (bool)$isBeingCopied);
if ($nodeId != null)
{
$reportToTreeAdapter = new ReportRelationsAndAttributesToTreeAdapter($report, $treeType);
echo ZurmoTreeView::saveDataAsJson($reportToTreeAdapter->getData($nodeId));
Yii::app()->end(0, false);
}
$view = new ReportRelationsAndAttributesTreeView($type, $treeType, 'edit-form');
$content = $view->render();
Yii::app()->getClientScript()->setToAjaxMode();
Yii::app()->getClientScript()->render($content);
echo $content;
}
public function actionAddAttributeFromTree($type, $treeType, $nodeId, $rowNumber,
$trackableStructurePosition = false, $id = null, $isBeingCopied = false)
{
$postData = PostUtil::getData();
$savedReport = null;
$report = null;
$this->resolveSavedReportAndReportByPostData($postData, $savedReport, $report, $type, $id, (bool)$isBeingCopied);
ReportUtil::processAttributeAdditionFromTree($nodeId, $treeType, $report, $rowNumber, $trackableStructurePosition);
}
public function actionGetAvailableSeriesAndRangesForChart($type, $id = null, $isBeingCopied = false)
{
$postData = PostUtil::getData();
$savedReport = null;
$report = null;
$this->resolveSavedReportAndReportByPostData($postData, $savedReport, $report, $type, $id, (bool)$isBeingCopied);
$moduleClassName = $report->getModuleClassName();
$modelClassName = $moduleClassName::getPrimaryModelName();
$modelToReportAdapter = ModelRelationsAndAttributesToReportAdapter::
make($moduleClassName, $modelClassName, $report->getType());
if (!$modelToReportAdapter instanceof ModelRelationsAndAttributesToSummationReportAdapter)
{
throw new NotSupportedException();
}
$seriesAttributesData = $modelToReportAdapter->
getAttributesForChartSeries($report->getGroupBys(),
$report->getDisplayAttributes());
$rangeAttributesData = $modelToReportAdapter->
getAttributesForChartRange ($report->getDisplayAttributes());
$dataAndLabels = array();
$dataAndLabels['firstSeriesDataAndLabels'] = array('' => Zurmo::t('Core', '(None)'));
$dataAndLabels['firstSeriesDataAndLabels'] = array_merge($dataAndLabels['firstSeriesDataAndLabels'],
ReportUtil::makeDataAndLabelsForSeriesOrRange($seriesAttributesData));
$dataAndLabels['firstRangeDataAndLabels'] = array('' => Zurmo::t('Core', '(None)'));
$dataAndLabels['firstRangeDataAndLabels'] = array_merge($dataAndLabels['firstRangeDataAndLabels'],
ReportUtil::makeDataAndLabelsForSeriesOrRange($rangeAttributesData));
$dataAndLabels['secondSeriesDataAndLabels'] = array('' => Zurmo::t('Core', '(None)'));
$dataAndLabels['secondSeriesDataAndLabels'] = array_merge($dataAndLabels['secondSeriesDataAndLabels'],
ReportUtil::makeDataAndLabelsForSeriesOrRange($seriesAttributesData));
$dataAndLabels['secondRangeDataAndLabels'] = array('' => Zurmo::t('Core', '(None)'));
$dataAndLabels['secondRangeDataAndLabels'] = array_merge($dataAndLabels['secondRangeDataAndLabels'],
ReportUtil::makeDataAndLabelsForSeriesOrRange($rangeAttributesData));
echo CJSON::encode($dataAndLabels);
}
public function actionApplyRuntimeFilters($id)
{
$postData = PostUtil::getData();
$savedReport = SavedReport::getById((int)$id);
ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName);
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport);
$report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport);
$wizardFormClassName = ReportToWizardFormAdapter::getFormClassNameByType($report->getType());
if (!isset($postData[$wizardFormClassName]))
{
throw new NotSupportedException();
}
DataToReportUtil::resolveFilters($postData[$wizardFormClassName], $report, true);
if (isset($postData['ajax']) && $postData['ajax'] == 'edit-form')
{
$adapter = new ReportToWizardFormAdapter($report);
$reportWizardForm = $adapter->makeFormByType();
$reportWizardForm->setScenario(reportWizardForm::FILTERS_VALIDATION_SCENARIO);
if (!$reportWizardForm->validate())
{
$errorData = array();
foreach ($reportWizardForm->getErrors() as $attribute => $errors)
{
$errorData[ZurmoHtml::activeId($reportWizardForm, $attribute)] = $errors;
}
echo CJSON::encode($errorData);
Yii::app()->end(0, false);
}
}
$filtersData = ArrayUtil::getArrayValue($postData[$wizardFormClassName],
ComponentForReportForm::TYPE_FILTERS);
$sanitizedFiltersData = DataToReportUtil::sanitizeFiltersData($report->getModuleClassName(),
$report->getType(),
$filtersData);
$stickyData = array(ComponentForReportForm::TYPE_FILTERS => $sanitizedFiltersData);
StickyReportUtil::setDataByKeyAndData($report->getId(), $stickyData);
}
public function actionResetRuntimeFilters($id)
{
$savedReport = SavedReport::getById((int)$id);
ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName);
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport);
$report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport);
StickyReportUtil::clearDataByKey($report->getId());
}
public function actionDelete($id)
{
$savedReport = SavedReport::GetById(intval($id));
ControllerSecurityUtil::resolveAccessCanCurrentUserDeleteModel($savedReport);
$savedReport->delete();
$this->redirect(array($this->getId() . '/index'));
}
public function actionDrillDownDetails($id, $rowId)
{
$savedReport = SavedReport::getById((int)$id);
ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName);
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport, true);
$report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport);
$report->resolveGroupBysAsFilters(GetUtil::getData());
if (null != $stickyData = StickyReportUtil::getDataByKey($report->id))
{
StickyReportUtil::resolveStickyDataToReport($report, $stickyData);
}
$pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType(
'reportResultsSubListPageSize', get_class($this->getModule()));
$dataProvider = ReportDataProviderFactory::makeForSummationDrillDown($report, $pageSize);
$dataProvider->setRunReport(true);
$view = new SummationDrillDownReportResultsGridView('default', 'reports', $dataProvider, $rowId);
$content = $view->render();
Yii::app()->getClientScript()->setToAjaxMode();
Yii::app()->getClientScript()->render($content);
echo $content;
}
public function actionExport($id, $stickySearchKey = null)
{
assert('$stickySearchKey == null || is_string($stickySearchKey)');
$savedReport = SavedReport::getById((int)$id);
ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName);
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport);
$report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport);
$dataProvider = $this->getDataProviderForExport($report, $report->getId(), false);
$totalItems = intval($dataProvider->calculateTotalItemCount());
$data = array();
if ($totalItems > 0)
{
if ($totalItems <= ExportModule::$asynchronousThreshold)
{
// Output csv file directly to user browser
if ($dataProvider)
{
$reportToExportAdapter = ReportToExportAdapterFactory::createReportToExportAdapter($report, $dataProvider);
$headerData = $reportToExportAdapter->getHeaderData();
$data = $reportToExportAdapter->getData();
}
// Output data
if (count($data))
{
$fileName = $this->getModule()->getName() . ".csv";
ExportItemToCsvFileUtil::export($data, $headerData, $fileName, true);
}
else
{
Yii::app()->user->setFlash('notification',
Zurmo::t('ZurmoModule', 'There is no data to export.')
);
}
}
else
{
if ($dataProvider)
{
$serializedData = ExportUtil::getSerializedDataForExport($dataProvider);
}
// Create background job
$exportItem = new ExportItem();
$exportItem->isCompleted = 0;
$exportItem->exportFileType = 'csv';
$exportItem->exportFileName = $this->getModule()->getName();
$exportItem->modelClassName = 'SavedReport';
$exportItem->serializedData = $serializedData;
$exportItem->save();
$exportItem->forget();
Yii::app()->user->setFlash('notification',
Zurmo::t('ZurmoModule', 'A large amount of data has been requested for export. You will receive ' .
'a notification with the download link when the export is complete.')
);
}
}
else
{
Yii::app()->user->setFlash('notification',
Zurmo::t('ZurmoModule', 'There is no data to export.')
);
}
$this->redirect(array($this->getId() . '/index'));
}
public function actionModalList($stateMetadataAdapterClassName = null)
{
$modalListLinkProvider = new SelectFromRelatedEditModalListLinkProvider(
$_GET['modalTransferInformation']['sourceIdFieldId'],
$_GET['modalTransferInformation']['sourceNameFieldId'],
$_GET['modalTransferInformation']['modalId']
);
echo ModalSearchListControllerUtil::
setAjaxModeAndRenderModalSearchList($this, $modalListLinkProvider, $stateMetadataAdapterClassName);
}
public function actionAutoComplete($term, $moduleClassName = null, $type = null, $autoCompleteOptions = null)
{
$pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType(
'autoCompleteListPageSize', get_class($this->getModule()));
$autoCompleteResults = ReportAutoCompleteUtil::getByPartialName($term, $pageSize, $moduleClassName,
$type, $autoCompleteOptions);
echo CJSON::encode($autoCompleteResults);
}
protected function resolveCanCurrentUserAccessReports()
{
if (!RightsUtil::doesUserHaveAllowByRightName('ReportsModule',
ReportsModule::RIGHT_CREATE_REPORTS,
Yii::app()->user->userModel))
{
$messageView = new AccessFailureView();
$view = new AccessFailurePageView($messageView);
echo $view->render();
Yii::app()->end(0, false);
}
return true;
}
protected function resolveSavedReportAndReportByPostData(Array $postData, & $savedReport, & $report, $type,
$id = null, $isBeingCopied = false)
{
if ($id == null)
{
$this->resolveCanCurrentUserAccessReports();
$savedReport = new SavedReport();
$report = new Report();
$report->setType($type);
}
elseif ($isBeingCopied)
{
$savedReport = new SavedReport();
$oldReport = SavedReport::getById(intval($id));
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($oldReport);
ZurmoCopyModelUtil::copy($oldReport, $savedReport);
$report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport);
}
else
{
$savedReport = SavedReport::getById(intval($id));
ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($savedReport);
$report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport);
}
DataToReportUtil::resolveReportByWizardPostData($report, $postData,
ReportToWizardFormAdapter::getFormClassNameByType($type));
}
protected function resolveAfterSaveHasPermissionsProblem(SavedReport $savedReport, $modelToStringValue)
{
assert('is_string($modelToStringValue)');
if (ControllerSecurityUtil::doesCurrentUserHavePermissionOnSecurableItem($savedReport, Permission::READ))
{
return false;
}
else
{
$notificationContent = Zurmo::t(
'ReportsModule',
'You no longer have permissions to access {modelName}.',
array('{modelName}' => $modelToStringValue)
);
Yii::app()->user->setFlash('notification', $notificationContent);
return true;
}
}
protected function makeReportDetailsAndRelationsView(SavedReport $savedReport, $redirectUrl,
ReportBreadCrumbView $breadCrumbView)
{
$reportDetailsAndRelationsView = ReportDetailsAndResultsViewFactory::makeView($savedReport, $this->getId(),
$this->getModule()->getId(),
$redirectUrl);
$gridView = new GridView(2, 1);
$gridView->setView($breadCrumbView, 0, 0);
$gridView->setView($reportDetailsAndRelationsView, 1, 0);
return $gridView;
}
protected function getDataProviderForExport(Report $report, $stickyKey, $runReport)
{
assert('is_string($stickyKey) || is_int($stickyKey)');
assert('is_bool($runReport)');
if (null != $stickyData = StickyReportUtil::getDataByKey($stickyKey))
{
StickyReportUtil::resolveStickyDataToReport($report, $stickyData);
}
$pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType(
'reportResultsListPageSize', get_class($this->getModule()));
$dataProvider = ReportDataProviderFactory::makeByReport($report, $pageSize);
if (!($dataProvider instanceof MatrixReportDataProvider))
{
$totalItems = intval($dataProvider->calculateTotalItemCount());
$dataProvider->getPagination()->setPageSize($totalItems);
}
if ($runReport)
{
$dataProvider->setRunReport($runReport);
}
return $dataProvider;
}
protected function resolveMetadataBeforeMakingDataProvider(& $metadata)
{
$metadata = SavedReportUtil::resolveSearchAttributeDataByModuleClassNames($metadata,
Report::getReportableModulesClassNamesCurrentUserHasAccessTo());
}
}
?>
| maruthisivaprasad/zurmo | app/protected/modules/reports/controllers/DefaultController1.php | PHP | agpl-3.0 | 30,234 |
<%page expression_filter="h"/>
<%inherit file="../main.html" />
<%!
from django.utils.translation import ugettext as _
from django.urls import reverse
from openedx.core.djangolib.js_utils import js_escaped_string
from openedx.core.djangolib.markup import HTML, Text
%>
<%block name="bodyclass">register verification-process step-select-track</%block>
<%block name="pagetitle">
${_("Enroll In {course_name} | Choose Your Track").format(course_name=course_name)}
</%block>
<%block name="js_extra">
<script type="text/javascript">
var expandCallback = function(event) {
event.preventDefault();
$(this).next('.expandable-area').slideToggle();
var title = $(this).parent();
title.toggleClass('is-expanded');
if (title.attr("aria-expanded") === "false") {
title.attr("aria-expanded", "true");
} else {
title.attr("aria-expanded", "false");
}
};
$(document).ready(function() {
$('.expandable-area').slideUp();
$('.is-expandable').addClass('is-ready');
$('.is-expandable .title-expand').click(expandCallback);
$('.is-expandable .title-expand').keypress(function(e) {
if (e.which == 13) { // only activate on pressing enter
expandCallback.call(this, e); // make sure that we bind `this` correctly
}
});
$('#contribution-other-amt').focus(function() {
$('#contribution-other').attr('checked',true);
});
% if use_ecommerce_payment_flow:
$('input[name=verified_mode]').click(function(e){
e.preventDefault();
window.location.href = '${ecommerce_payment_page | n, js_escaped_string}?sku=' +
encodeURIComponent('${sku | n, js_escaped_string}');
});
% endif
});
</script>
</%block>
<%block name="content">
% if error:
<div class="wrapper-msg wrapper-msg-error">
<div class=" msg msg-error">
<span class="msg-icon icon fa fa-exclamation-triangle" aria-hidden="true"></span>
<div class="msg-content">
<h3 class="title">${_("Sorry, there was an error when trying to enroll you")}</h3>
<div class="copy">
<p>${error}</p>
</div>
</div>
</div>
</div>
%endif
<div class="container">
<section class="wrapper">
<div class="wrapper-register-choose wrapper-content-main">
<article class="register-choose content-main">
<header class="page-header content-main">
<h3 class="title">
${title_content}
</h3>
</header>
<form class="form-register-choose" method="post" name="enrollment_mode_form" id="enrollment_mode_form">
<%
b_tag_kwargs = {'b_start': HTML('<b>'), 'b_end': HTML('</b>')}
%>
% if "verified" in modes:
<div class="register-choice register-choice-certificate">
<div class="wrapper-copy">
<span class="deco-ribbon"></span>
% if has_credit_upsell:
% if content_gating_enabled or course_duration_limit_enabled:
<h4 class="title">${_("Pursue Academic Credit with the Verified Track")}</h4>
% else:
<h4 class="title">${_("Pursue Academic Credit with a Verified Certificate")}</h4>
% endif
<div class="copy">
<p>${_("Become eligible for academic credit and highlight your new skills and knowledge with a verified certificate. Use this valuable credential to qualify for academic credit, advance your career, or strengthen your school applications.")}</p>
<p>
<div class="wrapper-copy-inline">
<div class="copy-inline">
% if content_gating_enabled or course_duration_limit_enabled:
<h4>${_("Benefits of the Verified Track")}</h4>
<ul>
<li>${Text(_("{b_start}Eligible for credit:{b_end} Receive academic credit after successfully completing the course")).format(**b_tag_kwargs)}</li>
% if course_duration_limit_enabled:
<li>${Text(_("{b_start}Unlimited Course Access: {b_end}Learn at your own pace, and access materials anytime to brush up on what you've learned.")).format(**b_tag_kwargs)}</li>
% endif
% if content_gating_enabled:
<li>${Text(_("{b_start}Graded Assignments: {b_end}Build your skills through graded assignments and projects.")).format(**b_tag_kwargs)}</li>
% endif
<li>${Text(_("{b_start}Easily Sharable: {b_end}Add the certificate to your CV or resume, or post it directly on LinkedIn.")).format(**b_tag_kwargs)}</li>
</ul>
% else:
<h4>${_("Benefits of a Verified Certificate")}</h4>
<ul>
<li>${Text(_("{b_start}Eligible for credit:{b_end} Receive academic credit after successfully completing the course")).format(**b_tag_kwargs)}</li>
<li>${Text(_("{b_start}Official:{b_end} Receive an instructor-signed certificate with the institution's logo")).format(**b_tag_kwargs)}</li>
<li>${Text(_("{b_start}Easily shareable:{b_end} Add the certificate to your CV or resume, or post it directly on LinkedIn")).format(**b_tag_kwargs)}</li>
</ul>
% endif
</div>
<div class="copy-inline list-actions">
<ul class="list-actions">
<li class="action action-select">
<input type="hidden" name="contribution" value="${min_price}" />
<input type="submit" name="verified_mode" value="${_('Pursue a Verified Certificate')} ($${min_price} USD)" />
</li>
</ul>
</div>
</div>
</p>
</div>
% else:
% if content_gating_enabled or course_duration_limit_enabled:
<h4 class="title">${_("Pursue the Verified Track")}</h4>
% else:
<h4 class="title">${_("Pursue a Verified Certificate")}</h4>
% endif
<div class="copy">
<p>${_("Highlight your new knowledge and skills with a verified certificate. Use this valuable credential to improve your job prospects and advance your career, or highlight your certificate in school applications.")}</p>
<p>
<div class="wrapper-copy-inline">
<div class="copy-inline">
% if content_gating_enabled or course_duration_limit_enabled:
<h4>${_("Benefits of the Verified Track")}</h4>
<ul>
% if course_duration_limit_enabled:
<li>${Text(_("{b_start}Unlimited Course Access: {b_end}Learn at your own pace, and access materials anytime to brush up on what you've learned.")).format(**b_tag_kwargs)}</li>
% endif
% if content_gating_enabled:
<li>${Text(_("{b_start}Graded Assignments: {b_end}Build your skills through graded assignments and projects.")).format(**b_tag_kwargs)}</li>
% endif
<li>${Text(_("{b_start}Easily Sharable: {b_end}Add the certificate to your CV or resume, or post it directly on LinkedIn.")).format(**b_tag_kwargs)}</li>
</ul>
% else:
<h4>${_("Benefits of a Verified Certificate")}</h4>
<ul>
<li>${Text(_("{b_start}Official: {b_end}Receive an instructor-signed certificate with the institution's logo")).format(**b_tag_kwargs)}</li>
<li>${Text(_("{b_start}Easily shareable: {b_end}Add the certificate to your CV or resume, or post it directly on LinkedIn")).format(**b_tag_kwargs)}</li>
<li>${Text(_("{b_start}Motivating: {b_end}Give yourself an additional incentive to complete the course")).format(**b_tag_kwargs)}</li>
</ul>
% endif
</div>
<div class="copy-inline list-actions">
<ul class="list-actions">
<li class="action action-select">
<input type="hidden" name="contribution" value="${min_price}" />
% if content_gating_enabled or course_duration_limit_enabled:
<input type="submit" name="verified_mode" value="${_('Pursue the Verified Track')} ($${min_price} USD)" />
% else:
<input type="submit" name="verified_mode" value="${_('Pursue a Verified Certificate')} ($${min_price} USD)" />
% endif
</li>
</ul>
</div>
</div>
</p>
</div>
% endif
</div>
</div>
% endif
% if "honor" in modes:
<span class="deco-divider">
<span class="copy">${_("or")}</span>
</span>
<div class="register-choice register-choice-audit">
<div class="wrapper-copy">
<span class="deco-ribbon"></span>
<h4 class="title">${_("Audit This Course")}</h4>
<div class="copy">
<p>${_("Audit this course for free and have complete access to all the course material, activities, tests, and forums.")}</p>
</div>
</div>
<ul class="list-actions">
<li class="action action-select">
<input type="submit" name="honor_mode" value="${_('Audit This Course')}" />
</li>
</ul>
</div>
% elif "audit" in modes:
<span class="deco-divider">
<span class="copy">${_("or")}</span>
</span>
<div class="register-choice register-choice-audit">
<div class="wrapper-copy">
<span class="deco-ribbon"></span>
<h4 class="title">${_("Audit This Course (No Certificate)")}</h4>
<div class="copy">
## Translators: b_start notes the beginning of a section of text bolded for emphasis, and b_end marks the end of the bolded text.
% if content_gating_enabled and course_duration_limit_enabled:
<p>${Text(_("Audit this course for free and have access to course materials and discussions forums. {b_start}This track does not include graded assignments, or unlimited course access.{b_end}")).format(**b_tag_kwargs)}</p>
% elif content_gating_enabled and not course_duration_limit_enabled:
<p>${Text(_("Audit this course for free and have access to course materials and discussions forums. {b_start}This track does not include graded assignments.{b_end}")).format(**b_tag_kwargs)}</p>
% elif not content_gating_enabled and course_duration_limit_enabled:
<p>${Text(_("Audit this course for free and have access to course materials and discussions forums. {b_start}This track does not include unlimited course access.{b_end}")).format(**b_tag_kwargs)}</p>
% else:
<p>${Text(_("Audit this course for free and have complete access to all the course material, activities, tests, and forums. {b_start}Please note that this track does not offer a certificate for learners who earn a passing grade.{b_end}")).format(**b_tag_kwargs)}</p>
% endif
</div>
</div>
<ul class="list-actions">
<li class="action action-select">
<input type="submit" name="audit_mode" value="${_('Audit This Course')}" />
</li>
</ul>
</div>
% endif
<input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }">
</form>
</article>
</div> <!-- /wrapper-content-main -->
</section>
</div>
</%block>
| philanthropy-u/edx-platform | lms/templates/course_modes/choose.html | HTML | agpl-3.0 | 16,775 |
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** 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.
**
** 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#ifndef INSPECTORSETTINGS_H
#define INSPECTORSETTINGS_H
#include <QtCore/QObject>
QT_FORWARD_DECLARE_CLASS(QSettings)
namespace QmlJSInspector {
namespace Internal {
class InspectorSettings : public QObject
{
Q_OBJECT
public:
InspectorSettings(QObject *parent = 0);
void restoreSettings(QSettings *settings);
void saveSettings(QSettings *settings) const;
bool showLivePreviewWarning() const;
void setShowLivePreviewWarning(bool value);
private:
bool m_showLivePreviewWarning;
};
} // namespace Internal
} // namespace QmlJSInspector
#endif // INSPECTORSETTINGS_H
| renatofilho/QtCreator | src/plugins/qmljsinspector/qmljsinspectorsettings.h | C | lgpl-2.1 | 1,884 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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
*/
package org.opencms.gwt.shared.sort;
import java.util.Comparator;
/**
* Comparator for objects with a type property.<p>
*
* @see I_CmsHasType
*
* @since 8.0.0
*/
public class CmsComparatorType implements Comparator<I_CmsHasType> {
/** Sort order flag. */
private boolean m_ascending;
/**
* Constructor.<p>
*
* @param ascending if <code>true</code> order is ascending
*/
public CmsComparatorType(boolean ascending) {
m_ascending = ascending;
}
/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(I_CmsHasType o1, I_CmsHasType o2) {
int result = o1.getType().compareTo(o2.getType());
return m_ascending ? result : -result;
}
}
| ggiudetti/opencms-core | src/org/opencms/gwt/shared/sort/CmsComparatorType.java | Java | lgpl-2.1 | 1,889 |
/*
eXokernel Development Kit (XDK)
Based on code by Samsung Research America Copyright (C) 2013
The GNU C 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.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>.
As a special exception, if you link the code in this file with
files compiled with a GNU compiler to produce an executable,
that does not cause the resulting executable to be covered by
the GNU Lesser General Public License. This exception does not
however invalidate any other reasons why the executable file
might be covered by the GNU Lesser General Public License.
This exception applies to code released by its copyright holders
in files containing the exception.
*/
#include <stdio.h>
#include <stdarg.h>
#include <common/logging.h>
#include "nvme_common.h"
#ifdef NVME_VERBOSE
void NVME_INFO(const char *fmt, ...) {
printf(NORMAL_MAGENTA);
va_list list;
va_start(list, fmt);
printf("[NVME]:");
vprintf(fmt, list);
va_end(list);
printf(RESET);
}
#endif
| dwaddington/xdk | drivers/nvme-ssd/nvme_common.cc | C++ | lgpl-2.1 | 1,621 |
package railo.runtime.search.lucene2.query;
import railo.commons.lang.StringUtil;
public final class Concator implements Op {
private Op left;
private Op right;
public Concator(Op left,Op right) {
this.left=left;
this.right=right;
}
@Override
public String toString() {
if(left instanceof Literal && right instanceof Literal) {
String str=((Literal)left).literal+" "+((Literal)right).literal;
return "\""+StringUtil.replace(str, "\"", "\"\"", false)+"\"";
}
return left+" "+right;
}
}
| modius/railo | railo-java/railo-core/src/railo/runtime/search/lucene2/query/Concator.java | Java | lgpl-2.1 | 516 |
/*
* Portable Object Compiler (c) 1997,98,2003. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __OBJSET_H__
#define __OBJSET_H__
#include "cltn.h"
typedef struct objset
{
int count;
int capacity;
id * ptr;
} * objset_t;
/*!
* @abstract Set of objects.
* @discussion Stores objects in a hashed table. Each object may be added only
* once; no duplicates are permitted. The @link hash @/link message is used for
* this purpose. Both that and the @link isEqual: @/link message should be
* responded to by any object to be added to the set, and @link hash @/link
* should return an identical hash for an object to that of one that
* @link isEqual: @/link to another.
*
* The object may not be properly located within the Set, or duplicates may be
* permitted to be added, if the object should change its respond to
* @link hash @/link while it is in the Set.
* @see Cltn
* @indexgroup Collection
*/
@interface Set <T> : Cltn
{
struct objset value;
}
+ new;
+ new:(unsigned)n;
+ with:(int)nArgs, ...;
+ with:firstObject with:nextObject;
+ add:(T)firstObject;
- copy;
- deepCopy;
- emptyYourself;
- freeContents;
- free;
- (unsigned)size;
- (BOOL)isEmpty;
- eachElement;
- (BOOL)isEqual:set;
- add:(T)anObject;
- addNTest:(T)anObject;
- filter:(T)anObject;
- add:(T)anObject ifDuplicate:aBlock;
- replace:(T)anObject;
- remove:(T)oldObject;
- remove:(T)oldObject ifAbsent:exceptionBlock;
- (BOOL)includesAllOf:aCltn;
- (BOOL)includesAnyOf:aCltn;
- addAll:aCltn;
- addContentsOf:aCltn;
- addContentsTo:aCltn;
- removeAll:aCltn;
- removeContentsFrom:aCltn;
- removeContentsOf:aCltn;
- intersection:bag;
- union:bag;
- difference:bag;
- asSet;
- asOrdCltn;
- detect:aBlock;
- detect:aBlock ifNone:noneBlock;
- select:testBlock;
- reject:testBlock;
- collect:transformBlock;
- (unsigned)count:aBlock;
- elementsPerform:(SEL)aSelector;
- elementsPerform:(SEL)aSelector with:anObject;
- elementsPerform:(SEL)aSelector with:anObject with:otherObject;
- elementsPerform:(SEL)aSelector with:anObject with:otherObject with:thirdObj;
- do:aBlock;
- do:aBlock until:(BOOL *)flag;
- find:(T)anObject;
- (BOOL)contains:(T)anObject;
- (BOOL)includes:(T)anObject;
- (unsigned)occurrencesOf:(T)anObject;
- printOn:(IOD)aFile;
- fileOutOn:aFiler;
- fileInFrom:aFiler;
- awakeFrom:aFiler;
/* private */
- (objset_t)objsetvalue;
- addYourself;
- freeAll;
- ARC_dealloc;
- (uintptr_t)hash;
@end
#endif /* __OBJSET_H__ */
| JX7P/PCPlusPlus | objpak/hdr/Set.h | C | lgpl-2.1 | 3,158 |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class XorgServer(AutotoolsPackage, XorgPackage):
"""X.Org Server is the free and open source implementation of the display
server for the X Window System stewarded by the X.Org Foundation."""
homepage = "http://cgit.freedesktop.org/xorg/xserver"
xorg_mirror_path = "xserver/xorg-server-1.18.99.901.tar.gz"
version('1.18.99.901', sha256='c8425163b588de2ee7e5c8e65b0749f2710f55a7e02a8d1dc83b3630868ceb21')
depends_on('pixman@0.27.2:')
depends_on('font-util')
depends_on('libxshmfence@1.1:')
depends_on('libdrm@2.3.0:')
depends_on('libx11')
depends_on('dri2proto@2.8:', type='build')
depends_on('dri3proto@1.0:', type='build')
depends_on('glproto@1.4.17:', type='build')
depends_on('flex', type='build')
depends_on('bison', type='build')
depends_on('pkgconfig', type='build')
depends_on('util-macros', type='build')
depends_on('fixesproto@5.0:')
depends_on('damageproto@1.1:')
depends_on('xcmiscproto@1.2.0:')
depends_on('xtrans@1.3.5:')
depends_on('bigreqsproto@1.1.0:')
depends_on('xproto@7.0.28:')
depends_on('randrproto@1.5.0:')
depends_on('renderproto@0.11:')
depends_on('xextproto@7.2.99.901:')
depends_on('inputproto@2.3:')
depends_on('kbproto@1.0.3:')
depends_on('fontsproto@2.1.3:')
depends_on('pixman@0.27.2:')
depends_on('videoproto')
depends_on('compositeproto@0.4:')
depends_on('recordproto@1.13.99.1:')
depends_on('scrnsaverproto@1.1:')
depends_on('resourceproto@1.2.0:')
depends_on('xf86driproto@2.1.0:')
depends_on('glproto@1.4.17:')
depends_on('presentproto@1.0:')
depends_on('xineramaproto')
depends_on('libxkbfile')
depends_on('libxfont2')
depends_on('libxext')
depends_on('libxdamage')
depends_on('libxfixes')
depends_on('libepoxy')
| iulian787/spack | var/spack/repos/builtin/packages/xorg-server/package.py | Python | lgpl-2.1 | 2,055 |
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtXmlPatterns 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$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
#ifndef Patternist_OperandsIterator_H
#define Patternist_OperandsIterator_H
#include <QPair>
#include <QStack>
#include "qexpression_p.h"
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
namespace QPatternist
{
/**
* @short A helper class that iterates a tree of Expression instances. It
* is not a sub-class of QAbstractXmlForwardIterator.
*
* The OperandsIterator delivers all Expression instances that are children at any
* depth of the Expression passed in the constructor.
* The order is delivered in a defined way, from left to right and depth
* first.
*
* @author Frans Englich <frans.englich@nokia.com>
*/
class OperandsIterator
{
/**
* The second value, the int, is the current position in the first.
*/
typedef QPair<Expression::List, int> Level;
public:
enum TreatParent
{
ExcludeParent,
IncludeParent
};
/**
* if @p treatParent is @c IncludeParent, @p start is excluded.
*
* @p start must be a valid Expression.
*/
inline OperandsIterator(const Expression::Ptr &start,
const TreatParent treatParent)
{
Q_ASSERT(start);
if(treatParent == IncludeParent)
{
Expression::List l;
l.append(start);
m_exprs.push(qMakePair(l, -1));
}
m_exprs.push(qMakePair(start->operands(), -1));
}
/**
* @short Returns the current Expression and advances the iterator.
*
* If the end has been reached, a default constructed pointer is
* returned.
*
* We intentionally return by reference.
*/
inline Expression::Ptr next()
{
if(m_exprs.isEmpty())
return Expression::Ptr();
Level &lvl = m_exprs.top();
++lvl.second;
if(lvl.second == lvl.first.size())
{
/* Resume iteration above us. */
m_exprs.pop();
if(m_exprs.isEmpty())
return Expression::Ptr();
while(true)
{
Level &previous = m_exprs.top();
++previous.second;
if(previous.second < previous.first.count())
{
const Expression::Ptr &op = previous.first.at(previous.second);
m_exprs.push(qMakePair(op->operands(), -1));
return op;
}
else
{
// We have already reached the end of this level.
m_exprs.pop();
if(m_exprs.isEmpty())
return Expression::Ptr();
}
}
}
else
{
const Expression::Ptr &op = lvl.first.at(lvl.second);
m_exprs.push(qMakePair(op->operands(), -1));
return op;
}
}
/**
* Advances this iterator by the current expression and its operands.
*/
Expression::Ptr skipOperands()
{
if(m_exprs.isEmpty())
return Expression::Ptr();
Level &lvl = m_exprs.top();
++lvl.second;
if(lvl.second == lvl.first.size())
{
/* We've reached the end of this level, at least. */
m_exprs.pop();
}
return next();
}
private:
Q_DISABLE_COPY(OperandsIterator)
QStack<Level> m_exprs;
};
}
QT_END_NAMESPACE
QT_END_HEADER
#endif
| kobolabs/qt-everywhere-4.8.0 | src/xmlpatterns/expr/qoperandsiterator_p.h | C | lgpl-2.1 | 5,802 |
package org.hivedb.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.shards.session.OpenSessionEvent;
import java.sql.SQLException;
public class RecordNodeOpenSessionEvent implements OpenSessionEvent {
public static ThreadLocal<String> node = new ThreadLocal<String>();
public static String getNode() {
return node.get();
}
public static void setNode(Session session) {
node.set(getNode(session));
}
public void onOpenSession(Session session) {
setNode(session);
}
@SuppressWarnings("deprecation")
private static String getNode(Session session) {
String node = "";
if (session != null) {
try {
node = session.connection().getMetaData().getURL();
} catch (SQLException ex) {
} catch (HibernateException ex) {
}
}
return node;
}
}
| britt/hivedb | src/main/java/org/hivedb/hibernate/RecordNodeOpenSessionEvent.java | Java | lgpl-2.1 | 834 |
using System;
using System.Collections;
using System.Collections.Generic;
using NHibernate.Driver;
using NHibernate.Test.SecondLevelCacheTests;
using NUnit.Framework;
namespace NHibernate.Test.QueryTest
{
[TestFixture]
public class MultipleMixedQueriesFixture : TestCase
{
protected override string MappingsAssembly
{
get { return "NHibernate.Test"; }
}
protected override IList Mappings
{
get { return new[] { "SecondLevelCacheTest.Item.hbm.xml" }; }
}
protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory)
{
return factory.ConnectionProvider.Driver.SupportsMultipleQueries;
}
protected override void OnTearDown()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
session.Delete("from System.Object");
session.Flush();
transaction.Commit();
}
}
[Test]
public void NH_1085_WillIgnoreParametersIfDoesNotAppearInQuery()
{
using (var s = Sfi.OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:ids)").AddEntity(typeof (Item)))
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:ids2)").AddEntity(typeof (Item)))
.SetParameterList("ids", new[] {50})
.SetParameterList("ids2", new[] {50});
multiQuery.List();
}
}
[Test]
public void NH_1085_WillGiveReasonableErrorIfBadParameterName()
{
using (var s = Sfi.OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:ids)").AddEntity(typeof(Item)))
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:ids2)").AddEntity(typeof(Item)));
var e = Assert.Throws<QueryException>(() => multiQuery.List());
Assert.That(e.Message, Is.EqualTo("Not all named parameters have been set: ['ids'] [select * from ITEM where Id in (:ids)]"));
}
}
[Test]
public void CanGetMultiQueryFromSecondLevelCache()
{
CreateItems();
//set the query in the cache
DoMutiQueryAndAssert();
var cacheHashtable = MultipleQueriesFixture.GetHashTableUsedAsQueryCache(Sfi);
var cachedListEntry = (IList)new ArrayList(cacheHashtable.Values)[0];
var cachedQuery = (IList)cachedListEntry[1];
var firstQueryResults = (IList)cachedQuery[0];
firstQueryResults.Clear();
firstQueryResults.Add(3);
firstQueryResults.Add(4);
var secondQueryResults = (IList)cachedQuery[1];
secondQueryResults[0] = 2L;
using (var s = Sfi.OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id > ?").AddEntity(typeof(Item))
.SetInt32(0, 50)
.SetFirstResult(10))
.Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
.SetInt32(0, 50));
multiQuery.SetCacheable(true);
var results = multiQuery.List();
var items = (IList)results[0];
Assert.AreEqual(2, items.Count);
var count = (long)((IList)results[1])[0];
Assert.AreEqual(2L, count);
}
}
[Test]
public void CanSpecifyParameterOnMultiQueryWhenItIsNotUsedInAllQueries()
{
using (var s = OpenSession())
{
s.CreateMultiQuery()
.Add("from Item")
.Add(s.CreateSQLQuery("select * from ITEM where Id > :id").AddEntity(typeof(Item)))
.SetParameter("id", 5)
.List();
}
}
[Test]
public void CanSpecifyParameterOnMultiQueryWhenItIsNotUsedInAllQueries_MoreThanOneParameter()
{
using (var s = OpenSession())
{
s.CreateMultiQuery()
.Add("from Item")
.Add(s.CreateSQLQuery("select * from ITEM where Id = :id or Id = :id2").AddEntity(typeof(Item)))
.Add("from Item i where i.Id = :id2")
.SetParameter("id", 5)
.SetInt32("id2", 5)
.List();
}
}
[Test]
public void TwoMultiQueriesWithDifferentPagingGetDifferentResultsWhenUsingCachedQueries()
{
CreateItems();
using (var s = OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateQuery("from Item i where i.Id > ?")
.SetInt32(0, 50)
.SetFirstResult(10))
.Add(s.CreateSQLQuery("select count(*) as count from ITEM where Id > ?").AddScalar("count", NHibernateUtil.Int64)
.SetInt32(0, 50));
multiQuery.SetCacheable(true);
var results = multiQuery.List();
var items = (IList)results[0];
Assert.AreEqual(89, items.Count);
var count = (long)((IList)results[1])[0];
Assert.AreEqual(99L, count);
}
using (var s = OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id > ?").AddEntity(typeof(Item))
.SetInt32(0, 50)
.SetFirstResult(20))
.Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
.SetInt32(0, 50));
multiQuery.SetCacheable(true);
var results = multiQuery.List();
var items = (IList)results[0];
Assert.AreEqual(79, items.Count,
"Should have gotten different result here, because the paging is different");
var count = (long)((IList)results[1])[0];
Assert.AreEqual(99L, count);
}
}
[Test]
public void CanUseSecondLevelCacheWithPositionalParameters()
{
var cacheHashtable = MultipleQueriesFixture.GetHashTableUsedAsQueryCache(Sfi);
cacheHashtable.Clear();
CreateItems();
DoMutiQueryAndAssert();
Assert.AreEqual(1, cacheHashtable.Count);
}
private void DoMutiQueryAndAssert()
{
using (var s = OpenSession())
{
var multiQuery = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id > ?").AddEntity(typeof(Item))
.SetInt32(0, 50)
.SetFirstResult(10))
.Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
.SetInt32(0, 50));
multiQuery.SetCacheable(true);
var results = multiQuery.List();
var items = (IList)results[0];
Assert.AreEqual(89, items.Count);
var count = (long)((IList)results[1])[0];
Assert.AreEqual(99L, count);
}
}
private void CreateItems()
{
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
for (var i = 0; i < 150; i++)
{
var item = new Item();
item.Id = i;
s.Save(item);
}
t.Commit();
}
}
[Test]
public void CanUseWithParameterizedQueriesAndLimit()
{
using (var s = OpenSession())
{
for (var i = 0; i < 150; i++)
{
var item = new Item();
item.Id = i;
s.Save(item);
}
s.Flush();
}
using (var s = OpenSession())
{
var getItems = s.CreateSQLQuery("select * from ITEM where Id > :id").AddEntity(typeof(Item)).SetFirstResult(10);
var countItems = s.CreateQuery("select count(*) from Item i where i.Id > :id");
var results = s.CreateMultiQuery()
.Add(getItems)
.Add(countItems)
.SetInt32("id", 50)
.List();
var items = (IList)results[0];
Assert.AreEqual(89, items.Count);
var count = (long)((IList)results[1])[0];
Assert.AreEqual(99L, count);
}
}
[Test]
public void CanUseSetParameterList()
{
using (var s = OpenSession())
{
var item = new Item();
item.Id = 1;
s.Save(item);
s.Flush();
}
using (var s = OpenSession())
{
var results = s.CreateMultiQuery()
.Add(s.CreateSQLQuery("select * from ITEM where Id in (:items)").AddEntity(typeof(Item)))
.Add("select count(*) from Item i where i.id in (:items)")
.SetParameterList("items", new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 })
.List();
var items = (IList)results[0];
var fromDb = (Item)items[0];
Assert.AreEqual(1, fromDb.Id);
var counts = (IList)results[1];
var count = (long)counts[0];
Assert.AreEqual(1L, count);
}
}
[Test]
public void CanExecuteMultiplyQueriesInSingleRoundTrip()
{
using (var s = OpenSession())
{
var item = new Item();
item.Id = 1;
s.Save(item);
s.Flush();
}
using (var s = OpenSession())
{
var getItems = s.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item));
var countItems = s.CreateQuery("select count(*) from Item");
var results = s.CreateMultiQuery()
.Add(getItems)
.Add(countItems)
.List();
var items = (IList)results[0];
var fromDb = (Item)items[0];
Assert.AreEqual(1, fromDb.Id);
var counts = (IList)results[1];
var count = (long)counts[0];
Assert.AreEqual(1L, count);
}
}
[Test]
public void CanAddIQueryWithKeyAndRetrieveResultsWithKey()
{
CreateItems();
using (var session = OpenSession())
{
var multiQuery = session.CreateMultiQuery();
var firstQuery = session.CreateSQLQuery("select * from ITEM where Id < :id").AddEntity(typeof(Item))
.SetInt32("id", 50);
var secondQuery = session.CreateQuery("from Item");
multiQuery.Add("first", firstQuery).Add("second", secondQuery);
var secondResult = (IList)multiQuery.GetResult("second");
var firstResult = (IList)multiQuery.GetResult("first");
Assert.Greater(secondResult.Count, firstResult.Count);
}
}
[Test]
public void CanNotAddQueryWithKeyThatAlreadyExists()
{
using (var session = OpenSession())
{
var multiQuery = session.CreateMultiQuery();
var firstQuery = session.CreateSQLQuery("select * from ITEM where Id < :id").AddEntity(typeof(Item))
.SetInt32("id", 50);
try
{
IQuery secondQuery = session.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item));
multiQuery.Add("first", firstQuery).Add("second", secondQuery);
}
catch (InvalidOperationException)
{
}
catch (Exception)
{
Assert.Fail("This should've thrown an InvalidOperationException");
}
}
}
[Test]
public void CanNotRetrieveQueryResultWithUnknownKey()
{
using (var session = OpenSession())
{
var multiQuery = session.CreateMultiQuery();
multiQuery.Add("firstQuery", session.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item)));
try
{
multiQuery.GetResult("unknownKey");
Assert.Fail("This should've thrown an InvalidOperationException");
}
catch (InvalidOperationException)
{
}
catch (Exception)
{
Assert.Fail("This should've thrown an InvalidOperationException");
}
}
}
[Test]
public void ExecutingQueryThroughMultiQueryTransformsResults()
{
CreateItems();
using (var session = OpenSession())
{
var transformer = new ResultTransformerStub();
var query = session.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item))
.SetResultTransformer(transformer);
session.CreateMultiQuery()
.Add(query)
.List();
Assert.IsTrue(transformer.WasTransformTupleCalled, "Transform Tuple was not called");
Assert.IsTrue(transformer.WasTransformListCalled, "Transform List was not called");
}
}
[Test]
public void ExecutingQueryThroughMultiQueryTransformsResults_When_setting_on_multi_query_directly()
{
CreateItems();
using (var session = OpenSession())
{
var transformer = new ResultTransformerStub();
IQuery query = session.CreateSQLQuery("select * from ITEM").AddEntity(typeof(Item));
session.CreateMultiQuery()
.Add(query)
.SetResultTransformer(transformer)
.List();
Assert.IsTrue(transformer.WasTransformTupleCalled, "Transform Tuple was not called");
Assert.IsTrue(transformer.WasTransformListCalled, "Transform List was not called");
}
}
[Test]
public void CanGetResultsInAGenericList()
{
using (var s = OpenSession())
{
var getItems = s.CreateQuery("from Item");
var countItems = s.CreateSQLQuery("select count(*) as count from ITEM").AddScalar("count", NHibernateUtil.Int64);
var results = s.CreateMultiQuery()
.Add(getItems)
.Add<long>(countItems)
.List();
Assert.That(results[0], Is.InstanceOf<List<object>>());
Assert.That(results[1], Is.InstanceOf<List<long>>());
}
}
}
}
| nkreipke/nhibernate-core | src/NHibernate.Test/QueryTest/MultipleMixedQueriesFixture.cs | C# | lgpl-2.1 | 11,919 |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import spack.cmd.location
import spack.modules
description = "cd to spack directories in the shell"
section = "environment"
level = "long"
def setup_parser(subparser):
"""This is for decoration -- spack cd is used through spack's
shell support. This allows spack cd to print a descriptive
help message when called with -h."""
spack.cmd.location.setup_parser(subparser)
def cd(parser, args):
spack.modules.print_help()
| TheTimmy/spack | lib/spack/spack/cmd/cd.py | Python | lgpl-2.1 | 1,684 |
/**
* Copyright (c) 2014, 2015, Oracle and/or its affiliates.
* All rights reserved.
*/
"use strict";
/*
Copyright 2013 jQuery Foundation and other contributors
Released under the MIT license.
http://jquery.org/license
Copyright 2013 jQuery Foundation and other contributors
Released under the MIT license.
http://jquery.org/license
*/
define(["ojs/ojcore","jquery","ojs/ojcomponentcore","ojs/ojpopupcore","jqueryui-amd/draggable"],function(a,f){(function(){a.Da("oj.ojDialog",f.oj.baseComponent,{version:"1.0.0",widgetEventPrefix:"oj",options:{cancelBehavior:"icon",dragAffordance:"title-bar",initialVisibility:"hide",modality:"modal",position:{my:"center",at:"center",of:window,collision:"fit",tja:function(a){var b=f(this).css(a).offset().top;0>b&&f(this).css("top",a.top-b)}},resizeBehavior:"resizable",role:"dialog",title:null,beforeClose:null,
beforeOpen:null,close:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},_ComponentCreate:function(){this._super();this.Wga={display:this.element[0].style.display,width:this.element[0].style.width,height:this.element[0].style.height};this.xn={parent:this.element.parent(),index:this.element.parent().children().index(this.element)};this.OK=this.element.attr("title");this.options.title=this.options.title||this.OK;this.j6();this.element.show().removeAttr("title").addClass("oj-dialog-content oj-dialog-default-content").appendTo(this.Ga);
this.Ls=!1;if(this.element.find(".oj-dialog").length){var d=this;this.element.find(".oj-dialog-header").each(function(a,c){var e=f(c);if(!e.closest(".oj-dialog-body").length)return d.gl=e,d.Ls=!0,!1})}else this.gl=this.element.find(".oj-dialog-header"),this.gl.length&&(this.Ls=!0);this.Ls?(this.Y5(this.gl),this.gl.prependTo(this.Ga),"icon"===this.options.cancelBehavior&&(this.uy(this.gl),this.Rv=this.gl.find(".oj-dialog-title"),this.Rv.length&&this.Rv.insertAfter(this.Gn))):this.i6();this.ij=this.element.children(".oj-dialog-footer");
this.X5(this.ij);this.ij.length&&(this.ij.addClass("oj-helper-clearfix"),this.ij.appendTo(this.Ga));"title-bar"===this.options.dragAffordance&&f.fn.draggable&&this.Po();this.er=!1;this.FS=this.tV.bind(this);this.Ga.length&&(a.C.jh(this.Ga[0],this.FS,30),this.er=!0);this.Dm=!1},uM:function(){"show"===this.options.initialVisibility&&this.open()},_destroy:function(){this.bQ&&window.clearTimeout(this.bQ);this.isOpen()&&this.Dq();this.er&&(a.C.gj(this.Ga[0],this.FS),this.er=!1);var d=this.Ga.hasClass("oj-draggable");
this.Ga.draggable&&d&&this.Ga.draggable("destroy");this.$o&&(this.$o("destroy"),this.$o=null);this.ij.length&&(this.ij.removeClass("oj-helper-clearfix"),f("#"+this.tU).replaceWith(this.ij));this.Dy();this.Ls&&(d=this.Ga.find(".oj-dialog-header"))&&f("#"+this.uU).replaceWith(d);this.Z_&&(this.Z_.remove(),this.Z_=null);this.element.removeUniqueId().removeClass("oj-dialog-content oj-dialog-default-content").css(this.Wga);this.Ga&&this.Ga.stop(!0,!0);this.element.unwrap();this.OK&&this.element.attr("title",
this.OK);this.ik&&(this.ik.remove(),this.ik=null);delete this.Ni;delete this.Dm;this._super()},widget:function(){return this.Ga},disable:f.noop,enable:f.noop,close:function(d){if(this.isOpen()&&(!1!==this._trigger("beforeClose",d)||this.Mu)){this.Dm=!1;this.n7=null;this.opener.filter(":focusable").focus().length||f(this.document[0].activeElement).blur();var b={};b[a.T.bb.Cf]=this.Ga;a.T.le().close(b);this._trigger("close",d)}},isOpen:function(){return this.Dm},open:function(d){!1!==this._trigger("beforeOpen",
d)&&(this.isOpen()||(this.Dm=!0,this.opener=f(this.document[0].activeElement),this.Qi(),"resizable"===this.options.resizeBehavior&&this.WT(),d={},d[a.T.bb.Cf]=this.Ga,d[a.T.bb.Rs]=this.opener,d[a.T.bb.Vs]=this.options.position,d[a.T.bb.mi]=this.options.modality,d[a.T.bb.Kn]=this.$q(),d[a.T.bb.Pl]="oj-dialog-layer",a.T.le().open(d),this._trigger("open")),this.VQ())},refresh:function(){this._super();this.Qi();this.tV()},VQ:function(){var d=this.n7;d&&0<d.length&&a.C.nn(this.Ga[0],d[0])||(d||(d=this.element.find("[autofocus]")),
d.length||(d=this.element.find(":tabbable")),d.length||this.ij.length&&(d=this.ij.find(":tabbable")),d.length||this.pL&&(d=this.pL.filter(":tabbable")),d.length||(d=this.Ga),d.eq(0).focus(),this._trigger("focus"))},_keepFocus:function(a){a.preventDefault();a=this.document[0].activeElement;this.Ga[0]===a||f.contains(this.Ga[0],a)||this.VQ()},Md:function(a){return!isNaN(parseInt(a,10))},j6:function(){this.gH=!1;this.element.uniqueId();this.lF=this.element.attr("id");this.Qea="ojDialogWrapper-"+this.lF;
this.Ga=f("\x3cdiv\x3e");this.Ga.addClass("oj-dialog oj-component").hide().attr({tabIndex:-1,role:this.options.role,id:this.Qea});this.Ga.insertBefore(this.element);this._on(this.Ga,{keyup:function(){},keydown:function(a){if("none"!=this.options.cancelBehavior&&!a.isDefaultPrevented()&&a.keyCode&&a.keyCode===f.ui.keyCode.ESCAPE)a.preventDefault(),a.stopImmediatePropagation(),this.close(a);else if(a.keyCode===f.ui.keyCode.TAB&&"modeless"!==this.options.modality){var b=this.Ga.find(":tabbable"),c=b.filter(":first"),
e=b.filter(":last");a.shiftKey?a.shiftKey&&(a.target===c[0]||a.target===this.Ga[0]?(e.focus(),a.preventDefault()):(c=b.index(document.activeElement),1==c&&b[0]&&(b[0].focus(),a.preventDefault()))):a.target===e[0]||a.target===this.Ga[0]?(c.focus(),a.preventDefault()):(c=b.index(document.activeElement),0==c&&b[1]&&(b[1].focus(),a.preventDefault()))}}});this.element.find("[aria-describedby]").length||this.Ga.attr({"aria-describedby":this.element.uniqueId().attr("id")})},Dy:function(){this.Gn&&(this.Gn.remove(),
this.pL=this.Gn=null)},uy:function(a){this.Gn=f("\x3cdiv\x3e").addClass("oj-dialog-header-close-wrapper").attr("tabindex","1").attr("aria-label","close").attr("role","button").appendTo(a);this.pL=f("\x3cspan\x3e").addClass("oj-component-icon oj-clickable-icon oj-dialog-close-icon").attr("alt","close icon").prependTo(this.Gn);this._on(this.Gn,{click:function(a){a.preventDefault();a.stopImmediatePropagation();this.close(a)},mousedown:function(a){f(a.currentTarget).addClass("oj-active")},mouseup:function(a){f(a.currentTarget).removeClass("oj-active")},
mouseenter:function(a){f(a.currentTarget).addClass("oj-hover")},mouseleave:function(a){a=a.currentTarget;f(a).removeClass("oj-hover");f(a).removeClass("oj-active")},keyup:function(a){if(a.keyCode&&a.keyCode===f.ui.keyCode.SPACE||a.keyCode===f.ui.keyCode.ENTER)a.preventDefault(),a.stopImmediatePropagation(),this.close(a)}})},i6:function(){var a;this.ik=f("\x3cdiv\x3e").addClass("oj-dialog-header oj-helper-clearfix").prependTo(this.Ga);this._on(this.ik,{mousedown:function(a){f(a.target).closest(".oj-dialog-close-icon")||
this.Ga.focus()}});"icon"===this.options.cancelBehavior&&this.uy(this.ik);a=f("\x3cspan\x3e").uniqueId().addClass("oj-dialog-title").appendTo(this.ik);this.SW(a);this.Ga.attr({"aria-labelledby":a.attr("id")})},SW:function(a){this.options.title||a.html("\x26#160;");a.text(this.options.title)},Po:function(){function a(b){return{position:b.position,offset:b.offset}}var b=this,c=this.options;this.Ga.draggable({Jia:!1,cancel:".oj-dialog-content, .oj-dialog-header-close",handle:".oj-dialog-header",containment:"document",
start:function(c,g){f(this).addClass("oj-dialog-dragging");b.LO();b._trigger("dragStart",c,a(g))},drag:function(c,f){b._trigger("drag",c,a(f))},stop:function(e,g){c.position=[g.position.left-b.document.scrollLeft(),g.position.top-b.document.scrollTop()];f(this).removeClass("oj-dialog-dragging");b.$W();b._trigger("dragStop",e,a(g))}});this.Ga.addClass("oj-draggable")},WT:function(){function a(b){return{originalPosition:b.xn,originalSize:b.fj,position:b.position,size:b.size}}var b=this;this.Ga.css("position");
this.$o=this.Ga.ojResizable.bind(this.Ga);this.$o({cancel:".oj-dialog-content",containment:"document",handles:"n,e,s,w,se,sw,ne,nw",start:function(c,e){b.gH=!0;f(this).addClass("oj-dialog-resizing");b.LO();b._trigger("resizeStart",c,a(e))},resize:function(c,e){b._trigger("resize",c,a(e))},stop:function(c,e){b.gH=!1;f(this).removeClass("oj-dialog-resizing");b.$W();b._trigger("resizeStop",c,a(e))}})},IH:function(){var d="rtl"===this.hc(),d=a.jd.Kg(this.options.position,d);this.Ga.position(d);this.vU()},
vU:function(){a.T.le().oL(this.Ga,a.T.sc.Rl)},_setOption:function(d,b,c){var e;e=this.Ga;if("disabled"!==d)switch(this._super(d,b,c),d){case "dragAffordance":(d=e.hasClass("oj-draggable"))&&"none"===b&&(e.draggable("destroy"),this.Ga.removeClass("oj-draggable"));d||"title-bar"!==b||this.Po();break;case "position":this.IH();break;case "resizeBehavior":e=!1;this.$o&&(e=!0);e&&"resizable"!=b&&(this.$o("destroy"),this.$o=null);e||"resizable"!==b||this.WT();break;case "title":this.SW(this.ik.find(".oj-dialog-title"));
break;case "role":e.attr("role",b);break;case "modality":this.isOpen()&&(e={},e[a.T.bb.Cf]=this.Ga,e[a.T.bb.mi]=b,a.T.le().$v(e));break;case "cancelBehavior":"none"===b||"escape"===b?this.Dy():"icon"===b&&(this.Ls?(this.Dy(),this.uy(this.gl),this.Rv=this.gl.find(".oj-dialog-title"),this.Rv.length&&this.Rv.insertAfter(this.Gn)):(this.Dy(),this.uy(this.ik),this.F_=this.ik.find(".oj-dialog-title"),this.F_.length&&this.F_.insertAfter(this.Gn)))}},tV:function(){var a=!1;this.Ga.length&&this.Ga[0].style.height&&
(a=this.Ga[0].style.height.indexOf("%"));this.gH&&a&&(a=this.y7(),this.element.css({height:a}))},y7:function(){this.bQ=null;var a=(this.Ls?this.gl:this.ik).outerHeight(),b=0;this.ij.length&&(b=this.ij.outerHeight());return this.Ga.height()-a-b},Saa:function(){var a=f("\x3cdiv\x3e");this.RP=this.Ga.css("height");"auto"!=this.RP?(a.height(this.RP),this.Xt=a.height(),this.Md(this.Xt)&&(this.Xt=Math.ceil(this.Xt))):this.Xt="auto";a.remove()},Qi:function(){this.Saa();var a=this.Ga[0].style.height,b=this.Ga[0].style.width,
c=this.Ga[0].style.minHeight,e=this.Ga[0].style.maxHeight;this.element.css({width:"auto",minHeight:0,maxHeight:"none",height:0});var f;f=this.Ga.css({minHeight:0,maxHeight:"none",height:"auto"}).outerHeight();this.element.css({width:"",minHeight:"",maxHeight:"",height:""});this.Ga.css({width:b});this.Ga.css({height:a});this.Ga.css({minHeight:c});this.Ga.css({maxHeight:e});"auto"!=a&&""!=a&&this.element.height(Math.max(0,this.Xt+0-f))},LO:function(){this.eK=this.document.find("iframe").map(function(){var a=
f(this),b=a.offset();return f("\x3cdiv\x3e").css({width:a.outerWidth(),height:a.outerHeight()}).appendTo(a.parent()).offset(b)[0]})},$W:function(){this.eK&&(this.eK.remove(),delete this.eK)},X5:function(a){this.tU="ojDialogPlaceHolderFooter-"+this.lF;this.zba=f("\x3cdiv\x3e").hide().attr({id:this.tU});this.zba.insertBefore(a)},Y5:function(a){this.uU="ojDialogPlaceHolderHeader-"+this.lF;this.Aba=f("\x3cdiv\x3e").hide().attr({id:this.uU});this.Aba.insertBefore(a)},getNodeBySubId:function(a){if(null==
a)return this.element?this.element[0]:null;a=a.subId;switch(a){case "oj-dialog":case "oj-dialog-header":case "oj-dialog-body":case "oj-dialog-footer":case "oj-dialog-content":case "oj-dialog-header-close-wrapper":case "oj-dialog-close-icon":case "oj-resizable-n":case "oj-resizable-e":case "oj-resizable-s":case "oj-resizable-w":case "oj-resizable-se":case "oj-resizable-sw":case "oj-resizable-ne":case "oj-resizable-nw":return a="."+a,this.widget().find(a)[0]}return null},ep:function(){this.element.remove()},
$q:function(){if(!this.Ni){var d=this.Ni={};d[a.T.sc.Tp]=f.proxy(this.Dq,this);d[a.T.sc.Up]=f.proxy(this.ep,this);d[a.T.sc.Rl]=f.proxy(this.vU,this)}return this.Ni},Dq:function(){this.Mu=!0;this.close();delete this.Mu}})})();(function(){var d=!1;f(document).mouseup(function(){d=!1});a.Da("oj.ojResizable",f.oj.baseComponent,{version:"1.0.0",widgetEventPrefix:"oj",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,alsoResize:!1,
animate:!1,animateDuration:"slow",animateEasing:"swing",containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,resize:null,start:null,stop:null},eba:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(c){return a.dba(c)}).bind("click."+this.widgetName,function(c){if(!0===f.data(c.target,a.widgetName+".preventClickEvent"))return f.removeData(c.target,a.widgetName+".preventClickEvent"),c.stopImmediatePropagation(),!1})},cba:function(){this.element.unbind("."+this.widgetName);
this.Xz&&this.document.unbind("mousemove."+this.widgetName,this.Xz).unbind("mouseup."+this.widgetName,this.rH)},dba:function(a){if(!d){this.Jm&&this.Yz(a);this.Vz=a;var c=this,e=1===a.which,g="string"===typeof this.options.cancel&&a.target.nodeName?f(a.target).closest(this.options.cancel).length:!1;if(!e||g||!this.bba(a))return!0;(this.Iw=!this.options.delay)||setTimeout(function(){c.Iw=!0},this.options.delay);if(this.dU(a)&&this.Iw&&(this.Jm=!1!==this.qH(a),!this.Jm))return a.preventDefault(),!0;
!0===f.data(a.target,this.widgetName+".preventClickEvent")&&f.removeData(a.target,this.widgetName+".preventClickEvent");this.Xz=function(a){return c.fba(a)};this.rH=function(a){return c.Yz(a)};this.document.bind("mousemove."+this.widgetName,this.Xz).bind("mouseup."+this.widgetName,this.rH);a.preventDefault();return d=!0}},fba:function(a){if(f.ui.Wia&&(!document.documentMode||9>document.documentMode)&&!a.button||!a.which)return this.Yz(a);if(this.Jm)return this.Wz(a),a.preventDefault();this.dU(a)&&
this.Iw&&((this.Jm=!1!==this.qH(this.Vz,a))?this.Wz(a):this.Yz(a));return!this.Jm},Yz:function(a){this.document.unbind("mousemove."+this.widgetName,this.Xz).unbind("mouseup."+this.widgetName,this.rH);this.Jm&&(this.Jm=!1,a.target===this.Vz.target&&f.data(a.target,this.widgetName+".preventClickEvent",!0),this.bv(a));return d=!1},dU:function(a){return Math.max(Math.abs(this.Vz.pageX-a.pageX),Math.abs(this.Vz.pageY-a.pageY))>=this.options.distance},Cia:function(){return this.Iw},vH:function(a){return parseInt(a,
10)||0},Md:function(a){return!isNaN(parseInt(a,10))},JS:function(a,c){if("hidden"===f(a).css("overflow"))return!1;var d=c&&"left"===c?"scrollLeft":"scrollTop",g=!1;if(0<a[d])return!0;a[d]=1;g=0<a[d];a[d]=0;return g},_ComponentCreate:function(){this._super();var a,c,d,g,h,k=this;a=this.options;this.element.addClass("oj-resizable");f.extend(this,{PB:this.element,jA:[],Gj:null});this.handles=a.handles||(f(".oj-resizable-handle",this.element).length?{cja:".oj-resizable-n",Oia:".oj-resizable-e",lja:".oj-resizable-s",
Gc:".oj-resizable-w",nja:".oj-resizable-se",pja:".oj-resizable-sw",dja:".oj-resizable-ne",gja:".oj-resizable-nw"}:"e,s,se");if(this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),a=this.handles.split(","),this.handles={},c=0;c<a.length;c++)d=f.trim(a[c]),h="oj-resizable-"+d,g=f("\x3cdiv class\x3d'oj-resizable-handle "+h+"'\x3e\x3c/div\x3e"),this.handles[d]=".oj-resizable-"+d,this.element.append(g);this.Ica=function(){for(var a in this.handles)this.handles[a].constructor===
String&&(this.handles[a]=this.element.children(this.handles[a]).first().show())};this.Ica();this.l$=f(".oj-resizable-handle",this.element);this.l$.mouseover(function(){k.k_||(this.className&&(g=this.className.match(/oj-resizable-(se|sw|ne|nw|n|e|s|w)/i)),k.axis=g&&g[1]?g[1]:"se")});this.eba()},_destroy:function(){this.cba();f(this.PB).removeClass("oj-resizable oj-resizable-disabled oj-resizable-resizing").removeData("resizable").removeData("oj-resizable").unbind(".resizable").find(".oj-resizable-handle").remove();
return this},bba:function(a){var c,d,g=!1;for(c in this.handles)if(d=f(this.handles[c])[0],d===a.target||f.contains(d,a.target))g=!0;return!this.options.disabled&&g},qH:function(a){var c,d,g;g=this.options;c=this.element.position();var h=this.element;this.k_=!0;/absolute/.test(h.css("position"))?h.css({position:"absolute",top:h.css("top"),left:h.css("left")}):h.is(".oj-draggable")&&h.css({position:"absolute",top:c.top,left:c.left});this.Jca();c=this.vH(this.helper.css("left"));d=this.vH(this.helper.css("top"));
g.containment&&(c+=f(g.containment).scrollLeft()||0,d+=f(g.containment).scrollTop()||0);this.offset=this.helper.offset();this.position={left:c,top:d};this.size={width:h.width(),height:h.height()};this.fj={width:h.width(),height:h.height()};this.xn={left:c,top:d};this.YB={width:h.outerWidth()-h.width(),height:h.outerHeight()-h.height()};this.Xga={left:a.pageX,top:a.pageY};this.Sj=this.fj.width/this.fj.height||1;g=f(".oj-resizable-"+this.axis).css("cursor");f("body").css("cursor","auto"===g?this.axis+
"-resize":g);h.addClass("oj-resizable-resizing");this.MH("start",a);this.g4(a);this.u5(a);return!0},Wz:function(a){var c,d=this.helper,g={},h=this.Xga;c=a.pageX-h.left||0;var h=a.pageY-h.top||0,k=this.rg[this.axis];this.Fs={top:this.position.top,left:this.position.left};this.Gs={width:this.size.width,height:this.size.height};if(!k)return!1;c=k.apply(this,[a,c,h]);this.Hea(a.shiftKey);a.shiftKey&&(c=this.Gea(c,a));c=this.Uca(c,a);this.Aea(c);this.MH("resize",a);this.f4(a,this.ui());this.t5(a,this.ui());
this.position.top!==this.Fs.top&&(g.top=this.position.top+"px");this.position.left!==this.Fs.left&&(g.left=this.position.left+"px");this.size.width!==this.Gs.width&&(g.width=this.size.width+"px");this.size.height!==this.Gs.height&&(g.height=this.size.height+"px");d.css(g);!this.Gj&&this.jA.length&&this.Vba();f.isEmptyObject(g)||this._trigger("resize",a,this.ui());return!1},bv:function(a){this.k_=!1;f("body").css("cursor","auto");this.element.removeClass("oj-resizable-resizing");this.MH("stop",a);
this.h4(a);this.v5(a);return!1},Hea:function(a){var c,d,f,h;h=this.options;h={minWidth:this.Md(h.minWidth)?h.minWidth:0,maxWidth:this.Md(h.maxWidth)?h.maxWidth:Infinity,minHeight:this.Md(h.minHeight)?h.minHeight:0,maxHeight:this.Md(h.maxHeight)?h.maxHeight:Infinity};a&&(a=h.minHeight*this.Sj,d=h.minWidth/this.Sj,c=h.maxHeight*this.Sj,f=h.maxWidth/this.Sj,a>h.minWidth&&(h.minWidth=a),d>h.minHeight&&(h.minHeight=d),c<h.maxWidth&&(h.maxWidth=c),f<h.maxHeight&&(h.maxHeight=f));this.Kea=h},Aea:function(a){this.offset=
this.helper.offset();this.Md(a.left)&&(this.position.left=a.left);this.Md(a.top)&&(this.position.top=a.top);this.Md(a.height)&&(this.size.height=a.height);this.Md(a.width)&&(this.size.width=a.width)},Gea:function(a){var c=this.position,d=this.size,f=this.axis;this.Md(a.height)?a.width=a.height*this.Sj:this.Md(a.width)&&(a.height=a.width/this.Sj);"sw"===f&&(a.left=c.left+(d.width-a.width),a.top=null);"nw"===f&&(a.top=c.top+(d.height-a.height),a.left=c.left+(d.width-a.width));return a},Uca:function(a){var c=
this.Kea,d=this.axis,f=this.Md(a.width)&&c.maxWidth&&c.maxWidth<a.width,h=this.Md(a.height)&&c.maxHeight&&c.maxHeight<a.height,k=this.Md(a.width)&&c.minWidth&&c.minWidth>a.width,l=this.Md(a.height)&&c.minHeight&&c.minHeight>a.height,m=this.xn.left+this.fj.width,n=this.position.top+this.size.height,q=/sw|nw|w/.test(d),d=/nw|ne|n/.test(d);k&&(a.width=c.minWidth);l&&(a.height=c.minHeight);f&&(a.width=c.maxWidth);h&&(a.height=c.maxHeight);k&&q&&(a.left=m-c.minWidth);f&&q&&(a.left=m-c.maxWidth);l&&d&&
(a.top=n-c.minHeight);h&&d&&(a.top=n-c.maxHeight);a.width||a.height||a.left||!a.top?a.width||a.height||a.top||!a.left||(a.left=null):a.top=null;return a},Vba:function(){if(this.jA.length){var a,c,d,f,h,k=this.helper||this.element;for(a=0;a<this.jA.length;a++){h=this.jA[a];if(!this.as)for(this.as=[],d=[h.css("borderTopWidth"),h.css("borderRightWidth"),h.css("borderBottomWidth"),h.css("borderLeftWidth")],f=[h.css("paddingTop"),h.css("paddingRight"),h.css("paddingBottom"),h.css("paddingLeft")],c=0;c<
d.length;c++)this.as[c]=(parseInt(d[c],10)||0)+(parseInt(f[c],10)||0);h.css({height:k.height()-this.as[0]-this.as[2]||0,width:k.width()-this.as[1]-this.as[3]||0})}}},Jca:function(){this.element.offset();this.helper=this.element},rg:{e:function(a,c){return{width:this.fj.width+c}},w:function(a,c){return{left:this.xn.left+c,width:this.fj.width-c}},n:function(a,c,d){return{top:this.xn.top+d,height:this.fj.height-d}},s:function(a,c,d){return{height:this.fj.height+d}},se:function(a,c,d){return f.extend(this.rg.s.apply(this,
arguments),this.rg.e.apply(this,[a,c,d]))},sw:function(a,c,d){return f.extend(this.rg.s.apply(this,arguments),this.rg.w.apply(this,[a,c,d]))},ne:function(a,c,d){return f.extend(this.rg.n.apply(this,arguments),this.rg.e.apply(this,[a,c,d]))},nw:function(a,c,d){return f.extend(this.rg.n.apply(this,arguments),this.rg.w.apply(this,[a,c,d]))}},MH:function(a,c){"resize"!==a&&this._trigger(a,c,this.ui())},g4:function(){function a(b){f(b).each(function(){var a=f(this);a.data("oj-resizable-alsoresize",{width:parseInt(a.width(),
10),height:parseInt(a.height(),10),left:parseInt(a.css("left"),10),top:parseInt(a.css("top"),10)})})}var c=this.options;"object"!==typeof c.alsoResize||c.alsoResize.parentNode?a(c.alsoResize):c.alsoResize.length?(c.alsoResize=c.alsoResize[0],a(c.alsoResize)):f.each(c.alsoResize,function(c){a(c)})},f4:function(a,c){function d(a,b){f(a).each(function(){var a=f(this),d=f(this).data("oj-resizable-alsoresize"),e={};f.each(b&&b.length?b:a.parents(c.PB[0]).length?["width","height"]:["width","height","top",
"left"],function(a,b){var c=(d[b]||0)+(l[b]||0);c&&0<=c&&(e[b]=c||null)});a.css(e)})}var g=this.options,h=this.fj,k=this.xn,l={height:this.size.height-h.height||0,width:this.size.width-h.width||0,top:this.position.top-k.top||0,left:this.position.left-k.left||0};"object"!==typeof g.alsoResize||g.alsoResize.nodeType?d(g.alsoResize,null):f.each(g.alsoResize,function(a,b){d(a,b)})},h4:function(){f(this).removeData("oj-resizable-alsoresize")},u5:function(){var a,c,d,g,h,k=this,l=k.element;d=k.options.containment;
if(l=d instanceof f?d.get(0):/parent/.test(d)?l.parent().get(0):d)k.iB=f(l),/document/.test(d)||d===document?(k.jB={left:0,top:0},k.HX={left:0,top:0},k.yn={element:f(document),left:0,top:0,width:f(document).width(),height:f(document).height()||document.body.parentNode.scrollHeight}):(a=f(l),c=[],f(["Top","Right","Left","Bottom"]).each(function(d,e){c[d]=k.vH(a.css("padding"+e))}),k.jB=a.offset(),k.HX=a.position(),k.IX={height:a.innerHeight()-c[3],width:a.innerWidth()-c[1]},d=k.jB,g=k.IX.height,h=
k.IX.width,h=k.JS(l,"left")?l.scrollWidth:h,g=k.JS(l)?l.scrollHeight:g,k.yn={element:l,left:d.left,top:d.top,width:h,height:g})},t5:function(a,c){var d,f,h,k;d=this.options;f=this.jB;k=this.position;var l=a.shiftKey;h={top:0,left:0};var m=this.iB,n=!0;m[0]!==document&&/static/.test(m.css("position"))&&(h=f);k.left<(this.Gj?f.left:0)&&(this.size.width+=this.Gj?this.position.left-f.left:this.position.left-h.left,l&&(this.size.height=this.size.width/this.Sj,n=!1),this.position.left=d.helper?f.left:0);
k.top<(this.Gj?f.top:0)&&(this.size.height+=this.Gj?this.position.top-f.top:this.position.top,l&&(this.size.width=this.size.height*this.Sj,n=!1),this.position.top=this.Gj?f.top:0);this.offset.left=this.yn.left+this.position.left;this.offset.top=this.yn.top+this.position.top;d=Math.abs((this.Gj?this.offset.left-h.left:this.offset.left-f.left)+this.YB.width);f=Math.abs((this.Gj?this.offset.top-h.top:this.offset.top-f.top)+this.YB.height);h=this.iB.get(0)===this.element.parent().get(0);k=/relative|absolute/.test(this.iB.css("position"));
h&&k&&(d-=Math.abs(this.yn.left));d+this.size.width>=this.yn.width&&(this.size.width=this.yn.width-d,l&&(this.size.height=this.size.width/this.Sj,n=!1));f+this.size.height>=this.yn.height&&(this.size.height=this.yn.height-f,l&&(this.size.width=this.size.height*this.Sj,n=!1));n||(this.position.left=c.Fs.left,this.position.top=c.Fs.top,this.size.width=c.Gs.width,this.size.height=c.Gs.height)},v5:function(){var a=this.options,c=this.jB,d=this.HX,g=this.iB,h=f(this.helper),k=h.offset(),l=h.outerWidth()-
this.YB.width,h=h.outerHeight()-this.YB.height;this.Gj&&!a.animate&&/relative/.test(g.css("position"))&&f(this).css({left:k.left-d.left-c.left,width:l,height:h});this.Gj&&!a.animate&&/static/.test(g.css("position"))&&f(this).css({left:k.left-d.left-c.left,width:l,height:h})},ui:function(){return{PB:this.PB,element:this.element,helper:this.helper,position:this.position,size:this.size,fj:this.fj,xn:this.xn,Gs:this.Gs,Fs:this.Fs}}})})()}); | afsinka/jet_jsp | src/main/webapp/js/libs/oj/v1.1.2/min/ojdialog.js | JavaScript | lgpl-2.1 | 24,005 |
/* $XConsortium: xrmLib.h /main/5 1995/07/15 20:46:59 drk $ */
/*
* Motif
*
* Copyright (c) 1987-2012, The Open Group. All rights reserved.
*
* These libraries and programs are free software; you can
* redistribute them and/or modify them under the terms of the GNU
* Lesser General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* These libraries and programs are distributed in the hope that
* they 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 these librararies and programs; if not, write
* to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301 USA
*/
/*
* HISTORY
*/
#ifndef xrmLib_h
#define xrmLib_h
/* Function Name: InitializeXrm
*
* Description: Open the Xrm database
*
* Arguments: file_name - name of xrm database file
*
*
*/
extern Boolean InitializeXrm(
char *
);
/* Function Name: GetWorkspaceResources
*
* Description: Gets the workspace resources for a window
*
* Arguments: widget - any widget
* specifier - A list of quarks that specifies the
* window (SM_CLIENT_ID, WM_ROLE).
* room_list - returns a quark list of room names that
* the window is in.
* all_workspaces - returns allWorkspaces resource
* linked - returns linked resource
*
*/
extern Boolean GetWorkspaceResources(
Widget w,
XrmQuarkList specifier,
XrmQuarkList *room_qlist,
Boolean *all_workspaces,
Boolean *linked
);
extern Boolean GetSpaceListResources(
Widget w,
char ***,
char ***,
char ***,
char**,
Boolean*
);
/* Function Name: GetWindowConfigurationEntry
*
* Description: Gets the configuration information for a specified
* window.
*
* Arguments: specifier - A list of quarks that specifies the
* window (SM_CLIENT_ID, WM_ROLE).
* attribute_list - A quark list of attribute names
* to search for in database.
* room_name - Room name that the window is in.
* if it is linked then the linkedRoom
* quark should be passed.
* attributes_values - Returns array of values
* found in the database. The array
* length is equal to attribute_list length.
* (If no value is found for an attribute then
* a value with 0 length and NULL addr is passed)
*
* Returns: True if any resources found, else False.
*
*
*/
extern Boolean GetWindowConfigurationEntry(
XrmQuarkList specifier,
XrmQuarkList attribute_list,
XrmQuark room_name,
XrmValue **attribute_values
);
/* Function Name: GetWindowStackedEntry
*
* Description: Gets the stacked resource for a specified
* window.
*
* Arguments: specifier - A list of quarks that specifies the
* window (SM_CLIENT_ID, WM_ROLE).
* room_name - Room name that the window is in.
* if it is linked then the linkedRoom
* quark should be passed.
* attributes_value - Returns a stacked value
*
* Returns: True if resources found, else False.
*
*
*/
extern Boolean GetWindowStackedEntry(
XrmQuarkList specifier,
XrmQuark room_name,
XrmValue *attribute_value
);
/*
* Function Name: GetAllWindowConfigurationEntry
*
* Description: Gets the configuration information for a specified
* window.
*
* Arguments: specifier - A list of quarks that specifies the
* window (SM_CLIENT_ID, WM_ROLE).
* attribute_list - A quark list of attribute names
* to search for in database.
* room_list - list of room names that the window is in.
* if it is linked then the linkedRoom
* quark should be passed.
* attributes_values - Returns double array of values
* found in the database. The array
* width is equal to the number of rooms. The array
* length is equal to attribute_list length.
* (If no value is found for an attribute then
* a value with 0 length and NULL addr is passed)
*
* Returns: True if any resources found, else False.
*
*
*
*/
extern Boolean GetAllWindowConfigurationEntry(
XrmQuarkList specifier,
XrmQuarkList attribute_list,
XrmQuarkList room_list,
XrmValue ***attribute_values
);
/*
*
* Function Name: SaveWorkspaceResources
*
* Description: Save the workspaces resources in the xrm database
* window.
*
* Arguments: widget - any widget
* specifier - A list of quarks that specifies the
* window (SM_CLIENT_ID, WM_ROLE).
* room_nameq - Room name quark to be added to database.
* all_workspaces - allWorkspaces resource
* linked - linked resource
*
*/
extern Boolean SaveWorkspaceResources(
Widget,
XrmQuarkList,
XrmQuark,
XrmQuark,
Boolean,
Boolean
);
extern Boolean SaveSpaceListResources(
char *,
char *,
char *,
char *
);
/*
*
* Function Name: SaveWindowConfiguration
*
* Description: Save the window configuration in the xrm database
*
* Arguments: specifier - A list of quarks that specifies the
* window (SM_CLIENT_ID, WM_ROLE).
* attribute_qlist - A quark list of attribute names to
* be saved in database.
* room_nameq - Room name quark that the configuration is in.
* if it is linked then the linkedRoom
* quark should be passed.
* attr_values - list of attribute values (matches attrib_qlist)
*
*/
extern Boolean SaveWindowConfiguration(
XrmQuarkList,
XrmQuarkList,
XrmQuark,
XrmValue *
);
/*
*
* Function Name: PurgeWindowConfiguration
*
* Description: Remove the window configuration from the xrm database
*
* Arguments: specifier - A list of quarks that specifies the
* window (SM_CLIENT_ID, WM_ROLE).
* attribute_qlist - A quark list of attribute names to
* be removed in database.
* room_nameq - the room that the configuration
*
*/
extern Boolean
PurgeWindowConfiguration(
Widget w,
XrmQuarkList specifier_list,
XrmQuarkList attribute_qlist,
XrmQuark room_nameq
);
/*
*
* Function Name: PurgeAllWindowConfiguration
*
* Description: Remove the window configuration from the xrm database
*
* Arguments: specifier - A list of quarks that specifies the
* window (SM_CLIENT_ID, WM_ROLE).
* attribute_qlist - A quark list of attribute names to
* be removed in database.
* room_nameq - the room that the configuration
*
*/
extern Boolean
PurgeAllWindowConfiguration(
Widget w,
XrmQuarkList specifier_list,
XrmQuarkList attribute_qlist
);
/*
*
* Function Name: SaveWsmToFile
*
* Description: Saves the Xrm database to a specified file
*
* Arguments: file_name - file name
*
*/
extern void
SaveWsmToFile(
char *file_name
);
#endif
| fjardon/motif | demos/programs/workspace/xrmLib.h | C | lgpl-2.1 | 8,336 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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 Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlprofilertraceview.h"
#include "qmlprofilertool.h"
#include "qmlprofilerstatemanager.h"
#include "qmlprofilerdatamodel.h"
// Needed for the load&save actions in the context menu
#include <analyzerbase/ianalyzertool.h>
// Comunication with the other views (limit events to range)
#include "qmlprofilerviewmanager.h"
#include <utils/styledbar.h>
#include <QDeclarativeContext>
#include <QToolButton>
#include <QEvent>
#include <QVBoxLayout>
#include <QGraphicsObject>
#include <QScrollBar>
#include <QSlider>
#include <QMenu>
#include <math.h>
using namespace QmlDebug;
namespace QmlProfiler {
namespace Internal {
const int sliderTicks = 10000;
const qreal sliderExp = 3;
/////////////////////////////////////////////////////////
bool MouseWheelResizer::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::Wheel) {
QWheelEvent *ev = static_cast<QWheelEvent *>(event);
if (ev->modifiers() & Qt::ControlModifier) {
emit mouseWheelMoved(ev->pos().x(), ev->pos().y(), ev->delta());
return true;
}
}
return QObject::eventFilter(obj, event);
}
/////////////////////////////////////////////////////////
void ZoomControl::setRange(qint64 startTime, qint64 endTime)
{
if (m_startTime != startTime || m_endTime != endTime) {
m_startTime = startTime;
m_endTime = endTime;
emit rangeChanged();
}
}
/////////////////////////////////////////////////////////
ScrollableDeclarativeView::ScrollableDeclarativeView(QWidget *parent)
: QDeclarativeView(parent)
{
}
ScrollableDeclarativeView::~ScrollableDeclarativeView()
{
}
void ScrollableDeclarativeView::scrollContentsBy(int dx, int dy)
{
// special workaround to track the scrollbar
if (rootObject()) {
int scrollY = rootObject()->property("scrollY").toInt();
rootObject()->setProperty("scrollY", QVariant(scrollY - dy));
}
QDeclarativeView::scrollContentsBy(dx,dy);
}
/////////////////////////////////////////////////////////
class QmlProfilerTraceView::QmlProfilerTraceViewPrivate
{
public:
QmlProfilerTraceViewPrivate(QmlProfilerTraceView *qq) : q(qq) {}
QmlProfilerTraceView *q;
QmlProfilerStateManager *m_profilerState;
Analyzer::IAnalyzerTool *m_profilerTool;
QmlProfilerViewManager *m_viewContainer;
QSize m_sizeHint;
ScrollableDeclarativeView *m_mainView;
QDeclarativeView *m_timebar;
QDeclarativeView *m_overview;
QmlProfilerDataModel *m_profilerDataModel;
ZoomControl *m_zoomControl;
QToolButton *m_buttonRange;
QToolButton *m_buttonLock;
QWidget *m_zoomToolbar;
int m_currentZoomLevel;
};
QmlProfilerTraceView::QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerTool *profilerTool, QmlProfilerViewManager *container, QmlProfilerDataModel *model, QmlProfilerStateManager *profilerState)
: QWidget(parent), d(new QmlProfilerTraceViewPrivate(this))
{
setObjectName(QLatin1String("QML Profiler"));
d->m_zoomControl = new ZoomControl(this);
connect(d->m_zoomControl, SIGNAL(rangeChanged()), this, SLOT(updateRange()));
QVBoxLayout *groupLayout = new QVBoxLayout;
groupLayout->setContentsMargins(0, 0, 0, 0);
groupLayout->setSpacing(0);
d->m_mainView = new ScrollableDeclarativeView(this);
d->m_mainView->setResizeMode(QDeclarativeView::SizeViewToRootObject);
d->m_mainView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
d->m_mainView->setBackgroundBrush(QBrush(Qt::white));
d->m_mainView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
d->m_mainView->setFocus();
MouseWheelResizer *resizer = new MouseWheelResizer(this);
connect(resizer,SIGNAL(mouseWheelMoved(int,int,int)), this, SLOT(mouseWheelMoved(int,int,int)));
d->m_mainView->viewport()->installEventFilter(resizer);
QHBoxLayout *toolsLayout = new QHBoxLayout;
d->m_timebar = new QDeclarativeView(this);
d->m_timebar->setResizeMode(QDeclarativeView::SizeRootObjectToView);
d->m_timebar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
d->m_timebar->setFixedHeight(24);
d->m_overview = new QDeclarativeView(this);
d->m_overview->setResizeMode(QDeclarativeView::SizeRootObjectToView);
d->m_overview->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
d->m_overview->setMaximumHeight(50);
d->m_zoomToolbar = createZoomToolbar();
d->m_zoomToolbar->move(0, d->m_timebar->height());
d->m_zoomToolbar->setVisible(false);
toolsLayout->addWidget(createToolbar());
toolsLayout->addWidget(d->m_timebar);
emit enableToolbar(false);
groupLayout->addLayout(toolsLayout);
groupLayout->addWidget(d->m_mainView);
groupLayout->addWidget(d->m_overview);
setLayout(groupLayout);
d->m_profilerTool = profilerTool;
d->m_viewContainer = container;
d->m_profilerDataModel = model;
connect(d->m_profilerDataModel, SIGNAL(stateChanged()),
this, SLOT(profilerDataModelStateChanged()));
d->m_mainView->rootContext()->setContextProperty(QLatin1String("qmlProfilerDataModel"),
d->m_profilerDataModel);
d->m_overview->rootContext()->setContextProperty(QLatin1String("qmlProfilerDataModel"),
d->m_profilerDataModel);
d->m_profilerState = profilerState;
connect(d->m_profilerState, SIGNAL(stateChanged()),
this, SLOT(profilerStateChanged()));
connect(d->m_profilerState, SIGNAL(clientRecordingChanged()),
this, SLOT(clientRecordingChanged()));
connect(d->m_profilerState, SIGNAL(serverRecordingChanged()),
this, SLOT(serverRecordingChanged()));
// Minimum height: 5 rows of 20 pixels + scrollbar of 50 pixels + 20 pixels margin
setMinimumHeight(170);
d->m_currentZoomLevel = 0;
}
QmlProfilerTraceView::~QmlProfilerTraceView()
{
delete d;
}
/////////////////////////////////////////////////////////
// Initialize widgets
void QmlProfilerTraceView::reset()
{
d->m_mainView->rootContext()->setContextProperty(QLatin1String("zoomControl"), d->m_zoomControl);
d->m_timebar->rootContext()->setContextProperty(QLatin1String("zoomControl"), d->m_zoomControl);
d->m_overview->rootContext()->setContextProperty(QLatin1String("zoomControl"), d->m_zoomControl);
d->m_timebar->setSource(QUrl(QLatin1String("qrc:/qmlprofiler/TimeDisplay.qml")));
d->m_overview->setSource(QUrl(QLatin1String("qrc:/qmlprofiler/Overview.qml")));
d->m_mainView->setSource(QUrl(QLatin1String("qrc:/qmlprofiler/MainView.qml")));
QGraphicsObject *rootObject = d->m_mainView->rootObject();
rootObject->setProperty("width", QVariant(width()));
rootObject->setProperty("candidateHeight", QVariant(height() - d->m_timebar->height() - d->m_overview->height()));
connect(rootObject, SIGNAL(updateCursorPosition()), this, SLOT(updateCursorPosition()));
connect(rootObject, SIGNAL(updateRangeButton()), this, SLOT(updateRangeButton()));
connect(rootObject, SIGNAL(updateLockButton()), this, SLOT(updateLockButton()));
connect(this, SIGNAL(jumpToPrev()), rootObject, SLOT(prevEvent()));
connect(this, SIGNAL(jumpToNext()), rootObject, SLOT(nextEvent()));
connect(rootObject, SIGNAL(selectedEventChanged(int)), this, SIGNAL(selectedEventChanged(int)));
connect(rootObject, SIGNAL(changeToolTip(QString)), this, SLOT(updateToolTip(QString)));
connect(rootObject, SIGNAL(updateVerticalScroll(int)), this, SLOT(updateVerticalScroll(int)));
}
QWidget *QmlProfilerTraceView::createToolbar()
{
Utils::StyledBar *bar = new Utils::StyledBar(this);
bar->setStyleSheet(QLatin1String("background: #9B9B9B"));
bar->setSingleRow(true);
bar->setFixedWidth(150);
bar->setFixedHeight(24);
QHBoxLayout *toolBarLayout = new QHBoxLayout(bar);
toolBarLayout->setMargin(0);
toolBarLayout->setSpacing(0);
QToolButton *buttonPrev= new QToolButton;
buttonPrev->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_prev.png")));
buttonPrev->setToolTip(tr("Jump to previous event"));
connect(buttonPrev, SIGNAL(clicked()), this, SIGNAL(jumpToPrev()));
connect(this, SIGNAL(enableToolbar(bool)), buttonPrev, SLOT(setEnabled(bool)));
QToolButton *buttonNext= new QToolButton;
buttonNext->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_next.png")));
buttonNext->setToolTip(tr("Jump to next event"));
connect(buttonNext, SIGNAL(clicked()), this, SIGNAL(jumpToNext()));
connect(this, SIGNAL(enableToolbar(bool)), buttonNext, SLOT(setEnabled(bool)));
QToolButton *buttonZoomControls = new QToolButton;
buttonZoomControls->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_zoom.png")));
buttonZoomControls->setToolTip(tr("Show zoom slider"));
buttonZoomControls->setCheckable(true);
buttonZoomControls->setChecked(false);
connect(buttonZoomControls, SIGNAL(toggled(bool)), d->m_zoomToolbar, SLOT(setVisible(bool)));
connect(this, SIGNAL(enableToolbar(bool)), buttonZoomControls, SLOT(setEnabled(bool)));
d->m_buttonRange = new QToolButton;
d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselection.png")));
d->m_buttonRange->setToolTip(tr("Select range"));
d->m_buttonRange->setCheckable(true);
d->m_buttonRange->setChecked(false);
connect(d->m_buttonRange, SIGNAL(clicked(bool)), this, SLOT(toggleRangeMode(bool)));
connect(this, SIGNAL(enableToolbar(bool)), d->m_buttonRange, SLOT(setEnabled(bool)));
connect(this, SIGNAL(rangeModeChanged(bool)), d->m_buttonRange, SLOT(setChecked(bool)));
d->m_buttonLock = new QToolButton;
d->m_buttonLock->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_selectionmode.png")));
d->m_buttonLock->setToolTip(tr("View event information on mouseover"));
d->m_buttonLock->setCheckable(true);
d->m_buttonLock->setChecked(false);
connect(d->m_buttonLock, SIGNAL(clicked(bool)), this, SLOT(toggleLockMode(bool)));
connect(this, SIGNAL(enableToolbar(bool)), d->m_buttonLock, SLOT(setEnabled(bool)));
connect(this, SIGNAL(lockModeChanged(bool)), d->m_buttonLock, SLOT(setChecked(bool)));
toolBarLayout->addWidget(buttonPrev);
toolBarLayout->addWidget(buttonNext);
toolBarLayout->addWidget(new Utils::StyledSeparator());
toolBarLayout->addWidget(buttonZoomControls);
toolBarLayout->addWidget(new Utils::StyledSeparator());
toolBarLayout->addWidget(d->m_buttonRange);
toolBarLayout->addWidget(d->m_buttonLock);
return bar;
}
QWidget *QmlProfilerTraceView::createZoomToolbar()
{
Utils::StyledBar *bar = new Utils::StyledBar(this);
bar->setStyleSheet(QLatin1String("background: #9B9B9B"));
bar->setSingleRow(true);
bar->setFixedWidth(150);
bar->setFixedHeight(24);
QHBoxLayout *toolBarLayout = new QHBoxLayout(bar);
toolBarLayout->setMargin(0);
toolBarLayout->setSpacing(0);
QSlider *zoomSlider = new QSlider(Qt::Horizontal);
zoomSlider->setFocusPolicy(Qt::NoFocus);
zoomSlider->setRange(1, sliderTicks);
zoomSlider->setInvertedAppearance(true);
zoomSlider->setPageStep(sliderTicks/100);
connect(this, SIGNAL(enableToolbar(bool)), zoomSlider, SLOT(setEnabled(bool)));
connect(zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setZoomLevel(int)));
connect(this, SIGNAL(zoomLevelChanged(int)), zoomSlider, SLOT(setValue(int)));
zoomSlider->setStyleSheet(QLatin1String("\
QSlider:horizontal {\
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #444444, stop: 1 #5a5a5a);\
border: 1px #313131;\
height: 20px;\
margin: 0px 0px 0px 0px;\
}\
QSlider::add-page:horizontal {\
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #5a5a5a, stop: 1 #444444);\
border: 1px #313131;\
}\
QSlider::sub-page:horizontal {\
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #5a5a5a, stop: 1 #444444);\
border: 1px #313131;\
}\
"));
toolBarLayout->addWidget(zoomSlider);
return bar;
}
/////////////////////////////////////////////////////////
bool QmlProfilerTraceView::hasValidSelection() const
{
QGraphicsObject *rootObject = d->m_mainView->rootObject();
if (rootObject)
return rootObject->property("selectionRangeReady").toBool();
return false;
}
qint64 QmlProfilerTraceView::selectionStart() const
{
QGraphicsObject *rootObject = d->m_mainView->rootObject();
if (rootObject)
return rootObject->property("selectionRangeStart").toLongLong();
return 0;
}
qint64 QmlProfilerTraceView::selectionEnd() const
{
QGraphicsObject *rootObject = d->m_mainView->rootObject();
if (rootObject)
return rootObject->property("selectionRangeEnd").toLongLong();
return 0;
}
void QmlProfilerTraceView::clearDisplay()
{
d->m_zoomControl->setRange(0,0);
updateVerticalScroll(0);
d->m_mainView->rootObject()->setProperty("scrollY", QVariant(0));
QMetaObject::invokeMethod(d->m_mainView->rootObject(), "clearAll");
QMetaObject::invokeMethod(d->m_overview->rootObject(), "clearDisplay");
}
void QmlProfilerTraceView::selectNextEventWithId(int eventId)
{
QGraphicsObject *rootObject = d->m_mainView->rootObject();
if (rootObject)
QMetaObject::invokeMethod(rootObject, "selectNextWithId",
Q_ARG(QVariant,QVariant(eventId)));
}
/////////////////////////////////////////////////////////
// Goto source location
void QmlProfilerTraceView::updateCursorPosition()
{
QGraphicsObject *rootObject = d->m_mainView->rootObject();
emit gotoSourceLocation(rootObject->property("fileName").toString(),
rootObject->property("lineNumber").toInt(),
rootObject->property("columnNumber").toInt());
}
/////////////////////////////////////////////////////////
// Toolbar buttons
void QmlProfilerTraceView::toggleRangeMode(bool active)
{
QGraphicsObject *rootObject = d->m_mainView->rootObject();
bool rangeMode = rootObject->property("selectionRangeMode").toBool();
if (active != rangeMode) {
if (active)
d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselected.png")));
else
d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselection.png")));
rootObject->setProperty("selectionRangeMode", QVariant(active));
}
}
void QmlProfilerTraceView::updateRangeButton()
{
bool rangeMode = d->m_mainView->rootObject()->property("selectionRangeMode").toBool();
if (rangeMode)
d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselected.png")));
else
d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselection.png")));
emit rangeModeChanged(rangeMode);
}
void QmlProfilerTraceView::toggleLockMode(bool active)
{
QGraphicsObject *rootObject = d->m_mainView->rootObject();
bool lockMode = !rootObject->property("selectionLocked").toBool();
if (active != lockMode) {
rootObject->setProperty("selectionLocked", QVariant(!active));
rootObject->setProperty("selectedItem", QVariant(-1));
}
}
void QmlProfilerTraceView::updateLockButton()
{
bool lockMode = !d->m_mainView->rootObject()->property("selectionLocked").toBool();
emit lockModeChanged(lockMode);
}
////////////////////////////////////////////////////////
// Zoom control
void QmlProfilerTraceView::setZoomLevel(int zoomLevel)
{
if (d->m_currentZoomLevel != zoomLevel && d->m_mainView->rootObject()) {
QVariant newFactor = pow(qreal(zoomLevel) / qreal(sliderTicks), sliderExp);
d->m_currentZoomLevel = zoomLevel;
QMetaObject::invokeMethod(d->m_mainView->rootObject(), "updateWindowLength", Q_ARG(QVariant, newFactor));
}
}
void QmlProfilerTraceView::updateRange()
{
if (!d->m_profilerDataModel)
return;
qreal duration = d->m_zoomControl->endTime() - d->m_zoomControl->startTime();
if (duration <= 0)
return;
if (d->m_profilerDataModel->traceDuration() <= 0)
return;
int newLevel = pow(duration / d->m_profilerDataModel->traceDuration(), 1/sliderExp) * sliderTicks;
if (d->m_currentZoomLevel != newLevel) {
d->m_currentZoomLevel = newLevel;
emit zoomLevelChanged(newLevel);
}
}
void QmlProfilerTraceView::mouseWheelMoved(int mouseX, int mouseY, int wheelDelta)
{
Q_UNUSED(mouseY);
QGraphicsObject *rootObject = d->m_mainView->rootObject();
if (rootObject) {
QMetaObject::invokeMethod(rootObject, "wheelZoom",
Q_ARG(QVariant, QVariant(mouseX)),
Q_ARG(QVariant, QVariant(wheelDelta)));
}
}
////////////////////////////////////////////////////////
void QmlProfilerTraceView::updateToolTip(const QString &text)
{
setToolTip(text);
}
void QmlProfilerTraceView::updateVerticalScroll(int newPosition)
{
d->m_mainView->verticalScrollBar()->setValue(newPosition);
}
void QmlProfilerTraceView::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
QGraphicsObject *rootObject = d->m_mainView->rootObject();
if (rootObject) {
rootObject->setProperty("width", QVariant(event->size().width()));
int newHeight = event->size().height() - d->m_timebar->height() - d->m_overview->height();
rootObject->setProperty("candidateHeight", QVariant(newHeight));
}
emit resized();
}
////////////////////////////////////////////////////////////////
// Context menu
void QmlProfilerTraceView::contextMenuEvent(QContextMenuEvent *ev)
{
QMenu menu;
QAction *viewAllAction = 0;
QmlProfilerTool *profilerTool = qobject_cast<QmlProfilerTool *>(d->m_profilerTool);
if (profilerTool)
menu.addActions(profilerTool->profilerContextMenuActions());
menu.addSeparator();
QAction *getLocalStatsAction = menu.addAction(tr("Limit Events Pane to Current Range"));
if (!d->m_viewContainer->hasValidSelection())
getLocalStatsAction->setEnabled(false);
QAction *getGlobalStatsAction = menu.addAction(tr("Reset Events Pane"));
if (d->m_viewContainer->hasGlobalStats())
getGlobalStatsAction->setEnabled(false);
if (d->m_profilerDataModel->count() > 0) {
menu.addSeparator();
viewAllAction = menu.addAction(tr("Reset Zoom"));
}
QAction *selectedAction = menu.exec(ev->globalPos());
if (selectedAction) {
if (selectedAction == viewAllAction) {
d->m_zoomControl->setRange(
d->m_profilerDataModel->traceStartTime(),
d->m_profilerDataModel->traceEndTime());
}
if (selectedAction == getLocalStatsAction) {
d->m_viewContainer->getStatisticsInRange(
d->m_viewContainer->selectionStart(),
d->m_viewContainer->selectionEnd());
}
if (selectedAction == getGlobalStatsAction) {
d->m_viewContainer->getStatisticsInRange(
d->m_profilerDataModel->traceStartTime(),
d->m_profilerDataModel->traceEndTime());
}
}
}
/////////////////////////////////////////////////
// Tell QML the state of the profiler
void QmlProfilerTraceView::setRecording(bool recording)
{
QGraphicsObject *rootObject = d->m_mainView->rootObject();
if (rootObject)
rootObject->setProperty("recordingEnabled", QVariant(recording));
}
void QmlProfilerTraceView::setAppKilled()
{
QGraphicsObject *rootObject = d->m_mainView->rootObject();
if (rootObject)
rootObject->setProperty("appKilled",QVariant(true));
}
////////////////////////////////////////////////////////////////
// Profiler State
void QmlProfilerTraceView::profilerDataModelStateChanged()
{
switch (d->m_profilerDataModel->currentState()) {
case QmlProfilerDataModel::Empty :
emit enableToolbar(false);
break;
case QmlProfilerDataModel::AcquiringData :
// nothing to be done
break;
case QmlProfilerDataModel::ProcessingData :
// nothing to be done
break;
case QmlProfilerDataModel::Done :
emit enableToolbar(true);
break;
default:
break;
}
}
void QmlProfilerTraceView::profilerStateChanged()
{
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppKilled : {
if (d->m_profilerDataModel->currentState() == QmlProfilerDataModel::AcquiringData)
setAppKilled();
break;
}
default:
// no special action needed for other states
break;
}
}
void QmlProfilerTraceView::clientRecordingChanged()
{
// nothing yet
}
void QmlProfilerTraceView::serverRecordingChanged()
{
setRecording(d->m_profilerState->serverRecording());
}
} // namespace Internal
} // namespace QmlProfiler
| duythanhphan/qt-creator | src/plugins/qmlprofiler/qmlprofilertraceview.cpp | C++ | lgpl-2.1 | 22,504 |
// @(#)root/tmva $Id$
// Author: Peter Speckmayer
/**********************************************************************************
* Project: TMVA - a Root-integrated toolkit for multivariate data analysis *
* Package: TMVA *
* Class : MethodDNN *
* Web : http://tmva.sourceforge.net *
* *
* Description: *
* NeuralNetwork *
* *
* Authors (alphabetical): *
* Peter Speckmayer <peter.speckmayer@gmx.at> - CERN, Switzerland *
* Simon Pfreundschuh <s.pfreundschuh@gmail.com> - CERN, Switzerland *
* *
* Copyright (c) 2005-2015: *
* CERN, Switzerland *
* U. of Victoria, Canada *
* MPI-K Heidelberg, Germany *
* U. of Bonn, Germany *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted according to the terms listed in LICENSE *
* (http://tmva.sourceforge.net/LICENSE) *
**********************************************************************************/
//#pragma once
#ifndef ROOT_TMVA_MethodDNN
#define ROOT_TMVA_MethodDNN
//////////////////////////////////////////////////////////////////////////
// //
// MethodDNN //
// //
// Neural Network implementation //
// //
//////////////////////////////////////////////////////////////////////////
#include <vector>
#include <map>
#include <string>
#include <sstream>
#include "TString.h"
#include "TTree.h"
#include "TRandom3.h"
#include "TH1F.h"
#include "TMVA/MethodBase.h"
#include "TMVA/NeuralNet.h"
#include "TMVA/Tools.h"
#include "TMVA/DNN/Net.h"
#include "TMVA/DNN/Minimizers.h"
#include "TMVA/DNN/Architectures/Reference.h"
#ifdef R__HAS_TMVACPU
#define DNNCPU
#endif
#ifdef R__HAS_TMVAGPU
#define DNNCUDA
#endif
#ifdef DNNCPU
#include "TMVA/DNN/Architectures/Cpu.h"
#endif
#ifdef DNNCUDA
#include "TMVA/DNN/Architectures/Cuda.h"
#endif
namespace TMVA {
class MethodDNN : public MethodBase
{
friend struct TestMethodDNNValidationSize;
using Architecture_t = DNN::TReference<Float_t>;
using Net_t = DNN::TNet<Architecture_t>;
using Matrix_t = typename Architecture_t::Matrix_t;
using Scalar_t = typename Architecture_t::Scalar_t;
private:
using LayoutVector_t = std::vector<std::pair<int, DNN::EActivationFunction>>;
using KeyValueVector_t = std::vector<std::map<TString, TString>>;
struct TTrainingSettings
{
size_t batchSize;
size_t testInterval;
size_t convergenceSteps;
DNN::ERegularization regularization;
Double_t learningRate;
Double_t momentum;
Double_t weightDecay;
std::vector<Double_t> dropoutProbabilities;
bool multithreading;
};
// the option handling methods
void DeclareOptions();
void ProcessOptions();
UInt_t GetNumValidationSamples();
// general helper functions
void Init();
Net_t fNet;
DNN::EInitialization fWeightInitialization;
DNN::EOutputFunction fOutputFunction;
TString fLayoutString;
TString fErrorStrategy;
TString fTrainingStrategyString;
TString fWeightInitializationString;
TString fArchitectureString;
TString fValidationSize;
LayoutVector_t fLayout;
std::vector<TTrainingSettings> fTrainingSettings;
bool fResume;
KeyValueVector_t fSettings;
ClassDef(MethodDNN,0); // neural network
static inline void WriteMatrixXML(void *parent, const char *name,
const TMatrixT<Double_t> &X);
static inline void ReadMatrixXML(void *xml, const char *name,
TMatrixT<Double_t> &X);
protected:
void MakeClassSpecific( std::ostream&, const TString& ) const;
void GetHelpMessage() const;
public:
// Standard Constructors
MethodDNN(const TString& jobName,
const TString& methodTitle,
DataSetInfo& theData,
const TString& theOption);
MethodDNN(DataSetInfo& theData,
const TString& theWeightFile);
virtual ~MethodDNN();
virtual Bool_t HasAnalysisType(Types::EAnalysisType type,
UInt_t numberClasses,
UInt_t numberTargets );
LayoutVector_t ParseLayoutString(TString layerSpec);
KeyValueVector_t ParseKeyValueString(TString parseString,
TString blockDelim,
TString tokenDelim);
void Train();
void TrainGpu();
void TrainCpu();
virtual Double_t GetMvaValue( Double_t* err=0, Double_t* errUpper=0 );
virtual const std::vector<Float_t>& GetRegressionValues();
virtual const std::vector<Float_t>& GetMulticlassValues();
using MethodBase::ReadWeightsFromStream;
// write weights to stream
void AddWeightsXMLTo ( void* parent ) const;
// read weights from stream
void ReadWeightsFromStream( std::istream & i );
void ReadWeightsFromXML ( void* wghtnode );
// ranking of input variables
const Ranking* CreateRanking();
};
inline void MethodDNN::WriteMatrixXML(void *parent,
const char *name,
const TMatrixT<Double_t> &X)
{
std::stringstream matrixStringStream("");
matrixStringStream.precision( 16 );
for (size_t i = 0; i < (size_t) X.GetNrows(); i++)
{
for (size_t j = 0; j < (size_t) X.GetNcols(); j++)
{
matrixStringStream << std::scientific << X(i,j) << " ";
}
}
std::string s = matrixStringStream.str();
void* matxml = gTools().xmlengine().NewChild(parent, 0, name);
gTools().xmlengine().NewAttr(matxml, 0, "rows",
gTools().StringFromInt((int)X.GetNrows()));
gTools().xmlengine().NewAttr(matxml, 0, "cols",
gTools().StringFromInt((int)X.GetNcols()));
gTools().xmlengine().AddRawLine (matxml, s.c_str());
}
inline void MethodDNN::ReadMatrixXML(void *xml,
const char *name,
TMatrixT<Double_t> &X)
{
void *matrixXML = gTools().GetChild(xml, name);
size_t rows, cols;
gTools().ReadAttr(matrixXML, "rows", rows);
gTools().ReadAttr(matrixXML, "cols", cols);
const char * matrixString = gTools().xmlengine().GetNodeContent(matrixXML);
std::stringstream matrixStringStream(matrixString);
for (size_t i = 0; i < rows; i++)
{
for (size_t j = 0; j < cols; j++)
{
matrixStringStream >> X(i,j);
}
}
}
} // namespace TMVA
#endif
| karies/root | tmva/tmva/inc/TMVA/MethodDNN.h | C | lgpl-2.1 | 8,107 |
/* GIO - GLib Input, Output and Streaming Library
*
* Copyright (C) 2006-2007 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 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.
*
* Author: Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include "gappinfo.h"
#include "glibintl.h"
#include <gioerror.h>
#include <gfile.h>
/**
* SECTION:gappinfo
* @short_description: Application information and launch contexts
* @include: gio/gio.h
*
* #GAppInfo and #GAppLaunchContext are used for describing and launching
* applications installed on the system.
*
* As of GLib 2.20, URIs will always be converted to POSIX paths
* (using g_file_get_path()) when using g_app_info_launch() even if
* the application requested an URI and not a POSIX path. For example
* for an desktop-file based application with Exec key <literal>totem
* %U</literal> and a single URI,
* <literal>sftp://foo/file.avi</literal>, then
* <literal>/home/user/.gvfs/sftp on foo/file.avi</literal> will be
* passed. This will only work if a set of suitable GIO extensions
* (such as gvfs 2.26 compiled with FUSE support), is available and
* operational; if this is not the case, the URI will be passed
* unmodified to the application. Some URIs, such as
* <literal>mailto:</literal>, of course cannot be mapped to a POSIX
* path (in gvfs there's no FUSE mount for it); such URIs will be
* passed unmodified to the application.
*
* Specifically for gvfs 2.26 and later, the POSIX URI will be mapped
* back to the GIO URI in the #GFile constructors (since gvfs
* implements the #GVfs extension point). As such, if the application
* needs to examine the URI, it needs to use g_file_get_uri() or
* similar on #GFile. In other words, an application cannot assume
* that the URI passed to e.g. g_file_new_for_commandline_arg() is
* equal to the result of g_file_get_uri(). The following snippet
* illustrates this:
*
* <programlisting>
* GFile *f;
* char *uri;
*
* file = g_file_new_for_commandline_arg (uri_from_commandline);
*
* uri = g_file_get_uri (file);
* strcmp (uri, uri_from_commandline) == 0; // FALSE
* g_free (uri);
*
* if (g_file_has_uri_scheme (file, "cdda"))
* {
* // do something special with uri
* }
* g_object_unref (file);
* </programlisting>
*
* This code will work when both <literal>cdda://sr0/Track
* 1.wav</literal> and <literal>/home/user/.gvfs/cdda on sr0/Track
* 1.wav</literal> is passed to the application. It should be noted
* that it's generally not safe for applications to rely on the format
* of a particular URIs. Different launcher applications (e.g. file
* managers) may have different ideas of what a given URI means.
*
**/
typedef GAppInfoIface GAppInfoInterface;
G_DEFINE_INTERFACE (GAppInfo, g_app_info, G_TYPE_OBJECT)
static void
g_app_info_default_init (GAppInfoInterface *iface)
{
}
/**
* g_app_info_dup:
* @appinfo: a #GAppInfo.
*
* Creates a duplicate of a #GAppInfo.
*
* Returns: (transfer full): a duplicate of @appinfo.
**/
GAppInfo *
g_app_info_dup (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), NULL);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->dup) (appinfo);
}
/**
* g_app_info_equal:
* @appinfo1: the first #GAppInfo.
* @appinfo2: the second #GAppInfo.
*
* Checks if two #GAppInfo<!-- -->s are equal.
*
* Returns: %TRUE if @appinfo1 is equal to @appinfo2. %FALSE otherwise.
**/
gboolean
g_app_info_equal (GAppInfo *appinfo1,
GAppInfo *appinfo2)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo1), FALSE);
g_return_val_if_fail (G_IS_APP_INFO (appinfo2), FALSE);
if (G_TYPE_FROM_INSTANCE (appinfo1) != G_TYPE_FROM_INSTANCE (appinfo2))
return FALSE;
iface = G_APP_INFO_GET_IFACE (appinfo1);
return (* iface->equal) (appinfo1, appinfo2);
}
/**
* g_app_info_get_id:
* @appinfo: a #GAppInfo.
*
* Gets the ID of an application. An id is a string that
* identifies the application. The exact format of the id is
* platform dependent. For instance, on Unix this is the
* desktop file id from the xdg menu specification.
*
* Note that the returned ID may be %NULL, depending on how
* the @appinfo has been constructed.
*
* Returns: a string containing the application's ID.
**/
const char *
g_app_info_get_id (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), NULL);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->get_id) (appinfo);
}
/**
* g_app_info_get_name:
* @appinfo: a #GAppInfo.
*
* Gets the installed name of the application.
*
* Returns: the name of the application for @appinfo.
**/
const char *
g_app_info_get_name (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), NULL);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->get_name) (appinfo);
}
/**
* g_app_info_get_display_name:
* @appinfo: a #GAppInfo.
*
* Gets the display name of the application. The display name is often more
* descriptive to the user than the name itself.
*
* Returns: the display name of the application for @appinfo, or the name if
* no display name is available.
*
* Since: 2.24
**/
const char *
g_app_info_get_display_name (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), NULL);
iface = G_APP_INFO_GET_IFACE (appinfo);
if (iface->get_display_name == NULL)
return (* iface->get_name) (appinfo);
return (* iface->get_display_name) (appinfo);
}
/**
* g_app_info_get_description:
* @appinfo: a #GAppInfo.
*
* Gets a human-readable description of an installed application.
*
* Returns: a string containing a description of the
* application @appinfo, or %NULL if none.
**/
const char *
g_app_info_get_description (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), NULL);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->get_description) (appinfo);
}
/**
* g_app_info_get_executable:
* @appinfo: a #GAppInfo
*
* Gets the executable's name for the installed application.
*
* Returns: a string containing the @appinfo's application
* binaries name
**/
const char *
g_app_info_get_executable (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), NULL);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->get_executable) (appinfo);
}
/**
* g_app_info_get_commandline:
* @appinfo: a #GAppInfo
*
* Gets the commandline with which the application will be
* started.
*
* Returns: a string containing the @appinfo's commandline,
* or %NULL if this information is not available
*
* Since: 2.20
**/
const char *
g_app_info_get_commandline (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), NULL);
iface = G_APP_INFO_GET_IFACE (appinfo);
if (iface->get_commandline)
return (* iface->get_commandline) (appinfo);
return NULL;
}
/**
* g_app_info_set_as_default_for_type:
* @appinfo: a #GAppInfo.
* @content_type: the content type.
* @error: a #GError.
*
* Sets the application as the default handler for a given type.
*
* Returns: %TRUE on success, %FALSE on error.
**/
gboolean
g_app_info_set_as_default_for_type (GAppInfo *appinfo,
const char *content_type,
GError **error)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
g_return_val_if_fail (content_type != NULL, FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->set_as_default_for_type) (appinfo, content_type, error);
}
/**
* g_app_info_set_as_last_used_for_type:
* @appinfo: a #GAppInfo.
* @content_type: the content type.
* @error: a #GError.
*
* Sets the application as the last used application for a given type.
* This will make the application appear as first in the list returned
* by g_app_info_get_recommended_for_type(), regardless of the default
* application for that content type.
*
* Returns: %TRUE on success, %FALSE on error.
**/
gboolean
g_app_info_set_as_last_used_for_type (GAppInfo *appinfo,
const char *content_type,
GError **error)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
g_return_val_if_fail (content_type != NULL, FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->set_as_last_used_for_type) (appinfo, content_type, error);
}
/**
* g_app_info_set_as_default_for_extension:
* @appinfo: a #GAppInfo.
* @extension: a string containing the file extension (without the dot).
* @error: a #GError.
*
* Sets the application as the default handler for the given file extension.
*
* Returns: %TRUE on success, %FALSE on error.
**/
gboolean
g_app_info_set_as_default_for_extension (GAppInfo *appinfo,
const char *extension,
GError **error)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
g_return_val_if_fail (extension != NULL, FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
if (iface->set_as_default_for_extension)
return (* iface->set_as_default_for_extension) (appinfo, extension, error);
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
"g_app_info_set_as_default_for_extension not supported yet");
return FALSE;
}
/**
* g_app_info_add_supports_type:
* @appinfo: a #GAppInfo.
* @content_type: a string.
* @error: a #GError.
*
* Adds a content type to the application information to indicate the
* application is capable of opening files with the given content type.
*
* Returns: %TRUE on success, %FALSE on error.
**/
gboolean
g_app_info_add_supports_type (GAppInfo *appinfo,
const char *content_type,
GError **error)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
g_return_val_if_fail (content_type != NULL, FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
if (iface->add_supports_type)
return (* iface->add_supports_type) (appinfo, content_type, error);
g_set_error_literal (error, G_IO_ERROR,
G_IO_ERROR_NOT_SUPPORTED,
"g_app_info_add_supports_type not supported yet");
return FALSE;
}
/**
* g_app_info_can_remove_supports_type:
* @appinfo: a #GAppInfo.
*
* Checks if a supported content type can be removed from an application.
*
* Returns: %TRUE if it is possible to remove supported
* content types from a given @appinfo, %FALSE if not.
**/
gboolean
g_app_info_can_remove_supports_type (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
if (iface->can_remove_supports_type)
return (* iface->can_remove_supports_type) (appinfo);
return FALSE;
}
/**
* g_app_info_remove_supports_type:
* @appinfo: a #GAppInfo.
* @content_type: a string.
* @error: a #GError.
*
* Removes a supported type from an application, if possible.
*
* Returns: %TRUE on success, %FALSE on error.
**/
gboolean
g_app_info_remove_supports_type (GAppInfo *appinfo,
const char *content_type,
GError **error)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
g_return_val_if_fail (content_type != NULL, FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
if (iface->remove_supports_type)
return (* iface->remove_supports_type) (appinfo, content_type, error);
g_set_error_literal (error, G_IO_ERROR,
G_IO_ERROR_NOT_SUPPORTED,
"g_app_info_remove_supports_type not supported yet");
return FALSE;
}
/**
* g_app_info_get_supported_types:
* @appinfo: a #GAppInfo that can handle files
*
* Retrieves the list of content types that @app_info claims to support.
* If this information is not provided by the environment, this function
* will return %NULL.
* This function does not take in consideration associations added with
* g_app_info_add_supports_type(), but only those exported directly by
* the application.
*
* Returns: (transfer none) (array zero-terminated=1) (element-type utf8):
* a list of content types.
*
* Since: 2.34
*/
const char **
g_app_info_get_supported_types (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), NULL);
iface = G_APP_INFO_GET_IFACE (appinfo);
if (iface->get_supported_types)
return iface->get_supported_types (appinfo);
else
return NULL;
}
/**
* g_app_info_get_icon:
* @appinfo: a #GAppInfo.
*
* Gets the icon for the application.
*
* Returns: (transfer none): the default #GIcon for @appinfo or %NULL
* if there is no default icon.
**/
GIcon *
g_app_info_get_icon (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), NULL);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->get_icon) (appinfo);
}
/**
* g_app_info_launch:
* @appinfo: a #GAppInfo
* @files: (allow-none) (element-type GFile): a #GList of #GFile objects
* @launch_context: (allow-none): a #GAppLaunchContext or %NULL
* @error: a #GError
*
* Launches the application. Passes @files to the launched application
* as arguments, using the optional @launch_context to get information
* about the details of the launcher (like what screen it is on).
* On error, @error will be set accordingly.
*
* To launch the application without arguments pass a %NULL @files list.
*
* Note that even if the launch is successful the application launched
* can fail to start if it runs into problems during startup. There is
* no way to detect this.
*
* Some URIs can be changed when passed through a GFile (for instance
* unsupported URIs with strange formats like mailto:), so if you have
* a textual URI you want to pass in as argument, consider using
* g_app_info_launch_uris() instead.
*
* The launched application inherits the environment of the launching
* process, but it can be modified with g_app_launch_context_setenv() and
* g_app_launch_context_unsetenv().
*
* On UNIX, this function sets the <envar>GIO_LAUNCHED_DESKTOP_FILE</envar>
* environment variable with the path of the launched desktop file and
* <envar>GIO_LAUNCHED_DESKTOP_FILE_PID</envar> to the process
* id of the launched process. This can be used to ignore
* <envar>GIO_LAUNCHED_DESKTOP_FILE</envar>, should it be inherited
* by further processes. The <envar>DISPLAY</envar> and
* <envar>DESKTOP_STARTUP_ID</envar> environment variables are also
* set, based on information provided in @launch_context.
*
* Returns: %TRUE on successful launch, %FALSE otherwise.
**/
gboolean
g_app_info_launch (GAppInfo *appinfo,
GList *files,
GAppLaunchContext *launch_context,
GError **error)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->launch) (appinfo, files, launch_context, error);
}
/**
* g_app_info_supports_uris:
* @appinfo: a #GAppInfo.
*
* Checks if the application supports reading files and directories from URIs.
*
* Returns: %TRUE if the @appinfo supports URIs.
**/
gboolean
g_app_info_supports_uris (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->supports_uris) (appinfo);
}
/**
* g_app_info_supports_files:
* @appinfo: a #GAppInfo.
*
* Checks if the application accepts files as arguments.
*
* Returns: %TRUE if the @appinfo supports files.
**/
gboolean
g_app_info_supports_files (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->supports_files) (appinfo);
}
/**
* g_app_info_launch_uris:
* @appinfo: a #GAppInfo
* @uris: (allow-none) (element-type utf8): a #GList containing URIs to launch.
* @launch_context: (allow-none): a #GAppLaunchContext or %NULL
* @error: a #GError
*
* Launches the application. This passes the @uris to the launched application
* as arguments, using the optional @launch_context to get information
* about the details of the launcher (like what screen it is on).
* On error, @error will be set accordingly.
*
* To launch the application without arguments pass a %NULL @uris list.
*
* Note that even if the launch is successful the application launched
* can fail to start if it runs into problems during startup. There is
* no way to detect this.
*
* Returns: %TRUE on successful launch, %FALSE otherwise.
**/
gboolean
g_app_info_launch_uris (GAppInfo *appinfo,
GList *uris,
GAppLaunchContext *launch_context,
GError **error)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->launch_uris) (appinfo, uris, launch_context, error);
}
/**
* g_app_info_should_show:
* @appinfo: a #GAppInfo.
*
* Checks if the application info should be shown in menus that
* list available applications.
*
* Returns: %TRUE if the @appinfo should be shown, %FALSE otherwise.
**/
gboolean
g_app_info_should_show (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
return (* iface->should_show) (appinfo);
}
/**
* g_app_info_launch_default_for_uri:
* @uri: the uri to show
* @launch_context: (allow-none): an optional #GAppLaunchContext.
* @error: a #GError.
*
* Utility function that launches the default application
* registered to handle the specified uri. Synchronous I/O
* is done on the uri to detect the type of the file if
* required.
*
* Returns: %TRUE on success, %FALSE on error.
**/
gboolean
g_app_info_launch_default_for_uri (const char *uri,
GAppLaunchContext *launch_context,
GError **error)
{
char *uri_scheme;
GAppInfo *app_info = NULL;
GList l;
gboolean res;
/* g_file_query_default_handler() calls
* g_app_info_get_default_for_uri_scheme() too, but we have to do it
* here anyway in case GFile can't parse @uri correctly.
*/
uri_scheme = g_uri_parse_scheme (uri);
if (uri_scheme && uri_scheme[0] != '\0')
app_info = g_app_info_get_default_for_uri_scheme (uri_scheme);
g_free (uri_scheme);
if (!app_info)
{
GFile *file;
file = g_file_new_for_uri (uri);
app_info = g_file_query_default_handler (file, NULL, error);
g_object_unref (file);
if (app_info == NULL)
return FALSE;
/* We still use the original @uri rather than calling
* g_file_get_uri(), because GFile might have modified the URI
* in ways we don't want (eg, removing the fragment identifier
* from a file: URI).
*/
}
l.data = (char *)uri;
l.next = l.prev = NULL;
res = g_app_info_launch_uris (app_info, &l,
launch_context, error);
g_object_unref (app_info);
return res;
}
/**
* g_app_info_can_delete:
* @appinfo: a #GAppInfo
*
* Obtains the information whether the #GAppInfo can be deleted.
* See g_app_info_delete().
*
* Returns: %TRUE if @appinfo can be deleted
*
* Since: 2.20
*/
gboolean
g_app_info_can_delete (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
if (iface->can_delete)
return (* iface->can_delete) (appinfo);
return FALSE;
}
/**
* g_app_info_delete:
* @appinfo: a #GAppInfo
*
* Tries to delete a #GAppInfo.
*
* On some platforms, there may be a difference between user-defined
* #GAppInfo<!-- -->s which can be deleted, and system-wide ones which
* cannot. See g_app_info_can_delete().
*
* Virtual: do_delete
* Returns: %TRUE if @appinfo has been deleted
*
* Since: 2.20
*/
gboolean
g_app_info_delete (GAppInfo *appinfo)
{
GAppInfoIface *iface;
g_return_val_if_fail (G_IS_APP_INFO (appinfo), FALSE);
iface = G_APP_INFO_GET_IFACE (appinfo);
if (iface->do_delete)
return (* iface->do_delete) (appinfo);
return FALSE;
}
enum {
LAUNCH_FAILED,
LAUNCHED,
LAST_SIGNAL
};
guint signals[LAST_SIGNAL] = { 0 };
G_DEFINE_TYPE (GAppLaunchContext, g_app_launch_context, G_TYPE_OBJECT);
struct _GAppLaunchContextPrivate {
char **envp;
};
/**
* g_app_launch_context_new:
*
* Creates a new application launch context. This is not normally used,
* instead you instantiate a subclass of this, such as #GdkAppLaunchContext.
*
* Returns: a #GAppLaunchContext.
**/
GAppLaunchContext *
g_app_launch_context_new (void)
{
return g_object_new (G_TYPE_APP_LAUNCH_CONTEXT, NULL);
}
static void
g_app_launch_context_finalize (GObject *object)
{
GAppLaunchContext *context = G_APP_LAUNCH_CONTEXT (object);
g_strfreev (context->priv->envp);
G_OBJECT_CLASS (g_app_launch_context_parent_class)->finalize (object);
}
static void
g_app_launch_context_class_init (GAppLaunchContextClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (klass, sizeof (GAppLaunchContextPrivate));
object_class->finalize = g_app_launch_context_finalize;
/*
* GAppLaunchContext::launch-failed:
* @context: the object emitting the signal
* @startup_notify_id: the startup notification id for the failed launch
*
* The ::launch-failed signal is emitted when a #GAppInfo launch
* fails. The startup notification id is provided, so that the launcher
* can cancel the startup notification.
*
* Since: 2.36
*/
signals[LAUNCH_FAILED] = g_signal_new ("launch-failed",
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GAppLaunchContextClass, launch_failed),
NULL, NULL, NULL,
G_TYPE_NONE, 1, G_TYPE_STRING);
/*
* GAppLaunchContext::launched:
* @context: the object emitting the signal
* @info: the #GAppInfo that was just launched
* @platform_data: additional platform-specific data for this launch
*
* The ::launched signal is emitted when a #GAppInfo is successfully
* launched. The @platform_data is an GVariant dictionary mapping
* strings to variants (ie a{sv}), which contains additional,
* platform-specific data about this launch. On UNIX, at least the
* "pid" and "startup-notification-id" keys will be present.
*
* Since: 2.36
*/
signals[LAUNCHED] = g_signal_new ("launched",
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GAppLaunchContextClass, launched),
NULL, NULL, NULL,
G_TYPE_NONE, 2,
G_TYPE_APP_INFO, G_TYPE_VARIANT);
}
static void
g_app_launch_context_init (GAppLaunchContext *context)
{
context->priv = G_TYPE_INSTANCE_GET_PRIVATE (context, G_TYPE_APP_LAUNCH_CONTEXT, GAppLaunchContextPrivate);
}
/**
* g_app_launch_context_setenv:
* @context: a #GAppLaunchContext
* @variable: the environment variable to set
* @value: the value for to set the variable to.
*
* Arranges for @variable to be set to @value in the child's
* environment when @context is used to launch an application.
*
* Since: 2.32
*/
void
g_app_launch_context_setenv (GAppLaunchContext *context,
const char *variable,
const char *value)
{
if (!context->priv->envp)
context->priv->envp = g_get_environ ();
context->priv->envp =
g_environ_setenv (context->priv->envp, variable, value, TRUE);
}
/**
* g_app_launch_context_unsetenv:
* @context: a #GAppLaunchContext
* @variable: the environment variable to remove
*
* Arranges for @variable to be unset in the child's environment
* when @context is used to launch an application.
*
* Since: 2.32
*/
void
g_app_launch_context_unsetenv (GAppLaunchContext *context,
const char *variable)
{
if (!context->priv->envp)
context->priv->envp = g_get_environ ();
context->priv->envp =
g_environ_unsetenv (context->priv->envp, variable);
}
/**
* g_app_launch_context_get_environment:
* @context: a #GAppLaunchContext
*
* Gets the complete environment variable list to be passed to
* the child process when @context is used to launch an application.
* This is a %NULL-terminated array of strings, where each string has
* the form <literal>KEY=VALUE</literal>.
*
* Return value: (array zero-terminated=1) (transfer full): the
* child's environment
*
* Since: 2.32
*/
char **
g_app_launch_context_get_environment (GAppLaunchContext *context)
{
if (!context->priv->envp)
context->priv->envp = g_get_environ ();
return g_strdupv (context->priv->envp);
}
/**
* g_app_launch_context_get_display:
* @context: a #GAppLaunchContext
* @info: a #GAppInfo
* @files: (element-type GFile): a #GList of #GFile objects
*
* Gets the display string for the @context. This is used to ensure new
* applications are started on the same display as the launching
* application, by setting the <envar>DISPLAY</envar> environment variable.
*
* Returns: a display string for the display.
*/
char *
g_app_launch_context_get_display (GAppLaunchContext *context,
GAppInfo *info,
GList *files)
{
GAppLaunchContextClass *class;
g_return_val_if_fail (G_IS_APP_LAUNCH_CONTEXT (context), NULL);
g_return_val_if_fail (G_IS_APP_INFO (info), NULL);
class = G_APP_LAUNCH_CONTEXT_GET_CLASS (context);
if (class->get_display == NULL)
return NULL;
return class->get_display (context, info, files);
}
/**
* g_app_launch_context_get_startup_notify_id:
* @context: a #GAppLaunchContext
* @info: a #GAppInfo
* @files: (element-type GFile): a #GList of of #GFile objects
*
* Initiates startup notification for the application and returns the
* <envar>DESKTOP_STARTUP_ID</envar> for the launched operation,
* if supported.
*
* Startup notification IDs are defined in the <ulink
* url="http://standards.freedesktop.org/startup-notification-spec/startup-notification-latest.txt">
* FreeDesktop.Org Startup Notifications standard</ulink>.
*
* Returns: a startup notification ID for the application, or %NULL if
* not supported.
**/
char *
g_app_launch_context_get_startup_notify_id (GAppLaunchContext *context,
GAppInfo *info,
GList *files)
{
GAppLaunchContextClass *class;
g_return_val_if_fail (G_IS_APP_LAUNCH_CONTEXT (context), NULL);
g_return_val_if_fail (G_IS_APP_INFO (info), NULL);
class = G_APP_LAUNCH_CONTEXT_GET_CLASS (context);
if (class->get_startup_notify_id == NULL)
return NULL;
return class->get_startup_notify_id (context, info, files);
}
/**
* g_app_launch_context_launch_failed:
* @context: a #GAppLaunchContext.
* @startup_notify_id: the startup notification id that was returned by g_app_launch_context_get_startup_notify_id().
*
* Called when an application has failed to launch, so that it can cancel
* the application startup notification started in g_app_launch_context_get_startup_notify_id().
*
**/
void
g_app_launch_context_launch_failed (GAppLaunchContext *context,
const char *startup_notify_id)
{
g_return_if_fail (G_IS_APP_LAUNCH_CONTEXT (context));
g_return_if_fail (startup_notify_id != NULL);
g_signal_emit (context, signals[LAUNCH_FAILED], 0, startup_notify_id);
}
| staceyson/glib-2.0 | gio/gappinfo.c | C | lgpl-2.1 | 28,691 |
/* -*- mode: C++; c-file-style: "gnu" -*-
This file is part of KMail, the KDE mail client.
Copyright (c) 2009 Martin Koller <kollix@aon.at>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef MESSAGEVIEWERT_ATTACHMENTDIALOG_H
#define MESSAGEVIEWERT_ATTACHMENTDIALOG_H
#include <QObject>
class KDialog;
/** A class which handles the dialog used to present the user a choice what to do
with an attachment.
*/
class AttachmentDialog : public QObject
{
Q_OBJECT
public:
/// returncodes for exec()
enum
{
Save = 2,
Open,
OpenWith,
Cancel
};
// if @application is non-empty, the "open with <application>" button will also be shown,
// otherwise only save, open with, cancel
AttachmentDialog( QWidget *parent, const QString &filenameText, const QString &application,
const QString &dontAskAgainName );
// executes the modal dialog
int exec();
private slots:
void saveClicked();
void openClicked();
void openWithClicked();
private:
QString text, dontAskName;
KDialog *dialog;
};
#endif
| lefou/kdepim-noakonadi | messageviewer/attachmentdialog.h | C | lgpl-2.1 | 1,769 |
package railo.runtime.functions.dateTime;
import java.util.TimeZone;
import railo.runtime.PageContext;
import railo.runtime.exp.ExpressionException;
import railo.runtime.ext.function.Function;
import railo.runtime.tag.util.DeprecatedUtil;
import railo.runtime.type.dt.DateTime;
import railo.runtime.type.dt.DateTimeImpl;
/**
* Implements the CFML Function now
* @deprecated removed with no replacement
*/
public final class NowServer implements Function {
/**
* @param pc
* @return server time
* @throws ExpressionException
*/
public static DateTime call(PageContext pc ) throws ExpressionException {
DeprecatedUtil.function(pc,"nowServer");
long now = System.currentTimeMillis();
int railo = pc.getTimeZone().getOffset(now);
int server = TimeZone.getDefault().getOffset(now);
return new DateTimeImpl(pc,now-(railo-server),false);
}
} | JordanReiter/railo | railo-java/railo-core/src/railo/runtime/functions/dateTime/NowServer.java | Java | lgpl-2.1 | 870 |
/*
* gstvaapidisplay_egl_priv.h - Internal VA/EGL interface
*
* Copyright (C) 2014 Splitted-Desktop Systems
* Author: Gwenole Beauchesne <gwenole.beauchesne@intel.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#ifndef GST_VAAPI_DISPLAY_EGL_PRIV_H
#define GST_VAAPI_DISPLAY_EGL_PRIV_H
#include <gst/vaapi/gstvaapiwindow.h>
#include <gst/vaapi/gstvaapitexturemap.h>
#include "gstvaapidisplay_egl.h"
#include "gstvaapidisplay_priv.h"
#include "gstvaapiutils_egl.h"
G_BEGIN_DECLS
#define GST_VAAPI_IS_DISPLAY_EGL(display) \
(G_TYPE_CHECK_INSTANCE_TYPE ((display), GST_TYPE_VAAPI_DISPLAY_EGL))
#define GST_VAAPI_DISPLAY_EGL_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST ((klass), GST_TYPE_VAAPI_DISPLAY_EGL, GstVaapiDisplayEGLClass))
#define GST_VAAPI_DISPLAY_EGL_GET_CLASS(obj) \
(G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_VAAPI_DISPLAY_EGL, GstVaapiDisplayEGLClass))
#define GST_VAAPI_DISPLAY_EGL_CAST(obj) \
((GstVaapiDisplayEGL *)(obj))
/**
* GST_VAAPI_DISPLAY_EGL_DISPLAY:
* @display: a #GstVaapiDisplay
*
* Macro that evaluates to #EglDisplay wrapper for @display.
* This is an internal macro that does not do any run-time type check.
*/
#undef GST_VAAPI_DISPLAY_EGL_DISPLAY
#define GST_VAAPI_DISPLAY_EGL_DISPLAY(display) \
(GST_VAAPI_DISPLAY_EGL_CAST (display)->egl_display)
/**
* GST_VAAPI_DISPLAY_EGL_CONTEXT:
* @display: a #GstVaapiDisplay
*
* Macro that evaluates to #EglContext wrapper for @display.
* This is an internal macro that does not do any run-time type check.
*/
#undef GST_VAAPI_DISPLAY_EGL_CONTEXT
#define GST_VAAPI_DISPLAY_EGL_CONTEXT(display) \
gst_vaapi_display_egl_get_context (GST_VAAPI_DISPLAY_EGL (display))
typedef struct _GstVaapiDisplayEGLClass GstVaapiDisplayEGLClass;
/**
* GstVaapiDisplayEGL:
*
* VA/EGL display wrapper.
*/
struct _GstVaapiDisplayEGL
{
/*< private >*/
GstVaapiDisplay parent_instance;
gpointer loader;
GstVaapiDisplay *display;
EglDisplay *egl_display;
EglContext *egl_context;
guint gles_version;
GstVaapiTextureMap *texture_map;
};
/**
* GstVaapiDisplayEGLClass:
*
* VA/EGL display wrapper clas.
*/
struct _GstVaapiDisplayEGLClass
{
/*< private >*/
GstVaapiDisplayClass parent_class;
};
G_GNUC_INTERNAL
EglContext *
gst_vaapi_display_egl_get_context (GstVaapiDisplayEGL * display);
G_END_DECLS
#endif /* GST_VAAPI_DISPLAY_EGL_PRIV_H */
| GStreamer/gstreamer-vaapi | gst-libs/gst/vaapi/gstvaapidisplay_egl_priv.h | C | lgpl-2.1 | 3,088 |
/*
* Copyright (c) 2012 Citrix Systems, 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <xenctrl.h>
#include <surfman.h>
#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xinerama.h>
#define GL_GLEXT_PROTOTYPES 1
#include <GL/glx.h>
#include <GL/gl.h>
#include "glgfx.h"
#define MAX_MONITORS 32
#define MAX_SURFACES 256
#define MAX_DISPLAY_CONFIGS 64
#define XORG_TEMPLATE "/etc/X11/xorg.conf-glgfx-nvidia"
static int g_attributes[] = {
GLX_RGBA, GLX_DOUBLEBUFFER,
GLX_RED_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_GREEN_SIZE, 8,
None
};
Display *g_display = NULL;
static GLXContext g_context = NULL;
static Colormap g_colormap;
static int g_have_colormap = 0;
static Window g_window = None;
static int g_have_window = 0;
static xc_interface *g_xc = NULL;
static glgfx_surface *g_current_surface = NULL;
static struct event hotplug_timer;
typedef struct {
/* taken from xinerama */
int xoff,yoff,w,h;
} xinemonitor_t;
xinemonitor_t g_monitors[MAX_MONITORS];
int g_num_monitors = 0;
static int g_num_surfaces = 0;
static glgfx_surface* g_surfaces[MAX_SURFACES];
/* current display configuration */
static surfman_display_t g_dispcfg[MAX_DISPLAY_CONFIGS];
static int g_num_dispcfgs = 0;
static int stop_X();
static int
get_gpu_busid(int *b, int *d, int *f)
{
FILE *p;
char buff[1024];
int id = -1;
*b = *d = *f = 0;
p = popen("nvidia-xconfig --query-gpu-info", "r");
if (!p)
{
warning("nvidia-xconfig --query-gpu-info failed\n");
return 0;
}
while (!feof(p))
{
if (!fgets(buff, 1024, p))
break;
sscanf(buff, "GPU #%d:\n", &id);
if (id == 0)
{
if (sscanf(buff, " PCI BusID : PCI:%d:%d:%d\n", b, d, f) == 3)
break;
}
}
pclose(p);
return (*b != 0 || *d != 0 || *f != 0);
}
static char *
generate_xorg_config()
{
int b, d, f;
FILE *in, *out;
char buff[1024];
int id = -1;
int fd = -1;
int generated = 0;
char filename[] = "/tmp/xorg.conf-glgfx-nvidia-XXXXXX";
if (!get_gpu_busid(&b, &d, &f))
{
error("Can't get GPU#0 busid\n");
return NULL;
}
info("Found Nvidia GPU#0 %04x:%02x.%01x", b, d, f);
info("Temp fd %d\n", fd);
fd = mkstemp(filename);
info("Temp fd %d %s\n", fd, filename);
out = fdopen(fd, "w");
info("Generated config file %s\n", filename);
in = fopen(XORG_TEMPLATE, "r");
if (!in || !out)
goto out;
while (!feof(in))
{
if (!fgets(buff, 1024, in))
break;
info(buff);
if (strcmp(buff, " BusID \"PCI:b:d:f\"\n") == 0)
{
fprintf(out, " BusID \"PCI:%d:%d:%d\"\n",
b, d, f);
generated = 1;
}
else
fprintf(out, buff);
}
out:
if (out)
fclose(out);
if (in)
fclose(in);
if (!generated)
return NULL;
return strdup(filename);
}
static void
resize_gl( int w, int h )
{
info("resize_gl");
h = h == 0 ? 1 : h;
glViewport( 0, 0, w, h );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho( 0, w-1, h-1, 0, -10, 10 );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
static void
init_gl()
{
info("init_gl");
glClearColor( 0, 0, 0, 0 );
glClear( GL_COLOR_BUFFER_BIT );
glEnable( GL_TEXTURE );
glEnable( GL_TEXTURE_2D );
glFlush();
}
static void
resize_pbo( GLuint id, size_t sz )
{
GLubyte *ptr;
info( "sizing PBO %d to %d bytes", id, sz );
glBindBuffer( GL_PIXEL_UNPACK_BUFFER, id );
glBufferData( GL_PIXEL_UNPACK_BUFFER, sz, 0, GL_DYNAMIC_DRAW );
ptr = (GLubyte*) glMapBuffer( GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY );
info( "PBO %d seems to map onto %p", id, ptr );
glUnmapBuffer( GL_PIXEL_UNPACK_BUFFER );
}
static GLuint
create_pbo( size_t sz )
{
GLuint id;
glGenBuffers( 1, &id );
info( "created PBO %d", id );
return id;
}
static GLuint
create_texobj()
{
GLuint id;
info("creating texture object");
glGenTextures( 1, &id );
glBindTexture( GL_TEXTURE_2D, id );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
info( "created texture object %d", id );
return id;
}
static int get_gl_formats( int surfman_surface_fmt, GLenum *gl_fmt, GLenum *gl_typ )
{
switch (surfman_surface_fmt) {
case SURFMAN_FORMAT_BGRX8888:
*gl_fmt = GL_BGRA;
*gl_typ = GL_UNSIGNED_BYTE;
return 0;
case SURFMAN_FORMAT_RGBX8888:
*gl_fmt = GL_RGBA;
*gl_typ = GL_UNSIGNED_BYTE;
return 0;
case SURFMAN_FORMAT_BGR565:
*gl_fmt = GL_BGR;
*gl_typ = GL_UNSIGNED_SHORT_5_6_5;
return 0;
default:
error("unsupported surfman surface format %d", surfman_surface_fmt );
return -1;
}
}
static void
upload_pbo_to_texture(
GLuint pbo,
GLenum pbo_format,
GLenum pbo_type,
GLuint tex,
int recreate_texture,
int x,
int y,
int w,
int h,
int stride_in_bytes )
{
glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo );
glBindTexture( GL_TEXTURE_2D, tex );
glPixelStorei( GL_UNPACK_ALIGNMENT, 4 );
glPixelStorei( GL_UNPACK_ROW_LENGTH, stride_in_bytes / 4 ); // assume 4bpp for now
if (recreate_texture) {
glTexImage2D( GL_TEXTURE_2D, 0, 4, w, h, 0, pbo_format, pbo_type, 0 );
} else {
glTexSubImage2D( GL_TEXTURE_2D, 0, x, y, w, h, pbo_format, pbo_type, 0 );
}
}
static int
copy_to_pbo( GLuint pbo, GLubyte *src, size_t len, uint8_t *dirty_bitmap )
{
GLubyte *ptr;
glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo );
ptr = (GLubyte*) glMapBuffer( GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY );
if (!ptr) {
error("copy_to_pbo %d %p %d: map buffer FAILED", pbo, src, len);
return -1;
}
if (!dirty_bitmap) {
memcpy( ptr, src, len );
} else {
/* FIXME: this is bit suboptimal */
int num_pages = (len+XC_PAGE_SIZE-1) / XC_PAGE_SIZE;
int num_bytes = num_pages/8;
uint8_t* p = dirty_bitmap;
int i = 0, j;
while (i < num_bytes) {
switch (*p) {
case 0x00:
break;
default:
memcpy( ptr + XC_PAGE_SIZE*i*8, src + XC_PAGE_SIZE*i*8, XC_PAGE_SIZE*8 );
break;
}
++p;
++i;
}
ptr = ptr + XC_PAGE_SIZE*i*8;
src = src + XC_PAGE_SIZE*i*8;
i = 0;
while (i < num_pages%8) {
if (*p & (1<<i)) {
memcpy( ptr + XC_PAGE_SIZE*i, src + XC_PAGE_SIZE*i, XC_PAGE_SIZE );
}
++i;
}
}
glUnmapBuffer( GL_PIXEL_UNPACK_BUFFER );
return 0;
}
static void
upload_to_gpu( surfman_surface_t *src, glgfx_surface *dst, uint8_t *dirty_bitmap )
{
GLenum fb_format, fb_type;
int recreate=0, rv;
if ( !dst->initialised ) {
error("gpu surface not initialised");
return;
}
if ( !dst->mapped_fb ) {
error("framebuffer does not appear to be mapped");
return;
}
if ( dst->mapped_fb_size < dst->stride * dst->h ) {
error("framebuffer mapping appears to be too short");
return;
}
if ( get_gl_formats( src->format, &fb_format, &fb_type ) < 0 ) {
error("unsupported/unknown surface format");
return;
}
if ( dst->last_w != dst->w || dst->last_h != dst->h ) {
recreate = 1;
}
if ( recreate ) {
info("stride: %d, height: %d", dst->stride, dst->h);
resize_pbo( dst->pbo, dst->stride*dst->h );
}
rv = copy_to_pbo( dst->pbo, dst->mapped_fb, dst->stride * dst->h, recreate ? NULL : dirty_bitmap );
upload_pbo_to_texture( dst->pbo, fb_format, fb_type, dst->tex, recreate, 0, 0, dst->w, dst->h, dst->stride );
/* only overwrite if success from previous ops */
if (rv == 0) {
dst->last_w = dst->w;
dst->last_h = dst->h;
}
}
static void
map_fb( surfman_surface_t *src, glgfx_surface *dst )
{
if ( !( dst->mapped_fb = surface_map( src ) ) ) {
error("failed to map framebuffer pages");
}
}
static int
init_surface_resources( glgfx_surface *surface )
{
GLubyte *buf;
info("init surface resources for %p", surface);
if (surface->initialised) {
error("surface already initialised");
return -1;
}
surface->tex = create_texobj();
surface->pbo = create_pbo( surface->w*surface->stride );
map_fb( surface->src, surface );
surface->initialised = 1;
return 0;
}
static void
free_surface_resources( glgfx_surface *surf )
{
if (surf) {
info("free surface resources %p", surf);
if (surf->anim_next && surf->anim_next->anim_prev == surf) {
surf->anim_next->anim_prev = NULL;
}
if (surf->anim_prev && surf->anim_prev->anim_next == surf) {
surf->anim_prev->anim_next = NULL;
}
glDeleteTextures( 1, &surf->tex );
glBufferData( GL_PIXEL_UNPACK_BUFFER, 0, NULL, GL_DYNAMIC_DRAW );
glDeleteBuffers( 1, &surf->pbo );
surface_unmap( surf );
surf->initialised = 0;
}
}
static void
render( glgfx_surface *surface, int w, int h )
{
glBindTexture( GL_TEXTURE_2D, surface->tex );
glColor3f( 1,1,1 );
glBegin( GL_QUADS );
glTexCoord2f( 0,0 ); glVertex2f( 0, 0 );
glTexCoord2f( 1,0 ); glVertex2f( w-1, 0 );
glTexCoord2f( 1,1 ); glVertex2f( w-1, h-1 );
glTexCoord2f( 0,1 ); glVertex2f( 0, h-1 );
glEnd();
glFlush();
}
static void
render_as_tiles( glgfx_surface *surface, int xtiles, int ytiles, float z, int rev,
int w, int h, float phase )
{
int x,y;
float xstep = 1.0 / xtiles;
float ystep = 1.0 / ytiles;
float xc = xstep*xtiles/2;
float yc = ystep*ytiles/2;
glBindTexture( GL_TEXTURE_2D, surface->tex );
glColor3f( 1,1,1 );
for (y = 0; y < ytiles; ++y) {
for (x = 0; x < xtiles; ++x) {
float x0 = xstep*x;
float y0 = ystep*y;
float x1 = x0+xstep;
float y1 = y0+xstep;
float dst = sqrtf(sqrtf((x1-xc)*(x1-xc)+(y1-yc)*(y1-yc)));
float speed = cos(dst*3.14159/2)*2;
if (speed<1) speed=1;
float rot = phase * speed * 180;
if (rev) {
rot = 180-rot;
}
glLoadIdentity();
glTranslatef( x0*(w-1), y0*(h-1), z );
if (rot > 180) rot=180;
if (rot < 0) rot=0;
glRotatef( rot, 1, 1, 0 );
glBegin( GL_QUADS );
glTexCoord2f( x0,y0 ); glVertex3f( 0,0,0 );
glTexCoord2f( x1,y0 ); glVertex3f( xstep*(w-1),0,0 );
glTexCoord2f( x1,y1 ); glVertex3f( xstep*(w-1),ystep*(h-1),0 );
glTexCoord2f( x0,y1 ); glVertex3f( 0,ystep*(h-1),0 );
glEnd();
}
}
}
static void
render_animated( glgfx_surface *surface, int w, int h )
{
if ( !surface->anim_active ) {
render( surface, w, h );
} else {
glPushAttrib( GL_DEPTH_BUFFER_BIT );
glEnable( GL_CULL_FACE );
glClearColor( 0, 0, 0, 0 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glFrontFace( GL_CW );
render_as_tiles( surface, 16, 16, 1, 1, w, h, surface->anim_phase );
if ( surface->anim_prev ) {
glFrontFace( GL_CW );
render_as_tiles( surface->anim_prev, 16, 16, -1, 0, w, h, surface->anim_phase );
}
/* update animation frame */
surface->anim_phase += 0.02;
if (surface->anim_phase > 1) {
surface->anim_phase = 0;
surface->anim_active = 0;
surface->anim_next = NULL;
if (surface->anim_prev) {
surface->anim_prev->anim_next = NULL;
}
}
glPopAttrib();
glDisable( GL_CULL_FACE );
}
glFlush();
}
static void
hide_x_cursor(Display *display, Window window)
{
Cursor invis_cur;
Pixmap empty_pix;
XColor black;
static char empty_data[] = { 0,0,0,0,0,0,0,0 };
black.red = black.green = black.blue = 0;
empty_pix = XCreateBitmapFromData(display, window, empty_data, 8, 8);
invis_cur = XCreatePixmapCursor(
display, empty_pix, empty_pix,
&black, &black, 0, 0);
XDefineCursor(display, window, invis_cur);
XFreeCursor(display, invis_cur);
}
static void
dump_visuals(Display *display)
{
XVisualInfo template;
XVisualInfo *vi = NULL;
int count;
vi = XGetVisualInfo( display, 0, &template, &count );
if (vi) {
int i;
for ( i = 0; i < count; ++i ) {
XVisualInfo *v = &vi[i];
info( "visual %d: depth=%d bits_per_rgb=%d, screen=%d, class=%d", i, v->depth, v->bits_per_rgb, v->screen, v->class );
}
XFree( vi );
}
}
static int
init_window(int w, int h)
{
int screen;
XVisualInfo *vi;
XSetWindowAttributes winattr;
info( "create X window");
if (!g_display) {
error("init_window: no display");
return -1;
}
screen = DefaultScreen(g_display);
info( "screen=%d", screen);
dump_visuals( g_display );
vi = glXChooseVisual( g_display, screen, g_attributes );
if (!vi) {
error("failed to choose appropriate visual");
return -1;
}
g_context = glXCreateContext( g_display, vi, 0, GL_TRUE );
g_colormap = XCreateColormap( g_display, RootWindow(g_display, vi->screen), vi->visual, AllocNone );
g_have_colormap = 1;
winattr.colormap = g_colormap;
winattr.border_pixel = 0;
winattr.event_mask = ExposureMask | StructureNotifyMask;
g_window = XCreateWindow(
g_display, RootWindow(g_display, vi->screen),
0, 0, w, h, 0, vi->depth, InputOutput, vi->visual,
CWBorderPixel | CWColormap | CWEventMask, &winattr
);
XMapRaised( g_display, g_window );
glXMakeCurrent( g_display, g_window, g_context );
if ( glXIsDirect( g_display, g_context ) ) {
info( "DRI enabled");
} else {
info( "no DRI available");
}
hide_x_cursor( g_display, g_window );
info ("GL extensions: %s", glGetString( GL_EXTENSIONS ));
init_gl();
resize_gl( w, h );
info ("window init completed");
XFree( vi );
return 0;
}
static void
update_monitors()
{
if (!g_display) {
error("update_monitors: NO DISPLAY");
return;
}
if (XineramaIsActive(g_display)) {
int num_screens = 0, i;
XineramaScreenInfo *info = XineramaQueryScreens( g_display, &num_screens );
XineramaScreenInfo *scr = info;
g_num_monitors = 0;
for (i = 0; i < num_screens && i < MAX_MONITORS; ++i) {
xinemonitor_t *m = &g_monitors[i];
info( "Xinerama screen %d: x_org=%d y_org=%d width=%d height=%d",
i, scr->x_org, scr->y_org, scr->width, scr->height );
m->xoff = scr->x_org;
m->yoff = scr->y_org;
m->w = scr->width;
m->h = scr->height;
++scr;
++g_num_monitors;
}
XFree( info );
} else {
/* one monitor then */
int scr;
xinemonitor_t *m;
info("XINERAMA is inactive");
scr = XDefaultScreen(g_display);
if (!scr) {
error("update_monitors w/o xinerama: NO DEFAULT SCREEN?");
return;
}
m = &g_monitors[0];
m->xoff = m->yoff = 0;
m->w = DisplayWidth(g_display, scr);
m->h = DisplayHeight(g_display, scr);
g_num_monitors = 1;
}
}
static int
start_X()
{
Display *display = NULL;
int i;
int rv;
const int TRIES = 10;
char *config_filename;
char cmd[1024];
config_filename = generate_xorg_config();
if (!config_filename)
{
error("Can't generate xorg config file");
return SURFMAN_ERROR;
}
info( "starting X server (config:%s)", config_filename);
snprintf(cmd, 1024, "start-stop-daemon -S -b --exec /usr/bin/X -- -config %s",
config_filename);
free(config_filename);
unlink(config_filename);
rv = system(cmd);
if (rv < 0) {
return rv;
}
for (i = 0; i < TRIES; ++i) {
display = XOpenDisplay( ":0" );
if (display) {
info( "opened X display");
break;
}
sleep(1);
}
if (!display) {
error("failed to open X display");
return SURFMAN_ERROR;
}
g_display = display;
if (XineramaIsActive(display)) {
info("XINERAMA is active");
int num_screens = 0;
XineramaScreenInfo *info = XineramaQueryScreens( display, &num_screens );
XineramaScreenInfo *scr = info;
for (i = 0; i < num_screens; ++i) {
info( "Xinerama screen %d: x_org=%d y_org=%d width=%d height=%d",
i, scr->x_org, scr->y_org, scr->width, scr->height );
++scr;
}
XFree( info );
} else {
info("XINERAMA is inactive");
}
return SURFMAN_SUCCESS;
}
static int
start_X_and_create_window()
{
int rv = start_X();
if (rv < 0) {
return rv;
}
if (!g_have_window) {
int screen, w, h;
screen = DefaultScreen(g_display);
w = DisplayWidth(g_display, screen);
h = DisplayHeight(g_display, screen);
info("creating window %d %d screen=%d", w, h, screen);
rv = init_window(w,h);
if (rv < 0) {
error("failed to create window");
return SURFMAN_ERROR;
}
g_have_window = 1;
}
return 0;
}
static int
stop_X()
{
int rv, tries=0,i;
info( "stopping X server");
/* free all surface resources */
for (i = 0; i < g_num_surfaces; ++i) {
info("freeing surface %d", i);
free_surface_resources( g_surfaces[i] );
}
if (g_context) {
info("freeing context");
glXMakeCurrent( g_display, None, NULL );
glXDestroyContext( g_display, g_context );
g_context = NULL;
}
if (g_window != None) {
info("freeing window");
XUnmapWindow( g_display, g_window );
XDestroyWindow( g_display, g_window );
g_window = None;
g_have_window = 0;
}
if (g_have_colormap) {
info("freeing colormap");
XFreeColormap( g_display, g_colormap );
g_have_colormap = 0;
}
if (g_display) {
info("closing display");
XCloseDisplay( g_display );
g_display = NULL;
}
rv = system("start-stop-daemon -K --exec /usr/bin/X");
if (rv != 0) {
return SURFMAN_ERROR;
}
while (tries < 10) {
rv = system("pidof X");
if (rv == 0) {
info("waiting for X server to disappear..");
sleep(1);
++tries;
} else {
info("X server disappeared");
return SURFMAN_SUCCESS;
}
}
error("timeout waiting for X server to disappear");
return SURFMAN_ERROR;
}
static int
check_monitor_hotplug(surfman_plugin_t *plugin)
{
static int monitors = 1;
int l_monitor;
int id;
FILE *f = NULL;
char buff[1024];
struct timeval tv = {1, 0};
event_add(&hotplug_timer, &tv);
f = popen("nvidia-xconfig --query-gpu-info", "r");
if (!f)
{
warning("nvidia-xconfig --query-gpu-info failed\n");
return monitors;
}
while (!feof(f))
{
if (!fgets(buff, 1024, f))
break;
if (sscanf(buff, "GPU #%d:\n", &id) == 1 &&
id != 0)
break;
if (sscanf(buff, " Number of Display Devices: %d\n", &l_monitor) == 1)
{
if (monitors != l_monitor)
{
if (monitors != -1)
{
info("Detect monitor hotplug, %d monitors, before was %d\n",
l_monitor, monitors);
stop_X();
start_X_and_create_window();
plugin->notify = SURFMAN_NOTIFY_MONITOR_RESCAN;
}
monitors = l_monitor;
break;
}
}
}
pclose(f);
return monitors;
}
static void
check_monitor_hotplug_cb(int fd, short event, void *opaque)
{
check_monitor_hotplug(opaque);
}
static int
have_nvidia()
{
return system("lspci -d 10de:* -mm -n | cut -d \" \" -f 2 | grep 0300") == 0;
}
static int
glgfx_init (surfman_plugin_t * p)
{
int rv;
struct timeval tv = {1, 0};
info( "glgfx_init");
if (!have_nvidia()) {
error("NVIDIA device not present");
return SURFMAN_ERROR;
}
g_xc = xc_interface_open(NULL, NULL, 0);
if (!g_xc) {
error("failed to open XC interface");
return SURFMAN_ERROR;
}
rv = start_X_and_create_window();
if (rv < 0) {
error("starting X failed");
return SURFMAN_ERROR;
}
event_set(&hotplug_timer, -1, EV_TIMEOUT,
check_monitor_hotplug_cb, p);
event_add(&hotplug_timer, &tv);
return SURFMAN_SUCCESS;
}
static void
glgfx_shutdown (surfman_plugin_t * p)
{
int rv;
info("shutting down");
if ( g_context ) {
if ( !glXMakeCurrent(g_display, None, NULL)) {
error("could not release drawing context");
}
glXDestroyContext( g_display, g_context );
}
if ( g_display ) {
XCloseDisplay( g_display );
g_display = NULL;
}
rv = stop_X();
if (rv < 0) {
error("stopping X failed");
}
xc_interface_close(g_xc);
g_xc = NULL;
}
static int
glgfx_display (surfman_plugin_t * p,
surfman_display_t * config,
size_t size)
{
int rv;
glgfx_surface *surf = NULL;
size_t i;
info("glgfx_display, num config=%d", (int)size);
/* initialise surfaces should that be necessary */
for (i = 0; i < size; ++i) {
surfman_display_t *d = &config[i];
info("surface %p on monitor %p", d->psurface, d->monitor);
if (d->psurface) {
surf = (glgfx_surface*) d->psurface;
if (!surf->initialised) {
info("initialising surface");
if (init_surface_resources(surf) < 0) {
error("FAILED to initialise surface!");
return SURFMAN_ERROR;
}
}
/* perhaps begin animation sequence if we changed surface on i-th display */
if (i < (size_t)g_num_dispcfgs) {
glgfx_surface *prev_surf = (glgfx_surface*) g_dispcfg[i].psurface;
if (prev_surf && prev_surf != surf) {
/* yes */
prev_surf->anim_next = surf;
prev_surf->anim_prev = NULL;
prev_surf->anim_active = 0;
surf->anim_prev = prev_surf;
surf->anim_next = NULL;
surf->anim_phase = 0;
surf->anim_active = 1;
}
}
}
}
/* cache the display config for actual rendering done during refresh callback */
memcpy( g_dispcfg, config, sizeof(surfman_display_t) * size );
g_num_dispcfgs = size;
return SURFMAN_SUCCESS;
}
static int
glgfx_get_monitors (surfman_plugin_t * p,
surfman_monitor_t * monitors,
size_t size)
{
static surfman_monitor_t m = NULL;
int i;
info( "glgfx_get_monitors");
update_monitors();
for (i = 0; i < g_num_monitors && i < (int)size; ++i) {
monitors[i] = &g_monitors[i];
}
info( "found %d monitors", g_num_monitors );
return g_num_monitors;
}
static int
glgfx_set_monitor_modes (surfman_plugin_t * p,
surfman_monitor_t monitor,
surfman_monitor_mode_t * mode)
{
info( "glgfx_set_monitor_modes");
return SURFMAN_SUCCESS;
}
static int
glgfx_get_monitor_info_by_monitor (surfman_plugin_t * p,
surfman_monitor_t monitor,
surfman_monitor_info_t * info,
unsigned int modes_count)
{
int w,h,screen;
xinemonitor_t *m;
// info( "glgfx_get_monitor_info_by_monitor" );
m = (xinemonitor_t*) monitor;
w = m->w; h = m->h;
info->modes[0].htimings[SURFMAN_TIMING_ACTIVE] = w;
info->modes[0].htimings[SURFMAN_TIMING_SYNC_START] = w;
info->modes[0].htimings[SURFMAN_TIMING_SYNC_END] = w;
info->modes[0].htimings[SURFMAN_TIMING_TOTAL] = w;
info->modes[0].vtimings[SURFMAN_TIMING_ACTIVE] = h;
info->modes[0].vtimings[SURFMAN_TIMING_SYNC_START] = h;
info->modes[0].vtimings[SURFMAN_TIMING_SYNC_END] = h;
info->modes[0].vtimings[SURFMAN_TIMING_TOTAL] = h;
info->prefered_mode = &info->modes[0];
info->current_mode = &info->modes[0];
info->mode_count = 1;
return SURFMAN_SUCCESS;
}
static int
glgfx_get_monitor_edid_by_monitor (surfman_plugin_t * p,
surfman_monitor_t monitor,
surfman_monitor_edid_t * edid)
{
info( "glgfx_get_edid_by_monitor");
return SURFMAN_SUCCESS;
}
static surfman_psurface_t
glgfx_get_psurface_from_surface (surfman_plugin_t * p,
surfman_surface_t * surfman_surface)
{
glgfx_surface *surface = NULL;
info("glgfx_get_psurface_from_surface");
if (g_num_surfaces >= MAX_SURFACES) {
error("too many surfaces");
return NULL;
}
surface = calloc(1, sizeof(glgfx_surface));
if (!surface) {
return NULL;
}
surface->last_w = 0;
surface->last_h = 0;
surface->w = surfman_surface->width;
surface->h = surfman_surface->height;
surface->stride = surfman_surface->stride;
surface->src = surfman_surface;
surface->initialised = 0;
surface->mapped_fb = NULL;
surface->anim_next = NULL;
surface->anim_prev = NULL;
surface->anim_active = 0;
surface->anim_phase = 0;
info("allocated psurface %p", surface);
map_fb( surfman_surface, surface );
g_surfaces[g_num_surfaces++] = surface;
return surface;
}
static void
glgfx_update_psurface (surfman_plugin_t *plugin,
surfman_psurface_t psurface,
surfman_surface_t *surface,
unsigned int flags)
{
glgfx_surface *glsurf = (glgfx_surface*)psurface;
info( "glgfx_update_psurface %p", surface);
if (!psurface) {
return;
}
glsurf->last_w = 0;
glsurf->last_h = 0;
glsurf->w = surface->width;
glsurf->h = surface->height;
glsurf->stride = surface->stride;
glsurf->src = surface;
if (flags & SURFMAN_UPDATE_PAGES) {
surface_unmap( psurface );
map_fb( surface, psurface );
}
}
static void
glgfx_refresh_surface(struct surfman_plugin *plugin,
surfman_psurface_t psurface,
uint8_t *refresh_bitmap)
{
glgfx_surface *dst = (glgfx_surface*) psurface;
int i;
if (!dst) {
return;
}
glLoadIdentity();
/* upload the surface which requires refresh into GPU */
upload_to_gpu( dst->src, dst, refresh_bitmap );
/* then render all currently visible surfaces */
for (i = 0; i < g_num_dispcfgs; ++i) {
surfman_display_t *d = &g_dispcfg[i];
xinemonitor_t *m = (xinemonitor_t*) d->monitor;
glgfx_surface *surf = (glgfx_surface*) d->psurface;
if (surf && surf == psurface && surf->initialised) {
/* translate onto monitor */
glLoadIdentity();
glTranslatef( m->xoff, m->yoff, 0 );
render_animated( dst, m->w, m->h );
}
}
/* deus ex machina */
glXSwapBuffers( g_display, g_window );
}
static void
glgfx_free_psurface_pages(surfman_plugin_t * p,
surfman_psurface_t psurface)
{
info( "%s", __func__);
}
static int
glgfx_get_pages_from_psurface (surfman_plugin_t * p,
surfman_psurface_t psurface,
uint64_t * pages)
{
info( "glgfx_get_pages_from_psurface");
return SURFMAN_ERROR;
}
static int
glgfx_copy_surface_on_psurface (surfman_plugin_t * p,
surfman_psurface_t psurface)
{
info( "glgfx_copy_surface_on_psurface");
return SURFMAN_ERROR;
}
static int
glgfx_copy_psurface_on_surface (surfman_plugin_t * p,
surfman_psurface_t psurface)
{
info( "glgfx_copy_psurface_on_surface");
return SURFMAN_ERROR;
}
static void
glgfx_free_psurface (surfman_plugin_t * plugin,
surfman_psurface_t psurface)
{
int i;
glgfx_surface *surf = (glgfx_surface*) psurface;
info( "glgfx_free_psurface");
if (surf) {
free_surface_resources( surf );
surface_unmap( surf );
for (i = 0; i < g_num_surfaces; ++i) {
if (g_surfaces[i] == surf) {
info ("removing surface at %d", i);
if (i != MAX_SURFACES-1 ) {
memcpy( &g_surfaces[i], &g_surfaces[i+1], (g_num_surfaces-i-1)*sizeof(glgfx_surface*) );
}
--g_num_surfaces;
break;
}
}
free(surf);
}
}
surfman_plugin_t surfman_plugin = {
.init = glgfx_init,
.shutdown = glgfx_shutdown,
.display = glgfx_display,
.get_monitors = glgfx_get_monitors,
.set_monitor_modes = glgfx_set_monitor_modes,
.get_monitor_info = glgfx_get_monitor_info_by_monitor,
.get_monitor_edid = glgfx_get_monitor_edid_by_monitor,
.get_psurface_from_surface = glgfx_get_psurface_from_surface,
.update_psurface = glgfx_update_psurface,
.refresh_psurface = glgfx_refresh_surface,
.get_pages_from_psurface = glgfx_get_pages_from_psurface,
.free_psurface_pages = glgfx_free_psurface_pages,
.copy_surface_on_psurface = glgfx_copy_surface_on_psurface,
.copy_psurface_on_surface = glgfx_copy_psurface_on_surface,
.free_psurface = glgfx_free_psurface,
.options = {1, SURFMAN_FEATURE_NEED_REFRESH},
.notify = SURFMAN_NOTIFY_NONE
};
| OpenXT/surfman | plugins/glgfx/glgfx.c | C | lgpl-2.1 | 31,356 |
/*****************************************************************************
* schroedinger.c: Dirac decoder module making use of libschroedinger.
* (http://www.bbc.co.uk/rd/projects/dirac/index.shtml)
* (http://diracvideo.org)
*****************************************************************************
* Copyright (C) 2008-2011 VLC authors and VideoLAN
*
* Authors: Jonathan Rosser <jonathan.rosser@gmail.com>
* David Flynn <davidf at rd dot bbc.co.uk>
* Anuradha Suraparaju <asuraparaju at gmail dot com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <assert.h>
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_codec.h>
#include <schroedinger/schro.h>
/*****************************************************************************
* Module descriptor
*****************************************************************************/
static int OpenDecoder ( vlc_object_t * );
static void CloseDecoder ( vlc_object_t * );
static int OpenEncoder ( vlc_object_t * );
static void CloseEncoder ( vlc_object_t * );
#define ENC_CFG_PREFIX "sout-schro-"
#define ENC_CHROMAFMT "chroma-fmt"
#define ENC_CHROMAFMT_TEXT N_("Chroma format")
#define ENC_CHROMAFMT_LONGTEXT N_("Picking chroma format will force a " \
"conversion of the video into that format")
static const char *const enc_chromafmt_list[] =
{ "420", "422", "444" };
static const char *const enc_chromafmt_list_text[] =
{ N_("4:2:0"), N_("4:2:2"), N_("4:4:4") };
#define ENC_RATE_CONTROL "rate-control"
#define ENC_RATE_CONTROL_TEXT N_("Rate control method")
#define ENC_RATE_CONTROL_LONGTEXT N_("Method used to encode the video sequence")
static const char *enc_rate_control_list[] = {
"constant_noise_threshold",
"constant_bitrate",
"low_delay",
"lossless",
"constant_lambda",
"constant_error",
"constant_quality"
};
static const char *enc_rate_control_list_text[] = {
N_("Constant noise threshold mode"),
N_("Constant bitrate mode (CBR)"),
N_("Low Delay mode"),
N_("Lossless mode"),
N_("Constant lambda mode"),
N_("Constant error mode"),
N_("Constant quality mode")
};
#define ENC_GOP_STRUCTURE "gop-structure"
#define ENC_GOP_STRUCTURE_TEXT N_("GOP structure")
#define ENC_GOP_STRUCTURE_LONGTEXT N_("GOP structure used to encode the video sequence")
static const char *enc_gop_structure_list[] = {
"adaptive",
"intra_only",
"backref",
"chained_backref",
"biref",
"chained_biref"
};
static const char *enc_gop_structure_list_text[] = {
N_("No fixed gop structure. A picture can be intra or inter and refer to previous or future pictures."),
N_("I-frame only sequence"),
N_("Inter pictures refere to previous pictures only"),
N_("Inter pictures refere to previous pictures only"),
N_("Inter pictures can refer to previous or future pictures"),
N_("Inter pictures can refer to previous or future pictures")
};
#define ENC_QUALITY "quality"
#define ENC_QUALITY_TEXT N_("Constant quality factor")
#define ENC_QUALITY_LONGTEXT N_("Quality factor to use in constant quality mode")
#define ENC_NOISE_THRESHOLD "noise-threshold"
#define ENC_NOISE_THRESHOLD_TEXT N_("Noise Threshold")
#define ENC_NOISE_THRESHOLD_LONGTEXT N_("Noise threshold to use in constant noise threshold mode")
#define ENC_BITRATE "bitrate"
#define ENC_BITRATE_TEXT N_("CBR bitrate (kbps)")
#define ENC_BITRATE_LONGTEXT N_("Target bitrate in kbps when encoding in constant bitrate mode")
#define ENC_MAX_BITRATE "max-bitrate"
#define ENC_MAX_BITRATE_TEXT N_("Maximum bitrate (kbps)")
#define ENC_MAX_BITRATE_LONGTEXT N_("Maximum bitrate in kbps when encoding in constant bitrate mode")
#define ENC_MIN_BITRATE "min-bitrate"
#define ENC_MIN_BITRATE_TEXT N_("Minimum bitrate (kbps)")
#define ENC_MIN_BITRATE_LONGTEXT N_("Minimum bitrate in kbps when encoding in constant bitrate mode")
#define ENC_AU_DISTANCE "gop-length"
#define ENC_AU_DISTANCE_TEXT N_("GOP length")
#define ENC_AU_DISTANCE_LONGTEXT N_("Number of pictures between successive sequence headers i.e. length of the group of pictures")
#define ENC_PREFILTER "filtering"
#define ENC_PREFILTER_TEXT N_("Prefilter")
#define ENC_PREFILTER_LONGTEXT N_("Enable adaptive prefiltering")
static const char *enc_filtering_list[] = {
"none",
"center_weighted_median",
"gaussian",
"add_noise",
"adaptive_gaussian",
"lowpass"
};
static const char *enc_filtering_list_text[] = {
N_("No pre-filtering"),
N_("Centre Weighted Median"),
N_("Gaussian Low Pass Filter"),
N_("Add Noise"),
N_("Gaussian Adaptive Low Pass Filter"),
N_("Low Pass Filter"),
};
#define ENC_PREFILTER_STRENGTH "filter-value"
#define ENC_PREFILTER_STRENGTH_TEXT N_("Amount of prefiltering")
#define ENC_PREFILTER_STRENGTH_LONGTEXT N_("Higher value implies more prefiltering")
#define ENC_CODINGMODE "coding-mode"
#define ENC_CODINGMODE_TEXT N_("Picture coding mode")
#define ENC_CODINGMODE_LONGTEXT N_("Field coding is where interlaced fields are coded" \
" separately as opposed to a pseudo-progressive frame")
static const char *const enc_codingmode_list[] =
{ "auto", "progressive", "field" };
static const char *const enc_codingmode_list_text[] =
{ N_("auto - let encoder decide based upon input (Best)"),
N_("force coding frame as single picture"),
N_("force coding frame as separate interlaced fields"),
};
/* advanced option only */
#define ENC_MCBLK_SIZE "motion-block-size"
#define ENC_MCBLK_SIZE_TEXT N_("Size of motion compensation blocks")
static const char *enc_block_size_list[] = {
"automatic",
"small",
"medium",
"large"
};
static const char *const enc_block_size_list_text[] =
{ N_("automatic - let encoder decide based upon input (Best)"),
N_("small - use small motion compensation blocks"),
N_("medium - use medium motion compensation blocks"),
N_("large - use large motion compensation blocks"),
};
/* advanced option only */
#define ENC_MCBLK_OVERLAP "motion-block-overlap"
#define ENC_MCBLK_OVERLAP_TEXT N_("Overlap of motion compensation blocks")
static const char *enc_block_overlap_list[] = {
"automatic",
"none",
"partial",
"full"
};
static const char *const enc_block_overlap_list_text[] =
{ N_("automatic - let encoder decide based upon input (Best)"),
N_("none - Motion compensation blocks do not overlap"),
N_("partial - Motion compensation blocks only partially overlap"),
N_("full - Motion compensation blocks fully overlap"),
};
#define ENC_MVPREC "mv-precision"
#define ENC_MVPREC_TEXT N_("Motion Vector precision")
#define ENC_MVPREC_LONGTEXT N_("Motion Vector precision in pels")
static const char *const enc_mvprec_list[] =
{ "1", "1/2", "1/4", "1/8" };
/* advanced option only */
#define ENC_ME_COMBINED "me-combined"
#define ENC_ME_COMBINED_TEXT N_("Three component motion estimation")
#define ENC_ME_COMBINED_LONGTEXT N_("Use chroma as part of the motion estimation process")
#define ENC_DWTINTRA "intra-wavelet"
#define ENC_DWTINTRA_TEXT N_("Intra picture DWT filter")
#define ENC_DWTINTER "inter-wavelet"
#define ENC_DWTINTER_TEXT N_("Inter picture DWT filter")
static const char *enc_wavelet_list[] = {
"desl_dubuc_9_7",
"le_gall_5_3",
"desl_dubuc_13_7",
"haar_0",
"haar_1",
"fidelity",
"daub_9_7"
};
static const char *enc_wavelet_list_text[] = {
"Deslauriers-Dubuc (9,7)",
"LeGall (5,3)",
"Deslauriers-Dubuc (13,7)",
"Haar with no shift",
"Haar with single shift per level",
"Fidelity filter",
"Daubechies (9,7) integer approximation"
};
#define ENC_DWTDEPTH "transform-depth"
#define ENC_DWTDEPTH_TEXT N_("Number of DWT iterations")
#define ENC_DWTDEPTH_LONGTEXT N_("Also known as DWT levels")
/* advanced option only */
#define ENC_MULTIQUANT "enable-multiquant"
#define ENC_MULTIQUANT_TEXT N_("Enable multiple quantizers")
#define ENC_MULTIQUANT_LONGTEXT N_("Enable multiple quantizers per subband (one per codeblock)")
/* advanced option only */
#define ENC_NOAC "enable-noarith"
#define ENC_NOAC_TEXT N_("Disable arithmetic coding")
#define ENC_NOAC_LONGTEXT N_("Use variable length codes instead, useful for very high bitrates")
/* visual modelling */
/* advanced option only */
#define ENC_PWT "perceptual-weighting"
#define ENC_PWT_TEXT N_("perceptual weighting method")
static const char *enc_perceptual_weighting_list[] = {
"none",
"ccir959",
"moo",
"manos_sakrison"
};
/* advanced option only */
#define ENC_PDIST "perceptual-distance"
#define ENC_PDIST_TEXT N_("perceptual distance")
#define ENC_PDIST_LONGTEXT N_("perceptual distance to calculate perceptual weight")
/* advanced option only */
#define ENC_HSLICES "horiz-slices"
#define ENC_HSLICES_TEXT N_("Horizontal slices per frame")
#define ENC_HSLICES_LONGTEXT N_("Number of horizontal slices per frame in low delay mode")
/* advanced option only */
#define ENC_VSLICES "vert-slices"
#define ENC_VSLICES_TEXT N_("Vertical slices per frame")
#define ENC_VSLICES_LONGTEXT N_("Number of vertical slices per frame in low delay mode")
/* advanced option only */
#define ENC_SCBLK_SIZE "codeblock-size"
#define ENC_SCBLK_SIZE_TEXT N_("Size of code blocks in each subband")
static const char *enc_codeblock_size_list[] = {
"automatic",
"small",
"medium",
"large",
"full"
};
static const char *const enc_codeblock_size_list_text[] =
{ N_("automatic - let encoder decide based upon input (Best)"),
N_("small - use small code blocks"),
N_("medium - use medium sized code blocks"),
N_("large - use large code blocks"),
N_("full - One code block per subband"),
};
/* advanced option only */
#define ENC_ME_HIERARCHICAL "enable-hierarchical-me"
#define ENC_ME_HIERARCHICAL_TEXT N_("Enable hierarchical Motion Estimation")
/* advanced option only */
#define ENC_ME_DOWNSAMPLE_LEVELS "downsample-levels"
#define ENC_ME_DOWNSAMPLE_LEVELS_TEXT N_("Number of levels of downsampling")
#define ENC_ME_DOWNSAMPLE_LEVELS_LONGTEXT N_("Number of levels of downsampling in hierarchical motion estimation mode")
/* advanced option only */
#define ENC_ME_GLOBAL_MOTION "enable-global-me"
#define ENC_ME_GLOBAL_MOTION_TEXT N_("Enable Global Motion Estimation")
/* advanced option only */
#define ENC_ME_PHASECORR "enable-phasecorr-me"
#define ENC_ME_PHASECORR_TEXT N_("Enable Phase Correlation Estimation")
/* advanced option only */
#define ENC_SCD "enable-scd"
#define ENC_SCD_TEXT N_("Enable Scene Change Detection")
/* advanced option only */
#define ENC_FORCE_PROFILE "force-profile"
#define ENC_FORCE_PROFILE_TEXT N_("Force Profile")
static const char *enc_profile_list[] = {
"auto",
"vc2_low_delay",
"vc2_simple",
"vc2_main",
"main"
};
static const char *const enc_profile_list_text[] =
{ N_("automatic - let encoder decide based upon input (Best)"),
N_("VC2 Low Delay Profile"),
N_("VC2 Simple Profile"),
N_("VC2 Main Profile"),
N_("Main Profile"),
};
static const char *const ppsz_enc_options[] = {
ENC_RATE_CONTROL, ENC_GOP_STRUCTURE, ENC_QUALITY, ENC_NOISE_THRESHOLD, ENC_BITRATE,
ENC_MIN_BITRATE, ENC_MAX_BITRATE, ENC_AU_DISTANCE, ENC_CHROMAFMT,
ENC_PREFILTER, ENC_PREFILTER_STRENGTH, ENC_CODINGMODE, ENC_MCBLK_SIZE,
ENC_MCBLK_OVERLAP, ENC_MVPREC, ENC_ME_COMBINED, ENC_DWTINTRA, ENC_DWTINTER,
ENC_DWTDEPTH, ENC_MULTIQUANT, ENC_NOAC, ENC_PWT, ENC_PDIST, ENC_HSLICES,
ENC_VSLICES, ENC_SCBLK_SIZE, ENC_ME_HIERARCHICAL, ENC_ME_DOWNSAMPLE_LEVELS,
ENC_ME_GLOBAL_MOTION, ENC_ME_PHASECORR, ENC_SCD, ENC_FORCE_PROFILE,
NULL
};
/* Module declaration */
vlc_module_begin ()
set_category( CAT_INPUT )
set_subcategory( SUBCAT_INPUT_VCODEC )
set_shortname( "Schroedinger" )
set_description( N_("Dirac video decoder using libschroedinger") )
set_capability( "decoder", 200 )
set_callbacks( OpenDecoder, CloseDecoder )
add_shortcut( "schroedinger" )
/* encoder */
add_submodule()
set_section( N_("Encoding") , NULL )
set_description( N_("Dirac video encoder using libschroedinger") )
set_capability( "encoder", 110 )
set_callbacks( OpenEncoder, CloseEncoder )
add_shortcut( "schroedinger", "schro" )
add_string( ENC_CFG_PREFIX ENC_RATE_CONTROL, NULL,
ENC_RATE_CONTROL_TEXT, ENC_RATE_CONTROL_LONGTEXT, false )
change_string_list( enc_rate_control_list, enc_rate_control_list_text )
add_float( ENC_CFG_PREFIX ENC_QUALITY, -1.,
ENC_QUALITY_TEXT, ENC_QUALITY_LONGTEXT, false )
change_float_range(-1., 10.);
add_float( ENC_CFG_PREFIX ENC_NOISE_THRESHOLD, -1.,
ENC_NOISE_THRESHOLD_TEXT, ENC_NOISE_THRESHOLD_LONGTEXT, false )
change_float_range(-1., 100.);
add_integer( ENC_CFG_PREFIX ENC_BITRATE, -1,
ENC_BITRATE_TEXT, ENC_BITRATE_LONGTEXT, false )
change_integer_range(-1, INT_MAX);
add_integer( ENC_CFG_PREFIX ENC_MAX_BITRATE, -1,
ENC_MAX_BITRATE_TEXT, ENC_MAX_BITRATE_LONGTEXT, false )
change_integer_range(-1, INT_MAX);
add_integer( ENC_CFG_PREFIX ENC_MIN_BITRATE, -1,
ENC_MIN_BITRATE_TEXT, ENC_MIN_BITRATE_LONGTEXT, false )
change_integer_range(-1, INT_MAX);
add_string( ENC_CFG_PREFIX ENC_GOP_STRUCTURE, NULL,
ENC_GOP_STRUCTURE_TEXT, ENC_GOP_STRUCTURE_LONGTEXT, false )
change_string_list( enc_gop_structure_list, enc_gop_structure_list_text )
add_integer( ENC_CFG_PREFIX ENC_AU_DISTANCE, -1,
ENC_AU_DISTANCE_TEXT, ENC_AU_DISTANCE_LONGTEXT, false )
change_integer_range(-1, INT_MAX);
add_string( ENC_CFG_PREFIX ENC_CHROMAFMT, "420",
ENC_CHROMAFMT_TEXT, ENC_CHROMAFMT_LONGTEXT, false )
change_string_list( enc_chromafmt_list, enc_chromafmt_list_text )
add_string( ENC_CFG_PREFIX ENC_CODINGMODE, "auto",
ENC_CODINGMODE_TEXT, ENC_CODINGMODE_LONGTEXT, false )
change_string_list( enc_codingmode_list, enc_codingmode_list_text )
add_string( ENC_CFG_PREFIX ENC_MVPREC, NULL,
ENC_MVPREC_TEXT, ENC_MVPREC_LONGTEXT, false )
change_string_list( enc_mvprec_list, enc_mvprec_list )
/* advanced option only */
add_string( ENC_CFG_PREFIX ENC_MCBLK_SIZE, NULL,
ENC_MCBLK_SIZE_TEXT, ENC_MCBLK_SIZE_TEXT, true )
change_string_list( enc_block_size_list, enc_block_size_list_text )
/* advanced option only */
add_string( ENC_CFG_PREFIX ENC_MCBLK_OVERLAP, NULL,
ENC_MCBLK_OVERLAP_TEXT, ENC_MCBLK_OVERLAP_TEXT, true )
change_string_list( enc_block_overlap_list, enc_block_overlap_list_text )
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_ME_COMBINED, -1,
ENC_ME_COMBINED_TEXT, ENC_ME_COMBINED_LONGTEXT, true )
change_integer_range(-1, 1 );
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_ME_HIERARCHICAL, -1,
ENC_ME_HIERARCHICAL_TEXT, ENC_ME_HIERARCHICAL_TEXT, true )
change_integer_range(-1, 1 );
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_ME_DOWNSAMPLE_LEVELS, -1,
ENC_ME_DOWNSAMPLE_LEVELS_TEXT, ENC_ME_DOWNSAMPLE_LEVELS_LONGTEXT, true )
change_integer_range(-1, 8 );
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_ME_GLOBAL_MOTION, -1,
ENC_ME_GLOBAL_MOTION_TEXT, ENC_ME_GLOBAL_MOTION_TEXT, true )
change_integer_range(-1, 1 );
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_ME_PHASECORR, -1,
ENC_ME_PHASECORR_TEXT, ENC_ME_PHASECORR_TEXT, true )
change_integer_range(-1, 1 );
add_string( ENC_CFG_PREFIX ENC_DWTINTRA, NULL,
ENC_DWTINTRA_TEXT, ENC_DWTINTRA_TEXT, false )
change_string_list( enc_wavelet_list, enc_wavelet_list_text )
add_string( ENC_CFG_PREFIX ENC_DWTINTER, NULL,
ENC_DWTINTER_TEXT, ENC_DWTINTER_TEXT, false )
change_string_list( enc_wavelet_list, enc_wavelet_list_text )
add_integer( ENC_CFG_PREFIX ENC_DWTDEPTH, -1,
ENC_DWTDEPTH_TEXT, ENC_DWTDEPTH_LONGTEXT, false )
change_integer_range(-1, SCHRO_LIMIT_ENCODER_TRANSFORM_DEPTH );
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_MULTIQUANT, -1,
ENC_MULTIQUANT_TEXT, ENC_MULTIQUANT_LONGTEXT, true )
change_integer_range(-1, 1 );
/* advanced option only */
add_string( ENC_CFG_PREFIX ENC_SCBLK_SIZE, NULL,
ENC_SCBLK_SIZE_TEXT, ENC_SCBLK_SIZE_TEXT, true )
change_string_list( enc_codeblock_size_list, enc_codeblock_size_list_text )
add_string( ENC_CFG_PREFIX ENC_PREFILTER, NULL,
ENC_PREFILTER_TEXT, ENC_PREFILTER_LONGTEXT, false )
change_string_list( enc_filtering_list, enc_filtering_list_text )
add_float( ENC_CFG_PREFIX ENC_PREFILTER_STRENGTH, -1.,
ENC_PREFILTER_STRENGTH_TEXT, ENC_PREFILTER_STRENGTH_LONGTEXT, false )
change_float_range(-1., 100.0);
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_SCD, -1,
ENC_SCD_TEXT, ENC_SCD_TEXT, true )
change_integer_range(-1, 1 );
/* advanced option only */
add_string( ENC_CFG_PREFIX ENC_PWT, NULL,
ENC_PWT_TEXT, ENC_PWT_TEXT, true )
change_string_list( enc_perceptual_weighting_list, enc_perceptual_weighting_list )
/* advanced option only */
add_float( ENC_CFG_PREFIX ENC_PDIST, -1,
ENC_PDIST_TEXT, ENC_PDIST_LONGTEXT, true )
change_float_range(-1., 100.);
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_NOAC, -1,
ENC_NOAC_TEXT, ENC_NOAC_LONGTEXT, true )
change_integer_range(-1, 1 );
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_HSLICES, -1,
ENC_HSLICES_TEXT, ENC_HSLICES_LONGTEXT, true )
change_integer_range(-1, INT_MAX );
/* advanced option only */
add_integer( ENC_CFG_PREFIX ENC_VSLICES, -1,
ENC_VSLICES_TEXT, ENC_VSLICES_LONGTEXT, true )
change_integer_range(-1, INT_MAX );
/* advanced option only */
add_string( ENC_CFG_PREFIX ENC_FORCE_PROFILE, NULL,
ENC_FORCE_PROFILE_TEXT, ENC_FORCE_PROFILE_TEXT, true )
change_string_list( enc_profile_list, enc_profile_list_text )
vlc_module_end ()
/*****************************************************************************
* Local prototypes
*****************************************************************************/
static picture_t *DecodeBlock ( decoder_t *p_dec, block_t **pp_block );
static void Flush( decoder_t * );
struct picture_free_t
{
picture_t *p_pic;
decoder_t *p_dec;
};
/*****************************************************************************
* decoder_sys_t : Schroedinger decoder descriptor
*****************************************************************************/
struct decoder_sys_t
{
/*
* Dirac properties
*/
mtime_t i_lastpts;
mtime_t i_frame_pts_delta;
SchroDecoder *p_schro;
SchroVideoFormat *p_format;
};
/*****************************************************************************
* OpenDecoder: probe the decoder and return score
*****************************************************************************/
static int OpenDecoder( vlc_object_t *p_this )
{
decoder_t *p_dec = (decoder_t*)p_this;
decoder_sys_t *p_sys;
SchroDecoder *p_schro;
if( p_dec->fmt_in.i_codec != VLC_CODEC_DIRAC )
{
return VLC_EGENERIC;
}
/* Allocate the memory needed to store the decoder's structure */
p_sys = malloc(sizeof(decoder_sys_t));
if( p_sys == NULL )
return VLC_ENOMEM;
/* Initialise the schroedinger (and hence liboil libraries */
/* This does no allocation and is safe to call */
schro_init();
/* Initialise the schroedinger decoder */
if( !(p_schro = schro_decoder_new()) )
{
free( p_sys );
return VLC_EGENERIC;
}
p_dec->p_sys = p_sys;
p_sys->p_schro = p_schro;
p_sys->p_format = NULL;
p_sys->i_lastpts = VLC_TS_INVALID;
p_sys->i_frame_pts_delta = 0;
/* Set output properties */
p_dec->fmt_out.i_cat = VIDEO_ES;
p_dec->fmt_out.i_codec = VLC_CODEC_I420;
/* Set callbacks */
p_dec->pf_decode_video = DecodeBlock;
p_dec->pf_flush = Flush;
return VLC_SUCCESS;
}
/*****************************************************************************
* SetPictureFormat: Set the decoded picture params to the ones from the stream
*****************************************************************************/
static void SetVideoFormat( decoder_t *p_dec )
{
decoder_sys_t *p_sys = p_dec->p_sys;
p_sys->p_format = schro_decoder_get_video_format(p_sys->p_schro);
if( p_sys->p_format == NULL ) return;
p_sys->i_frame_pts_delta = CLOCK_FREQ
* p_sys->p_format->frame_rate_denominator
/ p_sys->p_format->frame_rate_numerator;
switch( p_sys->p_format->chroma_format )
{
case SCHRO_CHROMA_420: p_dec->fmt_out.i_codec = VLC_CODEC_I420; break;
case SCHRO_CHROMA_422: p_dec->fmt_out.i_codec = VLC_CODEC_I422; break;
case SCHRO_CHROMA_444: p_dec->fmt_out.i_codec = VLC_CODEC_I444; break;
default:
p_dec->fmt_out.i_codec = 0;
break;
}
p_dec->fmt_out.video.i_visible_width = p_sys->p_format->clean_width;
p_dec->fmt_out.video.i_x_offset = p_sys->p_format->left_offset;
p_dec->fmt_out.video.i_width = p_sys->p_format->width;
p_dec->fmt_out.video.i_visible_height = p_sys->p_format->clean_height;
p_dec->fmt_out.video.i_y_offset = p_sys->p_format->top_offset;
p_dec->fmt_out.video.i_height = p_sys->p_format->height;
/* aspect_ratio_[numerator|denominator] describes the pixel aspect ratio */
p_dec->fmt_out.video.i_sar_num = p_sys->p_format->aspect_ratio_numerator;
p_dec->fmt_out.video.i_sar_den = p_sys->p_format->aspect_ratio_denominator;
p_dec->fmt_out.video.i_frame_rate =
p_sys->p_format->frame_rate_numerator;
p_dec->fmt_out.video.i_frame_rate_base =
p_sys->p_format->frame_rate_denominator;
}
/*****************************************************************************
* SchroFrameFree: schro_frame callback to release the associated picture_t
* When schro_decoder_reset() is called there will be pictures in the
* decoding pipeline that need to be released rather than displayed.
*****************************************************************************/
static void SchroFrameFree( SchroFrame *frame, void *priv)
{
struct picture_free_t *p_free = priv;
if( !p_free )
return;
picture_Release( p_free->p_pic );
free(p_free);
(void)frame;
}
/*****************************************************************************
* CreateSchroFrameFromPic: wrap a picture_t in a SchroFrame
*****************************************************************************/
static SchroFrame *CreateSchroFrameFromPic( decoder_t *p_dec )
{
decoder_sys_t *p_sys = p_dec->p_sys;
SchroFrame *p_schroframe = schro_frame_new();
picture_t *p_pic = NULL;
struct picture_free_t *p_free;
if( !p_schroframe )
return NULL;
if( decoder_UpdateVideoFormat( p_dec ) )
return NULL;
p_pic = decoder_NewPicture( p_dec );
if( !p_pic )
return NULL;
p_schroframe->format = SCHRO_FRAME_FORMAT_U8_420;
if( p_sys->p_format->chroma_format == SCHRO_CHROMA_422 )
{
p_schroframe->format = SCHRO_FRAME_FORMAT_U8_422;
}
else if( p_sys->p_format->chroma_format == SCHRO_CHROMA_444 )
{
p_schroframe->format = SCHRO_FRAME_FORMAT_U8_444;
}
p_schroframe->width = p_sys->p_format->width;
p_schroframe->height = p_sys->p_format->height;
p_free = malloc( sizeof( *p_free ) );
p_free->p_pic = p_pic;
p_free->p_dec = p_dec;
schro_frame_set_free_callback( p_schroframe, SchroFrameFree, p_free );
for( int i=0; i<3; i++ )
{
p_schroframe->components[i].width = p_pic->p[i].i_visible_pitch;
p_schroframe->components[i].stride = p_pic->p[i].i_pitch;
p_schroframe->components[i].height = p_pic->p[i].i_visible_lines;
p_schroframe->components[i].length =
p_pic->p[i].i_pitch * p_pic->p[i].i_lines;
p_schroframe->components[i].data = p_pic->p[i].p_pixels;
if(i!=0)
{
p_schroframe->components[i].v_shift =
SCHRO_FRAME_FORMAT_V_SHIFT( p_schroframe->format );
p_schroframe->components[i].h_shift =
SCHRO_FRAME_FORMAT_H_SHIFT( p_schroframe->format );
}
}
p_pic->b_progressive = !p_sys->p_format->interlaced;
p_pic->b_top_field_first = p_sys->p_format->top_field_first;
p_pic->i_nb_fields = 2;
return p_schroframe;
}
/*****************************************************************************
* SchroBufferFree: schro_buffer callback to release the associated block_t
*****************************************************************************/
static void SchroBufferFree( SchroBuffer *buf, void *priv )
{
block_t *p_block = priv;
if( !p_block )
return;
block_Release( p_block );
(void)buf;
}
/*****************************************************************************
* CloseDecoder: decoder destruction
*****************************************************************************/
static void CloseDecoder( vlc_object_t *p_this )
{
decoder_t *p_dec = (decoder_t *)p_this;
decoder_sys_t *p_sys = p_dec->p_sys;
schro_decoder_free( p_sys->p_schro );
free( p_sys );
}
/*****************************************************************************
* Flush:
*****************************************************************************/
static void Flush( decoder_t *p_dec )
{
decoder_sys_t *p_sys = p_dec->p_sys;
schro_decoder_reset( p_sys->p_schro );
p_sys->i_lastpts = VLC_TS_INVALID;
}
/****************************************************************************
* DecodeBlock: the whole thing
****************************************************************************
* Blocks need not be Dirac dataunit aligned.
* If a block has a PTS signaled, it applies to the first picture at or after p_block
*
* If this function returns a picture (!NULL), it is called again and the
* same block is resubmitted. To avoid this, set *pp_block to NULL;
* If this function returns NULL, the *pp_block is lost (and leaked).
* This function must free all blocks when finished with them.
****************************************************************************/
static picture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
{
decoder_sys_t *p_sys = p_dec->p_sys;
if( !pp_block ) return NULL;
if ( *pp_block ) {
block_t *p_block = *pp_block;
/* reset the decoder when seeking as the decode in progress is invalid */
/* discard the block as it is just a null magic block */
if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY | BLOCK_FLAG_CORRUPTED) ) {
Flush( p_dec );
block_Release( p_block );
*pp_block = NULL;
return NULL;
}
SchroBuffer *p_schrobuffer;
p_schrobuffer = schro_buffer_new_with_data( p_block->p_buffer, p_block->i_buffer );
p_schrobuffer->free = SchroBufferFree;
p_schrobuffer->priv = p_block;
if( p_block->i_pts > VLC_TS_INVALID ) {
mtime_t *p_pts = malloc( sizeof(*p_pts) );
if( p_pts ) {
*p_pts = p_block->i_pts;
/* if this call fails, p_pts is freed automatically */
p_schrobuffer->tag = schro_tag_new( p_pts, free );
}
}
/* this stops the same block being fed back into this function if
* we were on the next iteration of this loop to output a picture */
*pp_block = NULL;
schro_decoder_autoparse_push( p_sys->p_schro, p_schrobuffer );
/* DO NOT refer to p_block after this point, it may have been freed */
}
while( 1 )
{
SchroFrame *p_schroframe;
picture_t *p_pic;
int state = schro_decoder_autoparse_wait( p_sys->p_schro );
switch( state )
{
case SCHRO_DECODER_FIRST_ACCESS_UNIT:
SetVideoFormat( p_dec );
break;
case SCHRO_DECODER_NEED_BITS:
return NULL;
case SCHRO_DECODER_NEED_FRAME:
p_schroframe = CreateSchroFrameFromPic( p_dec );
if( !p_schroframe )
{
msg_Err( p_dec, "Could not allocate picture for decoder");
return NULL;
}
schro_decoder_add_output_picture( p_sys->p_schro, p_schroframe);
break;
case SCHRO_DECODER_OK: {
SchroTag *p_tag = schro_decoder_get_picture_tag( p_sys->p_schro );
p_schroframe = schro_decoder_pull( p_sys->p_schro );
if( !p_schroframe || !p_schroframe->priv )
{
/* frame can't be one that was allocated by us
* -- no private data: discard */
if( p_tag ) schro_tag_free( p_tag );
if( p_schroframe ) schro_frame_unref( p_schroframe );
break;
}
p_pic = ((struct picture_free_t*) p_schroframe->priv)->p_pic;
p_schroframe->priv = NULL;
if( p_tag )
{
/* free is handled by schro_frame_unref */
p_pic->date = *(mtime_t*) p_tag->value;
schro_tag_free( p_tag );
}
else if( p_sys->i_lastpts > VLC_TS_INVALID )
{
/* NB, this shouldn't happen since the packetizer does a
* very thorough job of inventing timestamps. The
* following is just a very rough fall back incase packetizer
* is missing. */
/* maybe it would be better to set p_pic->b_force ? */
p_pic->date = p_sys->i_lastpts + p_sys->i_frame_pts_delta;
}
p_sys->i_lastpts = p_pic->date;
schro_frame_unref( p_schroframe );
return p_pic;
}
case SCHRO_DECODER_EOS:
/* NB, the new api will not emit _EOS, it handles the reset internally */
break;
case SCHRO_DECODER_ERROR:
msg_Err( p_dec, "SCHRO_DECODER_ERROR");
return NULL;
}
}
}
/*****************************************************************************
* Local prototypes
*****************************************************************************/
static block_t *Encode( encoder_t *p_enc, picture_t *p_pict );
/*****************************************************************************
* picture_pts_t : store pts alongside picture number, not carried through
* encoder
*****************************************************************************/
struct picture_pts_t
{
mtime_t i_pts; /* associated pts */
uint32_t u_pnum; /* dirac picture number */
bool b_empty; /* entry is invalid */
};
/*****************************************************************************
* encoder_sys_t : Schroedinger encoder descriptor
*****************************************************************************/
#define SCHRO_PTS_TLB_SIZE 256
struct encoder_sys_t
{
/*
* Schro properties
*/
SchroEncoder *p_schro;
SchroVideoFormat *p_format;
int started;
bool b_auto_field_coding;
uint32_t i_input_picnum;
block_fifo_t *p_dts_fifo;
block_t *p_chain;
struct picture_pts_t pts_tlb[SCHRO_PTS_TLB_SIZE];
mtime_t i_pts_offset;
mtime_t i_field_time;
bool b_eos_signalled;
bool b_eos_pulled;
};
static struct
{
unsigned int i_height;
int i_approx_fps;
SchroVideoFormatEnum i_vf;
} schro_format_guess[] = {
/* Important: Keep this list ordered in ascending picture height */
{1, 0, SCHRO_VIDEO_FORMAT_CUSTOM},
{120, 15, SCHRO_VIDEO_FORMAT_QSIF},
{144, 12, SCHRO_VIDEO_FORMAT_QCIF},
{240, 15, SCHRO_VIDEO_FORMAT_SIF},
{288, 12, SCHRO_VIDEO_FORMAT_CIF},
{480, 30, SCHRO_VIDEO_FORMAT_SD480I_60},
{480, 15, SCHRO_VIDEO_FORMAT_4SIF},
{576, 12, SCHRO_VIDEO_FORMAT_4CIF},
{576, 25, SCHRO_VIDEO_FORMAT_SD576I_50},
{720, 50, SCHRO_VIDEO_FORMAT_HD720P_50},
{720, 60, SCHRO_VIDEO_FORMAT_HD720P_60},
{1080, 24, SCHRO_VIDEO_FORMAT_DC2K_24},
{1080, 25, SCHRO_VIDEO_FORMAT_HD1080I_50},
{1080, 30, SCHRO_VIDEO_FORMAT_HD1080I_60},
{1080, 50, SCHRO_VIDEO_FORMAT_HD1080P_50},
{1080, 60, SCHRO_VIDEO_FORMAT_HD1080P_60},
{2160, 24, SCHRO_VIDEO_FORMAT_DC4K_24},
{0, 0, 0},
};
/*****************************************************************************
* ResetPTStlb: Purge all entries in @p_enc@'s PTS-tlb
*****************************************************************************/
static void ResetPTStlb( encoder_t *p_enc )
{
encoder_sys_t *p_sys = p_enc->p_sys;
for( int i = 0; i < SCHRO_PTS_TLB_SIZE; i++ )
{
p_sys->pts_tlb[i].b_empty = true;
}
}
/*****************************************************************************
* StorePicturePTS: Store the PTS value for a particular picture number
*****************************************************************************/
static void StorePicturePTS( encoder_t *p_enc, uint32_t u_pnum, mtime_t i_pts )
{
encoder_sys_t *p_sys = p_enc->p_sys;
for( int i = 0; i<SCHRO_PTS_TLB_SIZE; i++ )
{
if( p_sys->pts_tlb[i].b_empty )
{
p_sys->pts_tlb[i].u_pnum = u_pnum;
p_sys->pts_tlb[i].i_pts = i_pts;
p_sys->pts_tlb[i].b_empty = false;
return;
}
}
msg_Err( p_enc, "Could not store PTS %"PRId64" for frame %u", i_pts, u_pnum );
}
/*****************************************************************************
* GetPicturePTS: Retrieve the PTS value for a particular picture number
*****************************************************************************/
static mtime_t GetPicturePTS( encoder_t *p_enc, uint32_t u_pnum )
{
encoder_sys_t *p_sys = p_enc->p_sys;
for( int i = 0; i < SCHRO_PTS_TLB_SIZE; i++ )
{
if( !p_sys->pts_tlb[i].b_empty &&
p_sys->pts_tlb[i].u_pnum == u_pnum )
{
p_sys->pts_tlb[i].b_empty = true;
return p_sys->pts_tlb[i].i_pts;
}
}
msg_Err( p_enc, "Could not retrieve PTS for picture %u", u_pnum );
return 0;
}
static inline bool SchroSetEnum( const encoder_t *p_enc, int i_list_size, const char *list[],
const char *psz_name, const char *psz_name_text, const char *psz_value)
{
encoder_sys_t *p_sys = p_enc->p_sys;
if( list && psz_name_text && psz_name && psz_value ) {
for( int i = 0; i < i_list_size; ++i ) {
if( strcmp( list[i], psz_value ) )
continue;
schro_encoder_setting_set_double( p_sys->p_schro, psz_name, i );
return true;
}
msg_Err( p_enc, "Invalid %s: %s", psz_name_text, psz_value );
}
return false;
}
static bool SetEncChromaFormat( encoder_t *p_enc, uint32_t i_codec )
{
encoder_sys_t *p_sys = p_enc->p_sys;
switch( i_codec ) {
case VLC_CODEC_I420:
p_enc->fmt_in.i_codec = i_codec;
p_enc->fmt_in.video.i_bits_per_pixel = 12;
p_sys->p_format->chroma_format = SCHRO_CHROMA_420;
break;
case VLC_CODEC_I422:
p_enc->fmt_in.i_codec = i_codec;
p_enc->fmt_in.video.i_bits_per_pixel = 16;
p_sys->p_format->chroma_format = SCHRO_CHROMA_422;
break;
case VLC_CODEC_I444:
p_enc->fmt_in.i_codec = i_codec;
p_enc->fmt_in.video.i_bits_per_pixel = 24;
p_sys->p_format->chroma_format = SCHRO_CHROMA_444;
break;
default:
return false;
}
return true;
}
#define SCHRO_SET_FLOAT(psz_name, pschro_name) \
f_tmp = var_GetFloat( p_enc, ENC_CFG_PREFIX psz_name ); \
if( f_tmp >= 0.0 ) \
schro_encoder_setting_set_double( p_sys->p_schro, pschro_name, f_tmp );
#define SCHRO_SET_INTEGER(psz_name, pschro_name, ignore_val) \
i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX psz_name ); \
if( i_tmp > ignore_val ) \
schro_encoder_setting_set_double( p_sys->p_schro, pschro_name, i_tmp );
#define SCHRO_SET_ENUM(list, psz_name, psz_name_text, pschro_name) \
psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX psz_name ); \
if( !psz_tmp ) \
goto error; \
else if ( *psz_tmp != '\0' ) { \
int i_list_size = ARRAY_SIZE(list); \
if( !SchroSetEnum( p_enc, i_list_size, list, pschro_name, psz_name_text, psz_tmp ) ) { \
free( psz_tmp ); \
goto error; \
} \
} \
free( psz_tmp );
/*****************************************************************************
* OpenEncoder: probe the encoder and return score
*****************************************************************************/
static int OpenEncoder( vlc_object_t *p_this )
{
encoder_t *p_enc = (encoder_t *)p_this;
encoder_sys_t *p_sys;
int i_tmp;
float f_tmp;
char *psz_tmp;
if( p_enc->fmt_out.i_codec != VLC_CODEC_DIRAC &&
!p_enc->obj.force )
{
return VLC_EGENERIC;
}
if( !p_enc->fmt_in.video.i_frame_rate || !p_enc->fmt_in.video.i_frame_rate_base ||
!p_enc->fmt_in.video.i_visible_height || !p_enc->fmt_in.video.i_visible_width )
{
msg_Err( p_enc, "Framerate and picture dimensions must be non-zero" );
return VLC_EGENERIC;
}
/* Allocate the memory needed to store the decoder's structure */
if( ( p_sys = calloc( 1, sizeof( *p_sys ) ) ) == NULL )
return VLC_ENOMEM;
p_enc->p_sys = p_sys;
p_enc->pf_encode_video = Encode;
p_enc->fmt_out.i_codec = VLC_CODEC_DIRAC;
p_enc->fmt_out.i_cat = VIDEO_ES;
if( ( p_sys->p_dts_fifo = block_FifoNew() ) == NULL )
{
CloseEncoder( p_this );
return VLC_ENOMEM;
}
ResetPTStlb( p_enc );
/* guess the video format based upon number of lines and picture height */
int i = 0;
SchroVideoFormatEnum guessed_video_fmt = SCHRO_VIDEO_FORMAT_CUSTOM;
/* Pick the dirac_video_format in this order of preference:
* 1. an exact match in frame height and an approximate fps match
* 2. the previous preset with a smaller number of lines.
*/
do
{
if( schro_format_guess[i].i_height > p_enc->fmt_in.video.i_height )
{
guessed_video_fmt = schro_format_guess[i-1].i_vf;
break;
}
if( schro_format_guess[i].i_height != p_enc->fmt_in.video.i_height )
continue;
int src_fps = p_enc->fmt_in.video.i_frame_rate / p_enc->fmt_in.video.i_frame_rate_base;
int delta_fps = abs( schro_format_guess[i].i_approx_fps - src_fps );
if( delta_fps > 2 )
continue;
guessed_video_fmt = schro_format_guess[i].i_vf;
break;
} while( schro_format_guess[++i].i_height );
schro_init();
p_sys->p_schro = schro_encoder_new();
if( !p_sys->p_schro ) {
msg_Err( p_enc, "Failed to initialize libschroedinger encoder" );
return VLC_EGENERIC;
}
schro_encoder_set_packet_assembly( p_sys->p_schro, true );
if( !( p_sys->p_format = schro_encoder_get_video_format( p_sys->p_schro ) ) ) {
msg_Err( p_enc, "Failed to get Schroedigner video format" );
schro_encoder_free( p_sys->p_schro );
return VLC_EGENERIC;
}
/* initialise the video format parameters to the guessed format */
schro_video_format_set_std_video_format( p_sys->p_format, guessed_video_fmt );
/* constants set from the input video format */
p_sys->p_format->width = p_enc->fmt_in.video.i_visible_width;
p_sys->p_format->height = p_enc->fmt_in.video.i_visible_height;
p_sys->p_format->frame_rate_numerator = p_enc->fmt_in.video.i_frame_rate;
p_sys->p_format->frame_rate_denominator = p_enc->fmt_in.video.i_frame_rate_base;
unsigned u_asr_num, u_asr_den;
vlc_ureduce( &u_asr_num, &u_asr_den,
p_enc->fmt_in.video.i_sar_num,
p_enc->fmt_in.video.i_sar_den, 0 );
p_sys->p_format->aspect_ratio_numerator = u_asr_num;
p_sys->p_format->aspect_ratio_denominator = u_asr_den;
config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
SCHRO_SET_ENUM(enc_rate_control_list, ENC_RATE_CONTROL, ENC_RATE_CONTROL_TEXT, "rate_control")
SCHRO_SET_ENUM(enc_gop_structure_list, ENC_GOP_STRUCTURE, ENC_GOP_STRUCTURE_TEXT, "gop_structure")
psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX ENC_CHROMAFMT );
if( !psz_tmp )
goto error;
else {
uint32_t i_codec;
if( !strcmp( psz_tmp, "420" ) ) {
i_codec = VLC_CODEC_I420;
}
else if( !strcmp( psz_tmp, "422" ) ) {
i_codec = VLC_CODEC_I422;
}
else if( !strcmp( psz_tmp, "444" ) ) {
i_codec = VLC_CODEC_I444;
}
else {
msg_Err( p_enc, "Invalid chroma format: %s", psz_tmp );
free( psz_tmp );
goto error;
}
SetEncChromaFormat( p_enc, i_codec );
}
free( psz_tmp );
SCHRO_SET_FLOAT(ENC_QUALITY, "quality")
SCHRO_SET_FLOAT(ENC_NOISE_THRESHOLD, "noise_threshold")
/* use bitrate from sout-transcode-vb in kbps */
i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX ENC_BITRATE );
if( i_tmp > -1 )
schro_encoder_setting_set_double( p_sys->p_schro, "bitrate", i_tmp * 1000 );
else
schro_encoder_setting_set_double( p_sys->p_schro, "bitrate", p_enc->fmt_out.i_bitrate );
p_enc->fmt_out.i_bitrate = schro_encoder_setting_get_double( p_sys->p_schro, "bitrate" );
i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX ENC_MIN_BITRATE );
if( i_tmp > -1 )
schro_encoder_setting_set_double( p_sys->p_schro, "min_bitrate", i_tmp * 1000 );
i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX ENC_MAX_BITRATE );
if( i_tmp > -1 )
schro_encoder_setting_set_double( p_sys->p_schro, "max_bitrate", i_tmp * 1000 );
SCHRO_SET_INTEGER(ENC_AU_DISTANCE, "au_distance", -1)
SCHRO_SET_ENUM(enc_filtering_list, ENC_PREFILTER, ENC_PREFILTER_TEXT, "filtering")
SCHRO_SET_FLOAT(ENC_PREFILTER_STRENGTH, "filter_value")
psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX ENC_CODINGMODE );
if( !psz_tmp )
goto error;
else if( !strcmp( psz_tmp, "auto" ) ) {
p_sys->b_auto_field_coding = true;
}
else if( !strcmp( psz_tmp, "progressive" ) ) {
p_sys->b_auto_field_coding = false;
schro_encoder_setting_set_double( p_sys->p_schro, "interlaced_coding", false);
}
else if( !strcmp( psz_tmp, "field" ) ) {
p_sys->b_auto_field_coding = false;
schro_encoder_setting_set_double( p_sys->p_schro, "interlaced_coding", true);
}
else {
msg_Err( p_enc, "Invalid codingmode: %s", psz_tmp );
free( psz_tmp );
goto error;
}
free( psz_tmp );
SCHRO_SET_ENUM(enc_block_size_list, ENC_MCBLK_SIZE, ENC_MCBLK_SIZE_TEXT, "motion_block_size")
SCHRO_SET_ENUM(enc_block_overlap_list, ENC_MCBLK_OVERLAP, ENC_MCBLK_OVERLAP_TEXT, "motion_block_overlap")
psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX ENC_MVPREC );
if( !psz_tmp )
goto error;
else if( *psz_tmp != '\0') {
if( !strcmp( psz_tmp, "1" ) ) {
schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 0 );
}
else if( !strcmp( psz_tmp, "1/2" ) ) {
schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 1 );
}
else if( !strcmp( psz_tmp, "1/4" ) ) {
schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 2 );
}
else if( !strcmp( psz_tmp, "1/8" ) ) {
schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 3 );
}
else {
msg_Err( p_enc, "Invalid mv_precision: %s", psz_tmp );
free( psz_tmp );
goto error;
}
}
free( psz_tmp );
SCHRO_SET_INTEGER(ENC_ME_COMBINED, "enable_chroma_me", -1)
SCHRO_SET_ENUM(enc_wavelet_list, ENC_DWTINTRA, ENC_DWTINTRA_TEXT, "intra_wavelet")
SCHRO_SET_ENUM(enc_wavelet_list, ENC_DWTINTER, ENC_DWTINTER_TEXT, "inter_wavelet")
SCHRO_SET_INTEGER(ENC_DWTDEPTH, "transform_depth", -1)
SCHRO_SET_INTEGER(ENC_MULTIQUANT, "enable_multiquant", -1)
SCHRO_SET_INTEGER(ENC_NOAC, "enable_noarith", -1)
SCHRO_SET_ENUM(enc_perceptual_weighting_list, ENC_PWT, ENC_PWT_TEXT, "perceptual_weighting")
SCHRO_SET_FLOAT(ENC_PDIST, "perceptual_distance")
SCHRO_SET_INTEGER(ENC_HSLICES, "horiz_slices", -1)
SCHRO_SET_INTEGER(ENC_VSLICES, "vert_slices", -1)
SCHRO_SET_ENUM(enc_codeblock_size_list, ENC_SCBLK_SIZE, ENC_SCBLK_SIZE_TEXT, "codeblock_size")
SCHRO_SET_INTEGER(ENC_ME_HIERARCHICAL, "enable_hierarchical_estimation", -1)
SCHRO_SET_INTEGER(ENC_ME_DOWNSAMPLE_LEVELS, "downsample_levels", 1)
SCHRO_SET_INTEGER(ENC_ME_GLOBAL_MOTION, "enable_global_motion", -1)
SCHRO_SET_INTEGER(ENC_ME_PHASECORR, "enable_phasecorr_estimation", -1)
SCHRO_SET_INTEGER(ENC_SCD, "enable_scene_change_detection", -1)
SCHRO_SET_ENUM(enc_profile_list, ENC_FORCE_PROFILE, ENC_FORCE_PROFILE_TEXT, "force_profile")
p_sys->started = 0;
return VLC_SUCCESS;
error:
CloseEncoder( p_this );
return VLC_EGENERIC;
}
struct enc_picture_free_t
{
picture_t *p_pic;
encoder_t *p_enc;
};
/*****************************************************************************
* EncSchroFrameFree: schro_frame callback to release the associated picture_t
* When schro_encoder_reset() is called there will be pictures in the
* encoding pipeline that need to be released rather than displayed.
*****************************************************************************/
static void EncSchroFrameFree( SchroFrame *frame, void *priv )
{
struct enc_picture_free_t *p_free = priv;
if( !p_free )
return;
picture_Release( p_free->p_pic );
free( p_free );
(void)frame;
}
/*****************************************************************************
* CreateSchroFrameFromPic: wrap a picture_t in a SchroFrame
*****************************************************************************/
static SchroFrame *CreateSchroFrameFromInputPic( encoder_t *p_enc, picture_t *p_pic )
{
encoder_sys_t *p_sys = p_enc->p_sys;
SchroFrame *p_schroframe = schro_frame_new();
struct enc_picture_free_t *p_free;
if( !p_schroframe )
return NULL;
if( !p_pic )
return NULL;
p_schroframe->format = SCHRO_FRAME_FORMAT_U8_420;
if( p_sys->p_format->chroma_format == SCHRO_CHROMA_422 )
{
p_schroframe->format = SCHRO_FRAME_FORMAT_U8_422;
}
else if( p_sys->p_format->chroma_format == SCHRO_CHROMA_444 )
{
p_schroframe->format = SCHRO_FRAME_FORMAT_U8_444;
}
p_schroframe->width = p_sys->p_format->width;
p_schroframe->height = p_sys->p_format->height;
p_free = malloc( sizeof( *p_free ) );
if( unlikely( p_free == NULL ) ) {
schro_frame_unref( p_schroframe );
return NULL;
}
p_free->p_pic = p_pic;
p_free->p_enc = p_enc;
schro_frame_set_free_callback( p_schroframe, EncSchroFrameFree, p_free );
for( int i=0; i<3; i++ )
{
p_schroframe->components[i].width = p_pic->p[i].i_visible_pitch;
p_schroframe->components[i].stride = p_pic->p[i].i_pitch;
p_schroframe->components[i].height = p_pic->p[i].i_visible_lines;
p_schroframe->components[i].length =
p_pic->p[i].i_pitch * p_pic->p[i].i_lines;
p_schroframe->components[i].data = p_pic->p[i].p_pixels;
if( i!=0 )
{
p_schroframe->components[i].v_shift =
SCHRO_FRAME_FORMAT_V_SHIFT( p_schroframe->format );
p_schroframe->components[i].h_shift =
SCHRO_FRAME_FORMAT_H_SHIFT( p_schroframe->format );
}
}
return p_schroframe;
}
/* Attempt to find dirac picture number in an encapsulation unit */
static int ReadDiracPictureNumber( uint32_t *p_picnum, block_t *p_block )
{
uint32_t u_pos = 4;
/* protect against falling off the edge */
while( u_pos + 13 < p_block->i_buffer )
{
/* find the picture startcode */
if( p_block->p_buffer[u_pos] & 0x08 )
{
*p_picnum = GetDWBE( p_block->p_buffer + u_pos + 9 );
return 1;
}
/* skip to the next dirac data unit */
uint32_t u_npo = GetDWBE( p_block->p_buffer + u_pos + 1 );
assert( u_npo <= UINT32_MAX - u_pos );
if( u_npo == 0 )
u_npo = 13;
u_pos += u_npo;
}
return 0;
}
static block_t *Encode( encoder_t *p_enc, picture_t *p_pic )
{
encoder_sys_t *p_sys = p_enc->p_sys;
block_t *p_block, *p_output_chain = NULL;
SchroFrame *p_frame;
bool b_go = true;
if( !p_pic ) {
if( !p_sys->started || p_sys->b_eos_pulled )
return NULL;
if( !p_sys->b_eos_signalled ) {
p_sys->b_eos_signalled = 1;
schro_encoder_end_of_stream( p_sys->p_schro );
}
} else {
/* we only know if the sequence is interlaced when the first
* picture arrives, so final setup is done here */
/* XXX todo, detect change of interlace */
p_sys->p_format->interlaced = !p_pic->b_progressive;
p_sys->p_format->top_field_first = p_pic->b_top_field_first;
if( p_sys->b_auto_field_coding )
schro_encoder_setting_set_double( p_sys->p_schro, "interlaced_coding", !p_pic->b_progressive );
}
if( !p_sys->started ) {
date_t date;
if( p_pic->format.i_chroma != p_enc->fmt_in.i_codec ) {
char chroma_in[5], chroma_out[5];
vlc_fourcc_to_char( p_pic->format.i_chroma, chroma_in );
chroma_in[4] = '\0';
chroma_out[4] = '\0';
vlc_fourcc_to_char( p_enc->fmt_in.i_codec, chroma_out );
msg_Warn( p_enc, "Resetting chroma from %s to %s", chroma_out, chroma_in );
if( !SetEncChromaFormat( p_enc, p_pic->format.i_chroma ) ) {
msg_Err( p_enc, "Could not reset chroma format to %s", chroma_in );
return NULL;
}
}
date_Init( &date, p_enc->fmt_in.video.i_frame_rate, p_enc->fmt_in.video.i_frame_rate_base );
/* FIXME - Unlike dirac-research codec Schro doesn't have a function that returns the delay in pics yet.
* Use a default of 1
*/
date_Increment( &date, 1 );
p_sys->i_pts_offset = date_Get( &date );
if( schro_encoder_setting_get_double( p_sys->p_schro, "interlaced_coding" ) > 0.0 ) {
date_Set( &date, 0 );
date_Increment( &date, 1);
p_sys->i_field_time = date_Get( &date ) / 2;
}
schro_video_format_set_std_signal_range( p_sys->p_format, SCHRO_SIGNAL_RANGE_8BIT_VIDEO );
schro_encoder_set_video_format( p_sys->p_schro, p_sys->p_format );
schro_encoder_start( p_sys->p_schro );
p_sys->started = 1;
}
if( !p_sys->b_eos_signalled ) {
/* create a schro frame from the input pic and load */
/* Increase ref count by 1 so that the picture is not freed until
Schro finishes with it */
picture_Hold( p_pic );
p_frame = CreateSchroFrameFromInputPic( p_enc, p_pic );
if( !p_frame )
return NULL;
schro_encoder_push_frame( p_sys->p_schro, p_frame );
/* store pts in a lookaside buffer, so that the same pts may
* be used for the picture in coded order */
StorePicturePTS( p_enc, p_sys->i_input_picnum, p_pic->date );
p_sys->i_input_picnum++;
/* store dts in a queue, so that they appear in order in
* coded order */
p_block = block_Alloc( 1 );
if( !p_block )
return NULL;
p_block->i_dts = p_pic->date - p_sys->i_pts_offset;
block_FifoPut( p_sys->p_dts_fifo, p_block );
p_block = NULL;
/* for field coding mode, insert an extra value into both the
* pts lookaside buffer and dts queue, offset to correspond
* to a one field delay. */
if( schro_encoder_setting_get_double( p_sys->p_schro, "interlaced_coding" ) > 0.0 ) {
StorePicturePTS( p_enc, p_sys->i_input_picnum, p_pic->date + p_sys->i_field_time );
p_sys->i_input_picnum++;
p_block = block_Alloc( 1 );
if( !p_block )
return NULL;
p_block->i_dts = p_pic->date - p_sys->i_pts_offset + p_sys->i_field_time;
block_FifoPut( p_sys->p_dts_fifo, p_block );
p_block = NULL;
}
}
do
{
SchroStateEnum state;
state = schro_encoder_wait( p_sys->p_schro );
switch( state )
{
case SCHRO_STATE_NEED_FRAME:
b_go = false;
break;
case SCHRO_STATE_AGAIN:
break;
case SCHRO_STATE_END_OF_STREAM:
p_sys->b_eos_pulled = 1;
b_go = false;
break;
case SCHRO_STATE_HAVE_BUFFER:
{
SchroBuffer *p_enc_buf;
uint32_t u_pic_num;
int i_presentation_frame;
p_enc_buf = schro_encoder_pull( p_sys->p_schro, &i_presentation_frame );
p_block = block_Alloc( p_enc_buf->length );
if( !p_block )
return NULL;
memcpy( p_block->p_buffer, p_enc_buf->data, p_enc_buf->length );
schro_buffer_unref( p_enc_buf );
/* Presence of a Sequence header indicates a seek point */
if( 0 == p_block->p_buffer[4] )
{
p_block->i_flags |= BLOCK_FLAG_TYPE_I;
if( !p_enc->fmt_out.p_extra ) {
const uint8_t eos[] = { 'B','B','C','D',0x10,0,0,0,13,0,0,0,0 };
uint32_t len = GetDWBE( p_block->p_buffer + 5 );
/* if it hasn't been done so far, stash a copy of the
* sequence header for muxers such as ogg */
/* The OggDirac spec advises that a Dirac EOS DataUnit
* is appended to the sequence header to allow guard
* against poor streaming servers */
/* XXX, should this be done using the packetizer ? */
if( len > UINT32_MAX - sizeof( eos ) )
return NULL;
p_enc->fmt_out.p_extra = malloc( len + sizeof( eos ) );
if( !p_enc->fmt_out.p_extra )
return NULL;
memcpy( p_enc->fmt_out.p_extra, p_block->p_buffer, len );
memcpy( (uint8_t*)p_enc->fmt_out.p_extra + len, eos, sizeof( eos ) );
SetDWBE( (uint8_t*)p_enc->fmt_out.p_extra + len + sizeof(eos) - 4, len );
p_enc->fmt_out.i_extra = len + sizeof( eos );
}
}
if( ReadDiracPictureNumber( &u_pic_num, p_block ) ) {
block_t *p_dts_block = block_FifoGet( p_sys->p_dts_fifo );
p_block->i_dts = p_dts_block->i_dts;
p_block->i_pts = GetPicturePTS( p_enc, u_pic_num );
block_Release( p_dts_block );
block_ChainAppend( &p_output_chain, p_block );
} else {
/* End of sequence */
block_ChainAppend( &p_output_chain, p_block );
}
break;
}
default:
break;
}
} while( b_go );
return p_output_chain;
}
/*****************************************************************************
* CloseEncoder: Schro encoder destruction
*****************************************************************************/
static void CloseEncoder( vlc_object_t *p_this )
{
encoder_t *p_enc = (encoder_t *)p_this;
encoder_sys_t *p_sys = p_enc->p_sys;
/* Free the encoder resources */
if( p_sys->p_schro )
schro_encoder_free( p_sys->p_schro );
free( p_sys->p_format );
if( p_sys->p_dts_fifo )
block_FifoRelease( p_sys->p_dts_fifo );
block_ChainRelease( p_sys->p_chain );
free( p_sys );
}
| xkfz007/vlc | modules/codec/schroedinger.c | C | lgpl-2.1 | 57,647 |
/**
******************************************************************************
* @file stm32wbxx_hal_pcd_ex.c
* @author MCD Application Team
* @brief PCD Extended HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the USB Peripheral Controller:
* + Extended features functions
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32wbxx_hal.h"
/** @addtogroup STM32WBxx_HAL_Driver
* @{
*/
/** @defgroup PCDEx PCDEx
* @brief PCD Extended HAL module driver
* @{
*/
#ifdef HAL_PCD_MODULE_ENABLED
#if defined (USB)
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup PCDEx_Exported_Functions PCDEx Exported Functions
* @{
*/
/** @defgroup PCDEx_Exported_Functions_Group1 Peripheral Control functions
* @brief PCDEx control functions
*
@verbatim
===============================================================================
##### Extended features functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Update FIFO configuration
@endverbatim
* @{
*/
/**
* @brief Configure PMA for EP
* @param hpcd Device instance
* @param ep_addr endpoint address
* @param ep_kind endpoint Kind
* USB_SNG_BUF: Single Buffer used
* USB_DBL_BUF: Double Buffer used
* @param pmaadress: EP address in The PMA: In case of single buffer endpoint
* this parameter is 16-bit value providing the address
* in PMA allocated to endpoint.
* In case of double buffer endpoint this parameter
* is a 32-bit value providing the endpoint buffer 0 address
* in the LSB part of 32-bit value and endpoint buffer 1 address
* in the MSB part of 32-bit value.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd,
uint16_t ep_addr,
uint16_t ep_kind,
uint32_t pmaadress)
{
PCD_EPTypeDef *ep;
/* initialize ep structure*/
if ((0x80U & ep_addr) == 0x80U)
{
ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK];
}
else
{
ep = &hpcd->OUT_ep[ep_addr];
}
/* Here we check if the endpoint is single or double Buffer*/
if (ep_kind == PCD_SNG_BUF)
{
/* Single Buffer */
ep->doublebuffer = 0U;
/* Configure the PMA */
ep->pmaadress = (uint16_t)pmaadress;
}
else /* USB_DBL_BUF */
{
/* Double Buffer Endpoint */
ep->doublebuffer = 1U;
/* Configure the PMA */
ep->pmaaddr0 = (uint16_t)(pmaadress & 0xFFFFU);
ep->pmaaddr1 = (uint16_t)((pmaadress & 0xFFFF0000U) >> 16);
}
return HAL_OK;
}
/**
* @brief Activate BatteryCharging feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_ActivateBCD(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->battery_charging_active = 1U;
/* Enable BCD feature */
USBx->BCDR |= USB_BCDR_BCDEN;
/* Enable DCD : Data Contact Detect */
USBx->BCDR &= ~(USB_BCDR_PDEN);
USBx->BCDR &= ~(USB_BCDR_SDEN);
USBx->BCDR |= USB_BCDR_DCDEN;
return HAL_OK;
}
/**
* @brief Deactivate BatteryCharging feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_DeActivateBCD(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->battery_charging_active = 0U;
/* Disable BCD feature */
USBx->BCDR &= ~(USB_BCDR_BCDEN);
return HAL_OK;
}
/**
* @brief Handle BatteryCharging Process.
* @param hpcd PCD handle
* @retval HAL status
*/
void HAL_PCDEx_BCD_VBUSDetect(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
uint32_t tickstart = HAL_GetTick();
/* Wait Detect flag or a timeout is happen*/
while ((USBx->BCDR & USB_BCDR_DCDET) == 0U)
{
/* Check for the Timeout */
if ((HAL_GetTick() - tickstart) > 1000U)
{
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_ERROR);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_ERROR);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
return;
}
}
HAL_Delay(200U);
/* Data Pin Contact ? Check Detect flag */
if ((USBx->BCDR & USB_BCDR_DCDET) == USB_BCDR_DCDET)
{
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_CONTACT_DETECTION);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CONTACT_DETECTION);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
/* Primary detection: checks if connected to Standard Downstream Port
(without charging capability) */
USBx->BCDR &= ~(USB_BCDR_DCDEN);
HAL_Delay(50U);
USBx->BCDR |= (USB_BCDR_PDEN);
HAL_Delay(50U);
/* If Charger detect ? */
if ((USBx->BCDR & USB_BCDR_PDET) == USB_BCDR_PDET)
{
/* Start secondary detection to check connection to Charging Downstream
Port or Dedicated Charging Port */
USBx->BCDR &= ~(USB_BCDR_PDEN);
HAL_Delay(50U);
USBx->BCDR |= (USB_BCDR_SDEN);
HAL_Delay(50U);
/* If CDP ? */
if ((USBx->BCDR & USB_BCDR_SDET) == USB_BCDR_SDET)
{
/* Dedicated Downstream Port DCP */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
else
{
/* Charging Downstream Port CDP */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
}
else /* NO */
{
/* Standard Downstream Port */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
/* Battery Charging capability discovery finished Start Enumeration */
(void)HAL_PCDEx_DeActivateBCD(hpcd);
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_DISCOVERY_COMPLETED);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DISCOVERY_COMPLETED);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
/**
* @brief Activate LPM feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->lpm_active = 1U;
hpcd->LPM_State = LPM_L0;
USBx->LPMCSR |= USB_LPMCSR_LMPEN;
USBx->LPMCSR |= USB_LPMCSR_LPMACK;
return HAL_OK;
}
/**
* @brief Deactivate LPM feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->lpm_active = 0U;
USBx->LPMCSR &= ~(USB_LPMCSR_LMPEN);
USBx->LPMCSR &= ~(USB_LPMCSR_LPMACK);
return HAL_OK;
}
/**
* @brief Send LPM message to user layer callback.
* @param hpcd PCD handle
* @param msg LPM message
* @retval HAL status
*/
__weak void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(msg);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCDEx_LPM_Callback could be implemented in the user file
*/
}
/**
* @brief Send BatteryCharging message to user layer callback.
* @param hpcd PCD handle
* @param msg LPM message
* @retval HAL status
*/
__weak void HAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(msg);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCDEx_BCD_Callback could be implemented in the user file
*/
}
/**
* @}
*/
/**
* @}
*/
#endif /* defined (USB) */
#endif /* HAL_PCD_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| prefetchnta/crhack | src/naked/arm-stm32/stm32wbxx/stm32wbxx_hal_pcd_ex.c | C | lgpl-2.1 | 9,702 |
package org.hivedb.hibernate.simplified;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.action.Executable;
import org.hibernate.event.PostDeleteEvent;
import org.hibernate.event.PostDeleteEventListener;
import org.hivedb.Hive;
import org.hivedb.HiveLockableException;
import org.hivedb.configuration.EntityConfig;
import org.hivedb.configuration.EntityHiveConfig;
import org.hivedb.hibernate.HiveIndexer;
import org.hivedb.util.classgen.ReflectionTools;
import org.hivedb.util.functional.Transform;
import org.hivedb.util.functional.Unary;
import java.io.Serializable;
/**
* This is an alternative way of deleting the hive indexes after successful
* transaction completion (instead of using a custom Interceptor) and up
* for discussion. Hooked up via org.hibernate.cfg.Configuration.
* getEventListeners().setPostDeleteEventListeners
*
* @author mellwanger
*/
public class PostDeleteEventListenerImpl implements PostDeleteEventListener {
private static final Logger log = Logger.getLogger(PostInsertEventListenerImpl.class);
private final EntityHiveConfig hiveConfig;
private final HiveIndexer indexer;
public PostDeleteEventListenerImpl(EntityHiveConfig hiveConfig, Hive hive) {
this.hiveConfig = hiveConfig;
indexer = new HiveIndexer(hive);
}
public void onPostDelete(final PostDeleteEvent event) {
event.getSession().getActionQueue().execute(new Executable() {
public void afterTransactionCompletion(boolean success) {
if (success) {
deleteIndexes(event.getEntity());
}
}
public void beforeExecutions() throws HibernateException {
// TODO Auto-generated method stub
}
public void execute() throws HibernateException {
// TODO Auto-generated method stub
}
public Serializable[] getPropertySpaces() {
// TODO Auto-generated method stub
return null;
}
public boolean hasAfterTransactionCompletion() {
return true;
}
});
}
@SuppressWarnings("unchecked")
private Class resolveEntityClass(Class clazz) {
return ReflectionTools.whichIsImplemented(
clazz,
Transform.map(new Unary<EntityConfig, Class>() {
public Class f(EntityConfig entityConfig) {
return entityConfig.getRepresentedInterface();
}
},
hiveConfig.getEntityConfigs()));
}
private void deleteIndexes(Object entity) {
try {
final Class<?> resolvedEntityClass = resolveEntityClass(entity.getClass());
if (resolvedEntityClass != null)
indexer.delete(hiveConfig.getEntityConfig(entity.getClass()), entity);
} catch (HiveLockableException e) {
log.warn(e);
}
}
}
| aruanruan/hivedb | src/main/java/org/hivedb/hibernate/simplified/PostDeleteEventListenerImpl.java | Java | lgpl-2.1 | 2,748 |
/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "KKSACBulkF.h"
template<>
InputParameters validParams<KKSACBulkF>()
{
InputParameters params = validParams<KKSACBulkBase>();
// params.addClassDescription("KKS model kernel for the Bulk Allen-Cahn. This operates on the order parameter 'eta' as the non-linear variable");
params.addRequiredParam<Real>("w", "Double well height parameter");
params.addParam<MaterialPropertyName>("g_name", "g", "Base name for the double well function g(eta)");
return params;
}
KKSACBulkF::KKSACBulkF(const InputParameters & parameters) :
KKSACBulkBase(parameters),
_w(getParam<Real>("w")),
_prop_dg(getMaterialPropertyDerivative<Real>("g_name", _eta_name)),
_prop_d2g(getMaterialPropertyDerivative<Real>("g_name", _eta_name, _eta_name))
{
}
Real
KKSACBulkF::computeDFDOP(PFFunctionType type)
{
Real res = 0.0;
Real A1 = _prop_Fa[_qp] - _prop_Fb[_qp];
switch (type)
{
case Residual:
return -_prop_dh[_qp] * A1 + _w * _prop_dg[_qp];
case Jacobian:
{
res = -_prop_d2h[_qp] * A1
+ _w * _prop_d2g[_qp];
// the -\frac{dh}{d\eta}\left(\frac{dF_a}{d\eta}-\frac{dF_b}{d\eta}\right)
// term is handled in KKSACBulkC!
return _phi[_j][_qp] * res;
}
}
mooseError("Invalid type passed in");
}
Real
KKSACBulkF::computeQpOffDiagJacobian(unsigned int jvar)
{
// get the coupled variable jvar is referring to
unsigned int cvar;
if (!mapJvarToCvar(jvar, cvar))
return 0.0;
Real res = _prop_dh[_qp] * ( (*_derivatives_Fa[cvar])[_qp]
- (*_derivatives_Fb[cvar])[_qp])
* _phi[_j][_qp];
return res * _test[_j][_qp];
}
// DEPRECATED CONSTRUCTOR
KKSACBulkF::KKSACBulkF(const std::string & deprecated_name, InputParameters parameters) :
KKSACBulkBase(deprecated_name, parameters),
_w(getParam<Real>("w")),
_prop_dg(getMaterialPropertyDerivative<Real>("g_name", _eta_name)),
_prop_d2g(getMaterialPropertyDerivative<Real>("g_name", _eta_name, _eta_name))
{
}
| raghavaggarwal/moose | modules/phase_field/src/kernels/KKSACBulkF.C | C++ | lgpl-2.1 | 2,419 |
// Boost.Geometry Index
//
// R-tree spatial query visitor implementation
//
// Copyright (c) 2011-2014 Adam Wulkiewicz, Lodz, Poland.
//
// This file was modified by Oracle on 2019-2021.
// Modifications copyright (c) 2019-2021 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
//
// Use, modification and distribution is subject to 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)
#ifndef BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_SPATIAL_QUERY_HPP
#define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_SPATIAL_QUERY_HPP
#include <boost/geometry/index/detail/rtree/node/node_elements.hpp>
#include <boost/geometry/index/detail/predicates.hpp>
#include <boost/geometry/index/parameters.hpp>
namespace boost { namespace geometry { namespace index {
namespace detail { namespace rtree { namespace visitors {
template <typename MembersHolder, typename Predicates, typename OutIter>
struct spatial_query
{
typedef typename MembersHolder::parameters_type parameters_type;
typedef typename MembersHolder::translator_type translator_type;
typedef typename MembersHolder::allocators_type allocators_type;
typedef typename index::detail::strategy_type<parameters_type>::type strategy_type;
typedef typename MembersHolder::node node;
typedef typename MembersHolder::internal_node internal_node;
typedef typename MembersHolder::leaf leaf;
typedef typename allocators_type::node_pointer node_pointer;
typedef typename allocators_type::size_type size_type;
spatial_query(MembersHolder const& members, Predicates const& p, OutIter out_it)
: m_tr(members.translator())
, m_strategy(index::detail::get_strategy(members.parameters()))
, m_pred(p)
, m_out_iter(out_it)
, m_found_count(0)
{}
size_type apply(node_pointer ptr, size_type reverse_level)
{
namespace id = index::detail;
if (reverse_level > 0)
{
internal_node& n = rtree::get<internal_node>(*ptr);
// traverse nodes meeting predicates
for (auto const& p : rtree::elements(n))
{
// if node meets predicates (0 is dummy value)
if (id::predicates_check<id::bounds_tag>(m_pred, 0, p.first, m_strategy))
{
apply(p.second, reverse_level - 1);
}
}
}
else
{
leaf& n = rtree::get<leaf>(*ptr);
// get all values meeting predicates
for (auto const& v : rtree::elements(n))
{
// if value meets predicates
if (id::predicates_check<id::value_tag>(m_pred, v, m_tr(v), m_strategy))
{
*m_out_iter = v;
++m_out_iter;
++m_found_count;
}
}
}
return m_found_count;
}
size_type apply(MembersHolder const& members)
{
return apply(members.root, members.leafs_level);
}
private:
translator_type const& m_tr;
strategy_type m_strategy;
Predicates const& m_pred;
OutIter m_out_iter;
size_type m_found_count;
};
template <typename MembersHolder, typename Predicates>
class spatial_query_incremental
{
typedef typename MembersHolder::value_type value_type;
typedef typename MembersHolder::parameters_type parameters_type;
typedef typename MembersHolder::translator_type translator_type;
typedef typename MembersHolder::allocators_type allocators_type;
typedef typename index::detail::strategy_type<parameters_type>::type strategy_type;
typedef typename MembersHolder::node node;
typedef typename MembersHolder::internal_node internal_node;
typedef typename MembersHolder::leaf leaf;
typedef typename allocators_type::size_type size_type;
typedef typename allocators_type::const_reference const_reference;
typedef typename allocators_type::node_pointer node_pointer;
typedef typename rtree::elements_type<internal_node>::type::const_iterator internal_iterator;
typedef typename rtree::elements_type<leaf>::type leaf_elements;
typedef typename rtree::elements_type<leaf>::type::const_iterator leaf_iterator;
struct internal_data
{
internal_data(internal_iterator f, internal_iterator l, size_type rl)
: first(f), last(l), reverse_level(rl)
{}
internal_iterator first;
internal_iterator last;
size_type reverse_level;
};
public:
spatial_query_incremental()
: m_translator(nullptr)
// , m_strategy()
// , m_pred()
, m_values(nullptr)
, m_current()
{}
spatial_query_incremental(Predicates const& p)
: m_translator(nullptr)
// , m_strategy()
, m_pred(p)
, m_values(nullptr)
, m_current()
{}
spatial_query_incremental(MembersHolder const& members, Predicates const& p)
: m_translator(::boost::addressof(members.translator()))
, m_strategy(index::detail::get_strategy(members.parameters()))
, m_pred(p)
, m_values(nullptr)
, m_current()
{}
const_reference dereference() const
{
BOOST_GEOMETRY_INDEX_ASSERT(m_values, "not dereferencable");
return *m_current;
}
void initialize(MembersHolder const& members)
{
apply(members.root, members.leafs_level);
search_value();
}
void increment()
{
++m_current;
search_value();
}
bool is_end() const
{
return 0 == m_values;
}
friend bool operator==(spatial_query_incremental const& l, spatial_query_incremental const& r)
{
return (l.m_values == r.m_values) && (0 == l.m_values || l.m_current == r.m_current);
}
private:
void apply(node_pointer ptr, size_type reverse_level)
{
namespace id = index::detail;
if (reverse_level > 0)
{
internal_node& n = rtree::get<internal_node>(*ptr);
auto const& elements = rtree::elements(n);
m_internal_stack.push_back(internal_data(elements.begin(), elements.end(), reverse_level - 1));
}
else
{
leaf& n = rtree::get<leaf>(*ptr);
m_values = ::boost::addressof(rtree::elements(n));
m_current = rtree::elements(n).begin();
}
}
void search_value()
{
namespace id = index::detail;
for (;;)
{
// if leaf is choosen, move to the next value in leaf
if ( m_values )
{
if ( m_current != m_values->end() )
{
// return if next value is found
value_type const& v = *m_current;
if (id::predicates_check<id::value_tag>(m_pred, v, (*m_translator)(v), m_strategy))
{
return;
}
++m_current;
}
// no more values, clear current leaf
else
{
m_values = 0;
}
}
// if leaf isn't choosen, move to the next leaf
else
{
// return if there is no more nodes to traverse
if (m_internal_stack.empty())
{
return;
}
internal_data& current_data = m_internal_stack.back();
// no more children in current node, remove it from stack
if (current_data.first == current_data.last)
{
m_internal_stack.pop_back();
continue;
}
internal_iterator it = current_data.first;
++current_data.first;
// next node is found, push it to the stack
if (id::predicates_check<id::bounds_tag>(m_pred, 0, it->first, m_strategy))
{
apply(it->second, current_data.reverse_level);
}
}
}
}
const translator_type * m_translator;
strategy_type m_strategy;
Predicates m_pred;
std::vector<internal_data> m_internal_stack;
const leaf_elements * m_values;
leaf_iterator m_current;
};
}}} // namespace detail::rtree::visitors
}}} // namespace boost::geometry::index
#endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_SPATIAL_QUERY_HPP
| qianqians/abelkhan | cpp_component/3rdparty/boost/boost/geometry/index/detail/rtree/visitors/spatial_query.hpp | C++ | lgpl-2.1 | 8,657 |
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_mobile_warren_irradiated_worker_s01 = object_mobile_shared_warren_irradiated_worker_s01:new {
}
ObjectTemplates:addTemplate(object_mobile_warren_irradiated_worker_s01, "object/mobile/warren_irradiated_worker_s01.iff")
| kidaa/Awakening-Core3 | bin/scripts/object/mobile/warren_irradiated_worker_s01.lua | Lua | lgpl-3.0 | 2,228 |
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_wearables_ithorian_ith_pants_s13 = object_tangible_wearables_ithorian_shared_ith_pants_s13:new {
playerRaces = { "object/creature/player/ithorian_male.iff",
"object/creature/player/ithorian_female.iff",
"object/mobile/vendor/ithorian_female.iff",
"object/mobile/vendor/ithorian_male.iff" },
numberExperimentalProperties = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalProperties = {"XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX"},
experimentalWeights = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalGroupTitles = {"null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"},
experimentalSubGroupTitles = {"null", "null", "sockets", "hitpoints", "mod_idx_one", "mod_val_one", "mod_idx_two", "mod_val_two", "mod_idx_three", "mod_val_three", "mod_idx_four", "mod_val_four", "mod_idx_five", "mod_val_five", "mod_idx_six", "mod_val_six"},
experimentalMin = {0, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalMax = {0, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalCombineType = {0, 0, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
}
ObjectTemplates:addTemplate(object_tangible_wearables_ithorian_ith_pants_s13, "object/tangible/wearables/ithorian/ith_pants_s13.iff")
| kidaa/Awakening-Core3 | bin/scripts/object/tangible/wearables/ithorian/ith_pants_s13.lua | Lua | lgpl-3.0 | 3,451 |
#
# Secret Labs' Regular Expression Engine
#
# various symbols used by the regular expression engine.
# run this script to update the _sre include files!
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# See the sre.py file for information on usage and redistribution.
#
"""Internal support module for sre"""
# update when constants are added or removed
MAGIC = 20031017
# max code word in this release
MAXREPEAT = 65535
# SRE standard exception (access as sre.error)
# should this really be here?
class error(Exception):
pass
# operators
FAILURE = "failure"
SUCCESS = "success"
ANY = "any"
ANY_ALL = "any_all"
ASSERT = "assert"
ASSERT_NOT = "assert_not"
AT = "at"
BIGCHARSET = "bigcharset"
BRANCH = "branch"
CALL = "call"
CATEGORY = "category"
CHARSET = "charset"
GROUPREF = "groupref"
GROUPREF_IGNORE = "groupref_ignore"
GROUPREF_EXISTS = "groupref_exists"
IN = "in"
IN_IGNORE = "in_ignore"
INFO = "info"
JUMP = "jump"
LITERAL = "literal"
LITERAL_IGNORE = "literal_ignore"
MARK = "mark"
MAX_REPEAT = "max_repeat"
MAX_UNTIL = "max_until"
MIN_REPEAT = "min_repeat"
MIN_UNTIL = "min_until"
NEGATE = "negate"
NOT_LITERAL = "not_literal"
NOT_LITERAL_IGNORE = "not_literal_ignore"
RANGE = "range"
REPEAT = "repeat"
REPEAT_ONE = "repeat_one"
SUBPATTERN = "subpattern"
MIN_REPEAT_ONE = "min_repeat_one"
# positions
AT_BEGINNING = "at_beginning"
AT_BEGINNING_LINE = "at_beginning_line"
AT_BEGINNING_STRING = "at_beginning_string"
AT_BOUNDARY = "at_boundary"
AT_NON_BOUNDARY = "at_non_boundary"
AT_END = "at_end"
AT_END_LINE = "at_end_line"
AT_END_STRING = "at_end_string"
AT_LOC_BOUNDARY = "at_loc_boundary"
AT_LOC_NON_BOUNDARY = "at_loc_non_boundary"
AT_UNI_BOUNDARY = "at_uni_boundary"
AT_UNI_NON_BOUNDARY = "at_uni_non_boundary"
# categories
CATEGORY_DIGIT = "category_digit"
CATEGORY_NOT_DIGIT = "category_not_digit"
CATEGORY_SPACE = "category_space"
CATEGORY_NOT_SPACE = "category_not_space"
CATEGORY_WORD = "category_word"
CATEGORY_NOT_WORD = "category_not_word"
CATEGORY_LINEBREAK = "category_linebreak"
CATEGORY_NOT_LINEBREAK = "category_not_linebreak"
CATEGORY_LOC_WORD = "category_loc_word"
CATEGORY_LOC_NOT_WORD = "category_loc_not_word"
CATEGORY_UNI_DIGIT = "category_uni_digit"
CATEGORY_UNI_NOT_DIGIT = "category_uni_not_digit"
CATEGORY_UNI_SPACE = "category_uni_space"
CATEGORY_UNI_NOT_SPACE = "category_uni_not_space"
CATEGORY_UNI_WORD = "category_uni_word"
CATEGORY_UNI_NOT_WORD = "category_uni_not_word"
CATEGORY_UNI_LINEBREAK = "category_uni_linebreak"
CATEGORY_UNI_NOT_LINEBREAK = "category_uni_not_linebreak"
OPCODES = [
# failure=0 success=1 (just because it looks better that way :-)
FAILURE, SUCCESS,
ANY, ANY_ALL,
ASSERT, ASSERT_NOT,
AT,
BRANCH,
CALL,
CATEGORY,
CHARSET, BIGCHARSET,
GROUPREF, GROUPREF_EXISTS, GROUPREF_IGNORE,
IN, IN_IGNORE,
INFO,
JUMP,
LITERAL, LITERAL_IGNORE,
MARK,
MAX_UNTIL,
MIN_UNTIL,
NOT_LITERAL, NOT_LITERAL_IGNORE,
NEGATE,
RANGE,
REPEAT,
REPEAT_ONE,
SUBPATTERN,
MIN_REPEAT_ONE
]
ATCODES = [
AT_BEGINNING, AT_BEGINNING_LINE, AT_BEGINNING_STRING, AT_BOUNDARY,
AT_NON_BOUNDARY, AT_END, AT_END_LINE, AT_END_STRING,
AT_LOC_BOUNDARY, AT_LOC_NON_BOUNDARY, AT_UNI_BOUNDARY,
AT_UNI_NON_BOUNDARY
]
CHCODES = [
CATEGORY_DIGIT, CATEGORY_NOT_DIGIT, CATEGORY_SPACE,
CATEGORY_NOT_SPACE, CATEGORY_WORD, CATEGORY_NOT_WORD,
CATEGORY_LINEBREAK, CATEGORY_NOT_LINEBREAK, CATEGORY_LOC_WORD,
CATEGORY_LOC_NOT_WORD, CATEGORY_UNI_DIGIT, CATEGORY_UNI_NOT_DIGIT,
CATEGORY_UNI_SPACE, CATEGORY_UNI_NOT_SPACE, CATEGORY_UNI_WORD,
CATEGORY_UNI_NOT_WORD, CATEGORY_UNI_LINEBREAK,
CATEGORY_UNI_NOT_LINEBREAK
]
def makedict(list):
d = {}
i = 0
for item in list:
d[item] = i
i = i + 1
return d
OPCODES = makedict(OPCODES)
ATCODES = makedict(ATCODES)
CHCODES = makedict(CHCODES)
# replacement operations for "ignore case" mode
OP_IGNORE = {
GROUPREF: GROUPREF_IGNORE,
IN: IN_IGNORE,
LITERAL: LITERAL_IGNORE,
NOT_LITERAL: NOT_LITERAL_IGNORE
}
AT_MULTILINE = {
AT_BEGINNING: AT_BEGINNING_LINE,
AT_END: AT_END_LINE
}
AT_LOCALE = {
AT_BOUNDARY: AT_LOC_BOUNDARY,
AT_NON_BOUNDARY: AT_LOC_NON_BOUNDARY
}
AT_UNICODE = {
AT_BOUNDARY: AT_UNI_BOUNDARY,
AT_NON_BOUNDARY: AT_UNI_NON_BOUNDARY
}
CH_LOCALE = {
CATEGORY_DIGIT: CATEGORY_DIGIT,
CATEGORY_NOT_DIGIT: CATEGORY_NOT_DIGIT,
CATEGORY_SPACE: CATEGORY_SPACE,
CATEGORY_NOT_SPACE: CATEGORY_NOT_SPACE,
CATEGORY_WORD: CATEGORY_LOC_WORD,
CATEGORY_NOT_WORD: CATEGORY_LOC_NOT_WORD,
CATEGORY_LINEBREAK: CATEGORY_LINEBREAK,
CATEGORY_NOT_LINEBREAK: CATEGORY_NOT_LINEBREAK
}
CH_UNICODE = {
CATEGORY_DIGIT: CATEGORY_UNI_DIGIT,
CATEGORY_NOT_DIGIT: CATEGORY_UNI_NOT_DIGIT,
CATEGORY_SPACE: CATEGORY_UNI_SPACE,
CATEGORY_NOT_SPACE: CATEGORY_UNI_NOT_SPACE,
CATEGORY_WORD: CATEGORY_UNI_WORD,
CATEGORY_NOT_WORD: CATEGORY_UNI_NOT_WORD,
CATEGORY_LINEBREAK: CATEGORY_UNI_LINEBREAK,
CATEGORY_NOT_LINEBREAK: CATEGORY_UNI_NOT_LINEBREAK
}
# flags
SRE_FLAG_TEMPLATE = 1 # template mode (disable backtracking)
SRE_FLAG_IGNORECASE = 2 # case insensitive
SRE_FLAG_LOCALE = 4 # honour system locale
SRE_FLAG_MULTILINE = 8 # treat target as multiline string
SRE_FLAG_DOTALL = 16 # treat target as a single string
SRE_FLAG_UNICODE = 32 # use unicode "locale"
SRE_FLAG_VERBOSE = 64 # ignore whitespace and comments
SRE_FLAG_DEBUG = 128 # debugging
SRE_FLAG_ASCII = 256 # use ascii "locale"
# flags for INFO primitive
SRE_INFO_PREFIX = 1 # has prefix
SRE_INFO_LITERAL = 2 # entire pattern is literal (given by prefix)
SRE_INFO_CHARSET = 4 # pattern starts with character from given set
if __name__ == "__main__":
def dump(f, d, prefix):
items = d.items()
items.sort(key=lambda a: a[1])
for k, v in items:
f.write("#define %s_%s %s\n" % (prefix, k.upper(), v))
f = open("sre_constants.h", "w")
f.write("""\
/*
* Secret Labs' Regular Expression Engine
*
* regular expression matching engine
*
* NOTE: This file is generated by sre_constants.py. If you need
* to change anything in here, edit sre_constants.py and run it.
*
* Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved.
*
* See the _sre.c file for information on usage and redistribution.
*/
""")
f.write("#define SRE_MAGIC %d\n" % MAGIC)
dump(f, OPCODES, "SRE_OP")
dump(f, ATCODES, "SRE")
dump(f, CHCODES, "SRE")
f.write("#define SRE_FLAG_TEMPLATE %d\n" % SRE_FLAG_TEMPLATE)
f.write("#define SRE_FLAG_IGNORECASE %d\n" % SRE_FLAG_IGNORECASE)
f.write("#define SRE_FLAG_LOCALE %d\n" % SRE_FLAG_LOCALE)
f.write("#define SRE_FLAG_MULTILINE %d\n" % SRE_FLAG_MULTILINE)
f.write("#define SRE_FLAG_DOTALL %d\n" % SRE_FLAG_DOTALL)
f.write("#define SRE_FLAG_UNICODE %d\n" % SRE_FLAG_UNICODE)
f.write("#define SRE_FLAG_VERBOSE %d\n" % SRE_FLAG_VERBOSE)
f.write("#define SRE_INFO_PREFIX %d\n" % SRE_INFO_PREFIX)
f.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL)
f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET)
f.close()
print("done")
| harmy/kbengine | kbe/res/scripts/common/Lib/sre_constants.py | Python | lgpl-3.0 | 7,444 |
/* radare - LGPL - Copyright 2014-2015 - pancake */
#include "r_util/r_str.h"
#include <r_util.h>
/* dex/dwarf uleb128 implementation */
R_API const ut8 *r_uleb128(const ut8 *data, int datalen, ut64 *v, const char **error) {
ut8 c;
ut64 s, sum = 0;
const ut8 *data_end;
bool malformed_uleb = true;
if (v) {
*v = 0LL;
}
if (datalen == ST32_MAX) {
// WARNING; possible overflow
datalen = 0xffff;
}
if (datalen < 0) {
return NULL;
}
data_end = data + datalen;
if (data && datalen > 0) {
if (*data) {
for (s = 0; data < data_end; s += 7) {
c = *(data++) & 0xff;
if (s > 63) {
if (error) {
*error = r_str_newf ("r_uleb128: undefined behaviour in %d shift on ut32\n", (int)s);
}
break;
} else {
sum |= ((ut64) (c & 0x7f) << s);
}
if (!(c & 0x80)) {
malformed_uleb = false;
break;
}
}
if (malformed_uleb) {
if (error) {
*error = r_str_newf ("malformed uleb128\n");
}
}
} else {
data++;
}
}
if (v) {
*v = sum;
}
return data;
}
R_API int r_uleb128_len (const ut8 *data, int size) {
int i = 1;
ut8 c = *(data++);
while (c > 0x7f && i < size) {
c = *(data++);
i++;
}
return i;
}
/* data is the char array containing the uleb number
* datalen will point (if not NULL) to the length of the uleb number
* v (if not NULL) will point to the data's value (if fitting the size of an ut64)
*/
R_API const ut8 *r_uleb128_decode(const ut8 *data, int *datalen, ut64 *v) {
ut8 c = 0xff;
ut64 s = 0, sum = 0, l = 0;
do {
c = *(data++) & 0xff;
sum |= ((ut64) (c&0x7f) << s);
s += 7;
l++;
} while (c & 0x80);
if (v) {
*v = sum;
}
if (datalen) {
*datalen = l;
}
return data;
}
R_API ut8 *r_uleb128_encode(const ut64 s, int *len) {
ut8 c = 0;
int l = 0;
ut8 *otarget = NULL, *target = NULL, *tmptarget = NULL;
ut64 source = s;
do {
l++;
if (!(tmptarget = realloc (otarget, l))) {
l = 0;
free (otarget);
otarget = NULL;
break;
}
otarget = tmptarget;
target = otarget+l-1;
c = source & 0x7f;
source >>= 7;
if (source) {
c |= 0x80;
}
*(target) = c;
} while (source);
if (len) {
*len = l;
}
return otarget;
}
R_API const ut8 *r_leb128(const ut8 *data, int datalen, st64 *v) {
ut8 c = 0;
st64 s = 0, sum = 0;
const ut8 *data_end = data + datalen;
if (data && datalen > 0) {
if (!*data) {
data++;
goto beach;
}
while (data < data_end) {
c = *(data++) & 0x0ff;
sum |= ((st64) (c & 0x7f) << s);
s += 7;
if (!(c & 0x80)) {
break;
}
}
}
if ((s < (8 * sizeof (sum))) && (c & 0x40)) {
sum |= -((st64)1 << s);
}
beach:
if (v) {
*v = sum;
}
return data;
}
R_API st64 r_sleb128(const ut8 **data, const ut8 *end) {
const ut8 *p = *data;
st64 result = 0;
int offset = 0;
ut8 value;
bool cond;
do {
st64 chunk;
value = *p;
chunk = value & 0x7f;
result |= (chunk << offset);
offset += 7;
} while (cond = *p & 0x80 && p + 1 < end, p++, cond);
if ((value & 0x40) != 0) {
result |= ~0ULL << offset;
}
*data = p;
return result;
}
// API from https://github.com/WebAssembly/wabt/blob/master/src/binary-reader.cc
#define BYTE_AT(type, i, shift) (((type)(p[i]) & 0x7f) << (shift))
#define LEB128_1(type) (BYTE_AT (type, 0, 0))
#define LEB128_2(type) (BYTE_AT (type, 1, 7) | LEB128_1 (type))
#define LEB128_3(type) (BYTE_AT (type, 2, 14) | LEB128_2 (type))
#define LEB128_4(type) (BYTE_AT (type, 3, 21) | LEB128_3 (type))
#define LEB128_5(type) (BYTE_AT (type, 4, 28) | LEB128_4 (type))
#define LEB128_6(type) (BYTE_AT (type, 5, 35) | LEB128_5 (type))
#define LEB128_7(type) (BYTE_AT (type, 6, 42) | LEB128_6 (type))
#define LEB128_8(type) (BYTE_AT (type, 7, 49) | LEB128_7 (type))
#define LEB128_9(type) (BYTE_AT (type, 8, 56) | LEB128_8 (type))
#define LEB128_10(type) (BYTE_AT (type, 9, 63) | LEB128_9 (type))
#define SHIFT_AMOUNT(type, sign_bit) (sizeof(type) * 8 - 1 - (sign_bit))
#define SIGN_EXTEND(type, value, sign_bit) \
((type)((value) << SHIFT_AMOUNT (type, sign_bit)) >> \
SHIFT_AMOUNT (type, sign_bit))
R_API size_t read_u32_leb128 (const ut8* p, const ut8* max, ut32* out_value) {
if (p < max && !(p[0] & 0x80)) {
*out_value = LEB128_1 (ut32);
return 1;
} else if (p + 1 < max && !(p[1] & 0x80)) {
*out_value = LEB128_2 (ut32);
return 2;
} else if (p + 2 < max && !(p[2] & 0x80)) {
*out_value = LEB128_3 (ut32);
return 3;
} else if (p + 3 < max && !(p[3] & 0x80)) {
*out_value = LEB128_4 (ut32);
return 4;
} else if (p + 4 < max && !(p[4] & 0x80)) {
/* the top bits set represent values > 32 bits */
// if (p[4] & 0xf0) {}
*out_value = LEB128_5 (ut32);
return 5;
} else {
/* past the end */
*out_value = 0;
return 0;
}
}
R_API size_t read_i32_leb128 (const ut8* p, const ut8* max, st32* out_value) {
if (p < max && !(p[0] & 0x80)) {
ut32 result = LEB128_1 (ut32);
*out_value = SIGN_EXTEND (ut32, result, 6);
return 1;
} else if (p + 1 < max && !(p[1] & 0x80)) {
ut32 result = LEB128_2 (ut32);
*out_value = SIGN_EXTEND (ut32, result, 13);
return 2;
} else if (p + 2 < max && !(p[2] & 0x80)) {
ut32 result = LEB128_3 (ut32);
*out_value = SIGN_EXTEND (ut32, result, 20);
return 3;
} else if (p + 3 < max && !(p[3] & 0x80)) {
ut32 result = LEB128_4 (ut32);
*out_value = SIGN_EXTEND (ut32, result, 27);
return 4;
} else if (p+4 < max && !(p[4] & 0x80)) {
/* the top bits should be a sign-extension of the sign bit */
bool sign_bit_set = (p[4] & 0x8);
int top_bits = p[4] & 0xf0;
if ((sign_bit_set && top_bits != 0x70) || (!sign_bit_set && top_bits != 0)) {
return 0;
}
ut32 result = LEB128_5 (ut32);
*out_value = result;
return 5;
} else {
/* past the end */
return 0;
}
}
R_API size_t read_u64_leb128 (const ut8* p, const ut8* max, ut64* out_value) {
if (p < max && !(p[0] & 0x80)) {
*out_value = LEB128_1 (ut64);
return 1;
} else if (p + 1 < max && !(p[1] & 0x80)) {
*out_value = LEB128_2 (ut64);
return 2;
} else if (p + 2 < max && !(p[2] & 0x80)) {
*out_value = LEB128_3 (ut64);
return 3;
} else if (p + 3 < max && !(p[3] & 0x80)) {
*out_value = LEB128_4 (ut64);
return 4;
} else if (p + 4 < max && !(p[4] & 0x80)) {
*out_value = LEB128_5 (ut64);
return 5;
} else if (p + 5 < max && !(p[5] & 0x80)) {
*out_value = LEB128_6 (ut64);
return 6;
} else if (p + 6 < max && !(p[6] & 0x80)) {
*out_value = LEB128_7 (ut64);
return 7;
} else if (p + 7 < max && !(p[7] & 0x80)) {
*out_value = LEB128_8 (ut64);
return 8;
} else if (p + 8 < max && !(p[8] & 0x80)) {
*out_value = LEB128_9 (ut64);
return 9;
} else if (p + 9 < max && !(p[9] & 0x80)) {
*out_value = LEB128_10 (ut64);
return 10;
} else {
/* past the end */
*out_value = 0;
return 0;
}
}
R_API size_t read_i64_leb128 (const ut8* p, const ut8* max, st64* out_value) {
if (p < max && !(p[0] & 0x80)) {
ut64 result = LEB128_1 (ut64);
*out_value = SIGN_EXTEND (ut64, result, 6);
return 1;
} else if (p + 1 < max && !(p[1] & 0x80)) {
ut64 result = LEB128_2(ut64);
*out_value = SIGN_EXTEND (ut64, result, 13);
return 2;
} else if (p + 2 < max && !(p[2] & 0x80)) {
ut64 result = LEB128_3 (ut64);
*out_value = SIGN_EXTEND (ut64, result, 20);
return 3;
} else if (p + 3 < max && !(p[3] & 0x80)) {
ut64 result = LEB128_4 (ut64);
*out_value = SIGN_EXTEND (ut64, result, 27);
return 4;
} else if (p + 4 < max && !(p[4] & 0x80)) {
ut64 result = LEB128_5 (ut64);
*out_value = SIGN_EXTEND (ut64, result, 34);
return 5;
} else if (p + 5 < max && !(p[5] & 0x80)) {
ut64 result = LEB128_6 (ut64);
*out_value = SIGN_EXTEND (ut64, result, 41);
return 6;
} else if (p + 6 < max && !(p[6] & 0x80)) {
ut64 result = LEB128_7 (ut64);
*out_value = SIGN_EXTEND (ut64, result, 48);
return 7;
} else if (p + 7 < max && !(p[7] & 0x80)) {
ut64 result = LEB128_8 (ut64);
*out_value = SIGN_EXTEND (ut64, result, 55);
return 8;
} else if (p + 8 < max && !(p[8] & 0x80)) {
ut64 result = LEB128_9 (ut64);
*out_value = SIGN_EXTEND (ut64, result, 62);
return 9;
} else if (p + 9 < max && !(p[9] & 0x80)) {
/* the top bits should be a sign-extension of the sign bit */
bool sign_bit_set = (p[9] & 0x1);
int top_bits = p[9] & 0xfe;
if ((sign_bit_set && top_bits != 0x7e) || (!sign_bit_set && top_bits != 0)) {
return 0;
}
ut64 result = LEB128_10 (ut64);
*out_value = result;
return 10;
} else {
/* past the end */
return 0;
}
}
#undef BYTE_AT
#undef LEB128_1
#undef LEB128_2
#undef LEB128_3
#undef LEB128_4
#undef LEB128_5
#undef LEB128_6
#undef LEB128_7
#undef LEB128_8
#undef LEB128_9
#undef LEB128_10
#undef SHIFT_AMOUNT
#undef SIGN_EXTEND
#if 0
main() {
ut32 n;
ut8 *buf = "\x10\x02\x90\x88";
r_uleb128 (buf, &n);
printf ("n = %d\n", n);
}
#endif
| wargio/radare2 | libr/util/uleb128.c | C | lgpl-3.0 | 8,753 |
"""
Multiple dictation constructs
===============================================================================
This file is a showcase investigating the use and functionality of multiple
dictation elements within Dragonfly speech recognition grammars.
The first part of this file (i.e. the module's doc string) contains a
description of the functionality being investigated along with test code
and actual output in doctest format. This allows the reader to see what
really would happen, without needing to load the file into a speech
recognition engine and put effort into speaking all the showcased
commands.
The test code below makes use of Dragonfly's built-in element testing tool.
When run, it will connect to the speech recognition engine, load the element
being tested, mimic recognitions, and process the recognized value.
Multiple consecutive dictation elements
-------------------------------------------------------------------------------
>>> tester = ElementTester(RuleRef(ConsecutiveDictationRule()))
>>> print(tester.recognize("consecutive Alice Bob Charlie"))
Recognition: "consecutive Alice Bob Charlie"
Word and rule pairs: ("1000000" is "dgndictation")
- consecutive (1)
- Alice (1000000)
- Bob (1000000)
- Charlie (1000000)
Extras:
- dictation1: Alice
- dictation2: Bob
- dictation3: Charlie
>>> print(tester.recognize("consecutive Alice Bob"))
RecognitionFailure
Mixed literal and dictation elements
-------------------------------------------------------------------------------
Here we will investigate mixed, i.e. interspersed, fixed literal command
words and dynamic dictation elements. We will use the "MixedDictationRule"
class which has a spec of
"mixed [<dictation1>] <dictation2> command <dictation3>".
Note that "<dictation1>" was made optional instead of "<dictation2>"
because otherwise the first dictation elements would always gobble up
all dictated words. There would (by definition) be no way to distinguish
which words correspond with which dictation elements. Such consecutive
dictation elements should for that reason be avoided in real command
grammars. The way the spec is defined now, adds some interesting
dynamics, because of the order in which they dictation elements parse
the recognized words. However, do note that that order is well defined
but arbitrarily chosen.
>>> tester = ElementTester(RuleRef(MixedDictationRule()))
>>> print(tester.recognize("mixed Alice Bob command Charlie"))
Recognition: "mixed Alice Bob command Charlie"
Word and rule pairs: ("1000000" is "dgndictation")
- mixed (1)
- Alice (1000000)
- Bob (1000000)
- command (1)
- Charlie (1000000)
Extras:
- dictation1: Alice
- dictation2: Bob
- dictation3: Charlie
>>> print(tester.recognize("mixed Alice command Charlie"))
Recognition: "mixed Alice command Charlie"
Word and rule pairs: ("1000000" is "dgndictation")
- mixed (1)
- Alice (1000000)
- command (1)
- Charlie (1000000)
Extras:
- dictation2: Alice
- dictation3: Charlie
>>> print(tester.recognize("mixed Alice Bob command"))
RecognitionFailure
>>> print(tester.recognize("mixed command Charlie"))
RecognitionFailure
Repetition of dictation elements
-------------------------------------------------------------------------------
Now let's take a look at repetition of dictation elements. For this
we will use the "RepeatedDictationRule" class, which defines its spec
as a repetition of "command <dictation>". I.e. "command Alice" will
match, and "command Alice command Bob" will also match.
Note that this rule is inherently ambiguous, given the lack of a
clear definition of grouping or precedence rules for fixed literal
words in commands, and dynamic dictation elements. As an example,
"command Alice command Bob" could either match 2 repetitions with
"Alice" and "Bob" as dictation values, or a single repetition with
"Alice command Bob" as its only dictation value. The tests below
the show which of these actually occurs.
>>> tester = ElementTester(RuleRef(RepeatedDictationRule()))
>>> print(tester.recognize("command Alice"))
Recognition: "command Alice"
Word and rule pairs: ("1000000" is "dgndictation")
- command (1)
- Alice (1000000)
Extras:
- repetition: [[u'command', NatlinkDictationContainer(Alice)]]
>>> print(tester.recognize("command Alice command Bob"))
Recognition: "command Alice command Bob"
Word and rule pairs: ("1000000" is "dgndictation")
- command (1)
- Alice (1000000)
- command (1000000)
- Bob (1000000)
Extras:
- repetition: [[u'command', NatlinkDictationContainer(Alice, command, Bob)]]
"""
#---------------------------------------------------------------------------
import doctest
from dragonfly import *
from dragonfly.test.infrastructure import RecognitionFailure
from dragonfly.test.element_testcase import ElementTestCase
from dragonfly.test.element_tester import ElementTester
#---------------------------------------------------------------------------
class RecognitionAnalysisRule(CompoundRule):
"""
Base class that implements reporting in human-readable format
details about the recognized phrase. It is used by the actual
testing rules below, and allows the doctests above to be easily
readable and informative.
"""
def _process_recognition(self, node, extras):
Paste(text).execute()
def value(self, node):
return self.get_recognition_info(node)
def get_recognition_info(self, node):
output = []
output.append('Recognition: "{0}"'.format(" ".join(node.words())))
output.append('Word and rule pairs: ("1000000" is "dgndictation")')
for word, rule in node.full_results():
output.append(" - {0} ({1})".format(word, rule))
output.append("Extras:")
for key in sorted(extra.name for extra in self.extras):
extra_node = node.get_child_by_name(key)
if extra_node:
output.append(" - {0}: {1}".format(key, extra_node.value()))
return "\n".join(output)
#---------------------------------------------------------------------------
class ConsecutiveDictationRule(RecognitionAnalysisRule):
spec = "consecutive <dictation1> <dictation2> <dictation3>"
extras = [Dictation("dictation1"),
Dictation("dictation2"),
Dictation("dictation3")]
#---------------------------------------------------------------------------
class MixedDictationRule(RecognitionAnalysisRule):
spec = "mixed [<dictation1>] <dictation2> command <dictation3>"
extras = [Dictation("dictation1"),
Dictation("dictation2"),
Dictation("dictation3")]
#---------------------------------------------------------------------------
class RepeatedDictationRule(RecognitionAnalysisRule):
spec = "<repetition>"
extras = [Repetition(name="repetition",
child=Sequence([Literal("command"),
Dictation()]))]
#---------------------------------------------------------------------------
def main():
engine = get_engine()
engine.connect()
try:
doctest.testmod(verbose=True)
finally:
engine.disconnect()
if __name__ == "__main__":
main()
| Versatilus/dragonfly | dragonfly/examples/test_multiple_dictation.py | Python | lgpl-3.0 | 7,289 |
import os
import unittest
from mock import patch, Mock
from tests.utils import (
FakedCache,
ObjectWithSignals,
setup_test_env,
)
setup_test_env()
from softwarecenter.db.database import StoreDatabase
from softwarecenter.ui.gtk3.views import lobbyview
from softwarecenter.ui.gtk3.widgets.exhibits import (
_HtmlRenderer,
)
class ExhibitsTestCase(unittest.TestCase):
"""The test suite for the exhibits carousel."""
def setUp(self):
self.cache = FakedCache()
self.db = StoreDatabase(cache=self.cache)
self.lobby = lobbyview.LobbyView(cache=self.cache, db=self.db,
icons=None, apps_filter=None)
self.addCleanup(self.lobby.destroy)
def _get_banner_from_lobby(self):
return self.lobby.vbox.get_children()[-1].get_child()
def test_featured_exhibit_by_default(self):
"""Show the featured exhibit before querying the remote service."""
self.lobby._append_banner_ads()
banner = self._get_banner_from_lobby()
self.assertEqual(1, len(banner.exhibits))
self.assertIsInstance(banner.exhibits[0], lobbyview.FeaturedExhibit)
def test_no_exhibit_if_not_available(self):
"""The exhibit should not be shown if the package is not available."""
exhibit = Mock()
exhibit.package_names = u'foobarbaz'
sca = ObjectWithSignals()
sca.query_exhibits = lambda: sca.emit('exhibits', sca, [exhibit])
with patch.object(lobbyview, 'SoftwareCenterAgent', lambda: sca):
self.lobby._append_banner_ads()
banner = self._get_banner_from_lobby()
self.assertEqual(1, len(banner.exhibits))
self.assertIsInstance(banner.exhibits[0], lobbyview.FeaturedExhibit)
def test_exhibit_if_available(self):
"""The exhibit should be shown if the package is available."""
exhibit = Mock()
exhibit.package_names = u'foobarbaz'
exhibit.banner_urls = ['banner']
exhibit.title_translated = ''
self.cache[u'foobarbaz'] = Mock()
sca = ObjectWithSignals()
sca.query_exhibits = lambda: sca.emit('exhibits', sca, [exhibit])
with patch.object(lobbyview, 'SoftwareCenterAgent', lambda: sca):
self.lobby._append_banner_ads()
banner = self._get_banner_from_lobby()
self.assertEqual(1, len(banner.exhibits))
self.assertIs(banner.exhibits[0], exhibit)
def test_exhibit_if_mixed_availability(self):
"""The exhibit should be shown even if some are not available."""
# available exhibit
exhibit = Mock()
exhibit.package_names = u'foobarbaz'
exhibit.banner_urls = ['banner']
exhibit.title_translated = ''
self.cache[u'foobarbaz'] = Mock()
# not available exhibit
other = Mock()
other.package_names = u'not-there'
sca = ObjectWithSignals()
sca.query_exhibits = lambda: sca.emit('exhibits', sca,
[exhibit, other])
with patch.object(lobbyview, 'SoftwareCenterAgent', lambda: sca):
self.lobby._append_banner_ads()
banner = self._get_banner_from_lobby()
self.assertEqual(1, len(banner.exhibits))
self.assertIs(banner.exhibits[0], exhibit)
def test_exhibit_with_url(self):
# available exhibit
exhibit = Mock()
exhibit.package_names = ''
exhibit.click_url = 'http://example.com'
exhibit.banner_urls = ['banner']
exhibit.title_translated = ''
sca = ObjectWithSignals()
sca.query_exhibits = lambda: sca.emit('exhibits', sca,
[exhibit])
with patch.object(lobbyview, 'SoftwareCenterAgent', lambda: sca):
# add the banners
self.lobby._append_banner_ads()
# fake click
alloc = self.lobby.exhibit_banner.get_allocation()
mock_event = Mock()
mock_event.x = alloc.x
mock_event.y = alloc.y
with patch.object(self.lobby.exhibit_banner, 'emit') as mock_emit:
self.lobby.exhibit_banner.on_button_press(None, mock_event)
self.lobby.exhibit_banner.on_button_release(None, mock_event)
mock_emit.assert_called()
signal_name = mock_emit.call_args[0][0]
call_exhibit = mock_emit.call_args[0][1]
self.assertEqual(signal_name, "show-exhibits-clicked")
self.assertEqual(call_exhibit.click_url, "http://example.com")
def test_exhibit_with_featured_exhibit(self):
""" regression test for bug #1023777 """
sca = ObjectWithSignals()
sca.query_exhibits = lambda: sca.emit('exhibits', sca,
[lobbyview.FeaturedExhibit()])
with patch.object(lobbyview, 'SoftwareCenterAgent', lambda: sca):
# add the banners
self.lobby._append_banner_ads()
# fake click
alloc = self.lobby.exhibit_banner.get_allocation()
mock_event = Mock()
mock_event.x = alloc.x
mock_event.y = alloc.y
with patch.object(self.lobby, 'emit') as mock_emit:
self.lobby.exhibit_banner.on_button_press(None, mock_event)
self.lobby.exhibit_banner.on_button_release(None, mock_event)
mock_emit.assert_called()
signal_name = mock_emit.call_args[0][0]
call_category = mock_emit.call_args[0][1]
self.assertEqual(signal_name, "category-selected")
self.assertEqual(call_category.name, "Our star apps")
class HtmlRendererTestCase(unittest.TestCase):
def test_multiple_images(self):
downloader = ObjectWithSignals()
downloader.download_file = lambda *args, **kwargs: downloader.emit(
"file-download-complete", downloader, os.path.basename(args[0]))
with patch("softwarecenter.ui.gtk3.widgets.exhibits."
"SimpleFileDownloader", lambda: downloader):
renderer = _HtmlRenderer()
mock_exhibit = Mock()
mock_exhibit.banner_urls = [
"http://example.com/path1/banner1.png",
"http://example.com/path2/banner2.png",
]
mock_exhibit.html = "url('/path1/banner1.png')#"\
"url('/path2/banner2.png')"
renderer.set_exhibit(mock_exhibit)
# assert the stuff we expected to get downloaded got downloaded
self.assertEqual(
renderer._downloaded_banner_images,
["banner1.png", "banner2.png"])
# test that the path mangling worked
self.assertEqual(
mock_exhibit.html, "url('banner1.png')#url('banner2.png')")
if __name__ == "__main__":
unittest.main()
| sti-lyneos/shop | tests/gtk3/test_exhibits.py | Python | lgpl-3.0 | 6,973 |
///////////////////////////////////////////////////////////////////////////////
// Name: wx/msw/private/hiddenwin.h
// Purpose: Helper for creating a hidden window used by wxMSW internally.
// Author: Vadim Zeitlin
// Created: 2011-09-16
// Copyright: (c) 2011 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_MSW_PRIVATE_HIDDENWIN_H_
#define _WX_MSW_PRIVATE_HIDDENWIN_H_
#include "wx/msw/private.h"
/*
Creates a hidden window with supplied window proc registering the class for
it if necessary (i.e. the first time only). Caller is responsible for
destroying the window and unregistering the class (note that this must be
done because wxWidgets may be used as a DLL and so may be loaded/unloaded
multiple times into/from the same process so we can't rely on automatic
Windows class unregistration).
pclassname is a pointer to a caller stored classname, which must initially be
NULL. classname is the desired wndclass classname. If function successfully
registers the class, pclassname will be set to classname.
*/
extern "C" WXDLLIMPEXP_BASE HWND
wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);
#endif // _WX_MSW_PRIVATE_HIDDENWIN_H_
| dariusliep/LogViewer | thirdparty/wxWidgets-3.0.0/include/wx/msw/private/hiddenwin.h | C | lgpl-3.0 | 1,355 |
/*
* @BEGIN LICENSE
*
* Psi4: an open-source quantum chemistry software package
*
* Copyright (c) 2007-2017 The Psi4 Developers.
*
* The copyrights for code used from other parties are included in
* the corresponding files.
*
* This file is part of Psi4.
*
* Psi4 is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3.
*
* Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* @END LICENSE
*/
#ifndef APPS_H
#define APPS_H
#include <set>
#include <tuple>
#include "psi4/libmints/wavefunction.h"
namespace psi {
class JK;
class VBase;
// => BASE CLASSES <= //
class RBase : public Wavefunction {
protected:
int print_;
int bench_;
SharedMatrix C_;
SharedMatrix Cocc_;
SharedMatrix Cfocc_;
SharedMatrix Cfvir_;
SharedMatrix Caocc_;
SharedMatrix Cavir_;
std::shared_ptr<Vector> eps_focc_;
std::shared_ptr<Vector> eps_fvir_;
std::shared_ptr<Vector> eps_aocc_;
std::shared_ptr<Vector> eps_avir_;
SharedMatrix AO2USO_;
/// How far to converge the two-norm of the residual
double convergence_;
/// Global JK object, built in preiterations, destroyed in postiterations
std::shared_ptr<JK> jk_;
std::shared_ptr<VBase> v_;
bool use_symmetry_;
double Eref_;
public:
RBase(SharedWavefunction ref_wfn, Options& options, bool use_symmetry=true);
// TODO: Remove AS SOON AS POSSIBLE, such a dirty hack
RBase(bool flag);
virtual ~RBase();
virtual bool same_a_b_orbs() const { return true; }
virtual bool same_a_b_dens() const { return true; }
// TODO: Remove AS SOON AS POSSIBLE, such a dirty hack
virtual double compute_energy() { return 0.0; }
void set_print(int print) { print_ = print; }
/// Gets a handle to the JK object, if built by preiterations
std::shared_ptr<JK> jk() const { return jk_;}
/// Set the JK object, say from SCF
void set_jk(std::shared_ptr<JK> jk) { jk_ = jk; }
/// Gets a handle to the VBase object, if built by preiterations
std::shared_ptr<VBase> v() const { return v_;}
/// Set the VBase object, say from SCF (except that wouldn't work, right?)
void set_jk(std::shared_ptr<VBase> v) { v_ = v; }
/// Builds JK object, if needed
virtual void preiterations();
/// Destroys JK object, if needed
virtual void postiterations();
/// => Setters <= ///
void set_use_symmetry(bool usesym) { use_symmetry_ = usesym; }
/// Set convergence behavior
void set_convergence(double convergence) { convergence_ = convergence; }
/// Set reference info
void set_C(SharedMatrix C) { C_ = C; }
void set_Cocc(SharedMatrix Cocc) { Cocc_ = Cocc; }
void set_Cfocc(SharedMatrix Cfocc) { Cfocc_ = Cfocc; }
void set_Caocc(SharedMatrix Caocc) { Caocc_ = Caocc; }
void set_Cavir(SharedMatrix Cavir) { Cavir_ = Cavir; }
void set_Cfvir(SharedMatrix Cfvir) { Cfvir_ = Cfvir; }
void set_eps_focc(SharedVector eps) { eps_focc_ = eps; }
void set_eps_aocc(SharedVector eps) { eps_aocc_ = eps; }
void set_eps_avir(SharedVector eps) { eps_avir_ = eps; }
void set_eps_fvir(SharedVector eps) { eps_fvir_ = eps; }
void set_Eref(double Eref) { Eref_ = Eref; }
/// Update reference info
void set_reference(std::shared_ptr<Wavefunction> reference);
};
// => APPLIED CLASSES <= //
class RCIS : public RBase {
protected:
std::vector<std::tuple<double, int, int, int> > states_;
std::vector<SharedMatrix > singlets_;
std::vector<SharedMatrix > triplets_;
std::vector<double> E_singlets_;
std::vector<double> E_triplets_;
void sort_states();
virtual void print_header();
virtual void print_wavefunctions();
virtual void print_amplitudes();
virtual void print_transitions();
virtual void print_densities();
virtual SharedMatrix TDmo(SharedMatrix T1, bool singlet = true);
virtual SharedMatrix TDso(SharedMatrix T1, bool singlet = true);
virtual SharedMatrix TDao(SharedMatrix T1, bool singlet = true);
virtual SharedMatrix Dmo(SharedMatrix T1, bool diff = false);
virtual SharedMatrix Dso(SharedMatrix T1, bool diff = false);
virtual SharedMatrix Dao(SharedMatrix T1, bool diff = false);
virtual std::pair<SharedMatrix, std::shared_ptr<Vector> > Nmo(SharedMatrix T1, bool diff = false);
virtual std::pair<SharedMatrix, std::shared_ptr<Vector> > Nso(SharedMatrix T1, bool diff = false);
virtual std::pair<SharedMatrix, std::shared_ptr<Vector> > Nao(SharedMatrix T1, bool diff = false);
virtual std::pair<SharedMatrix, SharedMatrix > ADmo(SharedMatrix T1);
virtual std::pair<SharedMatrix, SharedMatrix > ADso(SharedMatrix T1);
virtual std::pair<SharedMatrix, SharedMatrix > ADao(SharedMatrix T1);
public:
RCIS(SharedWavefunction ref_wfn, Options& options);
virtual ~RCIS();
virtual double compute_energy();
};
class RTDHF : public RBase {
protected:
std::vector<SharedMatrix > singlets_X_;
std::vector<SharedMatrix > triplets_X_;
std::vector<SharedMatrix > singlets_Y_;
std::vector<SharedMatrix > triplets_Y_;
std::vector<double> E_singlets_;
std::vector<double> E_triplets_;
virtual void print_header();
public:
RTDHF(SharedWavefunction ref_wfn, Options& options);
virtual ~RTDHF();
virtual double compute_energy();
};
class RCPHF : public RBase {
protected:
// OV-Rotations
std::map<std::string, SharedMatrix> x_;
// OV-Perturbations
std::map<std::string, SharedMatrix> b_;
virtual void print_header();
void add_named_tasks();
void analyze_named_tasks();
void add_polarizability();
void analyze_polarizability();
std::set<std::string> tasks_;
public:
RCPHF(SharedWavefunction ref_wfn, Options& options, bool use_symmetry=true);
virtual ~RCPHF();
/// Solve for all perturbations currently in b
virtual double compute_energy();
/// Perturbation vector queue, shove tasks onto this guy before compute_energy
std::map<std::string, SharedMatrix>& b() { return b_; }
/// Resultant solution vectors, available after compute_energy is called
std::map<std::string, SharedMatrix>& x() { return x_; }
/// Add a named task
void add_task(const std::string& task);
};
class RCPKS : public RCPHF {
protected:
virtual void print_header();
public:
RCPKS(SharedWavefunction ref_wfn, Options& options);
virtual ~RCPKS();
virtual double compute_energy();
};
class RTDA : public RCIS {
protected:
virtual void print_header();
public:
RTDA(SharedWavefunction ref_wfn, Options& options);
virtual ~RTDA();
virtual double compute_energy();
};
class RTDDFT : public RTDHF {
protected:
virtual void print_header();
public:
RTDDFT(SharedWavefunction ref_wfn, Options& options);
virtual ~RTDDFT();
virtual double compute_energy();
};
}
#endif
| rmcgibbo/psi4public | psi4/src/psi4/libfock/apps.h | C | lgpl-3.0 | 7,398 |
<?php
/**
* @group regression
* @covers ApiKeys_ApiKeyStruct::validSecret
* User: dinies
* Date: 21/06/16
* Time: 15.50
*/
class GetUserApiKeyTest extends AbstractTest {
protected $uid;
private $test_data;
function setup() {
/**
* environment initialization
*/
$this->test_data = new StdClass();
$this->test_data->user = Factory_User::create();
$this->test_data->api_key = Factory_ApiKey::create( [
'uid' => $this->test_data->user->uid,
] );
}
public function test_getUser_success() {
$user = $this->test_data->api_key->getUser();
$this->assertTrue( $user instanceof Users_UserStruct );
$this->assertEquals( "{$this->test_data->user->uid}", $user->uid );
$this->assertEquals( "{$this->test_data->user->email}", $user->email );
$this->assertEquals( "{$this->test_data->user->salt}", $user->salt );
$this->assertEquals( "{$this->test_data->user->pass}", $user->pass );
$this->assertRegExp( '/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2]?[0-9]:[0-5][0-9]:[0-5][0-9]$/', $user->create_date );
$this->assertEquals( "{$this->test_data->user->create_date}", $user->create_date );
$this->assertEquals( "{$this->test_data->user->first_name}", $user->first_name );
$this->assertEquals( "{$this->test_data->user->last_name}", $user->last_name );
}
public function test_getUser_failure() {
$this->test_data->api_key->uid += 1000;
$this->assertNull( $this->test_data->api_key->getUser() );
}
} | riccio82/MateCat | test/unit/Structs/TestApiKeyStruct/GetUserApiKeyTest.php | PHP | lgpl-3.0 | 1,600 |
//
// System.Web.UI.HtmlControls.HtmlSelect.cs
//
// Author:
// Dick Porter <dick@ximian.com>
//
// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.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.
//
using System.Web.UI.WebControls;
using System.Web.Util;
using System.ComponentModel;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Security.Permissions;
namespace System.Web.UI.HtmlControls
{
// CAS
[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
// attributes
[DefaultEvent ("ServerChange")]
[ValidationProperty ("Value")]
[ControlBuilder (typeof (HtmlSelectBuilder))]
[SupportsEventValidation]
public class HtmlSelect : HtmlContainerControl, IPostBackDataHandler, IParserAccessor
{
static readonly object EventServerChange = new object ();
DataSourceView _boundDataSourceView;
bool requiresDataBinding;
bool _initialized;
object datasource;
ListItemCollection items;
public HtmlSelect () : base ("select")
{
}
[DefaultValue ("")]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription("")]
[WebCategory("Data")]
public virtual string DataMember {
get {
string member = Attributes["datamember"];
if (member == null) {
return (String.Empty);
}
return (member);
}
set {
if (value == null) {
Attributes.Remove ("datamember");
} else {
Attributes["datamember"] = value;
}
}
}
[DefaultValue (null)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription("")]
[WebCategory("Data")]
public virtual object DataSource {
get {
return (datasource);
}
set {
if ((value != null) &&
!(value is IEnumerable) &&
!(value is IListSource)) {
throw new ArgumentException ();
}
datasource = value;
}
}
[DefaultValue ("")]
public virtual string DataSourceID {
get {
return ViewState.GetString ("DataSourceID", "");
}
set {
if (DataSourceID == value)
return;
ViewState ["DataSourceID"] = value;
if (_boundDataSourceView != null)
_boundDataSourceView.DataSourceViewChanged -= OnDataSourceViewChanged;
_boundDataSourceView = null;
OnDataPropertyChanged ();
}
}
[DefaultValue ("")]
[WebSysDescription("")]
[WebCategory("Data")]
public virtual string DataTextField {
get {
string text = Attributes["datatextfield"];
if (text == null) {
return (String.Empty);
}
return (text);
}
set {
if (value == null) {
Attributes.Remove ("datatextfield");
} else {
Attributes["datatextfield"] = value;
}
}
}
[DefaultValue ("")]
[WebSysDescription("")]
[WebCategory("Data")]
public virtual string DataValueField {
get {
string value = Attributes["datavaluefield"];
if (value == null) {
return (String.Empty);
}
return (value);
}
set {
if (value == null) {
Attributes.Remove ("datavaluefield");
} else {
Attributes["datavaluefield"] = value;
}
}
}
public override string InnerHtml {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
public override string InnerText {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
protected bool IsBoundUsingDataSourceID {
get {
return (DataSourceID.Length != 0);
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
public ListItemCollection Items {
get {
if (items == null) {
items = new ListItemCollection ();
if (IsTrackingViewState)
((IStateManager) items).TrackViewState ();
}
return (items);
}
}
[DefaultValue ("")]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription("")]
[WebCategory("Behavior")]
public bool Multiple {
get {
string multi = Attributes["multiple"];
if (multi == null) {
return (false);
}
return (true);
}
set {
if (value == false) {
Attributes.Remove ("multiple");
} else {
Attributes["multiple"] = "multiple";
}
}
}
[DefaultValue ("")]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription("")]
[WebCategory("Behavior")]
public string Name {
get {
return (UniqueID);
}
set {
/* Do nothing */
}
}
protected bool RequiresDataBinding {
get { return requiresDataBinding; }
set { requiresDataBinding = value; }
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Browsable (false)]
public virtual int SelectedIndex {
get {
/* Make sure Items has been initialised */
ListItemCollection listitems = Items;
for (int i = 0; i < listitems.Count; i++) {
if (listitems[i].Selected) {
return (i);
}
}
/* There is always a selected item in
* non-multiple mode, if the size is
* <= 1
*/
if (!Multiple && Size <= 1) {
/* Select the first item */
if (listitems.Count > 0) {
/* And make it stick
* if there is
* anything in the
* list
*/
listitems[0].Selected = true;
}
return (0);
}
return (-1);
}
set {
ClearSelection ();
if (value == -1 || items == null) {
return;
}
if (value < 0 || value >= items.Count) {
throw new ArgumentOutOfRangeException ("value");
}
items[value].Selected = true;
}
}
/* "internal infrastructure" according to the docs,
* but has some documentation in 2.0
*/
protected virtual int[] SelectedIndices {
get {
ArrayList selected = new ArrayList ();
int count = Items.Count;
for (int i = 0; i < count; i++) {
if (Items [i].Selected) {
selected.Add (i);
}
}
return ((int[])selected.ToArray (typeof (int)));
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public int Size {
get {
string size = Attributes["size"];
if (size == null) {
return (-1);
}
return (Int32.Parse (size, Helpers.InvariantCulture));
}
set {
if (value == -1) {
Attributes.Remove ("size");
} else {
Attributes["size"] = value.ToString ();
}
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public string Value {
get {
int sel = SelectedIndex;
if (sel >= 0 && sel < Items.Count) {
return (Items[sel].Value);
}
return (String.Empty);
}
set {
int sel = Items.IndexOf (value);
if (sel >= 0) {
SelectedIndex = sel;
}
}
}
[WebSysDescription("")]
[WebCategory("Action")]
public event EventHandler ServerChange {
add {
Events.AddHandler (EventServerChange, value);
}
remove {
Events.RemoveHandler (EventServerChange, value);
}
}
protected override void AddParsedSubObject (object obj)
{
if (!(obj is ListItem)) {
throw new HttpException ("HtmlSelect can only contain ListItem");
}
Items.Add ((ListItem)obj);
base.AddParsedSubObject (obj);
}
/* "internal infrastructure" according to the docs,
* but has some documentation in 2.0
*/
protected virtual void ClearSelection ()
{
if (items == null) {
return;
}
int count = items.Count;
for (int i = 0; i < count; i++) {
items[i].Selected = false;
}
}
protected override ControlCollection CreateControlCollection ()
{
return (base.CreateControlCollection ());
}
protected void EnsureDataBound ()
{
if (IsBoundUsingDataSourceID && RequiresDataBinding)
DataBind ();
}
protected virtual IEnumerable GetData ()
{
if (DataSource != null && IsBoundUsingDataSourceID)
throw new HttpException ("Control bound using both DataSourceID and DataSource properties.");
if (DataSource != null)
return DataSourceResolver.ResolveDataSource (DataSource, DataMember);
if (!IsBoundUsingDataSourceID)
return null;
IEnumerable result = null;
DataSourceView boundDataSourceView = ConnectToDataSource ();
boundDataSourceView.Select (DataSourceSelectArguments.Empty, delegate (IEnumerable data) { result = data; });
return result;
}
protected override void LoadViewState (object savedState)
{
object first = null;
object second = null;
Pair pair = savedState as Pair;
if (pair != null) {
first = pair.First;
second = pair.Second;
}
base.LoadViewState (first);
if (second != null) {
IStateManager manager = Items as IStateManager;
manager.LoadViewState (second);
}
}
protected override void OnDataBinding (EventArgs e)
{
base.OnDataBinding (e);
/* Make sure Items has been initialised */
ListItemCollection listitems = Items;
listitems.Clear ();
IEnumerable list = GetData ();
if (list == null)
return;
foreach (object container in list) {
string text = null;
string value = null;
if (DataTextField == String.Empty &&
DataValueField == String.Empty) {
text = container.ToString ();
value = text;
} else {
if (DataTextField != String.Empty) {
text = DataBinder.Eval (container, DataTextField).ToString ();
}
if (DataValueField != String.Empty) {
value = DataBinder.Eval (container, DataValueField).ToString ();
} else {
value = text;
}
if (text == null &&
value != null) {
text = value;
}
}
if (text == null) {
text = String.Empty;
}
if (value == null) {
value = String.Empty;
}
ListItem item = new ListItem (text, value);
listitems.Add (item);
}
RequiresDataBinding = false;
IsDataBound = true;
}
protected virtual void OnDataPropertyChanged ()
{
if (_initialized)
RequiresDataBinding = true;
}
protected virtual void OnDataSourceViewChanged (object sender,
EventArgs e)
{
RequiresDataBinding = true;
}
protected internal override void OnInit (EventArgs e)
{
base.OnInit (e);
Page.PreLoad += new EventHandler (OnPagePreLoad);
}
protected virtual void OnPagePreLoad (object sender, EventArgs e)
{
Initialize ();
}
protected internal override void OnLoad (EventArgs e)
{
if (!_initialized)
Initialize ();
base.OnLoad (e);
}
void Initialize ()
{
_initialized = true;
if (!IsDataBound)
RequiresDataBinding = true;
if (IsBoundUsingDataSourceID)
ConnectToDataSource ();
}
bool IsDataBound{
get {
return ViewState.GetBool ("_DataBound", false);
}
set {
ViewState ["_DataBound"] = value;
}
}
DataSourceView ConnectToDataSource ()
{
if (_boundDataSourceView != null)
return _boundDataSourceView;
/* verify that the data source exists and is an IDataSource */
object ctrl = null;
Page page = Page;
if (page != null)
ctrl = page.FindControl (DataSourceID);
if (ctrl == null || !(ctrl is IDataSource)) {
string format;
if (ctrl == null)
format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. A control with ID '{1}' could not be found.";
else
format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. '{1}' is not an IDataSource.";
throw new HttpException (String.Format (format, ID, DataSourceID));
}
_boundDataSourceView = ((IDataSource)ctrl).GetView (String.Empty);
_boundDataSourceView.DataSourceViewChanged += OnDataSourceViewChanged;
return _boundDataSourceView;
}
protected internal override void OnPreRender (EventArgs e)
{
EnsureDataBound ();
base.OnPreRender (e);
Page page = Page;
if (page != null && !Disabled) {
page.RegisterRequiresPostBack (this);
page.RegisterEnabledControl (this);
}
}
protected virtual void OnServerChange (EventArgs e)
{
EventHandler handler = (EventHandler)Events[EventServerChange];
if (handler != null) {
handler (this, e);
}
}
protected override void RenderAttributes (HtmlTextWriter w)
{
Page page = Page;
if (page != null)
page.ClientScript.RegisterForEventValidation (UniqueID);
/* If there is no "name" attribute,
* LoadPostData doesn't work...
*/
w.WriteAttribute ("name", Name);
Attributes.Remove ("name");
/* Don't render the databinding attributes */
Attributes.Remove ("datamember");
Attributes.Remove ("datatextfield");
Attributes.Remove ("datavaluefield");
base.RenderAttributes (w);
}
protected internal override void RenderChildren (HtmlTextWriter w)
{
base.RenderChildren (w);
if (items == null)
return;
w.WriteLine ();
bool done_sel = false;
int count = items.Count;
for (int i = 0; i < count; i++) {
ListItem item = items[i];
w.Indent++;
/* Write the <option> elements this
* way so that the output HTML matches
* the ms version (can't make
* HtmlTextWriterTag.Option an inline
* element, cos that breaks other
* stuff.)
*/
w.WriteBeginTag ("option");
if (item.Selected && !done_sel) {
w.WriteAttribute ("selected", "selected");
if (!Multiple) {
done_sel = true;
}
}
w.WriteAttribute ("value", item.Value, true);
if (item.HasAttributes) {
AttributeCollection attrs = item.Attributes;
foreach (string key in attrs.Keys)
w.WriteAttribute (key, HttpUtility.HtmlAttributeEncode (attrs [key]));
}
w.Write (HtmlTextWriter.TagRightChar);
w.Write (HttpUtility.HtmlEncode(item.Text));
w.WriteEndTag ("option");
w.WriteLine ();
w.Indent--;
}
}
protected override object SaveViewState ()
{
object first = null;
object second = null;
first = base.SaveViewState ();
IStateManager manager = items as IStateManager;
if (manager != null) {
second = manager.SaveViewState ();
}
if (first == null && second == null)
return (null);
return new Pair (first, second);
}
/* "internal infrastructure" according to the docs,
* but has some documentation in 2.0
*/
protected virtual void Select (int[] selectedIndices)
{
if (items == null) {
return;
}
ClearSelection ();
int count = items.Count;
foreach (int i in selectedIndices) {
if (i >= 0 && i < count) {
items[i].Selected = true;
}
}
}
protected override void TrackViewState ()
{
base.TrackViewState ();
IStateManager manager = items as IStateManager;
if (manager != null) {
manager.TrackViewState ();
}
}
protected virtual void RaisePostDataChangedEvent ()
{
OnServerChange (EventArgs.Empty);
}
protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
{
/* postCollection contains the values that are
* selected
*/
string[] values = postCollection.GetValues (postDataKey);
bool changed = false;
if (values != null) {
if (Multiple) {
/* We have a set of
* selections. We can't just
* set the new list, because
* we need to know if the set
* has changed from last time
*/
int value_len = values.Length;
int[] old_sel = SelectedIndices;
int[] new_sel = new int[value_len];
int old_sel_len = old_sel.Length;
for (int i = 0; i < value_len; i++) {
new_sel[i] = Items.IndexOf (values[i]);
if (old_sel_len != value_len ||
old_sel[i] != new_sel[i]) {
changed = true;
}
}
if (changed) {
Select (new_sel);
}
} else {
/* Just take the first one */
int sel = Items.IndexOf (values[0]);
if (sel != SelectedIndex) {
SelectedIndex = sel;
changed = true;
}
}
}
if (changed)
ValidateEvent (postDataKey, String.Empty);
return (changed);
}
bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
{
return LoadPostData (postDataKey, postCollection);
}
void IPostBackDataHandler.RaisePostDataChangedEvent ()
{
RaisePostDataChangedEvent ();
}
}
}
| edwinspire/VSharp | class/System.Web/System.Web.UI.HtmlControls/HtmlSelect.cs | C# | lgpl-3.0 | 17,515 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Code Coverage for D:\work\log4php-tag\src\main\php/appenders</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-responsive.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="span12">
<ul class="breadcrumb">
<li><a href="index.html">D:\work\log4php-tag\src\main\php</a> <span class="divider">/</span></li>
<li class="active">appenders</li>
<li>(<a href="appenders.dashboard.html">Dashboard</a>)</li>
</ul>
</div>
</div>
</div>
</header>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<td> </td>
<td colspan="9"><div align="center"><strong>Code Coverage</strong></div></td>
</tr>
<tr>
<td> </td>
<td colspan="3"><div align="center"><strong>Lines</strong></div></td>
<td colspan="3"><div align="center"><strong>Functions and Methods</strong></div></td>
<td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
</tr>
</thead>
<tbody>
<tr>
<td class="success">Total</td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 76.66%;"></div>
</div>
</td>
<td class="success small"><div align="right">76.66%</div></td>
<td class="success small"><div align="right">463 / 604</div></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 60.14%;"></div>
</div>
</td>
<td class="warning small"><div align="right">60.14%</div></td>
<td class="warning small"><div align="right">83 / 138</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 28.57%;"></div>
</div>
</td>
<td class="danger small"><div align="right">28.57%</div></td>
<td class="danger small"><div align="right">4 / 14</div></td>
</tr>
<tr>
<td class="success"><i class="icon-file"></i> <a href="appenders_LoggerAppenderConsole.php.html">LoggerAppenderConsole.php</a></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 92.86%;"></div>
</div>
</td>
<td class="success small"><div align="right">92.86%</div></td>
<td class="success small"><div align="right">26 / 28</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 80.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">80.00%</div></td>
<td class="success small"><div align="right">4 / 5</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="success"><i class="icon-file"></i> <a href="appenders_LoggerAppenderDailyFile.php.html">LoggerAppenderDailyFile.php</a></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">25 / 25</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">6 / 6</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">1 / 1</div></td>
</tr>
<tr>
<td class="success"><i class="icon-file"></i> <a href="appenders_LoggerAppenderEcho.php.html">LoggerAppenderEcho.php</a></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">22 / 22</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">4 / 4</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">1 / 1</div></td>
</tr>
<tr>
<td class="warning"><i class="icon-file"></i> <a href="appenders_LoggerAppenderFile.php.html">LoggerAppenderFile.php</a></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 60.56%;"></div>
</div>
</td>
<td class="warning small"><div align="right">60.56%</div></td>
<td class="warning small"><div align="right">43 / 71</div></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 42.86%;"></div>
</div>
</td>
<td class="warning small"><div align="right">42.86%</div></td>
<td class="warning small"><div align="right">6 / 14</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="success"><i class="icon-file"></i> <a href="appenders_LoggerAppenderFirePHP.php.html">LoggerAppenderFirePHP.php</a></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 80.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">80.00%</div></td>
<td class="success small"><div align="right">24 / 30</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 75.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">75.00%</div></td>
<td class="success small"><div align="right">3 / 4</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="warning"><i class="icon-file"></i> <a href="appenders_LoggerAppenderMail.php.html">LoggerAppenderMail.php</a></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 67.74%;"></div>
</div>
</td>
<td class="warning small"><div align="right">67.74%</div></td>
<td class="warning small"><div align="right">21 / 31</div></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 44.44%;"></div>
</div>
</td>
<td class="warning small"><div align="right">44.44%</div></td>
<td class="warning small"><div align="right">4 / 9</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="warning"><i class="icon-file"></i> <a href="appenders_LoggerAppenderMailEvent.php.html">LoggerAppenderMailEvent.php</a></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 58.70%;"></div>
</div>
</td>
<td class="warning small"><div align="right">58.70%</div></td>
<td class="warning small"><div align="right">27 / 46</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 23.08%;"></div>
</div>
</td>
<td class="danger small"><div align="right">23.08%</div></td>
<td class="danger small"><div align="right">3 / 13</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="success"><i class="icon-file"></i> <a href="appenders_LoggerAppenderMongoDB.php.html">LoggerAppenderMongoDB.php</a></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 84.21%;"></div>
</div>
</td>
<td class="success small"><div align="right">84.21%</div></td>
<td class="success small"><div align="right">80 / 95</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 86.36%;"></div>
</div>
</td>
<td class="success small"><div align="right">86.36%</div></td>
<td class="success small"><div align="right">19 / 22</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="success"><i class="icon-file"></i> <a href="appenders_LoggerAppenderNull.php.html">LoggerAppenderNull.php</a></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">1 / 1</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">1 / 1</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">1 / 1</div></td>
</tr>
<tr>
<td class="warning"><i class="icon-file"></i> <a href="appenders_LoggerAppenderPDO.php.html">LoggerAppenderPDO.php</a></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 64.06%;"></div>
</div>
</td>
<td class="warning small"><div align="right">64.06%</div></td>
<td class="warning small"><div align="right">41 / 64</div></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 38.89%;"></div>
</div>
</td>
<td class="warning small"><div align="right">38.89%</div></td>
<td class="warning small"><div align="right">7 / 18</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="success"><i class="icon-file"></i> <a href="appenders_LoggerAppenderPhp.php.html">LoggerAppenderPhp.php</a></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">8 / 8</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">1 / 1</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">1 / 1</div></td>
</tr>
<tr>
<td class="success"><i class="icon-file"></i> <a href="appenders_LoggerAppenderRollingFile.php.html">LoggerAppenderRollingFile.php</a></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 77.42%;"></div>
</div>
</td>
<td class="success small"><div align="right">77.42%</div></td>
<td class="success small"><div align="right">72 / 93</div></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 46.67%;"></div>
</div>
</td>
<td class="warning small"><div align="right">46.67%</div></td>
<td class="warning small"><div align="right">7 / 15</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="warning"><i class="icon-file"></i> <a href="appenders_LoggerAppenderSocket.php.html">LoggerAppenderSocket.php</a></td>
<td class="warning big"> <div class="progress progress-warning" style="width: 100px;">
<div class="bar" style="width: 53.33%;"></div>
</div>
</td>
<td class="warning small"><div align="right">53.33%</div></td>
<td class="warning small"><div align="right">16 / 30</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 33.33%;"></div>
</div>
</td>
<td class="danger small"><div align="right">33.33%</div></td>
<td class="danger small"><div align="right">3 / 9</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="success"><i class="icon-file"></i> <a href="appenders_LoggerAppenderSyslog.php.html">LoggerAppenderSyslog.php</a></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 95.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">95.00%</div></td>
<td class="success small"><div align="right">57 / 60</div></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 88.24%;"></div>
</div>
</td>
<td class="success small"><div align="right">88.24%</div></td>
<td class="success small"><div align="right">15 / 17</div></td>
<td class="danger big"> <div class="progress progress-danger" style="width: 100px;">
<div class="bar" style="width: 0.00%;"></div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
</tbody>
</table>
<footer>
<h4>Legend</h4>
<p>
<span class="danger"><strong>Low</strong>: 0% to 35%</span>
<span class="warning"><strong>Medium</strong>: 35% to 70%</span>
<span class="success"><strong>High</strong>: 70% to 100%</span>
</p>
<p>
<small>Generated by <a href="http://github.com/sebastianbergmann/php-code-coverage" target="_top">PHP_CodeCoverage 1.2.3</a> using <a href="http://www.php.net/" target="_top">PHP 5.3.13</a> and <a href="http://phpunit.de/">PHPUnit 3.7.6</a> at Mon Oct 8 16:41:13 BST 2012.</small>
</p>
</footer>
</div>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
</body>
</html>
| MobiusMedical/sg-oc | lib/apache-log4php-2.3.0/site/coverage-report/appenders.html | HTML | lgpl-3.0 | 18,382 |
//
// ServiceCredentials.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2005 Novell, Inc. http://www.novell.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.
//
using System;
using System.Collections.ObjectModel;
using System.IdentityModel.Selectors;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
namespace System.ServiceModel.Description
{
public class ServiceCredentials
: SecurityCredentialsManager, IServiceBehavior
{
public ServiceCredentials ()
{
}
protected ServiceCredentials (ServiceCredentials other)
{
initiator = other.initiator.Clone ();
peer = other.peer.Clone ();
recipient = other.recipient.Clone ();
userpass = other.userpass.Clone ();
windows = other.windows.Clone ();
issued_token = other.issued_token.Clone ();
secure_conversation = other.secure_conversation.Clone ();
}
X509CertificateInitiatorServiceCredential initiator
= new X509CertificateInitiatorServiceCredential ();
PeerCredential peer = new PeerCredential ();
X509CertificateRecipientServiceCredential recipient
= new X509CertificateRecipientServiceCredential ();
UserNamePasswordServiceCredential userpass
= new UserNamePasswordServiceCredential ();
WindowsServiceCredential windows
= new WindowsServiceCredential ();
IssuedTokenServiceCredential issued_token =
new IssuedTokenServiceCredential ();
SecureConversationServiceCredential secure_conversation =
new SecureConversationServiceCredential ();
public X509CertificateInitiatorServiceCredential ClientCertificate {
get { return initiator; }
}
public IssuedTokenServiceCredential IssuedTokenAuthentication {
get { return issued_token; }
}
public PeerCredential Peer {
get { return peer; }
}
public SecureConversationServiceCredential SecureConversationAuthentication {
get { return secure_conversation; }
}
public X509CertificateRecipientServiceCredential ServiceCertificate {
get { return recipient; }
}
public UserNamePasswordServiceCredential UserNameAuthentication {
get { return userpass; }
}
public WindowsServiceCredential WindowsAuthentication {
get { return windows; }
}
public ServiceCredentials Clone ()
{
ServiceCredentials ret = CloneCore ();
if (ret.GetType () != GetType ())
throw new NotImplementedException ("CloneCore() must be implemented to return an instance of the same type in this custom ServiceCredentials type.");
return ret;
}
protected virtual ServiceCredentials CloneCore ()
{
return new ServiceCredentials (this);
}
public override SecurityTokenManager CreateSecurityTokenManager ()
{
return new ServiceCredentialsSecurityTokenManager (this);
}
void IServiceBehavior.AddBindingParameters (
ServiceDescription description,
ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection parameters)
{
parameters.Add (this);
}
void IServiceBehavior.ApplyDispatchBehavior (
ServiceDescription description,
ServiceHostBase serviceHostBase)
{
// do nothing
}
[MonoTODO]
void IServiceBehavior.Validate (
ServiceDescription description,
ServiceHostBase serviceHostBase)
{
// unlike MSDN description, it does not throw NIE.
}
}
}
| edwinspire/VSharp | class/System.ServiceModel/System.ServiceModel.Description/ServiceCredentials.cs | C# | lgpl-3.0 | 4,458 |
"use strict";
var express = require('express');
var less = require('less-middleware');
function HttpServer(port, staticServedPath, logRequest) {
this.port = port;
this.staticServedPath = staticServedPath;
this.logRequest = (typeof logRequest === "undefined") ? true : logRequest;
}
HttpServer.prototype.start = function(fn) {
console.log("Starting server");
var self = this;
var app = express();
self.app = app;
if(self.logRequest) {
app.use(function (req, res, next) {
console.log(req.method, req.url);
next();
});
}
app.use('/', express.static(self.staticServedPath));
self.server = app.listen(self.port, function () {
console.log("Server started on port", self.port);
if (fn !== undefined) fn();
});
};
HttpServer.prototype.stop = function() {
console.log("Stopping server");
var self = this;
self.server.close();
};
module.exports = HttpServer; | o-schneider/heroesdesk-front-web | src/server/HttpServer.js | JavaScript | lgpl-3.0 | 917 |
import java.util.*;
public class LineNumbersTest extends LinkedList<Object>{
public LineNumbersTest(int x) {
super((x & 0) == 1 ?
new LinkedList<Object>((x & 1) == x++ ? new ArrayList<Object>() : new HashSet<Object>())
:new HashSet<Object>());
super.add(x = getLineNo());
this.add(x = getLineNo());
}
static int getLineNo() {
return new Throwable().fillInStackTrace().getStackTrace()[1].getLineNumber();
}
public static void main(String[] args) {
System.out.println(getLineNo());
System.out.println(new Throwable().fillInStackTrace().getStackTrace()[0].getFileName());
System.out.println(getLineNo());
System.out.println(new LineNumbersTest(2));
List<Object> foo = new ArrayList<>();
System.out.println(foo.addAll(foo));
}
}
| xtiankisutsa/MARA_Framework | tools/decompilers/Krakatau/tests/disassembler/source/LineNumbersTest.java | Java | lgpl-3.0 | 857 |
#!/bin/bash
#python pyinstaller-pyinstaller-67b940c/pyinstaller.py ../pyNastran/pyNastran/gui/gui.py
rm -rf build dist
python pyinstaller-pyinstaller-67b940c/pyinstaller.py pyNastranGUI.spec
#dist/pywin27/gui.exe
#dist/gui/gui.exe
| saullocastro/pyNastran | dev/pyNastranGUI_build.sh | Shell | lgpl-3.0 | 239 |
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_mobile_dressed_tatooine_om_aynat = object_mobile_shared_dressed_tatooine_om_aynat:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_tatooine_om_aynat, "object/mobile/dressed_tatooine_om_aynat.iff")
| kidaa/Awakening-Core3 | bin/scripts/object/mobile/dressed_tatooine_om_aynat.lua | Lua | lgpl-3.0 | 2,216 |
using System;
using System.Collections.Generic;
using DoxygenWrapper.Wrappers.Compounds.Types;
using System.Xml;
namespace DoxygenWrapper.Wrappers.Compounds
{
public class CompoundMember:
Compound
{
protected override void OnParse(XmlNode _node)
{
base.OnParse(_node);
mCompoundType = new CompoundType(_node["type"], _node["name"].Value);
}
public CompoundType CompoundType
{
get { return mCompoundType; }
}
private CompoundType mCompoundType;
}
}
| blunted2night/MyGUI | Wrappers/DoxygenWrapper/DoxygenWrapper/Wrappers/Compounds/CompoundMember.cs | C# | lgpl-3.0 | 508 |
package org.opennaas.client.rest;
import java.io.FileNotFoundException;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBException;
import org.apache.log4j.Logger;
import org.opennaas.extensions.router.model.EnabledLogicalElement.EnabledState;
import org.opennaas.extensions.router.model.GRETunnelConfiguration;
import org.opennaas.extensions.router.model.GRETunnelService;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
public class GRETunnelTest {
private static final Logger LOGGER = Logger.getLogger(GRETunnelTest.class);
public static void main(String[] args) throws FileNotFoundException, JAXBException {
createGRETunnel();
deleteGRETunnel();
showGRETunnelConfiguration();
}
/**
*
*/
private static void createGRETunnel() {
ClientResponse response = null;
String url = "http://localhost:8888/opennaas/router/lolaM20/gretunnel/createGRETunnel";
try {
Client client = Client.create();
WebResource webResource = client.resource(url);
response = webResource.type(MediaType.APPLICATION_XML).post(ClientResponse.class, getGRETunnelService());
LOGGER.info("Response code: " + response.getStatus());
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
*
*/
private static void deleteGRETunnel() {
ClientResponse response = null;
String url = "http://localhost:8888/opennaas/router/lolaM20/gretunnel/deleteGRETunnel";
try {
Client client = Client.create();
WebResource webResource = client.resource(url);
response = webResource.type(MediaType.APPLICATION_XML).post(ClientResponse.class, getGRETunnelService());
LOGGER.info("Response code: " + response.getStatus());
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
*
*/
private static void showGRETunnelConfiguration() {
List<GRETunnelService> response = null;
String url = "http://localhost:8888/opennaas/router/lolaM20/gretunnel/showGRETunnelConfiguration";
GenericType<List<GRETunnelService>> genericType =
new GenericType<List<GRETunnelService>>() {
};
try {
Client client = Client.create();
WebResource webResource = client.resource(url);
response = webResource.accept(MediaType.APPLICATION_XML).post(genericType);
LOGGER.info("Number of GRETunnels: " + response.size());
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
* @return
*/
private static GRETunnelService getGRETunnelService() {
GRETunnelService greTunnelService = new GRETunnelService();
greTunnelService.setName("MyTunnelService");
greTunnelService.setEnabledState(EnabledState.OTHER);
GRETunnelConfiguration greTunnelConfiguration = new GRETunnelConfiguration();
greTunnelConfiguration.setCaption("MyCaption");
greTunnelConfiguration.setInstanceID("MyInstanceId");
greTunnelService.setGRETunnelConfiguration(greTunnelConfiguration);
return greTunnelService;
}
} | dana-i2cat/opennaas | utils/rest-client/src/test/java/org/opennaas/client/rest/GRETunnelTest.java | Java | lgpl-3.0 | 3,036 |
/////////////////////////////////////////////////////////////////////////////
// Name: wx/spinbutt.h
// Purpose: wxSpinButtonBase class
// Author: Julian Smart, Vadim Zeitlin
// Modified by:
// Created: 23.07.99
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_SPINBUTT_H_BASE_
#define _WX_SPINBUTT_H_BASE_
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/defs.h"
#if wxUSE_SPINBTN
#include "wx/control.h"
#include "wx/event.h"
#include "wx/range.h"
#define wxSPIN_BUTTON_NAME wxT("wxSpinButton")
// ----------------------------------------------------------------------------
// The wxSpinButton is like a small scrollbar than is often placed next
// to a text control.
//
// Styles:
// wxSP_HORIZONTAL: horizontal spin button
// wxSP_VERTICAL: vertical spin button (the default)
// wxSP_ARROW_KEYS: arrow keys increment/decrement value
// wxSP_WRAP: value wraps at either end
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxSpinButtonBase : public wxControl
{
public:
// ctor initializes the range with the default (0..100) values
wxSpinButtonBase() { m_min = 0; m_max = 100; }
// accessors
virtual int GetValue() const = 0;
virtual int GetMin() const { return m_min; }
virtual int GetMax() const { return m_max; }
wxRange GetRange() const { return wxRange( GetMin(), GetMax() );}
// operations
virtual void SetValue(int val) = 0;
virtual void SetMin(int minVal) { SetRange ( minVal , m_max ) ; }
virtual void SetMax(int maxVal) { SetRange ( m_min , maxVal ) ; }
virtual void SetRange(int minVal, int maxVal)
{
m_min = minVal;
m_max = maxVal;
}
void SetRange( const wxRange& range) { SetRange( range.GetMin(), range.GetMax()); }
// is this spin button vertically oriented?
bool IsVertical() const { return (m_windowStyle & wxSP_VERTICAL) != 0; }
protected:
// the range value
int m_min;
int m_max;
wxDECLARE_NO_COPY_CLASS(wxSpinButtonBase);
};
// ----------------------------------------------------------------------------
// include the declaration of the real class
// ----------------------------------------------------------------------------
#if defined(__WXUNIVERSAL__)
#include "wx/univ/spinbutt.h"
#elif defined(__WXMSW__)
#include "wx/msw/spinbutt.h"
#elif defined(__WXMOTIF__)
#include "wx/motif/spinbutt.h"
#elif defined(__WXGTK20__)
#include "wx/gtk/spinbutt.h"
#elif defined(__WXGTK__)
#include "wx/gtk1/spinbutt.h"
#elif defined(__WXMAC__)
#include "wx/osx/spinbutt.h"
#elif defined(__WXCOCOA__)
#include "wx/cocoa/spinbutt.h"
#elif defined(__WXPM__)
#include "wx/os2/spinbutt.h"
#endif
// ----------------------------------------------------------------------------
// the wxSpinButton event
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxSpinEvent : public wxNotifyEvent
{
public:
wxSpinEvent(wxEventType commandType = wxEVT_NULL, int winid = 0)
: wxNotifyEvent(commandType, winid)
{
}
wxSpinEvent(const wxSpinEvent& event) : wxNotifyEvent(event) {}
// get the current value of the control
int GetValue() const { return m_commandInt; }
void SetValue(int value) { m_commandInt = value; }
int GetPosition() const { return m_commandInt; }
void SetPosition(int pos) { m_commandInt = pos; }
virtual wxEvent *Clone() const { return new wxSpinEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxSpinEvent)
};
typedef void (wxEvtHandler::*wxSpinEventFunction)(wxSpinEvent&);
#define wxSpinEventHandler(func) \
wxEVENT_HANDLER_CAST(wxSpinEventFunction, func)
// macros for handling spin events: notice that we must use the real values of
// the event type constants and not their references (wxEVT_SPIN[_UP/DOWN])
// here as otherwise the event tables could end up with non-initialized
// (because of undefined initialization order of the globals defined in
// different translation units) references in them
#define EVT_SPIN_UP(winid, func) \
wx__DECLARE_EVT1(wxEVT_SPIN_UP, winid, wxSpinEventHandler(func))
#define EVT_SPIN_DOWN(winid, func) \
wx__DECLARE_EVT1(wxEVT_SPIN_DOWN, winid, wxSpinEventHandler(func))
#define EVT_SPIN(winid, func) \
wx__DECLARE_EVT1(wxEVT_SPIN, winid, wxSpinEventHandler(func))
#endif // wxUSE_SPINBTN
#endif
// _WX_SPINBUTT_H_BASE_
| dariusliep/LogViewer | thirdparty/wxWidgets-3.0.0/include/wx/spinbutt.h | C | lgpl-3.0 | 4,861 |
{extends file="layout.tpl"}
{block name="init"}
{$product_id={product attr="id"}}
{$pse_count=1}
{$product_virtual={product attr="virtual"}}
{$check_availability={config key="check-available-stock" default="1"}}
{/block}
{* Body Class *}
{block name="body-class"}page-product{/block}
{* Page Title *}
{block name='no-return-functions' append}
{loop name="product.seo.title" type="product" id=$product_id limit="1" with_prev_next_info="1"}
{$page_title = {$META_TITLE}}
{/loop}
{/block}
{* Meta *}
{block name="meta"}
{loop name="product.seo.meta" type="product" id=$product_id limit="1" with_prev_next_info="1"}
{include file="includes/meta-seo.html"}
{/loop}
{/block}
{* Breadcrumb *}
{block name='no-return-functions' append}
{$breadcrumbs = []}
{loop type="product" name="product_breadcrumb" id=$product_id limit="1" with_prev_next_info="1"}
{loop name="category_path" type="category-path" category="{$DEFAULT_CATEGORY}"}
{$breadcrumbs[] = ['title' => {$TITLE}, 'url'=> {$URL nofilter}]}
{/loop}
{$breadcrumbs[] = ['title' => {$TITLE}, 'url'=> {$URL nofilter}]}
{/loop}
{/block}
{* Content *}
{block name="main-content"}
{if $product_id}
<div class="main">
{loop name="product.details" type="product" id=$product_id limit="1" with_prev_next_info="1" with_prev_next_visible="1"}
<article id="product" class="col-main row" role="main" itemscope itemtype="http://schema.org/Product">
{$pse_count=$PSE_COUNT}
{* Use the meta tag to specify content that is not visible on the page in any way *}
{loop name="brand.feature" type="brand" product="{$ID}"}
<meta itemprop="brand" content="{$TITLE}">
{/loop}
{* Add custom feature if needed
{loop name="isbn.feature" type="feature" product="{$ID}" title="isbn"}
{loop name="isbn.value" type="feature_value" feature="{$ID}" product="{product attr="id"}"}
<meta itemprop="productID" content="isbn:{$TITLE}">
{/loop}
{/loop}
*}
{hook name="product.top" product="{$ID}"}
{ifhook rel="product.gallery"}
{hook name="product.gallery" product="{$ID}"}
{/ifhook}
{elsehook rel="product.gallery"}
<section id="product-gallery" class="col-sm-6">
{ifloop rel="image.main"}
<figure class="product-image">
{loop type="image" name="image.main" product="{$ID}" width="560" height="445" resize_mode="borders" limit="1"}
<img src="{$IMAGE_URL nofilter}" alt="{$TITLE}" class="img-responsive" itemprop="image" data-toggle="magnify">
{/loop}
</figure>
{/ifloop}
{ifloop rel="image.carousel"}
<div id="product-thumbnails" class="carousel slide" style="position:relative;">
<div class="carousel-inner">
<div class="item active">
<ul class="list-inline">
{loop name="image.carousel" type="image" product="{$ID}" width="560" height="445" resize_mode="borders" limit="5"}
<li>
<a href="{$IMAGE_URL nofilter}" class="thumbnail {if $LOOP_COUNT == 1}active{/if}">
{loop type="image" name="image.thumbs" id="{$ID}" product="$OBJECT_ID" width="118" height="85" resize_mode="borders"}
<img src="{$IMAGE_URL nofilter}" alt="{$TITLE}">
{/loop}
</a>
</li>
{/loop}
</ul>
</div>
{ifloop rel="image.carouselsup"}
<div class="item">
<ul class="list-inline">
{loop name="image.carouselsup" type="image" product="{$ID}" width="560" height="445" resize_mode="borders" offset="5"}
<li>
<a href="{$IMAGE_URL nofilter}" class="thumbnail">
{loop type="image" name="image.thumbssup" id="{$ID}" product="$OBJECT_ID" width="118" height="85" resize_mode="borders"}
<img src="{$IMAGE_URL nofilter}" alt="{$TITLE}">
{/loop}
</a>
</li>
{/loop}
</ul>
</div>
{/ifloop}
</div>
{ifloop rel="image.carouselsup"}
<a class="left carousel-control" href="#product-thumbnails" data-slide="prev"><i class="fa fa-caret-left"></i></a>
<a class="right carousel-control" href="#product-thumbnails" data-slide="next"><i class="fa fa-caret-right"></i></a>
{/ifloop}
</div>
{/ifloop}
</section>
{/elsehook}
<section id="product-details" class="col-sm-6">
{hook name="product.details-top" product="{$ID}"}
<div class="product-info">
<h1 class="name"><span itemprop="name">{$TITLE}</span><span id="pse-name" class="pse-name"></span></h1>
{if $REF}<span itemprop="sku" class="sku">{intl l='Ref.'}: <span id="pse-ref">{$REF}</span></span>{/if}
{loop name="brand_info" type="brand" product="{$ID}" limit="1"}
<p><a href="{$URL nofilter}" title="{intl l="More information about this brand"}"><span itemprop="brand">{$TITLE}</span></a></p>
{/loop}
{if $POSTSCRIPTUM}<div class="short-description">
<p>{$POSTSCRIPTUM}</p>
</div>{/if}
</div>
{loop type="sale" name="product-sale-info" product="{$ID}" active="1"}
<div class="product-promo">
<p class="sale-label">{$SALE_LABEL}</p>
<p class="sale-saving"> {intl l="Save %amount%sign on this product" amount={$PRICE_OFFSET_VALUE} sign={$PRICE_OFFSET_SYMBOL}}</p>
{if $HAS_END_DATE}
<p class="sale-period">{intl l="This offer is valid until %date" date={format_date date=$END_DATE output="date"}}</p>
{/if}
</div>
{/loop}
<div class="product-price" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
<div class="availability">
<span class="availibity-label sr-only">{intl l="Availability"}: </span>
<span itemprop="availability" href="{$current_stock_href}" class="" id="pse-availability">
<span class="in">{intl l='In Stock'}</span>
<span class="out">{intl l='Out of Stock'}</span>
</span>
</div>
<div class="price-container">
{loop type="category" name="category_tag" id=$DEFAULT_CATEGORY}
<meta itemprop="category" content="{$TITLE}">
{/loop}
{* List of condition : NewCondition, DamagedCondition, UsedCondition, RefurbishedCondition *}
<meta itemprop="itemCondition" itemscope itemtype="http://schema.org/NewCondition">
{* List of currency : The currency used to describe the product price, in three-letter ISO format. *}
<meta itemprop="priceCurrency" content="{currency attr="symbol"}">
<span id="pse-promo">
<span class="special-price"><span itemprop="price" class="price-label">{intl l="Special Price:"} </span><span id="pse-price" class="price">{format_money number=$TAXED_PROMO_PRICE}</span></span>
{if $SHOW_ORIGINAL_PRICE}
<span class="old-price"><span class="price-label">{intl l="Regular Price:"} </span><span id="pse-price-old" class="price">{format_money number=$TAXED_PRICE}</span></span>
{/if}
</span>
</div>
<div id="pse-validity" class="validity alert alert-warning" style="display: none;" >
{intl l="Sorry but this combination does not exist."}
</div>
</div>
{form name="thelia.cart.add" }
<form id="form-product-details" action="{url path="/cart/add" }" method="post" class="form-product">
{form_hidden_fields}
<input type="hidden" name="view" value="product">
<input type="hidden" name="product_id" value="{$ID}">
{form_field field="append"}
<input type="hidden" name="{$name}" value="1">
{/form_field}
{if $form_error}<div class="alert alert-error">{$form_error_message}</div>{/if}
{form_field field="product"}
<input id="{$label_attr.for}" type="hidden" name="{$name}" value="{$ID}" {$attr} >
{/form_field}
{* pse *}
{form_field field='product_sale_elements_id'}
<input id="pse-id" class="pse-id" type="hidden" name="{$name}" value="{$PRODUCT_SALE_ELEMENT}" {$attr} >
{/form_field}
{if $pse_count > 1}
{* We have more than 1 combination: custom form *}
<fieldset id="pse-options" class="product-options">
{loop name="attributes" type="attribute" product="$product_id" order="manual"}
<div class="option option-option">
<label for="option-{$ID}" class="option-heading">{$TITLE}</label>
<div class="option-content clearfix">
<select id="option-{$ID}" name="option-{$ID}" class="form-control input-sm pse-option" data-attribute="{$ID}"></select>
</div>
</div>
{/loop}
<div class="option option-fallback">
<label for="option-fallback" class="option-heading">{intl l="Options"}</label>
<div class="option-content clearfix">
<select id="option-fallback" name="option-fallback" class="form-control input-sm pse-option pse-fallback" data-attribute="0"></select>
</div>
</div>
</fieldset>
{/if}
<fieldset class="product-cart form-inline">
{form_field field='quantity'}
<div class="form-group group-qty {if $error}has-error{elseif $value != "" && !$error}has-success{/if}">
<label for="{$label_attr.for}">{$label}</label>
<input type="number" name="{$name}" id="{$label_attr.for}" class="form-control" value="{$value|default:1}" min="1" required>
{if $error }
<span class="help-block">{$message}</span>
{elseif $value != "" && !$error}
<span class="help-block"><i class="fa fa-check"></i></span>
{/if}
</div>
{/form_field}
<div class="form-group group-btn">
<button id="pse-submit" type="submit" class="btn btn_add_to_cart btn-primary"><i class="fa fa-chevron-right"></i> {intl l="Add to cart"}</button>
</div>
</fieldset>
</form>
{/form}
{hook name="product.details-bottom" product="{$ID}"}
</section>
{strip}
{capture "additional"}
{ifloop rel="feature_info"}
<ul>
{loop name="feature_info" type="feature" product="{$ID}"}
{ifloop rel="feature_value_info"}
<li>
<strong>{$TITLE}</strong> :
{loop name="feature_value_info" type="feature_value" feature="{$ID}" product="{product attr="id"}"}
{if $LOOP_COUNT > 1}, {else} {/if}
<span>{if $IS_FREE_TEXT == 1}{$FREE_TEXT_VALUE}{else}{$TITLE}{/if}</span>
{/loop}
</li>
{/ifloop}
{/loop}
</ul>
{/ifloop}
{/capture}
{/strip}
{strip}
{capture "brand_info"}
{loop name="brand_info" type="brand" product="{$ID}" limit="1"}
<p><strong><a href="{$URL nofilter}">{$TITLE}</a></strong></p>
{loop name="brand.image" type="image" source="brand" id={$LOGO_IMAGE_ID} width=218 height=146 resize_mode="borders"}
<p><a href="{$URL nofilter}"><img itemprop="image" src="{$IMAGE_URL nofilter}" alt="{$TITLE}"></a></p>
{/loop}
{if $CHAPO}
<div class="chapo">
{$CHAPO}
</div>
{/if}
{if $DESCRIPTION}
<div class="description">
{$DESCRIPTION nofilter}
</div>
{/if}
{if $POSTSCRIPTUM}
<small class="postscriptum">
{$POSTSCRIPTUM}
</small>
{/if}
{/loop}
{/capture}
{/strip}
{strip}
{capture "document"}
{ifloop rel="document"}
<ul>
{loop name="document" type="document" product=$ID visible="yes"}
<li>
<a href="{$DOCUMENT_URL}" title="{$TITLE}" target="_blank">{$TITLE}</a>
</li>
{/loop}
</ul>
{/ifloop}
{/capture}
{/strip}
<section id="product-tabs" class="col-sm-12">
{hookblock name="product.additional" product="{product attr="id"}" fields="id,class,title,content"}
<ul class="nav nav-tabs" role="tablist">
<li class="active" role="presentation"><a id="tab1" href="#description" data-toggle="tab" role="tab">{intl l="Description"}</a></li>
{if $smarty.capture.additional ne ""}<li role="presentation"><a id="tab2" href="#additional" data-toggle="tab" role="tab">{intl l="Additional Info"}</a></li>{/if}
{if $smarty.capture.brand_info ne ""}<li role="presentation"><a id="tab3" href="#brand_info" data-toggle="tab" role="tab">{intl l="Brand information"}</a></li>{/if}
{if $smarty.capture.document ne ""}<li role="presentation"><a id="tab4" href="#document" data-toggle="tab" role="tab">{intl l="Documents"}</a></li>{/if}
{forhook rel="product.additional"}
<li role="presentation"><a id="tab{$id}" href="#{$id}" data-toggle="tab" role="tab">{$title}</a></li>
{/forhook}
</ul>
<div class="tab-content">
<div class="tab-pane active in" id="description" itemprop="description" role="tabpanel" aria-labelledby="tab1">
<p>{$DESCRIPTION|default:'N/A' nofilter}</p>
</div>
{if $smarty.capture.additional ne ""}
<div class="tab-pane" id="additional" role="tabpanel" aria-labelledby="tab2">
{$smarty.capture.additional nofilter}
</div>
{/if}
{if $smarty.capture.brand_info ne ""}
<div class="tab-pane" id="brand_info" role="tabpanel" aria-labelledby="tab3">
{$smarty.capture.brand_info nofilter}
</div>
{/if}
{if $smarty.capture.document ne ""}
<div class="tab-pane" id="document" role="tabpanel" aria-labelledby="tab4">
{$smarty.capture.document nofilter}
</div>
{/if}
{forhook rel="product.additional"}
<div class="tab-pane" id="{$id}" role="tabpanel" aria-labelledby="tab{$id}">
{$content nofilter}
</div>
{/forhook}
</div>
{/hookblock}
</section>
{hook name="product.bottom" product="{$ID}"}
{* javascript confiuguration to display pse *}
{$pse=[]}
{$combination_label=[]}
{$combination_values=[]}
{loop name="pse" type="product_sale_elements" product="{product attr="id"}"}
{$pse[$ID]=["id" => $ID, "isDefault" => $IS_DEFAULT, "isPromo" => $IS_PROMO, "isNew" => $IS_NEW, "ref" => "{$REF}", "ean" => "{$EAN}", "quantity" => {$QUANTITY}, "price" => "{format_money number=$TAXED_PRICE}", "promo" => "{format_money number=$TAXED_PROMO_PRICE}" ]}
{$pse_combination=[]}
{loop name="combi" type="attribute_combination" product_sale_elements="$ID" order="manual"}
{if ! $combination_label[$ATTRIBUTE_ID]}
{$combination_label[$ATTRIBUTE_ID]=["name" => "{$ATTRIBUTE_TITLE}", "values" => []]}
{/if}
{if ! $combination_values[$ATTRIBUTE_AVAILABILITY_ID]}
{$combination_label[$ATTRIBUTE_ID]["values"][]=$ATTRIBUTE_AVAILABILITY_ID}
{$combination_values[$ATTRIBUTE_AVAILABILITY_ID]=["{$ATTRIBUTE_AVAILABILITY_TITLE}", $ATTRIBUTE_ID]}
{/if}
{$pse_combination[]=$ATTRIBUTE_AVAILABILITY_ID}
{/loop}
{$pse[$ID]["combinations"]=$pse_combination}
{/loop}
<script type="text/javascript">
// Product sale elements
var PSE_FORM = true;
var PSE_COUNT = {$pse_count};
{if $check_availability == 0 || $product_virtual == 1 }
var PSE_CHECK_AVAILABILITY = false;
{else}
var PSE_CHECK_AVAILABILITY = true;
{/if}
var PSE_DEFAULT_AVAILABLE_STOCK = {config key="default_available_stock" default="100"};
var PSE = {$pse|json_encode nofilter};
var PSE_COMBINATIONS = {$combination_label|json_encode nofilter};
var PSE_COMBINATIONS_VALUE = {$combination_values|json_encode nofilter};
</script>
</article><!-- /#product -->
<ul class="pager">
{if $HAS_PREVIOUS == 1}
{loop type="product" name="prev_product" id="{$PREVIOUS}"}
<li class="previous"><a href="{$URL nofilter}"><i class="fa fa-chevron-left"></i> {intl l="Previous product"}</a></li>
{/loop}
{/if}
{if $HAS_NEXT == 1}
{loop type="product" name="next_product" id="{$NEXT}"}
<li class="next"><a href="{$URL nofilter}"><i class="fa fa-chevron-right"></i> {intl l="Next product"}</a></li>
{/loop}
{/if}
</ul>
{/loop}
</div><!-- /.main -->
{else}
<div class="main">
<article id="content-main" class="col-main" role="main" aria-labelledby="main-label">
{include file="includes/empty.html"}
</article>
</div><!-- /.layout -->
{/if}
{/block}
{block name="stylesheet"}
{hook name="product.stylesheet"}
{/block}
{block name="after-javascript-include"}
{hook name="product.after-javascript-include"}
{/block}
{block name="javascript-initialization"}
{hook name="product.javascript-initialization"}
{/block}
| Yochima/thelia | templates/frontOffice/default/product.html | HTML | lgpl-3.0 | 21,000 |
/* =========================================================================
* This file is part of six.sicd-c++
* =========================================================================
*
* (C) Copyright 2004 - 2014, MDA Information Systems LLC
*
* six.sicd-c++ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; If not,
* see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __SIX_GRID_H__
#define __SIX_GRID_H__
#include <mem/ScopedCopyablePtr.h>
#include <mem/ScopedCloneablePtr.h>
#include "six/Types.h"
#include "six/Init.h"
#include "six/Parameter.h"
#include "six/ParameterCollection.h"
namespace six
{
namespace sicd
{
struct WeightType
{
WeightType();
/*!
* Type of aperture weighting applied in the spatial
* frequency domain to yield the impulse response in the r/c
* direction. Examples include UNIFORM, TAYLOR, HAMMING, UNKNOWN
*/
std::string windowName;
/*!
* Optional free format field that can be used to pass forward the
* weighting parameter information.
* This is present in 1.0 (but not 0.4.1) and can be 0 to unbounded
*/
ParameterCollection parameters;
};
/*!
* \struct DirectionParameters
* \brief Struct for SICD Row/Col Parameters
*
* Parameters describing increasing row or column
* direction image coords
*/
struct DirectionParameters
{
DirectionParameters();
DirectionParameters* clone() const;
//! Unit vector in increasing row or col direction
Vector3 unitVector;
//! Sample spacing in row or col direction
double sampleSpacing;
//! Half-power impulse response width in increasing row/col dir
//! Measured at scene center point
double impulseResponseWidth;
//! FFT sign
FFTSign sign;
//! Spatial bandwidth in Krow/Kcol used to form the impulse response
//! in row/col direction, measured at scene center
double impulseResponseBandwidth;
//! Center spatial frequency in the Krow/Kcol
double kCenter;
//! Minimum r/c offset from kCenter of spatial freq support for image
double deltaK1;
//! Maximum r/c offset from kCenter of spatial freq support for image
double deltaK2;
/*!
* Offset from kCenter of the center of support in the r/c
* spatial frequency. The polynomial is a function of the image
* r/c
*/
Poly2D deltaKCOAPoly;
//! Optional parameters describing the aperture weighting
mem::ScopedCopyablePtr<WeightType> weightType;
/*!
* Sampled aperture amplitude weighting function applied
* in Krow/col to form the SCP impulse response in the row
* direction
* \note You cannot have less than two weights if you have any
* 2 <= NW <= 512 according to spec
*
* \todo could make this an object (WeightFunction)
*
*/
std::vector<double> weights;
};
/*!
* \struct Grid
* \brief SICD Grid parameters
*
* The block of parameters that describes the image sample grid
*
*/
struct Grid
{
//! TODO what to do with plane
Grid();
Grid* clone() const;
ComplexImagePlaneType imagePlane;
ComplexImageGridType type;
Poly2D timeCOAPoly;
mem::ScopedCloneablePtr<DirectionParameters> row;
mem::ScopedCloneablePtr<DirectionParameters> col;
};
}
}
#endif
| mohseniaref/six-library | modules/c++/six.sicd/include/six/sicd/Grid.h | C | lgpl-3.0 | 3,975 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Result'
db.create_table('taxonomy_result', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=100)),
('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])),
('object_id', self.gf('django.db.models.fields.PositiveIntegerField')()),
))
db.send_create_signal('taxonomy', ['Result'])
# Adding model 'Tag'
db.create_table('taxonomy_tag', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(unique=True, max_length=100)),
('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50, db_index=True)),
))
db.send_create_signal('taxonomy', ['Tag'])
# Adding model 'Category'
db.create_table('taxonomy_category', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('parent', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='children', null=True, to=orm['taxonomy.Category'])),
('title', self.gf('django.db.models.fields.CharField')(unique=True, max_length=100)),
('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50, db_index=True)),
))
db.send_create_signal('taxonomy', ['Category'])
# Adding model 'Vote'
db.create_table('taxonomy_vote', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])),
('object_id', self.gf('django.db.models.fields.PositiveIntegerField')()),
('owner', self.gf('django.db.models.fields.related.ForeignKey')(related_name='poll_votes', to=orm['auth.User'])),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal('taxonomy', ['Vote'])
# Adding unique constraint on 'Vote', fields ['owner', 'content_type', 'object_id']
db.create_unique('taxonomy_vote', ['owner_id', 'content_type_id', 'object_id'])
def backwards(self, orm):
# Removing unique constraint on 'Vote', fields ['owner', 'content_type', 'object_id']
db.delete_unique('taxonomy_vote', ['owner_id', 'content_type_id', 'object_id'])
# Deleting model 'Result'
db.delete_table('taxonomy_result')
# Deleting model 'Tag'
db.delete_table('taxonomy_tag')
# Deleting model 'Category'
db.delete_table('taxonomy_category')
# Deleting model 'Vote'
db.delete_table('taxonomy_vote')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'taxonomy.category': {
'Meta': {'ordering': "('title',)", 'object_name': 'Category'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['taxonomy.Category']"}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})
},
'taxonomy.result': {
'Meta': {'object_name': 'Result'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'taxonomy.tag': {
'Meta': {'ordering': "('title',)", 'object_name': 'Tag'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})
},
'taxonomy.vote': {
'Meta': {'unique_together': "(('owner', 'content_type', 'object_id'),)", 'object_name': 'Vote'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'poll_votes'", 'to': "orm['auth.User']"})
}
}
complete_apps = ['taxonomy']
| zuck/prometeo-erp | core/taxonomy/migrations/0001_initial.py | Python | lgpl-3.0 | 8,429 |
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Copyright (c) 2013-2020 The plumed team
(see the PEOPLE file at the root of the distribution for a list of names)
See http://www.plumed.org for more information.
This file is part of plumed, version 2.
plumed 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.
plumed 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 plumed. If not, see <http://www.gnu.org/licenses/>.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
#ifndef __PLUMED_reference_SingleDomainRMSD_h
#define __PLUMED_reference_SingleDomainRMSD_h
#include "ReferenceAtoms.h"
namespace PLMD {
class Pbc;
class SingleDomainRMSD : public ReferenceAtoms {
protected:
void readReference( const PDB& pdb );
public:
explicit SingleDomainRMSD( const ReferenceConfigurationOptions& ro );
/// Set the reference structure
void setReferenceAtoms( const std::vector<Vector>& conf, const std::vector<double>& align_in, const std::vector<double>& displace_in ) override;
/// Calculate
double calc( const std::vector<Vector>& pos, const Pbc& pbc, const std::vector<Value*>& vals, const std::vector<double>& arg, ReferenceValuePack& myder, const bool& squared ) const override;
double calculate( const std::vector<Vector>& pos, const Pbc& pbc, ReferenceValuePack& myder, const bool& squared ) const;
/// Calculate the distance using the input position
virtual double calc( const std::vector<Vector>& pos, const Pbc& pbc, ReferenceValuePack& myder, const bool& squared ) const=0;
/// This sets upper and lower bounds on distances to be used in DRMSD (here it does nothing)
virtual void setBoundsOnDistances( bool dopbc, double lbound=0.0, double ubound=std::numeric_limits<double>::max( ) ) {};
/// This is used by MultiDomainRMSD to setup the RMSD object in Optimal RMSD type
virtual void setupRMSDObject() {};
};
}
#endif
| PabloPiaggi/plumed2 | src/reference/SingleDomainRMSD.h | C | lgpl-3.0 | 2,389 |
/*
* World Calendars
* https://github.com/alexcjohnson/world-calendars
*
* Batch-converted from kbwood/calendars
* Many thanks to Keith Wood and all of the contributors to the original project!
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* http://keith-wood.name/calendars.html
Traditional Chinese localisation for Taiwanese calendars for jQuery v2.0.2.
Written by Ressol (ressol@gmail.com). */
var main = require('../main');
main.calendars.taiwan.prototype.regionalOptions['zh-TW'] = {
name: 'Taiwan',
epochs: ['BROC', 'ROC'],
monthNames: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'],
monthNamesShort: ['一','二','三','四','五','六',
'七','八','九','十','十一','十二'],
dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
dayNamesMin: ['日','一','二','三','四','五','六'],
digits: null,
dateFormat: 'yyyy/mm/dd',
firstDay: 1,
isRTL: false
};
| andrealmeid/ToT | node_modules/world-calendars/dist/calendars/taiwan-zh-TW.js | JavaScript | unlicense | 1,220 |
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at GamerMan7799. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
| GamerMan7799/Cannon-Simulation | docs/CODE_OF_CONDUCT.md | Markdown | unlicense | 3,209 |
/***
*mbsupr.c - Convert string upper case (MBCS)
*
* Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
* Convert string upper case (MBCS)
*
*******************************************************************************/
#ifdef _MBCS
#if defined (_WIN32)
#include <awint.h>
#endif /* defined (_WIN32) */
#include <mtdll.h>
#include <cruntime.h>
#include <ctype.h>
#include <mbdata.h>
#include <mbstring.h>
#include <mbctype.h>
/***
* _mbsupr - Convert string upper case (MBCS)
*
*Purpose:
* Converts all the lower case characters in a string
* to upper case in place. Handles MBCS chars correctly.
*
*Entry:
* unsigned char *string = pointer to string
*
*Exit:
* Returns a pointer to the input string; no error return.
*
*Exceptions:
*
*******************************************************************************/
unsigned char * __cdecl _mbsupr(
unsigned char *string
)
{
unsigned char *cp;
_mlock(_MB_CP_LOCK);
for (cp=string; *cp; cp++)
{
if (_ISLEADBYTE(*cp))
{
#if defined (_WIN32)
int retval;
unsigned char ret[4];
if ((retval = __crtLCMapStringA(__mblcid,
LCMAP_UPPERCASE,
cp,
2,
ret,
2,
__mbcodepage,
TRUE)) == 0)
{
_munlock(_MB_CP_LOCK);
return NULL;
}
*cp = ret[0];
if (retval > 1)
*(++cp) = ret[1];
#else /* defined (_WIN32) */
int mbval = ((*cp) << 8) + *(cp+1);
cp++;
if ( mbval >= _MBLOWERLOW1
&& mbval <= _MBLOWERHIGH1 )
*cp -= _MBCASEDIFF1;
else if (mbval >= _MBLOWERLOW2
&& mbval <= _MBLOWERHIGH2 )
*cp -= _MBCASEDIFF2;
#endif /* defined (_WIN32) */
}
else
/* single byte, macro version */
*cp = (unsigned char) _mbbtoupper(*cp);
}
_munlock(_MB_CP_LOCK);
return string ;
}
#endif /* _MBCS */
| hyller/CodeLibrary | The_Standard_C_Library/MBSUPR.C | C++ | unlicense | 2,615 |
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<body>
<legend><a href="<?php echo base_url(); ?>" >Home</a> | <a href="<?php echo base_url(); ?>reviewer" >Refresh</a> | <?php echo anchor('reviewer/samples_for_review/'.$reviewer_id,'Worksheets Uploaded For Review'); ?> </legend>
<hr />
<!-- Menu Start -->
</div>
<!-- End Menu -->
<div>
<table id = "refsubs">
<thead>
<tr>
<th>File Name</th>
<th>Lab Reference No</th>
<th>Download </th>
<th>Status</th>
<th>Upload</th>
</tr>
</thead>
<tbody>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tbody>
</table>
<script type="text/javascript">
$('#refsubs').dataTable({
"bJQueryUI": true
}).rowGrouping({
iGroupingColumnIndex: 1,
sGroupingColumnSortDirection: "asc",
iGroupingOrderByColumnIndex: 1,
//bExpandableGrouping:true,
//bExpandSingleGroup: true,
iExpandGroupOffset: -1
});
</script>
</div>
</body>
</html>
| johnotaalo/NQCL_LIMS | application/views/reviewer_v_tr.php | PHP | unlicense | 1,312 |
## Tutorials
Practical Android Exploitation: http://theroot.ninja/PAE.pdf
Android Application Security Tutorial Series: http://manifestsecurity.com/android-application-security/
Smartphone OS Security: http://www.csc.ncsu.edu/faculty/enck/csc591-s12/index.html
ExploitMe Mobile Android Labs: http://securitycompass.github.com/AndroidLabs/
ExploitMe Mobile iPhone Labs: http://securitycompass.github.com/iPhoneLabs/
Server for the two labs above: https://github.com/securitycompass/LabServer
DFRWS 2011 Forensics Challenge: http://dfrws.org/2011/challenge/index.shtml
Android Forensics & Security Testing: http://opensecuritytraining.info/AndroidForensics.html
Introduction to ARM: http://opensecuritytraining.info/IntroARM.html
Mobile App Security Certification: https://viaforensics.com/services/training/mobile-app-security-certification/
| lovelyshaking/wiki.secmobi.com | pages/publications/Tutorials.md | Markdown | unlicense | 851 |
'use strict';
import EventMap from 'eventmap';
import Log from './log';
var audioTypes = {
'mp3': 'audio/mpeg',
'wav': 'audio/wav',
'ogg': 'audio/ogg'
};
var imageTypes = {
'png': 'image/png',
'jpg': 'image/jpg',
'gif': 'image/gif'
};
class AssetLoader extends EventMap {
constructor(assets) {
super();
this.assets = assets || {};
this.files = {};
this.maxAssets = 0;
this.assetsLoaded = 0;
this.percentLoaded = 0;
this.cache = {};
}
start() {
// TODO: Something was wrong here. So it's deleted right now
}
}
export default AssetLoader;
| maxwerr/gamebox | src/assetloader.js | JavaScript | unlicense | 599 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/docdb/model/DescribePendingMaintenanceActionsResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::DocDB::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
DescribePendingMaintenanceActionsResult::DescribePendingMaintenanceActionsResult()
{
}
DescribePendingMaintenanceActionsResult::DescribePendingMaintenanceActionsResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
DescribePendingMaintenanceActionsResult& DescribePendingMaintenanceActionsResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "DescribePendingMaintenanceActionsResult"))
{
resultNode = rootNode.FirstChild("DescribePendingMaintenanceActionsResult");
}
if(!resultNode.IsNull())
{
XmlNode pendingMaintenanceActionsNode = resultNode.FirstChild("PendingMaintenanceActions");
if(!pendingMaintenanceActionsNode.IsNull())
{
XmlNode pendingMaintenanceActionsMember = pendingMaintenanceActionsNode.FirstChild("ResourcePendingMaintenanceActions");
while(!pendingMaintenanceActionsMember.IsNull())
{
m_pendingMaintenanceActions.push_back(pendingMaintenanceActionsMember);
pendingMaintenanceActionsMember = pendingMaintenanceActionsMember.NextNode("ResourcePendingMaintenanceActions");
}
}
XmlNode markerNode = resultNode.FirstChild("Marker");
if(!markerNode.IsNull())
{
m_marker = Aws::Utils::Xml::DecodeEscapedXmlText(markerNode.GetText());
}
}
if (!rootNode.IsNull()) {
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::DocDB::Model::DescribePendingMaintenanceActionsResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
| jt70471/aws-sdk-cpp | aws-cpp-sdk-docdb/source/model/DescribePendingMaintenanceActionsResult.cpp | C++ | apache-2.0 | 2,358 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.