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 |
|---|---|---|---|---|---|
/*
* TfsNotificationRelay - http://github.com/kria/TfsNotificationRelay
*
* Copyright (C) 2016 Kristian Adrup
*
* This file is part of TfsNotificationRelay.
*
* TfsNotificationRelay 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. See included file COPYING for details.
*/
using DevCore.TfsNotificationRelay.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DevCore.TfsNotificationRelay.Notifications
{
class ReleaseCreatedNotification : ReleaseNotification
{
public override IList<string> ToMessage(BotElement bot, TextElement text, Func<string, string> transform)
{
var formatter = new
{
TeamProjectCollection = transform(TeamProjectCollection),
ProjectName = transform(ProjectName),
ReleaseDefinition = transform(ReleaseDefinition),
ReleaseStatus = transform(ReleaseStatus.ToString()),
ReleaseUrl,
ReleaseName = transform(ReleaseName),
ReleaseReason = transform(ReleaseReason.ToString()),
CreatedBy = transform(CreatedByUniqueName),
CreatedByDisplayName = transform(CreatedByDisplayName),
DisplayName = transform(CreatedByDisplayName),
CreatedOn,
UserName = transform(UserName),
MappedUser = bot.GetMappedUser(CreatedByUniqueName)
};
return new[] { text.ReleaseCreatedFormat.FormatWith(formatter) };
}
public override EventRuleElement GetRuleMatch(string collection, IEnumerable<EventRuleElement> eventRules)
{
var rule = GetRulesMatch(collection, eventRules).FirstOrDefault(r => r.Events.HasFlag(TfsEvents.ReleaseCreated));
return rule;
}
}
}
| kria/TfsNotificationRelay | src/TfsNotificationRelay/Notifications/ReleaseCreatedNotification.cs | C# | gpl-3.0 | 2,037 |
<?php
class TrainingController extends Controller
{
private function modal(){
$cs = Yii::app()->clientScript;
$modal_url = Yii::app()->theme->baseUrl . '/js/osx/';
$cs->registerCssFile($modal_url . 'css/osx.css');
$cs->registerCss('modal', '
div#osx-modal-data a:link,
div#osx-modal-data a:visited {
color: #F01800;
text-decoration: none;
}
div#osx-modal-data a:hover {
text-decoration: underline;
}
');
$cs->registerScriptFile($modal_url . 'js/jquery.simplemodal.js', CClientScript::POS_END);
$cs->registerScriptFile($modal_url . 'js/osx.js', CClientScript::POS_END);
$cs->registerScript('modal', '$("input.osx").click();', CClientScript::POS_READY);
}
public function actionIndex(){
$this->modal();
$this->render('index');
}
public function actionDetails($item){
$valid = array(
'symfony',
'drupal',
'python-django',
'xhtml-css',
'gnu-linux',
'proyecto-alba',
);
if (!in_array($item, $valid)){
throw new CHttpException(404);
}
if($item != 'proyecto-alba'){
$this->modal();
}
$this->render('details', array('item' => $item));
}
}
| pressEnter/www | protected/controllers/TrainingController.php | PHP | gpl-3.0 | 1,139 |
import fs from 'fs'
import path from 'path'
const Jimp = require('jimp')
const hjson = require('hjson')
const electronImageResize = require('./electronImageResize')
const {getPath1,getPath2} = require('./chromeExtensionUtil')
const contentScriptName = '___contentScriptModify_.js'
const backgroundScriptName = '___backgroundScriptModify_.js'
const polyfillName = 'browser-polyfill.min.js'
const webExtModifyBg = 'webextensionModifyBg.js'
const webExtModifyCs = 'webextensionModifyCs.js'
const webExtStyleName = 'webextension.css'
const backgroundHtmlName = '___backgroundModify_.html'
let backgroundHtmlStr = `<!DOCTYPE html>
<head><meta charset="UTF-8"></head>
<body>
<script src="${backgroundScriptName}"></script>
__REPLACE__
</body></html>`
function findJsTags(obj,callback){
if(obj.js){
obj.js = callback(obj.js)
}
if(Array.isArray(obj)) {
for(let ele of obj){
findJsTags(ele,callback)
}
}
else if(obj instanceof Object){
for(let [key,ele] of Object.entries(obj)){
if(key != 'js') findJsTags(ele,callback)
}
}
}
function copyModifyFile(to,flagContent,flagBackground,isWebExt){
if(flagContent){
const cont = fs.readFileSync(path.join(__dirname,'../src/extension/contentScriptModify.js')).toString()
const contPath = path.join(to,contentScriptName)
if(fs.existsSync(contPath)) fs.unlinkSync(contPath)
fs.writeFileSync(contPath,cont)
}
if(flagBackground){
const bg = fs.readFileSync(path.join(__dirname,'../src/extension/backgroundScriptModify.js')).toString()
const bgPath = path.join(to,backgroundScriptName)
if(fs.existsSync(bgPath)) fs.unlinkSync(bgPath)
fs.writeFileSync(bgPath,bg)
}
if(isWebExt){
for(let file of [polyfillName,webExtModifyBg,webExtModifyCs,webExtStyleName]){
const poli = fs.readFileSync(path.join(__dirname,`../resource/${file}`)).toString()
const poliPath = path.join(to,file)
if(fs.existsSync(poliPath)) fs.unlinkSync(poliPath)
fs.writeFileSync(poliPath,poli)
}
}
}
let cache = new Set()
function htmlModify(verPath,fname,isWebExt){
const dirName = path.dirname(fname)
const backStr = dirName == '.' ? dirName : dirName.split(/[\/\\]/).map(x=>'..').join('/')
console.log(verPath,fname,dirName,backStr)
const fullPath = path.join(verPath,dirName,path.basename(fname).split("?")[0])
if(cache.has(fullPath) || !fs.existsSync(fullPath)) return
cache.add(fullPath)
const str = fs.readFileSync(fullPath).toString()
if(str.includes(backgroundScriptName)) return
fs.unlinkSync(fullPath)
let writeStr = str.replace(/< *(head)([^>]*)>/i,`<$1$2>\n ${isWebExt ? `<script src="${backStr}/${polyfillName}"></script>\n<script src="${backStr}/${webExtModifyBg}"></script>\n` : ''}<script src="${backStr}/${backgroundScriptName}"></script>`)
if(!writeStr.includes(backgroundScriptName)){
writeStr = str.replace(/< *(body)([^>]*)>/i,`<$1$2>\n ${isWebExt ? `<script src="${backStr}/${polyfillName}"></script>\n<script src="${backStr}/${webExtModifyBg}"></script>\n` : ''}<script src="${backStr}/${backgroundScriptName}"></script>`)
}
if(!writeStr.includes(backgroundScriptName)){
writeStr = str.replace(/html>/i,`html>\n ${isWebExt ? `<script src="${backStr}/${polyfillName}"></script>\n<script src="${backStr}/${webExtModifyBg}"></script>\n<link rel="stylesheet" href="${backStr}/${webExtStyleName}">\n` : ''}\n<script src="${backStr}/${backgroundScriptName}"></script>`)
}
if(!writeStr.includes(backgroundScriptName)){
writeStr = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Background</title>
${isWebExt ? `<script src="${backStr}/${polyfillName}"></script>\n<script src="${backStr}/${webExtModifyBg}"></script>\n` : ''}
<script src="${backStr}/${backgroundScriptName}"></script>
${writeStr}
</head>
<body>
</body>
</html>`
}
fs.writeFileSync(fullPath,writeStr)
}
function removeBom(x){
return x.charCodeAt(0) === 0xFEFF ? x.slice(1) : x
}
export default async function modify(extensionId,verPath){
const isWebExt = !extensionId.match(/(^[a-z]+$)|(_chrome_$)/)
cache = new Set()
if(!verPath){
verPath = getPath2(extensionId) || getPath1(extensionId) //getPath1(extensionId)
}
const manifestPath = path.join(verPath, 'manifest.json')
const exists = fs.existsSync(manifestPath)
if (exists) {
const manifestStr = removeBom(fs.readFileSync(manifestPath).toString()).replace('\\u003Call_urls>','<all_urls>')
const infos = hjson.parse(manifestStr)
if(!infos.key || infos.key.match(/[\-\.]/)){
infos.key = new Buffer(extensionId).toString('base64')
}
if(infos.permissions && infos.permissions.includes('activeTab')
&& (!infos.permissions.includes('http://*/*') || !infos.permissions.includes('https://*/*'))){
infos.permissions = [...new Set([...infos.permissions,'http://*/*','https://*/*'])]
}
if(infos.optional_permissions){
infos.permissions = [...new Set([...(infos.permissions || []),...infos.optional_permissions])]
}
if(!infos.content_security_policy){
infos.content_security_policy = "script-src 'self' 'unsafe-eval'; object-src 'self'"
}
if(isWebExt && infos.permissions){
infos.permissions = infos.permissions.filter(x=>x!=='clipboardWrite' && x!=='clipboardRead')
const ind = infos.permissions.findIndex(x=>x=='menus')
if(ind != -1) infos.permissions[ind] = 'contextMenus'
}
let flagContent,flagBackground
if(infos.content_scripts){
findJsTags(infos.content_scripts,js=>{
if(!Array.isArray(js)) js = [js]
if(isWebExt && !js.includes(polyfillName)){
js.unshift(webExtModifyCs)
js.unshift(polyfillName)
}
if(!js.includes(contentScriptName)) js.unshift(contentScriptName)
return js
})
flagContent = true
}
let open
const imageResize = new electronImageResize()
try{
if(infos.background){
if(infos.background.persistent === false && !['jpkfjicglakibpenojifdiepckckakgk','occjjkgifpmdgodlplnacmkejpdionan'].includes(extensionId)){
infos.background.persistent = true
}
if(infos.background.page){
htmlModify(verPath,infos.background.page,isWebExt)
}
else if(infos.background.scripts){
if(!Array.isArray(infos.background.scripts)) infos.background.scripts = [infos.background.scripts]
if(isWebExt) backgroundHtmlStr = backgroundHtmlStr.replace('<body>',`<body>\n<script src="${polyfillName}"></script>\n<script src="${webExtModifyBg}"></script>`)
const content = backgroundHtmlStr.replace('__REPLACE__',infos.background.scripts.map(src=>`<script src="${src}"></script>`).join("\n "))
fs.writeFileSync(path.join(verPath,backgroundHtmlName),content)
infos.background.page = backgroundHtmlName
delete infos.background.scripts
}
flagBackground = true
}
if(infos.options_page){
htmlModify(verPath,infos.options_page,isWebExt)
flagBackground = true
}
if(infos.options_ui && infos.options_ui.page){
if(!infos.options_page) infos.options_page = infos.options_ui.page
htmlModify(verPath,infos.options_ui.page,isWebExt)
flagBackground = true
}
if(infos.page_action && infos.page_action.default_popup){
htmlModify(verPath,infos.page_action.default_popup,isWebExt)
flagBackground = true
}
if(infos.browser_action && infos.browser_action.default_popup){
htmlModify(verPath,infos.browser_action.default_popup,isWebExt)
flagBackground = true
}
if(infos.web_accessible_resources){
for(let file of infos.web_accessible_resources){
if(file.match(/\.html?$/)){
htmlModify(verPath,file,isWebExt)
flagBackground = true
}
}
}
if(infos.chrome_url_overrides){
for(let file of Object.values(infos.chrome_url_overrides)){
htmlModify(verPath,file,isWebExt)
flagBackground = true
}
}
if(infos.page_action){
if(!infos.browser_action){
infos.browser_action = infos.page_action
if(infos.browser_action.show){
infos.browser_action.enable = infos.browser_action.show
delete infos.browser_action.show
}
if(infos.browser_action.hide){
infos.browser_action.disable = infos.browser_action.hide
delete infos.browser_action.hide
}
}
delete infos.page_action
}
for(let file of require("glob").sync(`${verPath}/**/*.html`)){
console.log(222444,verPath,file.replace(`${verPath}/`,''),isWebExt)
htmlModify(verPath,file.replace(`${verPath.replace(/\\/g,'/')}/`,''),isWebExt)
}
for(let file of require("glob").sync(`${verPath}/**/*.js`)){
let datas = fs.readFileSync(file).toString(),needWrite = false
if (isWebExt && datas.includes('moz-extension')) {
// console.log(file)
datas = datas.replace(/moz\-extension/ig,'chrome-extension')
needWrite = true
}
if(extensionId == 'mlomiejdfkolichcflejclcbmpeaniij' && datas.includes('about:blank')){
datas = datas.replace(/about:blank/ig,'chrome-extension://dckpbojndfoinamcdamhkjhnjnmjkfjd/blank.html')
needWrite = true
}
if(needWrite){
fs.writeFileSync(file, datas)
}
}
if(infos.commands){
for(let [k,v] of Object.entries(infos.commands)) {
if(v.suggested_key){
for(let [k2,v2] of Object.entries(v.suggested_key)){
if(v2.match(/^F\d+$/)){
delete infos.commands[k]
break
}
}
}
if (k == '_execute_browser_action' || k == '_execute_page_action') continue
if (!v.description) v.description = "description"
}
}
copyModifyFile(verPath,flagContent,flagBackground,isWebExt)
fs.unlinkSync(manifestPath)
fs.writeFileSync(manifestPath,JSON.stringify(infos, null, ' '))
console.log(33332001)
for(let svg of require("glob").sync(`${verPath}/**/*.svg`)){
const out = svg.replace(/\.svg$/,".png")
if(!fs.existsSync(out)){
if(!open){
imageResize.open({width: 16, height: 16})
open = true
}
console.log(`file://${svg}`)
const url = path.join(path.parse(svg).dir,'svg.html')
fs.writeFileSync(url,`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style type="text/css">
img,svg{
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<img src="${svg}"/>
</body>
</html>`)
const img = await imageResize.capture({url: `file://${url}`, width: 16, height: 16})
Jimp.read(img.toPNG(), function (err, image) {
if(image.bitmap.width > image.bitmap.height){
image = image.resize(16,Jimp.AUTO,Jimp.RESIZE_BICUBIC)
}
else{
image = image.resize(Jimp.AUTO,16,Jimp.RESIZE_BICUBIC)
}
image.write(out)
})
}
}
if(open) imageResize.close()
}catch(e){
if(open) imageResize.close()
console.log(33332002,e)
}
// if(isWebExt){
// for(let js of require("glob").sync(`${verPath}/**/*.js`)){
// const datas = fs.readFileSync(js).toString()
// if(datas.match(/document.execCommand\( *(["'])copy\1 *\)/)){
// const result = datas.replace(/document.execCommand\( *(["'])copy\1 *\)/,`chrome.ipcRenderer.send('execCommand-copy')`)
// fs.writeFileSync(js, result)
// }
// }
// }
}
}
| kura52/sushi-browser | src/chromeManifestModify.js | JavaScript | gpl-3.0 | 11,818 |
HostCMS 6.7 = 2d5da5db37e69bb24965125a6471caac
| gohdan/DFC | known_files/hashes/hostcmsfiles/lib/lib_30/lib_30.php | PHP | gpl-3.0 | 47 |
# -*- coding: utf-8 -*-
from bottle import run, get, post, view, request, redirect, route, static_file, template
import bottle
import json
import threading
import requests
import time
import sys
messages = set([])
@bottle.route('/static/<path:path>')
def server_static(path):
return static_file(path, root='static')
@get('/chat')
@view('chat')
def chat():
name = request.query.name
return dict(msg=list(messages), name=name)
@route('/')
def index():
redirect('chat')
@post('/send')
def sendmsg():
name = request.forms.getunicode('name')
msg = request.forms.getunicode('msg')
global messages
if name != None and msg != None:
messages.add((name, msg))
redirect('chat?name=' + name)
else:
redirect('chat')
run(host='localhost', port=int(sys.argv[1]))
| jpwbernardi/Computacao-Distribuida | Trabalho1/main.py | Python | gpl-3.0 | 816 |
<?php
namespace ApacheSolrForTypo3\Solr\System\Language;
/***************************************************************
* Copyright notice
*
* (c) 2018 Timo Hund <timo.hund@dkd.de>
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
use ApacheSolrForTypo3\Solr\System\TCA\TCAService;
use ApacheSolrForTypo3\Solr\Util;
use TYPO3\CMS\Core\Context\Exception\AspectNotFoundException;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
/**
* Class FrontendOverlayService
*/
class FrontendOverlayService
{
/**
* @var TCAService
*/
protected $tcaService = null;
/**
* @var TypoScriptFrontendController|null
*/
protected ?TypoScriptFrontendController $tsfe = null;
/**
* Relation constructor.
* @param TCAService|null $tcaService
* @param TypoScriptFrontendController|null $tsfe
*/
public function __construct(TCAService $tcaService = null, TypoScriptFrontendController $tsfe = null)
{
$this->tcaService = $tcaService ?? GeneralUtility::makeInstance(TCAService::class);
$this->tsfe = $tsfe;
}
/**
* Return the translated record
*
* @param string $tableName
* @param array $record
* @return array
* @throws AspectNotFoundException
*/
public function getOverlay(string $tableName, array $record): ?array
{
$currentLanguageUid = $this->tsfe->getContext()->getPropertyFromAspect('language', 'id');
if ($tableName === 'pages') {
// @extensionScannerIgnoreLine
return $this->tsfe->sys_page->getPageOverlay($record, $currentLanguageUid);
}
// @extensionScannerIgnoreLine
return $this->tsfe->sys_page->getRecordOverlay($tableName, $record, $currentLanguageUid);
}
/**
* When the record has an overlay we retrieve the uid of the translated record,
* to resolve the relations from the translation.
*
* @param string $table
* @param string $field
* @param int $uid
* @return int
* @throws AspectNotFoundException
*/
public function getUidOfOverlay(string $table, string $field, int $uid): int
{
$contextsLanguageId = $this->tsfe->getContext()->getPropertyFromAspect('language', 'id');
// when no language is set at all we do not need to overlay
if ($contextsLanguageId === null) {
return $uid;
}
// when no language is set we can return the passed recordUid
if (!($contextsLanguageId > 0)) {
return $uid;
}
$record = $this->getRecord($table, $uid);
// when the overlay is not an array, we return the localRecordUid
if (!is_array($record)) {
return $uid;
}
$overlayUid = $this->getLocalRecordUidFromOverlay($table, $record);
return ($overlayUid !== 0) ? $overlayUid : $uid;
}
/**
* This method retrieves the _PAGES_OVERLAY_UID or _LOCALIZED_UID from the localized record.
*
* @param string $localTableName
* @param array $originalRecord
* @return int
* @throws AspectNotFoundException
*/
protected function getLocalRecordUidFromOverlay(string $localTableName, array $originalRecord): int
{
$overlayRecord = $this->getOverlay($localTableName, $originalRecord);
// when there is a _PAGES_OVERLAY_UID | _LOCALIZED_UID in the overlay, we return it
if ($localTableName === 'pages' && isset($overlayRecord['_PAGES_OVERLAY_UID'])) {
return (int)$overlayRecord['_PAGES_OVERLAY_UID'];
} elseif (isset($overlayRecord['_LOCALIZED_UID'])) {
return (int)$overlayRecord['_LOCALIZED_UID'];
}
return 0;
}
/**
* @param $localTableName
* @param $localRecordUid
* @return mixed
*/
protected function getRecord($localTableName, $localRecordUid)
{
/* @var QueryBuilder $queryBuilder */
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($localTableName);
return $queryBuilder->select('*')->from($localTableName)->where($queryBuilder->expr()->eq('uid', $localRecordUid))->execute()->fetch();
}
}
| dkd-kaehm/ext-solr | Classes/System/Language/FrontendOverlayService.php | PHP | gpl-3.0 | 5,124 |
507. Perfect Number
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
Example:
Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14
Note: The input number n will not exceed 100,000,000. (1e8)
题目大意:完美数字是指它的所有可以整除的正数中除了它本身,其他数字之和等于这个数字的数。给一个正整数n,写一个函数,当它是一个完美数字的时候返回true否则false。
分析:从2~sqrt(num),累加所有i和num/i【因为如果从1~num一个个试是否可以整除的话会超时,而且也没必要,因为知道了除数a必然就知道了num/a这个数字也是它的除数】因为最后还有一个1没有加,所以sum一开始为1,然后返回num == sum,注意如果num本身为1,则要return false,因为1的唯一一个除数1是它本身不能累加,所以1不满足条件。
class Solution {
public:
bool checkPerfectNumber(int num) {
if (num == 1) return false;
int sum = 1;
for (int i = 2; i <= sqrt(num); i++)
if (num % i == 0) sum = sum + (num / i) + i;
return num == sum;
}
}; | liuchuo/LeetCode-practice | C++/507. Perfect Number.cpp | C++ | gpl-3.0 | 1,316 |
Bitrix 16.5 Business Demo = 818811a8ef1a847b4775a91e2db1876b
Bitrix 17.0.9 Business Demo = 5c5c79041601a158a8e904e0cc966e79
| gohdan/DFC | known_files/hashes/bitrix/modules/main/classes/mysql/database.php | PHP | gpl-3.0 | 124 |
#!/usr/bin/python3
'''
This is a simple example of how to use the dbm.gnu module of the
standard python library
NOTES:
- the attempt to insert None as value throws an exception.
so only strings and bytes are allowed.
'''
import dbm.gnu # for open
# the 'c' in the next row means open rw and create if it doesn't exist
d = dbm.gnu.open('/tmp/foo.gdbm', 'c')
d['one'] = 'ehad'
d['two'] = 'shtaim'
d['three'] = None
d.close()
| nonZero/demos-python | src/examples/short/dbm/gdbm_insert.py | Python | gpl-3.0 | 431 |
package jamel.models.util;
/**
* Represents a labor contract.
*/
public interface JobContract {
/**
* Breaks the contract.
*/
void breach();
/**
* Returns the starting period of this contract.
*
* @return the starting period of this contract.
*/
int getStart();
/**
* Returns the wage.
*
* @return the wage.
*/
long getWage();
/**
* Returns the worker.
*
* @return the worker.
*/
Worker getWorker();
/**
* Returns {@code true} if the contract is valid, {@code false}
* otherwise.
*
* @return {@code true} if the contract is valid, {@code false}
* otherwise.
*/
boolean isValid();
}
| pseppecher/jamel | src/jamel/models/util/JobContract.java | Java | gpl-3.0 | 653 |
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2017 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 builtin
import (
"strings"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/interfaces/apparmor"
"github.com/snapcore/snapd/interfaces/dbus"
"github.com/snapcore/snapd/interfaces/seccomp"
"github.com/snapcore/snapd/interfaces/udev"
"github.com/snapcore/snapd/snap"
)
const udisks2Summary = `allows operating as or interacting with the UDisks2 service`
const udisks2BaseDeclarationSlots = `
udisks2:
allow-installation:
slot-snap-type:
- app
deny-connection: true
deny-auto-connection: true
`
const udisks2PermanentSlotAppArmor = `
# Description: Allow operating as the udisks2. This gives privileged access to
# the system.
# DBus accesses
#include <abstractions/dbus-strict>
dbus (send)
bus=system
path=/org/freedesktop/DBus
interface=org.freedesktop.DBus
member="{Request,Release}Name"
peer=(name=org.freedesktop.DBus, label=unconfined),
dbus (send)
bus=system
path=/org/freedesktop/DBus
interface=org.freedesktop.DBus
member="GetConnectionUnix{ProcessID,User}"
peer=(label=unconfined),
# Allow binding the service to the requested connection name
dbus (bind)
bus=system
name="org.freedesktop.UDisks2",
# Allow unconfined to talk to us. The API for unconfined will be limited
# with DBus policy, below.
dbus (receive, send)
bus=system
path=/org/freedesktop/UDisks2{,/**}
interface=org.freedesktop.DBus*
peer=(label=unconfined),
# Needed for mount/unmount operations
capability sys_admin,
# Allow scanning of devices
network netlink raw,
/run/udev/data/b[0-9]*:[0-9]* r,
/sys/devices/**/block/** r,
# Mount points could be in /run/media/<user>/* or /media/<user>/*
/run/systemd/seats/* r,
/{,run/}media/{,**} rw,
mount options=(ro,nosuid,nodev) /dev/{sd*,mmcblk*} -> /{,run/}media/**,
mount options=(rw,nosuid,nodev) /dev/{sd*,mmcblk*} -> /{,run/}media/**,
umount /{,run/}media/**,
# This should probably be patched to use $SNAP_DATA/run/...
/run/udisks2/{,**} rw,
# udisksd execs mount/umount to do the actual operations
/bin/mount ixr,
/bin/umount ixr,
# mount/umount (via libmount) track some mount info in these files
/run/mount/utab* wrl,
# Udisks2 needs to read the raw device for partition information. These rules
# give raw read access to the system disks and therefore the entire system.
/dev/sd* r,
/dev/mmcblk* r,
/dev/vd* r,
# Needed for probing raw devices
capability sys_rawio,
`
const udisks2ConnectedSlotAppArmor = `
# Allow connected clients to interact with the service. This gives privileged
# access to the system.
dbus (receive, send)
bus=system
path=/org/freedesktop/UDisks2/**
interface=org.freedesktop.DBus.Properties
peer=(label=###PLUG_SECURITY_TAGS###),
dbus (receive, send)
bus=system
path=/org/freedesktop/UDisks2
interface=org.freedesktop.DBus.ObjectManager
peer=(label=###PLUG_SECURITY_TAGS###),
# Allow access to the Udisks2 API
dbus (receive, send)
bus=system
path=/org/freedesktop/UDisks2/**
interface=org.freedesktop.UDisks2.*
peer=(label=###PLUG_SECURITY_TAGS###),
# Allow clients to introspect the service
dbus (receive)
bus=system
path=/org/freedesktop/UDisks2
interface=org.freedesktop.DBus.Introspectable
member=Introspect
peer=(label=###PLUG_SECURITY_TAGS###),
`
const udisks2ConnectedPlugAppArmor = `
# Description: Allow using udisks service. This gives privileged access to the
# service.
#include <abstractions/dbus-strict>
dbus (receive, send)
bus=system
path=/org/freedesktop/UDisks2/**
interface=org.freedesktop.DBus.Properties
peer=(label=###SLOT_SECURITY_TAGS###),
dbus (receive, send)
bus=system
path=/org/freedesktop/UDisks2
interface=org.freedesktop.DBus.ObjectManager
peer=(label=###SLOT_SECURITY_TAGS###),
# Allow access to the Udisks2 API
dbus (receive, send)
bus=system
path=/org/freedesktop/UDisks2/**
interface=org.freedesktop.UDisks2.*
peer=(label=###SLOT_SECURITY_TAGS###),
# Allow clients to introspect the service
dbus (send)
bus=system
path=/org/freedesktop/UDisks2
interface=org.freedesktop.DBus.Introspectable
member=Introspect
peer=(label=###SLOT_SECURITY_TAGS###),
`
const udisks2PermanentSlotSecComp = `
bind
chown32
fchown
fchown32
fchownat
lchown
lchown32
mount
shmctl
umount
umount2
# libudev
socket AF_NETLINK - NETLINK_KOBJECT_UEVENT
`
const udisks2PermanentSlotDBus = `
<policy user="root">
<allow own="org.freedesktop.UDisks2"/>
<allow send_destination="org.freedesktop.UDisks2"/>
</policy>
<policy context="default">
<allow send_destination="org.freedesktop.UDisks2" send_interface="org.freedesktop.DBus.Introspectable" />
</policy>
`
const udisks2ConnectedPlugDBus = `
<policy context="default">
<deny own="org.freedesktop.UDisks2"/>
<deny send_destination="org.freedesktop.UDisks2"/>
</policy>
`
const udisks2PermanentSlotUDev = `
# These udev rules come from the upstream udisks2 package
#
# This file contains udev rules for udisks 2.x
#
# Do not edit this file, it will be overwritten on updates
#
# ------------------------------------------------------------------------
# Probing
# ------------------------------------------------------------------------
# Skip probing if not a block device or if requested by other rules
#
SUBSYSTEM!="block", GOTO="udisks_probe_end"
ENV{DM_MULTIPATH_DEVICE_PATH}=="?*", GOTO="udisks_probe_end"
ENV{DM_UDEV_DISABLE_OTHER_RULES_FLAG}=="?*", GOTO="udisks_probe_end"
# MD-RAID (aka Linux Software RAID) members
#
# TODO: file bug against mdadm(8) to have --export-prefix option that can be used with e.g. UDISKS_MD_MEMBER
#
SUBSYSTEM=="block", ENV{ID_FS_USAGE}=="raid", ENV{ID_FS_TYPE}=="linux_raid_member", ENV{UDISKS_MD_MEMBER_LEVEL}=="", IMPORT{program}="/bin/sh -c '/sbin/mdadm --examine --export $tempnode | sed s/^MD_/UDISKS_MD_MEMBER_/g'"
SUBSYSTEM=="block", KERNEL=="md*", ENV{DEVTYPE}!="partition", IMPORT{program}="/bin/sh -c '/sbin/mdadm --detail --export $tempnode | sed s/^MD_/UDISKS_MD_/g'"
LABEL="udisks_probe_end"
# ------------------------------------------------------------------------
# Tag floppy drives since they need special care
# PC floppy drives
#
KERNEL=="fd*", ENV{ID_DRIVE_FLOPPY}="1"
# USB floppy drives
#
SUBSYSTEMS=="usb", ATTRS{bInterfaceClass}=="08", ATTRS{bInterfaceSubClass}=="04", ENV{ID_DRIVE_FLOPPY}="1"
# ATA Zip drives
#
ENV{ID_VENDOR}=="*IOMEGA*", ENV{ID_MODEL}=="*ZIP*", ENV{ID_DRIVE_FLOPPY_ZIP}="1"
# TODO: figure out if the drive supports SD and SDHC and what the current
# kind of media is - right now we just assume SD
KERNEL=="mmcblk[0-9]", SUBSYSTEMS=="mmc", ENV{DEVTYPE}=="disk", ENV{ID_DRIVE_FLASH_SD}="1", ENV{ID_DRIVE_MEDIA_FLASH_SD}="1"
# ditto for memstick
KERNEL=="mspblk[0-9]", SUBSYSTEMS=="memstick", ENV{DEVTYPE}=="disk", ENV{ID_DRIVE_FLASH_MS}="1", ENV{ID_DRIVE_MEDIA_FLASH_MS}="1"
# TODO: maybe automatically convert udisks1 properties to udisks2 ones?
# (e.g. UDISKS_PRESENTATION_HIDE -> UDISKS_IGNORE)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
# Whitelist for tagging drives with the property media type.
# TODO: figure out where to store this database
SUBSYSTEMS=="usb", ATTRS{idVendor}=="050d", ATTRS{idProduct}=="0248", ENV{ID_INSTANCE}=="0:0", ENV{ID_DRIVE_FLASH_CF}="1"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="050d", ATTRS{idProduct}=="0248", ENV{ID_INSTANCE}=="0:1", ENV{ID_DRIVE_FLASH_MS}="1"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="050d", ATTRS{idProduct}=="0248", ENV{ID_INSTANCE}=="0:2", ENV{ID_DRIVE_FLASH_SM}="1"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="050d", ATTRS{idProduct}=="0248", ENV{ID_INSTANCE}=="0:3", ENV{ID_DRIVE_FLASH_SD}="1"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="05e3", ATTRS{idProduct}=="070e", ENV{ID_INSTANCE}=="0:0", ENV{ID_DRIVE_FLASH_CF}="1"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="05e3", ATTRS{idProduct}=="070e", ENV{ID_INSTANCE}=="0:1", ENV{ID_DRIVE_FLASH_SM}="1"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="05e3", ATTRS{idProduct}=="070e", ENV{ID_INSTANCE}=="0:2", ENV{ID_DRIVE_FLASH_SD}="1"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="05e3", ATTRS{idProduct}=="070e", ENV{ID_INSTANCE}=="0:3", ENV{ID_DRIVE_FLASH_MS}="1"
# APPLE SD Card Reader (MacbookPro5,4)
#
SUBSYSTEMS=="usb", ATTRS{idVendor}=="05ac", ATTRS{idProduct}=="8403", ENV{ID_DRIVE_FLASH_SD}="1"
# Realtek card readers
DRIVERS=="rts_pstor", ENV{ID_DRIVE_FLASH_SD}="1"
DRIVERS=="rts5229", ENV{ID_DRIVE_FLASH_SD}="1"
# Lexar Dual Slot USB 3.0 Reader Professional
SUBSYSTEMS=="usb", ENV{ID_VENDOR_ID}=="05dc",ENV{ID_MODEL_ID}=="b049", ENV{ID_INSTANCE}=="0:0", ENV{ID_DRIVE_FLASH_CF}="1"
SUBSYSTEMS=="usb", ENV{ID_VENDOR_ID}=="05dc",ENV{ID_MODEL_ID}=="b049", ENV{ID_INSTANCE}=="0:1", ENV{ID_DRIVE_FLASH_SD}="1"
# Transcend USB 3.0 Multi-Card Reader (TS-RDF8K)
SUBSYSTEMS=="usb", ENV{ID_VENDOR_ID}=="8564",ENV{ID_MODEL_ID}=="4000", ENV{ID_INSTANCE}=="0:0", ENV{ID_DRIVE_FLASH_CF}="1"
SUBSYSTEMS=="usb", ENV{ID_VENDOR_ID}=="8564",ENV{ID_MODEL_ID}=="4000", ENV{ID_INSTANCE}=="0:1", ENV{ID_DRIVE_FLASH_SD}="1"
SUBSYSTEMS=="usb", ENV{ID_VENDOR_ID}=="8564",ENV{ID_MODEL_ID}=="4000", ENV{ID_INSTANCE}=="0:2", ENV{ID_DRIVE_FLASH_MS}="1"
# Common theme
#
SUBSYSTEMS=="usb", ENV{ID_MODEL}=="*Reader*SD*", ENV{ID_DRIVE_FLASH_SD}="1"
SUBSYSTEMS=="usb", ENV{ID_MODEL}=="*CF_Reader*", ENV{ID_DRIVE_FLASH_CF}="1"
SUBSYSTEMS=="usb", ENV{ID_MODEL}=="*SM_Reader*", ENV{ID_DRIVE_FLASH_SM}="1"
SUBSYSTEMS=="usb", ENV{ID_MODEL}=="*MS_Reader*", ENV{ID_DRIVE_FLASH_MS}="1"
# USB stick / thumb drives
#
SUBSYSTEMS=="usb", ENV{ID_VENDOR}=="*Kingston*", ENV{ID_MODEL}=="*DataTraveler*", ENV{ID_DRIVE_THUMB}="1"
SUBSYSTEMS=="usb", ENV{ID_VENDOR}=="*SanDisk*", ENV{ID_MODEL}=="*Cruzer*", ENV{ID_CDROM}!="1", ENV{ID_DRIVE_THUMB}="1"
SUBSYSTEMS=="usb", ENV{ID_VENDOR}=="HP", ENV{ID_MODEL}=="*v125w*", ENV{ID_DRIVE_THUMB}="1"
SUBSYSTEMS=="usb", ENV{ID_VENDOR_ID}=="13fe", ENV{ID_MODEL}=="*Patriot*", ENV{ID_DRIVE_THUMB}="1"
SUBSYSTEMS=="usb", ENV{ID_VENDOR}=="*JetFlash*", ENV{ID_MODEL}=="*Transcend*", ENV{ID_DRIVE_THUMB}="1"
# SD-Card reader in Chromebook Pixel
SUBSYSTEMS=="usb", ENV{ID_VENDOR_ID}=="05e3", ENV{ID_MODEL_ID}=="0727", ENV{ID_DRIVE_FLASH_SD}="1"
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
# Devices which should not be display in the user interface
#
# (note that RAID/LVM members are not normally shown in an user
# interface so setting UDISKS_IGNORE at first does not seem to achieve
# anything. However it helps for RAID/LVM members that are encrypted
# using LUKS. See bug #51439.)
# Apple Bootstrap partitions
ENV{ID_PART_ENTRY_SCHEME}=="mac", ENV{ID_PART_ENTRY_TYPE}=="Apple_Bootstrap", ENV{UDISKS_IGNORE}="1"
# Apple Boot partitions
ENV{ID_PART_ENTRY_SCHEME}=="gpt", ENV{ID_PART_ENTRY_TYPE}=="426f6f74-0000-11aa-aa11-00306543ecac", ENV{UDISKS_IGNORE}="1"
# special DOS partition types (EFI, hidden, etc.) and RAID/LVM
# see http://www.win.tue.nl/~aeb/partitions/partition_types-1.html
ENV{ID_PART_ENTRY_SCHEME}=="dos", \
ENV{ID_PART_ENTRY_TYPE}=="0x0|0x11|0x12|0x14|0x16|0x17|0x1b|0x1c|0x1e|0x27|0x3d|0x84|0x8d|0x8e|0x90|0x91|0x92|0x93|0x97|0x98|0x9a|0x9b|0xbb|0xc2|0xc3|0xdd|0xef|0xfd", \
ENV{UDISKS_IGNORE}="1"
# special GUID-identified partition types (EFI System Partition, BIOS Boot partition, RAID/LVM)
# see http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs
ENV{ID_PART_ENTRY_SCHEME}=="gpt", \
ENV{ID_PART_ENTRY_TYPE}=="c12a7328-f81f-11d2-ba4b-00a0c93ec93b|21686148-6449-6e6f-744e-656564454649|a19d880f-05fc-4d3b-a006-743f0f84911e|e6d6d379-f507-44c2-a23c-238f2a3df928|e3c9e316-0b5c-4db8-817d-f92df00215ae|de94bba4-06d1-4d40-a16a-bfd50179d6ac", \
ENV{UDISKS_IGNORE}="1"
# MAC recovery/tool partitions which are useless on Linux
ENV{ID_PART_ENTRY_SCHEME}=="mac", \
ENV{ID_CDROM}=="?*", ENV{ID_FS_TYPE}=="udf", ENV{ID_FS_LABEL}=="WD*SmartWare", \
ENV{UDISKS_IGNORE}="1"
# recovery partitions
ENV{ID_FS_TYPE}=="ntfs|vfat", \
ENV{ID_FS_LABEL}=="Recovery|RECOVERY|Lenovo_Recovery|HP_RECOVERY|Recovery_Partition|DellUtility|DellRestore|IBM_SERVICE|SERVICEV001|SERVICEV002|SYSTEM_RESERVED|System_Reserved|WINRE_DRV|DIAGS|IntelRST", \
ENV{UDISKS_IGNORE}="1"
# read-only non-Linux software installer partitions
ENV{ID_VENDOR}=="Sony", ENV{ID_MODEL}=="PRS*Launcher", ENV{UDISKS_IGNORE}="1"
# non-Linux software
KERNEL=="sr*", ENV{ID_VENDOR}=="SanDisk", ENV{ID_MODEL}=="Cruzer", ENV{ID_FS_LABEL}=="U3_System", ENV{UDISKS_IGNORE}="1"
# Content created using isohybrid (typically used on CDs and USB
# sticks for bootable media) is a bit special insofar that the
# interesting content is on a DOS partition with type 0x00 ... which
# is hidden above. So undo this.
#
# See http://mjg59.dreamwidth.org/11285.html for more details
#
ENV{ID_PART_TABLE_TYPE}=="dos", ENV{ID_PART_ENTRY_TYPE}=="0x0", ENV{ID_PART_ENTRY_NUMBER}=="1", ENV{ID_FS_TYPE}=="iso9660|udf", ENV{UDISKS_IGNORE}="0"
`
type udisks2Interface struct{}
func (iface *udisks2Interface) Name() string {
return "udisks2"
}
func (iface *udisks2Interface) StaticInfo() interfaces.StaticInfo {
return interfaces.StaticInfo{
Summary: udisks2Summary,
BaseDeclarationSlots: udisks2BaseDeclarationSlots,
}
}
func (iface *udisks2Interface) DBusConnectedPlug(spec *dbus.Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error {
spec.AddSnippet(udisks2ConnectedPlugDBus)
return nil
}
func (iface *udisks2Interface) DBusPermanentSlot(spec *dbus.Specification, slot *snap.SlotInfo) error {
spec.AddSnippet(udisks2PermanentSlotDBus)
return nil
}
func (iface *udisks2Interface) AppArmorConnectedPlug(spec *apparmor.Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error {
old := "###SLOT_SECURITY_TAGS###"
new := slotAppLabelExpr(slot)
snippet := strings.Replace(udisks2ConnectedPlugAppArmor, old, new, -1)
spec.AddSnippet(snippet)
return nil
}
func (iface *udisks2Interface) AppArmorPermanentSlot(spec *apparmor.Specification, slot *snap.SlotInfo) error {
spec.AddSnippet(udisks2PermanentSlotAppArmor)
return nil
}
func (iface *udisks2Interface) UDevPermanentSlot(spec *udev.Specification, slot *snap.SlotInfo) error {
spec.AddSnippet(udisks2PermanentSlotUDev)
spec.TagDevice(`SUBSYSTEM=="block"`)
// # This tags all USB devices, so we'll use AppArmor to mediate specific access (eg, /dev/sd* and /dev/mmcblk*)
spec.TagDevice(`SUBSYSTEM=="usb"`)
return nil
}
func (iface *udisks2Interface) AppArmorConnectedSlot(spec *apparmor.Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error {
old := "###PLUG_SECURITY_TAGS###"
new := plugAppLabelExpr(plug)
snippet := strings.Replace(udisks2ConnectedSlotAppArmor, old, new, -1)
spec.AddSnippet(snippet)
return nil
}
func (iface *udisks2Interface) SecCompPermanentSlot(spec *seccomp.Specification, slot *snap.SlotInfo) error {
spec.AddSnippet(udisks2PermanentSlotSecComp)
return nil
}
func (iface *udisks2Interface) AutoConnect(*snap.PlugInfo, *snap.SlotInfo) bool {
// allow what declarations allowed
return true
}
func init() {
registerIface(&udisks2Interface{})
}
| Conan-Kudo/snapd | interfaces/builtin/udisks2.go | GO | gpl-3.0 | 16,059 |
import gc
import os
import argparse
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from util import generate_features
def get_arguments():
parser = argparse.ArgumentParser(description='Generate features using a previously trained model')
parser.add_argument('data', type=str, help='File containing the input smiles matrices')
parser.add_argument('model', type=str, help='The model file')
parser.add_argument('features', type=str, help='Output file that will contain the generated features')
parser.add_argument('--batch_size', type=int, default=100, help='Size of the batches (default: 100)')
return parser.parse_args()
args = get_arguments()
generate_features.generate_features(args.data, args.model, args.features, args.batch_size)
gc.collect()
| patrick-winter-knime/deep-learning-on-molecules | smiles-vhts/generate_features.py | Python | gpl-3.0 | 769 |
package net.minecraft.Server1_7_10.command.server;
import com.mojang.authlib.GameProfile;
import java.util.List;
import net.minecraft.Server1_7_10.command.CommandBase;
import net.minecraft.Server1_7_10.command.CommandException;
import net.minecraft.Server1_7_10.command.ICommandSender;
import net.minecraft.Server1_7_10.command.WrongUsageException;
import net.minecraft.Server1_7_10.server.MinecraftServer;
import net.minecraft.Server1_7_10.util.ChatComponentText;
import net.minecraft.Server1_7_10.util.ChatComponentTranslation;
public class CommandWhitelist extends CommandBase
{
private static final String __OBFID = "CL_00001186";
public String getCommandName()
{
return "whitelist";
}
/**
* Return the required permission level for this command.
*/
public int getRequiredPermissionLevel()
{
return 3;
}
public String getCommandUsage(ICommandSender p_71518_1_)
{
return "commands.whitelist.usage";
}
public void processCommand(ICommandSender p_71515_1_, String[] p_71515_2_)
{
if (p_71515_2_.length >= 1)
{
MinecraftServer var3 = MinecraftServer.getServer();
if (p_71515_2_[0].equals("on"))
{
var3.getConfigurationManager().setWhiteListEnabled(true);
func_152373_a(p_71515_1_, this, "commands.whitelist.enabled", new Object[0]);
return;
}
if (p_71515_2_[0].equals("off"))
{
var3.getConfigurationManager().setWhiteListEnabled(false);
func_152373_a(p_71515_1_, this, "commands.whitelist.disabled", new Object[0]);
return;
}
if (p_71515_2_[0].equals("list"))
{
p_71515_1_.addChatMessage(new ChatComponentTranslation("commands.whitelist.list", new Object[] {Integer.valueOf(var3.getConfigurationManager().func_152598_l().length), Integer.valueOf(var3.getConfigurationManager().getAvailablePlayerDat().length)}));
String[] var5 = var3.getConfigurationManager().func_152598_l();
p_71515_1_.addChatMessage(new ChatComponentText(joinNiceString(var5)));
return;
}
GameProfile var4;
if (p_71515_2_[0].equals("add"))
{
if (p_71515_2_.length < 2)
{
throw new WrongUsageException("commands.whitelist.add.usage", new Object[0]);
}
var4 = var3.func_152358_ax().func_152655_a(p_71515_2_[1]);
if (var4 == null)
{
throw new CommandException("commands.whitelist.add.failed", new Object[] {p_71515_2_[1]});
}
var3.getConfigurationManager().func_152601_d(var4);
func_152373_a(p_71515_1_, this, "commands.whitelist.add.success", new Object[] {p_71515_2_[1]});
return;
}
if (p_71515_2_[0].equals("remove"))
{
if (p_71515_2_.length < 2)
{
throw new WrongUsageException("commands.whitelist.remove.usage", new Object[0]);
}
var4 = var3.getConfigurationManager().func_152599_k().func_152706_a(p_71515_2_[1]);
if (var4 == null)
{
throw new CommandException("commands.whitelist.remove.failed", new Object[] {p_71515_2_[1]});
}
var3.getConfigurationManager().func_152597_c(var4);
func_152373_a(p_71515_1_, this, "commands.whitelist.remove.success", new Object[] {p_71515_2_[1]});
return;
}
if (p_71515_2_[0].equals("reload"))
{
var3.getConfigurationManager().loadWhiteList();
func_152373_a(p_71515_1_, this, "commands.whitelist.reloaded", new Object[0]);
return;
}
}
throw new WrongUsageException("commands.whitelist.usage", new Object[0]);
}
/**
* Adds the strings available in this command to the given list of tab completion options.
*/
public List addTabCompletionOptions(ICommandSender p_71516_1_, String[] p_71516_2_)
{
if (p_71516_2_.length == 1)
{
return getListOfStringsMatchingLastWord(p_71516_2_, new String[] {"on", "off", "list", "add", "remove", "reload"});
}
else
{
if (p_71516_2_.length == 2)
{
if (p_71516_2_[0].equals("remove"))
{
return getListOfStringsMatchingLastWord(p_71516_2_, MinecraftServer.getServer().getConfigurationManager().func_152598_l());
}
if (p_71516_2_[0].equals("add"))
{
return getListOfStringsMatchingLastWord(p_71516_2_, MinecraftServer.getServer().func_152358_ax().func_152654_a());
}
}
return null;
}
}
}
| TheHecticByte/BananaJ1.7.10Beta | src/net/minecraft/Server1_7_10/command/server/CommandWhitelist.java | Java | gpl-3.0 | 5,087 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="uk_UA" version="2.1">
<context>
<name>GM_AddScriptDialog</name>
<message>
<location filename="../gm_addscriptdialog.ui" line="14"/>
<source>GreaseMonkey Installation</source>
<translation>Встановлення GreaseMonkey</translation>
</message>
<message>
<location filename="../gm_addscriptdialog.ui" line="51"/>
<source><h3>GreaseMonkey Installation</h3></source>
<translation><h3>Встановлення GreaseMonkey</h3></translation>
</message>
<message>
<location filename="../gm_addscriptdialog.ui" line="73"/>
<source>You are about to install this userscript into GreaseMonkey:</source>
<translation>Ви збираєтесь встановити наступний скрипт до GreaseMonkey:</translation>
</message>
<message>
<location filename="../gm_addscriptdialog.ui" line="86"/>
<source><b>You should only install scripts from sources you trust!</b></source>
<translation><b>Встановлюйте скрипти лише з ресурсів яким довіряєте!</b></translation>
</message>
<message>
<location filename="../gm_addscriptdialog.ui" line="96"/>
<source>Are you sure you want to install it?</source>
<translation>Ви впевнені, що хочете встановити цей скрипт?</translation>
</message>
<message>
<location filename="../gm_addscriptdialog.ui" line="114"/>
<source>Show source code of script</source>
<translation>Показати вихідний код скрипту</translation>
</message>
<message>
<location filename="../gm_addscriptdialog.cpp" line="49"/>
<source><p>runs at<br/><i>%1</i></p></source>
<translation><p>запускається на<br/><i>%1</i></p></translation>
</message>
<message>
<location filename="../gm_addscriptdialog.cpp" line="53"/>
<source><p>does not run at<br/><i>%1</i></p></source>
<translation><p>не запускається на<br/><i>%1</i></p></translation>
</message>
<message>
<location filename="../gm_addscriptdialog.cpp" line="83"/>
<source>Cannot install script</source>
<translation>Неможливо встановити скрипт</translation>
</message>
<message>
<location filename="../gm_addscriptdialog.cpp" line="86"/>
<source>'%1' installed successfully</source>
<translation>'%1' успішно встановлено</translation>
</message>
</context>
<context>
<name>GM_Icon</name>
<message>
<location filename="../gm_icon.cpp" line="29"/>
<source>Open GreaseMonkey settings</source>
<translation>Відкрити налаштування GreaseMonkey</translation>
</message>
</context>
<context>
<name>GM_Manager</name>
<message>
<location filename="../gm_manager.cpp" line="206"/>
<source>GreaseMonkey</source>
<translation>GreaseMonkey</translation>
</message>
<message>
<location filename="../gm_manager.cpp" line="270"/>
<source>'%1' is already installed</source>
<translation>'%1' уже встановлено</translation>
</message>
</context>
<context>
<name>GM_Notification</name>
<message>
<location filename="../gm_notification.ui" line="45"/>
<source>This script can be installed with the GreaseMonkey plugin.</source>
<translation>Цей скрипт можливо встановити за допомогою GreaseMonkey.</translation>
</message>
<message>
<location filename="../gm_notification.ui" line="65"/>
<source>Install</source>
<translation>Встановити</translation>
</message>
<message>
<location filename="../gm_notification.cpp" line="50"/>
<source>Cannot install script</source>
<translation>Неможливо встановити скрипт</translation>
</message>
<message>
<location filename="../gm_notification.cpp" line="58"/>
<source>'%1' installed successfully</source>
<translation>'%1' успішно встановлено</translation>
</message>
</context>
<context>
<name>GM_Settings</name>
<message>
<location filename="../settings/gm_settings.ui" line="14"/>
<source>GreaseMonkey Scripts</source>
<translation>Скрипти GreaseMonkey</translation>
</message>
<message>
<location filename="../settings/gm_settings.ui" line="51"/>
<source><h3>GreaseMonkey Scripts</h3></source>
<translation><h3>Скрипти GreaseMonkey</h3></translation>
</message>
<message>
<location filename="../settings/gm_settings.ui" line="73"/>
<source>Double clicking script will show additional information</source>
<translation>Щоб отримати додавткову інформацію про скрипт - двічі клікніть на ньому</translation>
</message>
<message>
<location filename="../settings/gm_settings.ui" line="153"/>
<source>More scripts can be downloaded from</source>
<translation>Більше скриптів можна завантажити з</translation>
</message>
<message>
<location filename="../settings/gm_settings.ui" line="196"/>
<source>Open scripts directory</source>
<translation>Відкрити папку зі скриптами</translation>
</message>
<message>
<location filename="../settings/gm_settings.ui" line="203"/>
<source>New user script</source>
<translation>Новий користувацький скрипт</translation>
</message>
<message>
<location filename="../settings/gm_settings.cpp" line="90"/>
<source>Remove script</source>
<translation>Видалити скрипт</translation>
</message>
<message>
<location filename="../settings/gm_settings.cpp" line="91"/>
<source>Are you sure you want to remove '%1'?</source>
<translation>Ви впевнені, що хїочете видалити '%1'?</translation>
</message>
<message>
<location filename="../settings/gm_settings.cpp" line="121"/>
<source>Add script</source>
<translation>Додати скрипт</translation>
</message>
<message>
<location filename="../settings/gm_settings.cpp" line="121"/>
<source>Choose name for script:</source>
<translation>Виберіть назву скрипту</translation>
</message>
</context>
<context>
<name>GM_SettingsScriptInfo</name>
<message>
<location filename="../settings/gm_settingsscriptinfo.ui" line="85"/>
<source>Name:</source>
<translation>Назва:</translation>
</message>
<message>
<location filename="../settings/gm_settingsscriptinfo.ui" line="55"/>
<source>Version:</source>
<translation>Версія:</translation>
</message>
<message>
<location filename="../settings/gm_settingsscriptinfo.ui" line="115"/>
<source>URL:</source>
<translation>URL-адреса:</translation>
</message>
<message>
<location filename="../settings/gm_settingsscriptinfo.ui" line="138"/>
<source>Namespace:</source>
<translation>Простір імен:</translation>
</message>
<message>
<location filename="../settings/gm_settingsscriptinfo.ui" line="155"/>
<source>Edit in text editor</source>
<translation>Редагувати в текстовому редакторі</translation>
</message>
<message>
<location filename="../settings/gm_settingsscriptinfo.ui" line="65"/>
<source>Start at:</source>
<translation>Починає діяти з:</translation>
</message>
<message>
<location filename="../settings/gm_settingsscriptinfo.ui" line="45"/>
<source>Description:</source>
<translation>Опис:</translation>
</message>
<message>
<location filename="../settings/gm_settingsscriptinfo.ui" line="19"/>
<source>Runs at:</source>
<translation>Запускається на:</translation>
</message>
<message>
<location filename="../settings/gm_settingsscriptinfo.ui" line="128"/>
<source>Does not run at:</source>
<translation>Не запускається на:</translation>
</message>
<message>
<location filename="../settings/gm_settingsscriptinfo.cpp" line="45"/>
<source>Script Details of %1</source>
<translation>Деталі скрипту %1</translation>
</message>
</context>
</TS> | ThaFireDragonOfDeath/qupzilla | src/plugins/GreaseMonkey/translations/uk_UA.ts | TypeScript | gpl-3.0 | 9,213 |
/*
Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colorbutton', 'hr', {
auto: 'Automatski',
bgColorTitle: 'Boja pozadine',
colors: {
'000': 'Crna',
'800000': 'Kesten',
'8B4513': 'Smeđa',
'2F4F4F': 'Tamno siva',
'008080': 'Teal',
'000080': 'Mornarska',
'4B0082': 'Indigo',
'696969': 'Tamno siva',
B22222: 'Vatrena cigla',
A52A2A: 'Smeđa',
DAA520: 'Zlatna',
'006400': 'Tamno zelena',
'40E0D0': 'Tirkizna',
'0000CD': 'Srednje plava',
'800080': 'Ljubičasta',
'808080': 'Siva',
F00: 'Crvena',
FF8C00: 'Tamno naranđasta',
FFD700: 'Zlatna',
'008000': 'Zelena',
'0FF': 'Cijan',
'00F': 'Plava',
EE82EE: 'Ljubičasta',
A9A9A9: 'Mutno siva',
FFA07A: 'Svijetli losos',
FFA500: 'Naranđasto',
FFFF00: 'Žuto',
'00FF00': 'Limun',
AFEEEE: 'Blijedo tirkizna',
ADD8E6: 'Svijetlo plava',
DDA0DD: 'Šljiva',
D3D3D3: 'Svijetlo siva',
FFF0F5: 'Lavanda rumeno',
FAEBD7: 'Antikno bijela',
FFFFE0: 'Svijetlo žuta',
F0FFF0: 'Med',
F0FFFF: 'Azurna',
F0F8FF: 'Alice plava',
E6E6FA: 'Lavanda',
FFF: 'Bijela',
'1ABC9C': 'Jaka cijan',
'2ECC71': 'Emerald',
'3498DB': 'Svijetlo plava',
'9B59B6': 'Ametist',
'4E5F70': 'Sivkasto plava',
'F1C40F': 'Žarka žuta',
'16A085': 'Tamna cijan',
'27AE60': 'Tamna emerald',
'2980B9': 'Jaka plava',
'8E44AD': 'Tamno ljubičasta',
'2C3E50': 'Desatuirarana plava',
'F39C12': 'Narančasta',
'E67E22': 'Mrkva',
'E74C3C': 'Blijedo crvena',
'ECF0F1': 'Sjana srebrna',
'95A5A6': 'Svijetlo sivkasta cijan',
'DDD': 'Svijetlo siva',
'D35400': 'Tikva',
'C0392B': 'Jaka crvena',
'BDC3C7': 'Srebrna',
'7F8C8D': 'Sivkasto cijan',
'999': 'Tamno siva'
},
more: 'Više boja...',
panelTitle: 'Boje',
textColorTitle: 'Boja teksta'
} );
| sgsinclair/Voyant | src/main/webapp/resources/ckeditor/ckeditor4.15.0/plugins/colorbutton/lang/hr.js | JavaScript | gpl-3.0 | 1,902 |
/*
This file is part of JATF.
<p>
JATF 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.
<p>
JATF 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.
<p>
You should have received a copy of the GNU General Public License
along with JATF. If not, see <http://www.gnu.org/licenses/>.
*/
package jatf.dependency;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import jatf.annotations.MustHaveAnnotation;
import jatf.annotations.MustNotHaveAnnotation;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.lang.annotation.Annotation;
import java.util.Set;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(DataProviderRunner.class)
public class AnnotationTypeTest extends DependencyTestBase {
@DataProvider
public static Object[][] provideClassesToTest() {
Set<Class<?>> classesToTest = provideClassesFor(AnnotationTypeTest.class);
return getProvider(classesToTest);
}
@Test
@UseDataProvider(DATA_PROVIDER_NAME)
public void isAnnotated(Class<?> clazz) {
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType().equals(MustHaveAnnotation.class)) {
assertTrue("Required annotation " + annotation + " not present in " + clazz.getName(),
checkIfAnnotationIsPresentIn(clazz, ((MustHaveAnnotation) annotation).annotation()));
}
if (annotation.annotationType().equals(MustNotHaveAnnotation.class)) {
assertFalse("Forbidden annotation " + annotation + " present in " + clazz.getName(),
checkIfAnnotationIsPresentIn(clazz, ((MustNotHaveAnnotation) annotation).annotation()));
}
}
}
private boolean checkIfAnnotationIsPresentIn(Class<?> clazz, Class<? extends Annotation> annotation) {
Annotation[] annotations = clazz.getAnnotations();
for (Annotation a : annotations) {
if (a.annotationType().equals(annotation)) {
return true;
}
}
return false;
}
}
| Duke2k/jatf | jatf-tests/src/main/java/jatf/dependency/AnnotationTypeTest.java | Java | gpl-3.0 | 2,474 |
package com.teksystems.qe.automata.sample.amazon.views;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.teksystems.qe.automata.interfaces.BaseView;
import com.teksystems.qe.automata.sample.amazon.data.AmazonUser;
public abstract class AmazonBaseView implements BaseView{
protected WebDriver driver;
protected AmazonUser user;
/**
* Define global elements here
*/
@FindBy(xpath="//input[@name='field-keywords']")
WebElement searchInput;
@FindBy(xpath="//input[contains(@class,'nav-input') and @type='submit']")
WebElement searchSubmit;
public AmazonBaseView(WebDriver driver, AmazonUser user){
this.driver = driver;
this.user = user;
PageFactory.initElements(driver, this);
}
public abstract void complete();
public void navigate() {
return;
}
/**
* Put utility functions here
*/
}
| jmastri/automata | sample_automata/src/main/java/com/teksystems/qe/automata/sample/amazon/views/AmazonBaseView.java | Java | gpl-3.0 | 967 |
//==============================================================================
//
// File drop zone view
//
//==============================================================================
(function(app, config, $)
{
app.FileDropZoneView = Marionette.ItemView.extend({
events : {
'drop' : 'handleDrop'
},
initialize : function()
{
_.bindAll(this, 'enableEffect', 'disableEffect');
},
delegateEvents : function()
{
// Check browser compatibility
if(!(window.File && window.FileList && window.FileReader))
{
return;
}
Marionette.ItemView.prototype.delegateEvents.apply(this, arguments);
this.el.addEventListener('dragover', this.enableEffect, false);
this.el.addEventListener('dragleave', this.disableEffect, false);
},
undelegateEvents : function()
{
// Check browser compatibility
if(!(window.File && window.FileList && window.FileReader))
{
return;
}
this.el.removeEventListener('dragover', this.enableEffect, false);
this.el.removeEventListener('dragleave', this.disableEffect, false);
Marionette.ItemView.prototype.undelegateEvents.apply(this, arguments);
},
enableEffect : function(e)
{
e.preventDefault();
e.stopPropagation();
if(!this._isFileTransfer(e)) return;
if(this.disableTimer) clearTimeout(this.disableTimer);
this.$el.addClass('active');
},
disableEffect : function(e)
{
if(this.disableTimer) clearTimeout(this.disableTimer);
var _this = this;
this.disableTimer = setTimeout(function()
{
_this.$el.removeClass('active');
}, 100);
},
handleDrop : function(e)
{
e.preventDefault();
e.stopPropagation();
this.disableEffect();
var files = e.originalEvent.dataTransfer.files || e.originalEvent.target.files;
if(files && files.length > 0)
{
this.trigger('drop', files);
}
},
_isFileTransfer : function(e)
{
if(e.dataTransfer.types)
{
for(var i = 0; i < e.dataTransfer.types.length; i++)
{
if(e.dataTransfer.types[i] === 'Files') return true;
}
return false;
}
return true;
}
});
})(window.Application, window.chatConfig, jQuery);
| johnnyswp/promin | chat/js/app/view/FileDropZoneView.js | JavaScript | gpl-3.0 | 2,758 |
"""
Diabicus: A calculator that plays music, lights up, and displays facts.
Copyright (C) 2016 Michael Lipschultz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import math
import os
import re
from functools import reduce
from .compute import ComputationError
def is_int(val):
""" Returns True if val is an int or a float with 0 fractional part """
return isinstance(val, int) or (isinstance(val, float) and val % 1 == 0)
def is_rational(val):
"""
Returns True if val is an int or float and not irrational.
Determining irrationality is done through the is_irrational method.
"""
return isinstance(val, (int, float)) and not is_irrational(val)
def is_irrational(val):
"""
Returns True if val is irrational.
Irrationality is determined by whether val is transcendental (as
determined by is_transcendental) or sqrt(2) or golden ratio.
"""
return is_transcendental(val) or val in {2**.5, GOLDEN_RATIO}
def is_transcendental(val):
""" Returns True if val is transcendental (i.e. pi or e). """
return val in (math.pi, math.e)
def is_real(val):
""" Returns True if val is int or float. """
return isinstance(val, (int, float))
def is_complex(val):
""" Returns True if val is complex. """
return isinstance(val, complex)
def is_surreal(val):
""" Returns True if val is surreal (currently always returns False). """
return False
def is_number(val):
""" Returns True if val is int, float, or complex. """
return isinstance(val, (int, float, complex))
def is_error(val):
""" Returns True if val is a ComputationError. """
return isinstance(val, ComputationError)
GOLDEN_RATIO = (1 + 5**0.5) / 2
GRAHAMS_NUMBER = False
I = complex(0, 1)
PI_DIGITS = (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2,
6, 4, 3, 3, 8, 3, 2, 7, 9, 5, 0, 2, 8, 8, 4, 1, 9, 7, 1, 6, 9, 3,
9, 9, 3, 7, 5, 1, 0, 5, 8, 2, 0, 9, 7, 4, 9, 4, 4, 5, 9, 2, 3, 0,
7, 8, 1, 6, 4, 0, 6, 2, 8, 6, 2, 0, 8, 9, 9, 8, 6, 2, 8, 0, 3, 4,
8, 2, 5, 3, 4, 2, 1, 1, 7, 0, 6, 7, 9, 8, 2, 1, 4
)
PRIME_NUMBERS = []
def __load_primes():
"""
Loads a comma-delimited list of prime numbers into PRIME_NUMBERS.
Prime numbers are loaded from the file prime_numbers.csv in the same
location as this python file and stores them into the global
variable PRIME_NUMBERS.
"""
global PRIME_NUMBERS
path = os.path.dirname(__file__)
with open(os.path.join(path, 'prime_numbers.csv')) as fin:
PRIME_NUMBERS = [int(v) for v in fin.read().split(',')]
__load_primes()
def is_prime(number):
""" Returns True if number is a prime number. """
return is_int(number) and number > 1 and int(number) in PRIME_NUMBERS
FACTORS_ALL = 'all'
FACTORS_PROPER = 'proper'
FACTORS_PRIME = 'prime'
def factors(num, form=FACTORS_PROPER):
"""
Return a list of factors for the provided number.
If form is FACTORS_PRIME, then the list will only contain the prime
factors of num. The product of the values in the list will always
return num. That is, if the number is a product of more than one of
the same prime (e.g. 12 = 2*2*3), then the list will contain those
duplicates (e.g. [2, 2, 3] in the example).
If form is FACTORS_ALL, then the list will contain all positive
integers that exactly divide num. For example, with num=12, the
list returned is [1, 2, 3, 4, 12].
If form is FACTORS_PROPER (default), then the list will be the same
as FACTORS_ALL, except the list will not include num. So, for
num=12, the list returned would be [1, 2, 3, 4].
If num is not an integer (as determined by is_int) greater than 1,
return empty list.
"""
if not is_int(num) or num < 2:
return []
if form == FACTORS_PRIME:
primes = []
i = 2
while num % i == 0:
primes.append(i)
num /= i
i = 3
while num > 1:
while num % i == 0:
primes.append(i)
num /= i
i += 2
return primes
else:
all_factors = reduce(list.__add__,
([i, num//i] for i in range(1, int(num**0.5) + 1) if num % i == 0)
)
if form == FACTORS_PROPER:
all_factors.remove(num)
return all_factors
FIBONACCI_NUMBERS = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,
377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
28657, 46368, 75025, 121393, 196418, 317811, 514229,
832040, 1346269
]
LUCAS_NUMBERS = (2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843,
1364, 2207, 3571, 5778, 9349, 15127, 24476, 39603, 64079,
103682, 167761, 271443, 439204, 710647, 1149851, 1860498,
3010349, 4870847, 7881196, 12752043, 20633239, 33385282
)
def is_subsequence_of(needle, haystack):
"""
Returns True if needle occurs as a consecutive subsequence in haystack.
Both needle and haystack must be ordered containers. The values in
needle must appear in haystack in the order they appear in needle
and must be consecutive in haystack.
For example, with needle=[1,2,3] and haystack=[1,1,2,3,4], the
function returns True since needle starts at index 1 in haystack.
With needle=[1,2,4] and haystack=[1,1,2,3,4], the function returns
False since, although the values do appear in haystack in the
correct order, they are not consecutive.
An empty needle will always return False.
"""
if len(needle) == 0:
return False
for offset in (i for i, x in enumerate(haystack) if x == needle[0]):
if offset + len(needle) > len(haystack):
return False
matches = [needle[i] == haystack[offset+i] for i in range(1, len(needle))]
if len(matches) == len(needle)-1 and all(matches):
return True
return False
def is_close(num1, num2, threshold=1e-5, method='raw'):
"""
Returns True if num1 is within threshold of num2.
If method is 'raw', then the closeness is determined by the absolute
value of the difference between num1 and num2.
If method is 'pct', then the absolute value of percent difference is
calculated and used.
num1 and num2 can be iterable. If one is iterable, then as long as
one value in the iterable object is close to the other number, the
function returns True. If both are iterable, then as long as one
value in num1 is close to one value in num2, the function returns
True.
"""
if isinstance(num1, ComputationError) or isinstance(num2, ComputationError):
return False
elif hasattr(num1, '__iter__'):
return any(is_close(n, num2, threshold) for n in num1)
elif hasattr(num2, '__iter__'):
return any(is_close(num1, n, threshold) for n in num2)
elif ((isinstance(num1, complex) or isinstance(num2, complex))
and not isinstance(num1, type(num2))):
return False
else:
if method == 'pct':
if num1 == num2 and num1 == 0:
return True
else:
return abs(num1-num2) / max([abs(v) for v in (num1, num2) if v != 0]) < threshold
else:
return abs(num1-num2) < threshold
| lipschultz/diabicus | src/numeric_tools.py | Python | gpl-3.0 | 8,003 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: aci_bd
short_description: Manage Bridge Domains (BD) on Cisco ACI Fabrics (fv:BD)
description:
- Manages Bridge Domains (BD) on Cisco ACI Fabrics.
- More information from the internal APIC class
I(fv:BD) at U(https://developer.cisco.com/media/mim-ref/MO-fvBD.html).
author:
- Swetha Chunduri (@schunduri)
- Dag Wieers (@dagwieers)
- Jacob McGill (@jmcgill298)
requirements:
- ACI Fabric 1.0(3f)+
version_added: '2.4'
notes:
- The C(tenant) used must exist before using this module in your playbook.
The M(aci_tenant) module can be used for this.
options:
arp_flooding:
description:
- Determines if the Bridge Domain should flood ARP traffic.
- The APIC defaults new Bridge Domains to C(no).
choices: [ no, yes ]
default: no
bd:
description:
- The name of the Bridge Domain.
aliases: [ bd_name, name ]
bd_type:
description:
- The type of traffic on the Bridge Domain.
- The APIC defaults new Bridge Domains to C(ethernet).
choices: [ ethernet, fc ]
default: ethernet
description:
description:
- Description for the Bridge Domain.
enable_multicast:
description:
- Determines if PIM is enabled
- The APIC defaults new Bridge Domains to C(no).
choices: [ no, yes ]
default: no
enable_routing:
description:
- Determines if IP forwarding should be allowed.
- The APIC defaults new Bridge Domains to C(yes).
choices: [ no, yes ]
default: yes
endpoint_clear:
description:
- Clears all End Points in all Leaves when C(yes).
- The APIC defaults new Bridge Domains to C(no).
- The value is not reset to disabled once End Points have been cleared; that requires a second task.
choices: [ no, yes ]
default: no
endpoint_move_detect:
description:
- Determines if GARP should be enabled to detect when End Points move.
- The APIC defaults new Bridge Domains to C(garp).
choices: [ default, garp ]
default: garp
endpoint_retention_action:
description:
- Determines if the Bridge Domain should inherit or resolve the End Point Retention Policy.
- The APIC defaults new Bridge Domain to End Point Retention Policies to C(resolve).
choices: [ inherit, resolve ]
default: resolve
endpoint_retention_policy:
description:
- The name of the End Point Retention Policy the Bridge Domain should use when
overriding the default End Point Retention Policy.
igmp_snoop_policy:
description:
- The name of the IGMP Snooping Policy the Bridge Domain should use when
overriding the default IGMP Snooping Policy.
ip_learning:
description:
- Determines if the Bridge Domain should learn End Point IPs.
- The APIC defaults new Bridge Domains to C(yes).
choices: [ no, yes ]
ipv6_nd_policy:
description:
- The name of the IPv6 Neighbor Discovery Policy the Bridge Domain should use when
overridding the default IPV6 ND Policy.
l2_unknown_unicast:
description:
- Determines what forwarding method to use for unknown l2 destinations.
- The APIC defaults new Bridge domains to C(proxy).
choices: [ proxy, flood ]
default: proxy
l3_unknown_multicast:
description:
- Determines the forwarding method to use for unknown multicast destinations.
- The APCI defaults new Bridge Domains to C(flood).
choices: [ flood, opt-flood ]
default: flood
limit_ip_learn:
description:
- Determines if the BD should limit IP learning to only subnets owned by the Bridge Domain.
- The APIC defaults new Bridge Domains to C(yes).
choices: [ no, yes ]
default: yes
multi_dest:
description:
- Determines the forwarding method for L2 multicast, broadcast, and link layer traffic.
- The APIC defaults new Bridge Domains to C(bd-flood).
choices: [ bd-flood, drop, encap-flood ]
default: bd-flood
state:
description:
- Use C(present) or C(absent) for adding or removing.
- Use C(query) for listing an object or multiple objects.
choices: [ absent, present, query ]
default: present
tenant:
description:
- The name of the Tenant.
aliases: [ tenant_name ]
vrf:
description:
- The name of the VRF.
aliases: [ vrf_name ]
'''
EXAMPLES = r'''
- name: Add Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: false
state: present
tenant: prod
bd: web_servers
vrf: prod_vrf
- name: Add an FC Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: false
state: present
tenant: prod
bd: storage
bd_type: fc
vrf: fc_vrf
enable_routing: no
- name: Modify a Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: true
state: present
tenant: prod
bd: web_servers
arp_flooding: yes
l2_unknown_unicast: flood
- name: Query All Bridge Domains
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: true
state: query
- name: Query a Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: true
state: query
tenant: prod
bd: web_servers
- name: Delete a Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: true
state: absent
tenant: prod
bd: web_servers
'''
RETURN = r''' # '''
from ansible.module_utils.aci import ACIModule, aci_argument_spec
from ansible.module_utils.basic import AnsibleModule
def main():
argument_spec = aci_argument_spec
argument_spec.update(
arp_flooding=dict(choices=['no', 'yes']),
bd=dict(type='str', aliases=['bd_name', 'name']),
bd_type=dict(type='str', choices=['ethernet', 'fc']),
description=dict(type='str'),
enable_multicast=dict(type='str', choices=['no', 'yes']),
enable_routing=dict(type='str', choices=['no', 'yes']),
endpoint_clear=dict(type='str', choices=['no', 'yes']),
endpoint_move_detect=dict(type='str', choices=['default', 'garp']),
endpoint_retention_action=dict(type='str', choices=['inherit', 'resolve']),
endpoint_retention_policy=dict(type='str'),
igmp_snoop_policy=dict(type='str'),
ip_learning=dict(type='str', choices=['no', 'yes']),
ipv6_nd_policy=dict(type='str'),
l2_unknown_unicast=dict(choices=['proxy', 'flood']),
l3_unknown_multicast=dict(choices=['flood', 'opt-flood']),
limit_ip_learn=dict(type='str', choices=['no', 'yes']),
multi_dest=dict(choices=['bd-flood', 'drop', 'encap-flood']),
state=dict(choices=['absent', 'present', 'query'], type='str', default='present'),
tenant=dict(type='str', aliases=['tenant_name']),
vrf=dict(type='str', aliases=['vrf_name']),
gateway_ip=dict(type='str', removed_in_version='2.4'), # Deprecated starting from v2.4
method=dict(type='str', choices=['delete', 'get', 'post'], aliases=['action'], removed_in_version='2.6'), # Deprecated starting from v2.6
scope=dict(type='str', removed_in_version='2.4'), # Deprecated starting from v2.4
subnet_mask=dict(type='str', removed_in_version='2.4'), # Deprecated starting from v2.4
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_if=[
['state', 'absent', ['bd', 'tenant']],
['state', 'present', ['bd', 'tenant']],
],
)
arp_flooding = module.params['arp_flooding']
bd = module.params['bd']
bd_type = module.params['bd_type']
if bd_type == 'ethernet':
# ethernet type is represented as regular, but that is not clear to the users
bd_type = 'regular'
description = module.params['description']
enable_multicast = module.params['enable_multicast']
enable_routing = module.params['enable_routing']
endpoint_clear = module.params['endpoint_clear']
endpoint_move_detect = module.params['endpoint_move_detect']
if endpoint_move_detect == 'default':
# the ACI default setting is an empty string, but that is not a good input value
endpoint_move_detect = ''
endpoint_retention_action = module.params['endpoint_retention_action']
endpoint_retention_policy = module.params['endpoint_retention_policy']
igmp_snoop_policy = module.params['igmp_snoop_policy']
ip_learning = module.params['ip_learning']
ipv6_nd_policy = module.params['ipv6_nd_policy']
l2_unknown_unicast = module.params['l2_unknown_unicast']
l3_unknown_multicast = module.params['l3_unknown_multicast']
limit_ip_learn = module.params['limit_ip_learn']
multi_dest = module.params['multi_dest']
state = module.params['state']
tenant = module.params['tenant']
vrf = module.params['vrf']
# Give warning when fvSubnet parameters are passed as those have been moved to the aci_subnet module
if module.params['gateway_ip'] or module.params['subnet_mask'] or module.params['scope']:
module._warnings = ["The support for managing Subnets has been moved to its own module, aci_subnet. \
The new modules still supports 'gateway_ip' and 'subnet_mask' along with more features"]
aci = ACIModule(module)
aci.construct_url(
root_class=dict(
aci_class='fvTenant',
aci_rn='tn-{}'.format(tenant),
filter_target='(fvTenant.name, "{}")'.format(tenant),
module_object=tenant,
),
subclass_1=dict(
aci_class='fvBD',
aci_rn='BD-{}'.format(bd),
filter_target='(fvBD.name, "{}")'.format(bd),
module_object=bd,
),
child_classes=['fvRsCtx', 'fvRsIgmpsn', 'fvRsBDToNdP', 'fvRsBdToEpRet'],
)
aci.get_existing()
if state == 'present':
# Filter out module params with null values
aci.payload(
aci_class='fvBD',
class_config=dict(
arpFlood=arp_flooding,
descr=description,
epClear=endpoint_clear,
epMoveDetectMode=endpoint_move_detect,
ipLearning=ip_learning,
limitIpLearnToSubnets=limit_ip_learn,
mcastAllow=enable_multicast,
multiDstPktAct=multi_dest,
name=bd,
type=bd_type,
unicastRoute=enable_routing,
unkMacUcastAct=l2_unknown_unicast,
unkMcastAct=l3_unknown_multicast,
),
child_configs=[
{'fvRsCtx': {'attributes': {'tnFvCtxName': vrf}}},
{'fvRsIgmpsn': {'attributes': {'tnIgmpSnoopPolName': igmp_snoop_policy}}},
{'fvRsBDToNdP': {'attributes': {'tnNdIfPolName': ipv6_nd_policy}}},
{'fvRsBdToEpRet': {'attributes': {'resolveAct': endpoint_retention_action, 'tnFvEpRetPolName': endpoint_retention_policy}}},
],
)
# generate config diff which will be used as POST request body
aci.get_diff(aci_class='fvBD')
# submit changes if module not in check_mode and the proposed is different than existing
aci.post_config()
elif state == 'absent':
aci.delete_config()
module.exit_json(**aci.result)
if __name__ == "__main__":
main()
| tsdmgz/ansible | lib/ansible/modules/network/aci/aci_bd.py | Python | gpl-3.0 | 12,055 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::uniformDiffusivity
Description
Uniform uniform finite volume mesh motion diffusivity.
SourceFiles
uniformDiffusivity.C
\*---------------------------------------------------------------------------*/
#ifndef uniformDiffusivity_H
#define uniformDiffusivity_H
#include <fvMotionSolvers/motionDiffusivity.H>
#include <finiteVolume/surfaceFields.H>
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class uniformDiffusivity Declaration
\*---------------------------------------------------------------------------*/
class uniformDiffusivity
:
public motionDiffusivity
{
protected:
// Protected data
surfaceScalarField faceDiffusivity_;
private:
// Private Member Functions
//- Disallow default bitwise copy construct
uniformDiffusivity(const uniformDiffusivity&);
//- Disallow default bitwise assignment
void operator=(const uniformDiffusivity&);
public:
//- Runtime type information
TypeName("uniform");
// Constructors
//- Construct for the given fvMotionSolver and data Istream
uniformDiffusivity
(
const fvMotionSolver& mSolver,
Istream& mdData
);
// Destructor
virtual ~uniformDiffusivity();
// Member Functions
//- Return diffusivity field
virtual tmp<surfaceScalarField> operator()() const
{
return faceDiffusivity_;
}
//- Do not correct the motion diffusivity
virtual void correct()
{}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************ vim: set sw=4 sts=4 et: ************************ //
| themiwi/freefoam-debian | src/fvMotionSolver/motionDiffusivity/uniform/uniformDiffusivity.H | C++ | gpl-3.0 | 3,051 |
# frozen_string_literal: true
class Api::V1::UsersController < Api::BaseController
end
| WhareHauora/wharehauora-server | app/controllers/api/v1/users_controller.rb | Ruby | gpl-3.0 | 88 |
package com.numbrcrunchr.domain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import java.util.List;
import org.joda.time.DateMidnight;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/domainApplicationContext.xml" })
public class FeasibilityAnalysisProjectionServiceTest {
@Autowired
private FeasibilityAnalysisProjectionService projectionService;
@Autowired
private ProjectionParameters projectionParameters;
private long income;
private long ongoingCosts;
private long weeklyRent;
private byte weeksRented;
private long loanAmount;
private double interestRate;
private double propertyManagementFee;
private long landlordInsurance;
private long maintenance;
private long strata;
private long waterRates;
private long cleaning;
private long councilRates;
private long gardening;
private long taxExpenses;
private long miscOngoingExpenses;
private double capitalGrowthRate;
private double cpi;
private double salaryIncreaseRate;
private double rentIncreaseRate;
private int loanTerm;
private int interestOnlyPeriod;
private int projectionYears;
@Test
public void checkProjectionFor1Year() {
income = 120000;
ongoingCosts = 7000;
weeklyRent = 320;
weeksRented = 50;
loanAmount = 427320;
interestRate = 8;
propertyManagementFee = 10;
Property property = PropertyTest.createProperty(income, true,
loanAmount, ongoingCosts, weeksRented, weeklyRent,
interestRate, propertyManagementFee);
List<FeasibilityAnalysisResult> projections = projectionService
.runProjection(property, 1, projectionParameters)
.getProjections();
assertEquals(2, projections.size());
}
@Test
public void checkProjectionFor1YearWithoutMedicareLevy() {
income = 120000;
ongoingCosts = 7000;
weeklyRent = 320;
weeksRented = 50;
loanAmount = 427320;
interestRate = 8;
propertyManagementFee = 10;
Property property = PropertyTest.createProperty(income, true,
loanAmount, ongoingCosts, weeksRented, weeklyRent,
interestRate, propertyManagementFee);
property.getOwnerList().get(0).setMedicareLevyApplies(Boolean.FALSE);
List<FeasibilityAnalysisResult> projections = projectionService
.runProjection(property, 1, projectionParameters)
.getProjections();
assertEquals(2, projections.size());
}
@Test
public void checkProjectionFor2Years() {
income = 120000;
ongoingCosts = 7000;
weeklyRent = 320;
weeksRented = 50;
loanAmount = 427320;
interestRate = 8;
propertyManagementFee = 10;
List<FeasibilityAnalysisResult> projections = runSomeProjections();
assertEquals(3, projections.size());
}
private List<FeasibilityAnalysisResult> runSomeProjections() {
Property property = PropertyTest.createProperty(income, true,
loanAmount, ongoingCosts, weeksRented, weeklyRent,
interestRate, propertyManagementFee);
List<FeasibilityAnalysisResult> projections = projectionService
.runProjection(property, 2, projectionParameters)
.getProjections();
return projections;
}
@Test
public void checkProjectionFor20Years() {
income = 120000;
ongoingCosts = 7000;
weeklyRent = 320;
weeksRented = 50;
loanAmount = 427320;
interestRate = 8;
propertyManagementFee = 10;
Property property = PropertyTest.createProperty(income, true,
loanAmount, ongoingCosts, weeksRented, weeklyRent,
interestRate, propertyManagementFee);
List<FeasibilityAnalysisResult> projections = projectionService
.runProjection(property, 20, projectionParameters)
.getProjections();
assertEquals(21, projections.size());
}
@Test
public void checkProjectionFor320kPropertyAt320PerWeekOver25Years() {
income = 100000;
weeklyRent = 320;
weeksRented = 50;
loanAmount = 320000;
interestRate = 6;
landlordInsurance = 400;
maintenance = 100;
strata = 0;
waterRates = 800;
cleaning = 100;
councilRates = 1500;
gardening = 100;
taxExpenses = 100;
miscOngoingExpenses = 0;
projectionYears = 24;
cpi = 3;
capitalGrowthRate = 8;
salaryIncreaseRate = 3.5;
rentIncreaseRate = 4;
loanTerm = 30;
interestOnlyPeriod = 10;
Date purchaseDate = new DateMidnight(2014, 2, 11).toDate();
ProjectionParameters projectionParameters = new ProjectionParameters();
projectionParameters.setCapitalGrowthRate(capitalGrowthRate);
projectionParameters.setCpi(cpi);
projectionParameters.setRentIncreaseRate(rentIncreaseRate);
projectionParameters.setSalaryIncreaseRate(salaryIncreaseRate);
OngoingCosts ongoingCosts = new OngoingCosts();
ongoingCosts.setMaintenance(maintenance);
ongoingCosts.setStrata(strata);
ongoingCosts.setWaterCharges(waterRates);
ongoingCosts.setCleaning(cleaning);
ongoingCosts.setCouncilRates(councilRates);
ongoingCosts.setGardening(gardening);
ongoingCosts.setTaxExpenses(taxExpenses);
ongoingCosts.setMiscOngoingExpenses(miscOngoingExpenses);
ongoingCosts.setLandlordsInsurance(landlordInsurance);
Property property = PropertyTest.createProperty(income, true,
loanAmount, ongoingCosts, weeksRented, weeklyRent,
interestRate, propertyManagementFee);
property.setLoanTerm(loanTerm);
property.setPurchaseDate(purchaseDate);
property.setInterestOnlyPeriod(interestOnlyPeriod);
property.setManagementFeeRate(8.8);
Projection projection = projectionService.runProjection(property,
projectionYears, projectionParameters);
projection.changeFrequency(FeasibilityAnalysisResult.MONTHLY);
}
@Test
public void checkProjectionFor50Years() {
income = 120000;
ongoingCosts = 7000;
weeklyRent = 320;
weeksRented = 50;
loanAmount = 427320;
interestRate = 8;
propertyManagementFee = 10;
Property property = PropertyTest.createProperty(income, true,
loanAmount, ongoingCosts, weeksRented, weeklyRent,
interestRate, propertyManagementFee);
Projection projection = projectionService.runProjection(property, 50,
projectionParameters);
projection.toString();
assertEquals(16, projection.getCashflowPositiveYearIndex());
List<FeasibilityAnalysisResult> projections = projection
.getProjections();
// TODO Why does projection for n years return n+1 results?
assertEquals(31, projections.size());
}
@Test
public void checkThatLoanBalanceReducesForPrincipalAndInterestProjection() {
income = 120000;
ongoingCosts = 7000;
weeklyRent = 320;
weeksRented = 50;
loanAmount = 427320;
interestRate = 8;
propertyManagementFee = 10;
Property property = PropertyTest.createProperty(income, true,
loanAmount, ongoingCosts, weeksRented, weeklyRent,
interestRate, propertyManagementFee);
property.setInterestOnlyPeriod(0);
Projection projection = projectionService.runProjection(property, 20,
projectionParameters);
List<FeasibilityAnalysisResult> projections = projection
.getProjections();
double previousLoanBalance = loanAmount + 1;
int i = 1;
for (FeasibilityAnalysisResult result : projections) {
assertTrue(result.getLoanBalance() < previousLoanBalance);
if (i == 1) {
assertEquals("Y 1 (partial)", result.getYear());
} else {
assertEquals("Y " + i, result.getYear());
}
i++;
previousLoanBalance = result.getLoanBalance();
}
}
}
| srirang/numbrcrunchr | src/test/java/com/numbrcrunchr/domain/FeasibilityAnalysisProjectionServiceTest.java | Java | gpl-3.0 | 8,965 |
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package org.openoffice.xmerge.merger.diff;
import java.util.ArrayList;
import org.openoffice.xmerge.merger.Difference;
/**
* <p>This is an implementations of <code>DiffAlgorithm</code> interface
* which will difference char arrays.</p>
*
* <p>It also use Longest Common Subsequence (LCS). The algorithm is based
* on the book "Introduction to Algorithms" by Thomas H.Cormen,
* Charles E.Leiserson, and Ronald L.Riverst (MIT Press 1990) page 314.</p>
*/
public class CharArrayLCSAlgorithm {
/**
* Return an <code>Difference</code> array. This method finds out
* the difference between two sequences.
*
* @param orgSeq The original sequence.
* @param modSeq The modified (or changed) sequence to
* compare against the origial.
*
* @return A <code>Difference</code> array.
*/
public Difference[] computeDiffs(char[] orgSeq, char[] modSeq) {
int orgSeqlen = orgSeq.length;
int modSeqlen = modSeq.length;
int[][] diffTable;
// Diff table is used to keep track which element is the same or not
// in those 2 sequences
diffTable = createDiffTable(orgSeq, modSeq);
ArrayList<Difference> diffResult = new ArrayList<Difference>();
generateResult(diffTable, orgSeqlen, modSeqlen, diffResult);
Difference[] diffArray = new Difference[0];
// convert the vector to array, it has to do in here as
// generateResult is called recursively
if (diffResult.size() > 0) {
diffArray = new Difference[diffResult.size()];
diffResult.toArray(diffArray);
}
diffTable = null;
diffResult = null;
return diffArray;
}
/**
* Create the difference table.
* The difference table is used internal to keep track what
* elements are common or different in the two sequences.
*
* @param orgSeq The original sequence to be used as a base.
* @param modSeq The modified sequence to compare.
*
* @return A difference table as a two-dimensional array of
* integers.
*/
private int[][] createDiffTable(char[] orgSeq, char[] modSeq) {
int orgSeqlen = orgSeq.length + 1;
int modSeqlen = modSeq.length + 1;
int[][] diffTable;
// initialize the diffTable (it need to be 1 row/col bigger
// than the original str)
diffTable = new int[orgSeqlen][];
for (int i = 0; i < orgSeqlen; i++) {
diffTable[i] = new int[modSeqlen];
}
// compute the diff Table using LCS algorithm, refer to the book
// mentioned at the top of the program
for (int i = 1; i < orgSeqlen; i++) {
for (int j = 1; j < modSeqlen; j++) {
if (orgSeq[i-1] == modSeq[j-1]) {
diffTable[i][j] = diffTable[i-1][j-1]+1;
} else {
if (diffTable[i-1][j] >= diffTable[i][j-1]) {
diffTable[i][j] = diffTable[i-1][j];
} else {
diffTable[i][j] = diffTable[i][j-1];
}
}
}
}
return diffTable;
}
/**
* Generate the <code>Difference</code> result vector.
* This method will be called recursively to backtrack the difference
* table to get the difference result (and also the LCS).
*
* @param diffTable The difference table containing the
* <code>Difference</code> result.
* @param i The nth element in original sequence to
* compare. This method is called recursively
* with i and j decreased until 0.
* @param j The nth element in modified sequence to
* compare.
* @param diffVector A vector to output the <code>Difference</code>
* result. Can not use a return variable as it
* is a recursive method. The vector will contain
* <code>Difference</code> objects with operation
* and positions filled in.
*/
private void generateResult(int[][] diffTable,
int i, int j, ArrayList<Difference> diffVector) {
// handle the first element
if (i == 0 || j == 0) {
if (i == 0 && j == 0) {
// return
} else if (j == 0) {
for (int cnt = 0; cnt < i; cnt++) {
Difference diff =
new Difference(Difference.DELETE, cnt, j);
diffVector.add(diff);
}
} else {
for (int cnt = 0; cnt < j; cnt++) {
Difference diff =
new Difference(Difference.ADD, i, cnt);
diffVector.add(diff);
}
}
return;
}
// for the detail of this algorithm, refer to the book mentioned on
// the top and page 317 and 318.
if ((diffTable[i-1][j-1] == diffTable[i][j] -1) &&
(diffTable[i-1][j-1] == diffTable[i-1][j]) &&
(diffTable[i-1][j-1] == diffTable[i][j-1])) {
// the element of ith and jth in org and mod sequence is the same
generateResult(diffTable, i-1, j-1, diffVector);
} else {
if (diffTable[i-1][j] > diffTable[i][j-1]) {
// recursively call first, then add the result so that
// the beginning of the diffs will be stored first
generateResult(diffTable, i-1, j, diffVector);
Difference diff =
new Difference(Difference.DELETE, i-1, j);
diffVector.add(diff);
} else if (diffTable[i-1][j] < diffTable[i][j-1]) {
// recursively call first, then add the result so that
// the beginning of the diffs will be stored first
generateResult(diffTable, i, j-1, diffVector);
Difference diff =
new Difference(Difference.ADD, i, j-1);
diffVector.add(diff);
} else { // diffTable[i-1][j] == diffTable[i][j-1]
// recursively call first, then add the result so that
// the beginning of the diffs will be stored first
generateResult(diffTable, i-1, j-1, diffVector);
Difference diff =
new Difference(Difference.CHANGE, i-1, j-1);
diffVector.add(diff);
}
}
}
}
| qt-haiku/LibreOffice | xmerge/source/xmerge/java/org/openoffice/xmerge/merger/diff/CharArrayLCSAlgorithm.java | Java | gpl-3.0 | 7,570 |
<?php
/**
* This is the base class for all AR models that needs to handle events
* fired by the simpleWorkflow behavior.
*/
class SWActiveRecord extends CActiveRecord {
public function onEnterWorkflow($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
public function enterWorkflow($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
public function onBeforeTransition($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
public function beforeTransition($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
public function onProcessTransition($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
public function processTransition($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
public function onAfterTransition($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
public function afterTransition($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
public function onFinalStatus($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
public function finalStatus($event)
{
Yii::trace(__CLASS__.'.'.__FUNCTION__,'application.simpleWorkflow');
}
}
?> | clevernet/CleverNIM | extensions/simpleWorkflow/SWActiveRecord.php | PHP | gpl-3.0 | 1,419 |
package com.hartwig.hmftools.protect;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Set;
import com.google.common.collect.Sets;
import com.hartwig.hmftools.common.genome.refgenome.RefGenomeVersion;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;
import org.immutables.value.Value;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Value.Immutable
@Value.Style(passAnnotations = { NotNull.class, Nullable.class })
public interface ProtectConfig {
String DOID_SEPARATOR = ";";
// General params needed for every analysis
String TUMOR_SAMPLE_ID = "tumor_sample_id";
String REFERENCE_SAMPLE_ID = "reference_sample_id";
String PRIMARY_TUMOR_DOIDS = "primary_tumor_doids";
String OUTPUT_DIRECTORY = "output_dir";
// Input files used by the algorithm
String SERVE_ACTIONABILITY_DIRECTORY = "serve_actionability_dir";
String DOID_JSON = "doid_json";
// Files containing the actual genomic results for this sample.
String PURPLE_PURITY_TSV = "purple_purity_tsv";
String PURPLE_QC_FILE = "purple_qc_file";
String PURPLE_GENE_COPY_NUMBER_TSV = "purple_gene_copy_number_tsv";
String PURPLE_SOMATIC_DRIVER_CATALOG_TSV = "purple_somatic_driver_catalog_tsv";
String PURPLE_GERMLINE_DRIVER_CATALOG_TSV = "purple_germline_driver_catalog_tsv";
String PURPLE_SOMATIC_VARIANT_VCF = "purple_somatic_variant_vcf";
String PURPLE_GERMLINE_VARIANT_VCF = "purple_germline_variant_vcf";
String LINX_FUSION_TSV = "linx_fusion_tsv";
String LINX_BREAKEND_TSV = "linx_breakend_tsv";
String LINX_DRIVER_CATALOG_TSV = "linx_driver_catalog_tsv";
String ANNOTATED_VIRUS_TSV = "annotated_virus_tsv";
String CHORD_PREDICTION_TXT = "chord_prediction_txt";
// Some additional optional params and flags
String LOG_DEBUG = "log_debug";
@NotNull
static Options createOptions() {
Options options = new Options();
options.addOption(TUMOR_SAMPLE_ID, true, "The sample ID for which PROTECT will run.");
options.addOption(REFERENCE_SAMPLE_ID, true, "(Optional) The reference sample of the tumor sample for which PROTECT will run.");
options.addOption(PRIMARY_TUMOR_DOIDS, true, "A semicolon-separated list of DOIDs representing the primary tumor of patient.");
options.addOption(OUTPUT_DIRECTORY, true, "Path to where the PROTECT output data will be written to.");
options.addOption(RefGenomeVersion.REF_GENOME_VERSION, true, "Ref genome version to use (either '37' or '38')");
options.addOption(SERVE_ACTIONABILITY_DIRECTORY, true, "Path towards the SERVE actionability directory.");
options.addOption(DOID_JSON, true, "Path to JSON file containing the full DOID tree.");
options.addOption(PURPLE_PURITY_TSV, true, "Path towards the purple purity TSV.");
options.addOption(PURPLE_QC_FILE, true, "Path towards the purple qc file.");
options.addOption(PURPLE_GENE_COPY_NUMBER_TSV, true, "Path towards the purple gene copynumber TSV.");
options.addOption(PURPLE_SOMATIC_DRIVER_CATALOG_TSV, true, "Path towards the purple somatic driver catalog TSV.");
options.addOption(PURPLE_GERMLINE_DRIVER_CATALOG_TSV, true, "Path towards the purple germline driver catalog TSV.");
options.addOption(PURPLE_SOMATIC_VARIANT_VCF, true, "Path towards the purple somatic variant VCF.");
options.addOption(PURPLE_GERMLINE_VARIANT_VCF, true, "Path towards the purple germline variant VCF.");
options.addOption(LINX_FUSION_TSV, true, "Path towards the LINX fusion TSV.");
options.addOption(LINX_BREAKEND_TSV, true, "Path towards the LINX breakend TSV.");
options.addOption(LINX_DRIVER_CATALOG_TSV, true, "Path towards the LINX driver catalog TSV.");
options.addOption(ANNOTATED_VIRUS_TSV, true, "Path towards the annotated virus TSV.");
options.addOption(CHORD_PREDICTION_TXT, true, "Path towards the CHORD prediction TXT.");
options.addOption(LOG_DEBUG, false, "If provided, set the log level to debug rather than default.");
return options;
}
@NotNull
String tumorSampleId();
@Nullable
String referenceSampleId();
@NotNull
Set<String> primaryTumorDoids();
@NotNull
String outputDir();
@NotNull
RefGenomeVersion refGenomeVersion();
@NotNull
String serveActionabilityDir();
@NotNull
String doidJsonFile();
@NotNull
String purplePurityTsv();
@NotNull
String purpleQcFile();
@NotNull
String purpleGeneCopyNumberTsv();
@NotNull
String purpleSomaticDriverCatalogTsv();
@NotNull
String purpleGermlineDriverCatalogTsv();
@NotNull
String purpleSomaticVariantVcf();
@NotNull
String purpleGermlineVariantVcf();
@NotNull
String linxFusionTsv();
@NotNull
String linxBreakendTsv();
@NotNull
String linxDriverCatalogTsv();
@NotNull
String annotatedVirusTsv();
@NotNull
String chordPredictionTxt();
@NotNull
static ProtectConfig createConfig(@NotNull CommandLine cmd) throws ParseException, IOException {
if (cmd.hasOption(LOG_DEBUG)) {
Configurator.setRootLevel(Level.DEBUG);
}
return ImmutableProtectConfig.builder()
.tumorSampleId(nonOptionalValue(cmd, TUMOR_SAMPLE_ID))
.referenceSampleId(optionalValue(cmd, REFERENCE_SAMPLE_ID))
.primaryTumorDoids(toStringSet(nonOptionalValue(cmd, PRIMARY_TUMOR_DOIDS), DOID_SEPARATOR))
.outputDir(outputDir(cmd, OUTPUT_DIRECTORY))
.refGenomeVersion(RefGenomeVersion.from(nonOptionalValue(cmd, RefGenomeVersion.REF_GENOME_VERSION)))
.serveActionabilityDir(nonOptionalDir(cmd, SERVE_ACTIONABILITY_DIRECTORY))
.doidJsonFile(nonOptionalFile(cmd, DOID_JSON))
.purplePurityTsv(nonOptionalFile(cmd, PURPLE_PURITY_TSV))
.purpleQcFile(nonOptionalFile(cmd, PURPLE_QC_FILE))
.purpleGeneCopyNumberTsv(nonOptionalFile(cmd, PURPLE_GENE_COPY_NUMBER_TSV))
.purpleSomaticDriverCatalogTsv(nonOptionalFile(cmd, PURPLE_SOMATIC_DRIVER_CATALOG_TSV))
.purpleGermlineDriverCatalogTsv(nonOptionalFile(cmd, PURPLE_GERMLINE_DRIVER_CATALOG_TSV))
.purpleSomaticVariantVcf(nonOptionalFile(cmd, PURPLE_SOMATIC_VARIANT_VCF))
.purpleGermlineVariantVcf(nonOptionalFile(cmd, PURPLE_GERMLINE_VARIANT_VCF))
.linxFusionTsv(nonOptionalFile(cmd, LINX_FUSION_TSV))
.linxBreakendTsv(nonOptionalFile(cmd, LINX_BREAKEND_TSV))
.linxDriverCatalogTsv(nonOptionalFile(cmd, LINX_DRIVER_CATALOG_TSV))
.annotatedVirusTsv(nonOptionalFile(cmd, ANNOTATED_VIRUS_TSV))
.chordPredictionTxt(nonOptionalFile(cmd, CHORD_PREDICTION_TXT))
.build();
}
@NotNull
static Iterable<String> toStringSet(@NotNull String paramValue, @NotNull String separator) {
return !paramValue.isEmpty() ? Sets.newHashSet(paramValue.split(separator)) : Sets.newHashSet();
}
@NotNull
static String nonOptionalValue(@NotNull CommandLine cmd, @NotNull String param) throws ParseException {
String value = cmd.getOptionValue(param);
if (value == null) {
throw new ParseException("Parameter must be provided: " + param);
}
return value;
}
@Nullable
static String optionalValue(@NotNull CommandLine cmd, @NotNull String param) {
String value = null;
if (cmd.hasOption(param)) {
value = cmd.getOptionValue(param);
}
if (value != null && value.isEmpty()) {
value = null;
}
return value;
}
@NotNull
static String nonOptionalDir(@NotNull CommandLine cmd, @NotNull String param) throws ParseException {
String value = nonOptionalValue(cmd, param);
if (!pathExists(value) || !pathIsDirectory(value)) {
throw new ParseException("Parameter '" + param + "' must be an existing directory: " + value);
}
return value;
}
@NotNull
static String outputDir(@NotNull CommandLine cmd, @NotNull String param) throws ParseException, IOException {
String value = nonOptionalValue(cmd, param);
File outputDir = new File(value);
if (!outputDir.exists() && !outputDir.mkdirs()) {
throw new IOException("Unable to write to directory " + value);
}
return value;
}
@NotNull
static String nonOptionalFile(@NotNull CommandLine cmd, @NotNull String param) throws ParseException {
String value = nonOptionalValue(cmd, param);
if (!pathExists(value)) {
throw new ParseException("Parameter '" + param + "' must be an existing file: " + value);
}
return value;
}
static boolean pathExists(@NotNull String path) {
return Files.exists(new File(path).toPath());
}
static boolean pathIsDirectory(@NotNull String path) {
return Files.isDirectory(new File(path).toPath());
}
}
| hartwigmedical/hmftools | protect/src/main/java/com/hartwig/hmftools/protect/ProtectConfig.java | Java | gpl-3.0 | 9,388 |
package com.vaadin.tutorial.todomvc;
import java.util.EnumSet;
import com.vaadin.data.provider.ConfigurableFilterDataProvider;
import com.vaadin.event.ShortcutListener;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.SelectionMode;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.RadioButtonGroup;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.renderers.ButtonRenderer;
import com.vaadin.ui.themes.ValoTheme;
public class TodoViewImpl extends VerticalLayout implements TodoView {
private static final String WIDTH = "500px";
private final TodoPresenter presenter;
private Grid<Todo> grid;
private HorizontalLayout bottomBar;
private Label itemCountLabel;
private TextField newTodoField;
private Button clearCompleted;
private boolean allCompleted;
private Button markAllDoneButton;
private Todo currentlyEditedTodo;
private EnterPressHandler newTodoFieldEnterPressHandler;
private ConfigurableFilterDataProvider<Todo, Void, TaskFilter> filterDataProvider;
public TodoViewImpl() {
setWidth("100%");
setDefaultComponentAlignment(Alignment.TOP_CENTER);
setMargin(false);
setSpacing(false);
Label headerLabel = new Label("todos");
headerLabel.addStyleName(ValoTheme.LABEL_H1);
addComponent(headerLabel);
initTopBar();
initGrid();
initBottomBar();
presenter = new TodoPresenter(this);
}
private void initTopBar() {
HorizontalLayout topBar = new HorizontalLayout();
topBar.setWidth(WIDTH);
markAllDoneButton = new Button(VaadinIcons.CHEVRON_DOWN);
markAllDoneButton.setId("mark-all-done");
markAllDoneButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);
markAllDoneButton.addClickListener(event -> {
allCompleted = !allCompleted;
presenter.markAllCompleted(allCompleted);
});
newTodoField = new TextField();
newTodoField.setId("new-todo");
newTodoField.addStyleName(ValoTheme.TEXTFIELD_BORDERLESS);
newTodoField.addStyleName(ValoTheme.TEXTFIELD_LARGE);
newTodoField.setWidth("100%");
// value might not be updated to server when quickly pressing enter
// without this ...
newTodoField.setValueChangeMode(ValueChangeMode.EAGER);
newTodoField.setPlaceholder("What needs to be done?");
newTodoField.focus(); // auto-focus
// there can only be one shortcut listener set, so need to add/remove
// this in editTodo()
newTodoFieldEnterPressHandler = new EnterPressHandler(
this::onNewTodoFieldEnter);
newTodoField.addShortcutListener(newTodoFieldEnterPressHandler);
topBar.addComponents(markAllDoneButton, newTodoField);
topBar.setExpandRatio(newTodoField, 1);
topBar.setSpacing(false);
addComponent(topBar);
}
private void initGrid() {
grid = new Grid<>();
grid.setSelectionMode(SelectionMode.NONE);
grid.setHeight(null);
grid.setDetailsGenerator(this::createTodoEditor);
grid.setStyleGenerator(this::createStyle);
Grid.Column<Todo, String> completeButtonColumn = grid
.addColumn(t -> "",
new ButtonRenderer<>(event -> presenter.markCompleted(
event.getItem(), !event.getItem()
.isCompleted())));
completeButtonColumn.setWidth(80);
Grid.Column<Todo, String> todoStringColumn = grid.addColumn(
Todo::getText,
new ButtonRenderer<>(e -> editTodo(e.getItem())));
todoStringColumn.setExpandRatio(1);
Grid.Column<Todo, String> deleteButtonColumn = grid.addColumn(t -> "",
new ButtonRenderer<>(
event -> presenter.delete(event.getItem())));
deleteButtonColumn.setWidth(60);
grid.removeHeaderRow(0);
addComponent(grid);
}
private void initBottomBar() {
itemCountLabel = new Label();
itemCountLabel.setId("count");
itemCountLabel.setWidth(13, Unit.EX);
RadioButtonGroup<TaskFilter> filters = new RadioButtonGroup<>(null,
EnumSet.allOf(TaskFilter.class));
filters.setItemCaptionGenerator(TaskFilter::getText);
filters.setId("filters");
filters.addStyleName(ValoTheme.OPTIONGROUP_HORIZONTAL);
filters.addStyleName(ValoTheme.OPTIONGROUP_SMALL);
filters.setValue(TaskFilter.ALL);
filters.addValueChangeListener(event -> {
filterDataProvider.setFilter(event.getValue());
presenter.refreshView();
});
clearCompleted = new Button("Clear completed");
clearCompleted.setId("clear-completed");
clearCompleted.addStyleName(ValoTheme.BUTTON_BORDERLESS);
clearCompleted.addStyleName(ValoTheme.BUTTON_SMALL);
clearCompleted.addClickListener(event -> presenter.clearCompleted());
bottomBar = new HorizontalLayout();
bottomBar.setId("bottom-bar");
bottomBar.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER);
bottomBar.addComponents(itemCountLabel, filters, clearCompleted);
bottomBar.setExpandRatio(filters, 1);
bottomBar.setComponentAlignment(filters, Alignment.TOP_LEFT);
bottomBar.setVisible(false);
bottomBar.setWidth(WIDTH);
addComponents(bottomBar);
}
@Override
public void refresh() {
grid.getDataProvider().refreshAll();
}
@Override
public void updateCounters(int completed, int active) {
bottomBar.setVisible(completed != 0 || active != 0);
clearCompleted.setVisible(completed != 0);
allCompleted = active == 0;
markAllDoneButton.setStyleName("all-done", allCompleted);
if (active > 1) {
itemCountLabel.setValue(String.format("%1$S items left", active));
} else {
itemCountLabel.setValue(String.format("%1$S item left", active));
}
}
@Override
public void setDataProvider(TodoJDBCDataProvider dataProvider) {
filterDataProvider = dataProvider.withConfigurableFilter();
grid.setDataProvider(filterDataProvider);
}
private void onNewTodoFieldEnter() {
String value = newTodoField.getValue().trim();
if (!value.isEmpty()) {
presenter.add(new Todo(value));
newTodoField.setValue("");
}
}
private void editTodo(Todo newTodo) {
if (currentlyEditedTodo == newTodo) {
return;
}
if (currentlyEditedTodo != null) {
presenter.updateTodo(currentlyEditedTodo);
grid.setDetailsVisible(currentlyEditedTodo, false);
newTodoField.addShortcutListener(newTodoFieldEnterPressHandler);
}
currentlyEditedTodo = newTodo;
if (currentlyEditedTodo != null) {
newTodoField.removeShortcutListener(newTodoFieldEnterPressHandler);
grid.setDetailsVisible(currentlyEditedTodo, true);
}
}
private TextField createTodoEditor(Todo todo) {
TextField textField = new TextField();
textField.setId("todo-editor");
textField.setWidth("100%");
textField.setValue(todo.getText());
textField.focus();
textField.addValueChangeListener(e -> todo.setText(e.getValue()));
textField.addShortcutListener(
new EnterPressHandler(() -> editTodo(null)));
textField.addBlurListener(e -> editTodo(null));
return textField;
}
private String createStyle(Todo todo) {
return todo.isCompleted() ? "done" : "";
}
private class EnterPressHandler extends ShortcutListener {
private Runnable handler;
public EnterPressHandler(Runnable handler) {
super("", KeyCode.ENTER, new int[0]);
this.handler = handler;
}
@Override
public void handleAction(Object sender, Object target) {
handler.run();
}
}
}
| 241180/Oryx | framework8-demo-master/todomvc/src/main/java/com/vaadin/tutorial/todomvc/TodoViewImpl.java | Java | gpl-3.0 | 8,359 |
"use strict";
const logger = require('../logwrapper');
const eventManager = require("../events/EventManager");
const NodeCache = require("node-cache");
const cache = new NodeCache({ stdTTL: 0, checkperiod: 5 });
exports._cache = cache;
cache.on("expired", function(key, value) {
eventManager.triggerEvent("firebot", "custom-variable-expired", {
username: "Firebot",
expiredCustomVariableName: key,
expiredCustomVariableData: value
});
});
cache.on("set", function(key, value) {
eventManager.triggerEvent("firebot", "custom-variable-set", {
username: "Firebot",
createdCustomVariableName: key,
createdCustomVariableData: value
});
});
function getVariableCacheDb() {
const profileManager = require("../common/profile-manager");
return profileManager
.getJsonDbInProfile("custom-variable-cache");
}
exports.persistVariablesToFile = () => {
const db = getVariableCacheDb();
db.push("/", cache.data);
};
exports.loadVariablesFromFile = () => {
const db = getVariableCacheDb();
const data = db.getData("/");
if (data) {
for (const [key, {t, v}] of Object.entries(data)) {
const now = Date.now();
if (t && t > 0 && t < now) {
// this var has expired
continue;
}
const ttl = t === 0 ? 0 : (t - now) / 1000;
cache.set(key, v, ttl);
}
}
};
exports.addCustomVariable = (name, data, ttl = 0, propertyPath = null) => {
//attempt to parse data as json
try {
data = JSON.parse(data);
} catch (error) {
//silently fail
}
let dataRaw = data != null ? data.toString().toLowerCase() : "null";
let dataIsNull = dataRaw === "null" || dataRaw === "undefined";
let currentData = cache.get(name);
if (propertyPath == null || propertyPath.length < 1) {
let dataToSet = dataIsNull ? undefined : data;
if (currentData && Array.isArray(currentData) && !Array.isArray(data) && !dataIsNull) {
currentData.push(data);
dataToSet = currentData;
}
cache.set(name, dataToSet, ttl === "" ? 0 : ttl);
} else {
let currentData = cache.get(name);
if (!currentData) return;
try {
let cursor = currentData;
let pathNodes = propertyPath.split(".");
for (let i = 0; i < pathNodes.length; i++) {
let node = pathNodes[i];
// parse to int for array access
if (!isNaN(node)) {
node = parseInt(node);
}
let isLastItem = i === pathNodes.length - 1;
if (isLastItem) {
// if data recognized as null and cursor is an array, remove index instead of setting value
if (dataIsNull && Array.isArray(cursor) && !isNaN(node)) {
cursor.splice(node, 1);
} else {
//if next node is an array and we detect we are not setting a new array or removing array, then push data to array
if (Array.isArray(cursor[node]) && !Array.isArray(data) && !dataIsNull) {
cursor[node].push(data);
} else {
cursor[node] = dataIsNull ? undefined : data;
}
}
} else {
cursor = cursor[node];
}
}
cache.set(name, currentData, ttl === "" ? 0 : ttl);
} catch (error) {
logger.debug(`error setting data to custom variable ${name} using property path ${propertyPath}`);
}
}
};
exports.getCustomVariable = (name, propertyPath, defaultData = null) => {
let data = cache.get(name);
if (data == null) {
return defaultData;
}
if (propertyPath == null) {
return data;
}
try {
let pathNodes = propertyPath.split(".");
for (let i = 0; i < pathNodes.length; i++) {
if (data == null) break;
let node = pathNodes[i];
// parse to int for array access
if (!isNaN(node)) {
node = parseInt(node);
}
data = data[node];
}
return data != null ? data : defaultData;
} catch (error) {
logger.debug(`error getting data from custom variable ${name} using property path ${propertyPath}`);
return defaultData;
}
}; | Firebottle/Firebot | backend/common/custom-variable-manager.js | JavaScript | gpl-3.0 | 4,564 |
# -*- coding:utf-8 -*-
print("Hello") | okkn/YagiMed | yagimed/main.py | Python | gpl-3.0 | 37 |
<?php
/*
* $Id: Query.php 1393 2007-05-19 17:49:16Z zYne $
*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
/**
* Doctrine_Query_Abstract
*
* @package Doctrine
* @subpackage Query
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 1.0
* @version $Revision: 1393 $
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
* @todo See {@link Doctrine_Query}
*/
abstract class Doctrine_Query_Abstract
{
/**
* QUERY TYPE CONSTANTS
*/
/**
* constant for SELECT queries
*/
const SELECT = 0;
/**
* constant for DELETE queries
*/
const DELETE = 1;
/**
* constant for UPDATE queries
*/
const UPDATE = 2;
/**
* constant for INSERT queries
*/
const INSERT = 3;
/**
* constant for CREATE queries
*/
const CREATE = 4;
/** @todo document the query states (and the transitions between them). */
/**
* A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts.
*/
const STATE_CLEAN = 1;
/**
* A query object is in state DIRTY when it has DQL parts that have not yet been
* parsed/processed.
*/
const STATE_DIRTY = 2;
/**
* A query is in DIRECT state when ... ?
*/
const STATE_DIRECT = 3;
/**
* A query object is on LOCKED state when ... ?
*/
const STATE_LOCKED = 4;
/**
* @var array Table alias map. Keys are SQL aliases and values DQL aliases.
*/
protected $_tableAliasMap = array();
/**
* @var Doctrine_View The view object used by this query, if any.
*/
protected $_view;
/**
* @var integer $_state The current state of this query.
*/
protected $_state = Doctrine_Query::STATE_CLEAN;
/**
* @var array $_params The parameters of this query.
*/
protected $_params = array('exec' => array(),
'join' => array(),
'where' => array(),
'set' => array(),
'having' => array());
/**
* @var array $_execParams The parameters passed to connection statement
*/
protected $_execParams = array();
/* Caching properties */
/**
* @var Doctrine_Cache_Interface The cache driver used for caching result sets.
*/
protected $_resultCache;
/**
* @var string Key to use for result cache entry in the cache driver
*/
protected $_resultCacheHash;
/**
* @var boolean $_expireResultCache A boolean value that indicates whether or not
* expire the result cache.
*/
protected $_expireResultCache = false;
protected $_resultCacheTTL;
/**
* @var Doctrine_Cache_Interface The cache driver used for caching queries.
*/
protected $_queryCache;
protected $_expireQueryCache = false;
protected $_queryCacheTTL;
/**
* @var Doctrine_Connection The connection used by this query object.
*/
protected $_conn;
/**
* @var bool Whether or not a connection was passed to this query object to use
*/
protected $_passedConn = false;
/**
* @var array $_sqlParts The SQL query string parts. Filled during the DQL parsing process.
*/
protected $_sqlParts = array(
'select' => array(),
'distinct' => false,
'forUpdate' => false,
'from' => array(),
'set' => array(),
'join' => array(),
'where' => array(),
'groupby' => array(),
'having' => array(),
'orderby' => array(),
'limit' => false,
'offset' => false,
);
/**
* @var array $_dqlParts an array containing all DQL query parts; @see Doctrine_Query::getDqlPart()
*/
protected $_dqlParts = array(
'from' => array(),
'select' => array(),
'forUpdate' => false,
'set' => array(),
'join' => array(),
'where' => array(),
'groupby' => array(),
'having' => array(),
'orderby' => array(),
'limit' => array(),
'offset' => array(),
);
/**
* @var array $_queryComponents Two dimensional array containing the components of this query,
* informations about their relations and other related information.
* The components are constructed during query parsing.
*
* Keys are component aliases and values the following:
*
* table table object associated with given alias
*
* relation the relation object owned by the parent
*
* parent the alias of the parent
*
* agg the aggregates of this component
*
* map the name of the column / aggregate value this
* component is mapped to a collection
*/
protected $_queryComponents = array();
/**
* Stores the root DQL alias
*
* @var string
*/
protected $_rootAlias = '';
/**
* @var integer $type the query type
*
* @see Doctrine_Query::* constants
*/
protected $_type = self::SELECT;
/**
* @var Doctrine_Hydrator The hydrator object used to hydrate query results.
*/
protected $_hydrator;
/**
* @var Doctrine_Query_Tokenizer The tokenizer that is used during the query parsing process.
*/
protected $_tokenizer;
/**
* @var Doctrine_Query_Parser The parser that is used for query parsing.
*/
protected $_parser;
/**
* @var array $_tableAliasSeeds A simple array keys representing table aliases and values
* table alias seeds. The seeds are used for generating short table
* aliases.
*/
protected $_tableAliasSeeds = array();
/**
* @var array $_options an array of options
*/
protected $_options = array(
'hydrationMode' => Doctrine_Core::HYDRATE_RECORD
);
/**
* @var boolean
*/
protected $_isLimitSubqueryUsed = false;
/**
* @var array components used in the DQL statement
*/
protected $_components;
/**
* @var bool Boolean variable for whether or not the preQuery process has been executed
*/
protected $_preQueried = false;
/**
* Fix for http://www.doctrine-project.org/jira/browse/DC-701
*
* @var bool Boolean variable for whether the limitSubquery method of accessing tables via a many relationship should be used.
*/
protected $disableLimitSubquery = false;
/**
* Constructor.
*
* @param Doctrine_Connection The connection object the query will use.
* @param Doctrine_Hydrator_Abstract The hydrator that will be used for generating result sets.
*/
public function __construct(Doctrine_Connection $connection = null,
Doctrine_Hydrator_Abstract $hydrator = null)
{
if ($connection === null) {
$connection = Doctrine_Manager::getInstance()->getCurrentConnection();
} else {
$this->_passedConn = true;
}
if ($hydrator === null) {
$hydrator = new Doctrine_Hydrator();
}
$this->_conn = $connection;
$this->_hydrator = $hydrator;
$this->_tokenizer = new Doctrine_Query_Tokenizer();
$this->_resultCacheTTL = $this->_conn->getAttribute(Doctrine_Core::ATTR_RESULT_CACHE_LIFESPAN);
$this->_queryCacheTTL = $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE_LIFESPAN);
}
/**
* Set the connection this query object should use
*
* @param Doctrine_Connection $connection
* @return void
*/
public function setConnection(Doctrine_Connection $connection)
{
$this->_passedConn = true;
$this->_conn = $connection;
}
/**
* setOption
*
* @param string $name option name
* @param string $value option value
* @return Doctrine_Query this object
*/
public function setOption($name, $value)
{
if ( ! isset($this->_options[$name])) {
throw new Doctrine_Query_Exception('Unknown option ' . $name);
}
$this->_options[$name] = $value;
}
/**
* hasSqlTableAlias
* whether or not this object has given tableAlias
*
* @param string $tableAlias the table alias to be checked
* @return boolean true if this object has given alias, otherwise false
*/
public function hasSqlTableAlias($sqlTableAlias)
{
return (isset($this->_tableAliasMap[$sqlTableAlias]));
}
/**
* getTableAliasMap
* returns all table aliases
*
* @return array table aliases as an array
*/
public function getTableAliasMap()
{
return $this->_tableAliasMap;
}
/**
* getDql
* returns the DQL query that is represented by this query object.
*
* the query is built from $_dqlParts
*
* @return string the DQL query
*/
public function getDql()
{
$q = '';
if ($this->_type == self::SELECT) {
$q .= ( ! empty($this->_dqlParts['select'])) ? 'SELECT ' . implode(', ', $this->_dqlParts['select']) : '';
$q .= ( ! empty($this->_dqlParts['from'])) ? ' FROM ' . implode(' ', $this->_dqlParts['from']) : '';
} else if ($this->_type == self::DELETE) {
$q .= 'DELETE';
$q .= ( ! empty($this->_dqlParts['from'])) ? ' FROM ' . implode(' ', $this->_dqlParts['from']) : '';
} else if ($this->_type == self::UPDATE) {
$q .= 'UPDATE ';
$q .= ( ! empty($this->_dqlParts['from'])) ? implode(' ', $this->_dqlParts['from']) : '';
$q .= ( ! empty($this->_dqlParts['set'])) ? ' SET ' . implode(' ', $this->_dqlParts['set']) : '';
}
$q .= ( ! empty($this->_dqlParts['where'])) ? ' WHERE ' . implode(' ', $this->_dqlParts['where']) : '';
$q .= ( ! empty($this->_dqlParts['groupby'])) ? ' GROUP BY ' . implode(', ', $this->_dqlParts['groupby']) : '';
$q .= ( ! empty($this->_dqlParts['having'])) ? ' HAVING ' . implode(' AND ', $this->_dqlParts['having']) : '';
$q .= ( ! empty($this->_dqlParts['orderby'])) ? ' ORDER BY ' . implode(', ', $this->_dqlParts['orderby']) : '';
$q .= ( ! empty($this->_dqlParts['limit'])) ? ' LIMIT ' . implode(' ', $this->_dqlParts['limit']) : '';
$q .= ( ! empty($this->_dqlParts['offset'])) ? ' OFFSET ' . implode(' ', $this->_dqlParts['offset']) : '';
return $q;
}
/**
* getSqlQueryPart
* gets an SQL query part from the SQL query part array
*
* @param string $name the name of the query part to be set
* @param string $part query part string
* @throws Doctrine_Query_Exception if trying to set unknown query part
* @return mixed this object
*/
public function getSqlQueryPart($part)
{
if ( ! isset($this->_sqlParts[$part])) {
throw new Doctrine_Query_Exception('Unknown SQL query part ' . $part);
}
return $this->_sqlParts[$part];
}
/**
* setSqlQueryPart
* sets an SQL query part in the SQL query part array
*
* @param string $name the name of the query part to be set
* @param string $part query part string
* @throws Doctrine_Query_Exception if trying to set unknown query part
* @return Doctrine_Query this object
*/
public function setSqlQueryPart($name, $part)
{
if ( ! isset($this->_sqlParts[$name])) {
throw new Doctrine_Query_Exception('Unknown query part ' . $name);
}
if ($name !== 'limit' && $name !== 'offset') {
if (is_array($part)) {
$this->_sqlParts[$name] = $part;
} else {
$this->_sqlParts[$name] = array($part);
}
} else {
$this->_sqlParts[$name] = $part;
}
return $this;
}
/**
* addSqlQueryPart
* adds an SQL query part to the SQL query part array
*
* @param string $name the name of the query part to be added
* @param string $part query part string
* @throws Doctrine_Query_Exception if trying to add unknown query part
* @return Doctrine_Query this object
*/
public function addSqlQueryPart($name, $part)
{
if ( ! isset($this->_sqlParts[$name])) {
throw new Doctrine_Query_Exception('Unknown query part ' . $name);
}
if (is_array($part)) {
$this->_sqlParts[$name] = array_merge($this->_sqlParts[$name], $part);
} else {
$this->_sqlParts[$name][] = $part;
}
return $this;
}
/**
* removeSqlQueryPart
* removes a query part from the query part array
*
* @param string $name the name of the query part to be removed
* @throws Doctrine_Query_Exception if trying to remove unknown query part
* @return Doctrine_Query this object
*/
public function removeSqlQueryPart($name)
{
if ( ! isset($this->_sqlParts[$name])) {
throw new Doctrine_Query_Exception('Unknown query part ' . $name);
}
if ($name == 'limit' || $name == 'offset' || $name == 'forUpdate') {
$this->_sqlParts[$name] = false;
} else {
$this->_sqlParts[$name] = array();
}
return $this;
}
/**
* removeDqlQueryPart
* removes a dql query part from the dql query part array
*
* @param string $name the name of the query part to be removed
* @throws Doctrine_Query_Exception if trying to remove unknown query part
* @return Doctrine_Query this object
*/
public function removeDqlQueryPart($name)
{
if ( ! isset($this->_dqlParts[$name])) {
throw new Doctrine_Query_Exception('Unknown query part ' . $name);
}
if ($name == 'limit' || $name == 'offset') {
$this->_dqlParts[$name] = false;
} else {
$this->_dqlParts[$name] = array();
}
return $this;
}
/**
* Get raw array of parameters for query and all parts.
*
* @return array $params
*/
public function getParams()
{
return $this->_params;
}
/**
* Get flattened array of parameters for query.
* Used internally and used to pass flat array of params to the database.
*
* @param array $params
* @return void
*/
public function getFlattenedParams($params = array())
{
return array_merge(
(array) $params, (array) $this->_params['exec'],
$this->_params['join'], $this->_params['set'],
$this->_params['where'], $this->_params['having']
);
}
/**
* getInternalParams
*
* @return array
*/
public function getInternalParams($params = array())
{
return array_merge($params, $this->_execParams);
}
/**
* setParams
*
* @param array $params
*/
public function setParams(array $params = array())
{
$this->_params = $params;
}
/**
* getCountQueryParams
* Retrieves the parameters for count query
*
* @return array Parameters array
*/
public function getCountQueryParams($params = array())
{
if ( ! is_array($params)) {
$params = array($params);
}
$this->_params['exec'] = $params;
$params = array_merge($this->_params['join'], $this->_params['where'], $this->_params['having'], $this->_params['exec']);
$this->fixArrayParameterValues($params);
return $this->_execParams;
}
/**
* @nodoc
*/
public function fixArrayParameterValues($params = array())
{
$i = 0;
foreach ($params as $param) {
if (is_array($param)) {
$c = count($param);
array_splice($params, $i, 1, $param);
$i += $c;
} else {
$i++;
}
}
$this->_execParams = $params;
}
/**
* setView
* sets a database view this query object uses
* this method should only be called internally by doctrine
*
* @param Doctrine_View $view database view
* @return void
*/
public function setView(Doctrine_View $view)
{
$this->_view = $view;
}
/**
* getView
* returns the view associated with this query object (if any)
*
* @return Doctrine_View the view associated with this query object
*/
public function getView()
{
return $this->_view;
}
/**
* limitSubqueryUsed
*
* @return boolean
*/
public function isLimitSubqueryUsed()
{
return $this->_isLimitSubqueryUsed;
}
/**
* Returns the inheritance condition for the passed componentAlias
* If no component alias is specified it defaults to the root component
*
* This function is used to append a SQL condition to models which have inheritance mapping
* The condition is applied to the FROM component in the WHERE, but the condition is applied to
* JOINS in the ON condition and not the WHERE
*
* @return string $str SQL condition string
*/
public function getInheritanceCondition($componentAlias)
{
$map = $this->_queryComponents[$componentAlias]['table']->inheritanceMap;
// No inheritance map so lets just return
if (empty($map)) {
return;
}
$tableAlias = $this->getSqlTableAlias($componentAlias);
if ($this->_type !== Doctrine_Query::SELECT) {
$tableAlias = '';
} else {
$tableAlias .= '.';
}
// Fix for 2015: loop through whole inheritanceMap to add all
// keyFields for inheritance (and not only the first)
$retVal = "";
$count = 0;
foreach ($map as $field => $value) {
if ($count++ > 0) {
$retVal .= ' AND ';
}
$identifier = $this->_conn->quoteIdentifier($tableAlias . $field);
$retVal .= $identifier . ' = ' . $this->_conn->quote($value);
}
return $retVal;
}
/**
* getSqlTableAlias
* some database such as Oracle need the identifier lengths to be < ~30 chars
* hence Doctrine creates as short identifier aliases as possible
*
* this method is used for the creation of short table aliases, its also
* smart enough to check if an alias already exists for given component (componentAlias)
*
* @param string $componentAlias the alias for the query component to search table alias for
* @param string $tableName the table name from which the table alias is being created
* @return string the generated / fetched short alias
*/
public function getSqlTableAlias($componentAlias, $tableName = null)
{
$alias = array_search($componentAlias, $this->_tableAliasMap);
if ($alias !== false) {
return $alias;
}
if ($tableName === null) {
throw new Doctrine_Query_Exception("Couldn't get short alias for " . $componentAlias);
}
return $this->generateSqlTableAlias($componentAlias, $tableName);
}
/**
* generateNewSqlTableAlias
* generates a new alias from given table alias
*
* @param string $tableAlias table alias from which to generate the new alias from
* @return string the created table alias
*/
public function generateNewSqlTableAlias($oldAlias)
{
if (isset($this->_tableAliasMap[$oldAlias])) {
// generate a new alias
$name = substr($oldAlias, 0, 1);
$i = ((int) substr($oldAlias, 1));
// Fix #1530: It was reaching unexistent seeds index
if ( ! isset($this->_tableAliasSeeds[$name])) {
$this->_tableAliasSeeds[$name] = 1;
}
$newIndex = ($this->_tableAliasSeeds[$name] + (($i == 0) ? 1 : $i));
return $name . $newIndex;
}
return $oldAlias;
}
/**
* getSqlTableAliasSeed
* returns the alias seed for given table alias
*
* @param string $tableAlias table alias that identifies the alias seed
* @return integer table alias seed
*/
public function getSqlTableAliasSeed($sqlTableAlias)
{
if ( ! isset($this->_tableAliasSeeds[$sqlTableAlias])) {
return 0;
}
return $this->_tableAliasSeeds[$sqlTableAlias];
}
/**
* hasAliasDeclaration
* whether or not this object has a declaration for given component alias
*
* @param string $componentAlias the component alias the retrieve the declaration from
* @return boolean
*/
public function hasAliasDeclaration($componentAlias)
{
return isset($this->_queryComponents[$componentAlias]);
}
/**
* getQueryComponent
* get the declaration for given component alias
*
* @param string $componentAlias the component alias the retrieve the declaration from
* @return array the alias declaration
*/
public function getQueryComponent($componentAlias)
{
if ( ! isset($this->_queryComponents[$componentAlias])) {
throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias);
}
return $this->_queryComponents[$componentAlias];
}
/**
* copySubqueryInfo
* copy aliases from another Hydrate object
*
* this method is needed by DQL subqueries which need the aliases
* of the parent query
*
* @param Doctrine_Hydrate $query the query object from which the
* aliases are copied from
* @return Doctrine_Query this object
*/
public function copySubqueryInfo(Doctrine_Query_Abstract $query)
{
$this->_params =& $query->_params;
$this->_tableAliasMap =& $query->_tableAliasMap;
$this->_queryComponents =& $query->_queryComponents;
$this->_tableAliasSeeds = $query->_tableAliasSeeds;
return $this;
}
/**
* getRootAlias
* returns the alias of the root component
*
* @return array
*/
public function getRootAlias()
{
if ( ! $this->_queryComponents) {
$this->getSqlQuery(array(), false);
}
return $this->_rootAlias;
}
/**
* getRootDeclaration
* returns the root declaration
*
* @return array
*/
public function getRootDeclaration()
{
$map = $this->_queryComponents[$this->_rootAlias];
return $map;
}
/**
* getRoot
* returns the root component for this object
*
* @return Doctrine_Table root components table
*/
public function getRoot()
{
$map = $this->_queryComponents[$this->_rootAlias];
if ( ! isset($map['table'])) {
throw new Doctrine_Query_Exception('Root component not initialized.');
}
return $map['table'];
}
/**
* generateSqlTableAlias
* generates a table alias from given table name and associates
* it with given component alias
*
* @param string $componentAlias the component alias to be associated with generated table alias
* @param string $tableName the table name from which to generate the table alias
* @return string the generated table alias
*/
public function generateSqlTableAlias($componentAlias, $tableName)
{
preg_match('/([^_|\d])/', $tableName, $matches);
$char = strtolower($matches[0]);
$alias = $char;
if ( ! isset($this->_tableAliasSeeds[$alias])) {
$this->_tableAliasSeeds[$alias] = 1;
}
while (isset($this->_tableAliasMap[$alias])) {
if ( ! isset($this->_tableAliasSeeds[$alias])) {
$this->_tableAliasSeeds[$alias] = 1;
}
$alias = $char . ++$this->_tableAliasSeeds[$alias];
}
$this->_tableAliasMap[$alias] = $componentAlias;
return $alias;
}
/**
* getComponentAlias
* get component alias associated with given table alias
*
* @param string $sqlTableAlias the SQL table alias that identifies the component alias
* @return string component alias
*/
public function getComponentAlias($sqlTableAlias)
{
$sqlTableAlias = trim($sqlTableAlias, '[]`"');
if ( ! isset($this->_tableAliasMap[$sqlTableAlias])) {
throw new Doctrine_Query_Exception('Unknown table alias ' . $sqlTableAlias);
}
return $this->_tableAliasMap[$sqlTableAlias];
}
/**
* calculateQueryCacheHash
* calculate hash key for query cache
*
* @return string the hash
*/
public function calculateQueryCacheHash()
{
$dql = $this->getDql();
$hash = md5($dql . var_export($this->_pendingJoinConditions, true) . 'DOCTRINE_QUERY_CACHE_SALT');
return $hash;
}
/**
* calculateResultCacheHash
* calculate hash key for result cache
*
* @param array $params
* @return string the hash
*/
public function calculateResultCacheHash($params = array())
{
$dql = $this->getDql();
$conn = $this->getConnection();
$params = $this->getFlattenedParams($params);
$hash = md5($this->_hydrator->getHydrationMode() . $conn->getName() . $conn->getOption('dsn') . $dql . var_export($this->_pendingJoinConditions, true) . var_export($params, true));
return $hash;
}
/**
* Get the result cache hash/key. Returns key set with useResultCache()
* or generates a unique key from the query automatically.
*
* @param array $params
* @return string $hash
*/
public function getResultCacheHash($params = array())
{
if ($this->_resultCacheHash) {
return $this->_resultCacheHash;
} else {
return $this->calculateResultCacheHash($params);
}
}
/**
* _execute
*
* @param array $params
* @return PDOStatement The executed PDOStatement.
*/
protected function _execute($params)
{
// Apply boolean conversion in DQL params
$params = $this->_conn->convertBooleans($params);
foreach ($this->_params as $k => $v) {
$this->_params[$k] = $this->_conn->convertBooleans($v);
}
$dqlParams = $this->getFlattenedParams($params);
// Check if we're not using a Doctrine_View
if ( ! $this->_view) {
if ($this->_queryCache !== false && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) {
$queryCacheDriver = $this->getQueryCacheDriver();
$hash = $this->calculateQueryCacheHash();
$cached = $queryCacheDriver->fetch($hash);
// If we have a cached query...
if ($cached) {
// Rebuild query from cache
$query = $this->_constructQueryFromCache($cached);
// Assign building/execution specific params
$this->_params['exec'] = $params;
// Initialize prepared parameters array
$this->_execParams = $this->getFlattenedParams();
// Fix possible array parameter values in SQL params
$this->fixArrayParameterValues($this->getInternalParams());
} else {
// Generate SQL or pick already processed one
$query = $this->getSqlQuery($params);
// Check again because getSqlQuery() above could have flipped the _queryCache flag
// if this query contains the limit sub query algorithm we don't need to cache it
if ($this->_queryCache !== false && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) {
// Convert query into a serialized form
$serializedQuery = $this->getCachedForm($query);
// Save cached query
$queryCacheDriver->save($hash, $serializedQuery, $this->getQueryCacheLifeSpan());
}
}
} else {
$query = $this->getSqlQuery($params);
}
} else {
$query = $this->_view->getSelectSql();
}
// Get prepared SQL params for execution
$params = $this->getInternalParams();
if ($this->isLimitSubqueryUsed() &&
$this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME) !== 'mysql') {
$params = array_merge((array) $params, (array) $params);
}
if ($this->_type !== self::SELECT) {
return $this->_conn->exec($query, $params);
}
$stmt = $this->_conn->execute($query, $params);
$this->_params['exec'] = array();
return $stmt;
}
/**
* execute
* executes the query and populates the data set
*
* @param array $params
* @return Doctrine_Collection the root collection
*/
public function execute($params = array(), $hydrationMode = null)
{
// Clean any possible processed params
$this->_execParams = array();
if (empty($this->_dqlParts['from']) && empty($this->_sqlParts['from'])) {
throw new Doctrine_Query_Exception('You must have at least one component specified in your from.');
}
$dqlParams = $this->getFlattenedParams($params);
$this->_preQuery($dqlParams);
if ($hydrationMode !== null) {
$this->_hydrator->setHydrationMode($hydrationMode);
}
$hydrationMode = $this->_hydrator->getHydrationMode();
if ($this->_resultCache && $this->_type == self::SELECT) {
$cacheDriver = $this->getResultCacheDriver();
$hash = $this->getResultCacheHash($params);
$cached = ($this->_expireResultCache) ? false : $cacheDriver->fetch($hash);
if ($cached === false) {
// cache miss
$stmt = $this->_execute($params);
$this->_hydrator->setQueryComponents($this->_queryComponents);
$result = $this->_hydrator->hydrateResultSet($stmt, $this->_tableAliasMap);
$cached = $this->getCachedForm($result);
$cacheDriver->save($hash, $cached, $this->getResultCacheLifeSpan());
} else {
$result = $this->_constructQueryFromCache($cached);
}
} else {
$stmt = $this->_execute($params);
if (is_integer($stmt)) {
$result = $stmt;
} else {
$this->_hydrator->setQueryComponents($this->_queryComponents);
if ($this->_type == self::SELECT && $hydrationMode == Doctrine_Core::HYDRATE_ON_DEMAND) {
$hydrationDriver = $this->_hydrator->getHydratorDriver($hydrationMode, $this->_tableAliasMap);
$result = new Doctrine_Collection_OnDemand($stmt, $hydrationDriver, $this->_tableAliasMap);
} else {
$result = $this->_hydrator->hydrateResultSet($stmt, $this->_tableAliasMap);
}
}
}
if ($this->getConnection()->getAttribute(Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS)) {
$this->free();
}
return $result;
}
/**
* Blank template method free(). Override to be used to free query object memory
*/
public function free()
{
}
/**
* Get the dql call back for this query
*
* @return array $callback
*/
protected function _getDqlCallback()
{
$callback = false;
if ( ! empty($this->_dqlParts['from'])) {
switch ($this->_type) {
case self::DELETE:
$callback = array(
'callback' => 'preDqlDelete',
'const' => Doctrine_Event::RECORD_DQL_DELETE
);
break;
case self::UPDATE:
$callback = array(
'callback' => 'preDqlUpdate',
'const' => Doctrine_Event::RECORD_DQL_UPDATE
);
break;
case self::SELECT:
$callback = array(
'callback' => 'preDqlSelect',
'const' => Doctrine_Event::RECORD_DQL_SELECT
);
break;
}
}
return $callback;
}
/**
* Pre query method which invokes the pre*Query() methods on the model instance or any attached
* record listeners
*
* @return void
*/
protected function _preQuery($params = array())
{
if ( ! $this->_preQueried && $this->getConnection()->getAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS)) {
$this->_preQueried = true;
$callback = $this->_getDqlCallback();
// if there is no callback for the query type, then we can return early
if ( ! $callback) {
return;
}
foreach ($this->_getDqlCallbackComponents($params) as $alias => $component) {
$table = $component['table'];
$record = $table->getRecordInstance();
// Trigger preDql*() callback event
$params = array('component' => $component, 'alias' => $alias);
$event = new Doctrine_Event($record, $callback['const'], $this, $params);
$record->$callback['callback']($event);
$table->getRecordListener()->$callback['callback']($event);
}
}
// Invoke preQuery() hook on Doctrine_Query for child classes which implement this hook
$this->preQuery();
}
/**
* Returns an array of components to execute the query callbacks for
*
* @param array $params
* @return array $components
*/
protected function _getDqlCallbackComponents($params = array())
{
$componentsBefore = array();
if ($this->isSubquery()) {
$componentsBefore = $this->getQueryComponents();
}
$copy = $this->copy();
$copy->getSqlQuery($params, false);
$componentsAfter = $copy->getQueryComponents();
$this->_rootAlias = $copy->getRootAlias();
$copy->free();
if ($componentsBefore !== $componentsAfter) {
return array_diff_assoc($componentsAfter, $componentsBefore);
} else {
return $componentsAfter;
}
}
/**
* Blank hook methods which can be implemented in Doctrine_Query child classes
*
* @return void
*/
public function preQuery()
{
}
/**
* Constructs the query from the cached form.
*
* @param string The cached query, in a serialized form.
* @return array The custom component that was cached together with the essential
* query data. This can be either a result set (result caching)
* or an SQL query string (query caching).
*/
protected function _constructQueryFromCache($cached)
{
$cached = unserialize($cached);
$this->_tableAliasMap = $cached[2];
$customComponent = $cached[0];
$queryComponents = array();
$cachedComponents = $cached[1];
foreach ($cachedComponents as $alias => $components) {
$e = explode('.', $components['name']);
if (count($e) === 1) {
$manager = Doctrine_Manager::getInstance();
if ( ! $this->_passedConn && $manager->hasConnectionForComponent($e[0])) {
$this->_conn = $manager->getConnectionForComponent($e[0]);
}
$queryComponents[$alias]['table'] = $this->_conn->getTable($e[0]);
} else {
$queryComponents[$alias]['parent'] = $e[0];
$queryComponents[$alias]['relation'] = $queryComponents[$e[0]]['table']->getRelation($e[1]);
$queryComponents[$alias]['table'] = $queryComponents[$alias]['relation']->getTable();
}
if (isset($components['agg'])) {
$queryComponents[$alias]['agg'] = $components['agg'];
}
if (isset($components['map'])) {
$queryComponents[$alias]['map'] = $components['map'];
}
}
$this->_queryComponents = $queryComponents;
return $customComponent;
}
/**
* getCachedForm
* returns the cached form of this query for given resultSet
*
* @param array $resultSet
* @return string serialized string representation of this query
*/
public function getCachedForm($customComponent = null)
{
$componentInfo = array();
foreach ($this->getQueryComponents() as $alias => $components) {
if ( ! isset($components['parent'])) {
$componentInfo[$alias]['name'] = $components['table']->getComponentName();
} else {
$componentInfo[$alias]['name'] = $components['parent'] . '.' . $components['relation']->getAlias();
}
if (isset($components['agg'])) {
$componentInfo[$alias]['agg'] = $components['agg'];
}
if (isset($components['map'])) {
$componentInfo[$alias]['map'] = $components['map'];
}
}
if ($customComponent instanceof Doctrine_Collection) {
foreach ($customComponent as $record) {
$record->serializeReferences(true);
}
}
return serialize(array($customComponent, $componentInfo, $this->getTableAliasMap()));
}
/**
* Adds fields or aliased functions.
*
* This method adds fields or dbms functions to the SELECT query part.
* <code>
* $query->addSelect('COUNT(p.id) as num_phonenumbers');
* </code>
*
* @param string $select Query SELECT part
* @return Doctrine_Query
*/
public function addSelect($select)
{
return $this->_addDqlQueryPart('select', $select, true);
}
/**
* addSqlTableAlias
* adds an SQL table alias and associates it a component alias
*
* @param string $componentAlias the alias for the query component associated with given tableAlias
* @param string $tableAlias the table alias to be added
* @return Doctrine_Query_Abstract
*/
public function addSqlTableAlias($sqlTableAlias, $componentAlias)
{
$this->_tableAliasMap[$sqlTableAlias] = $componentAlias;
return $this;
}
/**
* addFrom
* adds fields to the FROM part of the query
*
* @param string $from Query FROM part
* @return Doctrine_Query
*/
public function addFrom($from)
{
return $this->_addDqlQueryPart('from', $from, true);
}
/**
* Alias for @see andWhere().
* @return Doctrine_Query this object
*/
public function addWhere($where, $params = array())
{
return $this->andWhere($where, $params);
}
/**
* Adds conditions to the WHERE part of the query.
* <code>
* $q->andWhere('u.birthDate > ?', '1975-01-01');
* </code>
*
* @param string $where Query WHERE part
* @param mixed $params An array of parameters or a simple scalar
* @return Doctrine_Query
*/
public function andWhere($where, $params = array())
{
if (is_array($params)) {
$this->_params['where'] = array_merge($this->_params['where'], $params);
} else {
$this->_params['where'][] = $params;
}
if ($this->_hasDqlQueryPart('where')) {
$this->_addDqlQueryPart('where', 'AND', true);
}
return $this->_addDqlQueryPart('where', $where, true);
}
/**
* Adds conditions to the WHERE part of the query
* <code>
* $q->orWhere('u.role = ?', 'admin');
* </code>
*
* @param string $where Query WHERE part
* @param mixed $params An array of parameters or a simple scalar
* @return Doctrine_Query
*/
public function orWhere($where, $params = array())
{
if (is_array($params)) {
$this->_params['where'] = array_merge($this->_params['where'], $params);
} else {
$this->_params['where'][] = $params;
}
if ($this->_hasDqlQueryPart('where')) {
$this->_addDqlQueryPart('where', 'OR', true);
}
return $this->_addDqlQueryPart('where', $where, true);
}
/**
* Adds IN condition to the query WHERE part. Alias to @see andWhereIn().
*
* @param string $expr the operand of the IN
* @param mixed $params an array of parameters or a simple scalar
* @param boolean $not whether or not to use NOT in front of IN
* @return Doctrine_Query
*/
public function whereIn($expr, $params = array(), $not = false)
{
return $this->andWhereIn($expr, $params, $not);
}
/**
* Adds IN condition to the query WHERE part
* <code>
* $q->whereIn('u.id', array(10, 23, 44));
* </code>
*
* @param string $expr The operand of the IN
* @param mixed $params An array of parameters or a simple scalar
* @param boolean $not Whether or not to use NOT in front of IN. Defaults to false (simple IN clause)
* @return Doctrine_Query this object.
*/
public function andWhereIn($expr, $params = array(), $not = false)
{
// if there's no params, return (else we'll get a WHERE IN (), invalid SQL)
if (isset($params) and (count($params) == 0)) {
return $this;
}
if ($this->_hasDqlQueryPart('where')) {
$this->_addDqlQueryPart('where', 'AND', true);
}
return $this->_addDqlQueryPart('where', $this->_processWhereIn($expr, $params, $not), true);
}
/**
* Adds IN condition to the query WHERE part, appending it with an OR operator.
* <code>
* $q->orWhereIn('u.id', array(10, 23))
* ->orWhereIn('u.id', 44);
* // will select all record with id equal to 10, 23 or 44
* </code>
*
* @param string $expr The operand of the IN
* @param mixed $params An array of parameters or a simple scalar
* @param boolean $not Whether or not to use NOT in front of IN
* @return Doctrine_Query
*/
public function orWhereIn($expr, $params = array(), $not = false)
{
// if there's no params, return (else we'll get a WHERE IN (), invalid SQL)
if (isset($params) and (count($params) == 0)) {
return $this;
}
if ($this->_hasDqlQueryPart('where')) {
$this->_addDqlQueryPart('where', 'OR', true);
}
return $this->_addDqlQueryPart('where', $this->_processWhereIn($expr, $params, $not), true);
}
/**
* @nodoc
*/
protected function _processWhereIn($expr, $params = array(), $not = false)
{
$params = (array) $params;
// if there's no params, return (else we'll get a WHERE IN (), invalid SQL)
if (count($params) == 0) {
throw new Doctrine_Query_Exception('You must pass at least one parameter when using an IN() condition.');
}
$a = array();
foreach ($params as $k => $value) {
if ($value instanceof Doctrine_Expression) {
$value = $value->getSql();
unset($params[$k]);
} else {
$value = '?';
}
$a[] = $value;
}
$this->_params['where'] = array_merge($this->_params['where'], $params);
return $expr . ($not === true ? ' NOT' : '') . ' IN (' . implode(', ', $a) . ')';
}
/**
* Adds NOT IN condition to the query WHERE part.
* <code>
* $q->whereNotIn('u.id', array(10, 20));
* // will exclude users with id 10 and 20 from the select
* </code>
*
* @param string $expr the operand of the NOT IN
* @param mixed $params an array of parameters or a simple scalar
* @return Doctrine_Query this object
*/
public function whereNotIn($expr, $params = array())
{
return $this->whereIn($expr, $params, true);
}
/**
* Adds NOT IN condition to the query WHERE part
* Alias for @see whereNotIn().
*
* @param string $expr The operand of the NOT IN
* @param mixed $params An array of parameters or a simple scalar
* @return Doctrine_Query
*/
public function andWhereNotIn($expr, $params = array())
{
return $this->andWhereIn($expr, $params, true);
}
/**
* Adds NOT IN condition to the query WHERE part
*
* @param string $expr The operand of the NOT IN
* @param mixed $params An array of parameters or a simple scalar
* @return Doctrine_Query
*/
public function orWhereNotIn($expr, $params = array())
{
return $this->orWhereIn($expr, $params, true);
}
/**
* Adds fields to the GROUP BY part of the query.
* <code>
* $q->groupBy('u.id');
* </code>
*
* @param string $groupby Query GROUP BY part
* @return Doctrine_Query
*/
public function addGroupBy($groupby)
{
return $this->_addDqlQueryPart('groupby', $groupby, true);
}
/**
* Adds conditions to the HAVING part of the query.
*
* This methods add HAVING clauses. These clauses are used to narrow the
* results by operating on aggregated values.
* <code>
* $q->having('num_phonenumbers > ?', 1);
* </code>
*
* @param string $having Query HAVING part
* @param mixed $params an array of parameters or a simple scalar
* @return Doctrine_Query
*/
public function addHaving($having, $params = array())
{
if (is_array($params)) {
$this->_params['having'] = array_merge($this->_params['having'], $params);
} else {
$this->_params['having'][] = $params;
}
return $this->_addDqlQueryPart('having', $having, true);
}
/**
* addOrderBy
* adds fields to the ORDER BY part of the query
*
* @param string $orderby Query ORDER BY part
* @return Doctrine_Query
*/
public function addOrderBy($orderby)
{
return $this->_addDqlQueryPart('orderby', $orderby, true);
}
/**
* select
* sets the SELECT part of the query
*
* @param string $select Query SELECT part
* @return Doctrine_Query
*/
public function select($select = null)
{
$this->_type = self::SELECT;
if ($select) {
return $this->_addDqlQueryPart('select', $select);
} else {
return $this;
}
}
/**
* distinct
* Makes the query SELECT DISTINCT.
* <code>
* $q->distinct();
* </code>
*
* @param bool $flag Whether or not the SELECT is DISTINCT (default true).
* @return Doctrine_Query
*/
public function distinct($flag = true)
{
$this->_sqlParts['distinct'] = (bool) $flag;
return $this;
}
/**
* forUpdate
* Makes the query SELECT FOR UPDATE.
*
* @param bool $flag Whether or not the SELECT is FOR UPDATE (default true).
* @return Doctrine_Query
*/
public function forUpdate($flag = true)
{
$this->_sqlParts['forUpdate'] = (bool) $flag;
return $this;
}
/**
* delete
* sets the query type to DELETE
*
* @return Doctrine_Query
*/
public function delete($from = null)
{
$this->_type = self::DELETE;
if ($from != null) {
return $this->_addDqlQueryPart('from', $from);
}
return $this;
}
/**
* update
* sets the UPDATE part of the query
*
* @param string $update Query UPDATE part
* @return Doctrine_Query
*/
public function update($from = null)
{
$this->_type = self::UPDATE;
if ($from != null) {
return $this->_addDqlQueryPart('from', $from);
}
return $this;
}
/**
* set
* sets the SET part of the query
*
* @param string $update Query UPDATE part
* @return Doctrine_Query
*/
public function set($key, $value = null, $params = null)
{
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->set($k, '?', array($v));
}
return $this;
} else {
if ($params !== null) {
if (is_array($params)) {
$this->_params['set'] = array_merge($this->_params['set'], $params);
} else {
$this->_params['set'][] = $params;
}
}
return $this->_addDqlQueryPart('set', $key . ' = ' . $value, true);
}
}
/**
* from
* sets the FROM part of the query
* <code>
* $q->from('User u');
* </code>
*
* @param string $from Query FROM part
* @return Doctrine_Query
*/
public function from($from)
{
return $this->_addDqlQueryPart('from', $from);
}
/**
* innerJoin
* appends an INNER JOIN to the FROM part of the query
*
* @param string $join Query INNER JOIN
* @return Doctrine_Query
*/
public function innerJoin($join, $params = array())
{
if (is_array($params)) {
$this->_params['join'] = array_merge($this->_params['join'], $params);
} else {
$this->_params['join'][] = $params;
}
return $this->_addDqlQueryPart('from', 'INNER JOIN ' . $join, true);
}
/**
* leftJoin
* appends a LEFT JOIN to the FROM part of the query
*
* @param string $join Query LEFT JOIN
* @return Doctrine_Query
*/
public function leftJoin($join, $params = array())
{
if (is_array($params)) {
$this->_params['join'] = array_merge($this->_params['join'], $params);
} else {
$this->_params['join'][] = $params;
}
return $this->_addDqlQueryPart('from', 'LEFT JOIN ' . $join, true);
}
/**
* groupBy
* sets the GROUP BY part of the query
*
* @param string $groupby Query GROUP BY part
* @return Doctrine_Query
*/
public function groupBy($groupby)
{
return $this->_addDqlQueryPart('groupby', $groupby);
}
/**
* where
* sets the WHERE part of the query
*
* @param string $join Query WHERE part
* @param mixed $params an array of parameters or a simple scalar
* @return Doctrine_Query
*/
public function where($where, $params = array())
{
$this->_params['where'] = array();
if (is_array($params)) {
$this->_params['where'] = $params;
} else {
$this->_params['where'][] = $params;
}
return $this->_addDqlQueryPart('where', $where);
}
/**
* having
* sets the HAVING part of the query
*
* @param string $having Query HAVING part
* @param mixed $params an array of parameters or a simple scalar
* @return Doctrine_Query
*/
public function having($having, $params = array())
{
$this->_params['having'] = array();
if (is_array($params)) {
$this->_params['having'] = $params;
} else {
$this->_params['having'][] = $params;
}
return $this->_addDqlQueryPart('having', $having);
}
/**
* Sets the ORDER BY part of the query.
* <code>
* $q->orderBy('u.name');
* $query->orderBy('u.birthDate DESC');
* </code>
*
* @param string $orderby Query ORDER BY part
* @return Doctrine_Query
*/
public function orderBy($orderby)
{
return $this->_addDqlQueryPart('orderby', $orderby);
}
/**
* limit
* sets the Query query limit
*
* @param integer $limit limit to be used for limiting the query results
* @return Doctrine_Query
*/
public function limit($limit)
{
return $this->_addDqlQueryPart('limit', $limit);
}
/**
* offset
* sets the Query query offset
*
* @param integer $offset offset to be used for paginating the query
* @return Doctrine_Query
*/
public function offset($offset)
{
return $this->_addDqlQueryPart('offset', $offset);
}
/**
* Resets all the sql parts.
*
* @return void
*/
protected function clear()
{
$this->_sqlParts = array(
'select' => array(),
'distinct' => false,
'forUpdate' => false,
'from' => array(),
'set' => array(),
'join' => array(),
'where' => array(),
'groupby' => array(),
'having' => array(),
'orderby' => array(),
'limit' => false,
'offset' => false,
);
}
public function setHydrationMode($hydrationMode)
{
$this->_hydrator->setHydrationMode($hydrationMode);
return $this;
}
/**
* Gets the components of this query.
*/
public function getQueryComponents()
{
return $this->_queryComponents;
}
/**
* Return the SQL parts.
*
* @return array The parts
*/
public function getSqlParts()
{
return $this->_sqlParts;
}
/**
* getType
*
* returns the type of this query object
* by default the type is Doctrine_Query_Abstract::SELECT but if update() or delete()
* are being called the type is Doctrine_Query_Abstract::UPDATE and Doctrine_Query_Abstract::DELETE,
* respectively
*
* @see Doctrine_Query_Abstract::SELECT
* @see Doctrine_Query_Abstract::UPDATE
* @see Doctrine_Query_Abstract::DELETE
*
* @return integer return the query type
*/
public function getType()
{
return $this->_type;
}
/**
* useResultCache
*
* @param Doctrine_Cache_Interface|bool $driver cache driver
* @param integer $timeToLive how long the cache entry is valid
* @param string $resultCacheHash The key to use for storing the queries result cache entry
* @return Doctrine_Query this object
*/
public function useResultCache($driver = true, $timeToLive = null, $resultCacheHash = null)
{
if ($driver !== null && $driver !== true && ! ($driver instanceOf Doctrine_Cache_Interface)) {
$msg = 'First argument should be instance of Doctrine_Cache_Interface or null.';
throw new Doctrine_Query_Exception($msg);
}
$this->_resultCache = $driver;
$this->_resultCacheHash = $resultCacheHash;
if ($timeToLive !== null) {
$this->setResultCacheLifeSpan($timeToLive);
}
return $this;
}
/**
* Set the result cache hash to be used for storing the results in the cache driver
*
* @param string $resultCacheHash
* @return void
*/
public function setResultCacheHash($resultCacheHash)
{
$this->_resultCacheHash = $resultCacheHash;
return $this;
}
/**
* Clear the result cache entry for this query
*
* @return void
*/
public function clearResultCache()
{
$this->getResultCacheDriver()
->delete($this->getResultCacheHash());
return $this;
}
/**
* useQueryCache
*
* @param Doctrine_Cache_Interface|bool $driver cache driver
* @param integer $timeToLive how long the cache entry is valid
* @return Doctrine_Query this object
*/
public function useQueryCache($driver = true, $timeToLive = null)
{
if ($driver !== null && $driver !== true && $driver !== false && ! ($driver instanceOf Doctrine_Cache_Interface)) {
$msg = 'First argument should be instance of Doctrine_Cache_Interface or null.';
throw new Doctrine_Query_Exception($msg);
}
$this->_queryCache = $driver;
if ($timeToLive !== null) {
$this->setQueryCacheLifeSpan($timeToLive);
}
return $this;
}
/**
* expireCache
*
* @param boolean $expire whether or not to force cache expiration
* @return Doctrine_Query this object
*/
public function expireResultCache($expire = true)
{
$this->_expireResultCache = $expire;
return $this;
}
/**
* expireQueryCache
*
* @param boolean $expire whether or not to force cache expiration
* @return Doctrine_Query this object
*/
public function expireQueryCache($expire = true)
{
$this->_expireQueryCache = $expire;
return $this;
}
/**
* setResultCacheLifeSpan
*
* @param integer $timeToLive how long the cache entry is valid (in seconds)
* @return Doctrine_Query this object
*/
public function setResultCacheLifeSpan($timeToLive)
{
if ($timeToLive !== null) {
$timeToLive = (int) $timeToLive;
}
$this->_resultCacheTTL = $timeToLive;
return $this;
}
/**
* Gets the life span of the result cache in seconds.
*
* @return integer
*/
public function getResultCacheLifeSpan()
{
return $this->_resultCacheTTL;
}
/**
* setQueryCacheLifeSpan
*
* @param integer $timeToLive how long the cache entry is valid
* @return Doctrine_Query this object
*/
public function setQueryCacheLifeSpan($timeToLive)
{
if ($timeToLive !== null) {
$timeToLive = (int) $timeToLive;
}
$this->_queryCacheTTL = $timeToLive;
return $this;
}
/**
* Gets the life span of the query cache the Query object is using.
*
* @return integer The life span in seconds.
*/
public function getQueryCacheLifeSpan()
{
return $this->_queryCacheTTL;
}
/**
* getResultCacheDriver
* returns the cache driver used for caching result sets
*
* @return Doctrine_Cache_Interface|boolean|null cache driver
*/
public function getResultCacheDriver()
{
if ($this->_resultCache instanceof Doctrine_Cache_Interface) {
return $this->_resultCache;
} else {
return $this->_conn->getResultCacheDriver();
}
}
/**
* getQueryCacheDriver
* returns the cache driver used for caching queries
*
* @return Doctrine_Cache_Interface|boolean|null cache driver
*/
public function getQueryCacheDriver()
{
if ($this->_queryCache instanceof Doctrine_Cache_Interface) {
return $this->_queryCache;
} else {
return $this->_conn->getQueryCacheDriver();
}
}
/**
* getConnection
*
* @return Doctrine_Connection
*/
public function getConnection()
{
return $this->_conn;
}
/**
* Checks if there's at least one DQL part defined to the internal parts collection.
*
* @param string $queryPartName The name of the query part.
* @return boolean
*/
protected function _hasDqlQueryPart($queryPartName)
{
return count($this->_dqlParts[$queryPartName]) > 0;
}
/**
* Adds a DQL part to the internal parts collection.
*
* This method add the part specified to the array named by $queryPartName.
* Most part names support multiple parts addition.
*
* @see $_dqlParts;
* @see Doctrine_Query::getDqlPart()
* @param string $queryPartName The name of the query part.
* @param string $queryPart The actual query part to add.
* @param boolean $append Whether to append $queryPart to already existing
* parts under the same $queryPartName. Defaults to FALSE
* (previously added parts with the same name get overridden).
*/
protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false)
{
// We should prevent nullable query parts
if ($queryPart === null) {
throw new Doctrine_Query_Exception('Cannot define NULL as part of query when defining \'' . $queryPartName . '\'.');
}
if ($append) {
$this->_dqlParts[$queryPartName][] = $queryPart;
} else {
$this->_dqlParts[$queryPartName] = array($queryPart);
}
$this->_state = Doctrine_Query::STATE_DIRTY;
return $this;
}
/**
* _processDqlQueryPart
* parses given query part
*
* @param string $queryPartName the name of the query part
* @param array $queryParts an array containing the query part data
* @return Doctrine_Query this object
* @todo Better description. "parses given query part" ??? Then wheres the difference
* between process/parseQueryPart? I suppose this does something different.
*/
protected function _processDqlQueryPart($queryPartName, $queryParts)
{
$this->removeSqlQueryPart($queryPartName);
if (is_array($queryParts) && ! empty($queryParts)) {
foreach ($queryParts as $queryPart) {
$parser = $this->_getParser($queryPartName);
$sql = $parser->parse($queryPart);
if (isset($sql)) {
if ($queryPartName == 'limit' || $queryPartName == 'offset') {
$this->setSqlQueryPart($queryPartName, $sql);
} else {
$this->addSqlQueryPart($queryPartName, $sql);
}
}
}
}
}
/**
* _getParser
* parser lazy-loader
*
* @throws Doctrine_Query_Exception if unknown parser name given
* @return Doctrine_Query_Part
* @todo Doc/Description: What is the parameter for? Which parsers are available?
*/
protected function _getParser($name)
{
if ( ! isset($this->_parsers[$name])) {
$class = 'Doctrine_Query_' . ucwords(strtolower($name));
Doctrine_Core::autoload($class);
if ( ! class_exists($class)) {
throw new Doctrine_Query_Exception('Unknown parser ' . $name);
}
$this->_parsers[$name] = new $class($this, $this->_tokenizer);
}
return $this->_parsers[$name];
}
/**
* Gets the SQL query that corresponds to this query object.
* The returned SQL syntax depends on the connection driver that is used
* by this query object at the time of this method call.
*
* @param array $params
*/
abstract public function getSqlQuery($params = array());
/**
* parseDqlQuery
* parses a dql query
*
* @param string $query query to be parsed
* @return Doctrine_Query_Abstract this object
*/
abstract public function parseDqlQuery($query);
/**
* toString magic call
* this method is automatically called when Doctrine_Query object is trying to be used as a string
* So, it it converted into its DQL correspondant
*
* @return string DQL string
*/
public function __toString()
{
return $this->getDql();
}
/**
* Gets the disableLimitSubquery property.
*
* @return boolean
*/
public function getDisableLimitSubquery()
{
return $this->disableLimitSubquery;
}
/**
* Allows you to set the disableLimitSubquery property -- setting this to true will
* restrict the query object from using the limit sub query method of tranversing many relationships.
*
* @param boolean $disableLimitSubquery
*/
public function setDisableLimitSubquery($disableLimitSubquery)
{
$this->disableLimitSubquery = $disableLimitSubquery;
}
} | projectestac/intraweb | intranet/lib/vendor/Doctrine/Doctrine/Query/Abstract.php | PHP | gpl-3.0 | 67,293 |
/* This file is part of MAUS: http://micewww.pp.rl.ac.uk:8080/projects/maus
*
* MAUS 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.
*
* MAUS 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 MAUS. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "src/map/MapCppEMRSpacePoints/MapCppEMRSpacePoints.hh"
namespace MAUS {
PyMODINIT_FUNC init_MapCppEMRSpacePoints(void) {
PyWrapMapBase<MAUS::MapCppEMRSpacePoints>::PyWrapMapBaseModInit
("MapCppEMRSpacePoints", "", "", "", "");
}
MapCppEMRSpacePoints::MapCppEMRSpacePoints()
: MapBase<MAUS::Data>("MapCppEMRSpacePoints") {
}
void MapCppEMRSpacePoints::_birth(const std::string& argJsonConfigDocument) {
_classname = "MapCppEMRSpacePoints";
char* pMAUS_ROOT_DIR = getenv("MAUS_ROOT_DIR");
if (!pMAUS_ROOT_DIR) {
throw MAUS::Exceptions::Exception(Exceptions::recoverable,
"Could not resolve ${MAUS_ROOT_DIR} environment variable",
"MapCppEMRSpacePoints::birth");
}
// JsonCpp setup
Json::Value configJSON;
Json::Value map_file_name;
Json::Value xEnable_V1731_Unpacking;
Json::Value xEnable_DBB_Unpacking;
configJSON = JsonWrapper::StringToJson(argJsonConfigDocument);
// Fetch variables
_number_of_planes = configJSON["EMRnumberOfPlanes"].asInt();
_number_of_bars = configJSON["EMRnumberOfBars"].asInt();
_tot_func_p1 = configJSON["EMRtotFuncP1"].asDouble();
_tot_func_p2 = configJSON["EMRtotFuncP2"].asDouble();
_tot_func_p3 = configJSON["EMRtotFuncP3"].asDouble();
// Load the EMR calibration map
bool loaded = _calibMap.InitializeFromCards(configJSON);
if ( !loaded )
throw(Exceptions::Exception(Exceptions::recoverable,
"Could not find EMR calibration map",
"MapCppEMRRecon::birth"));
// Load the EMR attenuation map
loaded = _attenMap.InitializeFromCards(configJSON);
if ( !loaded )
throw(Exceptions::Exception(Exceptions::recoverable,
"Could not find EMR attenuation map",
"MapCppEMRReccon::birth"));
// Load the EMR geometry map
loaded = _geoMap.InitializeFromCards(configJSON);
if ( !loaded )
throw(Exceptions::Exception(Exceptions::recoverable,
"Could not find EMR geometry map",
"MapCppEMRReccon::birth"));
}
void MapCppEMRSpacePoints::_death() {
}
void MapCppEMRSpacePoints::_process(Data *data) const {
// Routine data checks before processing it
if ( !data )
throw Exceptions::Exception(Exceptions::recoverable, "Data was NULL",
"MapCppEMRSpacePoints::_process");
Spill* spill = data->GetSpill();
if ( !spill )
throw Exceptions::Exception(Exceptions::recoverable, "Spill was NULL",
"MapCppEMRSpacePoints::_process");
if ( spill->GetDaqEventType() != "physics_event" )
return;
size_t nPartEvents = spill->GetReconEventSize();
if ( !nPartEvents )
return;
if ( !spill->GetEMRSpillData() )
return;
bool emrData = false;
for (size_t iPe = 0; iPe < nPartEvents; iPe++) {
EMREvent *evt = spill->GetReconEvents()->at(iPe)->GetEMREvent();
if ( evt->GetMotherPtr() ) {
if ( evt->GetMotherPtr()->GetEMRPlaneHitArraySize() ) {
emrData = true;
break;
}
}
}
if ( !emrData )
return;
// Create a temporary array containing n+n' plane hit arrays (1 per trigger + spill data)
size_t nSeconPartEvents = spill->GetEMRSpillData()->GetEMREventTrackArraySize();
EMREventVector emr_events_tmp(nPartEvents+nSeconPartEvents);
// Remove the crosstalk hits from each plane hit
clean_crosstalk(spill, emr_events_tmp);
// Reconstruct the coordinates of the spacepoint for each plane hit
reconstruct_coordinates(emr_events_tmp);
// Correct the SAPMT charge and reconstruct the MAPMT charge for the fibre attenuation
correct_charge(emr_events_tmp, nPartEvents);
// Fill the Recon event array with spill information (1 per trigger + daughter candidates)
fill(spill, emr_events_tmp, nPartEvents);
}
void MapCppEMRSpacePoints::clean_crosstalk(MAUS::Spill* spill,
EMREventVector& emr_events_tmp) const {
size_t nPartEvents = spill->GetReconEvents()->size();
size_t nSeconPartEvents = spill->GetEMRSpillData()->GetEMREventTrackArraySize();
for (size_t iPe = 0; iPe < nPartEvents+nSeconPartEvents; iPe++) {
// Skip events without an EventTrack (mother or candidate)
EMREventTrack* evtTrack;
if ( iPe < nPartEvents ) {
evtTrack = spill->GetReconEvents()->at(iPe)->GetEMREvent()->GetMotherPtr();
} else {
evtTrack = spill->GetEMRSpillData()->GetEMREventTrackArray()[iPe-nPartEvents];
}
if ( !evtTrack )
continue;
// Reject arrays that do not contain both projections (cannot reconstruct a SP)
EMRPlaneHitArray plArray = evtTrack->GetEMRPlaneHitArray();
bool HitXY[2] = {false, false};
for (size_t iPlane = 0; iPlane < plArray.size(); iPlane++) {
int xOri = plArray[iPlane]->GetOrientation();
if ( !HitXY[xOri] && plArray[iPlane]->GetEMRBarHitArraySize() )
HitXY[xOri] = true;
if ( HitXY[0] && HitXY[1] )
break;
}
if ( !HitXY[0] || !HitXY[1] )
continue;
// Reject the crosstalk in each plane
for (size_t iPlane = 0; iPlane < plArray.size(); iPlane++) {
EMRBarHitArray barHitArray = plArray[iPlane]->GetEMRBarHitArray();
std::vector<EMRBarHitArray> barHitGroupVector;
if ( !barHitArray.size() ) { // Skip the plane if there is no bar
continue;
} else if ( barHitArray.size() == 1 ) { // Select automatically if there is only 1 hit
barHitGroupVector.push_back(EMRBarHitArray());
barHitGroupVector[0].push_back(barHitArray[0]);
} else { // Keep only the most energetic bunch if there is >= 2 hits
// Sort the vector in with respect to the bar channel ID
sort(barHitArray.begin(), barHitArray.end(),
[] (const EMRBarHit& a, const EMRBarHit& b) {
return a.GetChannel() < b.GetChannel();
});
// Create groups of adjacent hits
barHitGroupVector.push_back(EMRBarHitArray());
barHitGroupVector[0].push_back(barHitArray[0]);
for (size_t iHit = 1; iHit < barHitArray.size(); iHit++) {
int aBar = barHitArray[iHit-1].GetChannel()%_number_of_bars;
int bBar = barHitArray[iHit].GetChannel()%_number_of_bars;
if ( abs(bBar-aBar) == 1 ) {
barHitGroupVector.back().push_back(barHitArray[iHit]);
} else {
barHitGroupVector.push_back(EMRBarHitArray());
barHitGroupVector.back().push_back(barHitArray[iHit]);
}
}
}
// Only keep the group with the highest energy deposition (gets rid of XT)
size_t mGroup(0);
double mCharge(0.);
for (size_t iGroup = 0; iGroup < barHitGroupVector.size(); iGroup++) {
double aCharge(0);
for (size_t iHit = 0; iHit < barHitGroupVector[iGroup].size(); iHit++) {
double xTot = barHitGroupVector[iGroup][iHit].GetTot();
double xCharge = exp(xTot/_tot_func_p1-log(_tot_func_p2))
- _tot_func_p3/_tot_func_p2;
aCharge += xCharge;
}
if ( aCharge > mCharge ) {
mGroup = iGroup;
mCharge = aCharge;
}
}
// Fill the temporary array with the selected hits (XT cleaned) and plane information
EMRPlaneTmp plane;
for (size_t iHit = 0; iHit < barHitGroupVector[mGroup].size(); iHit++)
plane._barhits.push_back(barHitGroupVector[mGroup][iHit]);
plane._plane = plArray[iPlane]->GetPlane();
plane._charge = plArray[iPlane]->GetCharge();
emr_events_tmp[iPe].push_back(plane);
}
}
}
void MapCppEMRSpacePoints::reconstruct_coordinates(EMREventVector& emr_events_tmp)
const {
for (size_t iPe = 0; iPe < emr_events_tmp.size(); iPe++) {
// Sort the temporary planes from upstreammost to the downstreammost
sort(emr_events_tmp[iPe].begin(), emr_events_tmp[iPe].end(),
[] (const EMRPlaneTmp& a, const EMRPlaneTmp& b) {
return a._plane < b._plane;
});
// Look for hits in the other projection to reconstruct the missing coordinate
for (size_t iPlane = 0; iPlane < emr_events_tmp[iPe].size(); iPlane++) {
if ( !emr_events_tmp[iPe][iPlane]._barhits.size() )
continue;
int xPlane = emr_events_tmp[iPe][iPlane]._plane;
int xOri = xPlane%2;
ThreeVector v0, v1, v2;
bool Hit1(false), Hit2(false);
double a(-1.), b(-1.), xi(-1.);
// Look backwards for hits in the other projection
int aPlane(0);
for (aPlane = iPlane-1; aPlane >= 0; aPlane--) {
if ( emr_events_tmp[iPe][aPlane]._barhits.size() &&
emr_events_tmp[iPe][aPlane]._plane%2 != xOri ) {
v1 = get_weighted_position(emr_events_tmp[iPe][aPlane]._barhits);
Hit1 = true;
break;
}
}
// Look forwards for hits in the other projection
for (size_t bPlane = iPlane+1; bPlane < emr_events_tmp[iPe].size(); bPlane++) {
if ( emr_events_tmp[iPe][bPlane]._barhits.size() &&
emr_events_tmp[iPe][bPlane]._plane%2 != xOri ) {
if ( !Hit2 ) {
v2 = get_weighted_position(emr_events_tmp[iPe][bPlane]._barhits);
Hit2 = true;
if ( Hit1 )
break;
} else if ( Hit2 && !Hit1 ) {
v1 = get_weighted_position(emr_events_tmp[iPe][bPlane]._barhits);
Hit1 = true;
break;
}
}
}
// Look backwards for the second hit if nothing found in the forward direction
if ( Hit1 && !Hit2 ) {
for (int cPlane = aPlane-1; cPlane >= 0; cPlane--) {
if ( emr_events_tmp[iPe][cPlane]._barhits.size() &&
emr_events_tmp[iPe][cPlane]._plane%2 != xOri ) {
v2 = get_weighted_position(emr_events_tmp[iPe][cPlane]._barhits);
Hit2 = true;
break;
}
}
}
// Calculate the parameters of the line between the two complementary planes
if ( Hit1 && Hit2 ) {
if ( !xOri ) {
a = (v2.y() - v1.y())/(v2.z() - v1.z());
b = v1.y() - a*v1.z();
} else {
a = (v2.x() - v1.x())/(v2.z() - v1.z());
b = v1.x() - a*v1.z();
}
} else if ( Hit1 && !Hit2 ) {
if ( !xOri ) {
b = v1.y();
} else {
b = v1.x();
}
a = 0.;
} else if ( !Hit1 && Hit2 ) {
if ( !xOri ) {
b = v2.y();
} else {
b = v2.x();
}
a = 0.;
}
// Set the transverse (x or y) and longitudinal (z) errors
xi = (v0.z() - v1.z())/(v2.z() - v1.z());
ThreeVector dim = _geoMap.Dimensions(); // (w, h, l) of an EMR bar
double etrans = dim.y()/(2*sqrt(6)); // Transverse uncertainty
double elong = dim.z()/(3*sqrt(2)); // Longitudinal uncertainty
for (size_t iHit = 0; iHit < emr_events_tmp[iPe][iPlane]._barhits.size(); iHit++) {
// Find the position of the bar in local coordinates
EMRBarHit barHit = emr_events_tmp[iPe][iPlane]._barhits[iHit];
int xBar = barHit.GetChannel()%_number_of_bars;
EMRChannelKey xKey(xPlane, xOri, xBar, "emr");
v0 = _geoMap.LocalPosition(xKey);
// Set the reconstructed (y or x) errors
if ( Hit1 && Hit2 ) {
xi = (v0.z() - v1.z())/(v2.z() - v1.z());
} else {
xi = 0.;
}
double erecon = sqrt((pow(xi, 2) // Recon uncertainty !!!TODO!!! (FIX)
+ pow(1-xi, 2)) * pow(etrans, 2)
+ pow(a, 2) * (pow(xi, 2) + pow(1-xi, 2)) * pow(elong, 2));
// Add the missing coordinate and set the appropriate errors
// Interpolate or extrapolate y for an x plane and x for a y plane
ThreeVector errors;
if ( !xOri ) {
v0.SetY(a*v0.z() + b);
errors = ThreeVector(etrans, erecon, elong);
} else {
v0.SetX(a*v0.z() + b);
errors = ThreeVector(erecon, etrans, elong);
}
// Add a spacepoint to the array
EMRSpacePointTmp spacePoint;
spacePoint._pos = v0;
spacePoint._errors = errors;
spacePoint._ch = barHit.GetChannel();
spacePoint._time = barHit.GetTime()-_attenMap.fibreDelay(xKey, v0.x(), v0.y(), "MA");
spacePoint._deltat = barHit.GetDeltaT()-_attenMap.fibreDelay(xKey, v0.x(), v0.y(), "MA");
spacePoint._chargema = -1;
spacePoint._chargesa = -1;
emr_events_tmp[iPe][iPlane]._spacepoints.push_back(spacePoint);
}
}
}
}
void MapCppEMRSpacePoints::correct_charge(EMREventVector& emr_events_tmp,
size_t nPartEvents) const {
for (size_t iPe = 0; iPe < emr_events_tmp.size(); iPe++) {
for (size_t iPlane = 0; iPlane < emr_events_tmp[iPe].size(); iPlane++) {
int xPlane = emr_events_tmp[iPe][iPlane]._plane;
EMRSpacePointVector spacePointVector = emr_events_tmp[iPe][iPlane]._spacepoints;
// Reconstruct the MAPMT charge in each bar hit
double xPlaneChargeMA(0.);
for (size_t iSP = 0; iSP < spacePointVector.size(); iSP++) {
int xBar = spacePointVector[iSP]._ch%_number_of_bars;
EMRChannelKey xKey(xPlane, xPlane%2, xBar, "emr");
double x = spacePointVector[iSP]._pos.x(); // [mm]
double y = spacePointVector[iSP]._pos.y(); // [mm]
double alphMA = _attenMap.fibreAtten(xKey, x, y, "MA"); // Fibre attenuation
double epsMA = _calibMap.Eps(xKey, "MA"); // Calibration factor
double xTot = emr_events_tmp[iPe][iPlane]._barhits[iSP].GetTot();
double xCharge = exp(xTot/_tot_func_p1-log(_tot_func_p2))-_tot_func_p3/_tot_func_p2;
xCharge /= alphMA*epsMA;
spacePointVector[iSP]._chargema = xCharge;
emr_events_tmp[iPe][iPlane]._spacepoints[iSP]._chargema = xCharge;
xPlaneChargeMA += xCharge;
}
// Correct and split the SAPMT charge in each bar, reconstruct it for candidates
double xPlaneChargeSA(0.), xFactorSA(0.), xFactorMA(0.);
for (size_t iSP = 0; iSP < spacePointVector.size(); iSP++) {
int xBar = spacePointVector[iSP]._ch%_number_of_bars;
EMRChannelKey xKey(xPlane, xPlane%2, xBar, "emr");
double x = spacePointVector[iSP]._pos.x(); // [mm]
double y = spacePointVector[iSP]._pos.y(); // [mm]
double alphSA = _attenMap.fibreAtten(xKey, x, y, "SA");
double epsSA = _calibMap.Eps(xKey, "SA");
double alphMA = _attenMap.fibreAtten(xKey, x, y, "MA");
double epsMA = _calibMap.Eps(xKey, "MA");
double phi = spacePointVector[iSP]._chargema/xPlaneChargeMA; // Fraction of the total charge
xFactorSA += alphSA*epsSA*phi;
xFactorMA += alphMA*epsMA*phi;
}
if ( iPe < nPartEvents ) {
xPlaneChargeSA = emr_events_tmp[iPe][iPlane]._charge/xFactorSA;
} else {
xPlaneChargeSA = xPlaneChargeMA*xFactorSA/xFactorMA;
}
for ( size_t iSP = 0; iSP < spacePointVector.size(); iSP++)
emr_events_tmp[iPe][iPlane]._spacepoints[iSP]._chargesa =
xPlaneChargeSA*spacePointVector[iSP]._chargema/xPlaneChargeMA;
// Correct the error on the spacepoint for its charge fraction,
// A spacepoint that has comparatively less charge is less definite
for (size_t iSP = 0; iSP < spacePointVector.size(); iSP++) {
double xFactor = spacePointVector[iSP]._chargema/xPlaneChargeMA;
ThreeVector xErrors = spacePointVector[iSP]._errors;
if ( !(xPlane%2) ) {
xErrors.SetX(xErrors.x()/sqrt(fabs(xFactor)));
} else {
xErrors.SetY(xErrors.y()/sqrt(fabs(xFactor)));
}
emr_events_tmp[iPe][iPlane]._spacepoints[iSP]._errors = xErrors;
}
}
}
}
void MapCppEMRSpacePoints::fill(MAUS::Spill* spill,
EMREventVector emr_events_tmp,
size_t nPartEvents) const {
// Get the EMR recon events and the spill data
ReconEventPArray *recEvts = spill->GetReconEvents();
EMRSpillData *emrSpill = spill->GetEMRSpillData();
for (size_t iPe = 0; iPe < emr_events_tmp.size(); iPe++) {
EMRSpacePointArray spacePointArray;
for (size_t iPlane = 0; iPlane < emr_events_tmp[iPe].size(); iPlane++) {
EMRSpacePointVector spacePointVector = emr_events_tmp[iPe][iPlane]._spacepoints;
for (size_t iSP = 0; iSP < spacePointVector.size(); iSP++) {
EMRSpacePoint *spacePoint = new EMRSpacePoint;
spacePoint->SetChannel(spacePointVector[iSP]._ch);
spacePoint->SetPosition(spacePointVector[iSP]._pos);
spacePoint->SetGlobalPosition(_geoMap.MakeGlobal(spacePointVector[iSP]._pos));
spacePoint->SetPositionErrors(spacePointVector[iSP]._errors);
spacePoint->SetTime(spacePointVector[iSP]._time);
spacePoint->SetDeltaT(spacePointVector[iSP]._deltat);
spacePoint->SetChargeMA(spacePointVector[iSP]._chargema);
spacePoint->SetChargeSA(spacePointVector[iSP]._chargesa);
spacePointArray.push_back(spacePoint);
}
}
EMREventTrack *evtTrack;
if ( iPe < nPartEvents ) {
evtTrack = recEvts->at(iPe)->GetEMREvent()->GetMotherPtr();
} else {
evtTrack = emrSpill->GetEMREventTrackArray()[iPe-nPartEvents];
}
if ( evtTrack )
evtTrack->SetEMRSpacePointArray(spacePointArray);
}
}
ThreeVector MapCppEMRSpacePoints::get_weighted_position(EMRBarHitArray barHitArray) const {
double wx(0.), wy(0.), wz(0.), w(0.);
for (size_t iHit = 0; iHit < barHitArray.size(); iHit++) {
int xPlane = barHitArray[iHit].GetChannel()/_number_of_bars;
int xBar = barHitArray[iHit].GetChannel()%_number_of_bars;
EMRChannelKey xKey(xPlane, xPlane%2, xBar, "emr");
ThreeVector xPos = _geoMap.LocalPosition(xKey);
double xTot = barHitArray[iHit].GetTot();
double xCharge= exp(xTot/_tot_func_p1-log(_tot_func_p2))
- _tot_func_p3/_tot_func_p2;
wx += xPos.x()*xCharge;
wy += xPos.y()*xCharge;
wz += xPos.z()*xCharge;
w += xCharge;
}
if (w) {
return ThreeVector(wx/w, wy/w, wz/w);
} else {
return ThreeVector(0., 0., 0.);
}
}
} // namespace MAUS
| mice-software/maus | src/map/MapCppEMRSpacePoints/MapCppEMRSpacePoints.cc | C++ | gpl-3.0 | 17,957 |
/*
* OptionsOracle Interface Class Library
* Copyright 2006-2012 SamoaSky
*
* 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.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace OOServerUS
{
public class Symbol
{
private static string IndexSymbol = " BXO RUH DJX DXL OEX OEX XEO XEO VIX BVZ SPX XSP BSZ SPL SML VXN NDX MNX MML RUI RVX RUT RMN NFT RUH OEX OEX XEO XEO SPX XSP BSZ SPL SML VIX BVZ DJX DTX DUX VXN NDX MNX MML RUI RVX RUT RMN EXQ GOX INX OIX TXX MVR MVB MGO MSV NFT CJN CTH CYX NFT ";
private static string FundSymbol = " AINV AGQ AUS BGU BGZ BWX DAX DBA DBB DBC DBE DBO DBP DBS DBV DDM DGL DGT DIA DIG DND DOG DUG DVY DXD EDC EDZ EEB EEM EEV EFA EFU EPI EPP ERY ERX EUO EWA EWC EWD EWG EWH EWJ EWL EWM EWP EWT EWW EWY EWZ EZA EZU FAS FAZ FEZ FPX FPX FRC FXB FXC FXE FXP FXY GDX GEX GLD GLL GSG GWX GXC HKG HYG IAI IAT IAU IBB IDU IEF IEZ IGE IGM IGN IGV IGW IIF IJR ILF ITB IVV IYY IWB IWC IWD IWF IWM IWN IWO IWP IWR IWS IWV IWW IWZ IYE IYF IYH IYM IYR IYY IYZ KBE KCE KIE KOL KRE KWT LDN LQD MDY MOO MWJ MWN MZZ NLR OEF ONEQ PBP PBW PDP PEJ PFF PGF PGX PHO PIN PIO PRF PSQ PST PXJ QDA QDF QID QLD QQQQ RSP RSU RTH RWM SCO SDS SH SHY SIJ SKF SLV SLX SMN SPY SRS SSO TAN TBT TFI TIP TLT TNA TWM TYH TYP TZA UCO UDN UGL UNG URE USL USO UUP UWM UXY UYG UYM VDE VFH VGK VGT VHT VIS VNQ VPL VTI VTV VUG VV VWO VXF XBI XES XHB XLB XLE XLF XLI XLK XLP XLU XLV XLY XME XOP XRT XSD YCS ZSL OIH ";
public enum Type
{
Unknown,
Stock,
Fund,
Index,
Future
};
public static string CorrectSymbol(string ticker, out Type type)
{
ticker = ticker.ToUpper().Trim();
if (ticker.StartsWith("^") || IndexSymbol.Contains(" " + ticker + " "))
type = Type.Index;
else if (FundSymbol.Contains(" " + ticker + " "))
type = Type.Fund;
else if (ticker.StartsWith("~"))
type = Type.Future;
else
type = Type.Stock;
switch (ticker)
{
default:
if (type == Type.Index && ticker[0] != '^') ticker = "^" + ticker;
else if (type == Type.Future && ticker[0] != '~') ticker = "~" + ticker;
return ticker;
}
}
}
}
| Ciuco/OptionsOracle | OOServerUS/Symbol.cs | C# | gpl-3.0 | 2,890 |
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("ColosseumGame")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ColosseumGame")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("a9aea9a5-cb88-41ee-9002-7b198f8543b0")]
// 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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| TastyGrue/little-village | ColosseumFoundation/ColosseumGame/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,402 |
"use strict";
var uuid = require('node-uuid');
var crypto = require('crypto');
var NodeGeocoder = require('node-geocoder');
var secret = "I@Love@NNNode.JS";
var options = {
provider: 'google',
httpAdapter: 'https',
apiKey: 'AIzaSyBF9xb6TLxfTEji1O4UqL7rwZc16fQRctA',
formatter: null
};
var Util = function () {
return {
GenerateAuthToken: function () {
return uuid.v4();
},
Encrypt: function (strToEncrypt) {
return crypto.createHmac('sha256', secret)
.update(strToEncrypt)
.digest('hex');
},
getLatLon: function (address, callback) {
var geocoder = NodeGeocoder(options);
geocoder.geocode(address, function(err, res) {
if (err) {
callback(err.message, null)
}
else {
callback(null, {"lat": res[0].latitude, "lon": res[0].longitude});
}
});
}
};
}();
module.exports = Util;
| oczane/geochat | util.js | JavaScript | gpl-3.0 | 1,071 |
# Copyright (C) 2009 Mark Somerville <mark@scottishclimbs.com>
# Released under the General Public License (GPL) version 3.
# See COPYING
require "spandex/card"
require "spandex/list"
require_relative "../models/artist"
require_relative "tracks_card"
module Messier
class Messier::AlbumsCard < Spandex::Card
include JogWheelListMethods
top_left :back
jog_wheel_button card: Messier::TracksCard, params: -> do
if params and params[:genre]
{ genre: params[:genre], artist: params[:artist], album: @list.selected }
else
{ album: @list.selected, artist: @list.selected.artist }
end
end
top_right :method => :play_all
def play_all
ids = []
@list.items.each { |a| ids += a.tracks.map(&:id) }
pass_focus(application: "mozart", method: "play_ids", params: ids.join(", "))
end
def after_initialize
@list ||= Spandex::List.new Album.all
@title = "All albums"
end
def after_load
if params[:artist]
@list = Spandex::List.new params[:artist].albums
if params[:genre]
@title = "#{params[:genre].name} -> #{params[:artist].name}"
else
@title = "#{params[:artist].name}"
end
else
@list = Spandex::List.new Album.all
@title = "All albums"
end
end
def show
render %{
<title>#{@title}</title>
<button position="top_left">Back</button>
<button position="top_right">Play all</button>
#{@list}
}
end
end
end
| Spakman/px_messier | lib/cards/albums_card.rb | Ruby | gpl-3.0 | 1,545 |
#!/usr/bin/env python
import sys
import time
from envirophat import light, weather, motion, analog
def write():
try:
p = round(weather.pressure(),2)
c = light.light()
print('{"light": '+str(c)+', "pressure": '+str(p)+' }')
except KeyboardInterrupt:
pass
write()
| alexellis/docker-arm | images/armhf/python2-envirophat.dev/pressure/pressure.py | Python | gpl-3.0 | 277 |
#
# SPDX-FileCopyrightText: 2017 Dmytro Kolomoiets <amerlyq@gmail.com> and contributors.
#
# SPDX-License-Identifier: GPL-3.0-only
#
class NodeSuperimposeTr(object):
def __call__(self, g, node_uid, aug):
conv = {}
for uid in aug:
if uid == aug.get_root():
g[node_uid] = aug[uid]
conv[uid] = node_uid
else:
conv[uid] = g.add_object(aug[uid])
for uid in aug:
for edge in aug.neighbors(uid):
g.add_arrow(conv[uid], conv[edge])
| miur/miur | OLD/miur/graph/transform.py | Python | gpl-3.0 | 554 |
<?php
/* Copyright (C) 2010-2014 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2010 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2012-2015 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
* Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* or see http://www.gnu.org/
*/
/**
* \file htdocs/core/menus/standard/eldy.lib.php
* \brief Library for file eldy menus
*/
require_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php';
/**
* Core function to output top menu eldy
*
* @param DoliDB $db Database handler
* @param string $atarget Target (Example: '' or '_top')
* @param int $type_user 0=Menu for backoffice, 1=Menu for front office
* @param array $tabMenu If array with menu entries already loaded, we put this array here (in most cases, it's empty)
* @param array $menu Object Menu to return back list of menu entries
* @param int $noout Disable output (Initialise &$menu only).
* @return int 0
*/
function print_eldy_menu($db,$atarget,$type_user,&$tabMenu,&$menu,$noout=0)
{
global $user,$conf,$langs,$dolibarr_main_db_name;
$mainmenu=(empty($_SESSION["mainmenu"])?'':$_SESSION["mainmenu"]);
$leftmenu=(empty($_SESSION["leftmenu"])?'':$_SESSION["leftmenu"]);
$id='mainmenu';
$listofmodulesforexternal=explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL);
if (empty($noout)) print_start_menu_array();
// Home
$showmode=1;
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "home") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='home';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($langs->trans("Home"), 1, DOL_URL_ROOT.'/index.php?mainmenu=home&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/index.php?mainmenu=home&leftmenu=', $langs->trans("Home"), 0, $showmode, $atarget, "home", '');
// Third parties
$tmpentry=array('enabled'=>(( ! empty($conf->societe->enabled) && (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))) || ! empty($conf->fournisseur->enabled)), 'perms'=>(! empty($user->rights->societe->lire) || ! empty($user->rights->fournisseur->lire)), 'module'=>'societe|fournisseur');
$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
if ($showmode)
{
$langs->load("companies");
$langs->load("suppliers");
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "companies") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='companies';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($langs->trans("ThirdParties"), $showmode, DOL_URL_ROOT.'/societe/index.php?mainmenu=companies&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/societe/index.php?mainmenu=companies&leftmenu=', $langs->trans("ThirdParties"), 0, $showmode, $atarget, "companies", '');
}
// Products-Services
$tmpentry=array('enabled'=>(! empty($conf->product->enabled) || ! empty($conf->service->enabled)), 'perms'=>(! empty($user->rights->produit->lire) || ! empty($user->rights->service->lire)), 'module'=>'product|service');
$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
if ($showmode)
{
$langs->load("products");
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "products") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='products';
$chaine="";
if (! empty($conf->product->enabled)) {
$chaine.=$langs->trans("Products");
}
if (! empty($conf->product->enabled) && ! empty($conf->service->enabled)) {
$chaine.="/";
}
if (! empty($conf->service->enabled)) {
$chaine.=$langs->trans("Services");
}
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($chaine, $showmode, DOL_URL_ROOT.'/product/index.php?mainmenu=products&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/product/index.php?mainmenu=products&leftmenu=', $chaine, 0, $showmode, $atarget, "products", '');
}
// Commercial
$menuqualified=0;
if (! empty($conf->propal->enabled)) $menuqualified++;
if (! empty($conf->commande->enabled)) $menuqualified++;
if (! empty($conf->supplier_order->enabled)) $menuqualified++;
if (! empty($conf->contrat->enabled)) $menuqualified++;
if (! empty($conf->ficheinter->enabled)) $menuqualified++;
$tmpentry=array(
'enabled'=>$menuqualified,
'perms'=>(! empty($user->rights->societe->lire) || ! empty($user->rights->societe->contact->lire)),
'module'=>'propal|commande|supplier_order|contrat|ficheinter');
$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
if ($showmode)
{
$langs->load("commercial");
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "commercial") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='commercial';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($langs->trans("Commercial"), $showmode, DOL_URL_ROOT.'/comm/index.php?mainmenu=commercial&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/comm/index.php?mainmenu=commercial&leftmenu=', $langs->trans("Commercial"), 0, $showmode, $atarget, "commercial", "");
}
// Financial
$menuqualified=0;
if (! empty($conf->comptabilite->enabled)) $menuqualified++;
if (! empty($conf->accounting->enabled)) $menuqualified++;
if (! empty($conf->facture->enabled)) $menuqualified++;
if (! empty($conf->don->enabled)) $menuqualified++;
if (! empty($conf->tax->enabled)) $menuqualified++;
if (! empty($conf->salaries->enabled)) $menuqualified++;
if (! empty($conf->supplier_invoice->enabled)) $menuqualified++;
if (! empty($conf->loan->enabled)) $menuqualified++;
$tmpentry=array(
'enabled'=>$menuqualified,
'perms'=>(! empty($user->rights->compta->resultat->lire) || ! empty($user->rights->accounting->plancompte->lire) || ! empty($user->rights->facture->lire) || ! empty($user->rights->don->lire) || ! empty($user->rights->tax->charges->lire) || ! empty($user->rights->salaries->read) || ! empty($user->rights->fournisseur->facture->lire) || ! empty($user->rights->loan->read)),
'module'=>'comptabilite|accounting|facture|supplier_invoice|don|tax|salaries|loan');
$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
if ($showmode)
{
$langs->load("compta");
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "accountancy") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='accountancy';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($langs->trans("MenuFinancial"), $showmode, DOL_URL_ROOT.'/compta/index.php?mainmenu=accountancy&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/compta/index.php?mainmenu=accountancy&leftmenu=', $langs->trans("MenuFinancial"), 0, $showmode, $atarget, "accountancy", '');
}
// Bank
$tmpentry=array('enabled'=>(! empty($conf->banque->enabled) || ! empty($conf->prelevement->enabled)),
'perms'=>(! empty($user->rights->banque->lire) || ! empty($user->rights->prelevement->lire)),
'module'=>'banque|prelevement');
$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
if ($showmode)
{
$langs->load("compta");
$langs->load("banks");
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "bank") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='bank';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($langs->trans("MenuBankCash"), $showmode, DOL_URL_ROOT.'/compta/bank/index.php?mainmenu=bank&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/compta/bank/index.php?mainmenu=bank&leftmenu=', $langs->trans("MenuBankCash"), 0, $showmode, $atarget, "bank", '');
}
// Projects
$tmpentry=array('enabled'=>(! empty($conf->projet->enabled)),
'perms'=>(! empty($user->rights->projet->lire)),
'module'=>'projet');
$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
if ($showmode)
{
$langs->load("projects");
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "project") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='project';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($langs->trans("Projects"), $showmode, DOL_URL_ROOT.'/projet/index.php?mainmenu=project&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/projet/index.php?mainmenu=project&leftmenu=', $langs->trans("Projects"), 0, $showmode, $atarget, "project", '');
}
// HRM
$tmpentry=array('enabled'=>(! empty($conf->hrm->enabled) || ! empty($conf->holiday->enabled) || ! empty($conf->deplacement->enabled) || ! empty($conf->expensereport->enabled)),
'perms'=>(! empty($user->rights->hrm->employee->read) || ! empty($user->rights->holiday->write) || ! empty($user->rights->deplacement->lire) || ! empty($user->rights->expensereport->lire)),
'module'=>'hrm|holiday|deplacement|expensereport');
$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
if ($showmode)
{
$langs->load("holiday");
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "hrm") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='hrm';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($langs->trans("HRM"), $showmode, DOL_URL_ROOT.'/compta/hrm.php?mainmenu=hrm&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/compta/hrm.php?mainmenu=hrm&leftmenu=', $langs->trans("HRM"), 0, $showmode, $atarget, "hrm", '');
}
// Tools
$tmpentry=array('enabled'=>(! empty($conf->barcode->enabled) || ! empty($conf->mailing->enabled) || ! empty($conf->export->enabled) || ! empty($conf->import->enabled) || ! empty($conf->opensurvey->enabled) || ! empty($conf->resource->enabled)),
'perms'=>(! empty($conf->barcode->enabled) || ! empty($user->rights->mailing->lire) || ! empty($user->rights->export->lire) || ! empty($user->rights->import->run) || ! empty($user->rights->opensurvey->read) || ! empty($user->rights->resource->read)),
'module'=>'mailing|export|import|opensurvey|resource');
$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
if ($showmode)
{
$langs->load("other");
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "tools") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='tools';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($langs->trans("Tools"), $showmode, DOL_URL_ROOT.'/core/tools.php?mainmenu=tools&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/core/tools.php?mainmenu=tools&leftmenu=', $langs->trans("Tools"), 0, $showmode, $atarget, "tools", '');
}
// Members
$tmpentry=array('enabled'=>(! empty($conf->adherent->enabled)),
'perms'=>(! empty($user->rights->adherent->lire)),
'module'=>'adherent');
$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
if ($showmode)
{
$classname="";
if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "members") { $classname='class="tmenusel"'; $_SESSION['idmenu']=''; }
else $classname = 'class="tmenu"';
$idsel='members';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($langs->trans("MenuMembers"), $showmode, DOL_URL_ROOT.'/adherents/index.php?mainmenu=members&leftmenu=', $id, $idsel, $classname, $atarget);
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add('/adherents/index.php?mainmenu=members&leftmenu=', $langs->trans("MenuMembers"), 0, $showmode, $atarget, "members", '');
}
// Show personalized menus
$menuArbo = new Menubase($db,'eldy');
$newTabMenu = $menuArbo->menuTopCharger('','',$type_user,'eldy',$tabMenu); // Return tabMenu with only top entries
$num = count($newTabMenu);
for($i = 0; $i < $num; $i++)
{
$idsel=(empty($newTabMenu[$i]['mainmenu'])?'none':$newTabMenu[$i]['mainmenu']);
$showmode=dol_eldy_showmenu($type_user,$newTabMenu[$i],$listofmodulesforexternal);
if ($showmode == 1)
{
$url = $shorturl = $newTabMenu[$i]['url'];
if (! preg_match("/^(http:\/\/|https:\/\/)/i",$newTabMenu[$i]['url']))
{
$tmp=explode('?',$newTabMenu[$i]['url'],2);
$url = $shorturl = $tmp[0];
$param = (isset($tmp[1])?$tmp[1]:'');
if (! preg_match('/mainmenu/i',$param) || ! preg_match('/leftmenu/i',$param)) $param.=($param?'&':'').'mainmenu='.$newTabMenu[$i]['mainmenu'].'&leftmenu=';
//$url.="idmenu=".$newTabMenu[$i]['rowid']; // Already done by menuLoad
$url = dol_buildpath($url,1).($param?'?'.$param:'');
$shorturl = $shorturl.($param?'?'.$param:'');
}
$url=preg_replace('/__LOGIN__/',$user->login,$url);
$shorturl=preg_replace('/__LOGIN__/',$user->login,$shorturl);
$url=preg_replace('/__USERID__/',$user->id,$url);
$shorturl=preg_replace('/__USERID__/',$user->id,$shorturl);
// Define the class (top menu selected or not)
if (! empty($_SESSION['idmenu']) && $newTabMenu[$i]['rowid'] == $_SESSION['idmenu']) $classname='class="tmenusel"';
else if (! empty($_SESSION["mainmenu"]) && $newTabMenu[$i]['mainmenu'] == $_SESSION["mainmenu"]) $classname='class="tmenusel"';
else $classname='class="tmenu"';
}
else if ($showmode == 2) $classname='class="tmenu"';
if (empty($noout)) print_start_menu_entry($idsel,$classname,$showmode);
if (empty($noout)) print_text_menu_entry($newTabMenu[$i]['titre'], $showmode, $url, $id, $idsel, $classname, ($newTabMenu[$i]['target']?$newTabMenu[$i]['target']:$atarget));
if (empty($noout)) print_end_menu_entry($showmode);
$menu->add($shorturl, $newTabMenu[$i]['titre'], 0, $showmode, ($newTabMenu[$i]['target']?$newTabMenu[$i]['target']:$atarget), ($newTabMenu[$i]['mainmenu']?$newTabMenu[$i]['mainmenu']:$newTabMenu[$i]['rowid']), '');
}
$showmode=1;
if (empty($noout)) print_start_menu_entry('','class="tmenuend"',$showmode);
if (empty($noout)) print_end_menu_entry($showmode);
if (empty($noout)) print_end_menu_array();
return 0;
}
/**
* Output start menu array
*
* @return void
*/
function print_start_menu_array()
{
print '<div class="tmenudiv">';
print '<ul class="tmenu">';
}
/**
* Output start menu entry
*
* @param string $idsel Text
* @param string $classname String to add a css class
* @param int $showmode 0 = hide, 1 = allowed or 2 = not allowed
* @return void
*/
function print_start_menu_entry($idsel,$classname,$showmode)
{
if ($showmode)
{
print '<li '.$classname.' id="mainmenutd_'.$idsel.'">';
print '<div class="tmenuleft"></div><div class="tmenucenter">';
}
}
/**
* Output menu entry
*
* @param string $text Text
* @param int $showmode 0 = hide, 1 = allowed or 2 = not allowed
* @param string $url Url
* @param string $id Id
* @param string $idsel Id sel
* @param string $classname Class name
* @param string $atarget Target
* @return void
*/
function print_text_menu_entry($text, $showmode, $url, $id, $idsel, $classname, $atarget)
{
global $langs;
if ($showmode == 1)
{
print '<a class="tmenuimage" href="'.$url.'"'.($atarget?' target="'.$atarget.'"':'').'>';
print '<div class="'.$id.' '.$idsel.' topmenuimage"><span class="'.$id.' tmenuimage" id="mainmenuspan_'.$idsel.'"></span></div>';
print '</a>';
print '<a '.$classname.' id="mainmenua_'.$idsel.'" href="'.$url.'"'.($atarget?' target="'.$atarget.'"':'').'>';
print '<span class="mainmenuaspan">';
print $text;
print '</span>';
print '</a>';
}
if ($showmode == 2)
{
print '<div class="'.$id.' '.$idsel.' tmenudisabled"><span class="'.$id.'" id="mainmenuspan_'.$idsel.'"></span></div>';
print '<a class="tmenudisabled" id="mainmenua_'.$idsel.'" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">';
print '<span class="mainmenuaspan">';
print $text;
print '</span>';
print '</a>';
}
}
/**
* Output end menu entry
*
* @param int $showmode 0 = hide, 1 = allowed or 2 = not allowed
* @return void
*/
function print_end_menu_entry($showmode)
{
if ($showmode)
{
print '</div></li>';
}
print "\n";
}
/**
* Output menu array
*
* @return void
*/
function print_end_menu_array()
{
print '</ul>';
print '</div>';
print "\n";
}
/**
* Core function to output left menu eldy
*
* @param DoliDB $db Database handler
* @param array $menu_array_before Table of menu entries to show before entries of menu handler (menu->liste filled with menu->add)
* @param array $menu_array_after Table of menu entries to show after entries of menu handler (menu->liste filled with menu->add)
* @param array $tabMenu If array with menu entries already loaded, we put this array here (in most cases, it's empty)
* @param Menu $menu Object Menu to return back list of menu entries
* @param int $noout Disable output (Initialise &$menu only).
* @param string $forcemainmenu 'x'=Force mainmenu to mainmenu='x'
* @param string $forceleftmenu 'all'=Force leftmenu to '' (= all)
* @param array $moredata An array with more data to output
* @return int nb of menu entries
*/
function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu,&$menu,$noout=0,$forcemainmenu='',$forceleftmenu='',$moredata=null)
{
global $user,$conf,$langs,$dolibarr_main_db_name,$mysoc;
$newmenu = $menu;
$mainmenu=($forcemainmenu?$forcemainmenu:$_SESSION["mainmenu"]);
$leftmenu=($forceleftmenu?'':(empty($_SESSION["leftmenu"])?'none':$_SESSION["leftmenu"]));
// Show logo company
if (empty($conf->global->MAIN_MENU_INVERT) && empty($noout) && ! empty($conf->global->MAIN_SHOW_LOGO) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$mysoc->logo_mini=$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
if (! empty($mysoc->logo_mini) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_mini))
{
$urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=companylogo&file='.urlencode('thumbs/'.$mysoc->logo_mini);
}
else
{
$urllogo=DOL_URL_ROOT.'/theme/dolibarr_logo.png';
}
$title=$langs->trans("GoIntoSetupToChangeLogo");
print "\n".'<!-- Show logo on menu -->'."\n";
print '<div class="blockvmenuimpair blockvmenulogo">'."\n";
print '<div class="menu_titre" id="menu_titre_logo"></div>';
print '<div class="menu_top" id="menu_top_logo"></div>';
print '<div class="menu_contenu" id="menu_contenu_logo">';
print '<div class="center"><img class="companylogo" title="'.dol_escape_htmltag($title).'" alt="" src="'.$urllogo.'" style="max-width: 80%"></div>'."\n";
print '</div>';
print '<div class="menu_end" id="menu_end_logo"></div>';
print '</div>'."\n";
}
if (is_array($moredata) && ! empty($moredata['searchform']))
{
print "\n";
print "<!-- Begin SearchForm -->\n";
print '<div id="blockvmenusearch" class="blockvmenusearch">'."\n";
print $moredata['searchform'];
print '</div>'."\n";
print "<!-- End SearchForm -->\n";
}
/**
* We update newmenu with entries found into database
* --------------------------------------------------
*/
if ($mainmenu)
{
/*
* Menu HOME
*/
if ($mainmenu == 'home')
{
$langs->load("users");
//if ($user->admin)
//{
// Setup
$newmenu->add("/admin/index.php?mainmenu=home&leftmenu=setup", $langs->trans("Setup"), 0, $user->admin, '', $mainmenu, 'setup');
if (empty($leftmenu) || $leftmenu=="setup")
{
$langs->load("admin");
$langs->load("help");
$warnpicto='';
if (empty($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
{
$langs->load("errors");
$warnpicto =' '.img_warning($langs->trans("WarningMandatorySetupNotComplete"));
}
$newmenu->add("/admin/company.php?mainmenu=home", $langs->trans("MenuCompanySetup").$warnpicto,1);
$warnpicto='';
if (count($conf->modules) <= (empty($conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING)?1:$conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING)) // If only user module enabled
{
$langs->load("errors");
$warnpicto = ' '.img_warning($langs->trans("WarningMandatorySetupNotComplete"));
}
$newmenu->add("/admin/modules.php?mainmenu=home", $langs->trans("Modules").$warnpicto,1);
$newmenu->add("/admin/menus.php?mainmenu=home", $langs->trans("Menus"),1);
$newmenu->add("/admin/ihm.php?mainmenu=home", $langs->trans("GUISetup"),1);
if (! empty($conf->accounting->enabled))
{
$newmenu->add("/accountancy/admin/fiscalyear.php?mainmenu=home", $langs->trans("Fiscalyear"),1);
}
$newmenu->add("/admin/translation.php", $langs->trans("Translation"),1);
$newmenu->add("/admin/boxes.php?mainmenu=home", $langs->trans("Boxes"),1);
$newmenu->add("/admin/delais.php?mainmenu=home",$langs->trans("Alerts"),1);
$newmenu->add("/admin/security_other.php?mainmenu=home", $langs->trans("Security"),1);
$newmenu->add("/admin/limits.php?mainmenu=home", $langs->trans("MenuLimits"),1);
$newmenu->add("/admin/pdf.php?mainmenu=home", $langs->trans("PDF"),1);
$newmenu->add("/admin/mails.php?mainmenu=home", $langs->trans("Emails"),1);
$newmenu->add("/admin/sms.php?mainmenu=home", $langs->trans("SMS"),1);
$newmenu->add("/admin/dict.php?mainmenu=home", $langs->trans("Dictionary"),1);
$newmenu->add("/admin/const.php?mainmenu=home", $langs->trans("OtherSetup"),1);
}
// System tools
$newmenu->add("/admin/tools/index.php?mainmenu=home&leftmenu=admintools", $langs->trans("SystemTools"), 0, $user->admin, '', $mainmenu, 'admintools');
if (empty($leftmenu) || preg_match('/^admintools/',$leftmenu))
{
$langs->load("admin");
$langs->load("help");
$newmenu->add('/admin/system/dolibarr.php?mainmenu=home&leftmenu=admintools_info', $langs->trans('InfoDolibarr'), 1);
if (empty($leftmenu) || $leftmenu=='admintools_info') $newmenu->add('/admin/system/modules.php?mainmenu=home&leftmenu=admintools_info', $langs->trans('Modules'), 2);
if (empty($leftmenu) || $leftmenu=='admintools_info') $newmenu->add('/admin/triggers.php?mainmenu=home&leftmenu=admintools_info', $langs->trans('Triggers'), 2);
//if (empty($leftmenu) || $leftmenu=='admintools_info') $newmenu->add('/admin/system/filecheck.php?mainmenu=home&leftmenu=admintools_info', $langs->trans('FileCheck'), 2);
$newmenu->add('/admin/system/browser.php?mainmenu=home&leftmenu=admintools', $langs->trans('InfoBrowser'), 1);
$newmenu->add('/admin/system/os.php?mainmenu=home&leftmenu=admintools', $langs->trans('InfoOS'), 1);
$newmenu->add('/admin/system/web.php?mainmenu=home&leftmenu=admintools', $langs->trans('InfoWebServer'), 1);
$newmenu->add('/admin/system/phpinfo.php?mainmenu=home&leftmenu=admintools', $langs->trans('InfoPHP'), 1);
//if (function_exists('xdebug_is_enabled')) $newmenu->add('/admin/system/xdebug.php', $langs->trans('XDebug'),1);
$newmenu->add('/admin/system/database.php?mainmenu=home&leftmenu=admintools', $langs->trans('InfoDatabase'), 1);
if (function_exists('eaccelerator_info')) $newmenu->add("/admin/tools/eaccelerator.php?mainmenu=home&leftmenu=admintools", $langs->trans("EAccelerator"),1);
//$newmenu->add("/admin/system/perf.php?mainmenu=home&leftmenu=admintools", $langs->trans("InfoPerf"),1);
$newmenu->add("/admin/tools/purge.php?mainmenu=home&leftmenu=admintools", $langs->trans("Purge"),1);
$newmenu->add("/admin/tools/dolibarr_export.php?mainmenu=home&leftmenu=admintools", $langs->trans("Backup"),1);
$newmenu->add("/admin/tools/dolibarr_import.php?mainmenu=home&leftmenu=admintools", $langs->trans("Restore"),1);
$newmenu->add("/admin/tools/update.php?mainmenu=home&leftmenu=admintools", $langs->trans("MenuUpgrade"),1);
$newmenu->add("/admin/tools/listevents.php?mainmenu=home&leftmenu=admintools", $langs->trans("Audit"),1);
$newmenu->add("/admin/tools/listsessions.php?mainmenu=home&leftmenu=admintools", $langs->trans("Sessions"),1);
$newmenu->add('/admin/system/about.php?mainmenu=home&leftmenu=admintools', $langs->trans('About'), 1);
$newmenu->add("/support/index.php?mainmenu=home&leftmenu=admintools", $langs->trans("HelpCenter"),1,1,'targethelp');
}
// Modules system tools
if (! empty($conf->product->enabled) || ! empty($conf->service->enabled) || ! empty($conf->barcode->enabled) // TODO We should enabled module system tools entry without hardcoded test, but when at least one modules bringing such entries are on
|| ! empty($conf->global->MAIN_MENU_ENABLE_MODULETOOLS)) // Some external modules may need to force to have this entry on.
{
if (empty($user->societe_id))
{
$newmenu->add("/admin/tools/index.php?mainmenu=home&leftmenu=modulesadmintools", $langs->trans("ModulesSystemTools"), 0, $user->admin, '', $mainmenu, 'modulesadmintools');
// Special case: This entry can't be embedded into modules because we need it for both module service and products and we don't want duplicate lines.
if ((empty($leftmenu) || $leftmenu=="modulesadmintools") && $user->admin)
{
$langs->load("products");
$newmenu->add("/product/admin/product_tools.php?mainmenu=home&leftmenu=modulesadmintools", $langs->trans("ProductVatMassChange"), 1, $user->admin);
if (! empty($conf->accounting->enabled))
{
$langs->load("accountancy");
$newmenu->add("/accountancy/admin/productaccount.php?mainmenu=home&leftmenu=modulesadmintools", $langs->trans("InitAccountancy"), 1, $user->admin);
}
}
}
}
//}
$newmenu->add("/user/home.php?leftmenu=users", $langs->trans("MenuUsersAndGroups"), 0, $user->rights->user->user->lire, '', $mainmenu, 'users');
if ($user->rights->user->user->lire)
{
if (empty($leftmenu) || $leftmenu == 'none' || $leftmenu=="users")
{
$newmenu->add("", $langs->trans("Users"), 1, $user->rights->user->user->lire || $user->admin);
$newmenu->add("/user/card.php?action=create", $langs->trans("NewUser"),2, $user->rights->user->user->creer || $user->admin, '', 'home');
$newmenu->add("/user/index.php", $langs->trans("ListOfUsers"), 2, $user->rights->user->user->lire || $user->admin);
$newmenu->add("/user/hierarchy.php", $langs->trans("HierarchicView"), 2, $user->rights->user->user->lire || $user->admin);
$newmenu->add("", $langs->trans("Groups"), 1, $user->rights->user->user->lire || $user->admin);
$newmenu->add("/user/group/card.php?action=create", $langs->trans("NewGroup"), 2, ($conf->global->MAIN_USE_ADVANCED_PERMS?$user->rights->user->group_advance->write:$user->rights->user->user->creer) || $user->admin);
$newmenu->add("/user/group/index.php", $langs->trans("ListOfGroups"), 2, ($conf->global->MAIN_USE_ADVANCED_PERMS?$user->rights->user->group_advance->read:$user->rights->user->user->lire) || $user->admin);
}
}
}
/*
* Menu THIRDPARTIES
*/
if ($mainmenu == 'companies')
{
// Societes
if (! empty($conf->societe->enabled))
{
$langs->load("companies");
$newmenu->add("/societe/index.php?leftmenu=thirdparties", $langs->trans("ThirdParty"), 0, $user->rights->societe->lire, '', $mainmenu, 'thirdparties');
if ($user->rights->societe->creer)
{
$newmenu->add("/societe/soc.php?action=create", $langs->trans("MenuNewThirdParty"),1);
if (! $conf->use_javascript_ajax) $newmenu->add("/societe/soc.php?action=create&private=1",$langs->trans("MenuNewPrivateIndividual"),1);
}
}
$newmenu->add("/societe/list.php?leftmenu=thirdparties", $langs->trans("List"),1);
// Prospects
if (! empty($conf->societe->enabled) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
{
$langs->load("commercial");
$newmenu->add("/societe/list.php?type=p&leftmenu=prospects", $langs->trans("ListProspectsShort"), 1, $user->rights->societe->lire, '', $mainmenu, 'prospects');
/* no more required, there is a filter that can do more
if (empty($leftmenu) || $leftmenu=="prospects") $newmenu->add("/societe/list.php?type=p&sortfield=s.datec&sortorder=desc&begin=&search_stcomm=-1", $langs->trans("LastProspectDoNotContact"), 2, $user->rights->societe->lire);
if (empty($leftmenu) || $leftmenu=="prospects") $newmenu->add("/societe/list.php?type=p&sortfield=s.datec&sortorder=desc&begin=&search_stcomm=0", $langs->trans("LastProspectNeverContacted"), 2, $user->rights->societe->lire);
if (empty($leftmenu) || $leftmenu=="prospects") $newmenu->add("/societe/list.php?type=p&sortfield=s.datec&sortorder=desc&begin=&search_stcomm=1", $langs->trans("LastProspectToContact"), 2, $user->rights->societe->lire);
if (empty($leftmenu) || $leftmenu=="prospects") $newmenu->add("/societe/list.php?type=p&sortfield=s.datec&sortorder=desc&begin=&search_stcomm=2", $langs->trans("LastProspectContactInProcess"), 2, $user->rights->societe->lire);
if (empty($leftmenu) || $leftmenu=="prospects") $newmenu->add("/societe/list.php?type=p&sortfield=s.datec&sortorder=desc&begin=&search_stcomm=3", $langs->trans("LastProspectContactDone"), 2, $user->rights->societe->lire);
*/
$newmenu->add("/societe/soc.php?leftmenu=prospects&action=create&type=p", $langs->trans("MenuNewProspect"), 2, $user->rights->societe->creer);
//$newmenu->add("/contact/list.php?leftmenu=customers&type=p", $langs->trans("Contacts"), 2, $user->rights->societe->contact->lire);
}
// Customers/Prospects
if (! empty($conf->societe->enabled) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))
{
$langs->load("commercial");
$newmenu->add("/societe/list.php?type=c&leftmenu=customers", $langs->trans("ListCustomersShort"), 1, $user->rights->societe->lire, '', $mainmenu, 'customers');
$newmenu->add("/societe/soc.php?leftmenu=customers&action=create&type=c", $langs->trans("MenuNewCustomer"), 2, $user->rights->societe->creer);
//$newmenu->add("/contact/list.php?leftmenu=customers&type=c", $langs->trans("Contacts"), 2, $user->rights->societe->contact->lire);
}
// Suppliers
if (! empty($conf->societe->enabled) && ! empty($conf->fournisseur->enabled))
{
$langs->load("suppliers");
$newmenu->add("/societe/list.php?type=f&leftmenu=suppliers", $langs->trans("ListSuppliersShort"), 1, $user->rights->fournisseur->lire, '', $mainmenu, 'suppliers');
$newmenu->add("/societe/soc.php?leftmenu=suppliers&action=create&type=f",$langs->trans("MenuNewSupplier"), 2, $user->rights->societe->creer && $user->rights->fournisseur->lire);
}
// Contacts
$newmenu->add("/societe/index.php?leftmenu=thirdparties", (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ThirdParty") : $langs->trans("ContactsAddresses")), 0, $user->rights->societe->contact->lire, '', $mainmenu, 'contacts');
$newmenu->add("/contact/card.php?leftmenu=contacts&action=create", (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("NewContact") : $langs->trans("NewContactAddress")), 1, $user->rights->societe->contact->creer);
$newmenu->add("/contact/list.php?leftmenu=contacts", $langs->trans("List"), 1, $user->rights->societe->contact->lire);
if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) $newmenu->add("/contact/list.php?leftmenu=contacts&type=p", $langs->trans("Prospects"), 2, $user->rights->societe->contact->lire);
if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $newmenu->add("/contact/list.php?leftmenu=contacts&type=c", $langs->trans("Customers"), 2, $user->rights->societe->contact->lire);
if (! empty($conf->fournisseur->enabled)) $newmenu->add("/contact/list.php?leftmenu=contacts&type=f", $langs->trans("Suppliers"), 2, $user->rights->societe->contact->lire);
$newmenu->add("/contact/list.php?leftmenu=contacts&type=o", $langs->trans("ContactOthers"), 2, $user->rights->societe->contact->lire);
//$newmenu->add("/contact/list.php?userid=$user->id", $langs->trans("MyContacts"), 1, $user->rights->societe->contact->lire);
// Categories
if (! empty($conf->categorie->enabled))
{
$langs->load("categories");
if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))
{
// Categories prospects/customers
$menutoshow=$langs->trans("CustomersProspectsCategoriesShort");
if (! empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) $menutoshow=$langs->trans("CustomersCategoriesShort");
if (! empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $menutoshow=$langs->trans("ProspectsCategoriesShort");
$newmenu->add("/categories/index.php?leftmenu=cat&type=2", $menutoshow, 0, $user->rights->categorie->lire, '', $mainmenu, 'cat');
$newmenu->add("/categories/card.php?action=create&type=2", $langs->trans("NewCategory"), 1, $user->rights->categorie->creer);
}
// Categories Contact
$newmenu->add("/categories/index.php?leftmenu=cat&type=4", $langs->trans("ContactCategoriesShort"), 0, $user->rights->categorie->lire, '', $mainmenu, 'cat');
$newmenu->add("/categories/card.php?action=create&type=4", $langs->trans("NewCategory"), 1, $user->rights->categorie->creer);
// Categories suppliers
if (! empty($conf->fournisseur->enabled))
{
$newmenu->add("/categories/index.php?leftmenu=cat&type=1", $langs->trans("SuppliersCategoriesShort"), 0, $user->rights->categorie->lire);
$newmenu->add("/categories/card.php?action=create&type=1", $langs->trans("NewCategory"), 1, $user->rights->categorie->creer);
}
//if (empty($leftmenu) || $leftmenu=="cat") $newmenu->add("/categories/list.php", $langs->trans("List"), 1, $user->rights->categorie->lire);
}
}
/*
* Menu COMMERCIAL
*/
if ($mainmenu == 'commercial')
{
$langs->load("companies");
// Customer proposal
if (! empty($conf->propal->enabled))
{
$langs->load("propal");
$newmenu->add("/comm/propal/index.php?leftmenu=propals", $langs->trans("Prop"), 0, $user->rights->propale->lire, '', $mainmenu, 'propals', 100);
$newmenu->add("/comm/propal.php?action=create&leftmenu=propals", $langs->trans("NewPropal"), 1, $user->rights->propale->creer);
$newmenu->add("/comm/propal/list.php?leftmenu=propals", $langs->trans("List"), 1, $user->rights->propale->lire);
if (empty($leftmenu) || $leftmenu=="propals") $newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=0", $langs->trans("PropalsDraft"), 2, $user->rights->propale->lire);
if (empty($leftmenu) || $leftmenu=="propals") $newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=1", $langs->trans("PropalsOpened"), 2, $user->rights->propale->lire);
if (empty($leftmenu) || $leftmenu=="propals") $newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=2", $langs->trans("PropalStatusSigned"), 2, $user->rights->propale->lire);
if (empty($leftmenu) || $leftmenu=="propals") $newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=3", $langs->trans("PropalStatusNotSigned"), 2, $user->rights->propale->lire);
if (empty($leftmenu) || $leftmenu=="propals") $newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=4", $langs->trans("PropalStatusBilled"), 2, $user->rights->propale->lire);
//if (empty($leftmenu) || $leftmenu=="propals") $newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=2,3,4", $langs->trans("PropalStatusClosedShort"), 2, $user->rights->propale->lire);
$newmenu->add("/comm/propal/stats/index.php?leftmenu=propals", $langs->trans("Statistics"), 1, $user->rights->propale->lire);
}
// Customers orders
if (! empty($conf->commande->enabled))
{
$langs->load("orders");
$newmenu->add("/commande/index.php?leftmenu=orders", $langs->trans("CustomersOrders"), 0, $user->rights->commande->lire, '', $mainmenu, 'orders', 200);
$newmenu->add("/commande/card.php?action=create&leftmenu=orders", $langs->trans("NewOrder"), 1, $user->rights->commande->creer);
$newmenu->add("/commande/list.php?leftmenu=orders", $langs->trans("List"), 1, $user->rights->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders") $newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=0", $langs->trans("StatusOrderDraftShort"), 2, $user->rights->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders") $newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=1", $langs->trans("StatusOrderValidated"), 2, $user->rights->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders" && ! empty($conf->expedition->enabled)) $newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=2", $langs->trans("StatusOrderSentShort"), 2, $user->rights->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders") $newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=3", $langs->trans("StatusOrderDelivered"), 2, $user->rights->commande->lire);
//if (empty($leftmenu) || $leftmenu=="orders") $newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=4", $langs->trans("StatusOrderProcessed"), 2, $user->rights->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders") $newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=-1", $langs->trans("StatusOrderCanceledShort"), 2, $user->rights->commande->lire);
$newmenu->add("/commande/stats/index.php?leftmenu=orders", $langs->trans("Statistics"), 1, $user->rights->commande->lire);
}
// Suppliers orders
if (! empty($conf->supplier_order->enabled))
{
$langs->load("orders");
$newmenu->add("/fourn/commande/index.php?leftmenu=orders_suppliers",$langs->trans("SuppliersOrders"), 0, $user->rights->fournisseur->commande->lire, '', $mainmenu, 'orders_suppliers', 400);
$newmenu->add("/fourn/commande/card.php?action=create&leftmenu=orders_suppliers", $langs->trans("NewOrder"), 1, $user->rights->fournisseur->commande->creer);
$newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers", $langs->trans("List"), 1, $user->rights->fournisseur->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders_suppliers") $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=0", $langs->trans("StatusOrderDraftShort"), 2, $user->rights->fournisseur->commande->lire);
if ((empty($leftmenu) || $leftmenu=="orders_suppliers") && empty($conf->global->SUPPLIER_ORDER_HIDE_VALIDATED)) $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=1", $langs->trans("StatusOrderValidated"), 2, $user->rights->fournisseur->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders_suppliers") $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=2", $langs->trans("StatusOrderApprovedShort"), 2, $user->rights->fournisseur->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders_suppliers") $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=3", $langs->trans("StatusOrderOnProcessShort"), 2, $user->rights->fournisseur->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders_suppliers") $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=4", $langs->trans("StatusOrderReceivedPartiallyShort"), 2, $user->rights->fournisseur->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders_suppliers") $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=5", $langs->trans("StatusOrderReceivedAll"), 2, $user->rights->fournisseur->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders_suppliers") $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=6,7", $langs->trans("StatusOrderCanceled"), 2, $user->rights->fournisseur->commande->lire);
if (empty($leftmenu) || $leftmenu=="orders_suppliers") $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=9", $langs->trans("StatusOrderRefused"), 2, $user->rights->fournisseur->commande->lire);
// Billed is another field. We should add instead a dedicated filter on list. if (empty($leftmenu) || $leftmenu=="orders_suppliers") $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&billed=1", $langs->trans("StatusOrderBilled"), 2, $user->rights->fournisseur->commande->lire);
$newmenu->add("/commande/stats/index.php?leftmenu=orders_suppliers&mode=supplier", $langs->trans("Statistics"), 1, $user->rights->fournisseur->commande->lire);
}
// Contrat
if (! empty($conf->contrat->enabled))
{
$langs->load("contracts");
$newmenu->add("/contrat/index.php?leftmenu=contracts", $langs->trans("ContractsSubscriptions"), 0, $user->rights->contrat->lire, '', $mainmenu, 'contracts', 2000);
$newmenu->add("/contrat/card.php?action=create&leftmenu=contracts", $langs->trans("NewContractSubscription"), 1, $user->rights->contrat->creer);
$newmenu->add("/contrat/list.php?leftmenu=contracts", $langs->trans("List"), 1, $user->rights->contrat->lire);
$newmenu->add("/contrat/services.php?leftmenu=contracts", $langs->trans("MenuServices"), 1, $user->rights->contrat->lire);
if (empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services.php?leftmenu=contracts&mode=0", $langs->trans("MenuInactiveServices"), 2, $user->rights->contrat->lire);
if (empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services.php?leftmenu=contracts&mode=4", $langs->trans("MenuRunningServices"), 2, $user->rights->contrat->lire);
if (empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services.php?leftmenu=contracts&mode=4&filter=expired", $langs->trans("MenuExpiredServices"), 2, $user->rights->contrat->lire);
if (empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services.php?leftmenu=contracts&mode=5", $langs->trans("MenuClosedServices"), 2, $user->rights->contrat->lire);
}
// Interventions
if (! empty($conf->ficheinter->enabled))
{
$langs->load("interventions");
$newmenu->add("/fichinter/index.php?leftmenu=ficheinter", $langs->trans("Interventions"), 0, $user->rights->ficheinter->lire, '', $mainmenu, 'ficheinter', 2200);
$newmenu->add("/fichinter/card.php?action=create&leftmenu=ficheinter", $langs->trans("NewIntervention"), 1, $user->rights->ficheinter->creer, '', '', '', 201);
$newmenu->add("/fichinter/list.php?leftmenu=ficheinter", $langs->trans("List"), 1, $user->rights->ficheinter->lire, '', '', '', 202);
}
}
/*
* Menu COMPTA-FINANCIAL
*/
if ($mainmenu == 'accountancy')
{
$langs->load("companies");
// Customers invoices
if (! empty($conf->facture->enabled))
{
$langs->load("bills");
$newmenu->add("/compta/facture/list.php",$langs->trans("BillsCustomers"),0,$user->rights->facture->lire, '', $mainmenu, 'customers_bills');
$newmenu->add("/compta/facture.php?action=create",$langs->trans("NewBill"),1,$user->rights->facture->creer);
$newmenu->add("/compta/facture/list.php?leftmenu=customers_bills",$langs->trans("List"),1,$user->rights->facture->lire);
if (empty($leftmenu) || ($leftmenu == 'customers_bills'))
{
$newmenu->add("/compta/facture/list.php?leftmenu=customers_bills&search_status=0",$langs->trans("BillShortStatusDraft"),2,$user->rights->facture->lire);
$newmenu->add("/compta/facture/list.php?leftmenu=customers_bills&search_status=1",$langs->trans("BillShortStatusNotPaid"),2,$user->rights->facture->lire);
$newmenu->add("/compta/facture/list.php?leftmenu=customers_bills&search_status=2",$langs->trans("BillShortStatusPaid"),2,$user->rights->facture->lire);
$newmenu->add("/compta/facture/list.php?leftmenu=customers_bills&search_status=3",$langs->trans("BillShortStatusCanceled"),2,$user->rights->facture->lire);
}
$newmenu->add("/compta/facture/fiche-rec.php",$langs->trans("ListOfTemplates"),1,$user->rights->facture->lire);
$newmenu->add("/compta/paiement/list.php",$langs->trans("Payments"),1,$user->rights->facture->lire);
if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION))
{
$newmenu->add("/compta/paiement/avalider.php",$langs->trans("MenuToValid"),2,$user->rights->facture->lire);
}
$newmenu->add("/compta/paiement/rapport.php",$langs->trans("Reportings"),2,$user->rights->facture->lire);
$newmenu->add("/compta/facture/stats/index.php", $langs->trans("Statistics"),1,$user->rights->facture->lire);
$newmenu->add("/compta/facture/mergepdftool.php",$langs->trans("MergingPDFTool"),1,$user->rights->facture->lire);
}
// Suppliers invoices
if (! empty($conf->societe->enabled) && ! empty($conf->supplier_invoice->enabled))
{
$langs->load("bills");
$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills", $langs->trans("BillsSuppliers"),0,$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills');
$newmenu->add("/fourn/facture/card.php?action=create",$langs->trans("NewBill"),1,$user->rights->fournisseur->facture->creer);
$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills", $langs->trans("List"),1,$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills');
if (empty($leftmenu) || ($leftmenu == 'suppliers_bills')) {
$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills&search_status=0", $langs->trans("BillShortStatusDraft"),2,$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills');
$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills&search_status=1", $langs->trans("BillShortStatusNotPaid"),2,$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills');
$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills&search_status=2", $langs->trans("BillShortStatusPaid"),2,$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills');
}
$newmenu->add("/fourn/facture/paiement.php", $langs->trans("Payments"),1,$user->rights->fournisseur->facture->lire);
$newmenu->add("/compta/facture/stats/index.php?leftmenu=suppliers_bills&mode=supplier", $langs->trans("Statistics"),1,$user->rights->fournisseur->facture->lire);
}
// Orders
if (! empty($conf->commande->enabled))
{
$langs->load("orders");
if (! empty($conf->facture->enabled)) $newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=-3", $langs->trans("MenuOrdersToBill2"), 0, $user->rights->commande->lire, '', $mainmenu, 'orders');
// if (empty($leftmenu) || $leftmenu=="orders") $newmenu->add("/commande/", $langs->trans("StatusOrderToBill"), 1, $user->rights->commande->lire);
}
// Supplier Orders to bill
if (! empty($conf->supplier_invoice->enabled))
{
if (! empty($conf->global->SUPPLIER_MENU_ORDER_RECEIVED_INTO_INVOICE))
{
$langs->load("supplier");
$newmenu->add("/fourn/commande/list.php?leftmenu=orders&search_status=5&billed=0", $langs->trans("MenuOrdersSupplierToBill"), 0, $user->rights->commande->lire, '', $mainmenu, 'orders');
// if (empty($leftmenu) || $leftmenu=="orders") $newmenu->add("/commande/", $langs->trans("StatusOrderToBill"), 1, $user->rights->commande->lire);
}
}
// Donations
if (! empty($conf->don->enabled))
{
$langs->load("donations");
$newmenu->add("/don/index.php?leftmenu=donations&mainmenu=accountancy",$langs->trans("Donations"), 0, $user->rights->don->lire, '', $mainmenu, 'donations');
if (empty($leftmenu) || $leftmenu=="donations") $newmenu->add("/don/card.php?action=create",$langs->trans("NewDonation"), 1, $user->rights->don->creer);
if (empty($leftmenu) || $leftmenu=="donations") $newmenu->add("/don/list.php",$langs->trans("List"), 1, $user->rights->don->lire);
// if ($leftmenu=="donations") $newmenu->add("/don/stats/index.php",$langs->trans("Statistics"), 1, $user->rights->don->lire);
}
// Taxes and social contributions
if (! empty($conf->tax->enabled) || ! empty($conf->salaries->enabled) || ! empty($conf->loan->enabled))
{
global $mysoc;
$permtoshowmenu=((! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) || (! empty($conf->salaries->enabled) && $user->rights->salaries->read) || (! empty($conf->loan->enabled) && $user->rights->loan->read));
$newmenu->add("/compta/charges/index.php?leftmenu=tax&mainmenu=accountancy",$langs->trans("MenuSpecialExpenses"), 0, $permtoshowmenu, '', $mainmenu, 'tax');
// Salaries
if (! empty($conf->salaries->enabled))
{
$langs->load("salaries");
$newmenu->add("/compta/salaries/index.php?leftmenu=tax_salary&mainmenu=accountancy",$langs->trans("Salaries"),1,$user->rights->salaries->read, '', $mainmenu, 'tax_salary');
if (empty($leftmenu) || preg_match('/^tax_salary/i',$leftmenu)) $newmenu->add("/compta/salaries/card.php?leftmenu=tax_salary&action=create",$langs->trans("NewPayment"),2,$user->rights->salaries->write);
if (empty($leftmenu) || preg_match('/^tax_salary/i',$leftmenu)) $newmenu->add("/compta/salaries/index.php?leftmenu=tax_salary",$langs->trans("Payments"),2,$user->rights->salaries->read);
}
// Loan
if (! empty($conf->loan->enabled))
{
$langs->load("loan");
$newmenu->add("/loan/index.php?leftmenu=tax_loan&mainmenu=accountancy",$langs->trans("Loans"),1,$user->rights->loan->read, '', $mainmenu, 'tax_loan');
if (empty($leftmenu) || preg_match('/^tax_loan/i',$leftmenu)) $newmenu->add("/loan/card.php?leftmenu=tax_loan&action=create",$langs->trans("NewLoan"),2,$user->rights->loan->write);
if (empty($leftmenu) || preg_match('/^tax_loan/i',$leftmenu)) $newmenu->add("/loan/index.php?leftmenu=tax_loan",$langs->trans("Payments"),2,$user->rights->loan->read);
if (empty($leftmenu) || preg_match('/^tax_loan/i',$leftmenu)) $newmenu->add("/loan/calc.php?leftmenu=tax_loan",$langs->trans("Calculator"),2,$user->rights->loan->calc);
}
// Social contributions
if (! empty($conf->tax->enabled))
{
$newmenu->add("/compta/sociales/index.php?leftmenu=tax_social",$langs->trans("MenuSocialContributions"),1,$user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax_social/i',$leftmenu)) $newmenu->add("/compta/sociales/charges.php?leftmenu=tax_social&action=create",$langs->trans("MenuNewSocialContribution"), 2, $user->rights->tax->charges->creer);
if (empty($leftmenu) || preg_match('/^tax_social/i',$leftmenu)) $newmenu->add("/compta/sociales/index.php?leftmenu=tax_social",$langs->trans("List"),2,$user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax_social/i',$leftmenu)) $newmenu->add("/compta/charges/index.php?leftmenu=tax_social&mainmenu=accountancy&mode=sconly",$langs->trans("Payments"), 2, $user->rights->tax->charges->lire);
// VAT
if (empty($conf->global->TAX_DISABLE_VAT_MENUS))
{
$newmenu->add("/compta/tva/index.php?leftmenu=tax_vat&mainmenu=accountancy",$langs->trans("VAT"),1,$user->rights->tax->charges->lire, '', $mainmenu, 'tax_vat');
if (empty($leftmenu) || preg_match('/^tax_vat/i',$leftmenu)) $newmenu->add("/compta/tva/card.php?leftmenu=tax_vat&action=create",$langs->trans("New"),2,$user->rights->tax->charges->creer);
if (empty($leftmenu) || preg_match('/^tax_vat/i',$leftmenu)) $newmenu->add("/compta/tva/reglement.php?leftmenu=tax_vat",$langs->trans("List"),2,$user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax_vat/i',$leftmenu)) $newmenu->add("/compta/tva/clients.php?leftmenu=tax_vat", $langs->trans("ReportByCustomers"), 2, $user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax_vat/i',$leftmenu)) $newmenu->add("/compta/tva/quadri_detail.php?leftmenu=tax_vat", $langs->trans("ReportByQuarter"), 2, $user->rights->tax->charges->lire);
global $mysoc;
//Local Taxes
//Local Taxes 1
if($mysoc->useLocalTax(1) && (isset($mysoc->localtax1_assuj) && $mysoc->localtax1_assuj=="1"))
{
$newmenu->add("/compta/localtax/index.php?leftmenu=tax_vat&mainmenu=accountancy&localTaxType=1",$langs->transcountry("LT1",$mysoc->country_code),1,$user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax/i',$leftmenu)) $newmenu->add("/compta/localtax/card.php?leftmenu=tax_vat&action=create&localTaxType=1",$langs->trans("NewPayment"),2,$user->rights->tax->charges->creer);
if (empty($leftmenu) || preg_match('/^tax/i',$leftmenu)) $newmenu->add("/compta/localtax/reglement.php?leftmenu=tax_vat&localTaxType=1",$langs->trans("Payments"),2,$user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax/i',$leftmenu)) $newmenu->add("/compta/localtax/clients.php?leftmenu=tax_vat&localTaxType=1", $langs->trans("ReportByCustomers"), 2, $user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax/i',$leftmenu)) $newmenu->add("/compta/localtax/quadri_detail.php?leftmenu=tax_vat&localTaxType=1", $langs->trans("ReportByQuarter"), 2, $user->rights->tax->charges->lire);
}
//Local Taxes 2
if($mysoc->useLocalTax(2) && (isset($mysoc->localtax2_assuj) && $mysoc->localtax2_assuj=="1"))
{
$newmenu->add("/compta/localtax/index.php?leftmenu=tax_vat&mainmenu=accountancy&localTaxType=2",$langs->transcountry("LT2",$mysoc->country_code),1,$user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax/i',$leftmenu)) $newmenu->add("/compta/localtax/card.php?leftmenu=tax_vat&action=create&localTaxType=2",$langs->trans("NewPayment"),2,$user->rights->tax->charges->creer);
if (empty($leftmenu) || preg_match('/^tax/i',$leftmenu)) $newmenu->add("/compta/localtax/reglement.php?leftmenu=tax_vat&localTaxType=2",$langs->trans("Payments"),2,$user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax/i',$leftmenu)) $newmenu->add("/compta/localtax/clients.php?leftmenu=tax_vat&localTaxType=2", $langs->trans("ReportByCustomers"), 2, $user->rights->tax->charges->lire);
if (empty($leftmenu) || preg_match('/^tax/i',$leftmenu)) $newmenu->add("/compta/localtax/quadri_detail.php?leftmenu=tax_vat&localTaxType=2", $langs->trans("ReportByQuarter"), 2, $user->rights->tax->charges->lire);
}
}
}
}
// Accounting Expert
if (! empty($conf->accounting->enabled))
{
$langs->load("accountancy");
$newmenu->add("/accountancy/customer/index.php?leftmenu=ventil_customer",$langs->trans("CustomersVentilation"),0,$user->rights->accounting->ventilation->read, '', $mainmenu, 'ventil_customer');
if (empty($leftmenu) || $leftmenu=="ventil_customer") $newmenu->add("/accountancy/customer/list.php",$langs->trans("ToDispatch"),1,$user->rights->accounting->ventilation->dispatch);
if (empty($leftmenu) || $leftmenu=="ventil_customer") $newmenu->add("/accountancy/customer/lines.php",$langs->trans("Dispatched"),1,$user->rights->accounting->ventilation->read);
if (! empty($conf->supplier_invoice->enabled))
{
$newmenu->add("/accountancy/supplier/index.php?leftmenu=ventil_supplier",$langs->trans("SuppliersVentilation"),0,$user->rights->accounting->ventilation->read, '', $mainmenu, 'ventil_supplier');
if (empty($leftmenu) || $leftmenu=="ventil_supplier") $newmenu->add("/accountancy/supplier/list.php",$langs->trans("ToDispatch"),1,$user->rights->accounting->ventilation->dispatch);
if (empty($leftmenu) || $leftmenu=="ventil_supplier") $newmenu->add("/accountancy/supplier/lines.php",$langs->trans("Dispatched"),1,$user->rights->accounting->ventilation->read);
}
}
// Rapports
if (! empty($conf->comptabilite->enabled) || ! empty($conf->accounting->enabled))
{
$langs->load("compta");
// Bilan, resultats
$newmenu->add("/compta/resultat/index.php?leftmenu=report&mainmenu=accountancy",$langs->trans("Reportings"),0,$user->rights->compta->resultat->lire||$user->rights->accounting->comptarapport->lire, '', $mainmenu, 'ca');
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/resultat/index.php?leftmenu=report",$langs->trans("ReportInOut"),1,$user->rights->compta->resultat->lire||$user->rights->accounting->comptarapport->lire);
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/resultat/clientfourn.php?leftmenu=report",$langs->trans("ByCompanies"),2,$user->rights->compta->resultat->lire||$user->rights->accounting->comptarapport->lire);
/* On verra ca avec module compabilite expert
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/resultat/compteres.php?leftmenu=report","Compte de resultat",2,$user->rights->compta->resultat->lire);
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/resultat/bilan.php?leftmenu=report","Bilan",2,$user->rights->compta->resultat->lire);
*/
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/stats/index.php?leftmenu=report",$langs->trans("ReportTurnover"),1,$user->rights->compta->resultat->lire||$user->rights->accounting->comptarapport->lire);
/*
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/stats/cumul.php?leftmenu=report","Cumule",2,$user->rights->compta->resultat->lire);
if (! empty($conf->propal->enabled)) {
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/stats/prev.php?leftmenu=report","Previsionnel",2,$user->rights->compta->resultat->lire);
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/stats/comp.php?leftmenu=report","Transforme",2,$user->rights->compta->resultat->lire);
}
*/
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/stats/casoc.php?leftmenu=report",$langs->trans("ByCompanies"),2,$user->rights->compta->resultat->lire||$user->rights->accounting->comptarapport->lire);
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/stats/cabyuser.php?leftmenu=report",$langs->trans("ByUsers"),2,$user->rights->compta->resultat->lire||$user->rights->accounting->comptarapport->lire);
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/stats/cabyprodserv.php?leftmenu=report", $langs->trans("ByProductsAndServices"),2,$user->rights->compta->resultat->lire||$user->rights->accounting->comptarapport->lire);
if (! empty($conf->comptabilite->enabled))
{
// Journaux
//if ($leftmenu=="ca") $newmenu->add("/compta/journaux/index.php?leftmenu=ca",$langs->trans("Journaux"),1,$user->rights->compta->resultat->lire||$user->rights->accounting->comptarapport->lire);
//journaux
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/journal/sellsjournal.php?leftmenu=report",$langs->trans("SellsJournal"),1,$user->rights->compta->resultat->lire);
if (empty($leftmenu) || preg_match('/report/',$leftmenu)) $newmenu->add("/compta/journal/purchasesjournal.php?leftmenu=report",$langs->trans("PurchasesJournal"),1,$user->rights->compta->resultat->lire);
}
// Report expert
if (! empty($conf->accounting->enabled))
{
$langs->load("accountancy");
// Grand livre
$newmenu->add("/accountancy/bookkeeping/list.php?leftmenu=bookkeeping",$langs->trans("Bookkeeping"),0,$user->rights->accounting->mouvements->lire, '', $mainmenu, 'bookkeeping');
if (empty($leftmenu) || preg_match('/bookkeeping/',$leftmenu)) $newmenu->add("/accountancy/bookkeeping/listbyyear.php",$langs->trans("ByYear"),1,$user->rights->accounting->mouvements->lire);
if (empty($leftmenu) || preg_match('/bookkeeping/',$leftmenu)) $newmenu->add("/accountancy/bookkeeping/balancebymonth.php",$langs->trans("AccountBalanceByMonth"),1,$user->rights->accounting->mouvements->lire);
// Accountancy journals
if (! empty($conf->accounting->enabled) && !empty($user->rights->accounting->mouvements->lire) && $mainmenu == 'accountancy')
{
$newmenu->add('/accountancy/journal/index.php?leftmenu=journal',$langs->trans("Journaux"),0,$user->rights->banque->lire);
if ($leftmenu == 'journal')
{
$sql = "SELECT rowid, label, accountancy_journal";
$sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
$sql.= " WHERE entity = ".$conf->entity;
$sql.= " AND clos = 0";
$sql.= " ORDER BY label";
$resql = $db->query($sql);
if ($resql)
{
$numr = $db->num_rows($resql);
$i = 0;
if ($numr > 0)
while ($i < $numr)
{
$objp = $db->fetch_object($resql);
$newmenu->add('/accountancy/journal/bankjournal.php?id_account='.$objp->rowid,$langs->trans("Journal").' - '.$objp->label,1,$user->rights->accounting->comptarapport->lire);
$i++;
}
}
else dol_print_error($db);
$db->free($resql);
// Add other journal
$newmenu->add("/accountancy/journal/sellsjournal.php?leftmenu=journal",$langs->trans("SellsJournal"),1,$user->rights->accounting->comptarapport->lire);
$newmenu->add("/accountancy/journal/purchasesjournal.php?leftmenu=journal",$langs->trans("PurchasesJournal"),1,$user->rights->accounting->comptarapport->lire);
}
}
}
}
// Setup
if (! empty($conf->accounting->enabled))
{
$langs->load("admin");
// $newmenu->add("/accountancy/admin/fiscalyear.php?mainmenu=accountancy", $langs->trans("Fiscalyear"),0,$user->rights->accounting->fiscalyear, '', $mainmenu, 'fiscalyear');
$newmenu->add("/accountancy/admin/account.php?mainmenu=accountancy", $langs->trans("Chartofaccounts"),0,$user->rights->accounting->chartofaccount, '', $mainmenu, 'chartofaccount');
}
}
/*
* Menu BANK
*/
if ($mainmenu == 'bank')
{
$langs->load("withdrawals");
$langs->load("banks");
$langs->load("bills");
// Bank-Caisse
if (! empty($conf->banque->enabled))
{
$newmenu->add("/compta/bank/index.php?leftmenu=bank&mainmenu=bank",$langs->trans("MenuBankCash"),0,$user->rights->banque->lire, '', $mainmenu, 'bank');
$newmenu->add("/compta/bank/card.php?action=create",$langs->trans("MenuNewFinancialAccount"),1,$user->rights->banque->configurer);
$newmenu->add("/compta/bank/categ.php",$langs->trans("Rubriques"),1,$user->rights->banque->configurer);
$newmenu->add("/compta/bank/search.php",$langs->trans("ListTransactions"),1,$user->rights->banque->lire);
$newmenu->add("/compta/bank/budget.php",$langs->trans("ListTransactionsByCategory"),1,$user->rights->banque->lire);
$newmenu->add("/compta/bank/virement.php",$langs->trans("BankTransfers"),1,$user->rights->banque->transfer);
}
// Prelevements
if (! empty($conf->prelevement->enabled))
{
$newmenu->add("/compta/prelevement/index.php?leftmenu=withdraw&mainmenu=bank",$langs->trans("StandingOrders"),0,$user->rights->prelevement->bons->lire, '', $mainmenu, 'withdraw');
//if (empty($leftmenu) || $leftmenu=="withdraw") $newmenu->add("/compta/prelevement/demandes.php?status=0&mainmenu=bank",$langs->trans("StandingOrderToProcess"),1,$user->rights->prelevement->bons->lire);
if (empty($leftmenu) || $leftmenu=="withdraw") $newmenu->add("/compta/prelevement/create.php?mainmenu=bank",$langs->trans("NewStandingOrder"),1,$user->rights->prelevement->bons->creer);
if (empty($leftmenu) || $leftmenu=="withdraw") $newmenu->add("/compta/prelevement/bons.php?mainmenu=bank",$langs->trans("WithdrawalsReceipts"),1,$user->rights->prelevement->bons->lire);
if (empty($leftmenu) || $leftmenu=="withdraw") $newmenu->add("/compta/prelevement/list.php?mainmenu=bank",$langs->trans("WithdrawalsLines"),1,$user->rights->prelevement->bons->lire);
if (empty($leftmenu) || $leftmenu=="withdraw") $newmenu->add("/compta/prelevement/rejets.php?mainmenu=bank",$langs->trans("Rejects"),1,$user->rights->prelevement->bons->lire);
if (empty($leftmenu) || $leftmenu=="withdraw") $newmenu->add("/compta/prelevement/stats.php?mainmenu=bank",$langs->trans("Statistics"),1,$user->rights->prelevement->bons->lire);
//if (empty($leftmenu) || $leftmenu=="withdraw") $newmenu->add("/compta/prelevement/config.php",$langs->trans("Setup"),1,$user->rights->prelevement->bons->configurer);
}
// Gestion cheques
if (! empty($conf->banque->enabled) && (! empty($conf->facture->enabled)) || ! empty($conf->global->MAIN_MENU_CHEQUE_DEPOSIT_ON))
{
$newmenu->add("/compta/paiement/cheque/index.php?leftmenu=checks&mainmenu=bank",$langs->trans("MenuChequeDeposits"),0,$user->rights->banque->cheque, '', $mainmenu, 'checks');
$newmenu->add("/compta/paiement/cheque/card.php?leftmenu=checks&action=new&mainmenu=bank",$langs->trans("NewChequeDeposit"),1,$user->rights->banque->cheque);
$newmenu->add("/compta/paiement/cheque/list.php?leftmenu=checks&mainmenu=bank",$langs->trans("List"),1,$user->rights->banque->cheque);
}
}
/*
* Menu PRODUCTS-SERVICES
*/
if ($mainmenu == 'products')
{
// Products
if (! empty($conf->product->enabled))
{
$newmenu->add("/product/index.php?leftmenu=product&type=0", $langs->trans("Products"), 0, $user->rights->produit->lire, '', $mainmenu, 'product');
$newmenu->add("/product/card.php?leftmenu=product&action=create&type=0", $langs->trans("NewProduct"), 1, $user->rights->produit->creer);
$newmenu->add("/product/list.php?leftmenu=product&type=0", $langs->trans("List"), 1, $user->rights->produit->lire);
if (! empty($conf->stock->enabled))
{
$newmenu->add("/product/reassort.php?type=0", $langs->trans("Stocks"), 1, $user->rights->produit->lire && $user->rights->stock->lire);
}
if (! empty($conf->productbatch->enabled))
{
$langs->load("stocks");
$newmenu->add("/product/reassortlot.php?type=0", $langs->trans("StocksByLotSerial"), 1, $user->rights->produit->lire && $user->rights->stock->lire);
}
if (! empty($conf->propal->enabled))
{
$newmenu->add("/product/stats/card.php?id=all&leftmenu=stats&type=0", $langs->trans("Statistics"), 1, $user->rights->produit->lire && $user->rights->propale->lire);
}
}
// Services
if (! empty($conf->service->enabled))
{
$newmenu->add("/product/index.php?leftmenu=service&type=1", $langs->trans("Services"), 0, $user->rights->service->lire, '', $mainmenu, 'service');
$newmenu->add("/product/card.php?leftmenu=service&action=create&type=1", $langs->trans("NewService"), 1, $user->rights->service->creer);
$newmenu->add("/product/list.php?leftmenu=service&type=1", $langs->trans("List"), 1, $user->rights->service->lire);
if (! empty($conf->propal->enabled))
{
$newmenu->add("/product/stats/card.php?id=all&leftmenu=stats&type=1", $langs->trans("Statistics"), 1, $user->rights->service->lire && $user->rights->propale->lire);
}
}
// Categories
if (! empty($conf->categorie->enabled))
{
$langs->load("categories");
$newmenu->add("/categories/index.php?leftmenu=cat&type=0", $langs->trans("Categories"), 0, $user->rights->categorie->lire, '', $mainmenu, 'cat');
$newmenu->add("/categories/card.php?action=create&type=0", $langs->trans("NewCategory"), 1, $user->rights->categorie->creer);
//if (empty($leftmenu) || $leftmenu=="cat") $newmenu->add("/categories/list.php", $langs->trans("List"), 1, $user->rights->categorie->lire);
}
// Warehouse
if (! empty($conf->stock->enabled))
{
$langs->load("stocks");
$newmenu->add("/product/stock/index.php?leftmenu=stock", $langs->trans("Warehouses"), 0, $user->rights->stock->lire, '', $mainmenu, 'stock');
$newmenu->add("/product/stock/card.php?action=create", $langs->trans("MenuNewWarehouse"), 1, $user->rights->stock->creer);
$newmenu->add("/product/stock/list.php", $langs->trans("List"), 1, $user->rights->stock->lire);
$newmenu->add("/product/stock/mouvement.php", $langs->trans("Movements"), 1, $user->rights->stock->mouvement->lire);
if ($conf->supplier_order->enabled) $newmenu->add("/product/stock/replenish.php", $langs->trans("Replenishment"), 1, $user->rights->stock->mouvement->creer && $user->rights->fournisseur->lire);
$newmenu->add("/product/stock/massstockmove.php", $langs->trans("StockTransfer"), 1, $user->rights->stock->mouvement->creer);
}
// Expeditions
if (! empty($conf->expedition->enabled))
{
$langs->load("sendings");
$newmenu->add("/expedition/index.php?leftmenu=sendings", $langs->trans("Shipments"), 0, $user->rights->expedition->lire, '', $mainmenu, 'sendings');
$newmenu->add("/expedition/card.php?action=create2&leftmenu=sendings", $langs->trans("NewSending"), 1, $user->rights->expedition->creer);
$newmenu->add("/expedition/list.php?leftmenu=sendings", $langs->trans("List"), 1, $user->rights->expedition->lire);
if (empty($leftmenu) || $leftmenu=="sendings") $newmenu->add("/expedition/list.php?leftmenu=sendings&viewstatut=0", $langs->trans("StatusSendingDraftShort"), 2, $user->rights->expedition->lire);
if (empty($leftmenu) || $leftmenu=="sendings") $newmenu->add("/expedition/list.php?leftmenu=sendings&viewstatut=1", $langs->trans("StatusSendingValidatedShort"), 2, $user->rights->expedition->lire);
if (empty($leftmenu) || $leftmenu=="sendings") $newmenu->add("/expedition/list.php?leftmenu=sendings&viewstatut=2", $langs->trans("StatusSendingProcessedShort"), 2, $user->rights->expedition->lire);
$newmenu->add("/expedition/stats/index.php?leftmenu=sendings", $langs->trans("Statistics"), 1, $user->rights->expedition->lire);
}
}
/*
* Menu PROJECTS
*/
if ($mainmenu == 'project')
{
if (! empty($conf->projet->enabled))
{
$langs->load("projects");
// Project affected to user
$newmenu->add("/projet/index.php?leftmenu=projects&mode=mine", $langs->trans("MyProjects"), 0, $user->rights->projet->lire, '', $mainmenu, 'myprojects');
$newmenu->add("/projet/card.php?leftmenu=projects&action=create&mode=mine", $langs->trans("NewProject"), 1, $user->rights->projet->creer);
$newmenu->add("/projet/list.php?leftmenu=projects&mode=mine&search_status=1", $langs->trans("List"), 1, $user->rights->projet->lire);
// All project i have permission on
$newmenu->add("/projet/index.php?leftmenu=projects", $langs->trans("Projects"), 0, $user->rights->projet->lire && $user->rights->projet->lire, '', $mainmenu, 'projects');
$newmenu->add("/projet/card.php?leftmenu=projects&action=create", $langs->trans("NewProject"), 1, $user->rights->projet->creer && $user->rights->projet->creer);
$newmenu->add("/projet/list.php?leftmenu=projects&search_status=1", $langs->trans("List"), 1, $user->rights->projet->lire && $user->rights->projet->lire);
$newmenu->add("/projet/stats/index.php?leftmenu=projects", $langs->trans("Statistics"), 1, $user->rights->projet->lire && $user->rights->projet->lire);
if (empty($conf->global->PROJECT_HIDE_TASKS))
{
// Project affected to user
$newmenu->add("/projet/activity/index.php?mode=mine", $langs->trans("MyActivities"), 0, $user->rights->projet->lire);
$newmenu->add("/projet/tasks.php?action=create&mode=mine", $langs->trans("NewTask"), 1, $user->rights->projet->creer);
$newmenu->add("/projet/tasks/list.php?mode=mine", $langs->trans("List"), 1, $user->rights->projet->lire);
$newmenu->add("/projet/activity/perweek.php?mode=mine", $langs->trans("NewTimeSpent"), 1, $user->rights->projet->creer);
// All project i have permission on
$newmenu->add("/projet/activity/index.php", $langs->trans("Activities"), 0, $user->rights->projet->lire && $user->rights->projet->lire);
$newmenu->add("/projet/tasks.php?action=create", $langs->trans("NewTask"), 1, $user->rights->projet->creer && $user->rights->projet->creer);
$newmenu->add("/projet/tasks/list.php", $langs->trans("List"), 1, $user->rights->projet->lire && $user->rights->projet->lire);
$newmenu->add("/projet/activity/perweek.php", $langs->trans("NewTimeSpent"), 1, $user->rights->projet->creer && $user->rights->projet->creer);
}
}
}
/*
* Menu HRM
*/
if ($mainmenu == 'hrm')
{
// HRM module
if (! empty($conf->hrm->enabled))
{
$langs->load("hrm");
$newmenu->add("/user/index.php?&leftmenu=hrm&mode=employee", $langs->trans("Employees"), 0, $user->rights->hrm->employee->read, '', $mainmenu, 'hrm');
$newmenu->add("/user/card.php?&action=create", $langs->trans("NewEmployee"), 1,$user->rights->hrm->employee->write);
$newmenu->add("/user/index.php?&leftmenu=hrm&mode=employee", $langs->trans("List"), 1,$user->rights->hrm->employee->read);
}
// Leave/Holiday/Vacation module
if (! empty($conf->holiday->enabled))
{
$langs->load("holiday");
$langs->load("trips");
$newmenu->add("/holiday/list.php?&leftmenu=hrm", $langs->trans("CPTitreMenu"), 0, $user->rights->holiday->read, '', $mainmenu, 'hrm');
$newmenu->add("/holiday/card.php?&action=request", $langs->trans("New"), 1,$user->rights->holiday->write);
$newmenu->add("/holiday/list.php?&leftmenu=hrm", $langs->trans("List"), 1,$user->rights->holiday->read);
$newmenu->add("/holiday/list.php?select_statut=2&leftmenu=hrm", $langs->trans("ListToApprove"), 2, $user->rights->holiday->read);
$newmenu->add("/holiday/define_holiday.php?&action=request", $langs->trans("MenuConfCP"), 1, $user->rights->holiday->define_holiday);
$newmenu->add("/holiday/view_log.php?&action=request", $langs->trans("MenuLogCP"), 1, $user->rights->holiday->define_holiday);
}
// Trips and expenses (old module)
if (! empty($conf->deplacement->enabled))
{
$langs->load("trips");
$newmenu->add("/compta/deplacement/index.php?leftmenu=tripsandexpenses&mainmenu=hrm", $langs->trans("TripsAndExpenses"), 0, $user->rights->deplacement->lire, '', $mainmenu, 'tripsandexpenses');
$newmenu->add("/compta/deplacement/card.php?action=create&leftmenu=tripsandexpenses&mainmenu=hrm", $langs->trans("New"), 1, $user->rights->deplacement->creer);
$newmenu->add("/compta/deplacement/list.php?leftmenu=tripsandexpenses&mainmenu=hrm", $langs->trans("List"), 1, $user->rights->deplacement->lire);
$newmenu->add("/compta/deplacement/stats/index.php?leftmenu=tripsandexpenses&mainmenu=hrm", $langs->trans("Statistics"), 1, $user->rights->deplacement->lire);
}
}
/*
* Menu TOOLS
*/
if ($mainmenu == 'tools')
{
if (! empty($conf->mailing->enabled))
{
$langs->load("mails");
$newmenu->add("/comm/mailing/index.php?leftmenu=mailing", $langs->trans("EMailings"), 0, $user->rights->mailing->lire, '', $mainmenu, 'mailing');
$newmenu->add("/comm/mailing/card.php?leftmenu=mailing&action=create", $langs->trans("NewMailing"), 1, $user->rights->mailing->creer);
$newmenu->add("/comm/mailing/list.php?leftmenu=mailing", $langs->trans("List"), 1, $user->rights->mailing->lire);
}
if (! empty($conf->export->enabled))
{
$langs->load("exports");
$newmenu->add("/exports/index.php?leftmenu=export",$langs->trans("FormatedExport"),0, $user->rights->export->lire, '', $mainmenu, 'export');
$newmenu->add("/exports/export.php?leftmenu=export",$langs->trans("NewExport"),1, $user->rights->export->creer);
//$newmenu->add("/exports/export.php?leftmenu=export",$langs->trans("List"),1, $user->rights->export->lire);
}
if (! empty($conf->import->enabled))
{
$langs->load("exports");
$newmenu->add("/imports/index.php?leftmenu=import",$langs->trans("FormatedImport"),0, $user->rights->import->run, '', $mainmenu, 'import');
$newmenu->add("/imports/import.php?leftmenu=import",$langs->trans("NewImport"),1, $user->rights->import->run);
}
}
/*
* Menu MEMBERS
*/
if ($mainmenu == 'members')
{
if (! empty($conf->adherent->enabled))
{
$langs->load("members");
$langs->load("compta");
$newmenu->add("/adherents/index.php?leftmenu=members&mainmenu=members",$langs->trans("Members"),0,$user->rights->adherent->lire, '', $mainmenu, 'members');
$newmenu->add("/adherents/card.php?leftmenu=members&action=create",$langs->trans("NewMember"),1,$user->rights->adherent->creer);
$newmenu->add("/adherents/list.php?leftmenu=members",$langs->trans("List"),1,$user->rights->adherent->lire);
$newmenu->add("/adherents/list.php?leftmenu=members&statut=-1",$langs->trans("MenuMembersToValidate"),2,$user->rights->adherent->lire);
$newmenu->add("/adherents/list.php?leftmenu=members&statut=1",$langs->trans("MenuMembersValidated"),2,$user->rights->adherent->lire);
$newmenu->add("/adherents/list.php?leftmenu=members&statut=1&filter=uptodate",$langs->trans("MenuMembersUpToDate"),2,$user->rights->adherent->lire);
$newmenu->add("/adherents/list.php?leftmenu=members&statut=1&filter=outofdate",$langs->trans("MenuMembersNotUpToDate"),2,$user->rights->adherent->lire);
$newmenu->add("/adherents/list.php?leftmenu=members&statut=0",$langs->trans("MenuMembersResiliated"),2,$user->rights->adherent->lire);
$newmenu->add("/adherents/stats/index.php?leftmenu=members",$langs->trans("MenuMembersStats"),1,$user->rights->adherent->lire);
$newmenu->add("/adherents/index.php?leftmenu=members&mainmenu=members",$langs->trans("Subscriptions"),0,$user->rights->adherent->cotisation->lire);
$newmenu->add("/adherents/list.php?leftmenu=members&statut=-1,1&mainmenu=members",$langs->trans("NewSubscription"),1,$user->rights->adherent->cotisation->creer);
$newmenu->add("/adherents/cotisations.php?leftmenu=members",$langs->trans("List"),1,$user->rights->adherent->cotisation->lire);
$newmenu->add("/adherents/stats/index.php?leftmenu=members",$langs->trans("MenuMembersStats"),1,$user->rights->adherent->lire);
if (! empty($conf->categorie->enabled))
{
$langs->load("categories");
$newmenu->add("/categories/index.php?leftmenu=cat&type=3", $langs->trans("Categories"), 0, $user->rights->categorie->lire, '', $mainmenu, 'cat');
$newmenu->add("/categories/card.php?action=create&type=3", $langs->trans("NewCategory"), 1, $user->rights->categorie->creer);
//if (empty($leftmenu) || $leftmenu=="cat") $newmenu->add("/categories/list.php", $langs->trans("List"), 1, $user->rights->categorie->lire);
}
$newmenu->add("/adherents/index.php?leftmenu=export&mainmenu=members",$langs->trans("Exports"),0,$user->rights->adherent->export, '', $mainmenu, 'export');
if (! empty($conf->export->enabled) && (empty($leftmenu) || $leftmenu=="export")) $newmenu->add("/exports/index.php?leftmenu=export",$langs->trans("Datas"),1,$user->rights->adherent->export);
if (empty($leftmenu) || $leftmenu=="export") $newmenu->add("/adherents/htpasswd.php?leftmenu=export",$langs->trans("Filehtpasswd"),1,$user->rights->adherent->export);
if (empty($leftmenu) || $leftmenu=="export") $newmenu->add("/adherents/cartes/carte.php?leftmenu=export",$langs->trans("MembersCards"),1,$user->rights->adherent->export);
// Type
$newmenu->add("/adherents/type.php?leftmenu=setup&mainmenu=members",$langs->trans("MembersTypes"),0,$user->rights->adherent->configurer, '', $mainmenu, 'setup');
$newmenu->add("/adherents/type.php?leftmenu=setup&mainmenu=members&action=create",$langs->trans("New"),1,$user->rights->adherent->configurer);
$newmenu->add("/adherents/type.php?leftmenu=setup&mainmenu=members",$langs->trans("List"),1,$user->rights->adherent->configurer);
}
}
// Add personalized menus and modules menus
$menuArbo = new Menubase($db,'eldy');
$newmenu = $menuArbo->menuLeftCharger($newmenu,$mainmenu,$leftmenu,(empty($user->societe_id)?0:1),'eldy',$tabMenu);
// We update newmenu for special dynamic menus
if (!empty($user->rights->banque->lire) && $mainmenu == 'bank') // Entry for each bank account
{
$sql = "SELECT rowid, label, courant, rappro";
$sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
$sql.= " WHERE entity = ".$conf->entity;
$sql.= " AND clos = 0";
$sql.= " ORDER BY label";
$resql = $db->query($sql);
if ($resql)
{
$numr = $db->num_rows($resql);
$i = 0;
if ($numr > 0) $newmenu->add('/compta/bank/index.php',$langs->trans("BankAccounts"),0,$user->rights->banque->lire);
while ($i < $numr)
{
$objp = $db->fetch_object($resql);
$newmenu->add('/compta/bank/card.php?id='.$objp->rowid,$objp->label,1,$user->rights->banque->lire);
if ($objp->rappro && $objp->courant != 2 && empty($objp->clos)) // If not cash account and not closed and can be reconciliate
{
$newmenu->add('/compta/bank/rappro.php?account='.$objp->rowid,$langs->trans("Conciliate"),2,$user->rights->banque->consolidate);
}
$i++;
}
}
else dol_print_error($db);
$db->free($resql);
}
if (!empty($conf->ftp->enabled) && $mainmenu == 'ftp') // Entry for FTP
{
$MAXFTP=20;
$i=1;
while ($i <= $MAXFTP)
{
$paramkey='FTP_NAME_'.$i;
//print $paramkey;
if (! empty($conf->global->$paramkey))
{
$link="/ftp/index.php?idmenu=".$_SESSION["idmenu"]."&numero_ftp=".$i;
$newmenu->add($link, dol_trunc($conf->global->$paramkey,24));
}
$i++;
}
}
}
// Build final $menu_array = $menu_array_before +$newmenu->liste + $menu_array_after
//var_dump($menu_array_before);exit;
//var_dump($menu_array_after);exit;
$menu_array=$newmenu->liste;
if (is_array($menu_array_before)) $menu_array=array_merge($menu_array_before, $menu_array);
if (is_array($menu_array_after)) $menu_array=array_merge($menu_array, $menu_array_after);
//var_dump($menu_array);exit;
if (! is_array($menu_array)) return 0;
// TODO Use the position property in menu_array to reorder the $menu_array
//var_dump($menu_array);
/*$new_menu_array = array();
$level=0; $cusor=0; $position=0;
$nbentry = count($menu_array);
while (findNextEntryForLevel($menu_array, $cursor, $position, $level))
{
$cursor++;
}*/
// Show menu
$invert=empty($conf->global->MAIN_MENU_INVERT)?"":"invert";
if (empty($noout))
{
$alt=0; $altok=0; $blockvmenuopened=false;
$num=count($menu_array);
for ($i = 0; $i < $num; $i++)
{
$showmenu=true;
if (! empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED) && empty($menu_array[$i]['enabled'])) $showmenu=false;
$alt++;
if (empty($menu_array[$i]['level']) && $showmenu)
{
$altok++;
$blockvmenuopened=true;
if ($altok % 2 == 0)
{
print '<div class="blockvmenuimpair'.$invert.($altok == 1 ? ' blockvmenufirst':'').'">'."\n";
}
else
{
print '<div class="blockvmenupair'.$invert.($altok == 1 ? ' blockvmenufirst':'').'">'."\n";
}
}
// Place tabulation
$tabstring='';
$tabul=($menu_array[$i]['level'] - 1);
if ($tabul > 0)
{
for ($j=0; $j < $tabul; $j++)
{
$tabstring.=' ';
}
}
// For external modules
$tmp=explode('?',$menu_array[$i]['url'],2);
$url = $tmp[0];
$param = (isset($tmp[1])?$tmp[1]:'');
$url = dol_buildpath($url,1).($param?'?'.$param:'');
$url=preg_replace('/__LOGIN__/',$user->login,$url);
$url=preg_replace('/__USERID__/',$user->id,$url);
print '<!-- Process menu entry with mainmenu='.$menu_array[$i]['mainmenu'].', leftmenu='.$menu_array[$i]['leftmenu'].', level='.$menu_array[$i]['level'].' enabled='.$menu_array[$i]['enabled'].' -->'."\n";
// Menu niveau 0
if ($menu_array[$i]['level'] == 0)
{
if ($menu_array[$i]['enabled'])
{
print '<div class="menu_titre">'.$tabstring.'<a class="vmenu" href="'.$url.'"'.($menu_array[$i]['target']?' target="'.$menu_array[$i]['target'].'"':'').'>'.$menu_array[$i]['titre'].'</a></div>'."\n";
}
else if ($showmenu)
{
print '<div class="menu_titre">'.$tabstring.'<font class="vmenudisabled">'.$menu_array[$i]['titre'].'</font></div>'."\n";
}
if ($showmenu)
print '<div class="menu_top"></div>'."\n";
}
// Menu niveau > 0
if ($menu_array[$i]['level'] > 0)
{
if ($menu_array[$i]['enabled'])
{
print '<div class="menu_contenu">'.$tabstring;
if ($menu_array[$i]['url']) print '<a class="vsmenu" href="'.$url.'"'.($menu_array[$i]['target']?' target="'.$menu_array[$i]['target'].'"':'').'>';
else print '<span class="vsmenu">';
print $menu_array[$i]['titre'];
if ($menu_array[$i]['url']) print '</a>';
else print '</span>';
// If title is not pure text and contains a table, no carriage return added
if (! strstr($menu_array[$i]['titre'],'<table')) print '<br>';
print '</div>'."\n";
}
else if ($showmenu)
{
print '<div class="menu_contenu">'.$tabstring.'<font class="vsmenudisabled vsmenudisabledmargin">'.$menu_array[$i]['titre'].'</font><br></div>'."\n";
}
}
// If next is a new block or if there is nothing after
if (empty($menu_array[$i+1]['level']))
{
if ($showmenu)
print '<div class="menu_end"></div>'."\n";
if ($blockvmenuopened) { print '</div>'."\n"; $blockvmenuopened=false; }
}
}
if ($altok) print '<div class="blockvmenuend"></div>';
}
if (is_array($moredata) && ! empty($moredata['bookmarks']))
{
print "\n";
print "<!-- Begin Bookmarks -->\n";
print '<div id="blockvmenubookmarks" class="blockvmenubookmarks">'."\n";
print $moredata['bookmarks'];
print '</div>'."\n";
print "<!-- End Bookmarks -->\n";
}
return count($menu_array);
}
/**
* Function to test if an entry is enabled or not
*
* @param string $type_user 0=We need backoffice menu, 1=We need frontoffice menu
* @param array $menuentry Array for menu entry
* @param array $listofmodulesforexternal Array with list of modules allowed to external users
* @return int 0=Hide, 1=Show, 2=Show gray
*/
function dol_eldy_showmenu($type_user, &$menuentry, &$listofmodulesforexternal)
{
global $conf;
//print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
//print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition
if ($type_user && $menuentry['module'])
{
$tmploops=explode('|',$menuentry['module']);
$found=0;
foreach($tmploops as $tmploop)
{
if (in_array($tmploop, $listofmodulesforexternal)) {
$found++; break;
}
}
if (! $found) return 0; // Entry is for menus all excluded to external users
}
if (! $menuentry['perms'] && $type_user) return 0; // No permissions and user is external
if (! $menuentry['perms'] && ! empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) return 0; // No permissions and option to hide when not allowed, even for internal user, is on
if (! $menuentry['perms']) return 2; // No permissions and user is external
return 1;
}
| atm-robin/dolibarr | htdocs/core/menus/standard/eldy.lib.php | PHP | gpl-3.0 | 89,496 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of AudioLazy, the signal processing Python package.
# Copyright (C) 2012-2014 Danilo de Jesus da Silva Bellini
#
# AudioLazy 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.
#
# 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/>.
#
# Created on Wed May 01 2013
# danilo [dot] bellini [at] gmail [dot] com
"""
Pitch follower via DFT peak with Tkinter GUI
"""
# ------------------------
# AudioLazy pitch follower
# ------------------------
import sys
from audiolazy import (tostream, AudioIO, freq2str, sHz, chunks,
lowpass, envelope, pi, thub, Stream, maverage)
from numpy.fft import rfft
def limiter(sig, threshold=.1, size=256, env=envelope.rms, cutoff=pi/2048):
sig = thub(sig, 2)
return sig * Stream( 1. if el <= threshold else threshold / el
for el in maverage(size)(env(sig, cutoff=cutoff)) )
@tostream
def dft_pitch(sig, size=2048, hop=None):
for blk in Stream(sig).blocks(size=size, hop=hop):
dft_data = rfft(blk)
idx, vmax = max(enumerate(dft_data),
key=lambda el: abs(el[1]) / (2 * el[0] / size + 1)
)
yield 2 * pi * idx / size
def pitch_from_mic(upd_time_in_ms):
rate = 44100
s, Hz = sHz(rate)
api = sys.argv[1] if sys.argv[1:] else None # Choose API via command-line
chunks.size = 1 if api == "jack" else 16
with AudioIO(api=api) as recorder:
snd = recorder.record(rate=rate)
sndlow = lowpass(400 * Hz)(limiter(snd, cutoff=20 * Hz))
hop = int(upd_time_in_ms * 1e-3 * s)
for pitch in freq2str(dft_pitch(sndlow, size=2*hop, hop=hop) / Hz):
yield pitch
# ----------------
# GUI with tkinter
# ----------------
if __name__ == "__main__":
try:
import tkinter
except ImportError:
import Tkinter as tkinter
import threading
import re
# Window (Tk init), text label and button
tk = tkinter.Tk()
tk.title(__doc__.strip().splitlines()[0])
lbldata = tkinter.StringVar(tk)
lbltext = tkinter.Label(tk, textvariable=lbldata, font=("Purisa", 72),
width=10)
lbltext.pack(expand=True, fill=tkinter.BOTH)
btnclose = tkinter.Button(tk, text="Close", command=tk.destroy,
default="active")
btnclose.pack(fill=tkinter.X)
# Needed data
regex_note = re.compile(r"^([A-Gb#]*-?[0-9]*)([?+-]?)(.*?%?)$")
upd_time_in_ms = 200
# Update functions for each thread
def upd_value(): # Recording thread
pitches = iter(pitch_from_mic(upd_time_in_ms))
while not tk.should_finish:
tk.value = next(pitches)
def upd_timer(): # GUI mainloop thread
lbldata.set("\n".join(regex_note.findall(tk.value)[0]))
tk.after(upd_time_in_ms, upd_timer)
# Multi-thread management initialization
tk.should_finish = False
tk.value = freq2str(0) # Starting value
lbldata.set(tk.value)
tk.upd_thread = threading.Thread(target=upd_value)
# Go
tk.upd_thread.start()
tk.after_idle(upd_timer)
tk.mainloop()
tk.should_finish = True
tk.upd_thread.join()
| antiface/audiolazy | examples/dft_pitch.py | Python | gpl-3.0 | 3,525 |
////////////////////////////////////////////////////////////////////////////////
// Author: Thomas Arndt monotomy@cythar.sequenzer.org
// This file is part of CYTHAR Sequenzer
//
// 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/>.
////////////////////////////////////////////////////////////////////////////////
#ifndef DC_ALGROITHM_REBECA_HPP_INCLUDED
#define DC_ALGROITHM_REBECA_HPP_INCLUDED
#include <dc_objectstructure.h>
#include <dc_objectobserver.h>
#include <stddef.h>
#include <vector>
#ifdef DEBUG
#include <iostream>
#endif // DEBUG
namespace dc_algorithm{
using namespace dc_objects;
static inline int calc_one_repeat_step(int const left_hand_basevalue__,
OPERATOR const _operator_,
int const operand__) noexcept
{
switch (_operator_)
{
case OPERATOR::NOT:
return left_hand_basevalue__;
case OPERATOR::PLUS:
return left_hand_basevalue__+operand__;
case OPERATOR::MINUS:
return left_hand_basevalue__-operand__ ;
case OPERATOR::MULTI:
if(operand__ != 0)
return left_hand_basevalue__*operand__;
/*else*/
return left_hand_basevalue__;
case OPERATOR::DIV:
if(operand__ != 0)
return left_hand_basevalue__/operand__;
/*else*/
return left_hand_basevalue__;
case OPERATOR::MODULA:
if(operand__ != 0)
return left_hand_basevalue__%operand__;
/*else*/
return left_hand_basevalue__;
default:
return 0;
}
}
typedef std::vector<int> TYPE_series;
//! Berechnet eine einfache Serie
static inline TYPE_series calc_a_series(int const left_hand_basevalue__,
OPERATOR const _operator_,
int const operand__,
size_t const repeat_steps__) noexcept
{
TYPE_series results_serie{};
if(repeat_steps__ == 0)
return results_serie;
int repeat_step_result_or_base{left_hand_basevalue__};
for(size_t repeat_step{0} ; repeat_step != repeat_steps__ ; ++repeat_step)
{
repeat_step_result_or_base = calc_one_repeat_step(repeat_step_result_or_base,
_operator_,
operand__);
results_serie.push_back(repeat_step_result_or_base);
}
return results_serie;
}
//! Verrechnet zwei Serien per Eintrag mit _operator_ zu neuer Serie
inline static TYPE_series calc_two_series(TYPE_series const& left_hand_serie__,
OPERATOR const _operator_,
TYPE_series const& operand_serie__) noexcept
{
#ifdef DEBUG
if(left_hand_serie__.size() != operand_serie__.size())
std::cout << "BUG: Series incompatible!" << std::endl;
#endif // DEBUG
TYPE_series results_serie{};
for(size_t repeat_step{0};
repeat_step != left_hand_serie__.size();
++repeat_step)
{
results_serie.push_back(calc_one_repeat_step(left_hand_serie__[repeat_step],
_operator_,
operand_serie__[repeat_step]));
}
return std::move(results_serie);
}
//! Verrechnet Serien mit der Eintrags Id = Repeatstep
inline static TYPE_series calc_serie_by_index(TYPE_series const& left_hand_serie__,
OPERATOR const _operator_) noexcept
{
TYPE_series results_serie{};
for(size_t repeat_step{0};
repeat_step != left_hand_serie__.size();
++repeat_step)
{
results_serie.push_back(calc_one_repeat_step(left_hand_serie__[repeat_step],
_operator_,
repeat_step));
}
return std::move(results_serie);
}
//! Berechnung von Rebeca für Interval
static inline TYPE_series calc_rebeca_for_interval(dc_objects::Step const* step__)
{
//auto delay(step__->get_property<StepPropertiesIndex::DELAY>());
auto repeat_steps(step__->get_property<StepPropertiesIndex::REPEAT_TIMES>());
auto interval(step__->get_property<StepPropertiesIndex::INTERVAL>());
auto operator_(step__->get_property<StepPropertiesIndex::INTERVAL_OPERATOR>());
auto operand_(step__->get_property<StepPropertiesIndex::INTERVAL_OPERAND>());
return calc_a_series(interval,
static_cast<OPERATOR>(operator_),
operand_,
repeat_steps);
}
//! Berechnung von Rebeca für einfache Offset Serie
static inline TYPE_series calc_rebeca_for_offset(dc_objects::Step const* step__)
{
//auto delay(step__->get_property<StepPropertiesIndex::DELAY>());
auto repeat_steps(step__->get_property<StepPropertiesIndex::REPEAT_TIMES>());
auto offset(step__->get_property<StepPropertiesIndex::OFFSET>());
auto operator_(step__->get_property<StepPropertiesIndex::OFFSET_OPERATOR>());
auto operand_(step__->get_property<StepPropertiesIndex::OFFSET_OPERAND>());
return calc_a_series(offset,
static_cast<OPERATOR>(operator_),
operand_,
repeat_steps);
}
//! Berechnung von Rebeca für einfache Velcocity Serie
static inline TYPE_series calc_rebeca_for_velocity(dc_objects::Step const* step__)
{
//auto delay(step__->get_property<StepPropertiesIndex::DELAY>());
auto repeat_steps(step__->get_property<StepPropertiesIndex::REPEAT_TIMES>());
auto velocity(step__->get_property<StepPropertiesIndex::VELOCITY>());
auto operator_(step__->get_property<StepPropertiesIndex::VELOCITY_OPERATOR>());
auto operand_(step__->get_property<StepPropertiesIndex::VELOCITY_OPERAND>());
return calc_a_series(velocity,
static_cast<OPERATOR>(operator_),
operand_,
repeat_steps);
}
//! Berechnung von Rebeca für Length
static inline TYPE_series calc_rebeca_for_length(dc_objects::Step const* step__)
{
//auto delay(step__->get_property<StepPropertiesIndex::DELAY>());
auto repeat_steps(step__->get_property<StepPropertiesIndex::REPEAT_TIMES>());
auto length(step__->get_property<StepPropertiesIndex::LENGTH>());
auto operator_(step__->get_property<StepPropertiesIndex::LENGTH_OPERATOR>());
auto operand_(step__->get_property<StepPropertiesIndex::LENGTH_OPERAND>());
return calc_a_series(length,
static_cast<OPERATOR>(operator_),
operand_,
repeat_steps);
}
template<int MIN, int MAX>
static inline TYPE_series fit_series_to_range(TYPE_series serie__) noexcept
{
for(size_t i{0} ; i!= serie__.size() ; ++i)
{
if(serie__[i] < MIN)
{
serie__[i] = MIN;
continue;
}
if(serie__[i] > MAX)
serie__[i] = MAX;
}
return std::move(serie__);
}
//! Berechnung zwischen Offset-Interval & Repeat serie
static inline TYPE_series calc_rebeca_for_offet_complete(dc_objects::Step const* step__)
{
// Zwischenrechnung
auto offset2interval_serie(calc_two_series(calc_rebeca_for_offset(step__), //! atNOT will pass offset.
static_cast<OPERATOR>(step__->get_property<StepPropertiesIndex::OFFSET_2_INTERVAL_OPERATOR>()),
calc_rebeca_for_interval(step__)));
// Final Result
auto offset_series(calc_serie_by_index(offset2interval_serie,
static_cast<OPERATOR>(step__->get_property<StepPropertiesIndex::OFFSET_INTERVAL_2_REPEAT_OPERATOR>())));
// Abschnippel?
if(step__->get_property<StepPropertiesIndex::OFFSET_FIT_TO_RANGE>() == true)
offset_series = fit_series_to_range<OFFSET_MIN,OFFSET_MAX>(std::move(offset_series));
return offset_series;
}
//! Berechnung zwischen Velocity-Interval & Repeat serie
static inline TYPE_series calc_rebeca_for_velocity_complete(dc_objects::Step const* step__)
{
// Zwischenrechnung
auto velocity2interval_serie(calc_two_series(calc_rebeca_for_velocity(step__), //! atNOT will pass velocity.
static_cast<OPERATOR>(step__->get_property<StepPropertiesIndex::VELOCITY_2_INTERVAL_OPERATOR>()),
calc_rebeca_for_interval(step__)));
// Final Result
auto velocity_series(calc_serie_by_index(velocity2interval_serie,
static_cast<OPERATOR>(step__->get_property<StepPropertiesIndex::VELOCITY_INTERVAL_2_REPEAT_OPERATOR>())));
// Abschnippel?
if(step__->get_property<StepPropertiesIndex::VELOCITY_FIT_TO_RANGE>() == true)
velocity_series = fit_series_to_range<VELOCITY_MIN,VELOCITY_MAX>(std::move(velocity_series));
return velocity_series;
}
//! Berechnung zwischen Length-Interval & Repeat serie
static inline TYPE_series calc_rebeca_for_length_complete(dc_objects::Step const* step__)
{
// Zwischenrechnung
auto length2interval_serie(calc_two_series(calc_rebeca_for_length(step__), //! atNOT will pass length.
static_cast<OPERATOR>(step__->get_property<StepPropertiesIndex::LENGTH_2_INTERVAL_OPERATOR>()),
calc_rebeca_for_interval(step__)));
// Final Result
auto length_series(calc_serie_by_index(length2interval_serie,
static_cast<OPERATOR>(step__->get_property<StepPropertiesIndex::LENGTH_INTERVAL_2_REPEAT_OPERATOR>())));
// Abschnippel?
if(step__->get_property<StepPropertiesIndex::LENGTH_FIT_TO_RANGE>() == true)
length_series = fit_series_to_range<LENGTH_MIN,LENGTH_MAX>(std::move(length_series));
return length_series;
}
}
#endif // DC_ALGROITHM_REBECA_HPP_INCLUDED
| monotomy/CYTHAR-Sequenzer | dc_algorithm_rebeca.hpp | C++ | gpl-3.0 | 11,488 |
<?php namespace eduTrac\Classes\Models;
if ( ! defined('BASE_PATH') ) exit('No direct script access allowed');
/**
* Role Model
*
* PHP 5.4+
*
* eduTrac(tm) : Student Information System (http://www.7mediaws.org/)
* @copyright (c) 2013 7 Media Web Solutions, LLC
*
* 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/>.
*
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License, version 3
* @link http://www.7mediaws.org/
* @since 3.0.0
* @package eduTrac
* @author Joshua Parker <josh@7mediaws.org>
*/
use \eduTrac\Classes\Core\DB;
use \eduTrac\Classes\Libraries\Logs;
use \eduTrac\Classes\Libraries\Hooks;
use \eduTrac\Classes\Libraries\Cookies;
class RoleModel {
public function runRolePerm($data) {
$personID = $data['personID'];
if (isset($_POST['action'])) {
switch($_POST['action']) {
case 'saveRoles':
foreach ($_POST as $k => $v) {
if (substr($k,0,5) == "role_") {
$roleID = str_replace("role_","",$k);
if ($v == '0' || $v == 'x') {
$strSQL = sprintf("DELETE FROM `person_roles` WHERE `personID` = %u AND `roleID` = %u",$personID,$roleID);
} else {
$strSQL = sprintf("REPLACE INTO `person_roles` SET `personID` = %u, `roleID` = %u, `addDate` = '%s'",$personID,$roleID,date ("Y-m-d H:i:s"));
}
/* Write to logs */
//Logs::writeLog('Modified','Roles',$personID,$this->_auth->getPersonField('uname'));
DB::inst()->query($strSQL);
}
}
break;
case 'savePerms':
foreach ($_POST as $k => $v) {
if (substr($k,0,5) == "perm_") {
$permID = str_replace("perm_","",$k);
if ($v == 'x') {
$strSQL = sprintf("DELETE FROM `person_perms` WHERE `personID` = %u AND `permID` = %u",$personID,$permID);
} else {
$strSQL = sprintf("REPLACE INTO `person_perms` SET `personID` = %u, `permID` = %u, `value` = %u, `addDate` = '%s'",$personID,$permID,$v,date ("Y-m-d H:i:s"));
}
/* Write to logs */
//Logs::writeLog('Modified','Permissions',$personID,$this->_auth->getPersonField('uname'));
DB::inst()->query($strSQL);
}
}
break;
}
}
redirect($_SERVER['HTTP_REFERER']);
}
public function editSaveRole($data) {
$roleid = $data['roleID'];
$roleName = $data['roleName'];
if (isset($data['action'])) {
$strSQL = DB::inst()->query( sprintf("REPLACE INTO `role` SET `ID` = %u, `roleName` = '%s'",$roleid,$roleName ) ) or die(DB::inst()->is_error());
if ($strSQL->rowCount() > 1)
{
$roleID = $roleid;
} else {
$roleID = DB::inst()->lastInsertId();
}
foreach ($_POST as $k => $v)
{
if (substr($k,0,5) == "perm_")
{
$permID = str_replace("perm_","",$k);
if ($v == 'X')
{
$strSQL = sprintf("DELETE FROM `role_perms` WHERE `roleID` = %u AND `permID` = %u",$roleID,$permID);
DB::inst()->query($strSQL);
continue;
}
$strSQL = sprintf("REPLACE INTO `role_perms` SET `roleID` = %u, `permID` = %u, `value` = %u, `addDate` = '%s'",$roleID,$permID,$v,date ("Y-m-d H:i:s"));
DB::inst()->query($strSQL);
}
}
}
/* Write to logs */
//Logs::writeLog('Modified','Role',$roleName,$this->_auth->getPersonField('uname'));
redirect(BASE_URL . 'role/');
}
public function runRole($data) {
$roleID = $data['roleID'];
$roleName = $data['roleName'];
$rolePerm = Hooks::maybe_serialize($data['permission']);
$strSQL = DB::inst()->query( sprintf("REPLACE INTO `role` SET `ID` = %u, `roleName` = '%s', `permission` = '%s'",$roleID,$roleName,$rolePerm ) );
/* Write to logs */
//Logs::writeLog('Modified','Role',$roleName,$this->_auth->getPersonField('uname'));
redirect(BASE_URL . 'role/');
}
public function deleteRole($data) {
$id = $data['roleID'];
if (isset($data['delRole'])) :
$strSQL = sprintf("DELETE FROM `role` WHERE `ID` = '%u' LIMIT 1",$id);
DB::inst()->query($strSQL);
$strSQL = sprintf("DELETE FROM `person_roles` WHERE `roleID` = '%u'",$id);
DB::inst()->query($strSQL);
$strSQL = sprintf("DELETE FROM `role_perms` WHERE `roleID` = '%u'",$id);
DB::inst()->query($strSQL);
endif;
/* Write to logs */
//Logs::writeLog('Delete','Role',$id,$this->_auth->getPersonField('uname'));
}
public function __destruct() {
DB::inst()->close();
}
} | vb2005xu/eduTrac | eduTrac/Classes/Models/RoleModel.php | PHP | gpl-3.0 | 6,071 |
//This file is part of DictCCApp.
//
//DictCCApp 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.
//
//DictCCApp 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 DictCCApp. If not, see <http://www.gnu.org/licenses/>.
using DictCCApp.Domain;
using System;
using System.Collections.Generic;
namespace DictCCApp.Services
{
/// <summary>
/// this is a very weak cache
///
/// </summary>
internal class IndexCache
{
private Dictionary<string, WeakReference<WordSearchIndex>> _cache = new Dictionary<string, WeakReference<WordSearchIndex>>();
public WordSearchIndex GetIndex(string filename)
{
if (_cache.ContainsKey(filename))
{
WordSearchIndex index;
if (_cache[filename].TryGetTarget(out index))
{
return index;
}
_cache.Remove(filename);
return null;
}
return null;
}
public void AddIndex(string filename,WordSearchIndex index)
{
if (_cache.ContainsKey(filename))
{
_cache[filename] = new WeakReference<WordSearchIndex>(index);
} else
{
_cache.Add(filename, new WeakReference<WordSearchIndex>(index));
}
}
}
}
| universalappfactory/DictCCApp | DictCCApp/Services/IndexCache.cs | C# | gpl-3.0 | 1,802 |
var util = require( '../../utils/util.js' )
Page( {
data: {
projects: [ { name: 'FinalScheduler(终极排班系统)', git: "https://github.com/giscafer/FinalScheduler" },
{ name: 'MoveSite(电影狙击手)', git: "https://github.com/giscafer/moviesite" },
{ name: 'Ponitor(价格监控)', git: "https://github.com/giscafer/Ponitor" },
{ name: 'hexo-theme-cafe(Hexo博客主题)', git: "https://github.com/giscafer/hexo-theme-cafe" },
{ name: 'ife-course-demo(百度前端学院)', git: "https://github.com/giscafer/ife-course-demo" }
]
},
onReady: function() {
this.clickName();
},
clickName: function( e ) {
var pros = this.data.projects;
console.log( "#########################################################################################################" )
console.log( "## 其他项目 ##" )
console.log( "##-----------------------------------------------------------------------------------------------------##" )
pros.forEach( function( item, index ) {
console.log( "## ", item.name + ":" + item.git )
})
console.log( "## ##" )
console.log( "#########################################################################################################" )
}
})
| gouyuwang/private | wxapp/map/pages/logs/logs.js | JavaScript | gpl-3.0 | 1,470 |
/*! fabrik */
var FbListArticle=new Class({Extends:FbListPlugin}); | robho/fabrik | plugins/fabrik_list/article/article-min.js | JavaScript | gpl-3.0 | 66 |
@extends($layout)
@section('content-header')
<h1>
{{ trans('admin.permission.edit') }}
·
<small>{!! link_to_route('admin.permissions.index', trans('admin.public.back')) !!}</small>
</h1>
@stop
@section('content')
<div>
@include('admin::permissions.form', array('model' => $permission))
</div>
@stop
| thien3060/AppQuanAn | backend/sources/app_quan_an/resources/views/vendor/pingpong/admin/permissions/edit.blade.php | PHP | gpl-3.0 | 327 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package org.bradders.casiocfx9800g.node;
import org.bradders.casiocfx9800g.analysis.*;
@SuppressWarnings("nls")
public final class TComma extends Token
{
public TComma()
{
super.setText(",");
}
public TComma(int line, int pos)
{
super.setText(",");
setLine(line);
setPos(pos);
}
@Override
public Object clone()
{
return new TComma(getLine(), getPos());
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseTComma(this);
}
@Override
public void setText(@SuppressWarnings("unused") String text)
{
throw new RuntimeException("Cannot change TComma text.");
}
}
| RichardBradley/casio-cfx-9800g | cfx-9800g-emulator/src/org/bradders/casiocfx9800g/node/TComma.java | Java | gpl-3.0 | 807 |
/**
*
*/
package org.tlg.bot.mem.msg;
/**
* @author "Maksim Vakhnik"
*
*/
public class HelpMessage extends TextMessage {
private static final String MSG = "Send to bot your pictures"
+ ", add tags to these media. After this you can "
+ "search these media by these tags "
+ "and send it to your companion in a chat.\n"
+ "More details you can see here:\n"
+ "http://2686747.github.io/tagger-bot/" ;
public HelpMessage(final Long chatId) {
super(chatId, HelpMessage.MSG);
}
}
| 2686747/tagger-bot | src/main/java/org/tlg/bot/mem/msg/HelpMessage.java | Java | gpl-3.0 | 551 |
package maika.controller;
import java.beans.PropertyVetoException;
import maika.application.Application;
import maika.model.workspace.Diagram;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import maika.model.workspace.Project;
import javax.swing.JInternalFrame;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
public class WorkspaceTreeControler implements TreeSelectionListener{
public void valueChanged(TreeSelectionEvent e) {
// TODO Auto-generated method stub
TreePath path = e.getPath();
for(int i=0; i<path.getPathCount(); i++){
if(path.getPathComponent(i) instanceof Diagram){
Diagram d=(Diagram)path.getPathComponent(i);
JInternalFrame[] pom = new JInternalFrame[Application.getInstance().getDesktop().getAllFrames().length]; //napravim lokalne internal frameove
for (int j = 0; j < pom.length; j++) {
pom[j] = Application.getInstance().getDesktop().getAllFrames()[j]; //prepisem sve frameove u ove lokalne
if(pom[j].getName() == d.getName()){
try {
pom[j].setSelected(true);
} catch (PropertyVetoException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
}
}
break;
}
}
}
}
| remixgit/GraphicalEditor-Project | MaikaGraphicEditor/src/maika/controller/WorkspaceTreeControler.java | Java | gpl-3.0 | 1,508 |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class SItemReward : CVariable
{
[Ordinal(1)] [RED("item")] public CName Item { get; set;}
[Ordinal(2)] [RED("amount")] public CInt32 Amount { get; set;}
public SItemReward(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new SItemReward(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | Traderain/Wolven-kit | WolvenKit.CR2W/Types/W3/RTTIConvert/SItemReward.cs | C# | gpl-3.0 | 772 |
import os
import tempfile
import zipfile
from PyQt5 import QtCore, QtWidgets
import util
from vaults.modvault import utils
FormClass, BaseClass = util.THEME.loadUiType("vaults/modvault/upload.ui")
class UploadModWidget(FormClass, BaseClass):
def __init__(self, parent, modDir, modinfo, *args, **kwargs):
BaseClass.__init__(self, *args, **kwargs)
self.setupUi(self)
self.parent = parent
self.client = self.parent.client # type - ClientWindow
self.modinfo = modinfo
self.modDir = modDir
util.THEME.stylesheets_reloaded.connect(self.load_stylesheet)
self.load_stylesheet()
self.setWindowTitle("Uploading Mod")
self.Name.setText(modinfo.name)
self.Version.setText(str(modinfo.version))
if modinfo.ui_only:
self.isUILabel.setText("is UI Only")
else:
self.isUILabel.setText("not UI Only")
self.UID.setText(modinfo.uid)
self.Description.setPlainText(modinfo.description)
if modinfo.icon != "":
self.IconURI.setText(utils.iconPathToFull(modinfo.icon))
self.updateThumbnail()
else:
self.Thumbnail.setPixmap(
util.THEME.pixmap("games/unknown_map.png"),
)
self.UploadButton.pressed.connect(self.upload)
def load_stylesheet(self):
self.setStyleSheet(util.THEME.readstylesheet("client/client.css"))
@QtCore.pyqtSlot()
def upload(self):
n = self.Name.text()
if any([(i in n) for i in '"<*>|?/\\:']):
QtWidgets.QMessageBox.information(
self.client,
"Invalid Name",
"The mod name contains invalid characters: /\\<>|?:\"",
)
return
iconpath = utils.iconPathToFull(self.modinfo.icon)
infolder = False
if (
iconpath != ""
and (
os.path.commonprefix([
os.path.normcase(self.modDir),
os.path.normcase(iconpath),
])
== os.path.normcase(self.modDir)
)
): # the icon is in the game folder
# localpath = utils.fullPathToIcon(iconpath)
infolder = True
if iconpath != "" and not infolder:
QtWidgets.QMessageBox.information(
self.client,
"Invalid Icon File",
(
"The file {} is not located inside the modfolder. Copy the"
" icon file to your modfolder and change the mod_info.lua "
"accordingly".format(iconpath)
),
)
return
try:
temp = tempfile.NamedTemporaryFile(
mode='w+b', suffix=".zip", delete=False,
)
zipped = zipfile.ZipFile(temp, "w", zipfile.ZIP_DEFLATED)
zipdir(self.modDir, zipped, os.path.basename(self.modDir))
zipped.close()
temp.flush()
except BaseException:
QtWidgets.QMessageBox.critical(
self.client,
"Mod uploading error",
"Something went wrong zipping the mod files.",
)
return
# qfile = QtCore.QFile(temp.name)
# TODO: implement uploading via API
...
@QtCore.pyqtSlot()
def updateThumbnail(self):
iconfilename = utils.iconPathToFull(self.modinfo.icon)
if iconfilename == "":
return False
if os.path.splitext(iconfilename)[1].lower() == ".dds":
old = iconfilename
iconfilename = os.path.join(
self.modDir,
os.path.splitext(os.path.basename(iconfilename))[0] + ".png",
)
succes = utils.generateThumbnail(old, iconfilename)
if not succes:
QtWidgets.QMessageBox.information(
self.client,
"Invalid Icon File",
(
"Because FAF can't read DDS files, it tried to convert"
" it to a png. This failed. Try something else"
),
)
return False
try:
self.Thumbnail.setPixmap(util.THEME.pixmap(iconfilename, False))
except BaseException:
QtWidgets.QMessageBox.information(
self.client,
"Invalid Icon File",
"This was not a valid icon file. Please pick a png or jpeg",
)
return False
self.modinfo.thumbnail = utils.fullPathToIcon(iconfilename)
self.IconURI.setText(iconfilename)
return True
def zipdir(path, zipf, fname):
# zips the entire directory path to zipf. Every file in the zipfile starts
# with fname. So if path is "/foo/bar/hello" and fname is "test" then every
# file in zipf is of the form "/test/*.*"
path = os.path.normcase(path)
if path[-1] in r'\/':
path = path[:-1]
for root, dirs, files in os.walk(path):
for f in files:
name = os.path.join(os.path.normcase(root), f)
n = name[len(os.path.commonprefix([name, path])):]
if n[0] == "\\":
n = n[1:]
zipf.write(name, os.path.join(fname, n))
| FAForever/client | src/vaults/modvault/uploadwidget.py | Python | gpl-3.0 | 5,368 |
/*
* VITacademics
* Copyright (C) 2015 Aneesh Neelam <neelam.aneesh@gmail.com>
* Copyright (C) 2015 Saurabh Joshi <saurabhjoshi94@outlook.com>
* Copyright (C) 2015 Gaurav Agerwala <gauravagerwala@gmail.com>
* Copyright (C) 2015 Karthik Balakrishnan <karthikb351@gmail.com>
* Copyright (C) 2015 Pulkit Juneja <pulkit.16296@gmail.com>
* Copyright (C) 2015 Hemant Jain <hemanham@gmail.com>
* Copyright (C) 2015 Darshan Mehta <darshanmehta17@gmail.com>
*
* This file is part of VITacademics.
*
* VITacademics 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.
*
* VITacademics 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 VITacademics. If not, see <http://www.gnu.org/licenses/>.
*/
package com.karthikb351.vitinfo2.customwidget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import com.karthikb351.vitinfo2.R;
public class TimeLineView extends View {
public static final int STATE_FINISHED = 0X01;
public static final int STATE_CURRENT = 0X02;
public static final int STATE_SCHEDULED = 0X03;
public static final int TYPE_INITIAL = 0x04;
public static final int TYPE_INNER = 0x05;
public static final int TYPE_END = 0x06;
private float PADDING_TOP = 12;
private float CIRCLE_RADIUS = 6;
private float BORDER_THICKNESS = 4;
private float STROKE_WIDTH_RING = 3.33f;
private float STROKE_WIDTH_BORDER = 10;
private float STROKE_WIDTH_LINE = 2;
private int widgetState;
private int widgetType;
private Paint paintRing;
private Paint paintDot;
private Paint paintBorder;
private Paint paintLine;
private float cx;
private float cy;
private float height;
private float width;
private float density;
private RectF rectF;
private Path mPath;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
width = getWidth();
height = getHeight();
cx = width / 2;
cy = PADDING_TOP + CIRCLE_RADIUS;
switch (widgetState){
case STATE_CURRENT:
rectF.set(cx - BORDER_THICKNESS, cy - BORDER_THICKNESS,
cx + BORDER_THICKNESS, cy + BORDER_THICKNESS);
mPath.reset();
for (int i = 0; i <= 360; i++)
{
mPath.addArc(rectF, i, 1);
}
canvas.drawPath(mPath, paintBorder);
case STATE_SCHEDULED:
rectF.set(cx - CIRCLE_RADIUS, cy - CIRCLE_RADIUS,
cx + CIRCLE_RADIUS, cy + CIRCLE_RADIUS);
mPath.reset();
for (int i = 0; i <= 360; i += 1)
{
mPath.addArc(rectF, i, 1);
}
canvas.drawPath(mPath, paintRing);
break;
case STATE_FINISHED:
canvas.drawCircle(cx, cy, CIRCLE_RADIUS, paintDot);
break;
}
switch (widgetType){
case TYPE_INITIAL:
canvas.drawLine(cx, cy + (11 * density), cx, height, paintLine);
break;
case TYPE_INNER:
canvas.drawLine(cx, cy - (11 * density), cx, 0, paintLine);
canvas.drawLine(cx, cy + (11 * density), cx, height, paintLine);
break;
case TYPE_END:
canvas.drawLine(cx, cy - (11 * density), cx, 0, paintLine);
break;
}
}
private void initialize(){
density = getContext().getResources().getDisplayMetrics().density;
PADDING_TOP *= density;
BORDER_THICKNESS += CIRCLE_RADIUS;
BORDER_THICKNESS *= density;
CIRCLE_RADIUS *= density;
STROKE_WIDTH_RING *= density;
STROKE_WIDTH_BORDER *= density;
STROKE_WIDTH_LINE *= density;
paintDot = new Paint();
paintDot.setColor(ContextCompat.getColor(getContext(), R.color.text_secondary));
paintDot.setFlags(Paint.ANTI_ALIAS_FLAG);
paintRing = new Paint();
paintRing.setColor(ContextCompat.getColor(getContext(), R.color.text_secondary));
paintRing.setFlags(Paint.ANTI_ALIAS_FLAG);
paintRing.setStrokeWidth(STROKE_WIDTH_RING);
paintRing.setStyle(Paint.Style.FILL_AND_STROKE);
paintBorder = new Paint();
paintBorder.setColor(ContextCompat.getColor(getContext(), R.color.text_secondary));
paintBorder.setAlpha(90);
paintBorder.setFlags(Paint.ANTI_ALIAS_FLAG);
paintBorder.setStrokeWidth(STROKE_WIDTH_BORDER);
paintBorder.setStyle(Paint.Style.FILL_AND_STROKE);
paintLine = new Paint();
paintLine.setColor(ContextCompat.getColor(getContext(), R.color.text_secondary));
paintLine.setAlpha(70);
paintLine.setFlags(Paint.ANTI_ALIAS_FLAG);
paintLine.setStrokeWidth(STROKE_WIDTH_LINE);
paintLine.setStyle(Paint.Style.FILL_AND_STROKE);
widgetState = STATE_SCHEDULED;
widgetType = TYPE_INNER;
rectF = new RectF();
mPath = new Path();
}
public void setState(int state){
switch (state){
case STATE_CURRENT:
widgetState = STATE_CURRENT;
break;
case STATE_SCHEDULED:
widgetState = STATE_SCHEDULED;
break;
case STATE_FINISHED:
widgetState = STATE_FINISHED;
break;
default:
break;
}
invalidate();
}
public void setType(int type){
switch (type){
case TYPE_INITIAL:
widgetType = TYPE_INITIAL;
break;
case TYPE_INNER:
widgetType = TYPE_INNER;
break;
case TYPE_END:
widgetType = TYPE_END;
break;
default:
break;
}
invalidate();
}
public TimeLineView(Context context) {
super(context);
initialize();
}
public TimeLineView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
}
| saurabhsjoshi/VITacademics-for-Android | app/src/main/java/com/karthikb351/vitinfo2/customwidget/TimeLineView.java | Java | gpl-3.0 | 6,833 |
#include "filemetadatamodule.hh"
#include "../config/config.hh"
#include "../common/debug.hh"
extern ConfigLayer *configLayer;
using namespace mongo;
/**
* @brief Default Constructor
*/
FileMetaDataModule::FileMetaDataModule(ConfigMetaDataModule* configMetaDataModule) {
_configMetaDataModule = configMetaDataModule;
_collection = "FileMetaData";
_fileMetaDataStorage = new MongoDB();
_fileMetaDataStorage->connect();
_fileMetaDataStorage->setCollection(_collection);
//BSONObj querySegment = BSON ("id" << "config");
//BSONObj updateSegment = BSON ("$set" << BSON ("fileId" << 0));
//_fileMetaDataStorage->update(querySegment, updateSegment);
}
/**
* @brief Create a File
*/
void FileMetaDataModule::createFile(uint32_t clientId, const string &path,
uint64_t fileSize, uint32_t fileId) {
BSONObj insertSegment =
BSON ("id" << fileId << "path" << path << "fileSize" << (long long int)fileSize
<< "clientId" << clientId);
_fileMetaDataStorage->insert(insertSegment);
return;
}
/**
* @brief Delete a File
*/
void FileMetaDataModule::deleteFile(uint32_t fileId) {
BSONObj querySegment = BSON ("id" << fileId);
_fileMetaDataStorage->remove(querySegment);
}
/**
* @brief Rename a File
*/
void FileMetaDataModule::renameFile(uint32_t fileId, const string& newPath) {
BSONObj querySegment = BSON ("id" << fileId);
BSONObj updateSegment = BSON ("$set" << BSON ("path" << newPath));
_fileMetaDataStorage->update(querySegment, updateSegment);
}
/**
* @brief Lookup the File ID with file Path
*/
uint32_t FileMetaDataModule::lookupFileId(const string &path)
{
BSONObj querySegment = BSON ("path" << path);
uint32_t fileId = 0;
try {
BSONObj result = _fileMetaDataStorage->readOne(querySegment);
fileId = (uint32_t)result.getField("id").numberInt();
} catch (...) {
}
return fileId;
}
/**
* @brief Set File Size of a File
*
* @param fileId ID of the File
* @param fileSize Size of the File
*/
void FileMetaDataModule::setFileSize(uint32_t fileId, uint64_t fileSize)
{
BSONObj querySegment = BSON ("id" << fileId);
BSONObj updateSegment = BSON ("$set" << BSON ("fileSize" << (long long int)fileSize));
_fileMetaDataStorage->update(querySegment, updateSegment);
return ;
}
/**
* @brief Read File Size of a File
*
* @param fileId ID of the File
*
* @return File Size
*/
uint64_t FileMetaDataModule::readFileSize(uint32_t fileId)
{
BSONObj querySegment = BSON ("id" << fileId);
BSONObj result = _fileMetaDataStorage->readOne(querySegment);
return (uint64_t)result.getField("fileSize").numberLong();
}
/**
* @brief Save the Segment List of a File
*/
void FileMetaDataModule::saveSegmentList(uint32_t fileId, const vector<uint64_t> &segmentList) {
vector<uint64_t>::const_iterator it;
BSONObj querySegment = BSON ("id" << fileId);
BSONArrayBuilder arrb;
for(it = segmentList.begin(); it < segmentList.end(); ++it) {
arrb.append((long long int) *it);
}
BSONArray arr = arrb.arr();
BSONObj updateSegment = BSON ("$set" << BSON ("segmentList" << arr));
_fileMetaDataStorage->update(querySegment,updateSegment);
return;
}
/**
* @brief Read the Segment List of a File
*/
vector<uint64_t> FileMetaDataModule::readSegmentList(uint32_t fileId) {
vector<uint64_t> segmentList;
BSONObj querySegment = BSON ("id" << fileId);
BSONObj result = _fileMetaDataStorage->readOne(querySegment);
BSONForEach(it, result.getObjectField("segmentList")) {
segmentList.push_back((uint64_t)it.numberLong());
debug("SegmentList %lld\n",it.numberLong());
}
return segmentList;
}
/**
* @brief Generate a New File ID
*/
uint32_t FileMetaDataModule::generateFileId() {
return _configMetaDataModule->getAndInc("fileId");
}
| windkit/codfs-win | codfs/src/mds/filemetadatamodule.cc | C++ | gpl-3.0 | 3,685 |
package eu.siacs.conversations.xmpp.forms;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import eu.siacs.conversations.utils.Namespace;
import eu.siacs.conversations.xml.Element;
public class Data extends Element {
public static final String FORM_TYPE = "FORM_TYPE";
public Data() {
super("x");
this.setAttribute("xmlns", Namespace.DATA);
}
public List<Field> getFields() {
ArrayList<Field> fields = new ArrayList<Field>();
for (Element child : getChildren()) {
if (child.getName().equals("field")
&& !FORM_TYPE.equals(child.getAttribute("var"))) {
fields.add(Field.parse(child));
}
}
return fields;
}
public Field getFieldByName(String needle) {
for (Element child : getChildren()) {
if (child.getName().equals("field")
&& needle.equals(child.getAttribute("var"))) {
return Field.parse(child);
}
}
return null;
}
public Field put(String name, String value) {
Field field = getFieldByName(name);
if (field == null) {
field = new Field(name);
this.addChild(field);
}
field.setValue(value);
return field;
}
public void put(String name, Collection<String> values) {
Field field = getFieldByName(name);
if (field == null) {
field = new Field(name);
this.addChild(field);
}
field.setValues(values);
}
public void submit(Bundle options) {
for (Field field : getFields()) {
if (options.containsKey(field.getFieldName())) {
field.setValue(options.getString(field.getFieldName()));
}
}
submit();
}
public void submit() {
this.setAttribute("type", "submit");
removeUnnecessaryChildren();
for (Field field : getFields()) {
field.removeNonValueChildren();
}
}
private void removeUnnecessaryChildren() {
for (Iterator<Element> iterator = this.children.iterator(); iterator.hasNext(); ) {
Element element = iterator.next();
if (!element.getName().equals("field") && !element.getName().equals("title")) {
iterator.remove();
}
}
}
public static Data parse(Element element) {
Data data = new Data();
data.setAttributes(element.getAttributes());
data.setChildren(element.getChildren());
return data;
}
public void setFormType(String formType) {
Field field = this.put(FORM_TYPE, formType);
field.setAttribute("type", "hidden");
}
public String getFormType() {
String type = getValue(FORM_TYPE);
return type == null ? "" : type;
}
public String getValue(String name) {
Field field = this.getFieldByName(name);
return field == null ? null : field.getValue();
}
public String getTitle() {
return findChildContent("title");
}
public static Data create(String type, Bundle bundle) {
Data data = new Data();
data.setFormType(type);
data.setAttribute("type", "submit");
for (String key : bundle.keySet()) {
data.put(key, bundle.getString(key));
}
return data;
}
}
| kriztan/Pix-Art-Messenger | src/main/java/eu/siacs/conversations/xmpp/forms/Data.java | Java | gpl-3.0 | 3,497 |
/*
* This file is part of ARSnova Mobile.
* Copyright (C) 2011-2012 Christian Thomas Weber
* Copyright (C) 2012-2015 The ARSnova Team
*
* ARSnova Mobile 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.
*
* ARSnova Mobile 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 ARSnova Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
Ext.define('ARSnova.view.speaker.NewQuestionPanel', {
extend: 'Ext.Panel',
requires: [
'ARSnova.view.speaker.form.AbstentionForm',
'ARSnova.view.speaker.form.ExpandingAnswerForm',
'ARSnova.view.speaker.form.IndexedExpandingAnswerForm',
'ARSnova.view.speaker.form.FlashcardQuestion',
'ARSnova.view.speaker.form.SchoolQuestion',
'ARSnova.view.speaker.form.VoteQuestion',
'ARSnova.view.speaker.form.YesNoQuestion',
'ARSnova.view.speaker.form.NullQuestion',
'ARSnova.view.speaker.form.GridQuestion',
'ARSnova.view.speaker.form.FreeTextQuestion',
'ARSnova.view.speaker.form.ImageUploadPanel',
'ARSnova.view.MarkDownEditorPanel'
],
config: {
title: 'NewQuestionPanel',
fullscreen: true,
scrollable: true,
scroll: 'vertical',
variant: 'lecture',
releasedFor: 'all'
},
/* toolbar items */
toolbar: null,
backButton: null,
saveButton: null,
/* items */
text: null,
subject: null,
duration: null,
image: null,
/* for estudy */
userCourses: [],
initialize: function () {
this.callParent(arguments);
var screenWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width;
this.backButton = Ext.create('Ext.Button', {
text: Messages.QUESTIONS,
ui: 'back',
handler: function () {
var sTP = ARSnova.app.mainTabPanel.tabPanel.speakerTabPanel;
sTP.animateActiveItem(sTP.audienceQuestionPanel, {
type: 'slide',
direction: 'right',
duration: 700
});
}
});
this.saveButtonToolbar = Ext.create('Ext.Button', {
text: Messages.SAVE,
ui: 'confirm',
cls: 'saveQuestionButton',
style: 'width: 89px',
handler: function (button) {
this.saveHandler(button).then(function (response) {
ARSnova.app.getController('Questions').details({
question: Ext.decode(response.responseText)
});
});
},
scope: this
});
this.subject = Ext.create('Ext.field.Text', {
name: 'subject',
placeHolder: Messages.CATEGORY_PLACEHOLDER
});
this.textarea = Ext.create('Ext.plugins.ResizableTextArea', {
name: 'text',
placeHolder: Messages.FORMAT_PLACEHOLDER
});
this.markdownEditPanel = Ext.create('ARSnova.view.MarkDownEditorPanel', {
processElement: this.textarea
});
// Preview button
this.previewButton = Ext.create('Ext.Button', {
text: Ext.os.is.Desktop ?
Messages.QUESTION_PREVIEW_BUTTON_TITLE_DESKTOP :
Messages.QUESTION_PREVIEW_BUTTON_TITLE,
ui: 'action',
cls: Ext.os.is.Desktop ?
'previewButtonLong' :
'previewButton',
scope: this,
handler: function () {
this.defaultPreviewHandler();
}
});
// Preview panel with integrated button
this.previewPart = Ext.create('Ext.form.FormPanel', {
cls: 'newQuestion',
scrollable: null,
hidden: true,
items: [{
xtype: 'fieldset',
items: [this.previewButton]
}]
});
this.mainPart = Ext.create('Ext.form.FormPanel', {
cls: 'newQuestion',
scrollable: null,
items: [{
xtype: 'fieldset',
items: [this.subject]
}, {
xtype: 'fieldset',
items: [this.markdownEditPanel, this.textarea]
}]
});
this.abstentionPart = Ext.create('ARSnova.view.speaker.form.AbstentionForm', {
id: 'abstentionPart'
});
this.uploadView = Ext.create('ARSnova.view.speaker.form.ImageUploadPanel', {
handlerScope: this,
addRemoveButton: true,
activateTemplates: false,
urlUploadHandler: this.setImage,
fsUploadHandler: this.setImage
});
this.grid = Ext.create('ARSnova.view.components.GridImageContainer', {
editable: false,
gridIsHidden: true,
hidden: true,
style: "padding-top: 10px; margin-top: 30px"
});
this.releasePart = Ext.create('Ext.Panel', {
items: [
{
cls: 'gravure',
html: '<span class="coursemembersonlyicon"></span><span class="coursemembersonlymessage">' + Messages.MEMBERS_ONLY + '</span>'
}
],
hidden: true
});
this.yesNoQuestion = Ext.create('ARSnova.view.speaker.form.YesNoQuestion', {
hidden: true
});
this.multipleChoiceQuestion = Ext.create('ARSnova.view.speaker.form.ExpandingAnswerForm', {
hidden: true
});
this.voteQuestion = Ext.create('ARSnova.view.speaker.form.VoteQuestion', {
hidden: true
});
this.schoolQuestion = Ext.create('ARSnova.view.speaker.form.SchoolQuestion', {
hidden: true
});
this.abcdQuestion = Ext.create('ARSnova.view.speaker.form.IndexedExpandingAnswerForm', {
hidden: true
});
this.freetextQuestion = Ext.create('ARSnova.view.speaker.form.FreeTextQuestion', {
hidden: true
});
var messageAppendix = screenWidth >= 650 ? "_LONG" : "";
var formatItems = [
{text: Messages["MC" + messageAppendix], itemId: Messages.MC},
{text: Messages["ABCD" + messageAppendix], itemId: Messages.ABCD},
{text: Messages["YESNO" + messageAppendix], itemId: Messages.YESNO},
{text: Messages["FREETEXT" + messageAppendix], itemId: Messages.FREETEXT},
{text: Messages["EVALUATION" + messageAppendix], itemId: Messages.EVALUATION},
{text: Messages["SCHOOL" + messageAppendix], itemId: Messages.SCHOOL}
];
var me = this;
var config = ARSnova.app.globalConfig;
if (config.features.flashcard) {
formatItems.push({
itemId: Messages.FLASHCARD,
text: messageAppendix.length ?
Messages.FLASHCARD :
Messages.FLASHCARD_SHORT
});
me.flashcardQuestion = Ext.create('ARSnova.view.speaker.form.FlashcardQuestion', {
editPanel: false,
hidden: true
});
}
if (config.features.gridSquare) {
formatItems.push({
itemId: Messages.GRID,
text: Messages["GRID" + messageAppendix]
});
me.gridQuestion = Ext.create('ARSnova.view.speaker.form.GridQuestion', {
id: 'grid',
hidden: true
});
}
me.questionOptions = Ext.create('Ext.SegmentedButton', {
allowDepress: false,
items: formatItems,
defaults: {
ui: 'action'
},
listeners: {
scope: me,
toggle: function (container, button, pressed) {
var label = Ext.bind(function (longv, shortv) {
var screenWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width;
return (screenWidth >= 490 || me.backButton.isHidden()) ? longv : shortv;
}, me);
var title = '';
me.previewPart.hide();
me.previewButton.setHandler(this.defaultPreviewHandler);
switch (button.getText()) {
case Messages.GRID:
case Messages.GRID_LONG:
if (pressed) {
me.gridQuestion.show();
me.previewButton.setHandler(me.gridQuestion.previewHandler);
title = label(Messages.QUESTION_GRID, Messages.QUESTION_GRID_SHORT);
this.previewPart.show();
this.uploadView.hide();
this.grid.hide();
} else {
me.gridQuestion.hide();
this.uploadView.show();
if (this.grid.getImageFile()) {
this.grid.show();
}
}
break;
case Messages.EVALUATION:
case Messages.EVALUATION_LONG:
if (pressed) {
me.voteQuestion.show();
title = label(Messages.QUESTION_RATING, Messages.QUESTION_RATING_SHORT);
} else {
me.voteQuestion.hide();
}
break;
case Messages.SCHOOL:
case Messages.SCHOOL_LONG:
if (pressed) {
me.schoolQuestion.show();
title = label(Messages.QUESTION_GRADE, Messages.QUESTION_GRADE_SHORT);
} else {
me.schoolQuestion.hide();
}
break;
case Messages.MC:
case Messages.MC_LONG:
if (pressed) {
me.multipleChoiceQuestion.show();
title = label(Messages.QUESTION_MC, Messages.QUESTION_MC_SHORT);
} else {
me.multipleChoiceQuestion.hide();
}
break;
case Messages.YESNO:
case Messages.YESNO_LONG:
if (pressed) {
me.previewPart.show();
me.yesNoQuestion.show();
me.previewButton.setHandler(me.yesNoQuestion.previewHandler);
title = label(Messages.QUESTION_YESNO, Messages.QUESTION_YESNO_SHORT);
} else {
me.yesNoQuestion.hide();
}
break;
case Messages.ABCD:
case Messages.ABCD_LONG:
if (pressed) {
me.abcdQuestion.show();
title = label(Messages.QUESTION_SINGLE_CHOICE, Messages.QUESTION_SINGLE_CHOICE_SHORT);
} else {
me.abcdQuestion.hide();
}
break;
case Messages.FREETEXT:
case Messages.FREETEXT_LONG:
if (pressed) {
me.previewPart.show();
me.freetextQuestion.show();
title = label(Messages.QUESTION_FREETEXT, Messages.QUESTION_FREETEXT_SHORT);
} else {
me.freetextQuestion.hide();
}
break;
case Messages.FLASHCARD:
case Messages.FLASHCARD_SHORT:
if (pressed) {
me.textarea.setPlaceHolder(Messages.FLASHCARD_FRONT_PAGE);
me.flashcardQuestion.show();
me.abstentionPart.hide();
title = Messages.FLASHCARD;
me.uploadView.setUploadPanelConfig(
Messages.PICTURE_SOURCE + " - " +
Messages.FLASHCARD_BACK_PAGE,
me.setFcImage, me.setFcImage
);
} else {
me.textarea.setPlaceHolder(Messages.FORMAT_PLACEHOLDER);
me.flashcardQuestion.hide();
me.abstentionPart.show();
me.uploadView.setUploadPanelConfig(
Messages.PICTURE_SOURCE,
me.setImage, me.setImage
);
}
break;
default:
title = Messages.NEW_QUESTION_TITLE;
break;
}
me.toolbar.setTitle(title);
}
}
});
me.toolbar = Ext.create('Ext.Toolbar', {
title: Messages.NEW_QUESTION_TITLE,
cls: 'speakerTitleText',
docked: 'top',
ui: 'light',
items: [
me.backButton,
{xtype: 'spacer'},
me.saveButtonToolbar
]
});
me.saveAndContinueButton = Ext.create('Ext.Button', {
ui: 'confirm',
cls: 'saveQuestionButton',
text: Messages.SAVE_AND_CONTINUE,
style: 'margin-top: 70px',
handler: function (button) {
me.saveHandler(button).then(function () {
var theNotificationBox = {};
theNotificationBox = Ext.create('Ext.Panel', {
cls: 'notificationBox',
name: 'notificationBox',
showAnimation: 'pop',
modal: true,
centered: true,
width: 300,
styleHtmlContent: true,
styleHtmlCls: 'notificationBoxText',
html: Messages.QUESTION_SAVED
});
Ext.Viewport.add(theNotificationBox);
theNotificationBox.show();
/* Workaround for Chrome 34+ */
Ext.defer(function () {
theNotificationBox.destroy();
}, 3000);
}).then(Ext.bind(function (response) {
me.getScrollable().getScroller().scrollTo(0, 0, true);
}, me));
},
scope: me
});
me.add([me.toolbar,
Ext.create('Ext.Toolbar', {
cls: 'noBackground noBorder',
docked: 'top',
scrollable: {
direction: 'horizontal',
directionLock: true
},
items: [{
xtype: 'spacer'
},
me.questionOptions,
{
xtype: 'spacer'
}
]
}),
me.mainPart,
me.previewPart,
/* only one of the question types will be shown at the same time */
me.voteQuestion,
me.multipleChoiceQuestion,
me.yesNoQuestion,
me.schoolQuestion,
me.abcdQuestion,
me.freetextQuestion
]);
if (me.flashcardQuestion) {
me.add(me.flashcardQuestion);
}
me.add([
me.abstentionPart,
me.uploadView,
me.grid
]);
if (me.gridQuestion) {
me.add(me.gridQuestion);
}
me.add([
me.releasePart,
me.saveAndContinueButton
]);
me.on('activate', me.onActivate);
},
onActivate: function () {
this.questionOptions.setPressedButtons([0]);
this.releasePart.setHidden(localStorage.getItem('courseId') === null || localStorage.getItem('courseId').length === 0);
},
defaultPreviewHandler: function () {
var questionPreview = Ext.create('ARSnova.view.QuestionPreviewBox');
questionPreview.showPreview(this.subject.getValue(), this.textarea.getValue());
},
saveHandler: function (button) {
/* disable save button in order to avoid multiple question creation */
button.disable();
var panel = ARSnova.app.mainTabPanel.tabPanel.speakerTabPanel.newQuestionPanel;
var values = {};
/* get text, subject of question from mainPart */
var mainPartValues = panel.mainPart.getValues();
values.text = mainPartValues.text;
values.subject = mainPartValues.subject;
values.abstention = !panel.abstentionPart.isHidden() && panel.abstentionPart.getAbstention();
values.questionVariant = panel.getVariant();
values.image = this.image;
values.flashcardImage = null;
values.imageQuestion = false;
if (localStorage.getItem('courseId') != null && localStorage.getItem('courseId').length > 0) {
values.releasedFor = 'courses';
} else {
values.releasedFor = panel.getReleasedFor();
}
/* fetch the values */
switch (panel.questionOptions.getPressedButtons()[0]._text) {
case Messages.GRID:
case Messages.GRID_LONG:
values.questionType = "grid";
Ext.apply(values, panel.gridQuestion.getQuestionValues());
break;
case Messages.EVALUATION:
case Messages.EVALUATION_LONG:
values.questionType = "vote";
Ext.apply(values, panel.voteQuestion.getQuestionValues());
break;
case Messages.SCHOOL:
case Messages.SCHOOL_LONG:
values.questionType = "school";
Ext.apply(values, panel.schoolQuestion.getQuestionValues());
break;
case Messages.MC:
case Messages.MC_LONG:
values.questionType = "mc";
Ext.apply(values, panel.multipleChoiceQuestion.getQuestionValues());
break;
case Messages.YESNO:
case Messages.YESNO_LONG:
values.questionType = "yesno";
Ext.apply(values, panel.yesNoQuestion.getQuestionValues());
break;
case Messages.ABCD:
case Messages.ABCD_LONG:
values.questionType = "abcd";
Ext.apply(values, panel.abcdQuestion.getQuestionValues());
break;
case Messages.FREETEXT:
case Messages.FREETEXT_LONG:
values.questionType = "freetext";
values.possibleAnswers = [];
Ext.apply(values, panel.freetextQuestion.getQuestionValues());
break;
case Messages.FLASHCARD:
case Messages.FLASHCARD_SHORT:
values.questionType = "flashcard";
values.flashcardImage = this.fcImage;
Ext.apply(values, panel.flashcardQuestion.getQuestionValues());
break;
default:
break;
}
var promise = panel.dispatch(values, button);
promise.then(function () {
panel.subject.reset();
panel.textarea.reset();
if (panel.flashcardQuestion) {
panel.flashcardQuestion.answer.reset();
panel.flashcardQuestion.uploadView.resetButtons();
panel.setFcImage(null);
}
panel.multipleChoiceQuestion.resetFields();
panel.abcdQuestion.resetFields();
switch (panel.questionOptions.getPressedButtons()[0]._text) {
case Messages.GRID:
case Messages.GRID_LONG:
panel.gridQuestion.resetView();
/* fall through */
default:
panel.setImage(null);
panel.uploadView.resetButtons();
panel.uploadView.setUploadPanelConfig(
Messages.PICTURE_SOURCE,
panel.setImage, panel.setImage
);
break;
}
// animated scrolling to top
panel.getScrollable().getScroller().scrollTo(0, 0, true);
});
return promise;
},
dispatch: function (values, button) {
var promise = new RSVP.Promise();
ARSnova.app.getController('Questions').add({
sessionKeyword: sessionStorage.getItem('keyword'),
text: values.text,
subject: values.subject,
type: "skill_question",
questionType: values.questionType,
questionVariant: values.questionVariant,
duration: values.duration,
number: 0, // unused
active: 1,
possibleAnswers: values.possibleAnswers,
releasedFor: values.releasedFor,
noCorrect: values.noCorrect,
abstention: values.abstention,
showStatistic: 1,
gridSize: values.gridSize,
offsetX: values.offsetX,
offsetY: values.offsetY,
zoomLvl: values.zoomLvl,
image: values.image,
fcImage: values.flashcardImage,
gridOffsetX: values.gridOffsetX,
gridOffsetY: values.gridOffsetY,
gridZoomLvl: values.gridZoomLvl,
gridSizeX: values.gridSizeX,
gridSizeY: values.gridSizeY,
gridIsHidden: values.gridIsHidden,
imgRotation: values.imgRotation,
toggleFieldsLeft: values.toggleFieldsLeft,
numClickableFields: values.numClickableFields,
thresholdCorrectAnswers: values.thresholdCorrectAnswers,
cvIsColored: values.cvIsColored,
gridLineColor: values.gridLineColor,
numberOfDots: values.numberOfDots,
gridType: values.gridType,
scaleFactor: values.scaleFactor,
gridScaleFactor: values.gridScaleFactor,
imageQuestion: values.imageQuestion,
textAnswerEnabled: values.textAnswerEnabled,
saveButton: button,
successFunc: function (response, opts) {
promise.resolve(response);
button.enable();
},
failureFunc: function (response, opts) {
Ext.Msg.alert(Messages.NOTICE, Messages.QUESTION_CREATION_ERROR);
promise.reject(response);
button.enable();
}
});
return promise;
},
setGridConfiguration: function (grid) {
grid.setEditable(false);
grid.setGridIsHidden(true);
},
setImage: function (image, test) {
var title = this.toolbar.getTitle().getTitle(),
isFlashcard = title === Messages.FLASHCARD,
grid = isFlashcard ? this.flashcardQuestion.grid : this.grid;
this.image = image;
grid.setImage(image);
if (image) {
grid.show();
} else {
grid.hide();
grid.clearImage();
this.setGridConfiguration(grid);
}
},
setFcImage: function (image) {
this.fcImage = image;
this.grid.setImage(image);
if (image) {
this.grid.show();
} else {
this.grid.hide();
this.grid.clearImage();
this.setGridConfiguration(this.grid);
}
},
/**
* Selects a button of the segmentation component with the given name.
*
* @param text The text of the button to be selected.
*/
activateButtonWithText: function (text) {
var me = this;
this.questionOptions.innerItems.forEach(function (item, index) {
if (item.getItemId() === text) {
me.questionOptions.setPressedButtons([index]);
}
});
}
});
| commana/arsnova-mobile | src/main/webapp/app/view/speaker/NewQuestionPanel.js | JavaScript | gpl-3.0 | 18,815 |
package com.sk89q.craftbook.bukkit;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import com.sk89q.craftbook.LocalComponent;
import com.sk89q.craftbook.Mechanic;
import com.sk89q.craftbook.MechanicFactory;
import com.sk89q.craftbook.MechanicManager;
import com.sk89q.craftbook.bukkit.commands.CircuitCommands;
import com.sk89q.craftbook.circuits.GlowStone;
import com.sk89q.craftbook.circuits.JackOLantern;
import com.sk89q.craftbook.circuits.Netherrack;
import com.sk89q.craftbook.circuits.Pipes;
import com.sk89q.craftbook.circuits.gates.logic.AndGate;
import com.sk89q.craftbook.circuits.gates.logic.Clock;
import com.sk89q.craftbook.circuits.gates.logic.ClockDivider;
import com.sk89q.craftbook.circuits.gates.logic.ClockST;
import com.sk89q.craftbook.circuits.gates.logic.CombinationLock;
import com.sk89q.craftbook.circuits.gates.logic.Counter;
import com.sk89q.craftbook.circuits.gates.logic.DeMultiplexer;
import com.sk89q.craftbook.circuits.gates.logic.Delayer;
import com.sk89q.craftbook.circuits.gates.logic.Dispatcher;
import com.sk89q.craftbook.circuits.gates.logic.DownCounter;
import com.sk89q.craftbook.circuits.gates.logic.EdgeTriggerDFlipFlop;
import com.sk89q.craftbook.circuits.gates.logic.FullAdder;
import com.sk89q.craftbook.circuits.gates.logic.FullSubtractor;
import com.sk89q.craftbook.circuits.gates.logic.HalfAdder;
import com.sk89q.craftbook.circuits.gates.logic.HalfSubtractor;
import com.sk89q.craftbook.circuits.gates.logic.InvertedRsNandLatch;
import com.sk89q.craftbook.circuits.gates.logic.Inverter;
import com.sk89q.craftbook.circuits.gates.logic.JkFlipFlop;
import com.sk89q.craftbook.circuits.gates.logic.LevelTriggeredDFlipFlop;
import com.sk89q.craftbook.circuits.gates.logic.LowDelayer;
import com.sk89q.craftbook.circuits.gates.logic.LowNotPulser;
import com.sk89q.craftbook.circuits.gates.logic.LowPulser;
import com.sk89q.craftbook.circuits.gates.logic.Marquee;
import com.sk89q.craftbook.circuits.gates.logic.MemoryAccess;
import com.sk89q.craftbook.circuits.gates.logic.MemorySetter;
import com.sk89q.craftbook.circuits.gates.logic.Monostable;
import com.sk89q.craftbook.circuits.gates.logic.Multiplexer;
import com.sk89q.craftbook.circuits.gates.logic.NandGate;
import com.sk89q.craftbook.circuits.gates.logic.NotDelayer;
import com.sk89q.craftbook.circuits.gates.logic.NotLowDelayer;
import com.sk89q.craftbook.circuits.gates.logic.NotPulser;
import com.sk89q.craftbook.circuits.gates.logic.Pulser;
import com.sk89q.craftbook.circuits.gates.logic.Random3Bit;
import com.sk89q.craftbook.circuits.gates.logic.Random5Bit;
import com.sk89q.craftbook.circuits.gates.logic.RandomBit;
import com.sk89q.craftbook.circuits.gates.logic.RandomBitST;
import com.sk89q.craftbook.circuits.gates.logic.RangedOutput;
import com.sk89q.craftbook.circuits.gates.logic.Repeater;
import com.sk89q.craftbook.circuits.gates.logic.RsNandLatch;
import com.sk89q.craftbook.circuits.gates.logic.RsNorFlipFlop;
import com.sk89q.craftbook.circuits.gates.logic.ToggleFlipFlop;
import com.sk89q.craftbook.circuits.gates.logic.XnorGate;
import com.sk89q.craftbook.circuits.gates.logic.XorGate;
import com.sk89q.craftbook.circuits.gates.world.blocks.BlockBreaker;
import com.sk89q.craftbook.circuits.gates.world.blocks.BlockBreakerST;
import com.sk89q.craftbook.circuits.gates.world.blocks.BlockLauncher;
import com.sk89q.craftbook.circuits.gates.world.blocks.BonemealTerraformer;
import com.sk89q.craftbook.circuits.gates.world.blocks.BonemealTerraformerST;
import com.sk89q.craftbook.circuits.gates.world.blocks.CombineHarvester;
import com.sk89q.craftbook.circuits.gates.world.blocks.CombineHarvesterST;
import com.sk89q.craftbook.circuits.gates.world.blocks.Cultivator;
import com.sk89q.craftbook.circuits.gates.world.blocks.CultivatorST;
import com.sk89q.craftbook.circuits.gates.world.blocks.FlexibleSetBlock;
import com.sk89q.craftbook.circuits.gates.world.blocks.Irrigator;
import com.sk89q.craftbook.circuits.gates.world.blocks.IrrigatorST;
import com.sk89q.craftbook.circuits.gates.world.blocks.LiquidFlood;
import com.sk89q.craftbook.circuits.gates.world.blocks.LiquidFloodST;
import com.sk89q.craftbook.circuits.gates.world.blocks.MultipleSetBlock;
import com.sk89q.craftbook.circuits.gates.world.blocks.Planter;
import com.sk89q.craftbook.circuits.gates.world.blocks.PlanterST;
import com.sk89q.craftbook.circuits.gates.world.blocks.Pump;
import com.sk89q.craftbook.circuits.gates.world.blocks.PumpST;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockAbove;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockAboveChest;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockAboveChestST;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockAboveST;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockBelow;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockBelowChest;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockBelowChestST;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockBelowST;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetBridge;
import com.sk89q.craftbook.circuits.gates.world.blocks.SetDoor;
import com.sk89q.craftbook.circuits.gates.world.blocks.Spigot;
import com.sk89q.craftbook.circuits.gates.world.entity.AdvancedEntitySpawner;
import com.sk89q.craftbook.circuits.gates.world.entity.AnimalHarvester;
import com.sk89q.craftbook.circuits.gates.world.entity.AnimalHarvesterST;
import com.sk89q.craftbook.circuits.gates.world.entity.CreatureSpawner;
import com.sk89q.craftbook.circuits.gates.world.entity.EntityCannon;
import com.sk89q.craftbook.circuits.gates.world.entity.EntityCannonST;
import com.sk89q.craftbook.circuits.gates.world.entity.EntityTrap;
import com.sk89q.craftbook.circuits.gates.world.entity.EntityTrapST;
import com.sk89q.craftbook.circuits.gates.world.entity.TeleportReciever;
import com.sk89q.craftbook.circuits.gates.world.entity.TeleportRecieverST;
import com.sk89q.craftbook.circuits.gates.world.entity.TeleportTransmitter;
import com.sk89q.craftbook.circuits.gates.world.items.AutomaticCrafter;
import com.sk89q.craftbook.circuits.gates.world.items.AutomaticCrafterST;
import com.sk89q.craftbook.circuits.gates.world.items.ChestStocker;
import com.sk89q.craftbook.circuits.gates.world.items.ChestStockerST;
import com.sk89q.craftbook.circuits.gates.world.items.ContainerCollector;
import com.sk89q.craftbook.circuits.gates.world.items.ContainerCollectorST;
import com.sk89q.craftbook.circuits.gates.world.items.ContainerDispenser;
import com.sk89q.craftbook.circuits.gates.world.items.ContainerDispenserST;
import com.sk89q.craftbook.circuits.gates.world.items.ContainerStacker;
import com.sk89q.craftbook.circuits.gates.world.items.ContainerStackerST;
import com.sk89q.craftbook.circuits.gates.world.items.Distributer;
import com.sk89q.craftbook.circuits.gates.world.items.DistributerST;
import com.sk89q.craftbook.circuits.gates.world.items.ItemDispenser;
import com.sk89q.craftbook.circuits.gates.world.items.ItemFan;
import com.sk89q.craftbook.circuits.gates.world.items.ItemFanST;
import com.sk89q.craftbook.circuits.gates.world.items.Sorter;
import com.sk89q.craftbook.circuits.gates.world.items.SorterST;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ArrowBarrage;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ArrowShooter;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.FireBarrage;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.FireShooter;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.FlameThrower;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.Jukebox;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.LightningSummon;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.Melody;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.MessageSender;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ParticleEffect;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ParticleEffectST;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.PotionInducer;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.PotionInducerST;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ProgrammableFireworkShow;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.RadioPlayer;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.RadioStation;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.SoundEffect;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.TimedExplosion;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.Tune;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.WirelessReceiver;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.WirelessReceiverST;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.WirelessTransmitter;
import com.sk89q.craftbook.circuits.gates.world.miscellaneous.XPSpawner;
import com.sk89q.craftbook.circuits.gates.world.sensors.BlockSensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.BlockSensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.ContentsSensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.ContentsSensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.DaySensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.DaySensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.EntitySensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.EntitySensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.ItemNotSensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.ItemNotSensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.ItemSensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.ItemSensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.LavaSensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.LavaSensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.LightSensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.LightSensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.PlayerSensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.PlayerSensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.PowerSensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.PowerSensorST;
import com.sk89q.craftbook.circuits.gates.world.sensors.WaterSensor;
import com.sk89q.craftbook.circuits.gates.world.sensors.WaterSensorST;
import com.sk89q.craftbook.circuits.gates.world.weather.RainSensor;
import com.sk89q.craftbook.circuits.gates.world.weather.RainSensorST;
import com.sk89q.craftbook.circuits.gates.world.weather.ServerTimeModulus;
import com.sk89q.craftbook.circuits.gates.world.weather.TStormSensor;
import com.sk89q.craftbook.circuits.gates.world.weather.TStormSensorST;
import com.sk89q.craftbook.circuits.gates.world.weather.TimeControl;
import com.sk89q.craftbook.circuits.gates.world.weather.TimeControlAdvanced;
import com.sk89q.craftbook.circuits.gates.world.weather.TimeFaker;
import com.sk89q.craftbook.circuits.gates.world.weather.TimeSet;
import com.sk89q.craftbook.circuits.gates.world.weather.TimeSetST;
import com.sk89q.craftbook.circuits.gates.world.weather.WeatherControl;
import com.sk89q.craftbook.circuits.gates.world.weather.WeatherControlAdvanced;
import com.sk89q.craftbook.circuits.gates.world.weather.WeatherFaker;
import com.sk89q.craftbook.circuits.ic.IC;
import com.sk89q.craftbook.circuits.ic.ICFactory;
import com.sk89q.craftbook.circuits.ic.ICFamily;
import com.sk89q.craftbook.circuits.ic.ICManager;
import com.sk89q.craftbook.circuits.ic.ICMechanicFactory;
import com.sk89q.craftbook.circuits.ic.RegisteredICFactory;
import com.sk89q.craftbook.circuits.ic.RestrictedIC;
import com.sk89q.craftbook.circuits.ic.SelfTriggeredIC;
import com.sk89q.craftbook.circuits.ic.families.Family3I3O;
import com.sk89q.craftbook.circuits.ic.families.Family3ISO;
import com.sk89q.craftbook.circuits.ic.families.FamilyAISO;
import com.sk89q.craftbook.circuits.ic.families.FamilySI3O;
import com.sk89q.craftbook.circuits.ic.families.FamilySI5O;
import com.sk89q.craftbook.circuits.ic.families.FamilySISO;
import com.sk89q.craftbook.circuits.ic.families.FamilyVIVO;
import com.sk89q.craftbook.circuits.plc.PlcFactory;
import com.sk89q.craftbook.circuits.plc.lang.Perlstone;
import com.sk89q.craftbook.util.config.YAMLICConfiguration;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
/**
* Author: Turtle9598
*/
public class CircuitCore implements LocalComponent {
private static CircuitCore instance;
private CraftBookPlugin plugin = CraftBookPlugin.inst();
private MechanicManager manager;
private ICManager icManager;
private YAMLICConfiguration icConfiguration;
private ICMechanicFactory ICFactory;
private Pipes.Factory pipeFactory;
private File romFolder;
private File midiFolder;
private File fireworkFolder;
public static final ICFamily FAMILY_SISO = new FamilySISO();
public static final ICFamily FAMILY_3ISO = new Family3ISO();
public static final ICFamily FAMILY_SI3O = new FamilySI3O();
public static final ICFamily FAMILY_AISO = new FamilyAISO();
public static final ICFamily FAMILY_3I3O = new Family3I3O();
public static final ICFamily FAMILY_VIVO = new FamilyVIVO();
public static final ICFamily FAMILY_SI5O = new FamilySI5O();
public static boolean isEnabled() {
return instance != null;
}
public CircuitCore() {
instance = this;
}
public static CircuitCore inst() {
return instance;
}
@Override
public void enable() {
plugin.registerCommands(CircuitCommands.class);
plugin.createDefaultConfiguration(new File(plugin.getDataFolder(), "ic-config.yml"), "ic-config.yml", false);
icConfiguration = new YAMLICConfiguration(new YAMLProcessor(new File(plugin.getDataFolder(), "ic-config.yml"), true, YAMLFormat.EXTENDED), plugin.getLogger());
manager = new MechanicManager();
plugin.registerManager(manager, true, true, true, false);
midiFolder = new File(plugin.getDataFolder(), "midi/");
new File(getMidiFolder(), "playlists").mkdirs();
romFolder = new File(plugin.getDataFolder(), "rom/");
fireworkFolder = new File(plugin.getDataFolder(), "fireworks/");
getFireworkFolder();
registerMechanics();
try {
icConfiguration.load();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override
public void disable() {
unregisterAllMechanics();
ICManager.emptyCache();
icConfiguration.unload();
}
public File getFireworkFolder() {
if (!fireworkFolder.exists()) fireworkFolder.mkdir();
return fireworkFolder;
}
public File getRomFolder() {
if (!romFolder.exists()) romFolder.mkdir();
return romFolder;
}
public File getMidiFolder() {
if (!midiFolder.exists()) midiFolder.mkdir();
return midiFolder;
}
public ICMechanicFactory getICFactory() {
return ICFactory;
}
public Pipes.Factory getPipeFactory() {
return pipeFactory;
}
private void registerMechanics() {
BukkitConfiguration config = CraftBookPlugin.inst().getConfiguration();
if (config.ICEnabled) {
registerICs();
registerMechanic(ICFactory = new ICMechanicFactory(getIcManager()));
}
// Let's register mechanics!
if (config.netherrackEnabled) registerMechanic(new Netherrack.Factory());
if (config.pumpkinsEnabled) registerMechanic(new JackOLantern.Factory());
if (config.glowstoneEnabled) registerMechanic(new GlowStone.Factory());
if (config.pipesEnabled) registerMechanic(pipeFactory = new Pipes.Factory());
}
private void registerICs() {
Server server = plugin.getServer();
// Let's register ICs!
icManager = new ICManager();
ICFamily familySISO = FAMILY_SISO;
ICFamily family3ISO = FAMILY_3ISO;
ICFamily familySI3O = FAMILY_SI3O;
ICFamily familyAISO = FAMILY_AISO;
ICFamily family3I3O = FAMILY_3I3O;
ICFamily familyVIVO = FAMILY_VIVO;
ICFamily familySI5O = FAMILY_SI5O;
// SISOs
registerIC("MC1000", "repeater", new Repeater.Factory(server), familySISO, familyAISO);
registerIC("MC1001", "inverter", new Inverter.Factory(server), familySISO, familyAISO);
registerIC("MC1017", "re t flip", new ToggleFlipFlop.Factory(server, true), familySISO, familyAISO);
registerIC("MC1018", "fe t flip", new ToggleFlipFlop.Factory(server, false), familySISO, familyAISO);
registerIC("MC1020", "random bit", new RandomBit.Factory(server), familySISO, familyAISO);
registerIC("MC1025", "server time", new ServerTimeModulus.Factory(server), familySISO, familyAISO);
registerIC("MC1110", "transmitter", new WirelessTransmitter.Factory(server), familySISO, familyAISO);
registerIC("MC1111", "receiver", new WirelessReceiver.Factory(server), familySISO, familyAISO);
registerIC("MC1112", "tele-out", new TeleportTransmitter.Factory(server), familySISO, familyAISO);
registerIC("MC1113", "tele-in", new TeleportReciever.Factory(server), familySISO, familyAISO);
registerIC("MC1200", "spawner", new CreatureSpawner.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1201", "dispenser", new ItemDispenser.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1202", "c dispense", new ContainerDispenser.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1203", "strike", new LightningSummon.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1204", "trap", new EntityTrap.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1205", "set above", new SetBlockAbove.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1206", "set below", new SetBlockBelow.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1207", "flex set", new FlexibleSetBlock.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1208", "mult set", new MultipleSetBlock.Factory(server), familySISO, familyAISO);
registerIC("MC1209", "collector", new ContainerCollector.Factory(server), familySISO, familyAISO);
registerIC("MC1210", "emitter", new ParticleEffect.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1211", "set bridge", new SetBridge.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1212", "set door", new SetDoor.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1213", "sound", new SoundEffect.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1215", "set a chest", new SetBlockAboveChest.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1216", "set b chest", new SetBlockBelowChest.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1217", "pot induce", new PotionInducer.Factory(server), familySISO, familyAISO);
registerIC("MC1218", "block launch", new BlockLauncher.Factory(server), familySISO, familyAISO);
registerIC("MC1219", "auto craft", new AutomaticCrafter.Factory(server), familySISO, familyAISO);
registerIC("MC1220", "a b break", new BlockBreaker.Factory(server, false), familySISO, familyAISO);
registerIC("MC1221", "b b break", new BlockBreaker.Factory(server, true), familySISO, familyAISO);
registerIC("MC1222", "liquid flood", new LiquidFlood.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1223", "terraform", new BonemealTerraformer.Factory(server), familySISO, familyAISO);
registerIC("MC1224", "time bomb", new TimedExplosion.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1225", "pump", new Pump.Factory(server), familySISO, familyAISO);
registerIC("MC1226", "spigot", new Spigot.Factory(server), familySISO, familyAISO);
registerIC("MC1227", "avd spawner", new AdvancedEntitySpawner.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1228", "ent cannon", new EntityCannon.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1229", "sorter", new Sorter.Factory(server), familySISO, familyAISO);
registerIC("MC1230", "sense day", new DaySensor.Factory(server), familySISO, familyAISO);
registerIC("MC1231", "t control", new TimeControl.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1232", "time set", new TimeSet.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1233", "item fan", new ItemFan.Factory(server), familySISO, familyAISO);
registerIC("MC1234", "planter", new Planter.Factory(server), familySISO, familyAISO);
registerIC("MC1235", "cultivator", new Cultivator.Factory(server), familySISO, familyAISO);
registerIC("MC1236", "fake weather", new WeatherFaker.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1237", "fake time", new TimeFaker.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1238", "irrigate", new Irrigator.Factory(server), familySISO, familyAISO);
registerIC("MC1239", "harvester", new CombineHarvester.Factory(server), familySISO, familyAISO);
registerIC("MC1240", "shoot arrow", new ArrowShooter.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1241", "shoot arrows", new ArrowBarrage.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1242", "stocker", new ChestStocker.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1243", "distributer", new Distributer.Factory(server), familySISO, familyAISO);
registerIC("MC1244", "animal harvest", new AnimalHarvester.Factory(server), familySISO, familyAISO);
registerIC("MC1245", "cont stacker", new ContainerStacker.Factory(server), familySISO, familyAISO);
registerIC("MC1246", "xp spawner", new XPSpawner.Factory(server), familySISO, familyAISO); //Restricted
//TODO Dyed Armour Spawner (MC1247) (Sign Title: DYE ARMOUR)
registerIC("MC1250", "shoot fire", new FireShooter.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1251", "shoot fires", new FireBarrage.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1252", "flame thower", new FlameThrower.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1253", "firework show", new ProgrammableFireworkShow.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1260", "sense water", new WaterSensor.Factory(server), familySISO, familyAISO);
registerIC("MC1261", "sense lava", new LavaSensor.Factory(server), familySISO, familyAISO);
registerIC("MC1262", "sense light", new LightSensor.Factory(server), familySISO, familyAISO);
registerIC("MC1263", "sense block", new BlockSensor.Factory(server), familySISO, familyAISO);
registerIC("MC1264", "sense item", new ItemSensor.Factory(server), familySISO, familyAISO);
registerIC("MC1265", "inv sense item", new ItemNotSensor.Factory(server), familySISO, familyAISO);
registerIC("MC1266", "sense power", new PowerSensor.Factory(server), familySISO, familyAISO);
//FIXME registerIC("MC1267", "sense move", new MovementSensor.Factory(server), familySISO, familyAISO);
registerIC("MC1268", "sense contents", new ContentsSensor.Factory(server), familySISO, familyAISO);
registerIC("MC1270", "melody", new Melody.Factory(server), familySISO, familyAISO);
registerIC("MC1271", "sense entity", new EntitySensor.Factory(server), familySISO, familyAISO);
registerIC("MC1272", "sense player", new PlayerSensor.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC1273", "jukebox", new Jukebox.Factory(server), familySISO, familyAISO);
registerIC("MC1275", "tune", new Tune.Factory(server), familySISO, familyAISO);
registerIC("MC1276", "radio station", new RadioStation.Factory(server), familySISO, familyAISO);
registerIC("MC1277", "radio player", new RadioPlayer.Factory(server), familySISO, familyAISO);
registerIC("MC1420", "divide clock", new ClockDivider.Factory(server), familySISO, familyAISO);
registerIC("MC1421", "clock", new Clock.Factory(server), familySISO, familyAISO);
registerIC("MC1510", "send message", new MessageSender.Factory(server), familySISO, familyAISO);
registerIC("MC2100", "delayer", new Delayer.Factory(server), familySISO, familyAISO);
registerIC("MC2101", "inv delayer", new NotDelayer.Factory(server), familySISO, familyAISO);
registerIC("MC2110", "fe delayer", new LowDelayer.Factory(server), familySISO, familyAISO);
registerIC("MC2111", "inv fe delayer", new NotLowDelayer.Factory(server), familySISO, familyAISO);
registerIC("MC2500", "pulser", new Pulser.Factory(server), familySISO, familyAISO);
registerIC("MC2501", "inv pulser", new NotPulser.Factory(server), familySISO, familyAISO);
registerIC("MC2510", "fe pulser", new LowPulser.Factory(server), familySISO, familyAISO);
registerIC("MC2511", "inv fe pulser", new LowNotPulser.Factory(server), familySISO, familyAISO);
// SI3Os
registerIC("MC2020", "random 3", new Random3Bit.Factory(server), familySI3O);
registerIC("MC2999", "marquee", new Marquee.Factory(server), familySI3O);
// 3ISOs
registerIC("MC3002", "and", new AndGate.Factory(server), family3ISO);
registerIC("MC3003", "nand", new NandGate.Factory(server), family3ISO);
registerIC("MC3020", "xor", new XorGate.Factory(server), family3ISO);
registerIC("MC3021", "xnor", new XnorGate.Factory(server), family3ISO);
registerIC("MC3030", "nor flip", new RsNorFlipFlop.Factory(server), family3ISO);
registerIC("MC3031", "inv nand latch", new InvertedRsNandLatch.Factory(server), family3ISO);
registerIC("MC3032", "jk flip", new JkFlipFlop.Factory(server), family3ISO);
registerIC("MC3033", "nand latch", new RsNandLatch.Factory(server), family3ISO);
registerIC("MC3034", "edge df flip", new EdgeTriggerDFlipFlop.Factory(server), family3ISO);
registerIC("MC3036", "level df flip", new LevelTriggeredDFlipFlop.Factory(server), family3ISO);
registerIC("MC3040", "multiplexer", new Multiplexer.Factory(server), family3ISO);
registerIC("MC3050", "combo", new CombinationLock.Factory(server), family3ISO);
registerIC("MC3101", "down counter", new DownCounter.Factory(server), family3ISO);
registerIC("MC3102", "counter", new Counter.Factory(server), family3ISO);
registerIC("MC3231", "t control adva", new TimeControlAdvanced.Factory(server), family3ISO); // Restricted
registerIC("MC3300", "ROM set", new MemorySetter.Factory(server), family3ISO); // Restricted
registerIC("MC3301", "ROM get", new MemoryAccess.Factory(server), familySI3O); // Restricted
// 3I3Os
registerIC("MC4000", "full adder", new FullAdder.Factory(server), family3I3O);
registerIC("MC4010", "half adder", new HalfAdder.Factory(server), family3I3O);
registerIC("MC4040", "demultiplexer", new DeMultiplexer.Factory(server), family3I3O);
registerIC("MC4100", "full subtr", new FullSubtractor.Factory(server), family3I3O);
registerIC("MC4110", "half subtr", new HalfSubtractor.Factory(server), family3I3O);
registerIC("MC4200", "dispatcher", new Dispatcher.Factory(server), family3I3O);
// SI5O's
registerIC("MC6020", "random 5", new Random5Bit.Factory(server), familySI5O);
// PLCs
registerIC("MC5000", "perlstone", PlcFactory.fromLang(server, new Perlstone(), false), familyVIVO);
registerIC("MC5001", "perlstone 3i3o", PlcFactory.fromLang(server, new Perlstone(), false), family3I3O);
// Self triggered
registerIC("MC0020", "random 1 st", new RandomBitST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0111", "receiver st", new WirelessReceiverST.Factory(server), familySISO, familyAISO);
registerIC("MC0113", "tele-in st", new TeleportRecieverST.Factory(server), familySISO, familyAISO);
registerIC("MC0202", "c dispense st", new ContainerDispenserST.Factory(server), familySISO, familyAISO);
registerIC("MC0204", "trap st", new EntityTrapST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0205", "set above st", new SetBlockAboveST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0206", "set below st", new SetBlockBelowST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0209", "collector st", new ContainerCollectorST.Factory(server), familySISO, familyAISO);
registerIC("MC0210", "emitter st", new ParticleEffectST.Factory(server), familySISO, familyAISO);
registerIC("MC0215", "set a chest st", new SetBlockAboveChestST.Factory(server), familySISO, familyAISO);
registerIC("MC0216", "set b chest st", new SetBlockBelowChestST.Factory(server), familySISO, familyAISO);
registerIC("MC0217", "pot induce st", new PotionInducerST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0219", "auto craft st", new AutomaticCrafterST.Factory(server), familySISO, familyAISO);
registerIC("MC0220", "a bl break st", new BlockBreakerST.Factory(server, false), familySISO, familyAISO);
registerIC("MC0221", "b bl break st", new BlockBreakerST.Factory(server, true), familySISO, familyAISO);
registerIC("MC0222", "liq flood st", new LiquidFloodST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0223", "terraform st", new BonemealTerraformerST.Factory(server), familySISO, familyAISO);
registerIC("MC0225", "pump st", new PumpST.Factory(server), familySISO, familyAISO);
registerIC("MC0228", "ent cannon st", new EntityCannonST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0229", "sorter st", new SorterST.Factory(server), familySISO, familyAISO);
registerIC("MC0230", "sense day st", new DaySensorST.Factory(server), familySISO, familyAISO);
registerIC("MC0232", "time set st", new TimeSetST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0233", "item fan st", new ItemFanST.Factory(server), familySISO, familyAISO);
registerIC("MC0234", "planter st", new PlanterST.Factory(server), familySISO, familyAISO);
registerIC("MC0235", "cultivator st", new CultivatorST.Factory(server), familySISO, familyAISO);
registerIC("MC0238", "irrigate st", new IrrigatorST.Factory(server), familySISO, familyAISO);
registerIC("MC0239", "harvester st", new CombineHarvesterST.Factory(server), familySISO, familyAISO);
registerIC("MC0242", "stocker st", new ChestStockerST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0243", "distributer st", new DistributerST.Factory(server), familySISO, familyAISO);
registerIC("MC0244", "animal harvest st", new AnimalHarvesterST.Factory(server), familySISO, familyAISO);
registerIC("MC0245", "cont stacker st", new ContainerStackerST.Factory(server), familySISO, familyAISO);
registerIC("MC0260", "sense water st", new WaterSensorST.Factory(server), familySISO, familyAISO);
registerIC("MC0261", "sense lava st", new LavaSensorST.Factory(server), familySISO, familyAISO);
registerIC("MC0262", "sense light st", new LightSensorST.Factory(server), familySISO, familyAISO);
registerIC("MC0263", "sense block st", new BlockSensorST.Factory(server), familySISO, familyAISO);
registerIC("MC0264", "sense item st", new ItemSensorST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0265", "sense n item s", new ItemNotSensorST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0266", "sense power st", new PowerSensorST.Factory(server), familySISO, familyAISO); // Restricted
//FIXME registerIC("MC0267", "sense move st", new MovementSensorST.Factory(server), familySISO, familyAISO);
registerIC("MC0268", "sense contents st", new ContentsSensorST.Factory(server), familySISO, familyAISO);
registerIC("MC0270", "sense power st", new PowerSensorST.Factory(server), familySISO, familyAISO);
registerIC("MC0271", "sense entit st", new EntitySensorST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0272", "sense playe st", new PlayerSensorST.Factory(server), familySISO, familyAISO); // Restricted
registerIC("MC0420", "clock st", new ClockST.Factory(server), familySISO, familyAISO);
registerIC("MC0421", "monostable", new Monostable.Factory(server), familySISO, familyAISO);
registerIC("MC0500", "range output", new RangedOutput.Factory(server), familySISO, familyAISO);
// Xtra ICs
// SISOs
registerIC("MCX230", "rain sense", new RainSensor.Factory(server), familySISO, familyAISO);
registerIC("MCX231", "storm sense", new TStormSensor.Factory(server), familySISO, familyAISO);
registerIC("MCX233", "weather set", new WeatherControl.Factory(server), familySISO, familyAISO);
// 3ISOs
registerIC("MCT233", "weather set ad", new WeatherControlAdvanced.Factory(server), family3ISO);
// Self triggered
registerIC("MCZ230", "rain sense st", new RainSensorST.Factory(server), familySISO, familyAISO);
registerIC("MCZ231", "storm sense st", new TStormSensorST.Factory(server), familySISO, familyAISO);
}
/**
* Register a mechanic if possible
*
* @param name
* @param factory
* @param families
*/
public boolean registerIC(String name, String longName, ICFactory factory, ICFamily... families) {
if (CraftBookPlugin.inst().getConfiguration().disabledICs.contains(name)) return false;
return getIcManager().register(name, longName, factory, families);
}
/**
* Register a mechanic if possible
*
* @param factory
*/
public void registerMechanic(MechanicFactory<? extends Mechanic> factory) {
manager.register(factory);
}
/**
* Register a array of mechanics if possible
*
* @param factories
*/
protected void registerMechanic(MechanicFactory<? extends Mechanic>[] factories) {
for (MechanicFactory<? extends Mechanic> aFactory : factories) {
registerMechanic(aFactory);
}
}
/**
* Unregister a mechanic if possible TODO Ensure no remnants are left behind
*
* @param factory
*
* @return true if the mechanic was successfully unregistered.
*/
protected boolean unregisterMechanic(MechanicFactory<? extends Mechanic> factory) {
return manager.unregister(factory);
}
protected boolean unregisterAllMechanics() {
Iterator<MechanicFactory<? extends Mechanic>> iterator = manager.factories.iterator();
while (iterator.hasNext()) {
iterator.next();
manager.unregister(iterator);
}
return true;
}
public List<RegisteredICFactory> getICList() {
if(getIcManager() == null)
return new ArrayList<RegisteredICFactory>();
List<RegisteredICFactory> ics = new ArrayList<RegisteredICFactory>();
for (Map.Entry<String, RegisteredICFactory> e : getIcManager().registered.entrySet()) {
ics.add(e.getValue());
}
return ics;
}
public String getSearchID(Player p, String search) {
ArrayList<String> icNameList = new ArrayList<String>();
icNameList.addAll(getIcManager().registered.keySet());
Collections.sort(icNameList);
for (String ic : icNameList) {
try {
RegisteredICFactory ric = getIcManager().registered.get(ic);
IC tic = ric.getFactory().create(null);
if (search != null && !tic.getTitle().toLowerCase().contains(search.toLowerCase())
&& !ric.getId().toLowerCase().contains(search.toLowerCase())) continue;
return ic;
} catch (Exception ignored) {
}
}
return "";
}
/**
* Used for the /ic list command.
*
* @param p
*
* @return
*/
public String[] generateICText(Player p, String search, char[] parameters) {
ArrayList<String> icNameList = new ArrayList<String>();
icNameList.addAll(getIcManager().registered.keySet());
Collections.sort(icNameList);
ArrayList<String> strings = new ArrayList<String>();
boolean col = true;
for (String ic : icNameList) {
try {
thisIC:
{
RegisteredICFactory ric = getIcManager().registered.get(ic);
IC tic = ric.getFactory().create(null);
if (search != null && !tic.getTitle().toLowerCase().contains(search.toLowerCase())
&& !ric.getId().toLowerCase().contains(search.toLowerCase())) continue;
if (parameters != null) {
for (char c : parameters) {
if (c == 'r' && !(ric.getFactory() instanceof RestrictedIC)) break thisIC;
else if (c == 's' && ric.getFactory() instanceof RestrictedIC) break thisIC;
else if (c == 'b' && !ric.getFactory().getClass().getPackage().getName().endsWith("blocks"))
break thisIC;
else if (c == 'i' && !ric.getFactory().getClass().getPackage().getName().endsWith("items"))
break thisIC;
else if (c == 'e' && !ric.getFactory().getClass().getPackage().getName().endsWith("entity"))
break thisIC;
else if (c == 'w' && !ric.getFactory().getClass().getPackage().getName().endsWith
("weather"))
break thisIC;
else if (c == 'l' && !ric.getFactory().getClass().getPackage().getName().endsWith("logic"))
break thisIC;
else if (c == 'm' && !ric.getFactory().getClass().getPackage().getName().endsWith
("miscellaneous"))
break thisIC;
else if (c == 'c' && !ric.getFactory().getClass().getPackage().getName().endsWith
("sensors"))
break thisIC;
}
}
col = !col;
ChatColor colour = col ? ChatColor.YELLOW : ChatColor.GOLD;
if (!ICMechanicFactory.checkPermissionsBoolean(CraftBookPlugin.inst().wrapPlayer(p), ric.getFactory(), ic.toLowerCase())) {
colour = col ? ChatColor.RED : ChatColor.DARK_RED;
}
strings.add(colour + tic.getTitle() + " (" + ric.getId() + ")"
+ ": " + (tic instanceof SelfTriggeredIC ? "ST " : "T ")
+ (ric.getFactory() instanceof RestrictedIC ? ChatColor.DARK_RED + "R " : ""));
}
} catch (Throwable e) {
plugin.getLogger().warning("An error occurred generating the docs for IC: " + ic + ".");
plugin.getLogger().warning("Please report this error on: http://youtrack.sk89q.com/.");
}
}
return strings.toArray(new String[strings.size()]);
}
public ICManager getIcManager () {
return icManager;
}
}
| wizjany/craftbook | src/main/java/com/sk89q/craftbook/bukkit/CircuitCore.java | Java | gpl-3.0 | 41,280 |
/* Copyright: stbi-1.33 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
when you control the images you're loading
no warranty implied; use at your own risk
*/
#include "graphics/image/stb_image.h"
#include "platform/Platform.h"
#ifndef STBI_NO_HDR
#include <math.h> // ldexp
#include <string.h> // strcmp, strtok
#endif
#ifndef STBI_NO_STDIO
#include <stdio.h>
#endif
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
#include <stdarg.h>
namespace stbi {
#ifndef _MSC_VER
#ifdef __cplusplus
#define stbi_inline inline
#else
#define stbi_inline
#endif
#else
#define stbi_inline __forceinline
#endif
// implementation:
typedef unsigned char uint8;
typedef u16 uint16;
typedef s16 int16;
typedef u32 uint32;
typedef s32 int32;
typedef unsigned int uint;
#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
#define STBI_NO_WRITE
#endif
#define STBI_NOTUSED(v) (void)sizeof(v)
#ifdef _MSC_VER
#define STBI_HAS_LROTL
#endif
#ifdef STBI_HAS_LROTL
#define stbi_lrot(x,y) _lrotl(x,y)
#else
#define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))
#endif
#ifdef STBI_NO_CALLBACK
typedef const uint8 * bufptr;
#else
typedef uint8 * bufptr;
#endif
///////////////////////////////////////////////
//
// stbi struct and start_xxx functions
// stbi structure is our basic context used by all images, so it
// contains all the IO context, plus some basic image information
typedef struct
{
uint32 img_x, img_y;
int img_n, img_out_n;
#ifndef STBI_NO_CALLBACK
stbi_io_callbacks io;
void *io_user_data;
int read_from_callbacks;
int buflen;
uint8 buffer_start[128];
#endif // !STBI_NO_CALLBACK
bufptr img_buffer, img_buffer_end;
bufptr img_buffer_original;
} stbi;
#ifndef STBI_NO_CALLBACK
static void refill_buffer(stbi *s);
#endif // !STBI_NO_CALLBACK
// initialize a memory-decode context
static void start_mem(stbi *s, uint8 const *buffer, int len)
{
#ifndef STBI_NO_CALLBACK
s->io.read = NULL;
s->read_from_callbacks = 0;
#endif // !STBI_NO_CALLBACK
s->img_buffer = s->img_buffer_original = (bufptr) buffer;
s->img_buffer_end = (bufptr) buffer+len;
}
#ifndef STBI_NO_CALLBACK
// initialize a callback-based context
static void start_callbacks(stbi *s, stbi_io_callbacks *c, void *user)
{
s->io = *c;
s->io_user_data = user;
s->buflen = sizeof(s->buffer_start);
s->read_from_callbacks = 1;
s->img_buffer_original = s->buffer_start;
refill_buffer(s);
}
#ifndef STBI_NO_STDIO
static int stdio_read(void *user, char *data, int size)
{
return (int) fread(data,1,size,(FILE*) user);
}
static void stdio_skip(void *user, unsigned n)
{
fseek((FILE*) user, n, SEEK_CUR);
}
static int stdio_eof(void *user)
{
return feof((FILE*) user);
}
static stbi_io_callbacks stbi_stdio_callbacks =
{
stdio_read,
stdio_skip,
stdio_eof,
};
static void start_file(stbi *s, FILE *f)
{
start_callbacks(s, &stbi_stdio_callbacks, (void *) f);
}
//static void stop_file(stbi *s) { }
#endif // !STBI_NO_STDIO
#endif // !STBI_NO_CALLBACK
static void stbi_rewind(stbi *s)
{
// conceptually rewind SHOULD rewind to the beginning of the stream,
// but we just rewind to the beginning of the initial buffer, because
// we only use it after doing 'test', which only ever looks at at most 92 bytes
s->img_buffer = s->img_buffer_original;
}
static int stbi_jpeg_test(stbi *s);
static stbi_uc *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp);
static int stbi_png_test(stbi *s);
static stbi_uc *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_png_info(stbi *s, int *x, int *y, int *comp);
static int stbi_bmp_test(stbi *s);
static stbi_uc *stbi_bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_tga_test(stbi *s);
static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_tga_info(stbi *s, int *x, int *y, int *comp);
static int stbi_psd_test(stbi *s);
static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_HDR
static int stbi_hdr_test(stbi *s);
static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp);
#endif // !STBI_NO_HDR
static int stbi_pic_test(stbi *s);
static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_GIF
static int stbi_gif_test(stbi *s);
static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_gif_info(stbi *s, int *x, int *y, int *comp);
#endif // !STBI_NO_GIF
// this is not threadsafe
static const char *failure_reason;
const char *stbi_failure_reason(void)
{
return failure_reason;
}
static int stbi_error(const char *str)
{
failure_reason = str;
return 0;
}
// stbi_error - error
// stbi_error_pf - error returning pointer to float
// stbi_error_puc - error returning pointer to unsigned char
#ifdef STBI_NO_FAILURE_STRINGS
#define stbi_error(x,y) 0
#elif defined(STBI_FAILURE_USERMSG)
#define stbi_error(x,y) stbi_error(y)
#else
#define stbi_error(x,y) stbi_error(x)
#endif
#define stbi_error_pf(x,y) ((float *) (stbi_error(x,y)?NULL:NULL))
#define stbi_error_puc(x,y) ((unsigned char *) (stbi_error(x,y)?NULL:NULL))
void stbi_image_free(void *retval_from_stbi_load)
{
free(retval_from_stbi_load);
}
#ifndef STBI_NO_HDR
static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp);
#endif
static unsigned char *stbi_load_main(stbi *s, int *x, int *y, int *comp, int req_comp)
{
if (stbi_jpeg_test(s)) return stbi_jpeg_load(s,x,y,comp,req_comp);
if (stbi_png_test(s)) return stbi_png_load(s,x,y,comp,req_comp);
if (stbi_bmp_test(s)) return stbi_bmp_load(s,x,y,comp,req_comp);
#ifndef STBI_NO_GIF
if (stbi_gif_test(s)) return stbi_gif_load(s,x,y,comp,req_comp);
#endif // !STBI_NO_GIF
if (stbi_psd_test(s)) return stbi_psd_load(s,x,y,comp,req_comp);
if (stbi_pic_test(s)) return stbi_pic_load(s,x,y,comp,req_comp);
#ifndef STBI_NO_HDR
if (stbi_hdr_test(s)) {
float *hdr = stbi_hdr_load(s, x,y,comp,req_comp);
return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
}
#endif
// test tga last because it's a crappy test!
if (stbi_tga_test(s))
return stbi_tga_load(s,x,y,comp,req_comp);
return stbi_error_puc("unknown image type", "Image not of any known type, or corrupt");
}
#ifndef STBI_NO_STDIO
unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
{
FILE *f = fopen(filename, "rb");
unsigned char *result;
if (!f) return stbi_error_puc("can't fopen", "Unable to open file");
result = stbi_load_from_file(f,x,y,comp,req_comp);
fclose(f);
return result;
}
unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_file(&s,f);
return stbi_load_main(&s,x,y,comp,req_comp);
}
#endif //!STBI_NO_STDIO
unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_mem(&s,buffer,len);
return stbi_load_main(&s,x,y,comp,req_comp);
}
#ifndef STBI_NO_CALLBACK
unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
return stbi_load_main(&s,x,y,comp,req_comp);
}
#endif // !STBI_NO_CALLBACK
#ifndef STBI_NO_HDR
float *stbi_loadf_main(stbi *s, int *x, int *y, int *comp, int req_comp)
{
unsigned char *data;
#ifndef STBI_NO_HDR
if (stbi_hdr_test(s))
return stbi_hdr_load(s,x,y,comp,req_comp);
#endif
data = stbi_load_main(s, x, y, comp, req_comp);
if (data)
return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
return stbi_error_pf("unknown image type", "Image not of any known type, or corrupt");
}
float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_mem(&s,buffer,len);
return stbi_loadf_main(&s,x,y,comp,req_comp);
}
#ifndef STBI_NO_CALLBACK
float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
return stbi_loadf_main(&s,x,y,comp,req_comp);
}
#ifndef STBI_NO_STDIO
float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
{
FILE *f = fopen(filename, "rb");
float *result;
if (!f) return stbi_error_pf("can't fopen", "Unable to open file");
result = stbi_loadf_from_file(f,x,y,comp,req_comp);
fclose(f);
return result;
}
float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_file(&s,f);
return stbi_loadf_main(&s,x,y,comp,req_comp);
}
#endif // !STBI_NO_STDIO
#endif // !STBI_NO_CALLBACK
#endif // !STBI_NO_HDR
// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
// defined, for API simplicity; if STBI_NO_HDR is defined, it always
// reports false!
int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
{
#ifndef STBI_NO_HDR
stbi s;
start_mem(&s,buffer,len);
return stbi_hdr_test(&s);
#else
STBI_NOTUSED(buffer);
STBI_NOTUSED(len);
return 0;
#endif
}
#ifndef STBI_NO_CALLBACK
#ifndef STBI_NO_STDIO
extern int stbi_is_hdr (char const *filename)
{
FILE *f = fopen(filename, "rb");
int result=0;
if (f) {
result = stbi_is_hdr_from_file(f);
fclose(f);
}
return result;
}
extern int stbi_is_hdr_from_file(FILE *f)
{
#ifndef STBI_NO_HDR
stbi s;
start_file(&s,f);
return stbi_hdr_test(&s);
#else
return 0;
#endif
}
#endif // !STBI_NO_STDIO
extern int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
{
#ifndef STBI_NO_HDR
stbi s;
start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
return stbi_hdr_test(&s);
#else
return 0;
#endif
}
#endif // !STBI_NO_CALLBACK
#ifndef STBI_NO_HDR
static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
static float l2h_gamma=2.2f, l2h_scale=1.0f;
void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
#endif
//////////////////////////////////////////////////////////////////////////////
//
// Common code used by all image loaders
//
enum
{
SCAN_load=0,
SCAN_type,
SCAN_header
};
#ifndef STBI_NO_CALLBACK
static void refill_buffer(stbi *s)
{
int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
if (n == 0) {
// at end of file, treat same as if from memory
s->read_from_callbacks = 0;
s->img_buffer = s->img_buffer_end-1;
*s->img_buffer = 0;
} else {
s->img_buffer = s->buffer_start;
s->img_buffer_end = s->buffer_start + n;
}
}
#endif // !STBI_NO_CALLBACK
stbi_inline static int get8(stbi *s)
{
if (s->img_buffer < s->img_buffer_end)
return *s->img_buffer++;
#ifndef STBI_NO_CALLBACK
if (s->read_from_callbacks) {
refill_buffer(s);
return *s->img_buffer++;
}
#endif // !STBI_NO_CALLBACK
return 0;
}
stbi_inline static int at_eof(stbi *s)
{
#ifndef STBI_NO_CALLBACK
if (s->io.read) {
if (!(s->io.eof)(s->io_user_data)) return 0;
// if feof() is true, check if buffer = end
// special case: we've only got the special 0 character at the end
if (s->read_from_callbacks == 0) return 1;
}
#endif // !STBI_NO_CALLBACK
return s->img_buffer >= s->img_buffer_end;
}
stbi_inline static uint8 get8u(stbi *s)
{
return (uint8) get8(s);
}
static void skip(stbi *s, int n)
{
#ifndef STBI_NO_CALLBACK
if (s->io.read) {
int blen = s->img_buffer_end - s->img_buffer;
if (blen < n) {
s->img_buffer = s->img_buffer_end;
(s->io.skip)(s->io_user_data, n - blen);
return;
}
}
#endif // !STBI_NO_CALLBACK
s->img_buffer += n;
}
static int getn(stbi *s, stbi_uc *buffer, int n)
{
#ifndef STBI_NO_CALLBACK
if (s->io.read) {
int blen = s->img_buffer_end - s->img_buffer;
if (blen < n) {
int res, count;
memcpy(buffer, s->img_buffer, blen);
count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
res = (count == (n-blen));
s->img_buffer = s->img_buffer_end;
return res;
}
}
#endif // !STBI_NO_CALLBACK
if (s->img_buffer+n <= s->img_buffer_end) {
memcpy(buffer, s->img_buffer, n);
s->img_buffer += n;
return 1;
} else {
return 0;
}
}
static int get16(stbi *s)
{
int z = get8(s);
return (z << 8) + get8(s);
}
static uint32 get32(stbi *s)
{
uint32 z = get16(s);
return (z << 16) + get16(s);
}
static int get16le(stbi *s)
{
int z = get8(s);
return z + (get8(s) << 8);
}
static uint32 get32le(stbi *s)
{
uint32 z = get16le(s);
return z + (get16le(s) << 16);
}
//////////////////////////////////////////////////////////////////////////////
//
// generic converter from built-in img_n to req_comp
// individual types do this automatically as much as possible (e.g. jpeg
// does all cases internally since it needs to colorspace convert anyway,
// and it never has alpha, so very few cases ). png can automatically
// interleave an alpha=255 channel, but falls back to this for other cases
//
// assume data buffer is malloced, so malloc a new one and free that one
// only failure mode is malloc failing
static uint8 compute_y(int r, int g, int b)
{
return (uint8) (((r*77) + (g*150) + (29*b)) >> 8);
}
static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)
{
int i,j;
unsigned char *good;
if (req_comp == img_n) return data;
assert(req_comp >= 1 && req_comp <= 4);
good = (unsigned char *) malloc(req_comp * x * y);
if (good == NULL) {
free(data);
return stbi_error_puc("outofmem", "Out of memory");
}
for (j=0; j < (int) y; ++j) {
unsigned char *src = data + j * x * img_n ;
unsigned char *dest = good + j * x * req_comp;
#define STBI_COMBO(a,b) ((a)*8+(b))
#define STBI_CASE(a,b) case STBI_COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
// convert source image with img_n components to one with req_comp components;
// avoid switch per pixel, so use switch per scanline and massive macros
switch (STBI_COMBO(img_n, req_comp)) {
STBI_CASE(1,2) dest[0]=src[0], dest[1]=255; break;
STBI_CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
STBI_CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
STBI_CASE(2,1) dest[0]=src[0]; break;
STBI_CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
STBI_CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
STBI_CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
STBI_CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
STBI_CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
STBI_CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
STBI_CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
STBI_CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
default: assert(0);
}
#undef STBI_CASE
#undef STBI_COMBO
}
free(data);
return good;
}
#ifndef STBI_NO_HDR
static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
{
int i,k,n;
float *output = (float *) malloc(x * y * comp * sizeof(*output));
if (output == NULL) { free(data); return stbi_error_pf("outofmem", "Out of memory"); }
// compute number of non-alpha components
if (comp & 1) n = comp; else n = comp-1;
for (i=0; i < x*y; ++i) {
for (k=0; k < n; ++k) {
output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;
}
if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
}
free(data);
return output;
}
#define stbi_float2int(x) ((int) (x))
static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp)
{
int i,k,n;
stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
if (output == NULL) { free(data); return stbi_error_puc("outofmem", "Out of memory"); }
// compute number of non-alpha components
if (comp & 1) n = comp; else n = comp-1;
for (i=0; i < x*y; ++i) {
for (k=0; k < n; ++k) {
float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
if (z < 0) z = 0;
if (z > 255) z = 255;
output[i*comp + k] = (uint8) stbi_float2int(z);
}
if (k < comp) {
float z = data[i*comp+k] * 255 + 0.5f;
if (z < 0) z = 0;
if (z > 255) z = 255;
output[i*comp + k] = (uint8) stbi_float2int(z);
}
}
free(data);
return output;
}
#undef stbi_float2int
#endif
//////////////////////////////////////////////////////////////////////////////
//
// "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
//
// simple implementation
// - channel subsampling of at most 2 in each dimension
// - doesn't support delayed output of y-dimension
// - simple interface (only one output format: 8-bit interleaved RGB)
// - doesn't try to recover corrupt jpegs
// - doesn't allow partial loading, loading multiple at once
// - still fast on x86 (copying globals into locals doesn't help x86)
// - allocates lots of intermediate memory (full size of all components)
// - non-interleaved case requires this anyway
// - allows good upsampling (see next)
// high-quality
// - upsampled channels are bilinearly interpolated, even across blocks
// - quality integer IDCT derived from IJG's 'slow'
// performance
// - fast huffman; reasonable integer IDCT
// - uses a lot of intermediate memory, could cache poorly
// - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
// stb_jpeg: 1.34 seconds (MSVC6, default release build)
// stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)
// IJL11.dll: 1.08 seconds (compiled by intel)
// IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)
// IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)
// huffman decoding acceleration
#define STBI_FAST_BITS 9 // larger handles more cases; smaller stomps less cache
typedef struct
{
uint8 fast[1 << STBI_FAST_BITS];
// weirdly, repacking this into AoS is a 10% speed loss, instead of a win
uint16 code[256];
uint8 values[256];
uint8 size[257];
unsigned int maxcode[18];
int delta[17]; // old 'firstsymbol' - old 'firstcode'
} huffman;
typedef struct
{
#ifdef STBI_SIMD
unsigned short dequant2[4][64];
#endif
stbi *s;
huffman huff_dc[4];
huffman huff_ac[4];
uint8 dequant[4][64];
// sizes for components, interleaved MCUs
int img_h_max, img_v_max;
int img_mcu_x, img_mcu_y;
int img_mcu_w, img_mcu_h;
// definition of jpeg image component
struct
{
int id;
int h,v;
int tq;
int hd,ha;
int dc_pred;
int x,y,w2,h2;
uint8 *data;
void *raw_data;
uint8 *linebuf;
} img_comp[4];
uint32 code_buffer; // jpeg entropy-coded buffer
int code_bits; // number of valid bits
unsigned char marker; // marker seen while filling entropy buffer
int nomore; // flag if we saw a marker so must stop
int scan_n, order[4];
int restart_interval, todo;
} jpeg;
static int build_huffman(huffman *h, int *count)
{
int i,j,k=0,code;
// build size list for each symbol (from JPEG spec)
for (i=0; i < 16; ++i)
for (j=0; j < count[i]; ++j)
h->size[k++] = (uint8) (i+1);
h->size[k] = 0;
// compute actual symbols (from jpeg spec)
code = 0;
k = 0;
for(j=1; j <= 16; ++j) {
// compute delta to add to code to compute symbol id
h->delta[j] = k - code;
if (h->size[k] == j) {
while (h->size[k] == j)
h->code[k++] = (uint16) (code++);
if (code-1 >= (1 << j)) return stbi_error("bad code lengths","Corrupt JPEG");
}
// compute largest code + 1 for this size, preshifted as needed later
h->maxcode[j] = code << (16-j);
code <<= 1;
}
h->maxcode[j] = 0xffffffff;
// build non-spec acceleration table; 255 is flag for not-accelerated
memset(h->fast, 255, 1 << STBI_FAST_BITS);
for (i=0; i < k; ++i) {
int s = h->size[i];
if (s <= STBI_FAST_BITS) {
int c = h->code[i] << (STBI_FAST_BITS-s);
int m = 1 << (STBI_FAST_BITS-s);
for (j=0; j < m; ++j) {
h->fast[c+j] = (uint8) i;
}
}
}
return 1;
}
static void grow_buffer_unsafe(jpeg *j)
{
do {
int b = j->nomore ? 0 : get8(j->s);
if (b == 0xff) {
int c = get8(j->s);
if (c != 0) {
j->marker = (unsigned char) c;
j->nomore = 1;
return;
}
}
j->code_buffer |= b << (24 - j->code_bits);
j->code_bits += 8;
} while (j->code_bits <= 24);
}
// (1 << n) - 1
static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
// decode a jpeg huffman value from the bitstream
stbi_inline static int decode(jpeg *j, huffman *h)
{
unsigned int temp;
int c,k;
if (j->code_bits < 16) grow_buffer_unsafe(j);
// look at the top STBI_FAST_BITS and determine what symbol ID it is,
// if the code is <= STBI_FAST_BITS
c = (j->code_buffer >> (32 - STBI_FAST_BITS)) & ((1 << STBI_FAST_BITS)-1);
k = h->fast[c];
if (k < 255) {
int s = h->size[k];
if (s > j->code_bits)
return -1;
j->code_buffer <<= s;
j->code_bits -= s;
return h->values[k];
}
// naive test is to shift the code_buffer down so k bits are
// valid, then test against maxcode. To speed this up, we've
// preshifted maxcode left so that it has (16-k) 0s at the
// end; in other words, regardless of the number of bits, it
// wants to be compared against something shifted to have 16;
// that way we don't need to shift inside the loop.
temp = j->code_buffer >> 16;
for (k=STBI_FAST_BITS+1 ; ; ++k)
if (temp < h->maxcode[k])
break;
if (k == 17) {
// error! code not found
j->code_bits -= 16;
return -1;
}
if (k > j->code_bits)
return -1;
// convert the huffman code to the symbol id
c = ((j->code_buffer >> (32 - k)) & bmask[k]) + h->delta[k];
assert((((j->code_buffer) >> (32 - h->size[c])) & bmask[h->size[c]]) == h->code[c]);
// convert the id to a symbol
j->code_bits -= k;
j->code_buffer <<= k;
return h->values[c];
}
// combined JPEG 'receive' and JPEG 'extend', since baseline
// always extends everything it receives.
stbi_inline static int extend_receive(jpeg *j, int n)
{
unsigned int m = 1 << (n-1);
unsigned int k;
if (j->code_bits < n) grow_buffer_unsafe(j);
#if 1
k = stbi_lrot(j->code_buffer, n);
j->code_buffer = k & ~bmask[n];
k &= bmask[n];
j->code_bits -= n;
#else
k = (j->code_buffer >> (32 - n)) & bmask[n];
j->code_bits -= n;
j->code_buffer <<= n;
#endif
// the following test is probably a random branch that won't
// predict well. I tried to table accelerate it but failed.
// maybe it's compiling as a conditional move?
if (k < m)
return (-1 << n) + k + 1;
else
return k;
}
// given a value that's at position X in the zigzag stream,
// where does it appear in the 8x8 matrix coded as row-major?
static uint8 dezigzag[64+15] =
{
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63,
// let corrupt input sample past end
63, 63, 63, 63, 63, 63, 63, 63,
63, 63, 63, 63, 63, 63, 63
};
// decode one 64-entry block--
static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)
{
int diff,dc,k;
int t = decode(j, hdc);
if (t < 0) return stbi_error("bad huffman code","Corrupt JPEG");
// 0 all the ac values now so we can do it 32-bits at a time
memset(data,0,64*sizeof(data[0]));
diff = t ? extend_receive(j, t) : 0;
dc = j->img_comp[b].dc_pred + diff;
j->img_comp[b].dc_pred = dc;
data[0] = (short) dc;
// decode AC components, see JPEG spec
k = 1;
do {
int r,s;
int rs = decode(j, hac);
if (rs < 0) return stbi_error("bad huffman code","Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0) {
if (rs != 0xf0) break; // end block
k += 16;
} else {
k += r;
// decode into unzigzag'd location
data[dezigzag[k++]] = (short) extend_receive(j,s);
}
} while (k < 64);
return 1;
}
// take a -128..127 value and clamp it and convert to 0..255
stbi_inline static uint8 clamp(int x)
{
// trick to use a single test to catch both cases
if ((unsigned int) x > 255) {
if (x < 0) return 0;
if (x > 255) return 255;
}
return (uint8) x;
}
#define stbi_f2f(x) (int) (((x) * 4096 + 0.5))
#define stbi_fsh(x) ((x) << 12)
// derived from jidctint -- DCT_ISLOW
#define STBI_IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
p2 = s2; \
p3 = s6; \
p1 = (p2+p3) * stbi_f2f(0.5411961f); \
t2 = p1 + p3*stbi_f2f(-1.847759065f); \
t3 = p1 + p2*stbi_f2f( 0.765366865f); \
p2 = s0; \
p3 = s4; \
t0 = stbi_fsh(p2+p3); \
t1 = stbi_fsh(p2-p3); \
x0 = t0+t3; \
x3 = t0-t3; \
x1 = t1+t2; \
x2 = t1-t2; \
t0 = s7; \
t1 = s5; \
t2 = s3; \
t3 = s1; \
p3 = t0+t2; \
p4 = t1+t3; \
p1 = t0+t3; \
p2 = t1+t2; \
p5 = (p3+p4)*stbi_f2f( 1.175875602f); \
t0 = t0*stbi_f2f( 0.298631336f); \
t1 = t1*stbi_f2f( 2.053119869f); \
t2 = t2*stbi_f2f( 3.072711026f); \
t3 = t3*stbi_f2f( 1.501321110f); \
p1 = p5 + p1*stbi_f2f(-0.899976223f); \
p2 = p5 + p2*stbi_f2f(-2.562915447f); \
p3 = p3*stbi_f2f(-1.961570560f); \
p4 = p4*stbi_f2f(-0.390180644f); \
t3 += p1+p4; \
t2 += p2+p3; \
t1 += p2+p4; \
t0 += p1+p3;
#ifdef STBI_SIMD
typedef unsigned short stbi_dequantize_t;
#else
typedef uint8 stbi_dequantize_t;
#endif
// .344 seconds on 3*anemones.jpg
static void idct_block(uint8 *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)
{
int i,val[64],*v=val;
stbi_dequantize_t *dq = dequantize;
uint8 *o;
short *d = data;
// columns
for (i=0; i < 8; ++i,++d,++dq, ++v) {
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
&& d[40]==0 && d[48]==0 && d[56]==0) {
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * dq[0] << 2;
v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
} else {
STBI_IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
// constants scaled things up by 1<<12; let's bring them back
// down, but keep 2 extra bits of precision
x0 += 512; x1 += 512; x2 += 512; x3 += 512;
v[ 0] = (x0+t3) >> 10;
v[56] = (x0-t3) >> 10;
v[ 8] = (x1+t2) >> 10;
v[48] = (x1-t2) >> 10;
v[16] = (x2+t1) >> 10;
v[40] = (x2-t1) >> 10;
v[24] = (x3+t0) >> 10;
v[32] = (x3-t0) >> 10;
}
}
for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
// no fast case since the first 1D IDCT spread components out
STBI_IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
// constants scaled things up by 1<<12, plus we had 1<<2 from first
// loop, plus horizontal and vertical each scale by sqrt(8) so together
// we've got an extra 1<<3, so 1<<17 total we need to remove.
// so we want to round that, which means adding 0.5 * 1<<17,
// aka 65536. Also, we'll end up with -128 to 127 that we want
// to encode as 0..255 by adding 128, so we'll add that before the shift
x0 += 65536 + (128<<17);
x1 += 65536 + (128<<17);
x2 += 65536 + (128<<17);
x3 += 65536 + (128<<17);
// tried computing the shifts into temps, or'ing the temps to see
// if any were out of range, but that was slower
o[0] = clamp((x0+t3) >> 17);
o[7] = clamp((x0-t3) >> 17);
o[1] = clamp((x1+t2) >> 17);
o[6] = clamp((x1-t2) >> 17);
o[2] = clamp((x2+t1) >> 17);
o[5] = clamp((x2-t1) >> 17);
o[3] = clamp((x3+t0) >> 17);
o[4] = clamp((x3-t0) >> 17);
}
}
#ifdef STBI_SIMD
static stbi_idct_8x8 stbi_idct_installed = idct_block;
void stbi_install_idct(stbi_idct_8x8 func)
{
stbi_idct_installed = func;
}
#endif
#define STBI_MARKER_none 0xff
// if there's a pending marker from the entropy stream, return that
// otherwise, fetch from the stream and get a marker. if there's no
// marker, return 0xff, which is never a valid marker value
static uint8 get_marker(jpeg *j)
{
uint8 x;
if (j->marker != STBI_MARKER_none) { x = j->marker; j->marker = STBI_MARKER_none; return x; }
x = get8u(j->s);
if (x != 0xff) return STBI_MARKER_none;
while (x == 0xff)
x = get8u(j->s);
return x;
}
// in each scan, we'll have scan_n components, and the order
// of the components is specified by order[]
#define STBI_RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
// after a restart interval, reset the entropy decoder and
// the dc prediction
static void reset(jpeg *j)
{
j->code_bits = 0;
j->code_buffer = 0;
j->nomore = 0;
j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
j->marker = STBI_MARKER_none;
j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
// no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
// since we don't even allow 1<<30 pixels
}
static int parse_entropy_coded_data(jpeg *z)
{
reset(z);
if (z->scan_n == 1) {
int i,j;
#ifdef STBI_SIMD
__declspec(align(16))
#endif
short data[64];
int n = z->order[0];
// non-interleaved data, we just need to process one block at a time,
// in trivial scanline order
// number of blocks to do just depends on how many actual "pixels" this
// component has, independent of interleaved MCU blocking and such
int w = (z->img_comp[n].x+7) >> 3;
int h = (z->img_comp[n].y+7) >> 3;
for (j=0; j < h; ++j) {
for (i=0; i < w; ++i) {
if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
#ifdef STBI_SIMD
stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
#else
idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
#endif
// every data block is an MCU, so countdown the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) grow_buffer_unsafe(z);
// if it's NOT a restart, then just bail, so we get corrupt data
// rather than no data
if (!STBI_RESTART(z->marker)) return 1;
reset(z);
}
}
}
} else { // interleaved!
int i,j,k,x,y;
short data[64];
for (j=0; j < z->img_mcu_y; ++j) {
for (i=0; i < z->img_mcu_x; ++i) {
// scan an interleaved mcu... process scan_n components in order
for (k=0; k < z->scan_n; ++k) {
int n = z->order[k];
// scan out an mcu's worth of this component; that's just determined
// by the basic H and V specified for the component
for (y=0; y < z->img_comp[n].v; ++y) {
for (x=0; x < z->img_comp[n].h; ++x) {
int x2 = (i*z->img_comp[n].h + x)*8;
int y2 = (j*z->img_comp[n].v + y)*8;
if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
#ifdef STBI_SIMD
stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
#else
idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
#endif
}
}
}
// after all interleaved components, that's an interleaved MCU,
// so now count down the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) grow_buffer_unsafe(z);
// if it's NOT a restart, then just bail, so we get corrupt data
// rather than no data
if (!STBI_RESTART(z->marker)) return 1;
reset(z);
}
}
}
}
return 1;
}
static int process_marker(jpeg *z, int m)
{
int L;
switch (m) {
case STBI_MARKER_none: // no marker found
return stbi_error("expected marker","Corrupt JPEG");
case 0xC2: // SOF - progressive
return stbi_error("progressive jpeg","JPEG format not supported (progressive)");
case 0xDD: // DRI - specify restart interval
if (get16(z->s) != 4) return stbi_error("bad DRI len","Corrupt JPEG");
z->restart_interval = get16(z->s);
return 1;
case 0xDB: // DQT - define quantization table
L = get16(z->s)-2;
while (L > 0) {
int q = get8(z->s);
int p = q >> 4;
int t = q & 15,i;
if (p != 0) return stbi_error("bad DQT type","Corrupt JPEG");
if (t > 3) return stbi_error("bad DQT table","Corrupt JPEG");
for (i=0; i < 64; ++i)
z->dequant[t][dezigzag[i]] = get8u(z->s);
#ifdef STBI_SIMD
for (i=0; i < 64; ++i)
z->dequant2[t][i] = z->dequant[t][i];
#endif
L -= 65;
}
return L==0;
case 0xC4: // DHT - define huffman table
L = get16(z->s)-2;
while (L > 0) {
uint8 *v;
int sizes[16],i,m=0;
int q = get8(z->s);
int tc = q >> 4;
int th = q & 15;
if (tc > 1 || th > 3) return stbi_error("bad DHT header","Corrupt JPEG");
for (i=0; i < 16; ++i) {
sizes[i] = get8(z->s);
m += sizes[i];
}
L -= 17;
if (tc == 0) {
if (!build_huffman(z->huff_dc+th, sizes)) return 0;
v = z->huff_dc[th].values;
} else {
if (!build_huffman(z->huff_ac+th, sizes)) return 0;
v = z->huff_ac[th].values;
}
for (i=0; i < m; ++i)
v[i] = get8u(z->s);
L -= m;
}
return L==0;
}
// check for comment block or APP blocks
if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
skip(z->s, get16(z->s)-2);
return 1;
}
return 0;
}
// after we see SOS
static int process_scan_header(jpeg *z)
{
int i;
int Ls = get16(z->s);
z->scan_n = get8(z->s);
if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi_error("bad SOS component count","Corrupt JPEG");
if (Ls != 6+2*z->scan_n) return stbi_error("bad SOS len","Corrupt JPEG");
for (i=0; i < z->scan_n; ++i) {
int id = get8(z->s), which;
int q = get8(z->s);
for (which = 0; which < z->s->img_n; ++which)
if (z->img_comp[which].id == id)
break;
if (which == z->s->img_n) return 0;
z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi_error("bad DC huff","Corrupt JPEG");
z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi_error("bad AC huff","Corrupt JPEG");
z->order[i] = which;
}
if (get8(z->s) != 0) return stbi_error("bad SOS","Corrupt JPEG");
get8(z->s); // should be 63, but might be 0
if (get8(z->s) != 0) return stbi_error("bad SOS","Corrupt JPEG");
return 1;
}
static int process_frame_header(jpeg *z, int scan)
{
stbi *s = z->s;
int Lf,p,i,q, h_max=1,v_max=1,c;
Lf = get16(s); if (Lf < 11) return stbi_error("bad SOF len","Corrupt JPEG"); // JPEG
p = get8(s); if (p != 8) return stbi_error("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
s->img_y = get16(s); if (s->img_y == 0) return stbi_error("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
s->img_x = get16(s); if (s->img_x == 0) return stbi_error("0 width","Corrupt JPEG"); // JPEG requires
c = get8(s);
if (c != 3 && c != 1) return stbi_error("bad component count","Corrupt JPEG"); // JFIF requires
s->img_n = c;
for (i=0; i < c; ++i) {
z->img_comp[i].data = NULL;
z->img_comp[i].linebuf = NULL;
}
if (Lf != 8+3*s->img_n) return stbi_error("bad SOF len","Corrupt JPEG");
for (i=0; i < s->img_n; ++i) {
z->img_comp[i].id = get8(s);
if (z->img_comp[i].id != i+1) // JFIF requires
if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files!
return stbi_error("bad component ID","Corrupt JPEG");
q = get8(s);
z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi_error("bad H","Corrupt JPEG");
z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi_error("bad V","Corrupt JPEG");
z->img_comp[i].tq = get8(s); if (z->img_comp[i].tq > 3) return stbi_error("bad TQ","Corrupt JPEG");
}
if (scan != SCAN_load) return 1;
if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi_error("too large", "Image too large to decode");
for (i=0; i < s->img_n; ++i) {
if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
}
// compute interleaved mcu info
z->img_h_max = h_max;
z->img_v_max = v_max;
z->img_mcu_w = h_max * 8;
z->img_mcu_h = v_max * 8;
z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
for (i=0; i < s->img_n; ++i) {
// number of effective pixels (e.g. for non-interleaved MCU)
z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
// to simplify generation, we'll allocate enough memory to decode
// the bogus oversized data from using interleaved MCUs and their
// big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
// discard the extra data until colorspace conversion
z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
if (z->img_comp[i].raw_data == NULL) {
for(--i; i >= 0; --i) {
free(z->img_comp[i].raw_data);
z->img_comp[i].data = NULL;
}
return stbi_error("outofmem", "Out of memory");
}
// align blocks for installable-idct using mmx/sse
z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
z->img_comp[i].linebuf = NULL;
}
return 1;
}
// use comparisons since in some cases we handle more than one case (e.g. SOF)
#define STBI_DNL(x) ((x) == 0xdc)
#define STBI_SOI(x) ((x) == 0xd8)
#define STBI_EOI(x) ((x) == 0xd9)
#define STBI_SOF(x) ((x) == 0xc0 || (x) == 0xc1)
#define STBI_SOS(x) ((x) == 0xda)
static int decode_jpeg_header(jpeg *z, int scan)
{
int m;
z->marker = STBI_MARKER_none; // initialize cached marker to empty
m = get_marker(z);
if (!STBI_SOI(m)) return stbi_error("no SOI","Corrupt JPEG");
if (scan == SCAN_type) return 1;
m = get_marker(z);
while (!STBI_SOF(m)) {
if (!process_marker(z,m)) return 0;
m = get_marker(z);
while (m == STBI_MARKER_none) {
// some files have extra padding after their blocks, so ok, we'll scan
if (at_eof(z->s)) return stbi_error("no SOF", "Corrupt JPEG");
m = get_marker(z);
}
}
if (!process_frame_header(z, scan)) return 0;
return 1;
}
static int decode_jpeg_image(jpeg *j)
{
int m;
j->restart_interval = 0;
if (!decode_jpeg_header(j, SCAN_load)) return 0;
m = get_marker(j);
while (!STBI_EOI(m)) {
if (STBI_SOS(m)) {
if (!process_scan_header(j)) return 0;
if (!parse_entropy_coded_data(j)) return 0;
if (j->marker == STBI_MARKER_none ) {
// handle 0s at the end of image data from IP Kamera 9060
while (!at_eof(j->s)) {
int x = get8(j->s);
if (x == 255) {
j->marker = get8u(j->s);
break;
} else if (x != 0) {
return 0;
}
}
// if we reach eof without hitting a marker, get_marker() below will fail and we'll eventually return 0
}
} else {
if (!process_marker(j, m)) return 0;
}
m = get_marker(j);
}
return 1;
}
// static jfif-centered resampling (across block boundaries)
typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1,
int w, int hs);
#define stbi_div4(x) ((uint8) ((x) >> 2))
static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
STBI_NOTUSED(out);
STBI_NOTUSED(in_far);
STBI_NOTUSED(w);
STBI_NOTUSED(hs);
return in_near;
}
static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
// need to generate two samples vertically for every one in input
int i;
STBI_NOTUSED(hs);
for (i=0; i < w; ++i)
out[i] = stbi_div4(3*in_near[i] + in_far[i] + 2);
return out;
}
static uint8* resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
// need to generate two samples horizontally for every one in input
int i;
uint8 *input = in_near;
if (w == 1) {
// if only one sample, can't do any interpolation
out[0] = out[1] = input[0];
return out;
}
out[0] = input[0];
out[1] = stbi_div4(input[0]*3 + input[1] + 2);
for (i=1; i < w-1; ++i) {
int n = 3*input[i]+2;
out[i*2+0] = stbi_div4(n+input[i-1]);
out[i*2+1] = stbi_div4(n+input[i+1]);
}
out[i*2+0] = stbi_div4(input[w-2]*3 + input[w-1] + 2);
out[i*2+1] = input[w-1];
STBI_NOTUSED(in_far);
STBI_NOTUSED(hs);
return out;
}
#define stbi_div16(x) ((uint8) ((x) >> 4))
static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
// need to generate 2x2 samples for every one in input
int i,t0,t1;
if (w == 1) {
out[0] = out[1] = stbi_div4(3*in_near[0] + in_far[0] + 2);
return out;
}
t1 = 3*in_near[0] + in_far[0];
out[0] = stbi_div4(t1+2);
for (i=1; i < w; ++i) {
t0 = t1;
t1 = 3*in_near[i]+in_far[i];
out[i*2-1] = stbi_div16(3*t0 + t1 + 8);
out[i*2 ] = stbi_div16(3*t1 + t0 + 8);
}
out[w*2-1] = stbi_div4(t1+2);
STBI_NOTUSED(hs);
return out;
}
static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
{
STBI_NOTUSED(in_far);
// resample with nearest-neighbor
int i,j;
for (i=0; i < w; ++i)
for (j=0; j < hs; ++j)
out[i*hs+j] = in_near[i];
return out;
}
#define stbi_float2fixed(x) ((int) ((x) * 65536 + 0.5))
// 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro)
// VC6 without processor=Pro is generating multiple LEAs per multiply!
static void YCbCr_to_RGB_row(uint8 *out, const uint8 *y, const uint8 *pcb, const uint8 *pcr, int count, int step)
{
int i;
for (i=0; i < count; ++i) {
int y_fixed = (y[i] << 16) + 32768; // rounding
int r,g,b;
int cr = pcr[i] - 128;
int cb = pcb[i] - 128;
r = y_fixed + cr*stbi_float2fixed(1.40200f);
g = y_fixed - cr*stbi_float2fixed(0.71414f) - cb*stbi_float2fixed(0.34414f);
b = y_fixed + cb*stbi_float2fixed(1.77200f);
r >>= 16;
g >>= 16;
b >>= 16;
if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
out[0] = (uint8)r;
out[1] = (uint8)g;
out[2] = (uint8)b;
out[3] = 255;
out += step;
}
}
#ifdef STBI_SIMD
static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;
void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)
{
stbi_YCbCr_installed = func;
}
#endif
// clean up the temporary component buffers
static void cleanup_jpeg(jpeg *j)
{
int i;
for (i=0; i < j->s->img_n; ++i) {
if (j->img_comp[i].data) {
free(j->img_comp[i].raw_data);
j->img_comp[i].data = NULL;
}
free(j->img_comp[i].linebuf), j->img_comp[i].linebuf = NULL;
}
}
typedef struct
{
resample_row_func resample;
uint8 *line0,*line1;
int hs,vs; // expansion factor in each axis
int w_lores; // horizontal pixels pre-expansion
int ystep; // how far through vertical expansion we are
int ypos; // which pre-expansion row we're on
} stbi_resample;
static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
{
int n, decode_n;
// validate req_comp
if (req_comp < 0 || req_comp > 4) return stbi_error_puc("bad req_comp", "Internal error");
z->s->img_n = 0;
// load a jpeg image from whichever source
if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }
// determine actual number of components to generate
n = req_comp ? req_comp : z->s->img_n;
if (z->s->img_n == 3 && n < 3)
decode_n = 1;
else
decode_n = z->s->img_n;
// resample and color-convert
{
int k;
uint i,j;
uint8 *output;
uint8 *coutput[4];
stbi_resample res_comp[4];
for (k=0; k < decode_n; ++k) {
stbi_resample *r = &res_comp[k];
// allocate line buffer big enough for upsampling off the edges
// with upsample factor of 4
z->img_comp[k].linebuf = (uint8 *) malloc(z->s->img_x + 3);
if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return stbi_error_puc("outofmem", "Out of memory"); }
r->hs = z->img_h_max / z->img_comp[k].h;
r->vs = z->img_v_max / z->img_comp[k].v;
r->ystep = r->vs >> 1;
r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
r->ypos = 0;
r->line0 = r->line1 = z->img_comp[k].data;
if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2;
else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;
else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;
else r->resample = resample_row_generic;
}
// can't error after this so, this is safe
output = (uint8 *) malloc(n * z->s->img_x * z->s->img_y + 1);
if (!output) { cleanup_jpeg(z); return stbi_error_puc("outofmem", "Out of memory"); }
// now go ahead and resample
for (j=0; j < z->s->img_y; ++j) {
uint8 *out = output + n * z->s->img_x * j;
for (k=0; k < decode_n; ++k) {
stbi_resample *r = &res_comp[k];
int y_bot = r->ystep >= (r->vs >> 1);
coutput[k] = r->resample(z->img_comp[k].linebuf,
y_bot ? r->line1 : r->line0,
y_bot ? r->line0 : r->line1,
r->w_lores, r->hs);
if (++r->ystep >= r->vs) {
r->ystep = 0;
r->line0 = r->line1;
if (++r->ypos < z->img_comp[k].y)
r->line1 += z->img_comp[k].w2;
}
}
if (n >= 3) {
uint8 *y = coutput[0];
if (z->s->img_n == 3) {
#ifdef STBI_SIMD
stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n);
#else
YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n);
#endif
} else {
for (i=0; i < z->s->img_x; ++i) {
out[0] = out[1] = out[2] = y[i];
out[3] = 255; // not used if n==3
out += n;
}
}
} else {
uint8 *y = coutput[0];
if (n == 1)
for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
else
for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;
}
}
cleanup_jpeg(z);
*out_x = z->s->img_x;
*out_y = z->s->img_y;
if (comp) *comp = z->s->img_n; // report original components, not output
return output;
}
}
static unsigned char *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
jpeg j;
j.s = s;
return load_jpeg_image(&j, x,y,comp,req_comp);
}
static int stbi_jpeg_test(stbi *s)
{
int r;
jpeg j;
j.s = s;
r = decode_jpeg_header(&j, SCAN_type);
stbi_rewind(s);
return r;
}
static int stbi_jpeg_info_raw(jpeg *j, int *x, int *y, int *comp)
{
if (!decode_jpeg_header(j, SCAN_header)) {
stbi_rewind( j->s );
return 0;
}
if (x) *x = j->s->img_x;
if (y) *y = j->s->img_y;
if (comp) *comp = j->s->img_n;
return 1;
}
static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp)
{
jpeg j;
j.s = s;
return stbi_jpeg_info_raw(&j, x, y, comp);
}
// public domain zlib decode v0.2 Sean Barrett 2006-11-18
// simple implementation
// - all input must be provided in an upfront buffer
// - all output is written to a single output buffer (can malloc/realloc)
// performance
// - fast huffman
// fast-way is faster to check than jpeg huffman, but slow way is slower
#define STBI_ZFAST_BITS 9 // accelerate all cases in default tables
#define STBI_ZFAST_MASK ((1 << STBI_ZFAST_BITS) - 1)
// zlib-style huffman encoding
// (jpegs packs from left, zlib from right, so can't share code)
typedef struct
{
uint16 fast[1 << STBI_ZFAST_BITS];
uint16 firstcode[16];
int maxcode[17];
uint16 firstsymbol[16];
uint8 size[288];
uint16 value[288];
} zhuffman;
stbi_inline static int bitreverse16(int n)
{
n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
return n;
}
stbi_inline static int bit_reverse(int v, int bits)
{
assert(bits <= 16);
// to bit reverse n bits, reverse 16 and shift
// e.g. 11 bits, bit reverse and shift away 5
return bitreverse16(v) >> (16-bits);
}
static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)
{
int i,k=0;
int code, next_code[16], sizes[17];
// DEFLATE spec for generating codes
memset(sizes, 0, sizeof(sizes));
memset(z->fast, 255, sizeof(z->fast));
for (i=0; i < num; ++i)
++sizes[sizelist[i]];
sizes[0] = 0;
for (i=1; i < 16; ++i)
assert(sizes[i] <= (1 << i));
code = 0;
for (i=1; i < 16; ++i) {
next_code[i] = code;
z->firstcode[i] = (uint16) code;
z->firstsymbol[i] = (uint16) k;
code = (code + sizes[i]);
if (sizes[i])
if (code-1 >= (1 << i)) return stbi_error("bad codelengths","Corrupt JPEG");
z->maxcode[i] = code << (16-i); // preshift for inner loop
code <<= 1;
k += sizes[i];
}
z->maxcode[16] = 0x10000; // sentinel
for (i=0; i < num; ++i) {
int s = sizelist[i];
if (s) {
int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
z->size[c] = (uint8)s;
z->value[c] = (uint16)i;
if (s <= STBI_ZFAST_BITS) {
int k = bit_reverse(next_code[s],s);
while (k < (1 << STBI_ZFAST_BITS)) {
z->fast[k] = (uint16) c;
k += (1 << s);
}
}
++next_code[s];
}
}
return 1;
}
// zlib-from-memory implementation for PNG reading
// because PNG allows splitting the zlib stream arbitrarily,
// and it's annoying structurally to have PNG call ZLIB call PNG,
// we require PNG read all the IDATs and combine them into a single
// memory buffer
typedef struct
{
const uint8 *zbuffer, *zbuffer_end;
int num_bits;
uint32 code_buffer;
char *zout;
char *zout_start;
char *zout_end;
int z_expandable;
zhuffman z_length, z_distance;
} zbuf;
stbi_inline static int zget8(zbuf *z)
{
if (z->zbuffer >= z->zbuffer_end) return 0;
return *z->zbuffer++;
}
static void fill_bits(zbuf *z)
{
do {
assert(z->code_buffer < (1U << z->num_bits));
z->code_buffer |= zget8(z) << z->num_bits;
z->num_bits += 8;
} while (z->num_bits <= 24);
}
stbi_inline static unsigned int zreceive(zbuf *z, int n)
{
unsigned int k;
if (z->num_bits < n) fill_bits(z);
k = z->code_buffer & ((1 << n) - 1);
z->code_buffer >>= n;
z->num_bits -= n;
return k;
}
stbi_inline static int zhuffman_decode(zbuf *a, zhuffman *z)
{
int b,s,k;
if (a->num_bits < 16) fill_bits(a);
b = z->fast[a->code_buffer & STBI_ZFAST_MASK];
if (b < 0xffff) {
s = z->size[b];
a->code_buffer >>= s;
a->num_bits -= s;
return z->value[b];
}
// not resolved by fast table, so compute it the slow way
// use jpeg approach, which requires MSbits at top
k = bit_reverse(a->code_buffer, 16);
for (s=STBI_ZFAST_BITS+1; ; ++s)
if (k < z->maxcode[s])
break;
if (s == 16) return -1; // invalid code!
// code size is s, so:
b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
assert(z->size[b] == s);
a->code_buffer >>= s;
a->num_bits -= s;
return z->value[b];
}
static int expand(zbuf *z, int n) // need to make room for n bytes
{
char *q;
int cur, limit;
if (!z->z_expandable) return stbi_error("output buffer limit","Corrupt PNG");
cur = (int) (z->zout - z->zout_start);
limit = (int) (z->zout_end - z->zout_start);
while (cur + n > limit)
limit *= 2;
q = (char *) realloc(z->zout_start, limit);
if (q == NULL) return stbi_error("outofmem", "Out of memory");
z->zout_start = q;
z->zout = q + cur;
z->zout_end = q + limit;
return 1;
}
static int length_base[31] = {
3,4,5,6,7,8,9,10,11,13,
15,17,19,23,27,31,35,43,51,59,
67,83,99,115,131,163,195,227,258,0,0
};
static int length_extra[31] = {
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0
};
static int dist_base[32] = {
1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0
};
static int dist_extra[32] = {
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
static int parse_huffman_block(zbuf *a)
{
for(;;) {
int z = zhuffman_decode(a, &a->z_length);
if (z < 256) {
if (z < 0) return stbi_error("bad huffman code","Corrupt PNG"); // error in huffman codes
if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;
*a->zout++ = (char) z;
} else {
uint8 *p;
int len,dist;
if (z == 256) return 1;
z -= 257;
len = length_base[z];
if (length_extra[z]) len += zreceive(a, length_extra[z]);
z = zhuffman_decode(a, &a->z_distance);
if (z < 0) return stbi_error("bad huffman code","Corrupt PNG");
dist = dist_base[z];
if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);
if (a->zout - a->zout_start < dist) return stbi_error("bad dist","Corrupt PNG");
if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;
p = (uint8 *) (a->zout - dist);
while (len--)
*a->zout++ = *p++;
}
}
}
static int compute_huffman_codes(zbuf *a)
{
static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
zhuffman z_codelength;
uint8 lencodes[286+32+137];//padding for maximum single op
uint8 codelength_sizes[19];
int i,n;
int hlit = zreceive(a,5) + 257;
int hdist = zreceive(a,5) + 1;
int hclen = zreceive(a,4) + 4;
memset(codelength_sizes, 0, sizeof(codelength_sizes));
for (i=0; i < hclen; ++i) {
int s = zreceive(a,3);
codelength_sizes[length_dezigzag[i]] = (uint8) s;
}
if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
n = 0;
while (n < hlit + hdist) {
int c = zhuffman_decode(a, &z_codelength);
assert(c >= 0 && c < 19);
if (c < 16)
lencodes[n++] = (uint8) c;
else if (c == 16) {
c = zreceive(a,2)+3;
memset(lencodes+n, lencodes[n-1], c);
n += c;
} else if (c == 17) {
c = zreceive(a,3)+3;
memset(lencodes+n, 0, c);
n += c;
} else {
assert(c == 18);
c = zreceive(a,7)+11;
memset(lencodes+n, 0, c);
n += c;
}
}
if (n != hlit+hdist) return stbi_error("bad codelengths","Corrupt PNG");
if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
return 1;
}
static int parse_uncompressed_block(zbuf *a)
{
uint8 header[4];
int len,nlen,k;
if (a->num_bits & 7)
zreceive(a, a->num_bits & 7); // discard
// drain the bit-packed data into header
k = 0;
while (a->num_bits > 0) {
header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns?
a->code_buffer >>= 8;
a->num_bits -= 8;
}
assert(a->num_bits == 0);
// now fill header the normal way
while (k < 4)
header[k++] = (uint8) zget8(a);
len = header[1] * 256 + header[0];
nlen = header[3] * 256 + header[2];
if (nlen != (len ^ 0xffff)) return stbi_error("zlib corrupt","Corrupt PNG");
if (a->zbuffer + len > a->zbuffer_end) return stbi_error("read past buffer","Corrupt PNG");
if (a->zout + len > a->zout_end)
if (!expand(a, len)) return 0;
memcpy(a->zout, a->zbuffer, len);
a->zbuffer += len;
a->zout += len;
return 1;
}
static int parse_zlib_header(zbuf *a)
{
int cmf = zget8(a);
int cm = cmf & 15;
/* int cinfo = cmf >> 4; */
int flg = zget8(a);
if ((cmf*256+flg) % 31 != 0) return stbi_error("bad zlib header","Corrupt PNG"); // zlib spec
if (flg & 32) return stbi_error("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
if (cm != 8) return stbi_error("bad compression","Corrupt PNG"); // DEFLATE required for png
// window = 1 << (8 + cinfo)... but who cares, we fully buffer output
return 1;
}
// @TODO: should statically initialize these for optimal thread safety
static uint8 default_length[288], default_distance[32];
static void init_defaults(void)
{
int i; // use <= to match clearly with spec
for (i=0; i <= 143; ++i) default_length[i] = 8;
for ( ; i <= 255; ++i) default_length[i] = 9;
for ( ; i <= 279; ++i) default_length[i] = 7;
for ( ; i <= 287; ++i) default_length[i] = 8;
for (i=0; i <= 31; ++i) default_distance[i] = 5;
}
int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead
static int parse_zlib(zbuf *a, int parse_header)
{
int final, type;
if (parse_header)
if (!parse_zlib_header(a)) return 0;
a->num_bits = 0;
a->code_buffer = 0;
do {
final = zreceive(a,1);
type = zreceive(a,2);
if (type == 0) {
if (!parse_uncompressed_block(a)) return 0;
} else if (type == 3) {
return 0;
} else {
if (type == 1) {
// use fixed code lengths
if (!default_distance[31]) init_defaults();
if (!zbuild_huffman(&a->z_length , default_length , 288)) return 0;
if (!zbuild_huffman(&a->z_distance, default_distance, 32)) return 0;
} else {
if (!compute_huffman_codes(a)) return 0;
}
if (!parse_huffman_block(a)) return 0;
}
if (stbi_png_partial && a->zout - a->zout_start > 65536)
break;
} while (!final);
return 1;
}
static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)
{
a->zout_start = obuf;
a->zout = obuf;
a->zout_end = obuf + olen;
a->z_expandable = exp;
return parse_zlib(a, parse_header);
}
char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
{
zbuf a;
char *p = (char *) malloc(initial_size);
if (p == NULL) return NULL;
a.zbuffer = (const uint8 *) buffer;
a.zbuffer_end = (const uint8 *) buffer + len;
if (do_zlib(&a, p, initial_size, 1, 1)) {
if (outlen) *outlen = (int) (a.zout - a.zout_start);
return a.zout_start;
} else {
free(a.zout_start);
return NULL;
}
}
char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
{
return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
}
char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
{
zbuf a;
char *p = (char *) malloc(initial_size);
if (p == NULL) return NULL;
a.zbuffer = (const uint8 *) buffer;
a.zbuffer_end = (const uint8 *) buffer + len;
if (do_zlib(&a, p, initial_size, 1, parse_header)) {
if (outlen) *outlen = (int) (a.zout - a.zout_start);
return a.zout_start;
} else {
free(a.zout_start);
return NULL;
}
}
int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
{
zbuf a;
a.zbuffer = (const uint8 *) ibuffer;
a.zbuffer_end = (const uint8 *) ibuffer + ilen;
if (do_zlib(&a, obuffer, olen, 0, 1))
return (int) (a.zout - a.zout_start);
else
return -1;
}
char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
{
zbuf a;
char *p = (char *) malloc(16384);
if (p == NULL) return NULL;
a.zbuffer = (const uint8 *) buffer;
a.zbuffer_end = (const uint8 *) buffer+len;
if (do_zlib(&a, p, 16384, 1, 0)) {
if (outlen) *outlen = (int) (a.zout - a.zout_start);
return a.zout_start;
} else {
free(a.zout_start);
return NULL;
}
}
int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
{
zbuf a;
a.zbuffer = (const uint8 *) ibuffer;
a.zbuffer_end = (const uint8 *) ibuffer + ilen;
if (do_zlib(&a, obuffer, olen, 0, 0))
return (int) (a.zout - a.zout_start);
else
return -1;
}
// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
// simple implementation
// - only 8-bit samples
// - no CRC checking
// - allocates lots of intermediate memory
// - avoids problem of streaming data between subsystems
// - avoids explicit window management
// performance
// - uses stb_zlib, a PD zlib implementation with fast huffman decoding
typedef struct
{
uint32 length;
uint32 type;
} chunk;
#define STBI_PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
static chunk get_chunk_header(stbi *s)
{
chunk c;
c.length = get32(s);
c.type = get32(s);
return c;
}
static int check_png_header(stbi *s)
{
static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };
int i;
for (i=0; i < 8; ++i)
if (get8u(s) != png_sig[i]) return stbi_error("bad png sig","Not a PNG");
return 1;
}
typedef struct
{
stbi *s;
uint8 *idata, *expanded, *out;
} png;
enum {
F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,
F_avg_first, F_paeth_first
};
static uint8 first_row_filter[5] =
{
F_none, F_sub, F_none, F_avg_first, F_paeth_first
};
static int paeth(int a, int b, int c)
{
int p = a + b - c;
int pa = abs(p-a);
int pb = abs(p-b);
int pc = abs(p-c);
if (pa <= pb && pa <= pc) return a;
if (pb <= pc) return b;
return c;
}
// create the png data from post-deflated data
static int create_png_image_raw(png *a, uint8 *raw, uint32 raw_len, int out_n, uint32 x, uint32 y)
{
stbi *s = a->s;
uint32 i,j,stride = x*out_n;
int k;
int img_n = s->img_n; // copy it into a local for later
assert(out_n == s->img_n || out_n == s->img_n+1);
if (stbi_png_partial) y = 1;
a->out = (uint8 *) malloc(x * y * out_n);
if (!a->out) return stbi_error("outofmem", "Out of memory");
if (!stbi_png_partial) {
if (s->img_x == x && s->img_y == y) {
if (raw_len != (img_n * x + 1) * y) return stbi_error("not enough pixels","Corrupt PNG");
} else { // interlaced:
if (raw_len < (img_n * x + 1) * y) return stbi_error("not enough pixels","Corrupt PNG");
}
}
for (j=0; j < y; ++j) {
uint8 *cur = a->out + stride*j;
uint8 *prior = cur - stride;
int filter = *raw++;
if (filter > 4) return stbi_error("invalid filter","Corrupt PNG");
// if first row, use special filter that doesn't sample previous row
if (j == 0) filter = first_row_filter[filter];
// handle first pixel explicitly
for (k=0; k < img_n; ++k) {
switch (filter) {
case F_none : cur[k] = raw[k]; break;
case F_sub : cur[k] = raw[k]; break;
case F_up : cur[k] = raw[k] + prior[k]; break;
case F_avg : cur[k] = raw[k] + (prior[k]>>1); break;
case F_paeth : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;
case F_avg_first : cur[k] = raw[k]; break;
case F_paeth_first: cur[k] = raw[k]; break;
}
}
if (img_n != out_n) cur[img_n] = 255;
raw += img_n;
cur += out_n;
prior += out_n;
// this is a little gross, so that we don't switch per-pixel or per-component
if (img_n == out_n) {
#define STBI_CASE(f) \
case f: \
for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \
for (k=0; k < img_n; ++k)
switch (filter) {
STBI_CASE(F_none) cur[k] = raw[k]; break;
STBI_CASE(F_sub) cur[k] = raw[k] + cur[k-img_n]; break;
STBI_CASE(F_up) cur[k] = raw[k] + prior[k]; break;
STBI_CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;
STBI_CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;
STBI_CASE(F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break;
STBI_CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;
}
#undef STBI_CASE
} else {
assert(img_n+1 == out_n);
#define STBI_CASE(f) \
case f: \
for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \
for (k=0; k < img_n; ++k)
switch (filter) {
STBI_CASE(F_none) cur[k] = raw[k]; break;
STBI_CASE(F_sub) cur[k] = raw[k] + cur[k-out_n]; break;
STBI_CASE(F_up) cur[k] = raw[k] + prior[k]; break;
STBI_CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;
STBI_CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
STBI_CASE(F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break;
STBI_CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;
}
#undef STBI_CASE
}
}
return 1;
}
static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n, int interlaced)
{
uint8 *final;
int p;
int save;
if (!interlaced)
return create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y);
save = stbi_png_partial;
stbi_png_partial = 0;
// de-interlacing
final = (uint8 *) malloc(a->s->img_x * a->s->img_y * out_n);
for (p=0; p < 7; ++p) {
int xorig[] = { 0,4,0,2,0,1,0 };
int yorig[] = { 0,0,4,0,2,0,1 };
int xspc[] = { 8,8,4,4,2,2,1 };
int yspc[] = { 8,8,8,4,4,2,2 };
int i,j,x,y;
// pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
if (x && y) {
if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {
free(final);
return 0;
}
for (j=0; j < y; ++j)
for (i=0; i < x; ++i)
memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,
a->out + (j*x+i)*out_n, out_n);
free(a->out);
raw += (x*out_n+1)*y;
raw_len -= (x*out_n+1)*y;
}
}
a->out = final;
stbi_png_partial = save;
return 1;
}
static int compute_transparency(png *z, uint8 tc[3], int out_n)
{
stbi *s = z->s;
uint32 i, pixel_count = s->img_x * s->img_y;
uint8 *p = z->out;
// compute color-based transparency, assuming we've
// already got 255 as the alpha value in the output
assert(out_n == 2 || out_n == 4);
if (out_n == 2) {
for (i=0; i < pixel_count; ++i) {
p[1] = (p[0] == tc[0] ? 0 : 255);
p += 2;
}
} else {
for (i=0; i < pixel_count; ++i) {
if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
p[3] = 0;
p += 4;
}
}
return 1;
}
static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n)
{
uint32 i, pixel_count = a->s->img_x * a->s->img_y;
uint8 *p, *temp_out, *orig = a->out;
p = (uint8 *) malloc(pixel_count * pal_img_n);
if (p == NULL) return stbi_error("outofmem", "Out of memory");
// between here and free(out) below, exitting would leak
temp_out = p;
if (pal_img_n == 3) {
for (i=0; i < pixel_count; ++i) {
int n = orig[i]*4;
p[0] = palette[n ];
p[1] = palette[n+1];
p[2] = palette[n+2];
p += 3;
}
} else {
for (i=0; i < pixel_count; ++i) {
int n = orig[i]*4;
p[0] = palette[n ];
p[1] = palette[n+1];
p[2] = palette[n+2];
p[3] = palette[n+3];
p += 4;
}
}
free(a->out);
a->out = temp_out;
STBI_NOTUSED(len);
return 1;
}
static int stbi_unpremultiply_on_load = 0;
static int stbi_de_iphone_flag = 0;
void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
{
stbi_unpremultiply_on_load = flag_true_if_should_unpremultiply;
}
void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
{
stbi_de_iphone_flag = flag_true_if_should_convert;
}
static void stbi_de_iphone(png *z)
{
stbi *s = z->s;
uint32 i, pixel_count = s->img_x * s->img_y;
uint8 *p = z->out;
if (s->img_out_n == 3) { // convert bgr to rgb
for (i=0; i < pixel_count; ++i) {
uint8 t = p[0];
p[0] = p[2];
p[2] = t;
p += 3;
}
} else {
assert(s->img_out_n == 4);
if (stbi_unpremultiply_on_load) {
// convert bgr to rgb and unpremultiply
for (i=0; i < pixel_count; ++i) {
uint8 a = p[3];
uint8 t = p[0];
if (a) {
p[0] = p[2] * 255 / a;
p[1] = p[1] * 255 / a;
p[2] = t * 255 / a;
} else {
p[0] = p[2];
p[2] = t;
}
p += 4;
}
} else {
// convert bgr to rgb
for (i=0; i < pixel_count; ++i) {
uint8 t = p[0];
p[0] = p[2];
p[2] = t;
p += 4;
}
}
}
}
static int parse_png_file(png *z, int scan, int req_comp)
{
uint8 palette[1024], pal_img_n=0;
uint8 has_trans=0, tc[3];
uint32 ioff=0, idata_limit=0, i, pal_len=0;
int first=1,k,interlace=0, iphone=0;
stbi *s = z->s;
z->expanded = NULL;
z->idata = NULL;
z->out = NULL;
if (!check_png_header(s)) return 0;
if (scan == SCAN_type) return 1;
for (;;) {
chunk c = get_chunk_header(s);
switch (c.type) {
case STBI_PNG_TYPE('C','g','B','I'):
iphone = stbi_de_iphone_flag;
skip(s, c.length);
break;
case STBI_PNG_TYPE('I','H','D','R'): {
int depth,color,comp,filter;
if (!first) return stbi_error("multiple IHDR","Corrupt PNG");
first = 0;
if (c.length != 13) return stbi_error("bad IHDR len","Corrupt PNG");
s->img_x = get32(s); if (s->img_x > (1 << 24)) return stbi_error("too large","Very large image (corrupt?)");
s->img_y = get32(s); if (s->img_y > (1 << 24)) return stbi_error("too large","Very large image (corrupt?)");
depth = get8(s); if (depth != 8) return stbi_error("8bit only","PNG not supported: 8-bit only");
color = get8(s); if (color > 6) return stbi_error("bad ctype","Corrupt PNG");
if (color == 3) pal_img_n = 3; else if (color & 1) return stbi_error("bad ctype","Corrupt PNG");
comp = get8(s); if (comp) return stbi_error("bad comp method","Corrupt PNG");
filter= get8(s); if (filter) return stbi_error("bad filter method","Corrupt PNG");
interlace = get8(s); if (interlace>1) return stbi_error("bad interlace method","Corrupt PNG");
if (!s->img_x || !s->img_y) return stbi_error("0-pixel image","Corrupt PNG");
if (!pal_img_n) {
s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi_error("too large", "Image too large to decode");
if (scan == SCAN_header) return 1;
} else {
// if paletted, then pal_n is our final components, and
// img_n is # components to decompress/filter.
s->img_n = 1;
if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi_error("too large","Corrupt PNG");
// if SCAN_header, have to scan to see if we have a tRNS
}
break;
}
case STBI_PNG_TYPE('P','L','T','E'): {
if (first) return stbi_error("first not IHDR", "Corrupt PNG");
if (c.length > 256*3) return stbi_error("invalid PLTE","Corrupt PNG");
pal_len = c.length / 3;
if (pal_len * 3 != c.length) return stbi_error("invalid PLTE","Corrupt PNG");
for (i=0; i < pal_len; ++i) {
palette[i*4+0] = get8u(s);
palette[i*4+1] = get8u(s);
palette[i*4+2] = get8u(s);
palette[i*4+3] = 255;
}
break;
}
case STBI_PNG_TYPE('t','R','N','S'): {
if (first) return stbi_error("first not IHDR", "Corrupt PNG");
if (z->idata) return stbi_error("tRNS after IDAT","Corrupt PNG");
if (pal_img_n) {
if (scan == SCAN_header) { s->img_n = 4; return 1; }
if (pal_len == 0) return stbi_error("tRNS before PLTE","Corrupt PNG");
if (c.length > pal_len) return stbi_error("bad tRNS len","Corrupt PNG");
pal_img_n = 4;
for (i=0; i < c.length; ++i)
palette[i*4+3] = get8u(s);
} else {
if (!(s->img_n & 1)) return stbi_error("tRNS with alpha","Corrupt PNG");
if (c.length != (uint32) s->img_n*2) return stbi_error("bad tRNS len","Corrupt PNG");
has_trans = 1;
for (k=0; k < s->img_n; ++k)
tc[k] = (uint8) get16(s); // non 8-bit images will be larger
}
break;
}
case STBI_PNG_TYPE('I','D','A','T'): {
if (first) return stbi_error("first not IHDR", "Corrupt PNG");
if (pal_img_n && !pal_len) return stbi_error("no PLTE","Corrupt PNG");
if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }
if (ioff + c.length > idata_limit) {
uint8 *p;
if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
while (ioff + c.length > idata_limit)
idata_limit *= 2;
p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return stbi_error("outofmem", "Out of memory");
z->idata = p;
}
if (!getn(s, z->idata+ioff,c.length)) return stbi_error("outofdata","Corrupt PNG");
ioff += c.length;
break;
}
case STBI_PNG_TYPE('I','E','N','D'): {
uint32 raw_len;
if (first) return stbi_error("first not IHDR", "Corrupt PNG");
if (scan != SCAN_load) return 1;
if (z->idata == NULL) return stbi_error("no IDAT","Corrupt PNG");
z->expanded = (uint8 *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !iphone);
if (z->expanded == NULL) return 0; // zlib should set error
free(z->idata); z->idata = NULL;
if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
s->img_out_n = s->img_n+1;
else
s->img_out_n = s->img_n;
if (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;
if (has_trans)
if (!compute_transparency(z, tc, s->img_out_n)) return 0;
if (iphone && s->img_out_n > 2)
stbi_de_iphone(z);
if (pal_img_n) {
// pal_img_n == 3 or 4
s->img_n = pal_img_n; // record the actual colors we had
s->img_out_n = pal_img_n;
if (req_comp >= 3) s->img_out_n = req_comp;
if (!expand_palette(z, palette, pal_len, s->img_out_n))
return 0;
}
free(z->expanded); z->expanded = NULL;
return 1;
}
default:
// if critical, fail
if (first) return stbi_error("first not IHDR", "Corrupt PNG");
if ((c.type & (1 << 29)) == 0) {
#ifndef STBI_NO_FAILURE_STRINGS
// not threadsafe
static char invalid_chunk[] = "XXXX chunk not known";
invalid_chunk[0] = (uint8) (c.type >> 24);
invalid_chunk[1] = (uint8) (c.type >> 16);
invalid_chunk[2] = (uint8) (c.type >> 8);
invalid_chunk[3] = (uint8) (c.type >> 0);
#endif
return stbi_error(invalid_chunk, "PNG not supported: unknown chunk type");
}
skip(s, c.length);
break;
}
// end of chunk, read and skip CRC
get32(s);
}
}
static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)
{
unsigned char *result=NULL;
if (req_comp < 0 || req_comp > 4) return stbi_error_puc("bad req_comp", "Internal error");
if (parse_png_file(p, SCAN_load, req_comp)) {
result = p->out;
p->out = NULL;
if (req_comp && req_comp != p->s->img_out_n) {
result = convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
p->s->img_out_n = req_comp;
if (result == NULL) return result;
}
*x = p->s->img_x;
*y = p->s->img_y;
if (n) *n = p->s->img_n;
}
free(p->out); p->out = NULL;
free(p->expanded); p->expanded = NULL;
free(p->idata); p->idata = NULL;
return result;
}
static unsigned char *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
png p;
p.s = s;
return do_png(&p, x,y,comp,req_comp);
}
static int stbi_png_test(stbi *s)
{
int r;
r = check_png_header(s);
stbi_rewind(s);
return r;
}
static int stbi_png_info_raw(png *p, int *x, int *y, int *comp)
{
if (!parse_png_file(p, SCAN_header, 0)) {
stbi_rewind( p->s );
return 0;
}
if (x) *x = p->s->img_x;
if (y) *y = p->s->img_y;
if (comp) *comp = p->s->img_n;
return 1;
}
static int stbi_png_info(stbi *s, int *x, int *y, int *comp)
{
png p;
p.s = s;
return stbi_png_info_raw(&p, x, y, comp);
}
// Microsoft/Windows BMP image
static int bmp_test(stbi *s)
{
int sz;
if (get8(s) != 'B') return 0;
if (get8(s) != 'M') return 0;
get32le(s); // discard filesize
get16le(s); // discard reserved
get16le(s); // discard reserved
get32le(s); // discard data offset
sz = get32le(s);
if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;
return 0;
}
static int stbi_bmp_test(stbi *s)
{
int r = bmp_test(s);
stbi_rewind(s);
return r;
}
// returns 0..31 for the highest set bit
static int high_bit(unsigned int z)
{
int n=0;
if (z == 0) return -1;
if (z >= 0x10000) n += 16, z >>= 16;
if (z >= 0x00100) n += 8, z >>= 8;
if (z >= 0x00010) n += 4, z >>= 4;
if (z >= 0x00004) n += 2, z >>= 2;
if (z >= 0x00002) n += 1, z >>= 1;
return n;
}
static int bitcount(unsigned int a)
{
a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
a = (a + (a >> 8)); // max 16 per 8 bits
a = (a + (a >> 16)); // max 32 per 8 bits
return a & 0xff;
}
static int shiftsigned(int v, int shift, int bits)
{
int result;
int z=0;
if (shift < 0) v <<= -shift;
else v >>= shift;
result = v;
z = bits;
while (z < 8) {
result += v >> z;
z += bits;
}
return result;
}
static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
uint8 *out;
unsigned int mr=0,mg=0,mb=0,ma=0;
stbi_uc pal[256][4];
int psize=0,i,j,compress=0,width;
int bpp, flip_vertically, pad, target, offset, hsz;
if (get8(s) != 'B' || get8(s) != 'M') return stbi_error_puc("not BMP", "Corrupt BMP");
get32le(s); // discard filesize
get16le(s); // discard reserved
get16le(s); // discard reserved
offset = get32le(s);
hsz = get32le(s);
if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return stbi_error_puc("unknown BMP", "BMP type not supported: unknown");
if (hsz == 12) {
s->img_x = get16le(s);
s->img_y = get16le(s);
} else {
s->img_x = get32le(s);
s->img_y = get32le(s);
}
if (get16le(s) != 1) return stbi_error_puc("bad BMP", "bad BMP");
bpp = get16le(s);
if (bpp == 1) return stbi_error_puc("monochrome", "BMP type not supported: 1-bit");
flip_vertically = ((int) s->img_y) > 0;
s->img_y = abs((int) s->img_y);
if (hsz == 12) {
if (bpp < 24)
psize = (offset - 14 - 24) / 3;
} else {
compress = get32le(s);
if (compress == 1 || compress == 2) return stbi_error_puc("BMP RLE", "BMP type not supported: RLE");
get32le(s); // discard sizeof
get32le(s); // discard hres
get32le(s); // discard vres
get32le(s); // discard colorsused
get32le(s); // discard max important
if (hsz == 40 || hsz == 56) {
if (hsz == 56) {
get32le(s);
get32le(s);
get32le(s);
get32le(s);
}
if (bpp == 16 || bpp == 32) {
if (compress == 0) {
if (bpp == 32) {
mr = 0xffu << 16;
mg = 0xffu << 8;
mb = 0xffu << 0;
ma = 0xffu << 24;
// @TODO: check for cases like alpha value is all 0 and switch it to 255
} else {
mr = 31u << 10;
mg = 31u << 5;
mb = 31u << 0;
}
} else if (compress == 3) {
mr = get32le(s);
mg = get32le(s);
mb = get32le(s);
// not documented, but generated by photoshop and handled by mspaint
if (mr == mg && mg == mb) {
// ?!?!?
return stbi_error_puc("bad BMP", "bad BMP");
}
} else {
return stbi_error_puc("bad BMP", "bad BMP");
}
}
} else {
assert(hsz == 108);
mr = get32le(s);
mg = get32le(s);
mb = get32le(s);
ma = get32le(s);
get32le(s); // discard color space
for (i=0; i < 12; ++i)
get32le(s); // discard color space parameters
}
if (bpp < 16)
psize = (offset - 14 - hsz) >> 2;
}
s->img_n = ma ? 4 : 3;
if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
target = req_comp;
else
target = s->img_n; // if they want monochrome, we'll post-convert
out = (stbi_uc *) malloc(target * s->img_x * s->img_y);
if (!out) return stbi_error_puc("outofmem", "Out of memory");
if (bpp < 16) {
int z=0;
if (psize == 0 || psize > 256) { free(out); return stbi_error_puc("invalid", "Corrupt BMP"); }
for (i=0; i < psize; ++i) {
pal[i][2] = get8u(s);
pal[i][1] = get8u(s);
pal[i][0] = get8u(s);
if (hsz != 12) get8(s);
pal[i][3] = 255;
}
skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));
if (bpp == 4) width = (s->img_x + 1) >> 1;
else if (bpp == 8) width = s->img_x;
else
{ free(out); return stbi_error_puc("bad bpp", "Corrupt BMP"); }
pad = (-width)&3;
for (j=0; j < (int) s->img_y; ++j) {
for (i=0; i < (int) s->img_x; i += 2) {
int v=get8(s),v2=0;
if (bpp == 4) {
v2 = v & 15;
v >>= 4;
}
out[z++] = pal[v][0];
out[z++] = pal[v][1];
out[z++] = pal[v][2];
if (target == 4) out[z++] = 255;
if (i+1 == (int) s->img_x) break;
v = (bpp == 8) ? get8(s) : v2;
out[z++] = pal[v][0];
out[z++] = pal[v][1];
out[z++] = pal[v][2];
if (target == 4) out[z++] = 255;
}
skip(s, pad);
}
} else {
int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
int z = 0;
int easy=0;
skip(s, offset - 14 - hsz);
if (bpp == 24) width = 3 * s->img_x;
else if (bpp == 16) width = 2*s->img_x;
else /* bpp = 32 and pad = 0 */ width=0;
pad = (-width) & 3;
if (bpp == 24) {
easy = 1;
} else if (bpp == 32) {
if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
easy = 2;
}
if (!easy) {
if (!mr || !mg || !mb) { free(out); return stbi_error_puc("bad masks", "Corrupt BMP"); }
// right shift amt to put high bit in position #7
rshift = high_bit(mr)-7; rcount = bitcount(mr);
gshift = high_bit(mg)-7; gcount = bitcount(mr);
bshift = high_bit(mb)-7; bcount = bitcount(mr);
ashift = high_bit(ma)-7; acount = bitcount(mr);
}
for (j=0; j < (int) s->img_y; ++j) {
if (easy) {
for (i=0; i < (int) s->img_x; ++i) {
int a;
out[z+2] = get8u(s);
out[z+1] = get8u(s);
out[z+0] = get8u(s);
z += 3;
a = (easy == 2 ? get8(s) : 255);
if (target == 4) out[z++] = (uint8) a;
}
} else {
for (i=0; i < (int) s->img_x; ++i) {
uint32 v = (bpp == 16 ? get16le(s) : get32le(s));
int a;
out[z++] = (uint8) shiftsigned(v & mr, rshift, rcount);
out[z++] = (uint8) shiftsigned(v & mg, gshift, gcount);
out[z++] = (uint8) shiftsigned(v & mb, bshift, bcount);
a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);
if (target == 4) out[z++] = (uint8) a;
}
}
skip(s, pad);
}
}
if (flip_vertically) {
stbi_uc t;
for (j=0; j < (int) s->img_y>>1; ++j) {
stbi_uc *p1 = out + j *s->img_x*target;
stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
for (i=0; i < (int) s->img_x*target; ++i) {
t = p1[i], p1[i] = p2[i], p2[i] = t;
}
}
}
if (req_comp && req_comp != target) {
out = convert_format(out, target, req_comp, s->img_x, s->img_y);
if (out == NULL) return out; // convert_format frees input on failure
}
*x = s->img_x;
*y = s->img_y;
if (comp) *comp = s->img_n;
return out;
}
static stbi_uc *stbi_bmp_load(stbi *s,int *x, int *y, int *comp, int req_comp)
{
return bmp_load(s, x,y,comp,req_comp);
}
// Targa Truevision - TGA
// by Jonathan Dummer
static int tga_info(stbi *s, int *x, int *y, int *comp)
{
int tga_w, tga_h, tga_comp;
int sz;
get8u(s); // discard Offset
sz = get8u(s); // color type
if( sz > 1 ) {
stbi_rewind(s);
return 0; // only RGB or indexed allowed
}
sz = get8u(s); // image type
// only RGB or grey allowed, +/- RLE
if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;
skip(s,9);
tga_w = get16le(s);
if( tga_w < 1 ) {
stbi_rewind(s);
return 0; // test width
}
tga_h = get16le(s);
if( tga_h < 1 ) {
stbi_rewind(s);
return 0; // test height
}
sz = get8(s); // bits per pixel
// only RGB or RGBA or grey allowed
if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {
stbi_rewind(s);
return 0;
}
tga_comp = sz;
if (x) *x = tga_w;
if (y) *y = tga_h;
if (comp) *comp = tga_comp / 8;
return 1; // seems to have passed everything
}
int stbi_tga_info(stbi *s, int *x, int *y, int *comp)
{
return tga_info(s, x, y, comp);
}
static int tga_test(stbi *s)
{
int sz;
get8u(s); // discard Offset
sz = get8u(s); // color type
if ( sz > 1 ) return 0; // only RGB or indexed allowed
sz = get8u(s); // image type
if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE
get16(s); // discard palette start
get16(s); // discard palette length
get8(s); // discard bits per palette color entry
get16(s); // discard x origin
get16(s); // discard y origin
if ( get16(s) < 1 ) return 0; // test width
if ( get16(s) < 1 ) return 0; // test height
sz = get8(s); // bits per pixel
if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0; // only RGB or RGBA or grey allowed
return 1; // seems to have passed everything
}
static int stbi_tga_test(stbi *s)
{
int res = tga_test(s);
stbi_rewind(s);
return res;
}
static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
// read in the TGA header stuff
int tga_offset = get8u(s);
int tga_indexed = get8u(s);
int tga_image_type = get8u(s);
int tga_is_RLE = 0;
int tga_palette_start = get16le(s);
int tga_palette_len = get16le(s);
int tga_palette_bits = get8u(s);
/* tga_x_origin = */ (void)get16le(s);
/* tga_y_origin = */ (void)get16le(s);
int tga_width = get16le(s);
int tga_height = get16le(s);
int tga_bits_per_pixel = get8u(s);
int tga_inverted = get8u(s);
// image data
unsigned char *tga_data;
unsigned char *tga_palette = NULL;
int i, j;
unsigned char raw_data[4];
unsigned char trans_data[4];
int RLE_count = 0;
int RLE_repeating = 0;
int read_next_pixel = 1;
// do a tiny bit of precessing
if ( tga_image_type >= 8 )
{
tga_image_type -= 8;
tga_is_RLE = 1;
}
/* int tga_alpha_bits = tga_inverted & 15; */
tga_inverted = 1 - ((tga_inverted >> 5) & 1);
// error check
if ( //(tga_indexed) ||
(tga_width < 1) || (tga_height < 1) ||
(tga_image_type < 1) || (tga_image_type > 3) ||
((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&
(tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))
)
{
return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA
}
// If I'm paletted, then I'll use the number of bits from the palette
if ( tga_indexed )
{
tga_bits_per_pixel = tga_palette_bits;
}
// tga info
*x = tga_width;
*y = tga_height;
if ( (req_comp < 1) || (req_comp > 4) )
{
// just use whatever the file was
req_comp = tga_bits_per_pixel / 8;
*comp = req_comp;
}
else
{
// force a new number of components
*comp = tga_bits_per_pixel/8;
}
tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );
if (!tga_data) return stbi_error_puc("outofmem", "Out of memory");
// skip to the data's starting position (offset usually = 0)
skip(s, tga_offset );
// do I need to load a palette?
if ( tga_indexed )
{
// any data to skip? (offset usually = 0)
skip(s, tga_palette_start );
// load the palette
tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );
if (!tga_palette) return stbi_error_puc("outofmem", "Out of memory");
if (!getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {
free(tga_data);
free(tga_palette);
return stbi_error_puc("bad palette", "Corrupt TGA");
}
}
// load the data
trans_data[0] = trans_data[1] = trans_data[2] = trans_data[3] = 0;
for (i=0; i < tga_width * tga_height; ++i)
{
// if I'm in RLE mode, do I need to get a RLE chunk?
if ( tga_is_RLE )
{
if ( RLE_count == 0 )
{
// yep, get the next byte as a RLE command
int RLE_cmd = get8u(s);
RLE_count = 1 + (RLE_cmd & 127);
RLE_repeating = RLE_cmd >> 7;
read_next_pixel = 1;
}
else if ( !RLE_repeating )
{
read_next_pixel = 1;
}
}
else
{
read_next_pixel = 1;
}
// OK, if I need to read a pixel, do it now
if ( read_next_pixel )
{
// load however much data we did have
if ( tga_indexed )
{
// read in 1 byte, then perform the lookup
int pal_idx = get8u(s);
if ( pal_idx >= tga_palette_len )
{
// invalid index
pal_idx = 0;
}
pal_idx *= tga_bits_per_pixel / 8;
for (j = 0; j*8 < tga_bits_per_pixel; ++j)
{
raw_data[j] = tga_palette[pal_idx+j];
}
}
else
{
// read in the data raw
for (j = 0; j*8 < tga_bits_per_pixel; ++j)
{
raw_data[j] = get8u(s);
}
}
// convert raw to the intermediate format
switch (tga_bits_per_pixel)
{
case 8:
// Luminous => RGBA
trans_data[0] = raw_data[0];
trans_data[1] = raw_data[0];
trans_data[2] = raw_data[0];
trans_data[3] = 255;
break;
case 16: // B5G5R5A1 => RGBA
trans_data[3] = 255 * ((raw_data[1] & 0x80) >> 7);
case 15: // B5G5R5 => RGBA
trans_data[0] = (raw_data[1] >> 2) & 0x1F;
trans_data[1] = ((raw_data[1] << 3) & 0x1C) | ((raw_data[0] >> 5) & 0x07);
trans_data[2] = (raw_data[0] & 0x1F);
// Convert 5-bit channels to 8-bit channels by left shifting by three
// and repeating the first three bits to cover the range [0,255] with
// even spacing. For example:
// channel input bits: 4 3 2 1 0
// channel output bits: 4 3 2 1 0 4 3 2
trans_data[0] = (trans_data[0] << 3) | (trans_data[0] >> 2);
trans_data[1] = (trans_data[1] << 3) | (trans_data[1] >> 2);
trans_data[2] = (trans_data[2] << 3) | (trans_data[2] >> 2);
break;
case 24:
// BGR => RGBA
trans_data[0] = raw_data[2];
trans_data[1] = raw_data[1];
trans_data[2] = raw_data[0];
trans_data[3] = 255;
break;
case 32:
// BGRA => RGBA
trans_data[0] = raw_data[2];
trans_data[1] = raw_data[1];
trans_data[2] = raw_data[0];
trans_data[3] = raw_data[3];
break;
}
// clear the reading flag for the next pixel
read_next_pixel = 0;
} // end of reading a pixel
// convert to final format
switch (req_comp)
{
case 1:
// RGBA => Luminance
tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
break;
case 2:
// RGBA => Luminance,Alpha
tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
tga_data[i*req_comp+1] = trans_data[3];
break;
case 3:
// RGBA => RGB
tga_data[i*req_comp+0] = trans_data[0];
tga_data[i*req_comp+1] = trans_data[1];
tga_data[i*req_comp+2] = trans_data[2];
break;
case 4:
// RGBA => RGBA
tga_data[i*req_comp+0] = trans_data[0];
tga_data[i*req_comp+1] = trans_data[1];
tga_data[i*req_comp+2] = trans_data[2];
tga_data[i*req_comp+3] = trans_data[3];
break;
}
// in case we're in RLE mode, keep counting down
--RLE_count;
}
// do I need to invert the image?
if ( tga_inverted )
{
for (j = 0; j*2 < tga_height; ++j)
{
#ifdef PANDORA
const int taille = tga_width * req_comp;
unsigned char* index1 = tga_data + (j * taille);
unsigned char* index2 = tga_data + ((tga_height - 1 - j) * taille);
unsigned char temp[taille];
memcpy(temp, index1, taille);
memcpy(index1, index2, taille);
memcpy(index2, temp, taille);
#else
int index1 = j * tga_width * req_comp;
int index2 = (tga_height - 1 - j) * tga_width * req_comp;
for (i = tga_width * req_comp; i > 0; --i)
{
unsigned char temp = tga_data[index1];
tga_data[index1] = tga_data[index2];
tga_data[index2] = temp;
++index1;
++index2;
}
#endif
}
}
// clear my palette, if I had one
free(tga_palette);
// OK, done
return tga_data;
}
static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
return tga_load(s,x,y,comp,req_comp);
}
// *************************************************************************************************
// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
static int psd_test(stbi *s)
{
if (get32(s) != 0x38425053) return 0; // "8BPS"
else return 1;
}
static int stbi_psd_test(stbi *s)
{
int r = psd_test(s);
stbi_rewind(s);
return r;
}
static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
int pixelCount;
int channelCount, compression;
int channel, i, count, len;
int w,h;
uint8 *out;
// Check identifier
if (get32(s) != 0x38425053) // "8BPS"
return stbi_error_puc("not PSD", "Corrupt PSD image");
// Check file type version.
if (get16(s) != 1)
return stbi_error_puc("wrong version", "Unsupported version of PSD image");
// Skip 6 reserved bytes.
skip(s, 6 );
// Read the number of channels (R, G, B, A, etc).
channelCount = get16(s);
if (channelCount < 0 || channelCount > 16)
return stbi_error_puc("wrong channel count", "Unsupported number of channels in PSD image");
// Read the rows and columns of the image.
h = get32(s);
w = get32(s);
// Make sure the depth is 8 bits.
if (get16(s) != 8)
return stbi_error_puc("unsupported bit depth", "PSD bit depth is not 8 bit");
// Make sure the color mode is RGB.
// Valid options are:
// 0: Bitmap
// 1: Grayscale
// 2: Indexed color
// 3: RGB color
// 4: CMYK color
// 7: Multichannel
// 8: Duotone
// 9: Lab color
if (get16(s) != 3)
return stbi_error_puc("wrong color format", "PSD is not in RGB color format");
// Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
skip(s,get32(s) );
// Skip the image resources. (resolution, pen tool paths, etc)
skip(s, get32(s) );
// Skip the reserved data.
skip(s, get32(s) );
// Find out if the data is compressed.
// Known values:
// 0: no compression
// 1: RLE compressed
compression = get16(s);
if (compression > 1)
return stbi_error_puc("bad compression", "PSD has an unknown compression format");
// Create the destination image.
out = (stbi_uc *) malloc(4 * w*h);
if (!out) return stbi_error_puc("outofmem", "Out of memory");
pixelCount = w*h;
// Initialize the data to zero.
//memset( out, 0, pixelCount * 4 );
// Finally, the image data.
if (compression) {
// RLE as used by .PSD and .TIFF
// Loop until you get the number of unpacked bytes you are expecting:
// Read the next source byte into n.
// If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
// Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
// Else if n is 128, noop.
// Endloop
// The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,
// which we're going to just skip.
skip(s, h * channelCount * 2 );
// Read the RLE data by channel.
for (channel = 0; channel < 4; channel++) {
uint8 *p;
p = out+channel;
if (channel >= channelCount) {
// Fill this channel with default data.
for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;
} else {
// Read the RLE data.
count = 0;
while (count < pixelCount) {
len = get8(s);
if (len == 128) {
// No-op.
} else if (len < 128) {
// Copy next len+1 bytes literally.
len++;
count += len;
while (len) {
*p = get8u(s);
p += 4;
len--;
}
} else if (len > 128) {
uint8 val;
// Next -len+1 bytes in the dest are replicated from next source byte.
// (Interpret len as a negative 8-bit int.)
len ^= 0x0FF;
len += 2;
val = get8u(s);
count += len;
while (len) {
*p = val;
p += 4;
len--;
}
}
}
}
}
} else {
// We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
// where each channel consists of an 8-bit value for each pixel in the image.
// Read the data by channel.
for (channel = 0; channel < 4; channel++) {
uint8 *p;
p = out + channel;
if (channel > channelCount) {
// Fill this channel with default data.
for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;
} else {
// Read the data.
for (i = 0; i < pixelCount; i++)
*p = get8u(s), p += 4;
}
}
}
if (req_comp && req_comp != 4) {
out = convert_format(out, 4, req_comp, w, h);
if (out == NULL) return out; // convert_format frees input on failure
}
if (comp) *comp = channelCount;
*y = h;
*x = w;
return out;
}
static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
return psd_load(s,x,y,comp,req_comp);
}
// *************************************************************************************************
// Softimage PIC loader
// by Tom Seddon
//
// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
static int pic_is4(stbi *s,const char *str)
{
int i;
for (i=0; i<4; ++i)
if (get8(s) != (stbi_uc)str[i])
return 0;
return 1;
}
static int pic_test(stbi *s)
{
int i;
if (!pic_is4(s,"\x53\x80\xF6\x34"))
return 0;
for(i=0;i<84;++i)
get8(s);
if (!pic_is4(s,"PICT"))
return 0;
return 1;
}
typedef struct
{
stbi_uc size,type,channel;
} pic_packet_t;
static stbi_uc *pic_readval(stbi *s, int channel, stbi_uc *dest)
{
int mask=0x80, i;
for (i=0; i<4; ++i, mask>>=1) {
if (channel & mask) {
if (at_eof(s)) return stbi_error_puc("bad file","PIC file too short");
dest[i]=get8u(s);
}
}
return dest;
}
static void pic_copyval(int channel,stbi_uc *dest,const stbi_uc *src)
{
int mask=0x80,i;
for (i=0;i<4; ++i, mask>>=1)
if (channel&mask)
dest[i]=src[i];
}
static stbi_uc *pic_load2(stbi *s,int width,int height,int *comp, stbi_uc *result)
{
int act_comp=0,num_packets=0,y,chained;
pic_packet_t packets[10];
// this will (should...) cater for even some bizarre stuff like having data
// for the same channel in multiple packets.
do {
pic_packet_t *packet;
if (num_packets==sizeof(packets)/sizeof(packets[0]))
return stbi_error_puc("bad format","too many packets");
packet = &packets[num_packets++];
chained = get8(s);
packet->size = get8u(s);
packet->type = get8u(s);
packet->channel = get8u(s);
act_comp |= packet->channel;
if (at_eof(s)) return stbi_error_puc("bad file","file too short (reading packets)");
if (packet->size != 8) return stbi_error_puc("bad format","packet isn't 8bpp");
} while (chained);
*comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
for(y=0; y<height; ++y) {
int packet_idx;
for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
pic_packet_t *packet = &packets[packet_idx];
stbi_uc *dest = result+y*width*4;
switch (packet->type) {
default:
return stbi_error_puc("bad format","packet has bad compression type");
case 0: {//uncompressed
int x;
for(x=0;x<width;++x, dest+=4)
if (!pic_readval(s,packet->channel,dest))
return 0;
break;
}
case 1://Pure RLE
{
int left=width, i;
while (left>0) {
stbi_uc count,value[4];
count=get8u(s);
if (at_eof(s)) return stbi_error_puc("bad file","file too short (pure read count)");
if (count > left)
count = (uint8) left;
if (!pic_readval(s,packet->channel,value)) return 0;
for(i=0; i<count; ++i,dest+=4)
pic_copyval(packet->channel,dest,value);
left -= count;
}
}
break;
case 2: {//Mixed RLE
int left=width;
while (left>0) {
int count = get8(s), i;
if (at_eof(s)) return stbi_error_puc("bad file","file too short (mixed read count)");
if (count >= 128) { // Repeated
stbi_uc value[4];
int i;
if (count==128)
count = get16(s);
else
count -= 127;
if (count > left)
return stbi_error_puc("bad file","scanline overrun");
if (!pic_readval(s,packet->channel,value))
return 0;
for(i=0;i<count;++i, dest += 4)
pic_copyval(packet->channel,dest,value);
} else { // Raw
++count;
if (count>left) return stbi_error_puc("bad file","scanline overrun");
for(i=0;i<count;++i, dest+=4)
if (!pic_readval(s,packet->channel,dest))
return 0;
}
left-=count;
}
break;
}
}
}
}
return result;
}
static stbi_uc *pic_load(stbi *s,int *px,int *py,int *comp,int req_comp)
{
stbi_uc *result;
int i, x,y;
for (i=0; i<92; ++i)
get8(s);
x = get16(s);
y = get16(s);
if (at_eof(s)) return stbi_error_puc("bad file","file too short (pic header)");
if ((1 << 28) / x < y) return stbi_error_puc("too large", "Image too large to decode");
get32(s); //skip `ratio'
get16(s); //skip `fields'
get16(s); //skip `pad'
// intermediate buffer is RGBA
result = (stbi_uc *) malloc(x*y*4);
memset(result, 0xff, x*y*4);
if (!pic_load2(s,x,y,comp, result)) {
free(result);
result=0;
}
*px = x;
*py = y;
if (req_comp == 0) req_comp = *comp;
result=convert_format(result,4,req_comp,x,y);
return result;
}
static int stbi_pic_test(stbi *s)
{
int r = pic_test(s);
stbi_rewind(s);
return r;
}
static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
return pic_load(s,x,y,comp,req_comp);
}
#ifndef STBI_NO_GIF
// *************************************************************************************************
// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
typedef struct stbi_gif_lzw_struct {
int16 prefix;
uint8 first;
uint8 suffix;
} stbi_gif_lzw;
typedef struct stbi_gif_struct
{
int w,h;
stbi_uc *out; // output buffer (always 4 components)
int flags, bgindex, ratio, transparent, eflags;
uint8 pal[256][4];
uint8 lpal[256][4];
stbi_gif_lzw codes[4096];
uint8 *color_table;
int parse, step;
int lflags;
int start_x, start_y;
int max_x, max_y;
int cur_x, cur_y;
int line_size;
} stbi_gif;
static int gif_test(stbi *s)
{
int sz;
if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return 0;
sz = get8(s);
if (sz != '9' && sz != '7') return 0;
if (get8(s) != 'a') return 0;
return 1;
}
static int stbi_gif_test(stbi *s)
{
int r = gif_test(s);
stbi_rewind(s);
return r;
}
static void stbi_gif_parse_colortable(stbi *s, uint8 pal[256][4], int num_entries, int transp)
{
int i;
for (i=0; i < num_entries; ++i) {
pal[i][2] = get8u(s);
pal[i][1] = get8u(s);
pal[i][0] = get8u(s);
pal[i][3] = transp ? 0 : 255;
}
}
static int stbi_gif_header(stbi *s, stbi_gif *g, int *comp, int is_info)
{
uint8 version;
if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8')
return stbi_error("not GIF", "Corrupt GIF");
version = get8u(s);
if (version != '7' && version != '9') return stbi_error("not GIF", "Corrupt GIF");
if (get8(s) != 'a') return stbi_error("not GIF", "Corrupt GIF");
failure_reason = "";
g->w = get16le(s);
g->h = get16le(s);
g->flags = get8(s);
g->bgindex = get8(s);
g->ratio = get8(s);
g->transparent = -1;
if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
if (is_info) return 1;
if (g->flags & 0x80)
stbi_gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
return 1;
}
static int stbi_gif_info_raw(stbi *s, int *x, int *y, int *comp)
{
stbi_gif g;
if (!stbi_gif_header(s, &g, comp, 1)) {
stbi_rewind( s );
return 0;
}
if (x) *x = g.w;
if (y) *y = g.h;
return 1;
}
static void stbi_out_gif_code(stbi_gif *g, uint16 code)
{
uint8 *p, *c;
// recurse to decode the prefixes, since the linked-list is backwards,
// and working backwards through an interleaved image would be nasty
if (g->codes[code].prefix >= 0)
stbi_out_gif_code(g, g->codes[code].prefix);
if (g->cur_y >= g->max_y) return;
p = &g->out[g->cur_x + g->cur_y];
c = &g->color_table[g->codes[code].suffix * 4];
if (c[3] >= 128) {
p[0] = c[2];
p[1] = c[1];
p[2] = c[0];
p[3] = c[3];
}
g->cur_x += 4;
if (g->cur_x >= g->max_x) {
g->cur_x = g->start_x;
g->cur_y += g->step;
while (g->cur_y >= g->max_y && g->parse > 0) {
g->step = (1 << g->parse) * g->line_size;
g->cur_y = g->start_y + (g->step >> 1);
--g->parse;
}
}
}
static uint8 *stbi_process_gif_raster(stbi *s, stbi_gif *g)
{
uint8 lzw_cs;
int32 len, code;
uint32 first;
int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
stbi_gif_lzw *p;
lzw_cs = get8u(s);
clear = 1 << lzw_cs;
first = 1;
codesize = lzw_cs + 1;
codemask = (1 << codesize) - 1;
bits = 0;
valid_bits = 0;
for (code = 0; code < clear; code++) {
g->codes[code].prefix = -1;
g->codes[code].first = (uint8) code;
g->codes[code].suffix = (uint8) code;
}
// support no starting clear code
avail = clear+2;
oldcode = -1;
len = 0;
for(;;) {
if (valid_bits < codesize) {
if (len == 0) {
len = get8(s); // start new block
if (len == 0)
return g->out;
}
--len;
bits |= (int32) get8(s) << valid_bits;
valid_bits += 8;
} else {
int32 code = bits & codemask;
bits >>= codesize;
valid_bits -= codesize;
// @OPTIMIZE: is there some way we can accelerate the non-clear path?
if (code == clear) { // clear code
codesize = lzw_cs + 1;
codemask = (1 << codesize) - 1;
avail = clear + 2;
oldcode = -1;
first = 0;
} else if (code == clear + 1) { // end of stream code
skip(s, len);
while ((len = get8(s)) > 0)
skip(s,len);
return g->out;
} else if (code <= avail) {
if (first) return stbi_error_puc("no clear code", "Corrupt GIF");
if (oldcode >= 0) {
p = &g->codes[avail++];
if (avail > 4096) return stbi_error_puc("too many codes", "Corrupt GIF");
p->prefix = (int16) oldcode;
p->first = g->codes[oldcode].first;
p->suffix = (code == avail) ? p->first : g->codes[code].first;
} else if (code == avail) {
return stbi_error_puc("illegal code in raster", "Corrupt GIF");
}
stbi_out_gif_code(g, (uint16) code);
if ((avail & codemask) == 0 && avail <= 0x0FFF) {
codesize++;
codemask = (1 << codesize) - 1;
}
oldcode = code;
} else {
return stbi_error_puc("illegal code in raster", "Corrupt GIF");
}
}
}
}
static void stbi_fill_gif_background(stbi_gif *g)
{
int i;
uint8 *c = g->pal[g->bgindex];
// @OPTIMIZE: write a dword at a time
for (i = 0; i < g->w * g->h * 4; i += 4) {
uint8 *p = &g->out[i];
p[0] = c[2];
p[1] = c[1];
p[2] = c[0];
p[3] = c[3];
}
}
// this function is designed to support animated gifs, although stb_image doesn't support it
static uint8 *stbi_gif_load_next(stbi *s, stbi_gif *g, int *comp, int req_comp)
{
int i;
uint8 *old_out = 0;
if (g->out == 0) {
if (!stbi_gif_header(s, g, comp,0)) return 0; // failure_reason set by stbi_gif_header
g->out = (uint8 *) malloc(4 * g->w * g->h);
if (g->out == 0) return stbi_error_puc("outofmem", "Out of memory");
stbi_fill_gif_background(g);
} else {
// animated-gif-only path
if (((g->eflags & 0x1C) >> 2) == 3) {
old_out = g->out;
g->out = (uint8 *) malloc(4 * g->w * g->h);
if (g->out == 0) return stbi_error_puc("outofmem", "Out of memory");
memcpy(g->out, old_out, g->w*g->h*4);
}
}
for (;;) {
switch (get8(s)) {
case 0x2C: /* Image Descriptor */
{
int32 x, y, w, h;
uint8 *o;
x = get16le(s);
y = get16le(s);
w = get16le(s);
h = get16le(s);
if (((x + w) > (g->w)) || ((y + h) > (g->h)))
return stbi_error_puc("bad Image Descriptor", "Corrupt GIF");
g->line_size = g->w * 4;
g->start_x = x * 4;
g->start_y = y * g->line_size;
g->max_x = g->start_x + w * 4;
g->max_y = g->start_y + h * g->line_size;
g->cur_x = g->start_x;
g->cur_y = g->start_y;
g->lflags = get8(s);
if (g->lflags & 0x40) {
g->step = 8 * g->line_size; // first interlaced spacing
g->parse = 3;
} else {
g->step = g->line_size;
g->parse = 0;
}
if (g->lflags & 0x80) {
stbi_gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
g->color_table = (uint8 *) g->lpal;
} else if (g->flags & 0x80) {
for (i=0; i < 256; ++i) // @OPTIMIZE: reset only the previous transparent
g->pal[i][3] = 255;
if (g->transparent >= 0 && (g->eflags & 0x01))
g->pal[g->transparent][3] = 0;
g->color_table = (uint8 *) g->pal;
} else {
return stbi_error_puc("missing color table", "Corrupt GIF");
}
o = stbi_process_gif_raster(s, g);
if (o == NULL) return NULL;
if (req_comp && req_comp != 4)
o = convert_format(o, 4, req_comp, g->w, g->h);
return o;
}
case 0x21: // Comment Extension.
{
int len;
if (get8(s) == 0xF9) { // Graphic Control Extension.
len = get8(s);
if (len == 4) {
g->eflags = get8(s);
get16le(s); // delay
g->transparent = get8(s);
} else {
skip(s, len);
break;
}
}
while ((len = get8(s)) != 0)
skip(s, len);
break;
}
case 0x3B: // gif stream termination code
return (uint8 *) 1;
default:
return stbi_error_puc("unknown code", "Corrupt GIF");
}
}
}
static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
uint8 *u = 0;
stbi_gif g={0};
u = stbi_gif_load_next(s, &g, comp, req_comp);
if (u == (void *) 1) u = 0; // end of animated gif marker
if (u) {
*x = g.w;
*y = g.h;
}
return u;
}
static int stbi_gif_info(stbi *s, int *x, int *y, int *comp)
{
return stbi_gif_info_raw(s,x,y,comp);
}
#endif // ! STBI_NO_GIF
// *************************************************************************************************
// Radiance RGBE HDR loader
// originally by Nicolas Schulz
#ifndef STBI_NO_HDR
static int hdr_test(stbi *s)
{
const char *signature = "#?RADIANCE\n";
int i;
for (i=0; signature[i]; ++i)
if (get8(s) != signature[i])
return 0;
return 1;
}
static int stbi_hdr_test(stbi* s)
{
int r = hdr_test(s);
stbi_rewind(s);
return r;
}
#define STBI_HDR_BUFLEN 1024
static char *hdr_gettoken(stbi *z, char *buffer)
{
int len=0;
char c = '\0';
c = (char) get8(z);
while (!at_eof(z) && c != '\n') {
buffer[len++] = c;
if (len == STBI_HDR_BUFLEN-1) {
// flush to end of line
while (!at_eof(z) && get8(z) != '\n')
;
break;
}
c = (char) get8(z);
}
buffer[len] = 0;
return buffer;
}
static void hdr_convert(float *output, stbi_uc *input, int req_comp)
{
if ( input[3] != 0 ) {
float f1;
// Exponent
f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
if (req_comp <= 2) {
output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
} else {
output[0] = input[0] * f1;
output[1] = input[1] * f1;
output[2] = input[2] * f1;
}
if (req_comp == 2) output[1] = 1;
if (req_comp == 4) output[3] = 1;
} else {
switch (req_comp) {
case 4: output[3] = 1; /* fallthrough */
case 3: output[0] = output[1] = output[2] = 0;
break;
case 2: output[1] = 1; /* fallthrough */
case 1: output[0] = 0;
break;
}
}
}
static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
char buffer[STBI_HDR_BUFLEN];
char *token;
int valid = 0;
int width, height;
stbi_uc *scanline;
float *hdr_data;
int len;
unsigned char count, value;
int i, j, k, c1,c2, z;
// Check identifier
if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
return stbi_error_pf("not HDR", "Corrupt HDR image");
// Parse header
for(;;) {
token = hdr_gettoken(s,buffer);
if (token[0] == 0) break;
if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
}
if (!valid) return stbi_error_pf("unsupported format", "Unsupported HDR format");
// Parse width and height
// can't use sscanf() if we're not using stdio!
token = hdr_gettoken(s,buffer);
if (strncmp(token, "-Y ", 3)) return stbi_error_pf("unsupported data layout", "Unsupported HDR format");
token += 3;
height = strtol(token, &token, 10);
while (*token == ' ') ++token;
if (strncmp(token, "+X ", 3)) return stbi_error_pf("unsupported data layout", "Unsupported HDR format");
token += 3;
width = strtol(token, NULL, 10);
*x = width;
*y = height;
*comp = 3;
if (req_comp == 0) req_comp = 3;
// Read data
hdr_data = (float *) malloc(height * width * req_comp * sizeof(*hdr_data));
// Load image data
// image data is stored as some number of sca
if ( width < 8 || width >= 32768) {
// Read flat data
for (j=0; j < height; ++j) {
for (i=0; i < width; ++i) {
stbi_uc rgbe[4];
main_decode_loop:
getn(s, rgbe, 4);
hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
}
}
} else {
// Read RLE-encoded data
scanline = NULL;
for (j = 0; j < height; ++j) {
c1 = get8(s);
c2 = get8(s);
len = get8(s);
if (c1 != 2 || c2 != 2 || (len & 0x80)) {
// not run-length encoded, so we have to actually use THIS data as a decoded
// pixel (note this can't be a valid pixel--one of RGB must be >= 128)
uint8 rgbe[4];
rgbe[0] = (uint8) c1;
rgbe[1] = (uint8) c2;
rgbe[2] = (uint8) len;
rgbe[3] = (uint8) get8u(s);
hdr_convert(hdr_data, rgbe, req_comp);
i = 1;
j = 0;
free(scanline);
goto main_decode_loop; // yes, this makes no sense
}
len <<= 8;
len |= get8(s);
if (len != width) { free(hdr_data); free(scanline); return stbi_error_pf("invalid decoded scanline length", "corrupt HDR"); }
if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);
for (k = 0; k < 4; ++k) {
i = 0;
while (i < width) {
count = get8u(s);
if (count > 128) {
// Run
value = get8u(s);
count -= 128;
for (z = 0; z < count; ++z)
scanline[i++ * 4 + k] = value;
} else {
// Dump
for (z = 0; z < count; ++z)
scanline[i++ * 4 + k] = get8u(s);
}
}
}
for (i=0; i < width; ++i)
hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
}
free(scanline);
}
return hdr_data;
}
static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
return hdr_load(s,x,y,comp,req_comp);
}
static int stbi_hdr_info(stbi *s, int *x, int *y, int *comp)
{
char buffer[STBI_HDR_BUFLEN];
char *token;
int valid = 0;
if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {
stbi_rewind( s );
return 0;
}
for(;;) {
token = hdr_gettoken(s,buffer);
if (token[0] == 0) break;
if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
}
if (!valid) {
stbi_rewind( s );
return 0;
}
token = hdr_gettoken(s,buffer);
if (strncmp(token, "-Y ", 3)) {
stbi_rewind( s );
return 0;
}
token += 3;
*y = strtol(token, &token, 10);
while (*token == ' ') ++token;
if (strncmp(token, "+X ", 3)) {
stbi_rewind( s );
return 0;
}
token += 3;
*x = strtol(token, NULL, 10);
*comp = 3;
return 1;
}
#endif // STBI_NO_HDR
static int stbi_bmp_info(stbi *s, int *x, int *y, int *comp)
{
int hsz;
if (get8(s) != 'B' || get8(s) != 'M') {
stbi_rewind( s );
return 0;
}
skip(s,12);
hsz = get32le(s);
if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) {
stbi_rewind( s );
return 0;
}
if (hsz == 12) {
*x = get16le(s);
*y = get16le(s);
} else {
*x = get32le(s);
*y = get32le(s);
}
if (get16le(s) != 1) {
stbi_rewind( s );
return 0;
}
*comp = get16le(s) / 8;
return 1;
}
static int stbi_psd_info(stbi *s, int *x, int *y, int *comp)
{
int channelCount;
if (get32(s) != 0x38425053) {
stbi_rewind( s );
return 0;
}
if (get16(s) != 1) {
stbi_rewind( s );
return 0;
}
skip(s, 6);
channelCount = get16(s);
if (channelCount < 0 || channelCount > 16) {
stbi_rewind( s );
return 0;
}
*y = get32(s);
*x = get32(s);
if (get16(s) != 8) {
stbi_rewind( s );
return 0;
}
if (get16(s) != 3) {
stbi_rewind( s );
return 0;
}
*comp = 4;
return 1;
}
static int stbi_pic_info(stbi *s, int *x, int *y, int *comp)
{
int act_comp=0,num_packets=0,chained;
pic_packet_t packets[10];
skip(s, 92);
*x = get16(s);
*y = get16(s);
if (at_eof(s)) return 0;
if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
stbi_rewind( s );
return 0;
}
skip(s, 8);
do {
pic_packet_t *packet;
if (num_packets==sizeof(packets)/sizeof(packets[0]))
return 0;
packet = &packets[num_packets++];
chained = get8(s);
packet->size = get8u(s);
packet->type = get8u(s);
packet->channel = get8u(s);
act_comp |= packet->channel;
if (at_eof(s)) {
stbi_rewind( s );
return 0;
}
if (packet->size != 8) {
stbi_rewind( s );
return 0;
}
} while (chained);
*comp = (act_comp & 0x10 ? 4 : 3);
return 1;
}
static int stbi_info_main(stbi *s, int *x, int *y, int *comp, int *fmt)
{
if (stbi_jpeg_test(s)) { *fmt = STBI_jpeg; return stbi_jpeg_info(s, x, y, comp); }
if (stbi_png_test(s)) { *fmt = STBI_png; return stbi_png_info(s, x, y, comp); }
#ifndef STBI_NO_GIF
if (stbi_gif_test(s)) { *fmt = STBI_gif; return stbi_gif_info(s, x, y, comp); }
#endif // !STBI_NO_GIF
if (stbi_bmp_test(s)) { *fmt = STBI_bmp; return stbi_bmp_info(s, x, y, comp); }
if (stbi_psd_test(s)) { *fmt = STBI_psd; return stbi_psd_info(s, x, y, comp); }
if (stbi_pic_test(s)) { *fmt = STBI_pic; return stbi_pic_info(s, x, y, comp); }
#ifndef STBI_NO_HDR
if (stbi_hdr_test(s)) { *fmt = STBI_hdr; return stbi_hdr_info(s, x, y, comp); }
#endif
// test tga last because it's a crappy test!
if (stbi_tga_test(s)) { *fmt = STBI_tga; return stbi_tga_info(s, x, y, comp); }
*fmt = STBI_unknown;
return stbi_error("unknown image type", "Image not of any known type, or corrupt");
}
#ifndef STBI_NO_STDIO
int stbi_info(char const *filename, int *x, int *y, int *comp, int *fmt)
{
FILE *f = fopen(filename, "rb");
int result;
if (!f) return stbi_error("can't fopen", "Unable to open file");
result = stbi_info_from_file(f, x, y, comp, fmt);
fclose(f);
return result;
}
int stbi_info_from_file(FILE *f, int *x, int *y, int *comp, int *fmt)
{
int r;
stbi s;
long pos = ftell(f);
start_file(&s, f);
r = stbi_info_main(&s,x,y,comp,fmt);
fseek(f,pos,SEEK_SET);
return r;
}
#endif // !STBI_NO_STDIO
int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int *fmt)
{
stbi s;
start_mem(&s,buffer,len);
return stbi_info_main(&s,x,y,comp,fmt);
}
#ifndef STBI_NO_CALLBACK
int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp, int *fmt)
{
stbi s;
start_callbacks(&s, (stbi_io_callbacks *) c, user);
return stbi_info_main(&s,x,y,comp,fmt);
}
#endif // !STBI_NO_CALLBACK
} // namespace stbi
| ptitSeb/ArxLibertatis | src/graphics/image/stb_image.cpp | C++ | gpl-3.0 | 132,545 |
// =====================================================================================
//
// Filename: os.hpp
//
// Description: kernel dependend
//
// Version: 1.0
// Created: 03/27/2016 12:36:24 PM
// Revision: none
// Compiler: g++
//
// Author: Marc Puttkammer (MP), CryptoCodez@protonmail.com
// Organization:
//
// =====================================================================================
#ifndef _OS_HPP_
#define _OS_HPP_
#undef NO_IMPLICIT_EXTERN_C
#define NO_IMPLICIT_EXTERN_C 1
#define OS "CryptonixOS"
#include <sys/types.hpp>
extern "C" void __cxa_pure_virtual(); // {}
typedef void( *constructor )();
extern "C" constructor start_ctors;
extern "C" constructor end_ctors;
extern "C" void init_ctors();
void init_ctors() {
for( constructor* i { &start_ctors }; i != &end_ctors; ++i )
(*i)();
}
extern "C" {
int __cxa_atexit( void ( *f )( void* ), void* p, void* d);
void __cxa_finalize( void* d );
}
void *__dso_handle;
struct object {
void ( *f )( void* );
void *p;
void *d;
} object[ 32 ] = {};
typ::uint32_t iObject { 0 };
int __cxa_atexit( void ( *f )( void* ), void *p, void *d ) {
if( iObject >= 32 ) return -1;
object[ iObject ].f = f;
object[ iObject ].p = p;
object[ iObject ].d = d;
++iObject;
return 0;
}
void __cxa_finalize( void *d ) {
typ::uint32_t i { iObject };
for( ; i > 0; --i ) {
--iObject;
object[ iObject].f( object[ iObject ].p );
}
}
#endif // ----- #ifndef _OS_HPP_ -----
| CryptoCodez/CryptonixOS | sys/os.hpp | C++ | gpl-3.0 | 1,538 |
<?php
require_once(dirname(dirname(dirname(__FILE__))).'/config.php');
require_once(dirname(__FILE__).'/lib.php');
$id = optional_param('id', 0, PARAM_INT); // course_module ID, or
$n = optional_param('n', 0, PARAM_INT); // vrssregistration instance ID - it should be named as the first character of the module
if ($id) {
$cm = get_coursemodule_from_id('vrssregistration', $id, 0, false, MUST_EXIST);
$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
$vrssregistration = $DB->get_record('vrssregistration', array('id' => $cm->instance), '*', MUST_EXIST);
} elseif ($n) {
$vrssregistration = $DB->get_record('vrssregistration', array('id' => $n), '*', MUST_EXIST);
$course = $DB->get_record('course', array('id' => $vrssregistration->course), '*', MUST_EXIST);
$cm = get_coursemodule_from_instance('vrssregistration', $vrssregistration->id, $course->id, false, MUST_EXIST);
} else {
error('You must specify a course_module ID or an instance ID');
}
require_login($course, true, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (has_capability('mod/vrssregistration/detailview.php:read', $context))
{
require_login($course, true, $cm);
}
add_to_log($course->id, 'vrssregistration', 'detailed view', "detailview.php?id={$cm->id}", $vrssregistration->name, $cm->id);
/// Print the page header
$PAGE->set_url('/mod/vrssregistration/detailview.php', array('id' => $cm->id));
$PAGE->set_title(format_string($vrssregistration->name));
$PAGE->set_heading(format_string($course->fullname));
$PAGE->set_context($context);
// other things you may want to set - remove if not needed
//$PAGE->set_cacheable(false);
//$PAGE->set_focuscontrol('some-html-id');
//$PAGE->add_body_class('vrssregistration-'.$somevar);
// Output starts here
echo $OUTPUT->header();
if ($vrssregistration->intro) { // Conditions to show the intro can change to look for own settings or whatever
echo $OUTPUT->box(format_module_intro('vrssregistration', $vrssregistration, $cm->id), 'generalbox mod_introbox', 'vrssregistrationintro');
}
/*
if ($course->guest )
{
echo "not allowed";
}*/
?>
<?php
//echo $totalRows_Recordset1;
echo $OUTPUT->heading('Student Registration Records');
//echo "Total reocrds : ".$totalRows_Recordset1;
?>
<style type="text/css">
.myAltRowClass { background-color: #DDDDDC; }
</style>
<link rel="stylesheet" type="text/css" href="http://www.trirand.com/blog/jqgrid/themes/redmond/jquery-ui-1.8.1.custom.css"/>
<link rel="stylesheet" type="text/css" href="jscss/ui.jqgrid.css"/>
<script type="text/javascript" src="jscss/jquery.js"></script>
<script type="text/javascript" src="jscss/jquery-ui-1.8.1.custom.min.js"></script>
<script type="text/javascript" src="jscss/jquery.layout.js"></script>
<script type="text/javascript" src="jscss/grid.locale-en.js"></script>
<script type="text/javascript" src="jscss/ui.multiselect.js"></script>
<script type="text/javascript" src="jscss/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="jscss/jquery.tablednd.js"></script>
<script type="text/javascript" src="jscss/jquery.contextmenu.js"></script>
<script type="text/javascript">
// Here we set the altRows option globallly
//jQuery.extend(jQuery.jgrid.defaults, { altRows:true });
//$("tr.jqgrow:odd").css("background-color", "#B80A0A");
//$('#list2 tr:nth-child(even)').css("background", "#FCF9E6");;
//$('#list2 tr:nth-child(odd)').addClass("myAltRowClass");
$('#list2 tr:nth-child(even)').removeClass("myAltRowClass");
$('#list2 tr:nth-child(odd)').addClass("myAltRowClass");
</script>
<script type="text/javascript">
function loadgridData()
{
$grid= $("#list2");
$.ajax(
{
type: "POST",
url: "getgriddata.php",
async:false,
dataType:"json",
//contentType: "application/json; charset=utf-8",
success : function(data)
{
$grid.jqGrid({
data: data,
datatype: "local", // Set datatype to detect json data locally
colNames:['ID' , 'Date', 'Student Name','Institute','Qualification', 'Courses Apllied For', 'Experience', 'Experience Type','Phone No.','Email Id'],
colModel:[
{name:'id',index:'id', width:50,search:true,align:"center"},
{name:'subjectname',index:'subjectname', width:60,search:true,align:"center"},
],
rowNum: 10,
autowidth:true,
rownumbers: true,
rowList:[10,20],
height:245,
pager: '#pager2',
sortname: 'reg_date',
viewrecords: true,
sortorder: "desc",
altRows:false,
//altClass:'myAltRowClass',
caption:"Registration Data"
})
}
});
$grid.jqGrid('navGrid','#pager2',{edit:false,add:false,del:false},
{},
{},
{}, {multipleSearch:true, multipleGroup:true, showQuery: true});
// jQuery("#list2").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});
}
var varName = function(){
loadgridData();
};
$(document).ready( function(){
// Create JSON data locally
setInterval(varName, 20000);
loadgridData();
});
</script>
<table id="list2"></table>
<div id="pager2"></div>
<div id="ptoolbar" ></div>
<?php
// Finish the page
echo $OUTPUT->footer();
?>
| saurabh947/MoodleLearning | mod/subjectplugin/detailview.php | PHP | gpl-3.0 | 5,576 |
package com.github.marcelothebuilder.webpedidos.service;
import java.io.Serializable;
import javax.inject.Inject;
import com.github.marcelothebuilder.webpedidos.model.produto.Produto;
import com.github.marcelothebuilder.webpedidos.repository.Produtos;
import com.github.marcelothebuilder.webpedidos.util.interceptor.Transactional;
public class CadastroProdutoService implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private Produtos produtos;
@Transactional
public Produto salvar(Produto produto) {
Produto produtoExistente = produtos.porSku(produto.getSku());
// TODO: ao invés de validar este erro aqui, deixar que o database
// retorne o erro de unique constraint violation
if (produtoExistente != null && !produtoExistente.equals(produto)) {
throw new NegocioException("Já existe um produto com o mesmo Sku");
}
return produtos.guardar(produto);
}
}
| marcelothebuilder/webpedidos | src/main/java/com/github/marcelothebuilder/webpedidos/service/CadastroProdutoService.java | Java | gpl-3.0 | 918 |
#region Copyright
/////////////////////////////////////////////////////////////////////////////
// Altaxo: a data processing and data plotting program
// Copyright (C) 2002-2011 Dr. Dirk Lellinger
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
/////////////////////////////////////////////////////////////////////////////
#endregion Copyright
#nullable disable warnings
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace Altaxo.Gui.Common
{
public class TextBlockUtilities
{
/// <summary>
/// Gets the value of the AutoTooltipProperty dependency property
/// </summary>
public static bool GetAutoTooltip(DependencyObject obj)
{
return (bool)obj.GetValue(AutoTooltipProperty);
}
/// <summary>
/// Sets the value of the AutoTooltipProperty dependency property
/// </summary>
public static void SetAutoTooltip(DependencyObject obj, bool value)
{
obj.SetValue(AutoTooltipProperty, value);
}
/// <summary>
/// Identified the attached AutoTooltip property. When true, this will set the TextBlock TextTrimming
/// property to WordEllipsis, and display a tooltip with the full text whenever the text is trimmed.
/// </summary>
public static readonly DependencyProperty AutoTooltipProperty = DependencyProperty.RegisterAttached("AutoTooltip",
typeof(bool), typeof(TextBlockUtilities), new PropertyMetadata(false, OnAutoTooltipPropertyChanged));
private static void OnAutoTooltipPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBlock = d as TextBlock;
if (textBlock is null)
return;
if (e.NewValue.Equals(true))
{
ComputeAutoTooltip(textBlock);
textBlock.SizeChanged += EhTextBlockSizeChanged;
var dpd = DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, typeof(TextBlock));
dpd.AddValueChanged(d, EhTextBlockTextChanged);
}
else
{
textBlock.SizeChanged -= EhTextBlockSizeChanged;
var dpd = DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, typeof(TextBlock));
dpd.RemoveValueChanged(d, EhTextBlockTextChanged);
}
}
private static void EhTextBlockSizeChanged(object sender, EventArgs e)
{
var textBlock = sender as TextBlock;
ComputeAutoTooltip(textBlock);
}
private static void EhTextBlockTextChanged(object? sender, EventArgs e)
{
var textBlock = sender as TextBlock;
ComputeAutoTooltip(textBlock);
}
/// <summary>
/// Assigns the ToolTip for the given TextBlock based on whether the text is trimmed
/// </summary>
private static void ComputeAutoTooltip(TextBlock textBlock)
{
textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
var width = textBlock.DesiredSize.Width;
if (textBlock.ActualWidth < width)
{
ToolTipService.SetToolTip(textBlock, textBlock.Text);
}
else
{
ToolTipService.SetToolTip(textBlock, null);
}
}
}
}
| Altaxo/Altaxo | Altaxo/Base.Presentation/Gui/Common/TextBlockUtilities.cs | C# | gpl-3.0 | 3,940 |
/**
* Created by Akkadius on 2/10/2015.
*/
$(document).ready(function() {
var CalcDataTableHeight = function () {
return $(window).height() * 60 / 100;
};
var table = $("#npc_head_table").DataTable( {
scrollY: CalcDataTableHeight(),
scrollX: true,
scrollCollapse: true,
paging: false,
"searching": false,
"ordering": true,
"columnDefs": [ { "targets": 0, "orderable": false } ],
"oLanguage": {
"sProcessing": "DataTables is currently busy"
}
} );
// $(window).resize(function () {
// var table = $("#npc_head_table").DataTable();
// var oSettings = table.fnSettings().oScroll.sY = CalcDataTableHeight();
// table.fnDraw();
// });
new $.fn.dataTable.FixedColumns( table, {
leftColumns: 3
} );
var timer = setInterval(function () {
var table = $("#npc_head_table").DataTable();
table.draw();
window.clearInterval(timer);
}, 500);
$( "#npc_head_table td, .DTFC_Cloned td" ).unbind("mouseenter");
$( "#npc_head_table td, .DTFC_Cloned td" ).bind("mouseenter", function() {
// console.log("Hovering in");
if($(this).attr("is_field_translated") == 1){
return;
}
npc_id = $(this).attr("npc_id");
field_name = $(this).attr("npc_db_field");
width = $(this).css("width");
height = $(this).css("height");
data = $(this).html();
// console.log(npc_id + " " + field_name);
/* Dont replace the button */
if(data.match(/button/i)){ return; }
$(this).html('<input type="text" class="form-control" value="' + data + '" onchange="update_npc_field(npc_id, field_name, this.value)">');
$(this).children("input").css('width', (parseInt(width) * 1));
$(this).children("input").css('height', (parseInt(height)));
$(this).children("input").css("font-size", "12px");
// $('textarea').autosize();
data = "";
});
$( "#npc_head_table td, .DTFC_Cloned td" ).unbind("mouseleave");
$( "#npc_head_table td, .DTFC_Cloned td" ).bind("mouseleave", function() {
data = "";
if($(this).has("select").length){ data = $(this).children("select").val(); }
else if($(this).has("input").length){ data = $(this).children("input").val(); }
if($(this).has("button").length){ return; }
/* If no data present and */
if(!data && (!$(this).has("select").length && !$(this).has("input").length)){ $(this).attr("is_field_translated", 0); return; }
// console.log('data catch ' + data);
$(this).html(data);
data = "";
$(this).attr("is_field_translated", 0);
});
} );
/* NPC TABLE :: Click */
$( "#npc_head_table td" ).click(function() {
npc_id = $(this).attr("npc_id");
db_field = $(this).attr("npc_db_field");
width = $(this).css("width");
height = $(this).css("height");
data = $(this).html();
if(data.match(/button/i)){ return; }
// console.log(npc_id);
/* Highlight row */
if($('#top_right_pane').attr('npc_loaded') == npc_id){
console.log('npc already loaded, returning...');
return;
}
/* Highlight Row when selected */
$("td[background='yellow']").css("background", "").attr("background", "");
$("td[npc_id='" + npc_id + "']").css("background", "yellow").attr("background", "yellow");
$.ajax({
url: "ajax.php?M=NPC&load_npc_top_pane_dash=" + npc_id,
context: document.body
}).done(function(e) {
/* Update Data Table as well */
$('#top_right_pane').html(e).fadeIn();
$('#top_right_pane').attr('npc_loaded', npc_id);
});
});
/* NPC TABLE :: Double Click */
$( "#npc_head_table td" ).dblclick(function() {
npc_id = $(this).attr("npc_id");
db_field = $(this).attr("npc_db_field");
width = $(this).css("width");
height = $(this).css("height");
data = $(this).html();
input_data = $(this).find("input").val();
cell = $(this);
if(data.match(/button/i)){ return; }
if(db_field == "special_abilities"){
DoModal("ajax.php?M=NPC&special_abilities_editor&val=" + input_data + "&npc_id=" + npc_id + "&db_field=" + db_field);
return;
}
$.ajax({
url: "ajax.php?M=NPC&get_field_translator&npc_id=" + npc_id + "&field_name=" + db_field + "&value=" + input_data,
context: document.body
}).done(function(e) {
// console.log(e);
/* Return if tool result is empty */
if(e == ""){ return; }
/* Update Table Cell with Field Translator Tool */
cell.html(e).fadeIn();
cell.attr("is_field_translated", 1);
});
}); | Akkadius/EQEmuEOC | modules/NPC/ajax/npc_table.js | JavaScript | gpl-3.0 | 4,786 |
<?
//giriş kontrol
@include ("giris_kontrol.php");
// oturumu baslatalım
@session_start();
// giriş bilgilerini alalım.
$giris=$_SESSION["giris"];
$ad=$_SESSION["user_kadi"];
// giriş kontrolü yapalım
// giriş yapılmış ise $giris true olmalı
if($giris){
// giriş yapılmış hoşgeldin..
$user_nick = trim($_POST['nick']);
$user_sifre = trim($_POST['sifre']);
$user_sifre2 = trim($_POST['sifre2']);
$user_mail = trim($_POST['mail']);
$user_security = trim($_POST['securitycode']);
@include("yonetim/db.php");
if (
empty($user_nick) || empty($user_sifre) || empty($user_mail) || empty($user_security)
)
{
print '<script>alert(" Formu Eksik Doldurdunuz ! ");history.back(-1);</script>';
}
elseif (!preg_match("/[A-Za-z0-9_.-]+@([A-Za-z0-9_]+\.)+[A-Za-z]{2,4}/i", $user_mail))
{
print '<script>alert(" Mail Adresi Geçersiz ! ");history.back(-1);</script>';
}
elseif ( $user_sifre != $user_sifre2 ) {
print '<script>alert(" Şifreler Uyuşmuyor ! ");history.back(-1);</script>';
}
else
{
@include"yonetim/hbv/securitycode_kontrol.php";
$s = @mysql_query("SELECT user_id FROM user WHERE user_nick='$user_nick'");
if ( @mysql_num_rows($s) >= 1)
{
?>
<script>alert(" <?=$user_nick?> Kullanıcı adı kayıtlı ! ");history.back(-1);</script>
<?
exit();
}
$sorgu_mail = @mysql_query("SELECT user_mail FROM user WHERE user_mail='$user_mail'");
if ( @mysql_num_rows($sorgu_mail) >= 1)
{
?>
<script>alert(" <?=$user_mail?> Mail Adresi kayıtlı ! ");history.back();</script>
<?
exit();
}
$yeni_sifre = md5($user_sifre);
// Rastgele karakter
$karakter = 6;
$baslangic = rand(1,24);
$rastgelekod = md5(rand(0,500));
$kod = strtoupper(substr($rastgelekod,$baslangic,$karakter));
$user_lost_sifre = "$kod";
$tablo = "INSERT INTO user (user_nick, user_sifre, user_lost_sifre, user_mail) VALUES ('$user_nick','$yeni_sifre','$user_lost_sifre', '$user_mail')";
if ( mysql_query($tablo) ) {
?>
<script>
alert(" Kayıt işlemi Tamamlandı ");
window.top.location = '?shf=user&islem=oku';
</script>
<?
} else {
?>
<script>alert(" Hata Algılandı Tekrar Deneyiniz ! ");history.back(-1);</script>
<?
}
}
?>
<?
}else{
// giriş yapılmamış ise ;
@include ("../../hata.php");
}
?> | mustafairen/ferman | ferman/yonetim/acrophobia/islem_ekle.php | PHP | gpl-3.0 | 2,178 |
/*
Copyright 2015, 2017 Olli Helin / GainIT
This file is part of Kerppi, a free software released under the terms of the
GNU General Public License v3: http://www.gnu.org/licenses/gpl-3.0.en.html
*/
using System;
using System.Globalization;
using System.Windows.Data;
namespace Kerppi.ViewModels
{
class DecimalConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToDecimal(value).ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
decimal converted = Decimal.Zero;
Decimal.TryParse(value.ToString(), out converted);
return converted;
}
}
}
| ohel/kerppi | Kerppi/ViewModels/DecimalConverter.cs | C# | gpl-3.0 | 848 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jaddon.jlog;
import jaddon.controller.StaticStandard;
import java.io.InputStream;
import java.util.Scanner;
/**
*
* @author Paul
*/
public class SystemInputStream {
private InputStream inputstream = null;
private Scanner scanner = null;
private JLogger logger = null;
private final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while(scanner != null && scanner.hasNextLine()) {
try {
logger.sendCommand(scanner.nextLine());
} catch (Exception ex) {
}
}
} catch (Exception ex) {
}
StaticStandard.log("SystemInputSteam closed");
}
});
public SystemInputStream(InputStream inputstream, JLogger logger) {
this.inputstream = inputstream;
this.logger = logger;
updateScanner();
}
public void updateScanner() {
try {
stop();
scanner = new Scanner(inputstream);
thread.start();
} catch (Exception ex) {
StaticStandard.logErr("Error while updating scanner: " + ex, ex);
}
}
public void stop() {
while(thread.isAlive()) {
try {
thread.stop();
} catch (Exception ex) {
}
}
}
}
| Panzer1119/JAddOn | src/jaddon/jlog/SystemInputStream.java | Java | gpl-3.0 | 1,701 |
/*
* Copyright (c) 2016 Helmut Neemann
* Use of this source code is governed by the GPL v3 license
* that can be found in the LICENSE file.
*/
package de.neemann.digital.builder;
import de.neemann.digital.builder.jedec.FuseMapFillerException;
import java.io.IOException;
import java.io.OutputStream;
/**
* Interface used to create Jedec files.
* Every supported device implements this interface.
*
* @param <T> concrete type of {@link ExpressionExporter}
*/
public interface ExpressionExporter<T extends ExpressionExporter> {
/**
* @return builder to add expressions
*/
BuilderInterface getBuilder();
/**
* Gets the pin mapping which is to use/was used.
* You can modify the mapping before getBuilder is called.
* After the export you will find the used pin mapping.
*
* @return the actual pin mapping
*/
PinMap getPinMapping();
/**
* Writes the JEDEC file to the given output stream
*
* @param out the output stream
* @throws FuseMapFillerException FuseMapFillerException
* @throws IOException IOException
* @throws PinMapException PinMapException
*/
void writeTo(OutputStream out) throws FuseMapFillerException, IOException, PinMapException;
}
| hneemann/Digital | src/main/java/de/neemann/digital/builder/ExpressionExporter.java | Java | gpl-3.0 | 1,278 |
package edu.stanford.rsl.conrad.phantom.xcat;
import java.util.Iterator;
import edu.stanford.rsl.conrad.geometry.AbstractShape;
import edu.stanford.rsl.conrad.geometry.AbstractSurface;
import edu.stanford.rsl.conrad.geometry.shapes.compound.CompoundShape;
import edu.stanford.rsl.conrad.geometry.shapes.simple.PointND;
import edu.stanford.rsl.conrad.geometry.splines.SurfaceBSpline;
import edu.stanford.rsl.conrad.geometry.splines.TimeVariantSurfaceBSpline;
import edu.stanford.rsl.conrad.parallel.ParallelThread;
import edu.stanford.rsl.conrad.utils.TessellationUtil;
/**
* Thread to tessellate a SurfaceBSpline or TimeVariantSurfaceBSpline.
*
* @author akmaier
*
*/
public class TessellationThread extends ParallelThread {
private Object tessellationObject;
private double time;
private CompoundShape scene;
/**
* @return the mesh
*/
public CompoundShape getObjects() {
return scene;
}
public TessellationThread (Object tessellationObject, double time){
this.tessellationObject = tessellationObject;
this.time = time;
}
@SuppressWarnings("rawtypes")
@Override
public void execute(){
Object tObject = this;
scene = new CompoundShape();
while (tObject != null){
if (((Iterator)this.tessellationObject).hasNext()){
tObject = ((Iterator)this.tessellationObject).next();
int elementCountU = (int)TessellationUtil.getSamplingU((AbstractSurface) tObject);
int elementCountV = (int)TessellationUtil.getSamplingV((AbstractSurface) tObject);
if (tObject instanceof SurfaceBSpline){
SurfaceBSpline spline = (SurfaceBSpline)tObject;
scene.add(spline.tessellateMesh(elementCountU, elementCountV));
}
if (tObject instanceof TimeVariantSurfaceBSpline){
TimeVariantSurfaceBSpline spline = (TimeVariantSurfaceBSpline)tObject;
AbstractShape mesh = spline.tessellateMesh(elementCountU, elementCountV, time);
scene.add(mesh);
}
} else {
tObject = null;
}
}
}
@Override
public String getProcessName() {
return "Tessellation Thread";
}
}
/*
* Copyright (C) 2010-2014 Andreas Maier
* CONRAD is developed as an Open Source project under the GNU General Public License (GPL).
*/ | YixingHuang/CONRAD | src/edu/stanford/rsl/conrad/phantom/xcat/TessellationThread.java | Java | gpl-3.0 | 2,178 |
var mongoose = require('mongoose');
var characterSchema = new mongoose.Schema({
name: String,
userID: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
inventarID: { type: mongoose.Schema.Types.ObjectId, ref: 'Inventar' },
gender: String,
skincolor: String,
hair: Number,
haircolor: String,
gear: {
head: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' },
body: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' },
legs: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' }
},
costume: {
head: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' },
body: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' },
legs: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' }
},
hp: Number,
weapon: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' },
deaths: Number,
kills: Number,
rounds: Number,
created: { type: Date, default: Date.now }
});
// Updates a character from the database.
characterSchema.methods.update = function(_id, data, callback){
this.findById(_id, function(err, character){
if(err) return callback(err);
if(character){
updateCharacter(character, data, err);
if(err) return callback(err);
else return callback(null);
}
});
}
// Deletes a character from the database.
characterSchema.methods.delete = function(name, callback){
this.findById(name, function(err, character){
if(err) return callback(err);
if(character)
character.remove(function(err){
return callback(err);
});
else
return callback("Could not be removed");
});
}
// Helper function to update every single field in the database if it's in the data-object.
function updateCharacter(character, data, callback){
if("name" in data) character.name = data.name;
if("userID" in data) character.userID = data.userID;
if("inventarID" in data) character.inventarID = data.inventarID;
if("gender" in data) character.gender = data.gender;
if("skincolor" in data) character.skincolor = data.skincolor;
if("hair" in data) character.hair = data.hair;
if("haircolor" in data) character.haircolor = data.haircolor;
if("hp" in data) character.hp = data.hp;
if("weapon" in data) character.weapon = data.weapon;
if("deaths" in data) character.deaths = data.deaths;
if("kills" in data) character.kills = data.kills;
if("rounds" in data) character.rounds = data.rounds;
if("gear" in data){
if("head" in data.gear) character.gear.head = data.gear.head;
if("body" in data.gear) character.gear.body = data.gear.body;
if("legs" in data.gear) character.gear.legs = data.gear.legs;
}
if("costume" in data){
if("head" in data.costume) character.costume.head = data.costume.head;
if("body" in data.costume) character.costume.body = data.costume.body;
if("legs" in data.costume) character.costume.legs = data.costume.legs;
}
character.save(function(err){
if(err) return callback(err)
else return callback(null);
});
}
module.exports = mongoose.model("Character", characterSchema);
| FA15bZombieSurvival/Zurival | models/character.js | JavaScript | gpl-3.0 | 3,251 |
package net.dungeonrealms.game.listener;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.events.PacketListener;
import net.dungeonrealms.DungeonRealms;
import net.dungeonrealms.common.game.database.player.rank.Rank;
import org.bukkit.Bukkit;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
/**
* Created by Brad on 09/06/2016.
*/
public class TabCompleteCommands implements Listener {
private static PacketListener listener;
public void onEnable() {
listener = new PacketAdapter(DungeonRealms.getInstance(), PacketType.Play.Client.TAB_COMPLETE) {
public void onPacketReceiving(PacketEvent event) {
if (event.getPacketType() == PacketType.Play.Client.TAB_COMPLETE) {
// Allow GMs/OPs/DEVs to access tab completion.
if (Rank.isGM(event.getPlayer())) return;
PacketContainer packet = event.getPacket();
String message = (packet.getSpecificModifier(String.class).read(0)).toLowerCase();
if ((message.startsWith("/") || message.startsWith("@"))) event.setCancelled(true);
}
}
};
ProtocolLibrary.getProtocolManager().addPacketListener(listener);
Bukkit.getServer().getPluginManager().registerEvents(this, DungeonRealms.getInstance());
}
public void onDisable() {
ProtocolLibrary.getProtocolManager().removePacketListener(listener);
HandlerList.unregisterAll(this);
}
}
| TheSecretLife/DR-API | game/src/main/java/net/dungeonrealms/game/listener/TabCompleteCommands.java | Java | gpl-3.0 | 1,747 |
import { ExecuteInCurrentWindow, Inject, mutation, StatefulService } from 'services/core';
import {
EPlatformCallResult,
IPlatformState,
TPlatform,
TPlatformCapability,
TStartStreamOptions,
TPlatformCapabilityMap,
} from './index';
import { StreamingService } from 'services/streaming';
import { UserService } from 'services/user';
import { HostsService } from 'services/hosts';
import electron from 'electron';
import { IFacebookStartStreamOptions } from './facebook';
import { StreamSettingsService } from '../settings/streaming';
const VIEWER_COUNT_UPDATE_INTERVAL = 60 * 1000;
/**
* Base class for platforms
* Keeps shared code for all platforms
*/
export abstract class BasePlatformService<T extends IPlatformState> extends StatefulService<T> {
static initialState: IPlatformState = {
streamKey: '',
viewersCount: 0,
settings: null,
isPrepopulated: false,
};
@Inject() protected streamingService: StreamingService;
@Inject() protected userService: UserService;
@Inject() protected hostsService: HostsService;
@Inject() protected streamSettingsService: StreamSettingsService;
abstract readonly platform: TPlatform;
abstract capabilities: Set<TPlatformCapability>;
@ExecuteInCurrentWindow()
hasCapability<T extends TPlatformCapability>(capability: T): this is TPlatformCapabilityMap[T] {
return this.capabilities.has(capability);
}
get mergeUrl() {
const host = this.hostsService.streamlabs;
const token = this.userService.apiToken;
return `https://${host}/slobs/merge/${token}/${this.platform}_account`;
}
averageViewers: number;
peakViewers: number;
private nViewerSamples: number;
async afterGoLive(): Promise<void> {
this.averageViewers = 0;
this.peakViewers = 0;
this.nViewerSamples = 0;
// update viewers count
const runInterval = async () => {
if (this.hasCapability('viewerCount')) {
const count = await this.fetchViewerCount();
this.nViewerSamples += 1;
this.averageViewers =
(this.averageViewers * (this.nViewerSamples - 1) + count) / this.nViewerSamples;
this.peakViewers = Math.max(this.peakViewers, count);
this.SET_VIEWERS_COUNT(count);
}
// stop updating if streaming has stopped
if (this.streamingService.views.isMidStreamMode) {
setTimeout(runInterval, VIEWER_COUNT_UPDATE_INTERVAL);
}
};
if (this.hasCapability('viewerCount')) await runInterval();
}
unlink() {
// unlink platform and reload auth state
// const url = `https://${this.hostsService.streamlabs}/api/v5/slobs/unlink/${this.platform}_account`;
// const headers = authorizedHeaders(this.userService.apiToken!);
// const request = new Request(url, { headers });
// return fetch(request)
// .then(handleResponse)
// .then(_ => this.userService.updateLinkedPlatforms());
electron.remote.shell.openExternal(
`https://${this.hostsService.streamlabs}/dashboard#/settings/account-settings`,
);
}
protected syncSettingsWithLocalStorage() {
// save settings to the local storage
const savedSettings: IFacebookStartStreamOptions = JSON.parse(
localStorage.getItem(this.serviceName) as string,
);
if (savedSettings) this.UPDATE_STREAM_SETTINGS(savedSettings);
this.store.watch(
() => this.state.settings,
() => {
localStorage.setItem(this.serviceName, JSON.stringify(this.state.settings));
},
{ deep: true },
);
}
async validatePlatform() {
return EPlatformCallResult.Success;
}
fetchUserInfo() {
return Promise.resolve({});
}
@mutation()
protected SET_VIEWERS_COUNT(viewers: number) {
this.state.viewersCount = viewers;
}
@mutation()
protected SET_STREAM_KEY(key: string) {
this.state.streamKey = key;
}
@mutation()
protected SET_PREPOPULATED(isPrepopulated: boolean) {
this.state.isPrepopulated = isPrepopulated;
}
@mutation()
protected SET_STREAM_SETTINGS(settings: TStartStreamOptions) {
this.state.settings = settings;
}
@mutation()
protected UPDATE_STREAM_SETTINGS(settingsPatch: Partial<TStartStreamOptions>) {
this.state.settings = { ...this.state.settings, ...settingsPatch };
}
}
| stream-labs/streamlabs-obs | app/services/platforms/base-platform.ts | TypeScript | gpl-3.0 | 4,263 |
#include <cstdio>
#include <cmath>
#include "matrix.h"
#include "vector.h"
#include "quat.h"
using namespace std;
// ----------- Matrix3x3 --------------
Matrix3x3 Matrix3x3::identity = Matrix3x3(1, 0, 0, 0, 1, 0, 0, 0, 1);
Matrix3x3::Matrix3x3()
{
*this = identity;
}
Matrix3x3::Matrix3x3( scalar_t m11, scalar_t m12, scalar_t m13,
scalar_t m21, scalar_t m22, scalar_t m23,
scalar_t m31, scalar_t m32, scalar_t m33)
{
m[0][0] = m11; m[0][1] = m12; m[0][2] = m13;
m[1][0] = m21; m[1][1] = m22; m[1][2] = m23;
m[2][0] = m31; m[2][1] = m32; m[2][2] = m33;
}
Matrix3x3::Matrix3x3(const Vector3 &ivec, const Vector3 &jvec, const Vector3 &kvec)
{
set_row_vector(ivec, 0);
set_row_vector(jvec, 1);
set_row_vector(kvec, 2);
}
Matrix3x3::Matrix3x3(const mat3_t cmat)
{
memcpy(m, cmat, sizeof(mat3_t));
}
Matrix3x3::Matrix3x3(const Matrix4x4 &mat4x4)
{
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
m[i][j] = mat4x4[i][j];
}
}
}
Matrix3x3 operator +(const Matrix3x3 &m1, const Matrix3x3 &m2)
{
Matrix3x3 res;
const scalar_t *op1 = m1.m[0], *op2 = m2.m[0];
scalar_t *dest = res.m[0];
for(int i=0; i<9; i++) {
*dest++ = *op1++ + *op2++;
}
return res;
}
Matrix3x3 operator -(const Matrix3x3 &m1, const Matrix3x3 &m2)
{
Matrix3x3 res;
const scalar_t *op1 = m1.m[0], *op2 = m2.m[0];
scalar_t *dest = res.m[0];
for(int i=0; i<9; i++) {
*dest++ = *op1++ - *op2++;
}
return res;
}
Matrix3x3 operator *(const Matrix3x3 &m1, const Matrix3x3 &m2)
{
Matrix3x3 res;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
res.m[i][j] = m1.m[i][0] * m2.m[0][j] + m1.m[i][1] * m2.m[1][j] + m1.m[i][2] * m2.m[2][j];
}
}
return res;
}
void operator +=(Matrix3x3 &m1, const Matrix3x3 &m2)
{
scalar_t *op1 = m1.m[0];
const scalar_t *op2 = m2.m[0];
for(int i=0; i<9; i++) {
*op1++ += *op2++;
}
}
void operator -=(Matrix3x3 &m1, const Matrix3x3 &m2)
{
scalar_t *op1 = m1.m[0];
const scalar_t *op2 = m2.m[0];
for(int i=0; i<9; i++) {
*op1++ -= *op2++;
}
}
void operator *=(Matrix3x3 &m1, const Matrix3x3 &m2)
{
Matrix3x3 res;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
res.m[i][j] = m1.m[i][0] * m2.m[0][j] + m1.m[i][1] * m2.m[1][j] + m1.m[i][2] * m2.m[2][j];
}
}
memcpy(m1.m, res.m, 9 * sizeof(scalar_t));
}
Matrix3x3 operator *(const Matrix3x3 &mat, scalar_t scalar)
{
Matrix3x3 res;
const scalar_t *mptr = mat.m[0];
scalar_t *dptr = res.m[0];
for(int i=0; i<9; i++) {
*dptr++ = *mptr++ * scalar;
}
return res;
}
Matrix3x3 operator *(scalar_t scalar, const Matrix3x3 &mat)
{
Matrix3x3 res;
const scalar_t *mptr = mat.m[0];
scalar_t *dptr = res.m[0];
for(int i=0; i<9; i++) {
*dptr++ = *mptr++ * scalar;
}
return res;
}
void operator *=(Matrix3x3 &mat, scalar_t scalar)
{
scalar_t *mptr = mat.m[0];
for(int i=0; i<9; i++) {
*mptr++ *= scalar;
}
}
void Matrix3x3::translate(const Vector2 &trans)
{
Matrix3x3 tmat(1, 0, trans.x, 0, 1, trans.y, 0, 0, 1);
*this *= tmat;
}
void Matrix3x3::set_translation(const Vector2 &trans)
{
*this = Matrix3x3(1, 0, trans.x, 0, 1, trans.y, 0, 0, 1);
}
void Matrix3x3::rotate(scalar_t angle)
{
scalar_t cos_a = cos(angle);
scalar_t sin_a = sin(angle);
Matrix3x3 rmat( cos_a, -sin_a, 0,
sin_a, cos_a, 0,
0, 0, 1);
*this *= rmat;
}
void Matrix3x3::set_rotation(scalar_t angle)
{
scalar_t cos_a = cos(angle);
scalar_t sin_a = sin(angle);
*this = Matrix3x3(cos_a, -sin_a, 0, sin_a, cos_a, 0, 0, 0, 1);
}
void Matrix3x3::rotate(const Vector3 &euler_angles)
{
Matrix3x3 xrot, yrot, zrot;
xrot = Matrix3x3( 1, 0, 0,
0, cos(euler_angles.x), -sin(euler_angles.x),
0, sin(euler_angles.x), cos(euler_angles.x));
yrot = Matrix3x3( cos(euler_angles.y), 0, sin(euler_angles.y),
0, 1, 0,
-sin(euler_angles.y), 0, cos(euler_angles.y));
zrot = Matrix3x3( cos(euler_angles.z), -sin(euler_angles.z), 0,
sin(euler_angles.z), cos(euler_angles.z), 0,
0, 0, 1);
*this *= xrot * yrot * zrot;
}
void Matrix3x3::set_rotation(const Vector3 &euler_angles)
{
Matrix3x3 xrot, yrot, zrot;
xrot = Matrix3x3( 1, 0, 0,
0, cos(euler_angles.x), -sin(euler_angles.x),
0, sin(euler_angles.x), cos(euler_angles.x));
yrot = Matrix3x3( cos(euler_angles.y), 0, sin(euler_angles.y),
0, 1, 0,
-sin(euler_angles.y), 0, cos(euler_angles.y));
zrot = Matrix3x3( cos(euler_angles.z), -sin(euler_angles.z), 0,
sin(euler_angles.z), cos(euler_angles.z), 0,
0, 0, 1);
*this = xrot * yrot * zrot;
}
void Matrix3x3::rotate(const Vector3 &axis, scalar_t angle)
{
scalar_t sina = (scalar_t)sin(angle);
scalar_t cosa = (scalar_t)cos(angle);
scalar_t invcosa = 1-cosa;
scalar_t nxsq = axis.x * axis.x;
scalar_t nysq = axis.y * axis.y;
scalar_t nzsq = axis.z * axis.z;
Matrix3x3 xform;
xform.m[0][0] = nxsq + (1-nxsq) * cosa;
xform.m[0][1] = axis.x * axis.y * invcosa - axis.z * sina;
xform.m[0][2] = axis.x * axis.z * invcosa + axis.y * sina;
xform.m[1][0] = axis.x * axis.y * invcosa + axis.z * sina;
xform.m[1][1] = nysq + (1-nysq) * cosa;
xform.m[1][2] = axis.y * axis.z * invcosa - axis.x * sina;
xform.m[2][0] = axis.x * axis.z * invcosa - axis.y * sina;
xform.m[2][1] = axis.y * axis.z * invcosa + axis.x * sina;
xform.m[2][2] = nzsq + (1-nzsq) * cosa;
*this *= xform;
}
void Matrix3x3::set_rotation(const Vector3 &axis, scalar_t angle)
{
scalar_t sina = (scalar_t)sin(angle);
scalar_t cosa = (scalar_t)cos(angle);
scalar_t invcosa = 1-cosa;
scalar_t nxsq = axis.x * axis.x;
scalar_t nysq = axis.y * axis.y;
scalar_t nzsq = axis.z * axis.z;
reset_identity();
m[0][0] = nxsq + (1-nxsq) * cosa;
m[0][1] = axis.x * axis.y * invcosa - axis.z * sina;
m[0][2] = axis.x * axis.z * invcosa + axis.y * sina;
m[1][0] = axis.x * axis.y * invcosa + axis.z * sina;
m[1][1] = nysq + (1-nysq) * cosa;
m[1][2] = axis.y * axis.z * invcosa - axis.x * sina;
m[2][0] = axis.x * axis.z * invcosa - axis.y * sina;
m[2][1] = axis.y * axis.z * invcosa + axis.x * sina;
m[2][2] = nzsq + (1-nzsq) * cosa;
}
void Matrix3x3::scale(const Vector3 &scale_vec)
{
Matrix3x3 smat( scale_vec.x, 0, 0,
0, scale_vec.y, 0,
0, 0, scale_vec.z);
*this *= smat;
}
void Matrix3x3::set_scaling(const Vector3 &scale_vec)
{
*this = Matrix3x3( scale_vec.x, 0, 0,
0, scale_vec.y, 0,
0, 0, scale_vec.z);
}
void Matrix3x3::set_column_vector(const Vector3 &vec, unsigned int col_index)
{
m[0][col_index] = vec.x;
m[1][col_index] = vec.y;
m[2][col_index] = vec.z;
}
void Matrix3x3::set_row_vector(const Vector3 &vec, unsigned int row_index)
{
m[row_index][0] = vec.x;
m[row_index][1] = vec.y;
m[row_index][2] = vec.z;
}
Vector3 Matrix3x3::get_column_vector(unsigned int col_index) const
{
return Vector3(m[0][col_index], m[1][col_index], m[2][col_index]);
}
Vector3 Matrix3x3::get_row_vector(unsigned int row_index) const
{
return Vector3(m[row_index][0], m[row_index][1], m[row_index][2]);
}
void Matrix3x3::transpose()
{
Matrix3x3 tmp = *this;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
m[i][j] = tmp[j][i];
}
}
}
Matrix3x3 Matrix3x3::transposed() const
{
Matrix3x3 res;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
res[i][j] = m[j][i];
}
}
return res;
}
scalar_t Matrix3x3::determinant() const
{
return m[0][0] * (m[1][1]*m[2][2] - m[1][2]*m[2][1]) -
m[0][1] * (m[1][0]*m[2][2] - m[1][2]*m[2][0]) +
m[0][2] * (m[1][0]*m[2][1] - m[1][1]*m[2][0]);
}
Matrix3x3 Matrix3x3::inverse() const
{
// TODO: implement 3x3 inverse
return *this;
}
ostream &operator <<(ostream &out, const Matrix3x3 &mat)
{
for(int i=0; i<3; i++) {
char str[100];
sprintf(str, "[ %12.5f %12.5f %12.5f ]\n", (float)mat.m[i][0], (float)mat.m[i][1], (float)mat.m[i][2]);
out << str;
}
return out;
}
/* ----------------- Matrix4x4 implementation --------------- */
Matrix4x4 Matrix4x4::identity = Matrix4x4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
Matrix4x4::Matrix4x4()
{
*this = identity;
}
Matrix4x4::Matrix4x4( scalar_t m11, scalar_t m12, scalar_t m13, scalar_t m14,
scalar_t m21, scalar_t m22, scalar_t m23, scalar_t m24,
scalar_t m31, scalar_t m32, scalar_t m33, scalar_t m34,
scalar_t m41, scalar_t m42, scalar_t m43, scalar_t m44)
{
m[0][0] = m11; m[0][1] = m12; m[0][2] = m13; m[0][3] = m14;
m[1][0] = m21; m[1][1] = m22; m[1][2] = m23; m[1][3] = m24;
m[2][0] = m31; m[2][1] = m32; m[2][2] = m33; m[2][3] = m34;
m[3][0] = m41; m[3][1] = m42; m[3][2] = m43; m[3][3] = m44;
}
Matrix4x4::Matrix4x4(const mat4_t cmat)
{
memcpy(m, cmat, sizeof(mat4_t));
}
Matrix4x4::Matrix4x4(const Matrix3x3 &mat3x3)
{
reset_identity();
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
m[i][j] = mat3x3[i][j];
}
}
}
Matrix4x4 operator +(const Matrix4x4 &m1, const Matrix4x4 &m2)
{
Matrix4x4 res;
const scalar_t *op1 = m1.m[0], *op2 = m2.m[0];
scalar_t *dest = res.m[0];
for(int i=0; i<16; i++) {
*dest++ = *op1++ + *op2++;
}
return res;
}
Matrix4x4 operator -(const Matrix4x4 &m1, const Matrix4x4 &m2)
{
Matrix4x4 res;
const scalar_t *op1 = m1.m[0], *op2 = m2.m[0];
scalar_t *dest = res.m[0];
for(int i=0; i<16; i++) {
*dest++ = *op1++ - *op2++;
}
return res;
}
/*
Matrix4x4 operator *(const Matrix4x4 &m1, const Matrix4x4 &m2) {
Matrix4x4 res;
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
res.m[i][j] = m1.m[i][0] * m2.m[0][j] + m1.m[i][1] * m2.m[1][j] + m1.m[i][2] * m2.m[2][j] + m1.m[i][3] * m2.m[3][j];
}
}
return res;
}
*/
void operator +=(Matrix4x4 &m1, const Matrix4x4 &m2)
{
scalar_t *op1 = m1.m[0];
const scalar_t *op2 = m2.m[0];
for(int i=0; i<16; i++) {
*op1++ += *op2++;
}
}
void operator -=(Matrix4x4 &m1, const Matrix4x4 &m2)
{
scalar_t *op1 = m1.m[0];
const scalar_t *op2 = m2.m[0];
for(int i=0; i<16; i++) {
*op1++ -= *op2++;
}
}
void operator *=(Matrix4x4 &m1, const Matrix4x4 &m2)
{
Matrix4x4 res;
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
res.m[i][j] = m1.m[i][0] * m2.m[0][j] + m1.m[i][1] * m2.m[1][j] + m1.m[i][2] * m2.m[2][j] + m1.m[i][3] * m2.m[3][j];
}
}
memcpy(m1.m, res.m, 16 * sizeof(scalar_t));
}
Matrix4x4 operator *(const Matrix4x4 &mat, scalar_t scalar)
{
Matrix4x4 res;
const scalar_t *mptr = mat.m[0];
scalar_t *dptr = res.m[0];
for(int i=0; i<16; i++) {
*dptr++ = *mptr++ * scalar;
}
return res;
}
Matrix4x4 operator *(scalar_t scalar, const Matrix4x4 &mat)
{
Matrix4x4 res;
const scalar_t *mptr = mat.m[0];
scalar_t *dptr = res.m[0];
for(int i=0; i<16; i++) {
*dptr++ = *mptr++ * scalar;
}
return res;
}
void operator *=(Matrix4x4 &mat, scalar_t scalar)
{
scalar_t *mptr = mat.m[0];
for(int i=0; i<16; i++) {
*mptr++ *= scalar;
}
}
void Matrix4x4::translate(const Vector3 &trans)
{
Matrix4x4 tmat(1, 0, 0, trans.x, 0, 1, 0, trans.y, 0, 0, 1, trans.z, 0, 0, 0, 1);
*this *= tmat;
}
void Matrix4x4::set_translation(const Vector3 &trans)
{
*this = Matrix4x4(1, 0, 0, trans.x, 0, 1, 0, trans.y, 0, 0, 1, trans.z, 0, 0, 0, 1);
}
void Matrix4x4::rotate(const Vector3 &euler_angles)
{
Matrix3x3 xrot, yrot, zrot;
xrot = Matrix3x3( 1, 0, 0,
0, cos(euler_angles.x), -sin(euler_angles.x),
0, sin(euler_angles.x), cos(euler_angles.x));
yrot = Matrix3x3( cos(euler_angles.y), 0, sin(euler_angles.y),
0, 1, 0,
-sin(euler_angles.y), 0, cos(euler_angles.y));
zrot = Matrix3x3( cos(euler_angles.z), -sin(euler_angles.z), 0,
sin(euler_angles.z), cos(euler_angles.z), 0,
0, 0, 1);
*this *= Matrix4x4(xrot * yrot * zrot);
}
void Matrix4x4::set_rotation(const Vector3 &euler_angles)
{
Matrix3x3 xrot, yrot, zrot;
xrot = Matrix3x3( 1, 0, 0,
0, cos(euler_angles.x), -sin(euler_angles.x),
0, sin(euler_angles.x), cos(euler_angles.x));
yrot = Matrix3x3( cos(euler_angles.y), 0, sin(euler_angles.y),
0, 1, 0,
-sin(euler_angles.y), 0, cos(euler_angles.y));
zrot = Matrix3x3( cos(euler_angles.z), -sin(euler_angles.z), 0,
sin(euler_angles.z), cos(euler_angles.z), 0,
0, 0, 1);
*this = Matrix4x4(xrot * yrot * zrot);
}
void Matrix4x4::rotate(const Vector3 &axis, scalar_t angle)
{
scalar_t sina = (scalar_t)sin(angle);
scalar_t cosa = (scalar_t)cos(angle);
scalar_t invcosa = 1-cosa;
scalar_t nxsq = axis.x * axis.x;
scalar_t nysq = axis.y * axis.y;
scalar_t nzsq = axis.z * axis.z;
Matrix3x3 xform;
xform[0][0] = nxsq + (1-nxsq) * cosa;
xform[0][1] = axis.x * axis.y * invcosa - axis.z * sina;
xform[0][2] = axis.x * axis.z * invcosa + axis.y * sina;
xform[1][0] = axis.x * axis.y * invcosa + axis.z * sina;
xform[1][1] = nysq + (1-nysq) * cosa;
xform[1][2] = axis.y * axis.z * invcosa - axis.x * sina;
xform[2][0] = axis.x * axis.z * invcosa - axis.y * sina;
xform[2][1] = axis.y * axis.z * invcosa + axis.x * sina;
xform[2][2] = nzsq + (1-nzsq) * cosa;
*this *= Matrix4x4(xform);
}
void Matrix4x4::set_rotation(const Vector3 &axis, scalar_t angle)
{
scalar_t sina = (scalar_t)sin(angle);
scalar_t cosa = (scalar_t)cos(angle);
scalar_t invcosa = 1-cosa;
scalar_t nxsq = axis.x * axis.x;
scalar_t nysq = axis.y * axis.y;
scalar_t nzsq = axis.z * axis.z;
reset_identity();
m[0][0] = nxsq + (1-nxsq) * cosa;
m[0][1] = axis.x * axis.y * invcosa - axis.z * sina;
m[0][2] = axis.x * axis.z * invcosa + axis.y * sina;
m[1][0] = axis.x * axis.y * invcosa + axis.z * sina;
m[1][1] = nysq + (1-nysq) * cosa;
m[1][2] = axis.y * axis.z * invcosa - axis.x * sina;
m[2][0] = axis.x * axis.z * invcosa - axis.y * sina;
m[2][1] = axis.y * axis.z * invcosa + axis.x * sina;
m[2][2] = nzsq + (1-nzsq) * cosa;
}
void Matrix4x4::scale(const Vector4 &scale_vec)
{
Matrix4x4 smat( scale_vec.x, 0, 0, 0,
0, scale_vec.y, 0, 0,
0, 0, scale_vec.z, 0,
0, 0, 0, scale_vec.w);
*this *= smat;
}
void Matrix4x4::set_scaling(const Vector4 &scale_vec)
{
*this = Matrix4x4( scale_vec.x, 0, 0, 0,
0, scale_vec.y, 0, 0,
0, 0, scale_vec.z, 0,
0, 0, 0, scale_vec.w);
}
void Matrix4x4::set_column_vector(const Vector4 &vec, unsigned int col_index)
{
m[0][col_index] = vec.x;
m[1][col_index] = vec.y;
m[2][col_index] = vec.z;
m[3][col_index] = vec.w;
}
void Matrix4x4::set_row_vector(const Vector4 &vec, unsigned int row_index)
{
m[row_index][0] = vec.x;
m[row_index][1] = vec.y;
m[row_index][2] = vec.z;
m[row_index][3] = vec.w;
}
Vector4 Matrix4x4::get_column_vector(unsigned int col_index) const
{
return Vector4(m[0][col_index], m[1][col_index], m[2][col_index], m[3][col_index]);
}
Vector4 Matrix4x4::get_row_vector(unsigned int row_index) const
{
return Vector4(m[row_index][0], m[row_index][1], m[row_index][2], m[row_index][3]);
}
void Matrix4x4::transpose()
{
Matrix4x4 tmp = *this;
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
m[i][j] = tmp[j][i];
}
}
}
Matrix4x4 Matrix4x4::transposed() const
{
Matrix4x4 res;
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
res[i][j] = m[j][i];
}
}
return res;
}
scalar_t Matrix4x4::determinant() const
{
scalar_t det11 = (m[1][1] * (m[2][2] * m[3][3] - m[3][2] * m[2][3])) -
(m[1][2] * (m[2][1] * m[3][3] - m[3][1] * m[2][3])) +
(m[1][3] * (m[2][1] * m[3][2] - m[3][1] * m[2][2]));
scalar_t det12 = (m[1][0] * (m[2][2] * m[3][3] - m[3][2] * m[2][3])) -
(m[1][2] * (m[2][0] * m[3][3] - m[3][0] * m[2][3])) +
(m[1][3] * (m[2][0] * m[3][2] - m[3][0] * m[2][2]));
scalar_t det13 = (m[1][0] * (m[2][1] * m[3][3] - m[3][1] * m[2][3])) -
(m[1][1] * (m[2][0] * m[3][3] - m[3][0] * m[2][3])) +
(m[1][3] * (m[2][0] * m[3][1] - m[3][0] * m[2][1]));
scalar_t det14 = (m[1][0] * (m[2][1] * m[3][2] - m[3][1] * m[2][2])) -
(m[1][1] * (m[2][0] * m[3][2] - m[3][0] * m[2][2])) +
(m[1][2] * (m[2][0] * m[3][1] - m[3][0] * m[2][1]));
return m[0][0] * det11 - m[0][1] * det12 + m[0][2] * det13 - m[0][3] * det14;
}
Matrix4x4 Matrix4x4::adjoint() const
{
Matrix4x4 coef;
coef.m[0][0] = (m[1][1] * (m[2][2] * m[3][3] - m[3][2] * m[2][3])) -
(m[1][2] * (m[2][1] * m[3][3] - m[3][1] * m[2][3])) +
(m[1][3] * (m[2][1] * m[3][2] - m[3][1] * m[2][2]));
coef.m[0][1] = (m[1][0] * (m[2][2] * m[3][3] - m[3][2] * m[2][3])) -
(m[1][2] * (m[2][0] * m[3][3] - m[3][0] * m[2][3])) +
(m[1][3] * (m[2][0] * m[3][2] - m[3][0] * m[2][2]));
coef.m[0][2] = (m[1][0] * (m[2][1] * m[3][3] - m[3][1] * m[2][3])) -
(m[1][1] * (m[2][0] * m[3][3] - m[3][0] * m[2][3])) +
(m[1][3] * (m[2][0] * m[3][1] - m[3][0] * m[2][1]));
coef.m[0][3] = (m[1][0] * (m[2][1] * m[3][2] - m[3][1] * m[2][2])) -
(m[1][1] * (m[2][0] * m[3][2] - m[3][0] * m[2][2])) +
(m[1][2] * (m[2][0] * m[3][1] - m[3][0] * m[2][1]));
coef.m[1][0] = (m[0][1] * (m[2][2] * m[3][3] - m[3][2] * m[2][3])) -
(m[0][2] * (m[2][1] * m[3][3] - m[3][1] * m[2][3])) +
(m[0][3] * (m[2][1] * m[3][2] - m[3][1] * m[2][2]));
coef.m[1][1] = (m[0][0] * (m[2][2] * m[3][3] - m[3][2] * m[2][3])) -
(m[0][2] * (m[2][0] * m[3][3] - m[3][0] * m[2][3])) +
(m[0][3] * (m[2][0] * m[3][2] - m[3][0] * m[2][2]));
coef.m[1][2] = (m[0][0] * (m[2][1] * m[3][3] - m[3][1] * m[2][3])) -
(m[0][1] * (m[2][0] * m[3][3] - m[3][0] * m[2][3])) +
(m[0][3] * (m[2][0] * m[3][1] - m[3][0] * m[2][1]));
coef.m[1][3] = (m[0][0] * (m[2][1] * m[3][2] - m[3][1] * m[2][2])) -
(m[0][1] * (m[2][0] * m[3][2] - m[3][0] * m[2][2])) +
(m[0][2] * (m[2][0] * m[3][1] - m[3][0] * m[2][1]));
coef.m[2][0] = (m[0][1] * (m[1][2] * m[3][3] - m[3][2] * m[1][3])) -
(m[0][2] * (m[1][1] * m[3][3] - m[3][1] * m[1][3])) +
(m[0][3] * (m[1][1] * m[3][2] - m[3][1] * m[1][2]));
coef.m[2][1] = (m[0][0] * (m[1][2] * m[3][3] - m[3][2] * m[1][3])) -
(m[0][2] * (m[1][0] * m[3][3] - m[3][0] * m[1][3])) +
(m[0][3] * (m[1][0] * m[3][2] - m[3][0] * m[1][2]));
coef.m[2][2] = (m[0][0] * (m[1][1] * m[3][3] - m[3][1] * m[1][3])) -
(m[0][1] * (m[1][0] * m[3][3] - m[3][0] * m[1][3])) +
(m[0][3] * (m[1][0] * m[3][1] - m[3][0] * m[1][1]));
coef.m[2][3] = (m[0][0] * (m[1][1] * m[3][2] - m[3][1] * m[1][2])) -
(m[0][1] * (m[1][0] * m[3][2] - m[3][0] * m[1][2])) +
(m[0][2] * (m[1][0] * m[3][1] - m[3][0] * m[1][1]));
coef.m[3][0] = (m[0][1] * (m[1][2] * m[2][3] - m[2][2] * m[1][3])) -
(m[0][2] * (m[1][1] * m[2][3] - m[2][1] * m[1][3])) +
(m[0][3] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]));
coef.m[3][1] = (m[0][0] * (m[1][2] * m[2][3] - m[2][2] * m[1][3])) -
(m[0][2] * (m[1][0] * m[2][3] - m[2][0] * m[1][3])) +
(m[0][3] * (m[1][0] * m[2][2] - m[2][0] * m[1][2]));
coef.m[3][2] = (m[0][0] * (m[1][1] * m[2][3] - m[2][1] * m[1][3])) -
(m[0][1] * (m[1][0] * m[2][3] - m[2][0] * m[1][3])) +
(m[0][3] * (m[1][0] * m[2][1] - m[2][0] * m[1][1]));
coef.m[3][3] = (m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2])) -
(m[0][1] * (m[1][0] * m[2][2] - m[2][0] * m[1][2])) +
(m[0][2] * (m[1][0] * m[2][1] - m[2][0] * m[1][1]));
coef.transpose();
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
coef.m[i][j] = j%2 ? -coef.m[i][j] : coef.m[i][j];
if(i%2) coef.m[i][j] = -coef.m[i][j];
}
}
return coef;
}
Matrix4x4 Matrix4x4::inverse() const
{
Matrix4x4 adj = adjoint();
return adj * (1.0f / determinant());
}
ostream &operator <<(ostream &out, const Matrix4x4 &mat)
{
for(int i=0; i<4; i++) {
char str[100];
sprintf(str, "[ %12.5f %12.5f %12.5f %12.5f ]\n", (float)mat.m[i][0], (float)mat.m[i][1], (float)mat.m[i][2], (float)mat.m[i][3]);
out << str;
}
return out;
}
| MutantStargoat/calacirya | libs/vmath/matrix.cc | C++ | gpl-3.0 | 19,498 |
# -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2013 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.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/>.
#
from django.shortcuts import render_to_response, get_object_or_404
from django.views.decorators.cache import cache_page
from weblate.trans import appsettings
from django.core.servers.basehttp import FileWrapper
from django.utils.translation import ugettext as _
import django.utils.translation
from django.template import RequestContext, loader
from django.http import (
HttpResponse, HttpResponseRedirect, HttpResponseNotFound, Http404
)
from django.contrib import messages
from django.contrib.auth.decorators import (
login_required, permission_required, user_passes_test
)
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q, Count, Sum
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.utils.safestring import mark_safe
from weblate.trans.models import (
Project, SubProject, Translation, Unit, Suggestion, Check,
Dictionary, Change, Comment, get_versions
)
from weblate.lang.models import Language
from weblate.trans.checks import CHECKS
from weblate.trans.forms import (
TranslationForm, UploadForm, SimpleUploadForm, ExtraUploadForm, SearchForm,
MergeForm, AutoForm, WordForm, DictUploadForm, ReviewForm, LetterForm,
AntispamForm, CommentForm
)
from weblate.trans.util import join_plural
from weblate.accounts.models import Profile, send_notification_email
import weblate
from whoosh.analysis import StandardAnalyzer, StemmingAnalyzer
import datetime
import logging
import os.path
import json
import csv
from xml.etree import ElementTree
import urllib2
# See https://code.djangoproject.com/ticket/6027
class FixedFileWrapper(FileWrapper):
def __iter__(self):
self.filelike.seek(0)
return self
logger = logging.getLogger('weblate')
def home(request):
'''
Home page of Weblate showing list of projects, stats
and user links if logged in.
'''
projects = Project.objects.all_acl(request.user)
acl_projects = projects
if projects.count() == 1:
projects = SubProject.objects.filter(project=projects[0])
# Warn about not filled in username (usually caused by migration of
# users from older system
if not request.user.is_anonymous() and request.user.get_full_name() == '':
messages.warning(
request,
_('Please set your full name in your profile.')
)
# Load user translations if user is authenticated
usertranslations = None
if request.user.is_authenticated():
profile = request.user.get_profile()
usertranslations = Translation.objects.filter(
language__in=profile.languages.all()
).order_by(
'subproject__project__name', 'subproject__name'
)
# Some stats
top_translations = Profile.objects.order_by('-translated')[:10]
top_suggestions = Profile.objects.order_by('-suggested')[:10]
last_changes = Change.objects.filter(
translation__subproject__project__in=acl_projects,
).order_by( '-timestamp')[:10]
return render_to_response('index.html', RequestContext(request, {
'projects': projects,
'top_translations': top_translations,
'top_suggestions': top_suggestions,
'last_changes': last_changes,
'last_changes_rss': reverse('rss'),
'usertranslations': usertranslations,
}))
def show_checks(request):
'''
List of failing checks.
'''
allchecks = Check.objects.filter(
ignore=False
).values('check').annotate(count=Count('id'))
return render_to_response('checks.html', RequestContext(request, {
'checks': allchecks,
'title': _('Failing checks'),
}))
def show_check(request, name):
'''
Details about failing check.
'''
try:
check = CHECKS[name]
except KeyError:
raise Http404('No check matches the given query.')
checks = Check.objects.filter(
check=name, ignore=False
).values('project__slug').annotate(count=Count('id'))
return render_to_response('check.html', RequestContext(request, {
'checks': checks,
'title': check.name,
'check': check,
}))
def show_check_project(request, name, project):
'''
Show checks failing in a project.
'''
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
try:
check = CHECKS[name]
except KeyError:
raise Http404('No check matches the given query.')
units = Unit.objects.none()
if check.target:
langs = Check.objects.filter(
check=name, project=prj, ignore=False
).values_list('language', flat=True).distinct()
for lang in langs:
checks = Check.objects.filter(
check=name, project=prj, language=lang, ignore=False
).values_list('checksum', flat=True)
res = Unit.objects.filter(
checksum__in=checks,
translation__language=lang,
translation__subproject__project=prj,
translated=True
).values(
'translation__subproject__slug',
'translation__subproject__project__slug'
).annotate(count=Count('id'))
units |= res
if check.source:
checks = Check.objects.filter(
check=name,
project=prj,
language=None,
ignore=False
).values_list(
'checksum', flat=True
)
for subproject in prj.subproject_set.all():
lang = subproject.translation_set.all()[0].language
res = Unit.objects.filter(
checksum__in=checks,
translation__language=lang,
translation__subproject=subproject
).values(
'translation__subproject__slug',
'translation__subproject__project__slug'
).annotate(count=Count('id'))
units |= res
return render_to_response('check_project.html', RequestContext(request, {
'checks': units,
'title': '%s/%s' % (prj.__unicode__(), check.name),
'check': check,
'project': prj,
}))
def show_check_subproject(request, name, project, subproject):
'''
Show checks failing in a subproject.
'''
subprj = get_object_or_404(
SubProject,
slug=subproject,
project__slug=project
)
subprj.check_acl(request)
try:
check = CHECKS[name]
except KeyError:
raise Http404('No check matches the given query.')
units = Unit.objects.none()
if check.target:
langs = Check.objects.filter(
check=name,
project=subprj.project,
ignore=False
).values_list(
'language', flat=True
).distinct()
for lang in langs:
checks = Check.objects.filter(
check=name,
project=subprj.project,
language=lang,
ignore=False
).values_list('checksum', flat=True)
res = Unit.objects.filter(
translation__subproject=subprj,
checksum__in=checks,
translation__language=lang,
translated=True
).values(
'translation__language__code'
).annotate(count=Count('id'))
units |= res
source_checks = []
if check.source:
checks = Check.objects.filter(
check=name, project=subprj.project,
language=None,
ignore=False
).values_list('checksum', flat=True)
lang = subprj.translation_set.all()[0].language
res = Unit.objects.filter(
translation__subproject=subprj,
checksum__in=checks,
translation__language=lang
).count()
if res > 0:
source_checks.append(res)
return render_to_response(
'check_subproject.html',
RequestContext(request, {
'checks': units,
'source_checks': source_checks,
'anychecks': len(units) + len(source_checks) > 0,
'title': '%s/%s' % (subprj.__unicode__(), check.name),
'check': check,
'subproject': subprj,
})
)
def show_languages(request):
return render_to_response('languages.html', RequestContext(request, {
'languages': Language.objects.have_translation(),
'title': _('Languages'),
}))
def show_language(request, lang):
obj = get_object_or_404(Language, code=lang)
last_changes = Change.objects.filter(
translation__language=obj
).order_by('-timestamp')[:10]
dicts = Dictionary.objects.filter(
language=obj
).values_list('project', flat=True).distinct()
return render_to_response('language.html', RequestContext(request, {
'object': obj,
'last_changes': last_changes,
'last_changes_rss': reverse('rss-language', kwargs={'lang': obj.code}),
'dicts': Project.objects.filter(id__in=dicts),
}))
def show_dictionaries(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
dicts = Translation.objects.filter(
subproject__project=obj
).values_list('language', flat=True).distinct()
return render_to_response('dictionaries.html', RequestContext(request, {
'title': _('Dictionaries'),
'dicts': Language.objects.filter(id__in=dicts),
'project': obj,
}))
@login_required
@permission_required('trans.change_dictionary')
def edit_dictionary(request, project, lang):
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
word = get_object_or_404(
Dictionary,
project=prj,
language=lang,
id=request.GET.get('id')
)
if request.method == 'POST':
form = WordForm(request.POST)
if form.is_valid():
word.source = form.cleaned_data['source']
word.target = form.cleaned_data['target']
word.save()
return HttpResponseRedirect(reverse(
'weblate.trans.views.show_dictionary',
kwargs={'project': prj.slug, 'lang': lang.code}
))
else:
form = WordForm(
initial={'source': word.source, 'target': word.target}
)
return render_to_response('edit_dictionary.html', RequestContext(request, {
'title': _('%(language)s dictionary for %(project)s') %
{'language': lang, 'project': prj},
'project': prj,
'language': lang,
'form': form,
}))
@login_required
@permission_required('trans.delete_dictionary')
def delete_dictionary(request, project, lang):
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
word = get_object_or_404(
Dictionary,
project=prj,
language=lang,
id=request.POST.get('id')
)
word.delete()
return HttpResponseRedirect(reverse(
'weblate.trans.views.show_dictionary',
kwargs={'project': prj.slug, 'lang': lang.code})
)
@login_required
@permission_required('trans.upload_dictionary')
def upload_dictionary(request, project, lang):
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
if request.method == 'POST':
form = DictUploadForm(request.POST, request.FILES)
if form.is_valid():
try:
count = Dictionary.objects.upload(
prj,
lang,
request.FILES['file'],
form.cleaned_data['overwrite']
)
if count == 0:
messages.warning(
request,
_('No words to import found in file.')
)
else:
messages.info(
request,
_('Imported %d words from file.') % count
)
except Exception as e:
messages.error(
request,
_('File content merge failed: %s' % unicode(e))
)
else:
messages.error(request, _('Failed to process form!'))
else:
messages.error(request, _('Failed to process form!'))
return HttpResponseRedirect(reverse(
'weblate.trans.views.show_dictionary',
kwargs={'project': prj.slug, 'lang': lang.code}
))
def download_dictionary(request, project, lang):
'''
Exports dictionary.
'''
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
# Parse parameters
export_format = None
if 'format' in request.GET:
export_format = request.GET['format']
if not export_format in ['csv', 'po']:
export_format = 'csv'
# Grab all words
words = Dictionary.objects.filter(
project=prj,
language=lang
).order_by('source')
if export_format == 'csv':
response = HttpResponse(mimetype='text/csv; charset=utf-8')
filename = 'dictionary-%s-%s.csv' % (prj.slug, lang.code)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
writer = csv.writer(response)
for word in words.iterator():
writer.writerow((
word.source.encode('utf8'), word.target.encode('utf8')
))
return response
elif export_format == 'po':
from translate.storage.po import pounit, pofile
response = HttpResponse(mimetype='text/x-po; charset=utf-8')
filename = 'dictionary-%s-%s.po' % (prj.slug, lang.code)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
store = pofile()
site = Site.objects.get_current()
store.updateheader(
add=True,
language=lang.code,
x_generator='Weblate %s' % weblate.VERSION,
project_id_version='%s dictionary for %s' % (lang.name, prj.name),
language_team='%s <http://%s%s>' % (
lang.name,
site.domain,
reverse(
'weblate.trans.views.show_dictionary',
kwargs={'project': prj.slug, 'lang': lang.code}
),
)
)
for word in words.iterator():
unit = pounit(word.source)
unit.target = word.target
store.addunit(unit)
store.savefile(response)
return response
def show_dictionary(request, project, lang):
prj = get_object_or_404(Project, slug=project)
prj.check_acl(request)
lang = get_object_or_404(Language, code=lang)
if (request.method == 'POST'
and request.user.has_perm('trans.add_dictionary')):
form = WordForm(request.POST)
if form.is_valid():
Dictionary.objects.create(
project=prj,
language=lang,
source=form.cleaned_data['source'],
target=form.cleaned_data['target']
)
return HttpResponseRedirect(request.get_full_path())
else:
form = WordForm()
uploadform = DictUploadForm()
words = Dictionary.objects.filter(
project=prj, language=lang
).order_by('source')
limit = request.GET.get('limit', 25)
page = request.GET.get('page', 1)
letterform = LetterForm(request.GET)
if letterform.is_valid() and letterform.cleaned_data['letter'] != '':
words = words.filter(
source__istartswith=letterform.cleaned_data['letter']
)
letter = letterform.cleaned_data['letter']
else:
letter = ''
paginator = Paginator(words, limit)
try:
words = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
words = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
words = paginator.page(paginator.num_pages)
return render_to_response('dictionary.html', RequestContext(request, {
'title': _('%(language)s dictionary for %(project)s') %
{'language': lang, 'project': prj},
'project': prj,
'language': lang,
'words': words,
'form': form,
'uploadform': uploadform,
'letterform': letterform,
'letter': letter,
}))
def show_engage(request, project, lang=None):
# Get project object
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
# Handle language parameter
language = None
if lang is not None:
try:
django.utils.translation.activate(lang)
except:
# Ignore failure on activating language
pass
try:
language = Language.objects.get(code=lang)
except Language.DoesNotExist:
pass
context = {
'object': obj,
'project': obj.name,
'languages': obj.get_language_count(),
'total': obj.get_total(),
'percent': obj.get_translated_percent(language),
'url': obj.get_absolute_url(),
'language': language,
}
# Render text
if language is None:
status_text = _(
'<a href="%(url)s">Translation project for %(project)s</a> '
'currently contains %(total)s strings for translation and is '
'<a href="%(url)s">being translated into %(languages)s languages'
'</a>. Overall, these translations are %(percent)s%% complete.'
)
else:
# Translators: line of text in engagement widget, please use your
# language name instead of English
status_text = _(
'<a href="%(url)s">Translation project for %(project)s</a> into '
'English currently contains %(total)s strings for translation and '
'is %(percent)s%% complete.'
)
if 'English' in status_text:
status_text = status_text.replace('English', language.name)
context['status_text'] = mark_safe(status_text % context)
return render_to_response('engage.html', RequestContext(request, context))
def show_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
dicts = Dictionary.objects.filter(
project=obj
).values_list(
'language', flat=True
).distinct()
last_changes = Change.objects.filter(
translation__subproject__project=obj
).order_by('-timestamp')[:10]
return render_to_response('project.html', RequestContext(request, {
'object': obj,
'dicts': Language.objects.filter(id__in=dicts),
'last_changes': last_changes,
'last_changes_rss': reverse(
'rss-project',
kwargs={'project': obj.slug}
),
}))
def show_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
last_changes = Change.objects.filter(
translation__subproject=obj
).order_by('-timestamp')[:10]
return render_to_response('subproject.html', RequestContext(request, {
'object': obj,
'last_changes': last_changes,
'last_changes_rss': reverse(
'rss-subproject',
kwargs={'subproject': obj.slug, 'project': obj.project.slug}
),
}))
@login_required
@permission_required('trans.automatic_translation')
def auto_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
obj.commit_pending()
autoform = AutoForm(obj, request.POST)
change = None
if not obj.subproject.locked and autoform.is_valid():
if autoform.cleaned_data['inconsistent']:
units = obj.unit_set.filter_type('inconsistent', obj)
elif autoform.cleaned_data['overwrite']:
units = obj.unit_set.all()
else:
units = obj.unit_set.filter(translated=False)
sources = Unit.objects.filter(
translation__language=obj.language,
translated=True
)
if autoform.cleaned_data['subproject'] == '':
sources = sources.filter(
translation__subproject__project=obj.subproject.project
).exclude(
translation=obj
)
else:
subprj = SubProject.objects.get(
project=obj.subproject.project,
slug=autoform.cleaned_data['subproject']
)
sources = sources.filter(translation__subproject=subprj)
for unit in units.iterator():
update = sources.filter(checksum=unit.checksum)
if update.exists():
# Get first entry
update = update[0]
# No save if translation is same
if unit.fuzzy == update.fuzzy and unit.target == update.target:
continue
# Copy translation
unit.fuzzy = update.fuzzy
unit.target = update.target
# Create signle change object for whole merge
if change is None:
change = Change.objects.create(
unit=unit,
translation=unit.translation,
user=request.user
)
# Save unit to backend
unit.save_backend(request, False, False)
messages.info(request, _('Automatic translation completed.'))
else:
messages.error(request, _('Failed to process form!'))
return HttpResponseRedirect(obj.get_absolute_url())
def review_source(request, project, subproject):
'''
Listing of source strings to review.
'''
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if not obj.translation_set.exists():
raise Http404('No translation exists in this subproject.')
# Grab first translation in subproject
# (this assumes all have same source strings)
source = obj.translation_set.all()[0]
# Grab search type and page number
rqtype = request.GET.get('type', 'all')
limit = request.GET.get('limit', 50)
page = request.GET.get('page', 1)
# Fiter units
sources = source.unit_set.filter_type(rqtype, source)
paginator = Paginator(sources, limit)
try:
sources = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
sources = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
sources = paginator.page(paginator.num_pages)
return render_to_response('source-review.html', RequestContext(request, {
'object': obj,
'source': source,
'sources': sources,
'title': _('Review source strings in %s') % obj.__unicode__(),
}))
def show_source(request, project, subproject):
'''
Show source strings summary and checks.
'''
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if not obj.translation_set.exists():
raise Http404('No translation exists in this subproject.')
# Grab first translation in subproject
# (this assumes all have same source strings)
source = obj.translation_set.all()[0]
return render_to_response('source.html', RequestContext(request, {
'object': obj,
'source': source,
'title': _('Source strings in %s') % obj.__unicode__(),
}))
def show_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
last_changes = Change.objects.filter(
translation=obj
).order_by('-timestamp')[:10]
# Check locks
obj.is_locked(request)
# How much is user allowed to configure upload?
if request.user.has_perm('trans.author_translation'):
form = ExtraUploadForm()
elif request.user.has_perm('trans.overwrite_translation'):
form = UploadForm()
else:
form = SimpleUploadForm()
# Is user allowed to do automatic translation?
if request.user.has_perm('trans.automatic_translation'):
autoform = AutoForm(obj)
else:
autoform = None
# Search form for everybody
search_form = SearchForm()
# Review form for logged in users
if request.user.is_anonymous():
review_form = None
else:
review_form = ReviewForm(
initial={
'date': datetime.date.today() - datetime.timedelta(days=31)
}
)
return render_to_response('translation.html', RequestContext(request, {
'object': obj,
'form': form,
'autoform': autoform,
'search_form': search_form,
'review_form': review_form,
'last_changes': last_changes,
'last_changes_rss': reverse(
'rss-translation',
kwargs={
'lang': obj.language.code,
'subproject': obj.subproject.slug,
'project': obj.subproject.project.slug
}
),
}))
@login_required
@permission_required('trans.commit_translation')
def commit_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
obj.commit_pending()
messages.info(request, _('All pending translations were committed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.commit_translation')
def commit_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
obj.commit_pending()
messages.info(request, _('All pending translations were committed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.commit_translation')
def commit_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
obj.commit_pending()
messages.info(request, _('All pending translations were committed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.update_translation')
def update_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
if obj.do_update(request):
messages.info(request, _('All repositories were updated.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.update_translation')
def update_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if obj.do_update(request):
messages.info(request, _('All repositories were updated.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.update_translation')
def update_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if obj.do_update(request):
messages.info(request, _('All repositories were updated.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.push_translation')
def push_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
if obj.do_push(request):
messages.info(request, _('All repositories were pushed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.push_translation')
def push_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if obj.do_push(request):
messages.info(request, _('All repositories were pushed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.push_translation')
def push_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if obj.do_push(request):
messages.info(request, _('All repositories were pushed.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.reset_translation')
def reset_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
if obj.do_reset(request):
messages.info(request, _('All repositories have been reset.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.reset_translation')
def reset_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
if obj.do_reset(request):
messages.info(request, _('All repositories have been reset.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.reset_translation')
def reset_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if obj.do_reset(request):
messages.info(request, _('All repositories have been reset.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_translation')
def lock_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if not obj.is_user_locked(request):
obj.create_lock(request.user, True)
messages.info(request, _('Translation is now locked for you.'))
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
def update_lock(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if not obj.is_user_locked(request):
obj.update_lock_time()
return HttpResponse('ok')
@login_required
@permission_required('trans.lock_translation')
def unlock_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if not obj.is_user_locked(request):
obj.create_lock(None)
messages.info(
request,
_('Translation is now open for translation updates.')
)
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_subproject')
def lock_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
obj.commit_pending()
obj.locked = True
obj.save()
messages.info(
request,
_('Subproject is now locked for translation updates!')
)
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_subproject')
def unlock_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
obj.locked = False
obj.save()
messages.info(
request,
_('Subproject is now open for translation updates.')
)
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_subproject')
def lock_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
obj.commit_pending()
for subproject in obj.subproject_set.all():
subproject.locked = True
subproject.save()
messages.info(
request,
_('All subprojects are now locked for translation updates!')
)
return HttpResponseRedirect(obj.get_absolute_url())
@login_required
@permission_required('trans.lock_subproject')
def unlock_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
for subproject in obj.subproject_set.all():
subproject.locked = False
subproject.save()
messages.info(request, _('Project is now open for translation updates.'))
return HttpResponseRedirect(obj.get_absolute_url())
def download_translation(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
# Retrieve ttkit store to get extension and mime type
store = obj.get_store()
srcfilename = obj.get_filename()
if store.Mimetypes is None:
# Properties files do not expose mimetype
mime = 'text/plain'
else:
mime = store.Mimetypes[0]
if store.Extensions is None:
# Typo in translate-toolkit 1.9, see
# https://github.com/translate/translate/pull/10
if hasattr(store, 'Exensions'):
ext = store.Exensions[0]
else:
ext = 'txt'
else:
ext = store.Extensions[0]
# Construct file name (do not use real filename as it is usually not
# that useful)
filename = '%s-%s-%s.%s' % (project, subproject, lang, ext)
# Django wrapper for sending file
wrapper = FixedFileWrapper(file(srcfilename))
response = HttpResponse(wrapper, mimetype=mime)
# Fill in response headers
response['Content-Disposition'] = 'attachment; filename=%s' % filename
response['Content-Length'] = os.path.getsize(srcfilename)
return response
def bool2str(val):
if val:
return 'on'
return ''
def parse_search_url(request):
# Check where we are
rqtype = request.REQUEST.get('type', 'all')
direction = request.REQUEST.get('dir', 'forward')
pos = request.REQUEST.get('pos', '-1')
try:
pos = int(pos)
except:
pos = -1
# Pre-process search form
if request.method == 'POST':
search_form = SearchForm(request.POST)
else:
search_form = SearchForm(request.GET)
if search_form.is_valid():
search_query = search_form.cleaned_data['q']
search_type = search_form.cleaned_data['search']
if search_type == '':
search_type = 'ftx'
search_source = search_form.cleaned_data['src']
search_target = search_form.cleaned_data['tgt']
search_context = search_form.cleaned_data['ctx']
# Sane defaults
if not search_context and not search_source and not search_target:
search_source = True
search_target = True
search_url = '&q=%s&src=%s&tgt=%s&ctx=%s&search=%s' % (
search_query,
bool2str(search_source),
bool2str(search_target),
bool2str(search_context),
search_type,
)
else:
search_query = ''
search_type = 'ftx'
search_source = True
search_target = True
search_context = False
search_url = ''
if 'date' in request.REQUEST:
search_url += '&date=%s' % request.REQUEST['date']
return (
rqtype,
direction,
pos,
search_query,
search_type,
search_source,
search_target,
search_context,
search_url
)
def get_filter_name(rqtype, search_query):
'''
Returns name of current filter.
'''
if search_query != '':
return _('Search for "%s"') % search_query
if rqtype == 'all':
return None
elif rqtype == 'fuzzy':
return _('Fuzzy strings')
elif rqtype == 'untranslated':
return _('Untranslated strings')
elif rqtype == 'suggestions':
return _('Strings with suggestions')
elif rqtype == 'allchecks':
return _('Strings with any failing checks')
elif rqtype in CHECKS:
return CHECKS[rqtype].name
else:
return None
def translate(request, project, subproject, lang):
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
# Check locks
project_locked, user_locked, own_lock = obj.is_locked(request, True)
locked = project_locked or user_locked
if request.user.is_authenticated():
profile = request.user.get_profile()
antispam = None
else:
profile = None
antispam = AntispamForm()
secondary = None
unit = None
rqtype, direction, pos, search_query, search_type, search_source, search_target, search_context, search_url = parse_search_url(request)
# Any form submitted?
if request.method == 'POST':
# Antispam protection
if not request.user.is_authenticated():
antispam = AntispamForm(request.POST)
if not antispam.is_valid():
# Silently redirect to next entry
return HttpResponseRedirect('%s?type=%s&pos=%d%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
form = TranslationForm(request.POST)
if form.is_valid() and not project_locked:
# Check whether translation is not outdated
obj.check_sync()
try:
try:
unit = Unit.objects.get(
checksum=form.cleaned_data['checksum'],
translation=obj
)
except Unit.MultipleObjectsReturned:
# Possible temporary inconsistency caused by ongoing update
# of repo, let's pretend everyting is okay
unit = Unit.objects.filter(
checksum=form.cleaned_data['checksum'],
translation=obj
)[0]
if 'suggest' in request.POST:
# Handle suggesion saving
user = request.user
if isinstance(user, AnonymousUser):
user = None
if form.cleaned_data['target'] == len(form.cleaned_data['target']) * ['']:
messages.error(request, _('Your suggestion is empty!'))
# Stay on same entry
return HttpResponseRedirect(
'%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
)
)
# Create the suggestion
sug = Suggestion.objects.create(
target=join_plural(form.cleaned_data['target']),
checksum=unit.checksum,
language=unit.translation.language,
project=unit.translation.subproject.project,
user=user)
# Record in change
Change.objects.create(
unit=unit,
action=Change.ACTION_SUGGESTION,
translation=unit.translation,
user=user
)
# Invalidate counts cache
unit.translation.invalidate_cache('suggestions')
# Invite user to become translator if there is nobody else
recent_changes = Change.objects.content().filter(
translation=unit.translation,
).exclude(
user=None
).order_by('-timestamp')
if recent_changes.count() == 0 or True:
messages.info(
request,
_('There is currently no active translator for this translation, please consider becoming a translator as your suggestion might otherwise remain unreviewed.')
)
# Notify subscribed users
subscriptions = Profile.objects.subscribed_new_suggestion(
obj.subproject.project,
obj.language,
request.user
)
for subscription in subscriptions:
subscription.notify_new_suggestion(obj, sug, unit)
# Update suggestion stats
if profile is not None:
profile.suggested += 1
profile.save()
elif not request.user.is_authenticated():
# We accept translations only from authenticated
messages.error(
request,
_('You need to log in to be able to save translations!')
)
elif not request.user.has_perm('trans.save_translation'):
# Need privilege to save
messages.error(
request,
_('You don\'t have privileges to save translations!')
)
elif not user_locked:
# Remember old checks
oldchecks = set(
unit.active_checks().values_list('check', flat=True)
)
# Update unit and save it
unit.target = join_plural(form.cleaned_data['target'])
unit.fuzzy = form.cleaned_data['fuzzy']
saved = unit.save_backend(request)
if saved:
# Get new set of checks
newchecks = set(
unit.active_checks().values_list('check', flat=True)
)
# Did we introduce any new failures?
if newchecks > oldchecks:
# Show message to user
messages.error(
request,
_('Some checks have failed on your translation!')
)
# Stay on same entry
return HttpResponseRedirect(
'%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
)
)
# Redirect to next entry
return HttpResponseRedirect('%s?type=%s&pos=%d%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
except Unit.DoesNotExist:
logger.error(
'message %s disappeared!',
form.cleaned_data['checksum']
)
messages.error(
request,
_('Message you wanted to translate is no longer available!')
)
# Handle translation merging
if 'merge' in request.GET and not locked:
if not request.user.has_perm('trans.save_translation'):
# Need privilege to save
messages.error(
request,
_('You don\'t have privileges to save translations!')
)
else:
try:
mergeform = MergeForm(request.GET)
if mergeform.is_valid():
try:
unit = Unit.objects.get(
checksum=mergeform.cleaned_data['checksum'],
translation=obj
)
except Unit.MultipleObjectsReturned:
# Possible temporary inconsistency caused by ongoing
# update of repo, let's pretend everyting is okay
unit = Unit.objects.filter(
checksum=mergeform.cleaned_data['checksum'],
translation=obj
)[0]
merged = Unit.objects.get(
pk=mergeform.cleaned_data['merge']
)
if unit.checksum != merged.checksum:
messages.error(
request,
_('Can not merge different messages!')
)
else:
# Store unit
unit.target = merged.target
unit.fuzzy = merged.fuzzy
saved = unit.save_backend(request)
# Update stats if there was change
if saved:
profile.translated += 1
profile.save()
# Redirect to next entry
return HttpResponseRedirect('%s?type=%s&pos=%d%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
except Unit.DoesNotExist:
logger.error(
'message %s disappeared!',
form.cleaned_data['checksum']
)
messages.error(
request,
_('Message you wanted to translate is no longer available!')
)
# Handle accepting/deleting suggestions
if not locked and ('accept' in request.GET or 'delete' in request.GET):
# Check for authenticated users
if not request.user.is_authenticated():
messages.error(request, _('You need to log in to be able to manage suggestions!'))
return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
# Parse suggestion ID
if 'accept' in request.GET:
if not request.user.has_perm('trans.accept_suggestion'):
messages.error(request, _('You do not have privilege to accept suggestions!'))
return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
sugid = request.GET['accept']
else:
if not request.user.has_perm('trans.delete_suggestion'):
messages.error(request, _('You do not have privilege to delete suggestions!'))
return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
sugid = request.GET['delete']
try:
sugid = int(sugid)
suggestion = Suggestion.objects.get(pk=sugid)
except:
suggestion = None
if suggestion is not None:
if 'accept' in request.GET:
# Accept suggesiont
suggestion.accept(request)
# Invalidate caches
for unit in Unit.objects.filter(checksum=suggestion.checksum):
unit.translation.invalidate_cache('suggestions')
# Delete suggestion in both cases (accepted ones are no longer
# needed)
suggestion.delete()
else:
messages.error(request, _('Invalid suggestion!'))
# Redirect to same entry for possible editing
return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % (
obj.get_translate_url(),
rqtype,
pos,
search_url
))
reviewform = ReviewForm(request.GET)
if reviewform.is_valid():
allunits = obj.unit_set.review(
reviewform.cleaned_data['date'],
request.user
)
# Review
if direction == 'stay':
units = allunits.filter(position=pos)
elif direction == 'back':
units = allunits.filter(position__lt=pos).order_by('-position')
else:
units = allunits.filter(position__gt=pos)
elif search_query != '':
# Apply search conditions
if search_type == 'exact':
query = Q()
if search_source:
query |= Q(source=search_query)
if search_target:
query |= Q(target=search_query)
if search_context:
query |= Q(context=search_query)
allunits = obj.unit_set.filter(query)
elif search_type == 'substring':
query = Q()
if search_source:
query |= Q(source__icontains=search_query)
if search_target:
query |= Q(target__icontains=search_query)
if search_context:
query |= Q(context__icontains=search_query)
allunits = obj.unit_set.filter(query)
else:
allunits = obj.unit_set.search(
search_query,
search_source,
search_context,
search_target
)
if direction == 'stay':
units = obj.unit_set.filter(position=pos)
elif direction == 'back':
units = allunits.filter(position__lt=pos).order_by('-position')
else:
units = allunits.filter(position__gt=pos)
elif 'checksum' in request.GET:
allunits = obj.unit_set.filter(checksum=request.GET['checksum'])
units = allunits
else:
allunits = obj.unit_set.filter_type(rqtype, obj)
# What unit set is about to show
if direction == 'stay':
units = obj.unit_set.filter(position=pos)
elif direction == 'back':
units = allunits.filter(position__lt=pos).order_by('-position')
else:
units = allunits.filter(position__gt=pos)
# If we failed to get unit above or on no POST
if unit is None:
# Grab actual unit
try:
unit = units[0]
except IndexError:
messages.info(request, _('You have reached end of translating.'))
return HttpResponseRedirect(obj.get_absolute_url())
# Show secondary languages for logged in users
if profile:
secondary_langs = profile.secondary_languages.exclude(
id=unit.translation.language.id
)
project = unit.translation.subproject.project
secondary = Unit.objects.filter(
checksum=unit.checksum,
translated=True,
translation__subproject__project=project,
translation__language__in=secondary_langs,
)
# distinct('target') works with Django 1.4 so let's emulate that
# based on presumption we won't get too many results
targets = {}
res = []
for lang in secondary:
if lang.target in targets:
continue
targets[lang.target] = 1
res.append(lang)
secondary = res
# Prepare form
form = TranslationForm(initial={
'checksum': unit.checksum,
'target': (unit.translation.language, unit.get_target_plurals()),
'fuzzy': unit.fuzzy,
})
total = obj.unit_set.all().count()
filter_count = allunits.count()
return render_to_response(
'translate.html',
RequestContext(request, {
'object': obj,
'unit': unit,
'last_changes': unit.change_set.all()[:10],
'total': total,
'type': rqtype,
'filter_name': get_filter_name(rqtype, search_query),
'filter_count': filter_count,
'filter_pos': filter_count + 1 - units.count(),
'form': form,
'antispam': antispam,
'comment_form': CommentForm(),
'target_language': obj.language.code.replace('_', '-').lower(),
'update_lock': own_lock,
'secondary': secondary,
'search_query': search_query,
'search_url': search_url,
'search_source': bool2str(search_source),
'search_type': search_type,
'search_target': bool2str(search_target),
'search_context': bool2str(search_context),
'locked': locked,
'user_locked': user_locked,
'project_locked': project_locked,
},
))
@login_required
def comment(request, pk):
'''
Adds new comment.
'''
obj = get_object_or_404(Unit, pk=pk)
obj.check_acl(request)
if request.POST.get('type', '') == 'source':
lang = None
else:
lang = obj.translation.language
form = CommentForm(request.POST)
if form.is_valid():
new_comment = Comment.objects.create(
user=request.user,
checksum=obj.checksum,
project=obj.translation.subproject.project,
comment=form.cleaned_data['comment'],
language=lang
)
Change.objects.create(
unit=obj,
action=Change.ACTION_COMMENT,
translation=obj.translation,
user=request.user
)
# Invalidate counts cache
if lang is None:
obj.translation.invalidate_cache('sourcecomments')
else:
obj.translation.invalidate_cache('targetcomments')
messages.info(request, _('Posted new comment'))
# Notify subscribed users
subscriptions = Profile.objects.subscribed_new_comment(
obj.translation.subproject.project,
lang,
request.user
)
for subscription in subscriptions:
subscription.notify_new_comment(obj, new_comment)
# Notify upstream
if lang is None and obj.translation.subproject.report_source_bugs != '':
send_notification_email(
'en',
obj.translation.subproject.report_source_bugs,
'new_comment',
obj.translation,
{
'unit': obj,
'comment': new_comment,
'subproject': obj.translation.subproject,
},
from_email=request.user.email,
)
else:
messages.error(request, _('Failed to add comment!'))
return HttpResponseRedirect(obj.get_absolute_url())
def get_string(request, checksum):
'''
AJAX handler for getting raw string.
'''
units = Unit.objects.filter(checksum=checksum)
if units.count() == 0:
return HttpResponse('')
units[0].check_acl(request)
return HttpResponse(units[0].get_source_plurals()[0])
def get_similar(request, unit_id):
'''
AJAX handler for getting similar strings.
'''
unit = get_object_or_404(Unit, pk=int(unit_id))
unit.check_acl(request)
similar_units = Unit.objects.similar(unit)
# distinct('target') works with Django 1.4 so let's emulate that
# based on presumption we won't get too many results
targets = {}
res = []
for similar in similar_units:
if similar.target in targets:
continue
targets[similar.target] = 1
res.append(similar)
similar = res
return render_to_response('js/similar.html', RequestContext(request, {
'similar': similar,
}))
def get_other(request, unit_id):
'''
AJAX handler for same strings in other subprojects.
'''
unit = get_object_or_404(Unit, pk=int(unit_id))
unit.check_acl(request)
other = Unit.objects.same(unit)
rqtype, direction, pos, search_query, search_type, search_source, search_target, search_context, search_url = parse_search_url(request)
return render_to_response('js/other.html', RequestContext(request, {
'other': other,
'unit': unit,
'type': rqtype,
'search_url': search_url,
}))
def get_dictionary(request, unit_id):
'''
Lists words from dictionary for current translation.
'''
unit = get_object_or_404(Unit, pk=int(unit_id))
unit.check_acl(request)
words = set()
# Prepare analyzers
# - standard analyzer simply splits words
# - stemming extracts stems, to catch things like plurals
analyzers = (StandardAnalyzer(), StemmingAnalyzer())
# Extract words from all plurals and from context
for text in unit.get_source_plurals() + [unit.context]:
for analyzer in analyzers:
words = words.union([token.text for token in analyzer(text)])
# Grab all words in the dictionary
dictionary = Dictionary.objects.filter(
project = unit.translation.subproject.project,
language = unit.translation.language
)
if len(words) == 0:
# No extracted words, no dictionary
dictionary = dictionary.none()
else:
# Build the query (can not use __in as we want case insensitive lookup)
query = Q()
for word in words:
query |= Q(source__iexact=word)
# Filter dictionary
dictionary = dictionary.filter(query)
return render_to_response('js/dictionary.html', RequestContext(request, {
'dictionary': dictionary,
}))
@login_required
@permission_required('trans.ignore_check')
def ignore_check(request, check_id):
obj = get_object_or_404(Check, pk=int(check_id))
obj.project.check_acl(request)
# Mark check for ignoring
obj.ignore = True
obj.save()
# Invalidate caches
for unit in Unit.objects.filter(checksum=obj.checksum):
unit.translation.invalidate_cache()
# response for AJAX
return HttpResponse('ok')
@login_required
@permission_required('trans.upload_translation')
def upload_translation(request, project, subproject, lang):
'''
Handling of translation uploads.
'''
obj = get_object_or_404(
Translation,
language__code=lang,
subproject__slug=subproject,
subproject__project__slug=project,
enabled=True
)
obj.check_acl(request)
if not obj.is_locked(request) and request.method == 'POST':
if request.user.has_perm('trans.author_translation'):
form = ExtraUploadForm(request.POST, request.FILES)
elif request.user.has_perm('trans.overwrite_translation'):
form = UploadForm(request.POST, request.FILES)
else:
form = SimpleUploadForm(request.POST, request.FILES)
if form.is_valid():
if request.user.has_perm('trans.author_translation') and form.cleaned_data['author_name'] != '' and form.cleaned_data['author_email'] != '':
author = '%s <%s>' % (form.cleaned_data['author_name'], form.cleaned_data['author_email'])
else:
author = None
if request.user.has_perm('trans.overwrite_translation'):
overwrite = form.cleaned_data['overwrite']
else:
overwrite = False
try:
ret = obj.merge_upload(request, request.FILES['file'], overwrite, author, merge_header=form.cleaned_data['merge_header'])
if ret:
messages.info(request, _('File content successfully merged into translation.'))
else:
messages.info(request, _('There were no new strings in uploaded file.'))
except Exception as e:
messages.error(request, _('File content merge failed: %s' % unicode(e)))
return HttpResponseRedirect(obj.get_absolute_url())
def not_found(request):
'''
Error handler showing list of available projects.
'''
template = loader.get_template('404.html')
return HttpResponseNotFound(
template.render(RequestContext(request, {
'request_path': request.path,
'title': _('Page Not Found'),
'projects': Project.objects.all_acl(request.user),
}
)))
# Cache this page for one month, it should not really change much
@cache_page(30 * 24 * 3600)
def js_config(request):
'''
Generates settings for javascript. Includes things like
API keys for translaiton services or list of languages they
support.
'''
# Apertium support
if appsettings.MT_APERTIUM_KEY is not None and appsettings.MT_APERTIUM_KEY != '':
try:
listpairs = urllib2.urlopen('http://api.apertium.org/json/listPairs?key=%s' % appsettings.MT_APERTIUM_KEY)
pairs = listpairs.read()
parsed = json.loads(pairs)
apertium_langs = [p['targetLanguage'] for p in parsed['responseData'] if p['sourceLanguage'] == 'en']
except Exception as e:
logger.error('failed to get supported languages from Apertium, using defaults (%s)', str(e))
apertium_langs = ['gl', 'ca', 'es', 'eo']
else:
apertium_langs = None
# Microsoft translator support
if appsettings.MT_MICROSOFT_KEY is not None and appsettings.MT_MICROSOFT_KEY != '':
try:
listpairs = urllib2.urlopen('http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appID=%s' % appsettings.MT_MICROSOFT_KEY)
data = listpairs.read()
parsed = ElementTree.fromstring(data)
microsoft_langs = [p.text for p in parsed.getchildren()]
except Exception as e:
logger.error('failed to get supported languages from Microsoft, using defaults (%s)', str(e))
microsoft_langs = [
'ar', 'bg', 'ca', 'zh-CHS', 'zh-CHT', 'cs', 'da', 'nl', 'en',
'et', 'fi', 'fr', 'de', 'el', 'ht', 'he', 'hi', 'mww', 'hu',
'id', 'it', 'ja', 'ko', 'lv', 'lt', 'no', 'fa', 'pl', 'pt',
'ro', 'ru', 'sk', 'sl', 'es', 'sv', 'th', 'tr', 'uk', 'vi'
]
else:
microsoft_langs = None
return render_to_response('js/config.js', RequestContext(request, {
'apertium_langs': apertium_langs,
'microsoft_langs': microsoft_langs,
}),
mimetype = 'application/javascript')
def about(request):
context = {}
versions = get_versions()
totals = Profile.objects.aggregate(Sum('translated'), Sum('suggested'))
total_strings = 0
for project in SubProject.objects.iterator():
try:
total_strings += project.translation_set.all()[0].total
except Translation.DoesNotExist:
pass
context['title'] = _('About Weblate')
context['total_translations'] = totals['translated__sum']
context['total_suggestions'] = totals['suggested__sum']
context['total_users'] = Profile.objects.count()
context['total_strings'] = total_strings
context['total_languages'] = Language.objects.filter(
translation__total__gt=0
).distinct().count()
context['total_checks'] = Check.objects.count()
context['ignored_checks'] = Check.objects.filter(ignore=True).count()
context['versions'] = versions
return render_to_response('about.html', RequestContext(request, context))
@user_passes_test(lambda u: u.has_perm('trans.commit_translation') or u.has_perm('trans.update_translation'))
def git_status_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
return render_to_response('js/git-status.html', RequestContext(request, {
'object': obj,
}))
@user_passes_test(lambda u: u.has_perm('trans.commit_translation') or u.has_perm('trans.update_translation'))
def git_status_subproject(request, project, subproject):
obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
obj.check_acl(request)
return render_to_response('js/git-status.html', RequestContext(request, {
'object': obj,
}))
@user_passes_test(lambda u: u.has_perm('trans.commit_translation') or u.has_perm('trans.update_translation'))
def git_status_translation(request, project, subproject, lang):
obj = get_object_or_404(Translation, language__code=lang, subproject__slug=subproject, subproject__project__slug=project, enabled=True)
obj.check_acl(request)
return render_to_response('js/git-status.html', RequestContext(request, {
'object': obj,
}))
def data_root(request):
site = Site.objects.get_current()
return render_to_response('data-root.html', RequestContext(request, {
'site_domain': site.domain,
'api_docs': weblate.get_doc_url('api', 'exports'),
'rss_docs': weblate.get_doc_url('api', 'rss'),
'projects': Project.objects.all_acl(request.user),
}))
def data_project(request, project):
obj = get_object_or_404(Project, slug=project)
obj.check_acl(request)
site = Site.objects.get_current()
return render_to_response('data.html', RequestContext(request, {
'object': obj,
'site_domain': site.domain,
'api_docs': weblate.get_doc_url('api', 'exports'),
'rss_docs': weblate.get_doc_url('api', 'rss'),
}))
| power12317/weblate | weblate/trans/views.py | Python | gpl-3.0 | 68,329 |
package app.la2008.com.ar.la2008.interfaces;
public interface ObjectSelected {
void select(Object object);
}
| gdconde/la2008 | app/src/main/java/app/la2008/com/ar/la2008/interfaces/ObjectSelected.java | Java | gpl-3.0 | 114 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="ru_RU">
<context>
<name>AboutDialog</name>
<message>
<location filename="about.ui" line="20"/>
<source>About QProtractor</source>
<translation>О QProtractor</translation>
</message>
<message utf8="true">
<location filename="about.ui" line="57"/>
<source>QProtractor
©2011 Alexey Guseynov (kibergus)</source>
<translation>QProtractor
©2011 Гусейнов Алексей (kibergus)</translation>
</message>
<message>
<location filename="about.ui" line="79"/>
<source>Controls:
Move protractor with left mouse button pressed.
Rotate protractor with right mouse button pressed.
Watch for current rotation angle near top edge of the tool.
Resize protractor with scroll.
Use double click to grab mouse control and measure
angle by pointing target with cursor.
Use right mouse button click for menu.
Hint:
Adjust protractor to your needs and use
menu->"Save state" to make this configuration default.</source>
<oldsource>Controls:
Move protractor with left mouse button pressed.
Rotate protractor with right mouse button presed.
Watch for current rotation angle near top edge of the tool.
Resize protractor with scroll.
Use double click to grab mouse control and measure
angle by pointing target with cursor.
Use right mouse button click for menu.
Hint:
Adjust protractor to your needs and use
menu->"Save state" to make this configuration default.</oldsource>
<translation>Управление:
Передвигайте транспортир с зажатой левой кнопной мыши.
Крутите транспортир с зажатой правой кнопкой мыши.
Текущий угол поворота отображается вверху.
Масштабируйте транспортир колесом мыши.
Двойной клик захватывает курсор мыши и позволяет
измерять угол указывая курсором на желаемую точку.
Клик правой кнопкой открывает меню.
Подсказка:
Настройте транспортир под свои нужды и сохраните эти
настройки выбрав пункт меню "Сохранить".</translation>
</message>
</context>
<context>
<name>Protractor</name>
<message>
<location filename="protractor.cpp" line="35"/>
<source>Protractor</source>
<translation>Транспортир</translation>
</message>
<message>
<location filename="protractor.cpp" line="91"/>
<source>Rotate &right</source>
<translation>Ноль справа (&R)</translation>
</message>
<message>
<location filename="protractor.cpp" line="94"/>
<source>Rotate &up</source>
<translation>Ноль вверху (&U)</translation>
</message>
<message>
<location filename="protractor.cpp" line="97"/>
<source>Rotate &left</source>
<translation>Ноль слева (&L)</translation>
</message>
<message>
<location filename="protractor.cpp" line="100"/>
<source>Rotate &down</source>
<translation>Ноль внизу (&D)</translation>
</message>
<message>
<location filename="protractor.cpp" line="105"/>
<source>Re&verse</source>
<oldsource>&Reverse</oldsource>
<translation>В другую сторону (&V)</translation>
</message>
<message>
<location filename="protractor.cpp" line="108"/>
<source>Change &units</source>
<translation>Градусы/радианы (&U)</translation>
</message>
<message>
<location filename="protractor.cpp" line="113"/>
<source>&Save state</source>
<translation>Сохранить (&S)</translation>
</message>
<message>
<location filename="protractor.cpp" line="116"/>
<source>&About/help</source>
<translation>О программе/справка (&A)</translation>
</message>
<message>
<location filename="protractor.cpp" line="119"/>
<source>E&xit</source>
<translation>Выход (&X)</translation>
</message>
</context>
</TS>
| kellpossible/qProtractor | qprotractor_ru.ts | TypeScript | gpl-3.0 | 4,500 |
package org.usfirst.frc.team6162.robot;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SampleRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* This is a demo program showing the use of the RobotDrive class. The
* SampleRobot class is the base of a robot application that will automatically
* call your Autonomous and OperatorControl methods at the right time as
* controlled by the switches on the driver station or the field controls.
*
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SampleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*
* WARNING: While it may look like a good choice to use for your code if you're
* inexperienced, don't. Unless you know what you are doing, complex code will
* be much more difficult under this system. Use IterativeRobot or Command-Based
* instead if you're new.
*/
public class Robot extends SampleRobot {
RobotDrive myRobot = new RobotDrive(0, 1,2,3);
Joystick stick = new Joystick(0);
final String defaultAuto = "Default";
final String customAuto = "My Auto";
SendableChooser<String> chooser = new SendableChooser<>();
public Robot() {
myRobot.setExpiration(0.1);
}
@Override
public void robotInit() {
chooser.addDefault("Default Auto", defaultAuto);
chooser.addObject("My Auto", customAuto);
SmartDashboard.putData("Auto modes", chooser);
}
/**
* This autonomous (along with the chooser code above) shows how to select
* between different autonomous modes using the dashboard. The sendable
* chooser code works with the Java SmartDashboard. If you prefer the
* LabVIEW Dashboard, remove all of the chooser code and uncomment the
* getString line to get the auto name from the text box below the Gyro
*
* You can add additional auto modes by adding additional comparisons to the
* if-else structure below with additional strings. If using the
* SendableChooser make sure to add them to the chooser code above as well.
*/
@Override
public void autonomous() {
String autoSelected = chooser.getSelected();
// String autoSelected = SmartDashboard.getString("Auto Selector",
// defaultAuto);
System.out.println("Auto selected: " + autoSelected);
switch (autoSelected) {
case customAuto:
myRobot.setSafetyEnabled(false);
myRobot.drive(0.1, 0.1); // spin at half speed
Timer.delay(2.0); // for 2 seconds
myRobot.drive(0.2, -0.2); // stop robot
break;
case defaultAuto:
default:
myRobot.setSafetyEnabled(false);
myRobot.drive(0.1, 0.1); // drive forwards half speed
Timer.delay(2.0); // for 2 seconds
myRobot.drive(0.2, -0.2); // stop robot
break;
}
}
/**
* Runs the motors with arcade steering.
*/
@Override
public void operatorControl() {
myRobot.setSafetyEnabled(true);
while (isOperatorControl() && isEnabled()) {
myRobot.arcadeDrive(stick); // drive with arcade style (use right
// stick)
Timer.delay(0.005); // wait for a motor update time
}
}
/**
* Runs during test mode
*/
@Override
public void test() {
}
}
| wjaneal/liastem | SampleAutonomous/src/org/usfirst/frc/team6162/robot/Robot.java | Java | gpl-3.0 | 3,396 |
/*
This file is part of Subsonic.
Subsonic 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.
Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2010 (C) Sindre Mehus
*/
package net.nullsum.audinaut.util;
import android.content.Context;
/**
* @author Sindre Mehus
*/
public abstract class SilentBackgroundTask<T> extends BackgroundTask<T> {
public SilentBackgroundTask(Context context) {
super(context);
}
@Override
public void execute() {
queue.offer(task = new Task());
}
@Override
protected void done(T result) {
// Don't do anything unless overriden
}
@Override
public void updateProgress(String message) {
}
}
| nvllsvm/Audinaut | app/src/main/java/net/nullsum/audinaut/util/SilentBackgroundTask.java | Java | gpl-3.0 | 1,204 |
<?php
namespace InstagramAPI\Request;
use InstagramAPI\Constants;
use InstagramAPI\Response;
use InstagramAPI\Response\Model\Item;
use InstagramAPI\Signatures;
use InstagramAPI\Utils;
/**
* Functions for interacting with media items from yourself and others.
*
* @see Usertag for functions that let you tag people in media.
*/
class Media extends RequestCollection
{
/**
* Get detailed media information.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\MediaInfoResponse
*/
public function getInfo(
$mediaId)
{
return $this->ig->request("media/{$mediaId}/info/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('media_id', $mediaId)
->getResponse(new Response\MediaInfoResponse());
}
/**
* Delete a media item.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
* @param string $mediaType The type of the media item you are deleting. One of: "PHOTO", "VIDEO"
* "ALBUM", or the raw value of the Item's "getMediaType()" function.
*
* @throws \InvalidArgumentException
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\MediaDeleteResponse
*/
public function delete(
$mediaId,
$mediaType = 'PHOTO')
{
if (ctype_digit($mediaType) || is_int($mediaType)) {
if ($mediaType == Item::PHOTO) {
$mediaType = 'PHOTO';
} elseif ($mediaType == Item::VIDEO) {
$mediaType = 'VIDEO';
} elseif ($mediaType == Item::ALBUM) {
$mediaType = 'ALBUM';
}
}
if (!in_array($mediaType, ['PHOTO', 'VIDEO', 'ALBUM'], true)) {
throw new \InvalidArgumentException(sprintf('"%s" is not a valid media type.', $mediaType));
}
return $this->ig->request("media/{$mediaId}/delete/")
->addParam('media_type', $mediaType)
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('media_id', $mediaId)
->getResponse(new Response\MediaDeleteResponse());
}
/**
* Edit media.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
* @param string $captionText Caption text.
* @param null|string $usertags (optional) Special JSON string with user tagging instructions,
* if you want to modify the user tags.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\EditMediaResponse
*
* @see Usertag::tagMedia() for an example of proper $usertags parameter formatting.
* @see Usertag::untagMedia() for an example of proper $usertags parameter formatting.
*/
public function edit(
$mediaId,
$captionText = '',
$usertags = null)
{
$request = $this->ig->request("media/{$mediaId}/edit_media/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('caption_text', $captionText);
if (!is_null($usertags)) {
$request->addPost('usertags', $usertags);
}
return $request->getResponse(new Response\EditMediaResponse());
}
/**
* Like a media item.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\GenericResponse
*/
public function like(
$mediaId)
{
return $this->ig->request("media/{$mediaId}/like/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('media_id', $mediaId)
->getResponse(new Response\GenericResponse());
}
/**
* Unlike a media item.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\GenericResponse
*/
public function unlike(
$mediaId)
{
return $this->ig->request("media/{$mediaId}/unlike/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('media_id', $mediaId)
->getResponse(new Response\GenericResponse());
}
/**
* Get feed of your liked media.
*
* @param null|string $maxId Next "maximum ID", used for pagination.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\LikeFeedResponse
*/
public function getLikedFeed(
$maxId = null)
{
$request = $this->ig->request('feed/liked/');
if (!is_null($maxId)) {
$request->addParam('max_id', $maxId);
}
return $request->getResponse(new Response\LikeFeedResponse());
}
/**
* Get list of users who liked a media item.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\MediaLikersResponse
*/
public function getLikers(
$mediaId)
{
return $this->ig->request("media/{$mediaId}/likers/")->getResponse(new Response\MediaLikersResponse());
}
/**
* Get a simplified, chronological list of users who liked a media item.
*
* WARNING! DANGEROUS! Although this function works, we don't know
* whether it's used by Instagram's app right now. If it isn't used by
* the app, then you can easily get BANNED for using this function!
*
* If you call this function, you do that AT YOUR OWN RISK and you
* risk losing your Instagram account! This notice will be removed if
* the function is safe to use. Otherwise this whole function will
* be removed someday, if it wasn't safe.
*
* Only use this if you are OK with possibly losing your account!
*
* TODO: Research when/if the official app calls this function.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\MediaLikersResponse
*/
public function getLikersChrono(
$mediaId)
{
return $this->ig->request("media/{$mediaId}/likers_chrono/")->getResponse(new Response\MediaLikersResponse());
}
/**
* Enable comments for a media item.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\GenericResponse
*/
public function enableComments(
$mediaId)
{
return $this->ig->request("media/{$mediaId}/enable_comments/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_csrftoken', $this->ig->client->getToken())
->setSignedPost(false)
->getResponse(new Response\GenericResponse());
}
/**
* Disable comments for a media item.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\GenericResponse
*/
public function disableComments(
$mediaId)
{
return $this->ig->request("media/{$mediaId}/disable_comments/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_csrftoken', $this->ig->client->getToken())
->setSignedPost(false)
->getResponse(new Response\GenericResponse());
}
/**
* Post a comment on a media item.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
* @param string $commentText Your comment text.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\CommentResponse
*/
public function comment(
$mediaId,
$commentText)
{
return $this->ig->request("media/{$mediaId}/comment/")
->addPost('user_breadcrumb', Utils::generateUserBreadcrumb(mb_strlen($commentText)))
->addPost('idempotence_token', Signatures::generateUUID(true))
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('comment_text', $commentText)
->addPost('containermodule', 'comments_feed_timeline')
->addPost('radio_type', 'wifi-none')
->getResponse(new Response\CommentResponse());
}
/**
* Get media comments.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
* @param null|string $maxId Next "maximum ID", used for pagination.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\MediaCommentsResponse
*/
public function getComments(
$mediaId,
$maxId = null)
{
return $this->ig->request("media/{$mediaId}/comments/")
->addParam('ig_sig_key_version', Constants::SIG_KEY_VERSION)
->addParam('max_id', $maxId)
->getResponse(new Response\MediaCommentsResponse());
}
/**
* Delete a comment.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
* @param string $commentId The comment's ID.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\DeleteCommentResponse
*/
public function deleteComment(
$mediaId,
$commentId)
{
return $this->ig->request("media/{$mediaId}/comment/{$commentId}/delete/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->getResponse(new Response\DeleteCommentResponse());
}
/**
* Delete multiple comments.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
* @param string|string[] $commentIds The IDs of one or more comments to delete.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\DeleteCommentResponse
*/
public function deleteComments(
$mediaId,
$commentIds)
{
if (is_array($commentIds)) {
$commentIds = implode(',', $commentIds);
}
return $this->ig->request("media/{$mediaId}/comment/bulk_delete/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('comment_ids_to_delete', $commentIds)
->getResponse(new Response\DeleteCommentResponse());
}
/**
* Like a comment.
*
* @param string $commentId The comment's ID.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\CommentLikeUnlikeResponse
*/
public function likeComment(
$commentId)
{
return $this->ig->request("media/{$commentId}/comment_like/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->getResponse(new Response\CommentLikeUnlikeResponse());
}
/**
* Unlike a comment.
*
* @param string $commentId The comment's ID.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\CommentLikeUnlikeResponse
*/
public function unlikeComment(
$commentId)
{
return $this->ig->request("media/{$commentId}/comment_unlike/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->getResponse(new Response\CommentLikeUnlikeResponse());
}
/**
* Translates comments and/or media captions.
*
* Note that the text will be translated to American English (en-US).
*
* @param string|string[] $commentIds The IDs of one or more comments and/or media IDs
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\TranslateResponse
*/
public function translateComments(
$commentIds)
{
if (is_array($commentIds)) {
$commentIds = implode(',', $commentIds);
}
return $this->ig->request("language/bulk_translate/?comment_ids={$commentIds}")
->getResponse(new Response\TranslateResponse());
}
/**
* Save a media item.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\SaveAndUnsaveMedia
*/
public function save(
$mediaId)
{
return $this->ig->request("media/{$mediaId}/save/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->getResponse(new Response\SaveAndUnsaveMedia());
}
/**
* Unsave a media item.
*
* @param string $mediaId The media ID in Instagram's internal format (ie "3482384834_43294").
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\SaveAndUnsaveMedia
*/
public function unsave(
$mediaId)
{
return $this->ig->request("media/{$mediaId}/unsave/")
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->getResponse(new Response\SaveAndUnsaveMedia());
}
/**
* Get saved media items feed.
*
* @param null|string $maxId Next "maximum ID", used for pagination.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\SavedFeedResponse
*/
public function getSavedFeed(
$maxId = null)
{
$request = $this->ig->request('feed/saved/')
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken());
if (!is_null($maxId)) {
$request->addParam('max_id', $maxId);
}
return $request->getResponse(new Response\SavedFeedResponse());
}
/**
* Get blocked media.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\BlockedMediaResponse
*/
public function getBlockedMedia()
{
return $this->ig->request('media/blocked/')
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->getResponse(new Response\BlockedMediaResponse());
}
}
| wowDaiver/Instagram-API | src/Request/Media.php | PHP | gpl-3.0 | 16,462 |
/*
* Twidere - Twitter client for Android
*
* Copyright (C) 2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pahans.kichibichiya.model;
public abstract class ListAction {
public abstract long getId();
public abstract String getName();
public String getSummary() {
return null;
}
public void onClick() {
}
public boolean onLongClick() {
return false;
}
@Override
public final String toString() {
return getName();
}
}
| pahans/Kichibichiya | src/com/pahans/kichibichiya/model/ListAction.java | Java | gpl-3.0 | 1,111 |
package com.st0ck53y.testsudokuapplication.classes;
public class GridArea {
private int value;
public GridArea(int v) {
this();
if (v != 0) {
setValue(v);
}
}
public GridArea() {
value = 8185; // 4 bit for remaining possible (9), 9 bit for flags of each, and 1 bit for value flag (is value or check?)
}
public boolean isValue() {
return (value >> 15) == 1; //value flag set when number is certain
}
public int getValue() {
return (value & 15); //either the number in grid, or possibilities remaining
}
//creates list of integers from binary flags
public int[] getPossibles() {
int[] p = new int[getValue()];
int pointer = 0;
for (int i = 4; i <= 12; i++) {
if (((value >> i) & 1) == 1) {
p[pointer++] = i - 3;
}
}
return p;
}
//switches from check to value
public void checkGrid() {
if ((getValue()) == 1) {
setValue(getPossibles()[0]);
}
}
//turns off flag of number and decrements remaining counter
public void setImpossible(int i) {
int pos = i + 3;
int curSet = (value >> pos) & 1;
if (curSet == 1) { //Have to check to stop decrement if multiple passes are done
value &= (65535 - (1 << (i + 3)));
value--;
checkGrid();
}
}
public void setValue(int v) {
if (v == 0)
value = 8185;
else
value = (v | (1 << 15));
}
}
| st0ck53y/Sudoku_Solver | app/src/main/java/com/st0ck53y/testsudokuapplication/classes/GridArea.java | Java | gpl-3.0 | 1,644 |
/**
* Genji Scrum Tool and Issue Tracker
* Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions
* <a href="http://www.trackplus.com">Genji Scrum Tool</a>
*
* 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/>.
*/
/* $Id:$ */
package com.aurel.track.persist;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.torque.NoRowsException;
import org.apache.torque.TooManyRowsException;
import org.apache.torque.Torque;
import org.apache.torque.TorqueException;
import org.apache.torque.TorqueRuntimeException;
import org.apache.torque.map.MapBuilder;
import org.apache.torque.map.TableMap;
import org.apache.torque.om.DateKey;
import org.apache.torque.om.NumberKey;
import org.apache.torque.om.StringKey;
import org.apache.torque.om.ObjectKey;
import org.apache.torque.om.SimpleKey;
import org.apache.torque.util.BasePeer;
import org.apache.torque.util.Criteria;
import com.workingdogs.village.DataSetException;
import com.workingdogs.village.QueryDataSet;
import com.workingdogs.village.Record;
// Local classes
import com.aurel.track.persist.map.*;
/**
* grouping field for card
*
*/
public abstract class BaseTCardGroupingFieldPeer
extends BasePeer
{
/** the default database name for this class */
public static final String DATABASE_NAME;
/** the table name for this class */
public static final String TABLE_NAME;
/**
* @return the map builder for this peer
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @deprecated Torque.getMapBuilder(TCardGroupingFieldMapBuilder.CLASS_NAME) instead
*/
public static MapBuilder getMapBuilder()
throws TorqueException
{
return Torque.getMapBuilder(TCardGroupingFieldMapBuilder.CLASS_NAME);
}
/** the column name for the OBJECTID field */
public static final String OBJECTID;
/** the column name for the NAVIGATORLAYOUT field */
public static final String NAVIGATORLAYOUT;
/** the column name for the CARDFIELD field */
public static final String CARDFIELD;
/** the column name for the ISACTIV field */
public static final String ISACTIV;
/** the column name for the SORTFIELD field */
public static final String SORTFIELD;
/** the column name for the ISDESCENDING field */
public static final String ISDESCENDING;
/** the column name for the TPUUID field */
public static final String TPUUID;
static
{
DATABASE_NAME = "track";
TABLE_NAME = "TCARDGROUPINGFIELD";
OBJECTID = "TCARDGROUPINGFIELD.OBJECTID";
NAVIGATORLAYOUT = "TCARDGROUPINGFIELD.NAVIGATORLAYOUT";
CARDFIELD = "TCARDGROUPINGFIELD.CARDFIELD";
ISACTIV = "TCARDGROUPINGFIELD.ISACTIV";
SORTFIELD = "TCARDGROUPINGFIELD.SORTFIELD";
ISDESCENDING = "TCARDGROUPINGFIELD.ISDESCENDING";
TPUUID = "TCARDGROUPINGFIELD.TPUUID";
if (Torque.isInit())
{
try
{
Torque.getMapBuilder(TCardGroupingFieldMapBuilder.CLASS_NAME);
}
catch (TorqueException e)
{
log.error("Could not initialize Peer", e);
throw new TorqueRuntimeException(e);
}
}
else
{
Torque.registerMapBuilder(TCardGroupingFieldMapBuilder.CLASS_NAME);
}
}
/** number of columns for this peer */
public static final int numColumns = 7;
/** A class that can be returned by this peer. */
protected static final String CLASSNAME_DEFAULT =
"com.aurel.track.persist.TCardGroupingField";
/** A class that can be returned by this peer. */
protected static final Class CLASS_DEFAULT = initClass(CLASSNAME_DEFAULT);
/**
* Class object initialization method.
*
* @param className name of the class to initialize
* @return the initialized class
*/
private static Class initClass(String className)
{
Class c = null;
try
{
c = Class.forName(className);
}
catch (Throwable t)
{
log.error("A FATAL ERROR has occurred which should not "
+ "have happened under any circumstance. Please notify "
+ "the Torque developers <torque-dev@db.apache.org> "
+ "and give as many details as possible (including the error "
+ "stack trace).", t);
// Error objects should always be propagated.
if (t instanceof Error)
{
throw (Error) t.fillInStackTrace();
}
}
return c;
}
/**
* Get the list of objects for a ResultSet. Please not that your
* resultset MUST return columns in the right order. You can use
* getFieldNames() in BaseObject to get the correct sequence.
*
* @param results the ResultSet
* @return the list of objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TCardGroupingField> resultSet2Objects(java.sql.ResultSet results)
throws TorqueException
{
try
{
QueryDataSet qds = null;
List<Record> rows = null;
try
{
qds = new QueryDataSet(results);
rows = getSelectResults(qds);
}
finally
{
if (qds != null)
{
qds.close();
}
}
return populateObjects(rows);
}
catch (SQLException e)
{
throw new TorqueException(e);
}
catch (DataSetException e)
{
throw new TorqueException(e);
}
}
/**
* Method to do inserts.
*
* @param criteria object used to create the INSERT statement.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static ObjectKey doInsert(Criteria criteria)
throws TorqueException
{
return BaseTCardGroupingFieldPeer
.doInsert(criteria, (Connection) null);
}
/**
* Method to do inserts. This method is to be used during a transaction,
* otherwise use the doInsert(Criteria) method. It will take care of
* the connection details internally.
*
* @param criteria object used to create the INSERT statement.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static ObjectKey doInsert(Criteria criteria, Connection con)
throws TorqueException
{
correctBooleans(criteria);
setDbName(criteria);
if (con == null)
{
return BasePeer.doInsert(criteria);
}
else
{
return BasePeer.doInsert(criteria, con);
}
}
/**
* Add all the columns needed to create a new object.
*
* @param criteria object containing the columns to add.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void addSelectColumns(Criteria criteria)
throws TorqueException
{
criteria.addSelectColumn(OBJECTID);
criteria.addSelectColumn(NAVIGATORLAYOUT);
criteria.addSelectColumn(CARDFIELD);
criteria.addSelectColumn(ISACTIV);
criteria.addSelectColumn(SORTFIELD);
criteria.addSelectColumn(ISDESCENDING);
criteria.addSelectColumn(TPUUID);
}
/**
* changes the boolean values in the criteria to the appropriate type,
* whenever a booleanchar or booleanint column is involved.
* This enables the user to create criteria using Boolean values
* for booleanchar or booleanint columns
* @param criteria the criteria in which the boolean values should be corrected
* @throws TorqueException if the database map for the criteria cannot be
obtained.
*/
public static void correctBooleans(Criteria criteria) throws TorqueException
{
correctBooleans(criteria, getTableMap());
}
/**
* Create a new object of type cls from a resultset row starting
* from a specified offset. This is done so that you can select
* other rows than just those needed for this object. You may
* for example want to create two objects from the same row.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static TCardGroupingField row2Object(Record row,
int offset,
Class cls)
throws TorqueException
{
try
{
TCardGroupingField obj = (TCardGroupingField) cls.newInstance();
TCardGroupingFieldPeer.populateObject(row, offset, obj);
obj.setModified(false);
obj.setNew(false);
return obj;
}
catch (InstantiationException e)
{
throw new TorqueException(e);
}
catch (IllegalAccessException e)
{
throw new TorqueException(e);
}
}
/**
* Populates an object from a resultset row starting
* from a specified offset. This is done so that you can select
* other rows than just those needed for this object. You may
* for example want to create two objects from the same row.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void populateObject(Record row,
int offset,
TCardGroupingField obj)
throws TorqueException
{
try
{
obj.setObjectID(row.getValue(offset + 0).asIntegerObj());
obj.setNavigatorLayout(row.getValue(offset + 1).asIntegerObj());
obj.setCardField(row.getValue(offset + 2).asIntegerObj());
obj.setIsActiv(row.getValue(offset + 3).asString());
obj.setSortField(row.getValue(offset + 4).asIntegerObj());
obj.setIsDescending(row.getValue(offset + 5).asString());
obj.setUuid(row.getValue(offset + 6).asString());
}
catch (DataSetException e)
{
throw new TorqueException(e);
}
}
/**
* Method to do selects.
*
* @param criteria object used to create the SELECT statement.
* @return List of selected Objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TCardGroupingField> doSelect(Criteria criteria) throws TorqueException
{
return populateObjects(doSelectVillageRecords(criteria));
}
/**
* Method to do selects within a transaction.
*
* @param criteria object used to create the SELECT statement.
* @param con the connection to use
* @return List of selected Objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TCardGroupingField> doSelect(Criteria criteria, Connection con)
throws TorqueException
{
return populateObjects(doSelectVillageRecords(criteria, con));
}
/**
* Grabs the raw Village records to be formed into objects.
* This method handles connections internally. The Record objects
* returned by this method should be considered readonly. Do not
* alter the data and call save(), your results may vary, but are
* certainly likely to result in hard to track MT bugs.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<Record> doSelectVillageRecords(Criteria criteria)
throws TorqueException
{
return BaseTCardGroupingFieldPeer
.doSelectVillageRecords(criteria, (Connection) null);
}
/**
* Grabs the raw Village records to be formed into objects.
* This method should be used for transactions
*
* @param criteria object used to create the SELECT statement.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<Record> doSelectVillageRecords(Criteria criteria, Connection con)
throws TorqueException
{
if (criteria.getSelectColumns().size() == 0)
{
addSelectColumns(criteria);
}
correctBooleans(criteria);
setDbName(criteria);
// BasePeer returns a List of Value (Village) arrays. The array
// order follows the order columns were placed in the Select clause.
if (con == null)
{
return BasePeer.doSelect(criteria);
}
else
{
return BasePeer.doSelect(criteria, con);
}
}
/**
* The returned List will contain objects of the default type or
* objects that inherit from the default.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TCardGroupingField> populateObjects(List<Record> records)
throws TorqueException
{
List<TCardGroupingField> results = new ArrayList<TCardGroupingField>(records.size());
// populate the object(s)
for (int i = 0; i < records.size(); i++)
{
Record row = records.get(i);
results.add(TCardGroupingFieldPeer.row2Object(row, 1,
TCardGroupingFieldPeer.getOMClass()));
}
return results;
}
/**
* The class that the Peer will make instances of.
* If the BO is abstract then you must implement this method
* in the BO.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static Class getOMClass()
throws TorqueException
{
return CLASS_DEFAULT;
}
/**
* Method to do updates.
*
* @param criteria object containing data that is used to create the UPDATE
* statement.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doUpdate(Criteria criteria) throws TorqueException
{
BaseTCardGroupingFieldPeer
.doUpdate(criteria, (Connection) null);
}
/**
* Method to do updates. This method is to be used during a transaction,
* otherwise use the doUpdate(Criteria) method. It will take care of
* the connection details internally.
*
* @param criteria object containing data that is used to create the UPDATE
* statement.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doUpdate(Criteria criteria, Connection con)
throws TorqueException
{
Criteria selectCriteria = new Criteria(DATABASE_NAME, 2);
correctBooleans(criteria);
selectCriteria.put(OBJECTID, criteria.remove(OBJECTID));
setDbName(criteria);
if (con == null)
{
BasePeer.doUpdate(selectCriteria, criteria);
}
else
{
BasePeer.doUpdate(selectCriteria, criteria, con);
}
}
/**
* Method to do deletes.
*
* @param criteria object containing data that is used DELETE from database.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(Criteria criteria) throws TorqueException
{
TCardGroupingFieldPeer
.doDelete(criteria, (Connection) null);
}
/**
* Method to do deletes. This method is to be used during a transaction,
* otherwise use the doDelete(Criteria) method. It will take care of
* the connection details internally.
*
* @param criteria object containing data that is used DELETE from database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(Criteria criteria, Connection con)
throws TorqueException
{
correctBooleans(criteria);
setDbName(criteria);
if (con == null)
{
BasePeer.doDelete(criteria, TABLE_NAME);
}
else
{
BasePeer.doDelete(criteria, TABLE_NAME, con);
}
}
/**
* Method to do selects
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TCardGroupingField> doSelect(TCardGroupingField obj) throws TorqueException
{
return doSelect(buildSelectCriteria(obj));
}
/**
* Method to do inserts
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doInsert(TCardGroupingField obj) throws TorqueException
{
obj.setPrimaryKey(doInsert(buildCriteria(obj)));
obj.setNew(false);
obj.setModified(false);
}
/**
* @param obj the data object to update in the database.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doUpdate(TCardGroupingField obj) throws TorqueException
{
doUpdate(buildCriteria(obj));
obj.setModified(false);
}
/**
* @param obj the data object to delete in the database.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(TCardGroupingField obj) throws TorqueException
{
doDelete(buildSelectCriteria(obj));
}
/**
* Method to do inserts. This method is to be used during a transaction,
* otherwise use the doInsert(TCardGroupingField) method. It will take
* care of the connection details internally.
*
* @param obj the data object to insert into the database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doInsert(TCardGroupingField obj, Connection con)
throws TorqueException
{
obj.setPrimaryKey(doInsert(buildCriteria(obj), con));
obj.setNew(false);
obj.setModified(false);
}
/**
* Method to do update. This method is to be used during a transaction,
* otherwise use the doUpdate(TCardGroupingField) method. It will take
* care of the connection details internally.
*
* @param obj the data object to update in the database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doUpdate(TCardGroupingField obj, Connection con)
throws TorqueException
{
doUpdate(buildCriteria(obj), con);
obj.setModified(false);
}
/**
* Method to delete. This method is to be used during a transaction,
* otherwise use the doDelete(TCardGroupingField) method. It will take
* care of the connection details internally.
*
* @param obj the data object to delete in the database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(TCardGroupingField obj, Connection con)
throws TorqueException
{
doDelete(buildSelectCriteria(obj), con);
}
/**
* Method to do deletes.
*
* @param pk ObjectKey that is used DELETE from database.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(ObjectKey pk) throws TorqueException
{
BaseTCardGroupingFieldPeer
.doDelete(pk, (Connection) null);
}
/**
* Method to delete. This method is to be used during a transaction,
* otherwise use the doDelete(ObjectKey) method. It will take
* care of the connection details internally.
*
* @param pk the primary key for the object to delete in the database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(ObjectKey pk, Connection con)
throws TorqueException
{
doDelete(buildCriteria(pk), con);
}
/** Build a Criteria object from an ObjectKey */
public static Criteria buildCriteria( ObjectKey pk )
{
Criteria criteria = new Criteria();
criteria.add(OBJECTID, pk);
return criteria;
}
/** Build a Criteria object from the data object for this peer */
public static Criteria buildCriteria( TCardGroupingField obj )
{
Criteria criteria = new Criteria(DATABASE_NAME);
if (!obj.isNew())
criteria.add(OBJECTID, obj.getObjectID());
criteria.add(NAVIGATORLAYOUT, obj.getNavigatorLayout());
criteria.add(CARDFIELD, obj.getCardField());
criteria.add(ISACTIV, obj.getIsActiv());
criteria.add(SORTFIELD, obj.getSortField());
criteria.add(ISDESCENDING, obj.getIsDescending());
criteria.add(TPUUID, obj.getUuid());
return criteria;
}
/** Build a Criteria object from the data object for this peer, skipping all binary columns */
public static Criteria buildSelectCriteria( TCardGroupingField obj )
{
Criteria criteria = new Criteria(DATABASE_NAME);
if (!obj.isNew())
{
criteria.add(OBJECTID, obj.getObjectID());
}
criteria.add(NAVIGATORLAYOUT, obj.getNavigatorLayout());
criteria.add(CARDFIELD, obj.getCardField());
criteria.add(ISACTIV, obj.getIsActiv());
criteria.add(SORTFIELD, obj.getSortField());
criteria.add(ISDESCENDING, obj.getIsDescending());
criteria.add(TPUUID, obj.getUuid());
return criteria;
}
/**
* Retrieve a single object by pk
*
* @param pk the primary key
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @throws NoRowsException Primary key was not found in database.
* @throws TooManyRowsException Primary key was not found in database.
*/
public static TCardGroupingField retrieveByPK(Integer pk)
throws TorqueException, NoRowsException, TooManyRowsException
{
return retrieveByPK(SimpleKey.keyFor(pk));
}
/**
* Retrieve a single object by pk
*
* @param pk the primary key
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @throws NoRowsException Primary key was not found in database.
* @throws TooManyRowsException Primary key was not found in database.
*/
public static TCardGroupingField retrieveByPK(Integer pk, Connection con)
throws TorqueException, NoRowsException, TooManyRowsException
{
return retrieveByPK(SimpleKey.keyFor(pk), con);
}
/**
* Retrieve a single object by pk
*
* @param pk the primary key
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @throws NoRowsException Primary key was not found in database.
* @throws TooManyRowsException Primary key was not found in database.
*/
public static TCardGroupingField retrieveByPK(ObjectKey pk)
throws TorqueException, NoRowsException, TooManyRowsException
{
Connection db = null;
TCardGroupingField retVal = null;
try
{
db = Torque.getConnection(DATABASE_NAME);
retVal = retrieveByPK(pk, db);
}
finally
{
Torque.closeConnection(db);
}
return retVal;
}
/**
* Retrieve a single object by pk
*
* @param pk the primary key
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @throws NoRowsException Primary key was not found in database.
* @throws TooManyRowsException Primary key was not found in database.
*/
public static TCardGroupingField retrieveByPK(ObjectKey pk, Connection con)
throws TorqueException, NoRowsException, TooManyRowsException
{
Criteria criteria = buildCriteria(pk);
List<TCardGroupingField> v = doSelect(criteria, con);
if (v.size() == 0)
{
throw new NoRowsException("Failed to select a row.");
}
else if (v.size() > 1)
{
throw new TooManyRowsException("Failed to select only one row.");
}
else
{
return (TCardGroupingField)v.get(0);
}
}
/**
* Retrieve a multiple objects by pk
*
* @param pks List of primary keys
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TCardGroupingField> retrieveByPKs(List<ObjectKey> pks)
throws TorqueException
{
Connection db = null;
List<TCardGroupingField> retVal = null;
try
{
db = Torque.getConnection(DATABASE_NAME);
retVal = retrieveByPKs(pks, db);
}
finally
{
Torque.closeConnection(db);
}
return retVal;
}
/**
* Retrieve a multiple objects by pk
*
* @param pks List of primary keys
* @param dbcon the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TCardGroupingField> retrieveByPKs( List<ObjectKey> pks, Connection dbcon )
throws TorqueException
{
List<TCardGroupingField> objs = null;
if (pks == null || pks.size() == 0)
{
objs = new LinkedList<TCardGroupingField>();
}
else
{
Criteria criteria = new Criteria();
criteria.addIn( OBJECTID, pks );
objs = doSelect(criteria, dbcon);
}
return objs;
}
/**
* selects a collection of TCardGroupingField objects pre-filled with their
* TNavigatorLayout objects.
*
* This method is protected by default in order to keep the public
* api reasonable. You can provide public methods for those you
* actually need in TCardGroupingFieldPeer.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
protected static List<TCardGroupingField> doSelectJoinTNavigatorLayout(Criteria criteria)
throws TorqueException
{
return doSelectJoinTNavigatorLayout(criteria, null);
}
/**
* selects a collection of TCardGroupingField objects pre-filled with their
* TNavigatorLayout objects.
*
* This method is protected by default in order to keep the public
* api reasonable. You can provide public methods for those you
* actually need in TCardGroupingFieldPeer.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
protected static List<TCardGroupingField> doSelectJoinTNavigatorLayout(Criteria criteria, Connection conn)
throws TorqueException
{
setDbName(criteria);
TCardGroupingFieldPeer.addSelectColumns(criteria);
int offset = numColumns + 1;
TNavigatorLayoutPeer.addSelectColumns(criteria);
criteria.addJoin(TCardGroupingFieldPeer.NAVIGATORLAYOUT,
TNavigatorLayoutPeer.OBJECTID);
correctBooleans(criteria);
List<Record> rows;
if (conn == null)
{
rows = BasePeer.doSelect(criteria);
}
else
{
rows = BasePeer.doSelect(criteria,conn);
}
List<TCardGroupingField> results = new ArrayList<TCardGroupingField>();
for (int i = 0; i < rows.size(); i++)
{
Record row = rows.get(i);
Class omClass = TCardGroupingFieldPeer.getOMClass();
TCardGroupingField obj1 = (TCardGroupingField) TCardGroupingFieldPeer
.row2Object(row, 1, omClass);
omClass = TNavigatorLayoutPeer.getOMClass();
TNavigatorLayout obj2 = (TNavigatorLayout) TNavigatorLayoutPeer
.row2Object(row, offset, omClass);
boolean newObject = true;
for (int j = 0; j < results.size(); j++)
{
TCardGroupingField temp_obj1 = results.get(j);
TNavigatorLayout temp_obj2 = (TNavigatorLayout) temp_obj1.getTNavigatorLayout();
if (temp_obj2.getPrimaryKey().equals(obj2.getPrimaryKey()))
{
newObject = false;
temp_obj2.addTCardGroupingField(obj1);
break;
}
}
if (newObject)
{
obj2.initTCardGroupingFields();
obj2.addTCardGroupingField(obj1);
}
results.add(obj1);
}
return results;
}
/**
* Returns the TableMap related to this peer.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static TableMap getTableMap()
throws TorqueException
{
return Torque.getDatabaseMap(DATABASE_NAME).getTable(TABLE_NAME);
}
private static void setDbName(Criteria crit)
{
// Set the correct dbName if it has not been overridden
// crit.getDbName will return the same object if not set to
// another value so == check is okay and faster
if (crit.getDbName() == Torque.getDefaultDB())
{
crit.setDbName(DATABASE_NAME);
}
}
// The following methods wrap some methods in BasePeer
// to have more support for Java5 generic types in the Peer
/**
* Utility method which executes a given sql statement. This
* method should be used for select statements only. Use
* executeStatement for update, insert, and delete operations.
*
* @param queryString A String with the sql statement to execute.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String)
*/
public static List<Record> executeQuery(String queryString) throws TorqueException
{
return BasePeer.executeQuery(queryString);
}
/**
* Utility method which executes a given sql statement. This
* method should be used for select statements only. Use
* executeStatement for update, insert, and delete operations.
*
* @param queryString A String with the sql statement to execute.
* @param dbName The database to connect to.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,String)
*/
public static List<Record> executeQuery(String queryString, String dbName)
throws TorqueException
{
return BasePeer.executeQuery(queryString,dbName);
}
/**
* Method for performing a SELECT. Returns all results.
*
* @param queryString A String with the sql statement to execute.
* @param dbName The database to connect to.
* @param singleRecord Whether or not we want to select only a
* single record.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,String,boolean)
*/
public static List<Record> executeQuery(
String queryString,
String dbName,
boolean singleRecord)
throws TorqueException
{
return BasePeer.executeQuery(queryString,dbName,singleRecord);
}
/**
* Method for performing a SELECT. Returns all results.
*
* @param queryString A String with the sql statement to execute.
* @param singleRecord Whether or not we want to select only a
* single record.
* @param con A Connection.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,boolean,Connection)
*/
public static List<Record> executeQuery(
String queryString,
boolean singleRecord,
Connection con)
throws TorqueException
{
return BasePeer.executeQuery(queryString,singleRecord,con);
}
/**
* Method for performing a SELECT.
*
* @param queryString A String with the sql statement to execute.
* @param start The first row to return.
* @param numberOfResults The number of rows to return.
* @param dbName The database to connect to.
* @param singleRecord Whether or not we want to select only a
* single record.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,int,int,String,boolean)
*/
public static List<Record> executeQuery(
String queryString,
int start,
int numberOfResults,
String dbName,
boolean singleRecord)
throws TorqueException
{
return BasePeer.executeQuery(queryString,start,numberOfResults,dbName,singleRecord);
}
/**
* Method for performing a SELECT. Returns all results.
*
* @param queryString A String with the sql statement to execute.
* @param start The first row to return.
* @param numberOfResults The number of rows to return.
* @param singleRecord Whether or not we want to select only a
* single record.
* @param con A Connection.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,int,int,String,boolean,Connection)
*/
public static List<Record> executeQuery(
String queryString,
int start,
int numberOfResults,
boolean singleRecord,
Connection con)
throws TorqueException
{
return BasePeer.executeQuery(queryString,start,numberOfResults,singleRecord,con);
}
/**
* Returns all records in a QueryDataSet as a List of Record
* objects. Used for functionality like util.LargeSelect.
*
* @see #getSelectResults(QueryDataSet, int, int, boolean)
* @param qds the QueryDataSet
* @return a List of Record objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet)
*/
public static List<Record> getSelectResults(QueryDataSet qds)
throws TorqueException
{
return BasePeer.getSelectResults(qds);
}
/**
* Returns all records in a QueryDataSet as a List of Record
* objects. Used for functionality like util.LargeSelect.
*
* @see #getSelectResults(QueryDataSet, int, int, boolean)
* @param qds the QueryDataSet
* @param singleRecord
* @return a List of Record objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet,boolean)
*/
public static List<Record> getSelectResults(QueryDataSet qds, boolean singleRecord)
throws TorqueException
{
return BasePeer.getSelectResults(qds,singleRecord);
}
/**
* Returns numberOfResults records in a QueryDataSet as a List
* of Record objects. Starting at record 0. Used for
* functionality like util.LargeSelect.
*
* @see #getSelectResults(QueryDataSet, int, int, boolean)
* @param qds the QueryDataSet
* @param numberOfResults
* @param singleRecord
* @return a List of Record objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet,int,boolean)
*/
public static List<Record> getSelectResults(
QueryDataSet qds,
int numberOfResults,
boolean singleRecord)
throws TorqueException
{
return BasePeer.getSelectResults(qds,numberOfResults,singleRecord);
}
/**
* Returns numberOfResults records in a QueryDataSet as a List
* of Record objects. Starting at record start. Used for
* functionality like util.LargeSelect.
*
* @param qds The <code>QueryDataSet</code> to extract results
* from.
* @param start The index from which to start retrieving
* <code>Record</code> objects from the data set.
* @param numberOfResults The number of results to return (or
* <code> -1</code> for all results).
* @param singleRecord Whether or not we want to select only a
* single record.
* @return A <code>List</code> of <code>Record</code> objects.
* @exception TorqueException If any <code>Exception</code> occurs.
* @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet,int,int,boolean)
*/
public static List getSelectResults(
QueryDataSet qds,
int start,
int numberOfResults,
boolean singleRecord)
throws TorqueException
{
return BasePeer.getSelectResults(qds,start,numberOfResults,singleRecord);
}
/**
* Performs a SQL <code>select</code> using a PreparedStatement.
* Note: this method does not handle null criteria values.
*
* @param criteria
* @param con
* @return a List of Record objects.
* @throws TorqueException Error performing database query.
* @see org.apache.torque.util.BasePeer#doPSSelect(Criteria,Connection)
*/
public static List<Record> doPSSelect(Criteria criteria, Connection con)
throws TorqueException
{
return BasePeer.doPSSelect(criteria,con);
}
/**
* Do a Prepared Statement select according to the given criteria
*
* @param criteria
* @return a List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#doPSSelect(Criteria)
*/
public static List<Record> doPSSelect(Criteria criteria) throws TorqueException
{
return BasePeer.doPSSelect(criteria);
}
}
| trackplus/Genji | src/main/java/com/aurel/track/persist/BaseTCardGroupingFieldPeer.java | Java | gpl-3.0 | 42,159 |
# coding=utf-8
"""Dummy test.
Pointless dummy test.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
# import pysnapsync.server
# import pysnapsync.client
def inc(arg):
"""Return arg incremented by one."""
return arg + 1
def test_answer():
"""Assert 3+1 == 4."""
assert inc(3) == 4
| dtaylor84/pysnapsync | pysnapsync/tests/test_dummy.py | Python | gpl-3.0 | 370 |
#include "archiveviewwindow.h"
#include <QLocale>
#include <QCursor>
#include <QPrinter>
#include <QMessageBox>
#include <QFileDialog>
#include <QPrintDialog>
#include <QItemSelectionModel>
#include <QNetworkAccessManager>
#include <definitions/menuicons.h>
#include <definitions/resources.h>
#include <definitions/optionvalues.h>
#include <definitions/messagedataroles.h>
#include <utils/widgetmanager.h>
#include <utils/pluginhelper.h>
#include <utils/textmanager.h>
#include <utils/iconstorage.h>
#include <utils/logger.h>
#define ADR_HEADER_STREAM Action::DR_StreamJid
#define ADR_HEADER_WITH Action::DR_Parametr1
#define ADR_HEADER_START Action::DR_Parametr2
#define ADR_HEADER_END Action::DR_Parametr3
#define ADR_EXPORT_AS_HTML Action::DR_Parametr1
#define MIN_LOAD_HEADERS 50
#define MAX_HILIGHT_ITEMS 10
#define LOAD_COLLECTION_TIMEOUT 100
enum HistoryItemType {
HIT_CONTACT,
HIT_DATEGROUP,
HIT_HEADER
};
enum HistoryDataRoles {
HDR_TYPE = Qt::UserRole+1,
HDR_CONTACT_JID,
HDR_METACONTACT_ID,
HDR_DATEGROUP_DATE,
HDR_HEADER_WITH,
HDR_HEADER_STREAM,
HDR_HEADER_START,
HDR_HEADER_SUBJECT,
HDR_HEADER_THREAD,
HDR_HEADER_VERSION,
HDR_HEADER_ENGINE
};
static const int HistoryTimeCount = 8;
static const int HistoryTime[HistoryTimeCount] = { -1, -3, -6, -12, -24, -36, -48, -60 };
SortFilterProxyModel::SortFilterProxyModel(QObject *AParent) : QSortFilterProxyModel(AParent)
{
}
bool SortFilterProxyModel::lessThan(const QModelIndex &ALeft, const QModelIndex &ARight) const
{
int leftType = ALeft.data(HDR_TYPE).toInt();
int rightType = ARight.data(HDR_TYPE).toInt();
if (leftType == rightType)
{
if (leftType == HIT_CONTACT)
{
QString leftDisplay = ALeft.data(Qt::DisplayRole).toString();
QString rightDisplay = ARight.data(Qt::DisplayRole).toString();
if (sortCaseSensitivity() == Qt::CaseInsensitive)
{
leftDisplay = leftDisplay.toLower();
rightDisplay = rightDisplay.toLower();
}
return QString::localeAwareCompare(leftDisplay,rightDisplay) < 0;
}
else if (leftType == HIT_DATEGROUP)
{
QDate leftDate = ALeft.data(HDR_DATEGROUP_DATE).toDate();
QDate rightDate = ARight.data(HDR_DATEGROUP_DATE).toDate();
return leftDate >= rightDate;
}
else if (leftType == HIT_HEADER)
{
QDateTime leftDate = ALeft.data(HDR_HEADER_START).toDateTime();
QDateTime rightDate = ARight.data(HDR_HEADER_START).toDateTime();
return leftDate < rightDate;
}
return QSortFilterProxyModel::lessThan(ALeft,ARight);
}
return leftType < rightType;
}
ArchiveViewWindow::ArchiveViewWindow(IMessageArchiver *AArchiver, const QMultiMap<Jid,Jid> &AAddresses, QWidget *AParent) : QMainWindow(AParent)
{
REPORT_VIEW;
ui.setupUi(this);
setAttribute(Qt::WA_DeleteOnClose,true);
IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->insertAutoIcon(this,MNI_HISTORY,0,0,"windowIcon");
FFocusWidget = NULL;
FArchiver = AArchiver;
FRosterManager = PluginHelper::pluginInstance<IRosterManager>();
if (FRosterManager)
{
connect(FRosterManager->instance(),SIGNAL(rosterActiveChanged(IRoster *, bool)),SLOT(onRosterActiveChanged(IRoster *, bool)));
connect(FRosterManager->instance(),SIGNAL(rosterStreamJidChanged(IRoster *, const Jid &)),SLOT(onRosterStreamJidChanged(IRoster *, const Jid &)));
}
FStatusIcons = PluginHelper::pluginInstance<IStatusIcons>();
FUrlProcessor = PluginHelper::pluginInstance<IUrlProcessor>();
FMetaContacts = PluginHelper::pluginInstance<IMetaContacts>();
FMessageProcessor = PluginHelper::pluginInstance<IMessageProcessor>();
FFileMessageArchive = PluginHelper::pluginInstance<IFileMessageArchive>();
FMessageStyleManager = PluginHelper::pluginInstance<IMessageStyleManager>();
FHeaderActionLabel = new QLabel(ui.trvHeaders);
QPalette pal = FHeaderActionLabel->palette();
pal.setColor(QPalette::Active,QPalette::Window,pal.color(QPalette::Active,QPalette::Base));
pal.setColor(QPalette::Disabled,QPalette::Window,pal.color(QPalette::Disabled,QPalette::Base));
FHeaderActionLabel->setAlignment(Qt::AlignCenter);
FHeaderActionLabel->setAutoFillBackground(true);
FHeaderActionLabel->setPalette(pal);
FHeaderActionLabel->setMargin(3);
FHeadersEmptyLabel = new QLabel(tr("Conversations are not found"),ui.trvHeaders);
FHeadersEmptyLabel->setAlignment(Qt::AlignCenter);
FHeadersEmptyLabel->setEnabled(false);
FHeadersEmptyLabel->setMargin(3);
QVBoxLayout *headersLayout = new QVBoxLayout(ui.trvHeaders);
headersLayout->setMargin(0);
headersLayout->addStretch();
headersLayout->addWidget(FHeadersEmptyLabel);
headersLayout->addStretch();
headersLayout->addWidget(FHeaderActionLabel);
FMessagesEmptyLabel = new QLabel(tr("Conversation is not selected"),ui.tbrMessages);
FMessagesEmptyLabel->setAlignment(Qt::AlignCenter);
FMessagesEmptyLabel->setEnabled(false);
FMessagesEmptyLabel->setMargin(3);
QVBoxLayout *messagesLayout = new QVBoxLayout(ui.tbrMessages);
messagesLayout->setMargin(0);
messagesLayout->addStretch();
messagesLayout->addWidget(FMessagesEmptyLabel);
messagesLayout->addStretch();
FModel = new QStandardItemModel(this);
FProxyModel = new SortFilterProxyModel(FModel);
FProxyModel->setSourceModel(FModel);
FProxyModel->setDynamicSortFilter(true);
FProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
QFont messagesFont = ui.tbrMessages->font();
messagesFont.setPointSize(Options::node(OPV_HISTORY_ARCHIVEVIEW_FONTPOINTSIZE).value().toInt());
ui.tbrMessages->setFont(messagesFont);
QPalette palette = ui.tbrMessages->palette();
palette.setColor(QPalette::Inactive,QPalette::Highlight,palette.color(QPalette::Active,QPalette::Highlight));
palette.setColor(QPalette::Inactive,QPalette::HighlightedText,palette.color(QPalette::Active,QPalette::HighlightedText));
ui.tbrMessages->setPalette(palette);
ui.tbrMessages->setNetworkAccessManager(FUrlProcessor!=NULL ? FUrlProcessor->networkAccessManager() : new QNetworkAccessManager(ui.tbrMessages));
ui.trvHeaders->setModel(FProxyModel);
ui.trvHeaders->setBottomWidget(FHeaderActionLabel);
ui.trvHeaders->header()->setSortIndicator(0,Qt::AscendingOrder);
connect(ui.trvHeaders->selectionModel(),SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
SLOT(onCurrentSelectionChanged(const QItemSelection &, const QItemSelection &)));
connect(ui.trvHeaders,SIGNAL(customContextMenuRequested(const QPoint &)),SLOT(onHeaderContextMenuRequested(const QPoint &)));
FExportLabel = new QLabel(ui.stbStatusBar);
FExportLabel->setTextFormat(Qt::RichText);
FExportLabel->setText(QString("<a href='export'>%1</a>").arg(tr("Export")));
connect(FExportLabel,SIGNAL(linkActivated(const QString &)),SLOT(onExportLabelLinkActivated(const QString &)));
ui.stbStatusBar->addPermanentWidget(FExportLabel);
FHeadersRequestTimer.setSingleShot(true);
connect(&FHeadersRequestTimer,SIGNAL(timeout()),SLOT(onHeadersRequestTimerTimeout()));
FCollectionsProcessTimer.setSingleShot(true);
connect(&FCollectionsProcessTimer,SIGNAL(timeout()),SLOT(onCollectionsProcessTimerTimeout()));
FCollectionsRequestTimer.setSingleShot(true);
connect(&FCollectionsRequestTimer,SIGNAL(timeout()),SLOT(onCollectionsRequestTimerTimeout()));
FTextHilightTimer.setSingleShot(true);
connect(&FTextHilightTimer,SIGNAL(timeout()),SLOT(onTextHilightTimerTimeout()));
connect(ui.tbrMessages,SIGNAL(visiblePositionBoundaryChanged()),SLOT(onTextVisiblePositionBoundaryChanged()));
ui.lneArchiveSearch->setStartSearchTimeout(-1);
ui.lneArchiveSearch->setSelectTextOnFocusEnabled(false);
connect(ui.lneArchiveSearch,SIGNAL(searchStart()),SLOT(onArchiveSearchStart()));
ui.lneTextSearch->setPlaceholderText(tr("Search in text"));
connect(ui.tlbTextSearchPrev,SIGNAL(clicked()),SLOT(onTextSearchPrevClicked()));
connect(ui.tlbTextSearchNext,SIGNAL(clicked()),SLOT(onTextSearchNextClicked()));
connect(ui.lneTextSearch,SIGNAL(searchStart()),SLOT(onTextSearchStart()));
connect(ui.lneTextSearch,SIGNAL(searchNext()),SLOT(onTextSearchNextClicked()));
connect(FArchiver->instance(),SIGNAL(requestFailed(const QString &, const XmppError &)),
SLOT(onArchiveRequestFailed(const QString &, const XmppError &)));
connect(FArchiver->instance(),SIGNAL(headersLoaded(const QString &, const QList<IArchiveHeader> &)),
SLOT(onArchiveHeadersLoaded(const QString &, const QList<IArchiveHeader> &)));
connect(FArchiver->instance(),SIGNAL(collectionLoaded(const QString &, const IArchiveCollection &)),
SLOT(onArchiveCollectionLoaded(const QString &, const IArchiveCollection &)));
connect(FArchiver->instance(),SIGNAL(collectionsRemoved(const QString &, const IArchiveRequest &)),
SLOT(onArchiveCollectionsRemoved(const QString &, const IArchiveRequest &)));
if (!restoreGeometry(Options::fileValue("history.archiveview.geometry").toByteArray()))
setGeometry(WidgetManager::alignGeometry(QSize(960,640),this));
if (!ui.sprSplitter->restoreState(Options::fileValue("history.archiveview.splitter-state").toByteArray()))
ui.sprSplitter->setSizes(QList<int>() << 50 << 150);
restoreState(Options::fileValue("history.archiveview.state").toByteArray());
setAddresses(AAddresses);
}
ArchiveViewWindow::~ArchiveViewWindow()
{
Options::setFileValue(saveState(),"history.archiveview.state");
Options::setFileValue(saveGeometry(),"history.archiveview.geometry");
Options::setFileValue(ui.sprSplitter->saveState(),"history.archiveview.splitter-state");
Options::node(OPV_HISTORY_ARCHIVEVIEW_FONTPOINTSIZE).setValue(ui.tbrMessages->font().pointSize());
}
QMultiMap<Jid,Jid> ArchiveViewWindow::addresses() const
{
return FAddresses;
}
void ArchiveViewWindow::setAddresses(const QMultiMap<Jid,Jid> &AAddresses)
{
if (FAddresses != AAddresses)
{
FAddresses = AAddresses;
QStringList namesList;
for (QMultiMap<Jid,Jid>::const_iterator it=FAddresses.constBegin(); it!=FAddresses.constEnd(); ++it)
{
if (!it.value().isEmpty())
namesList.append(contactName(it.key(),it.value(),isConferencePrivateChat(it.value())));
}
namesList = namesList.toSet().toList(); qSort(namesList);
setWindowTitle(tr("Conversation History") + (!namesList.isEmpty() ? " - " + namesList.join(", ") : QString::null));
FArchiveSearchEnabled = false;
foreach(const Jid &streamJid, FAddresses.uniqueKeys())
{
if ((FArchiver->totalCapabilities(streamJid) & IArchiveEngine::FullTextSearch) > 0)
{
FArchiveSearchEnabled = true;
break;
}
}
if (!FArchiveSearchEnabled)
{
ui.lneArchiveSearch->clear();
ui.lneArchiveSearch->setPlaceholderText(tr("Search is not supported"));
}
else
{
ui.lneArchiveSearch->setPlaceholderText(tr("Search in history"));
}
reset();
}
}
void ArchiveViewWindow::reset()
{
clearHeaders();
clearMessages();
FHistoryTime = 0;
FHeadersLoaded = 0;
FGroupByContact = FAddresses.values().contains(Jid::null);
FHeadersRequestTimer.start(0);
}
Jid ArchiveViewWindow::gatewayJid(const Jid &AContactJid) const
{
if (FFileMessageArchive!=NULL && !AContactJid.node().isEmpty())
{
QString gateType = FFileMessageArchive->contactGateType(AContactJid);
if (!gateType.isEmpty())
{
Jid gateJid = AContactJid;
gateJid.setDomain(QString("%1.gateway").arg(gateType));
return gateJid;
}
}
return AContactJid;
}
bool ArchiveViewWindow::isConferencePrivateChat(const Jid &AWith) const
{
return !AWith.resource().isEmpty() && AWith.pDomain().startsWith("conference.");
}
bool ArchiveViewWindow::isJidMatched(const Jid &ARequestWith, const Jid &AHeaderWith) const
{
if (ARequestWith.pBare() != AHeaderWith.pBare())
return false;
else if (!ARequestWith.resource().isEmpty() && ARequestWith.pResource()!=AHeaderWith.pResource())
return false;
return true;
}
QString ArchiveViewWindow::contactName(const Jid &AStreamJid, const Jid &AContactJid, bool AShowResource) const
{
IRoster *roster = FRosterManager!=NULL ? FRosterManager->findRoster(AStreamJid) : NULL;
IRosterItem ritem = roster!=NULL ? roster->findItem(AContactJid) : IRosterItem();
QString name = !ritem.name.isEmpty() ? ritem.name : AContactJid.uBare();
if (AShowResource && !AContactJid.resource().isEmpty())
name = name + "/" +AContactJid.resource();
return name;
}
QList<ArchiveHeader> ArchiveViewWindow::convertHeaders(const Jid &AStreamJid, const QList<IArchiveHeader> &AHeaders) const
{
QList<ArchiveHeader> headers;
for (QList<IArchiveHeader>::const_iterator it = AHeaders.constBegin(); it!=AHeaders.constEnd(); ++it)
{
ArchiveHeader header;
header.stream = AStreamJid;
header.with = it->with;
header.start = it->start;
header.subject = it->subject;
header.threadId = it->threadId;
header.engineId = it->engineId;
headers.append(header);
}
return headers;
}
ArchiveCollection ArchiveViewWindow::convertCollection(const Jid &AStreamJid, const IArchiveCollection &ACollection) const
{
ArchiveCollection collection;
collection.header = convertHeaders(AStreamJid,QList<IArchiveHeader>()<<ACollection.header).value(0);
collection.body = ACollection.body;
collection.next = ACollection.next;
collection.previous = ACollection.previous;
collection.attributes = ACollection.attributes;
return collection;
}
void ArchiveViewWindow::clearHeaders()
{
FModel->clear();
FCollections.clear();
FHeadersRequests.clear();
FCollectionsRequests.clear();
}
ArchiveHeader ArchiveViewWindow::itemHeader(const QStandardItem *AItem) const
{
ArchiveHeader header;
if (AItem->data(HDR_TYPE).toInt() == HIT_HEADER)
{
header.stream = AItem->data(HDR_HEADER_STREAM).toString();
header.with = AItem->data(HDR_HEADER_WITH).toString();
header.start = AItem->data(HDR_HEADER_START).toDateTime();
header.subject = AItem->data(HDR_HEADER_SUBJECT).toString();
header.threadId = AItem->data(HDR_HEADER_THREAD).toString();
header.version = AItem->data(HDR_HEADER_VERSION).toInt();
header.engineId = AItem->data(HDR_HEADER_ENGINE).toString();
}
return header;
}
QList<ArchiveHeader> ArchiveViewWindow::itemHeaders(const QStandardItem *AItem) const
{
QList<ArchiveHeader> headers;
if (AItem->data(HDR_TYPE) == HIT_HEADER)
headers.append(itemHeader(AItem));
else for (int row=0; row<AItem->rowCount(); row++)
headers += itemHeaders(AItem->child(row));
return headers;
}
QMultiMap<Jid,Jid> ArchiveViewWindow::itemAddresses(const QStandardItem *AItem) const
{
QMultiMap<Jid,Jid> address;
if (AItem->data(HDR_TYPE).toInt() != HIT_HEADER)
{
for (int row=0; row<AItem->rowCount(); row++)
{
QMultiMap<Jid,Jid> itemAddress = itemAddresses(AItem->child(row));
for (QMultiMap<Jid,Jid>::const_iterator it=itemAddress.constBegin(); it!=itemAddress.constEnd(); ++it)
{
if (!address.contains(it.key(),it.value()))
address.insertMulti(it.key(),it.value());
}
}
}
else
{
Jid streamJid = AItem->data(HDR_HEADER_STREAM).toString();
Jid contactJid = AItem->data(HDR_HEADER_WITH).toString();
address.insertMulti(streamJid,isConferencePrivateChat(contactJid) ? contactJid : contactJid.bare());
}
return address;
}
QList<ArchiveHeader> ArchiveViewWindow::itemsHeaders(const QList<QStandardItem *> &AItems) const
{
QList<ArchiveHeader> headers;
foreach(QStandardItem *item, filterChildItems(AItems))
headers.append(itemHeaders(item));
return headers;
}
QStandardItem *ArchiveViewWindow::findItem(int AType, int ARole, const QVariant &AValue, QStandardItem *AParent) const
{
QStandardItem *parent = AParent!=NULL ? AParent : FModel->invisibleRootItem();
for (int row=0; row<parent->rowCount(); row++)
{
QStandardItem *item = parent->child(row);
if (item->data(HDR_TYPE)==AType && item->data(ARole)==AValue)
return item;
}
return NULL;
}
QList<QStandardItem *> ArchiveViewWindow::selectedItems() const
{
QList<QStandardItem *> items;
foreach(const QModelIndex &proxyIndex, ui.trvHeaders->selectionModel()->selectedIndexes())
{
QModelIndex sourceIndex = FProxyModel->mapToSource(proxyIndex);
if (sourceIndex.isValid())
items.append(FModel->itemFromIndex(sourceIndex));
}
return items;
}
QList<QStandardItem *> ArchiveViewWindow::filterChildItems(const QList<QStandardItem *> &AItems) const
{
QList<QStandardItem *> items;
QSet<QStandardItem *> acceptParents;
QSet<QStandardItem *> declineParents;
foreach(QStandardItem *item, AItems)
{
QStandardItem *parentItem = item->parent();
if (parentItem == NULL)
{
items.append(item);
}
else if (acceptParents.contains(parentItem))
{
items.append(item);
}
else if (!declineParents.contains(parentItem))
{
QSet<QStandardItem *> parents;
bool isChild = false;
while (!isChild && parentItem!=NULL)
{
parents += parentItem;
isChild = AItems.contains(parentItem);
parentItem = parentItem->parent();
}
if (!isChild)
{
acceptParents += parents;
items.append(item);
}
else
{
declineParents += parents;
}
}
}
return items;
}
QList<QStandardItem *> ArchiveViewWindow::findStreamItems(const Jid &AStreamJid, QStandardItem *AParent) const
{
QList<QStandardItem *> items;
QStandardItem *parent = AParent!=NULL ? AParent : FModel->invisibleRootItem();
for (int row=0; row<parent->rowCount(); row++)
{
QStandardItem *item = parent->child(row);
if (item->data(HDR_TYPE) == HIT_HEADER)
{
if (AStreamJid == item->data(HDR_HEADER_STREAM).toString())
items.append(item);
}
else
{
items += findStreamItems(AStreamJid,item);
}
}
return items;
}
QList<QStandardItem *> ArchiveViewWindow::findRequestItems(const Jid &AStreamJid, const IArchiveRequest &ARequest, QStandardItem *AParent) const
{
QList<QStandardItem *> items;
QStandardItem *parent = AParent!=NULL ? AParent : FModel->invisibleRootItem();
for (int row=0; row<parent->rowCount(); row++)
{
QStandardItem *item = parent->child(row);
if (item->data(HDR_TYPE) == HIT_HEADER)
{
bool checked = true;
if (AStreamJid != item->data(HDR_HEADER_STREAM).toString())
checked = false;
else if (ARequest.with.isValid() && !isJidMatched(ARequest.with,item->data(HDR_HEADER_WITH).toString()))
checked = false;
else if (ARequest.start.isValid() && ARequest.start>item->data(HDR_HEADER_START).toDateTime())
checked = false;
else if (ARequest.end.isValid() && ARequest.end<item->data(HDR_HEADER_START).toDateTime())
checked = false;
else if (ARequest.start.isValid() && !ARequest.end.isValid() && ARequest.start!=item->data(HDR_HEADER_START).toDateTime())
checked = false;
else if (!ARequest.threadId.isEmpty() && ARequest.threadId!=item->data(HDR_HEADER_THREAD).toString())
checked = false;
if (checked)
items.append(item);
}
else
{
items += findRequestItems(AStreamJid,ARequest,item);
}
}
return items;
}
void ArchiveViewWindow::removeRequestItems(const Jid &AStreamJid, const IArchiveRequest &ARequest)
{
foreach(QStandardItem *item, findRequestItems(AStreamJid, ARequest))
{
FCollections.remove(itemHeader(item));
QStandardItem *parentItem = item->parent();
while (parentItem != NULL)
{
if (parentItem->rowCount() > 1)
{
parentItem->removeRow(item->row());
break;
}
else
{
item = parentItem;
parentItem = parentItem->parent();
}
}
if (parentItem == NULL)
qDeleteAll(FModel->takeRow(item->row()));
}
}
void ArchiveViewWindow::setRequestStatus(RequestStatus AStatus, const QString &AMessage)
{
Q_UNUSED(AStatus);
ui.stbStatusBar->showMessage(AMessage);
}
void ArchiveViewWindow::setHeaderStatus(RequestStatus AStatus, const QString &AMessage)
{
if (AStatus == RequestStarted)
FFocusWidget = focusWidget();
else
FHeadersLoaded = 0;
ui.trvHeaders->setEnabled(AStatus != RequestStarted);
ui.wdtArchiveSearch->setEnabled(AStatus!=RequestStarted && FArchiveSearchEnabled);
FHeaderActionLabel->disconnect(this);
FHeaderActionLabel->setEnabled(AStatus != RequestStarted);
FHeadersEmptyLabel->setVisible(AStatus!=RequestStarted && FCollections.isEmpty());
if (AStatus == RequestFinished)
{
if (FFocusWidget)
FFocusWidget->setFocus(Qt::MouseFocusReason);
if (FHistoryTime < HistoryTimeCount)
FHeaderActionLabel->setText(QString("<a href='link'>%1</a>").arg(tr("Load more conversations")));
else
FHeaderActionLabel->setText(tr("All conversations loaded"));
connect(FHeaderActionLabel,SIGNAL(linkActivated(QString)),SLOT(onHeadersLoadMoreLinkClicked()));
if (!FCollections.isEmpty())
ui.stbStatusBar->showMessage(tr("%n conversation header(s) found",0,FCollections.count()));
else
ui.stbStatusBar->showMessage(tr("Conversation headers are not found"));
ui.trvHeaders->selectionModel()->clearSelection();
ui.trvHeaders->setCurrentIndex(QModelIndex());
}
else if(AStatus == RequestStarted)
{
ui.stbStatusBar->showMessage(tr("Loading conversation headers..."));
}
else if (AStatus == RequestError)
{
if (FFocusWidget)
FFocusWidget->setFocus(Qt::MouseFocusReason);
FHeaderActionLabel->setText(QString("<a href='link'>%1</a>").arg(tr("Retry")));
connect(FHeaderActionLabel,SIGNAL(linkActivated(QString)),SLOT(onHeadersRequestTimerTimeout()));
ui.stbStatusBar->showMessage(tr("Failed to load conversation headers: %1").arg(AMessage));
}
}
void ArchiveViewWindow::setMessageStatus(RequestStatus AStatus, const QString &AMessage)
{
ui.wdtTextSearch->setEnabled(AStatus!=RequestStarted && !ui.tbrMessages->document()->isEmpty());
FMessagesEmptyLabel->setVisible(AStatus!=RequestStarted && ui.tbrMessages->document()->isEmpty());
FExportLabel->setVisible(AStatus!=RequestStarted && !ui.tbrMessages->document()->isEmpty());
if (AStatus == RequestFinished)
{
if (FSelectedHeaders.isEmpty())
ui.stbStatusBar->showMessage(tr("Select conversation to show"));
else
ui.stbStatusBar->showMessage(tr("%n conversation(s) shown",0,FSelectedHeaders.count()));
onTextSearchStart();
}
else if(AStatus == RequestStarted)
{
if (FSelectedHeaders.isEmpty())
ui.stbStatusBar->showMessage(tr("Loading conversations..."));
else
ui.stbStatusBar->showMessage(tr("Shown %1 of %2 conversations...").arg(FSelectedHeaderIndex+1).arg(FSelectedHeaders.count()));
}
else if (AStatus == RequestError)
{
ui.stbStatusBar->showMessage(tr("Failed to load conversations: %1").arg(AMessage));
}
}
QStandardItem *ArchiveViewWindow::createHeaderItem(const ArchiveHeader &AHeader)
{
QStandardItem *item = new QStandardItem(AHeader.start.toString("dd MMM, ddd"));
item->setData(HIT_HEADER,HDR_TYPE);
item->setData(AHeader.stream.pFull(),HDR_HEADER_STREAM);
item->setData(AHeader.with.pFull(),HDR_HEADER_WITH);
item->setData(AHeader.start,HDR_HEADER_START);
item->setData(AHeader.subject,HDR_HEADER_SUBJECT);
item->setData(AHeader.threadId,HDR_HEADER_THREAD);
item->setData(AHeader.version,HDR_HEADER_VERSION);
item->setData(AHeader.engineId.toString(),HDR_HEADER_ENGINE);
item->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_HISTORY_DATE));
QString itemToolTip = Qt::escape(AHeader.with.uFull());
if (!AHeader.subject.isEmpty())
itemToolTip += "<hr>" + Qt::escape(AHeader.subject);
item->setToolTip(itemToolTip);
createParentItem(AHeader)->appendRow(item);
return item;
}
QStandardItem *ArchiveViewWindow::createParentItem(const ArchiveHeader &AHeader)
{
QStandardItem *item = FModel->invisibleRootItem();
if (FGroupByContact)
{
IMetaContact meta = FMetaContacts!=NULL ? FMetaContacts->findMetaContact(AHeader.stream,AHeader.with) : IMetaContact();
if (!meta.isNull())
item = createMetacontactItem(AHeader.stream,meta,item);
else
item = createContactItem(AHeader.stream,AHeader.with,item);
}
if (!FAddresses.contains(AHeader.stream,AHeader.with) && isConferencePrivateChat(AHeader.with))
item = createPrivateChatItem(AHeader.stream,AHeader.with,item);
item = createDateGroupItem(AHeader.start,item);
return item;
}
QStandardItem *ArchiveViewWindow::createDateGroupItem(const QDateTime &ADateTime, QStandardItem *AParent)
{
QDate date(ADateTime.date().year(),ADateTime.date().month(),1);
QStandardItem *item = findItem(HIT_DATEGROUP,HDR_DATEGROUP_DATE,date,AParent);
if (item == NULL)
{
item = new QStandardItem(date.toString("MMMM yyyy"));
item->setData(HIT_DATEGROUP,HDR_TYPE);
item->setData(date,HDR_DATEGROUP_DATE);
item->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_HISTORY_DATE));
AParent->appendRow(item);
}
return item;
}
QStandardItem *ArchiveViewWindow::createContactItem(const Jid &AStreamJid, const Jid &AContactJid, QStandardItem *AParent)
{
Jid gateJid = gatewayJid(AContactJid);
QStandardItem *item = findItem(HIT_CONTACT,HDR_CONTACT_JID,gateJid.pBare(),AParent);
if (item == NULL)
{
item = new QStandardItem(contactName(AStreamJid,AContactJid));
item->setData(HIT_CONTACT,HDR_TYPE);
item->setData(gateJid.pBare(),HDR_CONTACT_JID);
item->setIcon(FStatusIcons!=NULL ? FStatusIcons->iconByJidStatus(AContactJid,IPresence::Online,SUBSCRIPTION_BOTH,false) : QIcon());
AParent->appendRow(item);
}
return item;
}
QStandardItem * ArchiveViewWindow::createPrivateChatItem(const Jid &AStreamJid, const Jid &AContactJid, QStandardItem *AParent)
{
Q_UNUSED(AStreamJid);
QStandardItem *item = findItem(HIT_CONTACT,HDR_CONTACT_JID,AContactJid.pFull(),AParent);
if (item == NULL)
{
item = new QStandardItem(AContactJid.resource());
item->setData(HIT_CONTACT,HDR_TYPE);
item->setData(AContactJid.pFull(),HDR_CONTACT_JID);
item->setIcon(FStatusIcons!=NULL ? FStatusIcons->iconByJidStatus(AContactJid,IPresence::Online,SUBSCRIPTION_BOTH,false) : QIcon());
AParent->appendRow(item);
}
return item;
}
QStandardItem * ArchiveViewWindow::createMetacontactItem(const Jid &AStreamJid, const IMetaContact &AMeta, QStandardItem *AParent)
{
Q_UNUSED(AStreamJid);
QStandardItem *item = findItem(HIT_CONTACT,HDR_METACONTACT_ID,AMeta.id.toString(),AParent);
if (item == NULL)
{
item = new QStandardItem(AMeta.name);
item->setData(HIT_CONTACT,HDR_TYPE);
item->setData(AMeta.id.toString(),HDR_METACONTACT_ID);
item->setIcon(FStatusIcons!=NULL ? FStatusIcons->iconByJidStatus(AMeta.items.value(0),IPresence::Online,SUBSCRIPTION_BOTH,false) : QIcon());
AParent->appendRow(item);
}
return item;
}
void ArchiveViewWindow::clearMessages()
{
FSearchResults.clear();
ui.tbrMessages->clear();
FSelectedHeaders.clear();
FSelectedHeaderIndex = 0;
FCollectionsProcessTimer.stop();
setMessageStatus(RequestFinished);
}
void ArchiveViewWindow::processCollectionsLoad()
{
if (FSelectedHeaderIndex < FSelectedHeaders.count())
{
ArchiveHeader header = loadingCollectionHeader();
ArchiveCollection collection = FCollections.value(header);
if (collection.body.messages.isEmpty() && collection.body.notes.isEmpty())
{
QString reqId = FArchiver->loadCollection(header.stream,header);
if (!reqId.isEmpty())
FCollectionsRequests.insert(reqId,header);
else
setMessageStatus(RequestError,tr("Archive is not accessible"));
}
else
{
showCollection(collection);
FCollectionsProcessTimer.start(0);
}
}
else
{
setMessageStatus(RequestFinished);
}
}
ArchiveHeader ArchiveViewWindow::loadingCollectionHeader() const
{
return FSelectedHeaders.value(FSelectedHeaderIndex);
}
void ArchiveViewWindow::showCollection(const ArchiveCollection &ACollection)
{
if (FSelectedHeaderIndex == 0)
{
ui.tbrMessages->clear();
FViewOptions.isPrivateChat = isConferencePrivateChat(ACollection.header.with);
FViewOptions.isGroupChat = false;
if (!FViewOptions.isPrivateChat)
for (int i=0; !FViewOptions.isGroupChat && i<ACollection.body.messages.count(); i++)
FViewOptions.isGroupChat = ACollection.body.messages.at(i).type()==Message::GroupChat;
if (FMessageStyleManager)
{
IMessageStyleOptions soptions = FMessageStyleManager->styleOptions(FViewOptions.isGroupChat ? Message::GroupChat : Message::Chat);
FViewOptions.style = FViewOptions.isGroupChat ? FMessageStyleManager->styleForOptions(soptions) : NULL;
}
else
{
FViewOptions.style = NULL;
}
FViewOptions.lastInfo = QString::null;
FViewOptions.lastSubject = QString::null;
}
FViewOptions.lastTime = QDateTime();
FViewOptions.lastSenderId = QString::null;
if (!FViewOptions.isPrivateChat)
FViewOptions.senderName = Qt::escape(FMessageStyleManager!=NULL ? FMessageStyleManager->contactName(ACollection.header.stream,ACollection.header.with) : contactName(ACollection.header.stream,ACollection.header.with));
else
FViewOptions.senderName = Qt::escape(ACollection.header.with.resource());
FViewOptions.selfName = Qt::escape(FMessageStyleManager!=NULL ? FMessageStyleManager->contactName(ACollection.header.stream) : ACollection.header.stream.uBare());
QString html = showInfo(ACollection);
IMessageStyleContentOptions options;
QList<Message>::const_iterator messageIt = ACollection.body.messages.constBegin();
QMultiMap<QDateTime,QString>::const_iterator noteIt = ACollection.body.notes.constBegin();
while (noteIt!=ACollection.body.notes.constEnd() || messageIt!=ACollection.body.messages.constEnd())
{
if (messageIt!=ACollection.body.messages.constEnd() && (noteIt==ACollection.body.notes.constEnd() || messageIt->dateTime()<noteIt.key()))
{
int direction = messageIt->data(MDR_MESSAGE_DIRECTION).toInt();
Jid senderJid = direction==IMessageProcessor::DirectionIn ? messageIt->from() : ACollection.header.stream;
options.type = IMessageStyleContentOptions::TypeEmpty;
options.kind = IMessageStyleContentOptions::KindMessage;
options.senderId = senderJid.full();
options.time = messageIt->dateTime();
options.timeFormat = FMessageStyleManager!=NULL ? FMessageStyleManager->timeFormat(options.time,ACollection.header.start) : QString::null;
if (FViewOptions.isGroupChat)
{
options.type |= IMessageStyleContentOptions::TypeGroupchat;
options.direction = IMessageStyleContentOptions::DirectionIn;
options.senderName = Qt::escape(!senderJid.resource().isEmpty() ? senderJid.resource() : senderJid.uNode());
options.senderColor = FViewOptions.style!=NULL ? FViewOptions.style->senderColor(options.senderName) : "blue";
}
else if (direction == IMessageProcessor::DirectionIn)
{
options.direction = IMessageStyleContentOptions::DirectionIn;
options.senderName = FViewOptions.senderName;
options.senderColor = "blue";
}
else
{
options.direction = IMessageStyleContentOptions::DirectionOut;
options.senderName = FViewOptions.selfName;
options.senderColor = "red";
}
html += showMessage(*messageIt,options);
++messageIt;
}
else if (noteIt != ACollection.body.notes.constEnd())
{
options.kind = IMessageStyleContentOptions::KindStatus;
options.type = IMessageStyleContentOptions::TypeEmpty;
options.senderId = QString::null;
options.senderName = QString::null;
options.time = noteIt.key();
options.timeFormat = FMessageStyleManager!=NULL ? FMessageStyleManager->timeFormat(options.time,ACollection.header.start) : QString::null;
html += showNote(*noteIt,options);
++noteIt;
}
}
QTextCursor cursor(ui.tbrMessages->document());
cursor.movePosition(QTextCursor::End);
cursor.insertHtml(html);
FSelectedHeaderIndex++;
setMessageStatus(RequestStarted);
}
QString ArchiveViewWindow::showInfo(const ArchiveCollection &ACollection)
{
static const QString infoTmpl =
"<table width='100%' cellpadding='0' cellspacing='0' style='margin-top:10px;'>"
" <tr bgcolor='%bgcolor%'>"
" <td style='padding-top:5px; padding-bottom:5px; padding-left:15px; padding-right:15px;'><span style='color:darkCyan;'>%info%</span>%subject%</td>"
" </tr>"
"</table>";
QString startDate;
startDate = ACollection.header.start.toString(QString("dd MMM yyyy hh:mm"));
QString info;
QString infoHash = ACollection.header.start.date().toString(Qt::ISODate);
if (FViewOptions.isPrivateChat)
{
QString withName = Qt::escape(ACollection.header.with.resource());
QString confName = Qt::escape(ACollection.header.with.uBare());
info = tr("<b>%1</b> with %2 in %3").arg(startDate,withName,confName);
infoHash += "~"+withName+"~"+confName;
}
else if (FViewOptions.isGroupChat)
{
QString confName = Qt::escape(ACollection.header.with.uBare());
info = tr("<b>%1</b> in %2").arg(startDate,confName);
infoHash += "~"+confName;
}
else
{
QString withName = Qt::escape(contactName(ACollection.header.stream,ACollection.header.with,true));
info = tr("<b>%1</b> with %2").arg(startDate,withName);
infoHash += "~"+withName;
}
QString subject;
if (!ACollection.header.subject.isEmpty() && FViewOptions.lastSubject!=ACollection.header.subject)
{
subject += "<br>";
if (FMessageProcessor)
{
Message message;
message.setBody(ACollection.header.subject);
QTextDocument doc;
FMessageProcessor->messageToText(&doc,message);
subject += TextManager::getDocumentBody(doc);
}
else
{
subject += Qt::escape(ACollection.header.subject);
}
FViewOptions.lastSubject = ACollection.header.subject;
}
infoHash += "~"+subject;
QString html;
if (FViewOptions.lastInfo != infoHash)
{
html = infoTmpl;
html.replace("%bgcolor%",ui.tbrMessages->palette().color(QPalette::AlternateBase).name());
html.replace("%info%",info);
html.replace("%subject%",subject);
FViewOptions.lastInfo = infoHash;
}
return html;
}
QString ArchiveViewWindow::showNote(const QString &ANote, const IMessageStyleContentOptions &AOptions)
{
static const QString statusTmpl =
"<table width='100%' cellpadding='0' cellspacing='0' style='margin-top:5px;'>"
" <tr>"
" <td width='3%'>*** </td>"
" <td style='white-space:pre-wrap; color:darkgreen;'>%message%</td>"
" <td width='5%' align='right' style='white-space:nowrap; font-size:small; color:gray;'>[%time%]</td>"
" </tr>"
"</table>";
FViewOptions.lastTime = AOptions.time;
FViewOptions.lastSenderId = AOptions.senderId;
QString html = statusTmpl;
html.replace("%time%",AOptions.time.toString(AOptions.timeFormat));
html.replace("%message%",Qt::escape(ANote));
return html;
}
QString ArchiveViewWindow::showMessage(const Message &AMessage, const IMessageStyleContentOptions &AOptions)
{
QString html;
bool meMessage = false;
if (!AOptions.senderName.isEmpty() && AMessage.body().startsWith("/me "))
{
static const QString meMessageTmpl =
"<table width='100%' cellpadding='0' cellspacing='0' style='margin-top:5px;'>"
" <tr>"
" <td style='padding-left:10px; white-space:pre-wrap;'><b><i>* <span style='color:%senderColor%;'>%sender%</span></i></b> %message%</td>"
" <td width='5%' align='right' style='white-space:nowrap; font-size:small; color:gray;'>[%time%]</td>"
" </tr>"
"</table>";
meMessage = true;
html = meMessageTmpl;
}
else if (AOptions.senderId.isEmpty() || AOptions.senderId!=FViewOptions.lastSenderId || qAbs(FViewOptions.lastTime.secsTo(AOptions.time))>2*60)
{
static const QString firstMessageTmpl =
"<table width='100%' cellpadding='0' cellspacing='0' style='margin-top:5px;'>"
" <tr>"
" <td style='color:%senderColor%; white-space:nowrap; font-weight:bold;'>%sender%</td>"
" <td width='5%' align='right' style='white-space:nowrap; font-size:small; color:gray;'>[%time%]</td>"
" </tr>"
" <tr>"
" <td colspan='2' style='padding-left:10px; white-space:pre-wrap;'>%message%</td>"
" </tr>"
"</table>";
html = firstMessageTmpl;
}
else
{
static const QString nextMessageTmpl =
"<table width='100%' cellpadding='0' cellspacing='0'>"
" <tr>"
" <td style='padding-left:10px; white-space:pre-wrap;'>%message%</td>"
" </tr>"
"</table>";
html = nextMessageTmpl;
}
FViewOptions.lastTime = AOptions.time;
FViewOptions.lastSenderId = AOptions.senderId;
html.replace("%sender%",AOptions.senderName);
html.replace("%senderColor%",AOptions.senderColor);
html.replace("%time%",AOptions.time.toString(AOptions.timeFormat));
QTextDocument doc;
if (FMessageProcessor)
FMessageProcessor->messageToText(&doc,AMessage);
else
doc.setPlainText(AMessage.body());
if (meMessage)
{
QTextCursor cursor(&doc);
cursor.movePosition(QTextCursor::NextCharacter,QTextCursor::KeepAnchor,4);
if (cursor.selectedText() == "/me ")
cursor.removeSelectedText();
}
html.replace("%message%",TextManager::getDocumentBody(doc));
return html;
}
void ArchiveViewWindow::onArchiveSearchStart()
{
ui.lneTextSearch->setText(ui.lneArchiveSearch->text());
reset();
}
void ArchiveViewWindow::onTextHilightTimerTimeout()
{
if (FSearchResults.count() > MAX_HILIGHT_ITEMS)
{
QList<QTextEdit::ExtraSelection> selections;
QPair<int,int> boundary = ui.tbrMessages->visiblePositionBoundary();
for (QMap<int, QTextEdit::ExtraSelection>::const_iterator it = FSearchResults.lowerBound(boundary.first); it!=FSearchResults.constEnd() && it.key()<boundary.second; ++it)
selections.append(it.value());
ui.tbrMessages->setExtraSelections(selections);
}
else
{
ui.tbrMessages->setExtraSelections(FSearchResults.values());
}
}
void ArchiveViewWindow::onTextVisiblePositionBoundaryChanged()
{
FTextHilightTimer.start(0);
}
void ArchiveViewWindow::onTextSearchStart()
{
FSearchResults.clear();
if (!ui.lneTextSearch->text().isEmpty())
{
QTextDocument::FindFlags options = (QTextDocument::FindFlag)0;
QTextCursor cursor(ui.tbrMessages->document());
do {
cursor = ui.tbrMessages->document()->find(ui.lneTextSearch->text(),cursor,options);
if (!cursor.isNull())
{
QTextEdit::ExtraSelection selection;
selection.cursor = cursor;
selection.format = cursor.charFormat();
selection.format.setBackground(Qt::yellow);
FSearchResults.insert(cursor.position(),selection);
cursor.clearSelection();
}
} while (!cursor.isNull());
}
else
{
ui.lblTextSearchInfo->clear();
}
if (!FSearchResults.isEmpty())
{
ui.tbrMessages->setTextCursor(FSearchResults.lowerBound(0)->cursor);
ui.tbrMessages->ensureCursorVisible();
ui.lblTextSearchInfo->setText(tr("Found %n occurrence(s)",0,FSearchResults.count()));
}
else if (!ui.lneTextSearch->text().isEmpty())
{
QTextCursor cursor = ui.tbrMessages->textCursor();
if (cursor.hasSelection())
{
cursor.clearSelection();
ui.tbrMessages->setTextCursor(cursor);
}
ui.lblTextSearchInfo->setText(tr("Phrase was not found"));
}
if (!ui.lneTextSearch->text().isEmpty() && FSearchResults.isEmpty())
{
QPalette palette = ui.lneTextSearch->palette();
palette.setColor(QPalette::Active,QPalette::Base,QColor(255,200,200));
ui.lneTextSearch->setPalette(palette);
}
else
{
ui.lneTextSearch->setPalette(QPalette());
}
ui.tlbTextSearchNext->setEnabled(!FSearchResults.isEmpty());
ui.tlbTextSearchPrev->setEnabled(!FSearchResults.isEmpty());
FTextHilightTimer.start(0);
}
void ArchiveViewWindow::onTextSearchNextClicked()
{
QMap<int,QTextEdit::ExtraSelection>::const_iterator it = FSearchResults.upperBound(ui.tbrMessages->textCursor().position());
if (it != FSearchResults.constEnd())
{
ui.tbrMessages->setTextCursor(it->cursor);
ui.tbrMessages->ensureCursorVisible();
}
}
void ArchiveViewWindow::onTextSearchPrevClicked()
{
QMap<int,QTextEdit::ExtraSelection>::const_iterator it = FSearchResults.lowerBound(ui.tbrMessages->textCursor().position());
if (--it != FSearchResults.constEnd())
{
ui.tbrMessages->setTextCursor(it->cursor);
ui.tbrMessages->ensureCursorVisible();
}
}
void ArchiveViewWindow::onSetContactJidByAction()
{
Action *action = qobject_cast<Action *>(sender());
if (action)
{
QStringList streams = action->data(ADR_HEADER_STREAM).toStringList();
QStringList contacts = action->data(ADR_HEADER_WITH).toStringList();
QMultiMap<Jid,Jid> address;
for(int i=0; i<streams.count(); i++)
address.insertMulti(streams.at(i),contacts.at(i));
setAddresses(address);
}
}
void ArchiveViewWindow::onRemoveCollectionsByAction()
{
Action *action = qobject_cast<Action *>(sender());
if (action!=NULL && FRemoveRequests.isEmpty())
{
QVariantList headerStream = action->data(ADR_HEADER_STREAM).toList();
QVariantList headerWith = action->data(ADR_HEADER_WITH).toList();
QVariantList headerStart = action->data(ADR_HEADER_START).toList();
QVariantList headerEnd = action->data(ADR_HEADER_END).toList();
QSet<QString> conversationSet;
for (int i=0; i<headerStream.count() && i<headerWith.count() && i<headerStart.count() && i<headerEnd.count(); i++)
{
QString name = contactName(headerStream.value(i).toString(),headerWith.value(i).toString(),headerEnd.at(i).isNull());
if (!headerEnd.at(i).isNull())
{
conversationSet += tr("with <b>%1</b> for <b>%2 %3</b>?").arg(Qt::escape(name))
.arg(QLocale().monthName(headerStart.at(i).toDate().month()))
.arg(headerStart.at(i).toDate().year());
}
else if (!headerStart.at(i).isNull())
{
conversationSet += tr("with <b>%1</b> started at <b>%2</b>?").arg(Qt::escape(name)).arg(headerStart.at(i).toDateTime().toString());
}
else
{
conversationSet += tr("with <b>%1</b> for all time?").arg(Qt::escape(name));
}
}
QStringList conversationList = conversationSet.toList();
if (conversationSet.count() > 15)
{
conversationList = conversationList.mid(0,10);
conversationList += tr("And %n other conversations","",conversationSet.count()-conversationList.count());
}
if (QMessageBox::question(this,
tr("Remove conversation history"),
tr("Do you want to remove the following conversations?") + QString("<ul><li>%1</li></ul>").arg(conversationList.join("</li><li>")),
QMessageBox::Yes|QMessageBox::No) == QMessageBox::Yes)
{
for (int i=0; i<headerStream.count() && i<headerWith.count() && i<headerStart.count() && i<headerEnd.count(); i++)
{
IArchiveRequest request;
request.with = headerWith.at(i).toString();
request.start = headerStart.at(i).toDateTime();
request.end = headerEnd.at(i).toDateTime();
request.exactmatch = !request.with.isEmpty() && request.with.node().isEmpty();
QString reqId = FArchiver->removeCollections(headerStream.at(i).toString(),request);
if (!reqId.isEmpty())
FRemoveRequests.insert(reqId,headerStream.at(i).toString());
if (!FRemoveRequests.isEmpty())
setRequestStatus(RequestStarted,tr("Removing conversations..."));
else
setRequestStatus(RequestError,tr("Failed to remove conversations: %1").arg(tr("Archive is not accessible")));
}
}
}
}
void ArchiveViewWindow::onHeaderContextMenuRequested(const QPoint &APos)
{
QList<QStandardItem *> items = filterChildItems(selectedItems());
if (!items.isEmpty())
{
Menu *menu = new Menu(this);
menu->setAttribute(Qt::WA_DeleteOnClose,true);
QVariantList headerStream;
QVariantList headerWith;
QVariantList headerStart;
QVariantList headerEnd;
foreach(QStandardItem *item, items)
{
QMultiMap<Jid,Jid> address = itemAddresses(item);
for (QMultiMap<Jid,Jid>::const_iterator it=address.constBegin(); it!=address.constEnd(); ++it)
{
headerStream.append(it.key().pFull());
headerWith.append(it.value().pFull());
int itemType = item->data(HDR_TYPE).toInt();
if (itemType == HIT_DATEGROUP)
{
QDate date = item->data(HDR_DATEGROUP_DATE).toDate();
headerStart.append(QDateTime(date));
headerEnd.append(QDateTime(date).addMonths(1));
}
else if (itemType == HIT_HEADER)
{
headerStart.append(item->data(HDR_HEADER_START));
headerEnd.append(QVariant());
}
else
{
headerStart.append(QVariant());
headerEnd.append(QVariant());
}
}
}
QStandardItem *item = items.value(0);
int itemType = item->data(HDR_TYPE).toInt();
if (items.count() > 1)
{
Action *removeSelected = new Action(menu);
removeSelected->setText(tr("Remove Selected Conversations"));
removeSelected->setData(ADR_HEADER_STREAM,headerStream);
removeSelected->setData(ADR_HEADER_WITH,headerWith);
removeSelected->setData(ADR_HEADER_START,headerStart);
removeSelected->setData(ADR_HEADER_END,headerEnd);
connect(removeSelected,SIGNAL(triggered()),SLOT(onRemoveCollectionsByAction()));
menu->addAction(removeSelected,AG_DEFAULT+500);
}
else if (itemType == HIT_CONTACT)
{
Action *setContact = new Action(menu);
setContact->setText(tr("Show Contact History"));
setContact->setData(ADR_HEADER_STREAM,headerStream);
setContact->setData(ADR_HEADER_WITH,headerWith);
connect(setContact,SIGNAL(triggered()),SLOT(onSetContactJidByAction()));
menu->addAction(setContact,AG_DEFAULT);
Action *removeAll = new Action(menu);
removeAll->setText(tr("Remove all History with %1").arg(item->text()));
removeAll->setData(ADR_HEADER_STREAM,headerStream);
removeAll->setData(ADR_HEADER_WITH,headerWith);
removeAll->setData(ADR_HEADER_START,headerStart);
removeAll->setData(ADR_HEADER_END,headerEnd);
connect(removeAll,SIGNAL(triggered()),SLOT(onRemoveCollectionsByAction()));
menu->addAction(removeAll,AG_DEFAULT+500);
}
else if (itemType == HIT_DATEGROUP)
{
Action *removeDate = new Action(menu);
QDate date = item->data(HDR_DATEGROUP_DATE).toDate();
removeDate->setText(tr("Remove History for %1").arg(item->text()));
removeDate->setData(ADR_HEADER_STREAM,headerStream);
removeDate->setData(ADR_HEADER_WITH,headerWith);
removeDate->setData(ADR_HEADER_START,headerStart);
removeDate->setData(ADR_HEADER_END,headerEnd);
connect(removeDate,SIGNAL(triggered()),SLOT(onRemoveCollectionsByAction()));
menu->addAction(removeDate,AG_DEFAULT+500);
}
else if (itemType == HIT_HEADER)
{
Action *removeHeader = new Action(menu);
removeHeader->setText(tr("Remove this Conversation"));
removeHeader->setData(ADR_HEADER_STREAM,headerStream);
removeHeader->setData(ADR_HEADER_WITH,headerWith);
removeHeader->setData(ADR_HEADER_START,headerStart);
removeHeader->setData(ADR_HEADER_END,headerEnd);
connect(removeHeader,SIGNAL(triggered()),SLOT(onRemoveCollectionsByAction()));
menu->addAction(removeHeader);
}
if (!menu->isEmpty())
menu->popup(ui.trvHeaders->viewport()->mapToGlobal(APos));
else
delete menu;
}
}
void ArchiveViewWindow::onPrintConversationsByAction()
{
QPrinter printer;
QPrintDialog *dialog = new QPrintDialog(&printer, this);
dialog->setWindowTitle(tr("Print Conversation History"));
if (ui.tbrMessages->textCursor().hasSelection())
dialog->addEnabledOption(QAbstractPrintDialog::PrintSelection);
if (dialog->exec() == QDialog::Accepted)
ui.tbrMessages->print(&printer);
}
void ArchiveViewWindow::onExportConversationsByAction()
{
Action *action = qobject_cast<Action *>(sender());
if (action)
{
bool isHtml = action->data(ADR_EXPORT_AS_HTML).toBool();
QString filter = isHtml ? tr("HTML file (*.html)") : tr("Text file (*.txt)");
QString fileName = QFileDialog::getSaveFileName(this, tr("Save Conversations to File"),QString::null,filter);
if (!fileName.isEmpty())
{
QFile file(fileName);
if (file.open(QFile::WriteOnly|QFile::Truncate))
{
if (isHtml)
file.write(ui.tbrMessages->toHtml().toUtf8());
else
file.write(ui.tbrMessages->toPlainText().toUtf8());
file.close();
}
else
{
LOG_ERROR(QString("Failed to export conversation history to file: %1").arg(file.errorString()));
}
}
}
}
void ArchiveViewWindow::onExportLabelLinkActivated(const QString &ALink)
{
Q_UNUSED(ALink);
if (!FSelectedHeaders.isEmpty())
{
Menu *menu = new Menu(this);
menu->setAttribute(Qt::WA_DeleteOnClose,true);
Action *exportPrinter = new Action(menu);
exportPrinter->setText(tr("Print..."));
exportPrinter->setData(ADR_EXPORT_AS_HTML, false);
connect(exportPrinter,SIGNAL(triggered()),SLOT(onPrintConversationsByAction()));
menu->addAction(exportPrinter);
Action *exportHtml = new Action(menu);
exportHtml->setText(tr("Save as HTML"));
exportHtml->setData(ADR_EXPORT_AS_HTML, true);
connect(exportHtml,SIGNAL(triggered()),SLOT(onExportConversationsByAction()));
menu->addAction(exportHtml);
Action *exportPlain = new Action(menu);
exportPlain->setText(tr("Save as Text"));
exportPlain->setData(ADR_EXPORT_AS_HTML, false);
connect(exportPlain,SIGNAL(triggered()),SLOT(onExportConversationsByAction()));
menu->addAction(exportPlain);
menu->popup(QCursor::pos());
}
}
void ArchiveViewWindow::onHeadersRequestTimerTimeout()
{
if (FHeadersRequests.isEmpty())
{
IArchiveRequest request;
if (FHistoryTime > 0)
{
request.end = QDateTime(QDate::currentDate().addMonths(HistoryTime[FHistoryTime-1]));
request.end = request.end.addDays(1-request.end.date().day());
}
if (FHistoryTime < HistoryTimeCount)
{
request.start = QDateTime(QDate::currentDate().addMonths(HistoryTime[FHistoryTime]));
request.start = request.start.addDays(1-request.start.date().day());
}
request.order = Qt::DescendingOrder;
request.text = ui.lneArchiveSearch->text().trimmed();
for(QMultiMap<Jid,Jid>::const_iterator it=FAddresses.constBegin(); it!=FAddresses.constEnd(); ++it)
{
request.with = it.value();
request.exactmatch = request.with.isValid() && request.with.node().isEmpty();
QString reqId = FArchiver->loadHeaders(it.key(),request);
if (!reqId.isEmpty())
FHeadersRequests.insert(reqId,it.key());
}
if (!FHeadersRequests.isEmpty())
setHeaderStatus(RequestStarted);
else
setHeaderStatus(RequestError,tr("Archive is not accessible"));
}
}
void ArchiveViewWindow::onHeadersLoadMoreLinkClicked()
{
if (FHistoryTime < HistoryTimeCount)
{
FHistoryTime++;
FHeadersRequestTimer.start(0);
}
else
{
setHeaderStatus(RequestFinished);
}
}
void ArchiveViewWindow::onCollectionsRequestTimerTimeout()
{
QList<ArchiveHeader> headers = itemsHeaders(selectedItems());
qSort(headers);
if (FSelectedHeaders != headers)
{
clearMessages();
FSelectedHeaders = headers;
setMessageStatus(RequestStarted);
processCollectionsLoad();
}
}
void ArchiveViewWindow::onCollectionsProcessTimerTimeout()
{
processCollectionsLoad();
}
void ArchiveViewWindow::onCurrentSelectionChanged(const QItemSelection &ASelected, const QItemSelection &ADeselected)
{
Q_UNUSED(ASelected); Q_UNUSED(ADeselected);
if (ui.trvHeaders->selectionModel()->hasSelection())
FCollectionsRequestTimer.start(LOAD_COLLECTION_TIMEOUT);
else if (!ui.tbrMessages->document()->isEmpty())
clearMessages();
}
void ArchiveViewWindow::onArchiveRequestFailed(const QString &AId, const XmppError &AError)
{
if (FHeadersRequests.contains(AId))
{
FHeadersRequests.remove(AId);
if (FHeadersRequests.isEmpty())
{
if (FHeadersLoaded == 0)
setHeaderStatus(RequestError, AError.errorMessage());
else if (FHeadersLoaded >= MIN_LOAD_HEADERS)
setHeaderStatus(RequestFinished);
else
onHeadersLoadMoreLinkClicked();
}
}
else if (FCollectionsRequests.contains(AId))
{
ArchiveHeader header = FCollectionsRequests.take(AId);
if (loadingCollectionHeader() == header)
{
FSelectedHeaders.removeAt(FSelectedHeaderIndex);
if (FSelectedHeaders.isEmpty())
setMessageStatus(RequestError, AError.errorMessage());
else
processCollectionsLoad();
}
}
else if (FRemoveRequests.contains(AId))
{
FRemoveRequests.remove(AId);
if (FRemoveRequests.isEmpty())
setRequestStatus(RequestError,tr("Failed to remove conversations: %1").arg(AError.errorMessage()));
}
}
void ArchiveViewWindow::onArchiveHeadersLoaded(const QString &AId, const QList<IArchiveHeader> &AHeaders)
{
if (FHeadersRequests.contains(AId))
{
QList<ArchiveHeader> headers = convertHeaders(FHeadersRequests.take(AId),AHeaders);
for (QList<ArchiveHeader>::const_iterator it = headers.constBegin(); it!=headers.constEnd(); ++it)
{
if (it->with.isValid() && it->start.isValid() && !FCollections.contains(*it))
{
ArchiveCollection collection;
collection.header = *it;
FCollections.insert(collection.header,collection);
createHeaderItem(collection.header);
FHeadersLoaded++;
}
}
if (FHeadersRequests.isEmpty())
{
if (FHeadersLoaded >= MIN_LOAD_HEADERS)
setHeaderStatus(RequestFinished);
else
onHeadersLoadMoreLinkClicked();
}
}
}
void ArchiveViewWindow::onArchiveCollectionLoaded(const QString &AId, const IArchiveCollection &ACollection)
{
if (FCollectionsRequests.contains(AId))
{
ArchiveHeader header = FCollectionsRequests.take(AId);
ArchiveCollection collection = convertCollection(header.stream,ACollection);
FCollections.insert(header,collection);
if (loadingCollectionHeader() == header)
{
showCollection(collection);
processCollectionsLoad();
}
}
}
void ArchiveViewWindow::onArchiveCollectionsRemoved(const QString &AId, const IArchiveRequest &ARequest)
{
if (FRemoveRequests.contains(AId))
{
Jid streamJid = FRemoveRequests.take(AId);
if (FRemoveRequests.isEmpty())
setRequestStatus(RequestFinished,tr("Conversation history removed successfully"));
removeRequestItems(streamJid,ARequest);
}
}
void ArchiveViewWindow::onRosterActiveChanged(IRoster *ARoster, bool AActive)
{
if (!AActive && FAddresses.contains(ARoster->streamJid()))
{
FAddresses.remove(ARoster->streamJid());
if (!FAddresses.isEmpty())
removeRequestItems(ARoster->streamJid(),IArchiveRequest());
else
close();
}
}
void ArchiveViewWindow::onRosterStreamJidChanged(IRoster *ARoster, const Jid &ABefore)
{
if (FAddresses.contains(ABefore))
{
foreach(const Jid &contactJid, FAddresses.values(ABefore))
FAddresses.insertMulti(ARoster->streamJid(),contactJid);
FAddresses.remove(ABefore);
foreach(QStandardItem *item, findStreamItems(ABefore))
item->setData(ARoster->streamJid().pFull(),HDR_HEADER_STREAM);
QMap<ArchiveHeader,ArchiveCollection> collections;
for (QMap<ArchiveHeader,ArchiveCollection>::iterator it=FCollections.begin(); it!=FCollections.end(); )
{
if (it.key().stream == ABefore)
{
ArchiveHeader header = it.key();
ArchiveCollection collection = it.value();
header.stream = ARoster->streamJid();
collection.header.stream = header.stream;
collections.insert(header,collection);
it = FCollections.erase(it);
}
else
{
++it;
}
}
FCollections.unite(collections);
}
}
| Nikoli/vacuum-im | src/plugins/messagearchiver/archiveviewwindow.cpp | C++ | gpl-3.0 | 55,709 |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "guiappwizarddialog.h"
#include "filespage.h"
#include <projectexplorer/projectexplorerconstants.h>
namespace QmakeProjectManager {
namespace Internal {
GuiAppParameters::GuiAppParameters()
: designerForm(true),
isMobileApplication(false)
{
}
GuiAppWizardDialog::GuiAppWizardDialog(const Core::BaseFileWizardFactory *factory,
const QString &templateName,
const QIcon &icon, QWidget *parent,
const Core::WizardDialogParameters ¶meters) :
BaseQmakeProjectWizardDialog(factory, false, parent, parameters),
m_filesPage(new FilesPage)
{
setWindowIcon(icon);
setWindowTitle(templateName);
setSelectedModules(QLatin1String("core gui"), true);
setIntroDescription(tr("This wizard generates a Qt Widgets Application "
"project. The application derives by default from QApplication "
"and includes an empty widget."));
addModulesPage();
if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
addTargetSetupPage();
m_filesPage->setFormInputCheckable(true);
m_filesPage->setClassTypeComboVisible(false);
addPage(m_filesPage);
addExtensionPages(extensionPages());
}
void GuiAppWizardDialog::setBaseClasses(const QStringList &baseClasses)
{
m_filesPage->setBaseClassChoices(baseClasses);
if (!baseClasses.empty())
m_filesPage->setBaseClassName(baseClasses.front());
}
void GuiAppWizardDialog::setSuffixes(const QString &header, const QString &source, const QString &form)
{
m_filesPage->setSuffixes(header, source, form);
}
void GuiAppWizardDialog::setLowerCaseFiles(bool l)
{
m_filesPage->setLowerCaseFiles(l);
}
QtProjectParameters GuiAppWizardDialog::projectParameters() const
{
QtProjectParameters rc;
rc.type = QtProjectParameters::GuiApp;
rc.flags |= QtProjectParameters::WidgetsRequiredFlag;
rc.fileName = projectName();
rc.path = path();
rc.selectedModules = selectedModulesList();
rc.deselectedModules = deselectedModulesList();
return rc;
}
GuiAppParameters GuiAppWizardDialog::parameters() const
{
GuiAppParameters rc;
rc.className = m_filesPage->className();
rc.baseClassName = m_filesPage->baseClassName();
rc.sourceFileName = m_filesPage->sourceFileName();
rc.headerFileName = m_filesPage->headerFileName();
rc.formFileName = m_filesPage->formFileName();
rc.designerForm = m_filesPage->formInputChecked();
if (isQtPlatformSelected("Android.Device.Type")) { // FIXME: Is this really necessary?
rc.isMobileApplication = true;
rc.widgetWidth = 800;
rc.widgetHeight = 480;
} else {
rc.isMobileApplication = false;
rc.widgetWidth = 400;
rc.widgetHeight = 300;
}
return rc;
}
} // namespace Internal
} // namespace QmakeProjectManager
| frostasm/qt-creator | src/plugins/qmakeprojectmanager/wizards/guiappwizarddialog.cpp | C++ | gpl-3.0 | 4,473 |
/*
* @Author: LIU CHENG
* @Date: 2017-02-22 18:39:38
* @Last Modified by: LIU CHENG
* @Last Modified time: 2017-03-05 11:39:18
*/
import React, { PropTypes } from 'react';
import {
Text,
View,
Image,
TouchableHighlight,
ActivityIndicator,
StyleSheet
} from 'react-native';
/**
* Dashboard
* props:
* avatar_url: String uri of avatar
* buttonsController: Array [{onPress:func, backgroundColor: Color, buttonText: String}]
* loading: Boolean, if data is prepared
*/
function Dashboard(props) {
const { avatar_url, buttonsController, loading } = props;
return (
<View style={styles.container}>
{loading ? (
<ActivityIndicator
animating={loading}
color="#111"
size="large"
style={styles.image}
/>
) : (
<Image source={{uri: avatar_url}} style={styles.image} />
)}
{buttonsController.map((item, index) =>
(
<TouchableHighlight
key={index}
onPress={item.onPress}
style={[styles.button, {backgroundColor: item.backgroundColor}]}
underlayColor="#8BD4F5"
>
<Text style={styles.buttonText}>{item.buttonText}</Text>
</TouchableHighlight>
)
)}
</View>
)
}
Dashboard.propTypes = {
avatar_url: PropTypes.string.isRequired,
buttonsController: PropTypes.array.isRequired,
loading: PropTypes.bool.isRequired,
}
const styles = StyleSheet.create({
container: {
marginTop: 65,
flex: 1
},
image: {
height: 350
},
buttonText: {
fontSize: 24,
color: 'white',
alignSelf: 'center'
},
button: {
flexDirection: 'row',
alignSelf: 'stretch',
justifyContent: 'center',
flex: 1
}
});
export default Dashboard; | kimochg/react-native-githubnote-app | src/components/Dashboard.js | JavaScript | gpl-3.0 | 1,787 |
package plainsimple.space;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* Renders an image of a starry sky based on several parameters.
* Copyright(C) Plain Simple Apps 2015
* See github.com/Plain-Simple/GalaxyDraw for more information.
* Licensed under GPL GNU Version 3 (see license.txt)
*/
public class DrawSpace {
// color of stars
private Color starColor;
// color of background
private Color backgroundColor;
// whether or not to use gradient
private boolean useGradient;
// gradient to use, if backgroundGradient = true
private GradientPaint backgroundGradient;
// stars per 2500 px (50*50 square)
private double density;
// alpha value used when drawing stars
private int brightness;
// radius of stars, in px
private int starSize;
// random variance from given values
private double variance;
// used for random number generation
private Random random;
public Color getStarColor() {
return starColor;
}
public void setStarColor(Color starColor) {
this.starColor = starColor;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
}
public double getDensity() {
return density;
}
public void setDensity(double density) {
this.density = density;
}
public int getBrightness() {
return brightness;
}
public void setBrightness(int brightness) {
this.brightness = brightness;
}
public int getStarSize() {
return starSize;
}
public void setStarSize(int starSize) {
this.starSize = starSize;
}
public boolean usesGradient() {
return useGradient;
}
public void setUseGradient(boolean useGradient) {
this.useGradient = useGradient;
}
public GradientPaint getBackgroundGradient() {
return backgroundGradient;
}
public void setBackgroundGradient(GradientPaint backgroundGradient) {
this.backgroundGradient = backgroundGradient;
}
public double getVariance() {
return variance;
}
public void setVariance(double variance) {
this.variance = variance;
}
// init with default values
public DrawSpace() {
density = 5;
brightness = 150;
starSize = 3;
variance = 0.4;
starColor = new Color(255, 255, 238);
backgroundColor = Color.BLACK;
useGradient = false;
random = new Random();
}
// creates BufferedImage of given dimensions and renders space on it
public BufferedImage drawSpace(int imgWidth, int imgHeight) {
BufferedImage generated = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
drawSpace(generated);
return generated;
}
// renders space on given BufferedImage
public void drawSpace(BufferedImage canvas) {
Graphics2D graphics = canvas.createGraphics();
drawBackground(graphics, canvas.getWidth(), canvas.getHeight());
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int num_stars = (int) (canvas.getWidth() * canvas.getHeight() / 2500.0 * density);
for (int i = 0; i < num_stars; i++) {
drawStar(graphics, random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()),
varyBrightness(brightness, variance), varySize(starSize, variance));
}
}
private void drawBackground(Graphics2D graphics, int imgWidth, int imgHeight) {
if (useGradient) {
graphics.setPaint(backgroundGradient);
graphics.fillRect(0, 0, imgWidth, imgHeight);
} else {
graphics.setColor(backgroundColor);
graphics.fillRect(0, 0, imgWidth, imgHeight);
}
}
private void drawStar(Graphics2D graphics, int x, int y, int brightness, int size) {
graphics.setColor(starColor);
graphics.setColor(new Color(starColor.getRed(), starColor.getBlue(), starColor.getGreen(), brightness));
graphics.fillOval(x, y, size, size);
}
private int varyBrightness(int value, double variance) {
int varied = value + random.nextInt((int) (value * variance * 100)) / 100;
if (varied > 255) {
return 255;
} else {
return varied;
}
}
private int varySize(int value, double variance) {
return value + random.nextInt((int) (value * variance * 100)) / 100;
}
}
| Plain-Simple/GalaxyDraw | java/src/plainsimple/galaxydraw/DrawSpace.java | Java | gpl-3.0 | 4,687 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using FastColoredTextBoxNS.Enums;
using KEYS = System.Windows.Forms.Keys;
namespace FastColoredTextBoxNS
{
/// <summary>
/// Dictionary of shortcuts for FCTB
/// </summary>
public class HotkeysMapping : SortedDictionary<Keys, FCTBAction>
{
public virtual void InitDefault()
{
this[KEYS.Control | KEYS.G] = FCTBAction.GoToDialog;
this[KEYS.Control | KEYS.F] = FCTBAction.FindDialog;
this[KEYS.Alt | KEYS.F] = FCTBAction.FindChar;
// this[KEYS.F3] = FCTBAction.FindNext;
this[KEYS.Control | KEYS.H] = FCTBAction.ReplaceDialog;
this[KEYS.Control | KEYS.C] = FCTBAction.Copy;
this[KEYS.Control | KEYS.Shift | KEYS.C] = FCTBAction.CommentSelected;
this[KEYS.Control | KEYS.X] = FCTBAction.Cut;
this[KEYS.Control | KEYS.V] = FCTBAction.Paste;
this[KEYS.Control | KEYS.A] = FCTBAction.SelectAll;
this[KEYS.Control | KEYS.Z] = FCTBAction.Undo;
this[KEYS.Control | KEYS.R] = FCTBAction.Redo;
this[KEYS.Control | KEYS.U] = FCTBAction.UpperCase;
this[KEYS.Shift | KEYS.Control | KEYS.U] = FCTBAction.LowerCase;
this[KEYS.Control | KEYS.OemMinus] = FCTBAction.NavigateBackward;
this[KEYS.Control | KEYS.Shift | KEYS.OemMinus] = FCTBAction.NavigateForward;
this[KEYS.Control | KEYS.B] = FCTBAction.BookmarkLine;
this[KEYS.Control | KEYS.Shift | KEYS.B] = FCTBAction.UnbookmarkLine;
this[KEYS.Control | KEYS.N] = FCTBAction.GoNextBookmark;
this[KEYS.Control | KEYS.Shift | KEYS.N] = FCTBAction.GoPrevBookmark;
this[KEYS.Alt | KEYS.Back] = FCTBAction.Undo;
this[KEYS.Control | KEYS.Back] = FCTBAction.ClearWordLeft;
this[KEYS.Insert] = FCTBAction.ReplaceMode;
this[KEYS.Control | KEYS.Insert] = FCTBAction.Copy;
this[KEYS.Shift | KEYS.Insert] = FCTBAction.Paste;
this[KEYS.Delete] = FCTBAction.DeleteCharRight;
this[KEYS.Control | KEYS.Delete] = FCTBAction.ClearWordRight;
this[KEYS.Shift | KEYS.Delete] = FCTBAction.Cut;
this[KEYS.Left] = FCTBAction.GoLeft;
this[KEYS.Shift | KEYS.Left] = FCTBAction.GoLeftWithSelection;
this[KEYS.Control | KEYS.Left] = FCTBAction.GoWordLeft;
this[KEYS.Control | KEYS.Shift | KEYS.Left] = FCTBAction.GoWordLeftWithSelection;
this[KEYS.Alt | KEYS.Shift | KEYS.Left] = FCTBAction.GoLeft_ColumnSelectionMode;
this[KEYS.Right] = FCTBAction.GoRight;
this[KEYS.Shift | KEYS.Right] = FCTBAction.GoRightWithSelection;
this[KEYS.Control | KEYS.Right] = FCTBAction.GoWordRight;
this[KEYS.Control | KEYS.Shift | KEYS.Right] = FCTBAction.GoWordRightWithSelection;
this[KEYS.Alt | KEYS.Shift | KEYS.Right] = FCTBAction.GoRight_ColumnSelectionMode;
this[KEYS.Up] = FCTBAction.GoUp;
this[KEYS.Shift | KEYS.Up] = FCTBAction.GoUpWithSelection;
this[KEYS.Alt | KEYS.Shift | KEYS.Up] = FCTBAction.GoUp_ColumnSelectionMode;
this[KEYS.Alt | KEYS.Up] = FCTBAction.MoveSelectedLinesUp;
this[KEYS.Control | KEYS.Up] = FCTBAction.ScrollUp;
this[KEYS.Down] = FCTBAction.GoDown;
this[KEYS.Shift | KEYS.Down] = FCTBAction.GoDownWithSelection;
this[KEYS.Alt | KEYS.Shift | KEYS.Down] = FCTBAction.GoDown_ColumnSelectionMode;
this[KEYS.Alt | KEYS.Down] = FCTBAction.MoveSelectedLinesDown;
this[KEYS.Control | KEYS.Down] = FCTBAction.ScrollDown;
this[KEYS.PageUp] = FCTBAction.GoPageUp;
this[KEYS.Shift | KEYS.PageUp] = FCTBAction.GoPageUpWithSelection;
this[KEYS.PageDown] = FCTBAction.GoPageDown;
this[KEYS.Shift | KEYS.PageDown] = FCTBAction.GoPageDownWithSelection;
this[KEYS.Home] = FCTBAction.GoHome;
this[KEYS.Shift | KEYS.Home] = FCTBAction.GoHomeWithSelection;
this[KEYS.Control | KEYS.Home] = FCTBAction.GoFirstLine;
this[KEYS.Control | KEYS.Shift | KEYS.Home] = FCTBAction.GoFirstLineWithSelection;
this[KEYS.End] = FCTBAction.GoEnd;
this[KEYS.Shift | KEYS.End] = FCTBAction.GoEndWithSelection;
this[KEYS.Control | KEYS.End] = FCTBAction.GoLastLine;
this[KEYS.Control | KEYS.Shift | KEYS.End] = FCTBAction.GoLastLineWithSelection;
this[KEYS.Escape] = FCTBAction.ClearHints;
this[KEYS.Control | KEYS.M] = FCTBAction.MacroRecord;
this[KEYS.Control | KEYS.E] = FCTBAction.MacroExecute;
this[KEYS.Control | KEYS.Space] = FCTBAction.AutocompleteMenu;
this[KEYS.Tab] = FCTBAction.IndentIncrease;
this[KEYS.Shift | KEYS.Tab] = FCTBAction.IndentDecrease;
this[KEYS.Control | KEYS.Subtract] = FCTBAction.ZoomOut;
this[KEYS.Control | KEYS.Add] = FCTBAction.ZoomIn;
this[KEYS.Control | KEYS.D0] = FCTBAction.ZoomNormal;
this[KEYS.Control | KEYS.I] = FCTBAction.AutoIndentChars;
}
public override string ToString()
{
var cult = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
StringBuilder sb = new StringBuilder();
var kc = new KeysConverter();
foreach (var pair in this)
{
sb.AppendFormat("{0}={1}, ", kc.ConvertToString(pair.Key), pair.Value);
}
if (sb.Length > 1)
sb.Remove(sb.Length - 2, 2);
Thread.CurrentThread.CurrentUICulture = cult;
return sb.ToString();
}
public static HotkeysMapping Parse(string s)
{
var result = new HotkeysMapping();
result.Clear();
var cult = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
var kc = new KeysConverter();
foreach (var p in s.Split(','))
{
var pp = p.Split('=');
var k = (Keys)kc.ConvertFromString(pp[0].Trim());
var a = (FCTBAction)Enum.Parse(typeof(FCTBAction), pp[1].Trim());
result[k] = a;
}
Thread.CurrentThread.CurrentUICulture = cult;
return result;
}
}
}
| JannikArndt/Canal | FastColoredTextBox/HotkeysMapping.cs | C# | gpl-3.0 | 6,652 |
/*
* DexPatcher - Copyright 2015-2020 Rodrigo Balerdi
* (GNU General Public License version 3 or later)
*
* DexPatcher 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.
*/
package lanchon.dexpatcher.transform.util.wrapper;
import org.jf.dexlib2.base.BaseAnnotationElement;
import org.jf.dexlib2.iface.AnnotationElement;
import org.jf.dexlib2.iface.value.EncodedValue;
public class WrapperAnnotationElement extends BaseAnnotationElement {
protected final AnnotationElement wrappedAnnotationElement;
public WrapperAnnotationElement(AnnotationElement wrappedAnnotationElement) {
this.wrappedAnnotationElement = wrappedAnnotationElement;
}
@Override
public String getName() {
return wrappedAnnotationElement.getName();
}
@Override
public EncodedValue getValue() {
return wrappedAnnotationElement.getValue();
}
} | Lanchon/DexPatcher-tool | tool/src/main/java/lanchon/dexpatcher/transform/util/wrapper/WrapperAnnotationElement.java | Java | gpl-3.0 | 1,021 |
package org.trypticon.haqua;
import com.apple.laf.AquaMenuItemUI;
import org.jetbrains.annotations.NotNull;
import javax.accessibility.Accessible;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.MenuItemUI;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
* @author trejkaz
*/
public class HaquaMenuItemUI extends MenuItemUI {
private final AquaMenuItemUI delegate;
public HaquaMenuItemUI(AquaMenuItemUI delegate) {
this.delegate = delegate;
}
@NotNull
@SuppressWarnings("UnusedDeclaration") // called via reflection
public static ComponentUI createUI(JComponent component) {
// Unfortunately the constructor for AquaMenuItemUI is package local, so we can't just inherit from it. :(
return new HaquaMenuItemUI((AquaMenuItemUI) AquaMenuItemUI.createUI(component));
}
@Override
public void update(Graphics g, JComponent c) {
if (!c.getComponentOrientation().isLeftToRight()) {
Graphics2D gCopy = (Graphics2D) g.create();
try {
// By painting 9 pixels to the right, 9 pixels on the left of the background are not painted,
// so we work around that here.
delegate.paintBackground(g, c, c.getWidth(), c.getHeight());
// AquaMenuUI paints the item 9 pixels too far left in right-to-left orientation.
gCopy.translate(9, 0);
delegate.update(gCopy, c);
} finally {
gCopy.dispose();
}
} else {
delegate.update(g, c);
}
}
// Not overriding (nor delegating) paint() at the moment but we overrode update() and that seems to suffice.
// Everything below is straight delegation.
@Override
public void installUI(JComponent c) {
delegate.installUI(c);
}
@Override
public void uninstallUI(JComponent c) {
delegate.uninstallUI(c);
}
@Override
public Dimension getPreferredSize(JComponent c) {
return delegate.getPreferredSize(c);
}
@Override
public Dimension getMinimumSize(JComponent c) {
return delegate.getMinimumSize(c);
}
@Override
public Dimension getMaximumSize(JComponent c) {
return delegate.getMaximumSize(c);
}
@Override
public boolean contains(JComponent c, int x, int y) {
return delegate.contains(c, x, y);
}
@Override
public int getBaseline(JComponent c, int width, int height) {
return delegate.getBaseline(c, width, height);
}
@Override
public Component.BaselineResizeBehavior getBaselineResizeBehavior(JComponent c) {
return delegate.getBaselineResizeBehavior(c);
}
@Override
public int getAccessibleChildrenCount(JComponent c) {
return delegate.getAccessibleChildrenCount(c);
}
@Override
public Accessible getAccessibleChild(JComponent c, int i) {
return delegate.getAccessibleChild(c, i);
}
}
| trejkaz/haqua | src/org/trypticon/haqua/HaquaMenuItemUI.java | Java | gpl-3.0 | 3,093 |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import View
from .models import \
Course, Registration, Task, TaskSubmission, ScoreProfile
from .forms import TaskSubmissionForm
class CourseListView(View):
template_name = 'courses/course_select.html'
@method_decorator(login_required)
def get(self, request, *args, **kwargs):
context = {
'courses': request.user.course_set.all(),
'profile': ScoreProfile.get_score_profile(request.user),
'highscore': ScoreProfile.objects.all().order_by('-score')[:10]
}
return render(request,
self.template_name,
context)
@method_decorator(login_required)
def post(self, request, *args, **kwargs):
pass
class ProfileView(View):
@method_decorator(login_required)
def get(self, request, *args, **kwargs):
context = {}
profile = ScoreProfile.get_score_profile(request.user)
context['username'] = request.user.username
context['rank'] = profile.current_rank
context['score'] = profile.score
context['courses'] = request.user.course_set.all()
context['valid_submissions'] = \
TaskSubmission.objects.filter(submitted_by=request.user,
valid=True).values_list('task',
flat=True)
return render(request, 'courses/profile.html', context)
class TaskSubmissionView(View):
form_class = TaskSubmissionForm
template_name = 'courses/task.html'
@method_decorator(login_required)
def get(self, request, *args, **kwargs):
context = self.get_context_data()
context['form'] = self.form_class()
context['subs'] = TaskSubmission.objects.filter(
submitted_by=request.user,
task=self.kwargs['task_id']
)
context['valid_subs'] = context['subs'].filter(
valid=True
)
return render(request, self.template_name, context)
@method_decorator(login_required)
def post(self, request, *args, **kwargs):
task = Task.objects.get(pk=self.kwargs['task_id'])
sub = TaskSubmission()
sub.task = task
sub.submitted_by = request.user
sub.valid = False
form = self.form_class(request.POST, request.FILES, instance=sub)
if form.is_valid():
form.save()
return self.get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = {}
context['task'] = Task.objects.get(pk=self.kwargs['task_id'])
return context
class CourseRegistrationView(View):
@method_decorator(login_required)
def post(self, request, *args, **kwargs):
course_id = request.POST['course_id']
course = Course.objects.get(pk=course_id)
if course:
Registration.objects.filter(user=request.user,
course=course).delete()
else:
return
if request.POST['sign_up'] == u'master':
Registration(user=request.user,
course=course,
granted=False,
code_master=True,
role=Registration.CODE_MASTER).save()
elif request.POST['sign_up'] == u'kid':
Registration(user=request.user,
course=course,
granted=False,
code_master=False,
role=Registration.KID).save()
elif request.POST['sign_up'] == u'reserve':
Registration(user=request.user,
course=course,
granted=False,
code_master=False,
role=Registration.RESERVE).save()
return
| iver56/trondheim.kodeklubben.no | backend/wsgi/courses/views.py | Python | gpl-3.0 | 4,033 |
#include "InspectorAtemCutWidget.h"
#include "Global.h"
#include "DatabaseManager.h"
#include "EventManager.h"
#include "Models/Atem/AtemStepModel.h"
#include <QtGui/QApplication>
InspectorAtemCutWidget::InspectorAtemCutWidget(QWidget* parent)
: QWidget(parent),
model(NULL), command(NULL)
{
setupUi(this);
QObject::connect(&EventManager::getInstance(), SIGNAL(rundownItemSelected(const RundownItemSelectedEvent&)), this, SLOT(rundownItemSelected(const RundownItemSelectedEvent&)));
loadAtemStep();
}
void InspectorAtemCutWidget::rundownItemSelected(const RundownItemSelectedEvent& event)
{
this->model = event.getLibraryModel();
blockAllSignals(true);
if (dynamic_cast<AtemCutCommand*>(event.getCommand()))
{
this->command = dynamic_cast<AtemCutCommand*>(event.getCommand());
this->comboBoxStep->setCurrentIndex(this->comboBoxStep->findData(this->command->getStep()));
this->checkBoxTriggerOnNext->setChecked(this->command->getTriggerOnNext());
}
checkEmptyStep();
blockAllSignals(false);
}
void InspectorAtemCutWidget::blockAllSignals(bool block)
{
this->comboBoxStep->blockSignals(block);
this->checkBoxTriggerOnNext->blockSignals(block);
}
void InspectorAtemCutWidget::loadAtemStep()
{
// We do not have a command object, block the signals.
// Events will not be triggered while we update the values.
this->comboBoxStep->blockSignals(true);
QList<AtemStepModel> models = DatabaseManager::getInstance().getAtemStep();
foreach (AtemStepModel model, models)
{
this->comboBoxStep->addItem(model.getName(), model.getValue());
break; // We can't do CUT on DSK.
}
this->comboBoxStep->blockSignals(false);
}
void InspectorAtemCutWidget::checkEmptyStep()
{
if (this->comboBoxStep->isEnabled() && this->comboBoxStep->currentText() == "")
this->comboBoxStep->setStyleSheet("border-color: firebrick;");
else
this->comboBoxStep->setStyleSheet("");
}
void InspectorAtemCutWidget::stepChanged(int index)
{
this->command->setStep(this->comboBoxStep->itemData(index).toString());
checkEmptyStep();
}
void InspectorAtemCutWidget::triggerOnNextChanged(int state)
{
this->command->setTriggerOnNext((state == Qt::Checked) ? true : false);
}
| CasparPlay/CasparPlay | src/Widgets/Inspector/Atem/InspectorAtemCutWidget.cpp | C++ | gpl-3.0 | 2,391 |
import { commitMutation, graphql } from 'react-relay'
import { ConnectionHandler } from 'relay-runtime'
const mutation = graphql`
mutation CreateSpeciesMutation($input: CreateSpeciesInput!) {
createSpecies(input: $input) {
clientMutationId
speciesEdge {
node {
authorId
id
nodeId
air
temp
water
soil
}
}
query {
...SpeciesList_query
}
}
}
`
let nextClientMutationId = 0
const commit = (environment, { species, viewer }) =>
new Promise((resolve, reject) => {
const clientMutationId = nextClientMutationId++
const variables = {
input: {
clientMutationId,
species: {
...species,
authorId: viewer.id,
},
},
}
return commitMutation(environment, {
mutation,
variables,
onError: (error: Error) => {
reject(error)
},
onCompleted: (response: Object) => {
resolve(response)
},
// See https://github.com/facebook/relay/issues/1701#issuecomment-301012344
// and also https://github.com/facebook/relay/issues/1701#issuecomment-300995425
// and also https://github.com/facebook/relay/issues/1701
updater: store => {
const payload = store.getRootField('createSpecies')
const newEdge = payload.getLinkedRecord('speciesEdge')
const storeRoot = store.getRoot()
const connection = ConnectionHandler.getConnection(
storeRoot,
'SpeciesList_species',
{ first: 2147483647, orderBy: 'GENUS_ASC' }
)
if (connection) {
ConnectionHandler.insertEdgeBefore(connection, newEdge)
} else {
console.error('No connection found')
}
},
})
})
export default { commit }
| doeg/plantly-graphql | web/src/mutations/CreateSpeciesMutation.js | JavaScript | gpl-3.0 | 1,851 |
Wordpress 4.5.3 = 32fe0b53f931d8d480d903d317a5222a
Wordpress 4.6.1 = 26ff384d827d76b9b144f91b6b0064ea
Wordpress 4.1.13 = 878cb407a1aadba406b15976bba92ff2
Wordpress 4.7 = dfa381ff18f6a4b2fab2d8f72439d1f0
Wordpress 3.8.16 = cc6b4758554d3890e240c25e635e7327
Wordpress 3.5.2 = f87cc3f946d03ebf18e7ad30b3c8d856
Wordpress 4.2.13 = 3ebc5756031d6a12741708aed3267434
Wordpress 4.3.9 = 6b20cc2820278fa30ed885612523b8ca
Wordpress 3.4.2 = 7f2cc2640430694eb81a7359c0468729
Wordpress 4.4.2 = a2df3049bfb8adbf8769e1ebf13bf84f
Wordpress 4.0 = 96053d580857302f0e8964114fb273a7
Wordpress 4.8 = e79a20a923f67c6a9143cebe35a17b3c
Wordpress 4.9 = 60dbc96030a61bb695319279ec586811
Wordpress 5.0.3 = f760f5828e3137c624522b11e381b5dc
Wordpress 5.1.1 = bfaee3c6e1148603508eabe129d93267
Wordpress 5.2.2 = 9ceba27bca308fe45d6c4536460f7936
Wordpress 5.3.1 = 95f1e6205267b00d9049c57b9b2652e2
| gohdan/DFC | known_files/hashes/wp-includes/author-template.php | PHP | gpl-3.0 | 862 |
var fs = require('fs')
// Script directories
var settings = require('./settings.json'); // The settings file
var scriptDir = settings.scriptDir + '/'; // The directory where dota scripts are placed
var scriptDirOut = settings.scriptDirOut; // The directory where our files are outputted
var resourcePath = settings.dotaDir + 'game/dota/resource/'; // The directory to read resource files from
var customDir = settings.customDir; // The directory where our mods are read from, to be merged in
var customAbilitiesLocation = '../src/scripts/npc/npc_abilities_custom.txt'
var langDir = '../src/localization/';
// Code needed to do multipliers
var spellMult = require('./spellMult.json');
// Create the output folder
if(!fs.existsSync(scriptDirOut)) fs.mkdirSync(scriptDirOut);
// Create the output folder
//if(!fs.existsSync(scriptDirOut)) fs.mkdirSync(scriptDirOut);
// Store for our custom stuff
var customAbilities = {};
var customUnits = {};
//var customItems = {};
//var items = {};
var abilities = {};
/*
Prepare language files
*/
var langs = ['english', 'schinese'];
var langIn = {};
var langOut = {};
var specialChar; // Special character needed for doto encoding
// theString is the string we search for and use as a key to store in
// if theString can't be find, search using altString
// search in actual language, if that fails, search in english, if that fails, commit suicide
function generateLanguage(theString, altString, appendOnEnd) {
// Grab a reference to english
var english = langIn.english;
if(appendOnEnd == null) appendOnEnd = '';
for(var i=0; i<langs.length; ++i) {
// Grab a language
var lang = langs[i];
var langFile = langIn[lang];
var storeTo = langOut[lang];
if(langFile[theString]) {
storeTo[theString] = langFile[theString] + appendOnEnd;
} else if(langFile[altString]) {
storeTo[theString] = langFile[altString] + appendOnEnd;
} else if(english[theString]) {
storeTo[theString] = english[theString] + appendOnEnd;
} else if(english[altString]) {
storeTo[theString] = english[altString] + appendOnEnd;
} else if(storeTo[altString]) {
storeTo[theString] = storeTo[altString] + appendOnEnd;
} else {
console.log('Failed to find ' + theString);
}
if(!langFile[theString]) langFile[theString] = storeTo[theString];
}
}
var generateAfter = [];
function generateLanguageAfter(theString, altString, appendOnEnd) {
generateAfter.push([theString, altString, appendOnEnd]);
}
function clearGenerateAfter() {
generateAfter = [];
}
// Read in our language files
function prepareLanguageFiles(next) {
var ourData = ''+fs.readFileSync(langDir + 'addon_english.txt');
var english = parseKV(ourData).addon;
specialChar = fs.readFileSync(resourcePath + 'dota_english.txt', 'utf16le').substring(0, 1);
for(var i=0; i<langs.length; ++i) {
// Grab a language
var lang = langs[i];
var data = fs.readFileSync(resourcePath + 'dota_' + lang + '.txt', 'utf16le').substring(1);
// Load her up
langIn[lang] = parseKV(data).lang.Tokens;
langOut[lang] = {};
var toUse;
if(fs.existsSync(langDir + 'addon_' + lang + '.txt')) {
var ourData
if(lang == 'english') {
ourData = ''+fs.readFileSync(langDir + 'addon_' + lang + '.txt');
} else {
ourData = ''+fs.readFileSync(langDir + 'addon_' + lang + '.txt', 'utf16le').substring(1);
}
toUse = parseKV(ourData).addon;
} else {
toUse = english;
}
for(var key in english) {
if(toUse[key]) {
langOut[lang][key] = toUse[key];
} else {
langOut[lang][key] = english[key];
}
}
for(var key in toUse) {
if(!langIn[lang][key]) {
langIn[lang][key] = toUse[key];
}
}
}
console.log('Done loading languages!');
// Run the next step if there is one
if(next) next();
}
/*
Precache generator
*/
function generatePrecacheData(next) {
// Precache generator
fs.readFile(scriptDir+'npc_heroes.txt', function(err, rawHeroes) {
console.log('Loading heroes...');
var rootHeroes = parseKV(''+rawHeroes);
var newKV = {};
// List of heroes to ignore differs based on s1 and s2
// In s2, no bots are supported, so we can just strip every hero
var ignoreHeroes = {
npc_dota_hero_techies: true,
npc_dota_hero_gyrocopter: true,
npc_dota_hero_riki: true
};
var heroes = rootHeroes.DOTAHeroes;
for(var name in heroes) {
if(name == 'Version') continue;
if(name == 'npc_dota_hero_base') continue;
var data = heroes[name];
if(!ignoreHeroes[name]) {
newKV[name+'_lod'] = {
override_hero: name,
AbilityLayout: 6
}
if(data.BotImplemented != 1) {
//newKV[name+'_lod'].Ability1 = 'attribute_bonus';
for(var i=1;i<=32;++i) {
var txt = heroes[name]['Ability' + i];
if(txt) {
if(txt[0].indexOf('special_bonus_') != -1) {
//newKV[name+'_lod']['Ability' + i] = txt;
} else {
newKV[name+'_lod']['Ability' + i] = '';
}
}
}
}
}
// Check if they are melee
if(data.AttackCapabilities == 'DOTA_UNIT_CAP_MELEE_ATTACK') {
if(!newKV[name+'_lod']) {
newKV[name+'_lod'] = {
override_hero: name
}
}
// Give them projectile speed + model
newKV[name+'_lod'].ProjectileSpeed = 1000
newKV[name+'_lod'].ProjectileModel = 'luna_base_attack'
}
// Add ability layout = 6
if(!newKV[name+'_lod']) {
newKV[name+'_lod'] = {
override_hero: name
}
}
newKV[name+'_lod'].AbilityLayout = 6;
// Source2 precache
customUnits['npc_precache_'+name] = {
BaseClass: 'npc_dota_creep',
precache: {
particle_folder: data.particle_folder,
soundfile: data.GameSoundsFile
}
}
// Extra precache stuff
if(data.precache) {
for(var key in data.precache) {
customUnits['npc_precache_'+name].precache[key] = data.precache[key];
}
}
}
// Techies override prcaching
customUnits.npc_precache_npc_dota_hero_techies.precache.model = 'models/heroes/techies/fx_techiesfx_mine.vmdl';
// Store the hero data
fs.writeFile(scriptDirOut+'npc_heroes_custom.txt', toKV(newKV, 'DOTAHeroes'), function(err) {
if (err) throw err;
console.log('Done saving custom heroes!');
// Continue, if there is something else to run
if(next) next();
});
});
}
/*
Custom file mergers
*/
/*function loadItems(next) {
// Simply read in the file, and store into our varible
fs.readFile(scriptDir+'items.txt', function(err, rawItems) {
console.log('Loading items...');
items = parseKV(''+rawItems).DOTAAbilities;
// Continue, if there is something else to run
if(next) next();
});
}*/
function loadAbilities(next) {
// Simply read in the file, and store into our varible
fs.readFile(scriptDir+'npc_abilities.txt', function(err, rawAbs) {
console.log('Loading abilities...');
abilities = parseKV(''+rawAbs).DOTAAbilities;
// Continue, if there is something else to run
if(next) next();
});
}
function loadCustomUnits(next) {
// Simply read in the file, and store into our varible
fs.readFile(customDir+'npc_units_custom.txt', function(err, rawCustomUnits) {
console.log('Loading custom units...');
customUnits = parseKV(''+rawCustomUnits).DOTAUnits;
// Continue, if there is something else to run
if(next) next();
});
}
function loadCustomAbilities(next) {
// Simply read in the file, and store into our varible
fs.readFile(customAbilitiesLocation, function(err, rawCustomAbilities) {
console.log('Loading custom abilities...');
customAbilities = parseKV(''+rawCustomAbilities).DOTAAbilities;
// Continue, if there is something else to run
if(next) next();
});
}
/*
Process Skill Warnings
*/
function generateSkillWarnings(next) {
// Grab a reference to english
var english = langIn.english;
for(var word in english) {
if(word.indexOf('warning_') == 0) {
var value = english[word];
var abilityName = word.replace('warning_', '');
for(var i=0; i<langs.length; ++i) {
// Grab a language
var lang = langs[i];
var langFile = langIn[lang];
var storeTo = langOut[lang];
var storeValue = value;
// Does this language have a different translation of the word?
if(langFile[word]) {
storeValue = langFile[word];
}
// Do we have anything to change?
var searchKey = 'DOTA_Tooltip_ability_' + abilityName+ '_Description';
if(langFile[searchKey]) {
storeValue = langFile[searchKey] + '<br><br>' + storeValue + '<br>';
}
// Store it
storeTo[searchKey] = storeValue;
}
}
}
// Continue
next();
}
/*
Helper functions
*/
// Round to places decimal places
function r(value, places) {
for(var i=0; i<places; i++) {
value *= 10;
}
value = Math.round(value);
for(var i=0; i<places; i++) {
value /= 10;
}
return value;
}
function clone(x) {
if (x === null || x === undefined)
return x;
if (x.clone)
return x.clone();
if (x.constructor == Array)
{
var r = [];
for (var i=0,n=x.length; i<n; i++)
r.push(clone(x[i]));
return r;
}
if(typeof(x) == 'object') {
var y = {};
for(var key in x) {
y[key] = clone(x[key]);
}
return y;
}
return x;
}
/*
Parses most of a KV file
Mostly copied from here:
https://github.com/Matheus28/KeyValue/blob/master/m28/keyvalue/KeyValue.hx
*/
var TYPE_BLOCK = 0;
function parseKV(data) {
// Make sure we have some data to work with
if(!data) return null;
var tree = [{}];
var treeType = [TYPE_BLOCK];
var keys = [null];
var i = 0;
var line = 1;
while(i < data.length) {
var chr = data.charAt(i);
if(chr == ' ' || chr == '\t') {
// Ignore white space
} else if(chr == '\n') {
// We moved onto the next line
line++;
if(data.charAt(i+1) == '\r') i++;
} else if(chr == '\r') {
// We moved onto the next line
line++;
if(data.charAt(i+1) == '\n') i++;
} else if(chr == '/') {
if(data.charAt(i+1) == '/') {
// We found a comment, ignore rest of the line
while(++i < data.length) {
chr = data.charAt(i);
// Check for new line
if(chr == '\n') {
if(data.charAt(i+1) == '\r') ++i;
break;
}
if(chr == '\r') {
if(data.charAt(i+1) == '\n') ++i;
break;
}
}
// We are on a new line
line++;
}
} else if(chr == '"') {
var resultString = '';
i++;
while(i < data.length) {
chr = data.charAt(i);
if(chr == '"') break;
if(chr == '\n') {
// We moved onto the next line
line++;
if(data.charAt(i+1) == '\r') i++;
} else if(chr == '\r') {
// We moved onto the next line
line++;
if(data.charAt(i+1) == '\n') i++;
} else if(chr == '\\') {
i++;
// Gran the mext cjaracter
chr = data.charAt(i);
// Check for escaped characters
switch(chr) {
case '\\':chr = '\\'; break;
case '"': chr = '"'; break;
case '\'': chr = '\''; break;
case 'n': chr = '\n'; break;
case 'r': chr = '\r'; break;
default:
chr = '\\';
i--;
break;
}
}
resultString += chr;
i++;
}
if (i == data.length || chr == '\n' || chr == '\r') throw new Error("Unterminated string at line " + line);
if(treeType[treeType.length - 1] == TYPE_BLOCK){
if (keys[keys.length - 1] == null) {
keys[keys.length - 1] = resultString;
}else {
if(tree[tree.length - 1][keys[keys.length - 1]] == null) {
tree[tree.length - 1][keys[keys.length - 1]] = [];
}
tree[tree.length - 1][keys[keys.length - 1]].push(resultString);
keys[keys.length - 1] = null;
}
}
// Check if we need to reparse the character that ended this string
if(chr != '"') --i;
} else if(chr == '{') {
if(treeType[treeType.length - 1] == TYPE_BLOCK){
if (keys[keys.length - 1] == null) {
throw new Error("A block needs a key at line " + line + " (offset " + i + ")");
}
}
tree.push({});
treeType.push(TYPE_BLOCK);
keys.push(null);
} else if (chr == '}') {
if (tree.length == 1) {
throw new Error("Mismatching bracket at line " + line + " (offset " + i + ")");
}
if (treeType.pop() != TYPE_BLOCK) {
throw new Error("Mismatching brackets at line " + line + " (offset " + i + ")");
}
keys.pop();
var obj = tree.pop();
if(treeType[treeType.length - 1] == TYPE_BLOCK){
tree[tree.length - 1][keys[keys.length - 1]] = obj;
keys[keys.length - 1] = null;
}else {
tree[tree.length - 1].push(obj);
}
} else {
console.log("Unexpected character \"" + chr + "\" at line " + line + " (offset " + i + ")");
// Skip to next line
while(++i < data.length) {
chr = data.charAt(i);
// Check for new line
if(chr == '\n') {
if(data.charAt(i+1) == '\r') ++i;
break;
}
if(chr == '\r') {
if(data.charAt(i+1) == '\n') ++i;
break;
}
}
// We are on a new line
line++;
// Move onto the next char
i++;
}
i++;
}
if (tree.length != 1) {
throw new Error("Missing brackets");
}
return tree[0];
}
function escapeString(str) {
return str.replace(/\\/gm, '\\\\').replace(/\"/gm, '\\"').replace(/(\r\n|\n|\r|\n\r)/gm, '\\n');
}
function toKV(obj, key) {
var myStr = '';
if(obj == null) {
// Nothing to return
return '';
} else if (typeof obj == 'number') {
return '"' + escapeString(key) + '""' + obj + '"';
} else if (typeof obj == 'boolean') {
return '"' + escapeString(key) + '""' + obj + '"';
} else if (typeof obj == 'string') {
return '"' + escapeString(key) + '""' + escapeString(obj) + '"';
} else if(obj instanceof Array) {
// An array of strings
for(var i=0; i<obj.length; i++) {
myStr = myStr + '"' + escapeString(key) + '"\n"' + escapeString(obj[i]) + '"';
}
return myStr;
} else {
// An object
for(var entry in obj) {
myStr += toKV(obj[entry], entry)
}
if(key != null) {
return '"' + escapeString(key) + '"{\n' + myStr + '}';
} else {
return myStr;
}
}
}
/*
Run everything
*/
// Prepare hte languge files
prepareLanguageFiles(function() {
// Load our custom units
loadCustomUnits(function() {
// Load abilities
loadAbilities(function() {
// Load items
//loadItems(function() {
// Load our custom items
//loadCustomItems(function() {
// Load our custom abilities
loadCustomAbilities(function() {
// Generate the custom item abilities
//generateAbilityItems(function() {
// Generate our precache data
generatePrecacheData(function() {
//doCSP(function() {
//doLvl1Ults(function() {
generateSkillWarnings(function() {
// Output language files
for(var i=0; i<langs.length; ++i) {
(function(lang) {
fs.writeFile(scriptDirOut+'addon_' + lang + '_token.txt', specialChar + toKV({Tokens: langOut[lang]}, 'lang'), 'utf16le', function(err) {
if (err) throw err;
console.log('Finished saving ' + lang + '!');
});
fs.writeFile(scriptDirOut+'addon_' + lang + '.txt', specialChar + toKV(langOut[lang], 'addon'), 'utf16le', function(err) {
if (err) throw err;
console.log('Finished saving ' + lang + '!');
});
})(langs[i]);
}
// Output custom files
fs.writeFile(scriptDirOut+'npc_units_custom.txt', toKV(customUnits, 'DOTAUnits'), function(err) {
if (err) throw err;
console.log('Done saving custom units file!');
});
});
//});
//});
});
//});
});
//});
//});
});
});
});
| LegendsOfDota/LegendsOfDota | script_generator/app.js | JavaScript | gpl-3.0 | 20,039 |
/*******************************************************************************
* Copyright (C) 2006-2013 AITIA International, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package ai.aitia.meme.paramsweep.gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import ai.aitia.meme.gui.Preferences;
import ai.aitia.meme.gui.PreferencesPage;
import ai.aitia.meme.gui.Preferences.Button;
import ai.aitia.meme.paramsweep.gui.WizardPreferences.IReinitalizeable;
import ai.aitia.meme.paramsweep.platform.PlatformManager;
import ai.aitia.meme.paramsweep.platform.PlatformManager.PlatformType;
import ai.aitia.meme.paramsweep.utils.Utilities;
import ai.aitia.meme.utils.FormsUtils;
import ai.aitia.meme.utils.GUIUtils;
import ai.aitia.meme.utils.FormsUtils.Separator;
public class Page_EMILPrefs extends PreferencesPage implements IReinitalizeable, ActionListener {
//=====================================================================================
//members
private static final long serialVersionUID = 1L;
/** The owner component of the page. */
private WizardPreferences owner = null;
//=====================================================================================
// GUI members
private JPanel content = null;
private JButton registerButton = new JButton("Register");
private JButton deRegisterButton = new JButton("Deregister");
//=====================================================================================
// methods
//-------------------------------------------------------------------------------------
/** Constructor.
* @param owner the owner component of the page
*/
public Page_EMILPrefs(WizardPreferences owner) {
super("EMIL-S Repast");
this.owner = owner;
layoutGUI();
reinitialize();
}
//=====================================================================================
// implemented interfaces
//-------------------------------------------------------------------------------------
@Override public String getInfoText(Preferences p) { return "EMIL-S Repast properties."; }
@Override public boolean onButtonPress(Button b) { return true; }
//-------------------------------------------------------------------------------------
public void reinitialize() {}
//----------------------------------------------------------------------------------------------------
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("REGISTER".equals(cmd)) {
PlatformManager.registerPlatform(PlatformType.EMIL,".");
owner.warning(true,"Registration successful!",Preferences.MESSAGE,true);
} else if ("DEREGISTER".equals(cmd)) {
int result = Utilities.askUser(owner,false,"Confirmation","Are you sure?");
if (result == 1) {
PlatformManager.removePlatform(PlatformType.EMIL);
owner.warning(true,"Deregistration successful!",Preferences.MESSAGE,true);
}
}
}
//=====================================================================================
// GUI methods
//-------------------------------------------------------------------------------------
private void layoutGUI() {
JPanel tmp = FormsUtils.build("p ~ p ~ p:g",
"01_",
registerButton,deRegisterButton).getPanel();
content = FormsUtils.build("p ~ p:g ~ p ",
"[DialogBorder]000||" +
"111||" +
"222|" +
"___",
"A platform for Trass models",
tmp,
new Separator("")).getPanel();
this.setLayout(new BorderLayout());
this.add(content,BorderLayout.CENTER);
registerButton.setActionCommand("REGISTER");
deRegisterButton.setActionCommand("DEREGISTER");
GUIUtils.addActionListener(this,registerButton,deRegisterButton);
}
}
| lgulyas/MEME | src/ai/aitia/meme/paramsweep/gui/Page_EMILPrefs.java | Java | gpl-3.0 | 4,536 |
import hashlib
import re
import os
import pickle
from functools import partial
from externals.lib.misc import file_scan, update_dict
import logging
log = logging.getLogger(__name__)
VERSION = "0.0"
# Constants --------------------------------------------------------------------
DEFAULT_DESTINATION = './files/'
DEFAULT_CACHE_FILENAME = 'hash_cache.pickle'
DEFAULT_FILE_EXTS = {'mp4', 'avi', 'rm', 'mkv', 'ogm', 'ssa', 'srt', 'ass'}
# Utils ------------------------------------------------------------------------
def hash_files(folder, file_regex=None, hasher=hashlib.sha256):
return {
f.hash: f
for f in file_scan(folder, file_regex=file_regex, hasher=hasher)
}
# ------------------------------------------------------------------------------
def hash_source_dest(source_folder=None, destination_folder=None, hasher=hashlib.sha256, file_exts=DEFAULT_FILE_EXTS, **kwargs):
file_regex = re.compile(r'.*\.({})$'.format('|'.join(file_exts)))
gen_hashs_folder = partial(hash_files, **dict(hasher=hasher, file_regex=file_regex))
return {
'source_files': gen_hashs_folder(source_folder),
'destination_files': gen_hashs_folder(destination_folder),
}
def symlink_matched_files(source_files=None, destination_files=None, destination_folder=None, dry_run=False, **kwargs):
for key in sorted(set(source_files.keys()).difference(set(destination_files.keys())), key=lambda key: source_files[key].file):
f = source_files[key]
log.debug(f.file)
if not dry_run:
try:
os.symlink(f.absolute, os.path.join(destination_folder, f.file))
except OSError:
log.info('unable to symlink {0}'.format(f.file))
# ------------------------------------------------------------------------------
def move_files():
pass
# Command Line -----------------------------------------------------------------
def get_args():
import argparse
parser = argparse.ArgumentParser(
description="""
Find the duplicates
""",
epilog=""" """
)
# Folders
parser.add_argument('-d', '--destination_folder', action='store', help='', default=DEFAULT_DESTINATION)
parser.add_argument('-s', '--source_folder', action='store', help='', required=True)
parser.add_argument('-e', '--file_exts', nargs='*', help='file exts to find', default=DEFAULT_FILE_EXTS)
# Operation
#parser.add_argument('-c', '--copy', action='store_true', help='copy files to destination (to be ready for importing)', default=False)
# Cache
parser.add_argument('--cache_filename', action='store', help='', default=DEFAULT_CACHE_FILENAME)
# Common
parser.add_argument('--dry_run', action='store_true', help='', default=False)
parser.add_argument('-v', '--verbose', action='store_true', help='', default=False)
parser.add_argument('--version', action='version', version=VERSION)
args = vars(parser.parse_args())
return args
def main():
args = get_args()
logging.basicConfig(level=logging.DEBUG if args['verbose'] else logging.INFO)
try:
with open(args['cache_filename'], 'rb') as f:
data = pickle.load(f)
except IOError:
with open(args['cache_filename'], 'wb') as f:
data = hash_source_dest(**args)
pickle.dump(data, f)
symlink_matched_files(**update_dict(args.copy(), data))
if __name__ == "__main__":
main()
| richlanc/KaraKara | website/karakara/scripts/hash_matcher.py | Python | gpl-3.0 | 3,469 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aula01;
import java.util.Scanner;
/**
*
* @author Aluno
*/
public class Exemplo1 {
public static void main(String[] args)
{
/* Objeto Scan vai auxiliar na entrada de dados via teclado */
Scanner scan = new Scanner(System.in);
System.out.println("Qual o seu nome ?");
/* Metodo nextLine lê uma string do teclado */
String nome = scan.nextLine();
System.out.println("Seja Bem-Vindo" + nome);
System.out.println("Qual a sua idade ?");
/* Metodo nextInt lê um inteiro do teclado */
int idade = scan.nextInt();
System.out.println("Sua idade eh " + idade + " anos.");
}
}
| rfortti/PRS_rfortti | src/aula01/Exemplo1.java | Java | gpl-3.0 | 912 |
from controlscript import *
print "This is a simple control script. It just does nothing and exits successfully."
print "Start parameter is %s, additional parameters are %s" % (start, arguments)
class DoNothing(ControlAction):
""" Control script action for exiting with error 1 on stop """
def __init__(self):
ControlAction.__init__(self, "Do nothing")
def start(self):
print "Do nothing on start"
print
def stop(self):
print "Do nothing on stop"
print
ControlScript([
DoNothing()
]) | remybaranx/qtaste | Testbeds/ControlScripts/do_nothing.py | Python | gpl-3.0 | 507 |
package com.survey.app.server.repository;
import com.athena.server.repository.SearchInterface;
import com.athena.annotation.Complexity;
import com.athena.annotation.SourceCodeAuthorClass;
import com.athena.framework.server.exception.repository.SpartanPersistenceException;
import java.util.List;
import com.athena.framework.server.exception.biz.SpartanConstraintViolationException;
@SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Country Master table Entity", complexity = Complexity.LOW)
public interface CountryRepository<T> extends SearchInterface {
public List<T> findAll() throws SpartanPersistenceException;
public T save(T entity) throws SpartanPersistenceException;
public List<T> save(List<T> entity) throws SpartanPersistenceException;
public void delete(String id) throws SpartanPersistenceException;
public void update(T entity) throws SpartanConstraintViolationException, SpartanPersistenceException;
public void update(List<T> entity) throws SpartanPersistenceException;
public T findById(String countryId) throws Exception, SpartanPersistenceException;
}
| applifireAlgo/appDemoApps201115 | surveyportal/src/main/java/com/survey/app/server/repository/CountryRepository.java | Java | gpl-3.0 | 1,169 |
/*
* jQuery File Upload User Interface Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* jshint nomen:false */
/* global define, require, window */
;(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'tmpl',
'./jquery.fileupload-image',
'./jquery.fileupload-audio',
'./jquery.fileupload-video',
'./jquery.fileupload-validate'
], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(
require('jquery'),
require('tmpl')
);
} else {
// Browser globals:
factory(
window.jQuery,
window.tmpl
);
}
}(function ($, tmpl) {
'use strict';
jQuery.blueimp.fileupload.prototype._specialOptions.push(
'filesContainer',
'uploadTemplateId',
'downloadTemplateId'
);
// The UI version extends the file upload widget
// and adds complete user interface interaction:
jQuery.widget('blueimp.fileupload', jQuery.blueimp.fileupload, {
options: {
// By default, files added to the widget are uploaded as soon
// as the user clicks on the start buttons. To enable automatic
// uploads, set the following option to true:
autoUpload: false,
// The ID of the upload template:
uploadTemplateId: 'template-upload',
// The ID of the download template:
downloadTemplateId: 'template-download',
// The container for the list of files. If undefined, it is set to
// an element with class "files" inside of the widget element:
filesContainer: undefined,
// By default, files are appended to the files container.
// Set the following option to true, to prepend files instead:
prependFiles: false,
// The expected data type of the upload response, sets the dataType
// option of the jQuery.ajax upload requests:
dataType: 'json',
// Error and info messages:
messages: {
unknownError: 'Unknown error'
},
// Function returning the current number of files,
// used by the maxNumberOfFiles validation:
getNumberOfFiles: function () {
return this.filesContainer.children()
.not('.processing').length;
},
// Callback to retrieve the list of files from the server response:
getFilesFromResponse: function (data) {
if (data.result && jQuery.isArray(data.result.files)) {
return data.result.files;
}
return [];
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop or add API call).
// See the basic file upload widget for more information:
add: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var $this = jQuery(this),
that = $this.data('blueimp-fileupload') ||
$this.data('fileupload'),
options = that.options;
data.context = that._renderUpload(data.files)
.data('data', data)
.addClass('processing');
options.filesContainer[
options.prependFiles ? 'prepend' : 'append'
](data.context);
that._forceReflow(data.context);
that._transition(data.context);
data.process(function () {
return $this.fileupload('process', data);
}).always(function () {
data.context.each(function (index) {
jQuery(this).find('.size').text(
that._formatFileSize(data.files[index].size)
);
}).removeClass('processing');
that._renderPreviews(data);
}).done(function () {
data.context.find('.start').prop('disabled', false);
if ((that._trigger('added', e, data) !== false) &&
(options.autoUpload || data.autoUpload) &&
data.autoUpload !== false) {
data.submit();
}
}).fail(function () {
if (data.files.error) {
data.context.each(function (index) {
var error = data.files[index].error;
if (error) {
jQuery(this).find('.error').text(error);
}
});
}
});
},
// Callback for the start of each file upload request:
send: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var that = jQuery(this).data('blueimp-fileupload') ||
jQuery(this).data('fileupload');
if (data.context && data.dataType &&
data.dataType.substr(0, 6) === 'iframe') {
// Iframe Transport does not support progress events.
// In lack of an indeterminate progress bar, we set
// the progress to 100%, showing the full animated bar:
data.context
.find('.progress').addClass(
!jQuery.support.transition && 'progress-animated'
)
.attr('aria-valuenow', 100)
.children().first().css(
'width',
'100%'
);
}
return that._trigger('sent', e, data);
},
// Callback for successful uploads:
done: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var that = jQuery(this).data('blueimp-fileupload') ||
jQuery(this).data('fileupload'),
getFilesFromResponse = data.getFilesFromResponse ||
that.options.getFilesFromResponse,
files = getFilesFromResponse(data),
template,
deferred;
if (data.context) {
data.context.each(function (index) {
var file = files[index] ||
{error: 'Empty file upload result'};
deferred = that._addFinishedDeferreds();
that._transition(jQuery(this)).done(
function () {
var node = jQuery(this);
template = that._renderDownload([file])
.replaceAll(node);
that._forceReflow(template);
that._transition(template).done(
function () {
data.context = jQuery(this);
that._trigger('completed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
);
});
} else {
template = that._renderDownload(files)[
that.options.prependFiles ? 'prependTo' : 'appendTo'
](that.options.filesContainer);
that._forceReflow(template);
deferred = that._addFinishedDeferreds();
that._transition(template).done(
function () {
data.context = jQuery(this);
that._trigger('completed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
},
// Callback for failed (abort or error) uploads:
fail: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var that = jQuery(this).data('blueimp-fileupload') ||
jQuery(this).data('fileupload'),
template,
deferred;
if (data.context) {
data.context.each(function (index) {
if (data.errorThrown !== 'abort') {
var file = data.files[index];
file.error = file.error || data.errorThrown ||
data.i18n('unknownError');
deferred = that._addFinishedDeferreds();
that._transition(jQuery(this)).done(
function () {
var node = jQuery(this);
template = that._renderDownload([file])
.replaceAll(node);
that._forceReflow(template);
that._transition(template).done(
function () {
data.context = jQuery(this);
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
);
} else {
deferred = that._addFinishedDeferreds();
that._transition(jQuery(this)).done(
function () {
jQuery(this).remove();
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
});
} else if (data.errorThrown !== 'abort') {
data.context = that._renderUpload(data.files)[
that.options.prependFiles ? 'prependTo' : 'appendTo'
](that.options.filesContainer)
.data('data', data);
that._forceReflow(data.context);
deferred = that._addFinishedDeferreds();
that._transition(data.context).done(
function () {
data.context = jQuery(this);
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
} else {
that._trigger('failed', e, data);
that._trigger('finished', e, data);
that._addFinishedDeferreds().resolve();
}
},
// Callback for upload progress events:
progress: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var progress = Math.floor(data.loaded / data.total * 100);
if (data.context) {
data.context.each(function () {
jQuery(this).find('.progress')
.attr('aria-valuenow', progress)
.children().first().css(
'width',
progress + '%'
);
});
}
},
// Callback for global upload progress events:
progressall: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var $this = jQuery(this),
progress = Math.floor(data.loaded / data.total * 100),
globalProgressNode = $this.find('.fileupload-progress'),
extendedProgressNode = globalProgressNode
.find('.progress-extended');
if (extendedProgressNode.length) {
extendedProgressNode.html(
($this.data('blueimp-fileupload') || $this.data('fileupload'))
._renderExtendedProgress(data)
);
}
globalProgressNode
.find('.progress')
.attr('aria-valuenow', progress)
.children().first().css(
'width',
progress + '%'
);
},
// Callback for uploads start, equivalent to the global ajaxStart event:
start: function (e) {
if (e.isDefaultPrevented()) {
return false;
}
var that = jQuery(this).data('blueimp-fileupload') ||
jQuery(this).data('fileupload');
that._resetFinishedDeferreds();
that._transition(jQuery(this).find('.fileupload-progress')).done(
function () {
that._trigger('started', e);
}
);
},
// Callback for uploads stop, equivalent to the global ajaxStop event:
stop: function (e) {
if (e.isDefaultPrevented()) {
return false;
}
var that = jQuery(this).data('blueimp-fileupload') ||
jQuery(this).data('fileupload'),
deferred = that._addFinishedDeferreds();
jQuery.when.apply($, that._getFinishedDeferreds())
.done(function () {
that._trigger('stopped', e);
});
that._transition(jQuery(this).find('.fileupload-progress')).done(
function () {
jQuery(this).find('.progress')
.attr('aria-valuenow', '0')
.children().first().css('width', '0%');
jQuery(this).find('.progress-extended').html(' ');
deferred.resolve();
}
);
},
processstart: function (e) {
if (e.isDefaultPrevented()) {
return false;
}
jQuery(this).addClass('fileupload-processing');
},
processstop: function (e) {
if (e.isDefaultPrevented()) {
return false;
}
jQuery(this).removeClass('fileupload-processing');
},
// Callback for file deletion:
destroy: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var that = jQuery(this).data('blueimp-fileupload') ||
jQuery(this).data('fileupload'),
removeNode = function () {
that._transition(data.context).done(
function () {
jQuery(this).remove();
that._trigger('destroyed', e, data);
}
);
};
if (data.url) {
data.dataType = data.dataType || that.options.dataType;
jQuery.ajax(data).done(removeNode).fail(function () {
that._trigger('destroyfailed', e, data);
});
} else {
removeNode();
}
}
},
_resetFinishedDeferreds: function () {
this._finishedUploads = [];
},
_addFinishedDeferreds: function (deferred) {
if (!deferred) {
deferred = jQuery.Deferred();
}
this._finishedUploads.push(deferred);
return deferred;
},
_getFinishedDeferreds: function () {
return this._finishedUploads;
},
// Link handler, that allows to download files
// by drag & drop of the links to the desktop:
_enableDragToDesktop: function () {
var link = jQuery(this),
url = link.prop('href'),
name = link.prop('download'),
type = 'application/octet-stream';
link.bind('dragstart', function (e) {
try {
e.originalEvent.dataTransfer.setData(
'DownloadURL',
[type, name, url].join(':')
);
} catch (ignore) {}
});
},
_formatFileSize: function (bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
},
_formatBitrate: function (bits) {
if (typeof bits !== 'number') {
return '';
}
if (bits >= 1000000000) {
return (bits / 1000000000).toFixed(2) + ' Gbit/s';
}
if (bits >= 1000000) {
return (bits / 1000000).toFixed(2) + ' Mbit/s';
}
if (bits >= 1000) {
return (bits / 1000).toFixed(2) + ' kbit/s';
}
return bits.toFixed(2) + ' bit/s';
},
_formatTime: function (seconds) {
var date = new Date(seconds * 1000),
days = Math.floor(seconds / 86400);
days = days ? days + 'd ' : '';
return days +
('0' + date.getUTCHours()).slice(-2) + ':' +
('0' + date.getUTCMinutes()).slice(-2) + ':' +
('0' + date.getUTCSeconds()).slice(-2);
},
_formatPercentage: function (floatValue) {
return (floatValue * 100).toFixed(2) + ' %';
},
_renderExtendedProgress: function (data) {
return this._formatBitrate(data.bitrate) + ' | ' +
this._formatTime(
(data.total - data.loaded) * 8 / data.bitrate
) + ' | ' +
this._formatPercentage(
data.loaded / data.total
) + ' | ' +
this._formatFileSize(data.loaded) + ' / ' +
this._formatFileSize(data.total);
},
_renderTemplate: function (func, files) {
if (!func) {
return jQuery();
}
var result = func({
files: files,
formatFileSize: this._formatFileSize,
options: this.options
});
if (result instanceof $) {
return result;
}
return jQuery(this.options.templatesContainer).html(result).children();
},
_renderPreviews: function (data) {
data.context.find('.preview').each(function (index, elm) {
jQuery(elm).append(data.files[index].preview);
});
},
_renderUpload: function (files) {
return this._renderTemplate(
this.options.uploadTemplate,
files
);
},
_renderDownload: function (files) {
return this._renderTemplate(
this.options.downloadTemplate,
files
).find('a[download]').each(this._enableDragToDesktop).end();
},
_startHandler: function (e) {
e.preventDefault();
var button = jQuery(e.currentTarget),
template = button.closest('.template-upload'),
data = template.data('data');
button.prop('disabled', true);
if (data && data.submit) {
data.submit();
}
},
_cancelHandler: function (e) {
e.preventDefault();
var template = jQuery(e.currentTarget)
.closest('.template-upload,.template-download'),
data = template.data('data') || {};
data.context = data.context || template;
if (data.abort) {
data.abort();
} else {
data.errorThrown = 'abort';
this._trigger('fail', e, data);
}
},
_deleteHandler: function (e) {
e.preventDefault();
var button = jQuery(e.currentTarget);
this._trigger('destroy', e, jQuery.extend({
context: button.closest('.template-download'),
type: 'DELETE'
}, button.data()));
},
_forceReflow: function (node) {
return jQuery.support.transition && node.length &&
node[0].offsetWidth;
},
_transition: function (node) {
var dfd = jQuery.Deferred();
if (jQuery.support.transition && node.hasClass('fade') && node.is(':visible')) {
node.bind(
jQuery.support.transition.end,
function (e) {
// Make sure we don't respond to other transitions events
// in the container element, e.g. from button elements:
if (e.target === node[0]) {
node.unbind(jQuery.support.transition.end);
dfd.resolveWith(node);
}
}
).toggleClass('in');
} else {
node.toggleClass('in');
dfd.resolveWith(node);
}
return dfd;
},
_initButtonBarEventHandlers: function () {
var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
filesList = this.options.filesContainer;
this._on(fileUploadButtonBar.find('.start'), {
click: function (e) {
e.preventDefault();
filesList.find('.start').click();
}
});
this._on(fileUploadButtonBar.find('.cancel'), {
click: function (e) {
e.preventDefault();
filesList.find('.cancel').click();
}
});
this._on(fileUploadButtonBar.find('.delete'), {
click: function (e) {
e.preventDefault();
filesList.find('.toggle:checked')
.closest('.template-download')
.find('.delete').click();
fileUploadButtonBar.find('.toggle')
.prop('checked', false);
}
});
this._on(fileUploadButtonBar.find('.toggle'), {
change: function (e) {
filesList.find('.toggle').prop(
'checked',
jQuery(e.currentTarget).is(':checked')
);
}
});
},
_destroyButtonBarEventHandlers: function () {
this._off(
this.element.find('.fileupload-buttonbar')
.find('.start, .cancel, .delete'),
'click'
);
this._off(
this.element.find('.fileupload-buttonbar .toggle'),
'change.'
);
},
_initEventHandlers: function () {
this._super();
this._on(this.options.filesContainer, {
'click .start': this._startHandler,
'click .cancel': this._cancelHandler,
'click .delete': this._deleteHandler
});
this._initButtonBarEventHandlers();
},
_destroyEventHandlers: function () {
this._destroyButtonBarEventHandlers();
this._off(this.options.filesContainer, 'click');
this._super();
},
_enableFileInputButton: function () {
this.element.find('.fileinput-button input')
.prop('disabled', false)
.parent().removeClass('disabled');
},
_disableFileInputButton: function () {
this.element.find('.fileinput-button input')
.prop('disabled', true)
.parent().addClass('disabled');
},
_initTemplates: function () {
var options = this.options;
options.templatesContainer = this.document[0].createElement(
options.filesContainer.prop('nodeName')
);
if (tmpl) {
if (options.uploadTemplateId) {
options.uploadTemplate = tmpl(options.uploadTemplateId);
}
if (options.downloadTemplateId) {
options.downloadTemplate = tmpl(options.downloadTemplateId);
}
}
},
_initFilesContainer: function () {
var options = this.options;
if (options.filesContainer === undefined) {
options.filesContainer = this.element.find('.files');
} else if (!(options.filesContainer instanceof $)) {
options.filesContainer = jQuery(options.filesContainer);
}
},
_initSpecialOptions: function () {
this._super();
this._initFilesContainer();
this._initTemplates();
},
_create: function () {
this._super();
this._resetFinishedDeferreds();
if (!jQuery.support.fileInput) {
this._disableFileInputButton();
}
},
enable: function () {
var wasDisabled = false;
if (this.options.disabled) {
wasDisabled = true;
}
this._super();
if (wasDisabled) {
this.element.find('input, button').prop('disabled', false);
this._enableFileInputButton();
}
},
disable: function () {
if (!this.options.disabled) {
this.element.find('input, button').prop('disabled', true);
this._disableFileInputButton();
}
this._super();
}
});
}));
| sea75300/fanpresscm3 | inc/lib/jqupload/js/jquery.fileupload-ui.js | JavaScript | gpl-3.0 | 28,144 |
/**
* Taha Dogan Gunes
* <tdgunes@gmail.com>
* <p/>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
* <p/>
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
* <p/>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public class Utils {
public static String cleanStringForOnto(String string){
string = string.replace("[","");
string = string.replace("]","");
string = string.replace("#","");
string = string.replace(">","");
string = string.replace("%","");
string = string.replace("\"","");
//string = string.replace(" ","");
string = string.replace(".","");
string = string.replace("'","");
// string = string.replace("I","i");
return string;
}
}
| tdgunes/music-box | core/src/main/java/Utils.java | Java | gpl-3.0 | 1,662 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "Callback.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class CallbackType>
Foam::Callback<CallbackType>::Callback(CallbackRegistry<CallbackType>& cbr)
:
cbr_(cbr)
{
checkIn();
}
template<class CallbackType>
Foam::Callback<CallbackType>::Callback(const Callback<CallbackType>& cb)
:
cbr_(cb.cbr_)
{
checkIn();
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
template<class CallbackType>
Foam::Callback<CallbackType>::~Callback()
{
checkOut();
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class CallbackType>
bool Foam::Callback<CallbackType>::checkIn()
{
if (!Callback<CallbackType>::link::registered())
{
cbr_.append(static_cast<CallbackType*>(this));
return true;
}
else
{
return false;
}
}
template<class CallbackType>
bool Foam::Callback<CallbackType>::checkOut()
{
if (Callback<CallbackType>::link::registered())
{
CallbackType* cbPtr = cbr_.remove(static_cast<CallbackType*>(this));
if (cbPtr)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
// ************************ vim: set sw=4 sts=4 et: ************************ //
| themiwi/freefoam-debian | src/OpenFOAM/db/Callback/Callback.C | C++ | gpl-3.0 | 2,528 |