code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
package com.megion.site.core.service;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import com.megion.site.core.model.page.WebsitePage;
import com.megion.site.core.service.identify.Identifiable;
public interface WebsitePageService extends Identifiable {
public static final String WEBSITE_PAGE_TYPE_PROPERTY = "websitePageType";
WebsitePage getWebsitePage(Node websitePage) throws RepositoryException;
}
| megion/megion-site | megion-site-core/src/main/java/com/megion/site/core/service/WebsitePageService.java | Java | gpl-3.0 | 428 |
#include "FrakOutMigrationController.h"
#include "FrakOutVersion.h"
#include "FrakOutVersionState.h"
#include "FrakOutVersionStateFactory.h"
FrakOutMigrationController::FrakOutMigrationController()
{
m_states.push_back(FrakOutVersionStateFactory::create(FrakOutVersion::V1_0_0()));
m_states.push_back(FrakOutVersionStateFactory::create(FrakOutVersion::V1_1_0()));
}
FrakOutMigrationController::~FrakOutMigrationController()
{
foreach(FrakOutVersionState *state, m_states)
delete state;
}
void FrakOutMigrationController::migrate(FrakOutData& frakOutData,
const FrakOutVersion* const startVersion,
const FrakOutVersion* const endVersion)
{
QList<FrakOutVersionState*>::const_iterator beginIt =
std::find_if(m_states.begin(), m_states.end(), FrakOutVersionState::MatchVersion(startVersion));
QList<FrakOutVersionState*>::const_iterator endIt =
std::find_if(m_states.begin(), m_states.end(), FrakOutVersionState::MatchVersion(endVersion));
QList<FrakOutVersionState*>::const_iterator stateIt;
for (stateIt = beginIt; stateIt != endIt; stateIt++)
(*stateIt)->migrate(frakOutData);
}
| randusr836/frakout | migration/FrakOutMigrationController.cpp | C++ | gpl-3.0 | 1,233 |
<?php
/* @var $this ItemsController */
/* @var $model Item */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'item-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'amazon_id'); ?>
<?php echo $form->textField($model,'amazon_id',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'amazon_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'type_of_product'); ?>
<?php echo $form->error($model,'type_of_product'); ?>
<?php echo $form->dropDownList( $model, 'type_of_product', array(
'GMAT' => 'GMAT',
'MBA' => 'MBA'
),
array(
'empty'=>'Select type of product',
)
); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'ordinal_number'); ?>
<?php echo $form->textField($model,'ordinal_number'); ?>
<?php echo $form->error($model,'ordinal_number'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'is_published'); ?>
<?php echo $form->checkBox($model,'is_published'); ?>
<?php echo $form->error($model,'is_published'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form --> | radchenko/yiiBoilerplate | protected/modules/acp/modules/amazon/views/items/_form.php | PHP | gpl-3.0 | 1,740 |
package apollo.data.model;
import java.util.Date;
import java.util.List;
import android.provider.BaseColumns;
import apollo.util.DateTime;
public class AutoPost {
public static class Columns implements BaseColumns {
public static final String ID = "_id";
public static final String SECTION_ID = "section_id";
public static final String THREAD_ID = "thread_id";
public static final String THREAD_SUBJECT = "thread_subject";
public static final String FLOOR_NUM = "floor_num";
public static final String ACCOUNTS = "accounts";
public static final String POST_BODY = "post_body";
public static final String START_TIME = "start_time";
public static final String END_TIME = "end_time";
}
public int id = -1;
public int floorNum = 0;
public boolean floorEnable = false;
public List<User> accounts = null;
public String postBody = null;
public Date start = DateTime.now().getDate();
public Date end = DateTime.now().addDays(10).getDate();
public Thread thread = null;
}
| kuibobo/BlackStone | app/src/main/java/apollo/data/model/AutoPost.java | Java | gpl-3.0 | 997 |
/**
* repowatch - A yum repository watcher
*
* Copyright (C) 2008 Richard "Shred" Körber
* http://repowatch.shredzone.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.shredzone.repowatch.sync;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.Resource;
import org.shredzone.repowatch.model.Blacklist;
import org.shredzone.repowatch.model.Change;
import org.shredzone.repowatch.model.Package;
import org.shredzone.repowatch.model.Repository;
import org.shredzone.repowatch.model.Version;
import org.shredzone.repowatch.repository.BlacklistDAO;
import org.shredzone.repowatch.repository.ChangeDAO;
import org.shredzone.repowatch.repository.PackageDAO;
import org.shredzone.repowatch.repository.RepositoryDAO;
import org.shredzone.repowatch.repository.VersionDAO;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* This is the heart of the synchronizer. It synchronizes the repowatch
* database with the repository's databases.
* <p>
* This bean is prototype scoped. Use {@link RepositorySynchronizerFactory}
* to generate a new instance of this bean.
*
* @author Richard "Shred" Körber
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Transactional
public class RepositorySynchronizerImpl implements RepositorySynchronizer {
private final Logger logger = Logger.getLogger(getClass().getName());
@Resource
private RepositoryDAO repositoryDao;
@Resource
private PackageDAO packageDao;
@Resource
private VersionDAO versionDao;
@Resource
private ChangeDAO changeDao;
@Resource
private BlacklistDAO blacklistDao;
private Repository repository;
private URL baseUrl;
private RepoMdParser repomd;
private Date now;
/**
* Sets the {@link Repository} to be synchronized.
*/
@Override
public void setRepository(Repository repository) {
this.repository = repositoryDao.merge(repository);;
}
/**
* Starts the synchronization process.
*
* @throws SynchronizerException Synchronization failed for various reasons
*/
@Override
public void doSynchronize() throws SynchronizerException {
now = new Date();
try {
this.baseUrl = new URL(repository.getBaseUrl());
} catch (MalformedURLException ex) {
throw new SynchronizerException("Invalid base url", ex);
}
readRepoMd();
readPrimary();
}
/**
* Reads the repomd.xml file and fills the {@link RepoMdParser} with
* {@link DatabaseLocation} entities.
*
* @throws SynchronizerException
*/
private void readRepoMd() throws SynchronizerException {
logger.fine("Reading repomd.xml");
try {
repomd = new RepoMdParser(baseUrl);
repomd.parse();
} catch (IOException ex) {
throw new SynchronizerException("Could not read repomd.xml", ex);
}
}
/**
* Reads and processes the primary.xml database. This could take some
* time and some amount of heap memory.
*
* @throws SynchronizerException
*/
private void readPrimary() throws SynchronizerException {
logger.fine("Reading primary.xml");
boolean firstTime = false;
DatabaseLocation location = repomd.getDatabaseLocation("primary");
if (location == null) {
throw new SynchronizerException("primary database not defined!");
}
//--- Reading for the first time? ---
if (repository.getFirstScanned() == null) {
repository.setFirstScanned(now);
firstTime = true;
}
//--- Update available? ---
long localModifiedSince = repository.getLastModified();
long remoteModifiedSince = location.getTimestamp();
if (localModifiedSince != 0 && remoteModifiedSince != 0
&& remoteModifiedSince <= localModifiedSince ) {
return;
}
repository.setLastModified(remoteModifiedSince);
//--- Create a Version cache ---
Map<String,Version> versionCache = new HashMap<String,Version>();
for (Version version : versionDao.findAllVersions(repository)) {
versionCache.put(version.getPackage().getName(), version);
}
//--- Get the Blacklist ---
Set<String> blacklist = new HashSet<String>();
for (Blacklist bl : blacklistDao.findAllBlacklists()) {
blacklist.add(bl.getName());
}
//--- Iterate through the elements ---
logger.info("Repository " + repository.toString() + " is due for an update");
int versionCounter = 0;
int changeCounter = 0;
int deleteCounter = 0;
PrimaryParser parser = new PrimaryParser(repository, location);
try {
parser.parse();
for (Version version : parser) {
if (blacklist.contains(version.getPackage().getName())) {
continue;
}
versionCounter++;
Date fileDate = version.getFileDate();
if (fileDate == null || fileDate.after(now)) {
fileDate = now;
}
if (! firstTime) {
version.setFirstSeen(fileDate);
}
version.setLastSeen(now);
Change change = syncVersion(version, versionCache);
if (change != null && !firstTime) {
changeCounter++;
change.setTimestamp(fileDate);
changeDao.insert(change);
}
}
} finally {
parser.discard();
}
//--- Create "removed" entries ---
for (Version version : versionDao.findLastSeenBefore(repository, now)) {
Change change = new Change();
change.setTimestamp(now);
change.setChange(Change.Type.REMOVED);
change.setRepository(repository);
change.setPackage(version.getPackage());
change.setEpoch(version.getEpoch());
change.setVer(version.getVer());
change.setRel(version.getRel());
changeDao.insert(change);
version.setDeleted(true);
deleteCounter++;
}
//--- Successfully scanned ---
repository.setLastScanned(now);
logger.info("Repository " + repository.toString() +
" successfully updated (" +
versionCounter + " seen, " +
changeCounter + " changed, " +
deleteCounter + " deleted)");
}
/**
* Synchronizes a {@link Version} entity with the database.
*
* @param version Entity to sync with. Must be transient.
* @param versionCache Cache of all Versions of a repository, indexed by
* their Package names.
* @return Change entity, or null if the version was unchanged.
*/
private Change syncVersion(Version version, Map<String,Version> versionCache) {
//--- Create a Change entity ---
Change change = new Change();
change.setRepository(version.getRepository());
change.setEpoch(version.getEpoch());
change.setVer(version.getVer());
change.setRel(version.getRel());
//--- Find the Verison in Version cache ---
Version dbversion = versionCache.get(version.getPackage().getName());
if (dbversion != null) {
// The version (and the package) does already exist in database.
// This might be an update.
dbversion.setLastSeen(version.getLastSeen());
if (dbversion.getFileDate() == null
|| version.getFileDate() == null
|| version.getFileDate().after(dbversion.getFileDate())) {
dbversion.setEpoch(version.getEpoch());
dbversion.setVer(version.getVer());
dbversion.setRel(version.getRel());
dbversion.setFileLocation(version.getFileLocation());
dbversion.setFileDate(version.getFileDate());
if (version.getFileDate() != null) {
change.setChange(Change.Type.UPDATED);
change.setPackage(dbversion.getPackage());
return change;
} else {
return null;
}
}
} else {
// Version is not yet in the database. We need to add it.
// The package might be in the database, though.
Package newdbpack = packageDao.findPackage(
version.getPackage().getDomain(),
version.getPackage().getName()
);
if (newdbpack != null) {
// There is a package, so it is the first time for this
// Version to appear in this repository.
newdbpack.setSummary(version.getPackage().getSummary());
newdbpack.setDescription(version.getPackage().getDescription());
newdbpack.setHomeUrl(version.getPackage().getHomeUrl());
newdbpack.setPackGroup(version.getPackage().getPackGroup());
version.setPackage(newdbpack);
versionDao.insert(version);
versionCache.put(version.getPackage().getName(), version);
change.setChange(Change.Type.ADDED);
change.setPackage(newdbpack);
return change;
} else {
// Package was not found, which means that also the Version
// entity is not persisted yet. Persist the Version entity
// as it is and return that the version was added.
packageDao.insert(version.getPackage());
versionDao.insert(version);
versionCache.put(version.getPackage().getName(), version);
change.setChange(Change.Type.ADDED);
change.setPackage(version.getPackage());
return change;
}
}
// Nothing has changed
return null;
}
}
| shred/repowatch | src/main/java/org/shredzone/repowatch/sync/RepositorySynchronizerImpl.java | Java | gpl-3.0 | 11,167 |
from tests.base_widget_testcase import BaseWidgetTest
| RedFantom/ttkwidgets | tests/__init__.py | Python | gpl-3.0 | 54 |
class Solution
{
public:
bool isPowerOfThree(int n)
{
while (n > 1)
{
if ((n % 3) != 0)
{
return false;
}
n /= 3;
}
return n == 1;
}
};
| JetMeta/Zds | lc/math/326.hpp | C++ | gpl-3.0 | 249 |
//
//
// This source code is part of
//
// TD-ALCOVE
//
// Temporal Difference - ALCOVE
//
// VERSION 1.0.0
// Written by Joshua L. Phillips.
// Copyright (c) 2004-2016, Joshua L. Phillips.
// Check out http://www.cs.mtsu.edu/~jphillips/software.html for more
// information.
//
// 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.
//
// If you want to redistribute modifications, please consider that
// derived work must not be called official TDALCOVE. Details are found
// in the README & LICENSE files - if they are missing, get the
// official version at github.com/jlphillipsphd/tdalcove/.
//
// To help us fund TDALCOVE development, we humbly ask that you cite the
// papers on the package - you can find them in the top README file.
//
// For more info, check our website at
// http://www.cs.mtsu.edu/~jphillips/software.html
//
//
#include "threshold_activation_function.h"
#include <stddef.h>
#include <math.h>
ThresholdActivationFunction::ThresholdActivationFunction() : ActivationFunction() {
gains = new double[1];
gains[0] = 0.0;
mn = 0.0;
mx = 1.0;
high = true;
}
ThresholdActivationFunction::~ThresholdActivationFunction() {
delete gains;
}
ThresholdActivationFunction::ThresholdActivationFunction(int number_of_input_dimensions) : ActivationFunction(number_of_input_dimensions) {
int x;
gains = new double[dims];
for (x = 0; x < dims; x++)
gains[x] = 0.0;
mn = 0.0;
mx = 1.0;
high = true;
}
ThresholdActivationFunction::ThresholdActivationFunction(int number_of_input_dimensions, double min, double max) : ActivationFunction(number_of_input_dimensions) {
int x;
high = true;
gains = new double[dims];
for (x = 0; x < dims; x++)
gains[x] = 0.0;
if (max <= min) {
mn = 0.0;
mx = 1.0;
return;
}
mn = min;
mx = max;
}
ThresholdActivationFunction::ThresholdActivationFunction(int number_of_input_dimensions, double min, double max, double* thresholds) : ActivationFunction(number_of_input_dimensions) {
int x;
high = true;
gains = new double[dims];
for (x = 0; x < dims; x++)
gains[x] = 0.0;
if (thresholds != NULL)
for (x = 0; x < dims; x++)
gains[x] = thresholds[x];
if (max <= min) {
mn = 0.0;
mx = 1.0;
return;
}
mn = min;
mx = max;
}
double ThresholdActivationFunction::Compute(double* variables) {
if (variables == NULL)
return 0.0;
int x;
double value = mx;
bool meets_criterion = true;
if (high) {
for (x = 0; x < dims && meets_criterion; x++)
if (variables[x] < gains[x])
meets_criterion = false;
}
else {
for (x = 0; x < dims && meets_criterion; x++)
if (variables[x] <= gains[x])
meets_criterion = false;
}
if (!meets_criterion)
value = mn;
return value;
}
double ThresholdActivationFunction::Derivative(int dimension, double* variables) {
return 0.0;
}
double ThresholdActivationFunction::Derivative(double* variables) {
return 0.0;
}
bool ThresholdActivationFunction::setThreshold(int dim, double t) {
if (dim < 0 || dim >= dims)
return false;
gains[dim] = t;
return true;
}
double ThresholdActivationFunction::getThreshold(int dim) {
if (dim < 0 || dim >= dims)
return 0.0;
return gains[dim];
}
bool ThresholdActivationFunction::setThresholds(double* t) {
if (t == NULL)
return false;
for (int x = 0; x < dims; x++)
gains[x] = t[x];
return true;
}
bool ThresholdActivationFunction::getThresholds(double* t) {
if (t == NULL)
return false;
for (int x = 0; x < dims; x++)
t[x] = gains[x];
return true;
}
bool ThresholdActivationFunction::setMin(double min) {
if (min >= mx)
return false;
mn = min;
return true;
}
double ThresholdActivationFunction::getMin() {
return mn;
}
void ThresholdActivationFunction::biasMin() {
high = false;
return;
}
bool ThresholdActivationFunction::isBiasedMin() {
return !high;
}
bool ThresholdActivationFunction::setMax(double max) {
if (max <= mn)
return false;
mx = max;
return true;
}
double ThresholdActivationFunction::getMax() {
return mx;
}
void ThresholdActivationFunction::biasMax() {
high = true;
return;
}
bool ThresholdActivationFunction::isBiasedMax() {
return high;
}
| jlphillipsphd/tdalcove | libnnet/threshold_activation_function.cc | C++ | gpl-3.0 | 4,381 |
#include <iostream>
#include "FS.hpp"
#include "DefaultLoop.hpp"
#include "common.hpp"
#include "Argument.hpp"
using namespace cpuv;
int main(int /*argc*/,char**){
FS fs;
std::vector<std::string> files {"/home/hesham/cpplay/test"};
fs.watch(files,[](Argument<FS>& arg){
static int i = 5;
if(i-- > 0) {
std::cout<<arg.fileName.first<<std::endl;
std::cout<<arg.fileName.second<<std::endl;
}else
arg._this().unwatch(arg.fileName.first);
});
DefaultLoop::getInstance().run();
}
| heshamsafi/cpuv | src/main.cpp | C++ | gpl-3.0 | 521 |
import * as actions from '../../actions'
import AppBar from 'material-ui/AppBar'
import { connect } from 'react-redux'
import Menu from 'material-ui/Menu'
import MenuItem from 'material-ui/MenuItem'
import MUIDrawer from 'material-ui/Drawer'
import React, { PropTypes } from 'react'
import { reset } from 'redux-form'
import { toggleDrawer } from '../../actions'
import { Link } from 'react-router'
class Drawer extends React.Component {
render() {
return (
<MUIDrawer open={ this.props.isOpen } docked={ false } onRequestChange={ this.props.onDrawerToggle }>
<AppBar title="Math4Kids" onLeftIconButtonTouchTap={ this.props.onDrawerToggle }/>
<Menu onItemTouchTap={this.props.onItemTouchTap}>
<MenuItem value="add" containerElement={<Link to='/'/>}>Dodawanie</MenuItem>
<MenuItem value="substract" containerElement={<Link to='substract'/>}>Odejmowanie</MenuItem>
<MenuItem value="multiply" containerElement={<Link to='multiply'/>}>Mnożenie</MenuItem>
</Menu>
</MUIDrawer>
);
}
}
const mapStateToProps = (state) => {
return {
isOpen: state.drawer.open
}
}
const mapDispatchToProps = (dispatch) => {
return {
onDrawerToggle: () => {
dispatch(toggleDrawer())
},
onItemTouchTap: (event, menuItem, index) => {
dispatch(reset('AddForm'));
dispatch(reset('SubstractForm'));
dispatch(reset('MultiplyForm'));
dispatch(toggleDrawer())
switch (menuItem.props.value) {
case "add" :
return dispatch(actions.newAdd())
case "substract" :
return dispatch(actions.newSubstract())
case "multiply" :
return dispatch(actions.newMultiply())
default:
return null
}
}
}
}
Drawer.propTypes = {
isOpen: PropTypes.bool.isRequired,
onDrawerToggle: PropTypes.func.isRequired
}
export default connect(mapStateToProps, mapDispatchToProps)(Drawer)
| gom3s/math4Kids | src/components/app/Drawer.js | JavaScript | gpl-3.0 | 2,173 |
/**
* Copyright 2015 Poznań Supercomputing and Networking Center
*
* Licensed under the GNU General Public License, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pl.psnc.synat.wrdz.zmd.entity.object.content;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import pl.psnc.synat.wrdz.zmd.entity.object.metadata.FileProvidedMetadata;
/**
* An entity representing content version's data files.
*/
@Entity
@Table(name = "ZMD_DATA_FILE_VERSIONS", schema = "darceo", uniqueConstraints = { @UniqueConstraint(columnNames = {
"DFV_CONTENT_VERSION_ID", "DFV_DATA_FILE_ID" }) })
public class DataFileVersion implements Serializable {
/**
* Serial version UID.
*/
private static final long serialVersionUID = -7092338549546614906L;
/**
* Default constructor.
*/
public DataFileVersion() {
}
/**
* Entity's identifier (primary key).
*/
@Id
@SequenceGenerator(name = "dataFileVersionSequenceGenerator", sequenceName = "darceo.ZMD_DFVER_ID_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dataFileVersionSequenceGenerator")
@Column(name = "DFV_ID", unique = true, nullable = false)
private long id;
/**
* Content version this data file version is part of.
*/
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "DFV_CONTENT_VERSION_ID", nullable = false)
private ContentVersion contentVersion;
/**
* Data file this data file version represents.
*/
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "DFV_DATA_FILE_ID", nullable = false)
private DataFile dataFile;
/**
* Metadata provided for this file version.
*/
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.PERSIST })
@JoinTable(name = "ZMD_DATA_FILE_VERSIONS_METADATA_FILES", schema = "darceo", joinColumns = { @JoinColumn(
name = "DFV_ID", referencedColumnName = "DFV_ID") }, inverseJoinColumns = { @JoinColumn(name = "MF_ID",
referencedColumnName = "MF_ID") })
private List<FileProvidedMetadata> providedMetadata = new ArrayList<FileProvidedMetadata>();
/**
* Sequence value.
*/
@Column(name = "DFV_SEQUENCE", nullable = true)
private Integer sequence;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public ContentVersion getContentVersion() {
return contentVersion;
}
public void setContentVersion(ContentVersion contentVersion) {
this.contentVersion = contentVersion;
}
public DataFile getDataFile() {
return dataFile;
}
public void setDataFile(DataFile dataFile) {
this.dataFile = dataFile;
}
public List<FileProvidedMetadata> getProvidedMetadata() {
return providedMetadata;
}
public void setProvidedMetadata(List<FileProvidedMetadata> providedMetadata) {
this.providedMetadata = providedMetadata;
}
public Integer getSequence() {
return sequence;
}
public void setSequence(Integer sequence) {
this.sequence = sequence;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((contentVersion == null) ? 0 : contentVersion.hashCode());
result = prime * result + ((dataFile == null) ? 0 : dataFile.hashCode());
result = prime * result + ((sequence == null) ? 0 : sequence.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
DataFileVersion other = (DataFileVersion) obj;
if (contentVersion == null) {
if (other.contentVersion != null) {
return false;
}
} else if (!contentVersion.equals(other.contentVersion)) {
return false;
}
if (dataFile == null) {
if (other.dataFile != null) {
return false;
}
} else if (!dataFile.equals(other.dataFile)) {
return false;
}
if (sequence == null) {
if (other.sequence != null) {
return false;
}
} else if (!sequence.equals(other.sequence)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DataFileVersion [contentVersion.id=").append(contentVersion.getId());
builder.append(", dataFile.id=").append(dataFile.getId());
builder.append(", sequence=").append(sequence);
builder.append("]");
return builder.toString();
}
}
| psnc-dl/darceo | wrdz/wrdz-zmd/entity/src/main/java/pl/psnc/synat/wrdz/zmd/entity/object/content/DataFileVersion.java | Java | gpl-3.0 | 6,016 |
<?php head(); ?>
<div class="row">
<div class="three columns">
<div id="primary-nav">
<ul class="nav-bar">
<li>
<?php echo nav (
array(
'Browse Items' => uri('items'),
'Browse Collections' => uri('collections')
)
);
?>
</li>
</div><!-- end primary nav-bar-->
</div><!-- end three columns -->
<div class="nine columns">
<div id="primary" class="content">
<?php if (get_theme_option('Homepage Text')): ?>
<p><?php echo get_theme_option('Homepage Text'); ?></p>
<?php endif; ?>
</div><!-- end primary -->
</div><!-- end nine columns -->
</div><!-- end row -->
<!-- Featured Collection -->
<div class="row">
<div class="twelve columns">
<div class="panel">
<div id="featured">
<?php if (get_theme_option('Display Featured Collection')): ?>
<div id="featured-collection">
<div><?php echo display_random_featured_collection(); ?></div>
</div>
</div>
</div>
<?php endif; ?>
<!-- end featured collection -->
<!-- Featured Item -->
<?php if (get_theme_option('Display Featured Item') == 1): ?>
<div class="row">
<div id="featured-items" class="six columns">
<?php echo display_random_featured_item(); ?>
</div>
<?php endif; ?>
<!--end featured-item-->
<!-- Recent Items -->
<div id="recent-items" class="six columns">
<h2>Recently Added Items</h2>
<?php
$homepageRecentItems = (int)get_theme_option('Homepage Recent Items') ? get_theme_option('Homepage Recent Items') : '3';
set_items_for_loop(recent_items($homepageRecentItems));
if (has_items_for_loop()):
?>
<ul class="items-list">
<?php while (loop_items()): ?>
<li class="item">
<h3><?php echo link_to_item(); ?></h3>
<?php if($itemDescription = item('Dublin Core', 'Description', array('snippet'=>150))): ?>
<p class="item-description"><?php echo $itemDescription; ?></p>
<?php endif; ?>
</li>
<?php endwhile; ?>
</ul>
<?php else: ?>
<p>No recent items available.</p>
<?php endif; ?>
<p class="view-items-link"><?php echo link_to_browse_items('View All Items'); ?></p>
</div>
</div>
<!-- end recent-items -->
<!-- Featured Exhibit -->
<div class="row">
<?php if ((get_theme_option('Display Featured Exhibit')) && function_exists('exhibit_builder_display_random_featured_exhibit')): ?>
</div>
<?php echo exhibit_builder_display_random_featured_exhibit(); ?>
<?php endif; ?>
</div>
<!-- End featured Exhibit -->
</div>
<footer>
<?php foot(); ?></footer>
| StandardNerd/cassovia | themes/omeka-foundation/index.php | PHP | gpl-3.0 | 3,111 |
package com.epam.wilma.test.server;
/*==========================================================================
Copyright 2015 EPAM Systems
This file is part of Wilma.
Wilma is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Wilma 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 Wilma. If not, see <http://www.gnu.org/licenses/>.
===========================================================================*/
import java.util.Properties;
/**
* Starts the test server. The server can listen on a configurable port and answer to certain requests.
* @author Marton_Sereg
*
*/
public final class WilmaTestServerApplication {
private WilmaTestServerApplication() {
}
/**
* Starts the test server.
* @param args the program arguments. The properties file location is required.
* @throws Exception
*/
public static void main(final String[] args) {
new TestServerBootstrap().bootstrap(args, new Properties(), new JettyServer());
}
}
| nagyistoce/Wilma | wilma-test/wilma-test-server/src/main/java/com/epam/wilma/test/server/WilmaTestServerApplication.java | Java | gpl-3.0 | 1,412 |
package ca.licef.comete.metadata;
import ca.licef.comete.core.Core;
import ca.licef.comete.core.DefaultView;
import ca.licef.comete.core.util.Constants;
import ca.licef.comete.core.util.Util;
import ca.licef.comete.vocabularies.COMETE;
import ca.licef.comete.vocabulary.Vocabulary;
import licef.CommonNamespaceContext;
import licef.IOUtil;
import licef.reflection.Invoker;
import licef.tsapi.model.Tuple;
import licef.tsapi.TripleStore;
import licef.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: amiara
* Date: 4-Jun-2012
*/
public class LearningObjectView extends DefaultView {
public String getHtml(String uri, Locale locale, boolean isAdmin, String style, String isStandalone) throws Exception {
TripleStore tripleStore = Core.getInstance().getTripleStore();
Invoker inv = new Invoker( this, "ca.licef.comete.metadata.LearningObjectView", "doGetHtml", new Object[] { uri, locale, isAdmin, style, isStandalone } );
return( (String)tripleStore.transactionalCall( inv ) );
}
public String doGetHtml(String uri, Locale locale, boolean isAdmin, String style, String isStandalone) throws Exception {
Set contributes = new HashSet();
HashMap contribRoles = new HashMap();
HashMap contribOrganizations = new HashMap();
HashMap orgNames = new HashMap();
getIdentityData( uri, contributes, contribRoles, contribOrganizations, orgNames );
String loXml = getRdf(uri, "false", false, false);
InputSource inputSource = new InputSource( new StringReader(loXml) );
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware( true );
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse( inputSource );
Element rootElement = doc.getDocumentElement();
// We only consider the first format for now. A better solution would be to have one format property
// associated to each location. - FB
String firstFormat = null;
NodeList locationElements = doc.getElementsByTagNameNS( CommonNamespaceContext.foafNSURI, "page" );
for( int i = 0; i < locationElements.getLength(); i++ ) {
Element locationElement = (Element)locationElements.item( i );
try {
if( firstFormat == null ) {
NodeList formatElements = doc.getElementsByTagNameNS( CommonNamespaceContext.dctNSURI, "format" );
for( int j = 0; j < formatElements.getLength(); j++ ) {
Element formatElement = (Element)formatElements.item( j );
firstFormat = formatElement.getAttributeNS( CommonNamespaceContext.rdfNSURI, "resource" );
break;
}
}
if( firstFormat == null || "".equals( firstFormat ) ) {
NodeList formatElements = doc.getElementsByTagNameNS( CommonNamespaceContext.dctNSURI, "format" );
for( int j = 0; j < formatElements.getLength(); j++ ) {
Element formatElement = (Element)formatElements.item( j );
firstFormat = formatElement.getTextContent();
break;
}
}
String mimeType = null;
if( firstFormat == null || "".equals( firstFormat ) )
mimeType = IOUtil.getMimeType( locationElement.getTextContent() );
else
mimeType = firstFormat.substring( "http://purl.org/NET/mediatypes/".length() );
locationElement.setAttributeNS( CommonNamespaceContext.cometeNSURI, "icon", Util.getMimeTypeIcon( mimeType, isStandalone ) );
locationElement.setAttributeNS( CommonNamespaceContext.cometeNSURI, "mimeType", mimeType );
}
catch( IOException ioe ) {
// For some reasons, the mime type cannot be determined so we just omit it.
}
}
if( contributes.size() > 0 ) {
ArrayList sortedContributes = new ArrayList( contributes );
Collections.sort( sortedContributes, new ContributeComparator() );
Set alreadyShownOrg = new HashSet();
Element wrapperElement = doc.createElementNS( "", "contributes" );
for( Iterator it = sortedContributes.iterator(); it.hasNext(); ) {
String identityUri = (String)it.next();
String identityType = ca.licef.comete.core.util.Util.getURIType( identityUri );
// Omit organization that have already been shown with a person.
if( Constants.OBJ_TYPE_ORGANIZATION.equals( identityType ) && alreadyShownOrg.contains( identityUri ) )
continue;
String identityId = ca.licef.comete.core.util.Util.getIdValue(identityUri);
String identityXml = getRdf( identityUri, "false", false, false );
InputSource identitySrc = new InputSource( new StringReader( identityXml ) );
DocumentBuilder docBuilderIdentity = docFactory.newDocumentBuilder();
Document docIdentity = docBuilder.parse( identitySrc );
// Required to make a copy of the node to insert into the main document.
Node elementCopy = doc.importNode( docIdentity.getDocumentElement(), true );
Element contributeElement = doc.createElementNS( "", "contribute" );
wrapperElement.appendChild( contributeElement );
contributeElement.appendChild( elementCopy );
Set roles = (Set)contribRoles.get( identityUri );
for( Iterator itRoles = roles.iterator(); itRoles.hasNext(); ) {
String role = (String)itRoles.next();
Element roleElement = doc.createElementNS( "", "role" );
roleElement.setTextContent( role );
contributeElement.appendChild( roleElement );
}
// Insert an identity element giving a location where further information can be obtained.
String identityLocation = ca.licef.comete.core.util.Util.getRestUrl( identityType ) + "/" + identityId + "/html?lang=" + locale.getLanguage();
Element identityElement = doc.createElementNS( "", "identity" );
identityElement.setAttributeNS( "", "href", identityLocation );
contributeElement.appendChild( identityElement );
Set orgs = (Set)contribOrganizations.get( identityUri );
if( orgs != null && orgs.size() > 0 ) {
for( Iterator itOrgs = orgs.iterator(); itOrgs.hasNext(); ) {
String orgUri = (String)itOrgs.next();
alreadyShownOrg.add( orgUri );
String orgId = ca.licef.comete.core.util.Util.getIdValue(orgUri);
String orgXml = getRdf( orgUri, "false", false, false );
InputSource orgSrc = new InputSource( new StringReader( orgXml ) );
DocumentBuilder docBuilderOrg = docFactory.newDocumentBuilder();
Document docOrg = docBuilder.parse( orgSrc );
// Required to make a copy of the node to insert into the main document.
Node elementCopyOrg = doc.importNode( docOrg.getDocumentElement(), true );
Element orgElement = doc.createElementNS( "", "organization" );
contributeElement.appendChild( orgElement );
orgElement.appendChild( elementCopyOrg );
// Insert an identity element giving a location where further information can be obtained.
String orgIdentityType = ca.licef.comete.core.util.Util.getURIType( orgUri );
String orgIdentityLocation = ca.licef.comete.core.util.Util.getRestUrl( orgIdentityType ) + "/" + orgId + "/html?lang=" + locale.getLanguage();
Element orgIdentityElement = doc.createElementNS( "", "identity" );
orgIdentityElement.setAttributeNS( "", "href", orgIdentityLocation );
orgElement.appendChild( orgIdentityElement );
// We consider only the first org.
break;
}
}
}
rootElement.appendChild( wrapperElement );
}
NodeList learningResourceTypeElements = doc.getElementsByTagNameNS( CommonNamespaceContext.cometeNSURI, "learningResourceType" );
for( int i = 0; i < learningResourceTypeElements.getLength(); i++ ) {
Element learningResourceTypeElement = (Element)learningResourceTypeElements.item( i );
String learningResourceTypeUri = learningResourceTypeElement.getAttributeNS( CommonNamespaceContext.rdfNSURI, "resource" );
String learningResourceTypeLabel = getVocabularyConceptLabel( learningResourceTypeUri, locale.getLanguage() );
learningResourceTypeElement.setAttributeNS( "", "label", learningResourceTypeLabel );
}
NodeList educationalLevelElements = doc.getElementsByTagNameNS( CommonNamespaceContext.cometeNSURI, "educationalLevel" );
for( int i = 0; i < educationalLevelElements.getLength(); i++ ) {
Element educationalLevelElement = (Element)educationalLevelElements.item( i );
String educationalLevelUri = educationalLevelElement.getAttributeNS( CommonNamespaceContext.rdfNSURI, "resource" );
String educationalLevelLabel = getVocabularyConceptLabel( educationalLevelUri, locale.getLanguage() );
educationalLevelElement.setAttributeNS( "", "label", educationalLevelLabel );
}
String[] linkingPredicates = Vocabulary.getInstance().getAllConceptLinkingPredicates();
for( int i = 0; i < linkingPredicates.length; i++ ) {
String lp = linkingPredicates[ i ];
String lpNsUri = CommonNamespaceContext.getInstance().getNamespaceURIFromUri( lp );
String lpElementName = lp.substring( lpNsUri.length() );
// Skip special vocabularies that have already been handled previously.
if( lp.equals( COMETE.educationalLevel.getURI() ) ||
lp.equals( COMETE.learningResourceType.getURI() ) )
continue;
NodeList conceptElements = doc.getElementsByTagNameNS( lpNsUri, lpElementName );
for( int c = 0; c < conceptElements.getLength(); c++ ) {
Element conceptElement = (Element)conceptElements.item( c );
String conceptUri = conceptElement.getAttributeNS( CommonNamespaceContext.rdfNSURI, "resource" );
String conceptScheme = Vocabulary.getInstance().getConceptScheme( conceptUri );
String vocabLabel = Vocabulary.getInstance().getLabel( conceptScheme, locale.getLanguage() );
if( vocabLabel != null )
conceptElement.setAttributeNS( "", "vocabLabel", vocabLabel );
String conceptLabel = Vocabulary.getInstance().getLabel( conceptUri, locale.getLanguage() );
if( conceptLabel != null )
conceptElement.setAttributeNS( "", "conceptLabel", conceptLabel );
conceptElement.setAttributeNS( "", "navigable", Vocabulary.getInstance().isVocNavigable( conceptScheme ) + "" );
}
}
String expandedXml = XMLUtil.serialize( doc, true );
//System.out.println( "expandedXml="+expandedXml );
String styleSheet = "metadata/learningObjectToHtml";
Properties props = new Properties();
props.setProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
HashMap<String, String> params = new HashMap<String, String>();
params.put( "uri", uri );
params.put( "isAdmin", isAdmin + "" );
params.put( "isStandalone", isStandalone );
params.put( "imagePath", "true".equals(isStandalone)?"../../../":"" );
params.put( "standaloneCometeLink", Core.getInstance().getCometeUrl() +
"?lang=" + locale.getLanguage() + "&lo-uuid=" + CoreUtil.getIdValue(uri) );
StreamSource source = new StreamSource( new StringReader( expandedXml ) );
String str = ca.licef.comete.core.util.Util.applyXslToDocument( styleSheet, source, props, params, locale );
return( str );
}
private void getIdentityData( String loUri, Set identities, HashMap identityRoles, HashMap identityOrganizations, HashMap orgNames ) throws Exception {
TripleStore tripleStore = Core.getInstance().getTripleStore();
String query = Util.getQuery( "metadata/getLearningObjectIdentityData.sparql", loUri );
Tuple[] tuples = (Tuple[])tripleStore.sparqlSelect( query );
for( Tuple tuple : tuples ) {
String identityUri = tuple.getValue( "identity" ).getContent();
String predicate = tuple.getValue( "p" ).getContent();
String orgUri = tuple.getValue( "org" ).getContent();
String orgName = tuple.getValue( "orgName" ).getContent();
identities.add( identityUri );
Set roles = (Set)identityRoles.get( identityUri );
if( roles == null ) {
roles = new HashSet();
identityRoles.put( identityUri, roles );
}
roles.add( predicate );
if( orgUri != null && !"".equals( orgUri ) ) {
if( orgName != null && !"".equals( orgName ) )
orgNames.put( orgUri, orgName );
Set organizations = (Set)identityOrganizations.get( identityUri );
if( organizations == null ) {
organizations = new HashSet();
identityOrganizations.put( identityUri, organizations );
}
organizations.add( orgUri );
}
}
}
private String getVocabularyConceptLabel( String subjectUri, String lang ) throws Exception {
String[] labels = (String[])Util.getResourceLabel( subjectUri, lang,true );
return( labels[ 0 ] );
}
class ContributeComparator implements Comparator<String> {
public int compare( String a, String b ) {
int indexOfPersonInA = a.indexOf( "person" );
int indexOfOrgInA = a.indexOf( "organization" );
int indexOfPersonInB = b.indexOf( "person" );
int indexOfOrgInB = b.indexOf( "organization" );
if( indexOfPersonInA != -1 && indexOfPersonInB != -1 ||
indexOfOrgInA != -1 && indexOfOrgInB != -1 )
return( 0 );
if( indexOfOrgInA != -1 && indexOfPersonInB != -1 )
return( 1 );
return( -1 );
}
}
}
| LICEF/comete | src/main/java/ca/licef/comete/metadata/LearningObjectView.java | Java | gpl-3.0 | 15,478 |
/*
* @author Pablo Morillas Lozano
*/
package proyecto.blocktris.logica.fisica;
import java.util.ArrayList;
import org.andengine.entity.IEntity;
import org.andengine.entity.scene.Scene;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import com.badlogic.gdx.physics.box2d.Body;
/**
* The Class ObjetoFisico.
*
* @param <T>
* el tipo de gráfico
*/
public abstract class ObjetoFisico <T extends IEntity> {
/** El cuerpo. */
protected Body cuerpo ;
/** El gráfico. */
protected T grafico ;
/** El padre. */
protected Object padre;
/** El mundo. */
protected PhysicsWorld mundo;
/*
* Esta clase es práctica cómo base para cualquier elemento físisco.
* De esta manear se puede incluir una referencia en los userdata de los objetos y tener
* siempre a disposicion el tipo completo y no solo la parte (fisica o gráfica)
*/
public ObjetoFisico(){}
public Object getPadre() {
return padre;
}
public void setPadre(Object padre) {
this.padre = padre;
}
public Body getCuerpo() {
return cuerpo;
}
public T getGrafico() {
return grafico;
}
/**
* Destruye el cuerpo y desengancha el gráfico
*/
public void destruir(){
cuerpo.setActive(false);
mundo.destroyBody(cuerpo);
grafico.detachSelf();
}
public PhysicsWorld getMundo() {
return mundo;
}
/**
* Registrar area tactil.
*
* @param escena
* la escena
*/
public void registrarAreaTactil (Scene escena){
escena.registerTouchArea(this.grafico);
}
/**
* Desregistrar area tactil.
*
* @param escena
* la escena
*/
public void desregistrarAreaTactil (Scene escena){
escena.unregisterTouchArea(this.grafico);
}
/**
* Registrar grafico.
*
* @param entidad
* la entidad
*/
public void registrarGrafico (IEntity entidad){
entidad.attachChild(this.grafico);
}
/**
* Desregistrar grafico.
*/
public void desregistrarGrafico (){
this.grafico.detachSelf();
}
}
| sprayz/Phytris | src/proyecto/blocktris/logica/fisica/ObjetoFisico.java | Java | gpl-3.0 | 2,045 |
# -*- coding: utf-8 -*-
# EDIS - a simple cross-platform IDE for C
#
# This file is part of Edis
# Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail>
# License: GPLv3 (see http://www.gnu.org/licenses/gpl.html)
"""
Éste módulo tiene información acerca de los directorios necesarios para
la aplicación.
"""
import sys
import os
# Home
HOME = os.path.expanduser("~")
# Código fuente
if getattr(sys, 'frozen', ''):
# Ejecutable, cx_Freeze
PATH = os.path.realpath(os.path.dirname(sys.argv[0]))
else:
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), "..")
EDIS = os.path.join(HOME, ".edis")
# Archivo de configuración
CONFIGURACION = os.path.join(EDIS, "edis_config.ini")
# Archivo de log
LOG = os.path.join(EDIS, "edis_log.log")
# Proyecto
PROJECT_DIR = os.path.join(HOME, "EdisProjects")
# Se crea el directorio .edis en el HOME
if not os.path.isdir(EDIS):
os.mkdir(EDIS)
| centaurialpha/edis | src/core/paths.py | Python | gpl-3.0 | 927 |
/*
* Memoris
* Copyright (C) 2017 Jean LELIEVRE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file LevelAnimation.hpp
* @brief interface for all the level animations
* @package animations
* @author Jean LELIEVRE <Jean.LELIEVRE@supinfo.com>
*/
#ifndef MEMORIS_LEVELANIMATION_H_
#define MEMORIS_LEVELANIMATION_H_
#include <memory>
namespace sf
{
/* 'typedef unsigned int Uint32' in SFML/Config.hpp, we declare exactly
the same type here in order to both use declaration forwarding and
prevent conflicting declaration */
typedef unsigned int Uint32;
typedef unsigned char Uint8;
}
namespace memoris
{
namespace utils
{
class Context;
}
namespace entities
{
class Level;
}
namespace animations
{
class LevelAnimation
{
public:
/**
* @brief constructor
*
* @param context the context to use
* @param level the level of the animation
* @param floor the animation floor index
*/
LevelAnimation(
const utils::Context& context,
const std::shared_ptr<entities::Level>& level,
const unsigned short& floor
);
LevelAnimation(const LevelAnimation&) = delete;
LevelAnimation& operator=(const LevelAnimation&) = delete;
/**
* @brief default destructor
*/
virtual ~LevelAnimation();
/**
* @brief renders the animation, called by the game controller
*
* not const because definitions updates object attributes
*
* not noexcept because definitions calls SFML functions that are not
* noexcept
*/
virtual void renderAnimation() & = 0;
/**
* @brief true if the animation is finished
*
* @return const bool&
*/
const bool& isFinished() const & noexcept;
protected:
/**
* @brief getter of the context
*/
const utils::Context& getContext() const & noexcept;
/**
* @brief getter of the level
*/
const std::shared_ptr<entities::Level>& getLevel() const & noexcept;
/**
* @brief getter of the floor
*/
const unsigned short& getFloor() const & noexcept;
/**
* @brief hides or shows the given cell at the given index
*
* @param index the index of the cell to display or to hide
* @param visible boolean that indicates if the cell has to be hide or not
* @param transparency optional transparency of the cell
*
* NOTE: the transparency is used by some animations when updating
* the cells textures without immediately displaying it (horizontal
* mirror animation, vertical mirror animation)
*
* not noexcept because it calls SFML functions
*/
void showOrHideCell(
const unsigned short& index,
const bool& visible,
const sf::Uint8& transparency = 255
) const &;
/**
* @brief increments the animation step
*
* not noexcept because it calls SFML functions that are not noexcept
*/
void incrementAnimationStep() const &;
/**
* @brief moves the player on a new cell according to the updated player
* cell index value
* not noexcept because it calls SFML methods that are not noexcept
*/
void movePlayer() const &;
/**
* @brief getter of the last animation update time
*
* @return const sf::Uint32&
*/
const sf::Uint32& getAnimationLastUpdateTime() const & noexcept;
/**
* @brief setter of the last animation update time;
* used by the stairs animation
*/
void setAnimationLastUpdateTime(const sf::Uint32& time) const & noexcept;
/**
* @brief getter of the animation steps
*
* @return const unsigned short&
*/
const unsigned short& getAnimationSteps() const & noexcept;
/**
* @brief set the animation as finished
*/
void endsAnimation() const & noexcept;
/**
* @brief getter of the new player index after animation
*
* @return const short&
*/
const short& getUpdatedPlayerIndex() const & noexcept;
/**
* @brief setter of the new player index after animation
*
* @param index the new player index after animation
*/
void setUpdatedPlayerIndex(const short& index) const & noexcept;
private:
class Impl;
const std::unique_ptr<Impl> impl;
};
}
}
#endif
| jean553/Memoris | includes/LevelAnimation.hpp | C++ | gpl-3.0 | 4,904 |
<?php
/*
HCSF - A multilingual CMS and Shopsystem
Copyright (C) 2014 Marcus Haase - mail@marcus.haase.name
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace HaaseIT\HCSF;
use Symfony\Component\Yaml\Yaml;
use Zend\ServiceManager\ServiceManager;
/**
* Class HelperConfig
* @package HaaseIT\HCSF
*/
class HelperConfig
{
/**
* @var array
*/
protected $core = [];
/**
* @var array
*/
protected $secrets = [];
/**
* @var array
*/
protected $countries = [];
/**
* @var array
*/
protected $shop = [];
/**
* @var array
*/
protected $customer = [];
/**
* @var array
*/
protected $navigation = [];
/**
* @var string
*/
protected $lang;
/**
* @var array
*/
protected $customization = [];
/**
*
*/
public function __construct()
{
$this->loadCore();
$this->loadCountries();
$this->lang = $this->getLanguage();
$this->loadSecrets();
if ($this->core['enable_module_customer']) {
$this->loadCustomer();
}
if ($this->core['enable_module_shop']) {
$this->loadShop();
}
$this->loadCustomization();
}
/**
* @return string
*/
public function getLang()
{
return $this->lang;
}
/**
*
*/
protected function loadCore()
{
$core = Yaml::parse(file_get_contents(HCSF_BASEDIR.'config/core.yml'));
if (is_file(PATH_BASEDIR.'config/core.yml')) {
$core = array_merge($core, Yaml::parse(file_get_contents(PATH_BASEDIR.'config/core.yml')));
}
$core['directory_images'] = trim($core['directory_images'], " \t\n\r\0\x0B/"); // trim this
if (!empty($core['maintenancemode']) && $core['maintenancemode']) {
$core['enable_module_customer'] = false;
$core['enable_module_shop'] = false;
$core['templatecache_enable'] = false;
$core['debug'] = false;
$core['textcatsverbose'] = false;
} else {
$core['maintenancemode'] = false;
}
if ($core['enable_module_shop']) {
$core['enable_module_customer'] = true;
}
$this->core = $core;
}
/**
* @param string|false $setting
* @return mixed
*/
public function getCore($setting = false)
{
if (!$setting) {
return $this->core;
}
return !empty($this->core[$setting]) ? $this->core[$setting] : false;
}
/**
*
*/
protected function loadCountries()
{
$countries = Yaml::parse(file_get_contents(HCSF_BASEDIR.'config/countries.yml'));
if (is_file(PATH_BASEDIR.'config/countries.yml')) {
$countries = array_merge($countries, Yaml::parse(file_get_contents(PATH_BASEDIR.'config/countries.yml')));
}
$this->countries = $countries;
}
/**
* @param string|false $setting
* @return mixed
*/
public function getCountries($setting = false)
{
if (!$setting) {
return $this->countries;
}
return !empty($this->countries[$setting]) ? $this->countries[$setting] : false;
}
/**
*
*/
protected function loadSecrets()
{
$secrets = Yaml::parse(file_get_contents(HCSF_BASEDIR.'config/secrets.yml'));
if (is_file(PATH_BASEDIR.'config/secrets.yml')) {
$secrets = array_merge($secrets, Yaml::parse(file_get_contents(PATH_BASEDIR.'config/secrets.yml')));
}
$this->secrets = $secrets;
}
/**
* @param string|false $setting
* @return mixed
*/
public function getSecret($setting = false)
{
if (!$setting) {
return $this->secrets;
}
return !empty($this->secrets[$setting]) ? $this->secrets[$setting] : false;
}
/**
*
*/
protected function loadCustomer()
{
$customer = Yaml::parse(file_get_contents(HCSF_BASEDIR.'config/customer.yml'));
if (is_file(PATH_BASEDIR.'/config/customer.yml')) {
$customer = array_merge($customer, Yaml::parse(file_get_contents(PATH_BASEDIR.'config/customer.yml')));
}
$this->customer = $customer;
}
/**
* @param string|bool $setting
* @return mixed
*/
public function getCustomer($setting = false)
{
if (!$setting) {
return $this->customer;
}
return !empty($this->customer[$setting]) ? $this->customer[$setting] : false;
}
/**
*
*/
protected function loadShop()
{
$shop = Yaml::parse(file_get_contents(HCSF_BASEDIR.'config/shop.yml'));
if (is_file(PATH_BASEDIR.'config/shop.yml')) {
$shop = array_merge($shop, Yaml::parse(file_get_contents(PATH_BASEDIR.'config/shop.yml')));
}
if (isset($shop['vat_disable']) && $shop['vat_disable']) {
$shop['vat'] = ['full' => 0, 'reduced' => 0];
}
$this->shop = $shop;
}
/**
* @param string|false $setting
* @return mixed
*/
public function getShop($setting = false)
{
if (!$setting) {
return $this->shop;
}
return !empty($this->shop[$setting]) ? $this->shop[$setting] : false;
}
/**
* @param ServiceManager $serviceManager
*/
public function loadNavigation(ServiceManager $serviceManager)
{
if (is_file(PATH_BASEDIR.'config/navigation.yml')) {
$navstruct = Yaml::parse(file_get_contents(PATH_BASEDIR.'config/navigation.yml'));
} else {
$navstruct = Yaml::parse(file_get_contents(HCSF_BASEDIR.'config/navigation.yml'));
}
if (!empty($navstruct) && $this->core['navigation_fetch_text_from_textcats']) {
$textcats = $serviceManager->get('textcats');
$TMP = [];
foreach ($navstruct as $key => $item) {
foreach ($item as $subkey => $subitem) {
if (!empty($textcats->T($subkey))) {
$TMP[$key][$textcats->T($subkey)] = $subitem;
} else {
$TMP[$key][$subkey] = $subitem;
}
}
}
$navstruct = $TMP;
unset($TMP);
}
if (isset($navstruct['admin'])) {
unset($navstruct['admin']);
}
$hardcodedtextcats = $serviceManager->get('hardcodedtextcats');
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_home')] = '/_admin/index.html';
if ($this->core['enable_module_shop']) {
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_orders')] = '/_admin/shopadmin.html';
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_items')] = '/_admin/itemadmin.html';
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_itemgroups')] = '/_admin/itemgroupadmin.html';
}
if ($this->core['enable_module_customer']) {
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_customers')] = '/_admin/customeradmin.html';
}
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_pages')] = '/_admin/pageadmin.html';
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_textcats')] = '/_admin/textcatadmin.html';
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_cleartemplatecache')] = '/_admin/cleartemplatecache.html';
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_clearimagecache')] = '/_admin/clearimagecache.html';
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_phpinfo')] = '/_admin/phpinfo.html';
$navstruct['admin'][$hardcodedtextcats->get('admin_nav_dbstatus')] = '/_admin/dbstatus.html';
$this->navigation = $navstruct;
}
/**
* @param string|false $setting
* @return mixed
*/
public function getNavigation($setting = false)
{
if (!$setting) {
return $this->navigation;
}
return !empty($this->navigation[$setting]) ? $this->navigation[$setting] : false;
}
/**
* @return int|mixed|string
*/
public function getLanguage()
{
$langavailable = $this->core['lang_available'];
if (
$this->core['lang_detection_method'] === 'domain'
&& isset($this->core['lang_by_domain'])
&& is_array($this->core['lang_by_domain'])
) { // domain based language detection
$serverservername = filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_URL);
foreach ($this->core['lang_by_domain'] as $sKey => $sValue) {
if ($serverservername == $sValue || $serverservername == 'www.'.$sValue) {
$sLang = $sKey;
break;
}
}
} elseif ($this->core['lang_detection_method'] === 'legacy') { // legacy language detection
$sLang = key($langavailable);
$getlanguage = filter_input(INPUT_GET, 'language', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$cookielanguage = filter_input(INPUT_COOKIE, 'language', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$serverhttpaccepptlanguage = filter_input(INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
if ($getlanguage !== null && array_key_exists($getlanguage, $langavailable)) {
$sLang = strtolower($getlanguage);
setcookie('language', strtolower($getlanguage), 0, '/');
} elseif ($cookielanguage !== null && array_key_exists($cookielanguage, $langavailable)) {
$sLang = strtolower($cookielanguage);
} elseif ($serverhttpaccepptlanguage !== null && array_key_exists(substr($serverhttpaccepptlanguage, 0, 2), $langavailable)) {
$sLang = substr($serverhttpaccepptlanguage, 0, 2);
}
}
if (!isset($sLang)) {
$sLang = key($langavailable);
}
return $sLang;
}
protected function loadCustomization()
{
$customization = [];
if (is_file(PATH_BASEDIR.'config/customization.yml')) {
$customization = array_merge($customization, Yaml::parse(file_get_contents(PATH_BASEDIR.'config/customization.yml')));
}
$this->customization = $customization;
}
/**
* @param bool $setting
* @return array|bool|mixed
*/
public function getCustomization($setting = false) {
if (!$setting) {
return $this->customization;
}
return !empty($this->customization[$setting]) ? $this->customization[$setting] : false;
}
}
| HaaseIT/HCSF | src/HelperConfig.php | PHP | gpl-3.0 | 11,419 |
/* <pcapwrapper.cpp>
Copyright(C) 2013,2014 Jan Simon Bunten
Simon Kadel
Martin Sven Oehler
Arne Sven Stühlmeyer
This File is part of the WhisperLibrary
WhisperLibrary is free software : you can redistribute it and / or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
WhisperLibrary is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <pcapwrapper.hpp>
namespace whisper_library {
PcapWrapper::PcapWrapper() {
// initialize
DEBUG(2, "PcapWrapper construction.\n");
m_last_return_codes = boost::circular_buffer<int>(RETURN_CODE_BUFFER_SIZE);
m_adapter_raw_data = NULL;
retrieveAdapters();
}
PcapWrapper::~PcapWrapper() {
DEBUG(2, "PcapWrapper destruction.\n");
freeAdapters();
m_last_return_codes.clear();
}
inline bool PcapWrapper::checkForAdapterId(int adapter_id) {
if (m_adapter_data.empty()) {
// unsafe call
fprintf(stderr, "Warning: Adapter requested while all adapters are freed. Retrieving adapters...");
retrieveAdapters();
}
if (static_cast<int>(m_adapter_data.size()) <= adapter_id) { // ID starts with 0
// specified adapter not found
fprintf(stderr, "Error: No network device with ID #%d\n", adapter_id);
RETURN_VALUE(RC(ADAPTER_NOT_FOUND), false);
}
RETURN_VALUE(RC(NORMAL_EXECUTION), true);
}
std::string PcapWrapper::adapterName(int adapter_id) {
if (!checkForAdapterId(adapter_id)) {
// specified adapter not found
RETURN_VALUE(RC(ADAPTER_NOT_FOUND), NULL);
}
RETURN_VALUE(RC(NORMAL_EXECUTION), m_adapter_data[adapter_id][ADAPTER_NAME]);
}
std::vector<std::string> PcapWrapper::adapterNames() {
/* we could use getAdapterName(adapter_id) here,
but constant checking for the adapter_id would be a unnecessary waste of performance */
std::vector<std::string> ret;
for (std::vector<std::string> adapter : m_adapter_data) {
ret.push_back(adapter[ADAPTER_NAME]);
}
RETURN_VALUE(RC(NORMAL_EXECUTION), ret);
}
int PcapWrapper::adapterId(std::string value, int key, bool increment_key) {
int i, j;
for (i = 0; i < static_cast<int>(m_adapter_data.size()); ++i) {
for (j = key; j < static_cast<int>(m_adapter_data[i].size()) && increment_key || j == key; ++j) {
if (value.compare(m_adapter_data[i][j]) == 0) {
RETURN_VALUE(RC(NORMAL_EXECUTION), i);
}
}
}
RETURN_CODE(RC(ADAPTER_NOT_FOUND));
}
int PcapWrapper::adapterId(std::string adapter_value, int value_type) {
return adapterId(adapter_value, value_type, (value_type == ADAPTER_ADDRESS ? true : false));
}
std::vector<std::string> PcapWrapper::adapterAddresses(int adapter_id) {
std::vector<std::string> ret;
if (!checkForAdapterId(adapter_id)) { return ret; } // specified adapter not found
for (unsigned int i = ADAPTER_ADDRESS; i < (m_adapter_data[adapter_id]).size(); ++i) {
ret.push_back(m_adapter_data[adapter_id][i]);
}
RETURN_VALUE(RC(NORMAL_EXECUTION), ret);
}
std::string PcapWrapper::adapterDescription(int adapter_id) {
if (!checkForAdapterId(adapter_id)) {
// specified adapter not found
RETURN_VALUE(RC(ADAPTER_NOT_FOUND), NULL);
}
RETURN_VALUE(RC(NORMAL_EXECUTION), m_adapter_data[adapter_id][ADAPTER_DESCRIPTION]);
}
int PcapWrapper::adapterCount() {
return static_cast<int>(m_adapter_data.size());
}
int PcapWrapper::retrieveAdapters() {
freeAdapters(); // free potentially opened adapters
char error_buffer[PCAP_ERRBUF_SIZE]; // pcap error buffer
// find all openable devices
if (pcap_findalldevs(&m_adapter_raw_data, error_buffer) == -1) {
fprintf(stderr, "Error: Failed to retrieve network adapters: %s\n", error_buffer);
RETURN_CODE(RC(ERROR_RETRIEVING_ADAPTERS));
}
if ( m_adapter_raw_data == NULL ) {
fprintf(stderr, "Error: No network adapters found or insufficient permissions.\n");
RETURN_CODE(RC(NO_ADAPTERS_FOUND));
}
for (pcap_if_t* adapter = m_adapter_raw_data; adapter; adapter = adapter->next) {
/* Only include adapters with a pcap address
This prevents inactive or slave devices (aggregation/bonding slaves) from being added
and we only get the intermediate drivers instead.
*/
if (!adapter->addresses) { continue; }
std::vector<std::string> current_adapter;
current_adapter.push_back(adapter->name); // adapter/device name in the system (for example /dev/eth0)
if (adapter->description) {
current_adapter.push_back(adapter->description); // adapter descriptional name (usually the product name of the network card o.s.)
}
else {
current_adapter.push_back("");
}
bpf_u_int32 netmask;
bpf_u_int32 ip4_address;
if (pcap_lookupnet(adapter->name, &netmask, &ip4_address, error_buffer) < 0) {
netmask = 0;
}
m_adapter_netmasks.push_back(netmask);
DEBUG(1, "Device Name: %s\nDescription: %s\nFlags: #%d\n", adapter->name, adapter->description, adapter->flags);
// get adapter addresses
char* address_buffer;
size_t buffer_size = 0;
for (pcap_addr* address = adapter->addresses; address; address = address->next) {
buffer_size = 0;
switch (address->addr->sa_family) {
// address families with 32 bit addresses
case AF_INET: { // UDP, TCP, ...
buffer_size = 16; // usual size of a ipv4 string representation
break;
}
// address families with 128 bit addresses
case AF_INET6: { // IPv6
buffer_size = 45; // usual size of a ipv6 string representation
break;
}
// unknown or unspecified families
default: {
DEBUG(1, "Device Address Unknown\n\n");
// Currently no point in adding adapter addresses of unknown families.
continue;
}
}
// deallocation in freeAdapters
buffer_size *= sizeof(char); // byte size
address_buffer = static_cast<char*>(malloc(buffer_size));
if (!address_buffer) {
fprintf(stderr, "Error: Out of memory.\n");
RETURN_CODE(RC(OUT_OF_MEMORY));
}
// currently only addresses up to 128bit and known to getnameinfo are supported by ipToString
ipToString(address->addr, address_buffer, buffer_size);
if (address_buffer) {
current_adapter.push_back(std::string(address_buffer));
}
free(address_buffer);
}
// Set global adapter_data
m_adapter_data.push_back(current_adapter);
}
RETURN_CODE(RC(NORMAL_EXECUTION));
}
int PcapWrapper::openAdapter(int adapter_id, int max_packet_size, bool promiscuous_mode, int timeout) {
if (!checkForAdapterId(adapter_id)) { RETURN_CODE(RC(ADAPTER_NOT_FOUND)); } // specified adapter not found
// open handle
char error_buffer[PCAP_ERRBUF_SIZE]; // pcap error buffer
// resize handles vector as needed
if (static_cast<int>(m_adapter_handles.size()) <= adapter_id) {
m_adapter_handles.resize(adapter_id + 1);
} else if (m_adapter_handles[adapter_id]) {
fprintf(stderr, "Warning: Tried to open already open adapter #%d\n", adapter_id);
RETURN_CODE(RC(OPEN_ON_OPENED_HANDLE));
}
// open handle for live capturing
m_adapter_handles[adapter_id] = pcap_open_live(m_adapter_data[adapter_id][0].c_str(), max_packet_size, (promiscuous_mode ? 1 : 0 ), timeout, error_buffer);
if (!m_adapter_handles[adapter_id]) {
fprintf(stderr, "Error: Failed to open handle on network device #%d (%s)\n%s\n", adapter_id, m_adapter_data[adapter_id][0].c_str(), error_buffer);
RETURN_CODE(RC(ERROR_OPENING_HANDLE));
}
DEBUG(1, "Capturing started on device #%d\n", adapter_id);
RETURN_CODE(RC(NORMAL_EXECUTION));
}
int PcapWrapper::openAdapter(std::string adapter_name, int max_packet_size, bool promiscuous_mode, int timeout) {
return openAdapter(adapterId(adapter_name, ADAPTER_NAME), max_packet_size, promiscuous_mode, timeout);
}
int PcapWrapper::closeAdapter(std::string adapter_name) {
return closeAdapter(adapterId(adapter_name, ADAPTER_NAME));
}
int PcapWrapper::closeAdapter(int adapter_id) {
if (!checkForAdapterId(adapter_id)) { RETURN_CODE(RC(ADAPTER_NOT_FOUND)); } // specified adapter not found
if (static_cast<int>(m_adapter_handles.size()) > adapter_id && m_adapter_handles[adapter_id]) {
pcap_close(m_adapter_handles[adapter_id]);
m_adapter_handles[adapter_id] = NULL;
RETURN_CODE(RC(NORMAL_EXECUTION));
}
// Nothing to close
fprintf(stderr, "Warning: Tried to close unopened adapter #%d\n", adapter_id);
RETURN_CODE(RC(CLOSE_ON_UNOPENED_HANDLE));
}
int PcapWrapper::freeAdapters() {
if (m_adapter_raw_data == NULL) {
// nothing to free
RETURN_CODE(RC(NORMAL_EXECUTION));
}
// close (still) open handles
for (pcap_t* handle : m_adapter_handles) {
if (handle) { pcap_close(handle); }
}
// clear vector content
m_adapter_data.clear();
m_adapter_handles.clear();
m_adapter_netmasks.clear();
// free adapters
pcap_freealldevs( m_adapter_raw_data );
// purge old values
m_adapter_raw_data = NULL;
RETURN_CODE(RC(NORMAL_EXECUTION));
}
int PcapWrapper::applyFilter(int adapter_id, std::string filter) {
if (!checkForAdapterId(adapter_id)) { return -1; } // specified adapter not found
struct bpf_program filter_compiled;
pcap_t* handle = NULL;
if (static_cast<int>(m_adapter_handles.size()) > adapter_id) {
handle = m_adapter_handles[adapter_id]; // fetch adapter handle
}
if (!handle) {
fprintf(stderr, "Error: applyFilter() called on unopened adapter.\n");
RETURN_CODE(RC(ACCESS_ON_UNOPENED_HANDLE));
}
// get adapter netmask (if set)
bpf_u_int32 netmask;
if (m_adapter_netmasks.size() > adapter_id && m_adapter_netmasks[adapter_id] != 0) {
netmask = m_adapter_netmasks[adapter_id];
} else {
netmask = PCAP_NETMASK_UNKNOWN;
}
// compile packet filter
if (pcap_compile(handle, &filter_compiled, filter.c_str(), 1, netmask) < 0) {
fprintf(stderr, "Error: Failed to compile given filter.\n");
RETURN_CODE(RC(ERROR_COMPILING_FILTER));
}
// set packet filter
if (pcap_setfilter(handle, &filter_compiled) < 0) {
fprintf(stderr, "Error: Failed to apply the given filter.\n");
RETURN_CODE(RC(ERROR_APPLYING_FILTER));
}
DEBUG(1, "Filter successfully applied.\nFilter: %s\n", filter.c_str());
RETURN_CODE(RC(NORMAL_EXECUTION));
}
int PcapWrapper::applyFilter(std::string adapter_name, std::string filter) {
return applyFilter(adapterId(adapter_name, ADAPTER_NAME), filter);
}
int PcapWrapper::removeFilter(std::string adapter_name) {
return applyFilter(adapter_name, "");
}
int PcapWrapper::removeFilter(int adapter_id) {
return applyFilter(adapter_id, "");
}
PcapWrapper::PcapPacket PcapWrapper::retrievePacket(int adapter_id) {
PcapPacket packet = { {}, nullptr };
if (!checkForAdapterId(adapter_id)) {
RETURN_VALUE(RC(ADAPTER_NOT_FOUND), packet); // specified adapter not found
}
/*
struct pcap_pkthdr:
struct timeval ts; - system dependent size (either 32 or 64bit)
bpf_u_int32 caplen;
bpf_u_int32 len;
*/
struct pcap_pkthdr* packet_header;
const u_char* packet_data;
pcap_t* handle = NULL;
int iterations = 0;
int return_code = 0;
if (static_cast<int>(m_adapter_handles.size()) > adapter_id) {
handle = m_adapter_handles[adapter_id];
}
if (!handle) {
fprintf(stderr, "Error: retrievePacket() called on unopened adapter.\n");
RETURN_VALUE(RC(ACCESS_ON_UNOPENED_HANDLE), packet);
}
/* Note:
packet_data can contain NULL if
1. an error occured
2. no packets were read from live capture (due to read timeout) in 500 tries
3. no packet passed the filter
Quote from winpcap doc: "Unfortunately, there is no way to determine whether an error occured or not."
( http://www.winpcap.org/docs/docs_412/html/group__wpcapfunc.html#gadf60257f650aaf869671e0a163611fc3 )
*/
while ( (return_code = pcap_next_ex(handle, &packet_header, &packet_data)) == 0 && ++iterations <= 500);
DEBUG(3, "Packet data: %u - length: %d\n", (packet_data ? reinterpret_cast<const unsigned int*>(packet_data) : 0), packet_header->len);
if (return_code == 1) {
packet.payload = packet_data;
packet.header = *packet_header;
}
RETURN_VALUE(RC((return_code == 1 ? NORMAL_EXECUTION : EMPTY_PACKET_DATA)), packet);
}
PcapWrapper::PcapPacket PcapWrapper::retrievePacket(std::string adapter_name) {
return retrievePacket(adapterId(adapter_name, ADAPTER_NAME));
}
std::vector<bool> PcapWrapper::retrievePacketAsVector(int adapter_id) {
std::vector<bool> bitVector;
PcapPacket packet = retrievePacket(adapter_id);
if (packet.payload == NULL) {
RETURN_VALUE(RC(EMPTY_PACKET_DATA), bitVector);
}
const unsigned char* it = packet.payload;
unsigned int i, j;
for (i = 0; i < packet.header.len; ++i, ++it) {
for (j = 0; j < 8; ++j) {
bitVector.push_back((*it & (1 << j)) != 0);
}
}
RETURN_VALUE(RC(NORMAL_EXECUTION), bitVector);
}
std::vector<bool> PcapWrapper::retrievePacketAsVector(std::string adapter_name) {
return retrievePacketAsVector(adapterId(adapter_name, ADAPTER_NAME));
}
inline char* PcapWrapper::ipToString(struct sockaddr* socket_address, char* buffer, size_t buffer_length) {
if (!socket_address) { return NULL; }
// sockaddr_storage requires Windows XP, Windows Server 2003 or later
socklen_t address_length = sizeof(struct sockaddr_storage);
DEBUG(2, "ipToString()\nBuffer length: %d; Address Length: %d\n", static_cast<unsigned int>(buffer_length), static_cast<unsigned int>(address_length));
getnameinfo(socket_address, address_length, buffer, buffer_length, NULL, 0, NI_NUMERICHOST);
DEBUG(2, "Address from getnameinfo: %s\n\n", (buffer) ? buffer : "NULL");
return (buffer);
}
std::vector<int> PcapWrapper::lastReturnCodes() {
std::vector<int> returnCodes = std::vector<int>(m_last_return_codes.size());
for (unsigned int i = 0; i < m_last_return_codes.size(); ++i) {
returnCodes[i] = m_last_return_codes[i];
}
return returnCodes;
}
void PcapWrapper::clearReturnCodes() {
m_last_return_codes.clear();
}
int PcapWrapper::sendPacket(int adapter_id, unsigned char* packet_buffer, int buffer_size) {
#ifdef WIN32
if (!checkForAdapterId(adapter_id)) {
// specified adapter not found
RETURN_CODE(RC(ADAPTER_NOT_FOUND));
}
pcap_t* handle = NULL;
if (static_cast<int>(m_adapter_handles.size()) > adapter_id) {
handle = m_adapter_handles[adapter_id];
}
if (!handle) {
fprintf(stderr, "Error: retrievePacket() called on unopened adapter.\n");
RETURN_CODE(RC(ACCESS_ON_UNOPENED_HANDLE));
}
if (pcap_sendpacket(handle, packet_buffer, buffer_size ) < 0) {
fprintf(stderr, "Error: Failed to send the given packet: \n", pcap_geterr(handle));
RETURN_CODE(RC(UNSPECIFIED_ERROR_OCCURED));
}
RETURN_CODE(RC(NORMAL_EXECUTION));
#else
fprintf(stderr, "Error: Wrong function called. pcap_sendpacket(...) only works with WinPcap.\n");
RETURN_CODE(RC(UNSPECIFIED_ERROR_OCCURED));
#endif
}
int PcapWrapper::sendPacket(std::string adapter_name, unsigned char* packet_buffer, int buffer_size) {
return sendPacket(adapterId(adapter_name, ADAPTER_NAME), packet_buffer, buffer_size);
}
int PcapWrapper::sendPacket(int adapter_id, std::vector<bool> packet_data) {
if (packet_data.size() < 1) { RETURN_CODE(RC(NORMAL_EXECUTION)); } // nothing to send
int buffer_size = packet_data.size() / 8;
unsigned char* buffer = static_cast<unsigned char*>(malloc(buffer_size));
if (!buffer) {
fprintf(stderr, "Error: Out of memory.\n");
RETURN_CODE(RC(OUT_OF_MEMORY));
}
// convert logical values to numerical
int i, j, return_code;
for (i = 0; i < buffer_size; ++i) {
buffer[i] = 0; // initialize
for (j = 0; j < 8; ++j) {
DEBUG(4, "bit index: %d, data index: %d, value: %d\n", j, j + (i * 8), (packet_data[j + (i * 8)] ? 1 : 0));
buffer[i] |= (packet_data[j + (i * 8)] ? 1 : 0) << j;
}
DEBUG(3, "send buffer char #%d content: %u\n\n", i, buffer[i]);
}
return_code = sendPacket(adapter_id, buffer, buffer_size);
free(buffer); // important!
RETURN_CODE(return_code);
}
int PcapWrapper::sendPacket(std::string adapter_name, std::vector<bool> packet_data) {
return sendPacket(adapterId(adapter_name, ADAPTER_NAME), packet_data);
}
}
| UndeadKernel/whisper-library | whisperLibrary/src/pcapwrapper.cpp | C++ | gpl-3.0 | 16,517 |
require 'rake'
PKG_NAME = 'hornetseye-openexr'
PKG_VERSION = '1.0.2'
CFG = RbConfig::CONFIG
CXX = ENV[ 'CXX' ] || 'g++'
RB_FILES = ['config.rb'] + FileList[ 'lib/**/*.rb' ]
CC_FILES = FileList[ 'ext/*.cc' ]
HH_FILES = FileList[ 'ext/*.hh' ] + FileList[ 'ext/*.tcc' ]
TC_FILES = FileList[ 'test/tc_*.rb' ]
TS_FILES = FileList[ 'test/ts_*.rb' ]
SO_FILE = "ext/#{PKG_NAME.tr '\-', '_'}.#{CFG[ 'DLEXT' ]}"
PKG_FILES = [ 'Rakefile', 'README.md', 'COPYING', '.document' ] +
RB_FILES + CC_FILES + HH_FILES + TS_FILES + TC_FILES
BIN_FILES = [ 'README.md', 'COPYING', '.document', SO_FILE ] +
RB_FILES + TS_FILES + TC_FILES
SUMMARY = %q{Loading and saving images using OpenEXR}
DESCRIPTION = %q{This Ruby extension provides reading and writing high dynamic range images using OpenEXR.}
LICENSE = 'GPL-3+'
AUTHOR = %q{Jan Wedekind}
EMAIL = %q{jan@wedesoft.de}
HOMEPAGE = %q{http://wedesoft.github.com/hornetseye-openexr/}
| wedesoft/hornetseye-openexr | config.rb | Ruby | gpl-3.0 | 937 |
<?php
namespace AOE\HappyFeet\Typo3\Hook;
/*
* Copyright notice
*
* (c) 2014 AOE GmbH <dev@aoe.com>
*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Core\LinkHandling\LinkHandlingInterface;
/**
* Linkhandler hook to manipulate link data before it is processed by core typolink method.
*
* @package HappyFeet
*/
class LinkHandler implements LinkHandlingInterface
{
/**
* The Base URN for this link handling to act on
*
* @var string
*/
protected $baseUrn = 't3://happy_feet';
/**
* Returns all valid parameters for linking to a TYPO3 page as a string
*
* @param array $parameters
* @return string
* @throws \InvalidArgumentException
*/
public function asString(array $parameters): string
{
if (empty($parameters['uid'])) {
throw new \InvalidArgumentException('The HappyFeetLinkHandler expects uid as $parameter configuration.', 1486155150);
}
$urn = $this->baseUrn;
$urn .= sprintf('?uid=%s', $parameters['uid']);
if (!empty($parameters['fragment'])) {
$urn .= sprintf('#%s', $parameters['fragment']);
}
return $urn;
}
/**
* Returns all relevant information built in the link to a page (see asString())
*
* @param array $data
* @return array
* @throws \InvalidArgumentException
*/
public function resolveHandlerData(array $data): array
{
if (empty($data['uid'])) {
throw new \InvalidArgumentException('The HappyFeetLinkHandler expects identifier, uid as $data configuration', 1486155151);
}
return $data;
}
}
| AOEpeople/happy_feet | Classes/Typo3/Hook/LinkHandler.php | PHP | gpl-3.0 | 2,046 |
using System;
namespace BrickApp.Models.BrickStore
{
public class WebsiteAd
{
public int WebsiteAdId { get; set; }
public DateTime? Start { get; set; }
public DateTime? End { get; set; }
public string TagLine { get; set; }
public string Details { get; set; }
public string Url { get; set; }
public string ImageUrl { get; set; }
}
} | smulholland2/BrickApp | src/BrickApp/Models/BrickStore/WebsiteAd.cs | C# | gpl-3.0 | 403 |
package net.lecousin.framework.ui.eclipse.control.list;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.lecousin.framework.Pair;
import net.lecousin.framework.Triple;
import net.lecousin.framework.event.Event;
import net.lecousin.framework.event.Event.Listener;
import net.lecousin.framework.geometry.PointInt;
import net.lecousin.framework.geometry.RectangleInt;
import net.lecousin.framework.lang.MyBoolean;
import net.lecousin.framework.log.Log;
import net.lecousin.framework.thread.RunnableWithData;
import net.lecousin.framework.ui.eclipse.UIUtil;
import net.lecousin.framework.ui.eclipse.control.UIControlUtil;
import net.lecousin.framework.ui.eclipse.event.DragSourceListenerWithData;
import net.lecousin.framework.ui.eclipse.graphics.ColorUtil;
import net.lecousin.framework.ui.eclipse.helper.OnDemandLayoutAndCreate;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Pattern;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Slider;
public class LCTable<T> implements LCViewer<T,Composite> {
public LCTable(Composite parent, LCTableProvider<T> provider) {
this(parent, provider.getContentProvider(), provider.getColumns(), provider.getConfig());
}
public LCTable(Composite parent, LCContentProvider<T> contentProvider, ColumnProvider<T>[] columnsProvider, TableConfig config) {
this.contentProvider = contentProvider;
this.config = config;
panel = new Composite(parent, SWT.BORDER);
panel.setBackground(ColorUtil.getWhite());
UIUtil.gridLayout(panel, 2, 0, 0);
ScrolledComposite contentScroll = new ScrolledComposite(panel, SWT.H_SCROLL);
contentScroll.setBackground(panel.getBackground());
contentScroll.setLayoutData(UIUtil.gridData(1, true, 1, true));
verticalBar = new Slider(panel, SWT.VERTICAL);
verticalBar.setLayoutData(UIUtil.gridDataVert(1, true));
verticalBar.setMinimum(0);
verticalBar.setIncrement(20);
contentPanel = UIUtil.newGridComposite(contentScroll, 0, 0, columnsProvider.length, 1, 0);
contentScroll.setContent(contentPanel);
contentScroll.setExpandVertical(true);
resizer.register(contentPanel);
columns = new ArrayList<Column>(columnsProvider.length);
for (int i = 0; i < columnsProvider.length; ++i)
columns.add(new Column(columnsProvider[i]));
boolean first = true;
for (Column c : columns) {
c.header = new ColumnHeader(contentPanel, c);
if (first) {
first = false;
GridData gd = new GridData();
gd.horizontalIndent = 1;
c.header.setLayoutData(gd);
}
}
scrollRows = UIUtil.newComposite(contentPanel);
scrollRows.setLayoutData(UIUtil.gridData(columnsProvider.length, true, 1, true));
scrollRows.setLayout(new Layout() {
private boolean done = false;
@Override
protected Point computeSize(Composite composite, int hint, int hint2, boolean flushCache) {
return new Point(hint, hint2);
}
@Override
protected void layout(Composite composite, boolean flushCache) {
if (!done) {
done = true;
layout.refreshAll();
}
//layout.layout(panelRows, true);
}
});
panelRows = UIUtil.newComposite(scrollRows);
panelRows.setLocation(0, 0);
ondemand = new OnDemandLayoutAndCreate(panelRows);
layout = new TableLayout();
panelRows.setLayout(layout);
panelRows.addControlListener(new ControlListener() {
public void controlMoved(ControlEvent e) {
}
public void controlResized(ControlEvent e) {
refreshVerticalBar();
}
});
scrollRows.addControlListener(new ControlListener() {
public void controlMoved(ControlEvent e) {
}
public void controlResized(ControlEvent e) {
refreshScrollRowsSize();
}
});
scrollRows.addMouseWheelListener(new MouseWheelListener() {
public void mouseScrolled(MouseEvent e) {
if (e.button == 0) {
int i = verticalBar.getSelection();
i -= e.count * verticalBar.getIncrement();
if (i < 0) i = 0;
if (i > verticalBar.getMaximum()) i = verticalBar.getMaximum();
verticalBar.setSelection(i);
verticalScrollChanged();
}
}
});
verticalBar.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
verticalScrollChanged();
}
});
UIControlUtil.recursiveKeyListener(panel, keyListener);
refresh(true);
contentPanel.setSize(contentPanel.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
panelRows.addPaintListener(new RowsPainter());
panel.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
for (Event<T> ev : addElementEvents)
ev.removeListener(addElementListener);
for (Event<T> ev : removeElementEvents)
ev.removeListener(removeElementListener);
for (Event<T> ev : elementChangedEvents)
ev.removeListener(elementChangedListener);
for (Event<?> ev : contentChangedEvents)
ev.removeFireListener(contentChangedListener);
verticalBar = null;
panel = null;
scrollRows = null;
panelRows = null;
layout = null;
columns.clear(); columns = null;
rows.clear(); rows = null;
LCTable.this.contentProvider = null;
LCTable.this.config = null;
addElementEvents.clear(); addElementEvents = null;
addElementListener = null;
backgroundAdd = null;
LCTable.this.contentChangedEvents.clear(); LCTable.this.contentChangedEvents = null;
LCTable.this.contentChangedListener = null;
LCTable.this.doubleClick.free(); LCTable.this.doubleClick = null;
LCTable.this.drags.clear(); LCTable.this.drags = null;
for (DragSource ds : dragSources.values())
ds.dispose();
for (DropTarget dt : drops)
dt.dispose();
LCTable.this.drops.clear(); LCTable.this.drops = null;
LCTable.this.dragSources.clear(); LCTable.this.dragSources = null;
LCTable.this.elementChangedEvents.clear(); LCTable.this.elementChangedEvents = null;
LCTable.this.elementChangedListener = null;
LCTable.this.keyListener = null;
LCTable.this.keyListeners.clear(); LCTable.this.keyListeners = null;
LCTable.this.removeElementEvents.clear(); LCTable.this.removeElementEvents = null;
LCTable.this.removeElementListener = null;
LCTable.this.resizer = null;
LCTable.this.rightClick.free(); LCTable.this.rightClick = null;
LCTable.this.selectionChanged.free(); LCTable.this.selectionChanged = null;
}
});
}
private Slider verticalBar;
private Composite panel;
private Composite contentPanel;
private Composite scrollRows;
private Composite panelRows;
private OnDemandLayoutAndCreate ondemand;
private TableLayout layout;
private ArrayList<Column> columns;
private List<Row> rows = new LinkedList<Row>();
private LCContentProvider<T> contentProvider;
private TableConfig config;
public Composite getControl() { return panel; }
public interface ColumnProvider<T> {
public String getTitle();
public int getDefaultWidth();
public int getAlignment();
}
public interface ColumnProviderText<T> extends ColumnProvider<T> {
public String getText(T element);
public Font getFont(T element);
public Image getImage(T element);
public int compare(T element1, String text1, T element2, String text2);
}
public interface ColumnProviderControl<T> extends ColumnProvider<T> {
public Control getControl(Composite parent, T element);
public int compare(T element1, T element2);
}
public static class TableConfig {
public boolean multiSelection = true;
public int fixedRowHeight = 18;
public boolean sortable = true;
}
public static interface LCTableProvider<T> {
public LCContentProvider<T> getContentProvider();
public ColumnProvider<T>[] getColumns();
public TableConfig getConfig();
}
public static abstract class LCTableProvider_List<T> implements LCTableProvider<T> {
public LCTableProvider_List(List<T> data) {
this.list = data;
}
protected List<T> list;
}
public static abstract class LCTableProvider_SingleColumnText<T> implements LCTableProvider<T> {
public LCTableProvider_SingleColumnText(List<T> data) {
this(data, "", SWT.LEFT, true);
}
public LCTableProvider_SingleColumnText(List<T> data, String columnTitle, int alignment, boolean multiSelection) {
this.data = data;
this.columnTitle = columnTitle;
this.alignment = alignment;
this.multiSelection = multiSelection;
}
private List<T> data;
private String columnTitle;
private int alignment;
boolean multiSelection;
public LCContentProvider<T> getContentProvider() {
return new LCContentProvider<T>() {
public Iterable<T> getElements() { return data; }
};
}
@SuppressWarnings("unchecked")
public ColumnProvider<T>[] getColumns() {
return new ColumnProvider[] {
new ColumnProviderText<T>() {
public String getTitle() { return columnTitle; }
public String getText(T element) { return LCTableProvider_SingleColumnText.this.getText(element); }
public Image getImage(T element) { return LCTableProvider_SingleColumnText.this.getImage(element); }
public int getAlignment() { return alignment; }
public int getDefaultWidth() { return 200; }
public Font getFont(T element) { return null; }
public int compare(T element1, String text1, T element2, String text2) { return text1.compareTo(text2); }
}
};
}
public TableConfig getConfig() {
TableConfig config = new TableConfig();
config.fixedRowHeight = 18;
config.multiSelection = multiSelection;
return config;
}
public abstract String getText(T element);
public abstract Image getImage(T element);
}
private class Column {
Column(ColumnProvider<T> provider) {
this.provider = provider;
width = provider.getDefaultWidth();
}
ColumnProvider<T> provider;
int width;
int sort = 0;
ColumnHeader header;
}
private int lastSelection = -1;
private class Row implements OnDemandLayoutAndCreate.ControlsContainer {
Row(T element) {
this.element = element;
panel.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
Row.this.element = null;
_controls = null;
}
});
}
public Control[] createControls() {
_controls = new Control[columns.size()];
for (int i = 0; i < columns.size(); ++i)
_controls[i] = createControl(columns.get(i), i);
UIControlUtil.recursiveMouseListener(_controls[0], new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
panelRows.setFocus();
doubleClick.fire(Row.this.element);
}
public void mouseDown(MouseEvent e) {
panelRows.setFocus();
if (e.button == 1) {
int index = rows.indexOf(Row.this);
if ((e.stateMask & SWT.CTRL) != 0) {
if (config.multiSelection) {
if ((e.stateMask & SWT.SHIFT) != 0) {
if (lastSelection >= 0 && lastSelection < index && !selected) {
for (int i = lastSelection+1; i <= index; ++i) {
Row r = rows.get(i);
if (!r.selected)
r.setSelected(true);
}
lastSelection = index;
} else
if (setSelected(!selected))
lastSelection = index;
else
lastSelection = -1;
} else
if (setSelected(!selected))
lastSelection = index;
else
lastSelection = -1;
} else if (selected)
setSelection((T)null);
else
setSelection(Row.this.element);
fireSelection();
} else if (getSelection().size() < 2) {
setSelection(Row.this.element);
lastSelection = index;
}
}
}
public void mouseUp(MouseEvent e) {
panelRows.setFocus();
if (e.button == 1) {
if ((e.stateMask & SWT.CTRL) == 0 && getSelection().size() > 1) {
setSelection(Row.this.element);
lastSelection = rows.indexOf(Row.this);
}
} else if (e.button == 3) {
rightClick.fire(Row.this.element);
}
}
}, false);
UIControlUtil.recursiveKeyListener(_controls[0], keyListener);
addDragSupport(this);
return _controls;
}
public Control[] getControls() { return _controls; }
T element;
Control[] _controls = null;
boolean selected = false;
int height = 0;
private Control createControl(Column col, int index) {
if (col.provider instanceof ColumnProviderText)
return createCompositeText((ColumnProviderText<T>)col.provider, element);
return ((ColumnProviderControl<T>)col.provider).getControl(panelRows, element);
}
void update() {
if (_controls == null) return;
for (int i = 0; i < columns.size(); ++i) {
ColumnProvider<T> provider = columns.get(i).provider;
if (provider instanceof ColumnProviderText)
updateText(_controls[i], (ColumnProviderText<T>)provider, element);
}
}
void remove() {
if (_controls != null)
for (Control c : _controls)
dispose(c);
_controls = null;
}
boolean setSelected(boolean value) {
if (selected == value) return false;
selected = value;
if (_controls != null) {
_controls[0].setBackground(selected ? ColorUtil.get(192, 192, 255) : panelRows.getBackground());
RectangleInt r = ondemand.getBounds(this, 0);
panelRows.redraw(r.x-HORIZ_SPACE, r.y-VERT_SPACE, r.width+2*HORIZ_SPACE, r.height+2*VERT_SPACE, false);
}
return true;
}
void columnAdded(Column c, boolean deferResize, boolean deferUpdate) {
if (_controls != null) {
Control[] newControls = new Control[_controls.length+1];
System.arraycopy(_controls, 0, newControls, 0, _controls.length);
_controls = newControls;
_controls[_controls.length-1] = createControl(c, _controls.length-1);
}
layout.rowColumnsUpdated(this, deferResize, deferUpdate);
}
void columnRemoved(int index, boolean deferResize, boolean deferUpdate) {
ondemand.remove(this);
if (_controls != null) {
Control[] newControls = new Control[_controls.length-1];
for (int i = 0; i < _controls.length; ++i) {
if (i == index) {
dispose(_controls[i]);
continue;
}
newControls[i-(i>index?1:0)] = _controls[i];
}
_controls = newControls;
}
layout.rowColumnsUpdated(this, deferResize, deferUpdate);
}
}
private List<KeyListener> keyListeners = new LinkedList<KeyListener>();
private KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == 'a' || e.keyCode == 'A') {
if ((e.stateMask & SWT.CTRL) != 0) {
selectAll();
e.doit = false;
}
} else if (e.keyCode == SWT.ARROW_DOWN && rows.size() > 0) {
List<Row> sel = getSelectedRows();
if (sel == null || sel.size() == 0) {
setSelection(rows.get(0).element);
makeVisible(0);
e.doit = false;
} else {
Row r = sel.get(0);
int i = rows.indexOf(r);
if (i < rows.size() - 1) {
setSelection(rows.get(i+1).element);
makeVisible(i+1);
e.doit = false;
}
}
} else if (e.keyCode == SWT.ARROW_UP && rows.size() > 0) {
List<Row> sel = getSelectedRows();
if (sel == null || sel.size() == 0) {
setSelection(rows.get(0).element);
makeVisible(0);
e.doit = false;
} else {
Row r = sel.get(0);
int i = rows.indexOf(r);
if (i > 0) {
setSelection(rows.get(i-1).element);
makeVisible(i-1);
e.doit = false;
}
}
}
if (e.doit)
for (KeyListener listener : keyListeners)
listener.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
for (KeyListener listener : keyListeners)
listener.keyReleased(e);
}
};
public void addKeyListener(KeyListener listener) {
if (keyListeners.contains(listener)) return;
keyListeners.add(listener);
}
private Event<List<T>> selectionChanged = new Event<List<T>>();
private Event<T> doubleClick = new Event<T>();
private Event<T> rightClick = new Event<T>();
public void addSelectionChangedListener(Listener<List<T>> listener) { selectionChanged.addListener(listener); }
public void addDoubleClickListener(Listener<T> listener) { doubleClick.addListener(listener); }
public void addRightClickListener(Listener<T> listener) { rightClick.addListener(listener); }
private List<Event<T>> addElementEvents = new LinkedList<Event<T>>();
private Listener<T> addElementListener = new Listener<T>() { public void fire(T element) { UIUtil.execAsync(panelRows, new RunnableWithData<T>(element) { public void run() { add(data()); }}); } };
private List<Event<T>> removeElementEvents = new LinkedList<Event<T>>();
private Listener<T> removeElementListener = new Listener<T>() { public void fire(T element) { UIUtil.execAsync(panelRows, new RunnableWithData<T>(element) { public void run() { remove(data()); }}); } };
private List<Event<T>> elementChangedEvents = new LinkedList<Event<T>>();
private Listener<T> elementChangedListener = new Listener<T>() { public void fire(T element) { Row i = getRow(element); if (i != null) UIUtil.execAsync(panelRows, new RunnableWithData<Row>(i) { public void run() { updateRow(data(), false, false); }}); } };
private List<Event<?>> contentChangedEvents = new LinkedList<Event<?>>();
private Runnable contentChangedListener = new Runnable() { public void run() { refresh(true); } };
public void addAddElementEvent(Event<T> event) {
addElementEvents.add(event);
event.addListener(addElementListener);
}
public void addRemoveElementEvent(Event<T> event) {
removeElementEvents.add(event);
event.addListener(removeElementListener);
}
public void addElementChangedEvent(Event<T> event) {
elementChangedEvents.add(event);
event.addListener(elementChangedListener);
}
public void addContentChangedEvent(Event<?> event) {
contentChangedEvents.add(event);
event.addFireListener(contentChangedListener);
}
private List<Triple<Integer,Transfer[],DragListener<T>>> drags = new LinkedList<Triple<Integer,Transfer[],DragListener<T>>>();
public void addDragSupport(int style, Transfer[] transfers, DragListener<T> listener) {
drags.add(new Triple<Integer,Transfer[],DragListener<T>>(style, transfers, listener));
for (Row r : rows)
addDragSupport(r, style, transfers, listener);
}
private void addDragSupport(Row r) {
for (Triple<Integer,Transfer[],DragListener<T>> t : drags)
addDragSupport(r, t.getValue1(), t.getValue2(), t.getValue3());
}
private void addDragSupport(Row r, int style, Transfer[] transfers, DragListener<T> listener) {
addDragSupport(r._controls[0], style, transfers, listener);
}
private Map<Control, DragSource> dragSources = new HashMap<Control, DragSource>();
private void addDragSupport(Control c, int style, Transfer[] transfers, DragListener<T> listener) {
DragSource drag = new DragSource(c, style);
dragSources.put(c, drag);
drag.setTransfer(transfers);
drag.addDragListener(new DragSourceListenerWithData<DragListener<T>>(listener) {
public void dragStart(DragSourceEvent event) {
data().dragStart(event, getSelection());
}
public void dragSetData(DragSourceEvent event) {
data().dragSetData(event, getSelection());
}
public void dragFinished(DragSourceEvent event) {
data().dragFinished(event, getSelection());
}
});
if (c instanceof Composite)
for (Control child : ((Composite)c).getChildren())
addDragSupport(child, style, transfers, listener);
}
private void disposeDrag(Control c) {
DragSource src = dragSources.remove(c);
if (src != null)
src.dispose();
if (c instanceof Composite)
for (Control child : ((Composite)c).getChildren())
disposeDrag(child);
}
private List<DropTarget> drops = new LinkedList<DropTarget>();
public void addDropSupport(int style, Transfer[] transfers, DropTargetListener listener) {
DropTarget target = new DropTarget(panel, style);
target.setTransfer(transfers);
target.addDropListener(listener);
drops.add(target);
}
public void add(T element) {
createRow(element, false, false);
}
public void add(List<T> elements) {
for (T element : elements)
createRow(element, true, true);
panelRows.setSize(panelRowsSize);
layout.updateOnDemand();
}
public boolean remove(T element) {
Row i = getRow(element);
if (i == null) return false;
boolean selected = i.selected;
removeRow(i, false, false);
if (selected) fireSelection();
return true;
}
public void clear() {
for (T e : new ArrayList<T>(getElements()))
remove(e);
}
public void addColumn(ColumnProvider<T> provider) {
Column c = new Column(provider);
columns.add(c);
GridLayout l = (GridLayout)contentPanel.getLayout();
l.numColumns++;
c.header = new ColumnHeader(contentPanel, c);
c.header.moveBelow(contentPanel.getChildren()[l.numColumns-1-1]);
GridData gd = (GridData)scrollRows.getLayoutData();
gd.horizontalSpan++;
if (panelRowsSize != null) {
panelRowsSize.x += c.width + HORIZ_SPACE;
}
for (Row r : rows)
r.columnAdded(c, false, false);
if (panelRowsSize != null)
panelRows.setSize(panelRowsSize);
contentPanel.layout(true, true);
UIControlUtil.resize(contentPanel);
layout.updateOnDemand();
}
public void removeColumn(ColumnProvider<T> provider) {
Column col = null;
int index;
for (index = 0; index < columns.size(); ++index) {
Column c = columns.get(index);
if (c.provider == provider) { col = c; break; }
}
if (col == null) return;
columns.remove(col);
col.header.dispose();
GridLayout l = (GridLayout)contentPanel.getLayout();
l.numColumns--;
GridData gd = (GridData)scrollRows.getLayoutData();
gd.horizontalSpan--;
if (panelRowsSize != null) {
panelRowsSize.x -= col.width + HORIZ_SPACE;
}
for (Row r : rows)
r.columnRemoved(index, false, false);
if (panelRowsSize != null)
panelRows.setSize(panelRowsSize);
contentPanel.layout(true, true);
UIControlUtil.resize(contentPanel);
layout.updateOnDemand();
}
private MyBoolean isRefreshing = new MyBoolean(false);
private boolean needNewRefresh = false;
private boolean newRefreshBackground = false;
private LinkedList<T> backgroundAdd = new LinkedList<T>();
public void refresh(boolean background) {
refresh(background, contentProvider.getElements());
}
public void setContent(Iterable<T> elements, boolean background) {
refresh(background, elements);
}
private void refresh(boolean background, Iterable<T> elements) {
synchronized (isRefreshing) {
if (panel.isDisposed()) return;
if (isRefreshing.get()) {
needNewRefresh = true;
newRefreshBackground = background;
return;
}
isRefreshing.set(true);
}
try {
backgroundAdd.clear();
ArrayList<Row> list = new ArrayList<Row>(rows);
LinkedList<Row> toUpdate = new LinkedList<Row>();
for (T element : elements) {
if (element == null) continue;
Row item = null;
for (Iterator<Row> it = list.iterator(); it.hasNext(); ) {
Row i = it.next();
if (i.element.equals(element)) {
item = i;
it.remove();
break;
}
}
if (item == null)
backgroundAdd.add(element);
else
toUpdate.add(item);
}
boolean selChanged = false;
for (Row i : list)
if (getSelectedRows().contains(i)) { selChanged = true; break; }
if (!list.isEmpty())
removeRows(list, true, true);
if (selChanged)
fireSelection();
if (background) {
if (panelRowsSize != null)
panelRows.setSize(panelRowsSize);
layout.updateOnDemand();
panel.getDisplay().asyncExec(new RunnableWithData<Pair<LinkedList<T>,LinkedList<Row>>>(new Pair<LinkedList<T>,LinkedList<Row>>(backgroundAdd,toUpdate)) {
public void run() {
try {
if (panel == null || panel.isDisposed()) {
endRefresh();
return;
}
UIUtil.runPendingEvents(panel.getDisplay());
if (panel.isDisposed()) {
endRefresh();
return;
}
if (!data().getValue2().isEmpty()) {
for (int i = 0; i < 10 && !data().getValue2().isEmpty(); ++i)
updateRow(data().getValue2().removeFirst(), true, true);
panelRows.setSize(panelRowsSize);
layout.updateOnDemand();
} else {
for (int i = 0; i < 10 && !data().getValue1().isEmpty(); ++i)
createRow(data().getValue1().removeFirst(), true, true);
panelRows.setSize(panelRowsSize);
layout.updateOnDemand();
}
if (!needNewRefresh && (!data().getValue2().isEmpty() || !data().getValue1().isEmpty()))
panel.getDisplay().asyncExec(this);
else
endRefresh();
} catch (Throwable t) {
if (Log.error(this))
Log.error(this, "Error while updating table", t);
endRefresh();
}
}
});
} else {
for (Row item : toUpdate)
updateRow(item, true, true);
for (T element : backgroundAdd)
createRow(element, true, true);
if (panelRowsSize != null)
panelRows.setSize(panelRowsSize);
layout.updateOnDemand();
endRefresh();
}
} catch (Throwable t) {
if (Log.error(this))
Log.error(this, "Error while updating table", t);
endRefresh();
}
}
private void endRefresh() {
synchronized (isRefreshing) {
isRefreshing.set(false);
}
if (needNewRefresh) {
needNewRefresh = false;
refresh(newRefreshBackground);
}
}
public void refresh(T element) {
Row i = getRow(element);
if (i != null)
updateRow(i, false, false);
}
public void resizeColumn(int colIndex, int width) {
if (colIndex >= columns.size()) return;
int diff = width - columns.get(colIndex).width;
columns.get(colIndex).width = width;
layout.columnResized(colIndex, diff, false, false);
}
private void createRow(T element, boolean deferResize, boolean deferUpdate) {
Row row = new Row(element);
int index = getIndexToInsert(element);
layout.rowAdded(row, deferResize, deferUpdate);
if (index != rows.size())
layout.rowMoved(row, rows.size(), index, deferUpdate);
rows.add(index, row);
}
private void updateRow(Row row, boolean deferResize, boolean deferUpdate) {
row.update();
layout.rowUpdated(row, deferResize, deferUpdate);
int current = rows.indexOf(row);
int index = getSortIndex(row, current);
if (current != index)
moveRow(row, current, index, deferUpdate);
}
private void removeRow(Row r, boolean deferResize, boolean deferUpdate) {
layout.rowRemoved(r, deferResize, deferUpdate);
rows.remove(r);
r.remove();
}
private void removeRows(List<Row> list, boolean deferResize, boolean deferUpdate) {
layout.rowsRemoved(list, deferResize, deferUpdate);
rows.removeAll(list);
for (Row r : list)
r.remove();
}
private void moveRow(Row r, int srcIndex, int dstIndex, boolean deferUpdate) {
layout.rowMoved(r, srcIndex, dstIndex, deferUpdate);
rows.remove(srcIndex);
if (dstIndex >= rows.size())
rows.add(r);
else
rows.add(dstIndex, r);
panelRows.redraw();
}
private Row getRow(T element) {
for (Row r : rows)
if (r.element == element)
return r;
return null;
}
private int getIndexToInsert(T element) {
if (!config.sortable) return rows.size();
Column sortCol = null;
for (Column col : columns)
if (col.sort != 0) {
sortCol = col;
break;
}
if (sortCol == null) return rows.size();
int i = 0;
for (Row r : rows) {
int cmp = compare(sortCol.provider, element, r.element);
if (cmp <= 0 && sortCol.sort < 0)
return i;
if (cmp >= 0 && sortCol.sort > 0)
return i;
i++;
}
return i;
}
private int getSortIndex(Row row, int current) {
if (!config.sortable) return rows.indexOf(row);
Column sortCol = null;
for (Column col : columns)
if (col.sort != 0) {
sortCol = col;
break;
}
if (sortCol == null) return current;
int i = 0;
for (Row r : rows) {
if (r == row) continue;
int cmp = compare(sortCol.provider, row.element, r.element);
if (cmp <= 0 && sortCol.sort < 0)
return i;
if (cmp >= 0 && sortCol.sort > 0)
return i;
i++;
}
return i;
}
private int compare(ColumnProvider<T> provider, T e1, T e2) {
if (provider instanceof ColumnProviderText) {
ColumnProviderText<T> p = (ColumnProviderText<T>)provider;
return p.compare(e1, p.getText(e1), e2, p.getText(e2));
} else if (provider instanceof ColumnProviderControl) {
ColumnProviderControl<T> p = (ColumnProviderControl<T>)provider;
return p.compare(e1, e2);
}
return 0;
}
private void sort(Column col) {
LinkedList<Row> sorted = new LinkedList<Row>();
for (Row r : rows)
sort(col, r, sorted, 0, sorted.size()-1);
rows = sorted;
}
private void sort(Column col, Row r, List<Row> list, int min, int max) {
if (max < min) { list.add(min, r); return; }
if (min > max) { list.add(max+1, r); return; }
int pivot = (max-min)/2 + min;
int cmp = compare(col.provider, r.element, list.get(pivot).element);
if (col.sort > 0) cmp = -cmp;
if (cmp == 0) { list.add(pivot, r); return; }
if (cmp < 0)
sort(col, r, list, min, pivot-1);
else
sort(col, r, list, pivot+1, max);
}
private List<Row> getSelectedRows() {
List<Row> result = new LinkedList<Row>();
for (Row r : rows)
if (r.selected)
result.add(r);
return result;
}
public List<T> getSelection() {
List<T> result = new LinkedList<T>();
for (Row r : rows)
if (r.selected)
result.add(r.element);
return result;
}
public void setSelection(List<T> list) {
boolean changed = false;
for (Row r : rows)
changed |= r.setSelected(list.contains(r.element));
if (changed) fireSelection();
}
public void setSelection(T element) {
boolean changed = false;
for (Row r : rows)
changed |= r.setSelected(r.element == element);
if (changed) fireSelection();
}
public void selectAll() {
if (!config.multiSelection) return;
boolean changed = false;
for (Row r : rows)
changed |= r.setSelected(true);
if (changed) fireSelection();
}
private void fireSelection() {
selectionChanged.fire(getSelection());
}
public List<T> removeSelected() {
List<T> sel = getSelection();
removeRows(getSelectedRows(), false, false);
return sel;
}
public int indexOf(T element) {
int i = 0;
for (Row r : rows) {
if (r.element == element) return i;
i++;
}
return -1;
}
public List<T> getElements() {
List<T> result = new ArrayList<T>(rows.size());
for (Row r : rows)
result.add(r.element);
for (T element : new ArrayList<T>(backgroundAdd))
result.add(element);
return result;
}
public boolean move(T element, int index) {
int i = 0;
Row row = null;
for (Row r : rows) {
if (r.element == element) {
row = r;
break;
} else
i++;
}
if (row == null) return false;
if (i == index) return true;
moveRow(row, i, index, false);
return true;
}
public void makeVisible(int rowIndex) {
if (rowIndex >= rows.size()) return;
int y = VERT_SPACE;
int i = 0;
int startY = 0, endY = 0;
for (Row r : rows) {
if (i == rowIndex) {
startY = y;
endY = y+r.height;
break;
}
y += r.height + VERT_SPACE;
i++;
}
if (startY < panelRowsScrolled) {
verticalBar.setSelection(startY);
verticalScrollChanged();
} else if (endY > panelRowsScrolled + scrollRowsSize.y) {
verticalBar.setSelection(endY-scrollRowsSize.y);
verticalScrollChanged();
}
}
private Point panelRowsSize = null;
private int panelRowsScrolled = 0;
private Point scrollRowsSize = null;
private void refreshScrollRowsSize() {
scrollRowsSize = scrollRows.getSize();
verticalBar.setPageIncrement(scrollRowsSize.y);
if (panelRowsSize != null)
refreshVerticalBar();
layout.updateOnDemand();
}
private void refreshVerticalBar() {
int h = panelRowsSize.y;
int vh = scrollRowsSize.y;
int ecart = h - vh;
if (ecart < 0) ecart = 1;
verticalBar.setMaximum(ecart);
if (ecart < panelRowsScrolled)
verticalScrollChanged();
}
private void verticalScrollChanged() {
int vb = verticalBar.getSelection();
if (panelRowsScrolled != vb) {
panelRows.setLocation(0, -vb);
panelRowsScrolled = vb;
layout.updateOnDemand();
}
}
private static int COLUMN_HEADER_HEIGHT = 25;
private class ColumnHeader extends Canvas implements PaintListener, MouseListener {
public ColumnHeader(Composite parent, Column col) {
super(parent, SWT.NO_BACKGROUND);
this.col = col;
addPaintListener(this);
resizer.register(this);
addMouseListener(this);
}
Column col;
public void paintControl(PaintEvent e) {
Point size = ((Control)e.widget).getSize();
// e.gc.setBackgroundPattern(new Pattern(e.display, 0, 0, 0, size.y/2, ColorUtil.get(192, 192, 255), ColorUtil.get(240, 240, 255)));
// e.gc.fillRectangle(0, 0, size.x, size.y/2);
// e.gc.setBackgroundPattern(new Pattern(e.display, 0, size.y/2, 0, size.y, ColorUtil.get(240, 240, 255), ColorUtil.get(192, 192, 255)));
// e.gc.fillRectangle(0, size.y/2, size.x, size.y/2);
int y1 = size.y/3;
e.gc.setBackgroundPattern(new Pattern(e.display, 0, 0, 0, y1, ColorUtil.get(230, 230, 255), ColorUtil.get(210, 210, 255)));
e.gc.fillRectangle(0, 0, size.x, y1);
e.gc.setBackgroundPattern(new Pattern(e.display, 0, y1, 0, size.y, ColorUtil.get(192, 192, 255), ColorUtil.get(240, 240, 255)));
e.gc.fillRectangle(0, y1, size.x, size.y-y1);
int x, y;
int align = col.provider.getAlignment();
String title = col.provider.getTitle();
Point tsize = e.gc.textExtent(title);
List<Font> fonts = new LinkedList<Font>();
Font initialFont = e.gc.getFont();
while (tsize.x > size.x+4 && e.gc.getFont().getFontData()[0].height > 5) {
Font font = UIUtil.increaseFontSize(e.gc.getFont(), -1);
fonts.add(font);
e.gc.setFont(font);
tsize = e.gc.textExtent(title);
}
y = size.y - tsize.y - 2;
if (align == SWT.CENTER)
x = size.x/2 - tsize.x/2;
else if (align == SWT.RIGHT)
x = size.x - 2 - tsize.x;
else
x = 2;
e.gc.drawText(title, x, y, true);
e.gc.setForeground(ColorUtil.get(150, 150, 150));
e.gc.drawLine(0, size.y-1, size.x-1, size.y-1);
if (col.sort < 0) {
e.gc.setForeground(ColorUtil.get(100, 100, 200));
e.gc.drawPoint(size.x/2, 2);
e.gc.drawLine(size.x/2-1, 3, size.x/2+1, 3);
e.gc.drawLine(size.x/2-2, 4, size.x/2+2, 4);
} else if (col.sort > 0) {
e.gc.setForeground(ColorUtil.get(100, 100, 200));
e.gc.drawLine(size.x/2-2, 2, size.x/2+2, 2);
e.gc.drawLine(size.x/2-1, 3, size.x/2+1, 3);
e.gc.drawPoint(size.x/2, 4);
}
e.gc.setFont(initialFont);
for (Font f : fonts) f.dispose();
}
public void mouseDoubleClick(MouseEvent e) {
}
public void mouseDown(MouseEvent e) {
}
public void mouseUp(MouseEvent e) {
if (!config.sortable) return;
if (resizer.isResizing) return;
if (col.sort < 0)
col.sort = 1;
else if (col.sort > 0)
col.sort = -1;
else {
for (Column c : columns) {
if (c.sort != 0) {
c.sort = 0;
c.header.redraw();
break;
}
}
col.sort = -1;
}
redraw();
sort(col);
layout.refreshAll();
}
@Override
public Point computeSize(int hint, int hint2, boolean changed) {
return new Point(col.width, COLUMN_HEADER_HEIGHT);
}
}
private static int HORIZ_SPACE = 1;
private static int VERT_SPACE = 1;
private class RowsPainter implements PaintListener {
public void paintControl(PaintEvent e) {
int y = 0;
for (Row r : rows) {
if (y+r.height+1 >= e.y) {
if (r.selected) {
int w = columns.get(0).width+1;
e.gc.setForeground(ColorUtil.get(128, 128, 255));
e.gc.drawLine(0, y+1, 0, y+r.height);
e.gc.drawLine(1, y, w-1, y);
e.gc.drawLine(1, y+r.height+1, w-1, y+r.height+1);
e.gc.drawLine(w, y+1, w, y+r.height);
e.gc.setForeground(ColorUtil.get(200, 200, 255));
e.gc.drawPoint(0, y);
e.gc.drawPoint(0, y+r.height+1);
e.gc.drawPoint(w, y);
e.gc.drawPoint(w, y+r.height+1);
//e.gc.drawRectangle(0, y, w, r.height+1);
}
}
y += r.height + VERT_SPACE;
if (y > e.y + e.height - 1) break;
}
// Point size = panelRowsSize;
// if (size == null) return;
// e.gc.setForeground(ColorUtil.get(200, 200, 255));
// int y = 0;
// for (Row r : rows) {
// e.gc.drawLine(0, y, size.x, y);
// y += r.height+1;
// }
// int x = 0;
// for (Column c : columns) {
// if (x > 0)
// e.gc.drawLine(x-1, 0, x-1, size.y);
// x += c.width+1;
// }
// e.gc.drawLine(x-1, 0, x-1, size.y);
}
}
private class TableLayout extends Layout {
@Override
protected Point computeSize(Composite composite, int hint, int hint2, boolean flushCache) {
// int y = 1;
// for (Row r : rows) {
// int h = 0;
// if (flushCache) {
// for (int i = 0; i < columns.size(); ++i) {
// Point size = r.controls[i].computeSize(columns.get(i).width, SWT.DEFAULT);
// if (size.y > h)
// h = size.y;
// }
// } else
// h = r.height;
// y += h+1;
// }
// int w = 0;
// for (int i = 0; i < columns.size(); ++i)
// w += columns.get(i).width + 1;
// w--;
// return new Point(w, y);
return new Point(100,100);
}
@Override
protected void layout(Composite composite, boolean flushCache) {
}
private void refreshAll() {
int y = VERT_SPACE;
for (Row r : rows) {
int h;
if (config.fixedRowHeight <= 0) {
h = 0;
Point[] sizes = new Point[columns.size()];
Control[] controls = r.getControls();
if (controls == null) controls = r.createControls();
for (int i = 0; i < columns.size(); ++i) {
sizes[i] = controls[i].computeSize(columns.get(i).width, SWT.DEFAULT);
if (sizes[i].y > h)
h = sizes[i].y;
}
} else
h = config.fixedRowHeight;
r.height = h;
int x = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i) {
// int ecart = h-sizes[i].y;
// r.controls[i].setBounds(x, y+ecart/2, columns.get(i).width, sizes[i].y);
ondemand.setBounds(r, i, x, y, columns.get(i).width, h);
//r.controls[i].setBounds(x, y, columns.get(i).width, h);
x += columns.get(i).width + HORIZ_SPACE;
}
y += h+VERT_SPACE;
}
int w = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i)
w += columns.get(i).width + HORIZ_SPACE;
w-=HORIZ_SPACE;
panelRowsSize = new Point(w, y);
panelRows.setSize(panelRowsSize);
updateOnDemand();
}
void rowAdded(Row r, boolean deferResize, boolean deferUpdate) {
if (panelRowsSize == null) return;
int h;
if (config.fixedRowHeight <= 0) {
h = 0;
Point[] sizes = new Point[columns.size()];
Control[] controls = r.getControls();
if (controls == null) controls = r.createControls();
for (int i = 0; i < columns.size(); ++i) {
sizes[i] = controls[i].computeSize(columns.get(i).width, SWT.DEFAULT);
if (sizes[i].y > h)
h = sizes[i].y;
}
} else
h = config.fixedRowHeight;
r.height = h;
int x = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i) {
// int ecart = h-sizes[i].y;
// r.controls[i].setBounds(x, size.y+ecart/2, columns.get(i).width, sizes[i].y);
ondemand.setBounds(r, i, x, panelRowsSize.y, columns.get(i).width, h);
// r.controls[i].setBounds(x, panelRowsSize.y, columns.get(i).width, h);
x += columns.get(i).width + HORIZ_SPACE;
}
panelRowsSize.y += h+VERT_SPACE;
if (!deferResize)
panelRows.setSize(panelRowsSize);
if (!deferUpdate)
updateOnDemand();
}
void rowUpdated(Row r, boolean deferResize, boolean deferUpdate) {
if (config.fixedRowHeight > 0) return;
int h = 0;
Point[] sizes = new Point[columns.size()];
Control[] controls = r.getControls();
if (controls == null) controls = r.createControls();
for (int i = 0; i < columns.size(); ++i) {
sizes[i] = controls[i].computeSize(columns.get(i).width, SWT.DEFAULT);
if (sizes[i].y > h)
h = sizes[i].y;
}
if (r.height == h) return;
int y = VERT_SPACE;
Iterator<Row> it;
for (it = rows.iterator(); it.hasNext(); ) {
Row rr = it.next();
if (rr == r) break;
y += rr.height+VERT_SPACE;
}
int diff = h - r.height;
r.height = h;
int x = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i) {
// int ecart = h-sizes[i].y;
// r.controls[i].setBounds(x, y+ecart/2, columns.get(i).width, sizes[i].y);
ondemand.setBounds(r, i, x, y, columns.get(i).width, h);
// r.controls[i].setBounds(x, y, columns.get(i).width, h);
x += columns.get(i).width + HORIZ_SPACE;
}
while (it.hasNext()) {
Row rr = it.next();
for (int i = 0; i < columns.size(); ++i) {
PointInt loc = ondemand.getLocation(rr, i);
ondemand.setLocation(rr, i, loc.x, loc.y + diff);
// Point loc = rr.controls[i].getLocation();
// rr.controls[i].setLocation(loc.x, loc.y + diff);
}
}
panelRowsSize.y += diff;
if (!deferResize)
panelRows.setSize(panelRowsSize);
if (!deferUpdate)
updateOnDemand();
}
void rowMoved(Row r, int srcIndex, int dstIndex, boolean deferUpdate) {
int y = VERT_SPACE;
Iterator<Row> it;
int index = 0;
// go to the first row where change is needed
int startIndex = Math.min(srcIndex, dstIndex);
for (it = rows.iterator(); index < startIndex && it.hasNext(); ++index) {
Row rr = it.next();
y += rr.height+VERT_SPACE;
}
// if we are at the destination, we put the row
if (index == dstIndex) {
int x = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i) {
ondemand.setBounds(r, i, x, y, columns.get(i).width, r.height);
// r.controls[i].setBounds(x, y, columns.get(i).width, r.height);
x += columns.get(i).width + HORIZ_SPACE;
}
y += r.height+VERT_SPACE;
} else {
it.next();
}
// update until the last row where change is needed
startIndex = Math.max(srcIndex, dstIndex);
for (; index < startIndex && it.hasNext(); ++index) {
Row rr = it.next();
int x = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i) {
ondemand.setLocation(rr, i, x, y);
// rr.controls[i].setLocation(x, y);
x += columns.get(i).width + HORIZ_SPACE;
}
y += rr.height+VERT_SPACE;
}
// if we are at the destination, we put the row
if (index == dstIndex) {
int x = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i) {
ondemand.setBounds(r, i, x, y, columns.get(i).width, r.height);
// r.controls[i].setBounds(x, y, columns.get(i).width, r.height);
x += columns.get(i).width + HORIZ_SPACE;
}
y += r.height+VERT_SPACE;
}
if (!deferUpdate)
updateOnDemand();
}
void rowRemoved(Row r, boolean deferResize, boolean deferUpdate) {
Iterator<Row> it;
for (it = rows.iterator(); it.hasNext(); ) {
Row rr = it.next();
if (rr == r) break;
}
while (it.hasNext()) {
Row rr = it.next();
for (int i = 0; i < columns.size(); ++i) {
PointInt loc = ondemand.getLocation(rr, i);
ondemand.setLocation(rr, i, loc.x, loc.y - r.height - 1);
// Point loc = rr.controls[i].getLocation();
// rr.controls[i].setLocation(loc.x, loc.y - r.height - 1);
}
}
panelRowsSize.y -= r.height+VERT_SPACE;
if (!deferResize)
panelRows.setSize(panelRowsSize);
if (!deferUpdate)
updateOnDemand();
}
void rowsRemoved(List<Row> list, boolean deferResize, boolean deferUpdate) {
Iterator<Row> it;
int diff = 0;
for (it = rows.iterator(); it.hasNext(); ) {
Row r = it.next();
if (list.contains(r)) {
diff -= r.height+VERT_SPACE;
} else {
if (diff != 0)
for (int i = 0; i < columns.size(); ++i) {
PointInt loc = ondemand.getLocation(r, i);
ondemand.setLocation(r, i, loc.x, loc.y + diff);
// Point loc = r.controls[i].getLocation();
// r.controls[i].setLocation(loc.x, loc.y + diff);
}
}
}
panelRowsSize.y += diff;
if (!deferResize)
panelRows.setSize(panelRowsSize);
if (!deferUpdate)
updateOnDemand();
}
void rowColumnsUpdated(Row r, boolean deferResize, boolean deferUpdate) {
int h;
if (config.fixedRowHeight > 0) {
h = config.fixedRowHeight;
} else {
h = 0;
Point[] sizes = new Point[columns.size()];
Control[] controls = r.getControls();
if (controls == null) controls = r.createControls();
for (int i = 0; i < columns.size(); ++i) {
sizes[i] = controls[i].computeSize(columns.get(i).width, SWT.DEFAULT);
if (sizes[i].y > h)
h = sizes[i].y;
}
}
int y = VERT_SPACE;
Iterator<Row> it;
for (it = rows.iterator(); it.hasNext(); ) {
Row rr = it.next();
if (rr == r) break;
y += rr.height+VERT_SPACE;
}
if (r.height != h) {
int diff = h - r.height;
r.height = h;
int x = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i) {
// int ecart = h-sizes[i].y;
// r.controls[i].setBounds(x, y+ecart/2, columns.get(i).width, sizes[i].y);
ondemand.setBounds(r, i, x, y, columns.get(i).width, h);
// r.controls[i].setBounds(x, y, columns.get(i).width, h);
x += columns.get(i).width + HORIZ_SPACE;
}
while (it.hasNext()) {
Row rr = it.next();
for (int i = 0; i < columns.size(); ++i) {
PointInt loc = ondemand.getLocation(rr, i);
ondemand.setLocation(rr, i, loc.x, loc.y + diff);
// Point loc = rr.controls[i].getLocation();
// rr.controls[i].setLocation(loc.x, loc.y + diff);
}
}
panelRowsSize.y += diff;
} else {
int x = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i) {
ondemand.setBounds(r, i, x, y, columns.get(i).width, h);
x += columns.get(i).width + HORIZ_SPACE;
}
}
if (!deferResize)
panelRows.setSize(panelRowsSize);
if (!deferUpdate)
updateOnDemand();
}
void columnResized(int colIndex, int diff, boolean deferResize, boolean deferUpdate) {
if (diff == 0) return;
Composite p = columns.get(colIndex).header.getParent();
p.layout(true, false);
UIControlUtil.resize(p);
int y = VERT_SPACE;
for (Row r : rows) {
int x = HORIZ_SPACE;
for (int i = 0; i < columns.size(); ++i) {
int w = columns.get(i).width;
if (i >= colIndex) {
ondemand.setBounds(r, i, x, y, w, r.height);
// r.controls[i].setBounds(x, y, w, r.height);
}
x += w + HORIZ_SPACE;
}
y += r.height + VERT_SPACE;
}
panelRowsSize.x += diff;
if (!deferResize)
panelRows.setSize(panelRowsSize);
if (!deferUpdate)
updateOnDemand();
}
void updateOnDemand() {
if (panelRowsSize != null)
ondemand.update(new RectangleInt(0, panelRowsScrolled, panelRowsSize.x, scrollRowsSize.y));
}
}
private static class CompositeText<T> extends Composite {
public CompositeText(Composite parent, ColumnProviderText<T> provider, T element) {
super(parent, SWT.NONE);
super.setBackground(parent.getBackground());
Image image = provider.getImage(element);
setLayout(layout = new MyLayout());
if (image != null)
this.image = UIUtil.newImage(this, image);
text = createTextLabel(this, provider, element);
text.setLayoutData(UIUtil.gridData(1, true, 1, true));
if (image != null) {
this.image.setLocation(0, 0);
this.image.setSize(16, 16);
text.setLocation(16, 0);
} else
text.setLocation(0, 0);
}
private MyLayout layout;
private Label image;
private Label text;
@Override
public void setBackground(Color color) {
image.setBackground(color);
text.setBackground(color);
super.setBackground(color);
}
@Override
public Point computeSize(int hint, int hint2, boolean changed) {
return layout.computeSize(this, hint, hint2, changed);
}
private class MyLayout extends Layout {
@Override
protected Point computeSize(Composite composite, int hint, int hint2, boolean flushCache) {
int x;
if (hint == SWT.DEFAULT) {
x = text.computeSize(SWT.DEFAULT, 16, flushCache).x;
if (image != null)
x += 16;
} else
x = hint;
return new Point(x, 16);
}
@Override
protected void layout(Composite composite, boolean flushCache) {
Point size = composite.getSize();
if (image != null)
size.x -= 16;
text.setSize(size);
}
}
}
private static <T> Label createTextLabel(Composite parent, ColumnProviderText<T> provider, T element) {
String text = provider.getText(element);
Label label = UIUtil.newLabel(parent, text);
label.setAlignment(provider.getAlignment());
label.setFont(provider.getFont(element));
//label.setToolTipText(text);
return label;
}
// private LinkedList<Label> labelBank = new LinkedList<Label>();
// private LinkedList<CompositeText<T>> compositeBank = new LinkedList<CompositeText<T>>();
private Control createCompositeText(ColumnProviderText<T> provider, T element) {
Image img = provider.getImage(element);
if (img == null) {
// if (labelBank.isEmpty())
return createTextLabel(panelRows, provider, element);
// Label label = labelBank.removeFirst();
// updateText(label, provider, element);
// label.setVisible(true);
// return label;
}
// if (compositeBank.isEmpty())
return new CompositeText<T>(panelRows, provider, element);
// CompositeText<T> c = compositeBank.removeFirst();
// updateText(c, provider, element);
// c.setVisible(true);
// return c;
}
// @SuppressWarnings("unchecked")
private void dispose(Control c) {
disposeDrag(c);
// if (c instanceof CompositeText) {
// c.setVisible(false);
// compositeBank.add((CompositeText<T>)c);
// } else if (c instanceof Label) {
// c.setVisible(false);
// labelBank.add((Label)c);
// } else
c.dispose();
}
@SuppressWarnings("unchecked")
private void updateText(Control c, ColumnProviderText<T> provider, T element) {
if (c instanceof CompositeText)
updateText((CompositeText<T>)c, provider, element);
else
updateText((Label)c, provider, element);
}
private void updateText(CompositeText<T> c, ColumnProviderText<T> provider, T element) {
c.image.setImage(provider.getImage(element));
updateText(c.text, provider, element);
}
private void updateText(Label label, ColumnProviderText<T> provider, T element) {
String text = provider.getText(element);
label.setText(text);
label.setAlignment(provider.getAlignment());
label.setFont(provider.getFont(element));
//label.setToolTipText(text);
}
private Resizer resizer = new Resizer();
private class Resizer {
void register(Control c) {
c.addMouseListener(mouse);
c.addMouseMoveListener(mouse);
c.addMouseTrackListener(mouse);
}
private static final int SIZE = 5;
Mouse mouse = new Mouse();
Cursor cursor = new Cursor(Display.getDefault(), SWT.CURSOR_SIZEWE);
Column colToResize = null;
boolean isResizing = false;
private class Mouse implements MouseListener, MouseTrackListener, MouseMoveListener {
public void mouseDoubleClick(MouseEvent e) {
Control c = ((Control)e.widget);
if (c instanceof Canvas) {
ColumnHeader header = (ColumnHeader)c;
int index = columns.indexOf(header.col);
int w = 0;
for (Row r : rows) {
Control[] controls = r.getControls();
if (controls == null) controls = r.createControls();
int x = controls[index].computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x;
if (x > w)
w = x;
}
if (w < 10) w = 10;
resizeColumn(index, w);
}
}
public void mouseDown(MouseEvent e) {
if (((Control)e.widget).getCursor() == cursor)
isResizing = true;
}
public void mouseUp(MouseEvent e) {
isResizing = false;
}
public void mouseEnter(MouseEvent e) {
}
public void mouseExit(MouseEvent e) {
((Control)e.widget).setCursor(null);
}
public void mouseHover(MouseEvent e) {
}
public void mouseMove(MouseEvent e) {
Control c = ((Control)e.widget);
if (isResizing) {
int x;
if (c instanceof Canvas)
x = c.getLocation().x + e.x;
else
x = e.x;
int px = HORIZ_SPACE;
int index = 0;
for (Column col: columns) {
if (col == colToResize)
break;
px += col.width + HORIZ_SPACE;
index++;
}
x -= px;
if (x < 10) x = 10;
resizeColumn(index, x);
return;
}
Cursor current = c.getCursor();
if (c instanceof Canvas) {
ColumnHeader header = (ColumnHeader)c;
boolean ok = false;
if (e.x < SIZE && header.col != columns.get(0)) {
if (current != cursor) {
c.setCursor(cursor);
colToResize = columns.get(columns.indexOf(header.col)-1);
}
ok = true;
} else if (e.x > header.col.width-SIZE) {
if (current != cursor) {
c.setCursor(cursor);
colToResize = header.col;
}
ok = true;
}
if (!ok && current == cursor)
c.setCursor(null);
} else {
boolean ok = false;
if (e.y <= COLUMN_HEADER_HEIGHT) {
int x = HORIZ_SPACE;
for (Column col : columns) {
if (e.x >= x + col.width - SIZE && e.x <= x + col.width + SIZE) {
if (current != cursor) {
c.setCursor(cursor);
colToResize = col;
}
ok = true;
break;
}
x += col.width + HORIZ_SPACE;
}
}
if (!ok && current == cursor)
c.setCursor(null);
}
}
}
}
}
| lecousin/net.lecousin.framework-0.1 | net.lecousin.framework.ui/src/net/lecousin/framework/ui/eclipse/control/list/LCTable.java | Java | gpl-3.0 | 54,511 |
/*
Copyright 2015 Philipp Adam, Manuel Caspari, Nicolas Lukaschek
contact@ravenapp.org
This file is part of Raven.
Raven is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Raven 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 Raven. If not, see <http://www.gnu.org/licenses/>.
*/
package safe;
import java.io.File;
public class KeySafePC extends KeySafeAbstract{
public KeySafePC(KeyEntity universal_key) {
super(null, universal_key);
}
@Override
public File fileLocation() {
String OS = (System.getProperty("os.name")).toUpperCase();
String workingDir = "";
if (OS.contains("WIN")){
workingDir = System.getenv("APPDATA")+"/";
}
else {
workingDir = System.getProperty("user.home")+"/.";
}
if(! new File(workingDir+"Raven").exists()) new File(workingDir+"Raven").mkdir();
return new File(workingDir+"Raven/keySafe.dat");
}
}
| manuelsc/Raven-Messenger | Raven Core/src/safe/KeySafePC.java | Java | gpl-3.0 | 1,309 |
module FileStorage
# Store and retrieve files from the local filesystem.
class LocalFile
# Creates a new LocalFile store.
# +path+ Specifies the directory in which to store files. If not specified,
# files will be stored in a random-named temporary directory.
# +tag+ Controls naming of temporary directories. If specified, temporary
# directory names will be prefixed with this.
def initialize(path: nil, tag: 'storage')
@directory = path
@tag = tag
@ensured = false
end
def directory
@directory ||= Dir.mktmpdir "web-monitoring-db--#{@tag}"
end
def get_metadata(path)
get_metadata!(path)
# FIXME: should have a more specific error class than ArgumentError here;
# we could catch errors we don't want to.
rescue Errno::ENOENT, ArgumentError
nil
end
def get_metadata!(path)
data = File.stat(normalize_full_path(path))
{
last_modified: data.mtime,
size: data.size,
content_type: nil
}
end
def get_file(path)
File.read(normalize_full_path(path))
end
def save_file(path, content, _options = nil)
ensure_directory
File.open(full_path(path), 'wb') do |file|
content_string = content.try(:read) || content
file.write(content_string)
end
end
def url_for_file(path)
"file://#{full_path(path)}"
end
def contains_url?(url_string)
get_metadata(url_string).present?
end
private
def full_path(path)
File.join(directory, path)
end
# Normalize a file URI or path to an absolute path to the file.
# If the path specifies a directory outside this storage area, this raises
# ArgumentError.
def normalize_full_path(path)
# If it's a file URL, extract the path
path = path[7..-1] if path.starts_with? 'file://'
# If it's absolute, make sure it's in this storage's directory
if path.starts_with?('/')
unless path.starts_with?(File.join(directory, ''))
# FIXME: raise a more specific error type!
raise ArgumentError, "The path '#{path}' does not belong to this storage object"
end
path
else
full_path(path)
end
end
def ensure_directory
unless @ensured
@ensured = true
FileUtils.mkdir_p directory
end
directory
end
end
end
| edgi-govdata-archiving/web-monitoring-db | lib/file_storage/local_file.rb | Ruby | gpl-3.0 | 2,429 |
/*
* Copyright (C) 2019 debian
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main.mochila.cuadratica.ConjuntoInstancias;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author debian
*/
public class ConjuntoInstancias300 extends ConjuntoInstancias {
public ConjuntoInstancias300() {
}
@Override
public List<GrupoInstancias> getInstancias() {
instancias = new ArrayList();
instancias.add(new GrupoInstancias("mochilaCuadratica/grupo1/", "jeu_300_25_%d.txt", 1, 20, "300_25")); //1-20
instancias.add(new GrupoInstancias("mochilaCuadratica/grupo1/", "jeu_300_50_%d.txt", 1, 20, "300_50")); //1-20
instancias.forEach((instancia) -> {
instancia.setConjunto(this);
});
return instancias;
}
@Override
public String getNombre() {
return "300";
}
}
| andersonbui/metaheuristicas | src/main/mochila/cuadratica/ConjuntoInstancias/ConjuntoInstancias300.java | Java | gpl-3.0 | 1,476 |
/*
* QuarkPlayer, a Phonon media player
* Copyright (C) 2008 Trolltech ASA. All rights reserved.
* Copyright (C) 2008 Benjamin C. Meyer <ben@meyerhome.net>
* Copyright (C) 2008-2009 Tanguy Krotoff <tkrotoff@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SqueezeLabel.h"
#include "TkUtilLogger.h"
SqueezeLabel::SqueezeLabel(QWidget * parent)
: QLabel(parent) {
}
SqueezeLabel::SqueezeLabel(const QString & text, QWidget * parent)
: QLabel(text, parent) {
}
QString SqueezeLabel::plainText() const {
QString tmp = text();
tmp.replace(QRegExp("<[^>]*>"), "");
return tmp;
}
void SqueezeLabel::paintEvent(QPaintEvent * event) {
//FIXME: here we have a graphical bug
//in case the font is bold or italic since we assume here
//the font is a regular one without these attributes
QFontMetrics fm = fontMetrics();
if (fm.width(plainText()) > contentsRect().width()) {
QString elided = fm.elidedText(plainText(), Qt::ElideMiddle, width());
QString oldText = text();
setText(elided);
QLabel::paintEvent(event);
setText(oldText);
} else {
QLabel::paintEvent(event);
}
}
QSize SqueezeLabel::minimumSizeHint() const {
QSize size = QLabel::minimumSizeHint();
size.setWidth(-1);
return size;
}
| tkrotoff/QuarkPlayer | libs/TkUtil/SqueezeLabel.cpp | C++ | gpl-3.0 | 1,868 |
#include "ThreadPool.h"
#include <vector>
#include <chrono>
#include <list>
#include <algorithm>
using namespace Game;
using namespace std;
FixedThreadPool::Task::~Task(){}
FixedThreadPool::FixedThreadPool(size_t max_thread_count) : threads_(max_thread_count), max_thread_count_(max_thread_count), state_(State::STOPPED), mutex_(), condition_(), tasks_(), scheduled_tasks_(){
}
FixedThreadPool::~FixedThreadPool(){
stop();
for(Task *task : scheduled_tasks_){
delete task;
}
}
bool FixedThreadPool::start() {
lock_guard<mutex> guard{mutex_};
if(state_ == State::STOPPED){
copy(scheduled_tasks_.begin(), scheduled_tasks_.end(), back_inserter(tasks_));
scheduled_tasks_.clear();
for(size_t i = 0; i < max_thread_count_; ++i){
threads_.emplace_back(&FixedThreadPool::perform_tasks, this);
}
state_ = State::RUNNING;
return true;
}else{
return false;
}
}
bool FixedThreadPool::running() const{
lock_guard<mutex> guard{mutex_};
return state_ == State::RUNNING;
}
FixedThreadPool::Task* FixedThreadPool::claim_task() {
unique_lock<mutex> lock{mutex_};
while(true){
if(state_ == State::RUNNING){
if(!tasks_.empty()){
Task *task = tasks_.front();
tasks_.pop_front();
return task;
}
condition_.wait(lock);
}else if(state_ == State::FINISHING){
if(tasks_.empty()){
return nullptr;
}else{
Task *task = tasks_.front();
tasks_.pop_front();
return task;
}
}else{
return nullptr;
}
}
}
void FixedThreadPool::perform_tasks(){
Task *task;
while((task = claim_task())){
try{
task->execute();
delete task;
}catch(...){
delete task;
throw;
}
}
}
bool FixedThreadPool::stop(){
return do_stop(State::STOPPING);
}
bool FixedThreadPool::finish_and_stop(){
return do_stop(State::FINISHING);
}
bool FixedThreadPool::do_stop(State stopping_state) {
unique_lock<mutex> lock{mutex_};
if(state_ == State::RUNNING){
thread waiting_thread{[&](){
for(auto i = threads_.begin(); i != threads_.end(); ++i){
if(i->joinable()){
i->join();
}
}
}};
state_ = stopping_state;
condition_.notify_all();
lock.unlock();
waiting_thread.join();
threads_.clear();
lock.lock();
copy(tasks_.begin(), tasks_.end(), front_inserter(scheduled_tasks_));
tasks_.clear();
state_ = State::STOPPED;
return true;
}else{
return false;
}
}
void FixedThreadPool::do_submit(Task* task){
lock_guard<mutex> guard{mutex_};
if(state_ == State::RUNNING){
tasks_.push_back(task);
condition_.notify_one();
}else{
scheduled_tasks_.push_back(task);
}
};
void FixedThreadPool::clear(){
lock_guard<mutex> guard{mutex_};
for(Task *task : tasks_){
delete task;
}
tasks_.clear();
};
| hansvanmoer/space-game | src/ThreadPool.cpp | C++ | gpl-3.0 | 3,287 |
package com.ragingart.miningmodifications.client.gui.container.machines;
import com.ragingart.miningmodifications.container.machines.ContainerWaterTurbine;
import com.ragingart.miningmodifications.ref.Reference;
import com.ragingart.miningmodifications.tileentity.machines.TileEntityWaterTurbine;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.ForgeDirection;
import org.lwjgl.opengl.GL11;
/**
* Created by XtraX on 07.10.2014.
*/
public class GuiWaterTurbine extends GuiContainer {
private TileEntityWaterTurbine tileEntityWaterTurbine;
public GuiWaterTurbine(InventoryPlayer invPlayer, TileEntity tileEntity){
super(new ContainerWaterTurbine(invPlayer, tileEntity));
this.tileEntityWaterTurbine = (TileEntityWaterTurbine)tileEntity;
xSize = 176;
ySize = 140;
}
@Override
protected void drawGuiContainerForegroundLayer(int x, int y)
{
String containerName = tileEntityWaterTurbine.getInventoryName();
fontRendererObj.drawString(containerName, xSize / 2 - fontRendererObj.getStringWidth(containerName) / 2, 6, 4210752);
String astring = "HHWater: "+String.valueOf(tileEntityWaterTurbine.getFluidAmount())+"/"+String.valueOf(tileEntityWaterTurbine.getFluidCapacity());
fontRendererObj.drawString(astring, (xSize/2) - (fontRendererObj.getStringWidth(astring)/2), 35, 4210752);
astring = "RF: "+String.valueOf(tileEntityWaterTurbine.getEnergyStored(ForgeDirection.UNKNOWN))+"/"+String.valueOf(tileEntityWaterTurbine.getMaxEnergyStored(ForgeDirection.UNKNOWN));
fontRendererObj.drawString(astring, (xSize/2) - (fontRendererObj.getStringWidth(astring)/2), 45, 4210752);
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(new ResourceLocation(Reference.MOD_ID.toLowerCase(),"textures/gui/waterturbine.png"));
int xStart = (width - xSize) / 2;
int yStart = (height - ySize) / 2;
this.drawTexturedModalRect(xStart, yStart, 0, 0, xSize, ySize);
}
}
| Ragingart/MiningModifications | src/main/java/com/ragingart/miningmodifications/client/gui/container/machines/GuiWaterTurbine.java | Java | gpl-3.0 | 2,323 |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaiRong.Core;
using BaiRong.Core.Model.Enumerations;
using BaiRong.Core.Permissions;
using SiteServer.CMS.Core;
namespace SiteServer.BackgroundPages.Admin
{
public class ModalPermissionsSet : BasePageCms
{
public DropDownList DdlPredefinedRole;
public PlaceHolder PhPublishmentSystemId;
public CheckBoxList CblPublishmentSystemId;
public Control TrRolesRow;
public ListBox LbAvailableRoles;
public ListBox LbAssignedRoles;
private string _userName = string.Empty;
private AdministratorWithPermissions _permissions;
public static string GetOpenWindowString(string userName)
{
return PageUtils.GetOpenWindowString("权限设置",
PageUtils.GetAdminUrl(nameof(ModalPermissionsSet), new NameValueCollection
{
{"UserName", userName}
}));
}
public void Page_Load(object sender, EventArgs e)
{
if (IsForbidden) return;
_userName = Body.GetQueryString("UserName");
_permissions = PermissionsManager.GetPermissions(Body.AdministratorName);
if (IsPostBack) return;
var roles = BaiRongDataProvider.RoleDao.GetRolesForUser(_userName);
if (_permissions.IsConsoleAdministrator)
{
DdlPredefinedRole.Items.Add(EPredefinedRoleUtils.GetListItem(EPredefinedRole.ConsoleAdministrator, false));
DdlPredefinedRole.Items.Add(EPredefinedRoleUtils.GetListItem(EPredefinedRole.SystemAdministrator, false));
}
DdlPredefinedRole.Items.Add(EPredefinedRoleUtils.GetListItem(EPredefinedRole.Administrator, false));
var type = EPredefinedRoleUtils.GetEnumTypeByRoles(roles);
ControlUtils.SelectListItems(DdlPredefinedRole, EPredefinedRoleUtils.GetValue(type));
PublishmentSystemManager.AddListItems(CblPublishmentSystemId);
ControlUtils.SelectListItems(CblPublishmentSystemId, BaiRongDataProvider.AdministratorDao.GetPublishmentSystemIdList(_userName));
ListBoxDataBind();
DdlPredefinedRole_SelectedIndexChanged(null, EventArgs.Empty);
}
public void DdlPredefinedRole_SelectedIndexChanged(object sender, EventArgs e)
{
if (EPredefinedRoleUtils.Equals(EPredefinedRole.ConsoleAdministrator, DdlPredefinedRole.SelectedValue))
{
TrRolesRow.Visible = PhPublishmentSystemId.Visible = false;
}
else if (EPredefinedRoleUtils.Equals(EPredefinedRole.SystemAdministrator, DdlPredefinedRole.SelectedValue))
{
TrRolesRow.Visible = false;
PhPublishmentSystemId.Visible = true;
}
else
{
TrRolesRow.Visible = true;
PhPublishmentSystemId.Visible = false;
}
}
private void ListBoxDataBind()
{
LbAvailableRoles.Items.Clear();
LbAssignedRoles.Items.Clear();
var allRoles = _permissions.IsConsoleAdministrator ? BaiRongDataProvider.RoleDao.GetAllRoles() : BaiRongDataProvider.RoleDao.GetAllRolesByCreatorUserName(Body.AdministratorName);
var userRoles = BaiRongDataProvider.RoleDao.GetRolesForUser(_userName);
var userRoleNameArrayList = new ArrayList(userRoles);
foreach (var roleName in allRoles)
{
if (!EPredefinedRoleUtils.IsPredefinedRole(roleName) && !userRoleNameArrayList.Contains(roleName))
{
LbAvailableRoles.Items.Add(new ListItem(roleName, roleName));
}
}
foreach (var roleName in userRoles)
{
if (!EPredefinedRoleUtils.IsPredefinedRole(roleName))
{
LbAssignedRoles.Items.Add(new ListItem(roleName, roleName));
}
}
}
public void AddRole_OnClick(object sender, EventArgs e)
{
if (IsPostBack && IsValid)
{
try
{
if (LbAvailableRoles.SelectedIndex != -1)
{
var selectedRoles = ControlUtils.GetSelectedListControlValueArray(LbAvailableRoles);
if (selectedRoles.Length > 0)
{
BaiRongDataProvider.RoleDao.AddUserToRoles(_userName, selectedRoles);
}
}
ListBoxDataBind();
}
catch (Exception ex)
{
FailMessage(ex, "用户角色分配失败");
}
}
}
public void AddRoles_OnClick(object sender, EventArgs e)
{
if (IsPostBack && IsValid)
{
try
{
var roles = ControlUtils.GetListControlValues(LbAvailableRoles);
if (roles.Length > 0)
{
BaiRongDataProvider.RoleDao.AddUserToRoles(_userName, roles);
}
ListBoxDataBind();
}
catch (Exception ex)
{
FailMessage(ex, "用户角色分配失败");
}
}
}
public void DeleteRole_OnClick(object sender, EventArgs e)
{
if (IsPostBack && IsValid)
{
try
{
if (LbAssignedRoles.SelectedIndex != -1)
{
var selectedRoles = ControlUtils.GetSelectedListControlValueArray(LbAssignedRoles);
BaiRongDataProvider.RoleDao.RemoveUserFromRoles(_userName, selectedRoles);
}
ListBoxDataBind();
}
catch (Exception ex)
{
FailMessage(ex, "用户角色分配失败");
}
}
}
public void DeleteRoles_OnClick(object sender, EventArgs e)
{
if (IsPostBack && IsValid)
{
if (IsPostBack && IsValid)
{
try
{
var roles = ControlUtils.GetListControlValues(LbAssignedRoles);
if (roles.Length > 0)
{
BaiRongDataProvider.RoleDao.RemoveUserFromRoles(_userName, roles);
}
ListBoxDataBind();
}
catch (Exception ex)
{
FailMessage(ex, "用户角色分配失败");
}
}
}
}
public override void Submit_OnClick(object sender, EventArgs e)
{
var isChanged = false;
try
{
var allRoles = EPredefinedRoleUtils.GetAllPredefinedRoleName();
foreach (var roleName in allRoles)
{
BaiRongDataProvider.RoleDao.RemoveUserFromRole(_userName, roleName);
}
BaiRongDataProvider.RoleDao.AddUserToRole(_userName, DdlPredefinedRole.SelectedValue);
BaiRongDataProvider.AdministratorDao.UpdatePublishmentSystemIdCollection(_userName,
EPredefinedRoleUtils.Equals(EPredefinedRole.SystemAdministrator, DdlPredefinedRole.SelectedValue)
? ControlUtils.SelectedItemsValueToStringCollection(CblPublishmentSystemId.Items)
: string.Empty);
Body.AddAdminLog("设置管理员权限", $"管理员:{_userName}");
SuccessMessage("权限设置成功!");
isChanged = true;
}
catch (Exception ex)
{
FailMessage(ex, "权限设置失败!");
}
if (isChanged)
{
var redirectUrl = PageAdministrator.GetRedirectUrl(0);
PageUtils.CloseModalPageAndRedirect(Page, redirectUrl);
}
}
}
} | kk141242/siteserver | source/SiteServer.BackgroundPages/Admin/ModalPermissionsSet.cs | C# | gpl-3.0 | 8,475 |
/* This file is part of Imagine.
Imagine is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Imagine 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 Imagine. If not, see <http://www.gnu.org/licenses/> */
#define LOGTAG "CpufreqParam"
#include <imagine/base/android/RootCpufreqParamSetter.hh>
#include <imagine/io/PosixIO.hh>
#include <imagine/logger/logger.h>
#include <imagine/util/utility.h>
#include <cstdlib>
#include <array>
#define TIMER_RATE_PATH "/sys/devices/system/cpu/cpufreq/interactive/timer_rate"
#define UP_THRESHOLD_PATH "/sys/devices/system/cpu/cpufreq/ondemand/up_threshold"
#define SAMPLING_RATE_PATH "/sys/devices/system/cpu/cpufreq/ondemand/sampling_rate"
#define SAMPLING_RATE_MiN_PATH "/sys/devices/system/cpu/cpufreq/ondemand/sampling_rate_min"
namespace IG
{
static int readIntFileValue(const char *path)
{
try
{
PosixIO f{path};
std::array<char, 32> buff{};
f.readAtPos(buff.data(), sizeof(buff)-1, 0);
int val = -1;
sscanf(buff.data(), "%d", &val);
return val;
}
catch(...)
{
return -1;
}
}
RootCpufreqParamSetter::RootCpufreqParamSetter()
{
origTimerRate = readIntFileValue(TIMER_RATE_PATH);
if(origTimerRate <= 0)
{
origUpThreshold = readIntFileValue(UP_THRESHOLD_PATH);
logMsg("default up_threshold:%d", origUpThreshold);
origSamplingRate = readIntFileValue(SAMPLING_RATE_PATH);
logMsg("default sampling_rate:%d", origSamplingRate);
}
else
{
logMsg("default timer_rate:%d", origTimerRate);
}
if(origTimerRate <= 0 && origUpThreshold <= 0 && origSamplingRate <= 0)
{
logErr("couldn't read any cpufreq parameters");
return;
}
rootShell = popen("su", "w");
if(!rootShell)
{
logErr("error running root shell");
return;
}
logMsg("opened root shell");
}
RootCpufreqParamSetter::~RootCpufreqParamSetter()
{
if(rootShell)
{
pclose(rootShell);
logMsg("closed root shell");
}
}
void RootCpufreqParamSetter::setLowLatency()
{
assumeExpr(rootShell);
if(origTimerRate > 0)
{
// interactive
logMsg("setting low-latency interactive governor values");
fprintf(rootShell, "echo -n 6000 > " TIMER_RATE_PATH "\n");
}
else
{
// ondemand
logMsg("setting low-latency ondemand governor values");
if(origUpThreshold > 0)
fprintf(rootShell, "echo -n 40 > " UP_THRESHOLD_PATH "\n");
if(origSamplingRate > 0)
fprintf(rootShell, "echo -n `cat " SAMPLING_RATE_MiN_PATH "` > " SAMPLING_RATE_PATH "\n");
}
fflush(rootShell);
}
void RootCpufreqParamSetter::setDefaults()
{
assumeExpr(rootShell);
if(origTimerRate > 0)
{
// interactive
logMsg("setting default interactive governor values");
fprintf(rootShell, "echo -n %d > " TIMER_RATE_PATH "\n", origTimerRate);
}
else
{
// ondemand
logMsg("setting default ondemand governor values");
if(origUpThreshold > 0)
fprintf(rootShell, "echo -n %d > " UP_THRESHOLD_PATH "\n", origUpThreshold);
if(origSamplingRate > 0)
fprintf(rootShell, "echo -n %d > " SAMPLING_RATE_PATH "\n", origSamplingRate);
}
fflush(rootShell);
}
}
| Rakashazi/emu-ex-plus-alpha | imagine/src/base/android/RootCpufreqParamSetter.cc | C++ | gpl-3.0 | 3,431 |
package cn.nukkit.command.defaults;
import cn.nukkit.Player;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;
import cn.nukkit.event.TranslationContainer;
import cn.nukkit.item.Item;
import cn.nukkit.item.enchantment.Enchantment;
import cn.nukkit.utils.TextFormat;
/**
* Created by Pub4Game on 23.01.2016.
*/
public class EnchantCommand extends VanillaCommand {
public EnchantCommand(String name) {
super(name, "%nukkit.command.enchant.description", "%commands.enchant.usage");
this.setPermission("nukkit.command.enchant");
}
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
if (!this.testPermission(sender)) {
return true;
}
if (args.length < 2) {
sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage));
return true;
}
Player player = sender.getServer().getPlayer(args[0]);
if (player == null) {
sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.player.notFound"));
return true;
}
int enchantId;
int enchantLevel;
try {
enchantId = Integer.parseInt(args[1]);
enchantLevel = args.length == 3 ? Integer.parseInt(args[2]) : 1;
} catch (Exception e) {
sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage));
return true;
}
Enchantment enchantment = Enchantment.getEnchantment(enchantId);
if (enchantment.getId() == Enchantment.TYPE_INVALID) {
sender.sendMessage(new TranslationContainer("commands.enchant.notFound", String.valueOf(enchantId)));
return true;
}
enchantment.setLevel(enchantLevel);
Item item = player.getInventory().getItemInHand();
if (item.getId() <= 0) {
sender.sendMessage(new TranslationContainer("commands.enchant.noItem"));
return true;
}
item.addEnchantment(enchantment);
player.getInventory().setItemInHand(item);
Command.broadcastCommandMessage(sender, new TranslationContainer("%commands.enchant.success"));
return true;
}
}
| LinEvil/Nukkit | src/main/java/cn/nukkit/command/defaults/EnchantCommand.java | Java | gpl-3.0 | 2,298 |
<?php
/**
* Created by PhpStorm.
* User: Sebastian Erb
* Date: 21.02.17
* Time: 19:08
*/
require_once($_SERVER['DOCUMENT_ROOT'] . "/instagram/Instagram.php");
$insta = new AjaxInstagram();
$insta->jsonFile = $_SERVER['DOCUMENT_ROOT'] . "/cron/hashtaglist.json";
$insta->showImages(5);
| sebastianerb/Instagram-PHP-Hashtag-Feed | InstaFeed.php | PHP | gpl-3.0 | 296 |
/*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.core.genetics.alleles;
import com.google.common.collect.HashMultimap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import net.minecraft.item.ItemStack;
import com.mojang.authlib.GameProfile;
import forestry.api.genetics.IAllele;
import forestry.api.genetics.IAlleleHandler;
import forestry.api.genetics.IAlleleRegistry;
import forestry.api.genetics.IAlleleSpecies;
import forestry.api.genetics.IChromosomeType;
import forestry.api.genetics.IClassification;
import forestry.api.genetics.IClassification.EnumClassLevel;
import forestry.api.genetics.IFruitFamily;
import forestry.api.genetics.IIndividual;
import forestry.api.genetics.IMutation;
import forestry.api.genetics.ISpeciesRoot;
import forestry.core.config.ForestryItem;
import forestry.core.genetics.Classification;
import forestry.core.genetics.ItemResearchNote.EnumNoteType;
public class AlleleRegistry implements IAlleleRegistry {
private static final int ALLELE_ARRAY_SIZE = 2048;
/* SPECIES ROOT */
private final LinkedHashMap<String, ISpeciesRoot> rootMap = new LinkedHashMap<>(16);
@Override
public void registerSpeciesRoot(ISpeciesRoot root) {
rootMap.put(root.getUID(), root);
}
@Override
public Map<String, ISpeciesRoot> getSpeciesRoot() {
return Collections.unmodifiableMap(rootMap);
}
@Override
public ISpeciesRoot getSpeciesRoot(String uid) {
if (rootMap.containsKey(uid)) {
return rootMap.get(uid);
}
return null;
}
@Override
public ISpeciesRoot getSpeciesRoot(ItemStack stack) {
if (stack == null) {
return null;
}
for (ISpeciesRoot root : rootMap.values()) {
if (root.isMember(stack)) {
return root;
}
}
return null;
}
@Override
public ISpeciesRoot getSpeciesRoot(Class<? extends IIndividual> clz) {
for (ISpeciesRoot root : rootMap.values()) {
if (root.getMemberClass().isAssignableFrom(clz)) {
return root;
}
}
return null;
}
/* INDIVIDUALS */
@Override
public boolean isIndividual(ItemStack stack) {
if (stack == null) {
return false;
}
return getSpeciesRoot(stack) != null;
}
@Override
public IIndividual getIndividual(ItemStack stack) {
ISpeciesRoot root = getSpeciesRoot(stack);
if (root == null) {
return null;
}
return root.getMember(stack);
}
/* ALLELES */
private final LinkedHashMap<String, IAllele> alleleMap = new LinkedHashMap<>(ALLELE_ARRAY_SIZE);
private final HashMultimap<IChromosomeType, IAllele> allelesByType = HashMultimap.create();
private final HashMultimap<IAllele, IChromosomeType> typesByAllele = HashMultimap.create();
private final LinkedHashMap<String, IAllele> deprecatedAlleleMap = new LinkedHashMap<>(32);
private final LinkedHashMap<String, IClassification> classificationMap = new LinkedHashMap<>(128);
private final LinkedHashMap<String, IFruitFamily> fruitMap = new LinkedHashMap<>(64);
/*
* Internal HashSet of all alleleHandlers, which trigger when an allele or branch is registered
*/
private final HashSet<IAlleleHandler> alleleHandlers = new HashSet<>();
public void initialize() {
createAndRegisterClassification(EnumClassLevel.DOMAIN, "archaea", "Archaea");
createAndRegisterClassification(EnumClassLevel.DOMAIN, "bacteria", "Bacteria");
IClassification eukarya = createAndRegisterClassification(EnumClassLevel.DOMAIN, "eukarya", "Eukarya");
eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "animalia", "Animalia"));
eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "plantae", "Plantae"));
eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "fungi", "Fungi"));
eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "protista", "Protista"));
getClassification("kingdom.animalia").addMemberGroup(createAndRegisterClassification(EnumClassLevel.PHYLUM, "arthropoda", "Arthropoda"));
// Animalia
getClassification("phylum.arthropoda").addMemberGroup(createAndRegisterClassification(EnumClassLevel.CLASS, "insecta", "Insecta"));
}
@Override
public Map<String, IAllele> getRegisteredAlleles() {
return Collections.unmodifiableMap(alleleMap);
}
@Override
public Map<String, IAllele> getDeprecatedAlleleReplacements() {
return Collections.unmodifiableMap(deprecatedAlleleMap);
}
@Override
public void registerAllele(IAllele allele) {
alleleMap.put(allele.getUID(), allele);
if (allele instanceof IAlleleSpecies) {
IClassification branch = ((IAlleleSpecies) allele).getBranch();
if (branch != null) {
branch.addMemberSpecies((IAlleleSpecies) allele);
}
}
for (IAlleleHandler handler : this.alleleHandlers) {
handler.onRegisterAllele(allele);
}
}
@Override
public void registerAllele(IAllele allele, IChromosomeType... chromosomeTypes) {
for (IChromosomeType chromosomeType : chromosomeTypes) {
if (!chromosomeType.getAlleleClass().isAssignableFrom(allele.getClass())) {
throw new IllegalArgumentException("Allele class (" + allele.getClass() + ") does not match chromosome type (" + chromosomeType.getAlleleClass() + ").");
}
allelesByType.put(chromosomeType, allele);
typesByAllele.put(allele, chromosomeType);
}
registerAllele(allele);
}
@Override
public void registerDeprecatedAlleleReplacement(String deprecatedUID, IAllele replacementAllele) {
if (deprecatedAlleleMap.containsKey(deprecatedUID)) {
return;
}
deprecatedAlleleMap.put(deprecatedUID, replacementAllele);
}
@Override
public IAllele getAllele(String uid) {
IAllele allele = alleleMap.get(uid);
if (allele == null) {
allele = deprecatedAlleleMap.get(uid);
}
return allele;
}
@Override
public Collection<IAllele> getRegisteredAlleles(IChromosomeType type) {
return Collections.unmodifiableSet(allelesByType.get(type));
}
// This method is not useful until all mod addon alleles are registered with their valid IChromosomeTypes
public Collection<IChromosomeType> getChromosomeTypes(IAllele allele) {
return Collections.unmodifiableSet(typesByAllele.get(allele));
}
/* CLASSIFICATIONS */
@Override
public void registerClassification(IClassification branch) {
if (classificationMap.containsKey(branch.getUID())) {
throw new RuntimeException(String.format("Could not add new classification '%s', because the key is already taken by %s.", branch.getUID(),
classificationMap.get(branch.getUID())));
}
classificationMap.put(branch.getUID(), branch);
for (IAlleleHandler handler : this.alleleHandlers) {
handler.onRegisterClassification(branch);
}
}
@Override
public Map<String, IClassification> getRegisteredClassifications() {
return Collections.unmodifiableMap(classificationMap);
}
@Override
public IClassification createAndRegisterClassification(EnumClassLevel level, String uid, String scientific) {
return new Classification(level, uid, scientific);
}
@Override
public IClassification createAndRegisterClassification(EnumClassLevel level, String uid, String scientific, IClassification... members) {
IClassification classification = new Classification(level, uid, scientific);
for (IClassification member : members) {
classification.addMemberGroup(member);
}
return classification;
}
@Override
public IClassification getClassification(String uid) {
return classificationMap.get(uid);
}
/* FRUIT FAMILIES */
@Override
public void registerFruitFamily(IFruitFamily family) {
fruitMap.put(family.getUID(), family);
for (IAlleleHandler handler : this.alleleHandlers) {
handler.onRegisterFruitFamily(family);
}
}
@Override
public Map<String, IFruitFamily> getRegisteredFruitFamilies() {
return Collections.unmodifiableMap(fruitMap);
}
@Override
public IFruitFamily getFruitFamily(String uid) {
return fruitMap.get(uid);
}
/* ALLELE HANDLERS */
@Override
public void registerAlleleHandler(IAlleleHandler handler) {
this.alleleHandlers.add(handler);
}
/* BLACKLIST */
private final ArrayList<String> blacklist = new ArrayList<>();
@Override
public void blacklistAllele(String uid) {
blacklist.add(uid);
}
@Override
public Collection<String> getAlleleBlacklist() {
return Collections.unmodifiableCollection(blacklist);
}
@Override
public boolean isBlacklisted(String uid) {
return blacklist.contains(uid);
}
/* RESEARCH */
@Override
public ItemStack getSpeciesNoteStack(GameProfile researcher, IAlleleSpecies species) {
return EnumNoteType.createSpeciesNoteStack(ForestryItem.researchNote.item(), researcher, species);
}
@Override
public ItemStack getMutationNoteStack(GameProfile researcher, IMutation mutation) {
return EnumNoteType.createMutationNoteStack(ForestryItem.researchNote.item(), researcher, mutation);
}
}
| AnodeCathode/ForestryMC | src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java | Java | gpl-3.0 | 9,410 |
using System;
using System.Windows.Forms;
using System.Drawing;
namespace GitUI.Editor
{
public delegate void SelectedLineChangedEventHandler(object sender, int selectedLine);
public interface IFileViewer
{
event MouseEventHandler MouseMove;
event EventHandler MouseLeave;
event EventHandler TextChanged;
event EventHandler ScrollPosChanged;
event SelectedLineChangedEventHandler SelectedLineChanged;
event KeyEventHandler KeyDown;
event EventHandler DoubleClick;
void EnableScrollBars(bool enable);
void Find();
string GetText();
void SetText(string text);
void SetHighlighting(string syntax);
void HighlightLine(int line, Color color);
void ClearHighlighting();
string GetSelectedText();
int GetSelectionPosition();
int GetSelectionLength();
void AddPatchHighlighting();
int ScrollPos { get; set; }
bool ShowLineNumbers { get; set; }
bool ShowEOLMarkers { get; set; }
bool ShowSpaces { get; set; }
bool ShowTabs { get; set; }
bool IsReadOnly { get; set; }
bool Visible { get; set; }
int FirstVisibleLine { get; set; }
int GetLineFromVisualPosY(int visualPosY);
string GetLineText(int line);
int TotalNumberOfLines { get; }
}
}
| avish/gitextensions | GitUI/Editor/IFileViewer.cs | C# | gpl-3.0 | 1,439 |
package ca.aspibot.env.model;
import java.util.*;
import ca.aspibot.utils.CoordinatesInt2D;
/**
* Modèle : Représente l'environnement <br>
* Hérite de {@link Observable} pour notifier des changements <br>
* Implémente {@link Runnable} pour fonctionner dans un thread séparé
*
* @author Vincent PORTA & Pierre SERRUT
*
*/
public class EnvironnementModel extends Observable implements Runnable {
/**
* Représente les sections de l'environnement
*/
private PlaceState place[][];
/**
* Temps minimal entre deux actualisations de l'environnement
*/
private int spawnTimeMin;
/**
* Temps maximal entre deux actualisations de l'environnement
*/
private int spawnTimeMax;
/**
* Taux d'apparition des saletés
*/
private double dirtySpawnRate;
/**
* Taux d'apparition des bijoux
*/
private double jewelrySpawnRate;
/**
* Indique au thread s'il continue son execution ou non
*/
private boolean notEnd;
/**
* Générateur de nombre aléatoire
*/
private Random randGen;
/**
* Constructeur <br>
* Initialise les section avec la valeur PlaceState.CLEAN
*
* @see PlaceState
*
* @param nbLignes
* Nombre de lignes pour les différentes sections
* @param nbColonnes
* Nombre de colonnes pour les différentes sections
* @param spawnTimeMin
* Temps minimal entre deux actualisations de l'environnement (en secondes)
* @param spawnTimeMax
* Temps maximal entre deux actualisations de l'environnement (en secondes)
* @param dirtySpawnRate
* Taux d'apparition des saletés
* @param jewelrySpawnRate
* Taux d'apparition des bijoux
*/
public EnvironnementModel(int nbLignes, int nbColonnes, int spawnTimeMin, int spawnTimeMax, double dirtySpawnRate,
double jewelrySpawnRate) {
// Test si valeur négatives
if (nbLignes <= 0 | nbColonnes <= 0) {
throw new RuntimeException("Size must be positive");
}
// Init
this.place = new PlaceState[nbLignes][nbColonnes];
for (int ligne = 0; ligne < this.place.length; ligne++) {
for (int col = 0; col < this.place[ligne].length; col++) {
this.place[ligne][col] = PlaceState.CLEAN;
}
}
this.spawnTimeMin = spawnTimeMin;
this.spawnTimeMax = spawnTimeMax;
this.dirtySpawnRate = dirtySpawnRate;
this.jewelrySpawnRate = jewelrySpawnRate;
this.randGen = new Random();
this.notEnd = false;
}
/**
* Getter : Retourne l'état des différentes sections
*
* @return Matrice de {@link PlaceState}
*/
public PlaceState[][] getPlaces() {
return this.place;
}
/**
* Getter : Retourne le nombre de ligne
*
* @return Entier
*/
public int getPlacesRows() {
return this.place.length;
}
/**
* Getter : Retourne le nombre de colonnes
*
* @return Entier
*/
public int getPlacesCols() {
return this.place[0].length;
}
/**
* Getter : Retourne l'état d'une section particulière
*
* @param numLigne
* Emplacement de la section (ligne)
* @param numColonne
* Emplacement de la section (colonne)
* @return {@link PlaceState}
*/
public PlaceState getPlaceState(int numLigne, int numColonne) {
return this.place[numLigne][numColonne];
}
/**
* Setter : Change l'état d'une section particulière
*
* @param numLigne
* Emplacement de la section (ligne)
* @param numColonne
* Emplacement de la section (colonne)
* @param state
* Nouvel état - {@link PlaceState}
*/
public void setPlaceState(int numLigne, int numColonne, PlaceState state) {
synchronized (this.place) {
this.place[numLigne][numColonne] = state;
}
}
/**
* Enlève les bijoux sur une section
*
* @param numLigne
* Emplacement de la section (ligne)
* @param numColonne
* Emplacement de la section (colonne)
*/
public void removeJewelry(int numLigne, int numColonne) {
synchronized (this.place) {
if (this.place[numLigne][numColonne] != PlaceState.NONE) {
if (this.place[numLigne][numColonne] == PlaceState.BOTH) {
this.place[numLigne][numColonne] = PlaceState.DIRTY;
} else {
this.place[numLigne][numColonne] = PlaceState.CLEAN;
}
setChanged();
}
}
notifyObservers(new CoordinatesInt2D(numLigne, numColonne));
}
/**
* Nettoie une section
*
* @param numLigne
* Emplacement de la section (ligne)
* @param numColonne
* Emplacement de la section (colonne)
*/
public void clean(int numLigne, int numColonne) {
synchronized (this.place) {
if (this.place[numLigne][numColonne] != PlaceState.NONE
&& this.place[numLigne][numColonne] != PlaceState.CLEAN) {
this.place[numLigne][numColonne] = PlaceState.CLEAN;
setChanged();
}
}
notifyObservers(new CoordinatesInt2D(numLigne, numColonne));
}
/**
* Méthode utilisé pour le débogage ou l'affichage console
*/
public String toString() {
StringBuilder strMap = new StringBuilder();
for (int ligne = 0; ligne < this.place.length; ligne++) {
strMap.append("|");
for (int col = 0; col < this.place[ligne].length; col++) {
switch (place[ligne][col]) {
case CLEAN:
strMap.append(" ");
break;
case DIRTY:
strMap.append("D");
break;
case JEWELRY:
strMap.append("J");
break;
case BOTH:
strMap.append("B");
break;
default:
strMap.append("■");
break;
}
strMap.append("|");
}
strMap.append("\n");
}
return strMap.toString();
}
/**
* Méthode pour arrêter l'actualisation de l'environnement => thread
*/
public void stop() {
this.notEnd = false;
}
/**
* Méthode pour lancer l'actualisation de l'environnement => thread
*/
public void start() {
if (!this.notEnd) {
this.notEnd = true;
new Thread(this).start();
}
}
/**
* Méthode qui actualise l'environnement
*/
@Override
public void run() {
while (this.notEnd) {
// On attend aléatoirement entre les deux valeurs min et max
try {
Thread.sleep((spawnTimeMin + randGen.nextInt(spawnTimeMax - spawnTimeMin)) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/*
* On choisi une section et on tire aléatoirement un nombre qui va
* représenter soit un ajout de saletés, soit un ajout de bijoux,
* soit rien du tout
*/
int x = randGen.nextInt(place.length);
int y = randGen.nextInt(place[x].length);
float res = randGen.nextFloat();
// Si cette section est interdite, on recommence
while (place[x][y] == PlaceState.NONE) {
x = randGen.nextInt(place.length);
y = randGen.nextInt(place[x].length);
}
// Si la section n'est pas déjà sale et avec des bijoux
if (place[x][y] != PlaceState.BOTH) {
/*
* On applique l'ajout décidé plus haut en fonction des taux
* d'apparition
*/
if (place[x][y] != PlaceState.DIRTY && res < this.dirtySpawnRate) {
if (place[x][y] == PlaceState.JEWELRY) {
synchronized (this.place) {
place[x][y] = PlaceState.BOTH;
}
} else {
synchronized (this.place) {
place[x][y] = PlaceState.DIRTY;
}
}
setChanged();
}
if (place[x][y] != PlaceState.JEWELRY && (res - this.dirtySpawnRate) > 0
&& (res - this.dirtySpawnRate) < this.jewelrySpawnRate) {
if (place[x][y] == PlaceState.DIRTY) {
synchronized (this.place) {
place[x][y] = PlaceState.BOTH;
}
setChanged();
} else {
synchronized (this.place) {
place[x][y] = PlaceState.JEWELRY;
}
setChanged();
}
}
}
// On notifie les observeurs si il y a eu un changement
notifyObservers(new CoordinatesInt2D(x, y));
}
}
}
| vportascarta/UQAC-8INF846-TP1 | src/ca/aspibot/env/model/EnvironnementModel.java | Java | gpl-3.0 | 7,740 |
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package org.kisti.edison.virtuallaboratory.service.base;
import org.kisti.edison.virtuallaboratory.service.VirtualLabUserTempServiceUtil;
import java.util.Arrays;
/**
* @author EDISON
* @generated
*/
public class VirtualLabUserTempServiceClpInvoker {
public VirtualLabUserTempServiceClpInvoker() {
_methodName70 = "getBeanIdentifier";
_methodParameterTypes70 = new String[] { };
_methodName71 = "setBeanIdentifier";
_methodParameterTypes71 = new String[] { "java.lang.String" };
}
public Object invokeMethod(String name, String[] parameterTypes,
Object[] arguments) throws Throwable {
if (_methodName70.equals(name) &&
Arrays.deepEquals(_methodParameterTypes70, parameterTypes)) {
return VirtualLabUserTempServiceUtil.getBeanIdentifier();
}
if (_methodName71.equals(name) &&
Arrays.deepEquals(_methodParameterTypes71, parameterTypes)) {
VirtualLabUserTempServiceUtil.setBeanIdentifier((java.lang.String)arguments[0]);
return null;
}
throw new UnsupportedOperationException();
}
private String _methodName70;
private String[] _methodParameterTypes70;
private String _methodName71;
private String[] _methodParameterTypes71;
} | queza85/edison | edison-portal-framework/edison-virtuallab-2016-portlet/docroot/WEB-INF/src/org/kisti/edison/virtuallaboratory/service/base/VirtualLabUserTempServiceClpInvoker.java | Java | gpl-3.0 | 1,776 |
/* iterator_to_const and const_iterator_to_const class implementations:
inline functions.
Copyright (C) 2001-2009 Roberto Bagnara <bagnara@cs.unipr.it>
This file is part of the Parma Polyhedra Library (PPL).
The PPL is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
The PPL 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 02111-1307, USA.
For the most up-to-date information see the Parma Polyhedra Library
site: http://www.cs.unipr.it/ppl/ . */
#ifndef PPL_iterator_to_const_inlines_hh
#define PPL_iterator_to_const_inlines_hh 1
namespace Parma_Polyhedra_Library {
template <typename Container>
inline
iterator_to_const<Container>::iterator_to_const()
: base() {
}
template <typename Container>
inline
iterator_to_const<Container>::iterator_to_const(const iterator_to_const& y)
: base(y.base) {
}
template <typename Container>
inline
iterator_to_const<Container>::iterator_to_const(const Base& b)
: base(b) {
}
template <typename Container>
inline typename iterator_to_const<Container>::reference
iterator_to_const<Container>::operator*() const {
return *base;
}
template <typename Container>
inline typename iterator_to_const<Container>::pointer
iterator_to_const<Container>::operator->() const {
return &*base;
}
template <typename Container>
inline iterator_to_const<Container>&
iterator_to_const<Container>::operator++() {
++base;
return *this;
}
template <typename Container>
inline iterator_to_const<Container>
iterator_to_const<Container>::operator++(int) {
iterator_to_const tmp = *this;
operator++();
return tmp;
}
template <typename Container>
inline iterator_to_const<Container>&
iterator_to_const<Container>::operator--() {
--base;
return *this;
}
template <typename Container>
inline iterator_to_const<Container>
iterator_to_const<Container>::operator--(int) {
iterator_to_const tmp = *this;
operator--();
return tmp;
}
template <typename Container>
inline bool
iterator_to_const<Container>::operator==(const iterator_to_const& y) const {
return base == y.base;
}
template <typename Container>
inline bool
iterator_to_const<Container>::operator!=(const iterator_to_const& y) const {
return !operator==(y);
}
template <typename Container>
inline
const_iterator_to_const<Container>::const_iterator_to_const()
: base() {
}
template <typename Container>
inline
const_iterator_to_const<Container>
::const_iterator_to_const(const const_iterator_to_const& y)
: base(y.base) {
}
template <typename Container>
inline
const_iterator_to_const<Container>::const_iterator_to_const(const Base& b)
: base(b) {
}
template <typename Container>
inline typename const_iterator_to_const<Container>::reference
const_iterator_to_const<Container>::operator*() const {
return *base;
}
template <typename Container>
inline typename const_iterator_to_const<Container>::pointer
const_iterator_to_const<Container>::operator->() const {
return &*base;
}
template <typename Container>
inline const_iterator_to_const<Container>&
const_iterator_to_const<Container>::operator++() {
++base;
return *this;
}
template <typename Container>
inline const_iterator_to_const<Container>
const_iterator_to_const<Container>::operator++(int) {
const_iterator_to_const tmp = *this;
operator++();
return tmp;
}
template <typename Container>
inline const_iterator_to_const<Container>&
const_iterator_to_const<Container>::operator--() {
--base;
return *this;
}
template <typename Container>
inline const_iterator_to_const<Container>
const_iterator_to_const<Container>::operator--(int) {
const_iterator_to_const tmp = *this;
operator--();
return tmp;
}
template <typename Container>
inline bool
const_iterator_to_const<Container>
::operator==(const const_iterator_to_const& y) const {
return base == y.base;
}
template <typename Container>
inline bool
const_iterator_to_const<Container>
::operator!=(const const_iterator_to_const& y) const {
return !operator==(y);
}
template <typename Container>
inline
const_iterator_to_const<Container>
::const_iterator_to_const(const iterator_to_const<Container>& y)
: base(y.base) {
}
/*! \relates const_iterator_to_const */
template <typename Container>
inline bool
operator==(const iterator_to_const<Container>& x,
const const_iterator_to_const<Container>& y) {
return const_iterator_to_const<Container>(x).operator==(y);
}
/*! \relates const_iterator_to_const */
template <typename Container>
inline bool
operator!=(const iterator_to_const<Container>& x,
const const_iterator_to_const<Container>& y) {
return !(x == y);
}
} // namespace Parma_Polyhedra_Library
#endif // !defined(PPL_iterator_to_const_inlines_hh)
| OpenInkpot-archive/iplinux-ppl | src/iterator_to_const.inlines.hh | C++ | gpl-3.0 | 5,179 |
# frozen_string_literal: true
module Parser
# Holds p->max_numparam from parse.y
#
# @api private
class MaxNumparamStack
attr_reader :stack
ORDINARY_PARAMS = -1
def initialize
@stack = []
end
def empty?
@stack.size == 0
end
def has_ordinary_params!
set(ORDINARY_PARAMS)
end
def has_ordinary_params?
top == ORDINARY_PARAMS
end
def has_numparams?
top && top > 0
end
def register(numparam)
set( [top, numparam].max )
end
def top
@stack.last
end
def push
@stack.push(0)
end
def pop
@stack.pop
end
private
def set(value)
@stack[@stack.length - 1] = value
end
end
end
| BeGe78/esood | vendor/bundle/ruby/3.0.0/gems/parser-3.0.2.0/lib/parser/max_numparam_stack.rb | Ruby | gpl-3.0 | 739 |
"use strict";
const serversdb = require("../servers");
const hands = [":ok_hand::skin-tone-1:", ":ok_hand::skin-tone-2:", ":ok_hand::skin-tone-3:", ":ok_hand::skin-tone-4:", ":ok_hand::skin-tone-5:", ":ok_hand:"];
const hand = hands[Math.floor(Math.random() * hands.length)];
module.exports = {
// eslint-disable-next-line no-unused-vars
main: async function(bot, m, args, prefix) {
var data = await serversdb.load();
var guild = m.channel.guild;
if (!data[guild.id]) {
data[guild.id] = {};
data[guild.id].name = guild.name;
data[guild.id].owner = guild.ownerID;
bot.createMessage(m.channel.id, `Server: ${guild.name} added to database. Populating information ${hand}`).then(function(msg) {
return setTimeout(function() {
bot.deleteMessage(m.channel.id, m.id, "Timeout");
bot.deleteMessage(m.channel.id, msg.id, "Timeout");
}, 5000);
});
await serversdb.save(data);
}
if (!data[guild.id].art) {
bot.createMessage(m.channel.id, `An art channel has not been set up for this server. Please have a mod add one using the command: \`${prefix}edit art add #channel\``).then(function(msg) {
return setTimeout(function() {
bot.deleteMessage(m.channel.id, msg.id, "Timeout");
bot.deleteMessage(m.channel.id, m.id, "Timeout");
}, 10000);
});
return;
}
var index = 5000;
if (args) {
if (!isNaN(+args)) {
index = args;
}
}
var channel = data[guild.id].art;
channel = bot.getChannel(channel);
if (data[guild.id].art && !channel) {
bot.createMessage(m.channel.id, `The selected art channel, <#${data[guild.id].art}>, has either been deleted, or I no longer have access to it. Please set the art channel to an existing channel that I have access to.`).then(function(msg) {
return setTimeout(function() {
bot.deleteMessage(m.channel.id, msg.id, "Timeout");
bot.deleteMessage(m.channel.id, m.id, "Timeout");
}, 15000);
});
return;
}
var cName = channel.name;
var gName = channel.guild.name;
var icon = channel.guild.iconURL || null;
if (channel.nsfw && !m.channel.nsfw) {
bot.createMessage(m.channel.id, `The selected art channel, <#${channel.id}>, is an nsfw channel, and this channel is not. Please either use this command in an nsfw channel, or set the art channel to a non-nsfw channel`).then(function(msg) {
return setTimeout(function() {
bot.deleteMessage(m.channel.id, msg.id, "Timeout");
bot.deleteMessage(m.channel.id, m.id, "Timeout");
}, 10000);
});
return;
}
channel = channel.id;
if (index > 7000) {
bot.createMessage(m.channel.id, "I can't grab more than 7000 messages in any channel. Setting limit to 7000").then(function(msg) {
return setTimeout(function() {
bot.deleteMessage(m.channel.id, msg.id, "Timeout");
}, 5000);
});
index = 7000;
}
await bot.sendChannelTyping(m.channel.id);
var msgs = await bot.getMessages(channel, parseInt(index, 10));
var art = {};
for (var msg of msgs) {
if (msg.content.includes("pastebin.com")) {
art[msg.content] = [msg.author.id, msg.timestamp];
}
if (msg.attachments[0]) {
art[msg.attachments[0].url] = [msg.author.id, msg.timestamp];
}
if (msg.embeds[0]) {
if (msg.embeds[0].image) {
art[msg.embeds[0].image.url] = [msg.author.id, msg.timestamp];
}
if (!msg.embeds[0].image) {
art[msg.embeds[0].url] = [msg.author.id, msg.timestamp];
}
}
}
var number = Math.floor(Math.random() * Object.entries(art).length);
var list = Object.entries(art);
var chosen = list[number];
console.log(chosen);
if (!chosen) {
bot.createMessage(m.channel.id, `No art was found within the last \`${index}\` messages. Please try again using more messages`).then(function(msg) {
return setTimeout(function() {
bot.deleteMessage(m.channel.id, msg.id, "Timeout");
bot.deleteMessage(m.channel.id, m.id, "Timeout");
}, 5000);
});
return;
}
var author = m.channel.guild.members.get(chosen[1][0]) || m.channel.guild.members.get(chosen[1][0]) || bot.users.get(chosen[1][0]);
var url = author.avatarURL || undefined;
author = author.nick || author.username;
var time = new Date(chosen[1][1]).toISOString();
if (chosen[0].includes("pastebin.com")) {
const data = {
"embed": {
"color": 0xA260F6,
"title": chosen[0],
"description": `A random piece from <#${channel}>~`,
"url": chosen[0],
"timestamp": time,
"author": {
"name": author,
"icon_url": url
},
"footer": {
"icon_url": icon,
"text": `${cName} | ${gName}`
}
}
};
bot.createMessage(m.channel.id, data);
return;
}
else {
const data = {
"embed": {
"color": 0xA260F6,
"timestamp": time,
"description": `A random piece from <#${channel}>~`,
"image": {
"url": chosen[0]
},
"author": {
"name": author,
"icon_url": url
},
"footer": {
"icon_url": icon,
"text": `${cName} | ${gName}`
}
}
};
bot.createMessage(m.channel.id, data);
}
return;
},
help: "Show art from the set art channel" // add description
};
| LaChocola/Mei | commands/art.js | JavaScript | gpl-3.0 | 6,637 |
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <catch.hpp>
#include <actions/addspecialnoteproperty.h>
#include <score/note.h>
#include "actionfixture.h"
TEST_CASE_METHOD(ActionFixture, "Actions/AddLeftHandFingering", "")
{
Note note;
myLocation.getPosition()->insertNote(note);
LeftHandFingering fingering(LeftHandFingering::Finger::Index,
LeftHandFingering::DisplayPosition::Right);
AddLeftHandFingering action(myLocation, fingering);
action.redo();
REQUIRE(myLocation.getNote()->hasLeftHandFingering());
REQUIRE(myLocation.getNote()->getLeftHandFingering() == fingering);
action.undo();
REQUIRE(!myLocation.getNote()->hasLeftHandFingering());
}
| DontBelieveMe/powertabeditor | test/actions/test_addlefthandfingering.cpp | C++ | gpl-3.0 | 1,336 |
#include "editor.h"
#include "transform.h"
#include "indent.h"
#include <bundles/bundles.h>
#include <text/case.h>
#include <text/ctype.h>
#include <text/classification.h>
#include <text/utf8.h>
#include <text/parse.h>
#include <text/tokenize.h>
#include <text/trim.h>
#include <OakSystem/command.h>
#include <cf/run_loop.h>
#include <command/runner.h>
namespace ng
{
static std::map<oak::uuid_t, editor_ptr>& editors ()
{
static std::map<oak::uuid_t, editor_ptr> editors;
return editors;
}
editor_ptr editor_for_document (document::document_ptr document)
{
static struct document_close_callback_t : document::document_t::callback_t
{
WATCH_LEAKS(document_close_callback_t);
document_close_callback_t () { }
void handle_document_event (document::document_ptr document, event_t event)
{
if(event == did_change_open_status && !document->is_open())
{
document->remove_callback(this);
editors().erase(document->identifier());
}
}
} callback;
std::map<oak::uuid_t, editor_ptr>::iterator editor = editors().find(document->identifier());
if(editor == editors().end())
{
document->add_callback(&callback);
editor = editors().insert(std::make_pair(document->identifier(), editor_ptr(new editor_t(document)))).first;
}
return editor->second;
}
static find::options_t convert (std::map<std::string, std::string> const& options)
{
static struct { std::string key; find::options_t flag; } const map[] =
{
{ "fullWordMatch", find::full_words },
{ "ignoreCase", find::ignore_case },
{ "ignoreWhitespace", find::ignore_whitespace },
{ "regularExpression", find::regular_expression },
{ "wrapAround", find::wrap_around },
};
find::options_t res = find::none;
for(size_t i = 0; i < sizeofA(map); ++i)
{
std::map<std::string, std::string>::const_iterator it = options.find(map[i].key);
if(it != options.end() && it->second == "1")
res = res | map[i].flag;
}
return res;
}
template <typename _OutputIter>
_OutputIter transpose_selections (buffer_t const& _buffer, ranges_t const& _selections, _OutputIter out)
{
ranges_t sel;
iterate(range, _selections)
{
size_t from = range->min().index, to = range->max().index;
if(from == to)
{
text::pos_t const& pos = _buffer.convert(from);
if(from == 0 || from == _buffer.size())
{
}
else if(pos.column == 0)
{
from = _buffer.begin(pos.line - 1);
to = pos.line+1 == _buffer.lines() ? _buffer.size() : _buffer.begin(pos.line + 1);
}
else if(from == _buffer.eol(pos.line))
{
from = _buffer.begin(pos.line);
to = pos.line+2 == _buffer.lines() ? _buffer.size() : _buffer.begin(pos.line + 2);
}
else
{
from = from - _buffer[from-1].size();
to = to + _buffer[to].size();
}
*out++ = std::make_pair(range_t(from, to), transform::transpose(_buffer.substr(from, to)));
}
else if(range->columnar) // TODO from.line != to.line
{
std::vector<std::string> strings;
std::vector<range_t> ranges;
citerate(r, dissect_columnar(_buffer, *range))
{
strings.push_back(_buffer.substr(r->min().index, r->max().index));
ranges.push_back(*r);
}
for(size_t i = 0; i < ranges.size(); ++i)
*out++ = std::make_pair(ranges[i], strings[ranges.size()-1 - i]);
}
else
{
*out++ = std::make_pair(range_t(from, to), transform::transpose(_buffer.substr(from, to)));
}
}
return out;
}
// =============================
// = Preserve Selection Helper =
// =============================
static size_t const kColumnar = 1 << 0;
static size_t const kReversed = 1 << 1;
struct preserve_selection_helper_t : callback_t
{
preserve_selection_helper_t (buffer_t& buffer, ranges_t const& marks) : _buffer(buffer)
{
iterate(range, marks)
{
if(range->empty())
{
_marks.emplace_back(range->first, mark_t::kUnpairedMark);
_marks.emplace_back(range->first, mark_t::kEndMark);
}
else
{
size_t userInfo = (range->columnar ? kColumnar : 0) | (range->last < range->first ? kReversed : 0);
_marks.emplace_back(range->min(), mark_t::kBeginMark, userInfo);
_marks.emplace_back(range->max(), mark_t::kEndMark, userInfo);
}
}
_buffer.add_callback(this);
}
~preserve_selection_helper_t ()
{
_buffer.remove_callback(this);
}
ranges_t get (bool moveToEnd)
{
ranges_t sel;
for(size_t i = 0; i < _marks.size(); i += 2)
{
ASSERT(i+1 < _marks.size() && _marks[i+1].type == mark_t::kEndMark);
if(_marks[i].type == mark_t::kUnpairedMark)
{
sel.push_back(_marks[moveToEnd ? i+1 : i].position);
}
else
{
index_t first = _marks[i].position;
index_t last = _marks[i+1].position;
bool columnar = _marks[i].user_info & kColumnar;
if(_marks[i].user_info & kReversed)
std::swap(first, last);
sel.push_back(range_t(first, last, columnar));
}
}
return sel;
}
void will_replace (size_t from, size_t to, std::string const& str)
{
iterate(mark, _marks)
{
size_t& index = mark->position.index;
if(oak::cap(from, index, to) == index)
{
if(mark->type == mark_t::kUnpairedMark || index != from && index != to)
{
index = from + str.size() - std::min(to - index, str.size());
}
else
{
index = from;
if(mark->type == mark_t::kEndMark)
index += str.size();
}
}
else if(from < index)
{
ASSERT_LT(to, index);
index = index + str.size() - (to - from);
}
}
}
private:
struct mark_t
{
index_t position;
enum mark_type { kBeginMark, kUnpairedMark, kEndMark } type;
size_t user_info;
mark_t (index_t const& position, mark_type type, size_t user_info = 0) : position(position), type(type), user_info(user_info) { }
};
buffer_t& _buffer;
std::vector<mark_t> _marks;
};
// =======================================================
// = Transform ranges in buffer, accounting for snippets =
// =======================================================
template <typename F>
std::multimap<range_t, std::string> map (ng::buffer_t const& buffer, ng::ranges_t const& selections, F op)
{
std::multimap<range_t, std::string> replacements;
citerate(range, dissect_columnar(buffer, selections))
replacements.insert(std::make_pair(*range, op(buffer.substr(range->min().index, range->max().index))));
return replacements;
}
static ranges_t replace_helper (ng::buffer_t& buffer, snippet_controller_t& snippets, std::multimap<range_t, std::string> const& replacements)
{
ranges_t res;
ssize_t adjustment = 0;
iterate(p1, replacements)
{
range_t orgRange = p1->first.sorted();
if(orgRange.first.index == orgRange.last.index && p1->second.empty())
{
res.push_back(orgRange + adjustment);
continue;
}
std::string const pad = orgRange.freehanded && orgRange.first.carry ? std::string(orgRange.first.carry, ' ') : "";
orgRange.first.carry = orgRange.last.carry = 0;
std::vector< std::pair<range_t, std::string> > const& real = snippets.replace(orgRange.first.index, orgRange.last.index, pad + p1->second);
iterate(p2, real)
{
range_t const& range = p2->first;
std::string const& str = p2->second;
size_t from = range.first.index + adjustment, to = range.last.index + adjustment;
size_t caret = buffer.replace(from, to, str);
if(range == ng::range_t(orgRange.first.index, orgRange.last.index))
res.push_back(range_t(from + pad.size(), caret, false, orgRange.freehanded, true));
adjustment += str.size() - (to - from);
}
}
return res;
}
template <typename F>
ng::ranges_t apply (ng::buffer_t& buffer, ng::ranges_t const& selections, snippet_controller_t& snippets, F op)
{
return ng::move(buffer, replace_helper(buffer, snippets, map(buffer, selections, op)), kSelectionMoveToEndOfSelection);
}
// ============
// = editor_t =
// ============
static ng::buffer_t dummy;
void editor_t::setup ()
{
set_clipboard(create_simple_clipboard());
set_find_clipboard(create_simple_clipboard());
set_replace_clipboard(create_simple_clipboard());
set_yank_clipboard(create_simple_clipboard());
}
editor_t::editor_t () : _buffer(dummy)
{
setup();
}
editor_t::editor_t (buffer_t& buffer) : _buffer(buffer)
{
setup();
}
editor_t::editor_t (document::document_ptr document) : _buffer(document->buffer()), _document(document)
{
ASSERT(document->is_open());
setup();
}
struct my_clipboard_entry_t : clipboard_t::entry_t
{
my_clipboard_entry_t (std::string const& content, std::string const& indent, bool complete, size_t fragments, bool columnar) : clipboard_t::entry_t(content)
{
if(indent != NULL_STR) _options["indent"] = indent;
if(complete) _options["complete"] = "1";
if(fragments > 1) _options["fragments"] = std::to_string(fragments);
if(columnar) _options["columnar"] = "1";
}
std::map<std::string, std::string> const& options () const { return _options; }
private:
std::map<std::string, std::string> _options;
};
clipboard_t::entry_ptr editor_t::copy (ng::buffer_t const& buffer, ng::ranges_t const& selections)
{
std::string indent = NULL_STR;
bool complete = false;
if(selections.size() == 1)
{
range_t const& sel = selections.last();
text::pos_t const& from = buffer.convert(sel.min().index);
text::pos_t const& to = buffer.convert(sel.max().index);
if(from.line != to.line)
{
if(from.column != 0)
{
std::string const& leading = buffer.substr(buffer.begin(from.line), sel.min().index);
if(text::is_blank(leading.data(), leading.data() + leading.size()))
indent = leading;
}
if(to.column != 0 && sel.max().index == buffer.eol(to.line))
complete = true;
}
}
std::vector<std::string> v;
citerate(range, dissect_columnar(buffer, selections))
v.push_back(buffer.substr(range->min().index, range->max().index));
bool columnar = selections.size() == 1 && selections.last().columnar;
return clipboard_t::entry_ptr(new my_clipboard_entry_t(text::join(v, "\n"), indent, complete, v.size(), columnar));
}
static bool suitable_for_reindent (std::string const& str)
{
return oak::contains(str.begin(), str.end(), '\n');
}
// ============
// = Snippets =
// ============
bool editor_t::disallow_tab_expansion () const
{
if(!_snippets.empty() && _snippets.current() == ranges().last() && !_snippets.in_last_placeholder() || ranges().last().unanchored)
return true;
return false;
}
ranges_t editor_t::replace (std::multimap<range_t, std::string> const& replacements, bool selectInsertions)
{
ranges_t res = replace_helper(_buffer, _snippets, replacements);
return selectInsertions ? res : ng::move(_buffer, res, kSelectionMoveToEndOfSelection);
}
ranges_t editor_t::snippet (size_t from, size_t to, std::string const& str, std::map<std::string, std::string> const& variables, bool disableIndent)
{
struct callback_t : snippet::run_command_callback_t
{
std::string run_command (std::string const& cmd, std::map<std::string, std::string> const& environment)
{
struct command_t : oak::command_t
{
void did_exit (int rc, std::string const& output, std::string const& error)
{
result = rc == 0 ? output : error;
run_loop.stop();
}
std::string result;
cf::run_loop_t run_loop;
};
command_t runner;
runner.command = cmd;
runner.environment = environment;
command::fix_shebang(&runner.command);
runner.launch();
runner.run_loop.start();
return runner.result;
}
} callback;
std::string indent = disableIndent ? "" : _buffer.substr(_buffer.begin(_buffer.convert(from).line), from);
size_t i = 0;
while(i < indent.size() && text::is_space(indent[i]))
++i;
indent.resize(i);
snippet::snippet_t const& snippet = snippet::parse(str, variables, indent, _buffer.indent(), &callback);
std::multimap<range_t, std::string> map;
map.insert(std::make_pair(range_t(from, to), snippet.text));
_snippets.push(snippet, this->replace(map, true).last());
return _snippets.current();
}
void editor_t::clear_snippets ()
{
_snippets.clear();
}
std::vector<std::string> const& editor_t::choices () const
{
return _snippets.choices();
}
std::string editor_t::placeholder_content (ng::range_t* placeholderSelection) const
{
if(_snippets.empty())
return NULL_STR;
ng::range_t range = _snippets.current();
iterate(r, _selections)
{
if(placeholderSelection && range.min() <= r->min() && r->max() <= range.max())
*placeholderSelection = ng::range_t(r->min().index - range.min().index, r->max().index - range.min().index);
}
return _buffer.substr(range.min().index, range.max().index);
}
void editor_t::set_placeholder_content (std::string const& str, size_t selectFrom)
{
std::multimap<range_t, std::string> map;
map.insert(std::make_pair(_snippets.current(), str));
ng::ranges_t res = this->replace(map, true);
iterate(range, res)
range->min().index += selectFrom;
_selections = res;
}
// ============
ng::ranges_t editor_t::paste (ng::buffer_t& buffer, ng::ranges_t const& selections, snippet_controller_t& snippets, clipboard_t::entry_ptr entry)
{
if(!entry)
return selections;
std::string str = entry->content();
std::map<std::string, std::string> options = entry->options();
std::replace(str.begin(), str.end(), '\r', '\n');
std::string const& indent = options["indent"];
bool const complete = options["complete"] == "1";
size_t const fragments = strtol(options["fragments"].c_str(), NULL, 10);
bool const columnar = options["columnar"] == "1";
if((selections.size() != 1 || selections.last().columnar) && (fragments > 1 || oak::contains(str.begin(), str.end(), '\n')))
{
std::vector<std::string> words = text::split(str, "\n");
if(words.size() > 1 && words.back().empty())
words.pop_back();
size_t i = 0;
std::multimap<range_t, std::string> insertions;
citerate(range, dissect_columnar(buffer, selections))
insertions.insert(std::make_pair(*range, words[i++ % words.size()]));
return ng::move(buffer, replace_helper(buffer, snippets, insertions), kSelectionMoveToEndOfSelection);
}
if(fragments > 1 && selections.size() == 1)
{
ASSERT(fragments == std::count(str.begin(), str.end(), '\n') + 1);
if(columnar)
{
index_t caret = dissect_columnar(buffer, selections).last().min();
size_t n = buffer.convert(caret.index).line;
size_t col = visual_distance(buffer, buffer.begin(n), caret);
std::multimap<range_t, std::string> insertions;
citerate(line, text::tokenize(str.begin(), str.end(), '\n'))
{
if(n+1 < buffer.lines())
{
insertions.insert(std::make_pair(visual_advance(buffer, buffer.begin(n), col), *line));
}
else if(n < buffer.lines())
{
// we special-case this to ensure we do not insert at last line with carry, as that will cause potential following insertions to have a lower index, since those will be at EOB w/o a carry
index_t pos = visual_advance(buffer, buffer.begin(n), col);
insertions.insert(std::make_pair(index_t(pos.index), std::string(pos.carry, ' ') + *line));
}
else
{
insertions.insert(std::make_pair(index_t(buffer.size()), "\n" + std::string(col, ' ') + *line));
}
++n;
}
return ng::move(buffer, replace_helper(buffer, snippets, insertions), kSelectionMoveToEndOfSelection).first();
}
else
{
std::multimap<range_t, std::string> insertions;
ng::range_t caret = dissect_columnar(buffer, selections).last();
citerate(line, text::tokenize(str.begin(), str.end(), '\n'))
{
insertions.insert(std::make_pair(caret, *line));
caret = caret.max();
}
return ng::move(buffer, replace_helper(buffer, snippets, insertions), kSelectionMoveToEndOfSelection);
}
}
if(selections.size() == 1 && suitable_for_reindent(str))
{
size_t const index = selections.last().min().index;
size_t const line = buffer.convert(index).line;
std::string const& leftOfCaret = buffer.substr(buffer.begin(line), index);
if(text::is_blank(leftOfCaret.data(), leftOfCaret.data() + leftOfCaret.size()))
{
size_t const tabSize = buffer.indent().tab_size();
size_t const indentSize = buffer.indent().indent_size();
if(indent != NULL_STR)
str = indent + str;
if(complete)
{
std::string const& rightOfCaret = buffer.substr(index, buffer.eol(line));
if(!text::is_blank(rightOfCaret.data(), rightOfCaret.data() + rightOfCaret.size()))
str += '\n';
}
int minIndent = INT_MAX;
std::vector< std::pair<char const*, char const*> > const& v = text::to_lines(str.data(), str.data() + str.size());
iterate(it, v)
{
if(!text::is_blank(it->first, it->second))
minIndent = std::min(indent::leading_whitespace(it->first, it->second, tabSize), minIndent);
}
plist::any_t pasteBehaviorValue = bundles::value_for_setting("indentOnPaste", buffer.scope(index));
std::string const* pasteBehavior = boost::get<std::string>(&pasteBehaviorValue);
if(pasteBehavior && *pasteBehavior == "simple")
{
int currentIndent = indent::leading_whitespace(leftOfCaret.data(), leftOfCaret.data() + leftOfCaret.size(), tabSize);
if(currentIndent)
{
str = transform::shift(currentIndent-minIndent, buffer.indent())(str);
size_t len = str.size();
while(len > 0 && (str[len-1] == '\t' || str[len-1] == ' '))
--len;
str = str.substr(0, len);
if(!str.empty() && str[str.size()-1] == '\n')
str += leftOfCaret;
}
}
else if(!pasteBehavior || *pasteBehavior != "disable")
{
indent::fsm_t fsm = indent::create_fsm(buffer, line, indentSize, tabSize);
auto const patterns = indent::patterns_for_scope(buffer.scope(index));
iterate(it, v)
{
if(fsm.is_ignored(std::string(it->first, it->second), patterns))
continue;
size_t indent = fsm.scan_line(std::string(it->first, it->second), patterns);
int oldIndent = indent::leading_whitespace(it->first, it->second, tabSize);
transform::shift shifter(std::max(((int)indent)-oldIndent, -minIndent), buffer.indent());
str = shifter(str);
break;
}
if(!str.empty() && str[str.size()-1] == '\n')
str += leftOfCaret;
}
return ng::move(buffer, replace_helper(buffer, snippets, map(buffer, range_t(buffer.begin(line), selections.last().max()), transform::replace(str))), kSelectionMoveToEndOfSelection);
}
}
return ng::move(buffer, replace_helper(buffer, snippets, map(buffer, selections, transform::replace(str))), kSelectionMoveToEndOfSelection);
}
void editor_t::insert (std::string const& str, bool selectInsertion)
{
ng::ranges_t res = replace_helper(_buffer, _snippets, map(_buffer, _selections, transform::replace(str)));
_selections = selectInsertion ? res : ng::move(_buffer, res, kSelectionMoveToEndOfSelection);
}
struct indent_helper_t : ng::callback_t
{
indent_helper_t (editor_t& editor, buffer_t& buffer, bool indentCorrections) : _disabled(!indentCorrections), _editor(editor), _buffer(buffer)
{
_disabled = _disabled || editor._selections.size() != 1 || editor._selections.last().columnar;
if(_disabled)
return;
_buffer.add_callback(this);
}
void will_replace (size_t from, size_t to, std::string const& str)
{
text::pos_t pos = _buffer.convert(from);
indent::fsm_t fsm = indent::create_fsm(_buffer, pos.line, _buffer.indent().indent_size(), _buffer.indent().tab_size());
std::string const line = _buffer.substr(_buffer.begin(pos.line), _buffer.eol(pos.line));
bool ignored = fsm.is_ignored(line, indent::patterns_for_line(_buffer, pos.line));
int actual = indent::leading_whitespace(line.data(), line.data() + line.size(), _buffer.indent().tab_size());
size_t desired = fsm.scan_line(line, indent::patterns_for_line(_buffer, pos.line));
if(ignored || actual == desired)
_lines.insert(std::make_pair(pos.line, actual));
}
~indent_helper_t ()
{
if(_disabled)
return;
_buffer.remove_callback(this);
std::multimap<range_t, std::string> replacements;
iterate(pair, _lines)
{
size_t n = pair->first;
size_t bol = _buffer.begin(n);
size_t eos = bol;
std::string const line = _buffer.substr(bol, _buffer.eol(n));
int actual = indent::leading_whitespace(line.data(), line.data() + line.size(), _buffer.indent().tab_size());
if(actual != pair->second)
continue;
indent::fsm_t fsm = indent::create_fsm(_buffer, n, _buffer.indent().indent_size(), _buffer.indent().tab_size());
auto const patterns = indent::patterns_for_line(_buffer, n);
size_t desired = fsm.scan_line(line, patterns);
if(!fsm.is_ignored(line, patterns) && desired != actual)
{
while(eos != _buffer.size() && text::is_whitespace(_buffer[eos]))
eos += _buffer[eos].size();
replacements.insert(std::make_pair(range_t(bol, eos), indent::create(desired, _buffer.indent().tab_size(), _buffer.indent().soft_tabs())));
}
}
if(!replacements.empty())
{
preserve_selection_helper_t helper(_buffer, _editor._selections);
_editor.replace(replacements);
_editor._selections = helper.get(false);
}
}
private:
bool _disabled;
editor_t& _editor;
buffer_t& _buffer;
std::map<size_t, int> _lines;
};
static std::string find_paired (std::string const& str, scope::context_t const& scope)
{
plist::any_t typingPairs = bundles::value_for_setting("smartTypingPairs", scope);
if(plist::array_t const* typingPairsArray = boost::get<plist::array_t>(&typingPairs))
{
iterate(pair, *typingPairsArray)
{
if(plist::array_t const* pairArray = boost::get<plist::array_t>(&*pair))
{
if(pairArray->size() == 2)
{
std::string const* left = boost::get<std::string>(&(*pairArray)[0]);
std::string const* right = boost::get<std::string>(&(*pairArray)[1]);
if(left && *left == str && right)
return *right;
}
}
}
}
return NULL_STR;
}
void editor_t::insert_with_pairing (std::string const& str, bool indentCorrections, std::string const& scopeAttributes)
{
if(!has_selection())
{
size_t const caret = _selections.last().last.index;
if(_buffer.pairs().is_last(caret) && caret + str.size() <= _buffer.size() && str == _buffer.substr(caret, caret + str.size()))
{
_selections = ng::move(_buffer, _selections, kSelectionMoveRight);
_buffer.pairs().remove(caret);
return;
}
}
indent_helper_t indent_helper(*this, _buffer, indentCorrections);
std::string const autoInsert = find_paired(str, scope(scopeAttributes));
if(autoInsert != NULL_STR && has_selection())
{
_selections = replace_helper(_buffer, _snippets, map(_buffer, _selections, transform::surround(str, autoInsert)));
}
else if(autoInsert == NULL_STR || has_selection() || _selections.size() != 1 || _selections.last().columnar || (_selections.last().min().index < _buffer.size() && text::is_word_char(_buffer[_selections.last().min().index])))
{
insert(str);
}
else
{
if(str == autoInsert && str.size() == 1)
{
size_t const lineNo = _buffer.convert(_selections.last().last.index).line;
std::string line = _buffer.substr(_buffer.begin(lineNo), _buffer.eol(lineNo));
if(std::count(line.begin(), line.end(), str[0]) % 2 == 1)
return insert(str);
}
insert(str + autoInsert);
_selections = ng::move(_buffer, _selections, kSelectionMoveLeft);
size_t const caret = _selections.last().last.index;
_buffer.pairs().add_pair(caret - str.size(), caret);
}
}
void editor_t::move_selection_to (ng::index_t const& index, bool selectInsertion)
{
std::vector<std::string> v;
std::multimap<range_t, std::string> insertions;
citerate(range, dissect_columnar(_buffer, _selections))
{
v.push_back(_buffer.substr(range->min().index, range->max().index));
insertions.insert(std::make_pair(*range, ""));
}
insertions.insert(std::make_pair(index, text::join(v, "\n")));
ranges_t sel, tmp = this->replace(insertions, selectInsertion);
iterate(range, tmp)
{
if(!range->empty())
sel.push_back(*range);
}
_selections = tmp.empty() ? tmp : sel;
}
void editor_t::snippet (std::string const& str, std::map<std::string, std::string> const& variables, bool disableIndent)
{
size_t from = _selections.last().min().index;
size_t to = _selections.last().max().index;
_selections = this->snippet(from, to, str, variables, disableIndent);
}
void editor_t::perform (action_t action, layout_t const* layout, bool indentCorrections, std::string const& scopeAttributes)
{
static std::string const kSingleMarkType = "•";
preserve_selection_helper_t selectionHelper(_buffer, _selections);
if(action == kDeleteBackward && !has_selection() && _selections.size() == 1)
{
size_t caret = _selections.last().last.index;
size_t from = caret - (0 < caret ? _buffer[caret-1].size() : 0);
if(caret && _buffer.pairs().is_first(from))
{
size_t other = _buffer.pairs().counterpart(from);
size_t to = other + _buffer[other].size();
if(other == caret)
{
_selections = range_t(from, to);
action = kDeleteSelection;
}
else
{
std::multimap<range_t, std::string> insertions;
insertions.insert(std::make_pair(range_t(from, caret), ""));
insertions.insert(std::make_pair(range_t(other, to), ""));
_selections = this->replace(insertions).first();
action = kNop;
}
}
}
switch(action)
{
case kDeleteBackward: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendLeft, layout); break;
case kDeleteBackwardByDecomposingPreviousCharacter: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendLeft, layout); break;
case kDeleteForward: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendRight, layout); break;
case kDeleteSubWordLeft: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToBeginOfSubWord, layout); break;
case kDeleteSubWordRight: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToEndOfSubWord, layout); break;
case kDeleteWordBackward: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToBeginOfWord, layout); break;
case kDeleteWordForward: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToEndOfWord, layout); break;
case kDeleteToBeginningOfIndentedLine: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToBeginOfIndentedLine, layout); break;
case kDeleteToEndOfIndentedLine: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToEndOfIndentedLine, layout); break;
case kDeleteToBeginningOfLine: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToBeginOfSoftLine, layout); break;
case kDeleteToEndOfLine: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToEndOfSoftLine, layout); break;
case kDeleteToBeginningOfParagraph: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToBeginOfParagraph, layout); break;
case kDeleteToEndOfParagraph: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToEndOfParagraph, layout); break;
case kChangeCaseOfWord: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToEndOfWord, layout); break;
case kChangeCaseOfLetter: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendRight, layout); break;
case kUppercaseWord: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToWord, layout); break;
case kLowercaseWord: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToWord, layout); break;
case kCapitalizeWord: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToLineExclLF, layout); break;
case kReformatText: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToParagraph, layout); break;
case kReformatTextAndJustify: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToParagraph, layout); break;
case kUnwrapText: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToParagraph, layout); break;
case kMoveSelectionUp: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToLine, layout); break;
case kMoveSelectionDown: _selections = ng::extend_if_empty(_buffer, _selections, kSelectionExtendToLine, layout); break;
case kShiftLeft: _selections = ng::extend(_buffer, _selections, kSelectionExtendToLineExclLF, layout); break;
case kShiftRight: _selections = ng::extend(_buffer, _selections, kSelectionExtendToLineExclLF, layout); break;
}
static std::set<action_t> const deleteActions = { kDeleteBackward, kDeleteForward };
static std::set<action_t> const yankAppendActions = { kDeleteSubWordRight, kDeleteWordForward, kDeleteToEndOfIndentedLine, kDeleteToEndOfLine, kDeleteToEndOfParagraph };
static std::set<action_t> const yankPrependActions = { kDeleteSubWordLeft, kDeleteWordBackward, kDeleteToBeginningOfIndentedLine, kDeleteToBeginningOfLine, kDeleteToBeginningOfParagraph };
if(deleteActions.find(action) != deleteActions.end())
action = kDeleteSelection;
else if(yankAppendActions.find(action) != yankAppendActions.end())
action = _extend_yank_clipboard ? kAppendSelectionToYankPboard : kCopySelectionToYankPboard;
else if(yankPrependActions.find(action) != yankPrependActions.end())
action = _extend_yank_clipboard ? kPrependSelectionToYankPboard : kCopySelectionToYankPboard;
_extend_yank_clipboard = false;
switch(action)
{
case kMoveBackward: _selections = ng::move(_buffer, _selections, kSelectionMoveLeft, layout); break;
case kMoveForward: _selections = ng::move(_buffer, _selections, kSelectionMoveRight, layout); break;
case kMoveUp: _selections = ng::move(_buffer, _selections, kSelectionMoveUp, layout); break;
case kMoveDown: _selections = ng::move(_buffer, _selections, kSelectionMoveDown, layout); break;
case kMoveSubWordLeft: _selections = ng::move(_buffer, _selections, kSelectionMoveToBeginOfSubWord, layout); break;
case kMoveSubWordRight: _selections = ng::move(_buffer, _selections, kSelectionMoveToEndOfSubWord, layout); break;
case kMoveWordBackward: _selections = ng::move(_buffer, _selections, kSelectionMoveToBeginOfWord, layout); break;
case kMoveWordForward: _selections = ng::move(_buffer, _selections, kSelectionMoveToEndOfWord, layout); break;
case kMoveToBeginningOfIndentedLine: _selections = ng::move(_buffer, _selections, kSelectionMoveToBeginOfIndentedLine, layout); break;
case kMoveToEndOfIndentedLine: _selections = ng::move(_buffer, _selections, kSelectionMoveToEndOfIndentedLine, layout); break;
case kMoveToBeginningOfLine: _selections = ng::move(_buffer, _selections, kSelectionMoveToBeginOfSoftLine, layout); break;
case kMoveToEndOfLine: _selections = ng::move(_buffer, _selections, kSelectionMoveToEndOfSoftLine, layout); break;
case kMoveToBeginningOfParagraph: _selections = ng::move(_buffer, _selections, kSelectionMoveToBeginOfLine, layout); break;
case kMoveToEndOfParagraph: _selections = ng::move(_buffer, _selections, kSelectionMoveToEndOfLine, layout); break;
case kMoveToBeginningOfBlock: _selections = ng::move(_buffer, _selections, kSelectionMoveToBeginOfTypingPair, layout); break;
case kMoveToEndOfBlock: _selections = ng::move(_buffer, _selections, kSelectionMoveToEndOfTypingPair, layout); break;
case kMoveToBeginningOfColumn: _selections = ng::move(_buffer, _selections, kSelectionMoveToBeginOfColumn, layout); break;
case kMoveToEndOfColumn: _selections = ng::move(_buffer, _selections, kSelectionMoveToEndOfColumn, layout); break;
case kMoveToBeginningOfDocument: _selections = ng::move(_buffer, _selections, kSelectionMoveToBeginOfDocument, layout); break;
case kMoveToEndOfDocument: _selections = ng::move(_buffer, _selections, kSelectionMoveToEndOfDocument, layout); break;
case kPageUp: _selections = ng::move(_buffer, _selections, kSelectionMovePageUp, layout); break;
case kPageDown: _selections = ng::move(_buffer, _selections, kSelectionMovePageDown, layout); break;
case kMoveBackwardAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendLeft, layout); break;
case kMoveForwardAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendRight, layout); break;
case kMoveUpAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendUp, layout); break;
case kMoveDownAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendDown, layout); break;
case kMoveSubWordLeftAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToBeginOfSubWord, layout); break;
case kMoveSubWordRightAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToEndOfSubWord, layout); break;
case kMoveWordBackwardAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToBeginOfWord, layout); break;
case kMoveWordForwardAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToEndOfWord, layout); break;
case kMoveToBeginningOfIndentedLineAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToBeginOfIndentedLine, layout); break;
case kMoveToEndOfIndentedLineAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToEndOfIndentedLine, layout); break;
case kMoveToBeginningOfLineAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToBeginOfSoftLine, layout); break;
case kMoveToEndOfLineAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToEndOfSoftLine, layout); break;
case kMoveToBeginningOfParagraphAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToBeginOfParagraph, layout); break;
case kMoveToEndOfParagraphAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToEndOfParagraph, layout); break;
case kMoveParagraphBackwardAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToBeginOfLine, layout); break;
case kMoveParagraphForwardAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToEndOfLine, layout); break;
case kMoveToBeginningOfBlockAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToBeginOfTypingPair, layout); break;
case kMoveToEndOfBlockAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToEndOfTypingPair, layout); break;
case kMoveToBeginningOfColumnAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToBeginOfColumn, layout); break;
case kMoveToEndOfColumnAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToEndOfColumn, layout); break;
case kMoveToBeginningOfDocumentAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToBeginOfDocument, layout); break;
case kMoveToEndOfDocumentAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendToEndOfDocument, layout); break;
case kPageUpAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendPageUp, layout); break;
case kPageDownAndModifySelection: _selections = ng::extend(_buffer, _selections, kSelectionExtendPageDown, layout); break;
case kSelectAll: _selections = ng::extend(_buffer, _selections, kSelectionExtendToAll, layout); break;
case kSelectCurrentScope: _selections = ng::extend(_buffer, _selections, kSelectionExtendToScope, layout); break;
case kSelectBlock: _selections = ng::extend(_buffer, _selections, kSelectionExtendToTypingPair, layout); break;
case kSelectHardLine: _selections = ng::extend(_buffer, _selections, kSelectionExtendToLine, layout); break;
case kSelectLine: _selections = ng::extend(_buffer, _selections, kSelectionExtendToSoftLine, layout); break;
case kSelectParagraph: _selections = ng::extend(_buffer, _selections, kSelectionExtendToParagraph, layout); break;
case kSelectWord: _selections = ng::extend(_buffer, _selections, kSelectionExtendToWord, layout); break;
case kToggleColumnSelection: _selections = ng::toggle_columnar(_selections); break;
case kFindNext:
case kFindPrevious:
case kFindNextAndModifySelection:
case kFindPreviousAndModifySelection:
case kFindAll:
case kFindAllInSelection:
{
if(clipboard_t::entry_ptr findEntry = find_clipboard()->current())
{
find::options_t options = convert(findEntry->options());
if(action == kFindNextAndModifySelection || action == kFindPreviousAndModifySelection)
options = options | find::extend_selection;
if(action == kFindPrevious || action == kFindPreviousAndModifySelection)
options = options | find::backwards;
else if(action == kFindAll || action == kFindAllInSelection)
options = options | find::all_matches;
find(findEntry->content(), options, (action == kFindAll || action == kFindAllInSelection) && has_selection());
}
}
break;
case kReplaceAll:
case kReplaceAllInSelection:
{
clipboard_t::entry_ptr findEntry = find_clipboard()->current();
clipboard_t::entry_ptr replaceEntry = replace_clipboard()->current();
if(findEntry && replaceEntry)
{
find::options_t options = convert(findEntry->options());
if(action == kReplaceAll || action == kReplaceAllInSelection)
options = options | find::all_matches;
replace_all(findEntry->content(), replaceEntry->content(), options, action == kReplaceAllInSelection);
}
}
break;
case kReplace:
case kReplaceAndFind:
{
if(action == kReplace)
{
/* TODO Implement ‘Replace’ (after find) action */
}
perform(kFindNext, layout, indentCorrections, scopeAttributes);
}
break;
case kCopySelectionToYankPboard:
case kAppendSelectionToYankPboard:
case kPrependSelectionToYankPboard:
{
clipboard_t::entry_ptr entry = copy(_buffer, _selections);
if(action != kCopySelectionToYankPboard && !yank_clipboard()->empty())
{
if(clipboard_t::entry_ptr oldEntry = yank_clipboard()->current())
{
if(action == kAppendSelectionToYankPboard)
entry.reset(new my_clipboard_entry_t(oldEntry->content() + entry->content(), "", false, 1, false));
else if(action == kPrependSelectionToYankPboard)
entry.reset(new my_clipboard_entry_t(entry->content() + oldEntry->content(), "", false, 1, false));
}
}
yank_clipboard()->push_back(entry);
_extend_yank_clipboard = true;
}
// continue
case kDeleteSelection:
{
indent_helper_t indent_helper(*this, _buffer, indentCorrections);
_selections = apply(_buffer, _selections, _snippets, &transform::null);
}
break;
case kDeleteBackwardByDecomposingPreviousCharacter: _selections = apply(_buffer, _selections, _snippets, &transform::decompose); break;
case kSetMark:
{
_buffer.remove_all_marks(kSingleMarkType);
_buffer.set_mark(_selections.last().last.index, kSingleMarkType);
}
break;
case kDeleteToMark:
{
std::map<size_t, std::string> const& marks = _buffer.get_marks(0, _buffer.size(), kSingleMarkType);
if(marks.size() == 1)
{
std::multimap<range_t, std::string> replacements;
replacements.insert(std::make_pair(range_t(_selections.last().last, marks.begin()->first), ""));
_selections = this->replace(replacements);
}
}
break;
case kSelectToMark:
{
std::map<size_t, std::string> const& marks = _buffer.get_marks(0, _buffer.size(), kSingleMarkType);
if(marks.size() == 1)
_selections = ng::range_t(_selections.last().last, marks.begin()->first);
}
break;
case kSwapWithMark:
{
std::map<size_t, std::string> marks = _buffer.get_marks(0, _buffer.size(), kSingleMarkType);
if(marks.size() == 1)
{
_buffer.remove_all_marks(kSingleMarkType);
_buffer.set_mark(_selections.last().last.index, kSingleMarkType);
_selections = ng::index_t(marks.begin()->first);
}
}
break;
case kCut: clipboard()->push_back(copy(_buffer, _selections)); _selections = apply(_buffer, _selections, _snippets, &transform::null); break;
case kCopy: clipboard()->push_back(copy(_buffer, _selections)); break;
case kCopySelectionToFindPboard: find_clipboard()->push_back(copy(_buffer, dissect_columnar(_buffer, _selections).first())); break;
case kCopySelectionToReplacePboard: replace_clipboard()->push_back(copy(_buffer, dissect_columnar(_buffer, _selections).first())); break;
case kPaste: _selections = paste(_buffer, _selections, _snippets, clipboard()->current()); break;
case kPastePrevious: _selections = paste(_buffer, _selections, _snippets, clipboard()->previous()); break;
case kPasteNext: _selections = paste(_buffer, _selections, _snippets, clipboard()->next()); break;
case kPasteWithoutReindent: insert(clipboard()->current()->content()); break;
case kYank:
{
if(clipboard_t::entry_ptr entry = yank_clipboard()->current())
insert(entry->content());
}
break;
case kInsertTab:
{
_snippets.drop_for_pos(_selections.last().last.index);
if(_snippets.next())
_selections = _snippets.current();
else _selections = insert_tab_with_indent(_buffer, _selections, _snippets);
}
break;
case kInsertBacktab:
{
_snippets.drop_for_pos(_selections.last().last.index);
if(_snippets.previous())
_selections = _snippets.current();
}
break;
case kInsertTabIgnoringFieldEditor: insert("\t"); break;
case kInsertNewline: _selections = insert_newline_with_indent(_buffer, _selections, _snippets); break;
case kInsertNewlineIgnoringFieldEditor: insert("\n"); break;
case kTranspose:
{
std::multimap<range_t, std::string> replacements;
auto inserter = std::inserter(replacements, replacements.end());
if(_selections.size() > 1 && not_empty(_buffer, _selections))
{
std::multiset<range_t> ranges(_selections.begin(), _selections.end());
std::vector<std::string> strings;
std::transform(ranges.begin(), ranges.end(), back_inserter(strings), [this](range_t const& r){ return _buffer.substr(r.min().index, r.max().index); });
std::next_permutation(strings.begin(), strings.end());
std::transform(ranges.begin(), ranges.end(), strings.begin(), inserter, [](range_t const& r, std::string const& str){ return std::make_pair(r, str); });
}
else
{
transpose_selections(_buffer, _selections, inserter);
}
_selections = this->replace(replacements, not_empty(_buffer, _selections));
}
break;
case kTransposeWords:
break;
case kIndent:
{
range_t r = _selections.last();
text::pos_t p0 = _buffer.convert(r.first.index);
text::pos_t p1 = _buffer.convert(r.last.index);
if(p1 < p0)
std::swap(p0, p1);
size_t from = p0.line;
size_t to = p1.line + (p1.column != 0 || p0.line == p1.line ? 1 : 0);
indent::fsm_t fsm = indent::create_fsm(_buffer, from, _buffer.indent().indent_size(), _buffer.indent().tab_size());
std::multimap<range_t, std::string> replacements;
for(size_t n = from; n < to; ++n)
{
size_t bol = _buffer.begin(n);
size_t eos = bol;
std::string const line = _buffer.substr(bol, _buffer.eol(n));
if(text::is_blank(line.data(), line.data() + line.size()))
continue;
while(eos != _buffer.size() && text::is_whitespace(_buffer[eos]))
eos += _buffer[eos].size();
replacements.insert(std::make_pair(range_t(bol, eos), indent::create(fsm.scan_line(line, indent::patterns_for_line(_buffer, n)), _buffer.indent().tab_size(), _buffer.indent().soft_tabs())));
}
if(!replacements.empty())
_selections = this->replace(replacements);
}
break;
case kShiftLeft: _selections = apply(_buffer, _selections, _snippets, transform::shift(-_buffer.indent().indent_size(), _buffer.indent())); break;
case kShiftRight: _selections = apply(_buffer, _selections, _snippets, transform::shift(+_buffer.indent().indent_size(), _buffer.indent())); break;
case kChangeCaseOfWord: _selections = apply(_buffer, _selections, _snippets, &text::opposite_case); break;
case kChangeCaseOfLetter: _selections = apply(_buffer, _selections, _snippets, &text::opposite_case); break;
case kUppercaseWord: _selections = apply(_buffer, _selections, _snippets, &text::uppercase); break;
case kLowercaseWord: _selections = apply(_buffer, _selections, _snippets, &text::lowercase); break;
case kCapitalizeWord: _selections = apply(_buffer, _selections, _snippets, &transform::capitalize); break;
case kReformatText:
case kReformatTextAndJustify:
{
size_t wrapColumn = layout ? layout->effective_wrap_column() : 80;
if(_selections.last().columnar)
{
text::pos_t const& fromPos = _buffer.convert(_selections.last().min().index);
text::pos_t const& toPos = _buffer.convert(_selections.last().max().index);
size_t fromCol = visual_distance(_buffer, _buffer.begin(fromPos.line), _selections.last().min());
size_t toCol = visual_distance(_buffer, _buffer.begin(toPos.line), _selections.last().max());
if(toCol < fromCol)
std::swap(fromCol, toCol);
else if(fromCol == toCol && toCol != 0)
fromCol = 0;
else if(fromCol == toCol)
toCol = std::max(fromCol + 10, wrapColumn);
size_t const from = _buffer.begin(fromPos.line);
size_t const to = _buffer.eol(toPos.line);
std::string str = _buffer.substr(from, to);
str = text::trim(str);
str = transform::unwrap(str);
if(action == kReformatTextAndJustify)
str = transform::justify(toCol - fromCol, _buffer.indent().tab_size(), false)(str);
else str = transform::reformat(toCol - fromCol, _buffer.indent().tab_size(), false)(str);
str = transform::shift(fromCol, text::indent_t(8, 8, true))(str);
std::multimap<range_t, std::string> replacements;
replacements.insert(std::make_pair(range_t(from, to), str));
ng::range_t range = this->replace(replacements, true).first();
_selections = range_t(visual_advance(_buffer, _buffer.begin(_buffer.convert(range.min().index).line), fromCol), visual_advance(_buffer, _buffer.begin(_buffer.convert(range.max().index).line), toCol), true);
action = kNop; // skip selection preserving
}
else
{
if(action == kReformatTextAndJustify)
_selections = apply(_buffer, _selections, _snippets, transform::justify(wrapColumn, _buffer.indent().tab_size()));
else _selections = apply(_buffer, _selections, _snippets, transform::reformat(wrapColumn, _buffer.indent().tab_size()));
}
}
break;
case kUnwrapText: _selections = apply(_buffer, _selections, _snippets, &transform::unwrap); break;
case kComplete:
case kNextCompletion: next_completion(scopeAttributes); break;
case kPreviousCompletion: previous_completion(scopeAttributes); break;
case kMoveSelectionUp: move_selection( 0, -1); break;
case kMoveSelectionDown: move_selection( 0, +1); break;
case kMoveSelectionLeft: move_selection(-1, 0); break;
case kMoveSelectionRight: move_selection(+1, 0); break;
}
static std::set<action_t> const preserveSelectionActions = { kCapitalizeWord, kUppercaseWord, kLowercaseWord, kChangeCaseOfLetter, kIndent, kShiftLeft, kShiftRight, kReformatText, kReformatTextAndJustify, kUnwrapText };
if(preserveSelectionActions.find(action) != preserveSelectionActions.end())
_selections = selectionHelper.get(action == kChangeCaseOfLetter || action == kChangeCaseOfWord);
}
void editor_t::perform_replacements (std::multimap<text::range_t, std::string> const& replacements)
{
std::multimap<range_t, std::string> tmp;
riterate(pair, replacements)
{
// D(DBF_Editor, bug("replace %s with ‘%s’\n", std::string(pair->first).c_str(), pair->second.c_str()););
size_t from = _buffer.convert(pair->first.min());
size_t to = _buffer.convert(pair->first.max());
tmp.insert(std::make_pair(range_t(from, to), pair->second));
}
_selections = this->replace(tmp);
}
ng::ranges_t editor_t::insert_tab_with_indent (ng::buffer_t& buffer, ng::ranges_t const& selections, snippet_controller_t& snippets)
{
std::string estimatedIndent = NULL_STR;
std::multimap<range_t, std::string> insertions;
citerate(range, dissect_columnar(buffer, selections))
{
size_t const from = range->min().index;
size_t const firstLine = buffer.convert(from).line;
std::string const& leftOfCaret = buffer.substr(buffer.begin(firstLine), from);
if(!text::is_blank(leftOfCaret.data(), leftOfCaret.data() + leftOfCaret.size()))
{
size_t col = visual_distance(buffer, buffer.begin(firstLine), from);
insertions.insert(std::make_pair(*range, buffer.indent().create(col)));
}
else
{
size_t to = range->max().index;
if(estimatedIndent == NULL_STR)
{
size_t const lastLine = buffer.convert(to).line;
std::string const& rightOfCaret = buffer.substr(to, buffer.end(lastLine));
indent::fsm_t fsm = indent::create_fsm(buffer, firstLine, buffer.indent().indent_size(), buffer.indent().tab_size());
std::string const& line = leftOfCaret + rightOfCaret;
size_t existingIndent = indent::leading_whitespace(line.data(), line.data() + line.size(), buffer.indent().tab_size());
size_t newIndent = std::max(fsm.scan_line(line, indent::patterns_for_line(buffer, firstLine)), existingIndent + buffer.indent().indent_size());
estimatedIndent = indent::create(newIndent - indent::leading_whitespace(leftOfCaret.data(), leftOfCaret.data() + leftOfCaret.size(), buffer.indent().tab_size()), buffer.indent().tab_size(), buffer.indent().soft_tabs());
}
while(to != buffer.size() && text::is_whitespace(buffer[to]))
to += buffer[to].size();
insertions.insert(std::make_pair(ng::range_t(from, to), estimatedIndent));
}
}
return ng::move(buffer, replace_helper(buffer, snippets, insertions), kSelectionMoveToEndOfSelection);
}
ng::ranges_t editor_t::insert_newline_with_indent (ng::buffer_t& buffer, ng::ranges_t const& selections, snippet_controller_t& snippets)
{
std::multimap<range_t, std::string> insertions;
citerate(range, dissect_columnar(buffer, selections))
{
size_t const from = range->min().index;
size_t const firstLine = buffer.convert(from).line;
std::string const& leftOfCaret = buffer.substr(buffer.begin(firstLine), from);
auto const patterns = indent::patterns_for_line(buffer, firstLine);
size_t to = range->max().index;
size_t const lastLine = buffer.convert(to).line;
std::string const& rightOfCaret = buffer.substr(to, buffer.end(lastLine));
indent::fsm_t fsm(buffer.indent().indent_size(), buffer.indent().tab_size());
if(!fsm.is_seeded(leftOfCaret, patterns))
{
size_t n = firstLine;
while(n-- > 0 && !fsm.is_seeded(indent::line(buffer, n), indent::patterns_for_line(buffer, n)))
continue;
}
size_t existingIndent = indent::leading_whitespace(rightOfCaret.data(), rightOfCaret.data() + rightOfCaret.size(), buffer.indent().tab_size());
size_t newIndent = fsm.scan_line(rightOfCaret, patterns);
if(text::is_blank(leftOfCaret.data(), leftOfCaret.data() + leftOfCaret.size()))
newIndent = indent::leading_whitespace(leftOfCaret.data(), leftOfCaret.data() + leftOfCaret.size(), buffer.indent().tab_size()) + existingIndent;
else existingIndent = 0;
insertions.insert(std::make_pair(*range, existingIndent < newIndent ? "\n" + indent::create(newIndent - existingIndent, buffer.indent().tab_size(), buffer.indent().soft_tabs()) : "\n"));
}
return ng::move(buffer, replace_helper(buffer, snippets, insertions), kSelectionMoveToEndOfSelection);
}
void editor_t::move_selection (int deltaX, int deltaY)
{
ssize_t adjustment = 0;
std::map<size_t, std::string> clips;
citerate(range, dissect_columnar(_buffer, _selections).sorted())
{
range_t r = *range + adjustment;
std::string const& str = _buffer.substr(r.min().index, r.max().index);
std::multimap<range_t, std::string> replacements;
replacements.insert(std::make_pair(r, ""));
ranges_t res = this->replace(replacements);
clips.insert(std::make_pair(res.first().first.index, str));
adjustment -= str.size();
}
std::multimap<range_t, std::string> replacements;
iterate(pair, clips)
{
text::pos_t pos = _buffer.convert(pair->first);
int line = pos.line;
int col = visual_distance(_buffer, _buffer.begin(line), pair->first, false);
line = oak::cap(0, line + deltaY, int(_buffer.lines()-1));
col = std::max(col + deltaX, 0);
replacements.insert(std::make_pair(visual_advance(_buffer, _buffer.begin(line), col, false), pair->second));
}
_selections = this->replace(replacements, true);
}
bool editor_t::handle_result (std::string const& out, output::type placement, output_format::type format, output_caret::type outputCaret, text::range_t input_range, std::map<std::string, std::string> environment)
{
range_t range;
switch(placement)
{
case output::replace_input: range = range_t(_buffer.convert(input_range.min()), _buffer.convert(input_range.max())); break;
case output::replace_document: range = range_t(0, _buffer.size()); break;
case output::at_caret: range = _selections.last().last; break;
case output::after_input: range = range_t(_buffer.convert(input_range.max())); break;
case output::replace_selection: range = _selections.last(); break;
}
size_t caret = _selections.last().last.index;
size_t line = 0, column = 0, offset = 0;
if(range && format == output_format::text && outputCaret == output_caret::interpolate_by_char)
{
ASSERT_LE(range.min().index, caret); ASSERT_LE(caret, range.max().index);
offset = caret - range.min().index; // TODO we should let offset be number of code points (for non-combining marks)
}
else if(format == output_format::text && outputCaret == output_caret::interpolate_by_line)
{
line = _buffer.convert(caret).line;
column = visual_distance(_buffer, _buffer.begin(line), caret);
}
switch(format)
{
case output_format::snippet:
case output_format::snippet_no_auto_indent:
{
if(range)
_selections = range;
snippet(out, environment, format == output_format::snippet_no_auto_indent);
}
break;
case output_format::text:
{
if(range)
_selections = range;
insert(out, outputCaret == output_caret::select_output);
if(range && outputCaret == output_caret::interpolate_by_char)
{
offset = utf8::find_safe_end(out.begin(), out.begin() + std::min(offset, out.size())) - out.begin();
_selections = range_t(range.min().index + offset);
}
else if(outputCaret == output_caret::interpolate_by_line)
{
_selections = visual_advance(_buffer, _buffer.begin(std::min(line, _buffer.lines()-1)), column);
}
}
break;
// case output_format::completion_list:
// {
// std::vector<std::string> completions;
// citerate(line, text::tokenize(out.begin(), out.end(), '\n'))
// {
// if(!(*line).empty())
// completions.push_back(*line);
// }
// completion(completions, selection().last());
// }
// break;
}
return true;
}
void editor_t::delete_tab_trigger (std::string const& str)
{
ranges_t ranges;
iterate(range, _selections)
{
size_t from = range->min().index;
ranges.push_back(range_t(from - std::min(str.size(), from), range->max()));
}
_selections = apply(_buffer, ranges, _snippets, &transform::null);
}
scope::context_t editor_t::scope (std::string const& scopeAttributes) const
{
return ng::scope(_buffer, _selections, scopeAttributes);
}
std::map<std::string, std::string> editor_t::variables (std::map<std::string, std::string> map, std::string const& scopeAttributes) const
{
if(_document)
map = _document->variables(map);
else map = variables_for_path(NULL_STR, "", map);
map.insert(std::make_pair("TM_TAB_SIZE", std::to_string(_buffer.indent().tab_size())));
map.insert(std::make_pair("TM_SOFT_TABS", _buffer.indent().soft_tabs() ? "YES" : "NO"));
map.insert(std::make_pair("TM_SELECTION", to_s(_buffer, _selections)));
if(_selections.size() == 1)
{
range_t const range = _selections.last();
if(range.empty())
{
size_t const caret = range.last.index;
text::pos_t const& pos = _buffer.convert(caret);
map.insert(std::make_pair("TM_LINE_INDEX", std::to_string(pos.column)));
map.insert(std::make_pair("TM_LINE_NUMBER", std::to_string(pos.line+1)));
map.insert(std::make_pair("TM_COLUMN_NUMBER", std::to_string(visual_distance(_buffer, _buffer.begin(pos.line), caret)+1)));
range_t wordRange = ng::extend(_buffer, _selections, kSelectionExtendToWord).last();
map.insert(std::make_pair("TM_CURRENT_WORD", _buffer.substr(wordRange.min().index, wordRange.max().index)));
map.insert(std::make_pair("TM_CURRENT_LINE", _buffer.substr(_buffer.begin(pos.line), _buffer.eol(pos.line))));
map.insert(std::make_pair("TM_SCOPE_LEFT", to_s(_buffer.scope(caret).left)));
}
else
{
if(32 + range.max().index - range.min().index < ARG_MAX)
{
bool first = true;
citerate(r, dissect_columnar(_buffer, range))
{
if(first)
map["TM_SELECTED_TEXT"] = "";
else map["TM_SELECTED_TEXT"] += "\n";
map["TM_SELECTED_TEXT"] += _buffer.substr(r->min().index, r->max().index);
first = false;
}
}
else
{
map.insert(std::make_pair("TM_SELECTED_TEXT", text::format("Error: Selection exceeds %s. Command should read selection from stdin.", text::format_size(ARG_MAX-32).c_str())));
}
}
}
scope::context_t const& s = scope(scopeAttributes);
map.insert(std::make_pair("TM_SCOPE", to_s(s.right)));
return bundles::environment(s, map);
}
// ========
// = Find =
// ========
void editor_t::find (std::string const& searchFor, find::options_t options, bool searchOnlySelection)
{
ranges_t res;
if(options & find::all_matches)
{
citerate(pair, ng::find_all(_buffer, searchFor, options, searchOnlySelection ? _selections : ranges_t()))
res.push_back(pair->first);
if(searchOnlySelection && res.sorted() == _selections.sorted())
{
res = ranges_t();
citerate(pair, ng::find_all(_buffer, searchFor, options, ranges_t()))
res.push_back(pair->first);
}
}
else
{
citerate(pair, ng::find(_buffer, _selections, searchFor, options))
res.push_back(pair->first);
}
if(!res.empty())
_selections = res;
}
ranges_t editor_t::replace_all (std::string const& searchFor, std::string const& replaceWith, find::options_t options, bool searchOnlySelection)
{
ranges_t res;
if(options & find::all_matches)
{
preserve_selection_helper_t helper(_buffer, _selections);
std::multimap<range_t, std::string> replacements;
citerate(pair, ng::find_all(_buffer, searchFor, options, searchOnlySelection ? _selections : ranges_t()))
replacements.insert(std::make_pair(pair->first, options & find::regular_expression ? format_string::expand(replaceWith, pair->second) : replaceWith));
res = this->replace(replacements, true);
_selections = helper.get(false);
}
return res;
}
} /* ng */
| aarongraham9/TextMate | Frameworks/editor/src/editor.cc | C++ | gpl-3.0 | 63,238 |
package com.dennisbonke.testmod.utility;
import com.dennisbonke.testmod.reference.Reference;
import cpw.mods.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
/**
* Created by Dennisbonke on 14-2-2015.
*/
public class Log {
public static void log(Level logLevel, Object object)
{
FMLLog.log(Reference.modid, logLevel, String.valueOf(object));
}
public static void all ( Object object ) {
log( Level.ALL, object );
}
public static void debug ( Object object ) {
log( Level.DEBUG, object );
}
public static void error ( Object object ) {
log( Level.ERROR, object );
}
public static void fatal ( Object object ) {
log( Level.FATAL, object );
}
public static void info ( Object object ) {
log( Level.INFO, object );
}
public static void off ( Object object ) {
log( Level.OFF, object );
}
public static void trace ( Object object ) {
log( Level.TRACE, object );
}
public static void warn ( Object object ) {
log( Level.WARN, object );
}
}
| Dennisbonke/JiraiyasTuts | src/main/java/com/dennisbonke/testmod/utility/Log.java | Java | gpl-3.0 | 1,106 |
#include <iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cstdlib>
using namespace std;
int main()
{
char str1[2000],str2[2000],ans[2000],swap_str[2000];
bool check[2000];
long int i,j,k,l,swap,a;
while(gets(str1) && gets(str2))
{
memset(check,true,sizeof(check));
k=strlen(str1);
l=strlen(str2);
if(k>l)
{
swap=k;
k=l;
l=swap;
strcpy(swap_str,str1);
strcpy(str1,str2);
strcpy(str2,swap_str);
}
for(i=a=0;i<k;i++)
for(j=0;j<l;j++)
{
if(str1[i]==str2[j] && check[j]==true)
{
ans[a]=str1[i];
a++;
check[j]=false;
break;
}
}
ans[a]='\0';
sort(ans,ans+a);
printf("%s\n",ans);
}
return 0;
}
| tanmoy13/UVa | 10252 - Common Permutation/main.cpp | C++ | gpl-3.0 | 983 |
package craftedcart.smblevelworkshop.resource;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* @author CraftedCart
* Created on 04/04/2016 (DD/MM/YYYY)
*/
public class LangManager {
// <Locale, <Key , Value >>
@NotNull private static Map<String, Map<String, String>> localeMap = new HashMap<>();
@NotNull private static String selectedLang = "en_US";
/**
* Add an item given a locale, key and value
*
* @param locale The language locale (eg: en_US)
* @param key The identifier
* @param value The translated string
*/
public static void addItem(String locale, String key, String value) {
if (localeMap.containsKey(locale)) {
Map<String, String> langMap = localeMap.get(locale);
langMap.put(key, value);
localeMap.put(locale, langMap);
} else {
Map<String, String> langMap = new HashMap<>();
langMap.put(key, value);
localeMap.put(locale, langMap);
}
}
/**
* Get a translated string, given a locale and key
*
* @param locale The language locale (eg: en_US)
* @param key The identifier
* @return The translated string, or the key if the entry wasn't found
*/
public static String getItem(String locale, String key) {
if (localeMap.containsKey(locale)) {
if (localeMap.get(locale).containsKey(key)) {
return localeMap.get(locale).get(key);
} else {
return key;
}
} else {
return key;
}
}
public static String getItem(String key) {
return getItem(selectedLang, key);
}
public static void setSelectedLang(@NotNull String selectedLang) {
LangManager.selectedLang = selectedLang;
}
@NotNull
public static String getSelectedLang() {
return selectedLang;
}
}
| CraftedCart/SMBLevelWorkshop | src/main/java/craftedcart/smblevelworkshop/resource/LangManager.java | Java | gpl-3.0 | 1,987 |
from collections import namedtuple
ScoredObject = namedtuple('ScoredObject',
['key', 'score', 'variable1', 'variable2', 'rounds', 'opponents', 'wins', 'loses']
) | ubc/compair | compair/algorithms/scored_object.py | Python | gpl-3.0 | 165 |
'''
Created on 05.01.2018
@author: michael
'''
from alexplugins.systematic.tkgui import SystematicPointSelectionPresenter,\
SystematicPointSelectionDialog
from tkinter.ttk import Button
from alexplugins.systematic.base import SystematicIdentifier, SystematicPoint
from alexandriabase.domain import Tree
from manual.dialogs_test import DialogTest, DialogTestRunner
from alexplugins.cdexporter.tkgui import ChronoDialogPresenter, ChronoDialog,\
ExportInfoWizardPresenter, ExportInfoWizard
from tkgui.Dialogs import GenericStringEditDialog
from alexpresenters.DialogPresenters import GenericInputDialogPresenter
from alexplugins.cdexporter.base import ExportInfo
class SystematicServiceStub():
systematic_points = (SystematicPoint(SystematicIdentifier(None), "Root"),
SystematicPoint(SystematicIdentifier("0"), 'Node 0'),
SystematicPoint(SystematicIdentifier("1"), 'Node 1'),
SystematicPoint(SystematicIdentifier("1.1"), 'Node 1.1'),
)
def get_systematic_tree(self):
return Tree(self.systematic_points)
def fetch_systematic_entries_for_document(self, document):
return (self.systematic_points[document.id],)
class SystematicPointSelectionTest(DialogTest):
def __init__(self, window_manager):
super().__init__(window_manager)
self.name = "Systematic node selection"
def test_component(self, master, message_label):
self.master = master
self.message_label = message_label
presenter = SystematicPointSelectionPresenter(SystematicServiceStub(),
self.message_broker)
self.dialog = SystematicPointSelectionDialog(self.window_manager, presenter)
Button(self.master, text='Start dialog', command=self._start_dialog).pack()
def _start_dialog(self):
self.dialog.activate(self._systematic_dialog_callback, label="Test label")
def _systematic_dialog_callback(self, node):
self.message_label.set("Selection: %s Type: %s" % (node, type(node)))
class ChronoDialogTest(DialogTest):
def __init__(self, window_manager):
super().__init__(window_manager)
self.name = "Chrono dialog"
def test_component(self, master, message_label):
self.master = master
self.message_label = message_label
presenter = ChronoDialogPresenter()
self.dialog = ChronoDialog(self.window_manager, presenter)
Button(self.master, text='Start dialog', command=self._start_dialog).pack()
def _start_dialog(self):
self.dialog.activate(self._chrono_dialog_callback)
def _chrono_dialog_callback(self, info):
self.message_label.set(info)
class ExportInfoWizardTest(DialogTest):
def __init__(self, window_manager):
super().__init__(window_manager)
self.name = "Export info dialog"
def test_component(self, master, message_label):
self.master = master
self.message_label = message_label
location_dialog = GenericStringEditDialog(self.window_manager, GenericInputDialogPresenter())
presenter = ExportInfoWizardPresenter()
self.dialog = ExportInfoWizard(self.window_manager, presenter, location_dialog)
Button(self.master, text='Start dialog', command=self._start_dialog).pack()
def _start_dialog(self):
self.dialog.activate(self._export_info_callback, export_info=ExportInfo())
def _export_info_callback(self, info):
self.message_label.set(info)
if __name__ == '__main__':
test_classes = []
test_classes.append(SystematicPointSelectionTest)
test_classes.append(ChronoDialogTest)
test_classes.append(ExportInfoWizardTest)
test_runner = DialogTestRunner(test_classes)
test_runner.run()
| archivsozialebewegungen/AlexandriaPlugins | manualtests/manual/dialogs_test.py | Python | gpl-3.0 | 3,944 |
# == Schema Information
#
# Table name: reference
#
# authors :string(4000)
# crc :string(32)
# created_at :datetime
# dbxref_id :integer
# location :string(4000) not null
# reference_id :integer not null, primary key
# title :string(4000)
# updated_at :datetime
#
class Biosql::Reference < ActiveRecord::Base
set_table_name "reference"
set_primary_key :reference_id
belongs_to :dbxref, :class_name => "Dbxref"
has_many :bioentry_references, :class_name=>"BioentryReference"
has_many :bioentries, :through=>:bioentry_references
end
| Michigan-State-University/gxseq | app/models/biosql/reference.rb | Ruby | gpl-3.0 | 596 |
"""Abstract base audio mixer."""
from abc import ABCMeta, abstractmethod
import smokesignal
from volcorner import signals
__all__ = ['Mixer']
class Mixer(metaclass=ABCMeta):
@abstractmethod
def open(self):
"""Open the mixer and start monitoring for volume changes."""
@abstractmethod
def close(self):
"""Close the mixer."""
@property
@abstractmethod
def volume(self):
"""
Get the current volume as a float.
:return: volume, between 0.0 and 1.0
:rtype: float
"""
@volume.setter
@abstractmethod
def volume(self, value):
"""
Set the current volume as a float.
:param float value: the new volume, between 0.0 and 1.0
"""
def on_volume_changed(self, value):
"""
Subclasses should call this when the volume is changed outside of this app.
:param float value: the new volume, between 0.0 and 1.0
"""
smokesignal.emit(signals.CHANGE_VOLUME, value)
| cknave/volcorner | volcorner/mixer.py | Python | gpl-3.0 | 1,024 |
var ALLOWED_VARIANCE = 0.05;
/* Nested model forms BEGIN */
function inspect (obj) {
var str;
for(var i in obj)
str+=i+";\n"
//str+=i+"="+obj[i]+";\n"
alert(str);
}
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
//$(link).parent().next().hide();
if ($(link).hasClass('totals_callback')) {
updateTotalValuesCallback(link);
}
};
function add_fields(link, association, content) {
// before callback
before_add_fields_callback(association);
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
if (association === 'in_flows' || association === 'implementer_splits' ) {
$(link).parents('tr:first').before(content.replace(regexp, new_id));
} else {
$(link).parent().before(content.replace(regexp, new_id));
}
after_add_fields_callback(association);
};
//prevents non-numeric characters to be entered in the input field
var numericInputField = function (input) {
$(input).keydown(function(event) {
// Allow backspace and delete, enter and tab
var bksp = 46;
var del = 8;
var enter = 13;
var tab = 9;
if ( event.keyCode == bksp || event.keyCode == del || event.keyCode == enter || event.keyCode == tab ) {
// let it happen, don't do anything
} else {
// Ensure that it is a number or a '.' and stop the keypress
var period = 190;
if ((event.keyCode >= 48 && event.keyCode <= 57 ) || event.keyCode == period || event.keyCode >= 37 && event.keyCode <= 40) {
// let it happen
} else {
event.preventDefault();
};
};
});
}
var observeFormChanges = function (form) {
var catcher = function () {
var changed = false;
if ($(form).data('initialForm') != $(form).serialize()) {
changed = true;
}
if (changed) {
return 'You have unsaved changes!';
}
};
if ($(form).length) { //# dont bind unless you find the form element on the page
$('input[type=submit]').click(function (e) {
$(form).data('initialForm', $(form).serialize());
});
$(form).data('initialForm', $(form).serialize());
$(window).bind('beforeunload', catcher);
};
}
var build_activity_funding_source_row = function (edit_block) {
var organization = edit_block.find('.ff_organization option:selected').text();
var spend = '';
var budget = '';
spend = $('<li/>').append(
$('<span/>').text('Expenditure'),
edit_block.find('.ff_spend').val() || 'N/A'
)
budget = $('<li/>').append(
$('<span/>').text('Current Budget'),
edit_block.find('.ff_budget').val() || 'N/A'
)
return $('<ul/>').append(
$('<li/>').append(
$('<span/>').text('Funder'),
organization || 'N/A'
),
spend,
budget
)
};
var close_activity_funding_sources_fields = function (fields) {
$.each(fields, function () {
var element = $(this);
var edit_block = element.find('.edit_block');
var preview_block = element.find('.preview_block');
var manage_block = element.find('.manage_block');
edit_block.hide();
preview_block.html('');
preview_block.append(build_activity_funding_source_row(edit_block))
preview_block.show();
manage_block.find('.edit_button').remove();
manage_block.prepend(
$('<a/>').attr({'class': 'edit_button', 'href': '#'}).text('Edit')
)
});
};
var before_add_fields_callback = function (association) {
if (association === 'funding_sources') {
close_activity_funding_sources_fields($('.funding_sources .fields'));
}
};
var after_add_fields_callback = function (association) {
// show the jquery autocomplete combobox instead of
// standard dropdowns
$( ".js_combobox" ).combobox();
};
/* Nested model forms END */
/* Ajax CRUD BEGIN */
var getRowId = function (element) {
return element.parents('tr').attr('id');
};
var getResourceId = function (element) {
return Number(getRowId(element).match(/\d+/)[0]);
};
var getResourceName = function (element) {
return element.parents('.resources').attr("data-resource");
};
var getForm = function (element) {
return element.parents('form');
};
var addNewForm = function (resources, data) {
resources.find('.placer').html(data);
};
var addEditForm = function (rowId, data) {
$('#' + rowId).html('<td colspan="100">' + data + '</td>').addClass("edit_row");
};
var updateCount = function (resources) {
var count = resources.find('tbody tr').length;
resources.find('.count').html(count);
}
var addNewRow = function (resources, data) {
resources.find('tbody').prepend(data);
enableElement(resources.find('.new_btn'));
updateCount(resources);
var newRow = $(resources.find('tbody tr')[0]);
newRow.find(".rest_in_place").rest_in_place(); // inplace edit
};
var addExistingRow = function (rowId, data) {
var row = $('#' + rowId);
row.replaceWith(data)
var newRow = $('#' + rowId);
newRow.find(".rest_in_place").rest_in_place(); // inplace edit
};
var addSearchForm = function (element) {
if (element.hasClass('enabled')) {
disableElement(element);
var resourceName = getResourceName(element);
$.get(resourceName + '/search.js', function (data) {
$('#placer').prepend(data);
});
}
}
var closeForm = function (element) {
element.parents('.form_box').remove();
};
var disableElement = function (element) {
element.removeClass('enabled').addClass('disabled');
};
var enableElement = function (element) {
element.removeClass('disabled').addClass('enabled');
};
var buildUrl = function (url) {
var parts = url.split('?');
if (parts.length > 1) {
return parts.join('.js?');
} else {
return parts[0] + '.js';
}
};
var buildJsonUrl = function (url) {
var parts = url.split('?');
if (parts.length > 1) {
return parts.join('.json?');
} else {
return parts[0] + '.json';
}
};
var getResources = function (element) {
return element.parents('.resources');
}
var newResource = function (element) {
if (element.hasClass('enabled')) {
var resources = getResources(element);
disableElement(element);
$.get(buildUrl(element.attr('href')), function (data) {
addNewForm(resources, data);
});
}
};
var replaceTable = function (data) {
$("#main_table").replaceWith(data);
$("#main_table").find(".rest_in_place").rest_in_place(); // inplace edit
};
var searchResources = function (element, type) {
var resourceName = getResourceName(element);
var form = getForm(element);
var q = (type === "reset") ? '' : form.find("#s_q").val();
$.get(resourceName + '.js?q=' + q, function (data) {
replaceTable(data);
if (type === "reset") {
closeForm(element);
enableElement($(".search_btn"));
}
});
};
var editResource = function (element) {
var rowId = getRowId(element);
$.get(buildUrl(element.attr('href')), function (data) {
addEditForm(rowId, data);
});
};
var updateResource = function (element) {
var rowId = getRowId(element);
var form = getForm(element);
$.post(buildUrl(form.attr('action')), form.serialize(), function (data, status, response) {
closeForm(element);
response.status === 206 ? addEditForm(rowId, data) : addExistingRow(rowId, data);
});
};
var createResource = function (element) {
var form = getForm(element);
var resources = getResources(element);
$.post(buildUrl(form.attr('action')), form.serialize(), function (data, status, response) {
closeForm(element);
response.status === 206 ? addNewForm(resources, data) : addNewRow(resources, data);
});
};
var showResource = function (element) {
var rowId = getRowId(element);
var resourceId = getResourceId(element)
$.get(element.attr('href') + '/' + resourceId + '.js', function (data) {
closeForm(element);
addExistingRow(rowId, data);
});
};
var destroyResource = function (element) {
var rowId = getRowId(element);
var resources = getResources(element);
$.post(element.attr('href').replace('/delete', '') + '.js', {'_method': 'delete'}, function (data) {
removeRow(resources, rowId);
});
};
var sortResources = function (element) {
var link = element.find('a');
var resourceName = getResourceName(element);
var url = resourceName + '.js?' + link.attr('href').replace(/.*\?/, '');
$.get(url, function (data) {
replaceTable(data);
});
}
var getFormType = function (element) {
// new_form => new; edit_form => edit
return element.parents('.form_box').attr('class').replace(/form_box /, '').split('_')[0];
}
var ajaxifyResources = function (resources) {
var block = $(".resources[data-resources='" + resources + "']");
var newBtn = block.find(".new_btn");
var editBtn = block.find(".edit_btn");
var cancelBtn = block.find(".cancel_btn");
var searchBtn = block.find(".search_btn");
var submitBtn = block.find(".js_submit_comment_btn");
var destroyBtn = block.find(".destroy_btn");
// new
newBtn.live('click', function (e) {
e.preventDefault();
var element = $(this);
newResource(element);
});
// edit
editBtn.live('click', function (e) {
e.preventDefault();
var element = $(this);
editResource(element);
});
// cancel
cancelBtn.live('click', function (e) {
e.preventDefault();
var element = $(this);
var formType = getFormType(element);
if (formType === "new") {
closeForm(element);
enableElement(newBtn);
} else if (formType === "edit") {
showResource(element);
} else if (formType === "search") {
closeForm(element);
enableElement(searchBtn);
} else {
throw "Unknown form type:" + formType;
}
});
// submit
submitBtn.live('click', function (e) {
e.preventDefault();
var element = $(this);
var formType = getFormType(element);
if (formType === "new") {
createResource(element);
} else if (formType === "edit") {
updateResource(element);
} else if (formType === "search") {
searchResources(element);
} else {
throw "Unknown form type: " + formType;
}
});
// destroy
destroyBtn.live('click', function (e) {
e.preventDefault();
var element = $(this);
if (confirm('Are you sure?')) {
destroyResource(element);
}
});
};
/* Ajax CRUD END */
var collapse_expand = function (e, element, type) {
// if target element is link or the user is selecting text, skip collapsing
if (e.target.nodeName === 'A' || window.getSelection().toString() !== "") {
return;
}
var next_element = element.next('.' + type + '.entry_main');
var next_element_visible = next_element.is(':visible');
$('.' + type + '.entry_main').hide();
$('.' + type + '.entry_header').removeClass('active');
if (next_element_visible) {
next_element.hide();
} else {
element.addClass('active');
next_element.show();
}
};
var getRowId = function (element) {
return element.parents('tr').attr('id');
};
var getResourceName = function (element) {
return element.parents('.resources').attr("data-resources");
};
var getResourceId = function (element) {
return Number(getRowId(element).match(/\d+/)[0]);
};
var removeRow = function (resources, rowId) {
resources.find("#" + rowId).remove();
updateCount(resources);
};
var updateTotalValuesCallback = function (el) {
updateTotalValue($(el).parents('tr').find('.js_spend'));
updateTotalValue($(el).parents('tr').find('.js_budget'));
};
var getFieldsTotal = function (fields) {
var total = 0;
for (var i = 0; i < fields.length; i++) {
if (!isNaN(fields[i].value)) {
total += Number(fields[i].value);
}
}
return total;
}
var updateTotalValue = function (el) {
if ($(el).hasClass('js_spend')) {
if ($(el).parents('table').length) {
// table totals
var table = $(el).parents('table');
var input_fields = table.find('input.js_spend:visible');
var total_field = table.find('.js_total_spend .amount');
} else {
// classifications tree totals
var input_fields = $(el).parents('.activity_tree').find('> li > div input.js_spend');
var total_field = $('.js_total_spend .amount');
}
} else if ($(el).hasClass('js_budget')) {
if ($(el).parents('table').length) {
// table totals
var table = $(el).parents('table');
var input_fields = table.find('input.js_budget:visible');
var total_field = table.find('.js_total_budget .amount');
} else {
// classifications tree totals
var input_fields = $(el).parents('.activity_tree').find('> li > div input.js_budget');
var total_field = $('.js_total_budget .amount');
}
} else {
throw "Element class not valid";
}
var fieldsTotal = getFieldsTotal(input_fields);
total_field.html(fieldsTotal.toFixed(2));
};
var dynamicUpdateTotalsInit = function () {
$('.js_spend, .js_budget').live('keyup', function () {
updateTotalValue(this);
});
};
var admin_responses_index = {
run: function () {
// destroy
$(".destroy_btn").live('click', function (e) {
e.preventDefault();
var element = $(this);
if (confirm('Are you sure?')) {
destroyResource(element);
}
});
}
};
var admin_responses_empty = {
run: function () {
// destroy
$(".destroy_btn").live('click', function (e) {
e.preventDefault();
var element = $(this);
if (confirm('Are you sure?')) {
destroyResource(element);
}
});
}
};
var getOrganizationInfo = function (organization_id, box) {
if (organization_id) {
$.get(organization_id + '.js', function (data) {
box.find('.placer').html(data);
});
}
};
var displayFlashForReplaceOrganization = function (type, message) {
$('#content .wrapper').prepend(
$('<div/>').attr({id: 'flashes'}).append(
$('<div/>').attr({id: type}).text(message)
)
);
// fade out flash message
$("#" + type).delay(5000).fadeOut(3000, function () {
$("#flashes").remove();
});
}
var removeOrganizationFromLists = function (duplicate_id, box_type) {
$.each(['duplicate', 'target'], function (i, name) {
var select_element = $("#" + name + "_organization_id");
var current_option = select_element.find("option[value='" + duplicate_id + "']");
// remove element from page
if (name === box_type) {
var next_option = current_option.next().val();
if (next_option) {
select_element.val(next_option);
// update info block
getOrganizationInfo(select_element.val(), $('#' + name));
} else {
$('#' + name).html('')
}
}
current_option.remove();
});
}
var ReplaceOrganizationSuccessCallback = function (message, duplicate_id) {
removeOrganizationFromLists(duplicate_id, 'duplicate');
displayFlashForReplaceOrganization('notice', message);
};
var ReplaceOrganizationErrorCallback = function (message) {
displayFlashForReplaceOrganization('error', message)
}
var replaceOrganization = function (form) {
var duplicate_id = $("#duplicate_organization_id").val();
$.post(buildUrl(form.attr('action')), form.serialize(), function (data, status, response) {
var data = $.parseJSON(data)
response.status === 206 ? ReplaceOrganizationErrorCallback(data.message) : ReplaceOrganizationSuccessCallback(data.message, duplicate_id);
});
};
var admin_organizations_duplicate = {
run: function () {
$("#duplicate_organization_id, #target_organization_id").change(function() {
var organization_id = $(this).val();
var type = $(this).parents('.box').attr('data-type');
var box = $('#' + type); // type = duplicate; target
getOrganizationInfo(organization_id, box);
});
getOrganizationInfo($("#duplicate_organization_id").val(), $('#duplicate'));
getOrganizationInfo($("#target_organization_id").val(), $('#target'));
$("#replace_organization").click(function (e) {
e.preventDefault();
var element = $(this);
var form = element.parents('form')
if (confirm('Are you sure?')) {
replaceOrganization(form);
}
});
}
};
var admin_responses_show = {
run: function (){
build_data_response_review_screen();
ajaxifyResources('comments');
}
};
var reports_index = {
run: function () {
ajaxifyResources('comments');
drawPieChart('code_spent', _code_spent_values, 450, 300);
drawPieChart('code_budget', _code_budget_values, 450, 300);
}
};
var responses_review = {
run: function () {
build_data_response_review_screen();
ajaxifyResources('comments');
}
};
var activity_classification = function () {
/*
* Adds collapsible checkbox tree functionality for a tab and validates classification tree
* @param {String} tab
*
*/
var addCollabsibleButtons = function (tab) {
$('.' + tab + ' ul.activity_tree').collapsibleCheckboxTree({tab: tab});
$('.' + tab + ' ul.activity_tree').validateClassificationTree();
};
//collapsible checkboxes for tab1
var mode = document.location.search.split("=")[1]
if (mode != 'locations') {
addCollabsibleButtons('tab1');
}
checkRootNodes('budget');
checkRootNodes('spend');
checkAllChildren();
showSubtotalIcons();
$('.js_upload_btn').click(function (e) {
e.preventDefault();
$(this).parents('.upload').find('.upload_box').toggle();
});
$('.js_submit_btn').click(function (e) {
var ajaxLoader = $(this).closest('ol').find('.ajax-loader');
ajaxLoader.show();
checkRootNodes('spend');
checkRootNodes('budget');
if ($('.invalid_node').size() > 0){
e.preventDefault();
alert('The classification tree could not be saved. Please correct all errors and try again')
ajaxLoader.hide();
};
});
$('#js_budget_to_spend').click(function (e) {
e.preventDefault();
if ($(this).find('img').hasClass('approved')) {
alert('Classifications for an approved activity cannot be changed');
} else if (confirm('This will overwrite all Past Expenditure percentages with the Current Budget percentages. Are you sure?')) {
$('.js_budget input').each(function () {
var element = $(this);
element.parents('.js_values').find('.js_spend input').val(element.val());
});
checkRootNodes('spend');
checkAllChildren();
};
});
$('#js_spend_to_budget').click(function (e) {
e.preventDefault();
if ($(this).find('img').hasClass('approved')) {
alert('Classifications for an approved activity cannot be changed');
} else if (confirm('This will overwrite all Current Budget percentages with the Past Expenditure percentages. Are you sure?')) {
$('.js_spend input').each(function () {
var element = $(this);
element.parents('.js_values').find('.js_budget input').val(element.val());
});
checkRootNodes('budget');
checkAllChildren();
};
});
$(".percentage_box").keyup(function(event) {
var element = $(this);
var isSpend = element.parents('div:first').hasClass('spend')
var type = (isSpend) ? 'spend' : 'budget';
var childLi = element.parents('li:first').children('ul:first').children('li');
updateSubTotal(element);
updateTotalValue(element);
if (element.val().length == 0 && childLi.size() > 0) {
clearChildNodes(element, event, type);
}
var period = 190;
var bksp = 46;
var del = 8;
//update parent nodes if: numeric keys, backspace/delete, period or undefined (i.e. called from another function)
if (typeof event.keyCode == 'undefined' || (event.keyCode >= 48 && event.keyCode <= 57 ) || event.keyCode == period || event.keyCode == del || event.keyCode == bksp || event.keyCode >= 37 && event.keyCode <= 40){
updateParentNodes(element, type)
}
//check whether children (1 level deep) are equal to my total
if (childLi.size() > 0){
compareChildrenToParent(element, type);
};
//check whether root nodes are = 100%
checkRootNodes(type);
});
numericInputField(".percentage_box, .js_spend, .js_budget");
var updateParentNodes = function(element, type){
type = '.' + type + ':first'
var parentElement = element.parents('ul:first').prev('div:first').find(type).find('input');
var siblingLi = element.parents('ul:first').children('li');
var siblingValue = 0;
var siblingTotal = 0;
siblingLi.each(function (){
siblingValue = parseFloat($(this).find(type).find('input:first').val());
if ( !isNaN(siblingValue) ) {
siblingTotal = siblingTotal + siblingValue;
};
});
if ( siblingTotal !== 0 ) {
parentElement.val(siblingTotal);
parentElement.trigger('keyup');
}
}
var clearChildNodes = function(element, event, type){
var bksp = 46;
var del = 8;
type = '.' + type + ':first'
if ( (event.keyCode == bksp || event.keyCode == del) ){
childNodes = element.parents('li:first').children('ul:first').find('li').find(type).find('input');
var childTotal = 0;
childNodes.each(function (){
childValue = parseFloat($(this).val())
if (!isNaN(childValue)) {
childTotal = childTotal + childValue
};
});
if ( childTotal > 0 && confirm('Would you like to clear the value of all child nodes?') ){
childNodes.each(function(){
if ( $(this).val !== '' ){
$(this).val(' ');
updateSubTotal($(this));
}
});
}
}
}
var updateSubTotal = function(element){
var activity_budget = parseFloat(element.parents('ul:last').attr('activity_budget'));
var activity_spend = parseFloat(element.parents('ul:last').attr('activity_spend'));
var activity_currency = element.parents('ul:last').attr('activity_currency');
var elementValue = parseFloat(element.val());
var subtotal = element.siblings('.subtotal_icon');
var isSpend = element.parents('div:first').hasClass('spend')
if ( elementValue > 0 ){
subtotal.removeClass('hidden')
subtotal.attr('title', (isSpend ? activity_spend : activity_budget * (elementValue/100)).toFixed(2) + ' ' + activity_currency);
} else {
subtotal.attr('title','');
subtotal.addClass('hidden');
}
};
}
var checkAllChildren = function(){
var inputs = $('.percentage_box')
inputs.each(function(){
if ( $(this).val !== '' ){
var type = $(this).hasClass('js_spend') ? 'spend' : 'budget'
compareChildrenToParent($(this), type);
}
});
}
var compareChildrenToParent = function(parentElement, type){
var childValue = 0;
var childTotal = 0;
var childLi = parentElement.parents('li:first').children('ul:first').children('li');
type = '.' + type + ':first'
childLi.each(function (){
childValue = parseFloat($(this).find(type).find('input:first').val())
if (!isNaN(childValue)) {
childTotal = childTotal + childValue
};
});
var parentValue = parseFloat(parentElement.val()).toFixed(2)
childTotal = childTotal.toFixed(2)
if ( (Math.abs(childTotal - parentValue) > ALLOWED_VARIANCE) && childTotal > 0){
parentElement.addClass('invalid_node tooltip')
var message = "This amount is not the same as the sum of the amounts underneath (" ;
message += parentValue + "% - " + childTotal + "% = " + (parentValue - childTotal) + "%)";
parentElement.attr('original-title', message) ;
} else {
parentElement.removeClass('invalid_node tooltip')
};
};
var checkRootNodes = function(type){
var topNodes = $('.activity_tree').find('li:first').siblings().andSelf();
var total = 0;
var value = 0;
type = '.' + type + ':first'
topNodes.each(function(){
value = $(this).find(type).find('input').val();
if (!isNaN(parseFloat(value))){
total += parseFloat($(this).find(type).find('input').val());
};
});
$('.totals').find(type).find('.amount').html(total);
if ( (Math.abs(total - 100.00) > ALLOWED_VARIANCE) && total > 0){
topNodes.each(function(){
rootNode = $(this).find(type).find('input');
if (rootNode.val().length > 0 && (!(rootNode.hasClass('invalid_node tooltip')))){
rootNode.addClass('invalid_node tooltip');
}
var message = "The root nodes do not add up to 100%";
rootNode.attr('original-title', message) ;
});
} else {
topNodes.each(function(){
rootNode = $(this).find(type).find('input');
if (rootNode.attr('original-title') != undefined && rootNode.attr('original-title') == "The root nodes do not add up to 100%"){
rootNode.removeClass('invalid_node tooltip');
rootNode.attr('original-title', '')
}
});
};
};
var showSubtotalIcons = function(){
$('.tab1').find('.percentage_box').each(function(){
if ($(this).val().length > 0) {
$(this).siblings('.subtotal_icon').removeClass('hidden')
}
});
}
var update_use_budget_codings_for_spend = function (e, activity_id, checked) {
if (!checked || checked && confirm('All your expenditure codings will be deleted and replaced with copies of your budget codings, adjusted for the difference between your budget and spend. Your expenditure codings will also automatically update if you change your budget codings. Are you sure?')) {
$.post( "/activities/" + activity_id + "/use_budget_codings_for_spend", { checked: checked, "_method": "put" });
} else {
e.preventDefault();
}
};
var data_responses_review = {
run: function () {
$(".use_budget_codings_for_spend").click(function (e) {
var checked = $(this).is(':checked');
activity_id = Number($(this).attr('id').match(/\d+/)[0], 10);
update_use_budget_codings_for_spend(e, activity_id, checked);
})
}
}
var responses_submit = {
run: function () {
$(".collapse").click(function(e){
e.preventDefault();
var row_id = $(this).attr('id');
$("." + row_id).slideToggle("fast");
var row = row_id.split("_", 3);
var img = $(this).attr('img');
var image = row_id + "_image";
var source = $('.'+image).attr('src');
var split = source.split("?", 1);
if (split == "/images/icon_expand.png") {
$('.' + image).attr('src', "/images/icon_collapse.png");
} else {
$('.' + image).attr('src', "/images/icon_expand.png");
}
});
}
}
function drawPieChart(id, data_rows, width, height) {
if (typeof(data_rows) === "undefined") {
return;
}
var data = new google.visualization.DataTable();
data.addColumn('string', data_rows.names.column1);
data.addColumn('number', data_rows.names.column2);
data.addRows(data_rows.values.length);
for (var i = 0; i < data_rows.values.length; i++) {
var value = data_rows.values[i];
data.setValue(i, 0, value[0]);
data.setValue(i, 1, value[1]);
};
var chart = new google.visualization.PieChart(document.getElementById(id));
chart.draw(data, {width: width, height: height, chartArea: {width: 360, height: 220}});
};
var reports_districts_show = reports_countries_show = {
run: function () {
drawPieChart('budget_i_pie', _budget_i_values, 400, 250);
drawPieChart('spend_i_pie', _spend_i_values, 400, 250);
}
};
var reports_districts_classifications = reports_countries_classifications = {
run: function () {
if (_pie) {
drawPieChart('code_spent', _code_spent_values, 450, 300);
drawPieChart('code_budget', _code_budget_values, 450, 300);
} else {
drawTreemapChart('code_spent', _code_spent_values, 'w');
drawTreemapChart('code_budget', _code_budget_values, 'e');
}
}
}
var reports_districts_activities_show = {
run: function () {
drawPieChart('spent_pie', _spent_pie_values, 450, 300);
drawPieChart('budget_pie', _budget_pie_values, 450, 300);
drawPieChart('code_spent', _code_spent_values, 450, 300);
drawPieChart('code_budget', _code_budget_values, 450, 300);
}
};
var admin_currencies_index = {
run: function () {
$(".currency_label").live("click", function () {
var element = $(this);
var id = element.attr('id');
element.hide();
element.parent('td').append($("<input id=\'" + id + "\' class=\'currency\' />"));
});
$(".currency").live('focusout', function () {
element = $(this);
var input_rate = element.val();
var url = "/admin/currencies/" + element.attr('id');
$.post(url, { "rate" : input_rate, "_method" : "put" }, function(data){
var data = $.parseJSON(data);
if (data.status == 'success'){
element.parent('td').children('span').show();
element.parent('td').children('span').text(data.new_rate);
element.hide();
}
});
});
}
}
var reports_districts_activities_index = {
run: function () {
drawPieChart('spent_pie', _spent_pie_values, 450, 300);
drawPieChart('budget_pie', _budget_pie_values, 450, 300);
}
};
var reports_districts_organizations_index = {
run: function () {
drawPieChart('spent_pie', _spent_pie_values, 450, 300);
drawPieChart('budget_pie', _budget_pie_values, 450, 300);
}
};
var reports_districts_organizations_show = {
run: function () {
drawPieChart('code_spent', _code_spent_values, 450, 300);
drawPieChart('code_budget', _code_budget_values, 450, 300);
}
};
var reports_countries_organizations_index = {
run: function () {
drawPieChart('spent_pie', _spent_pie_values, 450, 300);
drawPieChart('budget_pie', _budget_pie_values, 450, 300);
}
};
var reports_countries_organizations_show = {
run: function () {
drawPieChart('code_spent', _code_spent_values, 450, 300);
drawPieChart('code_budget', _code_budget_values, 450, 300);
}
};
var reports_countries_activities_index = {
run: function () {
drawPieChart('spent_pie', _spent_pie_values, 450, 300);
drawPieChart('budget_pie', _budget_pie_values, 450, 300);
}
};
var reports_countries_activities_show = {
run: function () {
drawPieChart('code_spent', _code_spent_values, 450, 300);
drawPieChart('code_budget', _code_budget_values, 450, 300);
}
};
var validateDates = function (startDate, endDate) {
var checkDates = function (e) {
var element = $(e.target);
var d1 = new Date(startDate.val());
var d2 = new Date(endDate.val());
// remove old errors
startDate.parent('li').find('.inline-errors').remove();
endDate.parent('li').find('.inline-errors').remove();
if (startDate.length && endDate.length && d1 >= d2) {
if (startDate.attr('id') == element.attr('id')) {
message = "Start date must come before End date.";
} else {
message = "End date must come after Start date.";
}
element.parent('li').append(
$('<p/>').attr({"class": "inline-errors"}).text(message)
);
}
};
startDate.live('change', checkDates);
endDate.live('change', checkDates);
};
var commentsInit = function () {
initDemoText($('*[data-hint]'));
focusDemoText($('*[data-hint]'));
blurDemoText($('*[data-hint]'));
var removeInlineErrors = function (form) {
form.find('.inline-errors').remove(); // remove inline error if present
}
$('.js_reply').live('click', function (e) {
e.preventDefault();
var element = $(this);
element.parents('li:first').find('.js_reply_box:first').show();
})
$('.js_cancel_reply').live('click', function (e) {
e.preventDefault();
var element = $(this);
element.parents('.js_reply_box:first').hide();
removeInlineErrors(element.parents('form'));
})
// remove demo text when submiting comment
$('.js_submit_comment_btn').live('click', function (e) {
e.preventDefault();
removeDemoText($('*[data-hint]'));
var element = $(this);
if (element.hasClass('disabled')) {
return;
}
var form = element.parents('form');
var block;
var ajaxLoader = element.parent('li').nextAll('.ajax-loader');
element.addClass('disabled');
ajaxLoader.show();
$.post(buildJsonUrl(form.attr('action')), form.serialize(),
function (data, status, response) {
ajaxLoader.hide();
element.removeClass('disabled');
if (response.status === 206) {
form.replaceWith(data.html)
} else {
if (form.find('#comment_parent_id').length) {
// comment reply
block = element.parents('li.comment_item:first');
if (block.find('ul').length) {
block.find('ul').prepend(data.html);
} else {
block.append($('<ul/>').prepend(data.html));
}
} else {
// root comment
block = $('ul.js_comments_list');
block.prepend(data.html)
}
}
initDemoText(form.find('*[data-hint]'));
removeInlineErrors(form);
form.find('textarea').val(''); // reset comment value to blank
form.find('.js_cancel_reply').trigger('click'); // close comment block
});
});
}
var dropdown = {
// find the dropdown menu relative to the current element
menu: function(element){
return element.parents('.js_dropdown_menu');
},
toggle_on: function (menu_element) {
menu_element.find('.menu_items').slideDown(100);
menu_element.addClass('persist');
},
toggle_off: function (menu_element) {
menu_element.find('.menu_items').slideUp(100);
menu_element.removeClass('persist');
}
};
var projects_index = {
run: function () {
// use click() not toggle() here, as toggle() doesnt
// work when menu items are also toggling it
$('.js_project_row').hover(
function(e){
$(this).find('.js_am_approve').show();
},
function(e){
$(this).find('.js_am_approve').fadeOut(300);
}
);
$('.js_dropdown_trigger').click(function (e){
e.preventDefault();
menu = dropdown.menu($(this));
if (!menu.is('.persist')) {
dropdown.toggle_on(menu);
} else {
dropdown.toggle_off(menu);
};
});
$('.js_dropdown_menu .menu_items a').click(function (e){
menu = dropdown.menu($(this));
dropdown.toggle_off(menu);
$(this).click; // continue with desired click action
});
$('.js_upload_btn').click(function (e) {
e.preventDefault();
$(this).parents('tbody').find('.upload_box').slideToggle();
});
$('#import_export').click(function (e) {
e.preventDefault();
$('#import_export_box .upload_box').slideToggle();
});
$('.tooltip_projects').tipsy({gravity: $.fn.tipsy.autoWE, live: true, html: true});
commentsInit();
approveBudget();
$('.js_address').address(function() {
return 'new_' + $(this).html().toLowerCase();
});
$.address.externalChange(function() {
var hash = $.address.path();
if (hash == '/'){
if (!($('#projects_listing').is(":visible"))){
$('.js_toggle_projects_listing').click();
}
} else {
if (hash == '/new_project'){
hideAll();
$('#new_project_form').fadeIn();
validateDates($('.start_date'), $('.end_date'));
}else if (hash == '/new_activity'){
hideAll();
$('#new_activity_form').fadeIn();
activity_form();
}
else if (hash == '/new_other cost'){
hideAll();
$('#new_other_cost_form').fadeIn();
}
};
});
$('.js_toggle_project_form').click(function (e) {
e.preventDefault();
hideAll();
$('#new_project_form').fadeIn();
$('#new_project_form #project_name').focus();
});
$('.js_toggle_activity_form').click(function (e) {
e.preventDefault();
hideAll();
$('#new_activity_form').fadeIn();
$('#new_activity_form #activity_name').focus();
activity_form();
});
$('.js_toggle_other_cost_form').click(function (e) {
e.preventDefault();
hideAll();
$('#new_other_cost_form').fadeIn();
$('#new_other_cost_form #other_cost_name').focus();
});
$('.js_toggle_projects_listing').click(function (e) {
e.preventDefault();
hideAll();
$.address.path('/');
$( "form" )[ 0 ].reset()
$('#projects_listing').fadeIn();
$("html, body").animate({ scrollTop: 0 }, 0);
});
dynamicUpdateTotalsInit();
numericInputField(".js_spend, .js_budget");
}
};
var hideAll = function() {
$('#projects_listing').hide();
$('#new_project_form').hide();
$('#new_activity_form').hide();
$('#new_other_cost_form').hide();
$('.js_total_budget .amount, .js_total_spend .amount').html(0);
};
var initDemoText = function (elements) {
elements.each(function(){
var element = $(this);
var demo_text = element.attr('data-hint');
if (demo_text != null) {
element.attr('title', demo_text);
if (element.val() == '' || element.val() == demo_text) {
element.val( demo_text );
element.addClass('input_hint');
}
}
});
};
var focusDemoText = function (elements) {
elements.live('focus', function(){
var element = $(this);
var demo_text = element.attr('data-hint');
if (demo_text != null) {
if (element.val() == demo_text) {
element.val('');
element.removeClass('input_hint');
}
}
});
};
var removeDemoText = function (elements) {
elements.each(function () {
var element = $(this);
var demo_text = element.attr('data-hint');
if (demo_text != null) {
if (element.val() == demo_text) {
element.val('');
}
}
});
};
var blurDemoText = function (elements) {
elements.live('blur', function(){
var element = $(this);
var demo_text = element.attr('data-hint');
if (demo_text != null) {
if (element.val() == '') {
element.val( demo_text );
element.addClass('input_hint');
}
}
});
};
var toggle_collapsed = function (elem, indicator) {
var is_visible = elem.is(':visible');
if (is_visible) {
indicator.removeClass('collapsed');
} else {
indicator.addClass('collapsed');
};
};
var unsaved_warning = function () {
return 'You have projects that have not been saved. Saved projects show a green checkmark next to them. Are you sure you want to leave this page?'
};
var projects_import = {
run: function () {
$('.activity_box .header').live('click', function (e) {
e.preventDefault();
var activity_box = $(this).parents('.activity_box');
//collapse the others, in an accordion style
$.each($.merge(activity_box.prevAll('.activity_box'), activity_box.nextAll('.activity_box')), function () {
$(this).find('.main').hide();
toggle_collapsed($(this).find('.main'), $(this).find('.header span'));
});
activity_box.find('.main').toggle();
toggle_collapsed(activity_box.find('.main'), activity_box.find('.header span'));
});
$('.header:first').trigger('click'); // expand the first one on page load
$(window).bind('beforeunload',function (e) {
if ($('.js_unsaved').length > 0) {
return unsaved_warning();
}
});
$('.save_btn').live('click', function (e) {
e.preventDefault();
var element = $(this);
var form = element.parents('form');
var ajaxLoader = element.next('.ajax-loader');
var activity_box = element.parents('.activity_box');
ajaxLoader.show();
$.post(buildUrl(form.attr('action')), form.serialize(), function (data) {
activity_box.html(data.html);
activity_box.find(".js_combobox").combobox();
ajaxLoader.hide();
if (data.status == 'success') {
activity_box.find('.saved_tick').show();
activity_box.find('.saved_tick').removeClass('js_unsaved');
activity_box.find('.saved_tick').addClass('js_saved');
activity_box.find('.main').toggle();
toggle_collapsed(activity_box.find('.main'), activity_box.find('.header span'));
$('.js_unsaved:first').parents('.activity_box').find('.main').toggle();
toggle_collapsed($('.js_unsaved:first').parents('.activity_box').find('.main'), $('.js_unsaved:first').parents('.activity_box').find('.header span'));
}
});
});
}
}
// Post approval for an activity
//
// approval types;
// 'activity_manager_approve'
// 'sysadmin_approve'
// success text
//
//
var approveBudget = function() {
$(".js_am_approve").click(function (e) {
e.preventDefault();
approveActivity($(this), 'activity_manager_approve', 'Budget Approved');
})
};
var approveAsAdmin = function() {
$(".js_sysadmin_approve").click(function (e) {
e.preventDefault();
approveActivity($(this), 'sysadmin_approve', 'Admin Approved');
})
};
var approveActivity = function (element, approval_type, success_text) {
var activity_id = element.attr('activity-id');
var response_id = element.attr('response-id');
element.parent('li').find(".ajax-loader").show();
var url = "/responses/" + response_id + "/activities/" + activity_id + "/" + approval_type
$.post(url, {approve: true, "_method": "put"}, function (data) {
element.parent('li').find(".ajax-loader").hide();
if (data.status == 'success') {
element.parent('li').html('<span>' + success_text + '</span>');
}
})
};
var activities_new = activities_create = activities_edit = activities_update = other_costs_edit = other_costs_new = other_costs_create = other_costs_update = {
run: function () {
var mode = document.location.search.split("=")[1]
activity_classification();
activity_form();
if ($('.js_target_field').size() == 0) {
$(document).find('.js_add_nested').trigger('click');
}
numericInputField(".js_implementer_spend, .js_implementer_budget");
$('.ui-autocomplete-input').live('focusin', function () {
var element = $(this).siblings('select');
if(element.children('option').length < 2) { // because there is already one in to show default
element.append(selectOptions);
}
});
}
};
var activity_form = function () {
$('#activity_project_id').change(function () {
update_funding_source_selects();
});
$('#activity_name').live('keyup', function() {
var parent = $(this).parent('li')
var remaining = $(this).attr('data-maxlength') - $(this).val().length;
$('.remaining_characters').html("(?) <span class=\"red\">" + remaining + " Characters Remaining</span>")
});
$('.js_implementer_select').live('change', function(e) {
e.preventDefault();
var element = $(this);
if (element.val() == "-1") {
$('.js_implementer_container').hide();
$('.add_organization').show();
}
});
$('.cancel_organization_link').live('click', function(e) {
e.preventDefault();
$('.organization_name').attr('value', '');
$('.add_organization').hide();
$('.js_implementer_container').show();
$('.js_implementer_select').val(null);
});
$('.add_organization_link').live('click', function(e) {
e.preventDefault();
var name = $('.organization_name').val();
$.post("/organizations.js", { "name" : name }, function(data){
var data = $.parseJSON(data);
$('.js_implementer_container').show();
$('.add_organization').hide();
if (isNaN(data.organization.id)) {
$('.js_implementer_select').val(null);
} else {
$('.js_implementer_select').prepend("<option value=\'"+ data.organization.id + "\'>" + data.organization.name + "</option>");
$('.js_implementer_select').val(data.organization.id);
}
});
$('.organization_name').attr('value', '');
$('.add_organization').slideToggle();
});
$('.js_target_field').live('keydown', function (e) {
var block = $(this).parents('.js_targets');
if (e.keyCode === 13) {
e.preventDefault();
block.find('.js_add_nested').trigger('click');
block.find('.js_target_field:last').focus()
}
});
$('.edit_button').live('click', function (e) {
e.preventDefault();
var element = $(this).parents('.fields');
var fields = $.merge(element.prevAll('.fields'), element.nextAll('.fields'));
element.find('.edit_block').show();
element.find('.preview_block').hide();
close_activity_funding_sources_fields(fields);
});
$('.js_implementer_spend').live('keyup', function(e) {
var page_spend = parseFloat($('body').attr('page_spend'));
var current_spend = implementer_page_total('spend');
var difference = page_spend - current_spend;
var total = parseFloat($('body').attr('total_spend'));
$('.js_total_spend').find('.amount').html((total - difference).toFixed(2))
});
$('.js_implementer_budget').live('keyup', function(e) {
var page_budget = parseFloat($('body').attr('page_budget'));
var current_budget = implementer_page_total('budget');
var difference = page_budget - current_budget;
var total = parseFloat($('body').attr('total_budget'));
$('.js_total_budget').find('.amount').html((total - difference).toFixed(2))
});
approveBudget();
approveAsAdmin();
commentsInit();
dynamicUpdateTotalsInit();
close_activity_funding_sources_fields($('.funding_sources .fields'));
store_implementer_page_total();
};
var store_implementer_page_total = function(){
$('body').attr('total_spend', $('.js_total_spend').find('.amount').html() )
$('body').attr('total_budget', $('.js_total_budget').find('.amount').html() )
if( $('.js_implementer_budget').length > 0 ){
page_budget = implementer_page_total('budget')
$('body').attr('page_budget',page_budget);
}
if( $('.js_implementer_spend').length > 0 ){
page_spend = implementer_page_total('spend')
$('body').attr('page_spend',page_spend);
}
};
var implementer_page_total = function(type){
var page_total = 0;
inputs = (type == 'budget') ? $('.js_implementer_budget') : $('.js_implementer_spend');
inputs.each(function(){
float_val = parseFloat($(this).val());
if( !(isNaN(float_val)) ){
page_total += parseFloat($(this).val());
}
});
return page_total
}
var admin_activities_new = admin_activities_create = admin_activities_edit = admin_activities_update = {
run: function () {
activity_form();
}
};
var admin_users_new = admin_users_create = admin_users_edit = admin_users_update = {
run: function () {
var toggleMultiselect = function (element) {
var ac_selected = $('#user_roles option[value="activity_manager"]:selected').length > 0;
var dm_selected = $('#user_roles option[value="district_manager"]:selected').length > 0;
if (element.val() && ac_selected) {
$(".organizations").show().css('visibility', 'visible');
$(".js_manage_orgs").slideDown();
} else {
$(".js_manage_orgs").slideUp();
$(".organizations").hide().css('visibility', 'hidden');
}
if (element.val() && dm_selected) {
$(".locations").show().css('visibility', 'visible');
$(".js_manage_districts").slideDown();
} else {
$(".locations").hide().css('visibility', 'hidden');
$(".js_manage_districts").slideUp();
}
};
// choose either the full version
$(".multiselect").multiselect({sortable: false});
// or disable some features
//$(".multiselect").multiselect({sortable: false, searchable: false});
toggleMultiselect($('#user_roles'));
$('#user_roles').change(function () {
toggleMultiselect($(this));
});
}
}
var dashboard_index = {
run: function () {
$('.dropdown_trigger').click(function (e) {e.preventDefault()});
if (typeof(_code_spent_values) !== 'undefined' || typeof(_code_budget_values) !== 'undefined') {
drawPieChart('code_spent', _code_spent_values, 450, 300);
drawPieChart('code_budget', _code_budget_values, 450, 300);
}
$('.dropdown_menu').hover(function (e){
e.preventDefault();
$('ul', this).slideDown(100);
$('.dropdown_trigger').addClass('persist');
}, function(e) {
e.preventDefault();
$('ul', this).slideUp(100);
$('.dropdown_trigger').removeClass('persist');
});
}
};
var admin_organizations_create = admin_organizations_edit = {
run: function () {
$(".js_combobox" ).combobox();
jsAutoTab();
}
};
var projects_new = projects_create = projects_edit = projects_update = {
run: function () {
commentsInit();
validateDates($('.start_date'), $('.end_date'));
dynamicUpdateTotalsInit();
numericInputField(".js_spend, .js_budget");
}
}
// Autotabs a page using javascript
var jsAutoTab = function () {
var tabindex = 1;
$('input, select, textarea, checkbox').each(function() {
if (this.type != "hidden") {
var $input = $(this);
$input.attr("tabindex", tabindex);
tabindex++;
}
});
}
// DOM LOAD
$(function () {
// prevent going to top when tooltip clicked
$('.tooltip').live('click', function (e) {
if ($(this).attr('href') === '#') {
e.preventDefault();
}
});
//combobox everywhere!
$( ".js_combobox" ).combobox();
// keep below combobox
jsAutoTab();
// tipsy tooltips everywhere!
$('.tooltip').tipsy({gravity: $.fn.tipsy.autoWE, fade: true, live: true, html: true});
//jquery tools overlays
$(".overlay").overlay();
var id = $('body').attr("id");
if (id) {
controller_action = id;
if (typeof(window[controller_action]) !== 'undefined' && typeof(window[controller_action]['run']) === 'function') {
window[controller_action]['run']();
}
}
//observe form changes and alert user if form has unsaved data
observeFormChanges($('.js_form'));
$(".closeFlash").click(function (e) {
e.preventDefault();
$(this).parents('div:first').fadeOut("slow", function() {
$(this).show().css({display: "none"});
});
});
$('#page_tips_open').click(function (e) {
e.preventDefault();
$('#page_tips .desc').toggle();
$('#page_tips .nav').toggle();
});
$('#page_tips_close').click(function (e) {
e.preventDefault();
$('#page_tips .desc').toggle();
$('#page_tips .nav').toggle();
$("#page_tips_open_link").effect("highlight", {}, 1500);
});
// Date picker
$('.date_picker').live('click', function () {
$(this).datepicker('destroy').datepicker({
changeMonth: true,
changeYear: true,
yearRange: '2000:2025',
dateFormat: 'dd-mm-yy'
}).focus();
});
// Inplace edit
$(".rest_in_place").rest_in_place();
// clickable table rows
$('.clickable tbody tr').click(function (e) {
e.preventDefault();
var element = $(e.target);
if (element.attr('href')) {
var href = element.attr('href');
} else {
var href = $(this).find("a").attr("href");
}
if (href) {
window.location = href;
}
});
// CSV file upload
$("#csv_file").click( function(e) {
e.preventDefault();
$("#import").slideToggle();
});
// Show/hide getting started tips
$('.js_tips_hide').click(function (e) {
e.preventDefault();
$('.js_tips_container').fadeOut();
$.post('/profile/disable_tips', { "_method": "put" });
});
});
| siyelo/hrtv1 | public/javascripts/application.js | JavaScript | gpl-3.0 | 51,126 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Moodle's Clean theme, an example of how to make a Bootstrap theme
*
* DO NOT MODIFY THIS THEME!
* COPY IT FIRST, THEN RENAME THE COPY AND MODIFY IT INSTEAD.
*
* For full information about creating Moodle themes, see:
* http://docs.moodle.org/dev/Themes_2.0
*
* @package theme_blackly
* @copyright 2015 Nephzat Dev Team, nephzat.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
$settings = null;
if (is_siteadmin()) {
$ADMIN->add('themes', new admin_category('theme_blackly', 'Blackly'));
/* Header Settings */
$temp = new admin_settingpage('theme_blackly_header', get_string('headerheading', 'theme_blackly'));
// Logo file setting.
$name = 'theme_blackly/logo';
$title = get_string('logo','theme_blackly');
$description = get_string('logodesc', 'theme_blackly');
$setting = new admin_setting_configstoredfile($name, $title, $description, 'logo');
$setting->set_updatedcallback('theme_reset_all_caches');
$temp->add($setting);
// Custom CSS file.
$name = 'theme_blackly/customcss';
$title = get_string('customcss', 'theme_blackly');
$description = get_string('customcssdesc', 'theme_blackly');
$default = '';
$setting = new admin_setting_configtextarea($name, $title, $description, $default);
$setting->set_updatedcallback('theme_reset_all_caches');
$temp->add($setting);
$ADMIN->add('theme_blackly', $temp);
/* Slideshow Settings Start */
$temp = new admin_settingpage('theme_blackly_slideshow', get_string('slideshowheading', 'theme_blackly'));
$temp->add(new admin_setting_heading('theme_blackly_slideshow', get_string('slideshowheadingsub', 'theme_blackly'),
format_text(get_string('slideshowdesc', 'theme_blackly'), FORMAT_MARKDOWN)));
// Display Slideshow.
$name = 'theme_blackly/toggleslideshow';
$title = get_string('toggleslideshow', 'theme_blackly');
$description = get_string('toggleslideshowdesc', 'theme_blackly');
$yes = get_string('yes');
$no = get_string('no');
$default = 1;
$choices = array(1 => $yes , 0 => $no);
$setting = new admin_setting_configselect($name, $title, $description, $default, $choices);
$setting->set_updatedcallback('theme_reset_all_caches');
$temp->add($setting);
// Number of slides.
$name = 'theme_blackly/numberofslides';
$title = get_string('numberofslides', 'theme_blackly');
$description = get_string('numberofslides_desc', 'theme_blackly');
$default = 3;
$choices = array(
1 => '1',
2 => '2',
3 => '3',
4 => '4',
5 => '5',
6 => '6',
7 => '7',
8 => '8',
9 => '9',
10 => '10',
11 => '11',
12 => '12',
);
$temp->add(new admin_setting_configselect($name, $title, $description, $default, $choices));
$numberofslides = get_config('theme_blackly', 'numberofslides');
for ($i = 1; $i <= $numberofslides; $i++) {
// This is the descriptor for Slide One
$name = 'theme_blackly/slide' . $i . 'info';
$heading = get_string('slideno', 'theme_blackly', array('slide' => $i));
$information = get_string('slidenodesc', 'theme_blackly', array('slide' => $i));
$setting = new admin_setting_heading($name, $heading, $information);
$temp->add($setting);
// Slide Image.
$name = 'theme_blackly/slide' . $i . 'image';
$title = get_string('slideimage', 'theme_blackly');
$description = get_string('slideimagedesc', 'theme_blackly');
$setting = new admin_setting_configstoredfile($name, $title, $description, 'slide' . $i . 'image');
$setting->set_updatedcallback('theme_reset_all_caches');
$temp->add($setting);
// Slide Caption.
$name = 'theme_blackly/slide' . $i . 'caption';
$title = get_string('slidecaption', 'theme_blackly');
$description = get_string('slidecaptiondesc', 'theme_blackly');
$default = get_string('slidecaptiondefault','theme_blackly', array('slideno' => sprintf('%02d', $i) ));
$setting = new admin_setting_configtext($name, $title, $description, $default, PARAM_TEXT);
$setting->set_updatedcallback('theme_reset_all_caches');
$temp->add($setting);
// Slide Description Text.
$name = 'theme_blackly/slide' . $i . 'desc';
$title = get_string('slidedesc', 'theme_blackly');
$description = get_string('slidedesctext', 'theme_blackly');
$default = get_string('slidedescdefault','theme_blackly');
$setting = new admin_setting_confightmleditor($name, $title, $description, $default);
$setting->set_updatedcallback('theme_reset_all_caches');
$temp->add($setting);
}
$ADMIN->add('theme_blackly', $temp);
/* Slideshow Settings End*/
/* Footer Settings start */
$temp = new admin_settingpage('theme_blackly_footer', get_string('footerheading', 'theme_blackly'));
/* Footer Content */
$name = 'theme_blackly/footnote';
$title = get_string('footnote', 'theme_blackly');
$description = get_string('footnotedesc', 'theme_blackly');
$default = get_string('footnotedefault', 'theme_blackly');
$setting = new admin_setting_confightmleditor($name, $title, $description, $default);
$setting->set_updatedcallback('theme_reset_all_caches');
$temp->add($setting);
// INFO Link
$name = 'theme_blackly/infolink';
$title = get_string('infolink', 'theme_blackly');
$description = get_string('infolink_desc', 'theme_blackly');
$default = get_string('infolinkdefault', 'theme_blackly');
$setting = new admin_setting_configtextarea($name, $title, $description, $default);
$setting->set_updatedcallback('theme_reset_all_caches');
$temp->add($setting);
// copyright
$name = 'theme_blackly/copyright_footer';
$title = get_string('copyright_footer', 'theme_blackly');
$description = '';
$default = get_string('copyright_default','theme_blackly');
$setting = new admin_setting_configtext($name, $title, $description, $default);
$temp->add($setting);
/* Address , Email , Phone No */
$name = 'theme_blackly/address';
$title = get_string('address', 'theme_blackly');
$description = '';
$default = get_string('defaultaddress','theme_blackly');
$setting = new admin_setting_configtext($name, $title, $description, $default);
$temp->add($setting);
$name = 'theme_blackly/emailid';
$title = get_string('emailid', 'theme_blackly');
$description = '';
$default = get_string('defaultemailid','theme_blackly');
$setting = new admin_setting_configtext($name, $title, $description, $default);
$temp->add($setting);
$name = 'theme_blackly/phoneno';
$title = get_string('phoneno', 'theme_blackly');
$description = '';
$default = get_string('defaultphoneno','theme_blackly');
$setting = new admin_setting_configtext($name, $title, $description, $default);
$temp->add($setting);
/* Facebook,Pinterest,Twitter,Google+ Settings */
$name = 'theme_blackly/fburl';
$title = get_string('fburl', 'theme_blackly');
$description = get_string('fburldesc', 'theme_blackly');
$default = get_string('fburl_default','theme_blackly');
$setting = new admin_setting_configtext($name, $title, $description, $default);
$temp->add($setting);
$name = 'theme_blackly/pinurl';
$title = get_string('pinurl', 'theme_blackly');
$description = get_string('pinurldesc', 'theme_blackly');
$default = get_string('pinurl_default','theme_blackly');
$setting = new admin_setting_configtext($name, $title, $description, $default);
$temp->add($setting);
$name = 'theme_blackly/twurl';
$title = get_string('twurl', 'theme_blackly');
$description = get_string('twurldesc', 'theme_blackly');
$default = get_string('twurl_default','theme_blackly');
$setting = new admin_setting_configtext($name, $title, $description, $default);
$temp->add($setting);
$name = 'theme_blackly/gpurl';
$title = get_string('gpurl', 'theme_blackly');
$description = get_string('gpurldesc', 'theme_blackly');
$default = get_string('gpurl_default','theme_blackly');
$setting = new admin_setting_configtext($name, $title, $description, $default);
$temp->add($setting);
$ADMIN->add('theme_blackly', $temp);
/* Footer Settings end */
}
| mahalaxmi123/LTFB3 | theme/blackly/settings.php | PHP | gpl-3.0 | 9,300 |
package plugins.Freereader;
/**
* Version
*
* @author Mario Volke
*/
public class Version {
/** SVN revision number. Only set if the plugin is compiled properly e.g. by emu. */
private static final String svnRevision = "@custom@";
/** Version number of the plugin for getRealVersion(). Increment this on making
* a major change, a significant bugfix etc. These numbers are used in auto-update
* etc, at a minimum any build inserted into auto-update should have a unique
* version. */
public static long version = 1;
static String getSvnRevision() {
return svnRevision;
}
static long getVersion() {
return version;
}
public static void main(String[] args) {
System.out.println("=====");
System.out.println(svnRevision);
System.out.println("=====");
System.out.println(getVersion());
}
}
| webholics/Freereader | src/plugins/Freereader/Version.java | Java | gpl-3.0 | 830 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using SmartStore.Collections;
using SmartStore.Core;
using SmartStore.Core.Domain.Catalog;
using SmartStore.Core.Domain.Customers;
using SmartStore.Core.Domain.Orders;
using SmartStore.Utilities;
namespace SmartStore.Services.Catalog
{
/// <summary>
/// Product service
/// </summary>
public partial interface IProductService
{
#region Products
/// <summary>
/// Delete a product
/// </summary>
/// <param name="product">Product</param>
void DeleteProduct(Product product);
/// <summary>
/// Gets all products displayed on the home page
/// </summary>
/// <returns>Product collection</returns>
IList<Product> GetAllProductsDisplayedOnHomePage();
/// <summary>
/// Gets all products
/// </summary>
/// <returns>Product Collection</returns>
IList<Product> GetAllProducts();
/// <summary>
/// Gets product
/// </summary>
/// <param name="productId">Product identifier</param>
/// <returns>Product</returns>
Product GetProductById(int productId);
/// <summary>
/// Gets products by identifier
/// </summary>
/// <param name="productIds">Product identifiers</param>
/// <returns>Products</returns>
IList<Product> GetProductsByIds(int[] productIds);
/// <summary>
/// Inserts a product
/// </summary>
/// <param name="product">Product</param>
void InsertProduct(Product product);
/// <summary>
/// Updates the product
/// </summary>
/// <param name="product">Product</param>
void UpdateProduct(Product product, bool publishEvent = true);
/// <summary>
/// Gets the total count of products matching the criteria
/// </summary>
int CountProducts(ProductSearchContext productSearchContext);
/// <summary>
/// Search products
/// </summary>
IPagedList<Product> SearchProducts(ProductSearchContext productSearchContext);
/// <summary>
/// Builds a product query based on the options in ProductSearchContext parameter.
/// </summary>
/// <param name="ctx">Parameters to build the query.</param>
/// <param name="allowedCustomerRolesIds">Customer role ids (ACL).</param>
/// <param name="searchLocalizedValue">Whether to search localized values.</param>
IQueryable<Product> PrepareProductSearchQuery(ProductSearchContext ctx, IEnumerable<int> allowedCustomerRolesIds = null, bool searchLocalizedValue = false);
/// <summary>
/// Builds a product query based on the options in ProductSearchContext parameter.
/// </summary>
/// <param name="ctx">Parameters to build the query.</param>
/// <param name="selector">Data projector</param>
/// <param name="allowedCustomerRolesIds">Customer role ids (ACL).</param>
/// <param name="searchLocalizedValue">Whether to search localized values.</param>
IQueryable<TResult> PrepareProductSearchQuery<TResult>(ProductSearchContext ctx, Expression<Func<Product, TResult>> selector, IEnumerable<int> allowedCustomerRolesIds = null, bool searchLocalizedValue = false);
/// <summary>
/// Update product review totals
/// </summary>
/// <param name="product">Product</param>
void UpdateProductReviewTotals(Product product);
/// <summary>
/// Get low stock products
/// </summary>
/// <returns>Result</returns>
IList<Product> GetLowStockProducts();
/// <summary>
/// Gets a product by SKU
/// </summary>
/// <param name="sku">SKU</param>
/// <returns>Product</returns>
Product GetProductBySku(string sku);
/// <summary>
/// Gets a product by GTIN
/// </summary>
/// <param name="gtin">GTIN</param>
/// <returns>Product</returns>
Product GetProductByGtin(string gtin);
/// <summary>
/// Adjusts inventory
/// </summary>
/// <param name="sci">Shopping cart item</param>
/// <param name="decrease">A value indicating whether to increase or descrease product stock quantity</param>
/// <returns>Adjust inventory result</returns>
AdjustInventoryResult AdjustInventory(OrganizedShoppingCartItem sci, bool decrease);
/// <summary>
/// Adjusts inventory
/// </summary>
/// <param name="orderItem">Order item</param>
/// <param name="decrease">A value indicating whether to increase or descrease product stock quantity</param>
/// <param name="quantity">Quantity</param>
/// <returns>Adjust inventory result</returns>
AdjustInventoryResult AdjustInventory(OrderItem orderItem, bool decrease, int quantity);
/// <summary>
/// Adjusts inventory
/// </summary>
/// <param name="product">Product</param>
/// <param name="decrease">A value indicating whether to increase or descrease product stock quantity</param>
/// <param name="quantity">Quantity</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Adjust inventory result</returns>
AdjustInventoryResult AdjustInventory(Product product, bool decrease, int quantity, string attributesXml);
/// <summary>
/// Update HasTierPrices property (used for performance optimization)
/// </summary>
/// <param name="product">Product</param>
void UpdateHasTierPricesProperty(Product product);
/// <summary>
/// Update LowestAttributeCombinationPrice property (used for performance optimization)
/// </summary>
/// <param name="product">Product</param>
void UpdateLowestAttributeCombinationPriceProperty(Product product);
/// <summary>
/// Update HasDiscountsApplied property (used for performance optimization)
/// </summary>
/// <param name="product">Product</param>
void UpdateHasDiscountsApplied(Product product);
/// <summary>
/// Creates a RSS feed with recently added products
/// </summary>
/// <param name="urlHelper">UrlHelper to generate URLs</param>
/// <returns>SmartSyndicationFeed object</returns>
SmartSyndicationFeed CreateRecentlyAddedProductsRssFeed(UrlHelper urlHelper);
#endregion
#region Related products
/// <summary>
/// Deletes a related product
/// </summary>
/// <param name="relatedProduct">Related product</param>
void DeleteRelatedProduct(RelatedProduct relatedProduct);
/// <summary>
/// Gets a related product collection by product identifier
/// </summary>
/// <param name="productId1">The first product identifier</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Related product collection</returns>
IList<RelatedProduct> GetRelatedProductsByProductId1(int productId1, bool showHidden = false);
/// <summary>
/// Gets a related product
/// </summary>
/// <param name="relatedProductId">Related product identifier</param>
/// <returns>Related product</returns>
RelatedProduct GetRelatedProductById(int relatedProductId);
/// <summary>
/// Inserts a related product
/// </summary>
/// <param name="relatedProduct">Related product</param>
void InsertRelatedProduct(RelatedProduct relatedProduct);
/// <summary>
/// Updates a related product
/// </summary>
/// <param name="relatedProduct">Related product</param>
void UpdateRelatedProduct(RelatedProduct relatedProduct);
/// <summary>
/// Ensure existence of all mutually related products
/// </summary>
/// <param name="productId1">First product identifier</param>
/// <returns>Number of inserted related products</returns>
int EnsureMutuallyRelatedProducts(int productId1);
#endregion
#region Cross-sell products
/// <summary>
/// Deletes a cross-sell product
/// </summary>
/// <param name="crossSellProduct">Cross-sell</param>
void DeleteCrossSellProduct(CrossSellProduct crossSellProduct);
/// <summary>
/// Gets a cross-sell product collection by product identifier
/// </summary>
/// <param name="productId1">The first product identifier</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Cross-sell product collection</returns>
IList<CrossSellProduct> GetCrossSellProductsByProductId1(int productId1, bool showHidden = false);
/// <summary>
/// Gets a cross-sell product
/// </summary>
/// <param name="crossSellProductId">Cross-sell product identifier</param>
/// <returns>Cross-sell product</returns>
CrossSellProduct GetCrossSellProductById(int crossSellProductId);
/// <summary>
/// Inserts a cross-sell product
/// </summary>
/// <param name="crossSellProduct">Cross-sell product</param>
void InsertCrossSellProduct(CrossSellProduct crossSellProduct);
/// <summary>
/// Updates a cross-sell product
/// </summary>
/// <param name="crossSellProduct">Cross-sell product</param>
void UpdateCrossSellProduct(CrossSellProduct crossSellProduct);
/// <summary>
/// Gets a cross-sells
/// </summary>
/// <param name="cart">Shopping cart</param>
/// <param name="numberOfProducts">Number of products to return</param>
/// <returns>Cross-sells</returns>
IList<Product> GetCrosssellProductsByShoppingCart(IList<OrganizedShoppingCartItem> cart, int numberOfProducts);
/// <summary>
/// Ensure existence of all mutually cross selling products
/// </summary>
/// <param name="productId1">First product identifier</param>
/// <returns>Number of inserted cross selling products</returns>
int EnsureMutuallyCrossSellProducts(int productId1);
#endregion
#region Tier prices
/// <summary>
/// Deletes a tier price
/// </summary>
/// <param name="tierPrice">Tier price</param>
void DeleteTierPrice(TierPrice tierPrice);
/// <summary>
/// Gets a tier price
/// </summary>
/// <param name="tierPriceId">Tier price identifier</param>
/// <returns>Tier price</returns>
TierPrice GetTierPriceById(int tierPriceId);
/// <summary>
/// Gets tier prices by product identifiers
/// </summary>
/// <param name="productIds">Product identifiers</param>
/// <param name="customer">Filter tier prices by customer</param>
/// <param name="storeId">Filter tier prices by store</param>
/// <returns>Map of tier prices</returns>
Multimap<int, TierPrice> GetTierPrices(int[] productIds, Customer customer = null, int storeId = 0);
/// <summary>
/// Inserts a tier price
/// </summary>
/// <param name="tierPrice">Tier price</param>
void InsertTierPrice(TierPrice tierPrice);
/// <summary>
/// Updates the tier price
/// </summary>
/// <param name="tierPrice">Tier price</param>
void UpdateTierPrice(TierPrice tierPrice);
#endregion
#region Product pictures
/// <summary>
/// Deletes a product picture
/// </summary>
/// <param name="productPicture">Product picture</param>
void DeleteProductPicture(ProductPicture productPicture);
/// <summary>
/// Gets a product pictures by product identifier
/// </summary>
/// <param name="productId">The product identifier</param>
/// <returns>Product pictures</returns>
IList<ProductPicture> GetProductPicturesByProductId(int productId);
/// <summary>
/// Gets a product picture
/// </summary>
/// <param name="productPictureId">Product picture identifier</param>
/// <returns>Product picture</returns>
ProductPicture GetProductPictureById(int productPictureId);
/// <summary>
/// Inserts a product picture
/// </summary>
/// <param name="productPicture">Product picture</param>
void InsertProductPicture(ProductPicture productPicture);
/// <summary>
/// Updates a product picture
/// </summary>
/// <param name="productPicture">Product picture</param>
void UpdateProductPicture(ProductPicture productPicture);
#endregion
#region Bundled products
/// <summary>
/// Inserts a product bundle item
/// </summary>
/// <param name="bundleItem">Product bundle item</param>
void InsertBundleItem(ProductBundleItem bundleItem);
/// <summary>
/// Updates a product bundle item
/// </summary>
/// <param name="bundleItem">Product bundle item</param>
void UpdateBundleItem(ProductBundleItem bundleItem);
/// <summary>
/// Deletes a product bundle item
/// </summary>
/// <param name="bundleItem">Product bundle item</param>
void DeleteBundleItem(ProductBundleItem bundleItem);
/// <summary>
/// Get a product bundle item by item identifier
/// </summary>
/// <param name="bundleItemId">Product bundle item identifier</param>
/// <returns>Product bundle item</returns>
ProductBundleItem GetBundleItemById(int bundleItemId);
/// <summary>
/// Gets a list of bundle items for a particular product identifier
/// </summary>
/// <param name="bundleProductId">Product identifier</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>List of bundle items</returns>
IList<ProductBundleItemData> GetBundleItems(int bundleProductId, bool showHidden = false);
#endregion
}
}
| mandocaesar/MesinkuNew | src/Libraries/SmartStore.Services/Catalog/IProductService.cs | C# | gpl-3.0 | 14,021 |
/**
* @brief
*
* @file
* @ingroup python
*/
#include <src/common.hpp>
#include "genesis/genesis.hpp"
using namespace ::genesis::utils;
PYTHON_EXPORT_FUNCTIONS( utils_tools_color_names_export, ::genesis::utils, scope )
{
scope.def(
"color_from_name",
( Color ( * )( std::string const & ))( &::genesis::utils::color_from_name ),
pybind11::arg("name"),
get_docstring("Color ::genesis::utils::color_from_name (std::string const & name)")
);
scope.def(
"color_from_name_web",
( Color ( * )( std::string const & ))( &::genesis::utils::color_from_name_web ),
pybind11::arg("name"),
get_docstring("Color ::genesis::utils::color_from_name_web (std::string const & name)")
);
scope.def(
"color_from_name_xkcd",
( Color ( * )( std::string const & ))( &::genesis::utils::color_from_name_xkcd ),
pybind11::arg("name"),
get_docstring("Color ::genesis::utils::color_from_name_xkcd (std::string const & name)")
);
scope.def(
"is_color_name",
( bool ( * )( std::string const & ))( &::genesis::utils::is_color_name ),
pybind11::arg("name"),
get_docstring("bool ::genesis::utils::is_color_name (std::string const & name)")
);
scope.def(
"is_web_color_name",
( bool ( * )( std::string const & ))( &::genesis::utils::is_web_color_name ),
pybind11::arg("name"),
get_docstring("bool ::genesis::utils::is_web_color_name (std::string const & name)")
);
scope.def(
"is_xkcd_color_name",
( bool ( * )( std::string const & ))( &::genesis::utils::is_xkcd_color_name ),
pybind11::arg("name"),
get_docstring("bool ::genesis::utils::is_xkcd_color_name (std::string const & name)")
);
scope.def(
"color_palette_web",
( std::vector< Color > ( * )( ))( &::genesis::utils::color_palette_web )
);
scope.def(
"color_palette_xkcd",
( std::vector< Color > ( * )( ))( &::genesis::utils::color_palette_xkcd )
);
}
| lczech/genesis | python/src/utils/tools/color/names.cpp | C++ | gpl-3.0 | 2,103 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Anatoly F. Bondarenko
*/
/**
* Created on 31.03.2005
*/
package org.apache.harmony.jpda.tests.jdwp.ThreadReference;
// import org.apache.harmony.jpda.tests.share.JPDADebuggeeSynchronizer;
import org.apache.harmony.jpda.tests.share.SyncDebuggee;
/**
* The class specifies debuggee for <code>org.apache.harmony.jpda.tests.jdwp.ThreadReference.Status004Test</code>.
*/
public class Status004Debuggee extends SyncDebuggee {
static Status004Debuggee status004DebuggeeThis;
static volatile boolean status004DebuggeeThreadStarted = false;
static Object waitTimeObject = new Object();
static void waitMlsecsTime(long mlsecsTime) {
synchronized(waitTimeObject) {
try {
waitTimeObject.wait(mlsecsTime);
} catch (Throwable throwable) {
// ignore
}
}
}
public void run() {
logWriter.println("--> Debuggee: Status004Debuggee: START");
status004DebuggeeThis = this;
String status004DebuggeeThreadName = "Status004DebuggeeThread";
Status004Debuggee_Thread status004DebuggeeThread
= new Status004Debuggee_Thread(status004DebuggeeThreadName);
status004DebuggeeThread.start();
while ( ! status004DebuggeeThreadStarted ) {
waitMlsecsTime(1000);
}
logWriter.println("--> Debuggee: Status004Debuggee: will sleep for 1 second");
waitMlsecsTime(1000); // to make sure that status004DebuggeeThread is sleeping
synchronizer.sendMessage(status004DebuggeeThreadName);
synchronizer.receiveMessage(); // signal to finish
try {
status004DebuggeeThread.interrupt();
} catch (Throwable thrown) {
// ignore
}
while ( status004DebuggeeThread.isAlive() ) {
waitMlsecsTime(100);
}
logWriter.println("--> Debuggee: Status004Debuggee: FINISH");
System.exit(0);
}
public static void main(String [] args) {
runDebuggee(Status004Debuggee.class);
}
}
class Status004Debuggee_Thread extends Thread {
public Status004Debuggee_Thread(String name) {
super(name);
}
public void run() {
Status004Debuggee parent = Status004Debuggee.status004DebuggeeThis;
parent.logWriter.println("--> Thread: " + getName() + ": started...");
parent.logWriter.println
("--> Thread: " + getName() + ": will wait UNDEFINITELY");
Status004Debuggee.status004DebuggeeThreadStarted = true;
Object ObjectForWait = new Object();
synchronized(ObjectForWait) {
try {
ObjectForWait.wait();
} catch (Throwable throwable) {
// ignore
}
}
parent.logWriter.println("--> Thread: " + getName() + ": is finishibg...");
}
}
| s20121035/rk3288_android5.1_repo | external/apache-harmony/jdwp/src/test/java/org/apache/harmony/jpda/tests/jdwp/ThreadReference/Status004Debuggee.java | Java | gpl-3.0 | 3,688 |
package redecouverte.event.ctl;
import java.util.ArrayList;
import org.bukkit.entity.*;
import org.bukkit.Location;
import org.bukkit.block.*;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.*;
import org.bukkit.*;
public class Toolbox {
public static int SaveTeleportPlayerTo(Player player, World world, int x, int z) {
int y = world.getHighestBlockYAt(x, z) + 1;
if (y > 120) {
y = 120;
for (int i = 0; i < 5; i++) {
world.getBlockAt(x, y, z + i).setType(Material.AIR);
}
}
Location teleLoc = new Location(world, x, y, z);
player.teleportTo(teleLoc);
return y;
}
public static ArrayList<String> getPlayersInArea(Server server, World world, int minX, int maxX, int minZ, int maxZ) {
ArrayList<String> ret = new ArrayList<String>();
for (Player p : server.getOnlinePlayers()) {
if (!p.getWorld().equals(world)) {
continue;
}
int px = p.getLocation().getBlockX();
int pz = p.getLocation().getBlockZ();
if ((maxX < px | maxZ < pz) || (minX > px | minZ > pz)) {
continue;
}
ret.add(p.getName());
}
return ret;
}
}
| Redecouverte/CaptureTheLapis | src/redecouverte/event/ctl/Toolbox.java | Java | gpl-3.0 | 1,307 |
package ch.cyberduck.core.transfer;
/*
* Copyright (c) 2002-2013 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to:
* feedback@cyberduck.ch
*/
import ch.cyberduck.core.exception.BackgroundException;
public interface TransferErrorCallback {
/**
* @param item Transfer
* @param status Transfer Status
* @param failure Failure transferring file
* @param pending Number of pending transfers
* @return True to ignore failure continue regardless. False to abort file transfer silently
* @throws BackgroundException Abort file transfer with exception
*/
boolean prompt(TransferItem item, TransferStatus status, BackgroundException failure, int pending) throws BackgroundException;
}
| iterate-ch/cyberduck | core/src/main/java/ch/cyberduck/core/transfer/TransferErrorCallback.java | Java | gpl-3.0 | 1,303 |
package ch.fhnw.stizzo;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
//libreries of reading xml data
import javax.xml.parsers.DocumentBuilderFactory;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class Operations {
private ArrayList<OntologyClass> classes; // it contains all the classes of
// the ontology
private ArrayList<OntologyProperty> properties; // it contains all the
// properties of the
// ontology
private ArrayList<OntologyInstance> instances; // it contains all the
// instances of the ontology
private ArrayList<String> ontologyPreamble; // it contains all the lines
// that occurs between the start
// of the file (ttl) and the
// start of the first ontology
// object
private ArrayList<ADOxxDecisionTable> adoxxDecisionTables; // it contains
// all the ADOxx
// decision
// tables
private ArrayList<VariableMatch> variables;
private PrintWriter writer_status;
private String temp_file = ".temp";
private String status_file = "report_";
private String output_file = "rules_";
private boolean enable_debug_info = true;
public Operations() {
this.classes = new ArrayList<OntologyClass>();
this.properties = new ArrayList<OntologyProperty>();
this.instances = new ArrayList<OntologyInstance>();
this.ontologyPreamble = new ArrayList<String>();
this.adoxxDecisionTables = new ArrayList<ADOxxDecisionTable>();
}
public int[] parseOntology(String path_file, boolean offline) {
// this method parse the ontology
// takes in input the path of the file and it fills the four arrays
// stored this java-class (classes, properties, instances and the
// ontologyPreamble)
// returns an array with the number of classes, properties and instances
// loaded
String line = null;
FileReader reader = null;
Scanner scanner = null;
try {
if (offline) {
reader = new FileReader(path_file);
scanner = new Scanner(reader);
} else {
URL url = new URL(path_file);
scanner = new Scanner(url.openStream());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
// Set the variable "startPreamble" to detect when the preamble finish
boolean preamble = true;
ArrayList<String> temp_type = null;
String temp_name = null;
ArrayList<OntologyAttribute> temp_attributes = null;
boolean titleLine = true;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (preamble) {
// here we are in the preamble
if (!line.startsWith(".")) {
ontologyPreamble.add(line);
} else {
// here we are in the first dot
// where the ontology elements starts
preamble = false;
}
// here we are still in the preamble
// where the line doesn't start with "."
} else {
// here we are not in the preamble and we start to analyse
// the elements of the ontology
if (titleLine && !line.startsWith(".")) {
// first line of the object of the ontology
// here we can find prefix:name of the object
// and we instantiate all the data structures
temp_type = new ArrayList<String>();
temp_name = new String();
temp_attributes = new ArrayList<OntologyAttribute>();
temp_name = line;
titleLine = false;
} else if (!titleLine && line.trim().startsWith(".")) {
// end of the object of ontology
titleLine = true;
for (int t = 0; t < temp_type.size(); t++) {
if (temp_type.get(t).equals("owl:Class")) {
// Parsing a Class
OntologyClass c = new OntologyClass(temp_name, temp_type, temp_attributes);
classes.add(c);
break;
} else if (temp_type.get(t).equals("owl:AnnotationProperty")
|| temp_type.get(t).equals("owl:DatatypeProperty")
|| temp_type.get(t).equals("owl:DeprecatedProperty")
|| temp_type.get(t).equals("owl:FunctionalProperty")
|| temp_type.get(t).equals("owl:ObjectProperty")) {
// Parsing a Property
OntologyProperty p = new OntologyProperty(temp_name, temp_type, temp_attributes);
properties.add(p);
break;
} else if (t == temp_type.size() - 1) {
// Parsing an Istance
OntologyInstance i = new OntologyInstance(temp_name, temp_type, temp_attributes);
instances.add(i);
}
}
} else {
// body of the object of the ontology
String[] arraySplittate = parseAttributeName(line);
if (arraySplittate[0].equals("rdf:type")) {
temp_type.add(arraySplittate[1].replaceAll(";", "").trim());
} else {
// parsing attributes
OntologyAttribute oa;
String[] arraySplittate2 = arraySplittate[1].trim().split("\\^\\^");
// splitting the string with "^^" so we can define type
// and value
if (arraySplittate2.length == 2) {
// if the split has type and value
oa = new OntologyAttribute(arraySplittate[0].replaceAll(";", "").trim(),
arraySplittate2[1].replaceAll(";", "").trim(),
arraySplittate2[0].replaceAll("\"", "").replaceAll(";", "").trim()); // name,type,value
} else {
oa = new OntologyAttribute(arraySplittate[0].replaceAll(";", "").trim(), "",
arraySplittate2[0].replaceAll(";", "").trim()); // name,type,value
}
temp_attributes.add(oa);
}
}
} // end not preamble
} // end while scanner
scanner.close();
// -------------TESTING THE WHOLE ONTOLOGY-------------
/*
* System.out.println("Number of lines of preamble: " +
* ontologyPreamble.size()); System.out.println("Number of classes: "
* +classes.size()); for (int i = 0; i < classes.size(); i++){
* System.out.print(" "
* +classes.get(i).getPrefix()+":"+classes.get(i).getName());
* System.out.print(" - Type: "); for(int
* j=0;j<classes.get(i).getTypes().size();j++){
* System.out.print(classes.get(i).getTypes().get(j)+" ,"); }
* System.out.println(""); } System.out.println("Number of properties: "
* +properties.size()); for (int i = 0; i < properties.size(); i++){
* System.out.print(" "
* +properties.get(i).getPrefix()+":"+properties.get(i).getName());
* System.out.print(" - Type: "); for(int
* j=0;j<properties.get(i).getTypes().size();j++){
* System.out.print(properties.get(i).getTypes().get(j)+" ,"); }
* System.out.println(""); } System.out.println("Number of instances: "
* +instances.size()); for (int i = 0; i < instances.size(); i++){
* System.out.print(" "
* +instances.get(i).getPrefix()+":"+instances.get(i).getName());
* System.out.print(" - Type: "); for(int
* j=0;j<instances.get(i).getTypes().size();j++){
* System.out.print(instances.get(i).getTypes().get(j)+" ,"); }
* System.out.println(""); }
*/
// --------------------------TESTING THE CLASSES OF
// ONTOLOGY---------------------
/*
* System.out.println("Classes:"); for (int i = 0; i < classes.size();
* i++){ System.out.println(" Name: "
* +classes.get(i).getPrefix()+":"+classes.get(i).getName());
* System.out.println(" Types:"); for (int j = 0; j <
* classes.get(i).getTypes().size();j++){ System.out.println(" "
* +classes.get(i).getTypes().get(j)); } System.out.println(
* " Attributes:"); for (int j = 0; j <
* classes.get(i).getAttributes().size(); j++){ System.out.println(
* " name: "+classes.get(i).getAttributes().get(j).getName());
* System.out.println(" type: "
* +classes.get(i).getAttributes().get(j).getType());
* System.out.println(" value: "
* +classes.get(i).getAttributes().get(j).getValue());
* System.out.println(" -------"); }
* System.out.println("--------------------"); }
*
* //--------------------------TESTING THE PROPERTIES OF
* ONTOLOGY---------------------
*
* System.out.println("Property:"); for (int i = 0; i <
* properties.size(); i++){ System.out.println(" Name: "
* +properties.get(i).getPrefix()+":"+properties.get(i).getName());
* System.out.println(" Types:"); for (int j = 0; j <
* properties.get(i).getTypes().size();j++){ System.out.println(
* " "+properties.get(i).getTypes().get(j)); } System.out.println(
* " Attributes:"); for (int j = 0; j <
* properties.get(i).getAttributes().size(); j++){ System.out.println(
* " name: "+properties.get(i).getAttributes().get(j).getName());
* System.out.println(" type: "
* +properties.get(i).getAttributes().get(j).getType());
* System.out.println(" value: "
* +properties.get(i).getAttributes().get(j).getValue());
* System.out.println(" -------"); }
* System.out.println("--------------------"); }
*
* //--------------------------TESTING THE PROPERTIES OF
* ONTOLOGY--------------------- System.out.println("Instances:"); for
* (int i = 0; i < instances.size(); i++){ System.out.println(
* " Name: "
* +instances.get(i).getPrefix()+":"+instances.get(i).getName());
* System.out.println(" Types:"); for (int j = 0; j <
* instances.get(i).getTypes().size();j++){ System.out.println(" "
* +instances.get(i).getTypes().get(j)); } System.out.println(
* " Attributes:"); for (int j = 0; j <
* instances.get(i).getAttributes().size(); j++){ System.out.println(
* " name: "+instances.get(i).getAttributes().get(j).getName());
* System.out.println(" type: "
* +instances.get(i).getAttributes().get(j).getType());
* System.out.println(" value: "
* +instances.get(i).getAttributes().get(j).getValue());
* System.out.println(" -------"); }
* System.out.println("--------------------"); }
*/
return new int[] { classes.size(), properties.size(), instances.size() };
}// end method
public int[] loadXML(String path_file) {// this method load the xml file
// with the ADOxx DecisionTable(s)
// and instances
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
DocumentBuilder builder = null;
Document doc = null;
try {
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
builder = factory.newDocumentBuilder();
doc = builder.parse(new File(test.ui.getTxtOutputDirectory().getText() + "\\" + temp_file));
} catch (Exception e) {
e.printStackTrace();
}
Node root = doc.getFirstChild();
Node models = null;
Node model = null;
Node instance = null;
int numb_model = 0; // this counts how many models have we analysed
for (int i = 0; i < root.getChildNodes().getLength(); i++) {
// We look for the node MODELS
if (root.getChildNodes().item(i).getNodeName().equals("MODELS")) {
models = root.getChildNodes().item(i);
for (int j = 0; j < models.getChildNodes().getLength(); j++) {
// We look for the node MODEL
if (models.getChildNodes().item(j).getNodeName().equals("MODEL")) {
numb_model++;
model = models.getChildNodes().item(j);
for (int k = 0; k < model.getChildNodes().getLength(); k++) {
// We look for the model INSTANCE
if (model.getChildNodes().item(k).getNodeName().equals("INSTANCE")) {
instance = model.getChildNodes().item(k);
// creating a new ADOxxInstance
if (!instance.getAttributes().getNamedItem("class").getNodeValue()
.equals("Boxed Expression")) {
/*
* //here it is checking if the class of the
* adoxx instance is present in the excel
* file for (int y = 0; y <
* objectMatches.size();y++){ if
* (instance.getAttributes().getNamedItem(
* "class").getNodeValue().equals(
* objectMatches.get(y).
* getAdoxxAttributeName()) &&
* objectMatches.get(y).getAdoxxType().trim(
* ).equals("Class")){
*
* //here we are parsing a non-decision
* table instance String inst_id =
* instance.getAttributes().getNamedItem(
* "id").getNodeValue(); String inst_class =
* instance.getAttributes().getNamedItem(
* "class").getNodeValue(); String inst_name
* = instance.getAttributes().getNamedItem(
* "name").getNodeValue();
* ArrayList<ADOxxAttribute> inst_attributes
* = new ArrayList<ADOxxAttribute>();;
* //this arraylist is used to create the
* object ADOxxAttribute
* temp_attributes_to_save = null;
*
*
* ArrayList<Node> temp_attributes = new
* ArrayList<Node>(); //arraylist where to
* collect all the <ATTRIBUTES> of the XML
* of an object for (int z = 0; z <
* instance.getChildNodes().getLength();
* z++){ if
* (instance.getChildNodes().item(z).
* getNodeName().equals("ATTRIBUTE")){ //i
* save all the node ATTRIBUTE in an array
* called temp_attributes
* temp_attributes.add(instance.
* getChildNodes().item(z));
*
* } }
*
* for (int l = 0; l <
* temp_attributes.size();l++){
*
* for (int m = 0; m < objectMatches.size();
* m++){
*
* if
* (temp_attributes.get(l).getAttributes().
* getNamedItem("name").getNodeValue().
* equals(objectMatches.get(m).
* getAdoxxAttributeName()) &&
* inst_class.equals(objectMatches.get(m).
* getAdoxxType())){
*
* if
* (temp_attributes.get(l).getChildNodes().
* getLength() == 0){ //Checking for a
* non-null value; temp_attributes_to_save =
* new ADOxxAttribute(
* temp_attributes.get(l).getAttributes().
* getNamedItem("name").getNodeValue(),
* temp_attributes.get(l).getAttributes().
* getNamedItem("type").getNodeValue(), "");
* inst_attributes.add(
* temp_attributes_to_save);
*
* } else { temp_attributes_to_save = new
* ADOxxAttribute(
* temp_attributes.get(l).getAttributes().
* getNamedItem("name").getNodeValue(),
* temp_attributes.get(l).getAttributes().
* getNamedItem("type").getNodeValue(),
* temp_attributes.get(l).getLastChild().
* getNodeValue()); inst_attributes.add(
* temp_attributes_to_save); }
*
* } }
*
* }
*
* adoxxInstances.add(new
* ADOxxInstance(inst_id,inst_class,
* inst_name,inst_attributes)); }
*
* }
*/
} else {
String DT_name;
String hit_policy = null; // variable for
// ADOxxDecisionTable
String aggregation_indicator = null; // variable
// for
// ADOxxDecisionTable
int priority_of_execution = 0;
ArrayList<Node> temp_attributes = new ArrayList<Node>();
Node temp_record = null;
ArrayList<String> output_values = new ArrayList<String>();
; // arraylist for ADOxxDecisionTable
DT_name = instance.getAttributes().getNamedItem("name").getNodeValue();
// save all the attributes in a temp array:
for (int z = 0; z < instance.getChildNodes().getLength(); z++) {
if (instance.getChildNodes().item(z).getNodeName().equals("ATTRIBUTE")) {
// i save all the node ATTRIBUTE in
// an array called temp_attributes
temp_attributes.add(instance.getChildNodes().item(z));
} else if (instance.getChildNodes().item(z).getNodeName().equals("RECORD")
&& instance.getChildNodes().item(z).getAttributes().item(0)
.getNodeValue().equals("Decision Table GraphRep")) {
// we get the item(0) because
// we suppose that the item(0) is
// the "name=" attribute
temp_record = instance.getChildNodes().item(z);
}
}
Node temp_node = null;
for (int a = 0; a < temp_attributes.size(); a++) {
// searchin for hit policy value
for (int b = 0; b < temp_attributes.get(a).getAttributes().getLength(); b++) {
if (temp_attributes.get(a).getAttributes().item(b).getNodeValue()
.equals("Hit Policy")) {
temp_node = temp_attributes.get(a);
hit_policy = temp_node.getLastChild().getNodeValue();
}
if (temp_attributes.get(a).getAttributes().item(b).getNodeValue()
.equals("Aggregation Indicator")) {
temp_node = temp_attributes.get(a);
aggregation_indicator = temp_node.getLastChild().getNodeValue();
}
if (temp_attributes.get(a).getAttributes().item(b).getNodeValue()
.equals("Priority of Execution")) {
temp_node = temp_attributes.get(a);
if (temp_node.getLastChild().getNodeValue().equals("")) {
priority_of_execution = 0;
} else {
priority_of_execution = Integer
.parseInt(temp_node.getLastChild().getNodeValue());
}
}
}
}
// end cycle for assign hit_policy value
ArrayList<ADOxxDecisionTableEntry> input_names = new ArrayList<ADOxxDecisionTableEntry>(); // arraylist
// for
// ADOxxDecisionTable
ArrayList<ADOxxDecisionTableEntry> output_names = new ArrayList<ADOxxDecisionTableEntry>(); // arraylist
// for
// ADOxxDecisionTable
ArrayList<ADOxxDecisionTableRow> rows = new ArrayList<ADOxxDecisionTableRow>(); // arraylist
// for
// ADOxxDecisionTable
int num_row = 0;
// 1 means names of variable;
// 2 could means output values if the hit
// policy is "Single Hit Priority" or
// "Multiple Hit Rule Order" > 1 could mean
// input/output data for other Hit policies
int num_rule = 0; // variable for DTRow
ArrayList<String> input = null;
// arraylist for DTRow
ArrayList<String> output = null;
// arraylist for DTRow
Node temp_row = null;
Node temp_attribute = null;
for (int a = 0; a < temp_record.getChildNodes().getLength(); a++) {
// iterating all the rows
if (temp_record.getChildNodes().item(a).getNodeName().equals("ROW")) {
temp_row = temp_record.getChildNodes().item(a);
input = new ArrayList<String>();
output = new ArrayList<String>();
for (int b = 0; b < temp_row.getAttributes().getLength(); b++) {
// iterating attributes of the
// rows
if (temp_row.getAttributes().item(b).getNodeName().equals("number")) {
num_row = Integer
.parseInt(temp_row.getAttributes().item(b).getNodeValue());
}
} // end iterating attributes of the
// row
for (int c = 0; c < temp_row.getChildNodes().getLength(); c++) {
// iterating all ATTRIBUTE of
// the ROW
if (temp_row.getChildNodes().item(c).getNodeName()
.equals("ATTRIBUTE")) {
temp_attribute = temp_row.getChildNodes().item(c);
if (num_row == 1) {
// parsing
// name
// of
// values
if (temp_attribute.getChildNodes().getLength() != 0) {
// chicking for
// no-null value
if (temp_attribute.getAttributes().item(0).getNodeValue()
.startsWith("Input")) {
String[] inputSplittate = temp_attribute.getLastChild()
.getNodeValue().trim().replaceAll(" ", "_")
.split("\\.");
ArrayList<String> temp_properties = new ArrayList<String>();
String temp_obj_name = inputSplittate[0];
String temp_dest_name = inputSplittate[inputSplittate.length
- 1];
;
for (int x = 1; x < inputSplittate.length - 1; x++) {
temp_properties.add(inputSplittate[x]);
}
input_names
.add(new ADOxxDecisionTableEntry(temp_obj_name,
temp_properties, temp_dest_name));
} else if (temp_attribute.getAttributes().item(0)
.getNodeValue().startsWith("Output")) {
String[] outputSplittate = temp_attribute.getLastChild()
.getNodeValue().trim().replaceAll(" ", "_")
.split("\\.");
ArrayList<String> temp_properties = new ArrayList<String>();
temp_properties.add(outputSplittate[1]);
String temp_obj_name = outputSplittate[0];
String temp_dest_name = outputSplittate[2];
output_names
.add(new ADOxxDecisionTableEntry(temp_obj_name,
temp_properties, temp_dest_name));
}
num_rule = -1;
} // end if checking for
// no-null values
} else if (num_row == 2 && (hit_policy.equals("Single Hit Priority")
|| hit_policy.equals("Multiple Hit Output Order"))) {
if (temp_attribute.getAttributes().item(0).getNodeValue()
.startsWith("Output")) {
if (temp_attribute.getChildNodes().getLength() != 0){
output_values.add(temp_attribute.getLastChild().getNodeValue().replaceAll(""", "\""));
}
}
} else if (num_row >= 1)
{ // parsing
// data
if (temp_attribute.getChildNodes().getLength() != 0) { // chicking
// for
// no-null
// values
if (temp_attribute.getAttributes().item(0).getNodeValue()
.startsWith("Input")) {
input.add(temp_attribute.getLastChild().getNodeValue()
.replaceAll(""", "\""));
// System.out.println("input:
// "+temp_attribute.getLastChild().getNodeValue());
} else if (temp_attribute.getAttributes().item(0)
.getNodeValue().startsWith("Output")) {
output.add(temp_attribute.getLastChild().getNodeValue()
.replaceAll(""", "\""));
// System.out.println("output:
// "+temp_attribute.getLastChild().getNodeValue());
} else if (temp_attribute.getAttributes().item(0)
.getNodeValue().startsWith("Rule")) {
num_rule = Integer.parseInt(
temp_attribute.getLastChild().getNodeValue());
// System.out.println("rule
// number:
// "+temp_attribute.getLastChild().getNodeValue());
}
} // end if checking for
// no-null values
} // end checking number of
// row
} // end if we are analyzing an
// ATTRIBUTE
} // end iterating ATTRIBUTE of ROW
if (num_row > 2 && (hit_policy.equals("Single Hit Priority")
|| hit_policy.equals("Multiple Hit Output Order"))) {
rows.add(new ADOxxDecisionTableRow(num_rule, input, output));
} else if (num_row > 1 && !hit_policy.equals("Single Hit Priority")
&& !hit_policy.equals("Multiple Hit Output Order")) {
rows.add(new ADOxxDecisionTableRow(num_rule, input, output));
}
} // end if the node it's a row
} // end iterating rows
if (hit_policy.equals("Single Hit Priority")
|| hit_policy.equals("Multiple Hit Output Order")) {
adoxxDecisionTables.add(new ADOxxDecisionTable(DT_name, hit_policy,
aggregation_indicator, input_names, output_names, rows,
priority_of_execution, output_values));
} else {
adoxxDecisionTables
.add(new ADOxxDecisionTable(DT_name, hit_policy, aggregation_indicator,
input_names, output_names, rows, priority_of_execution));
}
}
} // end if
} // end looking for instance
} // end if
} // end for model
} // end if
} // end for models
File a = new File(test.ui.getTxtOutputDirectory().getText() + File.separator + temp_file);
a.delete();
// TEST, INSTANCES ONLY
/*
* for (int i = 0; i < adoxxInstances.size(); i++){
* System.out.println("------------------------"); System.out.println(
* "ID: "+adoxxInstances.get(i).getInst_id()+" Name: "
* +adoxxInstances.get(i).getInst_name()+" Type: "
* +adoxxInstances.get(i).getInst_class()+" #Instances: "
* +adoxxInstances.get(i).getAttributes().size()); for (int j = 0; j <
* adoxxInstances.get(i).getAttributes().size(); j++){
* System.out.println(" Name: "
* +adoxxInstances.get(i).getAttributes().get(j).get(0) + " - Type: "
* +adoxxInstances.get(i).getAttributes().get(j).get(1) + " - Value: "
* +adoxxInstances.get(i).getAttributes().get(j).get(2)); } }
*/
// TEST, DECISION TABLE ONLY (only the first decision table)
/*
* System.out.println("Decision table: " +
* adoxxDecisionTables.get(0).getHit_policy()); System.out.println(
* "Number of names: "+
* adoxxDecisionTables.get(0).getInput_names().size()); for (int i = 0;
* i < adoxxDecisionTables.get(0).getInput_names().size(); i++){
* System.out.println(" "
* +adoxxDecisionTables.get(0).getInput_names().get(i)); }
* System.out.println("Number of types: "+
* adoxxDecisionTables.get(0).getInput_types().size()); for (int i = 0;
* i < adoxxDecisionTables.get(0).getInput_types().size(); i++){
* System.out.println(" "
* +adoxxDecisionTables.get(0).getInput_types().get(i)); }
* System.out.println("Number of rules: "+
* adoxxDecisionTables.get(0).getRows().size());
*
* for (int i = 0; i < adoxxDecisionTables.get(0).getRows().size();
* i++){ System.out.println("Rule number: "+
* adoxxDecisionTables.get(0).getRows().get(i).num_row);
* System.out.println(" inputs:"); for (int j = 0; j <
* adoxxDecisionTables.get(0).getRows().get(i).getInput().size(); j++){
* System.out.println(" "
* +adoxxDecisionTables.get(0).getRows().get(i).getInput().get(j));
*
*
* } for (int k = 0; k <
* adoxxDecisionTables.get(0).getRows().get(i).getOutput().size(); k++){
*
* System.out.println(" outputs:");
*
* System.out.println(" "
* +adoxxDecisionTables.get(0).getRows().get(i).getOutput().get(k));
*
* } }
*/
return new int[] { numb_model, adoxxDecisionTables.size() }; // models,instances,decision
// tables
}
public void patchXML(String path_file, boolean offline) {// this method
// remove the
// DOCTYPE tag
// from the xml
// file and
// re-save the
// file without
// it
ArrayList<String> patched_file = new ArrayList<String>();
String line = null;
FileReader reader = null;
Scanner scanner = null;
try {
if (offline) {
reader = new FileReader(path_file);
scanner = new Scanner(reader);
} else {
URL url = new URL(test.windowPrefs.getTxtWebADOxx().getText());
scanner = new Scanner(url.openStream());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (!line.startsWith("<!DOCTYPE")) {
patched_file.add(line);
}
}
// delete the old file
scanner.close();
// create the new file patched
PrintWriter writer = null;
try {
writer = new PrintWriter(test.ui.getTxtOutputDirectory().getText() + File.separator + temp_file, "UTF-8");
for (int i = 0; i < patched_file.size(); i++) {
writer.println(patched_file.get(i));
}
} catch (Exception e) {
System.out.println(e.getMessage());
;
}
writer.close();
}
private String[] parseAttributeName(String attribute_line) { // this method
// parse the
// name-value
// of an
// Ontology
// attribute
attribute_line.replaceAll(";", "").trim(); // we remove the final ";"
String[] arraySplittate = attribute_line.trim().split(" ");
String temp_value = "";
for (int i = 1; i < arraySplittate.length; i++) {
temp_value = temp_value + " " + arraySplittate[i].trim();
}
return new String[] { arraySplittate[0], temp_value };
}
public void printDecisionTables() {
for (int i = 0; i < adoxxDecisionTables.size(); i++) {
System.out.print(adoxxDecisionTables.get(i).getName() + " - " + "Hit Policy: "
+ adoxxDecisionTables.get(i).getHit_policy() + " - "
+ adoxxDecisionTables.get(i).getAggregation_indicator() + " with "
+ adoxxDecisionTables.get(i).getOutput_names().size() + " outputs and priority "
+ adoxxDecisionTables.get(i).getPriority());
System.out.println();
for (int j = 0; j < adoxxDecisionTables.get(i).getRows().size(); j++) {
System.out.println(adoxxDecisionTables.get(i).getRows().get(j).getNum_rule() + " | "
+ adoxxDecisionTables.get(i).getRows().get(j).getInput() + " | "
+ adoxxDecisionTables.get(i).getRows().get(j).getOutput());
}
System.out.println("===================");
}
}
public void executeDecisionTables() {
writer_status = null;
PrintWriter writer = null;
try {
if (test.windowPrefs.getChkRenameTheOutput().isSelected()) {
writer = new PrintWriter(test.ui.getTxtOutputDirectory().getText() + File.separator + output_file
+ System.currentTimeMillis() + ".txt", "UTF-8");
writer_status = new PrintWriter(test.ui.getTxtOutputDirectory().getText() + File.separator + status_file
+ System.currentTimeMillis() + ".txt", "UTF-8");
} else {
writer = new PrintWriter(
test.ui.getTxtOutputDirectory().getText() + File.separator + output_file + ".txt", "UTF-8");
writer_status = new PrintWriter(
test.ui.getTxtOutputDirectory().getText() + File.separator + status_file + ".txt", "UTF-8");
}
} catch (Exception e) {
System.out.println(e.getMessage());
;
}
// SORTING DECISION TABLES
ArrayList<ADOxxDecisionTable> sorted_DT = new ArrayList<ADOxxDecisionTable>();
while (adoxxDecisionTables.size() != 0) {
int id = -100;
int min = 1000;
for (int h = 0; h < adoxxDecisionTables.size(); h++) {
if (adoxxDecisionTables.get(h).getPriority() < min) {
id = h;
min = adoxxDecisionTables.get(h).getPriority();
}
}
sorted_DT.add(adoxxDecisionTables.get(id));
adoxxDecisionTables.remove(id);
}
adoxxDecisionTables = sorted_DT;
for (int i = 0; i < adoxxDecisionTables.size(); i++) {
ADOxxDecisionTable DT = adoxxDecisionTables.get(i);
variables = new ArrayList<VariableMatch>();
ArrayList<ADOxxDecisionTableNormalizedEntry> temp_input_entries = normalizeInputEntries(
DT.getInput_names());
ArrayList<ADOxxDecisionTableNormalizedEntry> temp_output_entries = normalizeInputEntries(
DT.getOutput_names());
if (enable_debug_info){
//TEST FOR NORMALIZED INPUT ENTRY
for (int k = 0; k < temp_input_entries.size();k++){
printNormalizedEntry(temp_input_entries.get(k));
System.out.println("-------------");
}
for (int k = 0; k < temp_output_entries.size(); k++){
printNormalizedEntry(temp_output_entries.get(k));
System.out.println("-------------");
}
}
// INSTANTIATE VARIABLES OF CLASSES
for (int j = 0; j < temp_input_entries.size(); j++) {
if (!temp_input_entries.get(j).getObject_name().startsWith("?")
&& !variableIsInList(temp_input_entries.get(j).getObject_name())) {
variables.add(new VariableMatch(temp_input_entries.get(j).getObject_name(),
getClassFromString(temp_input_entries.get(j).getObject_name())));
}
}
// UPDATING THE CLASS VARIABLE ON NORMALIZED INPUT
for (int j = 0; j < temp_input_entries.size(); j++) {
for (int k = 0; k < variables.size(); k++) {
if (temp_input_entries.get(j).getObject_name().equals(variables.get(k).getVariableName())) {
temp_input_entries.get(j).setObject_name("?" + temp_input_entries.get(j).getObject_name());
}
if (temp_input_entries.get(j).getDest_name().equals(variables.get(k).getVariableName()) ) {
temp_input_entries.get(j).setDest_name("?" + temp_input_entries.get(j).getDest_name());
}
}
}
// UPDATING THE CLASS VARIABLE ON NORMALIZED OUTPUT
for (int j = 0; j < temp_output_entries.size(); j++) {
for (int k = 0; k < variables.size(); k++) {
if (temp_output_entries.get(j).getObject_name().equals(variables.get(k).getVariableName())) {
temp_output_entries.get(j).setObject_name("?" + temp_output_entries.get(j).getObject_name());
}
if (temp_output_entries.get(j).getDest_name().equals(variables.get(k).getVariableName())) {
temp_output_entries.get(j).setDest_name("?" + temp_output_entries.get(j).getDest_name());
}
}
}
// UPDATING THE CLASS VARIABLE ON OUTPUT
for (int j = 0; j < DT.getOutput_names().size(); j++) {
for (int k = 0; k < variables.size(); k++) {
if (DT.getOutput_names().get(j).getObject_name().equals(variables.get(k).getVariableName())) {
DT.getOutput_names().get(j).setObject_name("?" + DT.getOutput_names().get(j).getObject_name());
}
if (DT.getOutput_names().get(j).getDest_name().equals(variables.get(k).getVariableName())) {
DT.getOutput_names().get(j).setDest_name("?" + DT.getOutput_names().get(j).getDest_name());
}
}
}
if (DT.getHit_policy().equals("Single Hit Unique") ||
//DT.getHit_policy().equals("Single Hit First") ||
DT.getHit_policy().equals("Single Hit Any")) {
// ***********************
// 1 - SINGLE HIT UNIQUE
// ***********************
// ***********************
// 2 - SINGLE HIT ANY
// ***********************
if (DT.getHit_policy().equals("Single Hit Any")){
writer_status.println("WARNING: Cannot check the consistency for the Decision Table \""
+ adoxxDecisionTables.get(i).getName() + "\" with the Hit Policy \"Single Hit Any\" (A)");
}
String alternative_rule_index = "";
for (int l = 0; l < DT.getRows().size(); l++) {
boolean null_value = true;
for (int k = 0; k < DT.getRows().get(l).getInput().size(); k++) {
if (!DT.getRows().get(l).getInput().get(k).equals("-")) {
null_value = false;
}
}
if (null_value) {
alternative_rule_index = l + "";
}
}
for (int j = 0; j < temp_output_entries.size(); j++) {
// PARSING ALL THE OUTPUT
writer.println("CONSTRUCT {");
if (DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name()
.startsWith("?")) {
writer.print(
DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name());
} else {
for (int x = 0; x < variables.size(); x++) {
if (variables.get(x).getOntologyItem().getNameWithoutPrefix().equals(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getObject_name())) {
writer.print(variables.get(x).getVariableName());
}
}
}
// HERE THERE IS THE LIMITATION OF THE ONE PROPERTY ON THE
// OUTPUT ENTRY
writer.print(" "
+ getPropertyFromString(DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry())
.getProperties().get(0)).getName()
+ " " + DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getDest_name());
if (temp_output_entries.get(j).getNum_entry() != DT.getOutput_names().size() - 1) {
writer.println(" . ");
}
writer.println("}");
writer.println("WHERE {");
// DECLARATIONS OF CLASSES
for (int b = 0; b < variables.size(); b++) {
writer.println("?" + variables.get(b).getVariableName() + " rdf:type "
+ variables.get(b).getOntologyItem().getName() + " . ");
}
// INSTANCE OF INPUT ALL RELATIONS
for (int y = 0; y < temp_input_entries.size(); y++) {
if (temp_input_entries.get(y).getIsARelation()) {
writer.print("OPTIONAL {" + temp_input_entries.get(y).getObject_name() + " "
+ getPropertyFromString(temp_input_entries.get(y).getProperty()).getName() + " "
+ temp_input_entries.get(y).getDest_name() + "}");
writer.println(" . ");
}
}
// INSTANCE OF INPUT THAT ARE NOT A RELATION
for (int c = 0; c < temp_input_entries.size(); c++) {
if (temp_input_entries.get(c).getHaveValue() && !temp_input_entries.get(c).getIsARelation() && !temp_input_entries.get(c).getIsAnInstance()) {
writer.print("OPTIONAL {" + temp_input_entries.get(c).getObject_name() + " ");
if (temp_input_entries.get(c).getProperty().equals("label") ) {
writer.print("rdfs:label");
} else {
writer.print(getPropertyFromString(temp_input_entries.get(c).getProperty()).getName());
}
writer.print(" " + temp_input_entries.get(c).getDest_name() + "}");
writer.println(" . ");
}
}
// DECLARATIONS OF OUTPUT
// IF THE OUTPUT IS NOT A DATATYPE, WE NEED TO DEFINE THE
// LABEL OF THE DESTINATION OBJECT
if (temp_output_entries.get(j).getProperty().equals("label")) {
writer.print("OPTIONAL {" + temp_output_entries.get(j).getObject_name() + " " + "rdfs:label"
+ " " + temp_output_entries.get(j).getDest_name() + "}");
if (j != temp_output_entries.size() - 1) {
writer.println(" . ");
}
}
writer.println("BIND(");
int num_input = 0;
if (temp_output_entries.get(j).getHaveValue()) {
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
if (!("" + k).equals(alternative_rule_index)) {
writer.print("IF (");
num_input++;
boolean firstInput = true;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non number/date
// operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // for every input
// WRITING THE OUTPUT FOR THE ROW
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY IN
// THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isADataTypeProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
// Here it is expeecting to find a
// datatype value as output
writer.print(getInstanceFromString(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry())).getName());
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
writer.println(", ");
} // end if output is not "-"
if (k == DT.getRows().size() - 1) {
if(!alternative_rule_index.equals("")){
writer.print(DT.getRows().get(Integer.parseInt(alternative_rule_index))
.getOutput().get(temp_output_entries.get(j).getNum_entry()));
}else {
writer.print("\"\"");
}
for (int z = 0; z < num_input; z++) {
writer.print(")");
}
writer.println(" AS " + temp_output_entries.get(j).getDest_name() + ") .");
writer.println("FILTER(" + temp_output_entries.get(j).getDest_name() + " != \"\") .");
}
} // for every row
}
writer.println("}");
writer.println("");
writer.println("==============");
} // end output
variables.clear();
} else if (DT.getHit_policy().equals("Single Hit Priority")) {
// ***********************
// 3 - SINGLE HIT PRIORITY
// ***********************
for (int j = 0; j < temp_output_entries.size(); j++) {
//===== START THE ORDERING OF ROWS
ArrayList<ADOxxDecisionTableRow> ordered_rows = new ArrayList<ADOxxDecisionTableRow>();
String temp_output_values_array[] = DT.getOutput_values().get(temp_output_entries.get(j).getNum_entry()).split(",");
while (DT.getRows().size()>0){
for (int k = 0; k < temp_output_values_array.length; k++){
Boolean found = false;
while (found == false){
for (int l = DT.getRows().size()-1; l >= 0; l--){
//Finding the rows and adding them to an ordered list
if (DT.getRows().get(l).getOutput().get(temp_output_entries.get(j).getNum_entry()).equals(temp_output_values_array[k].trim())){
ordered_rows.add(DT.getRows().get(l));
DT.getRows().remove(l);
found = true;
}
}
}
}
if (DT.getRows().size()>0){
for (int l = DT.getRows().size()-1; l >= 0; l--){
//adding the remainders rows
ordered_rows.add(DT.getRows().get(l));
DT.getRows().remove(l);
}
}
}
DT.setRows(ordered_rows);
//===== FINISH THE ORDERING OF ROWS
int numberOfInputValues = 0; //THIS NUMBER DEFINES HOW MANY INPUT COLUMNS WITH VALUES ARE IN A TABLE
for (int l = 0; l < temp_input_entries.size(); l++){
if (temp_input_entries.get(l).getHaveValue() == true){
numberOfInputValues++;
}
}
String alternative_rule_index = "";
for (int l = 0; l < DT.getRows().size(); l++) {
boolean null_value = true;
for (int k = 0; k < DT.getRows().get(l).getInput().size(); k++) {
if (!DT.getRows().get(l).getInput().get(k).equals("-")) {
null_value = false;
}
}
if (null_value) {
alternative_rule_index = l + "";
}
}
// PARSING ALL THE OUTPUT
writer.println("CONSTRUCT {");
if (DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name()
.startsWith("?")) {
writer.print(
DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name());
} else {
for (int x = 0; x < variables.size(); x++) {
if (variables.get(x).getOntologyItem().getNameWithoutPrefix().equals(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getObject_name())) {
writer.print(variables.get(x).getVariableName());
}
}
}
// HERE THERE IS THE LIMITATION OF THE ONE PROPERTY ON THE
// OUTPUT ENTRY
writer.print(" "
+ getPropertyFromString(DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry())
.getProperties().get(0)).getName()
+ " " + DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getDest_name());
if (temp_output_entries.get(j).getNum_entry() != DT.getOutput_names().size() - 1) {
writer.println(" . ");
}
writer.println("}");
writer.println("WHERE {");
// DECLARATIONS OF CLASSES
for (int b = 0; b < variables.size(); b++) {
writer.println("?" + variables.get(b).getVariableName() + " rdf:type "
+ variables.get(b).getOntologyItem().getName() + " . ");
}
// INSTANCE OF INPUT ALL RELATIONS
for (int y = 0; y < temp_input_entries.size(); y++) {
if (temp_input_entries.get(y).getIsARelation()) {
writer.print("OPTIONAL {" + temp_input_entries.get(y).getObject_name() + " "
+ getPropertyFromString(temp_input_entries.get(y).getProperty()).getName() + " "
+ temp_input_entries.get(y).getDest_name() + "}");
writer.println(" . ");
}
}
// INSTANCE OF INPUT THAT ARE NOT A RELATION
for (int c = 0; c < temp_input_entries.size(); c++) {
if (temp_input_entries.get(c).getHaveValue() && !temp_input_entries.get(c).getIsARelation() && !temp_input_entries.get(c).getIsAnInstance()) {
writer.print("OPTIONAL {" + temp_input_entries.get(c).getObject_name() + " ");
if (temp_input_entries.get(c).getProperty().equals("label")) {
writer.print("rdfs:label");
} else {
writer.print(getPropertyFromString(temp_input_entries.get(c).getProperty()).getName());
}
writer.print(" " + temp_input_entries.get(c).getDest_name() + "}");
writer.println(" . ");
}
}
// DECLARATIONS OF OUTPUT
// IF THE OUTPUT IS NOT A DATATYPE, WE NEED TO DEFINE THE
// LABEL OF THE DESTINATION OBJECT
if (temp_output_entries.get(j).getProperty().equals("label")) {
writer.print("OPTIONAL {" + temp_output_entries.get(j).getObject_name() + " " + "rdfs:label"
+ " " + temp_output_entries.get(j).getDest_name() + "}");
if (j != temp_output_entries.size() - 1) {
writer.println(" . ");
}
}
writer.println("BIND(");
int num_input = 0;
if (temp_output_entries.get(j).getHaveValue()) {
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
if (!("" + k).equals(alternative_rule_index)) {
writer.print("IF (");
num_input++;
boolean firstInput = true;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non number/date
// operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // for every input
// WRITING THE OUTPUT FOR THE ROW
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY IN
// THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isADataTypeProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
// Here it is expeecting to find a
// datatype value as output
writer.print(getInstanceFromString(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry())).getName());
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
writer.println(", ");
} // end if output is not "-"
if (k == DT.getRows().size() - 1) {
if(!alternative_rule_index.equals("")){
writer.print(DT.getRows().get(Integer.parseInt(alternative_rule_index))
.getOutput().get(temp_output_entries.get(j).getNum_entry()));
}else {
writer.print("\"\"");
}
for (int z = 0; z < num_input; z++) {
writer.print(")");
}
writer.println(" AS " + temp_output_entries.get(j).getDest_name() + ") .");
writer.println("FILTER(" + temp_output_entries.get(j).getDest_name() + " != \"\") .");
}
} // for every row
}
writer.println("}");
writer.println("");
writer.println("==============");
} // end output
variables.clear();
} else if (DT.getHit_policy().equals("Single Hit First")) {
// ***********************
// 4 - SINGLE HIT FIRST
// ***********************
ArrayList<ADOxxDecisionTableRow> sorted_rows = new ArrayList<ADOxxDecisionTableRow>();
while (DT.getRows().size() != 0) {
int id = -100;
int min = 1000;
for (int h = 0; h < DT.getRows().size(); h++) {
if (DT.getRows().get(h).getNum_rule() < min) {
id = h;
min = DT.getRows().get(h).getNum_rule();
}
}
sorted_rows.add(DT.getRows().get(id));
DT.getRows().remove(id);
}
DT.setRows(sorted_rows);
for (int j = 0; j < temp_output_entries.size(); j++) {
int numberOfInputValues = 0; //THIS NUMBER DEFINES HOW MANY INPUT COLUMNS WITH VALUES ARE IN A TABLE
for (int l = 0; l < temp_input_entries.size(); l++){
if (temp_input_entries.get(l).getHaveValue() == true){
numberOfInputValues++;
}
}
String alternative_rule_index = "";
for (int l = 0; l < DT.getRows().size(); l++) {
boolean null_value = true;
for (int k = 0; k < DT.getRows().get(l).getInput().size(); k++) {
if (!DT.getRows().get(l).getInput().get(k).equals("-")) {
null_value = false;
}
}
if (null_value) {
alternative_rule_index = l + "";
}
}
// PARSING ALL THE OUTPUT
writer.println("CONSTRUCT {");
if (DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name()
.startsWith("?")) {
writer.print(
DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name());
} else {
for (int x = 0; x < variables.size(); x++) {
if (variables.get(x).getOntologyItem().getNameWithoutPrefix().equals(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getObject_name())) {
writer.print(variables.get(x).getVariableName());
}
}
}
// HERE THERE IS THE LIMITATION OF THE ONE PROPERTY ON THE
// OUTPUT ENTRY
writer.print(" "
+ getPropertyFromString(DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry())
.getProperties().get(0)).getName()
+ " " + DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getDest_name());
if (temp_output_entries.get(j).getNum_entry() != DT.getOutput_names().size() - 1) {
writer.println(" . ");
}
writer.println("}");
writer.println("WHERE {");
// DECLARATIONS OF CLASSES
for (int b = 0; b < variables.size(); b++) {
writer.println("?" + variables.get(b).getVariableName() + " rdf:type "
+ variables.get(b).getOntologyItem().getName() + " . ");
}
// INSTANCE OF INPUT ALL RELATIONS
for (int y = 0; y < temp_input_entries.size(); y++) {
if (temp_input_entries.get(y).getIsARelation()) {
writer.print("OPTIONAL {" + temp_input_entries.get(y).getObject_name() + " "
+ getPropertyFromString(temp_input_entries.get(y).getProperty()).getName() + " "
+ temp_input_entries.get(y).getDest_name() + "}");
writer.println(" . ");
}
}
// INSTANCE OF INPUT THAT ARE NOT A RELATION
for (int c = 0; c < temp_input_entries.size(); c++) {
if (temp_input_entries.get(c).getHaveValue() && !temp_input_entries.get(c).getIsARelation()&& !temp_input_entries.get(c).getIsAnInstance()) {
writer.print("OPTIONAL {" + temp_input_entries.get(c).getObject_name() + " ");
if (temp_input_entries.get(c).getProperty().equals("label")) {
writer.print("rdfs:label");
} else {
writer.print(getPropertyFromString(temp_input_entries.get(c).getProperty()).getName());
}
writer.print(" " + temp_input_entries.get(c).getDest_name() + "}");
writer.println(" . ");
}
}
// DECLARATIONS OF OUTPUT
// IF THE OUTPUT IS NOT A DATATYPE, WE NEED TO DEFINE THE
// LABEL OF THE DESTINATION OBJECT
if (temp_output_entries.get(j).getProperty().equals("label")) {
writer.print("OPTIONAL {" + temp_output_entries.get(j).getObject_name() + " " + "rdfs:label"
+ " " + temp_output_entries.get(j).getDest_name() + "}");
if (j != temp_output_entries.size() - 1) {
writer.println(" . ");
}
}
writer.println("BIND(");
int num_input = 0;
if (temp_output_entries.get(j).getHaveValue()) {
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
if (!("" + k).equals(alternative_rule_index)) {
writer.print("IF (");
num_input++;
boolean firstInput = true;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non number/date
// operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // for every input
// WRITING THE OUTPUT FOR THE ROW
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY IN
// THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isADataTypeProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
// Here it is expeecting to find a
// datatype value as output
writer.print(getInstanceFromString(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry())).getName());
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
writer.println(", ");
} // end if output is not "-"
if (k == DT.getRows().size() - 1) {
if(!alternative_rule_index.equals("")){
writer.print(DT.getRows().get(Integer.parseInt(alternative_rule_index))
.getOutput().get(temp_output_entries.get(j).getNum_entry()));
}else {
writer.print("\"\"");
}
for (int z = 0; z < num_input; z++) {
writer.print(")");
}
writer.println(" AS " + temp_output_entries.get(j).getDest_name() + ") .");
writer.println("FILTER(" + temp_output_entries.get(j).getDest_name() + " != \"\") .");
}
} // for every row
}
writer.println("}");
writer.println("");
writer.println("==============");
} // end output
variables.clear();
} else if (DT.getHit_policy().equals("Multiple Hit Output Order")) {
// ***********************
// 6 - MULTIPLE HIT OUTPUT ORDER
// ***********************
for (int j = 0; j < temp_output_entries.size(); j++) {
// GETTING ALL THE ROWS OF THE DT
//===== START THE ORDERING OF ROWS
ArrayList<ADOxxDecisionTableRow> ordered_rows = new ArrayList<ADOxxDecisionTableRow>();
String temp_output_values_array[] = DT.getOutput_values().get(temp_output_entries.get(j).getNum_entry()).split(",");
while (DT.getRows().size()>0){
for (int k = 0; k < temp_output_values_array.length; k++){
Boolean found = false;
while (found == false){
for (int l = DT.getRows().size()-1; l >= 0; l--){
//Finding the rows and adding them to an ordered list
if (DT.getRows().get(l).getOutput().get(temp_output_entries.get(j).getNum_entry()).equals(temp_output_values_array[k].trim())){
ordered_rows.add(DT.getRows().get(l));
DT.getRows().remove(l);
found = true;
}
}
}
}
if (DT.getRows().size()>0){
for (int l = DT.getRows().size()-1; l >= 0; l--){
//adding the remainders rows
ordered_rows.add(DT.getRows().get(l));
DT.getRows().remove(l);
}
}
}
DT.setRows(ordered_rows);
//===== FINISH THE ORDERING OF ROWS
for (int k = 0; k < DT.getRows().size(); k++) {
// PARSING ALL THE OUTPUT
writer.println("CONSTRUCT {");
if (DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name()
.startsWith("?")) {
writer.print(DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry())
.getObject_name());
} else {
for (int x = 0; x < variables.size(); x++) {
if (variables.get(x).getOntologyItem().getNameWithoutPrefix()
.equals(DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry())
.getObject_name())) {
writer.print(variables.get(x).getVariableName());
}
}
}
// HERE THERE IS THE LIMITATION OF THE ONE PROPERTY ON
// THE OUTPUT ENTRY
writer.print(" "
+ getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.getName()
+ " "
+ DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getDest_name());
if (temp_output_entries.get(j).getNum_entry() != DT.getOutput_names().size() - 1) {
writer.println(" . ");
}
writer.println("}");
writer.println("WHERE {");
// DECLARATIONS OF CLASSES
for (int b = 0; b < variables.size(); b++) {
writer.println("?" + variables.get(b).getVariableName() + " rdf:type "
+ variables.get(b).getOntologyItem().getName() + " . ");
}
// INSTANCE OF INPUT ALL RELATIONS
for (int y = 0; y < temp_input_entries.size(); y++) {
if (temp_input_entries.get(y).getIsARelation()) {
writer.print("OPTIONAL {" + temp_input_entries.get(y).getObject_name() + " "
+ getPropertyFromString(temp_input_entries.get(y).getProperty()).getName() + " "
+ temp_input_entries.get(y).getDest_name() + "}");
writer.println(" . ");
}
}
// INSTANCE OF INPUT THAT ARE NOT A RELATION
for (int c = 0; c < temp_input_entries.size(); c++) {
if (temp_input_entries.get(c).getHaveValue()
&& !temp_input_entries.get(c).getIsARelation() && !temp_input_entries.get(c).getIsAnInstance()) {
writer.print("OPTIONAL {" + temp_input_entries.get(c).getObject_name() + " ");
if (temp_input_entries.get(c).getProperty().equals("label")) {
writer.print("rdfs:label");
} else {
writer.print(
getPropertyFromString(temp_input_entries.get(c).getProperty()).getName());
}
writer.print(" " + temp_input_entries.get(c).getDest_name() + "}");
writer.println(" . ");
}
}
// DECLARATIONS OF OUTPUT
// IF THE OUTPUT IS NOT A DATATYPE, WE NEED TO DEFINE
// THE LABEL OF THE DESTINATION OBJECT
if (temp_output_entries.get(j).getProperty().equals("label")) {
writer.print("OPTIONAL {" + temp_output_entries.get(j).getObject_name() + " " + "rdfs:label"
+ " " + temp_output_entries.get(j).getDest_name() + "}");
if (j != temp_output_entries.size() - 1) {
writer.println(" . ");
}
}
writer.println("BIND(");
// int num_input = 0;
if (temp_output_entries.get(j).getHaveValue()) {
// IF THE OUTPUT IS DIFFERENT FROM "-"
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
writer.print("IF (");
// num_input++;
boolean firstInput = true;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non number/date
// operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // for every input
// WRITING THE OUTPUT FOR THE ROW
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY IN
// THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isADataTypeProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
// Here it is expeecting to find a
// datatype value as output
writer.print(getInstanceFromString(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry())).getName());
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
writer.println(", ");
} // end if output is not "-"
writer.print("\"\"");
writer.print(")");
writer.println(" AS " + temp_output_entries.get(j).getDest_name() + ") .");
writer.println("FILTER(" + temp_output_entries.get(j).getDest_name() + " != \"\") .");
}
writer.println("}");
writer.println("");
writer.println("==============");
} // end rows
} // end output
variables.clear();
} else if (DT.getHit_policy().equals("Multiple Hit Rule Order")) {
// ***********************
// 7 - MULTIPLE HIT RULE ORDER
// ***********************
ArrayList<ADOxxDecisionTableRow> sorted_rows = new ArrayList<ADOxxDecisionTableRow>();
while (DT.getRows().size() != 0) {
int id = -100;
int min = 1000;
for (int h = 0; h < DT.getRows().size(); h++) {
if (DT.getRows().get(h).getNum_rule() < min) {
id = h;
min = DT.getRows().get(h).getNum_rule();
}
}
sorted_rows.add(DT.getRows().get(id));
DT.getRows().remove(id);
}
DT.setRows(sorted_rows);
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
// PARSING ALL THE OUTPUT
for (int j = 0; j < temp_output_entries.size(); j++) {
writer.println("CONSTRUCT {");
if (DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name()
.startsWith("?")) {
writer.print(DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry())
.getObject_name());
} else {
for (int x = 0; x < variables.size(); x++) {
if (variables.get(x).getOntologyItem().getNameWithoutPrefix()
.equals(DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry())
.getObject_name())) {
writer.print(variables.get(x).getVariableName());
}
}
}
// HERE THERE IS THE LIMITATION OF THE ONE PROPERTY ON
// THE OUTPUT ENTRY
writer.print(" "
+ getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.getName()
+ " "
+ DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getDest_name());
if (temp_output_entries.get(j).getNum_entry() != DT.getOutput_names().size() - 1) {
writer.println(" . ");
}
writer.println("}");
writer.println("WHERE {");
// DECLARATIONS OF CLASSES
for (int b = 0; b < variables.size(); b++) {
writer.println("?" + variables.get(b).getVariableName() + " rdf:type "
+ variables.get(b).getOntologyItem().getName() + " . ");
}
// INSTANCE OF INPUT ALL RELATIONS
for (int y = 0; y < temp_input_entries.size(); y++) {
if (temp_input_entries.get(y).getIsARelation()) {
writer.print("OPTIONAL {" + temp_input_entries.get(y).getObject_name() + " "
+ getPropertyFromString(temp_input_entries.get(y).getProperty()).getName() + " "
+ temp_input_entries.get(y).getDest_name() + "}");
writer.println(" . ");
}
}
// INSTANCE OF INPUT THAT ARE NOT A RELATION
for (int c = 0; c < temp_input_entries.size(); c++) {
if (temp_input_entries.get(c).getHaveValue()
&& !temp_input_entries.get(c).getIsARelation() && !temp_input_entries.get(c).getIsAnInstance()) {
writer.print("OPTIONAL {" + temp_input_entries.get(c).getObject_name() + " ");
if (temp_input_entries.get(c).getProperty().equals("label")) {
writer.print("rdfs:label");
} else {
writer.print(
getPropertyFromString(temp_input_entries.get(c).getProperty()).getName());
}
writer.print(" " + temp_input_entries.get(c).getDest_name() + "}");
writer.println(" . ");
}
}
// DECLARATIONS OF OUTPUT
// IF THE OUTPUT IS NOT A DATATYPE, WE NEED TO DEFINE
// THE LABEL OF THE DESTINATION OBJECT
if (temp_output_entries.get(j).getProperty().equals("label")) {
writer.print("OPTIONAL {" + temp_output_entries.get(j).getObject_name() + " " + "rdfs:label"
+ " " + temp_output_entries.get(j).getDest_name() + "}");
if (j != temp_output_entries.size() - 1) {
writer.println(" . ");
}
}
writer.println("BIND(");
// int num_input = 0;
if (temp_output_entries.get(j).getHaveValue()) {
// IF THE OUTPUT IS DIFFERENT FROM "-"
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
writer.print("IF (");
// num_input++;
boolean firstInput = true;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non number/date
// operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // for every input
// WRITING THE OUTPUT FOR THE ROW
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY IN
// THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isADataTypeProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
// Here it is expeecting to find a
// datatype value as output
writer.print(getInstanceFromString(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry())).getName());
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
writer.println(", ");
} // end if output is not "-"
writer.print("\"\"");
writer.print(")");
writer.println(" AS " + temp_output_entries.get(j).getDest_name() + ") .");
writer.println("FILTER(" + temp_output_entries.get(j).getDest_name() + " != \"\") .");
}
writer.println("}");
writer.println("");
writer.println("==============");
} // end outputs
} // end rows
variables.clear();
} else if (DT.getHit_policy().equals("Multiple Hit Collection")) {
// ***********************
// 8 - MULTIPLE HIT COLLECTION
// ***********************
int numberOfInputValues = 0; //THIS NUMBER DEFINES HOW MANY INPUT COLUMNS WITH VALUES ARE IN A TABLE
for (int l = 0; l < temp_input_entries.size(); l++){
if (temp_input_entries.get(l).getHaveValue() == true){
numberOfInputValues++;
}
}
String alternative_rule_index = "";
for (int l = 0; l < DT.getRows().size(); l++) {
boolean null_value = true;
for (int k = 0; k < DT.getRows().get(l).getInput().size(); k++) {
if (!DT.getRows().get(l).getInput().get(k).equals("-")) {
null_value = false;
}
}
if (null_value) {
alternative_rule_index = l + "";
}
}
for (int j = 0; j < temp_output_entries.size(); j++) {
// PARSING ALL THE OUTPUT
writer.println("CONSTRUCT {");
if (DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name()
.startsWith("?")) {
writer.print(
DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getObject_name());
} else {
for (int x = 0; x < variables.size(); x++) {
if (variables.get(x).getOntologyItem().getNameWithoutPrefix().equals(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getObject_name())) {
writer.print(variables.get(x).getVariableName());
}
}
}
// HERE THERE IS THE LIMITATION OF THE ONE PROPERTY ON THE
// OUTPUT ENTRY
writer.print(" "
+ getPropertyFromString(DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry())
.getProperties().get(0)).getName()
+ " " + DT.getOutput_names().get(temp_output_entries.get(j).getNum_entry()).getDest_name());
if (temp_output_entries.get(j).getNum_entry() != DT.getOutput_names().size() - 1) {
writer.println(" . ");
}
writer.println("}");
writer.println("WHERE {");
// DECLARATIONS OF CLASSES
for (int b = 0; b < variables.size(); b++) {
writer.println("?" + variables.get(b).getVariableName() + " rdf:type "
+ variables.get(b).getOntologyItem().getName() + " . ");
}
// INSTANCE OF INPUT ALL RELATIONS
for (int y = 0; y < temp_input_entries.size(); y++) {
if (temp_input_entries.get(y).getIsARelation()) {
writer.print("OPTIONAL {" + temp_input_entries.get(y).getObject_name() + " "
+ getPropertyFromString(temp_input_entries.get(y).getProperty()).getName() + " "
+ temp_input_entries.get(y).getDest_name() + "}");
writer.println(" . ");
}
}
// INSTANCE OF INPUT THAT ARE NOT A RELATION
for (int c = 0; c < temp_input_entries.size(); c++) {
if (temp_input_entries.get(c).getHaveValue() && !temp_input_entries.get(c).getIsARelation() && !temp_input_entries.get(c).getIsAnInstance()) {
writer.print("OPTIONAL {" + temp_input_entries.get(c).getObject_name() + " ");
if (temp_input_entries.get(c).getProperty().equals("label")) {
writer.print("rdfs:label");
} else {
writer.print(getPropertyFromString(temp_input_entries.get(c).getProperty()).getName());
}
writer.print(" " + temp_input_entries.get(c).getDest_name() + "}");
writer.println(" . ");
}
}
// DECLARATIONS OF OUTPUT
// IF THE OUTPUT IS NOT A DATATYPE, WE NEED TO DEFINE THE
// LABEL OF THE DESTINATION OBJECT
if (temp_output_entries.get(j).getProperty().equals("label")) {
writer.print("OPTIONAL {" + temp_output_entries.get(j).getObject_name() + " " + "rdfs:label"
+ " " + temp_output_entries.get(j).getDest_name() + "}");
if (j != temp_output_entries.size() - 1) {
writer.println(" . ");
}
}
if (DT.getAggregation_indicator().equals("Min")) {
// ===============
// MIN AGGREGATOR
// ===============
int num_input = 0;
boolean firstRow = true;
if (temp_output_entries.get(j).getHaveValue()) {
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
// IF THE OUTPUT IS DIFFERENT FROM "-"
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-") && !("" + k).equals(alternative_rule_index)) {
boolean firstInput = true;
writer.print("BIND(");
writer.print("IF (");
num_input++;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non
// number/date operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // end for every input
if (!firstRow) {
writer.print(" && ?MIN" + (num_input - 1) + " > " + DT.getRows().get(k)
.getOutput().get(temp_output_entries.get(j).getNum_entry()));
}
// WRITING THE OUTPUT FOR THE ROW IF TRUE
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM
// "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY
// IN THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isADataTypeProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
// Here it is expeecting to find a
// datatype value as output
writer.print(getInstanceFromString(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry())).getName());
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
// WRITING THE OUTPUT FOR THE ROW IF FALSE
writer.print(", ");
if (firstRow) {
// HERE I WRITE THE ALTERNATIVE VALUE IF
// IT EXISTS
if (!alternative_rule_index.equals("")) {
writer.print(DT.getRows().get(Integer.parseInt(alternative_rule_index))
.getOutput().get(temp_output_entries.get(j).getNum_entry()));
} else {
writer.print("2147483647");
}
} else {
writer.print("?MIN" + (num_input - 1));
}
writer.print(")");
if (k == DT.getRows().size() - 1) {
writer.println(" AS " + temp_output_entries.get(j).getDest_name() + ") .");
} else {
writer.println(" AS " + "?MIN" + num_input + ") .");
}
} // end if output is not "-"
firstRow = false;
} // for every row
writer.println("FILTER(" + temp_output_entries.get(j).getDest_name() + " != 2147483647) .");
}
writer.println("}");
writer.println("");
} else if (DT.getAggregation_indicator().equals("Max")) {
// ===============
// MAX AGGREGATOR
// ===============
int num_input = 0;
boolean firstRow = true;
if (temp_output_entries.get(j).getHaveValue()) {
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
// IF THE OUTPUT IS DIFFERENT FROM "-"
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-") && !("" + k).equals(alternative_rule_index)) {
boolean firstInput = true;
writer.print("BIND(");
writer.print("IF (");
num_input++;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non
// number/date operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // end for every input
if (!firstRow) {
writer.print(" && ?MAX" + (num_input - 1) + " < " + DT.getRows().get(k)
.getOutput().get(temp_output_entries.get(j).getNum_entry()));
}
// WRITING THE OUTPUT FOR THE ROW IF TRUE
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM
// "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY
// IN THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isADataTypeProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
// Here it is expeecting to find a
// datatype value as output
writer.print(getInstanceFromString(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry())).getName());
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
// WRITING THE OUTPUT FOR THE ROW IF FALSE
writer.print(", ");
if (firstRow) {
// HERE I WRITE THE ALTERNATIVE VALUE IF
// IT EXISTS
if (!alternative_rule_index.equals("")) {
writer.print(DT.getRows().get(Integer.parseInt(alternative_rule_index))
.getOutput().get(temp_output_entries.get(j).getNum_entry()));
} else {
writer.print("-2147483648");
}
} else {
writer.print("?MAX" + (num_input - 1));
}
writer.print(")");
if (k == DT.getRows().size() - 1) {
writer.println(" AS " + temp_output_entries.get(j).getDest_name() + ") .");
} else {
writer.println(" AS " + "?MAX" + num_input + ") .");
}
} // end if output is not "-"
firstRow = false;
} // for every row
writer.println("FILTER(" + temp_output_entries.get(j).getDest_name() + " != -2147483648) .");
}
writer.println("}");
writer.println("");
} else if (DT.getAggregation_indicator().equals("Sum")) {
// ===============
// SUM AGGREGATOR
// ===============
int num_input = 0;
boolean firstRow = true;
if (temp_output_entries.get(j).getHaveValue()) {
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
// IF THE OUTPUT IS DIFFERENT FROM "-"
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-") && !("" + k).equals(alternative_rule_index)) {
boolean firstInput = true;
writer.print("BIND(");
writer.print("IF (");
num_input++;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non
// number/date operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // end for every input
// WRITING THE OUTPUT FOR THE ROW IF TRUE
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM
// "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY
// IN THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isAnObjectProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(
"?SUM" + (num_input - 1) + "+"
+ DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
if (firstRow) {
writer.print(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
writer.print("?SUM" + (num_input - 1) + "+" + DT.getRows().get(k)
.getOutput().get(temp_output_entries.get(j).getNum_entry()));
}
// Here it is expeecting to find a
// datatype value as output
// writer.print(DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry()));
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
// WRITING THE OUTPUT FOR THE ROW IF FALSE
writer.print(", ");
if (firstRow) {
// HERE I WRITE THE ALTERNATIVE VALUE IF
// IT EXISTS
if (!alternative_rule_index.equals("")) {
//THERE IS NO ALTERNATIVE RULE IN THe SUM AGGREGATOR
// writer.print(DT.getRows().get(Integer.parseInt(alternative_rule_index)).getOutput().get(temp_output_entries.get(j).getNum_entry()));
writer.print("0");
} else {
writer.print("0");
}
} else {
writer.print("?SUM" + (num_input - 1));
}
writer.print(")");
if (k == DT.getRows().size() - 1) {
writer.println(" AS " + temp_output_entries.get(j).getDest_name() + ") .");
} else {
writer.println(" AS " + "?SUM" + num_input + ") .");
}
} // end if output is not "-"
firstRow = false;
} // for every row
//writer.println("FILTER(" + temp_output_entries.get(j).getDest_name() + " != \"\") .");
}
writer.println("}");
writer.println("");
} else if (DT.getAggregation_indicator().equals("Count")) {
// ===============
// COUNT AGGREGATOR
// ===============
int num_input = 0;
boolean firstRow = true;
if (temp_output_entries.get(j).getHaveValue()) {
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
// IF THE OUTPUT IS DIFFERENT FROM "-"
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-") && !("" + k).equals(alternative_rule_index)) {
boolean firstInput = true;
writer.print("BIND(");
writer.print("IF (");
num_input++;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non
// number/date operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // end for every input
// WRITING THE OUTPUT FOR THE ROW IF TRUE
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM
// "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY
// IN THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isAnObjectProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(getInstanceFromString(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry())).getName());
} else {
if (firstRow) {
writer.print("1");
} else {
writer.print("?COUNT" + ((num_input) - 1) + "+1");
}
// Here it is expeecting to find a
// datatype value as output
// writer.print(DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry()));
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
// WRITING THE OUTPUT FOR THE ROW IF FALSE
writer.print(", ");
if (firstRow) {
// HERE I WRITE THE ALTERNATIVE VALUE IF
// IT EXISTS
if (!alternative_rule_index.equals("")) {
//THIS AGGREGATOR DOESN'T HAVE AN ALTERNATIVE RULE
// writer.print(DT.getRows().get(Integer.parseInt(alternative_rule_index)).getOutput().get(temp_output_entries.get(j).getNum_entry()));
writer.print("0");
} else {
writer.print("0");
}
} else {
writer.print("?COUNT" + (num_input - 1));
}
writer.print(")");
if (k == DT.getRows().size() - 1) {
writer.println(" AS " + temp_output_entries.get(j).getDest_name() + ") .");
} else {
writer.println(" AS " + "?COUNT" + num_input + ") .");
}
} // end if output is not "-"
firstRow = false;
} // for every row
//writer.println("FILTER(" + temp_output_entries.get(j).getDest_name() + " != \"\") .");
}
writer.println("}");
writer.println("");
} else if (DT.getAggregation_indicator().equals("Avg")) {
// ===============
// AVG AGGREGATOR
// ===============
int num_input = 0;
boolean firstRow = true;
//HERE STARTS THE SUM PART
if (temp_output_entries.get(j).getHaveValue()) {
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
// IF THE OUTPUT IS DIFFERENT FROM "-"
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-") && !("" + k).equals(alternative_rule_index)) {
boolean firstInput = true;
writer.print("BIND(");
writer.print("IF (");
num_input++;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non
// number/date operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // end for every input
// WRITING THE OUTPUT FOR THE ROW IF TRUE
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM
// "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY
// IN THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isAnObjectProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(
"?SUM" + (num_input - 1) + "+"
+ DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
if (firstRow) {
writer.print(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry()));
} else {
writer.print("?SUM" + (num_input - 1) + "+" + DT.getRows().get(k)
.getOutput().get(temp_output_entries.get(j).getNum_entry()));
}
// Here it is expeecting to find a
// datatype value as output
// writer.print(DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry()));
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
// WRITING THE OUTPUT FOR THE ROW IF FALSE
writer.print(", ");
if (firstRow) {
// HERE I WRITE THE ALTERNATIVE VALUE IF
// IT EXISTS
if (!alternative_rule_index.equals("")) {
//THERE IS NO ALTERNATIVE RULE IN THe SUM AGGREGATOR
// writer.print(DT.getRows().get(Integer.parseInt(alternative_rule_index)).getOutput().get(temp_output_entries.get(j).getNum_entry()));
writer.print("0");
} else {
writer.print("0");
}
} else {
writer.print("?SUM" + (num_input - 1));
}
writer.print(")");
if (k == DT.getRows().size() - 1) {
writer.println(" AS " + "?TOTSUM" + ") .");
} else {
writer.println(" AS " + "?SUM" + num_input + ") .");
}
} // end if output is not "-"
firstRow = false;
} // for every row
//writer.println("FILTER(" + "?TOTSUM" + " != \"\") .");
}
//HERE STARTS THE COUNT PART:
num_input = 0;
firstRow = true;
if (temp_output_entries.get(j).getHaveValue()) {
// GETTING ALL THE ROWS OF THE DT
for (int k = 0; k < DT.getRows().size(); k++) {
// IF THE OUTPUT IS DIFFERENT FROM "-"
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-") && !("" + k).equals(alternative_rule_index)) {
boolean firstInput = true;
writer.print("BIND(");
writer.print("IF (");
num_input++;
// PARSING ALL THE EFFECTIVE INPUTS
for (int l = 0; l < temp_input_entries.size(); l++) {
if (temp_input_entries.get(l).getHaveValue() && !DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).equals("-")) {
if (!firstInput) {
writer.print(" && ");
}
// WRITING THE DESTINATION INPUT
// CRITERIA
writer.print(temp_input_entries.get(l).getDest_name());
// WRITING THE OPERATOR OF INPUT
// CRITERIA
String[] arraySplittate = DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()).split(" ");
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is parsing a number/date
// operator
writer.print(arraySplittate[0]);
} else {
// Here is parsing a non
// number/date operator
writer.print(" = ");
}
// WRITING THE INPUT DATA CRITERIA
if (arraySplittate.length == 2 && arraySplittate[0].startsWith("=")
|| arraySplittate[0].startsWith(">")
|| arraySplittate[0].startsWith("<")) {
// Here is writing a date/number
// value
writer.print(arraySplittate[1]);
} else if (temp_input_entries.get(l).getIsARelation() || temp_input_entries.get(l).getIsAnInstance()) {
writer.print(getInstanceFromString(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry())).getName());
} else {
// Here is writing a "string" or
// value
writer.print(DT.getRows().get(k).getInput()
.get(temp_input_entries.get(l).getNum_entry()));
}
firstInput = false;
}
} // end for every input
// WRITING THE OUTPUT FOR THE ROW IF TRUE
writer.print(", ");
if (!DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry())
.equals("-")) {
// IF THE OUTPUT NAME IS DIFFERENT FROM
// "-"
// HERE THERE IS THE LIMIT OF 1 PROPERTY
// IN THE OUTPUT NAME
if (getPropertyFromString(DT.getOutput_names()
.get(temp_output_entries.get(j).getNum_entry()).getProperties().get(0))
.isAnObjectProperty()) {
// Here it is expecting to find an
// instance as output
writer.print(getInstanceFromString(DT.getRows().get(k).getOutput()
.get(temp_output_entries.get(j).getNum_entry())).getName());
} else {
if (firstRow) {
writer.print("1");
} else {
writer.print("?COUNT" + ((num_input) - 1) + "+1");
}
// Here it is expeecting to find a
// datatype value as output
// writer.print(DT.getRows().get(k).getOutput().get(temp_output_entries.get(j).getNum_entry()));
}
} else {
// IF THE OUTPUT IS "-"
writer.print("\"\"");
}
// WRITING THE OUTPUT FOR THE ROW IF FALSE
writer.print(", ");
if (firstRow) {
// HERE I WRITE THE ALTERNATIVE VALUE IF
// IT EXISTS
if (!alternative_rule_index.equals("")) {
//THIS AGGREGATOR DOESN'T HAVE AN ALTERNATIVE RULE
// writer.print(DT.getRows().get(Integer.parseInt(alternative_rule_index)).getOutput().get(temp_output_entries.get(j).getNum_entry()));
writer.print("0");
} else {
writer.print("0");
}
} else {
writer.print("?COUNT" + (num_input - 1));
}
writer.print(")");
if (k == DT.getRows().size() - 1) {
writer.println(" AS " + "?TOTCOUNT" + ") .");
} else {
writer.println(" AS " + "?COUNT" + num_input + ") .");
}
} // end if output is not "-"
firstRow = false;
} // for every row
writer.println("FILTER(" + "?TOTCOUNT" + " != 0) .");
writer.println("BIND(?TOTSUM/?TOTCOUNT AS " + temp_output_entries.get(j).getDest_name() + ")");
}
writer.println("}");
writer.println("");
} else {
writer_status.println(
"ERROR: AGGREGATOR not found/detected for the Decision Table \"" + DT.getName() + "\"");
}
writer.println("==============");
} // end output
variables.clear();
} else {
writer_status.println(
"ERROR: HIT POLICY not found/detected for the Decision Table \"" + DT.getName() + "\"");
}
}
writer.close();
writer_status.close();
JOptionPane.showMessageDialog(null, "Decision Tables transformed with success!", "Success!",
JOptionPane.INFORMATION_MESSAGE);
}
private OntologyClass getClassFromString(String class_name) {
OntologyClass result = null;
if (class_name.contains(":")) {
for (int i = 0; i < classes.size(); i++) {
if (classes.get(i).getName().equals(class_name)) {
result = classes.get(i);
}
}
} else {
for (int i = 0; i < classes.size(); i++) {
if (classes.get(i).getNameWithoutPrefix().equals(class_name)) {
result = classes.get(i);
}
}
}
if (result == null) {
writer_status.println("WARNING: Cannot find a class for the variable: " + class_name);
result = new OntologyClass(class_name, new ArrayList<String>(), new ArrayList<OntologyAttribute>());
}
return result;
}
private OntologyInstance getInstanceFromString(String instance_name) {
OntologyInstance result = null;
if (instance_name.contains(":")) {
for (int i = 0; i < instances.size(); i++) {
if (instances.get(i).getName().equals(instance_name)) {
result = instances.get(i);
}
}
} else {
for (int i = 0; i < instances.size(); i++) {
if (instances.get(i).getNameWithoutPrefix().equals(instance_name)) {
result = instances.get(i);
}
}
}
if (result == null && !instance_name.trim().toLowerCase().equals("true") && !instance_name.trim().toLowerCase().equals("false") && !instance_name.startsWith("\"")) {
writer_status.println("WARNING: Cannot find an instance for the variable: " + instance_name);
}
if (result == null) {
result = new OntologyInstance(instance_name, new ArrayList<String>(), new ArrayList<OntologyAttribute>());
}
return result;
}
private OntologyProperty getPropertyFromString(String property_name) {
OntologyProperty result = null;
if (property_name.contains(":")) {
for (int i = 0; i < properties.size(); i++) {
if (properties.get(i).getName().equals(property_name)) {
result = properties.get(i);
}
}
} else {
for (int i = 0; i < properties.size(); i++) {
if (properties.get(i).getNameWithoutPrefix().equals(property_name)) {
result = properties.get(i);
}
}
}
if (result == null) {
result = new OntologyProperty(property_name, new ArrayList<String>(), new ArrayList<OntologyAttribute>());
writer_status.println("WARNING: Cannot find a property with the name: " + property_name);
}
return result;
}
private boolean variableIsInList(String variable_name) {
boolean result = false;
for (int i = 0; i < variables.size(); i++) {
if (variables.get(i).getVariableName().equals(variable_name)) {
result = true;
}
}
return result;
}
private boolean stringIsInList(String name, ArrayList<String> list) {
boolean result = false;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(name)) {
result = true;
}
}
return result;
}
private ArrayList<ADOxxDecisionTableNormalizedEntry> normalizeInputEntries(
ArrayList<ADOxxDecisionTableEntry> entries) {
ArrayList<ADOxxDecisionTableNormalizedEntry> result = new ArrayList<ADOxxDecisionTableNormalizedEntry>();
for (int i = 0; i < entries.size(); i++) {
if (entries.get(i).getProperties().size() == 0){
//HERE we are parsing a single instance without relation
result.add(new ADOxxDecisionTableNormalizedEntry(entries.get(i).getObject_name(), entries.get(i).getObject_name(), false, true, i,true));
} else if (entries.get(i).getProperties().size() == 1) {
if (getPropertyFromString(entries.get(i).getProperties().get(0)).isAnObjectProperty()) {
// Here we are parsing both an INPUT entry and a RELATION
result.add(new ADOxxDecisionTableNormalizedEntry(entries.get(i).getObject_name(),
entries.get(i).getProperties().get(0), entries.get(i).getDest_name(), true, true, i, false));
} else if (getPropertyFromString(entries.get(i).getProperties().get(0)).isADataTypeProperty()) {
// Here we are parsing an INPUT entry only
result.add(new ADOxxDecisionTableNormalizedEntry(entries.get(i).getObject_name(),
entries.get(i).getProperties().get(0), entries.get(i).getDest_name(), false, true, i, false));
} else {
result.add(new ADOxxDecisionTableNormalizedEntry(entries.get(i).getObject_name(),
entries.get(i).getProperties().get(0), entries.get(i).getDest_name(), false, true, i, false));
}
} else {
// Here we are parsing a COMBO
String next_source = "";
for (int j = 0; j < entries.get(i).getProperties().size(); j++) {
if (j == 0) {
next_source = entries.get(i).getObject_name();
}
if (j != entries.get(i).getProperties().size() - 1) {
result.add(new ADOxxDecisionTableNormalizedEntry(next_source,
entries.get(i).getProperties().get(j), "?" + i + "temp" + j, true, false, false));
next_source = "?" + i + "temp" + j;
} else {
// Here we are parsing the last element of a COMBO
if (getPropertyFromString(entries.get(i).getProperties().get(j)).isAnObjectProperty()) {
// Here the last property is an objectProperty
result.add(new ADOxxDecisionTableNormalizedEntry(next_source,
entries.get(i).getProperties().get(j), entries.get(i).getDest_name(), true, true, i, false));
} else if (getPropertyFromString(entries.get(i).getProperties().get(j)).isADataTypeProperty()) {
// Here the last property is a DataType Property
result.add(new ADOxxDecisionTableNormalizedEntry(next_source,
entries.get(i).getProperties().get(j), entries.get(i).getDest_name(), false, true,
i, false));
} else {
// Here i cannot identify the property
result.add(new ADOxxDecisionTableNormalizedEntry(next_source,
entries.get(i).getProperties().get(j), entries.get(i).getDest_name(), true, true, false));
}
} // end if we are parsing the last property
}
} // end parsing a combo
}
return result;
}
public void testing() {
// THIS METHOD TESTS ALL THE RELATIONS, INPUTS AND OUTPUTS
for (int i = 0; i < adoxxDecisionTables.size(); i++) {
ADOxxDecisionTable DT = adoxxDecisionTables.get(i);
ArrayList<ADOxxDecisionTableNormalizedEntry> temp_output_entries = normalizeInputEntries(
DT.getOutput_names());
ArrayList<ADOxxDecisionTableNormalizedEntry> temp_input_entries = normalizeInputEntries(
DT.getInput_names());
for (int j = 0; j < temp_input_entries.size(); j++) {
System.out.println("Relation: " + temp_input_entries.get(j).getIsARelation() + " / " + "Input: "
+ temp_input_entries.get(j).getHaveValue() + " - " + temp_input_entries.get(j).getNum_entry()
+ " - " + temp_input_entries.get(j).getObject_name() + " - "
+ temp_input_entries.get(j).getProperty() + " - " + temp_input_entries.get(j).getDest_name());
}
System.out.println("-------------");
for (int j = 0; j < temp_output_entries.size(); j++) {
System.out.println("Relation: " + temp_output_entries.get(j).getIsARelation() + " / " + "Input: "
+ temp_output_entries.get(j).getHaveValue() + " - " + temp_output_entries.get(j).getNum_entry()
+ " - " + temp_output_entries.get(j).getObject_name() + " - "
+ temp_output_entries.get(j).getProperty() + " - " + temp_output_entries.get(j).getDest_name());
}
System.out.println("===========");
System.out.println("===========");
}
}
/*
* public void performConstructRule(ParameterizedSparqlString queryStr) {
* Model temp = ModelFactory.createOntologyModel();
* addNamespacesToQuery(queryStr); QueryExecution qexec =
* QueryExecutionFactory.create(queryStr.toString(), rdfModel); temp =
* qexec.execConstruct(); rdfModel.add(temp); }
*/
public void printNormalizedEntry (ADOxxDecisionTableNormalizedEntry normalized_entry){
System.out.println("NEW ENTRY:");
System.out.println(" Object_name: " + normalized_entry.getObject_name());
//if (normalized_entry.getProperty() != null){
System.out.println(" Property: " + normalized_entry.getProperty());
//}else {
//System.out.println(" Property: " + "NOT DEFINED");
//}
System.out.println(" Dest_name: " + normalized_entry.getDest_name());
System.out.println(" isARelation: " + normalized_entry.getIsARelation());
System.out.println(" haveValue: " + normalized_entry.getHaveValue());
//if (Integer.toString(normalized_entry.getNum_entry()) != null){
System.out.println(" num_entry: " + normalized_entry.getNum_entry());
//}else {
// System.out.println(" num_entry: " + "NOT DEFINED");
//}
System.out.println(" isAnInstance: " + normalized_entry.getIsAnInstance());
}
}
| Stizzo/SPARQL_Generator | SPARQL_Generator/src/ch/fhnw/stizzo/Operations.java | Java | gpl-3.0 | 123,707 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NuspecPortageGenerator
{
partial class GeneralSettingsPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.radioButton_UsePortage = new System.Windows.Forms.RadioButton();
this.radioButton_UseLayman = new System.Windows.Forms.RadioButton();
this.nuspecLabel = new System.Windows.Forms.Label();
this.nuspecPath = new System.Windows.Forms.TextBox();
this.ebuildLabel = new System.Windows.Forms.Label();
this.ebuildPath = new System.Windows.Forms.TextBox();
//
this.radioButton_UsePortage.AutoSize = true;
this.radioButton_UsePortage.Location = new System.Drawing.Point(4, 4);
this.radioButton_UsePortage.Name = "radioButton_UsePortage";
this.radioButton_UsePortage.Size = new System.Drawing.Size(263, 17);
this.radioButton_UsePortage.TabIndex = 0;
this.radioButton_UsePortage.Text = "Use main portage tree";
this.radioButton_UsePortage.Enabled = false;
this.radioButton_UsePortage.UseVisualStyleBackColor = true;
//
this.radioButton_UseLayman.AutoSize = true;
this.radioButton_UseLayman.Location = new System.Drawing.Point(4, 28);
this.radioButton_UseLayman.Name = "radioButton_UseLayman";
this.radioButton_UseLayman.Size = new System.Drawing.Size(174, 17);
this.radioButton_UseLayman.TabIndex = 1;
this.radioButton_UseLayman.Enabled = false;
this.radioButton_UseLayman.Text = "Use one of overlays from layman";
this.radioButton_UseLayman.UseVisualStyleBackColor = true;
//
this.nuspecLabel.AutoSize = true;
this.nuspecLabel.Location = new System.Drawing.Point(20, 100);
this.nuspecLabel.Name = "nuspecLabel";
this.nuspecLabel.Size = new System.Drawing.Size(281, 70);
this.nuspecLabel.TabIndex = 4;
this.nuspecLabel.Text = ".nuspec location:";
//
this.nuspecPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.nuspecPath.Location = new System.Drawing.Point(20, 120);
this.nuspecPath.Name = "nuspecPath";
this.nuspecPath.Size = new System.Drawing.Size(281, 70);
this.nuspecPath.TabIndex = 5;
//
this.ebuildLabel.AutoSize = true;
this.ebuildLabel.Location = new System.Drawing.Point(20, 160);
this.ebuildLabel.Name = "ebuildLabel";
this.ebuildLabel.Size = new System.Drawing.Size(281, 70);
this.ebuildLabel.TabIndex = 6;
this.ebuildLabel.Text = ".ebuild location:";
//
this.ebuildPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ebuildPath.Location = new System.Drawing.Point(20, 180);
this.ebuildPath.Name = ".ebuild Path";
this.ebuildPath.Size = new System.Drawing.Size(281, 70);
this.ebuildPath.TabIndex = 7;
this.SuspendLayout();
this.Name = "GeneralSettingsPage";
this.Size = new System.Drawing.Size(338, 150);
//
this.Controls.Add(this.radioButton_UseLayman);
this.Controls.Add(this.radioButton_UsePortage);
//
this.Controls.Add(this.nuspecPath);
this.Controls.Add(this.nuspecLabel);
//
this.Controls.Add(this.ebuildPath);
this.Controls.Add(this.ebuildLabel);
//
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RadioButton radioButton_UsePortage;
private System.Windows.Forms.RadioButton radioButton_UseLayman;
private System.Windows.Forms.Label nuspecLabel;
private System.Windows.Forms.TextBox nuspecPath;
private System.Windows.Forms.Label ebuildLabel;
private System.Windows.Forms.TextBox ebuildPath;
}
}
| ArsenShnurkov/nuspec-portage-generator | winforms-gui/OptionsDialog/GeneralSettingsPage.Designer.cs | C# | gpl-3.0 | 4,612 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cat_crud extends CI_Controller {
function __construct()
{
parent::__construct();
/* Standard Libraries of codeigniter are required */
$this->load->database();
$this->load->helper('url');
/* ------------------ */
$this->load->library('grocery_CRUD');
}
public function index()
{
echo "<h1>Welcome to the world of Codeigniter</h1>";//Just an example to ensure that we get into the function
die();
}
public function app_cat()
{
$this->grocery_crud->set_table('categories');
$output = $this->grocery_crud->render();
$this->_example_output($output);
}
function _example_output($output = null)
{
$this->load->view('edit_cat.php',$output);
}
} | CollinsIchigo/LEO | application/controllers/cat_crud.php | PHP | gpl-3.0 | 942 |
/*
* SystemPropertiesTable.java
*
* Copyright (C) 2002-2017 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.underworldlabs.swing;
import org.underworldlabs.swing.table.DefaultTableHeaderRenderer;
import org.underworldlabs.swing.table.PropertyWrapperModel;
import javax.swing.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
/**
* Simple system properties table with the values
* from <code>System.getProperties()</code>.
*
* @author Takis Diakoumis
*/
public class SystemPropertiesTable extends JTable {
/**
* table model
*/
private PropertyWrapperModel model;
/**
* Creates a new instance of SystemPropertiesTable
*/
public SystemPropertiesTable() {
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel) {
getTableHeader().setDefaultRenderer(new DefaultTableHeaderRenderer());
}
model = new PropertyWrapperModel(System.getProperties(),
PropertyWrapperModel.SORT_BY_KEY);
setModel(model);
getTableHeader().setReorderingAllowed(false);
getColumnModel().getColumn(0).setCellRenderer(new PropertiesTableCellRenderer());
getColumnModel().getColumn(1).setCellRenderer(new PropertiesTableCellRenderer());
}
private class PropertiesTableCellRenderer extends DefaultTableCellRenderer {
public PropertiesTableCellRenderer() {
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
if (value != null) {
String toolTip = value.toString();
setToolTipText(toolTip);
}
return super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
}
}
}
| redsoftbiz/executequery | src/org/underworldlabs/swing/SystemPropertiesTable.java | Java | gpl-3.0 | 2,792 |
package org.pwr.transporter.server.business.sales;
import java.util.List;
import java.util.Map;
import org.pwr.transporter.entity.sales.GoodsIssuedNote;
import org.pwr.transporter.server.core.hb.criteria.Criteria;
import org.pwr.transporter.server.dao.sales.GoodsIssuedNoteDAO;
/**
* <pre>
* Delegates logic for {@link GoodsIssuedNote}
* </pre>
* <hr/>
*
* @author W.S.
* @version 0.0.1
*/
public class GoodsIssuedNoteLogic {
GoodsIssuedNoteDAO goodsIssuedNoteDAO;
public GoodsIssuedNoteDAO getGoodsIssuedNoteDAO() {
return this.goodsIssuedNoteDAO;
}
public void setGoodsIssuedNoteDAO(GoodsIssuedNoteDAO goodsIssuedNoteDAO) {
this.goodsIssuedNoteDAO = goodsIssuedNoteDAO;
}
public List<GoodsIssuedNote> getByCustomerId(Long id) {
return this.goodsIssuedNoteDAO.getByCustomerId(id);
}
public GoodsIssuedNote getByID(Long id) {
return this.goodsIssuedNoteDAO.getByID(id);
}
public List<GoodsIssuedNote> search(Map<String, Object> parameterMap) {
return this.goodsIssuedNoteDAO.search(parameterMap);
}
public Long insert(GoodsIssuedNote entity) {
return this.goodsIssuedNoteDAO.insert(entity);
}
public void update(GoodsIssuedNote entity) {
this.goodsIssuedNoteDAO.update(entity);
}
public void delete(GoodsIssuedNote entity) {
this.goodsIssuedNoteDAO.delete(entity);
}
public void deleteById(Long id) {
this.goodsIssuedNoteDAO.deleteById(id);
}
public List<GoodsIssuedNote> getListRest(int amount, int fromRow) {
return this.goodsIssuedNoteDAO.getListRest(amount, fromRow);
}
public long count() {
return this.goodsIssuedNoteDAO.count();
}
public long count(Criteria criteria) {
return this.goodsIssuedNoteDAO.count(criteria);
}
public List<GoodsIssuedNote> getListRestCrit(int amount, int fromRow, Criteria criteria) {
return this.goodsIssuedNoteDAO.getListRestCrit(amount, fromRow, criteria);
}
}
| InfWGospodarce/projekt | transporter-server/src/org/pwr/transporter/server/business/sales/GoodsIssuedNoteLogic.java | Java | gpl-3.0 | 2,053 |
#include <iostream>
using namespace std;
long long exponent (int base, int power) {
long long result = 1, value = base;
while (power) {
if (power & 1)
result *= value;
value *= value;
power /= 2;
}
return result;
}
int main () {
int base, power;
cin >> base;
cin >> power;
cout << "Value of " << base << " raised to the power " << power << " is " << exponent(base, power);
return 0;
}
/*
Input:
base : 2, power : 32
Output:
Value of 2 raised to the power 32 is 4294967296
*/
| jainaman224/Algo_Ds_Notes | Logarithmic_Exponent/Logarithmic_Exponent.cpp | C++ | gpl-3.0 | 551 |
import unittest
import os.path
from math import pi
from sapphire import corsika
data_file_dir = os.path.dirname(__file__)
DATA_FILE = os.path.join(data_file_dir, 'test_data/1_2/DAT000000')
class CorsikaFileTests(unittest.TestCase):
def setUp(self):
self.file = corsika.reader.CorsikaFile(DATA_FILE)
def tearDown(self):
self.file.finish()
def test_validate_file(self):
"""Verify that the data file is valid"""
self.assertTrue(self.file.check())
def test_run_header(self):
"""Verify that the Run header is properly read"""
header = self.file.get_header()
self.assertIsInstance(header, corsika.blocks.RunHeader)
self.assertEqual(header.id, b'RUNH')
self.assertAlmostEqual(header.version, 7.4, 4)
for h in [10., 5000., 30000., 50000., 110000.]:
t = header.height_to_thickness(h)
self.assertAlmostEqual(header.thickness_to_height(t), h, 8)
def test_run_end(self):
"""Verify that the Run end is properly read"""
end = self.file.get_end()
self.assertIsInstance(end, corsika.blocks.RunEnd)
self.assertEqual(end.id, b'RUNE')
self.assertEqual(end.n_events_processed, 1)
def test_events(self):
"""Verify that the Events are properly read"""
events = self.file.get_events()
event = next(events)
self.assertIsInstance(event, corsika.reader.CorsikaEvent)
self.assertEqual(event.last_particle_index, 1086892)
def test_event_header(self):
"""Verify that the Event header is properly read"""
events = self.file.get_events()
event = next(events)
header = event.get_header()
self.assertIsInstance(header, corsika.blocks.EventHeader)
self.assertEqual(header.id, b'EVTH')
self.assertEqual(corsika.particles.name(header.particle_id), 'proton')
self.assertEqual(header.energy, 1e14)
self.assertEqual(header.azimuth, -pi / 2.)
self.assertEqual(header.zenith, 0.0)
self.assertEqual(header.hadron_model_high, 'QGSJET')
def test_event_end(self):
"""Verify that the Event end is properly read"""
events = self.file.get_events()
event = next(events)
end = event.get_end()
self.assertIsInstance(end, corsika.blocks.EventEnd)
self.assertEqual(end.id, b'EVTE')
self.assertEqual(end.n_muons_output, 1729)
def test_particles(self):
"""Verify that the Particles are properly read"""
events = self.file.get_events()
event = next(events)
particles = event.get_particles()
particle = next(particles)
self.assertIsInstance(particle, tuple)
self.assertEqual(len(particle), 11)
self.assertEqual(corsika.particles.name(int(particle[6])), 'muon_p')
self.assertAlmostEqual(particle[3], -56.2846679688)
self.assertAlmostEqual(particle[4], -172.535859375)
self.assertAlmostEqual(particle[7], 181.484397728)
particle = next(particles)
self.assertEqual(corsika.particles.name(int(particle[6])), 'muon_m')
if __name__ == '__main__':
unittest.main()
| tomkooij/sapphire | sapphire/tests/corsika/test_corsika.py | Python | gpl-3.0 | 3,194 |
"""
Abstract base classes define the primitives that renderers and
graphics contexts must implement to serve as a matplotlib backend
:class:`RendererBase`
An abstract base class to handle drawing/rendering operations.
:class:`FigureCanvasBase`
The abstraction layer that separates the
:class:`matplotlib.figure.Figure` from the backend specific
details like a user interface drawing area
:class:`GraphicsContextBase`
An abstract base class that provides color, line styles, etc...
:class:`Event`
The base class for all of the matplotlib event
handling. Derived classes suh as :class:`KeyEvent` and
:class:`MouseEvent` store the meta data like keys and buttons
pressed, x and y locations in pixel and
:class:`~matplotlib.axes.Axes` coordinates.
:class:`ShowBase`
The base class for the Show class of each interactive backend;
the 'show' callable is then set to Show.__call__, inherited from
ShowBase.
"""
import os
import warnings
import time
import io
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.colors as colors
import matplotlib.transforms as transforms
import matplotlib.widgets as widgets
#import matplotlib.path as path
from matplotlib import rcParams
from matplotlib import is_interactive
from matplotlib import get_backend
from matplotlib._pylab_helpers import Gcf
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
import matplotlib.tight_bbox as tight_bbox
import matplotlib.textpath as textpath
from matplotlib.path import Path
from matplotlib.cbook import mplDeprecation
try:
from PIL import Image
_has_pil = True
except ImportError:
_has_pil = False
_backend_d = {}
def register_backend(format, backend_class):
_backend_d[format] = backend_class
class ShowBase(object):
"""
Simple base class to generate a show() callable in backends.
Subclass must override mainloop() method.
"""
def __call__(self, block=None):
"""
Show all figures. If *block* is not None, then
it is a boolean that overrides all other factors
determining whether show blocks by calling mainloop().
The other factors are:
it does not block if run inside "ipython --pylab";
it does not block in interactive mode.
"""
managers = Gcf.get_all_fig_managers()
if not managers:
return
for manager in managers:
manager.show()
if block is not None:
if block:
self.mainloop()
return
else:
return
# Hack: determine at runtime whether we are
# inside ipython in pylab mode.
from matplotlib import pyplot
try:
ipython_pylab = not pyplot.show._needmain
# IPython versions >= 0.10 tack the _needmain
# attribute onto pyplot.show, and always set
# it to False, when in --pylab mode.
ipython_pylab = ipython_pylab and get_backend() != 'WebAgg'
# TODO: The above is a hack to get the WebAgg backend
# working with `ipython --pylab` until proper integration
# is implemented.
except AttributeError:
ipython_pylab = False
# Leave the following as a separate step in case we
# want to control this behavior with an rcParam.
if ipython_pylab:
return
if not is_interactive() or get_backend() == 'WebAgg':
self.mainloop()
def mainloop(self):
pass
class RendererBase:
"""An abstract base class to handle drawing/rendering operations.
The following methods *must* be implemented in the backend:
* :meth:`draw_path`
* :meth:`draw_image`
* :meth:`draw_text`
* :meth:`get_text_width_height_descent`
The following methods *should* be implemented in the backend for
optimization reasons:
* :meth:`draw_markers`
* :meth:`draw_path_collection`
* :meth:`draw_quad_mesh`
"""
def __init__(self):
self._texmanager = None
self._text2path = textpath.TextToPath()
def open_group(self, s, gid=None):
"""
Open a grouping element with label *s*. If *gid* is given, use
*gid* as the id of the group. Is only currently used by
:mod:`~matplotlib.backends.backend_svg`.
"""
pass
def close_group(self, s):
"""
Close a grouping element with label *s*
Is only currently used by :mod:`~matplotlib.backends.backend_svg`
"""
pass
def draw_path(self, gc, path, transform, rgbFace=None):
"""
Draws a :class:`~matplotlib.path.Path` instance using the
given affine transform.
"""
raise NotImplementedError
def draw_markers(self, gc, marker_path, marker_trans, path,
trans, rgbFace=None):
"""
Draws a marker at each of the vertices in path. This includes
all vertices, including control points on curves. To avoid
that behavior, those vertices should be removed before calling
this function.
*gc*
the :class:`GraphicsContextBase` instance
*marker_trans*
is an affine transform applied to the marker.
*trans*
is an affine transform applied to the path.
This provides a fallback implementation of draw_markers that
makes multiple calls to :meth:`draw_path`. Some backends may
want to override this method in order to draw the marker only
once and reuse it multiple times.
"""
for vertices, codes in path.iter_segments(trans, simplify=False):
if len(vertices):
x, y = vertices[-2:]
self.draw_path(gc, marker_path,
marker_trans +
transforms.Affine2D().translate(x, y),
rgbFace)
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
offsets, offsetTrans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds, urls,
offset_position):
"""
Draws a collection of paths selecting drawing properties from
the lists *facecolors*, *edgecolors*, *linewidths*,
*linestyles* and *antialiaseds*. *offsets* is a list of
offsets to apply to each of the paths. The offsets in
*offsets* are first transformed by *offsetTrans* before being
applied. *offset_position* may be either "screen" or "data"
depending on the space that the offsets are in.
This provides a fallback implementation of
:meth:`draw_path_collection` that makes multiple calls to
:meth:`draw_path`. Some backends may want to override this in
order to render each set of path data only once, and then
reference that path multiple times with the different offsets,
colors, styles etc. The generator methods
:meth:`_iter_collection_raw_paths` and
:meth:`_iter_collection` are provided to help with (and
standardize) the implementation across backends. It is highly
recommended to use those generators, so that changes to the
behavior of :meth:`draw_path_collection` can be made globally.
"""
path_ids = []
for path, transform in self._iter_collection_raw_paths(
master_transform, paths, all_transforms):
path_ids.append((path, transform))
for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
gc, master_transform, all_transforms, path_ids, offsets,
offsetTrans, facecolors, edgecolors, linewidths, linestyles,
antialiaseds, urls, offset_position):
path, transform = path_id
transform = transforms.Affine2D(
transform.get_matrix()).translate(xo, yo)
self.draw_path(gc0, path, transform, rgbFace)
def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight,
coordinates, offsets, offsetTrans, facecolors,
antialiased, edgecolors):
"""
This provides a fallback implementation of
:meth:`draw_quad_mesh` that generates paths and then calls
:meth:`draw_path_collection`.
"""
from matplotlib.collections import QuadMesh
paths = QuadMesh.convert_mesh_to_paths(
meshWidth, meshHeight, coordinates)
if edgecolors is None:
edgecolors = facecolors
linewidths = np.array([gc.get_linewidth()], np.float_)
return self.draw_path_collection(
gc, master_transform, paths, [], offsets, offsetTrans, facecolors,
edgecolors, linewidths, [], [antialiased], [None], 'screen')
def draw_gouraud_triangle(self, gc, points, colors, transform):
"""
Draw a Gouraud-shaded triangle.
*points* is a 3x2 array of (x, y) points for the triangle.
*colors* is a 3x4 array of RGBA colors for each point of the
triangle.
*transform* is an affine transform to apply to the points.
"""
raise NotImplementedError
def draw_gouraud_triangles(self, gc, triangles_array, colors_array,
transform):
"""
Draws a series of Gouraud triangles.
*points* is a Nx3x2 array of (x, y) points for the trianglex.
*colors* is a Nx3x4 array of RGBA colors for each point of the
triangles.
*transform* is an affine transform to apply to the points.
"""
transform = transform.frozen()
for tri, col in zip(triangles_array, colors_array):
self.draw_gouraud_triangle(gc, tri, col, transform)
def _iter_collection_raw_paths(self, master_transform, paths,
all_transforms):
"""
This is a helper method (along with :meth:`_iter_collection`) to make
it easier to write a space-efficent :meth:`draw_path_collection`
implementation in a backend.
This method yields all of the base path/transform
combinations, given a master transform, a list of paths and
list of transforms.
The arguments should be exactly what is passed in to
:meth:`draw_path_collection`.
The backend should take each yielded path and transform and
create an object that can be referenced (reused) later.
"""
Npaths = len(paths)
Ntransforms = len(all_transforms)
N = max(Npaths, Ntransforms)
if Npaths == 0:
return
transform = transforms.IdentityTransform()
for i in range(N):
path = paths[i % Npaths]
if Ntransforms:
transform = all_transforms[i % Ntransforms]
yield path, transform + master_transform
def _iter_collection(self, gc, master_transform, all_transforms,
path_ids, offsets, offsetTrans, facecolors,
edgecolors, linewidths, linestyles,
antialiaseds, urls, offset_position):
"""
This is a helper method (along with
:meth:`_iter_collection_raw_paths`) to make it easier to write
a space-efficent :meth:`draw_path_collection` implementation in a
backend.
This method yields all of the path, offset and graphics
context combinations to draw the path collection. The caller
should already have looped over the results of
:meth:`_iter_collection_raw_paths` to draw this collection.
The arguments should be the same as that passed into
:meth:`draw_path_collection`, with the exception of
*path_ids*, which is a list of arbitrary objects that the
backend will use to reference one of the paths created in the
:meth:`_iter_collection_raw_paths` stage.
Each yielded result is of the form::
xo, yo, path_id, gc, rgbFace
where *xo*, *yo* is an offset; *path_id* is one of the elements of
*path_ids*; *gc* is a graphics context and *rgbFace* is a color to
use for filling the path.
"""
Ntransforms = len(all_transforms)
Npaths = len(path_ids)
Noffsets = len(offsets)
N = max(Npaths, Noffsets)
Nfacecolors = len(facecolors)
Nedgecolors = len(edgecolors)
Nlinewidths = len(linewidths)
Nlinestyles = len(linestyles)
Naa = len(antialiaseds)
Nurls = len(urls)
if (Nfacecolors == 0 and Nedgecolors == 0) or Npaths == 0:
return
if Noffsets:
toffsets = offsetTrans.transform(offsets)
gc0 = self.new_gc()
gc0.copy_properties(gc)
if Nfacecolors == 0:
rgbFace = None
if Nedgecolors == 0:
gc0.set_linewidth(0.0)
xo, yo = 0, 0
for i in range(N):
path_id = path_ids[i % Npaths]
if Noffsets:
xo, yo = toffsets[i % Noffsets]
if offset_position == 'data':
if Ntransforms:
transform = (all_transforms[i % Ntransforms] +
master_transform)
else:
transform = master_transform
xo, yo = transform.transform_point((xo, yo))
xp, yp = transform.transform_point((0, 0))
xo = -(xp - xo)
yo = -(yp - yo)
if not (np.isfinite(xo) and np.isfinite(yo)):
continue
if Nfacecolors:
rgbFace = facecolors[i % Nfacecolors]
if Nedgecolors:
if Nlinewidths:
gc0.set_linewidth(linewidths[i % Nlinewidths])
if Nlinestyles:
gc0.set_dashes(*linestyles[i % Nlinestyles])
fg = edgecolors[i % Nedgecolors]
if len(fg) == 4:
if fg[3] == 0.0:
gc0.set_linewidth(0)
else:
gc0.set_foreground(fg)
else:
gc0.set_foreground(fg)
if rgbFace is not None and len(rgbFace) == 4:
if rgbFace[3] == 0:
rgbFace = None
gc0.set_antialiased(antialiaseds[i % Naa])
if Nurls:
gc0.set_url(urls[i % Nurls])
yield xo, yo, path_id, gc0, rgbFace
gc0.restore()
def get_image_magnification(self):
"""
Get the factor by which to magnify images passed to :meth:`draw_image`.
Allows a backend to have images at a different resolution to other
artists.
"""
return 1.0
def draw_image(self, gc, x, y, im):
"""
Draw the image instance into the current axes;
*gc*
a GraphicsContext containing clipping information
*x*
is the distance in pixels from the left hand side of the canvas.
*y*
the distance from the origin. That is, if origin is
upper, y is the distance from top. If origin is lower, y
is the distance from bottom
*im*
the :class:`matplotlib._image.Image` instance
"""
raise NotImplementedError
def option_image_nocomposite(self):
"""
override this method for renderers that do not necessarily
want to rescale and composite raster images. (like SVG)
"""
return False
def option_scale_image(self):
"""
override this method for renderers that support arbitrary
scaling of image (most of the vector backend).
"""
return False
def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
"""
"""
self._draw_text_as_path(gc, x, y, s, prop, angle, ismath="TeX")
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
"""
Draw the text instance
*gc*
the :class:`GraphicsContextBase` instance
*x*
the x location of the text in display coords
*y*
the y location of the text baseline in display coords
*s*
the text string
*prop*
a :class:`matplotlib.font_manager.FontProperties` instance
*angle*
the rotation angle in degrees
*mtext*
a :class:`matplotlib.text.Text` instance
**backend implementers note**
When you are trying to determine if you have gotten your bounding box
right (which is what enables the text layout/alignment to work
properly), it helps to change the line in text.py::
if 0: bbox_artist(self, renderer)
to if 1, and then the actual bounding box will be plotted along with
your text.
"""
self._draw_text_as_path(gc, x, y, s, prop, angle, ismath)
def _get_text_path_transform(self, x, y, s, prop, angle, ismath):
"""
return the text path and transform
*prop*
font property
*s*
text to be converted
*usetex*
If True, use matplotlib usetex mode.
*ismath*
If True, use mathtext parser. If "TeX", use *usetex* mode.
"""
text2path = self._text2path
fontsize = self.points_to_pixels(prop.get_size_in_points())
if ismath == "TeX":
verts, codes = text2path.get_text_path(prop, s, ismath=False,
usetex=True)
else:
verts, codes = text2path.get_text_path(prop, s, ismath=ismath,
usetex=False)
path = Path(verts, codes)
angle = angle / 180. * 3.141592
if self.flipy():
transform = Affine2D().scale(fontsize / text2path.FONT_SCALE,
fontsize / text2path.FONT_SCALE)
transform = transform.rotate(angle).translate(x, self.height - y)
else:
transform = Affine2D().scale(fontsize / text2path.FONT_SCALE,
fontsize / text2path.FONT_SCALE)
transform = transform.rotate(angle).translate(x, y)
return path, transform
def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):
"""
draw the text by converting them to paths using textpath module.
*prop*
font property
*s*
text to be converted
*usetex*
If True, use matplotlib usetex mode.
*ismath*
If True, use mathtext parser. If "TeX", use *usetex* mode.
"""
path, transform = self._get_text_path_transform(
x, y, s, prop, angle, ismath)
color = gc.get_rgb()
gc.set_linewidth(0.0)
self.draw_path(gc, path, transform, rgbFace=color)
def get_text_width_height_descent(self, s, prop, ismath):
"""
get the width and height, and the offset from the bottom to the
baseline (descent), in display coords of the string s with
:class:`~matplotlib.font_manager.FontProperties` prop
"""
if ismath == 'TeX':
# todo: handle props
size = prop.get_size_in_points()
texmanager = self._text2path.get_texmanager()
fontsize = prop.get_size_in_points()
w, h, d = texmanager.get_text_width_height_descent(s, fontsize,
renderer=self)
return w, h, d
dpi = self.points_to_pixels(72)
if ismath:
dims = self._text2path.mathtext_parser.parse(s, dpi, prop)
return dims[0:3] # return width, height, descent
flags = self._text2path._get_hinting_flag()
font = self._text2path._get_font(prop)
size = prop.get_size_in_points()
font.set_size(size, dpi)
# the width and height of unrotated string
font.set_text(s, 0.0, flags=flags)
w, h = font.get_width_height()
d = font.get_descent()
w /= 64.0 # convert from subpixels
h /= 64.0
d /= 64.0
return w, h, d
def flipy(self):
"""
Return true if y small numbers are top for renderer Is used
for drawing text (:mod:`matplotlib.text`) and images
(:mod:`matplotlib.image`) only
"""
return True
def get_canvas_width_height(self):
'return the canvas width and height in display coords'
return 1, 1
def get_texmanager(self):
"""
return the :class:`matplotlib.texmanager.TexManager` instance
"""
if self._texmanager is None:
from matplotlib.texmanager import TexManager
self._texmanager = TexManager()
return self._texmanager
def new_gc(self):
"""
Return an instance of a :class:`GraphicsContextBase`
"""
return GraphicsContextBase()
def points_to_pixels(self, points):
"""
Convert points to display units
*points*
a float or a numpy array of float
return points converted to pixels
You need to override this function (unless your backend
doesn't have a dpi, eg, postscript or svg). Some imaging
systems assume some value for pixels per inch::
points to pixels = points * pixels_per_inch/72.0 * dpi/72.0
"""
return points
def strip_math(self, s):
return cbook.strip_math(s)
def start_rasterizing(self):
"""
Used in MixedModeRenderer. Switch to the raster renderer.
"""
pass
def stop_rasterizing(self):
"""
Used in MixedModeRenderer. Switch back to the vector renderer
and draw the contents of the raster renderer as an image on
the vector renderer.
"""
pass
def start_filter(self):
"""
Used in AggRenderer. Switch to a temporary renderer for image
filtering effects.
"""
pass
def stop_filter(self, filter_func):
"""
Used in AggRenderer. Switch back to the original renderer.
The contents of the temporary renderer is processed with the
*filter_func* and is drawn on the original renderer as an
image.
"""
pass
class GraphicsContextBase:
"""
An abstract base class that provides color, line styles, etc...
"""
# a mapping from dash styles to suggested offset, dash pairs
dashd = {
'solid': (None, None),
'dashed': (0, (6.0, 6.0)),
'dashdot': (0, (3.0, 5.0, 1.0, 5.0)),
'dotted': (0, (1.0, 3.0)),
}
def __init__(self):
self._alpha = 1.0
self._forced_alpha = False # if True, _alpha overrides A from RGBA
self._antialiased = 1 # use 0,1 not True, False for extension code
self._capstyle = 'butt'
self._cliprect = None
self._clippath = None
self._dashes = None, None
self._joinstyle = 'round'
self._linestyle = 'solid'
self._linewidth = 1
self._rgb = (0.0, 0.0, 0.0, 1.0)
self._orig_color = (0.0, 0.0, 0.0, 1.0)
self._hatch = None
self._url = None
self._gid = None
self._snap = None
self._sketch = None
def copy_properties(self, gc):
'Copy properties from gc to self'
self._alpha = gc._alpha
self._forced_alpha = gc._forced_alpha
self._antialiased = gc._antialiased
self._capstyle = gc._capstyle
self._cliprect = gc._cliprect
self._clippath = gc._clippath
self._dashes = gc._dashes
self._joinstyle = gc._joinstyle
self._linestyle = gc._linestyle
self._linewidth = gc._linewidth
self._rgb = gc._rgb
self._orig_color = gc._orig_color
self._hatch = gc._hatch
self._url = gc._url
self._gid = gc._gid
self._snap = gc._snap
self._sketch = gc._sketch
def restore(self):
"""
Restore the graphics context from the stack - needed only
for backends that save graphics contexts on a stack
"""
pass
def get_alpha(self):
"""
Return the alpha value used for blending - not supported on
all backends
"""
return self._alpha
def get_antialiased(self):
"Return true if the object should try to do antialiased rendering"
return self._antialiased
def get_capstyle(self):
"""
Return the capstyle as a string in ('butt', 'round', 'projecting')
"""
return self._capstyle
def get_clip_rectangle(self):
"""
Return the clip rectangle as a :class:`~matplotlib.transforms.Bbox`
instance
"""
return self._cliprect
def get_clip_path(self):
"""
Return the clip path in the form (path, transform), where path
is a :class:`~matplotlib.path.Path` instance, and transform is
an affine transform to apply to the path before clipping.
"""
if self._clippath is not None:
return self._clippath.get_transformed_path_and_affine()
return None, None
def get_dashes(self):
"""
Return the dash information as an offset dashlist tuple.
The dash list is a even size list that gives the ink on, ink
off in pixels.
See p107 of to PostScript `BLUEBOOK
<http://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF>`_
for more info.
Default value is None
"""
return self._dashes
def get_forced_alpha(self):
"""
Return whether the value given by get_alpha() should be used to
override any other alpha-channel values.
"""
return self._forced_alpha
def get_joinstyle(self):
"""
Return the line join style as one of ('miter', 'round', 'bevel')
"""
return self._joinstyle
def get_linestyle(self, style):
"""
Return the linestyle: one of ('solid', 'dashed', 'dashdot',
'dotted').
"""
return self._linestyle
def get_linewidth(self):
"""
Return the line width in points as a scalar
"""
return self._linewidth
def get_rgb(self):
"""
returns a tuple of three or four floats from 0-1.
"""
return self._rgb
def get_url(self):
"""
returns a url if one is set, None otherwise
"""
return self._url
def get_gid(self):
"""
Return the object identifier if one is set, None otherwise.
"""
return self._gid
def get_snap(self):
"""
returns the snap setting which may be:
* True: snap vertices to the nearest pixel center
* False: leave vertices as-is
* None: (auto) If the path contains only rectilinear line
segments, round to the nearest pixel center
"""
return self._snap
def set_alpha(self, alpha):
"""
Set the alpha value used for blending - not supported on all backends.
If ``alpha=None`` (the default), the alpha components of the
foreground and fill colors will be used to set their respective
transparencies (where applicable); otherwise, ``alpha`` will override
them.
"""
if alpha is not None:
self._alpha = alpha
self._forced_alpha = True
else:
self._alpha = 1.0
self._forced_alpha = False
self.set_foreground(self._orig_color)
def set_antialiased(self, b):
"""
True if object should be drawn with antialiased rendering
"""
# use 0, 1 to make life easier on extension code trying to read the gc
if b:
self._antialiased = 1
else:
self._antialiased = 0
def set_capstyle(self, cs):
"""
Set the capstyle as a string in ('butt', 'round', 'projecting')
"""
if cs in ('butt', 'round', 'projecting'):
self._capstyle = cs
else:
raise ValueError('Unrecognized cap style. Found %s' % cs)
def set_clip_rectangle(self, rectangle):
"""
Set the clip rectangle with sequence (left, bottom, width, height)
"""
self._cliprect = rectangle
def set_clip_path(self, path):
"""
Set the clip path and transformation. Path should be a
:class:`~matplotlib.transforms.TransformedPath` instance.
"""
assert path is None or isinstance(path, transforms.TransformedPath)
self._clippath = path
def set_dashes(self, dash_offset, dash_list):
"""
Set the dash style for the gc.
*dash_offset*
is the offset (usually 0).
*dash_list*
specifies the on-off sequence as points.
``(None, None)`` specifies a solid line
"""
if dash_list is not None:
dl = np.asarray(dash_list)
if np.any(dl <= 0.0):
raise ValueError("All values in the dash list must be positive")
self._dashes = dash_offset, dash_list
def set_foreground(self, fg, isRGBA=False):
"""
Set the foreground color. fg can be a MATLAB format string, a
html hex color string, an rgb or rgba unit tuple, or a float between 0
and 1. In the latter case, grayscale is used.
If you know fg is rgba, set ``isRGBA=True`` for efficiency.
"""
self._orig_color = fg
if self._forced_alpha:
self._rgb = colors.colorConverter.to_rgba(fg, self._alpha)
elif isRGBA:
self._rgb = fg
else:
self._rgb = colors.colorConverter.to_rgba(fg)
def set_graylevel(self, frac):
"""
Set the foreground color to be a gray level with *frac*
"""
self._orig_color = frac
self._rgb = (frac, frac, frac, self._alpha)
def set_joinstyle(self, js):
"""
Set the join style to be one of ('miter', 'round', 'bevel')
"""
if js in ('miter', 'round', 'bevel'):
self._joinstyle = js
else:
raise ValueError('Unrecognized join style. Found %s' % js)
def set_linewidth(self, w):
"""
Set the linewidth in points
"""
self._linewidth = w
def set_linestyle(self, style):
"""
Set the linestyle to be one of ('solid', 'dashed', 'dashdot',
'dotted'). One may specify customized dash styles by providing
a tuple of (offset, dash pairs). For example, the predefiend
linestyles have following values.:
'dashed' : (0, (6.0, 6.0)),
'dashdot' : (0, (3.0, 5.0, 1.0, 5.0)),
'dotted' : (0, (1.0, 3.0)),
"""
if style in self.dashd:
offset, dashes = self.dashd[style]
elif isinstance(style, tuple):
offset, dashes = style
else:
raise ValueError('Unrecognized linestyle: %s' % str(style))
self._linestyle = style
self.set_dashes(offset, dashes)
def set_url(self, url):
"""
Sets the url for links in compatible backends
"""
self._url = url
def set_gid(self, id):
"""
Sets the id.
"""
self._gid = id
def set_snap(self, snap):
"""
Sets the snap setting which may be:
* True: snap vertices to the nearest pixel center
* False: leave vertices as-is
* None: (auto) If the path contains only rectilinear line
segments, round to the nearest pixel center
"""
self._snap = snap
def set_hatch(self, hatch):
"""
Sets the hatch style for filling
"""
self._hatch = hatch
def get_hatch(self):
"""
Gets the current hatch style
"""
return self._hatch
def get_hatch_path(self, density=6.0):
"""
Returns a Path for the current hatch.
"""
if self._hatch is None:
return None
return Path.hatch(self._hatch, density)
def get_sketch_params(self):
"""
Returns the sketch parameters for the artist.
Returns
-------
sketch_params : tuple or `None`
A 3-tuple with the following elements:
* `scale`: The amplitude of the wiggle perpendicular to the
source line.
* `length`: The length of the wiggle along the line.
* `randomness`: The scale factor by which the length is
shrunken or expanded.
May return `None` if no sketch parameters were set.
"""
return self._sketch
def set_sketch_params(self, scale=None, length=None, randomness=None):
"""
Sets the the sketch parameters.
Parameters
----------
scale : float, optional
The amplitude of the wiggle perpendicular to the source
line, in pixels. If scale is `None`, or not provided, no
sketch filter will be provided.
length : float, optional
The length of the wiggle along the line, in pixels
(default 128.0)
randomness : float, optional
The scale factor by which the length is shrunken or
expanded (default 16.0)
"""
if scale is None:
self._sketch = None
else:
self._sketch = (scale, length or 128.0, randomness or 16.0)
class TimerBase(object):
'''
A base class for providing timer events, useful for things animations.
Backends need to implement a few specific methods in order to use their
own timing mechanisms so that the timer events are integrated into their
event loops.
Mandatory functions that must be implemented:
* `_timer_start`: Contains backend-specific code for starting
the timer
* `_timer_stop`: Contains backend-specific code for stopping
the timer
Optional overrides:
* `_timer_set_single_shot`: Code for setting the timer to
single shot operating mode, if supported by the timer
object. If not, the `Timer` class itself will store the flag
and the `_on_timer` method should be overridden to support
such behavior.
* `_timer_set_interval`: Code for setting the interval on the
timer, if there is a method for doing so on the timer
object.
* `_on_timer`: This is the internal function that any timer
object should call, which will handle the task of running
all callbacks that have been set.
Attributes:
* `interval`: The time between timer events in
milliseconds. Default is 1000 ms.
* `single_shot`: Boolean flag indicating whether this timer
should operate as single shot (run once and then
stop). Defaults to `False`.
* `callbacks`: Stores list of (func, args) tuples that will be
called upon timer events. This list can be manipulated
directly, or the functions `add_callback` and
`remove_callback` can be used.
'''
def __init__(self, interval=None, callbacks=None):
#Initialize empty callbacks list and setup default settings if necssary
if callbacks is None:
self.callbacks = []
else:
self.callbacks = callbacks[:] # Create a copy
if interval is None:
self._interval = 1000
else:
self._interval = interval
self._single = False
# Default attribute for holding the GUI-specific timer object
self._timer = None
def __del__(self):
'Need to stop timer and possibly disconnect timer.'
self._timer_stop()
def start(self, interval=None):
'''
Start the timer object. `interval` is optional and will be used
to reset the timer interval first if provided.
'''
if interval is not None:
self._set_interval(interval)
self._timer_start()
def stop(self):
'''
Stop the timer.
'''
self._timer_stop()
def _timer_start(self):
pass
def _timer_stop(self):
pass
def _get_interval(self):
return self._interval
def _set_interval(self, interval):
# Force to int since none of the backends actually support fractional
# milliseconds, and some error or give warnings.
interval = int(interval)
self._interval = interval
self._timer_set_interval()
interval = property(_get_interval, _set_interval)
def _get_single_shot(self):
return self._single
def _set_single_shot(self, ss=True):
self._single = ss
self._timer_set_single_shot()
single_shot = property(_get_single_shot, _set_single_shot)
def add_callback(self, func, *args, **kwargs):
'''
Register `func` to be called by timer when the event fires. Any
additional arguments provided will be passed to `func`.
'''
self.callbacks.append((func, args, kwargs))
def remove_callback(self, func, *args, **kwargs):
'''
Remove `func` from list of callbacks. `args` and `kwargs` are optional
and used to distinguish between copies of the same function registered
to be called with different arguments.
'''
if args or kwargs:
self.callbacks.remove((func, args, kwargs))
else:
funcs = [c[0] for c in self.callbacks]
if func in funcs:
self.callbacks.pop(funcs.index(func))
def _timer_set_interval(self):
'Used to set interval on underlying timer object.'
pass
def _timer_set_single_shot(self):
'Used to set single shot on underlying timer object.'
pass
def _on_timer(self):
'''
Runs all function that have been registered as callbacks. Functions
can return False (or 0) if they should not be called any more. If there
are no callbacks, the timer is automatically stopped.
'''
for func, args, kwargs in self.callbacks:
ret = func(*args, **kwargs)
# docstring above explains why we use `if ret == False` here,
# instead of `if not ret`.
if ret == False:
self.callbacks.remove((func, args, kwargs))
if len(self.callbacks) == 0:
self.stop()
class Event:
"""
A matplotlib event. Attach additional attributes as defined in
:meth:`FigureCanvasBase.mpl_connect`. The following attributes
are defined and shown with their default values
*name*
the event name
*canvas*
the FigureCanvas instance generating the event
*guiEvent*
the GUI event that triggered the matplotlib event
"""
def __init__(self, name, canvas, guiEvent=None):
self.name = name
self.canvas = canvas
self.guiEvent = guiEvent
class IdleEvent(Event):
"""
An event triggered by the GUI backend when it is idle -- useful
for passive animation
"""
pass
class DrawEvent(Event):
"""
An event triggered by a draw operation on the canvas
In addition to the :class:`Event` attributes, the following event
attributes are defined:
*renderer*
the :class:`RendererBase` instance for the draw event
"""
def __init__(self, name, canvas, renderer):
Event.__init__(self, name, canvas)
self.renderer = renderer
class ResizeEvent(Event):
"""
An event triggered by a canvas resize
In addition to the :class:`Event` attributes, the following event
attributes are defined:
*width*
width of the canvas in pixels
*height*
height of the canvas in pixels
"""
def __init__(self, name, canvas):
Event.__init__(self, name, canvas)
self.width, self.height = canvas.get_width_height()
class CloseEvent(Event):
"""
An event triggered by a figure being closed
In addition to the :class:`Event` attributes, the following event
attributes are defined:
"""
def __init__(self, name, canvas, guiEvent=None):
Event.__init__(self, name, canvas, guiEvent)
class LocationEvent(Event):
"""
An event that has a screen location
The following additional attributes are defined and shown with
their default values.
In addition to the :class:`Event` attributes, the following
event attributes are defined:
*x*
x position - pixels from left of canvas
*y*
y position - pixels from bottom of canvas
*inaxes*
the :class:`~matplotlib.axes.Axes` instance if mouse is over axes
*xdata*
x coord of mouse in data coords
*ydata*
y coord of mouse in data coords
"""
x = None # x position - pixels from left of canvas
y = None # y position - pixels from right of canvas
inaxes = None # the Axes instance if mouse us over axes
xdata = None # x coord of mouse in data coords
ydata = None # y coord of mouse in data coords
# the last event that was triggered before this one
lastevent = None
def __init__(self, name, canvas, x, y, guiEvent=None):
"""
*x*, *y* in figure coords, 0,0 = bottom, left
"""
Event.__init__(self, name, canvas, guiEvent=guiEvent)
self.x = x
self.y = y
if x is None or y is None:
# cannot check if event was in axes if no x,y info
self.inaxes = None
self._update_enter_leave()
return
# Find all axes containing the mouse
if self.canvas.mouse_grabber is None:
axes_list = [a for a in self.canvas.figure.get_axes()
if a.in_axes(self)]
else:
axes_list = [self.canvas.mouse_grabber]
if len(axes_list) == 0: # None found
self.inaxes = None
self._update_enter_leave()
return
elif (len(axes_list) > 1): # Overlap, get the highest zorder
axes_list.sort(key=lambda x: x.zorder)
self.inaxes = axes_list[-1] # Use the highest zorder
else: # Just found one hit
self.inaxes = axes_list[0]
try:
trans = self.inaxes.transData.inverted()
xdata, ydata = trans.transform_point((x, y))
except ValueError:
self.xdata = None
self.ydata = None
else:
self.xdata = xdata
self.ydata = ydata
self._update_enter_leave()
def _update_enter_leave(self):
'process the figure/axes enter leave events'
if LocationEvent.lastevent is not None:
last = LocationEvent.lastevent
if last.inaxes != self.inaxes:
# process axes enter/leave events
try:
if last.inaxes is not None:
last.canvas.callbacks.process('axes_leave_event', last)
except:
pass
# See ticket 2901582.
# I think this is a valid exception to the rule
# against catching all exceptions; if anything goes
# wrong, we simply want to move on and process the
# current event.
if self.inaxes is not None:
self.canvas.callbacks.process('axes_enter_event', self)
else:
# process a figure enter event
if self.inaxes is not None:
self.canvas.callbacks.process('axes_enter_event', self)
LocationEvent.lastevent = self
class MouseEvent(LocationEvent):
"""
A mouse event ('button_press_event',
'button_release_event',
'scroll_event',
'motion_notify_event').
In addition to the :class:`Event` and :class:`LocationEvent`
attributes, the following attributes are defined:
*button*
button pressed None, 1, 2, 3, 'up', 'down' (up and down are used
for scroll events)
*key*
the key depressed when the mouse event triggered (see
:class:`KeyEvent`)
*step*
number of scroll steps (positive for 'up', negative for 'down')
Example usage::
def on_press(event):
print('you pressed', event.button, event.xdata, event.ydata)
cid = fig.canvas.mpl_connect('button_press_event', on_press)
"""
x = None # x position - pixels from left of canvas
y = None # y position - pixels from right of canvas
button = None # button pressed None, 1, 2, 3
dblclick = None # whether or not the event is the result of a double click
inaxes = None # the Axes instance if mouse us over axes
xdata = None # x coord of mouse in data coords
ydata = None # y coord of mouse in data coords
step = None # scroll steps for scroll events
def __init__(self, name, canvas, x, y, button=None, key=None,
step=0, dblclick=False, guiEvent=None):
"""
x, y in figure coords, 0,0 = bottom, left
button pressed None, 1, 2, 3, 'up', 'down'
"""
LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent)
self.button = button
self.key = key
self.step = step
self.dblclick = dblclick
def __str__(self):
return ("MPL MouseEvent: xy=(%d,%d) xydata=(%s,%s) button=%d " +
"dblclick=%s inaxes=%s") % (self.x, self.y, self.xdata,
self.ydata, self.button,
self.dblclick, self.inaxes)
class PickEvent(Event):
"""
a pick event, fired when the user picks a location on the canvas
sufficiently close to an artist.
Attrs: all the :class:`Event` attributes plus
*mouseevent*
the :class:`MouseEvent` that generated the pick
*artist*
the :class:`~matplotlib.artist.Artist` picked
other
extra class dependent attrs -- eg a
:class:`~matplotlib.lines.Line2D` pick may define different
extra attributes than a
:class:`~matplotlib.collections.PatchCollection` pick event
Example usage::
line, = ax.plot(rand(100), 'o', picker=5) # 5 points tolerance
def on_pick(event):
thisline = event.artist
xdata, ydata = thisline.get_data()
ind = event.ind
print('on pick line:', zip(xdata[ind], ydata[ind]))
cid = fig.canvas.mpl_connect('pick_event', on_pick)
"""
def __init__(self, name, canvas, mouseevent, artist,
guiEvent=None, **kwargs):
Event.__init__(self, name, canvas, guiEvent)
self.mouseevent = mouseevent
self.artist = artist
self.__dict__.update(kwargs)
class KeyEvent(LocationEvent):
"""
A key event (key press, key release).
Attach additional attributes as defined in
:meth:`FigureCanvasBase.mpl_connect`.
In addition to the :class:`Event` and :class:`LocationEvent`
attributes, the following attributes are defined:
*key*
the key(s) pressed. Could be **None**, a single case sensitive ascii
character ("g", "G", "#", etc.), a special key
("control", "shift", "f1", "up", etc.) or a
combination of the above (e.g., "ctrl+alt+g", "ctrl+alt+G").
.. note::
Modifier keys will be prefixed to the pressed key and will be in the
order "ctrl", "alt", "super". The exception to this rule is when the
pressed key is itself a modifier key, therefore "ctrl+alt" and
"alt+control" can both be valid key values.
Example usage::
def on_key(event):
print('you pressed', event.key, event.xdata, event.ydata)
cid = fig.canvas.mpl_connect('key_press_event', on_key)
"""
def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent)
self.key = key
class FigureCanvasBase(object):
"""
The canvas the figure renders into.
Public attributes
*figure*
A :class:`matplotlib.figure.Figure` instance
"""
events = [
'resize_event',
'draw_event',
'key_press_event',
'key_release_event',
'button_press_event',
'button_release_event',
'scroll_event',
'motion_notify_event',
'pick_event',
'idle_event',
'figure_enter_event',
'figure_leave_event',
'axes_enter_event',
'axes_leave_event',
'close_event'
]
supports_blit = True
def __init__(self, figure):
figure.set_canvas(self)
self.figure = figure
# a dictionary from event name to a dictionary that maps cid->func
self.callbacks = cbook.CallbackRegistry()
self.widgetlock = widgets.LockDraw()
self._button = None # the button pressed
self._key = None # the key pressed
self._lastx, self._lasty = None, None
self.button_pick_id = self.mpl_connect('button_press_event', self.pick)
self.scroll_pick_id = self.mpl_connect('scroll_event', self.pick)
self.mouse_grabber = None # the axes currently grabbing mouse
self.toolbar = None # NavigationToolbar2 will set me
self._is_saving = False
if False:
## highlight the artists that are hit
self.mpl_connect('motion_notify_event', self.onHilite)
## delete the artists that are clicked on
#self.mpl_disconnect(self.button_pick_id)
#self.mpl_connect('button_press_event',self.onRemove)
def is_saving(self):
"""
Returns `True` when the renderer is in the process of saving
to a file, rather than rendering for an on-screen buffer.
"""
return self._is_saving
def onRemove(self, ev):
"""
Mouse event processor which removes the top artist
under the cursor. Connect this to the 'mouse_press_event'
using::
canvas.mpl_connect('mouse_press_event',canvas.onRemove)
"""
def sort_artists(artists):
# This depends on stable sort and artists returned
# from get_children in z order.
L = [(h.zorder, h) for h in artists]
L.sort()
return [h for zorder, h in L]
# Find the top artist under the cursor
under = sort_artists(self.figure.hitlist(ev))
h = None
if under:
h = under[-1]
# Try deleting that artist, or its parent if you
# can't delete the artist
while h:
if h.remove():
self.draw_idle()
break
parent = None
for p in under:
if h in p.get_children():
parent = p
break
h = parent
def onHilite(self, ev):
"""
Mouse event processor which highlights the artists
under the cursor. Connect this to the 'motion_notify_event'
using::
canvas.mpl_connect('motion_notify_event',canvas.onHilite)
"""
if not hasattr(self, '_active'):
self._active = dict()
under = self.figure.hitlist(ev)
enter = [a for a in under if a not in self._active]
leave = [a for a in self._active if a not in under]
#print "within:"," ".join([str(x) for x in under])
#print "entering:",[str(a) for a in enter]
#print "leaving:",[str(a) for a in leave]
# On leave restore the captured colour
for a in leave:
if hasattr(a, 'get_color'):
a.set_color(self._active[a])
elif hasattr(a, 'get_edgecolor'):
a.set_edgecolor(self._active[a][0])
a.set_facecolor(self._active[a][1])
del self._active[a]
# On enter, capture the color and repaint the artist
# with the highlight colour. Capturing colour has to
# be done first in case the parent recolouring affects
# the child.
for a in enter:
if hasattr(a, 'get_color'):
self._active[a] = a.get_color()
elif hasattr(a, 'get_edgecolor'):
self._active[a] = (a.get_edgecolor(), a.get_facecolor())
else:
self._active[a] = None
for a in enter:
if hasattr(a, 'get_color'):
a.set_color('red')
elif hasattr(a, 'get_edgecolor'):
a.set_edgecolor('red')
a.set_facecolor('lightblue')
else:
self._active[a] = None
self.draw_idle()
def pick(self, mouseevent):
if not self.widgetlock.locked():
self.figure.pick(mouseevent)
def blit(self, bbox=None):
"""
blit the canvas in bbox (default entire canvas)
"""
pass
def resize(self, w, h):
"""
set the canvas size in pixels
"""
pass
def draw_event(self, renderer):
"""
This method will be call all functions connected to the
'draw_event' with a :class:`DrawEvent`
"""
s = 'draw_event'
event = DrawEvent(s, self, renderer)
self.callbacks.process(s, event)
def resize_event(self):
"""
This method will be call all functions connected to the
'resize_event' with a :class:`ResizeEvent`
"""
s = 'resize_event'
event = ResizeEvent(s, self)
self.callbacks.process(s, event)
def close_event(self, guiEvent=None):
"""
This method will be called by all functions connected to the
'close_event' with a :class:`CloseEvent`
"""
s = 'close_event'
try:
event = CloseEvent(s, self, guiEvent=guiEvent)
self.callbacks.process(s, event)
except (TypeError, AttributeError):
pass
# Suppress the TypeError when the python session is being killed.
# It may be that a better solution would be a mechanism to
# disconnect all callbacks upon shutdown.
# AttributeError occurs on OSX with qt4agg upon exiting
# with an open window; 'callbacks' attribute no longer exists.
def key_press_event(self, key, guiEvent=None):
"""
This method will be call all functions connected to the
'key_press_event' with a :class:`KeyEvent`
"""
self._key = key
s = 'key_press_event'
event = KeyEvent(
s, self, key, self._lastx, self._lasty, guiEvent=guiEvent)
self.callbacks.process(s, event)
def key_release_event(self, key, guiEvent=None):
"""
This method will be call all functions connected to the
'key_release_event' with a :class:`KeyEvent`
"""
s = 'key_release_event'
event = KeyEvent(
s, self, key, self._lastx, self._lasty, guiEvent=guiEvent)
self.callbacks.process(s, event)
self._key = None
def pick_event(self, mouseevent, artist, **kwargs):
"""
This method will be called by artists who are picked and will
fire off :class:`PickEvent` callbacks registered listeners
"""
s = 'pick_event'
event = PickEvent(s, self, mouseevent, artist, **kwargs)
self.callbacks.process(s, event)
def scroll_event(self, x, y, step, guiEvent=None):
"""
Backend derived classes should call this function on any
scroll wheel event. x,y are the canvas coords: 0,0 is lower,
left. button and key are as defined in MouseEvent.
This method will be call all functions connected to the
'scroll_event' with a :class:`MouseEvent` instance.
"""
if step >= 0:
self._button = 'up'
else:
self._button = 'down'
s = 'scroll_event'
mouseevent = MouseEvent(s, self, x, y, self._button, self._key,
step=step, guiEvent=guiEvent)
self.callbacks.process(s, mouseevent)
def button_press_event(self, x, y, button, dblclick=False, guiEvent=None):
"""
Backend derived classes should call this function on any mouse
button press. x,y are the canvas coords: 0,0 is lower, left.
button and key are as defined in :class:`MouseEvent`.
This method will be call all functions connected to the
'button_press_event' with a :class:`MouseEvent` instance.
"""
self._button = button
s = 'button_press_event'
mouseevent = MouseEvent(s, self, x, y, button, self._key,
dblclick=dblclick, guiEvent=guiEvent)
self.callbacks.process(s, mouseevent)
def button_release_event(self, x, y, button, guiEvent=None):
"""
Backend derived classes should call this function on any mouse
button release.
*x*
the canvas coordinates where 0=left
*y*
the canvas coordinates where 0=bottom
*guiEvent*
the native UI event that generated the mpl event
This method will be call all functions connected to the
'button_release_event' with a :class:`MouseEvent` instance.
"""
s = 'button_release_event'
event = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent)
self.callbacks.process(s, event)
self._button = None
def motion_notify_event(self, x, y, guiEvent=None):
"""
Backend derived classes should call this function on any
motion-notify-event.
*x*
the canvas coordinates where 0=left
*y*
the canvas coordinates where 0=bottom
*guiEvent*
the native UI event that generated the mpl event
This method will be call all functions connected to the
'motion_notify_event' with a :class:`MouseEvent` instance.
"""
self._lastx, self._lasty = x, y
s = 'motion_notify_event'
event = MouseEvent(s, self, x, y, self._button, self._key,
guiEvent=guiEvent)
self.callbacks.process(s, event)
def leave_notify_event(self, guiEvent=None):
"""
Backend derived classes should call this function when leaving
canvas
*guiEvent*
the native UI event that generated the mpl event
"""
self.callbacks.process('figure_leave_event', LocationEvent.lastevent)
LocationEvent.lastevent = None
self._lastx, self._lasty = None, None
def enter_notify_event(self, guiEvent=None, xy=None):
"""
Backend derived classes should call this function when entering
canvas
*guiEvent*
the native UI event that generated the mpl event
*xy*
the coordinate location of the pointer when the canvas is
entered
"""
if xy is not None:
x, y = xy
self._lastx, self._lasty = x, y
event = Event('figure_enter_event', self, guiEvent)
self.callbacks.process('figure_enter_event', event)
def idle_event(self, guiEvent=None):
"""Called when GUI is idle."""
s = 'idle_event'
event = IdleEvent(s, self, guiEvent=guiEvent)
self.callbacks.process(s, event)
def grab_mouse(self, ax):
"""
Set the child axes which are currently grabbing the mouse events.
Usually called by the widgets themselves.
It is an error to call this if the mouse is already grabbed by
another axes.
"""
if self.mouse_grabber not in (None, ax):
raise RuntimeError('two different attempted to grab mouse input')
self.mouse_grabber = ax
def release_mouse(self, ax):
"""
Release the mouse grab held by the axes, ax.
Usually called by the widgets.
It is ok to call this even if you ax doesn't have the mouse
grab currently.
"""
if self.mouse_grabber is ax:
self.mouse_grabber = None
def draw(self, *args, **kwargs):
"""
Render the :class:`~matplotlib.figure.Figure`
"""
pass
def draw_idle(self, *args, **kwargs):
"""
:meth:`draw` only if idle; defaults to draw but backends can overrride
"""
self.draw(*args, **kwargs)
def draw_cursor(self, event):
"""
Draw a cursor in the event.axes if inaxes is not None. Use
native GUI drawing for efficiency if possible
"""
pass
def get_width_height(self):
"""
Return the figure width and height in points or pixels
(depending on the backend), truncated to integers
"""
return int(self.figure.bbox.width), int(self.figure.bbox.height)
filetypes = {
'eps': 'Encapsulated Postscript',
'pdf': 'Portable Document Format',
'pgf': 'LaTeX PGF Figure',
'png': 'Portable Network Graphics',
'ps': 'Postscript',
'raw': 'Raw RGBA bitmap',
'rgba': 'Raw RGBA bitmap',
'svg': 'Scalable Vector Graphics',
'svgz': 'Scalable Vector Graphics'}
# All of these print_* functions do a lazy import because
# a) otherwise we'd have cyclical imports, since all of these
# classes inherit from FigureCanvasBase
# b) so we don't import a bunch of stuff the user may never use
# TODO: these print_* throw ImportErrror when called from
# compare_images_decorator (decorators.py line 112)
# if the backend has not already been loaded earlier on. Simple trigger:
# >>> import matplotlib.tests.test_spines
# >>> list(matplotlib.tests.test_spines.test_spines_axes_positions())[0][0]()
def print_eps(self, *args, **kwargs):
from .backends.backend_ps import FigureCanvasPS # lazy import
ps = self.switch_backends(FigureCanvasPS)
return ps.print_eps(*args, **kwargs)
def print_pdf(self, *args, **kwargs):
from .backends.backend_pdf import FigureCanvasPdf # lazy import
pdf = self.switch_backends(FigureCanvasPdf)
return pdf.print_pdf(*args, **kwargs)
def print_pgf(self, *args, **kwargs):
from .backends.backend_pgf import FigureCanvasPgf # lazy import
pgf = self.switch_backends(FigureCanvasPgf)
return pgf.print_pgf(*args, **kwargs)
def print_png(self, *args, **kwargs):
from .backends.backend_agg import FigureCanvasAgg # lazy import
agg = self.switch_backends(FigureCanvasAgg)
return agg.print_png(*args, **kwargs)
def print_ps(self, *args, **kwargs):
from .backends.backend_ps import FigureCanvasPS # lazy import
ps = self.switch_backends(FigureCanvasPS)
return ps.print_ps(*args, **kwargs)
def print_raw(self, *args, **kwargs):
from .backends.backend_agg import FigureCanvasAgg # lazy import
agg = self.switch_backends(FigureCanvasAgg)
return agg.print_raw(*args, **kwargs)
print_bmp = print_rgba = print_raw
def print_svg(self, *args, **kwargs):
from .backends.backend_svg import FigureCanvasSVG # lazy import
svg = self.switch_backends(FigureCanvasSVG)
return svg.print_svg(*args, **kwargs)
def print_svgz(self, *args, **kwargs):
from .backends.backend_svg import FigureCanvasSVG # lazy import
svg = self.switch_backends(FigureCanvasSVG)
return svg.print_svgz(*args, **kwargs)
if _has_pil:
filetypes['jpg'] = 'Joint Photographic Experts Group'
filetypes['jpeg'] = filetypes['jpg']
def print_jpg(self, filename_or_obj, *args, **kwargs):
"""
Supported kwargs:
*quality*: The image quality, on a scale from 1 (worst) to
95 (best). The default is 95, if not given in the
matplotlibrc file in the savefig.jpeg_quality parameter.
Values above 95 should be avoided; 100 completely
disables the JPEG quantization stage.
*optimize*: If present, indicates that the encoder should
make an extra pass over the image in order to select
optimal encoder settings.
*progressive*: If present, indicates that this image
should be stored as a progressive JPEG file.
"""
from .backends.backend_agg import FigureCanvasAgg # lazy import
agg = self.switch_backends(FigureCanvasAgg)
buf, size = agg.print_to_buffer()
if kwargs.pop("dryrun", False):
return
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
options = cbook.restrict_dict(kwargs, ['quality', 'optimize',
'progressive'])
if 'quality' not in options:
options['quality'] = rcParams['savefig.jpeg_quality']
return image.save(filename_or_obj, format='jpeg', **options)
print_jpeg = print_jpg
filetypes['tif'] = filetypes['tiff'] = 'Tagged Image File Format'
def print_tif(self, filename_or_obj, *args, **kwargs):
from .backends.backend_agg import FigureCanvasAgg # lazy import
agg = self.switch_backends(FigureCanvasAgg)
buf, size = agg.print_to_buffer()
if kwargs.pop("dryrun", False):
return
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
dpi = (self.figure.dpi, self.figure.dpi)
return image.save(filename_or_obj, format='tiff',
dpi=dpi)
print_tiff = print_tif
def get_supported_filetypes(self):
"""Return dict of savefig file formats supported by this backend"""
return self.filetypes
def get_supported_filetypes_grouped(self):
"""Return a dict of savefig file formats supported by this backend,
where the keys are a file type name, such as 'Joint Photographic
Experts Group', and the values are a list of filename extensions used
for that filetype, such as ['jpg', 'jpeg']."""
groupings = {}
for ext, name in self.filetypes.items():
groupings.setdefault(name, []).append(ext)
groupings[name].sort()
return groupings
def _get_print_method(self, format):
method_name = 'print_%s' % format
# check for registered backends
if format in _backend_d:
backend_class = _backend_d[format]
def _print_method(*args, **kwargs):
backend = self.switch_backends(backend_class)
print_method = getattr(backend, method_name)
return print_method(*args, **kwargs)
return _print_method
formats = self.get_supported_filetypes()
if (format not in formats or not hasattr(self, method_name)):
formats = sorted(formats)
raise ValueError(
'Format "%s" is not supported.\n'
'Supported formats: '
'%s.' % (format, ', '.join(formats)))
return getattr(self, method_name)
def print_figure(self, filename, dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', format=None, **kwargs):
"""
Render the figure to hardcopy. Set the figure patch face and edge
colors. This is useful because some of the GUIs have a gray figure
face color background and you'll probably want to override this on
hardcopy.
Arguments are:
*filename*
can also be a file object on image backends
*orientation*
only currently applies to PostScript printing.
*dpi*
the dots per inch to save the figure in; if None, use savefig.dpi
*facecolor*
the facecolor of the figure
*edgecolor*
the edgecolor of the figure
*orientation*
landscape' | 'portrait' (not supported on all backends)
*format*
when set, forcibly set the file format to save to
*bbox_inches*
Bbox in inches. Only the given portion of the figure is
saved. If 'tight', try to figure out the tight bbox of
the figure. If None, use savefig.bbox
*pad_inches*
Amount of padding around the figure when bbox_inches is
'tight'. If None, use savefig.pad_inches
*bbox_extra_artists*
A list of extra artists that will be considered when the
tight bbox is calculated.
"""
if format is None:
# get format from filename, or from backend's default filetype
if cbook.is_string_like(filename):
format = os.path.splitext(filename)[1][1:]
if format is None or format == '':
format = self.get_default_filetype()
if cbook.is_string_like(filename):
filename = filename.rstrip('.') + '.' + format
format = format.lower()
print_method = self._get_print_method(format)
if dpi is None:
dpi = rcParams['savefig.dpi']
origDPI = self.figure.dpi
origfacecolor = self.figure.get_facecolor()
origedgecolor = self.figure.get_edgecolor()
self.figure.dpi = dpi
self.figure.set_facecolor(facecolor)
self.figure.set_edgecolor(edgecolor)
bbox_inches = kwargs.pop("bbox_inches", None)
if bbox_inches is None:
bbox_inches = rcParams['savefig.bbox']
if bbox_inches:
# call adjust_bbox to save only the given area
if bbox_inches == "tight":
# when bbox_inches == "tight", it saves the figure
# twice. The first save command is just to estimate
# the bounding box of the figure. A stringIO object is
# used as a temporary file object, but it causes a
# problem for some backends (ps backend with
# usetex=True) if they expect a filename, not a
# file-like object. As I think it is best to change
# the backend to support file-like object, i'm going
# to leave it as it is. However, a better solution
# than stringIO seems to be needed. -JJL
#result = getattr(self, method_name)
result = print_method(
io.BytesIO(),
dpi=dpi,
facecolor=facecolor,
edgecolor=edgecolor,
orientation=orientation,
dryrun=True,
**kwargs)
renderer = self.figure._cachedRenderer
bbox_inches = self.figure.get_tightbbox(renderer)
bbox_artists = kwargs.pop("bbox_extra_artists", None)
if bbox_artists is None:
bbox_artists = self.figure.get_default_bbox_extra_artists()
bbox_filtered = []
for a in bbox_artists:
bbox = a.get_window_extent(renderer)
if a.get_clip_on():
clip_box = a.get_clip_box()
if clip_box is not None:
bbox = Bbox.intersection(bbox, clip_box)
clip_path = a.get_clip_path()
if clip_path is not None and bbox is not None:
clip_path = clip_path.get_fully_transformed_path()
bbox = Bbox.intersection(bbox,
clip_path.get_extents())
if bbox is not None and (bbox.width != 0 or
bbox.height != 0):
bbox_filtered.append(bbox)
if bbox_filtered:
_bbox = Bbox.union(bbox_filtered)
trans = Affine2D().scale(1.0 / self.figure.dpi)
bbox_extra = TransformedBbox(_bbox, trans)
bbox_inches = Bbox.union([bbox_inches, bbox_extra])
pad = kwargs.pop("pad_inches", None)
if pad is None:
pad = rcParams['savefig.pad_inches']
bbox_inches = bbox_inches.padded(pad)
restore_bbox = tight_bbox.adjust_bbox(self.figure, format,
bbox_inches)
_bbox_inches_restore = (bbox_inches, restore_bbox)
else:
_bbox_inches_restore = None
self._is_saving = True
try:
#result = getattr(self, method_name)(
result = print_method(
filename,
dpi=dpi,
facecolor=facecolor,
edgecolor=edgecolor,
orientation=orientation,
bbox_inches_restore=_bbox_inches_restore,
**kwargs)
finally:
if bbox_inches and restore_bbox:
restore_bbox()
self.figure.dpi = origDPI
self.figure.set_facecolor(origfacecolor)
self.figure.set_edgecolor(origedgecolor)
self.figure.set_canvas(self)
self._is_saving = False
#self.figure.canvas.draw() ## seems superfluous
return result
def get_default_filetype(self):
"""
Get the default savefig file format as specified in rcParam
``savefig.format``. Returned string excludes period. Overridden
in backends that only support a single file type.
"""
return rcParams['savefig.format']
def get_window_title(self):
"""
Get the title text of the window containing the figure.
Return None if there is no window (eg, a PS backend).
"""
if hasattr(self, "manager"):
return self.manager.get_window_title()
def set_window_title(self, title):
"""
Set the title text of the window containing the figure. Note that
this has no effect if there is no window (eg, a PS backend).
"""
if hasattr(self, "manager"):
self.manager.set_window_title(title)
def get_default_filename(self):
"""
Return a string, which includes extension, suitable for use as
a default filename.
"""
default_filename = self.get_window_title() or 'image'
default_filename = default_filename.lower().replace(' ', '_')
return default_filename + '.' + self.get_default_filetype()
def switch_backends(self, FigureCanvasClass):
"""
Instantiate an instance of FigureCanvasClass
This is used for backend switching, eg, to instantiate a
FigureCanvasPS from a FigureCanvasGTK. Note, deep copying is
not done, so any changes to one of the instances (eg, setting
figure size or line props), will be reflected in the other
"""
newCanvas = FigureCanvasClass(self.figure)
newCanvas._is_saving = self._is_saving
return newCanvas
def mpl_connect(self, s, func):
"""
Connect event with string *s* to *func*. The signature of *func* is::
def func(event)
where event is a :class:`matplotlib.backend_bases.Event`. The
following events are recognized
- 'button_press_event'
- 'button_release_event'
- 'draw_event'
- 'key_press_event'
- 'key_release_event'
- 'motion_notify_event'
- 'pick_event'
- 'resize_event'
- 'scroll_event'
- 'figure_enter_event',
- 'figure_leave_event',
- 'axes_enter_event',
- 'axes_leave_event'
- 'close_event'
For the location events (button and key press/release), if the
mouse is over the axes, the variable ``event.inaxes`` will be
set to the :class:`~matplotlib.axes.Axes` the event occurs is
over, and additionally, the variables ``event.xdata`` and
``event.ydata`` will be defined. This is the mouse location
in data coords. See
:class:`~matplotlib.backend_bases.KeyEvent` and
:class:`~matplotlib.backend_bases.MouseEvent` for more info.
Return value is a connection id that can be used with
:meth:`~matplotlib.backend_bases.Event.mpl_disconnect`.
Example usage::
def on_press(event):
print('you pressed', event.button, event.xdata, event.ydata)
cid = canvas.mpl_connect('button_press_event', on_press)
"""
return self.callbacks.connect(s, func)
def mpl_disconnect(self, cid):
"""
Disconnect callback id cid
Example usage::
cid = canvas.mpl_connect('button_press_event', on_press)
#...later
canvas.mpl_disconnect(cid)
"""
return self.callbacks.disconnect(cid)
def new_timer(self, *args, **kwargs):
"""
Creates a new backend-specific subclass of
:class:`backend_bases.Timer`. This is useful for getting periodic
events through the backend's native event loop. Implemented only for
backends with GUIs.
optional arguments:
*interval*
Timer interval in milliseconds
*callbacks*
Sequence of (func, args, kwargs) where func(*args, **kwargs) will
be executed by the timer every *interval*.
"""
return TimerBase(*args, **kwargs)
def flush_events(self):
"""
Flush the GUI events for the figure. Implemented only for
backends with GUIs.
"""
raise NotImplementedError
def start_event_loop(self, timeout):
"""
Start an event loop. This is used to start a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events. This should not be
confused with the main GUI event loop, which is always running
and has nothing to do with this.
This is implemented only for backends with GUIs.
"""
raise NotImplementedError
def stop_event_loop(self):
"""
Stop an event loop. This is used to stop a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.
This is implemented only for backends with GUIs.
"""
raise NotImplementedError
def start_event_loop_default(self, timeout=0):
"""
Start an event loop. This is used to start a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events. This should not be
confused with the main GUI event loop, which is always running
and has nothing to do with this.
This function provides default event loop functionality based
on time.sleep that is meant to be used until event loop
functions for each of the GUI backends can be written. As
such, it throws a deprecated warning.
Call signature::
start_event_loop_default(self,timeout=0)
This call blocks until a callback function triggers
stop_event_loop() or *timeout* is reached. If *timeout* is
<=0, never timeout.
"""
str = "Using default event loop until function specific"
str += " to this GUI is implemented"
warnings.warn(str, mplDeprecation)
if timeout <= 0:
timeout = np.inf
timestep = 0.01
counter = 0
self._looping = True
while self._looping and counter * timestep < timeout:
self.flush_events()
time.sleep(timestep)
counter += 1
def stop_event_loop_default(self):
"""
Stop an event loop. This is used to stop a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.
Call signature::
stop_event_loop_default(self)
"""
self._looping = False
def key_press_handler(event, canvas, toolbar=None):
"""
Implement the default mpl key bindings for the canvas and toolbar
described at :ref:`key-event-handling`
*event*
a :class:`KeyEvent` instance
*canvas*
a :class:`FigureCanvasBase` instance
*toolbar*
a :class:`NavigationToolbar2` instance
"""
# these bindings happen whether you are over an axes or not
if event.key is None:
return
# Load key-mappings from your matplotlibrc file.
fullscreen_keys = rcParams['keymap.fullscreen']
home_keys = rcParams['keymap.home']
back_keys = rcParams['keymap.back']
forward_keys = rcParams['keymap.forward']
pan_keys = rcParams['keymap.pan']
zoom_keys = rcParams['keymap.zoom']
save_keys = rcParams['keymap.save']
quit_keys = rcParams['keymap.quit']
grid_keys = rcParams['keymap.grid']
toggle_yscale_keys = rcParams['keymap.yscale']
toggle_xscale_keys = rcParams['keymap.xscale']
all = rcParams['keymap.all_axes']
# toggle fullscreen mode (default key 'f')
if event.key in fullscreen_keys:
canvas.manager.full_screen_toggle()
# quit the figure (defaut key 'ctrl+w')
if event.key in quit_keys:
Gcf.destroy_fig(canvas.figure)
if toolbar is not None:
# home or reset mnemonic (default key 'h', 'home' and 'r')
if event.key in home_keys:
toolbar.home()
# forward / backward keys to enable left handed quick navigation
# (default key for backward: 'left', 'backspace' and 'c')
elif event.key in back_keys:
toolbar.back()
# (default key for forward: 'right' and 'v')
elif event.key in forward_keys:
toolbar.forward()
# pan mnemonic (default key 'p')
elif event.key in pan_keys:
toolbar.pan()
# zoom mnemonic (default key 'o')
elif event.key in zoom_keys:
toolbar.zoom()
# saving current figure (default key 's')
elif event.key in save_keys:
toolbar.save_figure()
if event.inaxes is None:
return
# these bindings require the mouse to be over an axes to trigger
# switching on/off a grid in current axes (default key 'g')
if event.key in grid_keys:
event.inaxes.grid()
canvas.draw()
# toggle scaling of y-axes between 'log and 'linear' (default key 'l')
elif event.key in toggle_yscale_keys:
ax = event.inaxes
scale = ax.get_yscale()
if scale == 'log':
ax.set_yscale('linear')
ax.figure.canvas.draw()
elif scale == 'linear':
ax.set_yscale('log')
ax.figure.canvas.draw()
# toggle scaling of x-axes between 'log and 'linear' (default key 'k')
elif event.key in toggle_xscale_keys:
ax = event.inaxes
scalex = ax.get_xscale()
if scalex == 'log':
ax.set_xscale('linear')
ax.figure.canvas.draw()
elif scalex == 'linear':
ax.set_xscale('log')
ax.figure.canvas.draw()
elif (event.key.isdigit() and event.key != '0') or event.key in all:
# keys in list 'all' enables all axes (default key 'a'),
# otherwise if key is a number only enable this particular axes
# if it was the axes, where the event was raised
if not (event.key in all):
n = int(event.key) - 1
for i, a in enumerate(canvas.figure.get_axes()):
# consider axes, in which the event was raised
# FIXME: Why only this axes?
if event.x is not None and event.y is not None \
and a.in_axes(event):
if event.key in all:
a.set_navigate(True)
else:
a.set_navigate(i == n)
class NonGuiException(Exception):
pass
class FigureManagerBase:
"""
Helper class for pyplot mode, wraps everything up into a neat bundle
Public attibutes:
*canvas*
A :class:`FigureCanvasBase` instance
*num*
The figure number
"""
def __init__(self, canvas, num):
self.canvas = canvas
canvas.manager = self # store a pointer to parent
self.num = num
self.key_press_handler_id = self.canvas.mpl_connect('key_press_event',
self.key_press)
"""
The returned id from connecting the default key handler via
:meth:`FigureCanvasBase.mpl_connnect`.
To disable default key press handling::
manager, canvas = figure.canvas.manager, figure.canvas
canvas.mpl_disconnect(manager.key_press_handler_id)
"""
def show(self):
"""
For GUI backends, show the figure window and redraw.
For non-GUI backends, raise an exception to be caught
by :meth:`~matplotlib.figure.Figure.show`, for an
optional warning.
"""
raise NonGuiException()
def destroy(self):
pass
def full_screen_toggle(self):
pass
def resize(self, w, h):
""""For gui backends, resize the window (in pixels)."""
pass
def key_press(self, event):
"""
Implement the default mpl key bindings defined at
:ref:`key-event-handling`
"""
key_press_handler(event, self.canvas, self.canvas.toolbar)
def show_popup(self, msg):
"""
Display message in a popup -- GUI only
"""
pass
def get_window_title(self):
"""
Get the title text of the window containing the figure.
Return None for non-GUI backends (eg, a PS backend).
"""
return 'image'
def set_window_title(self, title):
"""
Set the title text of the window containing the figure. Note that
this has no effect for non-GUI backends (eg, a PS backend).
"""
pass
class Cursors:
# this class is only used as a simple namespace
HAND, POINTER, SELECT_REGION, MOVE = list(range(4))
cursors = Cursors()
class NavigationToolbar2(object):
"""
Base class for the navigation cursor, version 2
backends must implement a canvas that handles connections for
'button_press_event' and 'button_release_event'. See
:meth:`FigureCanvasBase.mpl_connect` for more information
They must also define
:meth:`save_figure`
save the current figure
:meth:`set_cursor`
if you want the pointer icon to change
:meth:`_init_toolbar`
create your toolbar widget
:meth:`draw_rubberband` (optional)
draw the zoom to rect "rubberband" rectangle
:meth:`press` (optional)
whenever a mouse button is pressed, you'll be notified with
the event
:meth:`release` (optional)
whenever a mouse button is released, you'll be notified with
the event
:meth:`dynamic_update` (optional)
dynamically update the window while navigating
:meth:`set_message` (optional)
display message
:meth:`set_history_buttons` (optional)
you can change the history back / forward buttons to
indicate disabled / enabled state.
That's it, we'll do the rest!
"""
# list of toolitems to add to the toolbar, format is:
# (
# text, # the text of the button (often not visible to users)
# tooltip_text, # the tooltip shown on hover (where possible)
# image_file, # name of the image for the button (without the extension)
# name_of_method, # name of the method in NavigationToolbar2 to call
# )
toolitems = (
('Home', 'Reset original view', 'home', 'home'),
('Back', 'Back to previous view', 'back', 'back'),
('Forward', 'Forward to next view', 'forward', 'forward'),
(None, None, None, None),
('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'),
('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'),
(None, None, None, None),
('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
('Save', 'Save the figure', 'filesave', 'save_figure'),
)
def __init__(self, canvas):
self.canvas = canvas
canvas.toolbar = self
# a dict from axes index to a list of view limits
self._views = cbook.Stack()
self._positions = cbook.Stack() # stack of subplot positions
self._xypress = None # the location and axis info at the time
# of the press
self._idPress = None
self._idRelease = None
self._active = None
self._lastCursor = None
self._init_toolbar()
self._idDrag = self.canvas.mpl_connect(
'motion_notify_event', self.mouse_move)
self._ids_zoom = []
self._zoom_mode = None
self._button_pressed = None # determined by the button pressed
# at start
self.mode = '' # a mode string for the status bar
self.set_history_buttons()
def set_message(self, s):
"""Display a message on toolbar or in status bar"""
pass
def back(self, *args):
"""move back up the view lim stack"""
self._views.back()
self._positions.back()
self.set_history_buttons()
self._update_view()
def dynamic_update(self):
pass
def draw_rubberband(self, event, x0, y0, x1, y1):
"""Draw a rectangle rubberband to indicate zoom limits"""
pass
def forward(self, *args):
"""Move forward in the view lim stack"""
self._views.forward()
self._positions.forward()
self.set_history_buttons()
self._update_view()
def home(self, *args):
"""Restore the original view"""
self._views.home()
self._positions.home()
self.set_history_buttons()
self._update_view()
def _init_toolbar(self):
"""
This is where you actually build the GUI widgets (called by
__init__). The icons ``home.xpm``, ``back.xpm``, ``forward.xpm``,
``hand.xpm``, ``zoom_to_rect.xpm`` and ``filesave.xpm`` are standard
across backends (there are ppm versions in CVS also).
You just need to set the callbacks
home : self.home
back : self.back
forward : self.forward
hand : self.pan
zoom_to_rect : self.zoom
filesave : self.save_figure
You only need to define the last one - the others are in the base
class implementation.
"""
raise NotImplementedError
def mouse_move(self, event):
if not event.inaxes or not self._active:
if self._lastCursor != cursors.POINTER:
self.set_cursor(cursors.POINTER)
self._lastCursor = cursors.POINTER
else:
if self._active == 'ZOOM':
if self._lastCursor != cursors.SELECT_REGION:
self.set_cursor(cursors.SELECT_REGION)
self._lastCursor = cursors.SELECT_REGION
elif (self._active == 'PAN' and
self._lastCursor != cursors.MOVE):
self.set_cursor(cursors.MOVE)
self._lastCursor = cursors.MOVE
if event.inaxes and event.inaxes.get_navigate():
try:
s = event.inaxes.format_coord(event.xdata, event.ydata)
except (ValueError, OverflowError):
pass
else:
if len(self.mode):
self.set_message('%s, %s' % (self.mode, s))
else:
self.set_message(s)
else:
self.set_message(self.mode)
def pan(self, *args):
"""Activate the pan/zoom tool. pan with left button, zoom with right"""
# set the pointer icon and button press funcs to the
# appropriate callbacks
if self._active == 'PAN':
self._active = None
else:
self._active = 'PAN'
if self._idPress is not None:
self._idPress = self.canvas.mpl_disconnect(self._idPress)
self.mode = ''
if self._idRelease is not None:
self._idRelease = self.canvas.mpl_disconnect(self._idRelease)
self.mode = ''
if self._active:
self._idPress = self.canvas.mpl_connect(
'button_press_event', self.press_pan)
self._idRelease = self.canvas.mpl_connect(
'button_release_event', self.release_pan)
self.mode = 'pan/zoom'
self.canvas.widgetlock(self)
else:
self.canvas.widgetlock.release(self)
for a in self.canvas.figure.get_axes():
a.set_navigate_mode(self._active)
self.set_message(self.mode)
def press(self, event):
"""Called whenver a mouse button is pressed."""
pass
def press_pan(self, event):
"""the press mouse button in pan/zoom mode callback"""
if event.button == 1:
self._button_pressed = 1
elif event.button == 3:
self._button_pressed = 3
else:
self._button_pressed = None
return
x, y = event.x, event.y
# push the current view to define home if stack is empty
if self._views.empty():
self.push_current()
self._xypress = []
for i, a in enumerate(self.canvas.figure.get_axes()):
if (x is not None and y is not None and a.in_axes(event) and
a.get_navigate() and a.can_pan()):
a.start_pan(x, y, event.button)
self._xypress.append((a, i))
self.canvas.mpl_disconnect(self._idDrag)
self._idDrag = self.canvas.mpl_connect('motion_notify_event',
self.drag_pan)
self.press(event)
def press_zoom(self, event):
"""the press mouse button in zoom to rect mode callback"""
# If we're already in the middle of a zoom, pressing another
# button works to "cancel"
if self._ids_zoom != []:
for zoom_id in self._ids_zoom:
self.canvas.mpl_disconnect(zoom_id)
self.release(event)
self.draw()
self._xypress = None
self._button_pressed = None
self._ids_zoom = []
return
if event.button == 1:
self._button_pressed = 1
elif event.button == 3:
self._button_pressed = 3
else:
self._button_pressed = None
return
x, y = event.x, event.y
# push the current view to define home if stack is empty
if self._views.empty():
self.push_current()
self._xypress = []
for i, a in enumerate(self.canvas.figure.get_axes()):
if (x is not None and y is not None and a.in_axes(event) and
a.get_navigate() and a.can_zoom()):
self._xypress.append((x, y, a, i, a.viewLim.frozen(),
a.transData.frozen()))
id1 = self.canvas.mpl_connect('motion_notify_event', self.drag_zoom)
id2 = self.canvas.mpl_connect('key_press_event',
self._switch_on_zoom_mode)
id3 = self.canvas.mpl_connect('key_release_event',
self._switch_off_zoom_mode)
self._ids_zoom = id1, id2, id3
self._zoom_mode = event.key
self.press(event)
def _switch_on_zoom_mode(self, event):
self._zoom_mode = event.key
self.mouse_move(event)
def _switch_off_zoom_mode(self, event):
self._zoom_mode = None
self.mouse_move(event)
def push_current(self):
"""push the current view limits and position onto the stack"""
lims = []
pos = []
for a in self.canvas.figure.get_axes():
xmin, xmax = a.get_xlim()
ymin, ymax = a.get_ylim()
lims.append((xmin, xmax, ymin, ymax))
# Store both the original and modified positions
pos.append((
a.get_position(True).frozen(),
a.get_position().frozen()))
self._views.push(lims)
self._positions.push(pos)
self.set_history_buttons()
def release(self, event):
"""this will be called whenever mouse button is released"""
pass
def release_pan(self, event):
"""the release mouse button callback in pan/zoom mode"""
if self._button_pressed is None:
return
self.canvas.mpl_disconnect(self._idDrag)
self._idDrag = self.canvas.mpl_connect(
'motion_notify_event', self.mouse_move)
for a, ind in self._xypress:
a.end_pan()
if not self._xypress:
return
self._xypress = []
self._button_pressed = None
self.push_current()
self.release(event)
self.draw()
def drag_pan(self, event):
"""the drag callback in pan/zoom mode"""
for a, ind in self._xypress:
#safer to use the recorded button at the press than current button:
#multiple button can get pressed during motion...
a.drag_pan(self._button_pressed, event.key, event.x, event.y)
self.dynamic_update()
def drag_zoom(self, event):
"""the drag callback in zoom mode"""
if self._xypress:
x, y = event.x, event.y
lastx, lasty, a, ind, lim, trans = self._xypress[0]
# adjust x, last, y, last
x1, y1, x2, y2 = a.bbox.extents
x, lastx = max(min(x, lastx), x1), min(max(x, lastx), x2)
y, lasty = max(min(y, lasty), y1), min(max(y, lasty), y2)
if self._zoom_mode == "x":
x1, y1, x2, y2 = a.bbox.extents
y, lasty = y1, y2
elif self._zoom_mode == "y":
x1, y1, x2, y2 = a.bbox.extents
x, lastx = x1, x2
self.draw_rubberband(event, x, y, lastx, lasty)
def release_zoom(self, event):
"""the release mouse button callback in zoom to rect mode"""
for zoom_id in self._ids_zoom:
self.canvas.mpl_disconnect(zoom_id)
self._ids_zoom = []
if not self._xypress:
return
last_a = []
for cur_xypress in self._xypress:
x, y = event.x, event.y
lastx, lasty, a, ind, lim, trans = cur_xypress
# ignore singular clicks - 5 pixels is a threshold
if abs(x - lastx) < 5 or abs(y - lasty) < 5:
self._xypress = None
self.release(event)
self.draw()
return
x0, y0, x1, y1 = lim.extents
# zoom to rect
inverse = a.transData.inverted()
lastx, lasty = inverse.transform_point((lastx, lasty))
x, y = inverse.transform_point((x, y))
Xmin, Xmax = a.get_xlim()
Ymin, Ymax = a.get_ylim()
# detect twinx,y axes and avoid double zooming
twinx, twiny = False, False
if last_a:
for la in last_a:
if a.get_shared_x_axes().joined(a, la):
twinx = True
if a.get_shared_y_axes().joined(a, la):
twiny = True
last_a.append(a)
if twinx:
x0, x1 = Xmin, Xmax
else:
if Xmin < Xmax:
if x < lastx:
x0, x1 = x, lastx
else:
x0, x1 = lastx, x
if x0 < Xmin:
x0 = Xmin
if x1 > Xmax:
x1 = Xmax
else:
if x > lastx:
x0, x1 = x, lastx
else:
x0, x1 = lastx, x
if x0 > Xmin:
x0 = Xmin
if x1 < Xmax:
x1 = Xmax
if twiny:
y0, y1 = Ymin, Ymax
else:
if Ymin < Ymax:
if y < lasty:
y0, y1 = y, lasty
else:
y0, y1 = lasty, y
if y0 < Ymin:
y0 = Ymin
if y1 > Ymax:
y1 = Ymax
else:
if y > lasty:
y0, y1 = y, lasty
else:
y0, y1 = lasty, y
if y0 > Ymin:
y0 = Ymin
if y1 < Ymax:
y1 = Ymax
if self._button_pressed == 1:
if self._zoom_mode == "x":
a.set_xlim((x0, x1))
elif self._zoom_mode == "y":
a.set_ylim((y0, y1))
else:
a.set_xlim((x0, x1))
a.set_ylim((y0, y1))
elif self._button_pressed == 3:
if a.get_xscale() == 'log':
alpha = np.log(Xmax / Xmin) / np.log(x1 / x0)
rx1 = pow(Xmin / x0, alpha) * Xmin
rx2 = pow(Xmax / x0, alpha) * Xmin
else:
alpha = (Xmax - Xmin) / (x1 - x0)
rx1 = alpha * (Xmin - x0) + Xmin
rx2 = alpha * (Xmax - x0) + Xmin
if a.get_yscale() == 'log':
alpha = np.log(Ymax / Ymin) / np.log(y1 / y0)
ry1 = pow(Ymin / y0, alpha) * Ymin
ry2 = pow(Ymax / y0, alpha) * Ymin
else:
alpha = (Ymax - Ymin) / (y1 - y0)
ry1 = alpha * (Ymin - y0) + Ymin
ry2 = alpha * (Ymax - y0) + Ymin
if self._zoom_mode == "x":
a.set_xlim((rx1, rx2))
elif self._zoom_mode == "y":
a.set_ylim((ry1, ry2))
else:
a.set_xlim((rx1, rx2))
a.set_ylim((ry1, ry2))
self.draw()
self._xypress = None
self._button_pressed = None
self._zoom_mode = None
self.push_current()
self.release(event)
def draw(self):
"""Redraw the canvases, update the locators"""
for a in self.canvas.figure.get_axes():
xaxis = getattr(a, 'xaxis', None)
yaxis = getattr(a, 'yaxis', None)
locators = []
if xaxis is not None:
locators.append(xaxis.get_major_locator())
locators.append(xaxis.get_minor_locator())
if yaxis is not None:
locators.append(yaxis.get_major_locator())
locators.append(yaxis.get_minor_locator())
for loc in locators:
loc.refresh()
self.canvas.draw_idle()
def _update_view(self):
"""Update the viewlim and position from the view and
position stack for each axes
"""
lims = self._views()
if lims is None:
return
pos = self._positions()
if pos is None:
return
for i, a in enumerate(self.canvas.figure.get_axes()):
xmin, xmax, ymin, ymax = lims[i]
a.set_xlim((xmin, xmax))
a.set_ylim((ymin, ymax))
# Restore both the original and modified positions
a.set_position(pos[i][0], 'original')
a.set_position(pos[i][1], 'active')
self.canvas.draw_idle()
def save_figure(self, *args):
"""Save the current figure"""
raise NotImplementedError
def set_cursor(self, cursor):
"""
Set the current cursor to one of the :class:`Cursors`
enums values
"""
pass
def update(self):
"""Reset the axes stack"""
self._views.clear()
self._positions.clear()
self.set_history_buttons()
def zoom(self, *args):
"""Activate zoom to rect mode"""
if self._active == 'ZOOM':
self._active = None
else:
self._active = 'ZOOM'
if self._idPress is not None:
self._idPress = self.canvas.mpl_disconnect(self._idPress)
self.mode = ''
if self._idRelease is not None:
self._idRelease = self.canvas.mpl_disconnect(self._idRelease)
self.mode = ''
if self._active:
self._idPress = self.canvas.mpl_connect('button_press_event',
self.press_zoom)
self._idRelease = self.canvas.mpl_connect('button_release_event',
self.release_zoom)
self.mode = 'zoom rect'
self.canvas.widgetlock(self)
else:
self.canvas.widgetlock.release(self)
for a in self.canvas.figure.get_axes():
a.set_navigate_mode(self._active)
self.set_message(self.mode)
def set_history_buttons(self):
"""Enable or disable back/forward button"""
pass
| alephu5/Soundbyte | environment/lib/python3.3/site-packages/matplotlib/backend_bases.py | Python | gpl-3.0 | 106,921 |
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import datetime
import decimal
import httplib
import json
import threading
import time
import re
from decimal import Decimal
from electrum_myr.plugins import BasePlugin, hook
from electrum_myr.i18n import _
from electrum_myr_gui.qt.util import *
from electrum_myr_gui.qt.amountedit import AmountEdit
EXCHANGES = ["Cryptsy",
"MintPal",
"Prelude"]
EXCH_SUPPORT_HIST = [("BitcoinVenezuela", "ARS"),
("BitcoinVenezuela", "EUR"),
("BitcoinVenezuela", "USD"),
("BitcoinVenezuela", "VEF"),
("Kraken", "EUR"),
("Kraken", "USD")]
class Exchanger(threading.Thread):
def __init__(self, parent):
threading.Thread.__init__(self)
self.daemon = True
self.parent = parent
self.quote_currencies = None
self.lock = threading.Lock()
self.query_rates = threading.Event()
self.use_exchange = self.parent.config.get('use_exchange', "MintPal")
self.parent.exchanges = EXCHANGES
self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
self.parent.win.emit(SIGNAL("refresh_currencies_combo()"))
self.is_running = False
def get_json(self, site, get_string, http=False):
try:
if http:
connection = httplib.HTTPConnection(site)
else:
connection = httplib.HTTPSConnection(site)
connection.request("GET", get_string, headers={"User-Agent":"Electrum"})
except Exception:
raise
resp = connection.getresponse()
if resp.reason == httplib.responses[httplib.NOT_FOUND]:
raise
try:
json_resp = json.loads(resp.read())
except Exception:
raise
return json_resp
def exchange(self, btc_amount, quote_currency):
with self.lock:
if self.quote_currencies is None:
return None
quote_currencies = self.quote_currencies.copy()
if quote_currency not in quote_currencies:
return None
return btc_amount * decimal.Decimal(str(quote_currencies[quote_currency]))
def stop(self):
self.is_running = False
def update_rate(self):
self.use_exchange = self.parent.config.get('use_exchange', "MintPal")
update_rates = {
"Cryptsy": self.update_c,
"MintPal": self.update_mp,
"Prelude": self.update_pl,
}
try:
update_rates[self.use_exchange]()
except KeyError:
return
def run(self):
self.is_running = True
while self.is_running:
self.query_rates.clear()
self.update_rate()
self.query_rates.wait(150)
def update_mp(self):
quote_currencies = {"BTC": 0.0}
for cur in quote_currencies:
try:
quote_currencies[cur] = Decimal(self.get_json('api.mintpal.com', "/v1/market/stats/MYR/BTC")[0]['last_price'])
except Exception:
pass
quote_currencies['mBTC'] = quote_currencies['BTC'] * Decimal('1000.0')
quote_currencies['uBTC'] = quote_currencies['mBTC'] * Decimal('1000.0')
quote_currencies['sat'] = quote_currencies['uBTC'] * Decimal('100.0')
with self.lock:
self.quote_currencies = quote_currencies
self.parent.set_currencies(quote_currencies)
def update_pl(self):
quote_currencies = {"BTC": 0.0}
try:
jsonresp = self.get_json('api.prelude.io', "/last/MYR")
except Exception:
return
try:
btcprice = jsonresp["last"]
quote_currencies["BTC"] = decimal.Decimal(str(btcprice))
quote_currencies['mBTC'] = quote_currencies['BTC'] * Decimal('1000.0')
quote_currencies['uBTC'] = quote_currencies['mBTC'] * Decimal('1000.0')
quote_currencies['sat'] = quote_currencies['uBTC'] * Decimal('100.0')
with self.lock:
self.quote_currencies = quote_currencies
except KeyError:
pass
self.parent.set_currencies(quote_currencies)
def update_c(self):
quote_currencies = {"BTC": 0.0}
try:
jsonresp = self.get_json('pubapi.cryptsy.com', "/api.php?method=singlemarketdata&marketid=200", http=True)['return']['markets']['MYR']
except Exception:
return
try:
btcprice = jsonresp['lasttradeprice']
quote_currencies['BTC'] = decimal.Decimal(str(btcprice))
quote_currencies['mBTC'] = quote_currencies['BTC'] * Decimal('1000.0')
quote_currencies['uBTC'] = quote_currencies['mBTC'] * Decimal('1000.0')
quote_currencies['sat'] = quote_currencies['uBTC'] * Decimal('100.0')
with self.lock:
self.quote_currencies = quote_currencies
except KeyError:
pass
self.parent.set_currencies(quote_currencies)
class Plugin(BasePlugin):
def fullname(self):
return "Exchange rates"
def description(self):
return """exchange rates, retrieved from MintPal"""
def __init__(self,a,b):
BasePlugin.__init__(self,a,b)
self.currencies = [self.fiat_unit()]
self.exchanges = [self.config.get('use_exchange', "MintPal")]
self.exchanger = None
@hook
def init_qt(self, gui):
self.gui = gui
self.win = self.gui.main_window
self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
self.btc_rate = Decimal("0.0")
self.resp_hist = {}
self.tx_list = {}
if self.exchanger is None:
# Do price discovery
self.exchanger = Exchanger(self)
self.exchanger.start()
self.gui.exchanger = self.exchanger #
self.add_fiat_edit()
self.win.update_status()
def close(self):
self.exchanger.stop()
self.exchanger = None
self.win.tabs.removeTab(1)
self.win.tabs.insertTab(1, self.win.create_send_tab(), _('Send'))
self.win.update_status()
def set_currencies(self, currency_options):
self.currencies = sorted(currency_options)
self.win.emit(SIGNAL("refresh_currencies()"))
self.win.emit(SIGNAL("refresh_currencies_combo()"))
@hook
def get_fiat_balance_text(self, btc_balance, r):
# return balance as: 1.23 USD
r[0] = self.create_fiat_balance_text(Decimal(btc_balance) / 100000000)
def get_fiat_price_text(self, r):
# return BTC price as: 123.45 USD
r[0] = self.create_fiat_balance_text(1)
quote = r[0]
if quote:
r[0] = "%s"%quote
@hook
def get_fiat_status_text(self, btc_balance, r2):
# return status as: (1.23 USD) 1 BTC~123.45 USD
text = ""
r = {}
self.get_fiat_price_text(r)
quote = r.get(0)
if quote:
price_text = "1 MYR~%s"%quote
fiat_currency = self.fiat_unit()
btc_price = self.btc_rate
fiat_balance = Decimal(btc_price) * (Decimal(btc_balance)/100000000)
balance_text = "(%.2f %s)" % (fiat_balance,fiat_currency)
text = " " + balance_text + " " + price_text + " "
r2[0] = text
def create_fiat_balance_text(self, btc_balance):
quote_currency = self.fiat_unit()
self.exchanger.use_exchange = self.config.get("use_exchange", "MintPal")
cur_rate = self.exchanger.exchange(Decimal("1.0"), quote_currency)
if cur_rate is None:
quote_text = ""
else:
quote_balance = btc_balance * Decimal(cur_rate)
self.btc_rate = cur_rate
quote_text = "%.2f %s" % (quote_balance, quote_currency)
return quote_text
@hook
def request_history_rates(self):
return
@hook
def load_wallet(self, wallet):
self.wallet = wallet
tx_list = {}
for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
tx_hash, conf, is_mine, value, fee, balance, timestamp = item
tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
self.tx_list = tx_list
self.cur_exchange = self.config.get('use_exchange', "BTC-e")
threading.Thread(target=self.request_history_rates, args=()).start()
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'), self.settings_dialog)
def settings_dialog(self):
d = QDialog()
d.setWindowTitle("Settings")
layout = QGridLayout(d)
layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
layout.addWidget(QLabel(_('Currency: ')), 1, 0)
combo = QComboBox()
combo_ex = QComboBox()
ok_button = QPushButton(_("OK"))
def on_change(x):
try:
cur_request = str(self.currencies[x])
except Exception:
return
if cur_request != self.fiat_unit():
self.config.set_key('currency', cur_request, True)
cur_exchange = self.config.get('use_exchange', "MintPal")
self.win.update_status()
try:
self.fiat_button
except:
pass
else:
self.fiat_button.setText(cur_request)
def on_change_ex(x):
cur_request = str(self.exchanges[x])
if cur_request != self.config.get('use_exchange', "MintPal"):
self.config.set_key('use_exchange', cur_request, True)
self.currencies = []
combo.clear()
self.exchanger.query_rates.set()
cur_currency = self.fiat_unit()
set_currencies(combo)
self.win.update_status()
def set_currencies(combo):
try:
combo.blockSignals(True)
current_currency = self.fiat_unit()
combo.clear()
except Exception:
return
combo.addItems(self.currencies)
try:
index = self.currencies.index(current_currency)
except Exception:
index = 0
if len(self.currencies):
on_change(0)
combo.blockSignals(False)
combo.setCurrentIndex(index)
def set_exchanges(combo_ex):
try:
combo_ex.clear()
except Exception:
return
combo_ex.addItems(self.exchanges)
try:
index = self.exchanges.index(self.config.get('use_exchange', "MintPal"))
except Exception:
index = 0
combo_ex.setCurrentIndex(index)
def ok_clicked():
if self.config.get('use_exchange', "BTC-e") in ["CoinDesk", "itBit"]:
self.exchanger.query_rates.set()
d.accept();
set_exchanges(combo_ex)
set_currencies(combo)
combo.currentIndexChanged.connect(on_change)
combo_ex.currentIndexChanged.connect(on_change_ex)
combo.connect(self.win, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
ok_button.clicked.connect(lambda: ok_clicked())
layout.addWidget(combo,1,1)
layout.addWidget(combo_ex,0,1)
layout.addWidget(ok_button,3,1)
if d.exec_():
return True
else:
return False
def fiat_unit(self):
return self.config.get("currency", "BTC")
def add_fiat_edit(self):
self.fiat_e = AmountEdit(self.fiat_unit)
self.btc_e = self.win.amount_e
grid = self.btc_e.parent()
def fiat_changed():
try:
fiat_amount = Decimal(str(self.fiat_e.text()))
except:
self.btc_e.setText("")
return
exchange_rate = self.exchanger.exchange(Decimal("1.0"), self.fiat_unit())
if exchange_rate is not None:
btc_amount = fiat_amount/exchange_rate
self.btc_e.setAmount(int(btc_amount*Decimal(100000000)))
self.fiat_e.textEdited.connect(fiat_changed)
def btc_changed():
btc_amount = self.btc_e.get_amount()
if btc_amount is None:
self.fiat_e.setText("")
return
fiat_amount = self.exchanger.exchange(Decimal(btc_amount)/Decimal(100000000), self.fiat_unit())
if fiat_amount is not None:
self.fiat_e.setText("%.2f"%fiat_amount)
self.btc_e.textEdited.connect(btc_changed)
self.btc_e.frozen.connect(lambda: self.fiat_e.setFrozen(self.btc_e.isReadOnly()))
self.win.send_grid.addWidget(self.fiat_e, 4, 3, Qt.AlignHCenter)
| wozz/electrum-myr | plugins/exchange_rate.py | Python | gpl-3.0 | 13,200 |
/*
* funCKit - functional Circuit Kit
* Copyright (C) 2013 Lukas Elsner <open@mindrunner.de>
* Copyright (C) 2013 Peter Dahlberg <catdog2@tuxzone.org>
* Copyright (C) 2013 Julian Stier <mail@julian-stier.de>
* Copyright (C) 2013 Sebastian Vetter <mail@b4sti.eu>
* Copyright (C) 2013 Thomas Poxrucker <poxrucker_t@web.de>
* Copyright (C) 2013 Alexander Treml <alex.treml@directbox.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.sep2011.funckit.validator;
/**
* Creates a LiveCheckValidator with four checks: TwoInputsConnectedCheck,
* TwoOutputsConnectedCheck, MultipleWiresOnInputCheck and ZeroDelayLoopCheck.
*/
public class LiveCheckValidatorFactory extends AbstractValidatorFactory {
/**
* Creates a new instance of {@link LiveCheckValidatorFactory}.
*/
public LiveCheckValidatorFactory() {
validator.addCheck(new TwoInputsConnectedCheck());
validator.addCheck(new TwoOutputsConnectedCheck());
validator.addCheck(new MultipleWiresOnInputCheck());
validator.addCheck(new ZeroDelayLoopCheck());
}
}
| mindrunner/funCKit | workspace/funCKit/src/main/java/de/sep2011/funckit/validator/LiveCheckValidatorFactory.java | Java | gpl-3.0 | 1,699 |
<?php
/**
* @copyright 2016 Mautic Contributors. All rights reserved.
* @author Mautic
*
* @link http://mautic.org
*
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\DynamicContentBundle\EventListener;
use Mautic\CampaignBundle\Event\CampaignExecutionEvent;
use Mautic\CoreBundle\Event\TokenReplacementEvent;
use Mautic\CoreBundle\EventListener\CommonSubscriber;
use Mautic\CampaignBundle\Event\CampaignBuilderEvent;
use Mautic\CampaignBundle\CampaignEvents;
use Mautic\CoreBundle\Factory\MauticFactory;
use Mautic\DynamicContentBundle\DynamicContentEvents;
use Mautic\DynamicContentBundle\Entity\DynamicContent;
use Mautic\DynamicContentBundle\Model\DynamicContentModel;
use Mautic\LeadBundle\Model\LeadModel;
use Symfony\Component\HttpFoundation\Session\Session;
/**
* Class CampaignSubscriber.
*/
class CampaignSubscriber extends CommonSubscriber
{
/**
* @var LeadModel
*/
protected $leadModel;
/**
* @var DynamicContentModel
*/
protected $dynamicContentModel;
/**
* @var Session
*/
protected $session;
/**
* CampaignSubscriber constructor.
*
* @param MauticFactory $factory
* @param LeadModel $leadModel
* @param DynamicContentModel $dynamicContentModel
*/
public function __construct(MauticFactory $factory, LeadModel $leadModel, DynamicContentModel $dynamicContentModel, Session $session)
{
$this->leadModel = $leadModel;
$this->dynamicContentModel = $dynamicContentModel;
$this->session = $session;
parent::__construct($factory);
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
CampaignEvents::CAMPAIGN_ON_BUILD => ['onCampaignBuild', 0],
DynamicContentEvents::ON_CAMPAIGN_TRIGGER_DECISION => ['onCampaignTriggerDecision', 0],
DynamicContentEvents::ON_CAMPAIGN_TRIGGER_ACTION => ['onCampaignTriggerAction', 0],
];
}
public function onCampaignBuild(CampaignBuilderEvent $event)
{
$event->addAction(
'dwc.push_content',
[
'label' => 'mautic.dynamicContent.campaign.send_dwc',
'description' => 'mautic.dynamicContent.campaign.send_dwc.tooltip',
'eventName' => DynamicContentEvents::ON_CAMPAIGN_TRIGGER_ACTION,
'formType' => 'dwcsend_list',
'formTypeOptions' => ['update_select' => 'campaignevent_properties_dynamicContent'],
'formTheme' => 'MauticDynamicContentBundle:FormTheme\DynamicContentPushList',
'timelineTemplate' => 'MauticDynamicContentBundle:SubscribedEvents\Timeline:index.html.php',
'hideTriggerMode' => true,
'associatedDecisions' => ['dwc.decision'],
'anchorRestrictions' => ['decision.inaction']
]
);
$event->addLeadDecision(
'dwc.decision',
[
'label' => 'mautic.dynamicContent.campaign.decision_dwc',
'description' => 'mautic.dynamicContent.campaign.decision_dwc.tooltip',
'eventName' => DynamicContentEvents::ON_CAMPAIGN_TRIGGER_DECISION,
'formType' => 'dwcdecision_list',
'formTypeOptions' => ['update_select' => 'campaignevent_properties_dynamicContent'],
'formTheme' => 'MauticDynamicContentBundle:FormTheme\DynamicContentDecisionList',
]
);
}
/**
* @param CampaignExecutionEvent $event
*/
public function onCampaignTriggerDecision(CampaignExecutionEvent $event)
{
$eventConfig = $event->getConfig();
$eventDetails = $event->getEventDetails();
$lead = $event->getLead();
if ($eventConfig['dwc_slot_name'] === $eventDetails) {
$defaultDwc = $this->dynamicContentModel->getRepository()->getEntity($eventConfig['dynamicContent']);
if ($defaultDwc instanceof DynamicContent) {
// Set the default content in case none of the actions return data
$this->dynamicContentModel->setSlotContentForLead($defaultDwc, $lead, $eventDetails);
}
$this->session->set('dwc.slot_name.lead.' . $lead->getId(), $eventDetails);
$event->stopPropagation();
return $event->setResult(true);
}
}
/**
* @param CampaignExecutionEvent $event
*/
public function onCampaignTriggerAction(CampaignExecutionEvent $event)
{
$eventConfig = $event->getConfig();
$lead = $event->getLead();
$slot = $this->session->get('dwc.slot_name.lead.'.$lead->getId());
$dwc = $this->dynamicContentModel->getRepository()->getEntity($eventConfig['dynamicContent']);
if ($dwc instanceof DynamicContent) {
// Use translation if available
list($ignore, $dwc) = $this->dynamicContentModel->getTranslatedEntity($dwc, $lead);
if ($slot) {
$this->dynamicContentModel->setSlotContentForLead($dwc, $lead, $slot);
}
$this->dynamicContentModel->createStatEntry($dwc, $lead, $slot);
$tokenEvent = new TokenReplacementEvent($dwc->getContent(), $lead, ['slot' => $slot, 'dynamic_content_id' => $dwc->getId()]);
$this->factory->getDispatcher()->dispatch(DynamicContentEvents::TOKEN_REPLACEMENT, $tokenEvent);
$content = $tokenEvent->getContent();
$event->stopPropagation();
$result = $event->setResult($content);
$event->setChannel('dynamicContent', $dwc->getId());
return $result;
}
}
}
| mqueme/mautic | app/bundles/DynamicContentBundle/EventListener/CampaignSubscriber.php | PHP | gpl-3.0 | 5,887 |
export * from './output-settings';
| stream-labs/streamlabs-obs | app/services/settings/output/index.ts | TypeScript | gpl-3.0 | 35 |
package LiVEZer.Medicine.WebApp;
public final class Globals
{
public static final String MenuId = "menuItem";
public static final String Method = "method";
public static final String Data = "data";
public final class Session
{
public static final String Opened = "SESSION_OPENED";
}
public final class Models
{
public final class LogInModel
{
public static final String Login = "login";
public static final String Password = "passw";
}
}
public final class Tables
{
public final class AP_USERS
{
public static final String TableName = "AP_USERS";
public static final String AP_USER_ID = "AP_USER_ID";
public static final String AP_USER_LOGIN = "AP_USER_LOGIN";
public static final String AP_USER_PASSW = "AP_USER_PASSW";
public static final String AP_USER_PERSON = "AP_USER_PERSON";
public static final String AP_USER_ROLE = "AP_USER_ROLE";
public static final String AP_USER_ACTV = "AP_USER_ACTV";
public static final String AP_USER_WEMAIL = "AP_USER_WEMAIL";
}
}
}
| VLisnevskiy/LiVEZer.Medicine | src/LiVEZer/Medicine/WebApp/Globals.java | Java | gpl-3.0 | 1,256 |
package dk.kiljacken.aestuscraft.library.nbt.handlers;
import dk.kiljacken.aestuscraft.library.nbt.INBTHandler;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
public class ItemStackNBTHandler implements INBTHandler {
@SuppressWarnings("unchecked")
@Override
public <T> T readFromTag(NBTBase tag)
{
if (tag instanceof NBTTagCompound)
{
return (T) ItemStack.loadItemStackFromNBT((NBTTagCompound) tag);
}
else if (tag instanceof NBTTagList)
{
NBTTagList tagList = (NBTTagList) tag;
NBTTagCompound identTag = (NBTTagCompound) tagList.tagAt(0);
ItemStack[] inventoryStacks = new ItemStack[identTag.getByte("invSize")];
for (int i = 1; i < tagList.tagCount(); i++)
{
NBTTagCompound itemStackTag = (NBTTagCompound) tagList.tagAt(i);
byte slot = itemStackTag.getByte("slot");
if (slot >= 0 && slot < inventoryStacks.length)
{
inventoryStacks[slot] = ItemStack.loadItemStackFromNBT(itemStackTag);
}
}
return (T) inventoryStacks;
}
return null;
}
@Override
public NBTBase writeToTag(String name, Object value)
{
if (value instanceof ItemStack)
{
ItemStack itemStack = (ItemStack) value;
NBTTagCompound tag = new NBTTagCompound(name);
itemStack.writeToNBT(tag);
return tag;
}
else if (value instanceof ItemStack[])
{
ItemStack[] inventory = (ItemStack[]) value;
NBTTagList inventoryTag = new NBTTagList(name);
NBTTagCompound identTag = new NBTTagCompound();
identTag.setByte("invSize", (byte) inventory.length);
inventoryTag.appendTag(identTag);
for (int i = 0; i < inventory.length; i++)
{
if (inventory[i] != null)
{
NBTTagCompound itemStackTag = new NBTTagCompound();
itemStackTag.setByte("slot", (byte) i);
inventory[i].writeToNBT(itemStackTag);
inventoryTag.appendTag(itemStackTag);
}
}
return inventoryTag;
}
return null;
}
}
| kiljacken/AestusCraft | aestuscraft_common/dk/kiljacken/aestuscraft/library/nbt/handlers/ItemStackNBTHandler.java | Java | gpl-3.0 | 2,469 |
<?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de https://trad.spip.net/tradlang_module/urls?lang_cible=pt
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// A
'actualiser_toutes' => 'Actualizar todos os URLs',
'actualiser_toutes_explication' => 'Pode re-calcular os URLs.
Se um URL mudou, uma nova entrada será criada (sem perder os URLs já presentes e sem os URLs definidos manualmente).', # MODIF
// B
'bouton_supprimer_url' => 'Eliminar este URL',
// E
'erreur_arbo_2_segments_max' => 'Não pode usar mais de dois segmentos URL para um objecto.',
'erreur_config_url_forcee' => 'A configuração dos URLs está fixada no ficheiro <tt>mes_options.php</tt>.',
'explication_editer' => 'A gestão avançada de URLs permite editar o URL das páginas de cada objecto editorial, e gerir o histórico da sua evolução.',
// I
'icone_configurer_urls' => 'Configurar os URLs',
'icone_controler_urls' => 'URLs significativos',
'info_1_url' => '1 URL',
'info_id_parent' => '#parent',
'info_nb_urls' => '@nb@ URLs',
'info_objet' => 'Objecto',
// L
'label_tri_date' => 'Data',
'label_tri_id' => 'ID',
'label_tri_url' => 'URL',
'label_url' => 'Novo URL',
'label_url_minuscules_0' => 'Conservar maiúsculas/minúsculas do título',
'label_url_minuscules_1' => 'Forçar os urls em minúsculas',
'label_url_permanente' => 'Bloquear este URL (sem actualizações após a modificação do objecto)',
'label_url_sep_id' => 'Caracter para separar o número adicionado em caso de duplicado',
'label_urls_activer_controle_oui' => 'Activar a gestão avançada de URLs',
'label_urls_nb_max_car' => 'Número máximo de caracteres',
'label_urls_nb_min_car' => 'Número mínimo de caracteres',
'liberer_url' => 'Lançar',
'liste_des_urls' => 'Todos os URLs',
// T
'texte_type_urls' => 'Pode escolher como os URLs das páginas serão calculados.',
'texte_type_urls_attention' => 'Atenção: esta opção apenas funcionará se o ficheiro @htaccess@ estiver correctamente instalado no directório raiz do seu sítio.',
'texte_urls_nb_max_car' => 'Se o título é mais longo, será cortado.',
'texte_urls_nb_min_car' => 'Se o título for demasiado curto, o número de identificação será utilizado.',
'titre_gestion_des_urls' => 'Gestão dos URLs',
'titre_type_arbo' => 'URLs Arborescentes',
'titre_type_html' => 'URLs Objectos HTML',
'titre_type_libres' => 'URLs Livres',
'titre_type_page' => 'Página URLs ',
'titre_type_propres' => 'URLs Limpos',
'titre_type_propres2' => 'URLs Limpos+<tt>.html</tt>',
'titre_type_propres_qs' => 'URLs Limpos em query-string',
'titre_type_simple' => 'URLs Simples',
'titre_type_standard' => 'URLs Históricos',
'titre_type_urls' => 'Tipo de endereços URL',
'tout_voir' => 'Ver todos os URLs',
// U
'url_ajout_impossible' => 'Ocorreu um erro. Este URL não pôde ser guardado.',
'url_ajoutee' => 'O URL foi adicionado',
// V
'verifier_url_nettoyee' => 'O URL foi corrigido. Pode verificar antes de guardar.',
'verrouiller_url' => 'Bloquear'
);
?>
| phenix-factory/p.henix.be | plugins-dist/urls_etendues/lang/urls_pt.php | PHP | gpl-3.0 | 3,159 |
"use strict";
const ConnectionState = Object.freeze({
Disconnected: "disconnected",
Connected: "connected",
Reconnecting: "reconnecting",
Connecting: "connecting"
});
exports.ConnectionState = ConnectionState; | Firebottle/Firebot | shared/connection-constants.js | JavaScript | gpl-3.0 | 227 |
// Copyright (c) Clickberry, Inc. All rights reserved.
// Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. See License.txt in the project root for license information.
using Portal.BackEnd.Encoder.Interface;
using Portal.BackEnd.Encoder.Pipeline.Data;
using Portal.BackEnd.Encoder.Status;
using Portal.Domain.BackendContext.Enum;
using Wrappers;
namespace Portal.BackEnd.Encoder.Pipeline.Step
{
public class EncodeStep : PipelineStep<CreatorStepData>
{
private readonly IFfmpeg _ffmpeg;
private readonly IWatchDogTimer _watchDogTimer;
public EncodeStep(IStepMediator mediator, IEncodeWebClient webClient, IFfmpeg ffmpeg, IWatchDogTimer watchDogTimer) :
base(mediator, webClient)
{
Mediator.AddEncodeStep(this);
_ffmpeg = ffmpeg;
_watchDogTimer = watchDogTimer;
}
public override void Execute(CancellationTokenSourceWrapper tokenSource)
{
string contentType = StepData.EncodeStringBuilder.GetContentType();
string arguments = StepData.EncodeStringBuilder.GetFfmpegArguments();
RegisterProcessCallback();
EncoderStatus encoderStatus = StartFfmpeg(tokenSource, arguments);
EncodeStepData nextStepData = CreateStepData(encoderStatus, contentType);
SetStatus();
Mediator.Send(nextStepData, this);
}
private void SetStatus()
{
if (!_watchDogTimer.IsOverflowing)
{
WebClient.SetStatus(100);
}
}
private EncoderStatus StartFfmpeg(CancellationTokenSourceWrapper tokenSource, string arguments)
{
_watchDogTimer.Start(tokenSource);
EncoderStatus encoderStatus = _ffmpeg.Start(arguments, tokenSource, StepData.DataReceivedHandler.ProcessData).Result;
_watchDogTimer.Stop();
return encoderStatus;
}
private void RegisterProcessCallback()
{
StepData.DataReceivedHandler.Register(_watchDogTimer.Reset);
StepData.DataReceivedHandler.Register(WebClient.SetStatus);
}
private EncodeStepData CreateStepData(EncoderStatus encoderStatus, string contentType)
{
if (_watchDogTimer.IsOverflowing)
{
return new EncodeStepData
{
EncoderState = EncoderState.Hanging,
ErrorMessage = "Ffmpeg is Hanging"
};
}
return new EncodeStepData
{
EncoderState = encoderStatus.EncoderState,
ErrorMessage = encoderStatus.ErrorMessage,
ContentType = contentType
};
}
}
} | clickberry/video-portal | Source/BackEnd/Portal.BackEnd.Encoder/Pipeline/Step/EncodeStep.cs | C# | gpl-3.0 | 2,787 |
/*
* Copyright 2012 Loong H
*
* Qingzhou is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Qingzhou is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.loongsoft.qingzhou;
public class MetaData {
public final static String PREFS_NAME = "Qingzhou";
public final static String USER_NAME = "Name";
public final static String PROMISE_TIME = "PromiseTime";
public final static String FIRST_RUN = "FirstRun";
public final static String LAST_DATE = "LastDate";
public final static String USE_PASSWORD = "UsePassword";
public final static String PASSWORD = "Password";
public final static String REMIND_HOUR = "RemindHour";
public final static String REMIND_MINUTE = "RemindMinute";
public static final long A_DAY_LONG_IN_MILL = 86400000;
public static Boolean isFirstRun = false;
public static Long promiseTime=System.currentTimeMillis();
public static String userName="";
public static Long lastDate=System.currentTimeMillis();
public static Boolean usePassword = false;
public static String password="";
public static int remindHour = 22;
public static int remindMinute = 30;
public static Long magicTimer;
public final static boolean DEBUG_TEST = false;
public final static boolean DEBUG_MAKE_FAKE_DATA = false;
public final static String VERSION = "V1.0@2012.11";
}
| godghost/qingzhou | src/com/loongsoft/qingzhou/MetaData.java | Java | gpl-3.0 | 1,848 |
<?php
class Database
{
private static $instance = NULL;
private $pdo;
//private $query;
private function __construct()
{
try{
$this->pdo = new PDO('mysql:host=localhost;dbname=hdi', 'root', '');
}
catch(exception $e)
{
die ( 'DATABASE: Connection Failed! ' . $e->getMessage() );
}
}
public static function obj()
{
if (self::$instance == NULL)
{
self::$instance = new Database();
}
return self::$instance;
}
/**
* Database::execute_query()
*
* This method executes all types of SQL transactions
* If it is a SELECT statement, always set the return $format
*
* @param mixed $query
* @param mixed $format
* @param mixed $bind_array
* @return
*/
public function execute_query($query,$format='',$bind_array=array())
{
// Init.
$result = false;
try
{
// Prepare Statement
$prep_stmt = $this->pdo->prepare($query);
// Bind
if (!empty($bind_array))
{
$this->bind_array($prep_stmt, $bind_array);
}
// Execute
$exec_msg = $prep_stmt->execute();
// If it is a SELECT statement, return an array or an object
if ($format != '')
{
if (($format == 'A') || ($format == 'Array'))
{
//return $this->obj2arr($result);
$result = $prep_stmt->fetchAll(PDO::FETCH_ASSOC);
//print_r($result);
return $result;
}
else if (($format == 'O') || ($format == 'Object'))
{
//return $result;
$result = $prep_stmt->fetchAll(PDO::FETCH_OBJ);
//print_r($result);
return $result;
}
}
// If it is not a SELECT statement, return the transaction status
else
{
return $exec_msg;
}
}
catch(exception $e)
{
die ('DATABASE: Query Execution Failed! ' . $e->getMessage());
}
}
private function bind_array(&$prep_stmt, &$bind_array)
{
foreach ($bind_array as $k=>$v)
{
@$prep_stmt->bindParam($k, $v[0], $v[1]);
}
}
public function begin_transaction()
{
return $this->pdo->beginTransaction();
}
public function commit_transaction()
{
return $this->pdo->commit();
}
public function roll_back()
{
return $this->pdo->rollBack();
}
public function last_insert_id()
{
return $this->pdo->lastInsertId();
}
public function get_error_info()
{
return $this->pdo->errorCode();
}
public function get_query()
{
//return $this->query;
}
} ?> | hdilink/hdi | calls/classes/Database.php | PHP | gpl-3.0 | 3,000 |
/*
fs.hpp
Author : BAKFR
File under GNU GPL v3.0
*/
#pragma once
#include <string>
namespace Utils {
namespace Fs {
/**
* Make a new directory (if it does not exist yet).
*
* @param path file path in the UNIX format
* @return `true` if the directory exists; `false` in case of error. On windows, always returns true.
*/
bool mkdir(const std::string &path);
} // namespace Fs
} // namespace Utils
| jlppc/OpMon | src/utils/fs.hpp | C++ | gpl-3.0 | 449 |
# Copyright (c) 2019 SUSE Linux GmbH. All rights reserved.
#
# This file is part of kiwi.
#
# kiwi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# kiwi 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 kiwi. If not, see <http://www.gnu.org/licenses/>
#
import os
import random
from textwrap import dedent
from typing import List
# project
from kiwi.storage.subformat.template.virtualbox_ovf import (
VirtualboxOvfTemplate
)
from kiwi.storage.subformat.vagrant_base import DiskFormatVagrantBase
from kiwi.storage.subformat.vmdk import DiskFormatVmdk
from kiwi.command import Command
class DiskFormatVagrantVirtualBox(DiskFormatVagrantBase):
"""
**Create a vagrant box for the virtualbox provider**
"""
def vagrant_post_init(self) -> None:
self.provider = 'virtualbox'
self.image_format = 'vagrant.virtualbox.box'
def get_additional_vagrant_config_settings(self) -> str:
"""
Configure the default shared folder to use rsync when guest additions
are not present inside the box.
:return:
ruby code to be evaluated as string
:rtype: str
"""
extra_settings = dedent('''
config.vm.base_mac = "{mac_address}"
''').strip().format(mac_address=self._random_mac())
if not self.xml_state.get_vagrant_config_virtualbox_guest_additions():
extra_settings += os.linesep + dedent('''
config.vm.synced_folder ".", "/vagrant", type: "rsync"
''').strip()
return extra_settings
def create_box_img(self, temp_image_dir: str) -> List[str]:
"""
Create the vmdk image for the Virtualbox vagrant provider.
This function creates the vmdk disk image and the ovf file.
The latter is created via the class :class:`VirtualboxOvfTemplate`.
:param str temp_image_dir:
Path to the temporary directory used to build the box image
:return:
A list of files relevant for the virtualbox box to be
included in the vagrant box
:rtype: list
"""
vmdk = DiskFormatVmdk(self.xml_state, self.root_dir, self.target_dir)
vmdk.create_image_format()
box_img = os.sep.join([temp_image_dir, 'box.vmdk'])
Command.run(
[
'mv', self.get_target_file_path_for_format(vmdk.image_format),
box_img
]
)
box_ovf = os.sep.join([temp_image_dir, 'box.ovf'])
ovf_template = VirtualboxOvfTemplate()
disk_image_capacity = self.vagrantconfig.get_virtualsize() or 42
xml_description_specification = self.xml_state \
.get_description_section().specification
with open(box_ovf, "w") as ovf_file:
ovf_file.write(
ovf_template.get_template().substitute(
{
'root_uuid': self.xml_state.get_root_filesystem_uuid(),
'vm_name': self.xml_state.xml_data.name,
'disk_image_capacity': disk_image_capacity,
'vm_description': xml_description_specification
}
)
)
return [box_img, box_ovf]
@staticmethod
def _random_mac():
return '%02x%02x%02x%02x%02x%02x'.upper() % (
0x00, 0x16, 0x3e,
random.randrange(0, 0x7e),
random.randrange(0, 0xff),
random.randrange(0, 0xff)
)
| dirkmueller/kiwi | kiwi/storage/subformat/vagrant_virtualbox.py | Python | gpl-3.0 | 3,951 |
// SoftSetServerDlg.cpp : ʵÏÖÎļþ
//
#include "stdafx.h"
#include "PMApp.h"
#include "MyHelp.h"
#include "SoftInfo.h"
#include "SoftSetServerDlg.h"
// CSoftSetServerDlg ¶Ô»°¿ò
using namespace SoftInfo;
IMPLEMENT_DYNAMIC(CSoftSetServerDlg, CDialog)
CSoftSetServerDlg::CSoftSetServerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CSoftSetServerDlg::IDD, pParent)
, m_uiDataFreshTime(0)
{
}
CSoftSetServerDlg::~CSoftSetServerDlg()
{
}
void CSoftSetServerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_uiDataFreshTime);
}
BEGIN_MESSAGE_MAP(CSoftSetServerDlg, CDialog)
ON_WM_HELPINFO()
END_MESSAGE_MAP()
// CSoftSetServerDlg ÏûÏ¢´¦Àí³ÌÐò
BOOL CSoftSetServerDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CSoftInfo* csi = &SoftInfo::CSoftInfo::GetMe();
m_uiDataFreshTime = csi->getFreshDataTime();
UpdateData(FALSE);
return TRUE;
}
BOOL CSoftSetServerDlg::DestroyWindow()
{
UpdateData(TRUE);
if(m_uiDataFreshTime < 50) m_uiDataFreshTime = 50;
if(m_uiDataFreshTime > 3600000) m_uiDataFreshTime = 3600000;
UpdateData(FALSE);
CSoftInfo* csi = &SoftInfo::CSoftInfo::GetMe();
csi->SetFreshDataTime(m_uiDataFreshTime);
return CDialog::DestroyWindow();
}
void CSoftSetServerDlg::OnOK()
{
CWnd* pWnd = GetParent();
if(!pWnd) return;
pWnd->PostMessage(MESSAGE_OK, 0, 0);
}
BOOL SoftInfo::CSoftSetServerDlg::OnHelpInfo(HELPINFO* pHelpInfo)
{
SoftInfo::CMyHelp::GetMe().ShowHelp(_T("±äÁ¿¼à¿ØÅäÖÃ"));
return CDialog::OnHelpInfo(pHelpInfo);
}
| atlaser/Tools | PMEditor/main/PM/SoftSetServerDlg.cpp | C++ | gpl-3.0 | 1,518 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RDI.NFe2.ORMAP.MySQL")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RDI.NFe2.ORMAP.MySQL")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("deb6cf8c-066d-4639-a0ec-b6f788e8819b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.3.1.0")]
[assembly: AssemblyFileVersion("2.3.1.0")]
| rodrigordi/opennfe | Open NFe 3/RDI.NFe2.ORMAP.MySQL/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,416 |
# -*- coding: utf-8 -*-
#
# SpamFighter, Copyright 2008, 2009 NetStream LLC (http://netstream.ru/, we@netstream.ru)
#
# This file is part of SpamFighter.
#
# SpamFighter is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SpamFighter 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 SpamFighter. If not, see <http://www.gnu.org/licenses/>.
#
"""
Диспетчеризация команд по имени.
Т.е. отображаем имя команды (атрибут comandName из интерфейса L{spamfighter.core.commands.ICommand}) в
класс команды.
"""
from spamfighter.utils.registrator import registrator
from spamfighter.core.commands import errors
dispatch_map = {}
"""
Карта отображения команд, имеет вид: имя_команды -> класс_команды.
"""
@registrator
def install(command_class):
"""Вариант функции L{installCommand} которую можно использовать в определении класса
Пример использования::
from spamfighter.core.commands import install, Command
class MyCommand(Command):
install()
"""
installCommand(command_class)
def installCommand(command_class):
"""Установить новую команду в карту диспетчеризации.
@param command_class: класс, производный от L{Command}
"""
name = command_class.commandName
assert name not in dispatch_map
dispatch_map[name] = command_class
def deinstallCommand(command_class):
"""
Убрать команду из карты диспетчеризации.
@param command_class: класс, производный от L{Command}
"""
name = command_class.commandName
assert name in dispatch_map
del dispatch_map[name]
def dispatchCommand(commandName):
"""
Найти класс команды, соответствующий данной команде по имени
@param commandName: имя команды
@type commandName: C{str}
@raise errors.CommandUnknownException: если такой команды не существует
@rtype: производная от L{Command}
"""
if commandName not in dispatch_map:
raise errors.CommandUnknownException, commandName
return dispatch_map[commandName]()
def listAllCommands():
"""
Вернуть список всех команд.
"""
return dispatch_map.keys()
| smira/spamfighter | spamfighter/core/commands/dispatcher.py | Python | gpl-3.0 | 2,984 |
<?php
require_once(dirname(__DIR__)) . "/php/class/autoload.php";
require_once("/etc/apache2/capstone-mysql/encrypted-config.php");
if(session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
$PAGE_TITLE = "My Account - Cheqout";
$pdo = connectToEncryptedMySQL("/etc/apache2/capstone-mysql/cheqout.ini");
if(@isset($_SESSION["email"])) {
$email = $_SESSION["email"];
$_SESSION["emailAddress"] = $email->getEmailAddress();
}
if(@isset($_SESSION["account"])) {
$account = $_SESSION["account"];
}
require_once("../stripe-php-2.2.0/init.php");
require_once("../lib/utilities.php");
$config = readConfig("/etc/apache2/capstone-mysql/cheqout.ini");
if(@isset($_SESSION["emailAddress"]) === false) {
return;
}
if(@isset($_SESSION["cart"]) === true) {
$testKey = $config['publishable_key'];
$logo = '../img/logo.png'; // taken from first product on the order
$tagline = 'Cheq out our booqs!'; //taken from the first product's description
$orderTotal = $_SESSION["total"]; // taken from the order total in productOrder
echo '<form action="../checkout/charge.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="' . $testKey . '"
data-email="' . $_SESSION['emailAddress'] . '"
data-image="' . $logo . '"
data-name="Cheqout"
data-description="' . $tagline . '"
data-zip-code="true"
data-amount="' . $orderTotal . '">
</script>
</form>';
}
| jameswlhill/cheqout | checkout/index.php | PHP | gpl-3.0 | 1,438 |
/*
* nutrition_server_application.cpp
* Part of nutritiond
*
* Created on: Jul 20, 2010
* Author: Tyler McHenry <tyler@nerdland.net>
*/
#include "nutrition_server_application.h"
#include "libnutrition/backend/mysql/mysql_back_end.h"
#include <QtSql/QSqlDatabase>
#include <QDebug>
#include <stdexcept>
NutritionServerApplication::NutritionServerApplication(int &c, char **v)
: QCoreApplication(c, v)
{
tcpServer = new QTcpServer(this);
// TODO: Configurable
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "nutrition_db");
db.setHostName("localhost");
db.setUserName("root");
db.setPassword("testpassword");
db.setDatabaseName("nutrition");
if (!db.open()) {
delete tcpServer;
throw std::runtime_error("Could not connect to database");
}
BackEnd::setBackEnd(QSharedPointer<MySQLBackEnd>(new MySQLBackEnd("nutrition_db")));
if (!tcpServer->listen(QHostAddress::Any, 2133)) {
qDebug() << "Server failed to start.";
} else {
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(acceptNewConnection()));
}
}
NutritionServerApplication::~NutritionServerApplication()
{
}
void NutritionServerApplication::acceptNewConnection()
{
QSharedPointer<ClientConnection> connection
(new ClientConnection(tcpServer->nextPendingConnection(), this));
connections.insert(connection->getSocketDescriptor(), connection);
}
| tylermchenry/nutrition_tracker | service/src/nutrition_server_application.cpp | C++ | gpl-3.0 | 1,383 |
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Login extends Controller_CL4_Login { } | claerosystems/cl4-jquery-mobile | classes/Controller/Login.php | PHP | gpl-3.0 | 117 |
using Android.Util;
using AsNum.XFControls;
using AsNum.XFControls.Droid;
using System.ComponentModel;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(TimePickerEx), typeof(TimePickerExRender))]
namespace AsNum.XFControls.Droid {
public class TimePickerExRender : TimePickerRenderer {
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.TimePicker> e) {
base.OnElementChanged(e);
this.UpdateTextColor();
this.UpdatePlaceHolder();
this.UpdateFont();
this.UpdateAlignment();
//this.Control.SetPadding(0, 20, 0, 20);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) {
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName.Equals(TimePickerEx.TextColorProperty.PropertyName)) {
this.UpdateTextColor();
}
else if (e.PropertyName.Equals(TimePickerEx.FontSizeProperty)) {
this.UpdateFont();
}
else if (e.PropertyName.Equals(TimePickerEx.HorizontalTextAlignmentProperty)) {
this.UpdateAlignment();
}
}
private void UpdateTextColor() {
var ele = (TimePickerEx)this.Element;
this.Control.SetTextColor(ele.TextColor.ToAndroid());
}
private void UpdatePlaceHolder() {
var ele = (TimePickerEx)this.Element;
this.Control.Hint = ele.PlaceHolder ?? "";
this.Control.SetHintTextColor(ele.PlaceHolderColor.ToAndroid());
}
private void UpdateFont() {
this.Control.SetTextSize(ComplexUnitType.Sp, (float)((TimePickerEx)this.Element).FontSize);
}
private void UpdateAlignment() {
this.Control.Gravity =
((TimePickerEx)this.Element).HorizontalTextAlignment.ToHorizontalGravityFlags();
}
}
} | gruan01/XFControls | XFControls/Src/AsNum.Control.Droid/TimePickerExRender.cs | C# | gpl-3.0 | 2,009 |
package SnippingTool;
public enum STNotificationTitle
{
NONE, TITLE_0, TITLE_1, TITLE_2, TITLE_3
}
| DJVUpp/Desktop | djuvpp-djvureader-_linux-f9cd57d25c2f/DjVuReader++/src/SnippingTool/STNotificationTitle.java | Java | gpl-3.0 | 104 |
package org.cloud.backend.system.dao.sys.service.imp;
import org.cloud.backend.system.comm.base.BaseServiceImpl;
import org.cloud.backend.system.dao.sys.mapper.SysUserOrganizationMapper;
import org.cloud.backend.system.dao.sys.model.SysUserOrganization;
import org.cloud.backend.system.dao.sys.model.SysUserOrganizationExample;
import org.cloud.backend.system.dao.sys.service.SysUserOrganizationService;
import org.cloud.core.annotation.MyBatisService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* SysUserOrganizationService实现
*/
@Service
@Transactional
@MyBatisService
public class SysUserOrganizationServiceImpl extends BaseServiceImpl<SysUserOrganizationMapper, SysUserOrganization, SysUserOrganizationExample> implements SysUserOrganizationService {
private static Logger _log = LoggerFactory.getLogger(SysUserOrganizationServiceImpl.class);
@Autowired
SysUserOrganizationMapper sysUserOrganizationMapper;
@Override
public int organization(String[] organizationIds, int id) {
int result = 0;
// 删除旧记录
SysUserOrganizationExample sysUserOrganizationExample = new SysUserOrganizationExample();
sysUserOrganizationExample.createCriteria()
.andUserIdEqualTo(id);
sysUserOrganizationMapper.deleteByExample(sysUserOrganizationExample);
// 增加新记录
if (null != organizationIds) {
for (String organizationId : organizationIds) {
if (StringUtils.isBlank(organizationId)) {
continue;
}
SysUserOrganization SysUserOrganization = new SysUserOrganization();
SysUserOrganization.setUserId(id);
SysUserOrganization.setOrganizationId(NumberUtils.toInt(organizationId));
result = sysUserOrganizationMapper.insertSelective(SysUserOrganization);
}
}
return result;
}
} | rock007/cloud-starter | cloud-backend-system/src/main/java/org/cloud/backend/system/dao/sys/service/imp/SysUserOrganizationServiceImpl.java | Java | gpl-3.0 | 2,219 |
// Copyright (c) François Paradis
// This file is part of Mox, a card game simulator.
//
// Mox is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Mox 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 Mox. If not, see <http://www.gnu.org/licenses/>.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Mox.Engine.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2d5f1768-2185-4c1f-a53e-04ae93824e58")]
| fparadis2/mox | Source/Mox.Engine/Tests/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,454 |
/*******************************************************************************************************************************
* AK.Login.Application.ILoginRequestParser
* Copyright © 2014 Aashish Koirala <http://aashishkoirala.github.io>
*
* This file is part of AK-Login.
*
* AK-Login is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AK-Login 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 AK-Login. If not, see <http://www.gnu.org/licenses/>.
*
*******************************************************************************************************************************/
using System.Web;
namespace AK.Login.Application
{
/// <summary>
/// Parses the given login request.
/// </summary>
/// <author>Aashish Koirala</author>
public interface ILoginRequestParser
{
/// <summary>
/// Parses the given request for the given stage.
/// </summary>
/// <param name="request">HTTP request.</param>
/// <param name="stage">Login stage.</param>
/// <returns>Information about the request.</returns>
LoginRequestInfo Parse(HttpRequestBase request, LoginStage stage);
}
} | aashishkoirala/login | src/AK.Login.Application/ILoginRequestParser.cs | C# | gpl-3.0 | 1,631 |
/**
* Cloud9 Language Foundation
*
* @copyright 2011, Ajax.org B.V.
* @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
*/
define(function(require, exports, module) {
var Range = require("ace/range").Range;
var Anchor = require('ace/anchor').Anchor;
var tooltip = require('ext/language/tooltip');
var Editors = require("ext/editors/editors");
module.exports = {
disabledMarkerTypes: {},
hook: function(ext, worker) {
var _self = this;
this.ext = ext;
worker.on("markers", function(event) {
if(ext.disabled) return;
_self.addMarkers(event, ext.editor);
});
worker.on("hint", function(event) {
_self.onHint(event);
});
},
onHint: function(event) {
var message = event.data.message;
var pos = event.data.pos;
var cursorPos = ceEditor.$editor.getCursorPosition();
if(cursorPos.column === pos.column && cursorPos.row === pos.row && message)
tooltip.show(cursorPos.row, cursorPos.column, message);
else
tooltip.hide();
},
removeMarkers: function(session) {
var markers = session.getMarkers(false);
for (var id in markers) {
// All language analysis' markers are prefixed with language_highlight
if (markers[id].clazz.indexOf('language_highlight_') === 0) {
session.removeMarker(id);
}
}
for (var i = 0; i < session.markerAnchors.length; i++) {
session.markerAnchors[i].detach();
}
session.markerAnchors = [];
},
addMarkers: function(event, editor) {
var _self = this;
var annos = event.data;
var mySession = editor.session;
if (!mySession.markerAnchors) mySession.markerAnchors = [];
this.removeMarkers(editor.session);
mySession.languageAnnos = [];
annos.forEach(function(anno) {
// Certain annotations can temporarily be disabled
if (_self.disabledMarkerTypes[anno.type])
return;
// Multi-line markers are not supported, and typically are a result from a bad error recover, ignore
if(anno.pos.el && anno.pos.sl !== anno.pos.el)
return;
// Using anchors here, to automaticaly move markers as text around the marker is updated
var anchor = new Anchor(mySession.getDocument(), anno.pos.sl, anno.pos.sc || 0);
mySession.markerAnchors.push(anchor);
var markerId;
var colDiff = anno.pos.ec - anno.pos.sc;
var rowDiff = anno.pos.el - anno.pos.sl;
var gutterAnno = {
guttertext: anno.message,
type: anno.level || "warning",
text: anno.message
// row will be filled in updateFloat()
};
function updateFloat(single) {
if (markerId)
mySession.removeMarker(markerId);
gutterAnno.row = anchor.row;
if (anno.pos.sc !== undefined && anno.pos.ec !== undefined) {
var range = Range.fromPoints(anchor.getPosition(), {
row: anchor.row + rowDiff,
column: anchor.column + colDiff
});
markerId = mySession.addMarker(range, "language_highlight_" + (anno.type ? anno.type : "default"));
}
if (single) mySession.setAnnotations(mySession.languageAnnos);
}
updateFloat();
anchor.on("change", function() {
updateFloat(true);
});
if (anno.message) mySession.languageAnnos.push(gutterAnno);
});
mySession.setAnnotations(mySession.languageAnnos);
},
/**
* Temporarily disable certain types of markers (e.g. when refactoring)
*/
disableMarkerType: function(type) {
this.disabledMarkerTypes[type] = true;
var session = Editors.currentEditor.amlEditor.$editor.session;
var markers = session.getMarkers(false);
for (var id in markers) {
// All language analysis' markers are prefixed with language_highlight
if (markers[id].clazz === 'language_highlight_' + type)
session.removeMarker(id);
}
},
enableMarkerType: function(type) {
this.disabledMarkerTypes[type] = false;
},
/**
* Called when text in editor is updated
* This attempts to predict how the worker is going to adapt markers based on the given edit
* it does so instanteously, rather than with a 500ms delay, thereby avoid ugly box bouncing etc.
*/
onChange: function(session, event) {
if(this.ext.disabled) return;
var range = event.data.range;
var isInserting = event.data.action.substring(0, 6) !== "remove";
var text = event.data.text;
var adaptingId = text && text.search(/[^a-zA-Z0-9\$_]/) === -1;
if (!isInserting) { // Removing some text
var markers = session.getMarkers(false);
// Run through markers
var foundOne = false;
for (var id in markers) {
var marker = markers[id];
if (marker.clazz.indexOf('language_highlight_') === 0) {
if (range.contains(marker.range.start.row, marker.range.start.column)) {
session.removeMarker(id);
foundOne = true;
}
else if (adaptingId && marker.range.contains(range.start.row, range.start.column)) {
foundOne = true;
var deltaLength = text.length;
marker.range.end.column -= deltaLength;
}
}
}
if (!foundOne) {
// Didn't find any markers, therefore there will not be any anchors or annotations either
return;
}
// Run through anchors
for (var i = 0; i < session.markerAnchors.length; i++) {
var anchor = session.markerAnchors[i];
if (range.contains(anchor.row, anchor.column)) {
anchor.detach();
}
}
// Run through annotations
for (var i = 0; i < session.languageAnnos.length; i++) {
var anno = session.languageAnnos[i];
if (range.contains(anno.row, 1)) {
session.languageAnnos.splice(i, 1);
i--;
}
}
session.setAnnotations(session.languageAnnos);
}
else { // Inserting some text
var markers = session.getMarkers(false);
// Only if inserting an identifier
if (!adaptingId) return;
// Run through markers
var foundOne = false;
for (var id in markers) {
var marker = markers[id];
if (marker.clazz.indexOf('language_highlight_') === 0) {
if (marker.range.contains(range.start.row, range.start.column)) {
foundOne = true;
var deltaLength = text.length;
marker.range.end.column += deltaLength;
}
}
}
}
if (foundOne)
session._dispatchEvent("changeBackMarker");
},
destroy : function(){
}
};
}); | Phara0h/cloud9 | plugins-client/ext.language/marker.js | JavaScript | gpl-3.0 | 7,580 |
package com.dmillerw.wac.item;
import java.util.List;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
import com.dmillerw.wac.WACMain;
import com.dmillerw.wac.lib.ModInfo;
public class ItemWireSpool extends Item {
private Icon[] textures;
private static String[] itemSubNames = new String[] {"emptySpool", "wireSpool"};
public static String[] itemNames = new String[] {"Empty Spool", "Wire Spool"};
public ItemWireSpool(int id) {
super(id);
setMaxStackSize(1);
setMaxDamage(0);
setHasSubtypes(true);
setCreativeTab(WACMain.wacCreativeTabItems);
}
@Override
public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float f1, float f2, float f3) {
if (world.isRemote) return false;
if (stack.getItemDamage() != 1) return false;
return true;
}
@Override
public Icon getIconFromDamage(int damage) {
return textures[damage];
}
@Override
public void registerIcons(IconRegister register) {
textures = new Icon[2];
textures[0] = register.registerIcon(ModInfo.MOD_ID.toLowerCase()+":spoolEmpty");
textures[1] = register.registerIcon(ModInfo.MOD_ID.toLowerCase()+":wireSpool");
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void getSubItems(int id, CreativeTabs tab, List list) {
for (int i=0; i<itemSubNames.length; i++) {
list.add(new ItemStack(id, 1, i));
}
}
@Override
public String getUnlocalizedName(ItemStack stack) {
return getUnlocalizedName() + "." + itemSubNames[stack.getItemDamage()];
}
}
| speilberg0/WiresAndCircuits | common/com/dmillerw/wac/item/ItemWireSpool.java | Java | gpl-3.0 | 1,785 |
from ..schema import default_radio_driver
from .base import OpenWrtConverter
class Radios(OpenWrtConverter):
netjson_key = 'radios'
intermediate_key = 'wireless'
_uci_types = ['wifi-device']
def to_intermediate_loop(self, block, result, index=None):
radio = self.__intermediate_radio(block)
result.setdefault('wireless', [])
result['wireless'].append(radio)
return result
def __intermediate_radio(self, radio):
radio.update({'.type': 'wifi-device', '.name': radio.pop('name')})
# rename tx_power to txpower
if 'tx_power' in radio:
radio['txpower'] = radio.pop('tx_power')
# rename driver to type
radio['type'] = radio.pop('driver', default_radio_driver)
# determine hwmode option
radio['hwmode'] = self.__intermediate_hwmode(radio)
# check if using channel 0, that means "auto"
if radio['channel'] == 0:
radio['channel'] = 'auto'
# determine channel width
if radio['type'] == 'mac80211':
radio['htmode'] = self.__intermediate_htmode(radio)
else:
del radio['protocol']
# ensure country is uppercase
if 'country' in radio:
radio['country'] = radio['country'].upper()
return self.sorted_dict(radio)
def __intermediate_hwmode(self, radio):
"""
possible return values are: 11a, 11b, 11g
"""
protocol = radio['protocol']
if protocol in ['802.11a', '802.11b', '802.11g']:
# return 11a, 11b or 11g
return protocol[4:]
if protocol == '802.11ac':
return '11a'
# determine hwmode depending on channel used
if radio['channel'] == 0:
# when using automatic channel selection, we need an
# additional parameter to determine the frequency band
return radio.get('hwmode')
elif radio['channel'] <= 13:
return '11g'
else:
return '11a'
def __intermediate_htmode(self, radio):
"""
only for mac80211 driver
"""
protocol = radio.pop('protocol')
channel_width = radio.pop('channel_width')
# allow overriding htmode
if 'htmode' in radio:
return radio['htmode']
if protocol == '802.11n':
return 'HT{0}'.format(channel_width)
elif protocol == '802.11ac':
return 'VHT{0}'.format(channel_width)
elif protocol == '802.11ax':
return 'HE{0}'.format(channel_width)
# disables n
return 'NONE'
def to_netjson_loop(self, block, result, index):
radio = self.__netjson_radio(block)
result.setdefault('radios', [])
result['radios'].append(radio)
return result
def __netjson_radio(self, radio):
del radio['.type']
radio['name'] = radio.pop('.name')
if 'txpower' in radio:
radio['tx_power'] = int(radio.pop('txpower'))
radio['driver'] = radio.pop('type')
if 'disabled' in radio:
radio['disabled'] = radio['disabled'] == '1'
radio['protocol'] = self.__netjson_protocol(radio)
radio['channel'] = self.__netjson_channel(radio)
radio['channel_width'] = self.__netjson_channel_width(radio)
return radio
def __netjson_protocol(self, radio):
"""
determines NetJSON protocol radio attribute
"""
htmode = radio.get('htmode')
hwmode = radio.get('hwmode', None)
if htmode.startswith('HT'):
return '802.11n'
elif htmode.startswith('VHT'):
return '802.11ac'
elif htmode.startswith('HE'):
return '802.11ax'
return '802.{0}'.format(hwmode)
def __netjson_channel(self, radio):
"""
determines NetJSON channel radio attribute
"""
if radio['channel'] == 'auto':
return 0
# delete hwmode because is needed
# only when channel is auto
del radio['hwmode']
return int(radio['channel'])
def __netjson_channel_width(self, radio):
"""
determines NetJSON channel_width radio attribute
"""
htmode = radio.pop('htmode')
if htmode == 'NONE':
return 20
channel_width = htmode.replace('VHT', '').replace('HT', '').replace('HE', '')
# we need to override htmode
if '+' in channel_width or '-' in channel_width:
radio['htmode'] = htmode
channel_width = channel_width[0:-1]
return int(channel_width)
| openwisp/netjsonconfig | netjsonconfig/backends/openwrt/converters/radios.py | Python | gpl-3.0 | 4,636 |
# Copyright (C) 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
from .urls import parse_bug_id, parse_attachment_id
class URLsTest(unittest.TestCase):
def test_parse_bug_id(self):
# FIXME: These would be all better as doctests
self.assertEquals(12345, parse_bug_id("http://webkit.org/b/12345"))
self.assertEquals(12345, parse_bug_id("foo\n\nhttp://webkit.org/b/12345\nbar\n\n"))
self.assertEquals(12345, parse_bug_id("http://bugs.webkit.org/show_bug.cgi?id=12345"))
# Our url parser is super-fragile, but at least we're testing it.
self.assertEquals(None, parse_bug_id("http://www.webkit.org/b/12345"))
self.assertEquals(None, parse_bug_id("http://bugs.webkit.org/show_bug.cgi?ctype=xml&id=12345"))
def test_parse_attachment_id(self):
self.assertEquals(12345, parse_attachment_id("https://bugs.webkit.org/attachment.cgi?id=12345&action=review"))
self.assertEquals(12345, parse_attachment_id("https://bugs.webkit.org/attachment.cgi?id=12345&action=edit"))
self.assertEquals(12345, parse_attachment_id("https://bugs.webkit.org/attachment.cgi?id=12345&action=prettypatch"))
self.assertEquals(12345, parse_attachment_id("https://bugs.webkit.org/attachment.cgi?id=12345&action=diff"))
# Direct attachment links are hosted from per-bug subdomains:
self.assertEquals(12345, parse_attachment_id("https://bug-23456-attachments.webkit.org/attachment.cgi?id=12345"))
# Make sure secure attachment URLs work too.
self.assertEquals(12345, parse_attachment_id("https://bug-23456-attachments.webkit.org/attachment.cgi?id=12345&t=Bqnsdkl9fs"))
| cs-au-dk/Artemis | WebKit/Tools/Scripts/webkitpy/common/config/urls_unittest.py | Python | gpl-3.0 | 3,141 |
/*
* Copyright (C) 2017 The Jappsy Open Source Project (http://jappsy.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "uGLShaders.h"
void GLShaders::clear() {
int32_t count = list.count();
GLShader** values = list.values();
for (int i = 0; i < count; i++) {
delete values[i];
}
list.clear();
}
GLShaders::GLShaders() {
}
GLShaders::~GLShaders() {
clear();
}
GLShader* GLShaders::get(const CString& key) throw(const char*) {
return list.get(key);
}
bool GLShaders::remove(const CString& key) {
GLShader* prevShader = list.remove(key);
if (prevShader != NULL) {
delete prevShader;
return true;
}
return false;
}
GLShader* GLShaders::set(const SharedStorage* storage, SharedShader* storageData) throw(const char*) {
GLShader* shader = NULL;
try {
shader = list.get(storage->key);
shader->setLinkerList(storage->key);
} catch (...) {
shader = new GLShader(this, storage->key);
try {
list.put(storage->key, shader);
} catch (...) {
delete shader;
throw;
}
}
try {
shader->update(storage, storageData);
} catch (...) {
list.remove(storage->key);
delete shader;
throw;
}
return shader;
}
void GLShaders::link(const CString& key, GLContextObjectLinker* linker, const uint32_t tag) throw(const char*) {
linkLinker(key, linker, tag);
try {
GLShader* shader = list.get(key);
shader->notifyLink(linker, shader, tag);
} catch (...) {
}
}
void GLShaders::unlink(const CString& key, GLContextObjectLinker* linker, const uint32_t tag) throw(const char*) {
if (unlinkLinker(key, linker, tag)) {
try {
GLShader* shader = list.get(key);
shader->notifyUnlink(linker, shader, tag);
} catch (...) {
}
}
}
| Jappsy/jappsy | src/common/include/opengl/collections/uGLShaders.cpp | C++ | gpl-3.0 | 2,215 |
/**
* selectbox-utils for jQuery
* For Virtual-Office Company
* Copyright (c) 2007 Yoshiomi KURISU
* Licensed under the MIT (MIT-LICENSE.txt) licenses.
*
* @example $('#year1').numericOptions({from:2007,to:2011});
* @example $('#month1').numericOptions({from:1,to:12});
* @example $('#date1').numericOptions().datePulldown({year:$('#year1'),month:$('#month1')});
*
*/
(function() {
//obj is Array
// Array : [[label,value],[label,value],....]
//set options to select node
//obj is null or obj is number
//get options from select node
$.fn.options = function(obj){
if(obj || obj == 0){
if(obj instanceof Array){
this.each(function(){
this.options.length = 0;
for(var i = 0,len = obj.length;i<len;i++){
var tmp = obj[i];
if(tmp.length && tmp.length == 2){
this.options[this.options.length] = new Option(tmp[0],tmp[1]);
}
}
});
return this;
}else if(typeof obj == 'number'){
return $('option:eq('+obj+')',this);
}else if(obj == 'selected'){
return this.val();
}
}else{
return $('option',this)
}
return $([]);
}
$.fn.numericOptions = function(settings){
settings = jQuery.extend({
remove:true
,from:1
,to:31
,selectedIndex:0
,valuePadding:0
,namePadding:0
,labels:[]
,exclude:null
,startLabel:null
},settings);
//error check
if(!(settings.from+'').match(/^\d+$/)||!(settings.to+'').match(/^\d+$/)||!(settings.selectedIndex+'').match(/^\d+$/)||!(settings.valuePadding+'').match(/^\d+$/)||!(settings.namePadding+'').match(/^\d+$/)) return;
if(settings.from > settings.to) return;
if(settings.to - settings.from < settings.selectedIndex) return;
//add options
if(settings.remove) this.children().remove();
var padfunc = function(v,p){
if((''+v).length < p){
for(var i = 0,l = p - (v+'').length;i < l ;i++){
v = '0' + v;
}
}
return v;
}
var exclude_strings = (settings.exclude && settings.exclude instanceof Array && settings.exclude.length > 0)?' '+settings.exclude.join(' ')+' ':'';
this.each(function(){
this.options.length = 0
//set startLabel
var sl = settings.startLabel;
if(sl && sl.length && sl.length == 2){
this.options[0] = new Option(sl[0],sl[1]);
}
});
for(var i=settings.from,j=0;i<=settings.to;i++){
this.each(function(){
var val = padfunc(i,settings.valuePadding);
if(exclude_strings.indexOf(' '+val+' ') < 0){
var lab = (settings.labels[j])?settings.labels[j]:padfunc(i,settings.namePadding);
this.options[this.options.length] = new Option(lab,val);
j++;
}
});
}
this.each(function(){
if(jQuery.browser.opera){
this.options[settings.selectedIndex].defaultSelected = true;
}else{
this.selectedIndex = settings.selectedIndex;
}
});
return this;
};
//
$.fn.datePulldown = function(settings){
if(!settings.year || !settings.month) return ;
var y = settings.year;
var m = settings.month;
if(!y.val() || !m.val()) return;
if(!y.val().match(/^\d{1,4}$/)) return;
if(!m.val().match(/^[0][1-9]$|^[1][1,2]$|^[0-9]$/)) return;
var self = this;
var fnc = function(){
var tmp = new Date(new Date(y.val(),m.val()).getTime() - 1000);
var lastDay = tmp.getDate() - 0;
self.each(function(){
var ind = (this.selectedIndex<lastDay-1)?this.selectedIndex:lastDay-1;
this.selectedIndex = ind;
$(this).numericOptions({to:lastDay,selectedIndex:ind});
});
}
y.change(fnc);
m.change(fnc);
return this;
};
})(jQuery);
| ulinke/phpb2b | static/scripts/jquery/selectbox.js | JavaScript | gpl-3.0 | 3,526 |
/**
* This file is part of BowWarfare
*
* Copyright (c) 2016 hitech95 <https://github.com/hitech95>
* Copyright (c) contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.kytech.bowwarfare.commands;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
/**
* Created by Hitech95 on 25/06/2015.
*/
public class DisableArena implements CommandExecutor {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
return null;
}
}
| hitech95/Bow-Warfare | bw-sponge/src/main/java/it/kytech/bowwarfare/commands/DisableArena.java | Java | gpl-3.0 | 1,346 |
require "string_utils"
describe StringUtils do
describe ".generate_random_string" do
context "given a length argument equal to 10" do
it "returns a string that's 10 characters long" do
expect(StringUtils.generate_random_string(10).length).to eql(10)
end
it "returns a random string that only contains the allowed alphanumeric characters" do
length = 10
# The allowed alphanumeric characters are 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
expect(StringUtils.generate_random_string(length)).to match(/^[A-Za-z0-9]{#{length}}+$/)
end
end
end
end
| dbruzzone/wishing-tree | Ruby/discover/spec/string_utils_spec.rb | Ruby | gpl-3.0 | 644 |
/*
Copyright (C) 2006 Thorsten Berger
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
*
*/
package de.thorstenberger.taskmodel.view.correction;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import de.thorstenberger.taskmodel.CorrectorDelegateObject;
import de.thorstenberger.taskmodel.ManualCorrection;
import de.thorstenberger.taskmodel.StudentAnnotation;
import de.thorstenberger.taskmodel.TaskModelServices;
import de.thorstenberger.taskmodel.TaskModelViewDelegate;
import de.thorstenberger.taskmodel.Tasklet;
import de.thorstenberger.taskmodel.UserInfo;
import de.thorstenberger.taskmodel.complex.ComplexTasklet;
import de.thorstenberger.taskmodel.complex.complextaskhandling.ManualSubTaskletCorrection;
import de.thorstenberger.taskmodel.complex.complextaskhandling.Page;
import de.thorstenberger.taskmodel.complex.complextaskhandling.SubTasklet;
import de.thorstenberger.taskmodel.view.DateUtil;
import de.thorstenberger.taskmodel.view.HtmlViewContext;
import de.thorstenberger.taskmodel.view.ParserUtil;
import de.thorstenberger.taskmodel.view.SubTaskletInfoVO;
import de.thorstenberger.taskmodel.view.ViewContext;
import de.thorstenberger.taskmodel.view.correction.CorrectionInfoVO.CorrectorAnnotation;
import de.thorstenberger.taskmodel.view.correction.tree.CorrectionNodeFormatter;
import de.thorstenberger.taskmodel.view.correction.tree.SubTaskletRootNode;
/**
* @author Thorsten Berger
*
*/
public class DoCorrectionAction extends Action {
/*
* (non-Javadoc)
*
* @seeorg.apache.struts.action.Action#execute(org.apache.struts.action.
* ActionMapping, org.apache.struts.action.ActionForm,
* javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward execute(final ActionMapping mapping, final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws Exception {
final ActionMessages errors = new ActionMessages();
long id;
final String userId = request.getParameter("userId");
final String selectedSubTaskletNum = request.getParameter("selectedSubTaskletNum");
SubTasklet selectedSubTasklet = null;
try {
id = Long.parseLong(request.getParameter("taskId"));
} catch (final NumberFormatException e) {
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("invalid.parameter"));
saveErrors(request, errors);
return mapping.findForward("error");
}
final CorrectorDelegateObject delegateObject = (CorrectorDelegateObject) TaskModelViewDelegate.getDelegateObject(request
.getSession().getId(), id);
if (delegateObject == null) {
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("no.session"));
saveErrors(request, errors);
return mapping.findForward("error");
}
request.setAttribute("ReturnURL", delegateObject.getReturnURL());
final ComplexTasklet tasklet = (ComplexTasklet) delegateObject.getTaskManager().getTaskletContainer().getTasklet(id,
userId);
if (!delegateObject.isPrivileged()) {
if (!delegateObject.getCorrectorLogin().equals(tasklet.getTaskletCorrection().getCorrector())) {
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("may.only.correct.assigned.tasklets"));
saveErrors(request, errors);
return mapping.findForward("error");
}
}
// check the status
if (tasklet.hasOrPassedStatus(Tasklet.Status.SOLVED)) {
final List<Page> pages = tasklet.getSolutionOfLatestTry().getPages();
final List<SubTasklet> subTasklets = new ArrayList<SubTasklet>();
for (final Page page : pages) {
final List<SubTasklet> sts = page.getSubTasklets();
for (final SubTasklet subTasklet : sts) {
subTasklets.add(subTasklet);
if (subTasklet.getVirtualSubtaskNumber().equals(selectedSubTaskletNum)) {
selectedSubTasklet = subTasklet;
}
}
}
final String currentCorrector = delegateObject.getCorrectorLogin();
final SubTaskletRootNode rn = new SubTaskletRootNode(subTasklets, userId, id, selectedSubTaskletNum, currentCorrector);
final CorrectionNodeFormatter cnf = new CorrectionNodeFormatter(id, userId, request.getContextPath()
+ mapping.findForward("doCorrection").getPath(), request, response);
request.setAttribute("rootNode", rn);
request.setAttribute("nodeFormatter", cnf);
final CorrectionInfoVO civo = new CorrectionInfoVO();
civo.setTaskId(id);
civo.setUserId(userId);
// set points
if (tasklet.getTaskletCorrection().isCorrected()) {
final List<CorrectionInfoVO.Correction> taskletCorrections = new LinkedList<CorrectionInfoVO.Correction>();
if (tasklet.getTaskletCorrection().isAutoCorrected()) {
taskletCorrections.add(new CorrectionInfoVO.Correction(null, true, tasklet.getTaskletCorrection()
.getAutoCorrectionPoints()));
} else {
for (final ManualCorrection mc : tasklet.getTaskletCorrection().getManualCorrections()) {
taskletCorrections.add(new CorrectionInfoVO.Correction(mc.getCorrector(), false, mc.getPoints()));
}
}
civo.setCorrections(taskletCorrections);
}
civo.setStatus(tasklet.getStatus().getValue());
civo.setCorrectorLogin(tasklet.getTaskletCorrection().getCorrector());
civo.setCorrectorHistory(tasklet.getTaskletCorrection().getCorrectorHistory());
// corrrector annotations
final List<CorrectorAnnotation> cas = new LinkedList<CorrectorAnnotation>();
for (final de.thorstenberger.taskmodel.CorrectorAnnotation ca : tasklet.getTaskletCorrection()
.getCorrectorAnnotations()) {
if (!ca.getCorrector().equals(currentCorrector)) {
cas.add(civo.new CorrectorAnnotation(ca.getCorrector(), ParserUtil.escapeCR(ca.getText())));
} else {
civo.setCurrentCorrectorAnnotation(ca.getText());
}
}
civo.setOtherCorrectorAnnotations(cas);
//
civo.setNumOfTry(tasklet.getComplexTaskHandlingRoot().getNumberOfTries());
final List<CorrectionInfoVO.AnnotationInfoVO> acknowledgedAnnotations = new ArrayList<CorrectionInfoVO.AnnotationInfoVO>();
final List<CorrectionInfoVO.AnnotationInfoVO> nonAcknowledgedAnnotations = new ArrayList<CorrectionInfoVO.AnnotationInfoVO>();
for (final StudentAnnotation anno : tasklet.getTaskletCorrection().getStudentAnnotations()) {
if (anno.isAcknowledged()) {
acknowledgedAnnotations.add(civo.new AnnotationInfoVO(DateUtil.getStringFromMillis(anno.getDate()),
ParserUtil.escapeCR(anno.getText())));
} else {
nonAcknowledgedAnnotations.add(civo.new AnnotationInfoVO(DateUtil.getStringFromMillis(anno.getDate()),
ParserUtil.escapeCR(anno.getText())));
}
}
civo.setAcknowledgedAnnotations(acknowledgedAnnotations);
civo.setNonAcknowledgedAnnotations(nonAcknowledgedAnnotations);
civo.setCanAcknowledge(tasklet.getStatus() == Tasklet.Status.ANNOTATED);
// available correctors
final List<UserInfo> availableCorrectorsUI = delegateObject.getTaskManager().getCorrectors();
final List<String> availableCorrectors = new LinkedList<String>();
for (final UserInfo corrector : availableCorrectorsUI) {
availableCorrectors.add(corrector.getLogin());
}
civo.setAvailableCorrectors(availableCorrectors);
request.setAttribute("Correction", civo);
final ViewContext context = new HtmlViewContext(request);
// SubTasklet selected -> show it
if (selectedSubTasklet != null) {
final SubTaskletInfoVO stivo = new SubTaskletInfoVO();
stivo.setCorrected(selectedSubTasklet.isCorrected());
if (selectedSubTasklet.isCorrected()) {
final List<de.thorstenberger.taskmodel.view.SubTaskletInfoVO.Correction> corrections = new LinkedList<de.thorstenberger.taskmodel.view.SubTaskletInfoVO.Correction>();
if (selectedSubTasklet.isAutoCorrected()) {
corrections.add(stivo.new Correction(null, true, selectedSubTasklet.getAutoCorrection().getPoints()));
} else {
for (final ManualSubTaskletCorrection msc : selectedSubTasklet.getManualCorrections()) {
corrections.add(stivo.new Correction(msc.getCorrector(), false, msc.getPoints()));
}
}
stivo.setCorrections(corrections);
}
stivo.setNeedsManualCorrectionFlag(selectedSubTasklet.isSetNeedsManualCorrectionFlag());
stivo.setHint(selectedSubTasklet.getHint());
stivo.setCorrectionHint(ParserUtil.getCorrectionHint(selectedSubTasklet.getCorrectionHint()));
stivo.setProblem(ParserUtil.getProblem(selectedSubTasklet.getProblem()));
stivo.setReachablePoints(selectedSubTasklet.getReachablePoints());
stivo.setVirtualSubTaskletNumber(selectedSubTasklet.getVirtualSubtaskNumber());
stivo.setCorrectionHTML(TaskModelServices.getInstance().getSubTaskView(selectedSubTasklet).getCorrectionHTML(
delegateObject.getCorrectorLogin(), context));
if (stivo.getCorrectionHTML() == null) {
stivo.setCorrectedHTML(TaskModelServices.getInstance().getSubTaskView(selectedSubTasklet).getCorrectedHTML(
context, -1));
}
civo.setSubTasklet(stivo);
}
return mapping.findForward("success");
} else {
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("task.cannot_correct_task_not_solved"));
saveErrors(request, errors);
return mapping.findForward("error");
}
}
}
| smee/elateXam | taskmodel/taskmodel-core-view/src/main/java/de/thorstenberger/taskmodel/view/correction/DoCorrectionAction.java | Java | gpl-3.0 | 11,783 |
package tmp.generated_people;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class Element_head2 extends Element_head {
public Element_head2(STag_head sTag_head, ArrayList<CMisc> cMisc1, Content_head_Seq1 content_head_Seq1, ETag_head eTag_head, ArrayList<CMisc> cMisc2, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyOne<STag_head>("sTag_head", sTag_head),
new PropertyZeroOrMore<CMisc>("cMisc1", cMisc1),
new PropertyOne<Content_head_Seq1>("content_head_Seq1", content_head_Seq1),
new PropertyOne<ETag_head>("eTag_head", eTag_head),
new PropertyZeroOrMore<CMisc>("cMisc2", cMisc2)
}, firstToken, lastToken);
}
public Element_head2(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public ASTNode deepCopy() {
return new Element_head2(cloneProperties(),firstToken,lastToken);
}
public STag_head getSTag_head() {
return ((PropertyOne<STag_head>)getProperty("sTag_head")).getValue();
}
public ArrayList<CMisc> getCMisc1() {
return ((PropertyZeroOrMore<CMisc>)getProperty("cMisc1")).getValue();
}
public Content_head_Seq1 getContent_head_Seq1() {
return ((PropertyOne<Content_head_Seq1>)getProperty("content_head_Seq1")).getValue();
}
public ETag_head getETag_head() {
return ((PropertyOne<ETag_head>)getProperty("eTag_head")).getValue();
}
public ArrayList<CMisc> getCMisc2() {
return ((PropertyZeroOrMore<CMisc>)getProperty("cMisc2")).getValue();
}
}
| ckaestne/CIDE | CIDE_Language_XML_concrete/src/tmp/generated_people/Element_head2.java | Java | gpl-3.0 | 1,615 |
package nfs
import (
"fmt"
)
const (
rpcLastFrag = 0x80000000
rpcSizeMask = 0x7fffffff
)
const (
rpcCall = 0
rpcReply = 1
)
const nfsProgramNumber = 100003
func handleCall(xid string, xdr *xdr, event *StreamEvent) {
// eat rpc version number
xdr.getUInt()
rpcProg := xdr.getUInt()
if rpcProg != nfsProgramNumber {
// not a NFS request
return
}
nfsVers := xdr.getUInt()
nfsProc := xdr.getUInt()
authFlavor := xdr.getUInt()
authOpaque := xdr.getDynamicOpaque()
var auth string
switch authFlavor {
case 0:
auth = "none"
case 1:
//auth = "unix"
credXdr := makeXDR(authOpaque)
// stamp
credXdr.getUInt()
// machine
credXdr.getString()
// uid
uid := credXdr.getUInt()
// gid
credXdr.getUInt()
// gids
credXdr.getUIntVector()
auth = fmt.Sprintf("%d", uid)
case 6:
auth = "rpcsec_gss"
default:
auth = fmt.Sprintf("unknown (%d)", authFlavor)
}
// eat auth verifier
xdr.getUInt()
xdr.getDynamicOpaque()
r := &NfsRequest{
vers: nfsVers,
proc: nfsProc,
auth: auth,
ctime: event.Timestamp,
client: event.Src + ":" + event.SrcPort,
server: event.Dst + ":" + event.DstPort,
pid: -1,
xid: xid,
}
r.getRequestInfo(xdr)
event.Stream.PendingRequests.SetDefault(xid, r)
}
func handleReply(xid string, xdr *xdr, event *StreamEvent) *NfsRequest {
var r *NfsRequest
if x, ok := event.Stream.PendingRequests.Get(xid); ok {
event.Stream.PendingRequests.Delete(xid)
r = x.(*NfsRequest)
r.rtime = event.Timestamp
return r
}
return nil
}
func procesRpcMessage(xdr *xdr, event *StreamEvent) *NfsRequest {
xid := fmt.Sprintf("%.8x", xdr.getUInt())
msgType := xdr.getUInt()
switch msgType {
case rpcCall:
handleCall(xid, xdr, event)
return nil
case rpcReply:
return handleReply(xid, xdr, event)
default:
// bad xdr
return nil
}
}
| kofemann/nfstop | nfs/rpc.go | GO | gpl-3.0 | 1,840 |