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
|
---|---|---|---|---|---|
class Cms::Controller::Admin::Base < Sys::Controller::Admin::Base
include Cms::Controller::Layout
helper Cms::FormHelper
layout 'admin/cms'
def default_url_options
Core.concept ? { :concept => Core.concept.id } : {}
end
def initialize_application
return false unless super
if params[:cms_navi] && params[:cms_navi][:site]
site_id = params[:cms_navi][:site]
expires = site_id.blank? ? Time.now - 60 : Time.now + 60*60*24*7
unless Core.user.root?
# システム管理者以外は所属サイトしか操作できない
site_id = Core.user.site_ids.first unless Core.user.site_ids.include?(site_id.to_i)
end
cookies[:cms_site] = {:value => site_id, :path => '/', :expires => expires}
Core.set_concept(session, 0)
return redirect_to "/#{ZomekiCMS::ADMIN_URL_PREFIX}"
end
if cookies[:cms_site] && !Core.site
cookies.delete(:cms_site)
Core.site = nil
end
if Core.user
if params[:concept]
concept = Cms::Concept.find_by(id: params[:concept])
if concept && Core.site.id != concept.site_id
Core.set_concept(session, 0)
else
Core.set_concept(session, params[:concept])
end
elsif Core.request_uri == "/#{ZomekiCMS::ADMIN_URL_PREFIX}"
Core.set_concept(session, 0)
else
Core.set_concept(session)
end
end
return true
end
end
| zomeki/zomeki2-development | lib/cms/controller/admin/base.rb | Ruby | gpl-3.0 | 1,475 |
<?php
/**
* Next/Previous Post Pagination Link
* -----------------------------------------------------------------------------
* @category PHP Script
* @package Sheepie
* @author Mark Grealish <mark@bhalash.com>
* @copyright Copyright (c) 2015 Mark Grealish
* @license https://www.gnu.org/copyleft/gpl.html The GNU GPL v3.0
* @version 1.0
* @link https://github.com/bhalash/sheepie
*/
?>
<nav class="pagination pagination--post noprint vcenter--full" id="pagination--post">
<p class="pagination__previous previous-post meta">
<?php next_post_link('%link', '%title', false); ?>
</p>
<p class="pagination__next next-post meta">
<?php previous_post_link('%link', '%title', false); ?>
</p>
</nav>
| bhalash/sheepie | partials/pagination-post.php | PHP | gpl-3.0 | 760 |
../../../../../share/pyshared/checkbox/reports/__init__.py | Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/checkbox/reports/__init__.py | Python | gpl-3.0 | 58 |
<?php
/**
* Copyright © OXID eSales AG. All rights reserved.
* See LICENSE file for license details.
*/
namespace OxidEsales\EshopCommunity\Application\Model;
use oxRegistry;
use oxDb;
/**
* Promotion List manager.
*/
class ActionList extends \OxidEsales\Eshop\Core\Model\ListModel
{
/**
* List Object class name
*
* @var string
*/
protected $_sObjectsInListName = 'oxactions';
/**
* Loads x last finished promotions
*
* @param int $iCount count to load
*/
public function loadFinishedByCount($iCount)
{
$sViewName = $this->getBaseObject()->getViewName();
$sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and oxactiveto>0 and oxactiveto < " . $oDb->quote($sDate) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto desc, oxactivefrom desc limit " . (int) $iCount;
$this->selectString($sQ);
$this->_aArray = array_reverse($this->_aArray, true);
}
/**
* Loads last finished promotions after given timespan
*
* @param int $iTimespan timespan to load
*/
public function loadFinishedByTimespan($iTimespan)
{
$sViewName = $this->getBaseObject()->getViewName();
$sDateTo = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$sDateFrom = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime() - $iTimespan);
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and oxactiveto < " . $oDb->quote($sDateTo) . " and oxactiveto > " . $oDb->quote($sDateFrom) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto, oxactivefrom";
$this->selectString($sQ);
}
/**
* Loads current promotions
*/
public function loadCurrent()
{
$sViewName = $this->getBaseObject()->getViewName();
$sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and (oxactiveto > " . $oDb->quote($sDate) . " or oxactiveto=0) and oxactivefrom != 0 and oxactivefrom < " . $oDb->quote($sDate) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto, oxactivefrom";
$this->selectString($sQ);
}
/**
* Loads next not yet started promotions by cound
*
* @param int $iCount count to load
*/
public function loadFutureByCount($iCount)
{
$sViewName = $this->getBaseObject()->getViewName();
$sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and (oxactiveto > " . $oDb->quote($sDate) . " or oxactiveto=0) and oxactivefrom > " . $oDb->quote($sDate) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto, oxactivefrom limit " . (int) $iCount;
$this->selectString($sQ);
}
/**
* Loads next not yet started promotions before the given timespan
*
* @param int $iTimespan timespan to load
*/
public function loadFutureByTimespan($iTimespan)
{
$sViewName = $this->getBaseObject()->getViewName();
$sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$sDateTo = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime() + $iTimespan);
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and (oxactiveto > " . $oDb->quote($sDate) . " or oxactiveto=0) and oxactivefrom > " . $oDb->quote($sDate) . " and oxactivefrom < " . $oDb->quote($sDateTo) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto, oxactivefrom";
$this->selectString($sQ);
}
/**
* Returns part of user group filter query
*
* @param \OxidEsales\Eshop\Application\Model\User $oUser user object
*
* @return string
* @deprecated underscore prefix violates PSR12, will be renamed to "getUserGroupFilter" in next major
*/
protected function _getUserGroupFilter($oUser = null) // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
{
$oUser = ($oUser == null) ? $this->getUser() : $oUser;
$sTable = getViewName('oxactions');
$sGroupTable = getViewName('oxgroups');
$aIds = [];
// checking for current session user which gives additional restrictions for user itself, users group and country
if ($oUser && count($aGroupIds = $oUser->getUserGroups())) {
foreach ($aGroupIds as $oGroup) {
$aIds[] = $oGroup->getId();
}
}
$sGroupSql = count($aIds) ? "EXISTS(select oxobject2action.oxid from oxobject2action where oxobject2action.oxactionid=$sTable.OXID and oxobject2action.oxclass='oxgroups' and oxobject2action.OXOBJECTID in (" . implode(', ', \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->quoteArray($aIds)) . ") )" : '0';
return " and (
select
if(EXISTS(select 1 from oxobject2action, $sGroupTable where $sGroupTable.oxid=oxobject2action.oxobjectid and oxobject2action.oxactionid=$sTable.OXID and oxobject2action.oxclass='oxgroups' LIMIT 1),
$sGroupSql,
1)
) ";
}
/**
* return true if there are any active promotions
*
* @return boolean
*/
public function areAnyActivePromotions()
{
return (bool) $this->fetchExistsActivePromotion();
}
/**
* Fetch the information, if there is an active promotion.
*
* @return string One, if there is an active promotion.
*/
protected function fetchExistsActivePromotion()
{
$query = "select 1 from " . getViewName('oxactions') . "
where oxtypex = :oxtype and oxactive = :oxactive and oxshopid = :oxshopid
limit 1";
return \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getOne($query, [
':oxtype' => 2,
':oxactive' => 1,
':oxshopid' => \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId()
]);
}
/**
* load active shop banner list
*/
public function loadBanners()
{
$oBaseObject = $this->getBaseObject();
$oViewName = $oBaseObject->getViewName();
$sQ = "select * from {$oViewName} where oxtype=3 and " . $oBaseObject->getSqlActiveSnippet()
. " and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' " . $this->_getUserGroupFilter()
. " order by oxsort";
$this->selectString($sQ);
}
}
| michaelkeiluweit/oxideshop_ce | source/Application/Model/ActionList.php | PHP | gpl-3.0 | 7,605 |
/////////////////////////////////////////////////////////////////////////////
/// @file AbstractSection.cpp
///
/// @author Daniel Wilczak
/////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2000-2013 by the CAPD Group.
//
// This file constitutes a part of the CAPD library,
// distributed under the terms of the GNU General Public License.
// Consult http://capd.ii.uj.edu.pl/ for details.
#ifdef __HAVE_MPFR__
#include "capd/vectalg/mplib.h"
#include "capd/poincare/AbstractSection.h"
#include "capd/poincare/AbstractSection.hpp"
#include "capd/poincare/AffineSection.h"
#include "capd/poincare/CoordinateSection.h"
#include "capd/poincare/NonlinearSection.h"
using namespace capd;
template class poincare::AbstractSection<MpMatrix>;
template class poincare::AbstractSection<MpIMatrix>;
template class poincare::AffineSection<MpMatrix>;
template class poincare::AffineSection<MpIMatrix>;
template class poincare::CoordinateSection<MpMatrix>;
template class poincare::CoordinateSection<MpIMatrix>;
template class poincare::NonlinearSection<MpMatrix>;
template class poincare::NonlinearSection<MpIMatrix>;
#endif
| soonhokong/capd4 | capdDynSys4/src/mpcapd/poincare/AbstractSection.cpp | C++ | gpl-3.0 | 1,168 |
/******************************************************************************/
/* */
/* X r d S e c g s i P r o x y . c c */
/* */
/* (c) 2005, G. Ganis / CERN */
/* */
/* This file is part of the XRootD software suite. */
/* */
/* XRootD is free software: you can redistribute it and/or modify it under */
/* the terms of the GNU Lesser General Public License as published by the */
/* Free Software Foundation, either version 3 of the License, or (at your */
/* option) any later version. */
/* */
/* XRootD is distributed in the hope that it will be useful, but WITHOUT */
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */
/* License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with XRootD in a file called COPYING.LESSER (LGPL license) and file */
/* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
/* */
/* The copyright holder's institutional names and contributor's names may not */
/* be used to endorse or promote products derived from this software without */
/* specific prior written permission of the institution or contributor. */
/* */
/******************************************************************************/
/* ************************************************************************** */
/* */
/* Manage GSI proxies */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <pwd.h>
#include <time.h>
#include "XrdOuc/XrdOucString.hh"
#include "XrdSys/XrdSysLogger.hh"
#include "XrdSys/XrdSysError.hh"
#include "XrdSys/XrdSysPwd.hh"
#include "XrdSut/XrdSutAux.hh"
#include "XrdCrypto/XrdCryptoAux.hh"
#include "XrdCrypto/XrdCryptoFactory.hh"
#include "XrdCrypto/XrdCryptoX509.hh"
#include "XrdCrypto/XrdCryptoX509Req.hh"
#include "XrdCrypto/XrdCryptoX509Chain.hh"
#include "XrdCrypto/XrdCryptoX509Crl.hh"
#include "XrdCrypto/XrdCryptosslgsiX509Chain.hh"
#include "XrdCrypto/XrdCryptosslgsiAux.hh"
#include "XrdSecgsi/XrdSecgsiTrace.hh"
#define PRT(x) {cerr <<x <<endl;}
//
// enum
enum kModes {
kM_undef = 0,
kM_init = 1,
kM_info,
kM_destroy,
kM_help
};
const char *gModesStr[] = {
"kM_undef",
"kM_init",
"kM_info",
"kM_destroy",
"kM_help"
};
//
// Prototypes
//
void Menu();
int ParseArguments(int argc, char **argv);
bool CheckOption(XrdOucString opt, const char *ref, int &ival);
void Display(XrdCryptoX509 *xp);
//
// Globals
//
int Mode = kM_undef;
bool Debug = 0;
bool Exists = 0;
XrdCryptoFactory *gCryptoFactory = 0;
XrdOucString CryptoMod = "ssl";
XrdOucString CAdir = "/etc/grid-security/certificates/";
XrdOucString CRLdir = "/etc/grid-security/certificates/";
XrdOucString DefEEcert = "/.globus/usercert.pem";
XrdOucString DefEEkey = "/.globus/userkey.pem";
XrdOucString DefPXcert = "/tmp/x509up_u";
XrdOucString EEcert = "";
XrdOucString EEkey = "";
XrdOucString PXcert = "";
XrdOucString Valid = "12:00";
int Bits = 512;
int PathLength = 0;
int ClockSkew = 30;
// For error logging and tracing
static XrdSysLogger Logger;
static XrdSysError eDest(0,"proxy_");
XrdOucTrace *gsiTrace = 0;
int main( int argc, char **argv )
{
// Test implemented functionality
int secValid = 0;
XrdProxyOpt_t pxopt;
XrdCryptosslgsiX509Chain *cPXp = 0;
XrdCryptoX509 *xPXp = 0, *xPXPp = 0;
XrdCryptoRSA *kPXp = 0;
XrdCryptoX509ParseFile_t ParseFile = 0;
int prc = 0;
int nci = 0;
int exitrc = 0;
// Parse arguments
if (ParseArguments(argc,argv)) {
exit(1);
}
//
// Initiate error logging and tracing
eDest.logger(&Logger);
if (!gsiTrace)
gsiTrace = new XrdOucTrace(&eDest);
if (gsiTrace) {
if (Debug)
// Medium level
gsiTrace->What |= (TRACE_Authen | TRACE_Debug);
}
//
// Set debug flags in other modules
if (Debug) {
XrdSutSetTrace(sutTRACE_Debug);
XrdCryptoSetTrace(cryptoTRACE_Debug);
}
//
// Load the crypto factory
if (!(gCryptoFactory = XrdCryptoFactory::GetCryptoFactory(CryptoMod.c_str()))) {
PRT(": cannot instantiate factory "<<CryptoMod);
exit(1);
}
if (Debug)
gCryptoFactory->SetTrace(cryptoTRACE_Debug);
//
// Depending on the mode
switch (Mode) {
case kM_help:
//
// We should not get here ... print the menu and go
Menu();
break;
case kM_init:
//
// Init proxies
secValid = XrdSutParseTime(Valid.c_str(), 1);
pxopt.bits = Bits;
pxopt.valid = secValid;
pxopt.depthlen = PathLength;
cPXp = new XrdCryptosslgsiX509Chain();
prc = XrdSslgsiX509CreateProxy(EEcert.c_str(), EEkey.c_str(), &pxopt,
cPXp, &kPXp, PXcert.c_str());
if (prc == 0) {
// The proxy is the first certificate
xPXp = cPXp->Begin();
if (xPXp) {
Display(xPXp);
} else {
PRT( ": proxy certificate not found");
}
} else {
PRT( ": problems creating proxy");
}
break;
case kM_destroy:
//
// Destroy existing proxies
if (unlink(PXcert.c_str()) == -1) {
perror("xrdgsiproxy");
}
break;
case kM_info:
//
// Display info about existing proxies
if (!(ParseFile = gCryptoFactory->X509ParseFile())) {
PRT("cannot attach to ParseFile function!");
break;
}
// Parse the proxy file
cPXp = new XrdCryptosslgsiX509Chain();
nci = (*ParseFile)(PXcert.c_str(), cPXp);
if (nci < 2) {
if (Exists) {
exitrc = 1;
} else {
PRT("proxy files must have at least two certificates"
" (found only: "<<nci<<")");
}
break;
}
// The proxy is the first certificate
xPXp = cPXp->Begin();
if (xPXp) {
if (!Exists) {
Display(xPXp);
if (strstr(xPXp->Subject(), "CN=limited proxy")) {
xPXPp = cPXp->SearchBySubject(xPXp->Issuer());
if (xPXPp) {
Display(xPXPp);
} else {
PRT("WARNING: found 'limited proxy' but not the associated proxy!");
}
}
} else {
// Check time validity
secValid = XrdSutParseTime(Valid.c_str(), 1);
int tl = xPXp->NotAfter() -(int)time(0);
if (Debug)
PRT("secValid: " << secValid<< ", tl: "<<tl<<", ClockSkew:"<<ClockSkew);
if (secValid > tl + ClockSkew) {
exitrc = 1;
break;
}
// Check bit strenght
if (Debug)
PRT("BitStrength: " << xPXp->BitStrength()<< ", Bits: "<<Bits);
if (xPXp->BitStrength() < Bits) {
exitrc = 1;
break;
}
}
} else {
if (Exists) {
exitrc = 1;
} else {
PRT( ": proxy certificate not found");
}
}
break;
default:
//
// Print menu
Menu();
}
exit(exitrc);
}
int ParseArguments(int argc, char **argv)
{
// Parse application arguments filling relevant global variables
// Number of arguments
if (argc < 0 || !argv[0]) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Insufficient number or arguments! +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
// Print main menu
Menu();
return 1;
}
--argc;
++argv;
//
// Loop over arguments
while ((argc >= 0) && (*argv)) {
XrdOucString opt = "";
int ival = -1;
if(*(argv)[0] == '-') {
opt = *argv;
opt.erase(0,1);
if (CheckOption(opt,"h",ival) || CheckOption(opt,"help",ival) ||
CheckOption(opt,"menu",ival)) {
Mode = kM_help;
} else if (CheckOption(opt,"debug",ival)) {
Debug = ival;
} else if (CheckOption(opt,"e",ival)) {
Exists = 1;
} else if (CheckOption(opt,"exists",ival)) {
Exists = 1;
} else if (CheckOption(opt,"f",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
PXcert = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-f' requires a proxy file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"file",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
PXcert = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-file' requires a proxy file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"out",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
PXcert = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-out' requires a proxy file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"cert",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
EEcert = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-cert' requires a cert file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"key",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
EEkey = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-key' requires a key file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"certdir",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
CAdir = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-certdir' requires a dir path: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"valid",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
Valid = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-valid' requires a time string: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"path-length",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
PathLength = strtol(*argv,0,10);
if (PathLength < -1 || errno == ERANGE) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-path-length' requires a number >= -1: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-path-length' requires a number >= -1: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"bits",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
Bits = strtol(*argv, 0, 10);
Bits = (Bits > 512) ? Bits : 512;
if (errno == ERANGE) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-bits' requires a number: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-bits' requires a number: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"clockskew",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
ClockSkew = strtol(*argv, 0, 10);
if (ClockSkew < -1 || errno == ERANGE) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-clockskew' requires a number >= -1: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-clockskew' requires a number >= -1: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Ignoring unrecognized option: "<<*argv);
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
} else {
//
// Mode keyword
opt = *argv;
if (CheckOption(opt,"init",ival)) {
Mode = kM_init;
} else if (CheckOption(opt,"info",ival)) {
Mode = kM_info;
} else if (CheckOption(opt,"destroy",ival)) {
Mode = kM_destroy;
} else if (CheckOption(opt,"help",ival)) {
Mode = kM_help;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Ignoring unrecognized keyword mode: "<<opt.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}
--argc;
++argv;
}
//
// Default mode 'info'
Mode = (Mode == 0) ? kM_info : Mode;
//
// If help mode, print menu and exit
if (Mode == kM_help) {
// Print main menu
Menu();
return 1;
}
//
// we may need later
struct passwd *pw = 0;
XrdSysPwd thePwd;
//
// Check proxy file
if (PXcert.length() <= 0) {
// Use defaults
if (!pw && !(pw = thePwd.Get(getuid()))) {
// Cannot get info about current user
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot get info about current user - exit ");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
// Build proxy file name
PXcert = DefPXcert + (int)(pw->pw_uid);
}
//
// Expand Path
XrdSutExpand(PXcert);
// Get info
struct stat st;
if (stat(PXcert.c_str(),&st) != 0) {
if (errno != ENOENT) {
// Path exists but we cannot access it - exit
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access requested proxy file: "<<PXcert.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
} else {
if (Mode != kM_init) {
// Path exists but we cannot access it - exit
if (!Exists) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ proxy file: "<<PXcert.c_str()<<" not found");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
return 1;
}
}
}
//
// The following applies in 'init' mode only
if (Mode == kM_init) {
//
// Check certificate file
if (EEcert.length()) {
//
// Expand Path
XrdSutExpand(EEcert);
// Get info
if (stat(EEcert.c_str(),&st) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access certificate file: "<<EEcert.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
} else {
// Use defaults
if (!pw && !(pw = thePwd.Get(getuid()))) {
// Cannot get info about current user
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot get info about current user - exit ");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
EEcert = DefEEcert;
EEcert.insert(XrdSutHome(), 0);
if (stat(EEcert.c_str(),&st) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access certificate file: "<<EEcert.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
}
//
// Check key file
if (EEkey.length()) {
//
// Expand Path
XrdSutExpand(EEkey);
// Get info
if (stat(EEkey.c_str(),&st) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access private key file: "<<EEkey.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
} else {
// Use defaults
if (!pw && !(pw = thePwd.Get(getuid()))) {
// Cannot get info about current user
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot get info about current user - exit ");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
EEkey = DefEEkey;
EEkey.insert(XrdSutHome(), 0);
if (stat(EEkey.c_str(),&st) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access private key file: "<<EEkey.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
}
// Check permissions
if (!S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) ||
(st.st_mode & (S_IWGRP | S_IWOTH)) != 0 ||
(st.st_mode & (S_IRGRP | S_IROTH)) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Wrong permissions for file: "<<EEkey.c_str()<< " (should be 0600)");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
}
return 0;
}
void Menu()
{
// Print the menu
PRT(" ");
PRT(" xrdgsiproxy: application to manage GSI proxies ");
PRT(" ");
PRT(" Syntax:");
PRT(" ");
PRT(" xrdgsiproxy [-h] [<mode>] [options] ");
PRT(" ");
PRT(" ");
PRT(" -h display this menu");
PRT(" ");
PRT(" mode (info, init, destroy) [info]");
PRT(" ");
PRT(" info: display content of existing proxy file");
PRT(" ");
PRT(" init: create proxy certificate and related proxy file");
PRT(" ");
PRT(" destroy: delete existing proxy file");
PRT(" ");
PRT(" options:");
PRT(" ");
PRT(" -debug Print more information while running this"
" query (use if something goes wrong) ");
PRT(" ");
PRT(" -f,-file,-out <file> Non-standard location of proxy file");
PRT(" ");
PRT(" init mode only:");
PRT(" ");
PRT(" -certdir <dir> Non-standard location of directory"
" with information about known CAs");
PRT(" -cert <file> Non-standard location of certificate"
" for which proxies are wanted");
PRT(" -key <file> Non-standard location of the private"
" key to be used to sign the proxy");
PRT(" -bits <bits> strength in bits of the key [512]");
PRT(" -valid <hh:mm> Time validity of the proxy certificate [12:00]");
PRT(" -path-length <len> max number of descendent levels below"
" this proxy [0] ");
PRT(" -e,-exists [options] returns 0 if valid proxy exists, 1 otherwise;");
PRT(" valid options: '-valid <hh:mm>', -bits <bits>");
PRT(" -clockskew <secs> max clock-skewness allowed when checking time validity [30 secs]");
PRT(" ");
}
bool CheckOption(XrdOucString opt, const char *ref, int &ival)
{
// Check opt against ref
// Return 1 if ok, 0 if not
// Fills ival = 1 if match is exact
// ival = 0 if match is exact with no<ref>
// ival = -1 in the other cases
bool rc = 0;
int lref = (ref) ? strlen(ref) : 0;
if (!lref)
return rc;
XrdOucString noref = ref;
noref.insert("no",0);
ival = -1;
if (opt == ref) {
ival = 1;
rc = 1;
} else if (opt == noref) {
ival = 0;
rc = 1;
}
return rc;
}
void Display(XrdCryptoX509 *xp)
{
// display content of proxy certificate
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
if (!xp) {
PRT(" Empty certificate! ");
return;
}
// File
PRT("file : "<<PXcert);
// Issuer
PRT("issuer : "<<xp->Issuer());
// Subject
PRT("subject : "<<xp->Subject());
// Path length field
int pathlen = 0;
XrdSslgsiProxyCertInfo(xp->GetExtension(gsiProxyCertInfo_OID), pathlen);
PRT("path length : "<<pathlen);
// Key strength
PRT("bits : "<<xp->BitStrength());
// Time left
int now = int(time(0)) - XrdCryptoTZCorr();
int tl = xp->NotAfter() - now;
int hh = (tl >= 3600) ? (tl/3600) : 0; tl -= (hh*3600);
int mm = (tl >= 60) ? (tl/60) : 0; tl -= (mm*60);
int ss = (tl >= 0) ? tl : 0;
PRT("time left : "<<hh<<"h:"<<mm<<"m:"<<ss<<"s");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
// Show VOMS attributes, if any
XrdOucString vatts, vat;
if (XrdSslgsiX509GetVOMSAttr(xp, vatts) == 0) {
int from = 0;
while ((from = vatts.tokenize(vat, from, ',')) != -1) {
if (vat.length() > 0) PRT("VOMS attributes: "<<vat);
}
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}
| ffurano/xrootd-xrdhttp | src/XrdSecgsi/XrdSecgsiProxy.cc | C++ | gpl-3.0 | 25,410 |
/*
lcdui - A simple framework for embedded systems with an LCD/button interface
Copyright (C) 2012 by Al Williams (al.williams@awce.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/>.
*/
#include "lcdui.h"
using namespace std;
namespace liblcdui
{
// This kicks off a menu (or a submenu)
// if level is zero (default) you can't go back from here
void lcdui::go(unsigned int level)
{
// This mode is 0 for normal, 1 for changing a number, and
// 2 for changing an enumeration
int mode=0;
while (1)
{
// skip anything disabled
while (menu[current].mstring && !menu[current].enabled) current++;
// if at the end back up
if (menu[current].mstring==NULL)
do
{
current--;
} while (current && !menu[current].enabled);
// now current is correct
// get string
#ifndef NOSTRING
string work=menu[current].mstring;
ostringstream digits;
#else
char work[81];
#endif
// modify based on type
switch (menu[current].menutype)
{
case T_INT: // add number
#ifndef NOSTRING
work+="\t";
digits<<*menu[current].value;
work+=digits.str();
#else
// assume 8 bit char
work[0]='\t';
itoa(*menu[current].value,work+1,10);
#endif
break;
case T_ENUM: // add enumerated value
#ifndef NOSTRING
work+="\t";
work+=+menu[current].enumeration[*menu[current].value].name;
#else
work[0]='\t';
strcpy(work+1,menu[current].enumeration[*menu[current].value].name);
#endif
break;
}
// write it
output(work);
// get input
INTYPE in;
do
{
in=getInput();
if (in==IN_NONE) idle(); // call idle if nothing
} while (in==IN_NONE);
// See what to do
switch (in)
{
case IN_UP: // Up arrow
if (mode==1) // if modifying #
{
if (((*menu[current].value)-menu[current].step)<menu[current].min) break;
(*menu[current].value)-=menu[current].step;
callback(menu[current].id,menu[current].menutype,EV_CHANGE,menu[current].value);
break;
}
if (mode==2) // if modifying an enum
{
if (*menu[current].value==0) break;
(*menu[current].value)--;
callback(menu[current].id,menu[current].menutype,EV_CHANGE, menu[current].value);
break;
}
// none of the above, just navigating the menu
if (current) current--;
break;
case IN_DN: // down arrow
if (mode==1) // change number
{
if (((*menu[current].value)+menu[current].step)>menu[current].max) break;
(*menu[current].value)+=menu[current].step;
callback(menu[current].id,menu[current].menutype,EV_CHANGE,menu[current].value);
break;
}
if (mode==2) // change enum
{
(*menu[current].value)++;
if (menu[current].enumeration[*menu[current].value].name==NULL)
(*menu[current].value)--;
callback(menu[current].id,menu[current].menutype,EV_CHANGE,menu[current].value);
break;
}
// none of the above, navigate the menu
current++;
break;
// Select key either executes menu,
// modifies int or enum
// or finishes modification
case IN_OK:
if (mode) // changing a value so exit change
{
mode=0;
// note we have no way to roll back with the current
// scheme; changes are "hot" unless you override callback
callback(menu[current].id,menu[current].menutype,EV_SAVE,menu[current].value);
break;
}
// Do a submenu
if (menu[current].menutype==T_MENU)
{
// remember where we are
MENU *parent=menu;
unsigned parentcur=current;
// go to new menu
menu=menu[current].submenu;
current=0;
callback(menu[current].id,menu[current].menutype,EV_ACTION,menu[current].value);
go(level+1);
// back, so restore
current=parentcur;
menu=parent;
break;
}
// integer and not read only
if (menu[current].menutype==T_INT && !menu[current].readonly)
{
callback(menu[current].id,menu[current].menutype,EV_EDIT,menu[current].value);
mode=1; // start edit
break;
}
// enum and not read only
if (menu[current].menutype==T_ENUM && !menu[current].readonly)
{
callback(menu[current].id,menu[current].menutype,EV_EDIT,menu[current].value);
mode=2; // start edit
break;
}
// none of the above, so must be T_ACTION
callback(menu[current].id,menu[current].menutype,EV_ACTION,menu[current].value);
break;
// back button gets out of a menu;
case IN_BACK:
if (mode)
{
mode=0; // stop editing
callback(menu[current].id,menu[current].menutype,EV_CANCEL,menu[current].value);
break; // don't leave submenu if editing
}
// note could save edited value and restore here
// or edit a local copy and only save on ok
if (level) return; // only return if nested
break;
}
}
}
void lcdui::callback(int id, MENUTYPE mtype, EVTYPE event, int *value)
{
switch (mtype)
{
case T_ACTION:
dispatch(id);
break;
// A custom override could get notified when anything changes here
case T_INT:
case T_ENUM:
case T_MENU:
break;
}
}
}
| thespeeder/lcdui | lcdui.cpp | C++ | gpl-3.0 | 5,873 |
######################################################################
# Copyright (C) 2014 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
######################################################################
# This file is part of BayesPy.
#
# BayesPy 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.
#
# BayesPy 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 BayesPy. If not, see <http://www.gnu.org/licenses/>.
######################################################################
"""
Module for the Gaussian-Wishart and similar distributions.
"""
import numpy as np
from scipy import special
from .expfamily import (ExponentialFamily,
ExponentialFamilyDistribution,
useconstructor)
from .gaussian import GaussianMoments
from .gamma import GammaMoments
from .wishart import (WishartMoments,
WishartPriorMoments)
from .node import (Moments,
ensureparents)
from bayespy.utils import random
from bayespy.utils import utils
class GaussianGammaISOMoments(Moments):
"""
Class for the moments of Gaussian-gamma-ISO variables.
"""
def compute_fixed_moments(self, x, alpha):
"""
Compute the moments for a fixed value
`x` is a mean vector.
`alpha` is a precision scale
"""
x = np.asanyarray(x)
alpha = np.asanyarray(alpha)
u0 = np.einsum('...,...i->...i', alpha, x)
u1 = np.einsum('...,...i,...j->...ij', alpha, x, x)
u2 = np.copy(alpha)
u3 = np.log(alpha)
u = [u0, u1, u2, u3]
return u
def compute_dims_from_values(self, x, alpha):
"""
Return the shape of the moments for a fixed value.
"""
if np.ndim(x) < 1:
raise ValueError("Mean must be a vector")
D = np.shape(x)[-1]
return ( (D,), (D,D), (), () )
class GaussianGammaARDMoments(Moments):
"""
Class for the moments of Gaussian-gamma-ARD variables.
"""
def compute_fixed_moments(self, x, alpha):
"""
Compute the moments for a fixed value
`x` is a mean vector.
`alpha` is a precision scale
"""
x = np.asanyarray(x)
alpha = np.asanyarray(alpha)
if np.ndim(x) < 1:
raise ValueError("Mean must be a vector")
if np.ndim(alpha) < 1:
raise ValueError("ARD scales must be a vector")
if np.shape(x)[-1] != np.shape(alpha)[-1]:
raise ValueError("Mean and ARD scales have inconsistent shapes")
u0 = np.einsum('...i,...i->...i', alpha, x)
u1 = np.einsum('...k,...k,...k->...k', alpha, x, x)
u2 = np.copy(alpha)
u3 = np.log(alpha)
u = [u0, u1, u2, u3]
return u
def compute_dims_from_values(self, x, alpha):
"""
Return the shape of the moments for a fixed value.
"""
if np.ndim(x) < 1:
raise ValueError("Mean must be a vector")
if np.ndim(alpha) < 1:
raise ValueError("ARD scales must be a vector")
D = np.shape(x)[-1]
if np.shape(alpha)[-1] != D:
raise ValueError("Mean and ARD scales have inconsistent shapes")
return ( (D,), (D,), (D,), (D,) )
class GaussianWishartMoments(Moments):
"""
Class for the moments of Gaussian-Wishart variables.
"""
def compute_fixed_moments(self, x, Lambda):
"""
Compute the moments for a fixed value
`x` is a vector.
`Lambda` is a precision matrix
"""
x = np.asanyarray(x)
Lambda = np.asanyarray(Lambda)
u0 = np.einsum('...ik,...k->...i', Lambda, x)
u1 = np.einsum('...i,...ij,...j->...', x, Lambda, x)
u2 = np.copy(Lambda)
u3 = linalg.logdet_cov(Lambda)
return [u0, u1, u2, u3]
def compute_dims_from_values(self, x, Lambda):
"""
Return the shape of the moments for a fixed value.
"""
if np.ndim(x) < 1:
raise ValueError("Mean must be a vector")
if np.ndim(Lambda) < 2:
raise ValueError("Precision must be a matrix")
D = np.shape(x)[-1]
if np.shape(Lambda)[-2:] != (D,D):
raise ValueError("Mean vector and precision matrix have "
"inconsistent shapes")
return ( (D,), (), (D,D), () )
class GaussianGammaISODistribution(ExponentialFamilyDistribution):
"""
Class for the VMP formulas of Gaussian-Gamma-ISO variables.
"""
def compute_message_to_parent(self, parent, index, u, u_mu_Lambda, u_a, u_b):
"""
Compute the message to a parent node.
"""
if index == 0:
raise NotImplementedError()
elif index == 1:
raise NotImplementedError()
elif index == 2:
raise NotImplementedError()
else:
raise ValueError("Index out of bounds")
def compute_phi_from_parents(self, u_mu_Lambda, u_a, u_b, mask=True):
"""
Compute the natural parameter vector given parent moments.
"""
raise NotImplementedError()
def compute_moments_and_cgf(self, phi, mask=True):
"""
Compute the moments and :math:`g(\phi)`.
"""
raise NotImplementedError()
return (u, g)
def compute_cgf_from_parents(self, u_mu_Lambda, u_a, u_b):
"""
Compute :math:`\mathrm{E}_{q(p)}[g(p)]`
"""
raise NotImplementedError()
return g
def compute_fixed_moments_and_f(self, x, alpha, mask=True):
"""
Compute the moments and :math:`f(x)` for a fixed value.
"""
raise NotImplementedError()
return (u, f)
class GaussianWishartDistribution(ExponentialFamilyDistribution):
"""
Class for the VMP formulas of Gaussian-Wishart variables.
"""
def compute_message_to_parent(self, parent, index, u, u_mu, u_alpha, u_V, u_n):
"""
Compute the message to a parent node.
"""
if index == 0:
raise NotImplementedError()
elif index == 1:
raise NotImplementedError()
elif index == 2:
raise NotImplementedError()
elif index == 3:
raise NotImplementedError()
else:
raise ValueError("Index out of bounds")
def compute_phi_from_parents(self, u_mu, u_alpha, u_V, u_n, mask=True):
"""
Compute the natural parameter vector given parent moments.
"""
raise NotImplementedError()
def compute_moments_and_cgf(self, phi, mask=True):
"""
Compute the moments and :math:`g(\phi)`.
"""
raise NotImplementedError()
return (u, g)
def compute_cgf_from_parents(self, u_mu, u_alpha, u_V, u_n):
"""
Compute :math:`\mathrm{E}_{q(p)}[g(p)]`
"""
raise NotImplementedError()
return g
def compute_fixed_moments_and_f(self, x, Lambda, mask=True):
"""
Compute the moments and :math:`f(x)` for a fixed value.
"""
raise NotImplementedError()
return (u, f)
class GaussianWishart(ExponentialFamily):
"""
Node for Gaussian-Wishart random variables.
The prior:
.. math::
p(x, \Lambda| \mu, \alpha, V, n)
p(x|\Lambda, \mu, \alpha) = \mathcal(N)(x | \mu, \alpha^{-1} Lambda^{-1})
p(\Lambda|V, n) = \mathcal(W)(\Lambda | n, V)
The posterior approximation :math:`q(x, \Lambda)` has the same Gaussian-Wishart form.
"""
_moments = GaussianWishartMoments()
_parent_moments = (GaussianGammaMoments(),
GammaMoments(),
WishartMoments(),
WishartPriorMoments())
_distribution = GaussianWishartDistribution()
@classmethod
@ensureparents
def _constructor(cls, mu, alpha, V, n, plates_lambda=None, plates_x=None, **kwargs):
"""
Constructs distribution and moments objects.
This method is called if useconstructor decorator is used for __init__.
`mu` is the mean/location vector
`alpha` is the scale
`V` is the scale matrix
`n` is the degrees of freedom
"""
D = mu.dims[0][0]
# Check shapes
if mu.dims != ( (D,), (D,D), (), () ):
raise ValueError("Mean vector has wrong shape")
if alpha.dims != ( (), () ):
raise ValueError("Scale has wrong shape")
if V.dims != ( (D,D), () ):
raise ValueError("Precision matrix has wrong shape")
if n.dims != ( (), () ):
raise ValueError("Degrees of freedom has wrong shape")
dims = ( (D,), (), (D,D), () )
return (dims,
kwargs,
cls._total_plates(kwargs.get('plates'),
cls._distribution.plates_from_parent(0, mu.plates),
cls._distribution.plates_from_parent(1, alpha.plates),
cls._distribution.plates_from_parent(2, V.plates),
cls._distribution.plates_from_parent(3, n.plates)),
cls._distribution,
cls._moments,
cls._parent_moments)
def random(self):
"""
Draw a random sample from the distribution.
"""
raise NotImplementedError()
def show(self):
"""
Print the distribution using standard parameterization.
"""
raise NotImplementedError()
| nipunreddevil/bayespy | bayespy/inference/vmp/nodes/gaussian_wishart.py | Python | gpl-3.0 | 10,240 |
using System;
using Server.Items;
namespace Server.Items
{
public class DecorativePlateKabuto : BaseArmor
{
public override int BasePhysicalResistance { get { return 6; } }
public override int BaseFireResistance { get { return 2; } }
public override int BaseColdResistance { get { return 2; } }
public override int BasePoisonResistance { get { return 2; } }
public override int BaseEnergyResistance { get { return 3; } }
public override int InitMinHits { get { return 55; } }
public override int InitMaxHits { get { return 75; } }
public override int StrengthReq { get { return 70; } }
public override ArmorMaterialType MaterialType { get { return ArmorMaterialType.Plate; } }
[Constructable]
public DecorativePlateKabuto()
: base( 0x2778 )
{
Weight = 6.0;
}
public DecorativePlateKabuto( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */
reader.ReadInt();
}
}
} | greeduomacro/xrunuo | Scripts/Distro/Items/Armor/Plate/DecorativePlateKabuto.cs | C# | gpl-3.0 | 1,204 |
<?php
/* Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.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/>.
*/
$contracts = array(
'CHARSET' => 'UTF-8',
'ContractsArea' => 'Kontrakter område',
'ListOfContracts' => 'Liste over kontrakter',
'LastContracts' => 'Seneste %s modificerede kontrakter',
'AllContracts' => 'Alle kontrakter',
'ContractCard' => 'Kontrakt-kortet',
'ContractStatus' => 'Kontrakt status',
'ContractStatusNotRunning' => 'Ikke kører',
'ContractStatusRunning' => 'Kørsel',
'ContractStatusDraft' => 'Udkast',
'ContractStatusValidated' => 'Valideret',
'ContractStatusClosed' => 'Lukket',
'ServiceStatusInitial' => 'Ikke kører',
'ServiceStatusRunning' => 'Kørsel',
'ServiceStatusNotLate' => 'Kører, ikke er udløbet',
'ServiceStatusNotLateShort' => 'Ikke er udløbet',
'ServiceStatusLate' => 'Kører, er udløbet',
'ServiceStatusLateShort' => 'Udløbet',
'ServiceStatusClosed' => 'Lukket',
'ServicesLegend' => 'Services legend',
'Contracts' => 'Kontrakter',
'Contract' => 'Kontrakt',
'NoContracts' => 'Nr. kontrakter',
'MenuServices' => 'Services',
'MenuInactiveServices' => 'Tjenester, der ikke er aktive',
'MenuRunningServices' => 'Kørsel tjenester',
'MenuExpiredServices' => 'Udløbet tjenester',
'MenuClosedServices' => 'Lukket tjenester',
'NewContract' => 'Ny kontrakt',
'AddContract' => 'Tilføj kontrakt',
'SearchAContract' => 'Søg en kontrakt',
'DeleteAContract' => 'Slet en kontrakt',
'CloseAContract' => 'Luk en kontrakt',
'ConfirmDeleteAContract' => 'Er du sikker på du vil slette denne kontrakt og alle dets tjenester?',
'ConfirmValidateContract' => 'Er du sikker på at du ønsker at validere denne kontrakt?',
'ConfirmCloseContract' => 'Dette vil lukke alle tjenester (aktiv eller ej). Er du sikker på du ønsker at lukke denne kontrakt?',
'ConfirmCloseService' => 'Er du sikker på du ønsker at lukke denne service med <b>dato %s?</b>',
'ValidateAContract' => 'Validere en kontrakt',
'ActivateService' => 'Aktivér service',
'ConfirmActivateService' => 'Er du sikker på du vil aktivere denne tjeneste med datoen <b>for %s?</b>',
'RefContract' => 'Contract reference',
'DateContract' => 'Kontrakt dato',
'DateServiceActivate' => 'Forkyndelsesdato aktivering',
'DateServiceUnactivate' => 'Forkyndelsesdato unactivation',
'DateServiceStart' => 'Dato for starten af service',
'DateServiceEnd' => 'Datoen for afslutningen af tjenesten',
'ShowContract' => 'Vis kontrakt',
'ListOfServices' => 'Liste over tjenesteydelser',
'ListOfInactiveServices' => 'Liste over ikke aktive tjenester',
'ListOfExpiredServices' => 'Liste over udløb aktive tjenester',
'ListOfClosedServices' => 'Liste over lukkede tjenester',
'ListOfRunningContractsLines' => 'Liste over kører kontrakt linjer',
'ListOfRunningServices' => 'Liste over kører tjenester',
'NotActivatedServices' => 'Ikke aktiverede tjenester (blandt valideret kontrakter)',
'BoardNotActivatedServices' => 'Tjenester for at aktivere blandt valideret kontrakter',
'LastContracts' => 'Seneste %s modificerede kontrakter',
'LastActivatedServices' => 'Seneste %s aktiveret tjenester',
'LastModifiedServices' => 'Seneste %s modificerede tjenester',
'EditServiceLine' => 'Rediger service line',
'ContractStartDate' => 'Startdato',
'ContractEndDate' => 'Slutdato',
'DateStartPlanned' => 'Planlagt startdato',
'DateStartPlannedShort' => 'Planlagt startdato',
'DateEndPlanned' => 'Planlagte slutdato',
'DateEndPlannedShort' => 'Planlagte slutdato',
'DateStartReal' => 'Real startdato',
'DateStartRealShort' => 'Real startdato',
'DateEndReal' => 'Real slutdato',
'DateEndRealShort' => 'Real slutdato',
'NbOfServices' => 'Nb af tjenesteydelser',
'CloseService' => 'Luk service',
'ServicesNomberShort' => '%s tjeneste (r)',
'RunningServices' => 'Kørsel tjenester',
'BoardRunningServices' => 'Udløbet kører tjenester',
'ServiceStatus' => 'Status for service',
'DraftContracts' => 'Drafts kontrakter',
'CloseRefusedBecauseOneServiceActive' => 'Kontrakten ikke kan lukkes, da der er mindst en åben tjeneste på det',
'CloseAllContracts' => 'Luk alle kontrakter',
'DeleteContractLine' => 'Slet en kontrakt linje',
'ConfirmDeleteContractLine' => 'Er du sikker på du vil slette denne kontrakt linje?',
'MoveToAnotherContract' => 'Flyt tjeneste i en anden kontrakt.',
'ConfirmMoveToAnotherContract' => 'Jeg choosed nyt mål kontrakt og bekræfte, jeg ønsker at flytte denne tjeneste i denne kontrakt.',
'ConfirmMoveToAnotherContractQuestion' => 'Vælg, hvor eksisterende kontrakt (af samme tredjemand), du ønsker at flytte denne service?',
'PaymentRenewContractId' => 'Forny kontrakten linje (antal %s)',
'ExpiredSince' => 'Udløbsdatoen',
'RelatedContracts' => 'Relaterede kontrakter',
'NoExpiredServices' => 'Ingen udløbne aktive tjenester',
////////// Types de contacts //////////
'TypeContact_contrat_internal_SALESREPSIGN' => 'Salg repræsentant, der underskriver kontrakt',
'TypeContact_contrat_internal_SALESREPFOLL' => 'Salg repræsentant opfølgning kontrakt',
'TypeContact_contrat_external_BILLING' => 'Faktureringsindstillinger kunde kontakt',
'TypeContact_contrat_external_CUSTOMER' => 'Opfølgning kunde kontakt',
'TypeContact_contrat_external_SALESREPSIGN' => 'Undertegnelse kontrakt kunde kontakt',
'Error_CONTRACT_ADDON_NotDefined' => 'Konstant CONTRACT_ADDON ikke defineret'
);
?> | woakes070048/crm-php | htdocs/langs/da_DK/contracts.lang.php | PHP | gpl-3.0 | 6,072 |
package bb
import "github.com/Syfaro/telegram-bot-api"
type message struct {
Err error
bot *tgbotapi.BotAPI
config tgbotapi.MessageConfig
Ret tgbotapi.Message
}
func (b *Base) NewMessage(chatID int, text string) *message {
return &message{
bot: b.Bot,
config: tgbotapi.NewMessage(chatID, text),
}
}
func (m *message) DisableWebPagePreview() *message {
m.config.DisableWebPagePreview = true
return m
}
func (m *message) MarkdownMode() *message {
m.config.ParseMode = tgbotapi.ModeMarkdown
return m
}
func (m *message) ReplyToMessageID(ID int) *message {
m.config.ReplyToMessageID = ID
return m
}
func (m *message) ReplyMarkup(markup interface{}) *message {
m.config.ReplyMarkup = markup
return m
}
func (m *message) Send() *message {
msg, err := m.bot.SendMessage(m.config)
m.Ret = msg
m.Err = err
return m
}
type forward struct {
Err error
bot *tgbotapi.BotAPI
config tgbotapi.ForwardConfig
Ret tgbotapi.Message
}
func (b *Base) NewForward(chatID, fromChatID, messageID int) *forward {
return &forward{
bot: b.Bot,
config: tgbotapi.NewForward(chatID, fromChatID, messageID),
}
}
func (f *forward) Send() *forward {
msg, err := f.bot.ForwardMessage(f.config)
f.Ret = msg
f.Err = err
return f
}
| jqs7/telegram-chinese-groups | vendor/github.com/jqs7/bb/message.go | GO | gpl-3.0 | 1,264 |
#
# This file is part of Checkbox.
#
# Copyright 2008 Canonical Ltd.
#
# Checkbox 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.
#
# Checkbox 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 Checkbox. If not, see <http://www.gnu.org/licenses/>.
#
import os
import hashlib
import shutil
from stat import ST_MODE, S_IMODE, S_ISFIFO
def safe_change_mode(path, mode):
if not os.path.exists(path):
raise Exception("Path does not exist: %s" % path)
old_mode = os.stat(path)[ST_MODE]
if mode != S_IMODE(old_mode):
os.chmod(path, mode)
def safe_make_directory(path, mode=0o755):
if os.path.exists(path):
if not os.path.isdir(path):
raise Exception("Path is not a directory: %s" % path)
else:
os.makedirs(path, mode)
def safe_make_fifo(path, mode=0o666):
if os.path.exists(path):
mode = os.stat(path)[ST_MODE]
if not S_ISFIFO(mode):
raise Exception("Path is not a FIFO: %s" % path)
else:
os.mkfifo(path, mode)
def safe_remove_directory(path):
if os.path.exists(path):
if not os.path.isdir(path):
raise Exception("Path is not a directory: %s" % path)
shutil.rmtree(path)
def safe_remove_file(path):
if os.path.exists(path):
if not os.path.isfile(path):
raise Exception("Path is not a file: %s" % path)
os.remove(path)
def safe_rename(old, new):
if old != new:
if not os.path.exists(old):
raise Exception("Old path does not exist: %s" % old)
if os.path.exists(new):
raise Exception("New path exists already: %s" % new)
os.rename(old, new)
class safe_md5sum:
def __init__(self):
self.digest = hashlib.md5()
self.hexdigest = self.digest.hexdigest
def update(self, string):
self.digest.update(string.encode("utf-8"))
def safe_md5sum_file(name):
md5sum = None
if os.path.exists(name):
file = open(name)
digest = safe_md5sum()
while 1:
buf = file.read(4096)
if buf == "":
break
digest.update(buf)
file.close()
md5sum = digest.hexdigest()
return md5sum
def safe_close(file, safe=True):
if safe:
file.flush()
os.fsync(file.fileno())
file.close()
| jds2001/ocp-checkbox | checkbox/lib/safe.py | Python | gpl-3.0 | 2,778 |
require 'working_class/version'
require 'working_class/parser'
require 'working_class/task'
require 'working_class/tasklist'
# WorkingClass Module
#
module WorkingClass
# Loads the file from the path and returns a Tasklist
#
# @param path [String] the filepath
# @return [WorkingClass::Tasklist] the parsed Tasklist
#
def self.load_file(path)
string = File.open(path, 'r').read()
self.load(string)
end
# Parses the given string and returns a Tasklist
#
# @param string [String] the WorkingClass tasklist syntax string
# @return [WorkingClass::Tasklist] the parsed Tasklist
#
def self.load(string)
Parser.new(string).to_tasklist
end
end
| TimKaechele/Working-Class | lib/working_class.rb | Ruby | gpl-3.0 | 680 |
/*
* Copyright 2012 OSBI Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var account = 'UA-16172251-17';
if (window.location.hostname && window.location.hostname == "dev.analytical-labs.com" ) {
account = 'UA-16172251-12';
} else if (window.location.hostname && window.location.hostname == "demo.analytical-labs.com" ) {
account = 'UA-16172251-5';
}
var _gaq = _gaq || [];
_gaq.push(['_setAccount', account]);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
| clevernet/CleverNIM | saiku-ui/js/ga.js | JavaScript | gpl-3.0 | 1,366 |
#ifndef STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_RNG_HPP
#define STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_RNG_HPP
#include <boost/random/student_t_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/lbeta.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <stan/math/prim/scal/fun/digamma.hpp>
#include <stan/math/prim/scal/meta/length.hpp>
#include <stan/math/prim/scal/fun/grad_reg_inc_beta.hpp>
#include <stan/math/prim/scal/fun/inc_beta.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <stan/math/prim/scal/meta/VectorBuilder.hpp>
namespace stan {
namespace math {
template <class RNG>
inline double
student_t_rng(double nu,
double mu,
double sigma,
RNG& rng) {
using boost::variate_generator;
using boost::random::student_t_distribution;
static const char* function("student_t_rng");
check_positive_finite(function, "Degrees of freedom parameter", nu);
check_finite(function, "Location parameter", mu);
check_positive_finite(function, "Scale parameter", sigma);
variate_generator<RNG&, student_t_distribution<> >
rng_unit_student_t(rng, student_t_distribution<>(nu));
return mu + sigma * rng_unit_student_t();
}
}
}
#endif
| TomasVaskevicius/bouncy-particle-sampler | third_party/stan_math/stan/math/prim/scal/prob/student_t_rng.hpp | C++ | gpl-3.0 | 1,700 |
from py2neo import Graph
from py2neo.ext.gremlin import Gremlin
import os
DEFAULT_GRAPHDB_URL = "http://localhost:7474/db/data/"
DEFAULT_STEP_DIR = os.path.dirname(__file__) + '/bjoernsteps/'
class BjoernSteps:
def __init__(self):
self._initJoernSteps()
self.initCommandSent = False
def setGraphDbURL(self, url):
""" Sets the graph database URL. By default,
http://localhost:7474/db/data/ is used."""
self.graphDbURL = url
def addStepsDir(self, stepsDir):
"""Add an additional directory containing steps to be injected
into the server"""
self.stepsDirs.append(stepsDir)
def connectToDatabase(self):
""" Connects to the database server."""
self.graphDb = Graph(self.graphDbURL)
self.gremlin = Gremlin(self.graphDb)
def runGremlinQuery(self, query):
""" Runs the specified gremlin query on the database. It is
assumed that a connection to the database has been
established. To allow the user-defined steps located in the
joernsteps directory to be used in the query, these step
definitions are prepended to the query."""
if not self.initCommandSent:
self.gremlin.execute(self._createInitCommand())
self.initCommandSent = True
return self.gremlin.execute(query)
def runCypherQuery(self, cmd):
""" Runs the specified cypher query on the graph database."""
return cypher.execute(self.graphDb, cmd)
def getGraphDbURL(self):
return self.graphDbURL
"""
Create chunks from a list of ids.
This method is useful when you want to execute many independent
traversals on a large set of start nodes. In that case, you
can retrieve the set of start node ids first, then use 'chunks'
to obtain disjoint subsets that can be passed to idListToNodes.
"""
def chunks(self, idList, chunkSize):
for i in xrange(0, len(idList), chunkSize):
yield idList[i:i+chunkSize]
def _initJoernSteps(self):
self.graphDbURL = DEFAULT_GRAPHDB_URL
self.stepsDirs = [DEFAULT_STEP_DIR]
def _createInitCommand(self):
initCommand = ""
for stepsDir in self.stepsDirs:
for (root, dirs, files) in os.walk(stepsDir, followlinks=True):
files.sort()
for f in files:
filename = os.path.join(root, f)
if not filename.endswith('.groovy'): continue
initCommand += file(filename).read() + "\n"
return initCommand
| mrphrazer/bjoern | python-bjoern/bjoern/all.py | Python | gpl-3.0 | 2,645 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2018 OpenFOAM Foundation
\\/ 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 "slipPointPatchFields.H"
#include "pointPatchFields.H"
#include "addToRunTimeSelectionTable.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
makePointPatchFields(slip);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
| will-bainbridge/OpenFOAM-dev | src/OpenFOAM/fields/pointPatchFields/derived/slip/slipPointPatchFields.C | C++ | gpl-3.0 | 1,689 |
/*
* gvNIX is an open source tool for rapid application development (RAD).
* Copyright (C) 2010 Generalitat Valenciana
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gvnix.addon.geo.addon;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.gvnix.addon.geo.annotations.GvNIXMapViewer;
import org.gvnix.support.WebProjectUtils;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.springframework.roo.addon.propfiles.PropFileOperations;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.ArrayAttributeValue;
import org.springframework.roo.classpath.details.annotations.ClassAttributeValue;
import org.springframework.roo.classpath.itd.AbstractItdMetadataProvider;
import org.springframework.roo.classpath.itd.ItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.model.SpringJavaType;
import org.springframework.roo.project.LogicalPath;
import org.springframework.roo.project.ProjectOperations;
import org.springframework.roo.support.logging.HandlerUtils;
/**
* Provides {@link GvNIXMapViewerMetadata}.
*
* @author <a href="http://www.disid.com">DISID Corporation S.L.</a> made for <a
* href="http://www.dgti.gva.es">General Directorate for Information
* Technologies (DGTI)</a>
* @since 1.4
*/
@Component
@Service
public final class GvNIXMapViewerMetadataProvider extends
AbstractItdMetadataProvider {
private static final Logger LOGGER = HandlerUtils
.getLogger(GvNIXMapViewerMetadataProvider.class);
private ProjectOperations projectOperations;
private PropFileOperations propFileOperations;
private WebProjectUtils webProjectUtils;
/**
* Register itself into metadataDependencyRegister and add metadata trigger
*
* @param context the component context
*/
protected void activate(ComponentContext cContext) {
context = cContext.getBundleContext();
getMetadataDependencyRegistry().registerDependency(
PhysicalTypeIdentifier.getMetadataIdentiferType(),
getProvidesType());
addMetadataTrigger(new JavaType(GvNIXMapViewer.class.getName()));
}
/**
* Unregister this provider
*
* @param context the component context
*/
protected void deactivate(ComponentContext context) {
getMetadataDependencyRegistry().deregisterDependency(
PhysicalTypeIdentifier.getMetadataIdentiferType(),
getProvidesType());
removeMetadataTrigger(new JavaType(GvNIXMapViewer.class.getName()));
}
/**
* Return an instance of the Metadata offered by this add-on
*/
protected ItdTypeDetailsProvidingMetadataItem getMetadata(
String metadataIdentificationString, JavaType aspectName,
PhysicalTypeMetadata governorPhysicalTypeMetadata,
String itdFilename) {
JavaType javaType = GvNIXMapViewerMetadata
.getJavaType(metadataIdentificationString);
ClassOrInterfaceTypeDetails controller = getTypeLocationService()
.getTypeDetails(javaType);
// Getting @RequestMapping annotation
AnnotationMetadata requestMappingAnnotation = controller
.getAnnotation(SpringJavaType.REQUEST_MAPPING);
// Getting @GvNIXMapViewer annotation
AnnotationMetadata mapViewerAnnotation = controller
.getAnnotation(new JavaType(GvNIXMapViewer.class.getName()));
// Getting path value
AnnotationAttributeValue<Object> value = requestMappingAnnotation
.getAttribute("value");
String path = value.getValue().toString();
// Getting mapId
String mapId = String.format("ps_%s_%s", javaType.getPackage()
.getFullyQualifiedPackageName().replaceAll("[.]", "_"),
new JavaSymbolName(path.replaceAll("/", ""))
.getSymbolNameCapitalisedFirstLetter());
// Getting entityLayers
List<JavaType> entitiesToVisualize = new ArrayList<JavaType>();
@SuppressWarnings({ "unchecked", "rawtypes" })
ArrayAttributeValue<ClassAttributeValue> mapViewerAttributes = (ArrayAttributeValue) mapViewerAnnotation
.getAttribute("entityLayers");
if (mapViewerAttributes != null) {
List<ClassAttributeValue> entityLayers = mapViewerAttributes
.getValue();
for (ClassAttributeValue entity : entityLayers) {
entitiesToVisualize.add(entity.getValue());
}
}
// Getting projection
String projection = "";
AnnotationAttributeValue<Object> projectionAttr = mapViewerAnnotation
.getAttribute("projection");
if (projectionAttr != null) {
projection = projectionAttr.getValue().toString();
}
return new GvNIXMapViewerMetadata(metadataIdentificationString,
aspectName, governorPhysicalTypeMetadata,
getProjectOperations(), getPropFileOperations(),
getTypeLocationService(), getFileManager(),
entitiesToVisualize, path, mapId, projection,
getWebProjectUtils());
}
/**
* Define the unique ITD file name extension, here the resulting file name
* will be **_ROO_GvNIXMapViewer.aj
*/
public String getItdUniquenessFilenameSuffix() {
return "GvNIXMapViewer";
}
protected String getGovernorPhysicalTypeIdentifier(
String metadataIdentificationString) {
JavaType javaType = GvNIXMapViewerMetadata
.getJavaType(metadataIdentificationString);
LogicalPath path = GvNIXMapViewerMetadata
.getPath(metadataIdentificationString);
return PhysicalTypeIdentifier.createIdentifier(javaType, path);
}
protected String createLocalIdentifier(JavaType javaType, LogicalPath path) {
return GvNIXMapViewerMetadata.createIdentifier(javaType, path);
}
public String getProvidesType() {
return GvNIXMapViewerMetadata.getMetadataIdentiferType();
}
public ProjectOperations getProjectOperations() {
if (projectOperations == null) {
// Get all Services implement ProjectOperations interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(
ProjectOperations.class.getName(), null);
for (ServiceReference<?> ref : references) {
return (ProjectOperations) this.context.getService(ref);
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load ProjectOperations on GvNIXWebEntityMapLayerMetadataProvider.");
return null;
}
}
else {
return projectOperations;
}
}
public PropFileOperations getPropFileOperations() {
if (propFileOperations == null) {
// Get all Services implement PropFileOperations interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(
PropFileOperations.class.getName(), null);
for (ServiceReference<?> ref : references) {
return (PropFileOperations) this.context.getService(ref);
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load PropFileOperations on GvNIXWebEntityMapLayerMetadataProvider.");
return null;
}
}
else {
return propFileOperations;
}
}
public WebProjectUtils getWebProjectUtils() {
if (webProjectUtils == null) {
// Get all Services implement WebProjectUtils interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(
WebProjectUtils.class.getName(), null);
for (ServiceReference<?> ref : references) {
webProjectUtils = (WebProjectUtils) this.context
.getService(ref);
return webProjectUtils;
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load WebProjectUtils on GvNIXWebEntityMapLayerMetadataProvider.");
return null;
}
}
else {
return webProjectUtils;
}
}
} | osroca/gvnix | addon-web-mvc-geo/addon/src/main/java/org/gvnix/addon/geo/addon/GvNIXMapViewerMetadataProvider.java | Java | gpl-3.0 | 10,078 |
// Copyright � 2010 - May 2014 Rise Vision Incorporated.
// Use of this software is governed by the GPLv3 license
// (reproduced in the LICENSE file).
function rvPlayerDCPage() {
var pageHTML = "";
this.get = function (port, ports, dcStatus, onStr, offStr) {
var res = pageHTML.replace("[PORT]", port);
res = res.replace("[PORTS]", ports);
res = res.replace("[Status]", dcStatus);
res = res.replace("[onStr]", onStr);
res = res.replace("[offStr]", offStr);
return res;
}
this.init = function () {
download(chrome.runtime.getURL("display_page.html"));
}
var download = function (fileUrl) {
var xhr = new XMLHttpRequest();
xhr.responseType = "text";
//xhr.onerror = ???;
xhr.onload = function (xhrProgressEvent) {
pageHTML = xhrProgressEvent.target.responseText;
}
xhr.open('GET', fileUrl, true); //async=true
xhr.send();
};
} | xlsuite/reach.network | player-socialweedia/app/js/player/dc_page.js | JavaScript | gpl-3.0 | 985 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to manage A10 Networks slb service-group objects
(c) 2014, Mischa Peters <mpeters@a10networks.com>,
Eric Chou <ericc@a10networks.com>
This file is part of Ansible
Ansible 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.
Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
"""
DOCUMENTATION = '''
---
module: a10_service_group
version_added: 1.8
short_description: Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' service groups.
description:
- Manage SLB (Server Load Balancing) service-group objects on A10 Networks devices via aXAPIv2.
author: "Eric Chou (@ericchou) 2016, Mischa Peters (@mischapeters) 2014"
notes:
- Requires A10 Networks aXAPI 2.1.
- When a server doesn't exist and is added to the service-group the server will be created.
extends_documentation_fragment: a10
options:
partition:
version_added: "2.3"
description:
- set active-partition
required: false
default: null
service_group:
description:
- The SLB (Server Load Balancing) service-group name
required: true
default: null
aliases: ['service', 'pool', 'group']
service_group_protocol:
description:
- The SLB service-group protocol of TCP or UDP.
required: false
default: tcp
aliases: ['proto', 'protocol']
choices: ['tcp', 'udp']
service_group_method:
description:
- The SLB service-group load balancing method, such as round-robin or weighted-rr.
required: false
default: round-robin
aliases: ['method']
choices: ['round-robin', 'weighted-rr', 'least-connection', 'weighted-least-connection', 'service-least-connection', 'service-weighted-least-connection', 'fastest-response', 'least-request', 'round-robin-strict', 'src-ip-only-hash', 'src-ip-hash']
servers:
description:
- A list of servers to add to the service group. Each list item should be a
dictionary which specifies the C(server:) and C(port:), but can also optionally
specify the C(status:). See the examples below for details.
required: false
default: null
validate_certs:
description:
- If C(no), SSL certificates will not be validated. This should only be used
on personally controlled devices using self-signed certificates.
required: false
default: 'yes'
choices: ['yes', 'no']
'''
RETURN = '''
#
'''
EXAMPLES = '''
# Create a new service-group
- a10_service_group:
host: a10.mydomain.com
username: myadmin
password: mypassword
partition: mypartition
service_group: sg-80-tcp
servers:
- server: foo1.mydomain.com
port: 8080
- server: foo2.mydomain.com
port: 8080
- server: foo3.mydomain.com
port: 8080
- server: foo4.mydomain.com
port: 8080
status: disabled
'''
RETURN = '''
content:
description: the full info regarding the slb_service_group
returned: success
type: string
sample: "mynewservicegroup"
'''
VALID_SERVICE_GROUP_FIELDS = ['name', 'protocol', 'lb_method']
VALID_SERVER_FIELDS = ['server', 'port', 'status']
def validate_servers(module, servers):
for item in servers:
for key in item:
if key not in VALID_SERVER_FIELDS:
module.fail_json(msg="invalid server field (%s), must be one of: %s" % (key, ','.join(VALID_SERVER_FIELDS)))
# validate the server name is present
if 'server' not in item:
module.fail_json(msg="server definitions must define the server field")
# validate the port number is present and an integer
if 'port' in item:
try:
item['port'] = int(item['port'])
except:
module.fail_json(msg="server port definitions must be integers")
else:
module.fail_json(msg="server definitions must define the port field")
# convert the status to the internal API integer value
if 'status' in item:
item['status'] = axapi_enabled_disabled(item['status'])
else:
item['status'] = 1
def main():
argument_spec = a10_argument_spec()
argument_spec.update(url_argument_spec())
argument_spec.update(
dict(
state=dict(type='str', default='present', choices=['present', 'absent']),
service_group=dict(type='str', aliases=['service', 'pool', 'group'], required=True),
service_group_protocol=dict(type='str', default='tcp', aliases=['proto', 'protocol'], choices=['tcp', 'udp']),
service_group_method=dict(type='str', default='round-robin',
aliases=['method'],
choices=['round-robin',
'weighted-rr',
'least-connection',
'weighted-least-connection',
'service-least-connection',
'service-weighted-least-connection',
'fastest-response',
'least-request',
'round-robin-strict',
'src-ip-only-hash',
'src-ip-hash']),
servers=dict(type='list', aliases=['server', 'member'], default=[]),
partition=dict(type='str', default=[]),
)
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=False
)
host = module.params['host']
username = module.params['username']
password = module.params['password']
partition = module.params['partition']
state = module.params['state']
write_config = module.params['write_config']
slb_service_group = module.params['service_group']
slb_service_group_proto = module.params['service_group_protocol']
slb_service_group_method = module.params['service_group_method']
slb_servers = module.params['servers']
if slb_service_group is None:
module.fail_json(msg='service_group is required')
axapi_base_url = 'https://' + host + '/services/rest/V2.1/?format=json'
load_balancing_methods = {'round-robin': 0,
'weighted-rr': 1,
'least-connection': 2,
'weighted-least-connection': 3,
'service-least-connection': 4,
'service-weighted-least-connection': 5,
'fastest-response': 6,
'least-request': 7,
'round-robin-strict': 8,
'src-ip-only-hash': 14,
'src-ip-hash': 15}
if not slb_service_group_proto or slb_service_group_proto.lower() == 'tcp':
protocol = 2
else:
protocol = 3
# validate the server data list structure
validate_servers(module, slb_servers)
json_post = {
'service_group': {
'name': slb_service_group,
'protocol': protocol,
'lb_method': load_balancing_methods[slb_service_group_method],
}
}
# first we authenticate to get a session id
session_url = axapi_authenticate(module, axapi_base_url, username, password)
# then we select the active-partition
slb_server_partition = axapi_call(module, session_url + '&method=system.partition.active', json.dumps({'name': partition}))
# then we check to see if the specified group exists
slb_result = axapi_call(module, session_url + '&method=slb.service_group.search', json.dumps({'name': slb_service_group}))
slb_service_group_exist = not axapi_failure(slb_result)
changed = False
if state == 'present':
# before creating/updating we need to validate that servers
# defined in the servers list exist to prevent errors
checked_servers = []
for server in slb_servers:
result = axapi_call(module, session_url + '&method=slb.server.search', json.dumps({'name': server['server']}))
if axapi_failure(result):
module.fail_json(msg="the server %s specified in the servers list does not exist" % server['server'])
checked_servers.append(server['server'])
if not slb_service_group_exist:
result = axapi_call(module, session_url + '&method=slb.service_group.create', json.dumps(json_post))
if axapi_failure(result):
module.fail_json(msg=result['response']['err']['msg'])
changed = True
else:
# check to see if the service group definition without the
# server members is different, and update that individually
# if it needs it
do_update = False
for field in VALID_SERVICE_GROUP_FIELDS:
if json_post['service_group'][field] != slb_result['service_group'][field]:
do_update = True
break
if do_update:
result = axapi_call(module, session_url + '&method=slb.service_group.update', json.dumps(json_post))
if axapi_failure(result):
module.fail_json(msg=result['response']['err']['msg'])
changed = True
# next we pull the defined list of servers out of the returned
# results to make it a bit easier to iterate over
defined_servers = slb_result.get('service_group', {}).get('member_list', [])
# next we add/update new member servers from the user-specified
# list if they're different or not on the target device
for server in slb_servers:
found = False
different = False
for def_server in defined_servers:
if server['server'] == def_server['server']:
found = True
for valid_field in VALID_SERVER_FIELDS:
if server[valid_field] != def_server[valid_field]:
different = True
break
if found or different:
break
# add or update as required
server_data = {
"name": slb_service_group,
"member": server,
}
if not found:
result = axapi_call(module, session_url + '&method=slb.service_group.member.create', json.dumps(server_data))
changed = True
elif different:
result = axapi_call(module, session_url + '&method=slb.service_group.member.update', json.dumps(server_data))
changed = True
# finally, remove any servers that are on the target
# device but were not specified in the list given
for server in defined_servers:
found = False
for slb_server in slb_servers:
if server['server'] == slb_server['server']:
found = True
break
# remove if not found
server_data = {
"name": slb_service_group,
"member": server,
}
if not found:
result = axapi_call(module, session_url + '&method=slb.service_group.member.delete', json.dumps(server_data))
changed = True
# if we changed things, get the full info regarding
# the service group for the return data below
if changed:
result = axapi_call(module, session_url + '&method=slb.service_group.search', json.dumps({'name': slb_service_group}))
else:
result = slb_result
elif state == 'absent':
if slb_service_group_exist:
result = axapi_call(module, session_url + '&method=slb.service_group.delete', json.dumps({'name': slb_service_group}))
changed = True
else:
result = dict(msg="the service group was not present")
# if the config has changed, save the config unless otherwise requested
if changed and write_config:
write_result = axapi_call(module, session_url + '&method=system.action.write_memory')
if axapi_failure(write_result):
module.fail_json(msg="failed to save the configuration: %s" % write_result['response']['err']['msg'])
# log out of the session nicely and exit
axapi_call(module, session_url + '&method=session.close')
module.exit_json(changed=changed, content=result)
# standard ansible module imports
import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import url_argument_spec
from ansible.module_utils.a10 import axapi_call, a10_argument_spec, axapi_authenticate, axapi_failure, axapi_enabled_disabled
if __name__ == '__main__':
main()
| kbrebanov/ansible-modules-extras | network/a10/a10_service_group.py | Python | gpl-3.0 | 13,531 |
# The majority of The Supplejack Manager code is Crown copyright (C) 2014, New Zealand Government,
# and is licensed under the GNU General Public License, version 3. Some components are
# third party components that are licensed under the MIT license or otherwise publicly available.
# See https://github.com/DigitalNZ/supplejack_manager for details.
#
# Supplejack was created by DigitalNZ at the National Library of NZ and the Department of Internal Affairs.
# http://digitalnz.org/supplejack
require "spec_helper"
describe CollectionStatisticsHelper do
end | motizuki/supplejack_manager | spec/helpers/collection_statistics_helper_spec.rb | Ruby | gpl-3.0 | 566 |
package com.oryx.remote.webservice.element._enum;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java pour XmlEnumContact.
* <p>
* <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
* <p>
* <pre>
* <simpleType name="XmlEnumContact">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Phone"/>
* <enumeration value="Mobile"/>
* <enumeration value="Fax"/>
* <enumeration value="Web"/>
* <enumeration value="Email"/>
* </restriction>
* </simpleType>
* </pre>
*/
@XmlType(name = "XmlEnumContact", namespace = "http://enum.element.webservice.remote.oryx.com")
@XmlEnum
public enum XmlEnumContact {
@XmlEnumValue("Phone")
PHONE("Phone"),
@XmlEnumValue("Mobile")
MOBILE("Mobile"),
@XmlEnumValue("Fax")
FAX("Fax"),
@XmlEnumValue("Web")
WEB("Web"),
@XmlEnumValue("Email")
EMAIL("Email");
private final String value;
XmlEnumContact(String v) {
value = v;
}
public static XmlEnumContact fromValue(String v) {
for (XmlEnumContact c : XmlEnumContact.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public String value() {
return value;
}
}
| 241180/Oryx | oryx-server-ws-gen/src/main/java/copied/com/oryx/remote/webservice/element/_enum/XmlEnumContact.java | Java | gpl-3.0 | 1,467 |
# -*- coding: utf-8 -*-
"""
tiponpython Simulacion de ensayos de acuiferos
Copyright 2012 Andres Pias
This file is part of tiponpython.
tiponpython is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
tiponpython 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 tiponpython. If not, see http://www.gnu.org/licenses/gpl.txt.
"""
# Form implementation generated from reading ui file 'ingresarCaudal.ui'
#
# Created: Wed Dec 14 21:03:09 2011
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import observacion
import observacionesensayo
import sys
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Dialog(QtGui.QDialog):
def setupUi(self, Dialog, cont):
global ContEnsayo
ContEnsayo=cont
self.observaciones=[]
Dialog.setObjectName(_fromUtf8("ingresarobservacionesensayo"))
Dialog.resize(375, 214)
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Ingresar Observaciones Ensayo", None, QtGui.QApplication.UnicodeUTF8))
self.txttiempo = QtGui.QTextEdit(Dialog)
self.txttiempo.setGeometry(QtCore.QRect(170, 40, 101, 31))
self.txttiempo.setObjectName(_fromUtf8("txttiempo"))
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(100, 50, 46, 21))
self.label.setText(QtGui.QApplication.translate("Dialog", "Tiempo", None, QtGui.QApplication.UnicodeUTF8))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(100, 100, 46, 13))
self.label_2.setText(QtGui.QApplication.translate("Dialog", "Nivel", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.txtcaudal = QtGui.QTextEdit(Dialog)
self.txtcaudal.setGeometry(QtCore.QRect(170, 90, 101, 31))
self.txtcaudal.setObjectName(_fromUtf8("txtcaudal"))
self.btnagregar = QtGui.QPushButton(Dialog)
self.btnagregar.setGeometry(QtCore.QRect(100, 150, 71, 23))
self.btnagregar.setText(QtGui.QApplication.translate("Dialog", "Agregar", None, QtGui.QApplication.UnicodeUTF8))
self.btnagregar.setObjectName(_fromUtf8("btnagregar"))
self.btnfinalizar = QtGui.QPushButton(Dialog)
self.btnfinalizar.setGeometry(QtCore.QRect(200, 150, 71, 23))
self.btnfinalizar.setText(QtGui.QApplication.translate("Dialog", "Finalizar", None, QtGui.QApplication.UnicodeUTF8))
self.btnfinalizar.setObjectName(_fromUtf8("btnfinalizar"))
self.dialogo=Dialog
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.btnagregar, QtCore.SIGNAL(_fromUtf8("clicked()")), self.agregar)
QtCore.QObject.connect(self.btnfinalizar, QtCore.SIGNAL(_fromUtf8("clicked()")), self.finalizar)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
pass
def agregar(self):
global ContEnsayo
control=True
t=float(self.txttiempo.toPlainText())
print "tiempo: "+str(t)
## Se verifica que vengas los datos con sus tiempos ordenados de manera creciente sino salta
control=ContEnsayo.verificarFormato(self.observaciones, t)
if (control==False):
reply = QtGui.QMessageBox.critical(self,
"Error",
"Los datos de bombeo no fueron agregaos. Debe ingresar un valor para el tiempo mayor a los ingresados anteriormente.")
else:
n=float(self.txtcaudal.toPlainText())
print "caudal: "+str(n)
o=observacion.observacion(t,n)
self.observaciones.append(o)
reply = QtGui.QMessageBox.information(None,
"Información",
"Se agrego la nueva observacion del ensayo. Presione finalizar para guardar las observaciones")
self.txttiempo.setText('')
self.txtcaudal.setText('')
def finalizar(self):
global ContEnsayo
####Pedir un nombre para el ensayo
nombre, ok=QtGui.QInputDialog.getText(self,"Finalzar registro ",
"Nombre: ", QtGui.QLineEdit.Normal)
## Se manda al controlador las observaciones y se retorna el id de las observaciones
obse=ContEnsayo.agregarObservacion(self.observaciones, nombre)
reply = QtGui.QMessageBox.information(self,
"Información",
"Se ha creado un nuevo conjunto de observaciones en el sistema. El id es: "+ str(obse.id))
if reply == QtGui.QMessageBox.Ok:
print "OK"
self.dialogo.close()
else:
print "Escape"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
frmImpProyecto = QtGui.QWidget()
ui = Ui_Dialog()
ui.setupUi(frmImpProyecto)
frmImpProyecto.show()
sys.exit(app.exec_())
| fenixon/tiponpython | views/ingresarObservaciones.py | Python | gpl-3.0 | 5,555 |
import WordCombination from "../../src/values/WordCombination";
import relevantWords from "../../src/stringProcessing/relevantWords";
import polishFunctionWordsFactory from "../../src/researches/polish/functionWords.js";
const getRelevantWords = relevantWords.getRelevantWords;
const polishFunctionWords = polishFunctionWordsFactory().all;
describe( "gets Polish word combinations", function() {
it( "returns word combinations", function() {
const input = "W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast" +
" dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy " +
"natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, " +
"to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce " +
"piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w" +
" klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś " +
"odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że " +
"gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas" +
" wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę.";
const expected = [
new WordCombination( [ "odczuwa", "ból", "w", "klatce", "piersiowej" ], 8, polishFunctionWords ),
new WordCombination( [ "natychmiast", "dzwonić", "po", "karetkę" ], 8, polishFunctionWords ),
new WordCombination( [ "ból", "w", "klatce", "piersiowej" ], 8, polishFunctionWords ),
new WordCombination( [ "odczuwa", "ból", "w", "klatce" ], 8, polishFunctionWords ),
new WordCombination( [ "dzwonić", "po", "karetkę" ], 8, polishFunctionWords ),
new WordCombination( [ "ból", "w", "klatce" ], 8, polishFunctionWords ),
new WordCombination( [ "odczuwa", "ból" ], 8, polishFunctionWords ),
new WordCombination( [ "natychmiast", "dzwonić" ], 8, polishFunctionWords ),
new WordCombination( [ "klatce", "piersiowej" ], 8, polishFunctionWords ),
new WordCombination( [ "wie" ], 8, polishFunctionWords ),
new WordCombination( [ "karetkę" ], 8, polishFunctionWords ),
new WordCombination( [ "dzwonić" ], 8, polishFunctionWords ),
new WordCombination( [ "natychmiast" ], 8, polishFunctionWords ),
new WordCombination( [ "piersiowej" ], 8, polishFunctionWords ),
new WordCombination( [ "klatce" ], 8, polishFunctionWords ),
new WordCombination( [ "ból" ], 8, polishFunctionWords ),
new WordCombination( [ "odczuwa" ], 8, polishFunctionWords ),
new WordCombination( [ "zasadzie" ], 8, polishFunctionWords ),
];
// Make sure our words aren't filtered by density.
spyOn( WordCombination.prototype, "getDensity" ).and.returnValue( 0.01 );
const words = getRelevantWords( input, "pl_PL" );
words.forEach( function( word ) {
delete( word._relevantWords );
} );
expect( words ).toEqual( expected );
} );
} );
| Yoast/js-text-analysis | spec/stringProcessing/relevantWordsPolishSpec.js | JavaScript | gpl-3.0 | 3,204 |
<?php
if( ! post_password_required() ) {
if ( comments_open() or ( get_comments_number() > 0 ) ) {
get_template_part('templates/onePage/blocks/comments-list/comments-list');
get_template_part('templates/onePage/blocks/comments-pagination/comments-pagination');
get_template_part('templates/onePage/blocks/comments-form/comments-form');
}
}
| MarmonDesigns/cloud.ky | wp-content/themes/milo/comments.php | PHP | gpl-3.0 | 372 |
#region LICENSE
// Copyright 2014 LeagueSharp.Loader
// Profile.cs is part of LeagueSharp.Loader.
//
// LeagueSharp.Loader 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.
//
// LeagueSharp.Loader 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 LeagueSharp.Loader. If not, see <http://www.gnu.org/licenses/>.
#endregion
namespace LeagueSharp.Loader.Class
{
#region
using System.Collections.ObjectModel;
using System.ComponentModel;
#endregion
public class Profile : INotifyPropertyChanged
{
private ObservableCollection<LeagueSharpAssembly> _installedAssemblies;
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public ObservableCollection<LeagueSharpAssembly> InstalledAssemblies
{
get { return _installedAssemblies; }
set
{
_installedAssemblies = value;
OnPropertyChanged("InstalledAssemblies");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
} | RESISTANCEQQ/LeagueSharp.Loader-1 | Class/Profile.cs | C# | gpl-3.0 | 1,892 |
<div class="content">
<ul>
<?php foreach($enlaces as $key => $value): ?>
<li class="<?=$value->enlaceClase?>">
<? if($value->enlaceImagen != ''): ?>
<a href="<?=$value->enlaceLink?>">
<img src="<?=base_url()?>assets/public/images/enlaces/enlace_<?=$value->enlaceId?><?=$imageSize?>.<?=$value->enlaceImagen?>">
</a>
<? endif?>
<a href="<?=$value->enlaceLink?>"><?=$value->enlaceTexto?></a>
</li>
<?php endforeach;?>
</ul>
<a class="leer" href="<?=base_url($diminutivo.'/'.$paginaEnlacesUrl)?>"><?= lang('ui_view_all') ?></a>
<?=$pagination?>
</div>
| kaoz70/flexcms | themes/sectionalize/views/modulos/enlaces/default_view.php | PHP | gpl-3.0 | 584 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import common
class TestHrHolidaysBase(common.TransactionCase):
def setUp(self):
super(TestHrHolidaysBase, self).setUp()
Users = self.env['res.users'].with_context(no_reset_password=True)
# Find Employee group
group_employee_id = self.ref('base.group_user')
# Test users to use through the various tests
self.user_hruser_id = Users.create({
'name': 'Armande HrUser',
'login': 'Armande',
'alias_name': 'armande',
'email': 'armande.hruser@example.com',
'groups_id': [(6, 0, [group_employee_id, self.ref('base.group_hr_user')])]
}).id
self.user_hrmanager_id = Users.create({
'name': 'Bastien HrManager',
'login': 'bastien',
'alias_name': 'bastien',
'email': 'bastien.hrmanager@example.com',
'groups_id': [(6, 0, [group_employee_id, self.ref('base.group_hr_manager')])]
}).id
self.user_employee_id = Users.create({
'name': 'David Employee',
'login': 'david',
'alias_name': 'david',
'email': 'david.employee@example.com',
'groups_id': [(6, 0, [group_employee_id])]
}).id
# Hr Data
self.employee_emp_id = self.env['hr.employee'].create({
'name': 'David Employee',
'user_id': self.user_employee_id,
}).id
self.employee_hruser_id = self.env['hr.employee'].create({
'name': 'Armande HrUser',
'user_id': self.user_hruser_id,
}).id
| ayepezv/GAD_ERP | addons/hr_holidays/tests/common.py | Python | gpl-3.0 | 1,704 |
function gestionSelectElement(elementId,msgConfirm)
{field=document.getElementById(elementId);if(confirm(msgConfirm))
{selectedIndexASupprimer=field.options.selectedIndex;indice=new Array();texte=new Array();for(i=0;i<field.length;i++)
{indice[i]=field.options[i].value;texte[i]=field.options[i].text;}
field.innerHTML='';j=0;for(i=0;i<indice.length;i++)
{if(i!=selectedIndexASupprimer)
{field.options[j]=new Option(texte[i],indice[i]);j++;}}}
for(i=0;i<field.length;i++)
{field.options[i].selected=true;}} | rotagraziosi/archi-wiki-inpeople | includes/common.js | JavaScript | gpl-3.0 | 510 |
from pycbc.types import zeros, complex64, complex128
import numpy as _np
import ctypes
import pycbc.scheme as _scheme
from pycbc.libutils import get_ctypes_library
from .core import _BaseFFT, _BaseIFFT
from ..types import check_aligned
# IMPORTANT NOTE TO PYCBC DEVELOPERS:
# Because this module is loaded automatically when present, and because
# no FFTW function should be called until the user has had the chance
# to set the threading backend, it is ESSENTIAL that simply loading this
# module should not actually *call* ANY functions.
#FFTW constants, these are pulled from fftw3.h
FFTW_FORWARD = -1
FFTW_BACKWARD = 1
FFTW_MEASURE = 0
FFTW_DESTROY_INPUT = 1 << 0
FFTW_UNALIGNED = 1 << 1
FFTW_CONSERVE_MEMORY = 1 << 2
FFTW_EXHAUSTIVE = 1 << 3
FFTW_PRESERVE_INPUT = 1 << 4
FFTW_PATIENT = 1 << 5
FFTW_ESTIMATE = 1 << 6
FFTW_WISDOM_ONLY = 1 << 21
# Load the single and double precision libraries
# We need to construct them directly with CDLL so
# we can give the RTLD_GLOBAL mode, which we must do
# in order to use the threaded libraries as well.
double_lib = get_ctypes_library('fftw3',['fftw3'],mode=ctypes.RTLD_GLOBAL)
float_lib = get_ctypes_library('fftw3f',['fftw3f'],mode=ctypes.RTLD_GLOBAL)
if (double_lib is None) or (float_lib is None):
raise ImportError("Unable to find FFTW libraries")
# Support for FFTW's two different threading backends
_fftw_threaded_lib = None
_fftw_threaded_set = False
_double_threaded_lib = None
_float_threaded_lib = None
HAVE_FFTW_THREADED = False
# Although we set the number of threads based on the scheme,
# we need a private variable that records the last value used so
# we know whether we need to call plan_with_nthreads() again.
_fftw_current_nthreads = 0
# This function sets the number of threads used internally by FFTW
# in planning. It just takes a number of threads, rather than itself
# looking at scheme.mgr.num_threads, because it should not be called
# directly, but only by functions that get the value they use from
# scheme.mgr.num_threads
def _fftw_plan_with_nthreads(nthreads):
global _fftw_current_nthreads
if not HAVE_FFTW_THREADED:
if (nthreads > 1):
raise ValueError("Threading is NOT enabled, but {0} > 1 threads specified".format(nthreads))
else:
_pycbc_current_threads = nthreads
else:
dplanwthr = _double_threaded_lib.fftw_plan_with_nthreads
fplanwthr = _float_threaded_lib.fftwf_plan_with_nthreads
dplanwthr.restype = None
fplanwthr.restype = None
dplanwthr(nthreads)
fplanwthr(nthreads)
_fftw_current_nthreads = nthreads
# This is a global dict-of-dicts used when initializing threads and
# setting the threading library
_fftw_threading_libnames = { 'unthreaded' : {'double' : None, 'float' : None},
'openmp' : {'double' : 'fftw3_omp', 'float' : 'fftw3f_omp'},
'pthreads' : {'double' : 'fftw3_threads', 'float' : 'fftw3f_threads'}}
def _init_threads(backend):
# This function actually sets the backend and initializes. It returns zero on
# success and 1 if given a valid backend but that cannot be loaded. It raises
# an exception if called after the threading backend has already been set, or
# if given an invalid backend.
global _fftw_threaded_set
global _fftw_threaded_lib
global HAVE_FFTW_THREADED
global _double_threaded_lib
global _float_threaded_lib
if _fftw_threaded_set:
raise RuntimeError(
"Threading backend for FFTW already set to {0}; cannot be changed".format(_fftw_threaded_lib))
try:
double_threaded_libname = _fftw_threading_libnames[backend]['double']
float_threaded_libname = _fftw_threading_libnames[backend]['float']
except KeyError:
raise ValueError("Backend {0} for FFTW threading does not exist!".format(backend))
if double_threaded_libname is not None:
try:
# Note that the threaded libraries don't have their own pkg-config files;
# we must look for them wherever we look for double or single FFTW itself
_double_threaded_lib = get_ctypes_library(double_threaded_libname,['fftw3'],mode=ctypes.RTLD_GLOBAL)
_float_threaded_lib = get_ctypes_library(float_threaded_libname,['fftw3f'],mode=ctypes.RTLD_GLOBAL)
if (_double_threaded_lib is None) or (_float_threaded_lib is None):
raise RuntimeError("Unable to load threaded libraries {0} or {1}".format(double_threaded_libname,
float_threaded_libname))
dret = _double_threaded_lib.fftw_init_threads()
fret = _float_threaded_lib.fftwf_init_threads()
# FFTW for some reason uses *0* to indicate failure. In C.
if (dret == 0) or (fret == 0):
return 1
HAVE_FFTW_THREADED = True
_fftw_threaded_set = True
_fftw_threaded_lib = backend
return 0
except:
return 1
else:
# We get here when we were given the 'unthreaded' backend
HAVE_FFTW_THREADED = False
_fftw_threaded_set = True
_fftw_threaded_lib = backend
return 0
def set_threads_backend(backend=None):
# This is the user facing function. If given a backend it just
# calls _init_threads and lets it do the work. If not (the default)
# then it cycles in order through threaded backends,
if backend is not None:
retval = _init_threads(backend)
# Since the user specified this backend raise an exception if the above failed
if retval != 0:
raise RuntimeError("Could not initialize FFTW threading backend {0}".format(backend))
else:
# Note that we pop() from the end, so 'openmp' is the first thing tried
_backend_list = ['unthreaded','pthreads','openmp']
while not _fftw_threaded_set:
_next_backend = _backend_list.pop()
retval = _init_threads(_next_backend)
# Function to import system-wide wisdom files.
def import_sys_wisdom():
if not _fftw_threaded_set:
set_threads_backend()
double_lib.fftw_import_system_wisdom()
float_lib.fftwf_import_system_wisdom()
# We provide an interface for changing the "measure level"
# By default this is 0, which does no planning,
# but we provide functions to read and set it
_default_measurelvl = 0
def get_measure_level():
"""
Get the current 'measure level' used in deciding how much effort to put into
creating FFTW plans. From least effort (and shortest planning time) to most
they are 0 to 3. No arguments.
"""
return _default_measurelvl
def set_measure_level(mlvl):
"""
Set the current 'measure level' used in deciding how much effort to expend
creating FFTW plans. Must be an integer from 0 (least effort, shortest time)
to 3 (most effort and time).
"""
global _default_measurelvl
if mlvl not in (0,1,2,3):
raise ValueError("Measure level can only be one of 0, 1, 2, or 3")
_default_measurelvl = mlvl
_flag_dict = {0: FFTW_ESTIMATE,
1: FFTW_MEASURE,
2: FFTW_MEASURE|FFTW_PATIENT,
3: FFTW_MEASURE|FFTW_PATIENT|FFTW_EXHAUSTIVE}
def get_flag(mlvl,aligned):
if aligned:
return _flag_dict[mlvl]
else:
return (_flag_dict[mlvl]|FFTW_UNALIGNED)
# Add the ability to read/store wisdom to filenames
def wisdom_io(filename, precision, action):
"""Import or export an FFTW plan for single or double precision.
"""
if not _fftw_threaded_set:
set_threads_backend()
fmap = {('float', 'import'): float_lib.fftwf_import_wisdom_from_filename,
('float', 'export'): float_lib.fftwf_export_wisdom_to_filename,
('double', 'import'): double_lib.fftw_import_wisdom_from_filename,
('double', 'export'): double_lib.fftw_export_wisdom_to_filename}
f = fmap[(precision, action)]
f.argtypes = [ctypes.c_char_p]
retval = f(filename.encode())
if retval == 0:
raise RuntimeError(('Could not {0} wisdom '
'from file {1}').format(action, filename))
def import_single_wisdom_from_filename(filename):
wisdom_io(filename, 'float', 'import')
def import_double_wisdom_from_filename(filename):
wisdom_io(filename, 'double', 'import')
def export_single_wisdom_to_filename(filename):
wisdom_io(filename, 'float', 'export')
def export_double_wisdom_to_filename(filename):
wisdom_io(filename, 'double', 'export')
def set_planning_limit(time):
if not _fftw_threaded_set:
set_threads_backend()
f = double_lib.fftw_set_timelimit
f.argtypes = [ctypes.c_double]
f(time)
f = float_lib.fftwf_set_timelimit
f.argtypes = [ctypes.c_double]
f(time)
# Create function maps for the dtypes
plan_function = {'float32': {'complex64': float_lib.fftwf_plan_dft_r2c_1d},
'float64': {'complex128': double_lib.fftw_plan_dft_r2c_1d},
'complex64': {'float32': float_lib.fftwf_plan_dft_c2r_1d,
'complex64': float_lib.fftwf_plan_dft_1d},
'complex128': {'float64': double_lib.fftw_plan_dft_c2r_1d,
'complex128': double_lib.fftw_plan_dft_1d}
}
execute_function = {'float32': {'complex64': float_lib.fftwf_execute_dft_r2c},
'float64': {'complex128': double_lib.fftw_execute_dft_r2c},
'complex64': {'float32': float_lib.fftwf_execute_dft_c2r,
'complex64': float_lib.fftwf_execute_dft},
'complex128': {'float64': double_lib.fftw_execute_dft_c2r,
'complex128': double_lib.fftw_execute_dft}
}
def plan(size, idtype, odtype, direction, mlvl, aligned, nthreads, inplace):
if not _fftw_threaded_set:
set_threads_backend()
if nthreads != _fftw_current_nthreads:
_fftw_plan_with_nthreads(nthreads)
# Convert a measure-level to flags
flags = get_flag(mlvl,aligned)
# We make our arrays of the necessary type and size. Things can be
# tricky, especially for in-place transforms with one of input or
# output real.
if (idtype == odtype):
# We're in the complex-to-complex case, so lengths are the same
ip = zeros(size, dtype=idtype)
if inplace:
op = ip
else:
op = zeros(size, dtype=odtype)
elif (idtype.kind == 'c') and (odtype.kind == 'f'):
# Complex-to-real (reverse), so size is length of real array.
# However the complex array may be larger (in bytes) and
# should therefore be allocated first and reused for an in-place
# transform
ip = zeros(size/2+1, dtype=idtype)
if inplace:
op = ip.view(dtype=odtype)[0:size]
else:
op = zeros(size, dtype=odtype)
else:
# Real-to-complex (forward), and size is still that of real.
# However it is still true that the complex array may be larger
# (in bytes) and should therefore be allocated first and reused
# for an in-place transform
op = zeros(size/2+1, dtype=odtype)
if inplace:
ip = op.view(dtype=idtype)[0:size]
else:
ip = zeros(size, dtype=idtype)
# Get the plan function
idtype = _np.dtype(idtype)
odtype = _np.dtype(odtype)
f = plan_function[str(idtype)][str(odtype)]
f.restype = ctypes.c_void_p
# handle the C2C cases (forward and reverse)
if idtype.kind == odtype.kind:
f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_int, ctypes.c_int]
theplan = f(size, ip.ptr, op.ptr, direction, flags)
# handle the R2C and C2R case
else:
f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_int]
theplan = f(size, ip.ptr, op.ptr, flags)
# We don't need ip or op anymore
del ip, op
# Make the destructors
if idtype.char in ['f', 'F']:
destroy = float_lib.fftwf_destroy_plan
else:
destroy = double_lib.fftw_destroy_plan
destroy.argtypes = [ctypes.c_void_p]
return theplan, destroy
# Note that we don't need to check whether we've set the threading backend
# in the following functions, since execute is not called directly and
# the fft and ifft will call plan first.
def execute(plan, invec, outvec):
f = execute_function[str(invec.dtype)][str(outvec.dtype)]
f.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
f(plan, invec.ptr, outvec.ptr)
def fft(invec, outvec, prec, itype, otype):
theplan, destroy = plan(len(invec), invec.dtype, outvec.dtype, FFTW_FORWARD,
get_measure_level(),(check_aligned(invec.data) and check_aligned(outvec.data)),
_scheme.mgr.state.num_threads, (invec.ptr == outvec.ptr))
execute(theplan, invec, outvec)
destroy(theplan)
def ifft(invec, outvec, prec, itype, otype):
theplan, destroy = plan(len(outvec), invec.dtype, outvec.dtype, FFTW_BACKWARD,
get_measure_level(),(check_aligned(invec.data) and check_aligned(outvec.data)),
_scheme.mgr.state.num_threads, (invec.ptr == outvec.ptr))
execute(theplan, invec, outvec)
destroy(theplan)
# Class based API
# First, set up a lot of different ctypes functions:
plan_many_c2c_f = float_lib.fftwf_plan_many_dft
plan_many_c2c_f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_uint]
plan_many_c2c_f.restype = ctypes.c_void_p
plan_many_c2c_d = double_lib.fftw_plan_many_dft
plan_many_c2c_d.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_uint]
plan_many_c2c_d.restype = ctypes.c_void_p
plan_many_c2r_f = float_lib.fftwf_plan_many_dft_c2r
plan_many_c2r_f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_uint]
plan_many_c2r_f.restype = ctypes.c_void_p
plan_many_c2r_d = double_lib.fftw_plan_many_dft_c2r
plan_many_c2r_d.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_uint]
plan_many_c2r_d.restype = ctypes.c_void_p
plan_many_r2c_f = float_lib.fftwf_plan_many_dft_r2c
plan_many_r2c_f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_uint]
plan_many_r2c_f.restype = ctypes.c_void_p
plan_many_r2c_d = double_lib.fftw_plan_many_dft_r2c
plan_many_r2c_d.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_uint]
plan_many_r2c_d.restype = ctypes.c_void_p
# Now set up a dictionary indexed by (str(input_dtype), str(output_dtype)) to
# translate input and output dtypes into the correct planning function.
_plan_funcs_dict = { ('complex64', 'complex64') : plan_many_c2c_f,
('complex64', 'float32') : plan_many_r2c_f,
('float32', 'complex64') : plan_many_c2r_f,
('complex128', 'complex128') : plan_many_c2c_d,
('complex128', 'float64') : plan_many_r2c_d,
('float64', 'complex128') : plan_many_c2r_d }
# To avoid multiple-inheritance, we set up a function that returns much
# of the initialization that will need to be handled in __init__ of both
# classes.
def _fftw_setup(fftobj):
n = _np.asarray([fftobj.size], dtype=_np.int32)
inembed = _np.asarray([len(fftobj.invec)], dtype=_np.int32)
onembed = _np.asarray([len(fftobj.outvec)], dtype=_np.int32)
nthreads = _scheme.mgr.state.num_threads
if not _fftw_threaded_set:
set_threads_backend()
if nthreads != _fftw_current_nthreads:
_fftw_plan_with_nthreads(nthreads)
mlvl = get_measure_level()
aligned = check_aligned(fftobj.invec.data) and check_aligned(fftobj.outvec.data)
flags = get_flag(mlvl, aligned)
plan_func = _plan_funcs_dict[ (str(fftobj.invec.dtype), str(fftobj.outvec.dtype)) ]
tmpin = zeros(len(fftobj.invec), dtype = fftobj.invec.dtype)
tmpout = zeros(len(fftobj.outvec), dtype = fftobj.outvec.dtype)
# C2C, forward
if fftobj.forward and (fftobj.outvec.dtype in [complex64, complex128]):
plan = plan_func(1, n.ctypes.data, fftobj.nbatch,
tmpin.ptr, inembed.ctypes.data, 1, fftobj.idist,
tmpout.ptr, onembed.ctypes.data, 1, fftobj.odist,
FFTW_FORWARD, flags)
# C2C, backward
elif not fftobj.forward and (fftobj.invec.dtype in [complex64, complex128]):
plan = plan_func(1, n.ctypes.data, fftobj.nbatch,
tmpin.ptr, inembed.ctypes.data, 1, fftobj.idist,
tmpout.ptr, onembed.ctypes.data, 1, fftobj.odist,
FFTW_BACKWARD, flags)
# R2C or C2R (hence no direction argument for plan creation)
else:
plan = plan_func(1, n.ctypes.data, fftobj.nbatch,
tmpin.ptr, inembed.ctypes.data, 1, fftobj.idist,
tmpout.ptr, onembed.ctypes.data, 1, fftobj.odist,
flags)
del tmpin
del tmpout
return plan
class FFT(_BaseFFT):
def __init__(self, invec, outvec, nbatch=1, size=None):
super(FFT, self).__init__(invec, outvec, nbatch, size)
self.iptr = self.invec.ptr
self.optr = self.outvec.ptr
self._efunc = execute_function[str(self.invec.dtype)][str(self.outvec.dtype)]
self._efunc.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
self.plan = _fftw_setup(self)
def execute(self):
self._efunc(self.plan, self.iptr, self.optr)
class IFFT(_BaseIFFT):
def __init__(self, invec, outvec, nbatch=1, size=None):
super(IFFT, self).__init__(invec, outvec, nbatch, size)
self.iptr = self.invec.ptr
self.optr = self.outvec.ptr
self._efunc = execute_function[str(self.invec.dtype)][str(self.outvec.dtype)]
self._efunc.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
self.plan = _fftw_setup(self)
def execute(self):
self._efunc(self.plan, self.iptr, self.optr)
def insert_fft_options(optgroup):
"""
Inserts the options that affect the behavior of this backend
Parameters
----------
optgroup: fft_option
OptionParser argument group whose options are extended
"""
optgroup.add_argument("--fftw-measure-level",
help="Determines the measure level used in planning "
"FFTW FFTs; allowed values are: " + str([0,1,2,3]),
type=int, default=_default_measurelvl)
optgroup.add_argument("--fftw-threads-backend",
help="Give 'openmp', 'pthreads' or 'unthreaded' to specify which threaded FFTW to use",
default=None)
optgroup.add_argument("--fftw-input-float-wisdom-file",
help="Filename from which to read single-precision wisdom",
default=None)
optgroup.add_argument("--fftw-input-double-wisdom-file",
help="Filename from which to read double-precision wisdom",
default=None)
optgroup.add_argument("--fftw-output-float-wisdom-file",
help="Filename to which to write single-precision wisdom",
default=None)
optgroup.add_argument("--fftw-output-double-wisdom-file",
help="Filename to which to write double-precision wisdom",
default=None)
optgroup.add_argument("--fftw-import-system-wisdom",
help = "If given, call fftw[f]_import_system_wisdom()",
action = "store_true")
def verify_fft_options(opt,parser):
"""Parses the FFT options and verifies that they are
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes.
parser : object
OptionParser instance.
"""
if opt.fftw_measure_level not in [0,1,2,3]:
parser.error("{0} is not a valid FFTW measure level.".format(opt.fftw_measure_level))
if opt.fftw_import_system_wisdom and ((opt.fftw_input_float_wisdom_file is not None)
or (opt.fftw_input_double_wisdom_file is not None)):
parser.error("If --fftw-import-system-wisdom is given, then you cannot give"
" either of --fftw-input-float-wisdom-file or --fftw-input-double-wisdom-file")
if opt.fftw_threads_backend is not None:
if opt.fftw_threads_backend not in ['openmp','pthreads','unthreaded']:
parser.error("Invalid threads backend; must be 'openmp', 'pthreads' or 'unthreaded'")
def from_cli(opt):
# Since opt.fftw_threads_backend defaults to None, the following is always
# appropriate:
set_threads_backend(opt.fftw_threads_backend)
# Set the user-provided measure level
set_measure_level(opt.fftw_measure_level)
| ligo-cbc/pycbc | pycbc/fft/fftw.py | Python | gpl-3.0 | 22,427 |
package org.smssecure.smssecure.preferences;
import android.content.Context;
import android.os.Bundle;
import android.preference.ListPreference;
import org.smssecure.smssecure.ApplicationPreferencesActivity;
import org.smssecure.smssecure.R;
import org.smssecure.smssecure.util.SMSSecurePreferences;
import java.util.Arrays;
public class AppearancePreferenceFragment extends ListSummaryPreferenceFragment {
@Override
public void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
addPreferencesFromResource(R.xml.preferences_appearance);
this.findPreference(SMSSecurePreferences.THEME_PREF).setOnPreferenceChangeListener(new ListSummaryListener());
this.findPreference(SMSSecurePreferences.LANGUAGE_PREF).setOnPreferenceChangeListener(new ListSummaryListener());
initializeListSummary((ListPreference)findPreference(SMSSecurePreferences.THEME_PREF));
initializeListSummary((ListPreference)findPreference(SMSSecurePreferences.LANGUAGE_PREF));
}
@Override
public void onStart() {
super.onStart();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener((ApplicationPreferencesActivity)getActivity());
}
@Override
public void onResume() {
super.onResume();
((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.preferences__appearance);
}
@Override
public void onStop() {
super.onStop();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener((ApplicationPreferencesActivity) getActivity());
}
public static CharSequence getSummary(Context context) {
String[] languageEntries = context.getResources().getStringArray(R.array.language_entries);
String[] languageEntryValues = context.getResources().getStringArray(R.array.language_values);
String[] themeEntries = context.getResources().getStringArray(R.array.pref_theme_entries);
String[] themeEntryValues = context.getResources().getStringArray(R.array.pref_theme_values);
int langIndex = Arrays.asList(languageEntryValues).indexOf(SMSSecurePreferences.getLanguage(context));
int themeIndex = Arrays.asList(themeEntryValues).indexOf(SMSSecurePreferences.getTheme(context));
if (langIndex == -1) langIndex = 0;
if (themeIndex == -1) themeIndex = 0;
return context.getString(R.string.ApplicationPreferencesActivity_appearance_summary,
themeEntries[themeIndex],
languageEntries[langIndex]);
}
}
| rutaihwa/SMSSecure | src/org/smssecure/smssecure/preferences/AppearancePreferenceFragment.java | Java | gpl-3.0 | 2,545 |
<?php
/**
* Class QRDataAbstract
*
* @filesource QRDataAbstract.php
* @created 25.11.2015
* @package chillerlan\QRCode\Data
* @author Smiley <smiley@chillerlan.net>
* @copyright 2015 Smiley
* @license MIT
*/
namespace chillerlan\QRCode\Data;
use chillerlan\QRCode\{QRCode, QRCodeException};
use chillerlan\QRCode\Helpers\{BitBuffer, Polynomial};
use chillerlan\Settings\SettingsContainerInterface;
use function array_fill, array_merge, count, max, mb_convert_encoding, mb_detect_encoding, range, sprintf, strlen;
/**
* Processes the binary data and maps it on a matrix which is then being returned
*/
abstract class QRDataAbstract implements QRDataInterface{
/**
* the string byte count
*
* @var int
*/
protected $strlen;
/**
* the current data mode: Num, Alphanum, Kanji, Byte
*
* @var int
*/
protected $datamode;
/**
* mode length bits for the version breakpoints 1-9, 10-26 and 27-40
*
* @var array
*/
protected $lengthBits = [0, 0, 0];
/**
* current QR Code version
*
* @var int
*/
protected $version;
/**
* the raw data that's being passed to QRMatrix::mapData()
*
* @var array
*/
protected $matrixdata;
/**
* ECC temp data
*
* @var array
*/
protected $ecdata;
/**
* ECC temp data
*
* @var array
*/
protected $dcdata;
/**
* @var \chillerlan\QRCode\QROptions
*/
protected $options;
/**
* @var \chillerlan\QRCode\Helpers\BitBuffer
*/
protected $bitBuffer;
/**
* QRDataInterface constructor.
*
* @param \chillerlan\Settings\SettingsContainerInterface $options
* @param string|null $data
*/
public function __construct(SettingsContainerInterface $options, string $data = null){
$this->options = $options;
if($data !== null){
$this->setData($data);
}
}
/**
* @inheritDoc
*/
public function setData(string $data):QRDataInterface{
if($this->datamode === QRCode::DATA_KANJI){
$data = mb_convert_encoding($data, 'SJIS', mb_detect_encoding($data));
}
$this->strlen = $this->getLength($data);
$this->version = $this->options->version === QRCode::VERSION_AUTO
? $this->getMinimumVersion()
: $this->options->version;
$this->matrixdata = $this
->writeBitBuffer($data)
->maskECC()
;
return $this;
}
/**
* @inheritDoc
*/
public function initMatrix(int $maskPattern, bool $test = null):QRMatrix{
return (new QRMatrix($this->version, $this->options->eccLevel))
->setFinderPattern()
->setSeparators()
->setAlignmentPattern()
->setTimingPattern()
->setVersionNumber($test)
->setFormatInfo($maskPattern, $test)
->setDarkModule()
->mapData($this->matrixdata, $maskPattern)
;
}
/**
* returns the length bits for the version breakpoints 1-9, 10-26 and 27-40
*
* @return int
* @throws \chillerlan\QRCode\Data\QRCodeDataException
* @codeCoverageIgnore
*/
protected function getLengthBits():int{
foreach([9, 26, 40] as $key => $breakpoint){
if($this->version <= $breakpoint){
return $this->lengthBits[$key];
}
}
throw new QRCodeDataException(sprintf('invalid version number: %d', $this->version));
}
/**
* returns the byte count of the $data string
*
* @param string $data
*
* @return int
*/
protected function getLength(string $data):int{
return strlen($data);
}
/**
* returns the minimum version number for the given string
*
* @return int
* @throws \chillerlan\QRCode\Data\QRCodeDataException
*/
protected function getMinimumVersion():int{
$maxlength = 0;
// guess the version number within the given range
foreach(range($this->options->versionMin, $this->options->versionMax) as $version){
$maxlength = $this::MAX_LENGTH[$version][QRCode::DATA_MODES[$this->datamode]][QRCode::ECC_MODES[$this->options->eccLevel]];
if($this->strlen <= $maxlength){
return $version;
}
}
throw new QRCodeDataException(sprintf('data exceeds %d characters', $maxlength));
}
/**
* writes the actual data string to the BitBuffer
*
* @see \chillerlan\QRCode\Data\QRDataAbstract::writeBitBuffer()
*
* @param string $data
*
* @return void
*/
abstract protected function write(string $data):void;
/**
* creates a BitBuffer and writes the string data to it
*
* @param string $data
*
* @return \chillerlan\QRCode\Data\QRDataAbstract
* @throws \chillerlan\QRCode\QRCodeException
*/
protected function writeBitBuffer(string $data):QRDataInterface{
$this->bitBuffer = new BitBuffer;
$MAX_BITS = $this::MAX_BITS[$this->version][QRCode::ECC_MODES[$this->options->eccLevel]];
$this->bitBuffer
->clear()
->put($this->datamode, 4)
->put($this->strlen, $this->getLengthBits())
;
$this->write($data);
// there was an error writing the BitBuffer data, which is... unlikely.
if($this->bitBuffer->length > $MAX_BITS){
throw new QRCodeException(sprintf('code length overflow. (%d > %d bit)', $this->bitBuffer->length, $MAX_BITS)); // @codeCoverageIgnore
}
// end code.
if($this->bitBuffer->length + 4 <= $MAX_BITS){
$this->bitBuffer->put(0, 4);
}
// padding
while($this->bitBuffer->length % 8 !== 0){
$this->bitBuffer->putBit(false);
}
// padding
while(true){
if($this->bitBuffer->length >= $MAX_BITS){
break;
}
$this->bitBuffer->put(0xEC, 8);
if($this->bitBuffer->length >= $MAX_BITS){
break;
}
$this->bitBuffer->put(0x11, 8);
}
return $this;
}
/**
* ECC masking
*
* @link http://www.thonky.com/qr-code-tutorial/error-correction-coding
*
* @return array
*/
protected function maskECC():array{
[$l1, $l2, $b1, $b2] = $this::RSBLOCKS[$this->version][QRCode::ECC_MODES[$this->options->eccLevel]];
$rsBlocks = array_fill(0, $l1, [$b1, $b2]);
$rsCount = $l1 + $l2;
$this->ecdata = array_fill(0, $rsCount, null);
$this->dcdata = $this->ecdata;
if($l2 > 0){
$rsBlocks = array_merge($rsBlocks, array_fill(0, $l2, [$b1 + 1, $b2 + 1]));
}
$totalCodeCount = 0;
$maxDcCount = 0;
$maxEcCount = 0;
$offset = 0;
foreach($rsBlocks as $key => $block){
[$rsBlockTotal, $dcCount] = $block;
$ecCount = $rsBlockTotal - $dcCount;
$maxDcCount = max($maxDcCount, $dcCount);
$maxEcCount = max($maxEcCount, $ecCount);
$this->dcdata[$key] = array_fill(0, $dcCount, null);
foreach($this->dcdata[$key] as $a => $_z){
$this->dcdata[$key][$a] = 0xff & $this->bitBuffer->buffer[$a + $offset];
}
[$num, $add] = $this->poly($key, $ecCount);
foreach($this->ecdata[$key] as $c => $_z){
$modIndex = $c + $add;
$this->ecdata[$key][$c] = $modIndex >= 0 ? $num[$modIndex] : 0;
}
$offset += $dcCount;
$totalCodeCount += $rsBlockTotal;
}
$data = array_fill(0, $totalCodeCount, null);
$index = 0;
$mask = function($arr, $count) use (&$data, &$index, $rsCount){
for($x = 0; $x < $count; $x++){
for($y = 0; $y < $rsCount; $y++){
if($x < count($arr[$y])){
$data[$index] = $arr[$y][$x];
$index++;
}
}
}
};
$mask($this->dcdata, $maxDcCount);
$mask($this->ecdata, $maxEcCount);
return $data;
}
/**
* @param int $key
* @param int $count
*
* @return int[]
*/
protected function poly(int $key, int $count):array{
$rsPoly = new Polynomial;
$modPoly = new Polynomial;
for($i = 0; $i < $count; $i++){
$modPoly->setNum([1, $modPoly->gexp($i)]);
$rsPoly->multiply($modPoly->getNum());
}
$rsPolyCount = count($rsPoly->getNum());
$modPoly
->setNum($this->dcdata[$key], $rsPolyCount - 1)
->mod($rsPoly->getNum())
;
$this->ecdata[$key] = array_fill(0, $rsPolyCount - 1, null);
$num = $modPoly->getNum();
return [
$num,
count($num) - count($this->ecdata[$key]),
];
}
}
| andre-hub/Tiny-Tiny-RSS | vendor/chillerlan/php-qrcode/src/Data/QRDataAbstract.php | PHP | gpl-3.0 | 7,849 |
/* -*- mode: c++; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
* vim: ts=4 sw=4 noet ai cindent syntax=cpp
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2012 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "conky.h"
#include "core.h"
#include "logging.h"
#include "specials.h"
#include "text_object.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cmath>
#include <mutex>
#include "update-cb.hh"
namespace {
class exec_cb: public conky::callback<std::string, std::string> {
typedef conky::callback<std::string, std::string> Base;
protected:
virtual void work();
public:
exec_cb(uint32_t period, bool wait, const std::string &cmd)
: Base(period, wait, Base::Tuple(cmd))
{}
};
}
struct execi_data {
float interval;
char *cmd;
execi_data() : interval(0), cmd(0) {}
};
//our own implementation of popen, the difference : the value of 'childpid' will be filled with
//the pid of the running 'command'. This is useful if want to kill it when it hangs while reading
//or writing to it. We have to kill it because pclose will wait until the process dies by itself
static FILE* pid_popen(const char *command, const char *mode, pid_t *child) {
int ends[2];
int parentend, childend;
//by running pipe after the strcmp's we make sure that we don't have to create a pipe
//and close the ends if mode is something illegal
if(strcmp(mode, "r") == 0) {
if(pipe(ends) != 0) {
return NULL;
}
parentend = ends[0];
childend = ends[1];
} else if(strcmp(mode, "w") == 0) {
if(pipe(ends) != 0) {
return NULL;
}
parentend = ends[1];
childend = ends[0];
} else {
return NULL;
}
*child = fork();
if(*child == -1) {
close(parentend);
close(childend);
return NULL;
} else if(*child > 0) {
close(childend);
waitpid(*child, NULL, 0);
} else {
//don't read from both stdin and pipe or write to both stdout and pipe
if(childend == ends[0]) {
close(0);
} else {
close(1);
}
close(parentend);
//by dupping childend, the returned fd will have close-on-exec turned off
if (dup(childend) == -1)
perror("dup()");
close(childend);
execl("/bin/sh", "sh", "-c", command, (char *) NULL);
_exit(EXIT_FAILURE); //child should die here, (normally execl will take care of this but it can fail)
}
return fdopen(parentend, mode);
}
void exec_cb::work()
{
pid_t childpid;
std::string buf;
std::shared_ptr<FILE> fp;
char b[0x1000];
if(FILE *t = pid_popen(std::get<0>(tuple).c_str(), "r", &childpid))
fp.reset(t, fclose);
else
return;
while(!feof(fp.get()) && !ferror(fp.get())) {
int length = fread(b, 1, sizeof b, fp.get());
buf.append(b, length);
}
if(*buf.rbegin() == '\n')
buf.resize(buf.size()-1);
std::lock_guard<std::mutex> l(result_mutex);
result = buf;
}
//remove backspaced chars, example: "dog^H^H^Hcat" becomes "cat"
//string has to end with \0 and it's length should fit in a int
#define BACKSPACE 8
static void remove_deleted_chars(char *string){
int i = 0;
while(string[i] != 0){
if(string[i] == BACKSPACE){
if(i != 0){
strcpy( &(string[i-1]), &(string[i+1]) );
i--;
}else strcpy( &(string[i]), &(string[i+1]) ); //necessary for ^H's at the start of a string
}else i++;
}
}
static inline double get_barnum(const char *buf)
{
double barnum;
if (sscanf(buf, "%lf", &barnum) != 1) {
NORM_ERR("reading exec value failed (perhaps it's not the "
"correct format?)");
return 0.0;
}
if (barnum > 100.0 || barnum < 0.0) {
NORM_ERR("your exec value is not between 0 and 100, "
"therefore it will be ignored");
return 0.0;
}
return barnum;
}
void scan_exec_arg(struct text_object *obj, const char *arg)
{
/* XXX: do real bar parsing here */
scan_bar(obj, "", 100);
obj->data.s = strndup(arg ? arg : "", text_buffer_size.get(*state));
}
void scan_execi_arg(struct text_object *obj, const char *arg)
{
struct execi_data *ed;
int n;
ed = new execi_data;
if (sscanf(arg, "%f %n", &ed->interval, &n) <= 0) {
NORM_ERR("${execi* <interval> command}");
delete ed;
return;
}
ed->cmd = strndup(arg + n, text_buffer_size.get(*state));
obj->data.opaque = ed;
}
void scan_execi_bar_arg(struct text_object *obj, const char *arg)
{
/* XXX: do real bar parsing here */
scan_bar(obj, "", 100);
scan_execi_arg(obj, arg);
}
#ifdef BUILD_X11
void scan_execi_gauge_arg(struct text_object *obj, const char *arg)
{
/* XXX: do real gauge parsing here */
scan_gauge(obj, "", 100);
scan_execi_arg(obj, arg);
}
void scan_execgraph_arg(struct text_object *obj, const char *arg)
{
struct execi_data *ed;
char *buf;
ed = new execi_data;
memset(ed, 0, sizeof(struct execi_data));
buf = scan_graph(obj, arg, 100);
if (!buf) {
NORM_ERR("missing command argument to execgraph object");
return;
}
ed->cmd = buf;
obj->data.opaque = ed;
}
#endif /* BUILD_X11 */
void fill_p(const char *buffer, struct text_object *obj, char *p, int p_max_size) {
if(obj->parse == true) {
evaluate(buffer, p, p_max_size);
} else snprintf(p, p_max_size, "%s", buffer);
remove_deleted_chars(p);
}
void print_exec(struct text_object *obj, char *p, int p_max_size)
{
auto cb = conky::register_cb<exec_cb>(1, true, obj->data.s);
fill_p(cb->get_result_copy().c_str(), obj, p, p_max_size);
}
void print_execi(struct text_object *obj, char *p, int p_max_size)
{
struct execi_data *ed = (struct execi_data *)obj->data.opaque;
if (!ed)
return;
uint32_t period = std::max(lround(ed->interval/active_update_interval()), 1l);
auto cb = conky::register_cb<exec_cb>(period, !obj->thread, ed->cmd);
fill_p(cb->get_result_copy().c_str(), obj, p, p_max_size);
}
double execbarval(struct text_object *obj)
{
auto cb = conky::register_cb<exec_cb>(1, true, obj->data.s);
return get_barnum(cb->get_result_copy().c_str());
}
double execi_barval(struct text_object *obj)
{
struct execi_data *ed = (struct execi_data *)obj->data.opaque;
if (!ed)
return 0;
uint32_t period = std::max(lround(ed->interval/active_update_interval()), 1l);
auto cb = conky::register_cb<exec_cb>(period, !obj->thread, ed->cmd);
return get_barnum(cb->get_result_copy().c_str());
}
void free_exec(struct text_object *obj)
{
free_and_zero(obj->data.s);
}
void free_execi(struct text_object *obj)
{
struct execi_data *ed = (struct execi_data *)obj->data.opaque;
if (!ed)
return;
free_and_zero(ed->cmd);
delete ed;
obj->data.opaque = NULL;
}
| randy1/conky | src/exec.cc | C++ | gpl-3.0 | 7,376 |
# KicadModTree 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.
#
# KicadModTree 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 kicad-footprint-generator. If not, see < http://www.gnu.org/licenses/ >.
#
# (C) 2016 by Thomas Pointhuber, <thomas.pointhuber@gmx.at>
from copy import copy, deepcopy
from KicadModTree.Vector import *
class MultipleParentsError(RuntimeError):
def __init__(self, message):
# Call the base class constructor with the parameters it needs
super(MultipleParentsError, self).__init__(message)
class RecursionDetectedError(RuntimeError):
def __init__(self, message):
# Call the base class constructor with the parameters it needs
super(RecursionDetectedError, self).__init__(message)
class Node(object):
def __init__(self):
self._parent = None
self._childs = []
def append(self, node):
'''
add node to child
'''
if not isinstance(node, Node):
raise TypeError('invalid object, has to be based on Node')
if node._parent:
raise MultipleParentsError('muliple parents are not allowed!')
self._childs.append(node)
node._parent = self
def extend(self, nodes):
'''
add list of nodes to child
'''
new_nodes = []
for node in nodes:
if not isinstance(node, Node):
raise TypeError('invalid object, has to be based on Node')
if node._parent or node in new_nodes:
raise MultipleParentsError('muliple parents are not allowed!')
new_nodes.append(node)
# when all went smooth by now, we can set the parent nodes to ourself
for node in new_nodes:
node._parent = self
self._childs.extend(new_nodes)
def remove(self, node):
'''
remove child from node
'''
if not isinstance(node, Node):
raise TypeError('invalid object, has to be based on Node')
while node in self._childs:
self._childs.remove(node)
node._parent = None
def insert(self, node):
'''
moving all childs into the node, and using the node as new parent of those childs
'''
if not isinstance(node, Node):
raise TypeError('invalid object, has to be based on Node')
for child in copy(self._childs):
self.remove(child)
node.append(child)
self.append(node)
def copy(self):
copy = deepcopy(self)
copy._parent = None
return copy
def serialize(self):
nodes = [self]
for child in self.getAllChilds():
nodes += child.serialize()
return nodes
def getNormalChilds(self):
'''
Get all normal childs of this node
'''
return self._childs
def getVirtualChilds(self):
'''
Get virtual childs of this node
'''
return []
def getAllChilds(self):
'''
Get virtual and normal childs of this node
'''
return self.getNormalChilds() + self.getVirtualChilds()
def getParent(self):
'''
get Parent Node of this Node
'''
return self._parent
def getRootNode(self):
'''
get Root Node of this Node
'''
# TODO: recursion detection
if not self.getParent():
return self
return self.getParent().getRootNode()
def getRealPosition(self, coordinate, rotation=None):
'''
return position of point after applying all transformation and rotation operations
'''
if not self._parent:
if rotation is None:
# TODO: most of the points are 2D Nodes
return Vector3D(coordinate)
else:
return Vector3D(coordinate), rotation
return self._parent.getRealPosition(coordinate, rotation)
def calculateBoundingBox(self, outline=None):
min_x, min_y = 0, 0
max_x, max_y = 0, 0
if outline:
min_x = outline['min']['x']
min_y = outline['min']['y']
max_x = outline['max']['x']
max_y = outline['max']['y']
for child in self.getAllChilds():
child_outline = child.calculateBoundingBox()
min_x = min([min_x, child_outline['min']['x']])
min_y = min([min_y, child_outline['min']['y']])
max_x = max([max_x, child_outline['max']['x']])
max_y = max([max_y, child_outline['max']['y']])
return {'min': Vector2D(min_x, min_y), 'max': Vector2D(max_x, max_y)}
def _getRenderTreeText(self):
'''
Text which is displayed when generating a render tree
'''
return type(self).__name__
def _getRenderTreeSymbol(self):
'''
Symbol which is displayed when generating a render tree
'''
if self._parent is None:
return "+"
return "*"
def getRenderTree(self, rendered_nodes=None):
'''
print render tree
'''
if rendered_nodes is None:
rendered_nodes = set()
if self in rendered_nodes:
raise RecursionDetectedError('recursive definition of render tree!')
rendered_nodes.add(self)
tree_str = "{0} {1}".format(self._getRenderTreeSymbol(), self._getRenderTreeText())
for child in self.getNormalChilds():
tree_str += '\n '
tree_str += ' '.join(child.getRenderTree(rendered_nodes).splitlines(True))
return tree_str
def getCompleteRenderTree(self, rendered_nodes=None):
'''
print virtual render tree
'''
if rendered_nodes is None:
rendered_nodes = set()
if self in rendered_nodes:
raise RecursionDetectedError('recursive definition of render tree!')
rendered_nodes.add(self)
tree_str = "{0} {1}".format(self._getRenderTreeSymbol(), self._getRenderTreeText())
for child in self.getAllChilds():
tree_str += '\n '
tree_str += ' '.join(child.getCompleteRenderTree(rendered_nodes).splitlines(True))
return tree_str
| pointhi/kicad-footprint-generator | KicadModTree/nodes/Node.py | Python | gpl-3.0 | 6,713 |
package net.osmand.plus.resources;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.text.Collator;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import net.osmand.AndroidUtils;
import net.osmand.GeoidAltitudeCorrection;
import net.osmand.IProgress;
import net.osmand.IndexConstants;
import net.osmand.Location;
import net.osmand.PlatformUtil;
import net.osmand.ResultMatcher;
import net.osmand.binary.BinaryMapIndexReader;
import net.osmand.binary.BinaryMapIndexReader.SearchPoiTypeFilter;
import net.osmand.binary.CachedOsmandIndexes;
import net.osmand.data.Amenity;
import net.osmand.data.RotatedTileBox;
import net.osmand.data.TransportStop;
import net.osmand.map.ITileSource;
import net.osmand.map.MapTileDownloader;
import net.osmand.map.MapTileDownloader.DownloadRequest;
import net.osmand.map.OsmandRegions;
import net.osmand.osm.MapPoiTypes;
import net.osmand.osm.PoiCategory;
import net.osmand.plus.AppInitializer;
import net.osmand.plus.AppInitializer.InitEvents;
import net.osmand.plus.BusyIndicator;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R;
import net.osmand.plus.SQLiteTileSource;
import net.osmand.plus.Version;
import net.osmand.plus.render.MapRenderRepositories;
import net.osmand.plus.render.NativeOsmandLibrary;
import net.osmand.plus.resources.AsyncLoadingThread.MapLoadRequest;
import net.osmand.plus.resources.AsyncLoadingThread.TileLoadDownloadRequest;
import net.osmand.plus.resources.AsyncLoadingThread.TransportLoadRequest;
import net.osmand.plus.srtmplugin.SRTMPlugin;
import net.osmand.plus.views.OsmandMapLayer.DrawSettings;
import net.osmand.util.Algorithms;
import net.osmand.util.MapUtils;
import org.apache.commons.logging.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.HandlerThread;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.view.WindowManager;
/**
* Resource manager is responsible to work with all resources
* that could consume memory (especially with file resources).
* Such as indexes, tiles.
* Also it is responsible to create cache for that resources if they
* can't be loaded fully into memory & clear them on request.
*/
public class ResourceManager {
public static final String VECTOR_MAP = "#vector_map"; //$NON-NLS-1$
private static final String INDEXES_CACHE = "ind.cache";
private static final Log log = PlatformUtil.getLog(ResourceManager.class);
protected static ResourceManager manager = null;
// it is not good investigated but no more than 64 (satellite images)
// Only 8 MB (from 16 Mb whole mem) available for images : image 64K * 128 = 8 MB (8 bit), 64 - 16 bit, 32 - 32 bit
// at least 3*9?
protected int maxImgCacheSize = 28;
protected Map<String, Bitmap> cacheOfImages = new LinkedHashMap<String, Bitmap>();
protected Map<String, Boolean> imagesOnFS = new LinkedHashMap<String, Boolean>() ;
protected File dirWithTiles ;
private final OsmandApplication context;
private BusyIndicator busyIndicator;
public interface ResourceWatcher {
public boolean indexResource(File f);
public List<String> getWatchWorkspaceFolder();
}
// Indexes
private final Map<String, RegionAddressRepository> addressMap = new TreeMap<String, RegionAddressRepository>(Collator.getInstance());
protected final List<AmenityIndexRepository> amenityRepositories = new ArrayList<AmenityIndexRepository>();
protected final List<TransportIndexRepository> transportRepositories = new ArrayList<TransportIndexRepository>();
protected final Map<String, String> indexFileNames = new ConcurrentHashMap<String, String>();
protected final Map<String, String> basemapFileNames = new ConcurrentHashMap<String, String>();
protected final Map<String, BinaryMapIndexReader> routingMapFiles = new ConcurrentHashMap<String, BinaryMapIndexReader>();
protected final MapRenderRepositories renderer;
protected final MapTileDownloader tileDownloader;
public final AsyncLoadingThread asyncLoadingThread = new AsyncLoadingThread(this);
private HandlerThread renderingBufferImageThread;
protected boolean internetIsNotAccessible = false;
private java.text.DateFormat dateFormat;
public ResourceManager(OsmandApplication context) {
this.context = context;
this.renderer = new MapRenderRepositories(context);
asyncLoadingThread.start();
renderingBufferImageThread = new HandlerThread("RenderingBaseImage");
renderingBufferImageThread.start();
tileDownloader = MapTileDownloader.getInstance(Version.getFullVersion(context));
dateFormat = DateFormat.getDateFormat(context);
resetStoreDirectory();
WindowManager mgr = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
mgr.getDefaultDisplay().getMetrics(dm);
// Only 8 MB (from 16 Mb whole mem) available for images : image 64K * 128 = 8 MB (8 bit), 64 - 16 bit, 32 - 32 bit
// at least 3*9?
float tiles = (dm.widthPixels / 256 + 2) * (dm.heightPixels / 256 + 2) * 3;
log.info("Tiles to load in memory : " + tiles);
maxImgCacheSize = (int) (tiles) ;
}
public MapTileDownloader getMapTileDownloader() {
return tileDownloader;
}
public HandlerThread getRenderingBufferImageThread() {
return renderingBufferImageThread;
}
public void resetStoreDirectory() {
dirWithTiles = context.getAppPath(IndexConstants.TILES_INDEX_DIR);
dirWithTiles.mkdirs();
// ".nomedia" indicates there are no pictures and no music to list in this dir for the Gallery app
try {
context.getAppPath(".nomedia").createNewFile(); //$NON-NLS-1$
} catch( Exception e ) {
}
}
public java.text.DateFormat getDateFormat() {
return dateFormat;
}
public OsmandApplication getContext() {
return context;
}
////////////////////////////////////////////// Working with tiles ////////////////////////////////////////////////
public Bitmap getTileImageForMapAsync(String file, ITileSource map, int x, int y, int zoom, boolean loadFromInternetIfNeeded) {
return getTileImageForMap(file, map, x, y, zoom, loadFromInternetIfNeeded, false, true);
}
public synchronized Bitmap getTileImageFromCache(String file){
return cacheOfImages.get(file);
}
public synchronized void putTileInTheCache(String file, Bitmap bmp) {
cacheOfImages.put(file, bmp);
}
public Bitmap getTileImageForMapSync(String file, ITileSource map, int x, int y, int zoom, boolean loadFromInternetIfNeeded) {
return getTileImageForMap(file, map, x, y, zoom, loadFromInternetIfNeeded, true, true);
}
public synchronized void tileDownloaded(DownloadRequest request){
if(request instanceof TileLoadDownloadRequest){
TileLoadDownloadRequest req = ((TileLoadDownloadRequest) request);
imagesOnFS.put(req.tileId, Boolean.TRUE);
/* if(req.fileToSave != null && req.tileSource instanceof SQLiteTileSource){
try {
((SQLiteTileSource) req.tileSource).insertImage(req.xTile, req.yTile, req.zoom, req.fileToSave);
} catch (IOException e) {
log.warn("File "+req.fileToSave.getName() + " couldn't be read", e); //$NON-NLS-1$//$NON-NLS-2$
}
req.fileToSave.delete();
String[] l = req.fileToSave.getParentFile().list();
if(l == null || l.length == 0){
req.fileToSave.getParentFile().delete();
l = req.fileToSave.getParentFile().getParentFile().list();
if(l == null || l.length == 0){
req.fileToSave.getParentFile().getParentFile().delete();
}
}
}*/
}
}
public synchronized boolean tileExistOnFileSystem(String file, ITileSource map, int x, int y, int zoom){
if(!imagesOnFS.containsKey(file)){
boolean ex = false;
if(map instanceof SQLiteTileSource){
if(((SQLiteTileSource) map).isLocked()){
return false;
}
ex = ((SQLiteTileSource) map).exists(x, y, zoom);
} else {
if(file == null){
file = calculateTileId(map, x, y, zoom);
}
ex = new File(dirWithTiles, file).exists();
}
if (ex) {
imagesOnFS.put(file, Boolean.TRUE);
} else {
imagesOnFS.put(file, null);
}
}
return imagesOnFS.get(file) != null || cacheOfImages.get(file) != null;
}
public void clearTileImageForMap(String file, ITileSource map, int x, int y, int zoom){
getTileImageForMap(file, map, x, y, zoom, true, false, true, true);
}
/**
* @param file - null could be passed if you do not call very often with that param
*/
protected Bitmap getTileImageForMap(String file, ITileSource map, int x, int y, int zoom,
boolean loadFromInternetIfNeeded, boolean sync, boolean loadFromFs) {
return getTileImageForMap(file, map, x, y, zoom, loadFromInternetIfNeeded, sync, loadFromFs, false);
}
// introduce cache in order save memory
protected StringBuilder builder = new StringBuilder(40);
protected char[] tileId = new char[120];
private GeoidAltitudeCorrection geoidAltitudeCorrection;
private boolean searchAmenitiesInProgress;
public synchronized String calculateTileId(ITileSource map, int x, int y, int zoom) {
builder.setLength(0);
if (map == null) {
builder.append(IndexConstants.TEMP_SOURCE_TO_LOAD);
} else {
builder.append(map.getName());
}
if (map instanceof SQLiteTileSource) {
builder.append('@');
} else {
builder.append('/');
}
builder.append(zoom).append('/').append(x).append('/').append(y).
append(map == null ? ".jpg" : map.getTileFormat()).append(".tile"); //$NON-NLS-1$ //$NON-NLS-2$
return builder.toString();
}
protected synchronized Bitmap getTileImageForMap(String tileId, ITileSource map, int x, int y, int zoom,
boolean loadFromInternetIfNeeded, boolean sync, boolean loadFromFs, boolean deleteBefore) {
if (tileId == null) {
tileId = calculateTileId(map, x, y, zoom);
if(tileId == null){
return null;
}
}
if(deleteBefore){
cacheOfImages.remove(tileId);
if (map instanceof SQLiteTileSource) {
((SQLiteTileSource) map).deleteImage(x, y, zoom);
} else {
File f = new File(dirWithTiles, tileId);
if (f.exists()) {
f.delete();
}
}
imagesOnFS.put(tileId, null);
}
if (loadFromFs && cacheOfImages.get(tileId) == null && map != null) {
boolean locked = map instanceof SQLiteTileSource && ((SQLiteTileSource) map).isLocked();
if(!loadFromInternetIfNeeded && !locked && !tileExistOnFileSystem(tileId, map, x, y, zoom)){
return null;
}
String url = loadFromInternetIfNeeded ? map.getUrlToLoad(x, y, zoom) : null;
File toSave = null;
if (url != null) {
if (map instanceof SQLiteTileSource) {
toSave = new File(dirWithTiles, calculateTileId(((SQLiteTileSource) map).getBase(), x, y, zoom));
} else {
toSave = new File(dirWithTiles, tileId);
}
}
TileLoadDownloadRequest req = new TileLoadDownloadRequest(dirWithTiles, url, toSave,
tileId, map, x, y, zoom);
if(sync){
return getRequestedImageTile(req);
} else {
asyncLoadingThread.requestToLoadImage(req);
}
}
return cacheOfImages.get(tileId);
}
protected Bitmap getRequestedImageTile(TileLoadDownloadRequest req){
if(req.tileId == null || req.dirWithTiles == null){
return null;
}
Bitmap cacheBmp = cacheOfImages.get(req.tileId);
if (cacheBmp != null) {
return cacheBmp;
}
if (cacheOfImages.size() > maxImgCacheSize) {
clearTiles();
}
if (req.dirWithTiles.canRead() && !asyncLoadingThread.isFileCurrentlyDownloaded(req.fileToSave)
&& !asyncLoadingThread.isFilePendingToDownload(req.fileToSave)) {
long time = System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug("Start loaded file : " + req.tileId + " " + Thread.currentThread().getName()); //$NON-NLS-1$ //$NON-NLS-2$
}
Bitmap bmp = null;
if (req.tileSource instanceof SQLiteTileSource) {
try {
long[] tm = new long[1];
bmp = ((SQLiteTileSource) req.tileSource).getImage(req.xTile, req.yTile, req.zoom, tm);
if (tm[0] != 0) {
int ts = req.tileSource.getExpirationTimeMillis();
if (ts != -1 && req.url != null && time - tm[0] > ts) {
asyncLoadingThread.requestToDownload(req);
}
}
} catch (OutOfMemoryError e) {
log.error("Out of memory error", e); //$NON-NLS-1$
clearTiles();
}
} else {
File en = new File(req.dirWithTiles, req.tileId);
if (en.exists()) {
try {
bmp = BitmapFactory.decodeFile(en.getAbsolutePath());
int ts = req.tileSource.getExpirationTimeMillis();
if(ts != -1 && req.url != null && time - en.lastModified() > ts) {
asyncLoadingThread.requestToDownload(req);
}
} catch (OutOfMemoryError e) {
log.error("Out of memory error", e); //$NON-NLS-1$
clearTiles();
}
}
}
if (bmp != null) {
cacheOfImages.put(req.tileId, bmp);
if (log.isDebugEnabled()) {
log.debug("Loaded file : " + req.tileId + " " + -(time - System.currentTimeMillis()) + " ms " + cacheOfImages.size()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
if (cacheOfImages.get(req.tileId) == null && req.url != null) {
asyncLoadingThread.requestToDownload(req);
}
}
return cacheOfImages.get(req.tileId);
}
////////////////////////////////////////////// Working with indexes ////////////////////////////////////////////////
public List<String> reloadIndexesOnStart(AppInitializer progress, List<String> warnings){
close();
// check we have some assets to copy to sdcard
warnings.addAll(checkAssets(progress));
progress.notifyEvent(InitEvents.ASSETS_COPIED);
reloadIndexes(progress, warnings);
progress.notifyEvent(InitEvents.MAPS_INITIALIZED);
return warnings;
}
public List<String> reloadIndexes(IProgress progress, List<String> warnings) {
geoidAltitudeCorrection = new GeoidAltitudeCorrection(context.getAppPath(null));
// do it lazy
// indexingImageTiles(progress);
warnings.addAll(indexingMaps(progress));
warnings.addAll(indexVoiceFiles(progress));
warnings.addAll(OsmandPlugin.onIndexingFiles(progress));
warnings.addAll(indexAdditionalMaps(progress));
return warnings;
}
public List<String> indexAdditionalMaps(IProgress progress) {
return context.getAppCustomization().onIndexingFiles(progress, indexFileNames);
}
public List<String> indexVoiceFiles(IProgress progress){
File file = context.getAppPath(IndexConstants.VOICE_INDEX_DIR);
file.mkdirs();
List<String> warnings = new ArrayList<String>();
if (file.exists() && file.canRead()) {
File[] lf = file.listFiles();
if (lf != null) {
for (File f : lf) {
if (f.isDirectory()) {
File conf = new File(f, "_config.p");
if (!conf.exists()) {
conf = new File(f, "_ttsconfig.p");
}
if (conf.exists()) {
indexFileNames.put(f.getName(), dateFormat.format(conf.lastModified())); //$NON-NLS-1$
}
}
}
}
}
return warnings;
}
private List<String> checkAssets(IProgress progress) {
String fv = Version.getFullVersion(context);
if (!fv.equalsIgnoreCase(context.getSettings().PREVIOUS_INSTALLED_VERSION.get())) {
File applicationDataDir = context.getAppPath(null);
applicationDataDir.mkdirs();
if (applicationDataDir.canWrite()) {
try {
progress.startTask(context.getString(R.string.installing_new_resources), -1);
AssetManager assetManager = context.getAssets();
boolean isFirstInstall = context.getSettings().PREVIOUS_INSTALLED_VERSION.get().equals("");
unpackBundledAssets(assetManager, applicationDataDir, progress, isFirstInstall);
context.getSettings().PREVIOUS_INSTALLED_VERSION.set(fv);
copyRegionsBoundaries();
copyPoiTypes();
for (String internalStyle : context.getRendererRegistry().getInternalRenderers().keySet()) {
File fl = context.getRendererRegistry().getFileForInternalStyle(internalStyle);
if (fl.exists()) {
context.getRendererRegistry().copyFileForInternalStyle(internalStyle);
}
}
} catch (SQLiteException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
} catch (XmlPullParserException e) {
log.error(e.getMessage(), e);
}
}
}
return Collections.emptyList();
}
private void copyRegionsBoundaries() {
try {
File file = context.getAppPath("regions.ocbf");
if (file != null) {
FileOutputStream fout = new FileOutputStream(file);
Algorithms.streamCopy(OsmandRegions.class.getResourceAsStream("regions.ocbf"), fout);
fout.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private void copyPoiTypes() {
try {
File file = context.getAppPath("poi_types.xml");
if (file != null) {
FileOutputStream fout = new FileOutputStream(file);
Algorithms.streamCopy(MapPoiTypes.class.getResourceAsStream("poi_types.xml"), fout);
fout.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private final static String ASSET_INSTALL_MODE__alwaysCopyOnFirstInstall = "alwaysCopyOnFirstInstall";
private final static String ASSET_COPY_MODE__overwriteOnlyIfExists = "overwriteOnlyIfExists";
private final static String ASSET_COPY_MODE__alwaysOverwriteOrCopy = "alwaysOverwriteOrCopy";
private final static String ASSET_COPY_MODE__copyOnlyIfDoesNotExist = "copyOnlyIfDoesNotExist";
private void unpackBundledAssets(AssetManager assetManager, File appDataDir, IProgress progress, boolean isFirstInstall) throws IOException, XmlPullParserException {
XmlPullParser xmlParser = XmlPullParserFactory.newInstance().newPullParser();
InputStream isBundledAssetsXml = assetManager.open("bundled_assets.xml");
xmlParser.setInput(isBundledAssetsXml, "UTF-8");
int next = 0;
while ((next = xmlParser.next()) != XmlPullParser.END_DOCUMENT) {
if (next == XmlPullParser.START_TAG && xmlParser.getName().equals("asset")) {
final String source = xmlParser.getAttributeValue(null, "source");
final String destination = xmlParser.getAttributeValue(null, "destination");
final String combinedMode = xmlParser.getAttributeValue(null, "mode");
final String[] modes = combinedMode.split("\\|");
if(modes.length == 0) {
log.error("Mode '" + combinedMode + "' is not valid");
continue;
}
String installMode = null;
String copyMode = null;
for(String mode : modes) {
if(ASSET_INSTALL_MODE__alwaysCopyOnFirstInstall.equals(mode))
installMode = mode;
else if(ASSET_COPY_MODE__overwriteOnlyIfExists.equals(mode) ||
ASSET_COPY_MODE__alwaysOverwriteOrCopy.equals(mode) ||
ASSET_COPY_MODE__copyOnlyIfDoesNotExist.equals(mode))
copyMode = mode;
else
log.error("Mode '" + mode + "' is unknown");
}
final File destinationFile = new File(appDataDir, destination);
boolean unconditional = false;
if(installMode != null)
unconditional = unconditional || (ASSET_INSTALL_MODE__alwaysCopyOnFirstInstall.equals(installMode) && isFirstInstall);
if(copyMode == null)
log.error("No copy mode was defined for " + source);
unconditional = unconditional || ASSET_COPY_MODE__alwaysOverwriteOrCopy.equals(copyMode);
boolean shouldCopy = unconditional;
shouldCopy = shouldCopy || (ASSET_COPY_MODE__overwriteOnlyIfExists.equals(copyMode) && destinationFile.exists());
shouldCopy = shouldCopy || (ASSET_COPY_MODE__copyOnlyIfDoesNotExist.equals(copyMode) && !destinationFile.exists());
if(shouldCopy)
copyAssets(assetManager, source, destinationFile);
}
}
isBundledAssetsXml.close();
}
public static void copyAssets(AssetManager assetManager, String assetName, File file) throws IOException {
if(file.exists()){
Algorithms.removeAllFiles(file);
}
file.getParentFile().mkdirs();
InputStream is = assetManager.open(assetName, AssetManager.ACCESS_STREAMING);
FileOutputStream out = new FileOutputStream(file);
Algorithms.streamCopy(is, out);
Algorithms.closeStream(out);
Algorithms.closeStream(is);
}
private List<File> collectFiles(File dir, String ext, List<File> files) {
if(dir.exists() && dir.canRead()) {
File[] lf = dir.listFiles();
if(lf == null) {
lf = new File[0];
}
for (File f : lf) {
if (f.getName().endsWith(ext)) {
files.add(f);
}
}
}
return files;
}
public List<String> indexingMaps(final IProgress progress) {
long val = System.currentTimeMillis();
ArrayList<File> files = new ArrayList<File>();
File appPath = context.getAppPath(null);
collectFiles(appPath, IndexConstants.BINARY_MAP_INDEX_EXT, files);
if(OsmandPlugin.getEnabledPlugin(SRTMPlugin.class) != null) {
collectFiles(context.getAppPath(IndexConstants.SRTM_INDEX_DIR), IndexConstants.BINARY_MAP_INDEX_EXT, files);
}
List<String> warnings = new ArrayList<String>();
renderer.clearAllResources();
CachedOsmandIndexes cachedOsmandIndexes = new CachedOsmandIndexes();
File indCache = context.getAppPath(INDEXES_CACHE);
if (indCache.exists()) {
try {
cachedOsmandIndexes.readFromFile(indCache, CachedOsmandIndexes.VERSION);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
for (File f : files) {
progress.startTask(context.getString(R.string.indexing_map) + " " + f.getName(), -1); //$NON-NLS-1$
try {
BinaryMapIndexReader index = null;
try {
index = cachedOsmandIndexes.getReader(f);
if (index.getVersion() != IndexConstants.BINARY_MAP_VERSION) {
index = null;
}
if (index != null) {
renderer.initializeNewResource(progress, f, index);
}
} catch (IOException e) {
log.error(String.format("File %s could not be read", f.getName()), e);
}
if (index == null || (Version.isFreeVersion(context) && f.getName().contains("_wiki"))) {
warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$
} else {
if (index.isBasemap()) {
basemapFileNames.put(f.getName(), f.getName());
}
long dateCreated = index.getDateCreated();
if (dateCreated == 0) {
dateCreated = f.lastModified();
}
indexFileNames.put(f.getName(), dateFormat.format(dateCreated)); //$NON-NLS-1$
for (String rName : index.getRegionNames()) {
// skip duplicate names (don't make collision between getName() and name in the map)
// it can be dangerous to use one file to different indexes if it is multithreaded
RegionAddressRepositoryBinary rarb = new RegionAddressRepositoryBinary(index, rName);
addressMap.put(rName, rarb);
}
if (index.hasTransportData()) {
try {
RandomAccessFile raf = new RandomAccessFile(f, "r"); //$NON-NLS-1$
transportRepositories.add(new TransportIndexRepositoryBinary(new BinaryMapIndexReader(raf, index)));
} catch (IOException e) {
log.error("Exception reading " + f.getAbsolutePath(), e); //$NON-NLS-1$
warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$
}
}
if (index.containsRouteData()) {
try {
RandomAccessFile raf = new RandomAccessFile(f, "r"); //$NON-NLS-1$
routingMapFiles.put(f.getAbsolutePath(), new BinaryMapIndexReader(raf, index));
} catch (IOException e) {
log.error("Exception reading " + f.getAbsolutePath(), e); //$NON-NLS-1$
warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$
}
}
if (index.containsPoiData()) {
try {
RandomAccessFile raf = new RandomAccessFile(f, "r"); //$NON-NLS-1$
amenityRepositories.add(new AmenityIndexRepositoryBinary(new BinaryMapIndexReader(raf, index)));
} catch (IOException e) {
log.error("Exception reading " + f.getAbsolutePath(), e); //$NON-NLS-1$
warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$
}
}
}
} catch (SQLiteException e) {
log.error("Exception reading " + f.getAbsolutePath(), e); //$NON-NLS-1$
warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName())); //$NON-NLS-1$
} catch (OutOfMemoryError oome) {
log.error("Exception reading " + f.getAbsolutePath(), oome); //$NON-NLS-1$
warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_big_for_memory), f.getName()));
}
}
log.debug("All map files initialized " + (System.currentTimeMillis() - val) + " ms");
if (files.size() > 0 && (!indCache.exists() || indCache.canWrite())) {
try {
cachedOsmandIndexes.writeToFile(indCache);
} catch (Exception e) {
log.error("Index file could not be written", e);
}
}
return warnings;
}
public void initMapBoundariesCacheNative() {
File indCache = context.getAppPath(INDEXES_CACHE);
if (indCache.exists()) {
NativeOsmandLibrary nativeLib = NativeOsmandLibrary.getLoadedLibrary();
if (nativeLib != null) {
nativeLib.initCacheMapFile(indCache.getAbsolutePath());
}
}
}
////////////////////////////////////////////// Working with amenities ////////////////////////////////////////////////
public List<Amenity> searchAmenities(SearchPoiTypeFilter filter,
double topLatitude, double leftLongitude, double bottomLatitude, double rightLongitude, int zoom, final ResultMatcher<Amenity> matcher) {
final List<Amenity> amenities = new ArrayList<Amenity>();
searchAmenitiesInProgress = true;
try {
if (!filter.isEmpty()) {
for (AmenityIndexRepository index : amenityRepositories) {
if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) {
List<Amenity> r = index.searchAmenities(MapUtils.get31TileNumberY(topLatitude),
MapUtils.get31TileNumberX(leftLongitude), MapUtils.get31TileNumberY(bottomLatitude),
MapUtils.get31TileNumberX(rightLongitude), zoom, filter, matcher);
if(r != null) {
amenities.addAll(r);
}
}
}
}
} finally {
searchAmenitiesInProgress = false;
}
return amenities;
}
public List<Amenity> searchAmenitiesOnThePath(List<Location> locations, double radius, SearchPoiTypeFilter filter,
ResultMatcher<Amenity> matcher) {
searchAmenitiesInProgress = true;
final List<Amenity> amenities = new ArrayList<Amenity>();
try {
if (locations != null && locations.size() > 0) {
List<AmenityIndexRepository> repos = new ArrayList<AmenityIndexRepository>();
double topLatitude = locations.get(0).getLatitude();
double bottomLatitude = locations.get(0).getLatitude();
double leftLongitude = locations.get(0).getLongitude();
double rightLongitude = locations.get(0).getLongitude();
for (Location l : locations) {
topLatitude = Math.max(topLatitude, l.getLatitude());
bottomLatitude = Math.min(bottomLatitude, l.getLatitude());
leftLongitude = Math.min(leftLongitude, l.getLongitude());
rightLongitude = Math.max(rightLongitude, l.getLongitude());
}
if (!filter.isEmpty()) {
for (AmenityIndexRepository index : amenityRepositories) {
if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) {
repos.add(index);
}
}
if (!repos.isEmpty()) {
for (AmenityIndexRepository r : repos) {
List<Amenity> res = r.searchAmenitiesOnThePath(locations, radius, filter, matcher);
if(res != null) {
amenities.addAll(res);
}
}
}
}
}
} finally {
searchAmenitiesInProgress = false;
}
return amenities;
}
public boolean containsAmenityRepositoryToSearch(boolean searchByName){
for (AmenityIndexRepository index : amenityRepositories) {
if(searchByName){
if(index instanceof AmenityIndexRepositoryBinary){
return true;
}
} else {
return true;
}
}
return false;
}
public List<Amenity> searchAmenitiesByName(String searchQuery,
double topLatitude, double leftLongitude, double bottomLatitude, double rightLongitude,
double lat, double lon, ResultMatcher<Amenity> matcher) {
List<Amenity> amenities = new ArrayList<Amenity>();
List<AmenityIndexRepositoryBinary> list = new ArrayList<AmenityIndexRepositoryBinary>();
for (AmenityIndexRepository index : amenityRepositories) {
if (index instanceof AmenityIndexRepositoryBinary) {
if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) {
if(index.checkContains(lat, lon)){
list.add(0, (AmenityIndexRepositoryBinary) index);
} else {
list.add((AmenityIndexRepositoryBinary) index);
}
}
}
}
for (AmenityIndexRepositoryBinary index : list) {
if (matcher != null && matcher.isCancelled()) {
break;
}
List<Amenity> result = index.searchAmenitiesByName(MapUtils.get31TileNumberX(lon), MapUtils.get31TileNumberY(lat),
MapUtils.get31TileNumberX(leftLongitude), MapUtils.get31TileNumberY(topLatitude),
MapUtils.get31TileNumberX(rightLongitude), MapUtils.get31TileNumberY(bottomLatitude),
searchQuery, matcher);
amenities.addAll(result);
}
return amenities;
}
public Map<PoiCategory, List<String>> searchAmenityCategoriesByName(String searchQuery, double lat, double lon) {
Map<PoiCategory, List<String>> map = new LinkedHashMap<PoiCategory, List<String>>();
for (AmenityIndexRepository index : amenityRepositories) {
if (index instanceof AmenityIndexRepositoryBinary) {
if (index.checkContains(lat, lon)) {
((AmenityIndexRepositoryBinary) index).searchAmenityCategoriesByName(searchQuery, map);
}
}
}
return map;
}
////////////////////////////////////////////// Working with address ///////////////////////////////////////////
public RegionAddressRepository getRegionRepository(String name){
return addressMap.get(name);
}
public Collection<RegionAddressRepository> getAddressRepositories(){
return addressMap.values();
}
////////////////////////////////////////////// Working with transport ////////////////////////////////////////////////
public List<TransportIndexRepository> searchTransportRepositories(double latitude, double longitude) {
List<TransportIndexRepository> repos = new ArrayList<TransportIndexRepository>();
for (TransportIndexRepository index : transportRepositories) {
if (index.checkContains(latitude,longitude)) {
repos.add(index);
}
}
return repos;
}
public void searchTransportAsync(double topLatitude, double leftLongitude, double bottomLatitude, double rightLongitude, int zoom, List<TransportStop> toFill){
List<TransportIndexRepository> repos = new ArrayList<TransportIndexRepository>();
for (TransportIndexRepository index : transportRepositories) {
if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) {
if (!index.checkCachedObjects(topLatitude, leftLongitude, bottomLatitude, rightLongitude, zoom, toFill, true)) {
repos.add(index);
}
}
}
if(!repos.isEmpty()){
TransportLoadRequest req = asyncLoadingThread.new TransportLoadRequest(repos, zoom);
req.setBoundaries(topLatitude, leftLongitude, bottomLatitude, rightLongitude);
asyncLoadingThread.requestToLoadTransport(req);
}
}
////////////////////////////////////////////// Working with map ////////////////////////////////////////////////
public boolean updateRenderedMapNeeded(RotatedTileBox rotatedTileBox, DrawSettings drawSettings) {
return renderer.updateMapIsNeeded(rotatedTileBox, drawSettings);
}
public void updateRendererMap(RotatedTileBox rotatedTileBox){
renderer.interruptLoadingMap();
asyncLoadingThread.requestToLoadMap(new MapLoadRequest(rotatedTileBox));
}
public void interruptRendering(){
renderer.interruptLoadingMap();
}
public boolean isSearchAmenitiesInProgress() {
return searchAmenitiesInProgress;
}
public MapRenderRepositories getRenderer() {
return renderer;
}
////////////////////////////////////////////// Closing methods ////////////////////////////////////////////////
public void closeAmenities(){
for(AmenityIndexRepository r : amenityRepositories){
r.close();
}
amenityRepositories.clear();
}
public void closeAddresses(){
for(RegionAddressRepository r : addressMap.values()){
r.close();
}
addressMap.clear();
}
public void closeTransport(){
for(TransportIndexRepository r : transportRepositories){
r.close();
}
transportRepositories.clear();
}
public BusyIndicator getBusyIndicator() {
return busyIndicator;
}
public synchronized void setBusyIndicator(BusyIndicator busyIndicator) {
this.busyIndicator = busyIndicator;
}
public synchronized void close(){
imagesOnFS.clear();
indexFileNames.clear();
basemapFileNames.clear();
renderer.clearAllResources();
closeAmenities();
closeRouteFiles();
closeAddresses();
closeTransport();
}
public BinaryMapIndexReader[] getRoutingMapFiles() {
return routingMapFiles.values().toArray(new BinaryMapIndexReader[routingMapFiles.size()]);
}
public void closeRouteFiles() {
List<String> map = new ArrayList<String>(routingMapFiles.keySet());
for(String m : map){
try {
BinaryMapIndexReader ind = routingMapFiles.remove(m);
if(ind != null){
ind.getRaf().close();
}
} catch(IOException e){
log.error("Error closing resource " + m, e);
}
}
}
public Map<String, String> getIndexFileNames() {
return new LinkedHashMap<String, String>(indexFileNames);
}
public boolean containsBasemap(){
return !basemapFileNames.isEmpty();
}
public Map<String, String> getBackupIndexes(Map<String, String> map) {
File file = context.getAppPath(IndexConstants.BACKUP_INDEX_DIR);
if (file != null && file.isDirectory()) {
File[] lf = file.listFiles();
if (lf != null) {
for (File f : lf) {
if (f != null && f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) {
map.put(f.getName(), AndroidUtils.formatDate(context, f.lastModified())); //$NON-NLS-1$
}
}
}
}
return map;
}
public synchronized void reloadTilesFromFS(){
imagesOnFS.clear();
}
/// On low memory method ///
public void onLowMemory() {
log.info("On low memory : cleaning tiles - size = " + cacheOfImages.size()); //$NON-NLS-1$
clearTiles();
for(RegionAddressRepository r : addressMap.values()){
r.clearCache();
}
renderer.clearCache();
System.gc();
}
public GeoidAltitudeCorrection getGeoidAltitudeCorrection() {
return geoidAltitudeCorrection;
}
public OsmandRegions getOsmandRegions() {
return context.getRegions();
}
protected synchronized void clearTiles() {
log.info("Cleaning tiles - size = " + cacheOfImages.size()); //$NON-NLS-1$
ArrayList<String> list = new ArrayList<String>(cacheOfImages.keySet());
// remove first images (as we think they are older)
for (int i = 0; i < list.size() / 2; i++) {
cacheOfImages.remove(list.get(i));
}
}
}
| FreeDao/getintouchmaps | OsmAnd/src/net/osmand/plus/resources/ResourceManager.java | Java | gpl-3.0 | 35,554 |
package com.wizard.web.application.manage.permission.service;
import java.util.List;
import java.util.Map;
import com.wizard.web.application.manage.permission.bean.Menu;
import com.wizard.web.basic.io.PageResponse;
import com.wizard.web.basic.io.extjs.ExtPageRequest;
public interface PermissionManageService {
public PageResponse<Menu> searchMenu(ExtPageRequest request);
public Map<String, List<String>> getAuthority();
public void doSaveAuthority(Map<String, List<String>> map);
}
| joaquinaimar/wizard | 99 backup/02 source-20131113/wizard-web-esm/src/main/java/com/wizard/web/application/manage/permission/service/PermissionManageService.java | Java | gpl-3.0 | 503 |
package com.referendum.voting.results;
import java.util.List;
import com.referendum.voting.ballot.RankedBallot;
import com.referendum.voting.election.ElectionRound;
public interface MultipleWinnerElectionResults extends ElectionResults {
List<ElectionRound> getRounds();
List<RankedBallot> getBallots();
Integer getThreshold(Integer votes, Integer seats);
default ElectionResultsType getElectionResultsType() {
return ElectionResultsType.MULTIPLE_WINNER;
}
}
| tchoulihan/referendum | src/main/java/com/referendum/voting/results/MultipleWinnerElectionResults.java | Java | gpl-3.0 | 480 |
/*
* DRBDBReader
* Copyright (C) 2016-2017, Kyle Repinski
*
* 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/>.
*/
using System;
using DRBDBReader.DB.Records;
namespace DRBDBReader.DB.Converters
{
public class BinaryStateConverter : StateConverter
{
public BDSRecord bdsRecord;
public BinaryStateConverter( Database db, byte[] record, ushort cfid, ushort dsid ) : base( db, record, cfid, dsid )
{
}
protected override void buildStateList()
{
Table bdsTable = this.db.tables[Database.TABLE_BINARY_DATA_SPECIFIER];
this.dsRecord = bdsTable.getRecord( this.dsid );
this.bdsRecord = (BDSRecord)this.dsRecord;
this.entries.Add( 0, bdsRecord.falseString );
this.entries.Add( 1, bdsRecord.trueString );
}
protected override ushort getEntryID( ushort val )
{
switch( this.scRecord.op )
{
case Operator.GREATER:
return (ushort)( val > this.scRecord.mask ? 1 : 0 );
case Operator.LESS:
return (ushort)( val < this.scRecord.mask ? 1 : 0 );
case Operator.MASK_ZERO:
return (ushort)( ( val & this.scRecord.mask ) == 0 ? 1 : 0 );
case Operator.MASK_NOT_ZERO:
return (ushort)( ( val & this.scRecord.mask ) != 0 ? 1 : 0 );
case Operator.NOT_EQUAL:
return (ushort)( val != this.scRecord.mask ? 1 : 0 );
case Operator.EQUAL:
default:
return (ushort)( val == this.scRecord.mask ? 1 : 0 );
}
}
public override string ToString()
{
string ret = base.ToString() + Environment.NewLine;
ret = ret.Replace( Environment.NewLine + "0x00: ", Environment.NewLine + "FALSE: " );
ret = ret.Replace( Environment.NewLine + "0x01: ", Environment.NewLine + "TRUE: " );
ret += Environment.NewLine + "MASK: 0x" + this.scRecord.mask.ToString( "X2" );
ret += Environment.NewLine + "OP: " + this.scRecord.op.ToString();
return ret;
}
}
}
| laszlodaniel/ChryslerCCDSCIScanner | GUI/ChryslerCCDSCIScanner/DB/Converters/BinaryStateConverter.cs | C# | gpl-3.0 | 2,440 |
var http = require('https')
, qs = require('querystring')
, Cleverbot = function (options) {
this.configure(options);
};
Cleverbot.prepare = function(cb){
// noop for backwards compatibility
cb();
};
Cleverbot.prototype = {
configure: function (options){
if(options && options.constructor !== Object){
throw new TypeError("Cleverbot must be configured with an Object");
}
this.options = options || {};
},
path: function(message){
var path = '/getreply'
, query = {
input: JSON.stringify(message),
key: this.options.botapi || "CHANGEME"
};
if(this.state) {
query.cs = this.state;
}
return [path, qs.stringify(query)].join("?");
},
write: function (message, callback, errorCallback) {
var clever = this;
var body = this.params;
var options = {
host: 'www.cleverbot.com',
port: 443,
path: this.path(message),
method: 'GET',
headers: { 'Content-Type': 'text/javascript' }
};
var cb = callback || function() { };
var err = errorCallback || function() {};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function(data) {
chunks.push(data);
});
res.on("end", function(i) {
var body = Buffer.concat(chunks).toString();
var responseBody;
try{
responseBody = JSON.parse(body);
} catch(e) {
try{
eval("responseBody = " + body);
} catch(e) {
err(e, message, body);
return;
}
}
responseBody.message = responseBody.output; //for backwards compatibility
this.state = responseBody.cs;
cb(responseBody);
}.bind(this));
}.bind(this));
req.end();
}
};
module.exports = Cleverbot;
| SrNativee/BotDeUmBot | node_modules/cleverbot-node/lib/cleverbot.js | JavaScript | gpl-3.0 | 2,085 |
/*
* Quasar: lightweight threads and actors for the JVM.
* Copyright (c) 2013-2015, Parallel Universe Software Co. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 3.0
* as published by the Free Software Foundation.
*/
package co.paralleluniverse.strands;
import co.paralleluniverse.fibers.SuspendExecution;
/**
* This interface can represent any operation that may suspend the currently executing {@link Strand} (i.e. thread or fiber).
* Unlike {@link SuspendableRunnable}, the operation represented by this interface returns a result.
* This is just like a {@link java.util.concurrent.Callable}, only suspendable.
*
* @author circlespainter
*
* @param <V> The value being returned.
* @param <E> The user exception type being thrown.
*/
public interface CheckedSuspendableCallable<V, E extends Exception> extends java.io.Serializable {
V call() throws SuspendExecution, InterruptedException, E;
}
| tbrooks8/quasar | quasar-core/src/main/java/co/paralleluniverse/strands/CheckedSuspendableCallable.java | Java | gpl-3.0 | 1,178 |
// Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <cmath>
#include "../include/v8stdint.h"
#include "checks.h"
#include "utils.h"
#include "bignum-dtoa.h"
#include "bignum.h"
#include "double.h"
namespace v8 {
namespace internal {
static int NormalizedExponent(uint64_t significand, int exponent) {
ASSERT(significand != 0);
while ((significand & Double::kHiddenBit) == 0) {
significand = significand << 1;
exponent = exponent - 1;
}
return exponent;
}
// Forward declarations:
// Returns an estimation of k such that 10^(k-1) <= v < 10^k.
static int EstimatePower(int exponent);
// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
// and denominator.
static void InitialScaledStartValues(double v,
int estimated_power,
bool need_boundary_deltas,
Bignum* numerator,
Bignum* denominator,
Bignum* delta_minus,
Bignum* delta_plus);
// Multiplies numerator/denominator so that its values lies in the range 1-10.
// Returns decimal_point s.t.
// v = numerator'/denominator' * 10^(decimal_point-1)
// where numerator' and denominator' are the values of numerator and
// denominator after the call to this function.
static void FixupMultiply10(int estimated_power, bool is_even,
int* decimal_point,
Bignum* numerator, Bignum* denominator,
Bignum* delta_minus, Bignum* delta_plus);
// Generates digits from the left to the right and stops when the generated
// digits yield the shortest decimal representation of v.
static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
Bignum* delta_minus, Bignum* delta_plus,
bool is_even,
Vector<char> buffer, int* length);
// Generates 'requested_digits' after the decimal point.
static void BignumToFixed(int requested_digits, int* decimal_point,
Bignum* numerator, Bignum* denominator,
Vector<char>(buffer), int* length);
// Generates 'count' digits of numerator/denominator.
// Once 'count' digits have been produced rounds the result depending on the
// remainder (remainders of exactly .5 round upwards). Might update the
// decimal_point when rounding up (for example for 0.9999).
static void GenerateCountedDigits(int count, int* decimal_point,
Bignum* numerator, Bignum* denominator,
Vector<char>(buffer), int* length);
void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
Vector<char> buffer, int* length, int* decimal_point) {
ASSERT(v > 0);
ASSERT(!Double(v).IsSpecial());
uint64_t significand = Double(v).Significand();
bool is_even = (significand & 1) == 0;
int exponent = Double(v).Exponent();
int normalized_exponent = NormalizedExponent(significand, exponent);
// estimated_power might be too low by 1.
int estimated_power = EstimatePower(normalized_exponent);
// Shortcut for Fixed.
// The requested digits correspond to the digits after the point. If the
// number is much too small, then there is no need in trying to get any
// digits.
if (mode == BIGNUM_DTOA_FIXED && -estimated_power - 1 > requested_digits) {
buffer[0] = '\0';
*length = 0;
// Set decimal-point to -requested_digits. This is what Gay does.
// Note that it should not have any effect anyways since the string is
// empty.
*decimal_point = -requested_digits;
return;
}
Bignum numerator;
Bignum denominator;
Bignum delta_minus;
Bignum delta_plus;
// Make sure the bignum can grow large enough. The smallest double equals
// 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
// The maximum double is 1.7976931348623157e308 which needs fewer than
// 308*4 binary digits.
ASSERT(Bignum::kMaxSignificantBits >= 324*4);
bool need_boundary_deltas = (mode == BIGNUM_DTOA_SHORTEST);
InitialScaledStartValues(v, estimated_power, need_boundary_deltas,
&numerator, &denominator,
&delta_minus, &delta_plus);
// We now have v = (numerator / denominator) * 10^estimated_power.
FixupMultiply10(estimated_power, is_even, decimal_point,
&numerator, &denominator,
&delta_minus, &delta_plus);
// We now have v = (numerator / denominator) * 10^(decimal_point-1), and
// 1 <= (numerator + delta_plus) / denominator < 10
switch (mode) {
case BIGNUM_DTOA_SHORTEST:
GenerateShortestDigits(&numerator, &denominator,
&delta_minus, &delta_plus,
is_even, buffer, length);
break;
case BIGNUM_DTOA_FIXED:
BignumToFixed(requested_digits, decimal_point,
&numerator, &denominator,
buffer, length);
break;
case BIGNUM_DTOA_PRECISION:
GenerateCountedDigits(requested_digits, decimal_point,
&numerator, &denominator,
buffer, length);
break;
default:
UNREACHABLE();
}
buffer[*length] = '\0';
}
// The procedure starts generating digits from the left to the right and stops
// when the generated digits yield the shortest decimal representation of v. A
// decimal representation of v is a number lying closer to v than to any other
// double, so it converts to v when read.
//
// This is true if d, the decimal representation, is between m- and m+, the
// upper and lower boundaries. d must be strictly between them if !is_even.
// m- := (numerator - delta_minus) / denominator
// m+ := (numerator + delta_plus) / denominator
//
// Precondition: 0 <= (numerator+delta_plus) / denominator < 10.
// If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit
// will be produced. This should be the standard precondition.
static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
Bignum* delta_minus, Bignum* delta_plus,
bool is_even,
Vector<char> buffer, int* length) {
// Small optimization: if delta_minus and delta_plus are the same just reuse
// one of the two bignums.
if (Bignum::Equal(*delta_minus, *delta_plus)) {
delta_plus = delta_minus;
}
*length = 0;
while (true) {
uint16_t digit;
digit = numerator->DivideModuloIntBignum(*denominator);
ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
// digit = numerator / denominator (integer division).
// numerator = numerator % denominator.
buffer[(*length)++] = digit + '0';
// Can we stop already?
// If the remainder of the division is less than the distance to the lower
// boundary we can stop. In this case we simply round down (discarding the
// remainder).
// Similarly we test if we can round up (using the upper boundary).
bool in_delta_room_minus;
bool in_delta_room_plus;
if (is_even) {
in_delta_room_minus = Bignum::LessEqual(*numerator, *delta_minus);
} else {
in_delta_room_minus = Bignum::Less(*numerator, *delta_minus);
}
if (is_even) {
in_delta_room_plus =
Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
} else {
in_delta_room_plus =
Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
}
if (!in_delta_room_minus && !in_delta_room_plus) {
// Prepare for next iteration.
numerator->Times10();
delta_minus->Times10();
// We optimized delta_plus to be equal to delta_minus (if they share the
// same value). So don't multiply delta_plus if they point to the same
// object.
if (delta_minus != delta_plus) {
delta_plus->Times10();
}
} else if (in_delta_room_minus && in_delta_room_plus) {
// Let's see if 2*numerator < denominator.
// If yes, then the next digit would be < 5 and we can round down.
int compare = Bignum::PlusCompare(*numerator, *numerator, *denominator);
if (compare < 0) {
// Remaining digits are less than .5. -> Round down (== do nothing).
} else if (compare > 0) {
// Remaining digits are more than .5 of denominator. -> Round up.
// Note that the last digit could not be a '9' as otherwise the whole
// loop would have stopped earlier.
// We still have an assert here in case the preconditions were not
// satisfied.
ASSERT(buffer[(*length) - 1] != '9');
buffer[(*length) - 1]++;
} else {
// Halfway case.
// TODO(floitsch): need a way to solve half-way cases.
// For now let's round towards even (since this is what Gay seems to
// do).
if ((buffer[(*length) - 1] - '0') % 2 == 0) {
// Round down => Do nothing.
} else {
ASSERT(buffer[(*length) - 1] != '9');
buffer[(*length) - 1]++;
}
}
return;
} else if (in_delta_room_minus) {
// Round down (== do nothing).
return;
} else { // in_delta_room_plus
// Round up.
// Note again that the last digit could not be '9' since this would have
// stopped the loop earlier.
// We still have an ASSERT here, in case the preconditions were not
// satisfied.
ASSERT(buffer[(*length) -1] != '9');
buffer[(*length) - 1]++;
return;
}
}
}
// Let v = numerator / denominator < 10.
// Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
// from left to right. Once 'count' digits have been produced we decide wether
// to round up or down. Remainders of exactly .5 round upwards. Numbers such
// as 9.999999 propagate a carry all the way, and change the
// exponent (decimal_point), when rounding upwards.
static void GenerateCountedDigits(int count, int* decimal_point,
Bignum* numerator, Bignum* denominator,
Vector<char>(buffer), int* length) {
ASSERT(count >= 0);
for (int i = 0; i < count - 1; ++i) {
uint16_t digit;
digit = numerator->DivideModuloIntBignum(*denominator);
ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
// digit = numerator / denominator (integer division).
// numerator = numerator % denominator.
buffer[i] = digit + '0';
// Prepare for next iteration.
numerator->Times10();
}
// Generate the last digit.
uint16_t digit;
digit = numerator->DivideModuloIntBignum(*denominator);
if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
digit++;
}
buffer[count - 1] = digit + '0';
// Correct bad digits (in case we had a sequence of '9's). Propagate the
// carry until we hat a non-'9' or til we reach the first digit.
for (int i = count - 1; i > 0; --i) {
if (buffer[i] != '0' + 10) break;
buffer[i] = '0';
buffer[i - 1]++;
}
if (buffer[0] == '0' + 10) {
// Propagate a carry past the top place.
buffer[0] = '1';
(*decimal_point)++;
}
*length = count;
}
// Generates 'requested_digits' after the decimal point. It might omit
// trailing '0's. If the input number is too small then no digits at all are
// generated (ex.: 2 fixed digits for 0.00001).
//
// Input verifies: 1 <= (numerator + delta) / denominator < 10.
static void BignumToFixed(int requested_digits, int* decimal_point,
Bignum* numerator, Bignum* denominator,
Vector<char>(buffer), int* length) {
// Note that we have to look at more than just the requested_digits, since
// a number could be rounded up. Example: v=0.5 with requested_digits=0.
// Even though the power of v equals 0 we can't just stop here.
if (-(*decimal_point) > requested_digits) {
// The number is definitively too small.
// Ex: 0.001 with requested_digits == 1.
// Set decimal-point to -requested_digits. This is what Gay does.
// Note that it should not have any effect anyways since the string is
// empty.
*decimal_point = -requested_digits;
*length = 0;
return;
} else if (-(*decimal_point) == requested_digits) {
// We only need to verify if the number rounds down or up.
// Ex: 0.04 and 0.06 with requested_digits == 1.
ASSERT(*decimal_point == -requested_digits);
// Initially the fraction lies in range (1, 10]. Multiply the denominator
// by 10 so that we can compare more easily.
denominator->Times10();
if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
// If the fraction is >= 0.5 then we have to include the rounded
// digit.
buffer[0] = '1';
*length = 1;
(*decimal_point)++;
} else {
// Note that we caught most of similar cases earlier.
*length = 0;
}
return;
} else {
// The requested digits correspond to the digits after the point.
// The variable 'needed_digits' includes the digits before the point.
int needed_digits = (*decimal_point) + requested_digits;
GenerateCountedDigits(needed_digits, decimal_point,
numerator, denominator,
buffer, length);
}
}
// Returns an estimation of k such that 10^(k-1) <= v < 10^k where
// v = f * 2^exponent and 2^52 <= f < 2^53.
// v is hence a normalized double with the given exponent. The output is an
// approximation for the exponent of the decimal approimation .digits * 10^k.
//
// The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
// Note: this property holds for v's upper boundary m+ too.
// 10^k <= m+ < 10^k+1.
// (see explanation below).
//
// Examples:
// EstimatePower(0) => 16
// EstimatePower(-52) => 0
//
// Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0.
static int EstimatePower(int exponent) {
// This function estimates log10 of v where v = f*2^e (with e == exponent).
// Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)).
// Note that f is bounded by its container size. Let p = 53 (the double's
// significand size). Then 2^(p-1) <= f < 2^p.
//
// Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close
// to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)).
// The computed number undershoots by less than 0.631 (when we compute log3
// and not log10).
//
// Optimization: since we only need an approximated result this computation
// can be performed on 64 bit integers. On x86/x64 architecture the speedup is
// not really measurable, though.
//
// Since we want to avoid overshooting we decrement by 1e10 so that
// floating-point imprecisions don't affect us.
//
// Explanation for v's boundary m+: the computation takes advantage of
// the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement
// (even for denormals where the delta can be much more important).
const double k1Log10 = 0.30102999566398114; // 1/lg(10)
// For doubles len(f) == 53 (don't forget the hidden bit).
const int kSignificandSize = 53;
double estimate =
std::ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10);
return static_cast<int>(estimate);
}
// See comments for InitialScaledStartValues.
static void InitialScaledStartValuesPositiveExponent(
double v, int estimated_power, bool need_boundary_deltas,
Bignum* numerator, Bignum* denominator,
Bignum* delta_minus, Bignum* delta_plus) {
// A positive exponent implies a positive power.
ASSERT(estimated_power >= 0);
// Since the estimated_power is positive we simply multiply the denominator
// by 10^estimated_power.
// numerator = v.
numerator->AssignUInt64(Double(v).Significand());
numerator->ShiftLeft(Double(v).Exponent());
// denominator = 10^estimated_power.
denominator->AssignPowerUInt16(10, estimated_power);
if (need_boundary_deltas) {
// Introduce a common denominator so that the deltas to the boundaries are
// integers.
denominator->ShiftLeft(1);
numerator->ShiftLeft(1);
// Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
// denominator (of 2) delta_plus equals 2^e.
delta_plus->AssignUInt16(1);
delta_plus->ShiftLeft(Double(v).Exponent());
// Same for delta_minus (with adjustments below if f == 2^p-1).
delta_minus->AssignUInt16(1);
delta_minus->ShiftLeft(Double(v).Exponent());
// If the significand (without the hidden bit) is 0, then the lower
// boundary is closer than just half a ulp (unit in the last place).
// There is only one exception: if the next lower number is a denormal then
// the distance is 1 ulp. This cannot be the case for exponent >= 0 (but we
// have to test it in the other function where exponent < 0).
uint64_t v_bits = Double(v).AsUint64();
if ((v_bits & Double::kSignificandMask) == 0) {
// The lower boundary is closer at half the distance of "normal" numbers.
// Increase the common denominator and adapt all but the delta_minus.
denominator->ShiftLeft(1); // *2
numerator->ShiftLeft(1); // *2
delta_plus->ShiftLeft(1); // *2
}
}
}
// See comments for InitialScaledStartValues
static void InitialScaledStartValuesNegativeExponentPositivePower(
double v, int estimated_power, bool need_boundary_deltas,
Bignum* numerator, Bignum* denominator,
Bignum* delta_minus, Bignum* delta_plus) {
uint64_t significand = Double(v).Significand();
int exponent = Double(v).Exponent();
// v = f * 2^e with e < 0, and with estimated_power >= 0.
// This means that e is close to 0 (have a look at how estimated_power is
// computed).
// numerator = significand
// since v = significand * 2^exponent this is equivalent to
// numerator = v * / 2^-exponent
numerator->AssignUInt64(significand);
// denominator = 10^estimated_power * 2^-exponent (with exponent < 0)
denominator->AssignPowerUInt16(10, estimated_power);
denominator->ShiftLeft(-exponent);
if (need_boundary_deltas) {
// Introduce a common denominator so that the deltas to the boundaries are
// integers.
denominator->ShiftLeft(1);
numerator->ShiftLeft(1);
// Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
// denominator (of 2) delta_plus equals 2^e.
// Given that the denominator already includes v's exponent the distance
// to the boundaries is simply 1.
delta_plus->AssignUInt16(1);
// Same for delta_minus (with adjustments below if f == 2^p-1).
delta_minus->AssignUInt16(1);
// If the significand (without the hidden bit) is 0, then the lower
// boundary is closer than just one ulp (unit in the last place).
// There is only one exception: if the next lower number is a denormal
// then the distance is 1 ulp. Since the exponent is close to zero
// (otherwise estimated_power would have been negative) this cannot happen
// here either.
uint64_t v_bits = Double(v).AsUint64();
if ((v_bits & Double::kSignificandMask) == 0) {
// The lower boundary is closer at half the distance of "normal" numbers.
// Increase the denominator and adapt all but the delta_minus.
denominator->ShiftLeft(1); // *2
numerator->ShiftLeft(1); // *2
delta_plus->ShiftLeft(1); // *2
}
}
}
// See comments for InitialScaledStartValues
static void InitialScaledStartValuesNegativeExponentNegativePower(
double v, int estimated_power, bool need_boundary_deltas,
Bignum* numerator, Bignum* denominator,
Bignum* delta_minus, Bignum* delta_plus) {
const uint64_t kMinimalNormalizedExponent =
V8_2PART_UINT64_C(0x00100000, 00000000);
uint64_t significand = Double(v).Significand();
int exponent = Double(v).Exponent();
// Instead of multiplying the denominator with 10^estimated_power we
// multiply all values (numerator and deltas) by 10^-estimated_power.
// Use numerator as temporary container for power_ten.
Bignum* power_ten = numerator;
power_ten->AssignPowerUInt16(10, -estimated_power);
if (need_boundary_deltas) {
// Since power_ten == numerator we must make a copy of 10^estimated_power
// before we complete the computation of the numerator.
// delta_plus = delta_minus = 10^estimated_power
delta_plus->AssignBignum(*power_ten);
delta_minus->AssignBignum(*power_ten);
}
// numerator = significand * 2 * 10^-estimated_power
// since v = significand * 2^exponent this is equivalent to
// numerator = v * 10^-estimated_power * 2 * 2^-exponent.
// Remember: numerator has been abused as power_ten. So no need to assign it
// to itself.
ASSERT(numerator == power_ten);
numerator->MultiplyByUInt64(significand);
// denominator = 2 * 2^-exponent with exponent < 0.
denominator->AssignUInt16(1);
denominator->ShiftLeft(-exponent);
if (need_boundary_deltas) {
// Introduce a common denominator so that the deltas to the boundaries are
// integers.
numerator->ShiftLeft(1);
denominator->ShiftLeft(1);
// With this shift the boundaries have their correct value, since
// delta_plus = 10^-estimated_power, and
// delta_minus = 10^-estimated_power.
// These assignments have been done earlier.
// The special case where the lower boundary is twice as close.
// This time we have to look out for the exception too.
uint64_t v_bits = Double(v).AsUint64();
if ((v_bits & Double::kSignificandMask) == 0 &&
// The only exception where a significand == 0 has its boundaries at
// "normal" distances:
(v_bits & Double::kExponentMask) != kMinimalNormalizedExponent) {
numerator->ShiftLeft(1); // *2
denominator->ShiftLeft(1); // *2
delta_plus->ShiftLeft(1); // *2
}
}
}
// Let v = significand * 2^exponent.
// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
// and denominator. The functions GenerateShortestDigits and
// GenerateCountedDigits will then convert this ratio to its decimal
// representation d, with the required accuracy.
// Then d * 10^estimated_power is the representation of v.
// (Note: the fraction and the estimated_power might get adjusted before
// generating the decimal representation.)
//
// The initial start values consist of:
// - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power.
// - a scaled (common) denominator.
// optionally (used by GenerateShortestDigits to decide if it has the shortest
// decimal converting back to v):
// - v - m-: the distance to the lower boundary.
// - m+ - v: the distance to the upper boundary.
//
// v, m+, m-, and therefore v - m- and m+ - v all share the same denominator.
//
// Let ep == estimated_power, then the returned values will satisfy:
// v / 10^ep = numerator / denominator.
// v's boundarys m- and m+:
// m- / 10^ep == v / 10^ep - delta_minus / denominator
// m+ / 10^ep == v / 10^ep + delta_plus / denominator
// Or in other words:
// m- == v - delta_minus * 10^ep / denominator;
// m+ == v + delta_plus * 10^ep / denominator;
//
// Since 10^(k-1) <= v < 10^k (with k == estimated_power)
// or 10^k <= v < 10^(k+1)
// we then have 0.1 <= numerator/denominator < 1
// or 1 <= numerator/denominator < 10
//
// It is then easy to kickstart the digit-generation routine.
//
// The boundary-deltas are only filled if need_boundary_deltas is set.
static void InitialScaledStartValues(double v,
int estimated_power,
bool need_boundary_deltas,
Bignum* numerator,
Bignum* denominator,
Bignum* delta_minus,
Bignum* delta_plus) {
if (Double(v).Exponent() >= 0) {
InitialScaledStartValuesPositiveExponent(
v, estimated_power, need_boundary_deltas,
numerator, denominator, delta_minus, delta_plus);
} else if (estimated_power >= 0) {
InitialScaledStartValuesNegativeExponentPositivePower(
v, estimated_power, need_boundary_deltas,
numerator, denominator, delta_minus, delta_plus);
} else {
InitialScaledStartValuesNegativeExponentNegativePower(
v, estimated_power, need_boundary_deltas,
numerator, denominator, delta_minus, delta_plus);
}
}
// This routine multiplies numerator/denominator so that its values lies in the
// range 1-10. That is after a call to this function we have:
// 1 <= (numerator + delta_plus) /denominator < 10.
// Let numerator the input before modification and numerator' the argument
// after modification, then the output-parameter decimal_point is such that
// numerator / denominator * 10^estimated_power ==
// numerator' / denominator' * 10^(decimal_point - 1)
// In some cases estimated_power was too low, and this is already the case. We
// then simply adjust the power so that 10^(k-1) <= v < 10^k (with k ==
// estimated_power) but do not touch the numerator or denominator.
// Otherwise the routine multiplies the numerator and the deltas by 10.
static void FixupMultiply10(int estimated_power, bool is_even,
int* decimal_point,
Bignum* numerator, Bignum* denominator,
Bignum* delta_minus, Bignum* delta_plus) {
bool in_range;
if (is_even) {
// For IEEE doubles half-way cases (in decimal system numbers ending with 5)
// are rounded to the closest floating-point number with even significand.
in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
} else {
in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
}
if (in_range) {
// Since numerator + delta_plus >= denominator we already have
// 1 <= numerator/denominator < 10. Simply update the estimated_power.
*decimal_point = estimated_power + 1;
} else {
*decimal_point = estimated_power;
numerator->Times10();
if (Bignum::Equal(*delta_minus, *delta_plus)) {
delta_minus->Times10();
delta_plus->AssignBignum(*delta_minus);
} else {
delta_minus->Times10();
delta_plus->Times10();
}
}
}
} } // namespace v8::internal
| jiachenning/fibjs | vender/src/v8/src/bignum-dtoa.cc | C++ | gpl-3.0 | 26,817 |
/*******************************************************************************
* file name: same_tree.cpp
* author: hui chen. (c) 17
* mail: chenhui13@baidu.com
* created time: 17/11/07-11:11
* modified time: 17/11/07-11:11
*******************************************************************************/
#include <iostream>
#include <stack>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p==NULL || q==NULL)
return p==q;
if (p->val == q->val)
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
else
return false;
/*
stack<TreeNode*> mystack;
TreeNode *p_left = NULL;
TreeNode *p_right = NULL;
if (p->val == q->val)
{
if(p->left)
{
re
}
}
*/
}
};
int main()
{
}
| wisehead/Leetcode | 24.DFS_1/0100.Same_Tree.Tree_DepthFirstSearch.Easy/same_tree.recursive.cpp | C++ | gpl-3.0 | 1,331 |
using System;
using System.Collections.Generic;
using NzbDrone.Core.Datastore;
using NzbDrone.Core.Download.TrackedDownloads;
using NzbDrone.Core.Indexers;
using NzbDrone.Core.Languages;
using NzbDrone.Core.Movies;
using NzbDrone.Core.Parser.Model;
using NzbDrone.Core.Qualities;
namespace NzbDrone.Core.Queue
{
public class Queue : ModelBase
{
public Movie Movie { get; set; }
public List<Language> Languages { get; set; }
public QualityModel Quality { get; set; }
public decimal Size { get; set; }
public string Title { get; set; }
public decimal Sizeleft { get; set; }
public TimeSpan? Timeleft { get; set; }
public DateTime? EstimatedCompletionTime { get; set; }
public string Status { get; set; }
public TrackedDownloadStatus? TrackedDownloadStatus { get; set; }
public TrackedDownloadState? TrackedDownloadState { get; set; }
public List<TrackedDownloadStatusMessage> StatusMessages { get; set; }
public string DownloadId { get; set; }
public RemoteMovie RemoteMovie { get; set; }
public DownloadProtocol Protocol { get; set; }
public string DownloadClient { get; set; }
public string Indexer { get; set; }
public string OutputPath { get; set; }
public string ErrorMessage { get; set; }
}
}
| Radarr/Radarr | src/NzbDrone.Core/Queue/Queue.cs | C# | gpl-3.0 | 1,362 |
#include "equipmentList_common.hh"
#include "MiceDAQMessanger.hh"
#include "DAQManager.hh"
#include "EventBuildManager.hh"
#include "MDprocessor.h"
#include "MDfragmentDBB.h"
#include "MDpartEventV1731.h"
#include "MDprocessManager.h"
#include "DBBDataProcessor.hh"
#include "V1731DataProcessor.hh"
#include "DBBSpillData.hh"
#include "EMRDaq.hh"
#include "DAQData.hh"
#include "Spill.hh"
#include "TFile.h"
#include "TTree.h"
using namespace std;
MAUS::Spill *spill;
MAUS::DAQData *data;
// MAUS::EMRDaq *emr;
MAUS::DBBArray *dbb;
MAUS::V1731PartEventArray *v1731spill;
DBBDataProcessor *dbbProc;
V1731DataProcessor *v1731Proc;
TFile *dataFile;
TTree *dataTree;
DAQManager *myDAQ;
EventBuildManager *eventBuilder;
MiceDAQMessanger *messanger;
void start_of_run(int i) {
*(messanger->getStream()) << "-----> \nThis is Start of Run " << i << endl;
messanger->sendMessage(MDE_DEBUGGING);
stringstream ss_rf;
ss_rf << "../data_tmp/EMRdata_" << i << ".root";
// cout << ss_rf.str() << endl;
dataFile = new TFile(ss_rf.str().c_str(),"RECREATE","EMR Cosmoc data");
dataTree = new TTree("EMRCosmicData", "EMR Cosmic test Data");
// spill = new MAUS::Spill();
data = new MAUS::DAQData;
// emr = new MAUS::EMRDaq;
dbb = new MAUS::DBBArray;
v1731spill = new MAUS::V1731PartEventArray;
dbbProc->set_spill(dbb);
v1731Proc->set_spill(v1731spill);
dataTree->Branch("Spill", &data);
}
void end_of_run(int i) {
*(messanger->getStream()) << "-----> \nThis is End of Run " << i;
messanger->sendMessage(MDE_DEBUGGING);
dataTree->Write();
dataFile->Close();
}
void start_of_spill(int i) {
*(messanger->getStream()) << "-----> \nThis is Start of Spill " << i << endl;
messanger->sendMessage(MDE_DEBUGGING);
// dbb->resize(0);
// v1731spill->resize(0);
}
void end_of_spill(int i) {
*(messanger->getStream()) << "-----> \nThis is End of Spill " << i << endl;
messanger->sendMessage(MDE_DEBUGGING);
dbb->resize(0);
v1731spill->resize(0);
myDAQ->Process();
// if (dbb->size()==2) {
// (*dbb)[0].print();
// (*dbb)[1].print();
// }
MAUS::EMRDaq emr;
emr.SetDBBArray(*dbb);
emr.SetV1731PartEventArray(*v1731spill);
data->SetEMRDaq(emr);
dataTree->Fill();
}
int main(int argc, char** argv) {
int run_count(0);
if (argc==2) {
stringstream ss;
ss << argv[1];
ss >> run_count;
}
MDprocessManager proc_manager;
messanger = MiceDAQMessanger::Instance();
messanger->setVerbosity(1);
myDAQ = new DAQManager();
eventBuilder = new EventBuildManager();
dbbProc = new DBBDataProcessor();
dbbProc->SetProcessManager(&proc_manager);
// dbbProc->set_debug_mode(true);
v1731Proc = new V1731DataProcessor();
v1731Proc->SetProcessManager(&proc_manager);
// MDequipMap::Dump();
myDAQ->SetFragmentProc("DBB", dbbProc);
myDAQ->SetPartEventProc("V1731", v1731Proc);
myDAQ->DumpProcessors();
myDAQ->MemBankInit(1024*1024);
eventBuilder->SetDataPtr(myDAQ->getDataPtr());
eventBuilder->SetRunCount(run_count);
eventBuilder->SetOnStartOfRunDo(&start_of_run);
eventBuilder->SetOnEndOfRunDo(&end_of_run);
// eventBuilder->SetOnStartOfSpillDo(&start_of_spill);
eventBuilder->SetOnEndOfSpillDo(&end_of_spill);
eventBuilder->Go();
delete myDAQ;
delete eventBuilder;
delete dbbProc;
delete v1731Proc;
return 1;
}
| yordan-karadzhov/equipmentlist-mice | src/devel/eventbuild.cc | C++ | gpl-3.0 | 3,452 |
// Copyright CERN and copyright holders of ALICE O2. This software is
// distributed under the terms of the GNU General Public License v3 (GPL
// Version 3), copied verbatim in the file "COPYING".
//
// See http://alice-o2.web.cern.ch/license for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
#include "log.h"
#include <CL/cl.h>
#include <unordered_map>
namespace gpucf
{
namespace log
{
#define ERR_STR_PAIR(err) \
{ \
err, #err \
}
std::string clErrToStr(cl_int errcode)
{
static const std::unordered_map<int, std::string> mapErrToStr =
{
ERR_STR_PAIR(CL_SUCCESS),
ERR_STR_PAIR(CL_DEVICE_NOT_FOUND),
ERR_STR_PAIR(CL_DEVICE_NOT_AVAILABLE),
ERR_STR_PAIR(CL_COMPILER_NOT_AVAILABLE),
ERR_STR_PAIR(CL_MEM_OBJECT_ALLOCATION_FAILURE),
ERR_STR_PAIR(CL_OUT_OF_RESOURCES),
ERR_STR_PAIR(CL_OUT_OF_HOST_MEMORY),
ERR_STR_PAIR(CL_PROFILING_INFO_NOT_AVAILABLE),
ERR_STR_PAIR(CL_MEM_COPY_OVERLAP),
ERR_STR_PAIR(CL_IMAGE_FORMAT_MISMATCH),
ERR_STR_PAIR(CL_IMAGE_FORMAT_NOT_SUPPORTED),
ERR_STR_PAIR(CL_BUILD_PROGRAM_FAILURE),
ERR_STR_PAIR(CL_MAP_FAILURE),
ERR_STR_PAIR(CL_MISALIGNED_SUB_BUFFER_OFFSET),
ERR_STR_PAIR(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST),
ERR_STR_PAIR(CL_COMPILE_PROGRAM_FAILURE),
ERR_STR_PAIR(CL_LINKER_NOT_AVAILABLE),
ERR_STR_PAIR(CL_LINK_PROGRAM_FAILURE),
ERR_STR_PAIR(CL_DEVICE_PARTITION_FAILED),
ERR_STR_PAIR(CL_KERNEL_ARG_INFO_NOT_AVAILABLE),
ERR_STR_PAIR(CL_INVALID_VALUE),
ERR_STR_PAIR(CL_INVALID_DEVICE_TYPE),
ERR_STR_PAIR(CL_INVALID_PLATFORM),
ERR_STR_PAIR(CL_INVALID_DEVICE),
ERR_STR_PAIR(CL_INVALID_CONTEXT),
ERR_STR_PAIR(CL_INVALID_QUEUE_PROPERTIES),
ERR_STR_PAIR(CL_INVALID_COMMAND_QUEUE),
ERR_STR_PAIR(CL_INVALID_HOST_PTR),
ERR_STR_PAIR(CL_INVALID_MEM_OBJECT),
ERR_STR_PAIR(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR),
ERR_STR_PAIR(CL_INVALID_IMAGE_SIZE),
ERR_STR_PAIR(CL_INVALID_SAMPLER),
ERR_STR_PAIR(CL_INVALID_BINARY),
ERR_STR_PAIR(CL_INVALID_BUILD_OPTIONS),
ERR_STR_PAIR(CL_INVALID_PROGRAM),
ERR_STR_PAIR(CL_INVALID_PROGRAM_EXECUTABLE),
ERR_STR_PAIR(CL_INVALID_KERNEL_NAME),
ERR_STR_PAIR(CL_INVALID_KERNEL_DEFINITION),
ERR_STR_PAIR(CL_INVALID_KERNEL),
ERR_STR_PAIR(CL_INVALID_ARG_INDEX),
ERR_STR_PAIR(CL_INVALID_ARG_VALUE),
ERR_STR_PAIR(CL_INVALID_ARG_SIZE),
ERR_STR_PAIR(CL_INVALID_KERNEL_ARGS),
ERR_STR_PAIR(CL_INVALID_WORK_DIMENSION),
ERR_STR_PAIR(CL_INVALID_WORK_GROUP_SIZE),
ERR_STR_PAIR(CL_INVALID_WORK_ITEM_SIZE),
ERR_STR_PAIR(CL_INVALID_GLOBAL_OFFSET),
ERR_STR_PAIR(CL_INVALID_EVENT_WAIT_LIST),
ERR_STR_PAIR(CL_INVALID_EVENT),
ERR_STR_PAIR(CL_INVALID_OPERATION),
ERR_STR_PAIR(CL_INVALID_GL_OBJECT),
ERR_STR_PAIR(CL_INVALID_BUFFER_SIZE),
ERR_STR_PAIR(CL_INVALID_MIP_LEVEL),
ERR_STR_PAIR(CL_INVALID_GLOBAL_WORK_SIZE),
ERR_STR_PAIR(CL_INVALID_PROPERTY),
ERR_STR_PAIR(CL_INVALID_IMAGE_DESCRIPTOR),
ERR_STR_PAIR(CL_INVALID_COMPILER_OPTIONS),
ERR_STR_PAIR(CL_INVALID_LINKER_OPTIONS),
ERR_STR_PAIR(CL_INVALID_DEVICE_PARTITION_COUNT),
ERR_STR_PAIR(CL_INVALID_PIPE_SIZE),
ERR_STR_PAIR(CL_INVALID_DEVICE_QUEUE),
};
auto got = mapErrToStr.find(errcode);
if (got == mapErrToStr.end()) {
return "UNKNOWN_ERROR";
}
return got->second;
}
const char* levelToStr(Level lvl)
{
switch (lvl) {
case Level::Debug:
return "[Debug]";
case Level::Info:
return "[Info ]";
case Level::Error:
return "[Error]";
}
return "";
}
std::ostream& operator<<(std::ostream& o, Level lvl)
{
return o << levelToStr(lvl);
}
} // namespace log
} // namespace gpucf
// vim: set ts=4 sw=4 sts=4 expandtab:
| AllaMaevskaya/AliceO2 | GPU/GPUTracking/gpucf/src/gpucf/common/log.cpp | C++ | gpl-3.0 | 4,052 |
/*
* This file is generated and updated by Sencha Cmd. You can edit this file as
* needed for your application, but these edits will have to be merged by
* Sencha Cmd when upgrading.
*/
Ext.application({
name: 'LPB',
extend: 'LPB.Application',
requires: [
'LPB.util.sha256',
'Ext.plugin.Viewport',
'Ext.list.Tree',
'LPB.view.login.Login',
'LPB.view.admin.Main',
'LPB.view.user.User',
'Ext.container.Container',
'Ext.layout.container.Anchor',
'Ext.sunfield.imageUploader.ImageUploader',
'Ext.sunfield.locationSelect.LocationSelect',
'Ext.sunfield.imageField.ImageField',
'Ext.sunfield.imageField.DatesField',
'Ext.sunfield.DateSlider',
'Ext.sunfield.sunEditor.SunEditor',
'Ext.sunfield.mruImages.MruImages',
'Ext.sunfield.groupEditor.GroupEditor',
'Ext.ux.form.ItemSelector'
]
// The name of the initial view to create. With the classic toolkit this class
// will gain a "viewport" plugin if it does not extend Ext.Viewport. With the
// modern toolkit, the main view will be added to the Viewport.
//
//mainView: 'LPB.view.main.Main'
//-------------------------------------------------------------------------
// Most customizations should be made to LPB.Application. If you need to
// customize this file, doing so below this section reduces the likelihood
// of merge conflicts when upgrading to new versions of Sencha Cmd.
//-------------------------------------------------------------------------
});
| Lytjepole/Lytjepole-Beheer | LPB/app.js | JavaScript | gpl-3.0 | 1,604 |
<h1><?=$this->getTrans('settings') ?></h1>
<form class="form-horizontal" method="POST">
<?=$this->getTokenField() ?>
<div class="form-group <?=$this->validation()->hasError('articlesPerPage') ? 'has-error' : '' ?>">
<label for="articlesPerPageInput" class="col-lg-2 control-label">
<?=$this->getTrans('articlesPerPage') ?>
</label>
<div class="col-lg-1">
<input type="number"
class="form-control"
id="articlesPerPageInput"
name="articlesPerPage"
min="1"
value="<?=($this->get('articlesPerPage') != '') ? $this->escape($this->get('articlesPerPage')) : $this->originalInput('articlesPerPage') ?>" />
</div>
</div>
<div class="form-group <?=$this->validation()->hasError('articleRating') ? 'has-error' : '' ?>">
<div class="col-lg-2 control-label">
<?=$this->getTrans('articleRating') ?>
</div>
<div class="col-lg-4">
<div class="flipswitch">
<input type="radio" class="flipswitch-input" id="articleRating-on" name="articleRating" value="1" <?php if ($this->get('articleRating') == '1') { echo 'checked="checked"'; } ?> />
<label for="articleRating-on" class="flipswitch-label flipswitch-label-on"><?=$this->getTrans('on') ?></label>
<input type="radio" class="flipswitch-input" id="articleRating-off" name="articleRating" value="0" <?php if ($this->get('articleRating') != '1') { echo 'checked="checked"'; } ?> />
<label for="articleRating-off" class="flipswitch-label flipswitch-label-off"><?=$this->getTrans('off') ?></label>
<span class="flipswitch-selection"></span>
</div>
</div>
</div>
<div class="form-group <?=$this->validation()->hasError('disableComments') ? 'has-error' : '' ?>">
<div class="col-lg-2 control-label">
<?=$this->getTrans('disableComments') ?>
</div>
<div class="col-lg-4">
<div class="flipswitch">
<input type="radio" class="flipswitch-input" id="disableComments-on" name="disableComments" value="1" <?php if ($this->get('disableComments') == '1') { echo 'checked="checked"'; } ?> />
<label for="disableComments-on" class="flipswitch-label flipswitch-label-on"><?=$this->getTrans('on') ?></label>
<input type="radio" class="flipswitch-input" id="disableComments-off" name="disableComments" value="0" <?php if ($this->get('disableComments') != '1') { echo 'checked="checked"'; } ?> />
<label for="disableComments-off" class="flipswitch-label flipswitch-label-off"><?=$this->getTrans('off') ?></label>
<span class="flipswitch-selection"></span>
</div>
</div>
</div>
<h2><?=$this->getTrans('boxSettings') ?></h2>
<b><?=$this->getTrans('boxArticle') ?></b>
<div class="form-group <?=$this->validation()->hasError('boxArticleLimit') ? 'has-error' : '' ?>">
<label for="boxArticleLimit" class="col-lg-2 control-label">
<?=$this->getTrans('boxArticleLimit') ?>
</label>
<div class="col-lg-1">
<input type="number"
class="form-control"
id="boxArticleLimit"
name="boxArticleLimit"
min="1"
value="<?=($this->get('boxArticleLimit') != '') ? $this->escape($this->get('boxArticleLimit')) : $this->originalInput('boxArticleLimit') ?>" />
</div>
</div>
<b><?=$this->getTrans('boxArchive') ?></b>
<div class="form-group <?=$this->validation()->hasError('boxArchiveLimit') ? 'has-error' : '' ?>">
<label for="boxArchiveLimit" class="col-lg-2 control-label">
<?=$this->getTrans('boxArchiveLimit') ?>
</label>
<div class="col-lg-1">
<input type="number"
class="form-control"
id="boxArchiveLimit"
name="boxArchiveLimit"
min="1"
value="<?=($this->get('boxArchiveLimit') != '') ? $this->escape($this->get('boxArchiveLimit')) : $this->originalInput('boxArchiveLimit') ?>" />
</div>
</div>
<b><?=$this->getTrans('boxKeywords') ?></b>
<div class="form-group <?=$this->validation()->hasError('boxKeywordsH2') ? 'has-error' : '' ?>">
<label for="boxKeywordsH2" class="col-lg-2 control-label">
<?=$this->getTrans('boxKeywordsH2') ?>
</label>
<div class="col-lg-1">
<input type="number"
class="form-control"
id="boxKeywordsH2"
name="boxKeywordsH2"
min="1"
value="<?=($this->get('boxKeywordsH2') != '') ? $this->escape($this->get('boxKeywordsH2')) : $this->originalInput('boxKeywordsH2') ?>"
required />
</div>
</div>
<div class="form-group <?=$this->validation()->hasError('boxKeywordsH3') ? 'has-error' : '' ?>">
<label for="boxKeywordsH3" class="col-lg-2 control-label">
<?=$this->getTrans('boxKeywordsH3') ?>
</label>
<div class="col-lg-1">
<input type="number"
class="form-control"
id="boxKeywordsH3"
name="boxKeywordsH3"
min="1"
value="<?=($this->get('boxKeywordsH3') != '') ? $this->escape($this->get('boxKeywordsH3')) : $this->originalInput('boxKeywordsH3') ?>"
required />
</div>
</div>
<div class="form-group <?=$this->validation()->hasError('boxKeywordsH4') ? 'has-error' : '' ?>">
<label for="boxKeywordsH4" class="col-lg-2 control-label">
<?=$this->getTrans('boxKeywordsH4') ?>
</label>
<div class="col-lg-1">
<input type="number"
class="form-control"
id="boxKeywordsH4"
name="boxKeywordsH4"
min="1"
value="<?=($this->get('boxKeywordsH4') != '') ? $this->escape($this->get('boxKeywordsH4')) : $this->originalInput('boxKeywordsH4') ?>"
required />
</div>
</div>
<div class="form-group <?=$this->validation()->hasError('boxKeywordsH5') ? 'has-error' : '' ?>">
<label for="boxKeywordsH5" class="col-lg-2 control-label">
<?=$this->getTrans('boxKeywordsH5') ?>
</label>
<div class="col-lg-1">
<input type="number"
class="form-control"
id="boxKeywordsH5"
name="boxKeywordsH5"
min="1"
value="<?=($this->get('boxKeywordsH5') != '') ? $this->escape($this->get('boxKeywordsH5')) : $this->originalInput('boxKeywordsH5') ?>"
required />
</div>
</div>
<?=$this->getSaveBar() ?>
</form>
| dastiii/Ilch-2.0 | application/modules/article/views/admin/settings/index.php | PHP | gpl-3.0 | 7,007 |
// ***************************************************************************
// BamMultiReader.cpp (c) 2010 Erik Garrison, Derek Barnett
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 14 January 2013 (DB)
// ---------------------------------------------------------------------------
// Convenience class for reading multiple BAM files.
//
// This functionality allows applications to work on very large sets of files
// without requiring intermediate merge, sort, and index steps for each file
// subset. It also improves the performance of our merge system as it
// precludes the need to sort merged files.
// ***************************************************************************
#include "bamtools/api/BamMultiReader.h"
#include "internal/bam/BamMultiReader_p.h"
using namespace BamTools;
#include <string>
#include <vector>
using namespace std;
/*! \class BamTools::BamMultiReader
\brief Convenience class for reading multiple BAM files.
*/
/*! \enum BamMultiReader::MergeOrder
\brief Used to describe the merge strategy of the BamMultiReader.
The merge strategy determines which alignment is 'next' from across
all opened BAM files.
*/
/*! \var BamMultiReader::MergeOrder BamMultiReader::RoundRobinMerge
\brief Merge strategy when BAM files are unsorted, or their sorted status is either unknown or ignored
*/
/*! \var BamMultiReader::MergeOrder BamMultiReader::MergeByCoordinate
\brief Merge strategy when BAM files are sorted by position ('coordinate')
*/
/*! \var BamMultiReader::MergeOrder BamMultiReader::MergeByName
\brief Merge strategy when BAM files are sorted by read name ('queryname')
*/
/*! \fn BamMultiReader::BamMultiReader(void)
\brief constructor
*/
BamMultiReader::BamMultiReader(void)
: d(new Internal::BamMultiReaderPrivate)
{ }
/*! \fn BamMultiReader::~BamMultiReader(void)
\brief destructor
*/
BamMultiReader::~BamMultiReader(void) {
delete d;
d = 0;
}
/*! \fn void BamMultiReader::Close(void)
\brief Closes all open BAM files.
Also clears out all header and reference data.
\sa CloseFile(), IsOpen(), Open(), BamReader::Close()
*/
bool BamMultiReader::Close(void) {
return d->Close();
}
/*! \fn void BamMultiReader::CloseFile(const std::string& filename)
\brief Closes requested BAM file.
Leaves any other file(s) open, along with header and reference data.
\param[in] filename name of specific BAM file to close
\sa Close(), IsOpen(), Open(), BamReader::Close()
*/
bool BamMultiReader::CloseFile(const std::string& filename) {
return d->CloseFile(filename);
}
/*! \fn bool BamMultiReader::CreateIndexes(const BamIndex::IndexType& type)
\brief Creates index files for the current BAM files.
\param[in] type file format to create, see BamIndex::IndexType for available formats
\return \c true if index files created OK
\sa LocateIndexes(), OpenIndexes(), BamReader::CreateIndex()
*/
bool BamMultiReader::CreateIndexes(const BamIndex::IndexType& type) {
return d->CreateIndexes(type);
}
/*! \fn const std::vector<std::string> BamMultiReader::Filenames(void) const
\brief Returns list of filenames for all open BAM files.
Retrieved filenames will contain whatever was passed via Open().
If you need full directory paths here, be sure to include them
when you open the BAM files.
\returns names of open BAM files. If no files are open, returns an empty vector.
\sa IsOpen(), BamReader::GetFilename()
*/
const std::vector<std::string> BamMultiReader::Filenames(void) const {
return d->Filenames();
}
/*! \fn std::string BamMultiReader::GetErrorString(void) const
\brief Returns a human-readable description of the last error that occurred
This method allows elimination of STDERR pollution. Developers of client code
may choose how the messages are displayed to the user, if at all.
\return error description
*/
std::string BamMultiReader::GetErrorString(void) const {
return d->GetErrorString();
}
/*! \fn SamHeader BamMultiReader::GetHeader(void) const
\brief Returns unified SAM-format header for all files
\note Modifying the retrieved text does NOT affect the current
BAM files. These files have been opened in a read-only mode. However,
your modified header text can be used in conjunction with BamWriter
to generate a new BAM file with the appropriate header information.
\returns header data wrapped in SamHeader object
\sa GetHeaderText(), BamReader::GetHeader()
*/
SamHeader BamMultiReader::GetHeader(void) const {
return d->GetHeader();
}
/*! \fn std::string BamMultiReader::GetHeaderText(void) const
\brief Returns unified SAM-format header text for all files
\note Modifying the retrieved text does NOT affect the current
BAM files. These files have been opened in a read-only mode. However,
your modified header text can be used in conjunction with BamWriter
to generate a new BAM file with the appropriate header information.
\returns SAM-formatted header text
\sa GetHeader(), BamReader::GetHeaderText()
*/
std::string BamMultiReader::GetHeaderText(void) const {
return d->GetHeaderText();
}
/*! \fn BamMultiReader::MergeOrder BamMultiReader::GetMergeOrder(void) const
\brief Returns curent merge order strategy.
\returns current merge order enum value
\sa BamMultiReader::MergeOrder, SetExplicitMergeOrder()
*/
BamMultiReader::MergeOrder BamMultiReader::GetMergeOrder(void) const {
return d->GetMergeOrder();
}
/*! \fn bool BamMultiReader::GetNextAlignment(BamAlignment& alignment)
\brief Retrieves next available alignment.
Equivalent to BamReader::GetNextAlignment() with respect to what is a valid
overlapping alignment and what data gets populated.
This method takes care of determining which alignment actually is 'next'
across multiple files, depending on their sort order.
\param[out] alignment destination for alignment record data
\returns \c true if a valid alignment was found
\sa GetNextAlignmentCore(), SetExplicitMergeOrder(), SetRegion(), BamReader::GetNextAlignment()
*/
bool BamMultiReader::GetNextAlignment(BamAlignment& nextAlignment) {
return d->GetNextAlignment(nextAlignment);
}
/*! \fn bool BamMultiReader::GetNextAlignmentCore(BamAlignment& alignment)
\brief Retrieves next available alignment.
Equivalent to BamReader::GetNextAlignmentCore() with respect to what is a valid
overlapping alignment and what data gets populated.
This method takes care of determining which alignment actually is 'next'
across multiple files, depending on their sort order.
\param[out] alignment destination for alignment record data
\returns \c true if a valid alignment was found
\sa GetNextAlignment(), SetExplicitMergeOrder(), SetRegion(), BamReader::GetNextAlignmentCore()
*/
bool BamMultiReader::GetNextAlignmentCore(BamAlignment& nextAlignment) {
return d->GetNextAlignmentCore(nextAlignment);
}
/*! \fn int BamMultiReader::GetReferenceCount(void) const
\brief Returns number of reference sequences.
\sa BamReader::GetReferenceCount()
*/
int BamMultiReader::GetReferenceCount(void) const {
return d->GetReferenceCount();
}
/*! \fn const RefVector& BamMultiReader::GetReferenceData(void) const
\brief Returns all reference sequence entries.
\sa RefData, BamReader::GetReferenceData()
*/
const BamTools::RefVector BamMultiReader::GetReferenceData(void) const {
return d->GetReferenceData();
}
/*! \fn int BamMultiReader::GetReferenceID(const std::string& refName) const
\brief Returns the ID of the reference with this name.
If \a refName is not found, returns -1.
\param[in] refName name of reference to look up
\sa BamReader::GetReferenceID()
*/
int BamMultiReader::GetReferenceID(const std::string& refName) const {
return d->GetReferenceID(refName);
}
/*! \fn bool BamMultiReader::HasIndexes(void) const
\brief Returns \c true if all BAM files have index data available.
\sa BamReader::HasIndex()
*/
bool BamMultiReader::HasIndexes(void) const {
return d->HasIndexes();
}
/*! \fn bool BamMultiReader::HasOpenReaders(void) const
\brief Returns \c true if there are any open BAM files.
*/
bool BamMultiReader::HasOpenReaders(void) const {
return d->HasOpenReaders();
}
/*! \fn bool BamMultiReader::Jump(int refID, int position)
\brief Performs a random-access jump within current BAM files.
This is a convenience method, equivalent to calling SetRegion()
with only a left boundary specified.
\param[in] refID ID of reference to jump to
\param[in] position (0-based) left boundary
\returns \c true if jump was successful
\sa HasIndex(), BamReader::Jump()
*/
bool BamMultiReader::Jump(int refID, int position) {
return d->Jump(refID, position);
}
/*! \fn bool BamMultiReader::LocateIndexes(const BamIndex::IndexType& preferredType)
\brief Looks for index files that match current BAM files.
Use this function when you need index files, and perhaps have a
preferred index format, but do not depend heavily on which indexes
actually get loaded at runtime.
For each BAM file, this function will defer to your \a preferredType
whenever possible. However, if an index file of \a preferredType can
not be found, then it will look for any other index file that matches
that BAM file.
An example case would look this:
\code
BamMultiReader reader;
// do setup...
// ensure that all files have an index
if ( !reader.LocateIndexes() ) // opens any existing index files that match our BAM files
reader.CreateIndexes(); // creates index files for any BAM files that still lack one
// do interesting stuff using random-access...
\endcode
If you want precise control over which index files are loaded, use OpenIndexes()
with the desired index filenames. If that function returns false, you can use
CreateIndexes() to then build index files of the exact requested format.
\param[in] preferredType desired index file format, see BamIndex::IndexType for available formats
\returns \c true if index files could be found for \b ALL open BAM files
\sa BamReader::LocateIndex()
*/
bool BamMultiReader::LocateIndexes(const BamIndex::IndexType& preferredType) {
return d->LocateIndexes(preferredType);
}
/*! \fn bool BamMultiReader::Open(const std::vector<std::string>& filenames)
\brief Opens BAM files.
\note Opening BAM files will invalidate any current region set on the multireader.
All file pointers will be returned to the beginning of the alignment data. Follow
this with Jump() or SetRegion() to establish a region of interest.
\param[in] filenames list of BAM filenames to open
\returns \c true if BAM files were opened successfully
\sa Close(), HasOpenReaders(), OpenFile(), OpenIndexes(), BamReader::Open()
*/
bool BamMultiReader::Open(const std::vector<std::string>& filenames) {
return d->Open(filenames);
}
/*! \fn bool BamMultiReader::OpenFile(const std::string& filename)
\brief Opens a single BAM file.
Adds another BAM file to multireader "on-the-fly".
\note Opening a BAM file will invalidate any current region set on the multireader.
All file pointers will be returned to the beginning of the alignment data. Follow
this with Jump() or SetRegion() to establish a region of interest.
\param[in] filename BAM filename to open
\returns \c true if BAM file was opened successfully
\sa Close(), HasOpenReaders(), Open(), OpenIndexes(), BamReader::Open()
*/
bool BamMultiReader::OpenFile(const std::string& filename) {
return d->OpenFile(filename);
}
/*! \fn bool BamMultiReader::OpenIndexes(const std::vector<std::string>& indexFilenames)
\brief Opens index files for current BAM files.
\note Currently assumes that index filenames match the order (and number) of
BAM files passed to Open().
\param[in] indexFilenames list of BAM index file names
\returns \c true if BAM index file was opened & data loaded successfully
\sa LocateIndex(), Open(), SetIndex(), BamReader::OpenIndex()
*/
bool BamMultiReader::OpenIndexes(const std::vector<std::string>& indexFilenames) {
return d->OpenIndexes(indexFilenames);
}
/*! \fn bool BamMultiReader::Rewind(void)
\brief Returns the internal file pointers to the beginning of alignment records.
Useful for performing multiple sequential passes through BAM files.
Calling this function clears any prior region that may have been set.
\returns \c true if rewind operation was successful
\sa Jump(), SetRegion(), BamReader::Rewind()
*/
bool BamMultiReader::Rewind(void) {
return d->Rewind();
}
/*! \fn void BamMultiReader::SetExplicitMergeOrder(BamMultiReader::MergeOrder order)
\brief Sets an explicit merge order, regardless of the BAM files' SO header tag.
The default behavior of the BamMultiReader is to check the SO tag in the BAM files'
SAM header text to determine the merge strategy". The merge strategy is used to
determine from which BAM file the next alignment should come when either
GetNextAlignment() or GetNextAlignmentCore() are called. If files share a
'coordinate' or 'queryname' value for this tag, then the merge strategy is
selected accordingly. If any of them do not match, or if any fileis marked as
'unsorted', then the merge strategy is simply a round-robin.
This method allows client code to explicitly override the lookup behavior. This
method can be useful when you know, for example, that your BAM files are sorted
by coordinate but upstream processes did not set the header tag properly.
\note This method should \bold not be called while reading alignments via
GetNextAlignment() or GetNextAlignmentCore(). For proper results, you should
call this method before (or immediately after) opening files, rewinding,
jumping, etc. but \bold not once alignment fetching has started. There is
nothing in the API to prevent you from doing so, but the results may be
unexpected.
\returns \c true if merge order could be successfully applied
\sa BamMultiReader::MergeOrder, GetMergeOrder(), GetNextAlignment(), GetNextAlignmentCore()
*/
bool BamMultiReader::SetExplicitMergeOrder(BamMultiReader::MergeOrder order) {
return d->SetExplicitMergeOrder(order);
}
/*! \fn bool BamMultiReader::SetRegion(const BamRegion& region)
\brief Sets a target region of interest
Equivalent to calling BamReader::SetRegion() on all open BAM files.
\warning BamRegion now represents a zero-based, HALF-OPEN interval.
In previous versions of BamTools (0.x & 1.x) all intervals were treated
as zero-based, CLOSED.
\param[in] region desired region-of-interest to activate
\returns \c true if ALL readers set the region successfully
\sa HasIndexes(), Jump(), BamReader::SetRegion()
*/
bool BamMultiReader::SetRegion(const BamRegion& region) {
return d->SetRegion(region);
}
/*! \fn bool BamMultiReader::SetRegion(const int& leftRefID,
const int& leftPosition,
const int& rightRefID,
const int& rightPosition)
\brief Sets a target region of interest
This is an overloaded function. Equivalent to calling BamReader::SetRegion() on all open BAM files.
\warning This function now expects a zero-based, HALF-OPEN interval.
In previous versions of BamTools (0.x & 1.x) all intervals were treated
as zero-based, CLOSED.
\param[in] leftRefID referenceID of region's left boundary
\param[in] leftPosition position of region's left boundary
\param[in] rightRefID reference ID of region's right boundary
\param[in] rightPosition position of region's right boundary
\returns \c true if ALL readers set the region successfully
\sa HasIndexes(), Jump(), BamReader::SetRegion()
*/
bool BamMultiReader::SetRegion(const int& leftRefID,
const int& leftPosition,
const int& rightRefID,
const int& rightPosition)
{
return d->SetRegion( BamRegion(leftRefID, leftPosition, rightRefID, rightPosition) );
}
| fw1121/Pandoras-Toolbox-for-Bioinformatics | src/SPAdes/ext/src/bamtools/api/BamMultiReader.cpp | C++ | gpl-3.0 | 16,495 |
/*
Yelo: Open Sauce SDK
Halo 1 (CE) Edition
See license\OpenSauce\Halo1_CE for specific license information
*/
#include "Common/Precompile.hpp"
#include "Rasterizer/PostProcessing/Fade/c_shader_instance_fade.hpp"
#if !PLATFORM_IS_DEDI
#include "Rasterizer/PostProcessing/c_post_processing_main.hpp"
namespace Yelo
{
namespace Rasterizer { namespace PostProcessing { namespace Fade
{
/*!
* \brief
* Sets the fade shader this class will instance.
*
* \param definition
* The fade shader this class will instance.
*
* Sets the fade shader this class will instance.
*
* \see
* c_shader_fade
*/
void c_shader_instance_fade::SetShader(c_shader_postprocess* definition)
{
m_members_fade.definition = CAST_PTR(c_shader_fade*, definition);
c_shader_instance::SetShader(definition);
}
/*!
* \brief
* Sets the shaders parameters to the current fade values.
*
* Sets the shaders parameters to the current fade values.
*/
void c_shader_instance_fade::SetShaderInstanceVariables()
{
s_shader_fade_definition* definition = m_members.definition->GetShaderDefinition<s_shader_fade_definition>();
YELO_ASSERT_DISPLAY(definition != nullptr, "Fade shader has no tag definition");
LPD3DXEFFECT effect = m_members.definition->GetEffect();
// TODO: why are we reasserting definition?
YELO_ASSERT_DISPLAY(definition != nullptr, "Fade shader has no valid effect");
definition->fade_amount_handle.SetVariable(effect, &m_members_fade.fade_amount, false);
};
/*!
* \brief
* Custom render function for fading an effects result.
*
* \param render_device
* The current render device.
*
* \param quad_instance
* The quad instance to render with.
*
* \param fade_amount
* The amount to fade the result by.
*
* \returns
* S_OK if successful, non-zero if otherwise.
*
* Custom render function for fading an effects result. The fade effect swaps the current target with the scene texture, and re draws
* it with alpha blending to fade the result in/out.
*/
HRESULT c_shader_instance_fade::Render(IDirect3DDevice9* render_device, c_quad_instance* quad_instance, real fade_amount)
{
m_members_fade.fade_amount = fade_amount;
// set the effect result as the scene texture
c_post_processing_main::Instance().Globals().scene_buffer_chain.SetSceneToLast();
// set the scene prior to the effect as the render target
c_post_processing_main::Instance().Globals().scene_buffer_chain.Flip();
// set the fade value to the shader
SetShaderInstanceVariables();
// set the render state to enable alpha blending
render_device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
render_device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA);
render_device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
render_device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
// render the effect
HRESULT hr = GetShader()->Render(render_device, quad_instance);
// reset the render state to disable alpha blending
render_device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
render_device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE);
render_device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
render_device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO);
return hr;
}
}; }; };
};
#endif | BipolarAurora/H-CE-Opensauce-V5 | OpenSauce/Halo1/Halo1_CE/Rasterizer/PostProcessing/Fade/c_shader_instance_fade.cpp | C++ | gpl-3.0 | 3,549 |
/*!
* \file gps_l1_ca_observables_cc.cc
* \brief Implementation of the pseudorange computation block for GPS L1 C/A
* \author Javier Arribas, 2011. jarribas(at)cttc.es
* -------------------------------------------------------------------------
*
* Copyright (C) 2010-2015 (see AUTHORS file for a list of contributors)
*
* GNSS-SDR is a software defined Global Navigation
* Satellite Systems receiver
*
* This file is part of GNSS-SDR.
*
* GNSS-SDR 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.
*
* GNSS-SDR 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 GNSS-SDR. If not, see <http://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*/
#include "gps_l1_ca_observables_cc.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <vector>
#include <utility>
#include <armadillo>
#include <gnuradio/io_signature.h>
#include <glog/logging.h>
#include "control_message_factory.h"
#include "gnss_synchro.h"
#include "GPS_L1_CA.h"
using google::LogMessage;
gps_l1_ca_observables_cc_sptr
gps_l1_ca_make_observables_cc(unsigned int nchannels, bool dump, std::string dump_filename, unsigned int deep_history)
{
return gps_l1_ca_observables_cc_sptr(new gps_l1_ca_observables_cc(nchannels, dump, dump_filename, deep_history));
}
gps_l1_ca_observables_cc::gps_l1_ca_observables_cc(unsigned int nchannels, bool dump, std::string dump_filename, unsigned int deep_history) :
gr::block("gps_l1_ca_observables_cc", gr::io_signature::make(nchannels, nchannels, sizeof(Gnss_Synchro)),
gr::io_signature::make(nchannels, nchannels, sizeof(Gnss_Synchro)))
{
// initialize internal vars
d_dump = dump;
d_nchannels = nchannels;
d_dump_filename = dump_filename;
history_deep = deep_history;
for (unsigned int i = 0; i < d_nchannels; i++)
{
d_acc_carrier_phase_queue_rads.push_back(std::deque<double>(d_nchannels));
d_carrier_doppler_queue_hz.push_back(std::deque<double>(d_nchannels));
d_symbol_TOW_queue_s.push_back(std::deque<double>(d_nchannels));
}
// ############# ENABLE DATA FILE LOG #################
if (d_dump == true)
{
if (d_dump_file.is_open() == false)
{
try
{
d_dump_file.exceptions (std::ifstream::failbit | std::ifstream::badbit );
d_dump_file.open(d_dump_filename.c_str(), std::ios::out | std::ios::binary);
LOG(INFO) << "Observables dump enabled Log file: " << d_dump_filename.c_str();
}
catch (const std::ifstream::failure & e)
{
LOG(WARNING) << "Exception opening observables dump file " << e.what();
}
}
}
}
gps_l1_ca_observables_cc::~gps_l1_ca_observables_cc()
{
d_dump_file.close();
}
bool pairCompare_gnss_synchro_Prn_delay_ms(const std::pair<int,Gnss_Synchro>& a, const std::pair<int,Gnss_Synchro>& b)
{
return (a.second.Prn_timestamp_ms) < (b.second.Prn_timestamp_ms);
}
bool pairCompare_gnss_synchro_d_TOW_at_current_symbol(const std::pair<int,Gnss_Synchro>& a, const std::pair<int,Gnss_Synchro>& b)
{
return (a.second.d_TOW_at_current_symbol) < (b.second.d_TOW_at_current_symbol);
}
int gps_l1_ca_observables_cc::general_work (int noutput_items, gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items, gr_vector_void_star &output_items)
{
Gnss_Synchro **in = (Gnss_Synchro **) &input_items[0]; // Get the input pointer
Gnss_Synchro **out = (Gnss_Synchro **) &output_items[0]; // Get the output pointer
Gnss_Synchro current_gnss_synchro[d_nchannels];
std::map<int,Gnss_Synchro> current_gnss_synchro_map;
std::map<int,Gnss_Synchro>::iterator gnss_synchro_iter;
if (d_nchannels != ninput_items.size())
{
LOG(WARNING) << "The Observables block is not well connected";
}
/*
* 1. Read the GNSS SYNCHRO objects from available channels
*/
for (unsigned int i = 0; i < d_nchannels; i++)
{
//Copy the telemetry decoder data to local copy
current_gnss_synchro[i] = in[i][0];
/*
* 1.2 Assume no valid pseudoranges
*/
current_gnss_synchro[i].Flag_valid_pseudorange = false;
current_gnss_synchro[i].Pseudorange_m = 0.0;
if (current_gnss_synchro[i].Flag_valid_word) //if this channel have valid word
{
//record the word structure in a map for pseudorange computation
current_gnss_synchro_map.insert(std::pair<int, Gnss_Synchro>(current_gnss_synchro[i].Channel_ID, current_gnss_synchro[i]));
//################### SAVE DOPPLER AND ACC CARRIER PHASE HISTORIC DATA FOR INTERPOLATION IN OBSERVABLE MODULE #######
d_carrier_doppler_queue_hz[i].push_back(current_gnss_synchro[i].Carrier_Doppler_hz);
d_acc_carrier_phase_queue_rads[i].push_back(current_gnss_synchro[i].Carrier_phase_rads);
// save TOW history
d_symbol_TOW_queue_s[i].push_back(current_gnss_synchro[i].d_TOW_at_current_symbol);
if (d_carrier_doppler_queue_hz[i].size() > history_deep)
{
d_carrier_doppler_queue_hz[i].pop_front();
}
if (d_acc_carrier_phase_queue_rads[i].size() > history_deep)
{
d_acc_carrier_phase_queue_rads[i].pop_front();
}
if (d_symbol_TOW_queue_s[i].size() > history_deep)
{
d_symbol_TOW_queue_s[i].pop_front();
}
}
else
{
// Clear the observables history for this channel
if (d_symbol_TOW_queue_s[i].size() > 0)
{
d_symbol_TOW_queue_s[i].clear();
d_carrier_doppler_queue_hz[i].clear();
d_acc_carrier_phase_queue_rads[i].clear();
}
}
}
/*
* 2. Compute RAW pseudoranges using COMMON RECEPTION TIME algorithm. Use only the valid channels (channels that are tracking a satellite)
*/
if(current_gnss_synchro_map.size() > 0)
{
/*
* 2.1 Use CURRENT set of measurements and find the nearest satellite
* common RX time algorithm
*/
// what is the most recent symbol TOW in the current set? -> this will be the reference symbol
gnss_synchro_iter = max_element(current_gnss_synchro_map.begin(), current_gnss_synchro_map.end(), pairCompare_gnss_synchro_d_TOW_at_current_symbol);
double d_TOW_reference = gnss_synchro_iter->second.d_TOW_at_current_symbol;
double d_ref_PRN_rx_time_ms = gnss_synchro_iter->second.Prn_timestamp_ms;
// Now compute RX time differences due to the PRN alignment in the correlators
double traveltime_ms;
double pseudorange_m;
double delta_rx_time_ms;
arma::vec symbol_TOW_vec_s;
arma::vec dopper_vec_hz;
arma::vec dopper_vec_interp_hz;
arma::vec acc_phase_vec_rads;
arma::vec acc_phase_vec_interp_rads;
arma::vec desired_symbol_TOW(1);
for(gnss_synchro_iter = current_gnss_synchro_map.begin(); gnss_synchro_iter != current_gnss_synchro_map.end(); gnss_synchro_iter++)
{
// compute the required symbol history shift in order to match the reference symbol
delta_rx_time_ms = gnss_synchro_iter->second.Prn_timestamp_ms - d_ref_PRN_rx_time_ms;
//compute the pseudorange
traveltime_ms = (d_TOW_reference - gnss_synchro_iter->second.d_TOW_at_current_symbol) * 1000.0 + delta_rx_time_ms + GPS_STARTOFFSET_ms;
//convert to meters and remove the receiver time offset in meters
pseudorange_m = traveltime_ms * GPS_C_m_ms; // [m]
// update the pseudorange object
current_gnss_synchro[gnss_synchro_iter->second.Channel_ID] = gnss_synchro_iter->second;
current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].Pseudorange_m = pseudorange_m;
current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].Flag_valid_pseudorange = true;
current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].d_TOW_at_current_symbol = round(d_TOW_reference * 1000.0) / 1000.0 + GPS_STARTOFFSET_ms / 1000.0;
if (d_symbol_TOW_queue_s[gnss_synchro_iter->second.Channel_ID].size() >= history_deep)
{
// compute interpolated observation values for Doppler and Accumulate carrier phase
symbol_TOW_vec_s = arma::vec(std::vector<double>(d_symbol_TOW_queue_s[gnss_synchro_iter->second.Channel_ID].begin(), d_symbol_TOW_queue_s[gnss_synchro_iter->second.Channel_ID].end()));
acc_phase_vec_rads = arma::vec(std::vector<double>(d_acc_carrier_phase_queue_rads[gnss_synchro_iter->second.Channel_ID].begin(), d_acc_carrier_phase_queue_rads[gnss_synchro_iter->second.Channel_ID].end()));
dopper_vec_hz = arma::vec(std::vector<double>(d_carrier_doppler_queue_hz[gnss_synchro_iter->second.Channel_ID].begin(), d_carrier_doppler_queue_hz[gnss_synchro_iter->second.Channel_ID].end()));
desired_symbol_TOW[0] = symbol_TOW_vec_s[history_deep - 1] + delta_rx_time_ms / 1000.0;
// arma::interp1(symbol_TOW_vec_s,dopper_vec_hz,desired_symbol_TOW,dopper_vec_interp_hz);
// arma::interp1(symbol_TOW_vec_s,acc_phase_vec_rads,desired_symbol_TOW,acc_phase_vec_interp_rads);
// Curve fitting to quadratic function
arma::mat A = arma::ones<arma::mat> (history_deep, 2);
A.col(1) = symbol_TOW_vec_s;
arma::mat coef_acc_phase(1,3);
arma::mat pinv_A = arma::pinv(A.t() * A) * A.t();
coef_acc_phase = pinv_A * acc_phase_vec_rads;
arma::mat coef_doppler(1,3);
coef_doppler = pinv_A * dopper_vec_hz;
arma::vec acc_phase_lin;
arma::vec carrier_doppler_lin;
acc_phase_lin = coef_acc_phase[0] + coef_acc_phase[1] * desired_symbol_TOW[0];
carrier_doppler_lin = coef_doppler[0] + coef_doppler[1] * desired_symbol_TOW[0];
current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].Carrier_phase_rads = acc_phase_lin[0];
current_gnss_synchro[gnss_synchro_iter->second.Channel_ID].Carrier_Doppler_hz = carrier_doppler_lin[0];
}
}
}
if(d_dump == true)
{
// MULTIPLEXED FILE RECORDING - Record results to file
try
{
double tmp_double;
for (unsigned int i = 0; i < d_nchannels; i++)
{
tmp_double = current_gnss_synchro[i].d_TOW_at_current_symbol;
d_dump_file.write((char*)&tmp_double, sizeof(double));
//tmp_double = current_gnss_synchro[i].Prn_timestamp_ms;
tmp_double = current_gnss_synchro[i].Carrier_Doppler_hz;
d_dump_file.write((char*)&tmp_double, sizeof(double));
tmp_double = current_gnss_synchro[i].Carrier_phase_rads/GPS_TWO_PI;
d_dump_file.write((char*)&tmp_double, sizeof(double));
tmp_double = current_gnss_synchro[i].Pseudorange_m;
d_dump_file.write((char*)&tmp_double, sizeof(double));
tmp_double = current_gnss_synchro[i].PRN;
d_dump_file.write((char*)&tmp_double, sizeof(double));
}
}
catch (const std::ifstream::failure& e)
{
LOG(WARNING) << "Exception writing observables dump file " << e.what();
}
}
consume_each(1); //one by one
for (unsigned int i = 0; i < d_nchannels; i++)
{
*out[i] = current_gnss_synchro[i];
}
if (noutput_items == 0)
{
LOG(WARNING) << "noutput_items = 0";
}
return 1;
}
| Arribas/gnss-sdr | src/algorithms/observables/gnuradio_blocks/gps_l1_ca_observables_cc.cc | C++ | gpl-3.0 | 13,634 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
public class ConnectionObject {
public string moduleName1;
public string moduleName2;
public string nodeName1;
public string nodeName2;
public float distance;
public float angle;
public ConnectionObject () {
distance = 0f;
angle = 0f;
}
}
| MOD-ASL/ModularRobotSystemToolKit | unity3d/Assets/Scripts/Objects/ConnectionObject.cs | C# | gpl-3.0 | 408 |
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var Q = require('q'); /* jshint ignore:line */
var _ = require('lodash'); /* jshint ignore:line */
var Page = require('../../../../../base/Page'); /* jshint ignore:line */
var deserialize = require(
'../../../../../base/deserialize'); /* jshint ignore:line */
var values = require('../../../../../base/values'); /* jshint ignore:line */
var MemberList;
var MemberPage;
var MemberInstance;
var MemberContext;
/* jshint ignore:start */
/**
* @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberList
* @description Initialize the MemberList
*
* @param {Twilio.Api.V2010} version - Version of the resource
* @param {string} accountSid - The account_sid
* @param {string} queueSid - A string that uniquely identifies this queue
*/
/* jshint ignore:end */
MemberList = function MemberList(version, accountSid, queueSid) {
/* jshint ignore:start */
/**
* @function members
* @memberof Twilio.Api.V2010.AccountContext.QueueContext
* @instance
*
* @param {string} sid - sid of instance
*
* @returns {Twilio.Api.V2010.AccountContext.QueueContext.MemberContext}
*/
/* jshint ignore:end */
function MemberListInstance(sid) {
return MemberListInstance.get(sid);
}
MemberListInstance._version = version;
// Path Solution
MemberListInstance._solution = {
accountSid: accountSid,
queueSid: queueSid
};
MemberListInstance._uri = _.template(
'/Accounts/<%= accountSid %>/Queues/<%= queueSid %>/Members.json' // jshint ignore:line
)(MemberListInstance._solution);
/* jshint ignore:start */
/**
* Streams MemberInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory efficient.
*
* If a function is passed as the first argument, it will be used as the callback function.
*
* @function each
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList
* @instance
*
* @param {object|function} opts - ...
* @param {number} [opts.limit] -
* Upper limit for the number of records to return.
* each() guarantees never to return more than limit.
* Default is no limit
* @param {number} [opts.pageSize=50] -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no pageSize is defined but a limit is defined,
* each() will attempt to read the limit with the most efficient
* page size, i.e. min(limit, 1000)
* @param {Function} [opts.callback] -
* Function to process each record. If this and a positional
* callback are passed, this one will be used
* @param {Function} [opts.done] -
* Function to be called upon completion of streaming
* @param {Function} [callback] - Function to process each record
*/
/* jshint ignore:end */
MemberListInstance.each = function each(opts, callback) {
opts = opts || {};
if (_.isFunction(opts)) {
opts = { callback: opts };
} else if (_.isFunction(callback) && !_.isFunction(opts.callback)) {
opts.callback = callback;
}
if (_.isUndefined(opts.callback)) {
throw new Error('Callback function must be provided');
}
var done = false;
var currentPage = 1;
var currentResource = 0;
var limits = this._version.readLimits({
limit: opts.limit,
pageSize: opts.pageSize
});
function onComplete(error) {
done = true;
if (_.isFunction(opts.done)) {
opts.done(error);
}
}
function fetchNextPage(fn) {
var promise = fn();
if (_.isUndefined(promise)) {
onComplete();
return;
}
promise.then(function(page) {
_.each(page.instances, function(instance) {
if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) {
done = true;
return false;
}
currentResource++;
opts.callback(instance, onComplete);
});
if ((limits.pageLimit && limits.pageLimit <= currentPage)) {
onComplete();
} else if (!done) {
currentPage++;
fetchNextPage(_.bind(page.nextPage, page));
}
});
promise.catch(onComplete);
}
fetchNextPage(_.bind(this.page, this, _.merge(opts, limits)));
};
/* jshint ignore:start */
/**
* @description Lists MemberInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback function.
*
* @function list
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList
* @instance
*
* @param {object|function} opts - ...
* @param {number} [opts.limit] -
* Upper limit for the number of records to return.
* list() guarantees never to return more than limit.
* Default is no limit
* @param {number} [opts.pageSize] -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no page_size is defined but a limit is defined,
* list() will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @param {function} [callback] - Callback to handle list of records
*
* @returns {Promise} Resolves to a list of records
*/
/* jshint ignore:end */
MemberListInstance.list = function list(opts, callback) {
if (_.isFunction(opts)) {
callback = opts;
opts = {};
}
opts = opts || {};
var deferred = Q.defer();
var allResources = [];
opts.callback = function(resource, done) {
allResources.push(resource);
if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) {
done();
}
};
opts.done = function(error) {
if (_.isUndefined(error)) {
deferred.resolve(allResources);
} else {
deferred.reject(error);
}
};
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
this.each(opts);
return deferred.promise;
};
/* jshint ignore:start */
/**
* Retrieve a single page of MemberInstance records from the API.
* Request is executed immediately
*
* If a function is passed as the first argument, it will be used as the callback function.
*
* @function page
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList
* @instance
*
* @param {object|function} opts - ...
* @param {string} [opts.pageToken] - PageToken provided by the API
* @param {number} [opts.pageNumber] -
* Page Number, this value is simply for client state
* @param {number} [opts.pageSize] - Number of records to return, defaults to 50
* @param {function} [callback] - Callback to handle list of records
*
* @returns {Promise} Resolves to a list of records
*/
/* jshint ignore:end */
MemberListInstance.page = function page(opts, callback) {
opts = opts || {};
var deferred = Q.defer();
var data = values.of({
'PageToken': opts.pageToken,
'Page': opts.pageNumber,
'PageSize': opts.pageSize
});
var promise = this._version.page({
uri: this._uri,
method: 'GET',
params: data
});
promise = promise.then(function(payload) {
deferred.resolve(new MemberPage(
this._version,
payload,
this._solution
));
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
/* jshint ignore:start */
/**
* Retrieve a single target page of MemberInstance records from the API.
* Request is executed immediately
*
* If a function is passed as the first argument, it will be used as the callback function.
*
* @function getPage
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList
* @instance
*
* @param {string} [targetUrl] - API-generated URL for the requested results page
* @param {function} [callback] - Callback to handle list of records
*
* @returns {Promise} Resolves to a list of records
*/
/* jshint ignore:end */
MemberListInstance.getPage = function getPage(targetUrl, callback) {
var deferred = Q.defer();
var promise = this._version._domain.twilio.request({
method: 'GET',
uri: targetUrl
});
promise = promise.then(function(payload) {
deferred.resolve(new MemberPage(
this._version,
payload,
this._solution
));
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
/* jshint ignore:start */
/**
* Constructs a member
*
* @function get
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList
* @instance
*
* @param {string} callSid - The call_sid
*
* @returns {Twilio.Api.V2010.AccountContext.QueueContext.MemberContext}
*/
/* jshint ignore:end */
MemberListInstance.get = function get(callSid) {
return new MemberContext(
this._version,
this._solution.accountSid,
this._solution.queueSid,
callSid
);
};
return MemberListInstance;
};
/* jshint ignore:start */
/**
* @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberPage
* @augments Page
* @description Initialize the MemberPage
*
* @param {Twilio.Api.V2010} version - Version of the resource
* @param {object} response - Response from the API
* @param {object} solution - Path solution
*
* @returns MemberPage
*/
/* jshint ignore:end */
MemberPage = function MemberPage(version, response, solution) {
// Path Solution
this._solution = solution;
Page.prototype.constructor.call(this, version, response, this._solution);
};
_.extend(MemberPage.prototype, Page.prototype);
MemberPage.prototype.constructor = MemberPage;
/* jshint ignore:start */
/**
* Build an instance of MemberInstance
*
* @function getInstance
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberPage
* @instance
*
* @param {object} payload - Payload response from the API
*
* @returns MemberInstance
*/
/* jshint ignore:end */
MemberPage.prototype.getInstance = function getInstance(payload) {
return new MemberInstance(
this._version,
payload,
this._solution.accountSid,
this._solution.queueSid
);
};
/* jshint ignore:start */
/**
* @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberInstance
* @description Initialize the MemberContext
*
* @property {string} callSid - Unique string that identifies this resource
* @property {Date} dateEnqueued - The date the member was enqueued
* @property {number} position - This member's current position in the queue.
* @property {string} uri - The uri
* @property {number} waitTime -
* The number of seconds the member has been in the queue.
*
* @param {Twilio.Api.V2010} version - Version of the resource
* @param {object} payload - The instance payload
* @param {sid} accountSid - The account_sid
* @param {sid} queueSid - The Queue in which to find the members
* @param {sid} callSid - The call_sid
*/
/* jshint ignore:end */
MemberInstance = function MemberInstance(version, payload, accountSid, queueSid,
callSid) {
this._version = version;
// Marshaled Properties
this.callSid = payload.call_sid; // jshint ignore:line
this.dateEnqueued = deserialize.rfc2822DateTime(payload.date_enqueued); // jshint ignore:line
this.position = deserialize.integer(payload.position); // jshint ignore:line
this.uri = payload.uri; // jshint ignore:line
this.waitTime = deserialize.integer(payload.wait_time); // jshint ignore:line
// Context
this._context = undefined;
this._solution = {
accountSid: accountSid,
queueSid: queueSid,
callSid: callSid || this.callSid,
};
};
Object.defineProperty(MemberInstance.prototype,
'_proxy', {
get: function() {
if (!this._context) {
this._context = new MemberContext(
this._version,
this._solution.accountSid,
this._solution.queueSid,
this._solution.callSid
);
}
return this._context;
}
});
/* jshint ignore:start */
/**
* fetch a MemberInstance
*
* @function fetch
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberInstance
* @instance
*
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed MemberInstance
*/
/* jshint ignore:end */
MemberInstance.prototype.fetch = function fetch(callback) {
return this._proxy.fetch(callback);
};
/* jshint ignore:start */
/**
* update a MemberInstance
*
* @function update
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberInstance
* @instance
*
* @param {object} opts - ...
* @param {string} opts.url - The url
* @param {string} opts.method - The method
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed MemberInstance
*/
/* jshint ignore:end */
MemberInstance.prototype.update = function update(opts, callback) {
return this._proxy.update(opts, callback);
};
/* jshint ignore:start */
/**
* @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberContext
* @description Initialize the MemberContext
*
* @param {Twilio.Api.V2010} version - Version of the resource
* @param {sid} accountSid - The account_sid
* @param {sid} queueSid - The Queue in which to find the members
* @param {sid} callSid - The call_sid
*/
/* jshint ignore:end */
MemberContext = function MemberContext(version, accountSid, queueSid, callSid) {
this._version = version;
// Path Solution
this._solution = {
accountSid: accountSid,
queueSid: queueSid,
callSid: callSid,
};
this._uri = _.template(
'/Accounts/<%= accountSid %>/Queues/<%= queueSid %>/Members/<%= callSid %>.json' // jshint ignore:line
)(this._solution);
};
/* jshint ignore:start */
/**
* fetch a MemberInstance
*
* @function fetch
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberContext
* @instance
*
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed MemberInstance
*/
/* jshint ignore:end */
MemberContext.prototype.fetch = function fetch(callback) {
var deferred = Q.defer();
var promise = this._version.fetch({
uri: this._uri,
method: 'GET'
});
promise = promise.then(function(payload) {
deferred.resolve(new MemberInstance(
this._version,
payload,
this._solution.accountSid,
this._solution.queueSid,
this._solution.callSid
));
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
/* jshint ignore:start */
/**
* update a MemberInstance
*
* @function update
* @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberContext
* @instance
*
* @param {object} opts - ...
* @param {string} opts.url - The url
* @param {string} opts.method - The method
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed MemberInstance
*/
/* jshint ignore:end */
MemberContext.prototype.update = function update(opts, callback) {
if (_.isUndefined(opts)) {
throw new Error('Required parameter "opts" missing.');
}
if (_.isUndefined(opts.url)) {
throw new Error('Required parameter "opts.url" missing.');
}
if (_.isUndefined(opts.method)) {
throw new Error('Required parameter "opts.method" missing.');
}
var deferred = Q.defer();
var data = values.of({
'Url': _.get(opts, 'url'),
'Method': _.get(opts, 'method')
});
var promise = this._version.update({
uri: this._uri,
method: 'POST',
data: data
});
promise = promise.then(function(payload) {
deferred.resolve(new MemberInstance(
this._version,
payload,
this._solution.accountSid,
this._solution.queueSid,
this._solution.callSid
));
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
module.exports = {
MemberList: MemberList,
MemberPage: MemberPage,
MemberInstance: MemberInstance,
MemberContext: MemberContext
};
| together-web-pj/together-web-pj | node_modules/twilio/lib/rest/api/v2010/account/queue/member.js | JavaScript | gpl-3.0 | 17,007 |
package com.dotmarketing.portlets.workflows.ajax;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.business.Role;
import com.dotmarketing.business.RoleAPI;
import com.dotmarketing.cms.factories.PublicCompanyFactory;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.portlets.workflows.model.WorkflowAction;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
import com.liferay.portal.language.LanguageException;
import com.liferay.portal.language.LanguageUtil;
import com.liferay.portal.model.User;
import com.dotcms.repackage.org.codehaus.jackson.map.DeserializationConfig.Feature;
import com.dotcms.repackage.org.codehaus.jackson.map.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
public class WfRoleStoreAjax extends WfBaseAction {
public void action ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
String searchName = request.getParameter( "searchName" );
if ( searchName == null ) searchName = "";
String roleId = request.getParameter( "roleId" );
RoleAPI rapi = APILocator.getRoleAPI();
int start = 0;
int count = 20;
try {
start = Integer.parseInt( request.getParameter( "start" ) );
} catch ( Exception e ) {
}
try {
count = Integer.parseInt( request.getParameter( "count" ) );
} catch ( Exception e ) {
}
boolean includeFake = UtilMethods.isSet(request.getParameter( "includeFake" ))&&request.getParameter( "includeFake" ).equals("true");
try {
Role cmsAnon = APILocator.getRoleAPI().loadCMSAnonymousRole();
String cmsAnonName = LanguageUtil.get( getUser(), "current-user" );
cmsAnon.setName( cmsAnonName );
boolean addSystemUser = false;
if ( searchName.length() > 0 && cmsAnonName.startsWith( searchName ) ) {
addSystemUser = true;
}
List<Role> roleList = new ArrayList<Role>();
if ( UtilMethods.isSet( roleId ) ) {
try {
Role r = rapi.loadRoleById( roleId );
if ( r != null ) {
if ( r.getId().equals( cmsAnon.getId() ) )
roleList.add( cmsAnon );
else
roleList.add( r );
response.getWriter().write( rolesToJson( roleList, includeFake ) );
return;
}
} catch ( Exception e ) {
}
}
while ( roleList.size() < count ) {
List<Role> roles = rapi.findRolesByFilterLeftWildcard( searchName, start, count );
if ( roles.size() == 0 ) {
break;
}
for ( Role role : roles ) {
if ( role.isUser() ) {
try {
APILocator.getUserAPI().loadUserById( role.getRoleKey(), APILocator.getUserAPI().getSystemUser(), false );
} catch ( Exception e ) {
//Logger.error(WfRoleStoreAjax.class,e.getMessage(),e);
continue;
}
}
if ( role.getId().equals( cmsAnon.getId() ) ) {
role = cmsAnon;
addSystemUser = false;
}
if ( role.isSystem() && !role.isUser() && !role.getId().equals( cmsAnon.getId() ) && !role.getId().equals( APILocator.getRoleAPI().loadCMSAdminRole().getId() ) ) {
continue;
}
if ( role.getName().equals( searchName ) ) {
roleList.add( 0, role );
} else {
roleList.add( role );
}
}
start = start + count;
}
if ( addSystemUser ) {
cmsAnon.setName( cmsAnonName );
roleList.add( 0, cmsAnon );
}
//x = x.replaceAll("identifier", "x");
response.getWriter().write( rolesToJson( roleList, includeFake ) );
} catch ( Exception e ) {
Logger.error( WfRoleStoreAjax.class, e.getMessage(), e );
}
}
public void assignable ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
String name = request.getParameter( "name" );
boolean includeFake = UtilMethods.isSet(request.getParameter( "includeFake" ))&&request.getParameter( "includeFake" ).equals("true");
try {
String actionId = request.getParameter( "actionId" );
WorkflowAction action = APILocator.getWorkflowAPI().findAction( actionId, getUser() );
Role role = APILocator.getRoleAPI().loadRoleById( action.getNextAssign() );
List<Role> roleList = new ArrayList<Role>();
List<User> userList = new ArrayList<User>();
if ( !role.isUser() ) {
if ( action.isRoleHierarchyForAssign() ) {
userList = APILocator.getRoleAPI().findUsersForRole( role, true );
roleList.addAll( APILocator.getRoleAPI().findRoleHierarchy( role ) );
} else {
userList = APILocator.getRoleAPI().findUsersForRole( role, false );
roleList.add( role );
}
} else {
userList.add( APILocator.getUserAPI().loadUserById( role.getRoleKey(), APILocator.getUserAPI().getSystemUser(), false ) );
}
for ( User user : userList ) {
Role r = APILocator.getRoleAPI().getUserRole( user );
if ( r != null && UtilMethods.isSet( r.getId() ) ) {
roleList.add( r );
}
}
if ( name != null ) {
name = name.toLowerCase().replaceAll( "\\*", "" );
if ( UtilMethods.isSet( name ) ) {
List<Role> newRoleList = new ArrayList<Role>();
for ( Role r : roleList ) {
if ( r.getName().toLowerCase().startsWith( name ) ) {
newRoleList.add( r );
}
}
roleList = newRoleList;
}
}
response.setContentType("application/json");
response.getWriter().write( rolesToJson( roleList, includeFake ) );
} catch ( Exception e ) {
Logger.error( WfRoleStoreAjax.class, e.getMessage(), e );
}
}
private String rolesToJson ( List<Role> roles, boolean includeFake ) throws IOException, DotDataException, LanguageException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure( Feature.FAIL_ON_UNKNOWN_PROPERTIES, false );
Map<String, Object> m = new LinkedHashMap<String, Object>();
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = null;
if(includeFake) {
map = new HashMap<String, Object>();
map.put( "name", "" );
map.put( "id", 0 );
list.add( map );
}
User defaultUser = APILocator.getUserAPI().getDefaultUser();
Role defaultUserRole = null;
if ( defaultUser != null ) {
defaultUserRole = APILocator.getRoleAPI().getUserRole( defaultUser );
}
for ( Role role : roles ) {
map = new HashMap<String, Object>();
//Exclude default user
if ( defaultUserRole != null && role.getId().equals( defaultUserRole.getId() ) ) {
continue;
}
//We just want to add roles that can have permissions assigned to them
if ( !role.isEditPermissions() ) {
continue;
}
//We need to exclude also the anonymous user
if ( role.getName().equalsIgnoreCase( "anonymous user" ) ) {
continue;
}
map.put( "name", role.getName() + ((role.isUser()) ? " (" + LanguageUtil.get( PublicCompanyFactory.getDefaultCompany(), "User" ) + ")" : ""));
map.put( "id", role.getId() );
list.add( map );
}
m.put( "identifier", "id" );
m.put( "label", "name" );
m.put( "items", list );
return mapper.defaultPrettyPrintingWriter().writeValueAsString( m );
}
} | dotcms-legacy/core-2.x | src/com/dotmarketing/portlets/workflows/ajax/WfRoleStoreAjax.java | Java | gpl-3.0 | 8,847 |
// Mark Stankus 1999 (c)
// OrderTeXBanner.hpp
#ifndef INCLUDED_ORDERTEXBANNER_H
#define INCLUDED_ORDERTEXBANNER_H
class BroadCastData;
class OrderTeXBanner : public Recipient {
public:
OrderTeXBanner() {};
virtual ~OrderTeXBanner();
virtual void action(const BroadCastData & x) const;
virtual Recipient * clone() const;
};
#endif
| mcdeoliveira/NC | NCGB/Compile/src/OBSOLETE2009/OrderTeXBanner.hpp | C++ | gpl-3.0 | 342 |
# Copyright (c) 2013-2015 SUSE LLC
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 3 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact SUSE LLC.
#
# To contact SUSE about this file by physical or electronic mail,
# you may find current contact information at www.suse.com
require_relative "../unit/spec_helper"
describe "merge_users_and_groups.pl" do
let(:template) {
ERB.new(
File.read(File.join(Machinery::ROOT, "export_helpers", "merge_users_and_groups.pl.erb"))
)
}
before(:each) {
@passwd_tempfile = Tempfile.new("passwd")
@passwd_path = @passwd_tempfile.path
@shadow_tempfile = Tempfile.new("shadow")
@shadow_path = @shadow_tempfile.path
@group_tempfile = Tempfile.new("group")
@group_path = @group_tempfile.path
}
after(:each) {
@passwd_tempfile.unlink
@shadow_tempfile.unlink
@group_tempfile.unlink
}
def run_helper(passwd_entries, group_entries)
script = Tempfile.new("merge_users_and_groups.pl")
script.write(template.result(binding))
script.close
FileUtils.touch(@passwd_path)
FileUtils.touch(@shadow_path)
Cheetah.run("perl", script.path, @passwd_path, @shadow_path, @group_path, stdout: :capture)
end
it "adds new entries" do
entries = <<-EOF
["svn:x:482:476:user for Apache Subversion svnserve:/srv/svn:/sbin/nologin", "svn:!:16058::::::"],
["nscd:x:484:478:User for nscd:/var/run/nscd:/sbin/nologin", "nscd:!:16058::::::"]
EOF
expected_passwd = <<EOF
svn:x:482:476:user for Apache Subversion svnserve:/srv/svn:/sbin/nologin
nscd:x:484:478:User for nscd:/var/run/nscd:/sbin/nologin
EOF
expected_shadow = <<EOF
svn:!:16058::::::
nscd:!:16058::::::
EOF
run_helper(entries, "")
expect(File.read(@passwd_path)).to eq(expected_passwd)
expect(File.read(@shadow_path)).to eq(expected_shadow)
end
it "preserves attributes on conflicting entries" do
existing_passwd = <<-EOF
svn:x:482:476:user for Apache:/srv/svn:/sbin/nologin
nscd:x:484:478:User for nscd:/var/run/nscd:/sbin/nologin
EOF
existing_shadow = <<-EOF
svn:!:16058::::::
nscd:!:16058::::::
EOF
expected_passwd = <<-EOF
svn:x:482:456:user for Subversion:/srv/svn_new:/bin/bash
nscd:x:484:012:nscd user:/var/run/nscd_new:/bin/bash
EOF
expected_shadow = <<-EOF
svn:!:1112:1:2:3:4:5:
nscd:!:2223:5:4:3:2:1:
EOF
entries = <<-EOF
["svn:x:123:456:user for Subversion:/srv/svn_new:/bin/bash", "svn:!:1112:1:2:3:4:5:"],
["nscd:x:789:012:nscd user:/var/run/nscd_new:/bin/bash", "nscd:!:2223:5:4:3:2:1:"]
EOF
File.write(@passwd_path, existing_passwd)
File.write(@shadow_path, existing_shadow)
run_helper(entries, "")
expect(File.read(@passwd_path)).to eq(expected_passwd)
expect(File.read(@shadow_path)).to eq(expected_shadow)
end
it "does not reuse already existing uids and gids" do
existing_passwd = <<-EOF
svn:x:1:1:user for Apache Subversion svnserve:/srv/svn:/sbin/nologin
nscd:x:2:2:User for nscd:/var/run/nscd:/sbin/nologin
EOF
expected_passwd = <<-EOF
svn:x:1:1:user for Apache Subversion svnserve:/srv/svn:/sbin/nologin
nscd:x:2:2:User for nscd:/var/run/nscd:/sbin/nologin
nobody:x:3:13:nobody:/var/lib/nobody:/bin/bash
news:x:4:14:News system:/etc/news:/bin/bash
EOF
entries = <<-EOF
["nobody:x:1:13:nobody:/var/lib/nobody:/bin/bash"],
["news:x:2:14:News system:/etc/news:/bin/bash"]
EOF
File.write(@passwd_path, existing_passwd)
run_helper(entries, "")
expect(File.read(@passwd_path)).to eq(expected_passwd)
end
it "writes groups" do
group_entries = <<-EOF
"users:x:100:",
"uucp:x:14:"
EOF
expected_groups = <<EOF
users:x:100:
uucp:x:14:
EOF
run_helper("", group_entries)
expect(File.read(@group_path)).to eq(expected_groups)
end
it "skips existing groups" do
group_entries = <<-EOF
"users:x:100:",
"uucp:x:14:"
EOF
existing_groups = <<EOF
users:x:90:
EOF
expected_groups = <<EOF
users:x:90:
uucp:x:14:
EOF
File.write(@group_path, existing_groups)
run_helper("", group_entries)
expect(File.read(@group_path)).to eq(expected_groups)
end
it "does not reuse already existing gids" do
existing_group = <<-EOF
users:x:100:
uucp:x:101:
EOF
expected_group = <<-EOF
users:x:100:
uucp:x:101:
ntp:x:102:
at:x:103:
EOF
entries = <<-EOF
"ntp:x:100:",
"at:x:101:"
EOF
File.write(@group_path, existing_group)
run_helper("", entries)
expect(File.read(@group_path)).to eq(expected_group)
end
it "keeps passwd and group in sync when adjusting ids" do
existing_passwd = <<-EOF
a:x:1:1:existing user a:/home/a:/bin/bash
b:x:2:2:existing user b:/home/b:/bin/bash
c:x:3:100:existing user c:/home/b:/bin/bash
EOF
existing_group = <<-EOF
a:x:1:
b:x:2:
users:x:100:
common_group_with_different_id:x:200:
common_group_with_different_id2:x:201:
EOF
entries = <<-EOF
["x:x:50:100:new user x:/home/x:/bin/bash"],
["y:x:51:201:new user y:/home/y:/bin/bash"],
["z:x:52:200:new user z:/home/z:/bin/bash"],
EOF
group_entries = <<-EOF
"users_conflict:x:100:",
"common_group_with_different_id:x:201:",
"common_group_with_different_id2:x:200:"
EOF
expected_passwd = <<-EOF
a:x:1:1:existing user a:/home/a:/bin/bash
b:x:2:2:existing user b:/home/b:/bin/bash
c:x:3:100:existing user c:/home/b:/bin/bash
x:x:50:101:new user x:/home/x:/bin/bash
y:x:51:200:new user y:/home/y:/bin/bash
z:x:52:201:new user z:/home/z:/bin/bash
EOF
expected_group = <<-EOF
a:x:1:
b:x:2:
users:x:100:
common_group_with_different_id:x:200:
common_group_with_different_id2:x:201:
users_conflict:x:101:
EOF
File.write(@passwd_path, existing_passwd)
File.write(@group_path, existing_group)
run_helper(entries, group_entries)
expect(File.read(@passwd_path)).to eq(expected_passwd)
expect(File.read(@group_path)).to eq(expected_group)
end
it "merges the user lists of group users" do
existing_group = <<-EOF
users:x:100:foo,both
EOF
expected_group = <<-EOF
users:!:100:bar,both,foo
EOF
entries = <<-EOF
"users:!:200:bar,both",
EOF
File.write(@group_path, existing_group)
run_helper("", entries)
expect(File.read(@group_path)).to eq(expected_group)
end
end
| oucsaw/machinery | spec/helper/merge_users_and_groups_spec.rb | Ruby | gpl-3.0 | 6,762 |
<?php
/**
* This file is part of Missional Digerati Website.
*
* Missional Digerati Website 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.
*
* Missional Digerati Website 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/>.
*
* @author Johnathan Pulos <johnathan@missionaldigerati.org>
* @copyright Copyright 2012 Missional Digerati
*
*/
/**
* Basic settings for this web app
*
* @author Johnathan Pulos
*/
/**
* The email settings for the website
*
* @var array
* @author Johnathan Pulos
*/
$emailSettings = array(
'submit_idea' =>
array( 'to'=> 'email@yahoo.com',
'from' => 'email@yahoo.com',
'from_name' => 'Missional Digerati Website'
),
'contact_us' =>
array( 'to'=> 'email@yahoo.com',
'from' => 'email@yahoo.com',
'from_name' => 'Missional Digerati Website'
),
'volunteer' =>
array( 'to'=> 'email@yahoo.com',
'from' => 'email@yahoo.com',
'from_name' => 'Missional Digerati Website'
)
);
?> | MissionalDigerati/main_website | config/settings.sample.php | PHP | gpl-3.0 | 1,675 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Version details
*
* @package gradeexport
* @subpackage txt
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2020110900; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2020110300; // Requires this Moodle version
$plugin->component = 'gradeexport_txt'; // Full name of the plugin (used for diagnostics)
| ucsf-ckm/moodle | grade/export/txt/version.php | PHP | gpl-3.0 | 1,196 |
/*
* ============================================================================
* GNU General Public License
* ============================================================================
*
* Copyright (C) 2015 Infinite Automation Software. All rights reserved.
*
* 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/>.
*
* When signing a commercial license with Infinite Automation Software,
* the following extension to GPL is made. A special exception to the GPL is
* included to allow you to distribute a combined work that includes BAcnet4J
* without being obliged to provide the source code for any proprietary components.
*
* See www.infiniteautomation.com for commercial license options.
*
* @author Matthew Lohbihler
*/
package com.serotonin.bacnet4j.exception;
import com.serotonin.bacnet4j.apdu.Error;
import com.serotonin.bacnet4j.type.constructed.BACnetError;
public class ErrorAPDUException extends BACnetException {
private static final long serialVersionUID = -1;
private final Error apdu;
public ErrorAPDUException(Error apdu) {
super(apdu.toString());
this.apdu = apdu;
}
public Error getApdu() {
return apdu;
}
public BACnetError getBACnetError() {
return apdu.getError().getError();
}
}
| mlohbihler/BACnet4J | src/main/java/com/serotonin/bacnet4j/exception/ErrorAPDUException.java | Java | gpl-3.0 | 1,883 |
/**
* SpineBean.java
* Copyright (C) 2008 Zphinx Software Solutions
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* THERE IS NO WARRANTY FOR THIS SOFTWARE, TO THE EXTENT PERMITTED BY
* APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING WITH ZPHINX SOFTWARE SOLUTIONS
* AND/OR OTHER PARTIES WHO PROVIDE THIS SOFTWARE "AS IS" WITHOUT WARRANTY
* OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
* IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
* ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
*
* IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
* WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
* THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
* GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
* USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
* DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
* PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
* EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*
* For further information, please go to http://spine.zphinx.co.uk/
*
**/
package com.zphinx.spine.vo.dto;
import java.util.Date;
import java.util.Locale;
import com.zphinx.spine.Universal;
import com.zphinx.spine.security.SpinePermission;
/**
* <p>
* SpineBean contains the base properties of all classes that can be managed by Spine.
* </p>
* <p>
* A SpineBean contains base properties which can be used by client programmers to define subclasses and provides features which are needed by spine to identify objects which it can manipulate.
* </p>
*
* @author David Ladapo
* @version $1.0
* <p>
*
* Copyright ©Zphinx Software Solutions
* </p>
*/
public abstract class SpineBean implements DataTransferObject {
/**
* The date this object was created
*/
private Date creationDate = null;
/**
* The date this object was last modified
*/
private Date modifiedDate = null;
/**
* The serial version uid of this object
*/
private static final long serialVersionUID = 2386166294462675683L;
/**
* The id of this object
*/
private long id = 0;
/**
* The name of this object
*/
private String name = null;
/**
* The description of this object
*/
private String description = null;
/**
* The SpinePermission Object associated with this user
*/
private SpinePermission permission = null;
/**
* This beans unique ID
*/
private String sessionId = null;
/**
* The Locale where this object was created
*/
private Locale locale = null;
/**
* Public Constructor
*/
public SpineBean() {
super();
this.creationDate = new Date();
this.sessionId = Universal.getRandom(10);
}
/**
* Gets the id of this object
*
* @return Returns the id.
*/
public long getId() {
return id;
}
/**
* Sets the id of this object
*
* @param id The id to set.
*/
public void setId(long id) {
this.id = id;
}
/**
* Gets the description of this object
*
* @return Returns the description.
*/
public String getDescription() {
return description;
}
/**
* Sets the description of this object
*
* @param description The description to set.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Gets the name of this object
*
* @return Returns the name.
*/
public String getName() {
if(name == null){
name = this.getClass().getSimpleName();
}
return name;
}
/**
* Sets the name of this object
*
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets a clone of the SpinePermission for this object.The SpinePermission can be reset if necessary but a clone is always returned so that external operations does not affect the security state of this object.
*
* @return SpinePermission A SpinePermission for this member object
* @see SpinePermission
*/
public SpinePermission getPermission() {
SpinePermission perm = null;
if(permission == null){
PermissionFactory pf = new PermissionFactory();
if(getName() == null){
setName(this.getClass().getSimpleName());
}
this.permission = pf.getPermission(getName(), " ", getId());
}
try{
perm = (SpinePermission) this.permission.clone();
}
catch (CloneNotSupportedException e){
e.printStackTrace();
}
return perm;
}
/**
* Set the permission object associated with this user
*
* @param permission The permission object associated with this user
*/
public void setPermission(SpinePermission permission) {
this.permission = permission;
}
/**
* A permission Factory to create a permission for use by this object, called by implementations of SpineBean to retrieve a suitable SpinePrmission
*
* @author David Ladapo
* @version $Revision: 1.13 $ $Date: 2008/06/15 01:47:09 $
*/
public class PermissionFactory {
/*
* Create a default permission object of this type of member @return SpinePermission the default permission object for this member
*/
public SpinePermission getPermission(String name, String actions, long id) {
SpinePermission permission = new SpinePermission(name, actions, id + "");
setPermission(permission);
return permission;
}
}
/**
* Gets this objects creation date, normally created in the constructor of this object
*
* @return Returns the creationDate.
*/
public long getCreationDate() {
return creationDate.getTime();
}
/**
* Sets this objects creation date
*
* @param longDate The creationDate to set.
*/
public void setCreationDate(long longDate) {
this.creationDate = new Date(longDate);
}
/**
* Gets this objects last modified date
*
* @return Returns the modifiedDate.
*/
public Date getModifiedDate() {
return modifiedDate;
}
/**
* Sets this objects last modified date
*
* @param modifiedDate The modifiedDate to set.
*/
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
/*
* (non-Javadoc)
*
* @see com.zphinx.spine.vo.dto.DataTransferObject#getSessionId()
*/
public String getSessionId() {
return sessionId;
}
/**
* Sets this beans sessionId
*
* @param sessionId the sessionId to set
*/
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
/*
* (non-Javadoc)
*
* @see com.zphinx.spine.vo.dto.DataTransferObject#getLocale()
*/
public Locale getLocale() {
if(this.locale == null){
this.locale = Locale.getDefault();
}
return locale;
}
/**
* @param locale the locale to set
*/
public void setLocale(Locale locale) {
this.locale = locale;
}
}
| davidlad123/spine | spine/src/com/zphinx/spine/vo/dto/SpineBean.java | Java | gpl-3.0 | 8,317 |
// Locale.hh
//
// Copyright (C) 2008 Rob Caelers <robc@krandor.nl>
// All rights reserved.
//
// 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 LOCALE_HH
#define LOCALE_HH
#include <map>
#include <string>
#include <glib.h>
using namespace std;
class Locale
{
public:
struct Language
{
std::string language_name;
std::string country_name;
};
typedef std::map<std::string, Language> LanguageMap;
typedef LanguageMap::iterator LanguageMapIter;
typedef LanguageMap::const_iterator LanguageMapCIter;
static bool get_language(const std::string &code, std::string &language);
static bool get_country(const std::string &code, std::string &language);
static void get_all_languages_in_current_locale(LanguageMap &list);
static void get_all_languages_in_native_locale(LanguageMap &list);
static void set_locale(const std::string &code);
static std::string get_locale();
static void lookup(const string &domain, string &str);
static LanguageMap languages_native_locale;
private:
void init();
};
#endif // LOCALE_HH
| sebastien-villemot/workrave | common/include/Locale.hh | C++ | gpl-3.0 | 1,664 |
/*
* $Id: ProcapitaSchoolBMPBean.java,v 1.1 2004/03/01 08:36:13 anders Exp $
*
* Copyright (C) 2003 Agura IT. All Rights Reserved.
*
* This software is the proprietary information of Agura IT AB.
* Use is subject to license terms.
*
*/
package se.idega.idegaweb.commune.school.data;
import com.idega.block.school.data.School;
import com.idega.data.GenericEntity;
import com.idega.data.IDOQuery;
import java.util.Collection;
import javax.ejb.FinderException;
/**
* Entity bean mapping school names in the Procapita system to schools in the eGov system.
* <p>
* Last modified: $Date: 2004/03/01 08:36:13 $ by $Author: anders $
*
* @author Anders Lindman
* @version $Revision: 1.1 $
*/
public class ProcapitaSchoolBMPBean extends GenericEntity implements ProcapitaSchool {
private static final String ENTITY_NAME = "comm_procapita_school";
private static final String COLUMN_SCHOOL_ID = "sch_school_id";
private static final String COLUMN_SCHOOL_NAME = "school_name";
/**
* @see com.idega.data.GenericEntity#getEntityName()
*/
public String getEntityName() {
return ENTITY_NAME;
}
/**
* @see com.idega.data.GenericEntity#getIdColumnName()
*/
public String getIDColumnName() {
return COLUMN_SCHOOL_ID;
}
/**
* @see com.idega.data.GenericEntity#initializeAttributes()
*/
public void initializeAttributes() {
addOneToOneRelationship(getIDColumnName(), School.class);
setAsPrimaryKey (getIDColumnName(), true);
addAttribute(COLUMN_SCHOOL_NAME, "Procapita school name", true, true, String.class);
}
public School getSchool() {
return (School) getColumnValue(COLUMN_SCHOOL_ID);
}
public int getSchoolId() {
return getIntColumnValue(COLUMN_SCHOOL_ID);
}
public String getSchoolName() {
return getStringColumnValue(COLUMN_SCHOOL_NAME);
}
public void setSchoolId(int id) {
setColumn(COLUMN_SCHOOL_ID, id);
}
public void setSchoolName(String name) {
setColumn(COLUMN_SCHOOL_NAME, name);
}
public Collection ejbFindAll() throws FinderException {
final IDOQuery query = idoQuery();
query.appendSelectAllFrom(getTableName());
return idoFindPKsByQuery(query);
}
}
| idega/platform2 | src/se/idega/idegaweb/commune/school/data/ProcapitaSchoolBMPBean.java | Java | gpl-3.0 | 2,151 |
<?php
// Words that are reserved in javascript.
// - delete
// - new
// Please, use the following format i18n('save') not i18n.save
// JavaScript has reserved variables after the dot.
$LANG = array(
// This items are used internally by the GaiaEHR Application.
'pl_All' => 'Angielski (Stany Zjednoczone)',
'i18nExtFile' => 'ext-lang-pl.js',
// End of the items
'dashboard' => 'Pulpit',
'calendar' => 'Kalendarz',
'messages' => 'Wiadomości',
'patient_search' => 'Wyszukiwanie pacjentów',
'new_patient' => 'Nowy pacjent',
'established_patient' => 'Established Patient',
'patient_summary' => 'Patient Summary',
'visits_history' => 'Historia wizyt',
'encounter' => 'Badanie',
'billing' => 'Płatność',
'checkout' => 'Checkout',
'save' => 'Zapisz',
'save_and_print' => 'Save and Print',
'services_charges' => 'Services and Charges',
'payment' => 'Płatność',
'reference' => 'Reference',
'reference_#' => 'Reference #',
'visit_checkout' => 'Visit Checkout',
'billing_manager' => 'Menedżer płatności',
'area_floor_plan' => 'Area Floor Plan',
'patient_pool_areas' => 'Patient Pool Areas',
'patient' => 'Pacjent',
'administration' => 'Administracja',
'global_settings' => 'Ustawienia globalne',
'facilities' => 'Ośrodki',
'new_facility' => 'New Facility',
'users' => 'Użytkownicy',
'user' => 'Użytkownik',
'practice' => 'Practice',
'data_manager' => 'Menedżer danych',
'preventive_care' => 'Preventive Care',
'medications' => 'Medications',
'floor_areas' => 'Floor Areas',
'roles' => 'Role',
'layouts' => 'Układy',
'lists' => 'Listy',
'event_log' => 'Dziennik zdarzeń',
'documents' => 'Dokumenty',
'external_data_loads' => 'External Data Loads',
'miscellaneous' => 'Inne',
'web_search' => 'Wyszukiwanie w sieci',
'address_book' => 'Książka adresowa',
'office_notes' => 'Notatki biurowe',
'my_settings' => 'Moje ustawienia',
'my_account' => 'Moje konto',
'support' => 'Wsparcie',
'message' => 'Wiadomość',
'was_removed' => 'został usunięty',
'calendar_events' => 'Zdarzenia kalendarza',
'add' => 'Dodaj',
'update' => 'Uaktualnij',
'delete' => 'Usuń',
'event' => 'Zdarzenie',
'was_updated' => 'został uaktualniony',
'was_deleted' => 'został usunięty',
'was_moved_to' => 'został przeniesiony do',
'service_date' => 'Service Date',
'primary_provider' => 'Primary Provider',
'encounter_provider' => 'Encounter Provider',
'insurance' => 'Ubezpieczenie',
'first_insurance' => '1st Insurance',
'second_insurance' => '2nd Insurance',
'supplemental_insurance' => 'Supplemental Insurance',
'ins?' => 'Ins?',
'billing_stage' => 'Billing Stage',
'from' => 'Od',
'to' => 'Do',
'past_due' => 'Past due',
'encounter_billing_details' => 'Szczegóły dot. płatności za badanie',
'encounter_general_info' => 'Ogólne informacje dot. badania',
'hosp_date' => 'Hosp Date',
'sec_insurance' => 'Ubezpieczenie drugorzędne',
'provider' => 'Provider',
'authorization' => 'Authorization',
'sec_authorization' => 'SecAuthorization',
'referal_by' => 'Referral By',
'encounter _icd9' => 'Encounter ICD9s',
'progress_note' => 'Nota o postępie',
'progress_history' => 'Progress History',
'encounter_progress_note' => 'Postęp badania',
'back_to_encounter_list' => 'Powrót do listy badań',
'back' => 'Wróć',
'previous_encounter_details' => 'Szczegóły poprzedniego badania',
'save_billing_details' => 'Zapisz szczegóły płatności',
'cancel' => 'Anuluj',
'cancel_and_go_back_to_encounter_list' => 'Anuluj i wróć do listy badań',
'next' => 'Dalej',
'next_encounter_details' => 'Szczegóły następnego badania',
'page' => 'Strona',
'encounter_billing_data_updated' => 'Uaktualniono dane płatności za badanie',
'encounters' => 'Badania',
'paying_entity' => 'Podmiot płacący',
'add_new_payment' => 'Dodaj nową płatność',
'no' => 'Nie',
'payment_method' => 'Metoda płatności',
'pay_to' => 'Zapłać dla',
'amount' => 'Kwota',
'post_to_date' => 'Post To Date',
'note' => 'Nota',
'reset' => 'Wyczyść',
'payment_entry_error' => 'Payment entry error',
'search' => 'Szukaj',
'add_payment' => 'Dodaj płatność',
'patient_name' => 'Imię pacjenta',
'billing_notes' => 'Noty dot. płatności',
'balance_due' => 'Balance Due',
'detail' => 'Szczegóły',
'inbox' => 'Skrzynka odbiorcza',
'status' => 'Status',
'subject' => 'Temat',
'type' => 'Typ',
'no_office_notes_to_display' => 'Brak not biurowych do wyświetlenia',
'sent' => 'Wysłane',
'trash' => 'Kosz',
'new_message' => 'Nowa wiadomość',
'reply' => 'Odpowiedz',
'no_patient_selected' => 'Nie wybrano pacjenta',
'new' => 'Nowy',
'unassigned' => 'Unassigned',
'message_sent' => 'Wiadomość została wysłana',
'please_complete_all_required_fields' => 'Proszę wypełnić wszystkie wymagane pola',
'please_confirm' => 'Proszę potwierdzić',
'are_you_sure_to_delete_this_message' => 'Czy na pewno chcesz usunąć tę wiadomość?',
'sent_to_trash' => 'Sent to Trash',
'add_or_edit_contact' => 'Dodaj lub edytuj kontakt',
'primary_info' => 'Primary Info',
'primary_address' => 'Primary Address',
'secondary_address' => 'Secondary Address',
'phone_numbers' => 'Numery telefonów',
'online_info' => 'Online Info',
'other_info' => 'Other Info',
'notes' => 'Noty',
'name' => 'Imię',
'local' => 'Local',
'specialty' => 'Specialty',
'work_phone' => 'Telefon służbowy',
'home_phone' => 'Home Phone',
'mobile' => 'Telefon komórkowy',
'fax' => 'Faks',
'email' => 'Email',
'add_contact' => 'Dodaj kontakt',
'following_data_copied_to_clipboard' => 'Następujące dane zostały skopiowane do schowka',
'personal_info' => 'Informacje osobiste',
'login_info' => 'Informacje logowania',
'change_password' => 'Zmień hasło',
'change_you_password' => 'Zmień swoje hasło',
'old_password' => 'Stare hasło',
'new_password' => 'Nowe hasło',
're_type_password' => 'Powtórz hasło',
'appearance_settings' => 'Ustawienia wyglądu',
'locale_settings' => 'Locale Settings',
'calendar_settings' => 'Ustawienia kalendarza',
'type_new_note_here' => 'Wpisz nową notę',
'hide_this_note' => 'Ukryj tę notę',
'hide_selected_office_note' => 'Ukryj wybraną notę biurową',
'date' => 'Data',
'show_only_active_notes' => 'Pokaż tylko aktywne noty',
'show_all_notes' => 'Pokaż wszystkie noty',
'search_by' => 'Search By',
'heath_topics' => 'Heath Topics',
'ICD-9-CM' => 'ICD-9-CM',
'searching' => 'Szukam',
'please_wait' => 'Proszę czekać',
'search_results' => 'Wyniki wyszukiwania',
'nothing_to_display' => 'Brak wpisów do wyświetlenia',
'blood_pressure' => 'Ciśnienie krwi',
'systolic' => 'Skurczowe',
'diastolic' => 'Rozkurczowe',
'pulse_per_min' => 'Puls (na minutę)',
'pulse' => 'Puls',
'temperature' => 'Temperatura',
'temp_fahrenheits' => 'Temperatura w Fahrenheitach',
'circumference_cm' => 'Obwód (cm)',
'height_for_age' => 'Wzrost dla wieku',
'height_inches' => 'Wzrost (cale)',
'height_centimeters' => 'Wzrost (centymetry)',
'age_years' => 'Wiek (w latach)',
'actual_growth' => 'Actual Growth',
'normal_growth' => 'Normal Growth',
'weight_for_age' => 'Waga dla wieku',
'weight_kg' => 'Waga (kg)',
'length_cm' => 'Długość (cm)',
'weight' => 'Waga',
'length_for_age_0_36_mos' => 'Length For Age ( 0 - 36 mos )Length For Age ( 0 - 36 mos )',
'age_mos' => 'Wiek (w miesiącach)',
'weight_for_age_0_36_mos' => 'Weight For Age ( 0 - 36 mos )',
'full_description' => 'Pełny opis',
'place_of_service' => 'Place Of Service',
'emergency' => 'Wypadek',
'charges' => 'Charges',
'days_of_units' => 'Days of Units',
'essdt_fam_plan' => 'ESSDT Fam. Plan',
'modifiers' => 'Modyfikatory',
'diagnosis' => 'Diagnoza',
'cpt_search' => 'CPT Search',
'cpt_quick_reference_options' => 'CPT Quick Reference Options',
'show_related_cpt_for_current_diagnostics' => 'Show related CPTs for current diagnostics',
'show_cpt_history_for_this_patient' => 'Show CPTs history for this patient',
'show_cpt_commonly_used_by_clinic' => 'Show CPTs commonly used by Clinic',
'description' => 'Opis',
'code' => 'Kod',
'encounter_cpts' => 'Encounter CPTs',
'cpt_live_sarch' => 'CPT Live Search',
'quick_reference' => 'Quick Reference',
'reload' => 'Odśwież',
'cpt_removed_from_this_encounter' => 'CPT removed from this Encounter',
'cpt_added_to_this_encounter' => 'CPT added to this Encounter',
'hcfa_1500_options' => 'HCFA 1500 Options',
'icds_live_search' => 'ICDs Live Search',
'click_to_clear_selection' => 'Click to clear selection.',
'clearable_combo_box' => 'Clearable Combo Box',
'payments' => 'Płatności',
'patient_arrival_log' => 'Patient Arrival Log',
'look_for_patient' => 'Look for Patient',
'add_new_patient' => 'Dodaj nowego pacjenta',
'remove' => 'Usuń',
'time' => 'Czas',
'record' => 'Record',
'area' => 'Obszar',
'patient_have_a_opened_encounter' => 'Pacjent posiada otwarte badanie',
'patient_have_been_removed' => 'Patient have been removed',
'vector_charts' => 'Wykresy wektorowe',
'bp_pulse_temp' => 'BP/Pulse/Temp',
'length_for_age' => 'Długość dla wieku',
'weight_for_recumbent' => 'Weight for Recumbent',
'head_circumference' => 'Obwód głowy',
'weight_for_stature' => 'Waga dla postury',
'stature_for_age' => 'Postura dla wieku',
'bmi_for_age' => 'BMI dla wieku',
'print_chart' => 'Drukuj wykres',
'weight_for_age_0_3_mos' => 'Waga dla wieku (0-3 mies.)',
'age_months' => 'Wiek (w miesiącach)',
'length_for_age_0_3_mos' => 'Długość dla wieku (0-3 mies.)',
'weight_for_recumbent_0_3_mos' => 'Weight For Recumbent ( 0 - 3 mos )',
'head_circumference_0_3_mos' => 'Obwód głowy (0-3 mies.)',
'weight_for_age_2_20_years' => 'Waga dla wieku (2-20 lat)',
'stature_for_age_2_20_years' => 'Postura dla wieku (2-20 lat)',
'stature_cm' => 'Postura (cm)',
'bmi_for_age_2_20_years' => 'BMI dla wieku (2-20 lat)',
'bmi' => 'BMI',
'documents_viewer_window' => 'Okno przeglądarki dokumentów',
'medical_window' => 'Medical Window',
'immunization' => 'Szczepionka',
'immunization_name' => 'Nazwa szczepionki',
'lot_number' => 'Numer partii',
'dosis_number' => 'Dosis Number',
'info_statement_given' => 'Info. Statement Given',
'Manufacturer' => 'Producent',
'date_administered' => 'Date Administered',
'reviewed' => 'Reviewed',
'location' => 'Lokalizacja',
'severity' => 'Severity',
'active?' => 'Aktywny?',
'active' => 'Active',
'begin_date' => 'Data rozpoczęcia',
'allergy' => 'Alergia',
'reaction' => 'Reakcja',
'end_date' => 'Data zakończenia',
'problem' => 'Problem',
'general' => 'ogólne',
'occurrence' => 'Occurrence',
'outcome' => 'Outcome',
'referred_by' => 'Referred by',
'surgery' => 'Chirurgia',
'title' => 'Tytuł',
'medication' => 'Medication',
'laboratories' => 'Laboratoria',
'laboratory_preview' => 'Laboratory Preview',
'upload' => 'Załaduj',
'scan' => 'Skanuj',
'laboratory_entry_form' => 'Laboratory Entry Form',
'sign' => 'Sign',
'allergies' => 'Alergie',
'active_problems' => 'Aktywne problemy',
'surgeries' => 'Operacje chirurgiczne',
'dental' => 'Stomatologiczne',
'add_new' => 'Dodaj nowy',
'uploading_laboratory' => 'Uploading Laboratory',
'incorrect_password' => 'Nieprawidłowe hasło',
'nothing_to_sign' => 'Nothing to sign.',
'succefully_reviewed' => 'Successfully reviewed',
'order_window' => 'Order Window',
'lab_orders' => 'Lab Orders',
'new_lab_order' => 'Nowe zlecenie laboratoryjne',
'lab' => 'Laboratorium',
'create' => 'Utwórz',
'xray' => 'X-Ray',
'xray_orders' => 'X-Ray Orders',
'xray_ct_orders' => 'X-Ray/CT Orders',
'new_xray_ct_order' => 'New X-Ray/CT Order',
'ct_vascular_studies' => 'CT Vascular Studies',
'ct' => 'CT',
'dispense' => 'Dispense',
'refill' => 'Refill',
'pharmacies' => 'Pharmacies',
'dose' => 'Dose',
'dose_mg' => 'Dose mg',
'take' => 'Take',
'route' => 'Route',
'new_medication' => 'New Medication',
'new_doctors_note' => 'Nowa nota doktora',
'preventive_care_window' => 'Preventive Care Window',
'suggestions' => 'Sugestie',
'item' => 'Item',
'reason' => 'Powód',
'observation' => 'Observation',
'dismiss_alert' => 'Dismiss Alert?',
'dismissed' => 'Dismissed',
'no_alerts_found' => 'No Alerts Found',
'new_encounter_form' => 'Nowy formularz badania',
'create_encounter' => 'Utwórz spotkanie',
'checkout_and_signing' => 'Checkout and Signing',
'services_diagnostics' => 'Services / Diagnostics',
'additional_info' => 'Dodatkowe informacje',
'messages_notes_and_reminders' => 'Wiadomości, noty oraz przypomnienia',
'reminder' => 'Przypomnienie',
'time_interval' => 'Przedział czasowy',
'warnings_alerts' => 'Warnings / Alerts',
'co_sign' => 'Co-Sign',
'vitals' => 'Vitals',
'review_of_systems' => 'Review of Systems',
'review_of_systems_checks' => 'Review of Systems Checks',
'soap' => 'SOAP',
'items_to_review' => 'Items to Review',
'administrative' => 'Administrative',
'misc_billing_options_HCFA_1500' => 'Misc. Billing Options HCFA-1500',
'current_procedural_terminology' => 'Current Procedural Terminology',
'encounter_history' => 'Historia badań',
'print_progress_note' => 'Drukuj notę o postępie',
'new_prescription' => 'Nowa recepta',
'open_encounters_found' => 'Znalezione otwarte badania',
'do_you_want_to' => 'Czy chcesz',
'continue_creating_the_new_encounters' => 'kontynuować tworzenie nowych badań?',
'click_no_to_review_encounter_history' => 'Click No to review Encounter History',
'vitals_saved' => 'Vitals Saved',
'vitals_form_is_epmty' => 'Vitals form is empty',
'encounter_updated' => 'Uaktualniono badanie',
'vitals_signed' => 'Vitals Signed',
'closed_encounter' => 'Zamknięte badanie',
'encounter_closed' => 'Badanie zamknięte',
'this_column_can_not_be_modified_because_it_has_been_signed_by' => 'This column can not be modified because it has been signed by',
'opened_encounter' => 'Otwarte badanie',
'very_severely_underweight' => 'Silna niedowaga',
'severely_underweight' => 'Znaczna niedowaga',
'underweight' => 'Niedowaga',
'normal' => 'Waga w normie',
'overweight' => 'Nadwaga',
'obese_class_1' => 'Otyłość klasy I',
'obese_class_2' => 'Otyłość klasy II',
'obese_class_3' => 'Otyłość klasy III',
'visits' => 'Wizyty',
'view_document' => 'Wyświetl dokument',
'smoking_status' => 'Status palacza',
'alcohol' => 'Alkohol?',
'pregnant' => 'W ciąży?',
'review_all' => 'Review All',
'items_to_review_save_and_review' => 'Items To Review Save and Review',
'items_to_review_entry_error' => 'Items To Review entry error',
'no_laboratory_results_to_display' => 'Brak wyników z laboratorium do wyświetlenia',
'patient_entry_form' => 'Patient Entry Form',
'demographics' => 'Demographics',
'create_new_patient' => 'Utwórz nowego pacjenta',
'created' => 'Utworzono',
'something_went_wrong_saving_the_patient' => 'Something went wrong saving the patient',
'do_you_want_to_create_a_new_patient' => 'Czy chcesz utworzyć <strong>nowego pacjenta</strong>?',
'provider_date' => 'Provider date',
'onset_date' => 'Onset Date',
'visit_category' => 'Visit Category',
'priority' => 'Priorytet',
'close_on' => 'Close On',
'brief_description' => 'Brief Description',
'review_of_system_checks' => 'Review of System Checks',
'subjective' => 'Subjective',
'objective' => 'Objective',
'assessment' => 'Assessment',
'plan' => 'Plan',
'speech_dictation' => 'Speech Dictation',
'dictation' => 'Dictation',
'additional_notes' => 'Dodatkowe noty',
'additional_billing_notes' => 'Additional Billing Notes',
'date_&_time' => 'Data i czas',
'weight_lbs' => 'Waga (lbs)',
'height_in' => 'Wzrost (cale)',
'height_cm' => 'Wzrost (cm)',
'bp_systolic' => 'BP systolic',
'bp_diastolic' => 'BP diastolic',
'respiration' => 'Respiration',
'temp_f' => 'Temperatura F',
'temp_c' => 'Temperatura C',
'temp_location' => 'Temp Location',
'oxygen_saturation' => 'Oxygen Saturation',
'head_circumference_in' => 'Head Circumference in',
'head_circumference_cm' => 'Head Circumference cm',
'waist_circumference_in' => 'Waist Circumference in',
'waist_circumference_cm' => 'Waist Circumference cm',
'bmi' => 'BMI',
'bmi_status' => 'Status BMI',
'other_notes' => 'Inne noty',
'administer' => 'Administer',
'active_medications' => 'Active Medications',
'alert' => 'Alert',
'appointments' => 'Terminy',
'add_note' => 'Dodaj notę',
'immunizations' => 'Immunizations',
'reminders' => 'Przypomnienia',
'add_reminder' => 'Dodaj przypomnienie',
'history' => 'History',
'available_documents' => 'Dostępne dokumenty',
'upload_document' => 'Załaduj dokument',
'select_a_file' => 'Wybierz plik',
'dismissed_preventive_care_alerts' => 'Dismissed Preventive Care Alerts',
'account_balance' => 'Account Balance',
'uploading_document' => 'Uploading Document',
'take_picture' => 'Zrób zdjęcie',
'print_qrcode' => 'Drukuj kod QR',
'primary_insurance' => 'Ubezpieczenie pierwszorzędne',
'secondary_insurance' => 'Ubezpieczenie drugorzędne',
'tertiary_insurance' => 'Ubezpieczenie trzeciorzędne',
'details' => 'Szczegóły',
'patient_photo_id' => 'Patient Photo Id',
'uploading_insurance' => 'Załadowuję ubezpieczenie',
'copay_payment' => 'Co-Pay / Payment',
'paid' => 'Zapłacone',
'charge' => 'Charge',
'total' => 'Total',
'subtotal' => 'Subtotal',
'tax' => 'Tax',
'amount_due' => 'Amount Due',
'payment_amount' => 'Payment Amount',
'balance' => 'Balance',
'add_service' => 'Add Service',
'add_copay' => 'Add Co-Pay',
'notes_and_reminders' => 'Noty i przypomnienia',
'note_and_reminder' => 'Nota i przypomnienie',
'followup_information' => 'Follow-Up Information',
'schedule_appointment' => 'Schedule Appointment',
'note_entry_error' => 'Wystąpił błąd przy wprowadzaniu noty',
'billing_facility' => 'Billing Facility',
'close' => 'Zamknij',
'show_details' => 'Show Details',
'new_encounter' => 'Nowe badanie',
'no_vitals_to_display' => 'No Vitals to Display',
'advance_patient_search' => 'Advance Patient Search',
'first_name' => 'Imię',
'middle_name' => 'Drugie imię',
'last_name' => 'Nazwisko',
'please_sign' => 'Proszę podpisać',
'show_patient_record' => 'Show Patient Record',
'stow_patient_record' => 'Stow Patient Record',
'check_out_patient' => 'Check Out Patient',
'visit_check_out' => 'Visit Check Out',
'payment_entry' => 'Wpis płatności',
'patient_live_search' => 'Patient Live Search',
'create_a_new_patient' => 'Utwórz nowego pacjenta',
'create_new_emergency' => 'Utwórz nowy wypadek',
'logout' => 'Wyloguj',
'arrival_log' => 'Arrival Log',
'pool_areas' => 'Pool Areas',
'floor_plans' => 'Floor Plans',
'navigation' => 'Nawigacja',
'news' => 'aktualności',
'issues' => 'issues',
'wiki' => 'wiki',
'forums' => 'fora',
'patient_image_saved' => 'Patient image saved',
'wait' => 'Czekaj',
'are_you_sure_you_want_to_create_a_new' => 'Czy na pewno chcesz utworzyć nowego',
'is_currently_working_with' => 'is currently working with',
'in' => 'in',
'override_read_mode_will_remove_the_patient_from_previous_user' => 'Override "Read Mode" will remove the patient from previous user',
'do_you_would_like_to_override_read_mode' => 'Do you would like to override "Read Mode"?',
'are_you_sure_to_quit' => 'Czy na pewno chcesz wyjść?',
'drop_here_to_open' => 'Drop Here To Open',
'current_encounter' => 'Bieżące badanie',
'access_denied' => 'Dostęp wzbroniony',
'reportable' => 'Reportable?',
'category' => 'Kategoria',
'sex' => 'Płeć',
'coding_system' => 'System kodowania',
'frequency' => 'Częstotliwość',
'age_start' => 'Age Start',
'must_be_pregnant' => 'Must be pregnant',
'times_to_perform' => 'Times to Perform',
'age_end' => 'Age End',
'perform_only_once' => 'perform only once',
'add_problem' => 'Dodaj problem',
'labs' => 'Laboratoria',
'value_name' => 'Nazwa wartości',
'less_than' => 'Mniej niż',
'greater_than' => 'Więcej niż',
'equal_to' => 'Równe z',
'short_name_alias' => 'Short Name (alias)',
'label_alias' => 'Label (alias)',
'loinc_name' => 'Loinc Name',
'loinc_number' => 'Loinc Number',
'default_unit' => 'Default Unit',
'req_opt' => 'Req / Opt',
'range_start' => 'Range Start',
'range_end' => 'Range End',
'code_type' => 'Code Type',
'short_name' => 'Short Name',
'long_name' => 'Long Name',
'show_inactive_codes_only' => 'Show Inactive Codes Only',
'ops_laboratories' => 'Sorry, Unable to add laboratories. Laboratory data are pre-loaded using<br>Logical Observation Identifiers Names and Codes (LOINC)<br>visit <a href="http://loinc.org/" target="_blank">loinc.org</a> for more info.',
'patient_full_name' => 'Pełne imię pacjenta',
'patient_mothers_maiden_name' => 'Nazwisko panieńskie matki pacjenta',
'patient_last_name' => 'Nazwisko pacjenta',
'patient_birthdate' => 'Data urodzenia pacjenta',
'patient_marital_status' => 'Stan cywilny pacjenta',
'patient_home_phone' => 'Telefon domowy pacjenta',
'patient_mobile_phone' => 'Telefon komórkowy pacjenta',
'patient_work_phone' => 'Telefon służbowy pacjenta',
'patient_email' => 'Adres email pacjenta',
'patient_social_security' => 'Patient Social Security',
'patient_sex' => 'Płeć pacjenta',
'patient_age' => 'Wiek pacjenta',
'patient_city' => 'Miejscowość zamieszkania pacjenta',
'patient_state' => 'Patient State',
'patient_home_address_line_1' => 'Adres zamieszkania pacjenta',
'patient_home_address_line_2' => 'Adres zamieszkania pacjenta (cd.)',
'patient_home_address_zip_code' => 'Kod pocztowy miejsca zamieszkania pacjenta',
'patient_home_address_city' => 'Patient Home Address City',
'patient_home_address_state' => 'Patient Home Address State',
'patient_postal_address_line_1' => 'Patient Postal Address Line 1',
'patient_postal_address_line_2' => 'Patient Postal Address Line 2',
'patient_postal_address_zip_code' => 'Patient Postal Address Zip Code',
'patient_postal_address_city' => 'Patient Postal Address City',
'patient_postal_address_state' => 'Patient Postal Address State',
'patient_tabacco' => 'Patient Tobacco',
'patient_alcohol' => 'Patient Alcohol',
'patient_drivers_license' => 'Patient Drivers License',
'patient_employeer' => 'Pracodawca pacjenta',
'patient_first_emergency_contact' => 'Osoba, którą powiadomić w razie wypadku',
'patient_referral' => 'Patient Referral',
'patient_date_referred' => 'Patient Date Referred',
'patient_balance' => 'Patient Balance',
'patient_picture' => 'Zdjęcie pacjenta',
'patient_primary_plan' => 'Patient Primary Plan',
'patient_primary_plan_insured_person' => 'Patient Primary Plan Insured Person',
'patient_primary_plan_contract_number' => 'Patient Primary Plan Contract Number',
'patient_primary_plan_expiration_date' => 'Patient Primary Plan Expiration Date',
'patient_secondary_plan' => 'Patient Secondary Plan',
'patient_secondary_insured_person' => 'Patient Secondary Insured Person',
'patient_secondary_plan_contract_number'=> 'Patient Secondary Plan Contract Number',
'patient_secondary_plan_expiration_date'=> 'Patient Secondary Plan Expiration Date',
'patient_referral_details' => 'Patient Referral details',
'patient_referral_reason' => 'Patient Referral reason',
'patient_head_circumference' => 'Patient Head Circumference',
'patient_height' => 'Wzrost pacjenta',
'patient_pulse' => 'Puls pacjenta',
'patient_respiratory_rate' => 'Patient Respiratory Rate',
'patient_temperature' => 'Temperatura pacjenta',
'patient_weight' => 'Waga pacjenta',
'patient_pulse_oximeter' => 'Patient Pulse Oximeter',
'patient_blood_preasure' => 'Ciśnienie krwi pacjenta',
'patient_body_mass_index' => 'BMI pacjenta',
'patient_active_allergies_list' => 'Patient Active Allergies List',
'patient_inactive_allergies_list' => 'Patient Inactive Allergies List',
'patient_active_medications_list' => 'Patient Active Medications List',
'patient_inactive_medications_list' => 'Patient Inactive Medications List',
'patient_active_problems_list' => 'Patient Active Problems List',
'patient_inactive_problems_list' => 'Patient Inactive Problems List',
'patient_active_immunizations_list' => 'Patient Active Immunizations List',
'patient_inactive_immunizations_list' => 'Patient Inactive Immunizations List',
'patient_active_dental_list' => 'Patient Active Dental List',
'patient_inactive_dental_list' => 'Patient Inactive Dental List',
'patient_active_surgery_list' => 'Patient Active Surgery List',
'patient_inactive_surgery_list' => 'Patient Inactive Surgery List',
'encounter_date' => 'Data badania',
'encounter_subjective_part' => 'Encounter Subjective Part',
'encounter_assesment' => 'Encounter Assessment',
'encounter_assesment_list' => 'Encounter Assessment List',
'encounter_assesment_code_list' => 'Encounter Assessment Code List',
'encounter_assesment_full_list' => 'Encounter Assessment Full List',
'encounter_plan' => 'Plan badania',
'encounter_medications' => 'Zastosowane leki',
'encounter_immunizations' => 'Encounter Immunizations',
'encounter_allergies' => 'Alergie',
'encounter_active_problems' => 'Aktywne problemy badania',
'encounter_surgeries' => 'Operacje chirurgiczne',
'encounter_dental' => 'Stomatologiczne',
'encounter_laboratories' => 'Laboratoria',
'encounter_procedures_terms' => 'Zasady procedur',
'encounter_cpt_codes_list' => 'Encounter CPT Codes List',
'encounter_signature' => 'Sygnatura badania',
'procedure' => 'Procedure',
'procedures' => 'Procedures',
'orders_laboratories' => 'Zlecenia laboratoryjne',
'orders_x_rays' => 'Zlecenia prześwietleń',
'orders_referral' => 'Orders Referral',
'orders_other' => 'Orders Other',
'current_date' => 'Current Date',
'current_time' => 'Current Time',
'current_user_name' => 'Current User Name',
'current_user_full_name' => 'Current User Full Name',
'current_user_license_number' => 'Current User License Number',
'current_user_dea_license_number' => 'Current User DEA License Number',
'current_user_dm_license_number' => 'Current User DM License Number',
'current_user_npi_license_number' => 'Current User NPI License Number',
'header_footer_templates' => 'Szablony nagłówków i stopek',
'documents_defaults' => 'Documents Defaults',
'document_templates' => 'Szablony dokumentów',
'document_editor' => 'Edytor dokumentów',
'available_tokens' => 'Available Tokens',
'new_document' => 'Nowy dokument',
'new_defaults' => 'New Defaults',
'new_header_or_footer' => 'Nowy nagłówek lub stopka',
'update_icd9' => 'Uaktualnij ICD9',
'update_icd10' => 'Uaktualnij ICD10',
'update_rxnorm' => 'Uaktualnij RxNorm',
'update_snomed' => 'Uaktualnij SNOMED',
'update_hcpcs' => 'Update HCPCS',
'current_version_installed' => 'Current Version Installed',
'no_data_installed' => 'Brak zainstalowanych danych',
'revision_name' => 'Revision Name',
'document_template_editor' => 'Edytor szablonów dokumentów',
'revision_number' => 'Numer rewizji',
'revision_version' => 'Wersja rewizji',
'revision_date' => 'Data rewizji',
'imported_on' => 'Zaimportowano',
'installation' => 'Instalacja',
'data_file' => 'Plik danych',
'version' => 'Wersja',
'file' => 'Plik',
'uploading_and_updating_code_database' => 'Uploading And Updating Code Database',
'installing_database_please_wait' => 'Instaluję bazę danych, proszę czekać',
'new_database_installed' => 'Zainstalowano nową bazę danych',
'facilities_active' => 'Facilities (Active)',
'phone' => 'Telefon',
'city' => 'Miejscowość',
'add_new_facility' => 'Add New Facility',
'show_active_facilities' => 'Show Active Facilities',
'show_inactive_facilities' => 'Show Inactive Facilities',
'edit_facility' => 'Edit Facility',
'street' => 'Ulica',
'state' => 'State',
'postal_code' => 'Kod pocztowy',
'country_code' => 'Kod kraju',
'tax_id' => 'Identyfikator podatkowy',
'service_location' => 'Service Location',
'billing_location' => 'Billing Location',
'accepts_assignment' => 'Accepts assignment',
'pos_code' => 'POS Code',
'billing_attn' => 'Billing Attn',
'clia_number' => 'CLIA Number',
'facility_npi' => 'Facility NPI',
'floor_plan_editor' => 'Floor Plan Editor',
'add_floor' => 'Dodaj poziom',
'floor_plan' => 'Floor Plan',
'add_zone' => 'Add Zone',
'new_zone' => 'New Zone',
'zone_name' => 'Zone Name',
'new_floor' => 'Nowy poziom',
'remove_floor' => 'Usuń poziom',
'last_first_middle' => 'Last, First Middle',
'first_middle_last' => 'First Middle Last',
'main_navigation_menu_left' => 'Main Navigation Menu (left)',
'main_navigation_menu_right' => 'Main Navigation Menu (right)',
'grey_default' => 'Szary (domyślny)',
'blue' => 'Niebieski',
'access' => 'Access',
'oldstyle_static_form_without_search_or_duplication_check' => 'Old-style static form without search or duplication check',
'all_demographics_fields_with_search_and_duplication_check' => 'All demographics fields, with search and duplication check',
'mandatory_or_specified_fields_only_search_and_dup_check' => 'Mandatory or specified fields only, search and dup check',
'mandatory_or_specified_fields_only_dup_check_no_search' => 'Mandatory or specified fields only, dup check, no search',
'encounter_statistics' => 'Statystyki badania',
'mandatory_and_specified_fields' => 'Mandatory and specified fields',
'show_both_us_and_metric_main_unit_is_us)' => 'Show both US and metric (main unit is US)',
'show_both_us_and_metric_main_unit_is_metric' => 'Show both US and metric (main unit is metric)',
'show_us_only' => 'Show US only',
'show_metric_only' => 'Show metric only',
'yyyy_mm_dd' => 'YYYY-MM-DD',
'mm_dd_yyyy' => 'MM/DD/YYYY',
'dd_mm_yyyy' => 'DD/MM/YYYY',
'24_hr' => '24 hr',
'12 hr' => '12 hr',
'0' => '0',
'1' => '1',
'2' => '2',
'comma' => 'Comma',
'period' => 'Period',
'text_field' => 'Text field',
'single_selection_list' => 'Single-selection list',
'single_selection_list_with_ability_to_add_to_the_list' => 'Single-selection list with ability to add to the list',
'option_1' => 'Option 1',
'option_2' => 'Option 2',
'option_3' => 'Option 3',
'option_4' => 'Option 4',
'option_5' => 'Option 5',
'option_6' => 'Option 6',
'option_7' => 'Option 7',
'appearance' => 'Appearance',
'main_top_pane_screen' => 'Main Top Pane Screen',
'layout_style' => 'Layout Style',
'theme' => 'Theme',
'navigation_area_width' => 'Szerokość obszaru nawigacji',
'application_title' => 'Tytuł aplikacji',
'new_patient_form' => 'Nowy formularz pacjenta',
'patient_search_resuls_style' => 'Styl wyszukiwarki pacjentów',
'simplified_prescriptions' => 'Simplified Prescriptions',
'simplified_demographics' => 'Simplified Demographics',
'simplified_copay' => 'Simplified Co-Pay',
'user_charges_panel' => 'User Charges Panel',
'online_support_link' => 'Online Support Link',
'fullname_format' => 'Full Name Format',
'default_language' => 'Język domyślny',
'all_language_allowed' => 'Wszystkie języki dozwolone',
'allowed_languages' => 'Dozwolone języki',
'allow_debuging_language' => 'Allow Debugging Language',
'translate_layouts' => 'Translate Layouts',
'translate_list' => 'Translate List',
'translate_access_control_roles' => 'Translate Access Control Roles',
'translate_patient_note_titles' => 'Translate Patient Note Titles',
'translate_documents_categoies' => 'Translate Documents Categories',
'translate_appointment_categories' => 'Translate Appointment Categories',
'units_for_visits_forms' => 'Units for Visits Forms',
'disable_old_metric_vitals_form' => 'Disable Old Metric Vitals Form',
'telephone_country_code' => 'Numer kierunkowy kraju',
'date_display_format' => 'Format wyświetlania daty',
'time_display_format' => 'Format wyświetlania czasu',
'currency_decimal_places' => 'Ilość miejsc po przecinku dla waluty',
'currency_decimal_point_symbol' => 'Znak separatora waluty',
'currency_thousands_separator' => 'Separator tysięcy',
'currency_designator' => 'Currency Designator',
'specific_application' => 'Specific Application',
'drugs_and_prodructs' => 'Leki i produkty',
'disable_chart_tracker' => 'Disable Chart Tracker',
'disable_immunizations' => 'Disable Immunizations',
'disable_prescriptions' => 'Disable Prescriptions',
'omit_employers' => 'Omit Employers',
'support_multiprovider_events' => 'Support Multi-Provider Events',
'disable_user_groups' => 'Disable User Groups',
'skip_authorization_of_patient_notes' => 'Skip Authorization of Patient Notes',
'allow_encounters_claims' => 'Allow Encounters Claims',
'advance_directives_warning' => 'Advance Directives Warning',
'configuration_export_import' => 'Configuration Export/Import',
'restrict_users_to_facilities' => 'Restrict Users to Facilities',
'remember_selected_facility' => 'Remember Selected Facility',
'discounts_as_monetary_ammounts' => 'Discounts as monetary Amounts',
'referral_source_for_encounters' => 'Referral Source for Encounters',
'maks_for_patients_ids' => 'Mask for Patients IDs',
'mask_of_invoice_numbers' => 'Mask of Invoice Numbers',
'mask_for_product_ids' => 'Mask for Product IDs',
'force_billing_widget_open' => 'Force Billing Widget Open',
'actiate_ccr_ccd_reporting' => 'Activate CCR/CCD Reporting',
'hide_encryption_decryption_options_in_document_managment' => 'Hide Encryption/Decryption Options in Document Management',
'disable_calendar' => 'Wyłącz kalendarz',
'calendar_starting_hour' => 'Godzina początkowa kalendarza',
'calendar_ending_hour' => 'Godzina końcowa kalendarza',
'calendar_interval' => 'Calendar Interval',
'appointment_display_style' => 'Styl wyświetlania terminów',
'provider_see_entire_calendar' => 'Provider See Entire Calendar',
'auto_create_new_encounters' => 'Automatycznie twórz nowe spotkania',
'appointment_event_color' => 'Kolor terminów/zdarzeń',
'idle_session_timeout_seconds' => 'Idle Session Timeout Seconds',
'require_strong_passwords' => 'Wymagaj silnych haseł',
'require_unique_passwords' => 'Wymagaj unikalnych haseł',
'defaults_password_expiration_days' => 'Defaults Password Expiration Days',
'password_expiration_grace_period' => 'Okres ważności hasła',
'enable_clients_ssl' => 'Enable Clients SSL',
'notification_email_address' => 'Adres email dla powiadomień',
'notifications' => 'Powiadomienia',
'email_transport_method' => 'Email Transport Method',
'smpt_server_hostname' => 'SMPT Server Hostname',
'smpt_server_port_number' => 'SMPT Server Port Number',
'smpt_user_for_authentication' => 'SMPT User for Authentication',
'smpt_password_for_authentication' => 'SMPT Password for Authentication',
'email_notification_hours' => 'Godziny powiadomień email',
'sms_notification_hours' => 'Godziny powiadomień SMS',
'sms_gateway_usarname' => 'SMS Gateway Username',
'sms_gateway_password' => 'SMS Gateway Password',
'sms_gateway_api_Key' => 'SMS Gateway API Key',
'logging' => 'Logging',
'enable_audit_logging' => 'Enable Audit Logging',
'audit_logging_patient_record' => 'Audit Logging Patient Record',
'audid_logging_scheduling' => 'Audit Logging Scheduling',
'audid_logging_order' => 'Audit Logging Order',
'audid_logging_security_administration' => 'Audit Logging Security Administration',
'audid_logging_backups' => 'Audit Logging Backups',
'audid_logging_miscellaeous' => 'Audit Logging Miscellaneous',
'audid_logging_select_query' => 'Audit Logging SELECT Query',
'enable_atna_auditing' => 'Enable ATNA Auditing',
'atna_audit_host' => 'ATNA audit host',
'atna_audit_post' => 'ATNA audit post',
'atna_audit_local_certificate' => 'ATNA audit local certificate',
'atna_audit_ca_certificate' => 'ATNA audit CA certificate',
'path_to_mysql_binaries' => 'Path to MySQL Binaries',
'path_to_perl_binaries' => 'Path to Perl Binaries',
'path_to_temporary_files' => 'Path to Temporary Files',
'path_for_event_log_backup' => 'Path for Event Log Backup',
'state_data_type' => 'State Data Type',
'state_list' => 'State List',
'state_list_widget_custom_fields' => 'State List Widget Custom Fields',
'country_data_type' => 'Country Data Type',
'country_list' => 'Country list',
'print_command' => 'Print Command',
'default_reason_for_visit' => 'Default Reason for Visit',
'default_encounter_form_id' => 'Domyślny identyfikator formularza badania',
'patient_id_category_name' => 'Patient ID Category Name',
'patient_photo_category_name' => 'Patient Photo Category name',
'medicare_referrer_is_renderer' => 'Medicare Referrer is Renderer',
'final_close_date_yyy_mm_dd' => 'Final Close Date (yyy-mm-dd)',
'enable_hylafax_support' => 'Enable Hylafax Support',
'hylafax_server' => 'Hylafax Server',
'hylafax_directory' => 'Hylafax Directory',
'hylafax_enscript_command' => 'Hylafax Enscript Command',
'enable_scanner_support' => 'Enable Scanner Support',
'scanner_directory' => 'Scanner Directory',
'connectors' => 'Connectors',
'enable_lab_exchange' => 'Enable Lab Exchange',
'lab_exchange_site_id' => 'Lab Exchange Site ID',
'lab_exchange_token_id' => 'Lab Exchange Token ID',
'lab_exchange_site_address' => 'Lab Exchange Site Address',
'save_configuration' => 'Save Configuration',
'new_global_configuration_saved' => 'New Global Configuration Saved',
'refresh_the_application' => 'For some settings to take place you will have to refresh the application.',
'value' => 'Value',
'pos' => 'pos',
'form_id' => 'form_id',
'child_of' => 'Child Of',
'aditional_properties' => 'Właściwości dodatkowe',
'field_label' => 'Etykieta pola',
'box_label' => 'Etykieta kontenera',
'label_width' => 'Szerokość etykiety',
'hide_label' => 'Ukryj etykietę',
'empty_text' => 'Empty Text',
'layout' => 'Układ',
'input_value' => 'Input Value',
'width' => 'Szerokość',
'height' => 'Wysokość',
'anchor' => 'Anchor',
'flex' => 'Flex',
'collapsible' => 'Zwijalny',
'checkbox_toggle' => 'Checkbox Toggle',
'collapsed' => 'Zwinięty',
'margin' => 'Margines',
'column_width' => 'Szerokość kolumny',
'is_required' => 'Jest wymagany',
'max_value' => 'Wartość maksymalna',
'min_value' => 'Wartość minimalna',
'grow' => 'Grow',
'grow_min' => 'Grow Min',
'grow_max' => 'Grow Max',
'increment' => 'Increment',
'list_options' => 'Opcje listy',
'field_configuration' => 'Konfiguracja pola',
'add_child' => 'Add Child',
'form_preview' => 'Podgląd formularza',
'field_editor_demographics' => 'Field editor (Demographics)',
'field_type' => 'Typ pola',
'label' => 'Etykieta',
'form_list' => 'Lista formularzy',
'delete_this_field' => 'Czy na pewno chcesz usunąć to pole',
'field_deleted' => 'Pole usunięte',
'form_fields_sorted' => 'Posortowano pola formularza',
'field_editor' => 'Edytor pól',
'or_select_a_field_to_update' => 'Click "Add New" or Select a field to update',
'select_list_options' => 'Wybierz opcje listy',
'select_lists' => 'Wybierz listy',
'in_use' => 'W użyciu?',
'new_list' => 'Nowa lista',
'delete_list' => 'Usuń listę',
'can_be_disable' => 'Lists currently in used by forms can NOT be deleted, but they can be disabled',
'drag_and_drop_reorganize' => 'Przeciągnij i upuść, aby reorganizować',
'option_title' => 'Tytuł opcji',
'option_value' => 'Wartość opcji',
'add_option' => 'Dodaj opcję',
'delete_this_record' => 'Are you sure to delete this record?',
'list' => 'Lista',
'unable_to_delete' => 'Nie można usunąć',
'list_currently_used_forms' => 'Ta lista jest aktualnie używana przed jeden lub więcej formularzy',
'event_history_log' => 'Dziennik historii zdarzeń',
'view_log_event_details' => 'View Log Event Details',
'log_event_details' => 'Log Event Details',
'number' => 'Numer',
'active_component' => 'Active Component',
'dosage' => 'Dosage',
'unit' => 'Jednostka',
'dosis' => 'Dosis',
'practice_settings' => 'Practice Settings',
'address' => 'Adres',
'address_cont' => 'Adres (cd.)',
'city_state_zip' => 'Miejscowość, kod pocztowy',
'default_method' => 'Default Method',
'cms_id' => 'CMS ID',
'payer_type' => 'Payer Type',
'pharmacy_name' => 'Pharmacy Name',
'add_new_pharmacy' => 'Add New Pharmacy',
'insurance_companies' => 'Firmy ubezpieczeniowe',
'insurance_name' => 'Nazwa ubezpieczenia',
'default_x12_partner' => 'Default X12 Partner',
'add_new_insurance' => 'Dodaj nowe ubezpieczenie',
'x12_partners_clearing_houses' => 'X12 Partners (clearing houses)',
'sender_id' => 'Identyfikator nadawcy',
'receiver_id' => 'Identyfikator odbiorcy',
'hl7_viewer' => 'HL7 Viewer',
'clear_hl7_data' => 'Clear HL7 Data',
'parse_hl7' => 'Parse HL7',
'greater_than_1_or_just_check_perform_once' => 'Please enter a number greater than 1 or just check "Perform once"',
'add_labs' => 'Dodaj Laboratoria',
'roles_and_permissions' => 'Role i uprawnienia',
'permission' => 'Uprawnienie',
'front_office' => 'Front Office',
'auditors' => 'Auditors',
'clinician' => 'Clinician',
'physician' => 'Physician',
'administrator' => 'Administrator',
'saving_roles' => 'Zapisuję role, proszę czekać',
'roles_updated' => 'Role zostały uaktualnione',
'loading' => 'Ładuję',
'loading...' => 'Loading...',
'aditional_info' => 'Dodatkowe informacje',
'authorized' => 'Authorized?',
'calendar_q' => 'Kalendarz?',
'edit_user' => 'Edytuj użytkownika',
'add_new_user' => 'Dodaj nowego użytkownika',
'username' => 'Nazwa użytkownika',
'password' => 'Hasło',
'default_facility' => 'Default Facility',
'authorizations' => 'Authorizations',
'access_control' => 'Access Control',
'taxonomy' => 'Taxonomy',
'federal_tax_id' => 'Federal Tax ID',
'fed_drug_id' => 'Fed Drug ID',
'upin' => 'UPIN',
'npi' => 'NPI',
'job_description' => 'Job Description',
'password_currently_used' => 'This password is currently in used, or has been used before.<br>Please use a different password.',
'remove_patient' => 'Remove Patient',
'successfully_moved' => 'successfully moved',
'sent_to' => 'sent to',
'working' => 'Working',
'reports' => 'Reports',
'reportCenter' => 'Report Center',
'national_library' => 'National Library of Medicine Search',
'add_appointment' => 'Add Appointment',
'edit_appointment' => 'Edit Appointment',
'when' => 'When',
'web_link' => 'Web Link',
'repeats' => 'Repeats',
'edit_details' => 'Edit Details',
'saving_changes' => 'Saving changes',
'deleting_appointment' => 'Deleting appointment',
'select' => 'Select',
'all' => 'All',
'other_hcfa' => 'Other HCFA',
'medicare_part_b' => 'Medicare Part B',
'medicaid' => 'Medicaid',
'champusva' => 'ChampUSVA',
'champus' => 'ChampUS',
'blue_cross_blue_shield' => 'Blue Cross Blue Shield',
'feca' => 'FECA',
'self_pay' => 'Self Pay',
'central_certification' => 'Central Certification',
'other_nonfederal_programs' => 'Other Non-Federal Programs',
'ppo' => 'Preferred Provider Organization (PPO)',
'epo' => 'Exclusive Provider Organization (EPO)',
'indemnity_insurance' => 'Indemnity Insurance',
'hmo' => 'Health Maintenance Organization (HMO) Medicare Risk',
'automobile_medical' => 'Automobile Medical',
'commercial_insurance' => 'Commercial Insurance Co.',
'disability' => 'Disability',
'health_maintenance_organization' => 'Health Maintenance Organization',
'liability' => 'Liability',
'liability_medical' => 'Liability Medical',
'other_federal_program' => 'Other Federal Program',
'title_v' => 'Title V',
'veterans_administration_plan' => 'Veterans Administration Plan',
'workers_compensation_health_plan' => 'Workers Compensation Health Plan',
'mutually_defined' => 'Mutually Defined',
'select_existing_observation' => 'Select Existing Observation',
'threshold' => 'Threshold',
'help_message' => 'Help Message',
'errors' => 'Errors',
'commit_cancel_your_changes' => 'You need to commit or cancel your changes',
'unable_to_locate_address' => 'Unable to Locate Address',
'unable_locate_address_provided' => 'Unable to Locate the Address you provided',
'address_accuracy' => 'Address Accuracy',
'address_provided_low_accuracy' => 'The address provided has a low accuracy.',
'accuracy' => 'Accuracy',
'exact_match' => 'Dokładne trafienie',
'vague_match' => 'Niepewne trafienie',
'error_returned' => 'Błąd',
'nothing_found' => 'Nic nie znaleziono',
'find_previous_row' => 'Find Previous Row',
'find_next_row' => 'Find Next Row',
'regular_expression' => 'Regular expression',
'case_sensitive' => 'Uwzględnij wielkość liter',
'matches_found' => 'trafień.',
'config_required_not_defined' => 'config is required and is not defined.',
'the' => 'The',
'of' => 'of',
'close_other_tabs' => 'Zamknij inne karty',
'close_all_tabs' => 'Zamknij wszystkie karty',
'form_has_errors' => 'Formularz zawiera błędy (kliknij, aby dowiedzieć się szczegółów...)',
'click_again_hide_the_error_list' => 'Kliknij ponownie, aby ukryć listę błędów',
'saving' => 'Zapisuję',
'copyright_notice' => 'Nota prawna',
'select_patient_patient_live_search' => 'Please select a patient using the <strong>"Patient Live Search"</strong> or <strong>"Patient Pool Area"</strong>',
'password_verification' => 'Weryfikacja hasła',
'please_enter_your_password' => 'Wprowadź swoje hasło',
'search_for_a_immunizations' => 'Search for a Immunizations',
'search_for_a_medication' => 'Search for a Medication',
'search_for_a_surgery' => 'Search for a Surgery',
'frames_are_disabled' => 'Frames are disabled',
'capture' => 'Capture',
'read_only' => 'Tylko odczyt',
'vtype_empty_3chr' => 'To pole musi zawierać więcej niż 3 znaki i nie może pozostać puste.',
'vtype_empty_7chr' => 'To pole musi zawierać więcej niż 7 znaków i nie może pozostać puste.',
'vtype_empty' => 'To pole nie może być puste.',
'vtype_ssn' => 'Social Security Numbers, must no be empty or in the wrong format. (555-55-5555).',
'vtype_dateVal' => 'Nieprawidłowy format daty (RRRR-MM-DD).',
'vtype_checkEmail' => 'To pole powinno zawierać adres email w formacie użytkownik@domena.com',
'vtype_ipaddress' => 'To pole powinno zawierać adres IP w formacie 192.168.0.1',
'vtype_phoneNumber' => 'This field should be an valid PHONE number, in the format (000)-000-0000',
'vtype_postalCode' => 'This field should be an valid Postal Code number, it can by Canadian or US',
'vtype_password' => 'Hasła nie pokrywają się',
'vtype_mysqlField' => 'Pole zawiera niedozwolone znaki',
'patient_visits_history' => 'Patient Visits History',
'source' => 'Źródło',
'path_to_ca_certificate_file' => 'Path to CA Certificate File',
'path_to_ca_key_file' => 'Path to CA Key File',
'client_certificate_expiration_days' => 'Client Certificate Expiration Days',
'emergency_login_email_address' => 'Emergency Login Email Address',
'layout_form_editor' => 'Layout Form Editor',
'facility' => 'Facility',
'comments' => 'Komentarze',
'user_notes' => 'user Notes',
'patient_id' => 'Identyfikator pacjenta',
'success' => 'Powodzenie',
'check_sum' => 'Suma kontrolna',
'crt_user' => 'CRT USER',
'read_mode' => 'Tryb odczytu',
'day_s' => 'dzień/dni',
'event_form' => 'Event Form',
'close_tab' => 'Zamknij kartę',
'items' => 'Items',
'modules' => 'Moduły',
'report_center' => 'Report Center Basic',
'patient_reports' => 'Patient Reports',
'patient_list' => 'Lista pacjentów',
'prescriptions_and_dispensations' => 'Prescriptions and Dispensations',
'clinical' => 'Clinical',
'referrals' => 'Referrals',
'immunization_registry' => 'Immunization Registry',
'clinic_reports' => 'Clinic Reports',
'standard_measures' => 'Standard Measures',
'clinical_quality_measures_cqm' => 'Clinical Quality Measures (CQM)',
'automated_measure_calculations_amc' => 'Automated Measure Calculations (AMC)',
'automated_measure_calculations_tracking' => 'Automated Measure Calculations (AMC) Tracking',
'client_list_report' => 'Client List Report',
'filter' => 'Filtr',
'create_report' => 'Utwórz raport',
'create_pdf' => 'Utwórz PDF',
'create_html' => 'Utwórz HTML',
'last_visit' => 'Ostatnia wizyta',
'id' => 'Identyfikator',
'zipcode' => 'Kod pocztowy',
'visit_reports' => 'Visit Reports',
'super_bill' => 'Super Billing',
'patient_data' => 'Dane pacjenta',
'social_security' => 'Social Security',
'date_of_birth' => 'Data urodzenia',
'zip' => 'Kod pocztowy',
'mobile_phone' => 'Telefon komórkowy',
'emer_phone' => 'Emergency Phone',
'emer_contact' => 'Emergency Contact',
'insurance_data' => 'Dane ubezpieczenia',
'plan_name' => 'Plan Name',
'policy_number' => 'Policy Number',
'group_number' => 'Numer grupy',
'subscriber_name' => 'Subscriber Name',
'relationship' => 'Relationship',
'subscriber_employer' => 'Subscriber Employer',
'subscriber_address' => 'Subscriber Address',
'employer_address' => 'Employer Address',
'effective_date' => 'Effective Date',
'primary' => 'Primary',
'secondary' => 'Secondary',
'tertiary' => 'Tertiary',
'billing_information' => 'Billing Information',
'image_forms' => 'Image Forms',
'disclosure' => 'Disclosure',
'disclosures' => 'Disclosures',
'rx' => 'Rx',
'drug' => 'Drug',
'recipient_name' => 'Recipient Name',
'generate_x12' => 'Generate x12',
'generate_cms1500_pdf' => 'Generate CMS 1500 PDF format',
'generate_cms1500_text' => 'Generate CMS 1500 TXT format',
'utilities' => 'Utilities',
'drug_name' => 'Drug Name',
'units' => 'Units',
'drugs' => 'Drugs',
'end' => 'End',
'age_from' => 'Age From',
'date_from' => 'Date From',
'age_to' => 'Age To',
'date_to' => 'Date To',
'immunization_code' => 'Immunization Code',
'instructed' => 'Instructed',
'Administered' => 'Administered',
'race' => 'Race',
'ethnicity' => 'Ethnicity',
'problem_dx' => 'Problem DX',
'search_for_a_patient' => 'Search for a Patient',
'manufacturer' => 'Producent',
'autosave_forms' => 'Auto Save Forms',
'autosave' => 'Auto Save',
'generate' => 'Generate',
'generate_report' => 'Generate Report',
'pdf' => 'PDF',
'get_pdf' => 'Get PDF',
'generate_pdf' => 'Generate PDF',
'patient_btn_drag' => 'Click for Summary or Drag to Send Patient to Another Pool Area',
'username_exist_alert' => 'Username exist, please try a unique username',
'record_saved' => 'Record Saved',
'record_removed' => 'Record Removed',
'zone_editor' => 'Zone Editor',
'bg_color' => 'Background Color',
'border_color' => 'Kolor ramki',
'show_priority_color' => 'Pokaż kolor priorytetu',
'show_patient_preview' => 'Pokaż podgląd pacjenta',
'30+' => '30+',
'60+' => '60+',
'120+' => '120+',
'180+' => '180+',
'applications' => 'Aplikacje',
'private_key' => 'Klucz prywatny',
'administered_date' => 'Administered Date',
'immunization_id' => 'Immunization Id',
'instructions' => 'Instructions',
'clone_prescription' => 'Clone Prescription',
'template' => 'Template',
'create_doctors_notes' => 'Create Doctors Notes',
'prescriptions' => 'Prescriptions',
'prescription' => 'Prescription',
'add_medication' => 'Add Medication',
'encounter_icd9' => 'Badanie ICD9',
'signed_by' => 'Podpisane przez',
'key_if_required' => 'Key (if required)',
'enabled?' => 'Enabled?',
'related_dx' => 'Related Dx',
'live_styles' => 'Live Styles',
'administered_by' => 'Administered by',
'loinc' => 'LOINC',
'new_order' => 'New Order',
'add_item' => 'Add Item',
'new_item' => 'New Item',
'other' => 'Other',
'other_order_item_help_text' => 'Use commas (,) if more than one. ei: X-RAY Thoracic Spine, X-RAY Skull 3 View',
'form' => 'Form',
'templates' => 'Templates',
'snippets' => 'Snippets',
'complete_snippet' => 'Complete Snippet',
'done' => 'Done',
'ok' => 'Ok',
'submit' => 'Submit',
'shift_enter_submit' => 'Shift + Enter to Submit',
'add_category' => 'Add Category',
'add_snippet' => 'Add Snippet',
'service' => 'Service',
'added' => 'Added',
'copay' => 'Co-Pay',
'add_new_laboratory' => 'Add New Laboratory'
); | chithubco/doctorapp | langs/pl_All.php | PHP | gpl-3.0 | 59,528 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Unigram.Controls.Views
{
public sealed partial class EditYourAboutView : ContentDialog
{
public EditYourAboutView(string bio)
{
this.InitializeComponent();
FieldAbout.Text = bio;
Title = Strings.Resources.UserBio;
PrimaryButtonText = Strings.Resources.OK;
SecondaryButtonText = Strings.Resources.Cancel;
}
public string About
{
get
{
return FieldAbout.Text;
}
}
private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}
private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}
}
}
| ikarago/Unigram | Unigram/Unigram/Controls/Views/EditYourAboutView.xaml.cs | C# | gpl-3.0 | 1,250 |
export type eventNS = string[];
export interface ConstructorOptions {
/**
* @default false
* @description set this to `true` to use wildcards.
*/
wildcard?: boolean,
/**
* @default '.'
* @description the delimiter used to segment namespaces.
*/
delimiter?: string,
/**
* @default true
* @description set this to `true` if you want to emit the newListener events.
*/
newListener?: boolean,
/**
* @default 10
* @description the maximum amount of listeners that can be assigned to an event.
*/
maxListeners?: number
/**
* @default false
* @description show event name in memory leak message when more than maximum amount of listeners is assigned, default false
*/
verboseMemoryLeak?: boolean;
}
export interface Listener {
(...values: any[]): void;
}
export interface EventAndListener {
(event: string | string[], ...values: any[]): void;
}
export declare class EventEmitter2 {
constructor(options?: ConstructorOptions)
emit(event: string | string[], ...values: any[]): boolean;
emitAsync(event: string | string[], ...values: any[]): Promise<any[]>;
addListener(event: string, listener: Listener): this;
on(event: string | string[], listener: Listener): this;
prependListener(event: string | string[], listener: Listener): this;
once(event: string | string[], listener: Listener): this;
prependOnceListener(event: string | string[], listener: Listener): this;
many(event: string | string[], timesToListen: number, listener: Listener): this;
prependMany(event: string | string[], timesToListen: number, listener: Listener): this;
onAny(listener: EventAndListener): this;
prependAny(listener: EventAndListener): this;
offAny(listener: Listener): this;
removeListener(event: string | string[], listener: Listener): this;
off(event: string, listener: Listener): this;
removeAllListeners(event?: string | eventNS): this;
setMaxListeners(n: number): void;
eventNames(): string[];
listeners(event: string | string[]): () => {}[] // TODO: not in documentation by Willian
listenersAny(): () => {}[] // TODO: not in documentation by Willian
}
| UnSpiraTive/radio | node_modules/eventemitter2/eventemitter2.d.ts | TypeScript | gpl-3.0 | 2,291 |
<?php
/*
Gibbon, Flexible & Open School System
Copyright (C) 2010, Ross Parker
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/>.
*/
use Gibbon\Domain\System\SettingGateway;
use Gibbon\Data\Validator;
require_once '../../gibbon.php';
$_POST = $container->get(Validator::class)->sanitize($_POST);
$URL = $session->get('absoluteURL').'/index.php?q=/modules/System Admin/services_manage.php';
if (isActionAccessible($guid, $connection2, '/modules/System Admin/services_manage.php') == false) {
$URL .= '&return=error0';
header("Location: {$URL}");
} else {
//Proceed!
$partialFail = false;
$settingGateway = $container->get(SettingGateway::class);
$settingsToUpdate = [
'System' => [
'gibboneduComOrganisationName',
'gibboneduComOrganisationKey',
]
];
foreach ($settingsToUpdate as $scope => $settings) {
foreach ($settings as $name) {
$value = $_POST[$name] ?? '';
$updated = $settingGateway->updateSettingByScope($scope, $name, $value);
$partialFail &= !$updated;
}
}
getSystemSettings($guid, $connection2);
$URL .= $partialFail
? '&return=error2'
: '&return=success0';
header("Location: {$URL}");
}
| GibbonEdu/core | modules/System Admin/services_manageProcess.php | PHP | gpl-3.0 | 1,825 |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Text;
using Org.BouncyCastle.Security;
using Telegram.Api.Helpers;
using Telegram.Api.TL;
using Telegram.Api.TL.Methods;
namespace Telegram.Api.Services
{
public class AuthKeyItem
{
public long AutkKeyId { get; set; }
public byte[] AuthKey { get; set; }
}
public partial class MTProtoService
{
/// <summary>
/// Список имеющихся ключей авторизации
/// </summary>
private static readonly Dictionary<long, AuthKeyItem> _authKeys = new Dictionary<long, AuthKeyItem>();
private static readonly object _authKeysRoot = new object();
private void ReqPQAsync(TLInt128 nonce, Action<TLResPQ> callback, Action<TLRPCError> faultCallback = null)
{
var obj = new TLReqPQ{ Nonce = nonce };
SendNonEncryptedMessage("req_pq", obj, callback, faultCallback);
}
private void ReqDHParamsAsync(TLInt128 nonce, TLInt128 serverNonce, byte[] p, byte[] q, long publicKeyFingerprint, byte[] encryptedData, Action<TLServerDHParamsBase> callback, Action<TLRPCError> faultCallback = null)
{
var obj = new TLReqDHParams { Nonce = nonce, ServerNonce = serverNonce, P = p, Q = q, PublicKeyFingerprint = publicKeyFingerprint, EncryptedData = encryptedData };
SendNonEncryptedMessage("req_DH_params", obj, callback, faultCallback);
}
public void SetClientDHParamsAsync(TLInt128 nonce, TLInt128 serverNonce, byte[] encryptedData, Action<TLSetClientDHParamsAnswerBase> callback, Action<TLRPCError> faultCallback = null)
{
var obj = new TLSetClientDHParams { Nonce = nonce, ServerNonce = serverNonce, EncryptedData = encryptedData };
SendNonEncryptedMessage("set_client_DH_params", obj, callback, faultCallback);
}
private TimeSpan _authTimeElapsed;
public void InitAsync(Action<Tuple<byte[], long?, long?>> callback, Action<TLRPCError> faultCallback = null)
{
var authTime = Stopwatch.StartNew();
var newNonce = TLInt256.Random();
#if LOG_REGISTRATION
TLUtils.WriteLog("Start ReqPQ");
#endif
var nonce = TLInt128.Random();
ReqPQAsync(nonce,
resPQ =>
{
var serverNonce = resPQ.ServerNonce;
if (nonce != resPQ.Nonce)
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "incorrect nonce" };
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqPQ with error " + error);
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
}
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqPQ");
#endif
TimeSpan calcTime;
Tuple<ulong, ulong> pqPair;
var innerData = GetInnerData(resPQ, newNonce, out calcTime, out pqPair);
var encryptedInnerData = GetEncryptedInnerData(innerData);
#if LOG_REGISTRATION
var pq = BitConverter.ToUInt64(resPQ.PQ.Data.Reverse().ToArray(), 0);
var logPQString = new StringBuilder();
logPQString.AppendLine("PQ Counters");
logPQString.AppendLine();
logPQString.AppendLine("pq: " + pq);
logPQString.AppendLine("p: " + pqPair.Item1);
logPQString.AppendLine("q: " + pqPair.Item2);
logPQString.AppendLine("encrypted_data length: " + encryptedInnerData.Data.Length);
TLUtils.WriteLog(logPQString.ToString());
TLUtils.WriteLog("Start ReqDHParams");
#endif
ReqDHParamsAsync(
resPQ.Nonce,
resPQ.ServerNonce,
innerData.P,
innerData.Q,
resPQ.ServerPublicKeyFingerprints[0],
encryptedInnerData,
serverDHParams =>
{
if (nonce != serverDHParams.Nonce)
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "incorrect nonce" };
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqDHParams with error " + error);
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
}
if (serverNonce != serverDHParams.ServerNonce)
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "incorrect server_nonce" };
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqDHParams with error " + error);
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
}
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqDHParams");
#endif
var random = new SecureRandom();
var serverDHParamsOk = serverDHParams as TLServerDHParamsOk;
if (serverDHParamsOk == null)
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "Incorrect serverDHParams " + serverDHParams.GetType() };
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
#if LOG_REGISTRATION
TLUtils.WriteLog("ServerDHParams " + serverDHParams);
#endif
return;
}
var aesParams = GetAesKeyIV(resPQ.ServerNonce.ToArray(), newNonce.ToArray());
var decryptedAnswerWithHash = Utils.AesIge(serverDHParamsOk.EncryptedAnswer, aesParams.Item1, aesParams.Item2, false);
//var position = 0;
//var serverDHInnerData = (TLServerDHInnerData)new TLServerDHInnerData().FromBytes(decryptedAnswerWithHash.Skip(20).ToArray(), ref position);
var serverDHInnerData = TLFactory.From<TLServerDHInnerData>(decryptedAnswerWithHash.Skip(20).ToArray());
var sha1 = Utils.ComputeSHA1(serverDHInnerData.ToArray());
if (!TLUtils.ByteArraysEqual(sha1, decryptedAnswerWithHash.Take(20).ToArray()))
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "incorrect sha1 TLServerDHInnerData" };
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqDHParams with error " + error);
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
}
if (!TLUtils.CheckPrime(serverDHInnerData.DHPrime, serverDHInnerData.G))
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "incorrect (p, q) pair" };
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqDHParams with error " + error);
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
}
if (!TLUtils.CheckGaAndGb(serverDHInnerData.GA, serverDHInnerData.DHPrime))
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "incorrect g_a" };
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqDHParams with error " + error);
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
}
var bBytes = new byte[256]; //big endian B
random.NextBytes(bBytes);
var gbBytes = GetGB(bBytes, serverDHInnerData.G, serverDHInnerData.DHPrime);
var clientDHInnerData = new TLClientDHInnerData
{
Nonce = resPQ.Nonce,
ServerNonce = resPQ.ServerNonce,
RetryId = 0,
GB = gbBytes
};
var encryptedClientDHInnerData = GetEncryptedClientDHInnerData(clientDHInnerData, aesParams);
#if LOG_REGISTRATION
TLUtils.WriteLog("Start SetClientDHParams");
#endif
SetClientDHParamsAsync(resPQ.Nonce, resPQ.ServerNonce, encryptedClientDHInnerData,
dhGen =>
{
if (nonce != dhGen.Nonce)
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "incorrect nonce" };
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop SetClientDHParams with error " + error);
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
}
if (serverNonce != dhGen.ServerNonce)
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "incorrect server_nonce" };
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop SetClientDHParams with error " + error);
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
}
var dhGenOk = dhGen as TLDHGenOk;
if (dhGenOk == null)
{
var error = new TLRPCError { ErrorCode = 404, ErrorMessage = "Incorrect dhGen " + dhGen.GetType() };
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
#if LOG_REGISTRATION
TLUtils.WriteLog("DHGen result " + serverDHParams);
#endif
return;
}
_authTimeElapsed = authTime.Elapsed;
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop SetClientDHParams");
#endif
var getKeyTimer = Stopwatch.StartNew();
var authKey = GetAuthKey(bBytes, serverDHInnerData.GA.ToBytes(), serverDHInnerData.DHPrime.ToBytes());
var logCountersString = new StringBuilder();
logCountersString.AppendLine("Auth Counters");
logCountersString.AppendLine();
logCountersString.AppendLine("pq factorization time: " + calcTime);
logCountersString.AppendLine("calc auth key time: " + getKeyTimer.Elapsed);
logCountersString.AppendLine("auth time: " + _authTimeElapsed);
#if LOG_REGISTRATION
TLUtils.WriteLog(logCountersString.ToString());
#endif
//newNonce - little endian
//authResponse.ServerNonce - little endian
var salt = GetSalt(newNonce.ToArray(), resPQ.ServerNonce.ToArray());
var sessionId = new byte[8];
random.NextBytes(sessionId);
TLUtils.WriteLine("Salt " + BitConverter.ToInt64(salt, 0) + " (" + BitConverter.ToString(salt) + ")");
TLUtils.WriteLine("Session id " + BitConverter.ToInt64(sessionId, 0) + " (" + BitConverter.ToString(sessionId) + ")");
callback(new Tuple<byte[], long?, long?>(authKey, BitConverter.ToInt64(salt, 0), BitConverter.ToInt64(sessionId, 0)));
},
error =>
{
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop SetClientDHParams with error " + error.ToString());
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
});
},
error =>
{
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqDHParams with error " + error.ToString());
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
});
},
error =>
{
#if LOG_REGISTRATION
TLUtils.WriteLog("Stop ReqPQ with error " + error.ToString());
#endif
if (faultCallback != null) faultCallback(error);
TLUtils.WriteLine(error.ToString());
});
}
private static TLPQInnerData GetInnerData(TLResPQ resPQ, TLInt256 newNonce, out TimeSpan calcTime, out Tuple<ulong, ulong> pqPair)
{
var pq = BitConverter.ToUInt64(resPQ.PQ.Reverse().ToArray(), 0); //NOTE: add Reverse here
TLUtils.WriteLine("pq: " + pq);
var pqCalcTime = Stopwatch.StartNew();
try
{
pqPair = Utils.GetFastPQ(pq);
pqCalcTime.Stop();
calcTime = pqCalcTime.Elapsed;
TLUtils.WriteLineAtBegin("Pq Fast calculation time: " + pqCalcTime.Elapsed);
TLUtils.WriteLine("p: " + pqPair.Item1);
TLUtils.WriteLine("q: " + pqPair.Item2);
}
catch (Exception e)
{
pqCalcTime = Stopwatch.StartNew();
pqPair = Utils.GetPQPollard(pq);
pqCalcTime.Stop();
calcTime = pqCalcTime.Elapsed;
TLUtils.WriteLineAtBegin("Pq Pollard calculation time: " + pqCalcTime.Elapsed);
TLUtils.WriteLine("p: " + pqPair.Item1);
TLUtils.WriteLine("q: " + pqPair.Item2);
}
var p = pqPair.Item1.FromUInt64();
var q = pqPair.Item2.FromUInt64();
var innerData1 = new TLPQInnerData
{
NewNonce = newNonce,
Nonce = resPQ.Nonce,
P = p,
Q = q,
PQ = resPQ.PQ,
ServerNonce = resPQ.ServerNonce
};
return innerData1;
}
private static byte[] GetEncryptedClientDHInnerData(TLClientDHInnerData clientDHInnerData, Tuple<byte[], byte[]> aesParams)
{
var random = new Random();
var client_DH_inner_data = clientDHInnerData.ToArray();
var client_DH_inner_dataWithHash = Utils.ComputeSHA1(client_DH_inner_data).Concat(client_DH_inner_data).ToArray();
var addedBytesLength = 16 - (client_DH_inner_dataWithHash.Length % 16);
if (addedBytesLength > 0 && addedBytesLength < 16)
{
var addedBytes = new byte[addedBytesLength];
random.NextBytes(addedBytes);
client_DH_inner_dataWithHash = client_DH_inner_dataWithHash.Concat(addedBytes).ToArray();
//TLUtils.WriteLine(string.Format("Added {0} bytes", addedBytesLength));
}
var aesEncryptClientDHInnerDataWithHash = Utils.AesIge(client_DH_inner_dataWithHash, aesParams.Item1, aesParams.Item2, true);
return aesEncryptClientDHInnerDataWithHash;
}
public static byte[] GetEncryptedInnerData(TLPQInnerData innerData)
{
var innerDataBytes = innerData.ToArray();
#if LOG_REGISTRATION
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine("pq " + innerData.PQ.ToBytes().Length);
sb.AppendLine("p " + innerData.P.ToBytes().Length);
sb.AppendLine("q " + innerData.Q.ToBytes().Length);
sb.AppendLine("nonce " + innerData.Nonce.ToBytes().Length);
sb.AppendLine("serverNonce " + innerData.ServerNonce.ToBytes().Length);
sb.AppendLine("newNonce " + innerData.NewNonce.ToBytes().Length);
sb.AppendLine("innerData length " + innerDataBytes.Length);
TLUtils.WriteLog(sb.ToString());
#endif
var sha1 = Utils.ComputeSHA1(innerDataBytes);
var dataWithHash = TLUtils.Combine(sha1, innerDataBytes); //116
#if LOG_REGISTRATION
TLUtils.WriteLog("innerData+hash length " + dataWithHash.Length);
#endif
var data255 = new byte[255];
var random = new Random();
random.NextBytes(data255);
Array.Copy(dataWithHash, data255, dataWithHash.Length);
var reverseRSABytes = Utils.GetRSABytes(data255); // NOTE: remove Reverse here
// TODO: verify
//var encryptedData = new string { Data = reverseRSABytes };
//return encryptedData;
return reverseRSABytes;
}
public static byte[] GetSalt(byte[] newNonce, byte[] serverNonce)
{
var newNonceBytes = newNonce.Take(8).ToArray();
var serverNonceBytes = serverNonce.Take(8).ToArray();
var returnBytes = new byte[8];
for (int i = 0; i < returnBytes.Length; i++)
{
returnBytes[i] = (byte)(newNonceBytes[i] ^ serverNonceBytes[i]);
}
return returnBytes;
}
// return big-endian authKey
public static byte[] GetAuthKey(byte[] bBytes, byte[] g_aData, byte[] dhPrimeData)
{
var b = new BigInteger(bBytes.Reverse().Concat(new byte[] { 0x00 }).ToArray());
var dhPrime = TLFactory.From<byte[]>(dhPrimeData).ToBigInteger(); // TODO: I don't like this.
var g_a = TLFactory.From<byte[]>(g_aData).ToBigInteger();
var authKey = BigInteger.ModPow(g_a, b, dhPrime).ToByteArray(); // little endian + (may be) zero last byte
//remove last zero byte
if (authKey[authKey.Length - 1] == 0x00)
{
authKey = authKey.SubArray(0, authKey.Length - 1);
}
authKey = authKey.Reverse().ToArray();
if (authKey.Length > 256)
{
#if DEBUG
var authKeyInfo = new StringBuilder();
authKeyInfo.AppendLine("auth_key length > 256: " + authKey.Length);
authKeyInfo.AppendLine("g_a=" + g_a);
authKeyInfo.AppendLine("b=" + b);
authKeyInfo.AppendLine("dhPrime=" + dhPrime);
Execute.ShowDebugMessage(authKeyInfo.ToString());
#endif
var correctedAuth = new byte[256];
Array.Copy(authKey, authKey.Length - 256, correctedAuth, 0, 256);
authKey = correctedAuth;
}
else if (authKey.Length < 256)
{
#if DEBUG
var authKeyInfo = new StringBuilder();
authKeyInfo.AppendLine("auth_key length < 256: " + authKey.Length);
authKeyInfo.AppendLine("g_a=" + g_a);
authKeyInfo.AppendLine("b=" + b);
authKeyInfo.AppendLine("dhPrime=" + dhPrime);
Execute.ShowDebugMessage(authKeyInfo.ToString());
#endif
var correctedAuth = new byte[256];
Array.Copy(authKey, 0, correctedAuth, 256 - authKey.Length, authKey.Length);
for (var i = 0; i < 256 - authKey.Length; i++)
{
authKey[i] = 0;
}
authKey = correctedAuth;
}
return authKey;
}
// b - big endian bytes
// g - serialized data
// dhPrime - serialized data
// returns big-endian G_B
public static byte[] GetGB(byte[] bData, int? gData, byte[] pString)
{
//var bBytes = new byte[256]; // big endian bytes
//var random = new Random();
//random.NextBytes(bBytes);
var g = new BigInteger(gData.Value);
var p = pString.ToBigInteger();
var b = new BigInteger(bData.Reverse().Concat(new byte[] { 0x00 }).ToArray());
var gb = BigInteger.ModPow(g, b, p).ToByteArray(); // little endian + (may be) zero last byte
//remove last zero byte
if (gb[gb.Length - 1] == 0x00)
{
gb = gb.SubArray(0, gb.Length - 1);
}
var length = gb.Length;
var result = new byte[length];
for (int i = 0; i < length; i++)
{
result[length - i - 1] = gb[i];
}
return result;
}
//public BigInteger ToBigInteger()
//{
// var data = new List<byte>(Data);
// while (data[0] == 0x00)
// {
// data.RemoveAt(0);
// }
// return new BigInteger(Data.Reverse().Concat(new byte[] { 0x00 }).ToArray()); //NOTE: add reverse here
//}
public static Tuple<byte[], byte[]> GetAesKeyIV(byte[] serverNonce, byte[] newNonce)
{
var newNonceServerNonce = newNonce.Concat(serverNonce).ToArray();
var serverNonceNewNonce = serverNonce.Concat(newNonce).ToArray();
var key = Utils.ComputeSHA1(newNonceServerNonce)
.Concat(Utils.ComputeSHA1(serverNonceNewNonce).SubArray(0, 12));
var im = Utils.ComputeSHA1(serverNonceNewNonce).SubArray(12, 8)
.Concat(Utils.ComputeSHA1(newNonce.Concat(newNonce).ToArray()))
.Concat(newNonce.SubArray(0, 4));
return new Tuple<byte[], byte[]>(key.ToArray(), im.ToArray());
}
}
}
| crafti5/Unigram | Unigram/Unigram.Api/Services/MTProtoService.DHKeyExchange.cs | C# | gpl-3.0 | 23,396 |
package com.javalego.excel;
import java.io.File;
import java.io.OutputStream;
/**
* Crear ficheros de excel.
*
* @author ROBERTO RANZ
*
*/
public interface ExcelWorkbookWriter extends ExcelWriter {
/**
* Define el fichero de salida.
* @param fileName
* @return
*/
public abstract ExcelWorkbookWriter setFile(String fileName) throws Exception;
/**
* Define el fichero de salida.
* @param fileName
* @return
*/
public abstract ExcelWorkbookWriter setFile(File file) throws Exception;
/**
* Define el fichero de salida.
* @param fileName
* @return
*/
public abstract ExcelWorkbookWriter setFile(OutputStream stream) throws Exception;
}
| rranz/meccano4j_vaadin | javalego/javalego_office/src/main/java/com/javalego/excel/ExcelWorkbookWriter.java | Java | gpl-3.0 | 715 |
#include "CPUWidget.h"
#include "ui_CPUWidget.h"
CPUWidget::CPUWidget(QWidget* parent) : QWidget(parent), ui(new Ui::CPUWidget)
{
ui->setupUi(this);
setDefaultDisposition();
mDisas = new CPUDisassembly(0);
mSideBar = new CPUSideBar(mDisas);
connect(mDisas, SIGNAL(tableOffsetChanged(int_t)), mSideBar, SLOT(changeTopmostAddress(int_t)));
connect(mDisas, SIGNAL(viewableRows(int)), mSideBar, SLOT(setViewableRows(int)));
connect(mDisas, SIGNAL(repainted()), mSideBar, SLOT(repaint()));
connect(mDisas, SIGNAL(selectionChanged(int_t)), mSideBar, SLOT(setSelection(int_t)));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), mSideBar, SLOT(debugStateChangedSlot(DBGSTATE)));
connect(Bridge::getBridge(), SIGNAL(updateSideBar()), mSideBar, SLOT(repaint()));
QSplitter* splitter = new QSplitter(this);
splitter->addWidget(mSideBar);
splitter->addWidget(mDisas);
splitter->setChildrenCollapsible(false);
splitter->setHandleWidth(1);
ui->mTopLeftUpperFrameLayout->addWidget(splitter);
mInfo = new CPUInfoBox();
ui->mTopLeftLowerFrameLayout->addWidget(mInfo);
int height = mInfo->getHeight();
ui->mTopLeftLowerFrame->setMinimumHeight(height + 2);
ui->mTopLeftLowerFrame->setMaximumHeight(height + 2);
connect(mDisas, SIGNAL(selectionChanged(int_t)), mInfo, SLOT(disasmSelectionChanged(int_t)));
mGeneralRegs = new RegistersView(0);
mGeneralRegs->setFixedWidth(1000);
mGeneralRegs->setFixedHeight(1400);
mGeneralRegs->ShowFPU(true);
QScrollArea* scrollArea = new QScrollArea;
scrollArea->setWidget(mGeneralRegs);
scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal{border:1px solid grey;background:#f1f1f1;height:10px}QScrollBar::handle:horizontal{background:#aaa;min-width:20px;margin:1px}QScrollBar::add-line:horizontal,QScrollBar::sub-line:horizontal{width:0;height:0}");
scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical{border:1px solid grey;background:#f1f1f1;width:10px}QScrollBar::handle:vertical{background:#aaa;min-height:20px;margin:1px}QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{width:0;height:0}");
QPushButton* button_changeview = new QPushButton("");
mGeneralRegs->SetChangeButton(button_changeview);
button_changeview->setStyleSheet("Text-align:left;padding: 4px;padding-left: 10px;");
QFont font = QFont("Lucida Console");
font.setStyleHint(QFont::Monospace);
font.setPointSize(8);
button_changeview->setFont(font);
connect(button_changeview, SIGNAL(clicked()), mGeneralRegs, SLOT(onChangeFPUViewAction()));
ui->mTopRightFrameLayout->addWidget(button_changeview);
ui->mTopRightFrameLayout->addWidget(scrollArea);
mDump = new CPUDump(0); //dump widget
ui->mBotLeftFrameLayout->addWidget(mDump);
mStack = new CPUStack(0); //stack widget
ui->mBotRightFrameLayout->addWidget(mStack);
}
CPUWidget::~CPUWidget()
{
delete ui;
}
void CPUWidget::setDefaultDisposition(void)
{
QList<int> sizesList;
int wTotalSize;
// Vertical Splitter
wTotalSize = ui->mVSplitter->widget(0)->size().height() + ui->mVSplitter->widget(1)->size().height();
sizesList.append(wTotalSize * 70 / 100);
sizesList.append(wTotalSize - wTotalSize * 70 / 100);
ui->mVSplitter->setSizes(sizesList);
// Top Horizontal Splitter
wTotalSize = ui->mTopHSplitter->widget(0)->size().height() + ui->mTopHSplitter->widget(1)->size().height();
sizesList.append(wTotalSize * 70 / 100);
sizesList.append(wTotalSize - wTotalSize * 70 / 100);
ui->mTopHSplitter->setSizes(sizesList);
// Bottom Horizontal Splitter
wTotalSize = ui->mBotHSplitter->widget(0)->size().height() + ui->mBotHSplitter->widget(1)->size().height();
sizesList.append(wTotalSize * 70 / 100);
sizesList.append(wTotalSize - wTotalSize * 70 / 100);
ui->mBotHSplitter->setSizes(sizesList);
}
QVBoxLayout* CPUWidget::getTopLeftUpperWidget(void)
{
return ui->mTopLeftUpperFrameLayout;
}
QVBoxLayout* CPUWidget::getTopLeftLowerWidget(void)
{
return ui->mTopLeftLowerFrameLayout;
}
QVBoxLayout* CPUWidget::getTopRightWidget(void)
{
return ui->mTopRightFrameLayout;
}
QVBoxLayout* CPUWidget::getBotLeftWidget(void)
{
return ui->mBotLeftFrameLayout;
}
QVBoxLayout* CPUWidget::getBotRightWidget(void)
{
return ui->mBotRightFrameLayout;
}
| zerowindow/x64_dbg | x64_dbg_gui/Project/Src/Gui/CPUWidget.cpp | C++ | gpl-3.0 | 4,554 |
/*
Product Name: dhtmlxSuite
Version: 5.0
Edition: Standard
License: content of this file is covered by GPL. Usage outside GPL terms is prohibited. To obtain Commercial or Enterprise license contact sales@dhtmlx.com
Copyright UAB Dinamenta http://www.dhtmlx.com
*/
(function(){
var dhx = {};
//check some rule, show message as error if rule is not correct
dhx.assert = function(test, message){
if (!test){
dhx.assert_error(message);
}
};
dhx.assert_error = function(message){
dhx.log("error",message);
if (dhx.message && typeof message == "string")
dhx.message({ type:"debug", text:message, expire:-1 });
if (dhx.debug !== false)
eval("debugger;");
};
//entry point for analitic scripts
dhx.assert_core_ready = function(){
if (window.dhx_on_core_ready)
dhx_on_core_ready();
};
/*
Common helpers
*/
dhx.codebase="./";
dhx.name = "Core";
//coding helpers
dhx.clone = function(source){
var f = dhx.clone._function;
f.prototype = source;
return new f();
};
dhx.clone._function = function(){};
//copies methods and properties from source to the target
dhx.extend = function(base, source, force){
dhx.assert(base,"Invalid mixing target");
dhx.assert(source,"Invalid mixing source");
if (base._dhx_proto_wait){
dhx.PowerArray.insertAt.call(base._dhx_proto_wait, source,1);
return base;
}
//copy methods, overwrite existing ones in case of conflict
for (var method in source)
if (!base[method] || force)
base[method] = source[method];
//in case of defaults - preffer top one
if (source.defaults)
dhx.extend(base.defaults, source.defaults);
//if source object has init code - call init against target
if (source.$init)
source.$init.call(base);
return base;
};
//copies methods and properties from source to the target from all levels
dhx.copy = function(source){
dhx.assert(source,"Invalid mixing target");
if(arguments.length>1){
var target = arguments[0];
source = arguments[1];
} else
var target = (dhx.isArray(source)?[]:{});
for (var method in source){
if(source[method] && typeof source[method] == "object" && !dhx.isDate(source[method])){
target[method] = (dhx.isArray(source[method])?[]:{});
dhx.copy(target[method],source[method]);
}else{
target[method] = source[method];
}
}
return target;
};
dhx.single = function(source){
var instance = null;
var t = function(config){
if (!instance)
instance = new source({});
if (instance._reinit)
instance._reinit.apply(instance, arguments);
return instance;
};
return t;
};
dhx.protoUI = function(){
if (dhx.debug_proto)
dhx.log("UI registered: "+arguments[0].name);
var origins = arguments;
var selfname = origins[0].name;
var t = function(data){
if (!t)
return dhx.ui[selfname].prototype;
var origins = t._dhx_proto_wait;
if (origins){
var params = [origins[0]];
for (var i=1; i < origins.length; i++){
params[i] = origins[i];
if (params[i]._dhx_proto_wait)
params[i] = params[i].call(dhx, params[i].name);
if (params[i].prototype && params[i].prototype.name)
dhx.ui[params[i].prototype.name] = params[i];
}
dhx.ui[selfname] = dhx.proto.apply(dhx, params);
if (t._dhx_type_wait)
for (var i=0; i < t._dhx_type_wait.length; i++)
dhx.Type(dhx.ui[selfname], t._dhx_type_wait[i]);
t = origins = null;
}
if (this != dhx)
return new dhx.ui[selfname](data);
else
return dhx.ui[selfname];
};
t._dhx_proto_wait = Array.prototype.slice.call(arguments, 0);
return dhx.ui[selfname]=t;
};
dhx.proto = function(){
if (dhx.debug_proto)
dhx.log("Proto chain:"+arguments[0].name+"["+arguments.length+"]");
var origins = arguments;
var compilation = origins[0];
var has_constructor = !!compilation.$init;
var construct = [];
dhx.assert(compilation,"Invalid mixing target");
for (var i=origins.length-1; i>0; i--) {
dhx.assert(origins[i],"Invalid mixing source");
if (typeof origins[i]== "function")
origins[i]=origins[i].prototype;
if (origins[i].$init)
construct.push(origins[i].$init);
if (origins[i].defaults){
var defaults = origins[i].defaults;
if (!compilation.defaults)
compilation.defaults = {};
for (var def in defaults)
if (dhx.isUndefined(compilation.defaults[def]))
compilation.defaults[def] = defaults[def];
}
if (origins[i].type && compilation.type){
for (var def in origins[i].type)
if (!compilation.type[def])
compilation.type[def] = origins[i].type[def];
}
for (var key in origins[i]){
if (!compilation[key])
compilation[key] = origins[i][key];
}
}
if (has_constructor)
construct.push(compilation.$init);
compilation.$init = function(){
for (var i=0; i<construct.length; i++)
construct[i].apply(this, arguments);
};
var result = function(config){
this.$ready=[];
dhx.assert(this.$init,"object without init method");
this.$init(config);
if (this._parseSettings)
this._parseSettings(config, this.defaults);
for (var i=0; i < this.$ready.length; i++)
this.$ready[i].call(this);
};
result.prototype = compilation;
compilation = origins = null;
return result;
};
//creates function with specified "this" pointer
dhx.bind=function(functor, object){
return function(){ return functor.apply(object,arguments); };
};
//loads module from external js file
dhx.require=function(module, callback, master){
if (typeof module != "string"){
var count = module.length||0;
var callback_origin = callback;
if (!count){
for (var file in module) count++;
callback = function(){ count--; if (count === 0) callback_origin.apply(this, arguments); };
for (var file in module)
dhx.require(file, callback, master);
} else {
callback = function(){
if (count){
count--;
dhx.require(module[module.length - count - 1], callback, master);
} else
return callback_origin.apply(this, arguments);
};
callback();
}
return;
}
if (dhx._modules[module] !== true){
if (module.substr(-4) == ".css") {
var link = dhx.html.create("LINK",{ type:"text/css", rel:"stylesheet", href:dhx.codebase+module});
document.head.appendChild(link);
if (callback)
callback.call(master||window);
return;
}
var step = arguments[4];
//load and exec the required module
if (!callback){
//sync mode
dhx.exec( dhx.ajax().sync().get(dhx.codebase+module).responseText );
dhx._modules[module]=true;
} else {
if (!dhx._modules[module]){ //first call
dhx._modules[module] = [[callback, master]];
dhx.ajax(dhx.codebase+module, function(text){
dhx.exec(text); //evaluate code
var calls = dhx._modules[module]; //callbacks
dhx._modules[module] = true;
for (var i=0; i<calls.length; i++)
calls[i][0].call(calls[i][1]||window, !i); //first callback get true as parameter
});
} else //module already loading
dhx._modules[module].push([callback, master]);
}
}
};
dhx._modules = {}; //hash of already loaded modules
//evaluate javascript code in the global scoope
dhx.exec=function(code){
if (window.execScript) //special handling for IE
window.execScript(code);
else window.eval(code);
};
dhx.wrap = function(code, wrap){
if (!code) return wrap;
return function(){
var result = code.apply(this, arguments);
wrap.apply(this,arguments);
return result;
};
};
//check === undefined
dhx.isUndefined=function(a){
return typeof a == "undefined";
};
//delay call to after-render time
dhx.delay=function(method, obj, params, delay){
return window.setTimeout(function(){
var ret = method.apply(obj,(params||[]));
method = obj = params = null;
return ret;
},delay||1);
};
//common helpers
//generates unique ID (unique per window, nog GUID)
dhx.uid = function(){
if (!this._seed) this._seed=(new Date).valueOf(); //init seed with timestemp
this._seed++;
return this._seed;
};
//resolve ID as html object
dhx.toNode = function(node){
if (typeof node == "string") return document.getElementById(node);
return node;
};
//adds extra methods for the array
dhx.toArray = function(array){
return dhx.extend((array||[]),dhx.PowerArray, true);
};
//resolve function name
dhx.toFunctor=function(str){
return (typeof(str)=="string") ? eval(str) : str;
};
/*checks where an object is instance of Array*/
dhx.isArray = function(obj) {
return Array.isArray?Array.isArray(obj):(Object.prototype.toString.call(obj) === '[object Array]');
};
dhx.isDate = function(obj){
return obj instanceof Date;
};
//dom helpers
//hash of attached events
dhx._events = {};
//attach event to the DOM element
dhx.event=function(node,event,handler,master){
node = dhx.toNode(node);
var id = dhx.uid();
if (master)
handler=dhx.bind(handler,master);
dhx._events[id]=[node,event,handler]; //store event info, for detaching
//use IE's of FF's way of event's attaching
if (node.addEventListener)
node.addEventListener(event, handler, false);
else if (node.attachEvent)
node.attachEvent("on"+event, handler);
return id; //return id of newly created event, can be used in eventRemove
};
//remove previously attached event
dhx.eventRemove=function(id){
if (!id) return;
dhx.assert(this._events[id],"Removing non-existing event");
var ev = dhx._events[id];
//browser specific event removing
if (ev[0].removeEventListener)
ev[0].removeEventListener(ev[1],ev[2],false);
else if (ev[0].detachEvent)
ev[0].detachEvent("on"+ev[1],ev[2]);
delete this._events[id]; //delete all traces
};
//debugger helpers
//anything starting from error or log will be removed during code compression
//add message in the log
dhx.log = function(type,message,details){
if (arguments.length == 1){
message = type;
type = "log";
}
/*jsl:ignore*/
if (window.console && console.log){
type=type.toLowerCase();
if (window.console[type])
window.console[type](message||"unknown error");
else
window.console.log(type +": "+message);
if (details)
window.console.log(details);
}
/*jsl:end*/
};
//register rendering time from call point
dhx.log_full_time = function(name){
dhx._start_time_log = new Date();
dhx.log("Timing start ["+name+"]");
window.setTimeout(function(){
var time = new Date();
dhx.log("Timing end ["+name+"]:"+(time.valueOf()-dhx._start_time_log.valueOf())/1000+"s");
},1);
};
//register execution time from call point
dhx.log_time = function(name){
var fname = "_start_time_log"+name;
if (!dhx[fname]){
dhx[fname] = new Date();
dhx.log("Info","Timing start ["+name+"]");
} else {
var time = new Date();
dhx.log("Info","Timing end ["+name+"]:"+(time.valueOf()-dhx[fname].valueOf())/1000+"s");
dhx[fname] = null;
}
};
dhx.debug_code = function(code){
code.call(dhx);
};
//event system
dhx.EventSystem={
$init:function(){
if (!this._evs_events){
this._evs_events = {}; //hash of event handlers, name => handler
this._evs_handlers = {}; //hash of event handlers, ID => handler
this._evs_map = {};
}
},
//temporary block event triggering
blockEvent : function(){
this._evs_events._block = true;
},
//re-enable event triggering
unblockEvent : function(){
this._evs_events._block = false;
},
mapEvent:function(map){
dhx.extend(this._evs_map, map, true);
},
on_setter:function(config){
if(config){
for(var i in config){
if(typeof config[i] == 'function')
this.attachEvent(i, config[i]);
}
}
},
//trigger event
callEvent:function(type,params){
if (this._evs_events._block) return true;
type = type.toLowerCase();
var event_stack =this._evs_events[type.toLowerCase()]; //all events for provided name
var return_value = true;
if (dhx.debug) //can slowdown a lot
dhx.log("info","["+this.name+"] event:"+type,params);
if (event_stack)
for(var i=0; i<event_stack.length; i++){
/*
Call events one by one
If any event return false - result of whole event will be false
Handlers which are not returning anything - counted as positive
*/
if (event_stack[i].apply(this,(params||[]))===false) return_value=false;
}
if (this._evs_map[type] && !this._evs_map[type].callEvent(type,params))
return_value = false;
return return_value;
},
//assign handler for some named event
attachEvent:function(type,functor,id){
dhx.assert(functor, "Invalid event handler for "+type);
type=type.toLowerCase();
id=id||dhx.uid(); //ID can be used for detachEvent
functor = dhx.toFunctor(functor); //functor can be a name of method
var event_stack=this._evs_events[type]||dhx.toArray();
//save new event handler
event_stack.push(functor);
this._evs_events[type]=event_stack;
this._evs_handlers[id]={ f:functor,t:type };
return id;
},
//remove event handler
detachEvent:function(id){
if(!this._evs_handlers[id]){
return;
}
var type=this._evs_handlers[id].t;
var functor=this._evs_handlers[id].f;
//remove from all collections
var event_stack=this._evs_events[type];
event_stack.remove(functor);
delete this._evs_handlers[id];
},
hasEvent:function(type){
type=type.toLowerCase();
return this._evs_events[type]?true:false;
}
};
dhx.extend(dhx, dhx.EventSystem);
//array helper
//can be used by dhx.toArray()
dhx.PowerArray={
//remove element at specified position
removeAt:function(pos,len){
if (pos>=0) this.splice(pos,(len||1));
},
//find element in collection and remove it
remove:function(value){
this.removeAt(this.find(value));
},
//add element to collection at specific position
insertAt:function(data,pos){
if (!pos && pos!==0) //add to the end by default
this.push(data);
else {
var b = this.splice(pos,(this.length-pos));
this[pos] = data;
this.push.apply(this,b); //reconstruct array without loosing this pointer
}
},
//return index of element, -1 if it doesn't exists
find:function(data){
for (var i=0; i<this.length; i++)
if (data==this[i]) return i;
return -1;
},
//execute some method for each element of array
each:function(functor,master){
for (var i=0; i < this.length; i++)
functor.call((master||this),this[i]);
},
//create new array from source, by using results of functor
map:function(functor,master){
for (var i=0; i < this.length; i++)
this[i]=functor.call((master||this),this[i]);
return this;
},
filter:function(functor, master){
for (var i=0; i < this.length; i++)
if (!functor.call((master||this),this[i])){
this.splice(i,1);
i--;
}
return this;
}
};
dhx.env = {};
// dhx.env.transform
// dhx.env.transition
(function(){
if (navigator.userAgent.indexOf("Mobile")!=-1)
dhx.env.mobile = true;
if (dhx.env.mobile || navigator.userAgent.indexOf("iPad")!=-1 || navigator.userAgent.indexOf("Android")!=-1)
dhx.env.touch = true;
if (navigator.userAgent.indexOf('Opera')!=-1)
dhx.env.isOpera=true;
else{
//very rough detection, but it is enough for current goals
dhx.env.isIE=!!document.all;
dhx.env.isFF=!document.all;
dhx.env.isWebKit=(navigator.userAgent.indexOf("KHTML")!=-1);
dhx.env.isSafari=dhx.env.isWebKit && (navigator.userAgent.indexOf('Mac')!=-1);
}
if(navigator.userAgent.toLowerCase().indexOf("android")!=-1)
dhx.env.isAndroid = true;
dhx.env.transform = false;
dhx.env.transition = false;
var options = {};
options.names = ['transform', 'transition'];
options.transform = ['transform', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform'];
options.transition = ['transition', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
var d = document.createElement("DIV");
for(var i=0; i<options.names.length; i++) {
var coll = options[options.names[i]];
for (var j=0; j < coll.length; j++) {
if(typeof d.style[coll[j]] != 'undefined'){
dhx.env[options.names[i]] = coll[j];
break;
}
}
}
d.style[dhx.env.transform] = "translate3d(0,0,0)";
dhx.env.translate = (d.style[dhx.env.transform])?"translate3d":"translate";
var prefix = ''; // default option
var cssprefix = false;
if(dhx.env.isOpera){
prefix = '-o-';
cssprefix = "O";
}
if(dhx.env.isFF)
prefix = '-Moz-';
if(dhx.env.isWebKit)
prefix = '-webkit-';
if(dhx.env.isIE)
prefix = '-ms-';
dhx.env.transformCSSPrefix = prefix;
dhx.env.transformPrefix = cssprefix||(dhx.env.transformCSSPrefix.replace(/-/gi, ""));
dhx.env.transitionEnd = ((dhx.env.transformCSSPrefix == '-Moz-')?"transitionend":(dhx.env.transformPrefix+"TransitionEnd"));
})();
dhx.env.svg = (function(){
return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
})();
//html helpers
dhx.html={
_native_on_selectstart:0,
denySelect:function(){
if (!dhx._native_on_selectstart)
dhx._native_on_selectstart = document.onselectstart;
document.onselectstart = dhx.html.stopEvent;
},
allowSelect:function(){
if (dhx._native_on_selectstart !== 0){
document.onselectstart = dhx._native_on_selectstart||null;
}
dhx._native_on_selectstart = 0;
},
index:function(node){
var k=0;
//must be =, it is not a comparation!
/*jsl:ignore*/
while (node = node.previousSibling) k++;
/*jsl:end*/
return k;
},
_style_cache:{},
createCss:function(rule){
var text = "";
for (var key in rule)
text+= key+":"+rule[key]+";";
var name = this._style_cache[text];
if (!name){
name = "s"+dhx.uid();
this.addStyle("."+name+"{"+text+"}");
this._style_cache[text] = name;
}
return name;
},
addStyle:function(rule){
var style = document.createElement("style");
style.setAttribute("type", "text/css");
style.setAttribute("media", "screen");
/*IE8*/
if (style.styleSheet)
style.styleSheet.cssText = rule;
else
style.appendChild(document.createTextNode(rule));
document.getElementsByTagName("head")[0].appendChild(style);
},
create:function(name,attrs,html){
attrs = attrs || {};
var node = document.createElement(name);
for (var attr_name in attrs)
node.setAttribute(attr_name, attrs[attr_name]);
if (attrs.style)
node.style.cssText = attrs.style;
if (attrs["class"])
node.className = attrs["class"];
if (html)
node.innerHTML=html;
return node;
},
//return node value, different logic for different html elements
getValue:function(node){
node = dhx.toNode(node);
if (!node) return "";
return dhx.isUndefined(node.value)?node.innerHTML:node.value;
},
//remove html node, can process an array of nodes at once
remove:function(node){
if (node instanceof Array)
for (var i=0; i < node.length; i++)
this.remove(node[i]);
else
if (node && node.parentNode)
node.parentNode.removeChild(node);
},
//insert new node before sibling, or at the end if sibling doesn't exist
insertBefore: function(node,before,rescue){
if (!node) return;
if (before && before.parentNode)
before.parentNode.insertBefore(node, before);
else
rescue.appendChild(node);
},
//return custom ID from html element
//will check all parents starting from event's target
locate:function(e,id){
if (e.tagName)
var trg = e;
else {
e=e||event;
var trg=e.target||e.srcElement;
}
while (trg){
if (trg.getAttribute){ //text nodes has not getAttribute
var test = trg.getAttribute(id);
if (test) return test;
}
trg=trg.parentNode;
}
return null;
},
//returns position of html element on the page
offset:function(elem) {
if (elem.getBoundingClientRect) { //HTML5 method
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { y: Math.round(top), x: Math.round(left) };
} else { //fallback to naive approach
var top=0, left=0;
while(elem) {
top = top + parseInt(elem.offsetTop,10);
left = left + parseInt(elem.offsetLeft,10);
elem = elem.offsetParent;
}
return {y: top, x: left};
}
},
//returns relative position of event
posRelative:function(ev){
ev = ev || event;
if (!dhx.isUndefined(ev.offsetX))
return { x:ev.offsetX, y:ev.offsetY }; //ie, webkit
else
return { x:ev.layerX, y:ev.layerY }; //firefox
},
//returns position of event
pos:function(ev){
ev = ev || event;
if(ev.pageX || ev.pageY) //FF, KHTML
return {x:ev.pageX, y:ev.pageY};
//IE
var d = ((dhx.env.isIE)&&(document.compatMode != "BackCompat"))?document.documentElement:document.body;
return {
x:ev.clientX + d.scrollLeft - d.clientLeft,
y:ev.clientY + d.scrollTop - d.clientTop
};
},
//prevent event action
preventEvent:function(e){
if (e && e.preventDefault) e.preventDefault();
return dhx.html.stopEvent(e);
},
//stop event bubbling
stopEvent:function(e){
(e||event).cancelBubble=true;
return false;
},
//add css class to the node
addCss:function(node,name){
node.className+=" "+name;
},
//remove css class from the node
removeCss:function(node,name){
node.className=node.className.replace(RegExp(" "+name,"g"),"");
}
};
dhx.ready = function(code){
if (this._ready) code.call();
else this._ready_code.push(code);
};
dhx._ready_code = [];
//autodetect codebase folder
(function(){
var temp = document.getElementsByTagName("SCRIPT"); //current script, most probably
dhx.assert(temp.length,"Can't locate codebase");
if (temp.length){
//full path to script
temp = (temp[temp.length-1].getAttribute("src")||"").split("/");
//get folder name
temp.splice(temp.length-1, 1);
dhx.codebase = temp.slice(0, temp.length).join("/")+"/";
}
dhx.event(window, "load", function(){
dhx4.callEvent("onReady",[]);
dhx.delay(function(){
dhx._ready = true;
for (var i=0; i < dhx._ready_code.length; i++)
dhx._ready_code[i].call();
dhx._ready_code=[];
});
});
})();
dhx.locale=dhx.locale||{};
dhx.assert_core_ready();
dhx.ready(function(){
dhx.event(document.body,"click", function(e){
dhx4.callEvent("onClick",[e||event]);
});
});
/*DHX:Depend core/bind.js*/
/*DHX:Depend core/dhx.js*/
/*DHX:Depend core/config.js*/
/*
Behavior:Settings
@export
customize
config
*/
/*DHX:Depend core/template.js*/
/*
Template - handles html templates
*/
/*DHX:Depend core/dhx.js*/
(function(){
var _cache = {};
var newlines = new RegExp("(\\r\\n|\\n)","g");
var quotes = new RegExp("(\\\")","g");
dhx.Template = function(str){
if (typeof str == "function") return str;
if (_cache[str])
return _cache[str];
str=(str||"").toString();
if (str.indexOf("->")!=-1){
str = str.split("->");
switch(str[0]){
case "html": //load from some container on the page
str = dhx.html.getValue(str[1]);
break;
default:
//do nothing, will use template as is
break;
}
}
//supported idioms
// {obj.attr} => named attribute or value of sub-tag in case of xml
str=(str||"").toString();
str=str.replace(newlines,"\\n");
str=str.replace(quotes,"\\\"");
str=str.replace(/\{obj\.([^}?]+)\?([^:]*):([^}]*)\}/g,"\"+(obj.$1?\"$2\":\"$3\")+\"");
str=str.replace(/\{common\.([^}\(]*)\}/g,"\"+(common.$1||'')+\"");
str=str.replace(/\{common\.([^\}\(]*)\(\)\}/g,"\"+(common.$1?common.$1.apply(this, arguments):\"\")+\"");
str=str.replace(/\{obj\.([^}]*)\}/g,"\"+(obj.$1)+\"");
str=str.replace("{obj}","\"+obj+\"");
str=str.replace(/#([^#'";, ]+)#/gi,"\"+(obj.$1)+\"");
try {
_cache[str] = Function("obj","common","return \""+str+"\";");
} catch(e){
dhx.assert_error("Invalid template:"+str);
}
return _cache[str];
};
dhx.Template.empty=function(){ return ""; };
dhx.Template.bind =function(value){ return dhx.bind(dhx.Template(value),this); };
/*
adds new template-type
obj - object to which template will be added
data - properties of template
*/
dhx.Type=function(obj, data){
if (obj._dhx_proto_wait){
if (!obj._dhx_type_wait)
obj._dhx_type_wait = [];
obj._dhx_type_wait.push(data);
return;
}
//auto switch to prototype, if name of class was provided
if (typeof obj == "function")
obj = obj.prototype;
if (!obj.types){
obj.types = { "default" : obj.type };
obj.type.name = "default";
}
var name = data.name;
var type = obj.type;
if (name)
type = obj.types[name] = dhx.clone(data.baseType?obj.types[data.baseType]:obj.type);
for(var key in data){
if (key.indexOf("template")===0)
type[key] = dhx.Template(data[key]);
else
type[key]=data[key];
}
return name;
};
})();
/*DHX:Depend core/dhx.js*/
dhx.Settings={
$init:function(){
/*
property can be accessed as this.config.some
in same time for inner call it have sense to use _settings
because it will be minified in final version
*/
this._settings = this.config= {};
},
define:function(property, value){
if (typeof property == "object")
return this._parseSeetingColl(property);
return this._define(property, value);
},
_define:function(property,value){
//method with name {prop}_setter will be used as property setter
//setter is optional
var setter = this[property+"_setter"];
return this._settings[property]=setter?setter.call(this,value,property):value;
},
//process configuration object
_parseSeetingColl:function(coll){
if (coll){
for (var a in coll) //for each setting
this._define(a,coll[a]); //set value through config
}
},
//helper for object initialization
_parseSettings:function(obj,initial){
//initial - set of default values
var settings = {};
if (initial)
settings = dhx.extend(settings,initial);
//code below will copy all properties over default one
if (typeof obj == "object" && !obj.tagName)
dhx.extend(settings,obj, true);
//call config for each setting
this._parseSeetingColl(settings);
},
_mergeSettings:function(config, defaults){
for (var key in defaults)
switch(typeof config[key]){
case "object":
config[key] = this._mergeSettings((config[key]||{}), defaults[key]);
break;
case "undefined":
config[key] = defaults[key];
break;
default: //do nothing
break;
}
return config;
},
debug_freid_c_id:true,
debug_freid_a_name:true
};
/*DHX:Depend core/datastore.js*/
/*DHX:Depend core/load.js*/
/*
ajax operations
can be used for direct loading as
dhx.ajax(ulr, callback)
or
dhx.ajax().item(url)
dhx.ajax().post(url)
*/
/*DHX:Depend core/dhx.js*/
dhx.ajax = function(url,call,master){
//if parameters was provided - made fast call
if (arguments.length!==0){
var http_request = new dhx.ajax();
if (master) http_request.master=master;
return http_request.get(url,null,call);
}
if (!this.getXHR) return new dhx.ajax(); //allow to create new instance without direct new declaration
return this;
};
dhx.ajax.count = 0;
dhx.ajax.prototype={
master:null,
//creates xmlHTTP object
getXHR:function(){
if (dhx.env.isIE)
return new ActiveXObject("Microsoft.xmlHTTP");
else
return new XMLHttpRequest();
},
/*
send data to the server
params - hash of properties which will be added to the url
call - callback, can be an array of functions
*/
send:function(url,params,call){
var x=this.getXHR();
if (!dhx.isArray(call))
call = [call];
//add extra params to the url
if (typeof params == "object"){
var t=[];
for (var a in params){
var value = params[a];
if (value === null || value === dhx.undefined)
value = "";
t.push(a+"="+encodeURIComponent(value));// utf-8 escaping
}
params=t.join("&");
}
if (params && this.request==='GET'){
url=url+(url.indexOf("?")!=-1 ? "&" : "?")+params;
params=null;
}
x.open(this.request,url,!this._sync);
if (this.request === 'POST')
x.setRequestHeader('Content-type','application/x-www-form-urlencoded');
//async mode, define loading callback
var self=this;
x.onreadystatechange= function(){
if (!x.readyState || x.readyState == 4){
if (dhx.debug_time) dhx.log_full_time("data_loading"); //log rendering time
dhx.ajax.count++;
if (call && self){
for (var i=0; i < call.length; i++) //there can be multiple callbacks
if (call[i]){
var method = (call[i].success||call[i]);
if (x.status >= 400 || (!x.status && !x.responseText))
method = call[i].error;
if (method)
method.call((self.master||self),x.responseText,x.responseXML,x);
}
}
if (self) self.master=null;
call=self=null; //anti-leak
}
};
x.send(params||null);
return x; //return XHR, which can be used in case of sync. mode
},
//GET request
get:function(url,params,call){
if (arguments.length == 2){
call = params;
params = null;
}
this.request='GET';
return this.send(url,params,call);
},
//POST request
post:function(url,params,call){
this.request='POST';
return this.send(url,params,call);
},
//PUT request
put:function(url,params,call){
this.request='PUT';
return this.send(url,params,call);
},
//POST request
del:function(url,params,call){
this.request='DELETE';
return this.send(url,params,call);
},
sync:function(){
this._sync = true;
return this;
},
bind:function(master){
this.master = master;
return this;
}
};
/*submits values*/
dhx.send = function(url, values, method, target){
var form = dhx.html.create("FORM",{
"target":(target||"_self"),
"action":url,
"method":(method||"POST")
},"");
for (var k in values) {
var field = dhx.html.create("INPUT",{"type":"hidden","name": k,"value": values[k]},"");
form.appendChild(field);
}
form.style.display = "none";
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
};
dhx.AtomDataLoader={
$init:function(config){
//prepare data store
this.data = {};
if (config){
this._settings.datatype = config.datatype||"json";
this.$ready.push(this._load_when_ready);
}
},
_load_when_ready:function(){
this._ready_for_data = true;
if (this._settings.url)
this.url_setter(this._settings.url);
if (this._settings.data)
this.data_setter(this._settings.data);
},
url_setter:function(value){
if (!this._ready_for_data) return value;
this.load(value, this._settings.datatype);
return value;
},
data_setter:function(value){
if (!this._ready_for_data) return value;
this.parse(value, this._settings.datatype);
return true;
},
debug_freid_c_datatype:true,
debug_freid_c_dataFeed:true,
//loads data from external URL
load:function(url,call){
if (url.$proxy) {
url.load(this, typeof call == "string" ? call : "json");
return;
}
this.callEvent("onXLS",[]);
if (typeof call == "string"){ //second parameter can be a loading type or callback
//we are not using setDriver as data may be a non-datastore here
this.data.driver = dhx.DataDriver[call];
call = arguments[2];
} else if (!this.data.driver)
this.data.driver = dhx.DataDriver.json;
//load data by async ajax call
//loading_key - can be set by component, to ignore data from old async requests
var callback = [{
success: this._onLoad,
error: this._onLoadError
}];
if (call){
if (dhx.isArray(call))
callback.push.apply(callback,call);
else
callback.push(call);
}
return dhx.ajax(url,callback,this);
},
//loads data from object
parse:function(data,type){
this.callEvent("onXLS",[]);
this.data.driver = dhx.DataDriver[type||"json"];
this._onLoad(data,null);
},
//default after loading callback
_onLoad:function(text,xml,loader,key){
var driver = this.data.driver;
var data = driver.toObject(text,xml);
if (data){
var top = driver.getRecords(data)[0];
this.data=(driver?driver.getDetails(top):text);
} else
this._onLoadError(text,xml,loader);
this.callEvent("onXLE",[]);
},
_onLoadError:function(text, xml, xhttp){
this.callEvent("onXLE",[]);
this.callEvent("onLoadError",arguments);
dhx4.callEvent("onLoadError", [text, xml, xhttp, this]);
},
_check_data_feed:function(data){
if (!this._settings.dataFeed || this._ignore_feed || !data) return true;
var url = this._settings.dataFeed;
if (typeof url == "function")
return url.call(this, (data.id||data), data);
url = url+(url.indexOf("?")==-1?"?":"&")+"action=get&id="+encodeURIComponent(data.id||data);
this.callEvent("onXLS",[]);
dhx.ajax(url, function(text,xml,loader){
this._ignore_feed=true;
var data = dhx.DataDriver.toObject(text, xml);
if (data)
this.setValues(data.getDetails(data.getRecords()[0]));
else
this._onLoadError(text,xml,loader);
this._ignore_feed=false;
this.callEvent("onXLE",[]);
}, this);
return false;
}
};
/*
Abstraction layer for different data types
*/
dhx.DataDriver={};
dhx.DataDriver.json={
//convert json string to json object if necessary
toObject:function(data){
if (!data) data="[]";
if (typeof data == "string"){
try{
eval ("dhx.temp="+data);
} catch(e){
dhx.assert_error(e);
return null;
}
data = dhx.temp;
}
if (data.data){
var t = data.data.config = {};
for (var key in data)
if (key!="data")
t[key] = data[key];
data = data.data;
}
return data;
},
//get array of records
getRecords:function(data){
if (data && !dhx.isArray(data))
return [data];
return data;
},
//get hash of properties for single record
getDetails:function(data){
if (typeof data == "string")
return { id:dhx.uid(), value:data };
return data;
},
//get count of data and position at which new data need to be inserted
getInfo:function(data){
var cfg = data.config;
if (!cfg) return {};
return {
_size:(cfg.total_count||0),
_from:(cfg.pos||0),
_parent:(cfg.parent||0),
_config:(cfg.config),
_key:(cfg.dhx_security)
};
},
child:"data"
};
dhx.DataDriver.html={
/*
incoming data can be
- collection of nodes
- ID of parent container
- HTML text
*/
toObject:function(data){
if (typeof data == "string"){
var t=null;
if (data.indexOf("<")==-1) //if no tags inside - probably its an ID
t = dhx.toNode(data);
if (!t){
t=document.createElement("DIV");
t.innerHTML = data;
}
return t.getElementsByTagName(this.tag);
}
return data;
},
//get array of records
getRecords:function(node){
var data = [];
for (var i=0; i<node.childNodes.length; i++){
var child = node.childNodes[i];
if (child.nodeType == 1)
data.push(child);
}
return data;
},
//get hash of properties for single record
getDetails:function(data){
return dhx.DataDriver.xml.tagToObject(data);
},
//dyn loading is not supported by HTML data source
getInfo:function(data){
return {
_size:0,
_from:0
};
},
tag: "LI"
};
dhx.DataDriver.jsarray={
//eval jsarray string to jsarray object if necessary
toObject:function(data){
if (typeof data == "string"){
eval ("dhx.temp="+data);
return dhx.temp;
}
return data;
},
//get array of records
getRecords:function(data){
return data;
},
//get hash of properties for single record, in case of array they will have names as "data{index}"
getDetails:function(data){
var result = {};
for (var i=0; i < data.length; i++)
result["data"+i]=data[i];
return result;
},
//dyn loading is not supported by js-array data source
getInfo:function(data){
return {
_size:0,
_from:0
};
}
};
dhx.DataDriver.csv={
//incoming data always a string
toObject:function(data){
return data;
},
//get array of records
getRecords:function(data){
return data.split(this.row);
},
//get hash of properties for single record, data named as "data{index}"
getDetails:function(data){
data = this.stringToArray(data);
var result = {};
for (var i=0; i < data.length; i++)
result["data"+i]=data[i];
return result;
},
//dyn loading is not supported by csv data source
getInfo:function(data){
return {
_size:0,
_from:0
};
},
//split string in array, takes string surrounding quotes in account
stringToArray:function(data){
data = data.split(this.cell);
for (var i=0; i < data.length; i++)
data[i] = data[i].replace(/^[ \t\n\r]*(\"|)/g,"").replace(/(\"|)[ \t\n\r]*$/g,"");
return data;
},
row:"\n", //default row separator
cell:"," //default cell separator
};
dhx.DataDriver.xml={
_isValidXML:function(data){
if (!data || !data.documentElement)
return null;
if (data.getElementsByTagName("parsererror").length)
return null;
return data;
},
//convert xml string to xml object if necessary
toObject:function(text,xml){
if (this._isValidXML(data))
return data;
if (typeof text == "string")
var data = this.fromString(text.replace(/^[\s]+/,""));
else
data = text;
if (this._isValidXML(data))
return data;
return null;
},
//get array of records
getRecords:function(data){
return this.xpath(data,this.records);
},
records:"/*/item",
child:"item",
config:"/*/config",
//get hash of properties for single record
getDetails:function(data){
return this.tagToObject(data,{});
},
//get count of data and position at which new data_loading need to be inserted
getInfo:function(data){
var config = this.xpath(data, this.config);
if (config.length)
config = this.assignTypes(this.tagToObject(config[0],{}));
else
config = null;
return {
_size:(data.documentElement.getAttribute("total_count")||0),
_from:(data.documentElement.getAttribute("pos")||0),
_parent:(data.documentElement.getAttribute("parent")||0),
_config:config,
_key:(data.documentElement.getAttribute("dhx_security")||null)
};
},
//xpath helper
xpath:function(xml,path){
if (window.XPathResult){ //FF, KHTML, Opera
var node=xml;
if(xml.nodeName.indexOf("document")==-1)
xml=xml.ownerDocument;
var res = [];
var col = xml.evaluate(path, node, null, XPathResult.ANY_TYPE, null);
var temp = col.iterateNext();
while (temp){
res.push(temp);
temp = col.iterateNext();
}
return res;
}
else {
var test = true;
try {
if (typeof(xml.selectNodes)=="undefined")
test = false;
} catch(e){ /*IE7 and below can't operate with xml object*/ }
//IE
if (test)
return xml.selectNodes(path);
else {
//Google hate us, there is no interface to do XPath
//use naive approach
var name = path.split("/").pop();
return xml.getElementsByTagName(name);
}
}
},
assignTypes:function(obj){
for (var k in obj){
var test = obj[k];
if (typeof test == "object")
this.assignTypes(test);
else if (typeof test == "string"){
if (test === "")
continue;
if (test == "true")
obj[k] = true;
else if (test == "false")
obj[k] = false;
else if (test == test*1)
obj[k] = obj[k]*1;
}
}
return obj;
},
//convert xml tag to js object, all subtags and attributes are mapped to the properties of result object
tagToObject:function(tag,z){
z=z||{};
var flag=false;
//map attributes
var a=tag.attributes;
if(a && a.length){
for (var i=0; i<a.length; i++)
z[a[i].name]=a[i].value;
flag = true;
}
//map subtags
var b=tag.childNodes;
var state = {};
for (var i=0; i<b.length; i++){
if (b[i].nodeType==1){
var name = b[i].tagName;
if (typeof z[name] != "undefined"){
if (!dhx.isArray(z[name]))
z[name]=[z[name]];
z[name].push(this.tagToObject(b[i],{}));
}
else
z[b[i].tagName]=this.tagToObject(b[i],{}); //sub-object for complex subtags
flag=true;
}
}
if (!flag)
return this.nodeValue(tag);
//each object will have its text content as "value" property
z.value = z.value||this.nodeValue(tag);
return z;
},
//get value of xml node
nodeValue:function(node){
if (node.firstChild)
return node.firstChild.data; //FIXME - long text nodes in FF not supported for now
return "";
},
//convert XML string to XML object
fromString:function(xmlString){
try{
if (window.DOMParser) // FF, KHTML, Opera
return (new DOMParser()).parseFromString(xmlString,"text/xml");
if (window.ActiveXObject){ // IE, utf-8 only
var temp=new ActiveXObject("Microsoft.xmlDOM");
temp.loadXML(xmlString);
return temp;
}
} catch(e){
dhx.assert_error(e);
return null;
}
dhx.assert_error("Load from xml string is not supported");
}
};
/*DHX:Depend core/dhx.js*/
/*
Behavior:DataLoader - load data in the component
@export
load
parse
*/
dhx.DataLoader=dhx.proto({
$init:function(config){
//prepare data store
config = config || "";
//list of all active ajax requests
this._ajax_queue = dhx.toArray();
this.data = new dhx.DataStore();
this.data.attachEvent("onClearAll",dhx.bind(this._call_onclearall,this));
this.data.attachEvent("onServerConfig", dhx.bind(this._call_on_config, this));
this.data.feed = this._feed;
},
_feed:function(from,count,callback){
//allow only single request at same time
if (this._load_count)
return this._load_count=[from,count,callback]; //save last ignored request
else
this._load_count=true;
this._feed_last = [from, count];
this._feed_common.call(this, from, count, callback);
},
_feed_common:function(from, count, callback){
var url = this.data.url;
if (from<0) from = 0;
this.load(url+((url.indexOf("?")==-1)?"?":"&")+(this.dataCount()?("continue=true&"):"")+"start="+from+"&count="+count,[
this._feed_callback,
callback
]);
},
_feed_callback:function(){
//after loading check if we have some ignored requests
var temp = this._load_count;
var last = this._feed_last;
this._load_count = false;
if (typeof temp =="object" && (temp[0]!=last[0] || temp[1]!=last[1]))
this.data.feed.apply(this, temp); //load last ignored request
},
//loads data from external URL
load:function(url,call){
var ajax = dhx.AtomDataLoader.load.apply(this, arguments);
this._ajax_queue.push(ajax);
//prepare data feed for dyn. loading
if (!this.data.url)
this.data.url = url;
},
//load next set of data rows
loadNext:function(count, start, callback, url, now){
if (this._settings.datathrottle && !now){
if (this._throttle_request)
window.clearTimeout(this._throttle_request);
this._throttle_request = dhx.delay(function(){
this.loadNext(count, start, callback, url, true);
},this, 0, this._settings.datathrottle);
return;
}
if (!start && start !== 0) start = this.dataCount();
this.data.url = this.data.url || url;
if (this.callEvent("onDataRequest", [start,count,callback,url]) && this.data.url)
this.data.feed.call(this, start, count, callback);
},
_maybe_loading_already:function(count, from){
var last = this._feed_last;
if(this._load_count && last){
if (last[0]<=from && (last[1]+last[0] >= count + from )) return true;
}
return false;
},
//default after loading callback
_onLoad:function(text,xml,loader){
//ignore data loading command if data was reloaded
this._ajax_queue.remove(loader);
var data = this.data.driver.toObject(text,xml);
if (data)
this.data._parse(data);
else
return this._onLoadError(text, xml, loader);
//data loaded, view rendered, call onready handler
this._call_onready();
this.callEvent("onXLE",[]);
},
removeMissed_setter:function(value){
return this.data._removeMissed = value;
},
scheme_setter:function(value){
this.data.scheme(value);
},
dataFeed_setter:function(value){
this.data.attachEvent("onBeforeFilter", dhx.bind(function(text, value){
if (this._settings.dataFeed){
var filter = {};
if (!text && !value) return;
if (typeof text == "function"){
if (!value) return;
text(value, filter);
} else
filter = { text:value };
this.clearAll();
var url = this._settings.dataFeed;
var urldata = [];
if (typeof url == "function")
return url.call(this, value, filter);
for (var key in filter)
urldata.push("dhx_filter["+key+"]="+encodeURIComponent(filter[key]));
this.load(url+(url.indexOf("?")<0?"?":"&")+urldata.join("&"), this._settings.datatype);
return false;
}
},this));
return value;
},
debug_freid_c_ready:true,
debug_freid_c_datathrottle:true,
_call_onready:function(){
if (this._settings.ready && !this._ready_was_used){
var code = dhx.toFunctor(this._settings.ready);
if (code)
dhx.delay(code, this, arguments);
this._ready_was_used = true;
}
},
_call_onclearall:function(){
for (var i = 0; i < this._ajax_queue.length; i++)
this._ajax_queue[i].abort();
this._ajax_queue = dhx.toArray();
},
_call_on_config:function(config){
this._parseSeetingColl(config);
}
},dhx.AtomDataLoader);
/*
DataStore is not a behavior, it standalone object, which represents collection of data.
Call provideAPI to map data API
@export
exists
idByIndex
indexById
get
set
refresh
dataCount
sort
filter
next
previous
clearAll
first
last
*/
dhx.DataStore = function(){
this.name = "DataStore";
dhx.extend(this, dhx.EventSystem);
this.setDriver("json"); //default data source is an
this.pull = {}; //hash of IDs
this.order = dhx.toArray(); //order of IDs
this._marks = {};
};
dhx.DataStore.prototype={
//defines type of used data driver
//data driver is an abstraction other different data formats - xml, json, csv, etc.
setDriver:function(type){
dhx.assert(dhx.DataDriver[type],"incorrect DataDriver");
this.driver = dhx.DataDriver[type];
},
//process incoming raw data
_parse:function(data,master){
this.callEvent("onParse", [this.driver, data]);
if (this._filter_order)
this.filter();
//get size and position of data
var info = this.driver.getInfo(data);
if (info._key)
dhx.securityKey = info._key;
if (info._config)
this.callEvent("onServerConfig",[info._config]);
//get array of records
var recs = this.driver.getRecords(data);
this._inner_parse(info, recs);
//in case of tree store we may want to group data
if (this._scheme_group && this._group_processing)
this._group_processing(this._scheme_group);
//optional data sorting
if (this._scheme_sort){
this.blockEvent();
this.sort(this._scheme_sort);
this.unblockEvent();
}
this.callEvent("onStoreLoad",[this.driver, data]);
//repaint self after data loading
this.refresh();
},
_inner_parse:function(info, recs){
var from = (info._from||0)*1;
var subload = true;
var marks = false;
if (from === 0 && this.order[0]){ //update mode
if (this._removeMissed){
//update mode, create kill list
marks = {};
for (var i=0; i<this.order.length; i++)
marks[this.order[i]]=true;
}
subload = false;
from = this.order.length;
}
var j=0;
for (var i=0; i<recs.length; i++){
//get hash of details for each record
var temp = this.driver.getDetails(recs[i]);
var id = this.id(temp); //generate ID for the record
if (!this.pull[id]){ //if such ID already exists - update instead of insert
this.order[j+from]=id;
j++;
} else if (subload && this.order[j+from])
j++;
if(this.pull[id]){
dhx.extend(this.pull[id],temp,true);//add only new properties
if (this._scheme_update)
this._scheme_update(this.pull[id]);
//update mode, remove item from kill list
if (marks)
delete marks[id];
} else{
this.pull[id] = temp;
if (this._scheme_init)
this._scheme_init(temp);
}
}
//update mode, delete items which are not existing in the new xml
if (marks){
this.blockEvent();
for (var delid in marks)
this.remove(delid);
this.unblockEvent();
}
if (!this.order[info._size-1])
this.order[info._size-1] = dhx.undefined;
},
//generate id for data object
id:function(data){
return data.id||(data.id=dhx.uid());
},
changeId:function(old, newid){
//dhx.assert(this.pull[old],"Can't change id, for non existing item: "+old);
if(this.pull[old])
this.pull[newid] = this.pull[old];
this.pull[newid].id = newid;
this.order[this.order.find(old)]=newid;
if (this._filter_order)
this._filter_order[this._filter_order.find(old)]=newid;
if (this._marks[old]){
this._marks[newid] = this._marks[old];
delete this._marks[old];
}
this.callEvent("onIdChange", [old, newid]);
if (this._render_change_id)
this._render_change_id(old, newid);
delete this.pull[old];
},
//get data from hash by id
item:function(id){
return this.pull[id];
},
//assigns data by id
update:function(id,data){
if (dhx.isUndefined(data)) data = this.item(id);
if (this._scheme_update)
this._scheme_update(data);
if (this.callEvent("onBeforeUpdate", [id, data]) === false) return false;
this.pull[id]=data;
this.callEvent("onStoreUpdated",[id, data, "update"]);
},
//sends repainting signal
refresh:function(id){
if (this._skip_refresh) return;
if (id)
this.callEvent("onStoreUpdated",[id, this.pull[id], "paint"]);
else
this.callEvent("onStoreUpdated",[null,null,null]);
},
silent:function(code, master){
this._skip_refresh = true;
code.call(master||this);
this._skip_refresh = false;
},
//converts range IDs to array of all IDs between them
getRange:function(from,to){
//if some point is not defined - use first or last id
//BEWARE - do not use empty or null ID
if (from)
from = this.indexById(from);
else
from = (this.$min||this.startOffset)||0;
if (to)
to = this.indexById(to);
else {
to = Math.min(((this.$max||this.endOffset)||Infinity),(this.dataCount()-1));
if (to<0) to = 0; //we have not data in the store
}
if (from>to){ //can be in case of backward shift-selection
var a=to; to=from; from=a;
}
return this.getIndexRange(from,to);
},
//converts range of indexes to array of all IDs between them
getIndexRange:function(from,to){
to=Math.min((to||Infinity),this.dataCount()-1);
var ret=dhx.toArray(); //result of method is rich-array
for (var i=(from||0); i <= to; i++)
ret.push(this.item(this.order[i]));
return ret;
},
//returns total count of elements
dataCount:function(){
return this.order.length;
},
//returns truy if item with such ID exists
exists:function(id){
return !!(this.pull[id]);
},
//nextmethod is not visible on component level, check DataMove.move
//moves item from source index to the target index
move:function(sindex,tindex){
dhx.assert(sindex>=0 && tindex>=0, "DataStore::move","Incorrect indexes");
var id = this.idByIndex(sindex);
var obj = this.item(id);
this.order.removeAt(sindex); //remove at old position
//if (sindex<tindex) tindex--; //correct shift, caused by element removing
this.order.insertAt(id,Math.min(this.order.length, tindex)); //insert at new position
//repaint signal
this.callEvent("onStoreUpdated",[id,obj,"move"]);
},
scheme:function(config){
this._scheme = {};
this._scheme_init = config.$init;
this._scheme_update = config.$update;
this._scheme_serialize = config.$serialize;
this._scheme_group = config.$group;
this._scheme_sort = config.$sort;
//ignore $-starting properties, as they have special meaning
for (var key in config)
if (key.substr(0,1) != "$")
this._scheme[key] = config[key];
},
sync:function(source, filter, silent){
if (typeof source == "string")
source = $$("source");
if (typeof filter != "function"){
silent = filter;
filter = null;
}
if (dhx.debug_bind){
this.debug_sync_master = source;
dhx.log("[sync] "+this.debug_bind_master.name+"@"+this.debug_bind_master._settings.id+" <= "+this.debug_sync_master.name+"@"+this.debug_sync_master._settings.id);
}
this._backbone_source = false;
if (source.name != "DataStore"){
if (source.data && source.data.name == "DataStore")
source = source.data;
else
this._backbone_source = true;
}
var sync_logic = dhx.bind(function(mode, record, data){
if (this._backbone_source){
//ignore first call for backbone sync
if (!mode) return;
//data changing
if (mode.indexOf("change") === 0){
if (mode == "change"){
this.pull[record.id] = record.attributes;
this.refresh(record.id);
return;
} else return; //ignoring property change event
}
//we need to access global model, it has different position for different events
if (mode == "reset")
data = record;
//fill data collections from backbone model
this.order = []; this.pull = {};
this._filter_order = null;
for (var i=0; i<data.models.length; i++){
var id = data.models[i].id;
this.order.push(id);
this.pull[id] = data.models[i].attributes;
}
} else {
this._filter_order = null;
this.order = dhx.toArray([].concat(source.order));
this.pull = source.pull;
}
if (filter)
this.silent(filter);
if (this._on_sync)
this._on_sync();
if (dhx.debug_bind)
dhx.log("[sync:request] "+this.debug_sync_master.name+"@"+this.debug_sync_master._settings.id + " <= "+this.debug_bind_master.name+"@"+this.debug_bind_master._settings.id);
this.callEvent("onSyncApply",[]);
if (!silent)
this.refresh();
else
silent = false;
}, this);
if (this._backbone_source)
source.bind('all', sync_logic);
else
this._sync_events = [
source.attachEvent("onStoreUpdated", sync_logic),
source.attachEvent("onIdChange", dhx.bind(function(old, nid){ this.changeId(old, nid); }, this))
];
sync_logic();
},
//adds item to the store
add:function(obj,index){
//default values
if (this._scheme)
for (var key in this._scheme)
if (dhx.isUndefined(obj[key]))
obj[key] = this._scheme[key];
if (this._scheme_init)
this._scheme_init(obj);
//generate id for the item
var id = this.id(obj);
//in case of treetable order is sent as 3rd parameter
var order = arguments[2]||this.order;
//by default item is added to the end of the list
var data_size = order.length;
if (dhx.isUndefined(index) || index < 0)
index = data_size;
//check to prevent too big indexes
if (index > data_size){
dhx.log("Warning","DataStore:add","Index of out of bounds");
index = Math.min(order.length,index);
}
if (this.callEvent("onBeforeAdd", [id, obj, index]) === false) return false;
dhx.assert(!this.exists(id), "Not unique ID");
this.pull[id]=obj;
order.insertAt(id,index);
if (this._filter_order){ //adding during filtering
//we can't know the location of new item in full dataset, making suggestion
//put at end by default
var original_index = this._filter_order.length;
//put at start only if adding to the start and some data exists
if (!index && this.order.length)
original_index = 0;
this._filter_order.insertAt(id,original_index);
}
this.callEvent("onAfterAdd",[id,index]);
//repaint signal
this.callEvent("onStoreUpdated",[id,obj,"add"]);
return id;
},
//removes element from datastore
remove:function(id){
//id can be an array of IDs - result of getSelect, for example
if (dhx.isArray(id)){
for (var i=0; i < id.length; i++)
this.remove(id[i]);
return;
}
if (this.callEvent("onBeforeDelete",[id]) === false) return false;
dhx.assert(this.exists(id), "Not existing ID in remove command"+id);
var obj = this.item(id); //save for later event
//clear from collections
this.order.remove(id);
if (this._filter_order)
this._filter_order.remove(id);
delete this.pull[id];
if (this._marks[id])
delete this._marks[id];
this.callEvent("onAfterDelete",[id]);
//repaint signal
this.callEvent("onStoreUpdated",[id,obj,"delete"]);
},
//deletes all records in datastore
clearAll:function(){
//instead of deleting one by one - just reset inner collections
this.pull = {};
this.order = dhx.toArray();
//this.feed = null;
this._filter_order = this.url = null;
this.callEvent("onClearAll",[]);
this.refresh();
},
//converts id to index
idByIndex:function(index){
if (index>=this.order.length || index<0)
dhx.log("Warning","DataStore::idByIndex Incorrect index");
return this.order[index];
},
//converts index to id
indexById:function(id){
var res = this.order.find(id); //slower than idByIndex
if (!this.pull[id])
dhx.log("Warning","DataStore::indexById Non-existing ID: "+ id);
return res;
},
//returns ID of next element
next:function(id,step){
return this.order[this.indexById(id)+(step||1)];
},
//returns ID of first element
first:function(){
return this.order[0];
},
//returns ID of last element
last:function(){
return this.order[this.order.length-1];
},
//returns ID of previous element
previous:function(id,step){
return this.order[this.indexById(id)-(step||1)];
},
/*
sort data in collection
by - settings of sorting
or
by - sorting function
dir - "asc" or "desc"
or
by - property
dir - "asc" or "desc"
as - type of sortings
Sorting function will accept 2 parameters and must return 1,0,-1, based on desired order
*/
sort:function(by, dir, as){
var sort = by;
if (typeof by == "function")
sort = {as:by, dir:dir};
else if (typeof by == "string")
sort = {by:by.replace(/#/g,""), dir:dir, as:as};
var parameters = [sort.by, sort.dir, sort.as];
if (!this.callEvent("onBeforeSort",parameters)) return;
this._sort_core(sort);
//repaint self
this.refresh();
this.callEvent("onAfterSort",parameters);
},
_sort_core:function(sort){
if (this.order.length){
var sorter = this._sort._create(sort);
//get array of IDs
var neworder = this.getRange(this.first(), this.last());
neworder.sort(sorter);
this.order = neworder.map(function(obj){
dhx.assert(obj, "Client sorting can't be used with dynamic loading");
return this.id(obj);
},this);
}
},
/*
Filter datasource
text - property, by which filter
value - filter mask
or
text - filter method
Filter method will receive data object and must return true or false
*/
_filter_reset:function(preserve){
//remove previous filtering , if any
if (this._filter_order && !preserve){
this.order = this._filter_order;
delete this._filter_order;
}
},
_filter_core:function(filter, value, preserve){
var neworder = dhx.toArray();
for (var i=0; i < this.order.length; i++){
var id = this.order[i];
if (filter(this.item(id),value))
neworder.push(id);
}
//set new order of items, store original
if (!preserve || !this._filter_order)
this._filter_order = this.order;
this.order = neworder;
},
filter:function(text,value,preserve){
if (!this.callEvent("onBeforeFilter", [text, value])) return;
this._filter_reset(preserve);
if (!this.order.length) return;
//if text not define -just unfilter previous state and exit
if (text){
var filter = text;
value = value||"";
if (typeof text == "string"){
text = text.replace(/#/g,"");
if (typeof value == "function")
filter = function(obj){
return value(obj[text]);
};
else{
value = value.toString().toLowerCase();
filter = function(obj,value){ //default filter - string start from, case in-sensitive
dhx.assert(obj, "Client side filtering can't be used with dynamic loading");
return (obj[text]||"").toString().toLowerCase().indexOf(value)!=-1;
};
}
}
this._filter_core(filter, value, preserve, this._filterMode);
}
//repaint self
this.refresh();
this.callEvent("onAfterFilter", []);
},
/*
Iterate through collection
*/
each:function(method,master){
for (var i=0; i<this.order.length; i++)
method.call((master||this), this.item(this.order[i]));
},
_methodPush:function(object,method){
return function(){ return object[method].apply(object,arguments); };
},
addMark:function(id, mark, css, value){
var obj = this._marks[id]||{};
this._marks[id] = obj;
if (!obj[mark]){
obj[mark] = value||true;
if (css){
this.item(id).$css = (this.item(id).$css||"")+" "+mark;
this.refresh(id);
}
}
return obj[mark];
},
removeMark:function(id, mark, css){
var obj = this._marks[id];
if (obj && obj[mark])
delete obj[mark];
if (css){
var current_css = this.item(id).$css;
if (current_css){
this.item(id).$css = current_css.replace(mark, "");
this.refresh(id);
}
}
},
hasMark:function(id, mark){
var obj = this._marks[id];
return (obj && obj[mark]);
},
/*
map inner methods to some distant object
*/
provideApi:function(target,eventable){
this.debug_bind_master = target;
if (eventable){
this.mapEvent({
onbeforesort: target,
onaftersort: target,
onbeforeadd: target,
onafteradd: target,
onbeforedelete: target,
onafterdelete: target,
onbeforeupdate: target/*,
onafterfilter: target,
onbeforefilter: target*/
});
}
var list = ["sort","add","remove","exists","idByIndex","indexById","item","update","refresh","dataCount","filter","next","previous","clearAll","first","last","serialize","sync","addMark","removeMark","hasMark"];
for (var i=0; i < list.length; i++)
target[list[i]] = this._methodPush(this,list[i]);
},
/*
serializes data to a json object
*/
serialize: function(){
var ids = this.order;
var result = [];
for(var i=0; i< ids.length;i++) {
var el = this.pull[ids[i]];
if (this._scheme_serialize){
el = this._scheme_serialize(el);
if (el===false) continue;
}
result.push(el);
}
return result;
},
_sort:{
_create:function(config){
return this._dir(config.dir, this._by(config.by, config.as));
},
_as:{
"date":function(a,b){
a=a-0; b=b-0;
return a>b?1:(a<b?-1:0);
},
"int":function(a,b){
a = a*1; b=b*1;
return a>b?1:(a<b?-1:0);
},
"string_strict":function(a,b){
a = a.toString(); b=b.toString();
return a>b?1:(a<b?-1:0);
},
"string":function(a,b){
if (!b) return 1;
if (!a) return -1;
a = a.toString().toLowerCase(); b=b.toString().toLowerCase();
return a>b?1:(a<b?-1:0);
}
},
_by:function(prop, method){
if (!prop)
return method;
if (typeof method != "function")
method = this._as[method||"string"];
dhx.assert(method, "Invalid sorting method");
return function(a,b){
return method(a[prop],b[prop]);
};
},
_dir:function(prop, method){
if (prop == "asc" || !prop)
return method;
return function(a,b){
return method(a,b)*-1;
};
}
}
};
//UI interface
dhx.BaseBind = {
debug_freid_ignore:{
"id":true
},
bind:function(target, rule, format){
if (typeof target == 'string')
target = dhx.ui.get(target);
if (target._initBindSource) target._initBindSource();
if (this._initBindSource) this._initBindSource();
if (!target.getBindData)
dhx.extend(target, dhx.BindSource);
if (!this._bind_ready){
var old_render = this.render;
if (this.filter){
var key = this._settings.id;
this.data._on_sync = function(){
target._bind_updated[key] = false;
};
}
this.render = function(){
if (this._in_bind_processing) return;
this._in_bind_processing = true;
var result = this.callEvent("onBindRequest");
this._in_bind_processing = false;
return old_render.apply(this, ((result === false)?arguments:[]));
};
if (this.getValue||this.getValues)
this.save = function(){
if (this.validate && !this.validate()) return;
target.setBindData((this.getValue?this.getValue:this.getValues()),this._settings.id);
};
this._bind_ready = true;
}
target.addBind(this._settings.id, rule, format);
if (dhx.debug_bind)
dhx.log("[bind] "+this.name+"@"+this._settings.id+" <= "+target.name+"@"+target._settings.id);
var target_id = this._settings.id;
//FIXME - check for touchable is not the best solution, to detect necessary event
this.attachEvent(this.touchable?"onAfterRender":"onBindRequest", function(){
return target.getBindData(target_id);
});
//we want to refresh list after data loading if it has master link
//in same time we do not want such operation for dataFeed components
//as they are reloading data as response to the master link
if (!this._settings.dataFeed && this.loadNext)
this.data.attachEvent("onStoreLoad", function(){
target._bind_updated[target_id] = false;
});
if (this.isVisible(this._settings.id))
this.refresh();
},
unbind:function(target){
return this._unbind(target);
},
_unbind:function(target){
target.removeBind(this._settings.id);
var events = (this._sync_events||(this.data?this.data._sync_events:0));
if (events && target.data)
for (var i=0; i<events.length; i++)
target.data.detachEvent(events[i]);
}
};
//bind interface
dhx.BindSource = {
$init:function(){
this._bind_hash = {}; //rules per target
this._bind_updated = {}; //update flags
this._ignore_binds = {};
//apply specific bind extension
this._bind_specific_rules(this);
},
saveBatch:function(code){
this._do_not_update_binds = true;
code.call(this);
this._do_not_update_binds = false;
this._update_binds();
},
setBindData:function(data, key){
if (key)
this._ignore_binds[key] = true;
if (dhx.debug_bind)
dhx.log("[bind:save] "+this.name+"@"+this._settings.id+" <= "+"@"+key);
if (this.setValue)
this.setValue(data);
else if (this.setValues)
this.setValues(data);
else {
var id = this.getCursor();
if (id){
data = dhx.extend(this.item(id), data, true);
this.update(id, data);
}
}
this.callEvent("onBindUpdate", [data, key, id]);
if (this.save)
this.save();
if (key)
this._ignore_binds[key] = false;
},
//fill target with data
getBindData:function(key, update){
//fire only if we have data updates from the last time
if (this._bind_updated[key]) return false;
var target = dhx.ui.get(key);
//fill target only when it visible
if (target.isVisible(target._settings.id)){
this._bind_updated[key] = true;
if (dhx.debug_bind)
dhx.log("[bind:request] "+this.name+"@"+this._settings.id+" => "+target.name+"@"+target._settings.id);
this._bind_update(target, this._bind_hash[key][0], this._bind_hash[key][1]); //trigger component specific updating logic
if (update && target.filter)
target.refresh();
}
},
//add one more bind target
addBind:function(source, rule, format){
this._bind_hash[source] = [rule, format];
},
removeBind:function(source){
delete this._bind_hash[source];
delete this._bind_updated[source];
delete this._ignore_binds[source];
},
//returns true if object belong to "collection" type
_bind_specific_rules:function(obj){
if (obj.filter)
dhx.extend(this, dhx.CollectionBind);
else if (obj.setValue)
dhx.extend(this, dhx.ValueBind);
else
dhx.extend(this, dhx.RecordBind);
},
//inform all binded objects, that source data was updated
_update_binds:function(){
if (!this._do_not_update_binds)
for (var key in this._bind_hash){
if (this._ignore_binds[key]) continue;
this._bind_updated[key] = false;
this.getBindData(key, true);
}
},
//copy data from source to the target
_bind_update_common:function(target, rule, data){
if (target.setValue)
target.setValue(data?data[rule]:data);
else if (!target.filter){
if (!data && target.clear)
target.clear();
else {
if (target._check_data_feed(data))
target.setValues(dhx.clone(data));
}
} else {
target.data.silent(function(){
this.filter(rule,data);
});
}
target.callEvent("onBindApply", [data,rule,this]);
}
};
//pure data objects
dhx.DataValue = dhx.proto({
name:"DataValue",
isVisible:function(){ return true; },
$init:function(config){
this.data = ""||config;
var id = (config&&config.id)?config.id:dhx.uid();
this._settings = { id:id };
dhx.ui.views[id] = this;
},
setValue:function(value){
this.data = value;
this.callEvent("onChange", [value]);
},
getValue:function(){
return this.data;
},
refresh:function(){ this.callEvent("onBindRequest"); }
}, dhx.EventSystem, dhx.BaseBind);
dhx.DataRecord = dhx.proto({
name:"DataRecord",
isVisible:function(){ return true; },
$init:function(config){
this.data = config||{};
var id = (config&&config.id)?config.id:dhx.uid();
this._settings = { id:id };
dhx.ui.views[id] = this;
},
getValues:function(){
return this.data;
},
setValues:function(data){
this.data = data;
this.callEvent("onChange", [data]);
},
refresh:function(){ this.callEvent("onBindRequest"); }
}, dhx.EventSystem, dhx.BaseBind, dhx.AtomDataLoader, dhx.Settings);
dhx.DataCollection = dhx.proto({
name:"DataCollection",
isVisible:function(){
if (!this.data.order.length && !this.data._filter_order && !this._settings.dataFeed) return false;
return true;
},
$init:function(config){
this.data.provideApi(this, true);
var id = (config&&config.id)?config.id:dhx.uid();
this._settings.id =id;
dhx.ui.views[id] = this;
this.data.attachEvent("onStoreLoad", dhx.bind(function(){
this.callEvent("onBindRequest",[]);
}, this));
},
refresh:function(){ this.callEvent("onBindRequest",[]); }
}, dhx.DataLoader, dhx.EventSystem, dhx.BaseBind, dhx.Settings);
dhx.ValueBind={
$init:function(){
this.attachEvent("onChange", this._update_binds);
},
_bind_update:function(target, rule, format){
var data = this.getValue()||"";
if (format) data = format(data);
if (target.setValue)
target.setValue(data);
else if (!target.filter){
var pod = {}; pod[rule] = data;
if (target._check_data_feed(data))
target.setValues(pod);
} else{
target.data.silent(function(){
this.filter(rule,data);
});
}
target.callEvent("onBindApply", [data,rule,this]);
}
};
dhx.RecordBind={
$init:function(){
this.attachEvent("onChange", this._update_binds);
},
_bind_update:function(target, rule){
var data = this.getValues()||null;
this._bind_update_common(target, rule, data);
}
};
dhx.CollectionBind={
$init:function(){
this._cursor = null;
this.attachEvent("onSelectChange", function(data){
var sel = this.getSelected();
this.setCursor(sel?(sel.id||sel):null);
});
this.attachEvent("onAfterCursorChange", this._update_binds);
this.data.attachEvent("onStoreUpdated", dhx.bind(function(id, data, mode){
if (id && id == this.getCursor() && mode != "paint")
this._update_binds();
},this));
this.data.attachEvent("onClearAll", dhx.bind(function(){
this._cursor = null;
},this));
this.data.attachEvent("onIdChange", dhx.bind(function(oldid, newid){
if (this._cursor == oldid)
this._cursor = newid;
},this));
},
setCursor:function(id){
if (id == this._cursor || (id !== null && !this.item(id))) return;
this.callEvent("onBeforeCursorChange", [this._cursor]);
this._cursor = id;
this.callEvent("onAfterCursorChange",[id]);
},
getCursor:function(){
return this._cursor;
},
_bind_update:function(target, rule){
var data = this.item(this.getCursor())|| this._settings.defaultData || null;
this._bind_update_common(target, rule, data);
}
};
/*DHX:Depend core/legacy_bind.js*/
/*DHX:Depend core/dhx.js*/
/*DHX:Depend core/bind.js*/
/*jsl:ignore*/
if (!dhx.ui)
dhx.ui = {};
if (!dhx.ui.views){
dhx.ui.views = {};
dhx.ui.get = function(id){
if (id._settings) return id;
return dhx.ui.views[id];
};
}
if (window.dhtmlx)
dhtmlx.BaseBind = dhx.BaseBind;
dhtmlXDataStore = function(config){
var obj = new dhx.DataCollection(config);
var name = "_dp_init";
obj[name]=function(dp){
//map methods
var varname = "_methods";
dp[varname]=["dummy","dummy","changeId","dummy"];
this.data._old_names = {
"add":"inserted",
"update":"updated",
"delete":"deleted"
};
this.data.attachEvent("onStoreUpdated",function(id,data,mode){
if (id && !dp._silent)
dp.setUpdated(id,true,this._old_names[mode]);
});
varname = "_getRowData";
//serialize item's data in URL
dp[varname]=function(id,pref){
var ev=this.obj.data.item(id);
var data = { id:id };
data[this.action_param] = this.obj.getUserData(id);
if (ev)
for (var a in ev){
data[a]=ev[a];
}
return data;
};
this.changeId = function(oldid, newid){
this.data.changeId(oldid, newid);
dp._silent = true;
this.data.callEvent("onStoreUpdated", [newid, this.item(newid), "update"]);
dp._silent = false;
};
varname = "_clearUpdateFlag";
dp[varname]=function(){};
this._userdata = {};
};
obj.dummy = function(){};
obj.setUserData=function(id,name,value){
this._userdata[id]=value;
};
obj.getUserData=function(id,name){
return this._userdata[id];
};
obj.dataFeed=function(obj){
this.define("dataFeed", obj);
};
dhx.extend(obj, dhx.BindSource);
return obj;
};
if (window.dhtmlXDataView)
dhtmlXDataView.prototype._initBindSource=function(){
this.isVisible = function(){
if (!this.data.order.length && !this.data._filter_order && !this._settings.dataFeed) return false;
return true;
};
var settings = "_settings";
this._settings = this._settings || this[settings];
if (!this._settings.id)
this._settings.id = dhx.uid();
this.unbind = dhx.BaseBind.unbind;
this.unsync = dhx.BaseBind.unsync;
dhx.ui.views[this._settings.id] = this;
};
if (window.dhtmlXChart)
dhtmlXChart.prototype._initBindSource=function(){
this.isVisible = function(){
if (!this.data.order.length && !this.data._filtered_state && !this._settings.dataFeed) return false;
return true;
};
var settings = "_settings";
this._settings = this._settings || this[settings];
if (!this._settings.id)
this._settings.id = dhx.uid();
this.unbind = dhx.BaseBind.unbind;
this.unsync = dhx.BaseBind.unsync;
dhx.ui.views[this._settings.id] = this;
};
dhx.BaseBind.unsync = function(target){
return dhx.BaseBind._unbind.call(this, target);
}
dhx.BaseBind.unbind = function(target){
return dhx.BaseBind._unbind.call(this, target);
}
dhx.BaseBind.legacyBind = function(){
return dhx.BaseBind.bind.apply(this, arguments);
};
dhx.BaseBind.legacySync = function(source, rule){
if (this._initBindSource) this._initBindSource();
if (source._initBindSource) source._initBindSource();
this.attachEvent("onAfterEditStop", function(id){
this.save(id);
return true;
});
this.attachEvent("onDataRequest", function(start, count){
for (var i=start; i<start+count; i++)
if (!source.data.order[i]){
source.loadNext(count, start);
return false;
}
});
this.save = function(id){
if (!id) id = this.getCursor();
var sobj = this.item(id);
var tobj = source.item(id);
for (var key in sobj)
if (key.indexOf("$")!==0)
tobj[key] = sobj[key];
source.refresh(id);
};
if (source && source.name == "DataCollection")
return source.data.sync.apply(this.data, arguments);
else
return this.data.sync.apply(this.data, arguments);
};
if (window.dhtmlXForm){
dhtmlXForm.prototype.bind = function(target){
dhx.BaseBind.bind.apply(this, arguments);
target.getBindData(this._settings.id);
};
dhtmlXForm.prototype.unbind = function(target){
dhx.BaseBind._unbind.call(this,target);
};
dhtmlXForm.prototype._initBindSource = function(){
if (dhx.isUndefined(this._settings)){
this._settings = {
id: dhx.uid(),
dataFeed:this._server_feed
};
dhx.ui.views[this._settings.id] = this;
}
};
dhtmlXForm.prototype._check_data_feed = function(data){
if (!this._settings.dataFeed || this._ignore_feed || !data) return true;
var url = this._settings.dataFeed;
if (typeof url == "function")
return url.call(this, (data.id||data), data);
url = url+(url.indexOf("?")==-1?"?":"&")+"action=get&id="+encodeURIComponent(data.id||data);
this.load(url);
return false;
};
dhtmlXForm.prototype.setValues = dhtmlXForm.prototype.setFormData;
dhtmlXForm.prototype.getValues = function(){
return this.getFormData(false, true);
};
dhtmlXForm.prototype.dataFeed = function(value){
if (this._settings)
this._settings.dataFeed = value;
else
this._server_feed = value;
};
dhtmlXForm.prototype.refresh = dhtmlXForm.prototype.isVisible = function(value){
return true;
};
}
if (window.scheduler){
if (!window.Scheduler)
window.Scheduler = {};
Scheduler.$syncFactory=function(scheduler){
scheduler.sync = function(source, rule){
if (this._initBindSource) this._initBindSource();
if (source._initBindSource) source._initBindSource();
var process = "_process_loading";
var insync = function(ignore){
scheduler.clearAll();
var order = source.data.order;
var pull = source.data.pull;
var evs = [];
for (var i=0; i<order.length; i++){
if (rule && rule.copy)
evs[i]=dhx.clone(pull[order[i]]);
else
evs[i]=pull[order[i]];
}
scheduler[process](evs);
scheduler.callEvent("onSyncApply",[]);
};
this.save = function(id){
if (!id) id = this.getCursor();
var data = this.item(id);
var olddat = source.item(id);
if (this.callEvent("onStoreSave", [id, data, olddat])){
dhx.extend(source.item(id),data, true);
source.update(id);
}
};
this.item = function(id){
return this.getEvent(id);
};
this._sync_events=[
source.data.attachEvent("onStoreUpdated", function(id, data, mode){
insync.call(this);
}),
source.data.attachEvent("onIdChange", function(oldid, newid){
combo.changeOptionId(oldid, newid);
})
];
this.attachEvent("onEventChanged", function(id){
this.save(id);
});
this.attachEvent("onEventAdded", function(id, data){
if (!source.data.pull[id])
source.add(data);
});
this.attachEvent("onEventDeleted", function(id){
if (source.data.pull[id])
source.remove(id);
});
insync();
};
scheduler.unsync = function(target){
dhx.BaseBind._unbind.call(this,target);
}
scheduler._initBindSource = function(){
if (!this._settings)
this._settings = { id:dhx.uid() };
}
}
Scheduler.$syncFactory(window.scheduler);
}
if (window.dhtmlXCombo){
dhtmlXCombo.prototype.bind = function(){
dhx.BaseBind.bind.apply(this, arguments);
};
dhtmlXCombo.prototype.unbind = function(target){
dhx.BaseBind._unbind.call(this,target);
}
dhtmlXCombo.prototype.unsync = function(target){
dhx.BaseBind._unbind.call(this,target);
}
dhtmlXCombo.prototype.dataFeed = function(value){
if (this._settings)
this._settings.dataFeed = value;
else
this._server_feed = value;
};
dhtmlXCombo.prototype.sync = function(source, rule){
if (this._initBindSource) this._initBindSource();
if (source._initBindSource) source._initBindSource();
var combo = this;
var insync = function(ignore){
combo.clearAll();
combo.addOption(this.serialize());
combo.callEvent("onSyncApply",[]);
};
//source.data.attachEvent("onStoreLoad", insync);
this._sync_events=[
source.data.attachEvent("onStoreUpdated", function(id, data, mode){
insync.call(this);
}),
source.data.attachEvent("onIdChange", function(oldid, newid){
combo.changeOptionId(oldid, newid);
})
];
insync.call(source);
};
dhtmlXCombo.prototype._initBindSource = function() {
if (dhx.isUndefined(this._settings)){
this._settings = {
id: dhx.uid(),
dataFeed:this._server_feed
};
dhx.ui.views[this._settings.id] = this;
this.data = { silent:dhx.bind(function(code){
code.call(this);
},this)};
dhx4._eventable(this.data);
this.attachEvent("onChange", function() {
this.callEvent("onSelectChange", [this.getSelectedValue()]);
});
this.attachEvent("onXLE", function(){
this.callEvent("onBindRequest",[]);
});
}
};
dhtmlXCombo.prototype.item = function(id) {
return this.getOption(id);
};
dhtmlXCombo.prototype.getSelected = function() {
return this.getSelectedValue();
};
dhtmlXCombo.prototype.isVisible = function() {
if (!this.optionsArr.length && !this._settings.dataFeed) return false;
return true;
};
dhtmlXCombo.prototype.refresh = function() {
this.render(true);
};
}
if (window.dhtmlXGridObject){
dhtmlXGridObject.prototype.bind = function(source, rule, format) {
dhx.BaseBind.bind.apply(this, arguments);
};
dhtmlXGridObject.prototype.unbind = function(target){
dhx.BaseBind._unbind.call(this,target);
}
dhtmlXGridObject.prototype.unsync = function(target){
dhx.BaseBind._unbind.call(this,target);
}
dhtmlXGridObject.prototype.dataFeed = function(value){
if (this._settings)
this._settings.dataFeed = value;
else
this._server_feed = value;
};
dhtmlXGridObject.prototype.sync = function(source, rule){
if (this._initBindSource) this._initBindSource();
if (source._initBindSource) source._initBindSource();
var grid = this;
var parsing = "_parsing";
var parser = "_parser";
var locator = "_locator";
var parser_func = "_process_store_row";
var locator_func = "_get_store_data";
this.save = function(id){
if (!id) id = this.getCursor();
dhx.extend(source.item(id),this.item(id), true);
source.update(id);
};
var insync = function(ignore){
var cursor = grid.getCursor?grid.getCursor():null;
var from = 0;
if (grid._legacy_ignore_next){
from = grid._legacy_ignore_next;
grid._legacy_ignore_next = false;
} else {
grid.clearAll();
}
var count = this.dataCount();
if (count){
grid[parsing]=true;
for (var i = from; i < count; i++){
var id = this.order[i];
if (!id) continue;
if (from && grid.rowsBuffer[i]) continue;
grid.rowsBuffer[i]={
idd: id,
data: this.pull[id]
};
grid.rowsBuffer[i][parser] = grid[parser_func];
grid.rowsBuffer[i][locator] = grid[locator_func];
grid.rowsAr[id]=this.pull[id];
}
if (!grid.rowsBuffer[count-1]){
grid.rowsBuffer[count-1] = dhtmlx.undefined;
grid.xmlFileUrl = grid.xmlFileUrl||this.url;
}
if (grid.pagingOn)
grid.changePage();
else {
if (grid._srnd && grid._fillers)
grid._update_srnd_view();
else{
grid.render_dataset();
grid.callEvent("onXLE",[]);
}
}
grid[parsing]=false;
}
if (cursor && grid.setCursor)
grid.setCursor(grid.rowsAr[cursor]?cursor:null);
grid.callEvent("onSyncApply",[]);
};
//source.data.attachEvent("onStoreLoad", insync);
this._sync_events=[
source.data.attachEvent("onStoreUpdated", function(id, data, mode){
if (mode == "delete"){
grid.deleteRow(id);
grid.data.callEvent("onStoreUpdated",[id, data, mode]);
} else if (mode == "update"){
grid.callEvent("onSyncUpdate", [data, mode]);
grid.update(id, data);
grid.data.callEvent("onStoreUpdated",[id, data, mode]);
} else if (mode == "add"){
grid.callEvent("onSyncUpdate", [data, mode]);
grid.add(id, data, this.indexById(id));
grid.data.callEvent("onStoreUpdated",[id,data,mode]);
} else insync.call(this);
}),
source.data.attachEvent("onStoreLoad", function(driver, data){
grid.xmlFileUrl = source.data.url;
grid._legacy_ignore_next = driver.getInfo(data)._from;
}),
source.data.attachEvent("onIdChange", function(oldid, newid){
grid.changeRowId(oldid, newid);
})
];
grid.attachEvent("onDynXLS", function(start, count){
for (var i=start; i<start+count; i++)
if (!source.data.order[i]){
source.loadNext(count, start);
return false;
}
grid._legacy_ignore_next = start;
insync.call(source.data);
});
insync.call(source.data);
grid.attachEvent("onEditCell", function(stage, id, ind, value, oldvalue){
if (stage==2 && value != oldvalue)
this.save(id);
return true;
});
grid.attachEvent("onClearAll",function(){
var name = "_f_rowsBuffer";
this[name]=null;
});
if (rule && rule.sort)
grid.attachEvent("onBeforeSorting", function(ind, type, dir){
if (type == "connector") return false;
var id = this.getColumnId(ind);
source.sort("#"+id+"#", (dir=="asc"?"asc":"desc"), (type=="int"?type:"string"));
grid.setSortImgState(true, ind, dir);
return false;
});
if (rule && rule.filter){
grid.attachEvent("onFilterStart", function(cols, values){
var name = "_con_f_used";
if (grid[name] && grid[name].length)
return false;
source.data.silent(function(){
source.filter();
for (var i=0; i<cols.length; i++){
if (values[i] == "") continue;
var id = grid.getColumnId(cols[i]);
source.filter("#"+id+"#", values[i], i!=0);
}
});
source.refresh();
return false;
});
grid.collectValues = function(index){
var id = this.getColumnId(index);
return (function(id){
var values = [];
var checks = {};
this.data.each(function(obj){
var value = obj[id];
if (!checks[value]){
checks[value] = true;
values.push(value);
}
});
values.sort();
return values;
}).call(source, id);
};
}
if (rule && rule.select)
grid.attachEvent("onRowSelect", function(id){
source.setCursor(id);
});
grid.clearAndLoad = function(url){
source.clearAll();
source.load(url);
};
};
dhtmlXGridObject.prototype._initBindSource = function() {
if (dhx.isUndefined(this._settings)){
this._settings = {
id: dhx.uid(),
dataFeed:this._server_feed
};
dhx.ui.views[this._settings.id] = this;
this.data = { silent:dhx.bind(function(code){
code.call(this);
},this)};
dhx4._eventable(this.data);
var name = "_cCount";
for (var i=0; i<this[name]; i++)
if (!this.columnIds[i])
this.columnIds[i] = "cell"+i;
this.attachEvent("onSelectStateChanged", function(id) {
this.callEvent("onSelectChange", [id]);
});
this.attachEvent("onSelectionCleared", function() {
this.callEvent("onSelectChange", [null]);
});
this.attachEvent("onEditCell", function(stage,rId) {
if (stage === 2 && this.getCursor) {
if (rId && rId == this.getCursor())
this._update_binds();
}
return true;
});
this.attachEvent("onXLE", function(){
this.callEvent("onBindRequest",[]);
});
}
};
dhtmlXGridObject.prototype.item = function(id) {
if (id === null) return null;
var source = this.getRowById(id);
if (!source) return null;
var name = "_attrs";
var data = dhx.copy(source[name]);
data.id = id;
var length = this.getColumnsNum();
for (var i = 0; i < length; i++) {
data[this.columnIds[i]] = this.cells(id, i).getValue();
}
return data;
};
dhtmlXGridObject.prototype.update = function(id,data){
for (var i=0; i<this.columnIds.length; i++){
var key = this.columnIds[i];
if (!dhx.isUndefined(data[key]))
this.cells(id, i).setValue(data[key]);
}
var name = "_attrs";
var attrs = this.getRowById(id)[name];
for (var key in data)
attrs[key] = data[key];
this.callEvent("onBindUpdate",[data, null, id]);
};
dhtmlXGridObject.prototype.add = function(id,data,index){
var ar_data = [];
for (var i=0; i<this.columnIds.length; i++){
var key = this.columnIds[i];
ar_data[i] = dhx.isUndefined(data[key])?"":data[key];
}
this.addRow(id, ar_data, index);
var name = "_attrs";
this.getRowById(id)[name] = dhx.copy(data);
};
dhtmlXGridObject.prototype.getSelected = function() {
return this.getSelectedRowId();
};
dhtmlXGridObject.prototype.isVisible = function() {
var name = "_f_rowsBuffer";
if (!this.rowsBuffer.length && !this[name] && !this._settings.dataFeed) return false;
return true;
};
dhtmlXGridObject.prototype.refresh = function() {
this.render_dataset();
};
dhtmlXGridObject.prototype.filter = function(callback, master){
//if (!this.rowsBuffer.length && !this._f_rowsBuffer) return;
if (this._settings.dataFeed){
var filter = {};
if (!callback && !master) return;
if (typeof callback == "function"){
if (!master) return;
callback(master, filter);
} else if (dhx.isUndefined(callback))
filter = master;
else
filter[callback] = master;
this.clearAll();
var url = this._settings.dataFeed;
if (typeof url == "function")
return url.call(this, master, filter);
var urldata = [];
for (var key in filter)
urldata.push("dhx_filter["+key+"]="+encodeURIComponent(filter[key]));
this.load(url+(url.indexOf("?")<0?"?":"&")+urldata.join("&"));
return false;
}
if (master === null) {
return this.filterBy(0, function(){ return false; });
}
this.filterBy(0, function(value, id){
return callback.call(this, id, master);
});
};
}
if (window.dhtmlXTreeObject){
dhtmlXTreeObject.prototype.bind = function() {
dhx.BaseBind.bind.apply(this, arguments);
};
dhtmlXTreeObject.prototype.unbind = function(target){
dhx.BaseBind._unbind.call(this,target);
}
dhtmlXTreeObject.prototype.dataFeed = function(value){
if (this._settings)
this._settings.dataFeed = value;
else
this._server_feed = value;
};
dhtmlXTreeObject.prototype._initBindSource = function() {
if (dhx.isUndefined(this._settings)){
this._settings = {
id: dhx.uid(),
dataFeed:this._server_feed
};
dhx.ui.views[this._settings.id] = this;
this.data = { silent:dhx.bind(function(code){
code.call(this);
},this)};
dhx4._eventable(this.data);
this.attachEvent("onSelect", function(id) {
this.callEvent("onSelectChange", [id]);
});
this.attachEvent("onEdit", function(stage,rId) {
if (stage === 2) {
if (rId && rId == this.getCursor())
this._update_binds();
}
return true;
});
}
};
dhtmlXTreeObject.prototype.item = function(id) {
if (id === null) return null;
return { id: id, text:this.getItemText(id)};
};
dhtmlXTreeObject.prototype.getSelected = function() {
return this.getSelectedItemId();
};
dhtmlXTreeObject.prototype.isVisible = function() {
return true;
};
dhtmlXTreeObject.prototype.refresh = function() {
//dummy placeholder
};
dhtmlXTreeObject.prototype.filter = function(callback, master){
//dummy placeholder, because tree doesn't support filtering
if (this._settings.dataFeed){
var filter = {};
if (!callback && !master) return;
if (typeof callback == "function"){
if (!master) return;
callback(master, filter);
} else if (dhx.isUndefined(callback))
filter = master;
else
filter[callback] = master;
this.deleteChildItems(0);
var url = this._settings.dataFeed;
if (typeof url == "function")
return url.call(this, [(data.id||data), data]);
var urldata = [];
for (var key in filter)
urldata.push("dhx_filter["+key+"]="+encodeURIComponent(filter[key]));
this.loadXML(url+(url.indexOf("?")<0?"?":"&")+urldata.join("&"));
return false;
}
};
dhtmlXTreeObject.prototype.update = function(id,data){
if (!dhx.isUndefined(data.text))
this.setItemText(id, data.text);
};
}
/*jsl:end*/
})();
| vijaysebastian/bill | public/plugins/dhtmlxSuite_v50_std/sources/dhtmlxDataStore/codebase/datastore.js | JavaScript | gpl-3.0 | 94,389 |
<?php
/**
* @file plugins/generic/customBlockManager/CustomBlockEditForm.inc.php
*
* Copyright (c) 2013-2015 Simon Fraser University Library
* Copyright (c) 2003-2015 John Willinsky
* Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
*
* @package plugins.generic.customBlockManager
* @class CustomBlockEditForm
*
* Form for journal managers to create and modify sidebar blocks
*
*/
import('lib.pkp.classes.form.Form');
class CustomBlockEditForm extends Form {
/** @var $journalId int */
var $journalId;
/** @var $plugin object */
var $plugin;
/** $var $errors string */
var $errors;
/**
* Constructor
* @param $journalId int
*/
function CustomBlockEditForm(&$plugin, $journalId) {
parent::Form($plugin->getTemplatePath() . 'editCustomBlockForm.tpl');
$this->journalId = $journalId;
$this->plugin =& $plugin;
$this->addCheck(new FormValidatorPost($this));
$this->addCheck(new FormValidator($this, 'blockContent', 'required', 'plugins.generic.customBlock.contentRequired'));
}
/**
* Initialize form data from current group group.
*/
function initData() {
$journalId = $this->journalId;
$plugin =& $this->plugin;
// add the tiny MCE script
$this->addTinyMCE();
$this->setData('blockContent', $plugin->getSetting($journalId, 'blockContent'));
}
/**
* Add the tinyMCE script for editing sidebar blocks with a WYSIWYG editor
*/
function addTinyMCE() {
$journalId = $this->journalId;
$plugin =& $this->plugin;
$templateMgr =& TemplateManager::getManager();
// Enable TinyMCE with specific params
$additionalHeadData = $templateMgr->get_template_vars('additionalHeadData');
import('classes.file.JournalFileManager');
$publicFileManager = new PublicFileManager();
$tinyMCE_script = '
<script language="javascript" type="text/javascript" src="'.Request::getBaseUrl().'/'.TINYMCE_JS_PATH.'/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
mode : "textareas",
plugins : "style,paste,jbimages",
theme : "advanced",
theme_advanced_buttons1 : "formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink",
theme_advanced_buttons3 : "cut,copy,paste,pastetext,pasteword,|,cleanup,help,code,jbimages",
theme_advanced_toolbar_location : "bottom",
theme_advanced_toolbar_align : "left",
content_css : "' . Request::getBaseUrl() . '/styles/common.css",
relative_urls : false,
document_base_url : "'. Request::getBaseUrl() .'/'.$publicFileManager->getJournalFilesPath($journalId) .'/",
extended_valid_elements : "span[*], div[*]"
});
</script>';
$templateMgr->assign('additionalHeadData', $additionalHeadData."\n".$tinyMCE_script);
}
/**
* Assign form data to user-submitted data.
*/
function readInputData() {
$this->readUserVars(array('blockContent'));
}
/**
* Get the names of localized fields
* @return array
*/
function getLocaleFieldNames() {
return array('blockContent');
}
/**
* Save page into DB
*/
function save() {
$plugin =& $this->plugin;
$journalId = $this->journalId;
$plugin->updateSetting($journalId, 'blockContent', $this->getData('blockContent'));
}
}
?>
| jasonzou/journal.calaijol.org | tools/plugins/generic/customBlockManager/CustomBlockEditForm.inc.php | PHP | gpl-3.0 | 3,356 |
<?php
namespace Fbns\Client;
interface AuthInterface
{
/**
* @return string
*/
public function getClientId();
/**
* @return string
*/
public function getClientType();
/**
* @return int
*/
public function getUserId();
/**
* @return string
*/
public function getPassword();
/**
* @return string
*/
public function getDeviceId();
/**
* @return string
*/
public function getDeviceSecret();
/**
* @return string
*/
public function __toString();
}
| kotsios5/openclassifieds2 | oc/vendor/Instagram-API/vendor/valga/fbns-react/src/AuthInterface.php | PHP | gpl-3.0 | 576 |
#include "MapTileGraphicsObject.h"
#include <QPainter>
#include <QtDebug>
MapTileGraphicsObject::MapTileGraphicsObject(quint16 tileSize)
{
this->setTileSize(tileSize);
_tile = nullptr;
_tileX = 0;
_tileY = 0;
_tileZoom = 0;
_initialized = false;
_havePendingRequest = false;
//Default z-value is important --- used in MapGraphicsView
this->setZValue(-1.0);
}
MapTileGraphicsObject::~MapTileGraphicsObject()
{
if (_tile != nullptr)
{
delete _tile;
_tile = nullptr;
}
}
QRectF MapTileGraphicsObject::boundingRect() const
{
const quint16 size = this->tileSize();
return QRectF(-1 * size / 2.0,
-1 * size / 2.0,
size,
size);
}
void MapTileGraphicsObject::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option)
Q_UNUSED(widget)
//If we've got a tile, draw it. Otherwise, show a loading or "No tile source" message
if (_tile != nullptr)
painter->drawPixmap(this->boundingRect().toRect(),
*_tile);
else
{
QString string;
if (_tileSource.isNull())
string = " No tile source defined";
else
string = " Loading...";
painter->drawText(this->boundingRect(),
string,
QTextOption(Qt::AlignCenter));
}
}
quint16 MapTileGraphicsObject::tileSize() const
{
return _tileSize;
}
void MapTileGraphicsObject::setTileSize(quint16 tileSize)
{
if (tileSize == _tileSize)
return;
_tileSize = tileSize;
}
void MapTileGraphicsObject::setTile(quint32 x, quint32 y, quint8 z, bool force)
{
//Don't re-request the same tile we're already displaying unless force=true or _initialized=false
if (_tileX == x && _tileY == y && _tileZoom == z && !force && _initialized)
return;
//Get rid of the old tile
if (_tile != nullptr)
{
delete _tile;
_tile = nullptr;
}
//Store information for the tile we're requesting
_tileX = x;
_tileY = y;
_tileZoom = z;
_initialized = true;
//If we have a null tile source, there's not much more to do!
if (_tileSource.isNull())
return;
//If our tile source is good, connect to the signal we'll need to get the result after requesting
connect(_tileSource.data(),
SIGNAL(tileRetrieved(quint32,quint32,quint8)),
this,
SLOT(handleTileRetrieved(quint32,quint32,quint8)));
//Make sure we know that we're requesting a tile
_havePendingRequest = true;
//Request the tile from tileSource, which will emit tileRetrieved when finished
//qDebug() << this << "requests" << x << y << z;
_tileSource->requestTile(x,y,z);
}
QSharedPointer<MapTileSource> MapTileGraphicsObject::tileSource() const
{
return _tileSource;
}
void MapTileGraphicsObject::setTileSource(QSharedPointer<MapTileSource> nSource)
{
//Disconnect from the old source, if applicable
if (!_tileSource.isNull())
{
QObject::disconnect(_tileSource.data(),
SIGNAL(tileRetrieved(quint32,quint32,quint8)),
this,
SLOT(handleTileRetrieved(quint32,quint32,quint8)));
QObject::disconnect(_tileSource.data(),
SIGNAL(allTilesInvalidated()),
this,
SLOT(handleTileInvalidation()));
}
//Set the new source
QSharedPointer<MapTileSource> oldSource = _tileSource;
_tileSource = nSource;
//Connect signals if approprite
if (!_tileSource.isNull())
{
connect(_tileSource.data(),
SIGNAL(allTilesInvalidated()),
this,
SLOT(handleTileInvalidation()));
//We connect/disconnect the "tileRetrieved" signal as needed and don't do it here!
}
//Force a refresh from the new source
this->handleTileInvalidation();
}
//private slot
void MapTileGraphicsObject::handleTileRetrieved(quint32 x, quint32 y, quint8 z)
{
//If we don't care about retrieved tiles (i.e., we haven't requested a tile), return
//This shouldn't actually happen as the signal/slot should get disconnected
if (!_havePendingRequest)
return;
//If this isn't the tile we're looking for, return
else if (_tileX != x || _tileY != y || _tileZoom != z)
return;
//Now we know that our tile has been retrieved by the MapTileSource. We just need to get it.
_havePendingRequest = false;
//Make sure some mischevious person hasn't set our MapTileSource to null while we weren't looking...
if (_tileSource.isNull())
return;
QImage * image = _tileSource->getFinishedTile(x,y,z);
//Make sure someone didn't snake us to grabbing our tile
if (image == nullptr)
{
qWarning() << "Failed to get tile" << x << y << z << "from MapTileSource";
return;
}
//Convert the QImage to a QPixmap
//We have to do this here since we can't use QPixmaps in non-GUI threads (i.e., MapTileSource)
QPixmap * tile = new QPixmap();
*tile = QPixmap::fromImage(*image);
//Delete the QImage
delete image;
image = nullptr;
//Make sure that the old tile has been disposed of. If it hasn't, do it
//In reality, it should have been, so display a warning
if (_tile != nullptr)
{
qWarning() << "Tile should be null, but isn't";
delete _tile;
_tile = nullptr;
}
//Set the new tile and force a redraw
_tile = tile;
this->update();
//Disconnect our signal/slot connection with MapTileSource until we need to do another request
//It remains to be seen if it's better to continually connect/reconnect or just to filter events
QObject::disconnect(_tileSource.data(),
SIGNAL(tileRetrieved(quint32,quint32,quint8)),
this,
SLOT(handleTileRetrieved(quint32,quint32,quint8)));
}
//private slot
void MapTileGraphicsObject::handleTileInvalidation()
{
//If we haven't been initialized with a proper tile coordinate to fetch yet, don't force a refresh
if (!_initialized)
return;
//Call setTile with force=true so that it forces a refresh
this->setTile(_tileX,_tileY,_tileZoom,true);
}
| ftomei/CRITERIA3D | mapGraphics/guts/MapTileGraphicsObject.cpp | C++ | gpl-3.0 | 6,441 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'ImportFile.results_acoustid'
db.add_column('importer_importfile', 'results_acoustid',
self.gf('django.db.models.fields.TextField')(default='{}', null=True, blank=True),
keep_default=False)
# Adding field 'ImportFile.results_acoustid_status'
db.add_column('importer_importfile', 'results_acoustid_status',
self.gf('django.db.models.fields.PositiveIntegerField')(default=0),
keep_default=False)
def backwards(self, orm):
# Deleting field 'ImportFile.results_acoustid'
db.delete_column('importer_importfile', 'results_acoustid')
# Deleting field 'ImportFile.results_acoustid_status'
db.delete_column('importer_importfile', 'results_acoustid_status')
models = {
'actstream.action': {
'Meta': {'ordering': "('-timestamp',)", 'object_name': 'Action'},
'action_object_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'action_object'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'action_object_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'actor_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actor'", 'to': "orm['contenttypes.ContentType']"}),
'actor_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'data': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'target_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'importer.import': {
'Meta': {'ordering': "('-created',)", 'object_name': 'Import'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'type': ('django.db.models.fields.CharField', [], {'default': "'web'", 'max_length': "'10'"}),
'updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'import_user'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['auth.User']"})
},
'importer.importfile': {
'Meta': {'ordering': "('-created',)", 'object_name': 'ImportFile'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
'filename': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'import_session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'files'", 'null': 'True', 'to': "orm['importer.Import']"}),
'mimetype': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'results_acoustid': ('django.db.models.fields.TextField', [], {'default': "'{}'", 'null': 'True', 'blank': 'True'}),
'results_acoustid_status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'results_discogs': ('django.db.models.fields.TextField', [], {'default': "'{}'", 'null': 'True', 'blank': 'True'}),
'results_discogs_status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'results_musicbrainz': ('django.db.models.fields.TextField', [], {'default': "'{}'", 'null': 'True', 'blank': 'True'}),
'results_tag': ('django.db.models.fields.TextField', [], {'default': "'{}'", 'null': 'True', 'blank': 'True'}),
'results_tag_status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'})
}
}
complete_apps = ['importer'] | hzlf/openbroadcast | website/apps/importer/migrations/0009_auto__add_field_importfile_results_acoustid__add_field_importfile_resu.py | Python | gpl-3.0 | 8,507 |
import Component from './component';
export default class ElementsColorPicker extends elementorModules.ViewModule {
/**
* Initialize the Eye-Dropper module.
*
* @returns {void}
*/
onInit() {
super.onInit();
$e.components.register( new Component() );
}
}
| pojome/elementor | modules/elements-color-picker/assets/js/editor/module.js | JavaScript | gpl-3.0 | 271 |
// ==UserScript==
// @name Letterboxd Backdrop Remover
// @namespace https://github.com/emg/userscripts
// @description Removes backdrop image from film pages
// @copyright 2014+, Ramón Guijarro (http://soyguijarro.com)
// @homepageURL https://github.com/soyguijarro/userscripts
// @supportURL https://github.com/soyguijarro/userscripts/issues
// @updateURL https://raw.githubusercontent.com/soyguijarro/userscripts/master/Letterboxd_Backdrop_Remover.user.js
// @icon https://raw.githubusercontent.com/soyguijarro/userscripts/master/img/letterboxd_icon.png
// @license GPLv3; http://www.gnu.org/licenses/gpl.html
// @version 1.3
// @include *://letterboxd.com/film/*
// @include *://letterboxd.com/film/*/crew/*
// @include *://letterboxd.com/film/*/studios/*
// @include *://letterboxd.com/film/*/genres/*
// @exclude *://letterboxd.com/film/*/views/*
// @exclude *://letterboxd.com/film/*/lists/*
// @exclude *://letterboxd.com/film/*/likes/*
// @exclude *://letterboxd.com/film/*/fans/*
// @exclude *://letterboxd.com/film/*/ratings/*
// @exclude *://letterboxd.com/film/*/reviews/*
// @grant none
// ==/UserScript==
var containerElt = document.getElementById("content"),
backdropElt = document.getElementById("backdrop"),
contentElt = backdropElt.getElementsByClassName("content-wrap")[0];
containerElt.replaceChild(contentElt, backdropElt);
containerElt.classList.remove("has-backdrop"); | rcalderong/userscripts | Letterboxd_Backdrop_Remover.user.js | JavaScript | gpl-3.0 | 1,478 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | OpenQBMM - www.openqbmm.org
\\/ M anipulation |
-------------------------------------------------------------------------------
Code created 2010-2014 by Bo Kong and 2015-2018 by Alberto Passalacqua
Contributed 2018-07-31 to the OpenFOAM Foundation
Copyright (C) 2018 OpenFOAM Foundation
Copyright (C) 2019-2020 Alberto Passalacqua
-------------------------------------------------------------------------------
License
This file is derivative work 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 "hermiteQuadrature.H"
#include "scalar.H"
#include "scalarMatrices.H"
#include "EigenMatrix.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
const Foam::scalar Foam::hermiteQuadrature::thetaLimit_ = 1.0E-7;
Foam::hermiteQuadrature::hermiteQuadrature
(
const label& nDim,
const label& nOrder
)
:
nDim_(nDim),
nOrder_(nOrder),
nTolNodes_(pow(nOrder_, nDim)),
origWei_(nTolNodes_, Zero),
origAbs_(nTolNodes_, Zero),
resAbs_(nTolNodes_, Zero)
{
if((nOrder_ <= 0))
{
FatalErrorIn("Foam::hermiteQuadrature\n" )
<< "parameter(s) out of range ! "
<< abort(FatalError);
}
scalarRectangularMatrix ab(nOrder_, 2, scalar(0));
for(label i = 0; i < nOrder_; i++)
{
ab[i][1]= scalar(i);
}
scalarSquareMatrix z(nOrder_, Zero);
for (label i = 0; i < nOrder_ - 1; i++)
{
z[i][i] = ab[i][0];
z[i][i+1] = Foam::sqrt(ab[i+1][1]);
z[i+1][i] = z[i][i+1];
}
z[nOrder_-1][nOrder_-1] = ab[nOrder_-1][0];
EigenMatrix<scalar> zEig(z);
scalarList herWei_(nOrder_, Zero);
scalarList herAbs_(nOrder_, Zero);
forAll(herWei_,i)
{
herWei_[i] = sqr(zEig.EVecs()[0][i]);
herAbs_[i] = zEig.EValsRe()[i];
}
scalar wtotal = sum(herWei_) ;
forAll(herWei_,i)
{
herWei_[i] = herWei_[i]/wtotal;
}
if (nDim_ == 1)
{
forAll(origWei_,i)
{
origWei_[i] = herWei_[i];
origAbs_[i] = vector(herAbs_[i], 0, 0);
}
}
maxAbs_ = max(herAbs_);
if (nDim_ == 2)
{
for(label i = 0; i < nOrder_; i++)
{
for(label j = 0; j < nOrder_; j++)
{
label p = i*nOrder_ + j;
origWei_[p] = herWei_[i]*herWei_[j];
origAbs_[p] = vector(herAbs_[i], herAbs_[j], 0);
}
}
}
if (nDim_ == 3)
{
for(label i = 0; i < nOrder_; i++)
{
for(label j = 0; j < nOrder_; j++)
{
for(label k = 0; k < nOrder_; k++)
{
label p = i*nOrder_*nOrder_ + j*nOrder_ + k;
origWei_[p] = herWei_[i]*herWei_[j]*herWei_[k];
origAbs_[p] = vector(herAbs_[i], herAbs_[j], herAbs_[k]);
}
}
}
}
return ;
}
void Foam::hermiteQuadrature::calcHermiteQuadrature
(
const vector& mu,
const symmTensor& Pp
)
{
if (tr(Pp) > thetaLimit_)
{
tensor spM(tensor::zero);
if( nDim_ == 3)
{
scalarSquareMatrix z(3, Zero);
z[0][0] = Pp.xx();
z[0][1] = Pp.xy();
z[0][2] = Pp.xz();
z[1][0] = Pp.xy();
z[1][1] = Pp.yy();
z[1][2] = Pp.yz();
z[2][0] = Pp.xz();
z[2][1] = Pp.yz();
z[2][2] = Pp.zz();
EigenMatrix<scalar> zEig(z);
const scalarDiagonalMatrix& e(zEig.EValsRe());
const scalarSquareMatrix& ev(zEig.EVecs());
scalarSquareMatrix E(3, Zero);
forAll(e,i)
{
if(e[i] >= 0)
{
E[i][i] = sqrt(e[i]);
}
else
{
E[i][i] = 0.0;
}
}
z = Zero;
multiply(z, ev, E);
forAll(spM,i) spM[i] = z[label(i/3)][i % 3];
}
else
{
if(nDim_==2)
{
scalarSquareMatrix z(2, Zero);
z[0][0] = Pp.xx();
z[0][1] = Pp.xy();
z[1][0] = Pp.xy();
z[1][1] = Pp.yy();
EigenMatrix<scalar> zEig(z);
const scalarDiagonalMatrix& e(zEig.EValsRe());
const scalarSquareMatrix& ev(zEig.EVecs());
scalarSquareMatrix E(2,Zero);
forAll(e, i)
{
if(e[i] >=0)
{
E[i][i] = sqrt(e[i]);
}
else
{
E[i][i] = 0.0;
}
}
z = Zero;
multiply(z, ev, E);
spM.xx() = z[0][0];
spM.xy() = z[0][1];
spM.yx() = z[1][0];
spM.yy() = z[1][1];
}
else
{
spM.xx() = sqrt(Pp.xx());
}
}
resAbs_ = (spM & origAbs_) + mu;
}
else
{
resAbs_ = mu ;
}
return ;
}
// ************************************************************************* //
| OpenQBMM/OpenQBMM-dev | src/quadratureMethods/hermiteQuadrature/hermiteQuadrature.C | C++ | gpl-3.0 | 6,271 |
package matteroverdrive.data.matter;
import matteroverdrive.api.matter.IMatterEntry;
import net.minecraft.nbt.NBTTagCompound;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Simeon on 1/18/2016.
*/
public abstract class MatterEntryAbstract<KEY, MAT> implements IMatterEntry<KEY, MAT>
{
protected final List<IMatterEntryHandler<MAT>> handlers;
protected KEY key;
public MatterEntryAbstract()
{
this.handlers = new ArrayList<>();
}
public MatterEntryAbstract(KEY key)
{
this();
this.key = key;
}
@Override
public int getMatter(MAT key)
{
int matter = 0;
for (IMatterEntryHandler handler : handlers)
{
matter = handler.modifyMatter(key, matter);
if (handler.finalModification(key))
{
return matter;
}
}
return matter;
}
public abstract void writeTo(DataOutput output) throws IOException;
public abstract void writeTo(NBTTagCompound tagCompound);
public abstract void readFrom(DataInput input) throws IOException;
public abstract void readFrom(NBTTagCompound tagCompound);
public abstract void readKey(String data);
public abstract String writeKey();
public abstract boolean hasCached();
@Override
public void addHandler(IMatterEntryHandler<MAT> handler)
{
handlers.add(handler);
Collections.sort(handlers);
}
public void clearHandlers()
{
handlers.clear();
}
public KEY getKey()
{
return key;
}
}
| nacjm/MatterOverdrive | src/main/java/matteroverdrive/data/matter/MatterEntryAbstract.java | Java | gpl-3.0 | 1,512 |
/*
* Copyright (C) 2014 Cameron White
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <catch.hpp>
#include <actions/removetextitem.h>
#include <score/score.h>
TEST_CASE("Actions/RemoveTextItem", "")
{
Score score;
System system;
TextItem text(7, "foo");
system.insertTextItem(text);
score.insertSystem(system);
ScoreLocation location(score, 0, 0, 7);
RemoveTextItem action(location);
action.redo();
REQUIRE(location.getSystem().getTextItems().empty());
action.undo();
REQUIRE(location.getSystem().getTextItems().size() == 1);
REQUIRE(location.getSystem().getTextItems().front() == text);
}
| erawhctim/powertabeditor | test/actions/test_removetextitem.cpp | C++ | gpl-3.0 | 1,274 |
package de.matzefratze123.exampleaddon;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.event.player.PlayerInteractEvent;
import de.matzefratze123.heavyspleef.commands.base.Command;
import de.matzefratze123.heavyspleef.commands.base.CommandContext;
import de.matzefratze123.heavyspleef.commands.base.CommandException;
import de.matzefratze123.heavyspleef.commands.base.CommandValidate;
import de.matzefratze123.heavyspleef.commands.base.PlayerOnly;
import de.matzefratze123.heavyspleef.core.HeavySpleef;
import de.matzefratze123.heavyspleef.core.PlayerPostActionHandler.PostActionCallback;
import de.matzefratze123.heavyspleef.core.event.GameStateChangeEvent;
import de.matzefratze123.heavyspleef.core.event.Subscribe;
import de.matzefratze123.heavyspleef.core.extension.Extension;
import de.matzefratze123.heavyspleef.core.extension.GameExtension;
import de.matzefratze123.heavyspleef.core.game.Game;
import de.matzefratze123.heavyspleef.core.game.GameManager;
import de.matzefratze123.heavyspleef.core.game.GameState;
import de.matzefratze123.heavyspleef.core.i18n.Messages;
import de.matzefratze123.heavyspleef.core.player.SpleefPlayer;
import de.matzefratze123.heavyspleef.lib.dom4j.Element;
/*
* Every extension must be annotated with @Extension, declaring
* an internal name and wether there are command methods declared
* inside the class or not
*/
@SuppressWarnings("deprecation")
@Extension(name = "example-extension", hasCommands = true)
public class ExampleExtension extends GameExtension {
/* For a reference to data values see
* http://minecraft.gamepedia.com/Data_values#Wool.2C_Stained_Clay.2C_Stained_Glass_and_Carpet */
private static final byte RED_CLAY = (byte) 14;
private static final byte LIME_CLAY = (byte) 5;
/*
* Defining a command for adding the extension to a game
*/
@Command(name = "addgameindicator", usage = "/spleef addgameindicator <game>", minArgs = 1,
permission = "heavyspleef.admin.addgameindicator", description = "Adds an indicator block to a game")
@PlayerOnly
public static void onExampleExtensionAddCommand(CommandContext context, HeavySpleef heavySpleef, ExampleAddon addon)
throws CommandException {
//As the sender can only be a player, get a SpleefPlayer instance by calling
//HeavySpleef#getSpleefPlayer(Object)
final SpleefPlayer player = heavySpleef.getSpleefPlayer(context.getSender());
String gameName = context.getString(0);
//Get an instance of the GameManager
GameManager manager = heavySpleef.getGameManager();
//This throws a CommandException if the game does not exist with the specified message
CommandValidate.isTrue(manager.hasGame(gameName), addon.getI18n().getString(Messages.Command.GAME_DOESNT_EXIST));
//Get the game
Game game = manager.getGame(gameName);
//Handle a block click after executing this command
applyPostAction(heavySpleef, player, game, false);
player.sendMessage(ChatColor.GRAY + "Click on a block to add it as an indicator.");
}
/*
* Defining a command removing an indiciator block from a game
*/
@Command(name = "removegameindicator", usage = "/spleef removegameindicator",
permission = "heavyspleef.admin.removegameindicator", description = "Removes an indicator block")
@PlayerOnly
public static void onExampleExtensionRemoveCommand(CommandContext context, HeavySpleef heavySpleef, ExampleAddon addon) {
//As the sender can only be a player, get a SpleefPlayer instance by calling
//HeavySpleef#getSpleefPlayer(Object)
final SpleefPlayer player = heavySpleef.getSpleefPlayer(context.getSender());
//Handle a block click after executing this command
applyPostAction(heavySpleef, player, null, true);
player.sendMessage(ChatColor.GRAY + "Click on an existing indicator block to remove it.");
}
/*
* Method called when a player executed a remove/add command
*/
private static void applyPostAction(final HeavySpleef heavySpleef, SpleefPlayer player, final Game game, final boolean remove) {
//Wait until the player clicked a block (this block will be added)
heavySpleef.getPostActionHandler().addPostAction(player, PlayerInteractEvent.class, new PostActionCallback<PlayerInteractEvent>() {
/*
* This is called one time when the player interacts
*/
public void onPostAction(PlayerInteractEvent event, SpleefPlayer player, Object cookie) {
//Check if the player clicked a block
Block block = event.getClickedBlock();
if (block == null) {
player.sendMessage(ChatColor.RED + "You must click on a block to continue!");
return;
}
if (remove) {
//Remove any extensions found at this location
boolean removed = false;
for (Game game : heavySpleef.getGameManager().getGames()) {
for (ExampleExtension ext : game.getExtensionsByType(ExampleExtension.class)) {
if (!ext.location.equals(block.getLocation())) {
continue;
}
game.removeExtension(ext);
removed = true;
}
}
if (removed) {
player.sendMessage(ChatColor.GRAY + "Game indicator removed!");
} else {
player.sendMessage(ChatColor.RED + "No game indicators found where you clicked");
}
} else {
//Add a new extension to the game
ExampleExtension extension = new ExampleExtension(block.getLocation());
//Actually add the extension to the game
game.addExtension(extension);
//Update and set the block
extension.updateBlock(game.getGameState());
player.sendMessage(ChatColor.GRAY + "Indicator added!");
}
}
});
}
/* In this example we are storing a location whose block is either
* red stained clay for game running, or green stained clay for joinable */
private Location location;
/* Mandatory empty constructor for construction when deserializing/unmarshalling */
@SuppressWarnings("unused")
private ExampleExtension() {}
/* A constructor taking the location attribute as a parameter */
public ExampleExtension(Location where) {
this.location = where;
}
/*
* This methods stores all attributes of your extension in
* a XML element (dom4j).
*/
public void marshal(Element element) {
//Create a new child element for the location
Element locationElement = element.addElement("location");
//Store the world, x, y and z in separate child elements of locationElement
locationElement.addElement("world").setText(location.getWorld().getName());
locationElement.addElement("x").setText(String.valueOf(location.getBlockX()));
locationElement.addElement("y").setText(String.valueOf(location.getBlockY()));
locationElement.addElement("z").setText(String.valueOf(location.getBlockZ()));
}
/*
* This methods restores all attributes of your extension from
* a XML element previously created by #marshal(Element)
*/
public void unmarshal(Element element) {
//Gets our previously stored location element
Element locationElement = element.element("location");
//Restore all values that uniquely identify the location
World world = Bukkit.getWorld(locationElement.elementText("world"));
int x = Integer.parseInt(locationElement.elementText("x"));
int y = Integer.parseInt(locationElement.elementText("y"));
int z = Integer.parseInt(locationElement.elementText("z"));
//Finally create a new location and assign it to our field
this.location = new Location(world, x, y, z);
}
/*
* Listening for game state changes as we want to set the block
* to a specified color indicating the game state
*
* This listens only for events of the game this extension has been
* applied to.
*/
@Subscribe
public void onGameStateChange(GameStateChangeEvent event) {
//Getting the new game state
GameState state = event.getNewState();
//Calling a method to actually change the block
updateBlock(state);
}
public void updateBlock(GameState newState) {
Block block = location.getBlock();
block.setType(Material.STAINED_CLAY);
if (newState == GameState.INGAME || newState == GameState.DISABLED) {
block.setData(RED_CLAY);
} else {
block.setData(LIME_CLAY);
}
}
}
| matzefratze123/heavyspleef-example-addon | src/main/java/de/matzefratze123/exampleaddon/ExampleExtension.java | Java | gpl-3.0 | 8,246 |
/**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.voiceblue.phone.widgets;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;
public class MarqueeTextView extends TextView {
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if(focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void onWindowFocusChanged(boolean focused) {
if(focused)
super.onWindowFocusChanged(focused);
}
@Override
public boolean isFocused() {
return true;
}
}
| ngvoice/android-client | phone/src/com/voiceblue/phone/widgets/MarqueeTextView.java | Java | gpl-3.0 | 1,648 |
package nl.knaw.huygens.timbuctoo.v5.graphql.collectionfilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
public class Facet {
private static final Logger LOG = LoggerFactory.getLogger(Facet.class);
final LinkedHashMap<String, FacetOption> options = new LinkedHashMap<>();
final String caption;
public Facet(String caption) {
this.caption = caption;
}
public void incOption(String key, int value) {
if (options.containsKey(key)) {
LOG.warn("The aggregation '" + caption + "' resulted the same bucket (" + key + ") being mentioned twice. " +
"We did not expect that to be possible");
options.put(key, FacetOption.facetOption(key, options.get(key).getCount() + value));
} else {
options.put(key, FacetOption.facetOption(key, value));
}
}
public String getCaption() {
return caption;
}
public List<FacetOption> getOptions() {
return new ArrayList<>(options.values());
}
}
| HuygensING/timbuctoo | timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/v5/graphql/collectionfilter/Facet.java | Java | gpl-3.0 | 1,047 |
/*
* $Header$
* $Revision$
* $Date$
*
* ====================================================================
*
* Copyright 2000-2004 bob mcwhirter & James Strachan.
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the Jaxen Project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ====================================================================
* This software consists of voluntary contributions made by many
* individuals on behalf of the Jaxen Project and was originally
* created by bob mcwhirter <bob@werken.com> and
* James Strachan <jstrachan@apache.org>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id$
*/
package org.jaxen.expr;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.JaxenException;
/**
* @deprecated this class will become non-public in the future;
* use the interface instead
*/
public class DefaultFunctionCallExpr extends DefaultExpr implements FunctionCallExpr
{
/**
*
*/
private static final long serialVersionUID = -4747789292572193708L;
private String prefix;
private String functionName;
private List parameters;
public DefaultFunctionCallExpr(String prefix, String functionName)
{
this.prefix = prefix;
this.functionName = functionName;
this.parameters = new ArrayList();
}
public void addParameter(Expr parameter)
{
this.parameters.add(parameter);
}
public List getParameters()
{
return this.parameters;
}
public String getPrefix()
{
return this.prefix;
}
public String getFunctionName()
{
return this.functionName;
}
public String getText()
{
StringBuffer buf = new StringBuffer();
String prefix = getPrefix();
if (prefix != null &&
prefix.length() > 0)
{
buf.append(prefix);
buf.append(":");
}
buf.append(getFunctionName());
buf.append("(");
Iterator paramIter = getParameters().iterator();
while (paramIter.hasNext()) {
Expr eachParam = (Expr) paramIter.next();
buf.append(eachParam.getText());
if (paramIter.hasNext())
{
buf.append(", ");
}
}
buf.append(")");
return buf.toString();
}
public Expr simplify()
{
List paramExprs = getParameters();
int paramSize = paramExprs.size();
List newParams = new ArrayList(paramSize);
for (int i = 0; i < paramSize; ++i)
{
Expr eachParam = (Expr) paramExprs.get(i);
newParams.add(eachParam.simplify());
}
this.parameters = newParams;
return this;
}
public String toString()
{
String prefix = getPrefix();
if (prefix == null)
{
return "[(DefaultFunctionCallExpr): " + getFunctionName() + "(" + getParameters() + ") ]";
}
return "[(DefaultFunctionCallExpr): " + getPrefix() + ":" + getFunctionName() + "(" + getParameters() + ") ]";
}
public Object evaluate(Context context) throws JaxenException
{
String namespaceURI =
context.translateNamespacePrefixToUri(getPrefix());
Function func = context.getFunction(namespaceURI,
getPrefix(),
getFunctionName());
List paramValues = evaluateParams(context);
return func.call(context, paramValues);
}
public List evaluateParams(Context context) throws JaxenException
{
List paramExprs = getParameters();
int paramSize = paramExprs.size();
List paramValues = new ArrayList(paramSize);
for (int i = 0; i < paramSize; ++i)
{
Expr eachParam = (Expr) paramExprs.get(i);
Object eachValue = eachParam.evaluate(context);
paramValues.add(eachValue);
}
return paramValues;
}
}
| srnsw/xena | xena/src/org/jaxen/expr/DefaultFunctionCallExpr.java | Java | gpl-3.0 | 5,565 |
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>bundle/jquery/jquery-ui.min.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>bundle/io/src/iolib.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/roles.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/io-storage.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/io-missing-packets.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/io-adapter.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/io-ping-pong.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/virtualclass.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-canvas.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-utility.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/lang-en.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/lang.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/view.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/environment-validation.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-packetcontainer.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-drawobject.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-make-object.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-canvas-utility.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-canvas-main.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-events.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-virtualbox.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-interact.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-rectangle.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-oval.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-triangle.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-line.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-text.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-freedrawing.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-path.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-mouse.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-readyfreehandobj.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-refresh-play.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-readytextobj.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-keyboard.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/webrtc-adapter.js"></script>
<!--<script type="text/javascript" src="<?php //echo $whiteboardpath;?>src/com.js"></script>-->
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/audio-resampler.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/media.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-packet-queue.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/whiteboard-optimization.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/receive-messages-response.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/lzstring.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/audio-codec-g711.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/screenshare-getscreen.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/screenshare-dirtycorner.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/utility.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/screenshare.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/record-play.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/indexeddb-storage.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/footer-control-user.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/xhr.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/popup.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/storage-array-base64-converter.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/progressbar.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/youtube-iframe-api.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/youtube.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>codemirror/lib/codemirror.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>codemirror/addon/edit/continuelist.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>codemirror/mode/xml/xml.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>codemirror/mode/markdown/markdown.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/ot-server.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor-utils.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor-rich-toolbar.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor-text-op.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/ot-text-operation.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/ot-wrapped-operation.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/ot-cursor.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/ot-undo-manager.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/ot-client.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/ot-editor-client.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor-span.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor-annotation-list.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor-attribute-constants.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor-line-formatting.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor-serialize-html.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor-parse-html.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/ot-codemirror-adapter.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/ot-adapter.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/vceditor.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>src/editor.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>chat/chat.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>chat/footer.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>chat/jquery.ui.chatlist.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>chat/jquery.ui.chatbox.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>chat/jquery.ui.chatroom.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>chat/chatboxManager.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>chat/lib.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>chat/lang.en.js"></script>
<script type="text/javascript" src="<?php echo $whiteboardpath;?>index.js"></script>
| educacionbe/campus | mod/virtualclass/bundle/virtualclass/example/js.debug.php | PHP | gpl-3.0 | 9,101 |
package us.talabrek.ultimateskyblock.uuid;
import dk.lockfuglsang.minecraft.file.FileUtil;
import dk.lockfuglsang.minecraft.yml.YmlConfiguration;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.scheduler.BukkitTask;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.UUIDUtil;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* PlayerDB backed by a simple yml-uuid2NameFile.
*/
public class FilePlayerDB implements PlayerDB {
private static final Logger log = Logger.getLogger(FilePlayerDB.class.getName());
private final File uuid2NameFile;
private final YmlConfiguration uuid2NameConfig;
private final uSkyBlock plugin;
private boolean isShuttingDown = false;
private volatile BukkitTask saveTask;
private long saveDelay;
// These caches should NOT be guavaCaches, we need them alive most of the time
private final Map<String, UUID> name2uuidCache = new ConcurrentHashMap<>();
private final Map<UUID, String> uuid2nameCache = new ConcurrentHashMap<>();
public FilePlayerDB(uSkyBlock plugin) {
this.plugin = plugin;
uuid2NameFile = new File(plugin.getDataFolder(), "uuid2name.yml");
uuid2NameConfig = new YmlConfiguration();
if (uuid2NameFile.exists()) {
FileUtil.readConfig(uuid2NameConfig, uuid2NameFile);
}
// Save max every 10 seconds
saveDelay = plugin.getConfig().getInt("playerdb.saveDelay", 10000);
plugin.async(new Runnable() {
@Override
public void run() {
synchronized (uuid2NameConfig) {
Set<String> uuids = uuid2NameConfig.getKeys(false);
for (String uuid : uuids) {
UUID id = UUIDUtil.fromString(uuid);
String name = uuid2NameConfig.getString(uuid + ".name", null);
if (name != null) {
uuid2nameCache.put(id, name);
name2uuidCache.put(name, id);
List<String> akas = uuid2NameConfig.getStringList(uuid + ".aka");
for (String aka : akas) {
if (!name2uuidCache.containsKey(aka)) {
name2uuidCache.put(aka, id);
}
}
}
}
}
}
});
}
@Override
public void shutdown() {
isShuttingDown = true;
if (saveTask != null) {
saveTask.cancel();
}
saveToFile();
}
@Override
public UUID getUUIDFromName(String name) {
return getUUIDFromName(name, true);
}
@Override
public UUID getUUIDFromName(String name, boolean lookup) {
if (name2uuidCache.containsKey(name)) {
return name2uuidCache.get(name);
}
UUID result = null;
if (lookup) {
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(name);
if (offlinePlayer != null) {
updatePlayer(offlinePlayer.getUniqueId(), offlinePlayer.getName(), offlinePlayer.getName());
result = offlinePlayer.getUniqueId();
}
}
name2uuidCache.put(name, result);
return result;
}
@Override
public String getName(UUID uuid) {
if (UNKNOWN_PLAYER_UUID.equals(uuid)) {
return UNKNOWN_PLAYER_NAME;
}
if (uuid2nameCache.containsKey(uuid)) {
return uuid2nameCache.get(uuid);
}
String name = null;
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid);
if (offlinePlayer != null) {
updatePlayer(offlinePlayer.getUniqueId(), offlinePlayer.getName(), offlinePlayer.getName());
name = offlinePlayer.getName();
}
if (name != null) {
uuid2nameCache.put(uuid, name);
}
return name;
}
@Override
public String getDisplayName(UUID uuid) {
String uuidStr = UUIDUtil.asString(uuid);
synchronized (uuid2NameConfig) {
return uuid2NameConfig.getString(uuidStr + ".displayName", null);
}
}
@Override
public String getDisplayName(String playerName) {
UUID uuid = getUUIDFromName(playerName);
if (uuid != null) {
return getDisplayName(uuid);
}
return playerName;
}
@Override
public Set<String> getNames(String search) {
HashSet<String> names = new HashSet<>(uuid2nameCache.values());
String lowerSearch = search != null ? search.toLowerCase() : null;
for (Iterator<String> it = names.iterator(); it.hasNext(); ) {
String name = it.next();
if (name == null || (search != null && !name.toLowerCase().startsWith(lowerSearch))) {
it.remove();
}
}
return names;
}
@Override
public void updatePlayer(final UUID id, final String name, final String displayName) {
addEntry(id, name, displayName);
if (isShuttingDown) {
saveToFile();
} else {
if (saveTask == null) {
// Only have one pending save-task at a time
saveTask = plugin.async(new Runnable() {
@Override
public void run() {
saveToFile();
}
}, saveDelay);
}
}
}
@Override
public Player getPlayer(UUID uuid) {
if (uuid != null) {
Player player = Bukkit.getPlayer(uuid);
if (player != null) {
updatePlayer(player.getUniqueId(), player.getName(), player.getDisplayName());
}
return player;
}
return null;
}
@Override
public Player getPlayer(String name) {
if (name != null) {
UUID uuid = getUUIDFromName(name);
if (uuid != null) {
return getPlayer(uuid);
}
Player player = Bukkit.getPlayer(name);
if (player != null) {
updatePlayer(player.getUniqueId(), player.getName(), player.getDisplayName());
}
return player;
}
return null;
}
private void saveToFile() {
try {
synchronized (uuid2NameConfig) {
uuid2NameConfig.save(uuid2NameFile);
}
} catch (IOException e) {
log.log(Level.INFO, "Error saving playerdb", e);
} finally {
saveTask = null;
}
}
private void addEntry(UUID id, String name, String displayName) {
String uuid = UUIDUtil.asString(id);
UUID oldUUID = name2uuidCache.get(name);
if (name != null) {
uuid2nameCache.put(id, name);
name2uuidCache.put(name, id);
}
synchronized (uuid2NameConfig) {
String oldName = uuid2NameConfig.getString(uuid + ".name", name);
if (uuid2NameConfig.contains(uuid) && oldName != null && !oldName.equals(name)) {
List<String> stringList = uuid2NameConfig.getStringList(uuid + ".aka");
if (!stringList.contains(oldName)) {
stringList.add(oldName);
uuid2NameConfig.set(uuid + ".aka", stringList);
if (!name2uuidCache.containsKey(oldName)) {
name2uuidCache.put(oldName, id);
}
}
}
uuid2NameConfig.set(uuid + ".name", name);
uuid2NameConfig.set(uuid + ".updated", System.currentTimeMillis());
if (displayName != null) {
uuid2NameConfig.set(uuid + ".displayName", displayName);
}
if (oldUUID != null && !oldUUID.equals(id)) {
// Cleanup, remove all references to the new name for the old UUID
uuid2NameConfig.set(UUIDUtil.asString(oldUUID), null);
}
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerJoin(PlayerJoinEvent e) {
updatePlayer(e.getPlayer().getUniqueId(), e.getPlayer().getName(), e.getPlayer().getDisplayName());
}
}
| woolwind/uSkyBlock | uSkyBlock-Core/src/main/java/us/talabrek/ultimateskyblock/uuid/FilePlayerDB.java | Java | gpl-3.0 | 8,829 |
// Copyright (c) 2002 vbAccelerator.com
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED 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
// VBACCELERATOR OR ITS 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.
// Source:
// http://www.vbaccelerator.com/home/NET/Code/Libraries/Shell_Projects/Thumbnail_Extraction/article.asp
// License details:
// http://www.vbaccelerator.com/home/The_Site/Usage_Policy/article.asp
#if WIN32
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace vbAccelerator.Components.Shell
{
#region ThumbnailCreator
/// <summary>
/// Summary description for ThumbnailCreator.
/// </summary>
internal class ThumbnailCreator : IDisposable
{
#region ShellFolder Enumerations
[Flags]
private enum ESTRRET : int
{
STRRET_WSTR = 0x0000, // Use STRRET.pOleStr
STRRET_OFFSET = 0x0001, // Use STRRET.uOffset to Ansi
STRRET_CSTR = 0x0002 // Use STRRET.cStr
}
[Flags]
private enum ESHCONTF : int
{
SHCONTF_FOLDERS = 32,
SHCONTF_NONFOLDERS = 64,
SHCONTF_INCLUDEHIDDEN = 128
}
[Flags]
private enum ESHGDN : int
{
SHGDN_NORMAL = 0,
SHGDN_INFOLDER = 1,
SHGDN_FORADDRESSBAR = 16384,
SHGDN_FORPARSING = 32768
}
[Flags]
private enum ESFGAO : int
{
SFGAO_CANCOPY = 1,
SFGAO_CANMOVE = 2,
SFGAO_CANLINK = 4,
SFGAO_CANRENAME = 16,
SFGAO_CANDELETE = 32,
SFGAO_HASPROPSHEET = 64,
SFGAO_DROPTARGET = 256,
SFGAO_CAPABILITYMASK = 375,
SFGAO_LINK = 65536,
SFGAO_SHARE = 131072,
SFGAO_READONLY = 262144,
SFGAO_GHOSTED = 524288,
SFGAO_DISPLAYATTRMASK = 983040,
SFGAO_FILESYSANCESTOR = 268435456,
SFGAO_FOLDER = 536870912,
SFGAO_FILESYSTEM = 1073741824,
SFGAO_HASSUBFOLDER = -2147483648,
SFGAO_CONTENTSMASK = -2147483648,
SFGAO_VALIDATE = 16777216,
SFGAO_REMOVABLE = 33554432,
SFGAO_COMPRESSED = 67108864
}
#endregion
#region IExtractImage Enumerations
private enum EIEIFLAG
{
IEIFLAG_ASYNC = 0x0001, // ask the extractor if it supports ASYNC extract (free threaded)
IEIFLAG_CACHE = 0x0002, // returned from the extractor if it does NOT cache the thumbnail
IEIFLAG_ASPECT = 0x0004, // passed to the extractor to beg it to render to the aspect ratio of the supplied rect
IEIFLAG_OFFLINE = 0x0008, // if the extractor shouldn't hit the net to get any content neede for the rendering
IEIFLAG_GLEAM = 0x0010, // does the image have a gleam ? this will be returned if it does
IEIFLAG_SCREEN = 0x0020, // render as if for the screen (this is exlusive with IEIFLAG_ASPECT )
IEIFLAG_ORIGSIZE = 0x0040, // render to the approx size passed, but crop if neccessary
IEIFLAG_NOSTAMP = 0x0080, // returned from the extractor if it does NOT want an icon stamp on the thumbnail
IEIFLAG_NOBORDER = 0x0100, // returned from the extractor if it does NOT want an a border around the thumbnail
IEIFLAG_QUALITY = 0x0200 // passed to the Extract method to indicate that a slower, higher quality image is desired, re-compute the thumbnail
}
#endregion
#region ShellFolder Structures
[StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Auto)]
private struct STRRET_CSTR
{
public ESTRRET uType;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=520)]
public byte[] cStr;
}
[StructLayout(LayoutKind.Explicit, CharSet=CharSet.Auto)]
private struct STRRET_ANY
{
[FieldOffset(0)]
public ESTRRET uType;
[FieldOffset(4)]
public IntPtr pOLEString;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
private struct SIZE
{
public int cx;
public int cy;
}
#endregion
#region Com Interop for IUnknown
[ComImport, Guid("00000000-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IUnknown
{
[PreserveSig]
IntPtr QueryInterface(ref Guid riid, out IntPtr pVoid);
[PreserveSig]
IntPtr AddRef();
[PreserveSig]
IntPtr Release();
}
#endregion
#region COM Interop for IMalloc
[ComImportAttribute()]
[GuidAttribute("00000002-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
//helpstring("IMalloc interface")
private interface IMalloc
{
[PreserveSig]
IntPtr Alloc(int cb);
[PreserveSig]
IntPtr Realloc(
IntPtr pv,
int cb);
[PreserveSig]
void Free(IntPtr pv);
[PreserveSig]
int GetSize(IntPtr pv);
[PreserveSig]
int DidAlloc(IntPtr pv);
[PreserveSig]
void HeapMinimize();
};
#endregion
#region COM Interop for IEnumIDList
[ComImportAttribute()]
[GuidAttribute("000214F2-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
//helpstring("IEnumIDList interface")
private interface IEnumIDList
{
[PreserveSig]
int Next(
int celt,
ref IntPtr rgelt,
out int pceltFetched);
void Skip(
int celt);
void Reset();
void Clone(
ref IEnumIDList ppenum);
};
#endregion
#region COM Interop for IShellFolder
[ComImportAttribute()]
[GuidAttribute("000214E6-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
//helpstring("IShellFolder interface")
private interface IShellFolder
{
void ParseDisplayName(
IntPtr hwndOwner,
IntPtr pbcReserved,
[MarshalAs(UnmanagedType.LPWStr)] string lpszDisplayName,
out int pchEaten,
out IntPtr ppidl,
out int pdwAttributes);
void EnumObjects(
IntPtr hwndOwner,
[MarshalAs(UnmanagedType.U4)] ESHCONTF grfFlags,
ref IEnumIDList ppenumIDList
);
void BindToObject(
IntPtr pidl,
IntPtr pbcReserved,
ref Guid riid,
ref IShellFolder ppvOut);
void BindToStorage(
IntPtr pidl,
IntPtr pbcReserved,
ref Guid riid,
IntPtr ppvObj
);
[PreserveSig]
int CompareIDs(
IntPtr lParam,
IntPtr pidl1,
IntPtr pidl2);
void CreateViewObject(
IntPtr hwndOwner,
ref Guid riid,
IntPtr ppvOut);
void GetAttributesOf(
int cidl,
IntPtr apidl,
[MarshalAs(UnmanagedType.U4)] ref ESFGAO rgfInOut);
void GetUIObjectOf(
IntPtr hwndOwner,
int cidl,
ref IntPtr apidl,
ref Guid riid,
out int prgfInOut,
ref IUnknown ppvOut);
void GetDisplayNameOf(
IntPtr pidl,
[MarshalAs(UnmanagedType.U4)] ESHGDN uFlags,
ref STRRET_CSTR lpName);
void SetNameOf(
IntPtr hwndOwner,
IntPtr pidl,
[MarshalAs(UnmanagedType.LPWStr)] string lpszName,
[MarshalAs(UnmanagedType.U4)] ESHCONTF uFlags,
ref IntPtr ppidlOut);
};
#endregion
#region COM Interop for IExtractImage
[ComImportAttribute()]
[GuidAttribute("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
//helpstring("IExtractImage"),
private interface IExtractImage
{
void GetLocation(
[Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPathBuffer,
int cch,
ref int pdwPriority,
ref SIZE prgSize,
int dwRecClrDepth,
ref int pdwFlags);
void Extract(
out IntPtr phBmpThumbnail);
}
#endregion
#region UnManagedMethods for IShellFolder
private class UnManagedMethods
{
[DllImport("shell32", CharSet = CharSet.Auto)]
internal extern static int SHGetMalloc(out IMalloc ppMalloc);
[DllImport("shell32", CharSet = CharSet.Auto)]
internal extern static int SHGetDesktopFolder(out IShellFolder ppshf);
[DllImport("shell32", CharSet = CharSet.Auto)]
internal extern static int SHGetPathFromIDList (
IntPtr pidl,
StringBuilder pszPath);
[DllImport("gdi32", CharSet = CharSet.Auto)]
internal extern static int DeleteObject (
IntPtr hObject
);
}
#endregion
#region Member Variables
private IMalloc alloc = null;
private bool disposed = false;
private System.Drawing.Size desiredSize = new System.Drawing.Size(100,100);
private System.Drawing.Bitmap thumbNail = null;
#endregion
#region Implementation
public System.Drawing.Bitmap ThumbNail
{
get
{
return thumbNail;
}
}
public System.Drawing.Size DesiredSize
{
get
{
return desiredSize;
}
set
{
desiredSize = value;
}
}
private IMalloc Allocator
{
get
{
if (!disposed)
{
if (alloc == null)
{
UnManagedMethods.SHGetMalloc(out alloc);
}
}
else
{
System.Diagnostics.Debug.Assert(false, "Object has been disposed.");
}
return alloc;
}
}
public System.Drawing.Bitmap GetThumbNail(
string file
)
{
if ((!File.Exists(file)) && (!Directory.Exists(file)))
{
throw new FileNotFoundException(
String.Format("The file '{0}' does not exist", file),
file);
}
if (thumbNail != null)
{
thumbNail.Dispose();
thumbNail = null;
}
IShellFolder folder = null;
try
{
folder = getDesktopFolder;
}
catch (Exception ex)
{
throw ex;
}
if (folder != null)
{
IntPtr pidlMain = IntPtr.Zero;
try
{
int cParsed = 0;
int pdwAttrib = 0;
string filePath = Path.GetDirectoryName(file);
pidlMain = IntPtr.Zero;
folder.ParseDisplayName(
IntPtr.Zero,
IntPtr.Zero,
filePath,
out cParsed,
out pidlMain,
out pdwAttrib);
}
catch (Exception ex)
{
Marshal.ReleaseComObject(folder);
throw ex;
}
if (pidlMain != IntPtr.Zero)
{
// IShellFolder:
Guid iidShellFolder = new Guid("000214E6-0000-0000-C000-000000000046");
IShellFolder item = null;
try
{
folder.BindToObject(pidlMain, IntPtr.Zero, ref iidShellFolder, ref item);
}
catch (Exception ex)
{
Marshal.ReleaseComObject(folder);
Allocator.Free(pidlMain);
throw ex;
}
if (item != null)
{
//
IEnumIDList idEnum = null;
try
{
item.EnumObjects(
IntPtr.Zero,
(ESHCONTF.SHCONTF_FOLDERS | ESHCONTF.SHCONTF_NONFOLDERS),
ref idEnum);
}
catch (Exception ex)
{
Marshal.ReleaseComObject(folder);
Allocator.Free(pidlMain);
throw ex;
}
if (idEnum != null)
{
// start reading the enum:
int hRes = 0;
IntPtr pidl = IntPtr.Zero;
int fetched = 0;
bool complete = false;
while (!complete)
{
hRes = idEnum.Next(1, ref pidl, out fetched);
if (hRes != 0)
{
pidl = IntPtr.Zero;
complete = true;
}
else
{
if (getThumbNail(file, pidl, item))
{
complete = true;
}
}
if (pidl != IntPtr.Zero)
{
Allocator.Free(pidl);
}
}
Marshal.ReleaseComObject(idEnum);
}
Marshal.ReleaseComObject(item);
}
Allocator.Free(pidlMain);
}
Marshal.ReleaseComObject(folder);
}
return thumbNail;
}
private bool getThumbNail(
string file,
IntPtr pidl,
IShellFolder item
)
{
IntPtr hBmp = IntPtr.Zero;
IExtractImage extractImage = null;
try
{
string pidlPath = PathFromPidl(pidl);
if (Path.GetFileName(pidlPath).ToUpper().Equals(Path.GetFileName(file).ToUpper()))
{
// we have the item:
IUnknown iunk = null;
int prgf = 0;
Guid iidExtractImage = new Guid("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1");
item.GetUIObjectOf(
IntPtr.Zero,
1,
ref pidl,
ref iidExtractImage,
out prgf,
ref iunk);
extractImage = (IExtractImage)iunk;
if (extractImage != null)
{
Console.WriteLine("Got an IExtractImage object!");
SIZE sz = new SIZE();
sz.cx = desiredSize.Width;
sz.cy = desiredSize.Height;
StringBuilder location = new StringBuilder(260, 260);
int priority = 0;
int requestedColourDepth = 32;
EIEIFLAG flags = EIEIFLAG.IEIFLAG_ASPECT | EIEIFLAG.IEIFLAG_SCREEN;
int uFlags = (int)flags;
extractImage.GetLocation(
location,
location.Capacity,
ref priority,
ref sz,
requestedColourDepth,
ref uFlags);
extractImage.Extract(out hBmp);
if (hBmp != IntPtr.Zero)
{
// create the image object:
thumbNail = System.Drawing.Bitmap.FromHbitmap(hBmp);
// is thumbNail owned by the Bitmap?
}
Marshal.ReleaseComObject(extractImage);
extractImage = null;
}
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
if (hBmp != IntPtr.Zero)
{
UnManagedMethods.DeleteObject(hBmp);
}
if (extractImage != null)
{
Marshal.ReleaseComObject(extractImage);
}
throw ex;
}
}
private string PathFromPidl(
IntPtr pidl
)
{
StringBuilder path = new StringBuilder(260, 260);
int result = UnManagedMethods.SHGetPathFromIDList(pidl, path);
if (result == 0)
{
return string.Empty;
}
else
{
return path.ToString();
}
}
private IShellFolder getDesktopFolder
{
get
{
IShellFolder ppshf;
int r = UnManagedMethods.SHGetDesktopFolder(out ppshf);
return ppshf;
}
}
#endregion
#region Constructor, Destructor, Dispose
public ThumbnailCreator()
{
}
public void Dispose()
{
if (!disposed)
{
if (alloc != null)
{
Marshal.ReleaseComObject(alloc);
}
alloc = null;
if (thumbNail != null)
{
thumbNail.Dispose();
}
disposed = true;
}
}
~ThumbnailCreator()
{
Dispose();
}
#endregion
}
#endregion
}
#endif | kerimlcr/ab2017-dpyo | ornek/basenji/basenji-1.0.2/Platform/src/Win32/ThumbnailCreator.cs | C# | gpl-3.0 | 15,099 |
package com.benjaminsproule.converter.util;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static com.benjaminsproule.converter.util.MimeTypesUtil.APPLICATIONS_BSON;
import static com.benjaminsproule.converter.util.MimeTypesUtil.APPLICATIONS_JSON;
import static com.benjaminsproule.converter.util.MimeTypesUtil.APPLICATIONS_XML;
import static com.benjaminsproule.converter.util.MimeTypesUtil.IMAGES_JPG;
import static com.benjaminsproule.converter.util.MimeTypesUtil.IMAGES_TIFF;
import static com.benjaminsproule.converter.util.MimeTypesUtil.TEXTS_CSV;
import static com.benjaminsproule.converter.util.MimeTypesUtil.VIDEOS_AVI;
import static com.benjaminsproule.converter.util.MimeTypesUtil.VIDEOS_MP4;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
public class MimeTypesUtilITest {
private Path mimeTypes;
private Path mimeTypesBackup;
@Before
public void setup() throws Exception {
if (!MimeTypesUtil.requiresMimeTypesFile()) {
return;
}
String home = System.getProperty("user.home");
mimeTypes = new File(home + "/.mime.types").toPath();
mimeTypesBackup = new File(home + "/.mime.types.backup").toPath();
if (Files.exists(mimeTypes)) {
Files.deleteIfExists(mimeTypesBackup);
Files.move(mimeTypes, mimeTypesBackup);
}
}
@After
public void tearDown() throws Exception {
if (!MimeTypesUtil.requiresMimeTypesFile()) {
return;
}
Files.delete(mimeTypes);
if (Files.exists(mimeTypesBackup)) {
Files.move(mimeTypesBackup, mimeTypes);
Files.deleteIfExists(mimeTypesBackup);
}
}
@Test
public void testMimeTypesFileCreatedIfItDoesNotExist() throws Exception {
if (!MimeTypesUtil.requiresMimeTypesFile()) {
return;
}
MimeTypesUtil.createMimeTypesFile();
assertThat(Files.exists(mimeTypes), is(true));
}
@Test
public void testMimeTypesFileUpdatedIfItDoesExist() throws Exception {
if (!MimeTypesUtil.requiresMimeTypesFile()) {
return;
}
Files.createFile(mimeTypes);
MimeTypesUtil.createMimeTypesFile();
assertThat(Files.readAllLines(mimeTypes), hasItems(APPLICATIONS_BSON, APPLICATIONS_JSON, APPLICATIONS_XML, IMAGES_JPG, IMAGES_TIFF, TEXTS_CSV, VIDEOS_MP4, VIDEOS_AVI));
}
@Test
public void testMimeTypesFileUpdatedIfItDoesExist_DoesNotDeleteOldLines() throws Exception {
if (!MimeTypesUtil.requiresMimeTypesFile()) {
return;
}
populateMimeTypesFile("test");
MimeTypesUtil.createMimeTypesFile();
assertThat(Files.readAllLines(mimeTypes), hasItem("test"));
}
@Test
public void testMimeTypesFileUpdatedIfItDoesExist_IgnoresAlreadyExisting() throws Exception {
if (!MimeTypesUtil.requiresMimeTypesFile()) {
return;
}
populateMimeTypesFile(IMAGES_JPG, IMAGES_TIFF, VIDEOS_MP4, VIDEOS_AVI);
MimeTypesUtil.createMimeTypesFile();
assertThat(Files.readAllLines(mimeTypes), containsInAnyOrder(APPLICATIONS_BSON, APPLICATIONS_JSON, APPLICATIONS_XML, IMAGES_JPG, IMAGES_TIFF, TEXTS_CSV, VIDEOS_MP4, VIDEOS_AVI));
}
private void populateMimeTypesFile(final String... str) throws IOException {
Files.createFile(mimeTypes);
Files.write(mimeTypes, asList(str));
}
} | gigaSproule/file-converter | src/test/java/com/benjaminsproule/converter/util/MimeTypesUtilITest.java | Java | gpl-3.0 | 3,810 |
package com.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 AppCustomerType Master table Entity", complexity = Complexity.LOW)
public interface AppCustomerTypeRepository<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 appcustTypeId) throws Exception, SpartanPersistenceException;
}
| applifireAlgo/bloodbank | bloodbank/src/main/java/com/app/server/repository/AppCustomerTypeRepository.java | Java | gpl-3.0 | 1,182 |
/*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.beam;
import com.bc.ceres.core.CoreException;
import com.bc.ceres.core.runtime.*;
import com.sun.java.help.search.QueryEngine;
import org.esa.beam.framework.help.HelpSys;
import org.esa.beam.framework.ui.application.ApplicationDescriptor;
import org.esa.beam.framework.ui.application.ToolViewDescriptor;
import org.esa.beam.framework.ui.application.ToolViewDescriptorRegistry;
import org.esa.beam.framework.ui.command.Command;
import org.esa.beam.framework.ui.command.CommandGroup;
import org.esa.beam.framework.ui.layer.LayerEditorDescriptor;
import org.esa.beam.framework.ui.layer.LayerSourceDescriptor;
import org.esa.beam.util.TreeNode;
import javax.help.HelpSet;
import javax.help.HelpSet.DefaultHelpSetFactory;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The activator for the BEAM UI module. Registers help set extensions.
*
* @author Marco Peters
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class BeamUiActivator implements Activator, ToolViewDescriptorRegistry {
private static BeamUiActivator instance;
private ModuleContext moduleContext;
private TreeNode<HelpSet> helpSetRegistry;
private List<Command> actionList;
private List<CommandGroup> actionGroupList;
private Map<String, ToolViewDescriptor> toolViewDescriptorRegistry;
private Map<String, LayerSourceDescriptor> layerSourcesRegistry;
private ApplicationDescriptor applicationDescriptor;
private int helpSetNo;
@Override
public void start(ModuleContext moduleContext) throws CoreException {
this.moduleContext = moduleContext;
instance = this;
registerHelpSets(moduleContext);
registerToolViews(moduleContext);
registerActions(moduleContext);
registerActionGroups(moduleContext);
registerApplicationDescriptors(moduleContext);
registerLayerEditors(moduleContext);
registerLayerSources(moduleContext);
}
@Override
public void stop(ModuleContext moduleContext) throws CoreException {
this.helpSetRegistry = null;
this.moduleContext = null;
actionList = null;
toolViewDescriptorRegistry = null;
applicationDescriptor = null;
instance = null;
}
private void registerApplicationDescriptors(ModuleContext moduleContext) {
final List<ApplicationDescriptor> applicationDescriptorList = BeamCoreActivator.loadExecutableExtensions(moduleContext, "applicationDescriptors", "applicationDescriptor", ApplicationDescriptor.class);
final String applicationId = getApplicationId();
for (ApplicationDescriptor applicationDescriptor : applicationDescriptorList) {
if (applicationId.equals(applicationDescriptor.getApplicationId())) {
moduleContext.getLogger().info(String.format("Using application descriptor [%s]", applicationId));
this.applicationDescriptor = applicationDescriptor;
final String[] toolViewIds = applicationDescriptor.getExcludedToolViews();
for (String toolViewId : toolViewIds) {
BeamUiActivator.getInstance().removeToolViewDescriptor(toolViewId);
moduleContext.getLogger().info(String.format("Removed toolview [%s]", toolViewId));
}
final String[] actionIds = applicationDescriptor.getExcludedActions();
for (String actionId : actionIds) {
BeamUiActivator.getInstance().removeAction(actionId);
moduleContext.getLogger().info(String.format("Removed action [%s]", actionId));
}
final String[] actionGroupIds = applicationDescriptor.getExcludedActionGroups();
for (String actionGroupId : actionGroupIds) {
BeamUiActivator.getInstance().removeActionGroup(actionGroupId);
moduleContext.getLogger().info(String.format("Removed action group [%s]", actionGroupId));
}
} else {
moduleContext.getLogger().warning(String.format("Ignoring application descriptor [%s]", applicationId));
}
}
}
public static BeamUiActivator getInstance() {
return instance;
}
public ModuleContext getModuleContext() {
return moduleContext;
}
public String getApplicationId() {
return moduleContext.getRuntimeConfig().getApplicationId();
}
public ApplicationDescriptor getApplicationDescriptor() {
return applicationDescriptor;
}
public List<Command> getCommands() {
return Collections.unmodifiableList(actionList);
}
public List<CommandGroup> getCommandGroups() {
return Collections.unmodifiableList(actionGroupList);
}
@Override
public ToolViewDescriptor[] getToolViewDescriptors() {
return toolViewDescriptorRegistry.values().toArray(new ToolViewDescriptor[toolViewDescriptorRegistry.values().size()]);
}
@Override
public ToolViewDescriptor getToolViewDescriptor(String viewDescriptorId) {
return toolViewDescriptorRegistry.get(viewDescriptorId);
}
public LayerSourceDescriptor[] getLayerSources() {
return layerSourcesRegistry.values().toArray(
new LayerSourceDescriptor[layerSourcesRegistry.values().size()]);
}
public void removeToolViewDescriptor(String viewDescriptorId) {
toolViewDescriptorRegistry.remove(viewDescriptorId);
}
public void removeAction(String actionId) {
for (int i = 0; i < actionList.size(); i++) {
Command command = actionList.get(i);
if (actionId.equals(command.getCommandID())) {
actionList.remove(i);
return;
}
}
}
public void removeActionGroup(String actionGroupId) {
for (int i = 0; i < actionGroupList.size(); i++) {
Command command = actionGroupList.get(i);
if (actionGroupId.equals(command.getCommandID())) {
actionGroupList.remove(i);
return;
}
}
}
private void registerToolViews(ModuleContext moduleContext) {
List<ToolViewDescriptor> toolViewDescriptorList = BeamCoreActivator.loadExecutableExtensions(moduleContext,
"toolViews",
"toolView",
ToolViewDescriptor.class);
toolViewDescriptorRegistry = new HashMap<>(2 * toolViewDescriptorList.size());
for (ToolViewDescriptor toolViewDescriptor : toolViewDescriptorList) {
final String toolViewId = toolViewDescriptor.getId();
final ToolViewDescriptor existingViewDescriptor = toolViewDescriptorRegistry.get(toolViewId);
if (existingViewDescriptor != null) {
moduleContext.getLogger().info(String.format("Tool view [%s] has been redeclared!\n", toolViewId));
}
toolViewDescriptorRegistry.put(toolViewId, toolViewDescriptor);
}
}
private void registerActions(ModuleContext moduleContext) {
actionList = BeamCoreActivator.loadExecutableExtensions(moduleContext,
"actions",
"action",
Command.class);
HashMap<String, Command> actionMap = new HashMap<>(2 * actionList.size() + 1);
for (Command action : new ArrayList<>(actionList)) {
final String actionId = action.getCommandID();
final Command existingAction = actionMap.get(actionId);
if (existingAction != null) {
moduleContext.getLogger().warning(String.format("Action [%s] has been redeclared!\n", actionId));
actionMap.remove(actionId);
actionList.remove(existingAction);
}
actionMap.put(actionId, action);
}
}
private void registerActionGroups(ModuleContext moduleContext) {
actionGroupList = BeamCoreActivator.loadExecutableExtensions(moduleContext,
"actionGroups",
"actionGroup",
CommandGroup.class);
HashMap<String, CommandGroup> actionGroupMap = new HashMap<>(2 * actionGroupList.size() + 1);
for (CommandGroup actionGroup : new ArrayList<>(actionGroupList)) {
final String actionGroupId = actionGroup.getCommandID();
final CommandGroup existingActionGroup = actionGroupMap.get(actionGroupId);
if (existingActionGroup != null) {
moduleContext.getLogger().warning(String.format("Action group [%s] has been redeclared!\n", actionGroupId));
actionGroupMap.remove(actionGroupId);
actionGroupList.remove(existingActionGroup);
}
actionGroupMap.put(actionGroupId, actionGroup);
}
}
private void registerLayerEditors(ModuleContext moduleContext) {
BeamCoreActivator.loadExecutableExtensions(moduleContext,
"layerEditors",
"layerEditor",
LayerEditorDescriptor.class);
}
private void registerLayerSources(ModuleContext moduleContext) {
List<LayerSourceDescriptor> layerSourceListDescriptor =
BeamCoreActivator.loadExecutableExtensions(moduleContext,
"layerSources",
"layerSource",
LayerSourceDescriptor.class);
layerSourcesRegistry = new HashMap<>(2 * layerSourceListDescriptor.size());
for (LayerSourceDescriptor layerSourceDescriptor : layerSourceListDescriptor) {
final String id = layerSourceDescriptor.getId();
final LayerSourceDescriptor existingLayerSourceDescriptor = layerSourcesRegistry.get(id);
if (existingLayerSourceDescriptor
!= null) {
moduleContext.getLogger().info(String.format("Layer source [%s] has been redeclared!\n", id));
}
layerSourcesRegistry.put(id, layerSourceDescriptor);
}
}
private void registerHelpSets(ModuleContext moduleContext) {
this.helpSetRegistry = new TreeNode<>("");
ExtensionPoint hsExtensionPoint = moduleContext.getModule().getExtensionPoint("helpSets");
Extension[] hsExtensions = hsExtensionPoint.getExtensions();
for (Extension extension : hsExtensions) {
ConfigurationElement confElem = extension.getConfigurationElement();
ConfigurationElement[] helpSetElements = confElem.getChildren("helpSet");
for (ConfigurationElement helpSetElement : helpSetElements) {
final Module declaringModule = extension.getDeclaringModule();
if (declaringModule.getState().is(ModuleState.RESOLVED)) {
registerHelpSet(helpSetElement, declaringModule);
}
}
}
addNodeToHelpSys(helpSetRegistry);
}
private void addNodeToHelpSys(TreeNode<HelpSet> helpSetNode) {
if (helpSetNode.getContent() != null) {
HelpSys.add(helpSetNode.getContent());
}
TreeNode<HelpSet>[] children = helpSetNode.getChildren();
for (TreeNode<HelpSet> child : children) {
addNodeToHelpSys(child);
}
}
private void registerHelpSet(ConfigurationElement helpSetElement, Module declaringModule) {
String helpSetPath = null;
ConfigurationElement pathElem = helpSetElement.getChild("path");
if (pathElem != null) {
helpSetPath = pathElem.getValue();
}
// todo - remove
if (helpSetPath == null) {
helpSetPath = helpSetElement.getAttribute("path");
}
if (helpSetPath == null) {
String message = String.format("Missing resource [path] element in a help set declared in module [%s].",
declaringModule.getName());
moduleContext.getLogger().severe(message);
return;
}
URL helpSetUrl = declaringModule.getClassLoader().getResource(helpSetPath);
if (helpSetUrl == null) {
String message = String.format("Help set resource path [%s] of module [%s] not found.",
helpSetPath, declaringModule.getName());
moduleContext.getLogger().severe(message);
return;
}
DefaultHelpSetFactory factory = new VerifyingHelpSetFactory(helpSetPath, declaringModule.getName(), moduleContext.getLogger());
HelpSet helpSet = HelpSet.parse(helpSetUrl, declaringModule.getClassLoader(), factory);
if (helpSet == null) {
String message = String.format("Failed to add help set [%s] of module [%s]: %s.",
helpSetPath, declaringModule.getName(),
"");
moduleContext.getLogger().log(Level.SEVERE, message, "");
return;
}
String helpSetId;
ConfigurationElement idElem = helpSetElement.getChild("id");
if (idElem != null) {
helpSetId = idElem.getValue();
} else {
helpSetId = "helpSet$" + helpSetNo;
helpSetNo++;
String message = String.format("Missing [id] element in help set [%s] of module [%s].",
helpSetPath,
declaringModule.getSymbolicName());
moduleContext.getLogger().warning(message);
}
String helpSetParent;
ConfigurationElement parentElem = helpSetElement.getChild("parent");
if (parentElem != null) {
helpSetParent = parentElem.getValue();
} else {
helpSetParent = ""; // = root
}
TreeNode<HelpSet> parentNode = helpSetRegistry.createChild(helpSetParent);
TreeNode<HelpSet> childNode = parentNode.getChild(helpSetId);
if (childNode == null) {
childNode = new TreeNode<>(helpSetId, helpSet);
parentNode.addChild(childNode);
} else if (childNode.getContent() == null) {
childNode.setContent(helpSet);
} else {
String message = String.format("Help set ignored: Duplicate identifier [%s] in help set [%s] of module [%s] ignored.",
helpSetId,
helpSetPath,
declaringModule.getName());
moduleContext.getLogger().severe(message);
}
}
private static class VerifyingHelpSetFactory extends DefaultHelpSetFactory {
private final String helpSetPath;
private final String moduleName;
private final Logger logger;
public VerifyingHelpSetFactory(String helpSetPath, String moduleName, Logger logger) {
super();
this.helpSetPath = helpSetPath;
this.moduleName = moduleName;
this.logger = logger;
}
@Override
public void processView(HelpSet hs,
String name,
String label,
String type,
Hashtable viewAttributes,
String data,
Hashtable dataAttributes,
Locale locale) {
if (name.equals("Search")) {
// check if a search engine can be created, this means the search index is available
try {
// just for checking if it can be created
QueryEngine qe = new QueryEngine(data, hs.getHelpSetURL());
} catch (Exception exception) {
String message = String.format("Help set [%s] of module [%s] has no or bad search index. Search view removed.",
helpSetPath, moduleName);
logger.log(Level.SEVERE, message, "");
return;
}
}
super.processView(hs, name, label, type, viewAttributes, data, dataAttributes, locale);
}
}
}
| seadas/beam | beam-ui/src/main/java/org/esa/beam/BeamUiActivator.java | Java | gpl-3.0 | 17,807 |
package my.game.tile;
import my.game.render.Sprite;
public class SpawnTiles {
public static Tile floorboards = new BackgroundTile(Sprite.floorboards, "floorboards");
public static Tile walls = new ForegroundTile(Sprite.walls, "walls");
public static Tile bricks = new ForegroundTile(Sprite.bricks, "bricks");
public static Tile hedge = new ForegroundTile(Sprite.hedge, "hedge").setBreakable(true);
}
| xDIAMONDSx/ELEOS | src/my/game/tile/SpawnTiles.java | Java | gpl-3.0 | 420 |
<?php
/**
Copyright 2011-2017 Nick Korbel
This file is part of Booked Scheduler.
Booked Scheduler 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.
Booked Scheduler 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 Booked Scheduler. If not, see <http://www.gnu.org/licenses/>.
*/
define('ROOT_DIR', '../');
require_once(ROOT_DIR . 'Pages/PersonalCalendarPage.php');
$page = new SecureActionPageDecorator(new PersonalCalendarPage());
if ($page->TakingAction())
{
$page->ProcessAction();
}
else
{
$page->PageLoad();
}
| rafaelperazzo/ufca-web | booked/Web/my-calendar.php | PHP | gpl-3.0 | 959 |
<?php
/**
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\GiftMessage\Test\Unit\Model;
// @codingStandardsIgnoreFile
use Magento\GiftMessage\Model\ItemRepository;
class ItemRepositoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ItemRepository
*/
protected $itemRepository;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $quoteRepositoryMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $messageFactoryMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $quoteMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $messageMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $quoteItemMock;
/**
* @var string
*/
protected $cartId = 13;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $storeManagerMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $giftMessageManagerMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $helperMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $storeMock;
protected function setUp()
{
$this->quoteRepositoryMock = $this->getMock('\Magento\Quote\Api\CartRepositoryInterface');
$this->messageFactoryMock = $this->getMock(
'Magento\GiftMessage\Model\MessageFactory',
[
'create',
'__wakeup'
],
[],
'',
false
);
$this->messageMock = $this->getMock('Magento\GiftMessage\Model\Message', [], [], '', false);
$this->quoteItemMock = $this->getMock(
'\Magento\Quote\Model\Quote\Item',
[
'getGiftMessageId',
'__wakeup'
],
[],
'',
false
);
$this->quoteMock = $this->getMock(
'\Magento\Quote\Model\Quote',
[
'getGiftMessageId',
'getItemById',
'__wakeup',
],
[],
'',
false
);
$this->storeManagerMock = $this->getMock('Magento\Store\Model\StoreManagerInterface');
$this->giftMessageManagerMock =
$this->getMock('Magento\GiftMessage\Model\GiftMessageManager', [], [], '', false);
$this->helperMock = $this->getMock('Magento\GiftMessage\Helper\Message', [], [], '', false);
$this->storeMock = $this->getMock('Magento\Store\Model\Store', [], [], '', false);
$this->itemRepository = new \Magento\GiftMessage\Model\ItemRepository(
$this->quoteRepositoryMock,
$this->storeManagerMock,
$this->giftMessageManagerMock,
$this->helperMock,
$this->messageFactoryMock
);
$this->quoteRepositoryMock->expects($this->once())
->method('getActive')
->with($this->cartId)
->will($this->returnValue($this->quoteMock));
}
/**
* @expectedException \Magento\Framework\Exception\NoSuchEntityException
* @expectedExceptionMessage There is no item with provided id in the cart
*/
public function testGetWithNoSuchEntityException()
{
$itemId = 2;
$this->quoteMock->expects($this->once())->method('getItemById')->with($itemId)->will($this->returnValue(null));
$this->itemRepository->get($this->cartId, $itemId);
}
public function testGetWithoutMessageId()
{
$messageId = 0;
$itemId = 2;
$this->quoteMock->expects($this->once())
->method('getItemById')
->with($itemId)
->will($this->returnValue($this->quoteItemMock));
$this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue($messageId));
$this->assertNull($this->itemRepository->get($this->cartId, $itemId));
}
public function testGet()
{
$messageId = 123;
$itemId = 2;
$this->quoteMock->expects($this->once())
->method('getItemById')
->with($itemId)
->will($this->returnValue($this->quoteItemMock));
$this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue($messageId));
$this->messageFactoryMock->expects($this->once())
->method('create')
->will($this->returnValue($this->messageMock));
$this->messageMock->expects($this->once())
->method('load')
->with($messageId)
->will($this->returnValue($this->messageMock));
$this->assertEquals($this->messageMock, $this->itemRepository->get($this->cartId, $itemId));
}
/**
* @expectedException \Magento\Framework\Exception\NoSuchEntityException
* @expectedExceptionMessage There is no product with provided itemId: 1 in the cart
*/
public function testSaveWithNoSuchEntityException()
{
$itemId = 1;
$this->quoteMock->expects($this->once())->method('getItemById')->with($itemId)->will($this->returnValue(null));
$this->itemRepository->save($this->cartId, $this->messageMock, $itemId);
}
/**
* @expectedException \Magento\Framework\Exception\State\InvalidTransitionException
* @expectedExceptionMessage Gift Messages are not applicable for virtual products
*/
public function testSaveWithInvalidTransitionException()
{
$itemId = 1;
$quoteItem = $this->getMock('\Magento\Sales\Model\Quote\Item', ['getIsVirtual', '__wakeup'], [], '', false);
$this->quoteMock->expects($this->once())
->method('getItemById')
->with($itemId)
->will($this->returnValue($quoteItem));
$quoteItem->expects($this->once())->method('getIsVirtual')->will($this->returnValue(1));
$this->itemRepository->save($this->cartId, $this->messageMock, $itemId);
}
public function testSave()
{
$itemId = 1;
$quoteItem = $this->getMock('\Magento\Sales\Model\Quote\Item', ['getIsVirtual', '__wakeup'], [], '', false);
$this->quoteMock->expects($this->once())
->method('getItemById')
->with($itemId)
->will($this->returnValue($quoteItem));
$quoteItem->expects($this->once())->method('getIsVirtual')->will($this->returnValue(0));
$this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($this->storeMock));
$this->helperMock->expects($this->once())
->method('isMessagesAllowed')
->with('items', $this->quoteMock, $this->storeMock)
->will($this->returnValue(true));
$this->giftMessageManagerMock->expects($this->once())
->method('setMessage')
->with($this->quoteMock, 'quote_item', $this->messageMock, $itemId)
->will($this->returnValue($this->giftMessageManagerMock));
$this->messageMock->expects($this->once())->method('getMessage')->willReturn('message');
$this->assertTrue($this->itemRepository->save($this->cartId, $this->messageMock, $itemId));
}
}
| rajmahesh/magento2-master | vendor/magento/module-gift-message/Test/Unit/Model/ItemRepositoryTest.php | PHP | gpl-3.0 | 7,415 |
package org.freebus.fts.project;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.freebus.fts.common.address.PhysicalAddress;
import org.freebus.fts.persistence.vdx.VdxEntity;
/**
* Details about the programming of a physical KNX device.
*/
@Entity
@Table(name = "device_programming")
@VdxEntity(name = "device_programming_non_vd")
public class DeviceProgramming
{
@Id
@JoinColumn(name = "device_id", nullable = false)
@OneToOne(optional = false)
private Device device;
@Column(name = "physical_address")
private int physicalAddress;
@Column(name = "last_modified")
@Temporal(TemporalType.TIMESTAMP)
private Date lastModified;
@Column(name = "last_upload")
@Temporal(TemporalType.TIMESTAMP)
private Date lastUpload;
@Column(name = "communication_valid", nullable = false)
private boolean communicationValid;
@Column(name = "parameters_valid", nullable = false)
private boolean parametersValid;
@Column(name = "program_valid", nullable = false)
private boolean programValid;
/**
* Create a device programming details object.
*/
public DeviceProgramming()
{
}
/**
* Create a program description object.
*
* @param device - the device to which the programming object belongs.
*/
public DeviceProgramming(Device device)
{
this.device = device;
}
/**
* @return The device to which the object belongs.
*/
public Device getDevice()
{
return device;
}
/**
* Set the device to which the object belongs.
*
* @param device - the device to set.
*/
public void setDevice(Device device)
{
this.device = device;
}
/**
* Get the timestamp when the {@link #getDevice() device} was last modified.
*
* @return the last modified timestamp
*/
public Date getLastModified()
{
return lastModified;
}
/**
* Set the timestamp when the {@link #getDevice() device} was last modified.
*
* @param lastModified - the last modified timestamp to set
*/
public void setLastModified(Date lastModified)
{
this.lastModified = lastModified;
}
/**
* Set the timestamp when the {@link #getDevice() device} was last modified
* to now.
*/
public void setLastModifiedNow()
{
this.lastModified = new Date();
}
/**
* Get the timestamp when the device was last programmed. This does not imply
* that everything in the device is up to date.
*
* @return the last upload timestamp.
*/
public Date getLastUpload()
{
return lastUpload;
}
/**
* Set the timestamp when the {@link #getDevice() device} was last programmed
* to now.
*/
public void setLastUploadNow()
{
this.lastUpload = new Date();
}
/**
* Set the timestamp when the device was last programmed.
*
* @param lastUpload - the last upload timestamp.
*/
public void setLastUpload(Date lastUpload)
{
this.lastUpload = lastUpload;
}
/**
* @return The physical address that was programmed last.
*/
public PhysicalAddress getPhysicalAddress()
{
return PhysicalAddress.valueOf(physicalAddress);
}
/**
* Set the physical address that was programmed last.
*
* @param physicalAddress - the physical address to set.
*/
public void setPhysicalAddress(PhysicalAddress physicalAddress)
{
this.physicalAddress = physicalAddress.getAddr();
}
/**
* Test if everything in the device is up to date.
*/
public boolean isValid()
{
return communicationValid && parametersValid && programValid && isPhysicalAddressValid();
}
/**
* Test if the communication objects in the device are up to date.
*
* @return the communication valid flag.
*/
public boolean isCommunicationValid()
{
return communicationValid;
}
/**
* Set if the communication objects in the device are up to date.
*
* @param communicationValid - the communication valid flag to set
*/
public void setCommunicationValid(boolean communicationValid)
{
this.communicationValid = communicationValid;
}
/**
* Test if the parameters in the device are up to date.
*
* @return the parameters valid flag.
*/
public boolean isParametersValid()
{
return parametersValid;
}
/**
* Set if the parameters in the device are up to date.
*
* @param parametersValid - the parameters valid flag to set
*/
public void setParametersValid(boolean parametersValid)
{
this.parametersValid = parametersValid;
}
/**
* Test if the physical address of the device is up to date.
*
* @return True if the physical address is valid.
*/
public boolean isPhysicalAddressValid()
{
return device == null || device.getPhysicalAddress().equals(getPhysicalAddress());
}
/**
* Test if the application program of the device is up to date.
*
* @return the program valid flag.
*/
public boolean isProgramValid()
{
return programValid;
}
/**
* Set if the application program of the device is up to date.
*
* @param programValid - the program valid flag to set.
*/
public void setProgramValid(boolean programValid)
{
this.programValid = programValid;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
return device == null ? 0 : device.getId();
}
}
| Paolo-Maffei/freebus-fts | freebus-fts-persistence/src/main/java/org/freebus/fts/project/DeviceProgramming.java | Java | gpl-3.0 | 5,774 |
<?php
use LibreNMS\Authentication\LegacyAuth;
$param = array();
$select = "SELECT `F`.`port_id` AS `port_id`, `F`.`device_id`, `ifInErrors`, `ifOutErrors`, `ifOperStatus`,";
$select .= " `ifAdminStatus`, `ifAlias`, `ifDescr`, `mac_address`, `V`.`vlan_vlan` AS `vlan`,";
$select .= " `hostname`, `hostname` AS `device` , group_concat(`M`.`ipv4_address` SEPARATOR ', ') AS `ipv4_address`,";
$select .= " `P`.`ifDescr` AS `interface`";
$sql = " FROM `ports_fdb` AS `F`";
$sql .= " LEFT JOIN `devices` AS `D` USING(`device_id`)";
$sql .= " LEFT JOIN `ports` AS `P` USING(`port_id`, `device_id`)";
$sql .= " LEFT JOIN `vlans` AS `V` USING(`vlan_id`, `device_id`)";
// Add counter so we can ORDER BY the port_id with least amount of macs attached
$sql .= " LEFT JOIN ( SELECT `port_id`, COUNT(*) `portCount` FROM `ports_fdb` GROUP BY `port_id` ) AS `C` ON `C`.`port_id` = `F`.`port_id`";
$where = " WHERE 1";
if (!LegacyAuth::user()->hasGlobalRead()) {
$sql .= ' LEFT JOIN `devices_perms` AS `DP` USING (`device_id`)';
$where .= ' AND `DP`.`user_id`=?';
$param[] = LegacyAuth::id();
}
if (is_numeric($vars['device_id'])) {
$where .= ' AND `F`.`device_id`=?';
$param[] = $vars['device_id'];
}
if (is_numeric($vars['port_id'])) {
$where .= ' AND `F`.`port_id`=?';
$param[] = $vars['port_id'];
}
if (isset($vars['searchPhrase']) && !empty($vars['searchPhrase'])) {
$search = mres(trim($vars['searchPhrase']));
$mac_search = '%'.str_replace(array(':', ' ', '-', '.', '0x'), '', $search).'%';
if (isset($vars['searchby']) && $vars['searchby'] == 'vlan') {
$where .= ' AND `V`.`vlan_vlan` = ?';
$param[] = (int)$search;
} elseif (isset($vars['searchby']) && $vars['searchby'] == 'ip') {
$ip = $vars['searchPhrase'];
$ip_search = '%'.mres(trim($ip)).'%';
$sql .= " LEFT JOIN `ipv4_mac` AS `M` USING (`mac_address`)";
$where .= ' AND `M`.`ipv4_address` LIKE ?';
$param[] = $ip_search;
} elseif (isset($vars['searchby']) && $vars['searchby'] == 'dnsname') {
$ip = gethostbyname($vars['searchPhrase']);
$ip_search = '%'.mres(trim($ip)).'%';
$sql .= " LEFT JOIN `ipv4_mac` AS `M` USING (`mac_address`)";
$where .= ' AND `M`.`ipv4_address` LIKE ?';
$param[] = $ip_search;
} elseif (isset($vars['searchby']) && $vars['searchby'] == 'description') {
$desc_search = '%' . $search . '%';
$where .= ' AND `P`.`ifAlias` LIKE ?';
$param[] = $desc_search;
} elseif (isset($vars['searchby']) && $vars['searchby'] == 'mac') {
$where .= ' AND `F`.`mac_address` LIKE ?';
$param[] = $mac_search;
} else {
$sql .= " LEFT JOIN `ipv4_mac` AS `M` USING (`mac_address`)";
$where .= ' AND (`V`.`vlan_vlan` = ? OR `F`.`mac_address` LIKE ? OR `P`.`ifAlias` LIKE ? OR `M`.`ipv4_address` LIKE ?)';
$param[] = (int)$search;
$param[] = $mac_search;
$param[] = '%' . $search . '%';
$param[] = '%' . gethostbyname(trim($vars['searchPhrase'])) . '%';
}
}
$total = (int)dbFetchCell("SELECT COUNT(*) $sql $where", $param);
// Don't use ipv4_mac in count it will inflate the rows unless we aggregate it
// Except for ip search.
if (empty($vars['searchPhrase']) || isset($vars['searchby']) && $vars['searchby'] != 'ip' && $vars['searchby'] != 'dnsname') {
$sql .= " LEFT JOIN `ipv4_mac` AS `M` USING (`mac_address`)";
}
$sql .= $where;
$sql .= " GROUP BY `device_id`, `port_id`, `mac_address`, `vlan`";
// Get most likely endpoint port_id, used to add a visual marker for this element
// in the list
if (isset($vars['searchby']) && !empty($vars['searchPhrase']) && $vars['searchby'] != 'vlan') {
$countsql .= " ORDER BY `C`.`portCount` ASC LIMIT 1";
foreach (dbFetchRows($select . $sql . $countsql, $param) as $entry) {
$endpoint_portid = $entry['port_id'];
}
}
if (!isset($sort) || empty($sort)) {
$sort = '`C`.`portCount` ASC';
}
$sql .= " ORDER BY $sort";
if (isset($current)) {
$limit_low = (($current * $rowCount) - ($rowCount));
$limit_high = $rowCount;
}
if ($rowCount != -1) {
$sql .= " LIMIT $limit_low,$limit_high";
}
$response = array();
foreach (dbFetchRows($select . $sql, $param) as $entry) {
$entry = cleanPort($entry);
if (!$ignore) {
if ($entry['ifInErrors'] > 0 || $entry['ifOutErrors'] > 0) {
$error_img = generate_port_link(
$entry,
"<i class='fa fa-flag fa-lg' style='color:red' aria-hidden='true'></i>",
'port_errors'
);
} else {
$error_img = '';
}
if ($entry['port_id'] == $endpoint_portid) {
$endpoint_img = "<i class='fa fa-star fa-lg' style='color:green' aria-hidden='true' title='This indicates the most likely endpoint switchport'></i>";
$dnsname = gethostbyaddr(reset(explode(',', $entry['ipv4_address']))) ?: 'N/A';
} else {
$endpoint_img = '';
$dnsname = "N/A";
}
$response[] = array(
'device' => generate_device_link(device_by_id_cache($entry['device_id'])),
'mac_address' => formatMac($entry['mac_address']),
'ipv4_address' => $entry['ipv4_address'],
'interface' => generate_port_link($entry, makeshortif(fixifname($entry['label']))).' '.$error_img.' '.$endpoint_img,
'vlan' => $entry['vlan'],
'description' => $entry['ifAlias'],
'dnsname' => $dnsname,
);
}//end if
unset($ignore);
}//end foreach
$output = array(
'current' => $current,
'rowCount' => $rowCount,
'rows' => $response,
'total' => $total,
);
echo _json_encode($output);
| xbeaudouin/librenms | html/includes/table/fdb-search.inc.php | PHP | gpl-3.0 | 5,786 |
package net.comcraft.src;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
public final class RMS {
private RecordStore recordStore;
private RMS(String recordStoreName, boolean create) {
try {
recordStore = RecordStore.openRecordStore(recordStoreName, create);
} catch (RecordStoreException ex) {
//#debug debug
ex.printStackTrace();
throw new ComcraftException("Can't open record store! Record store name: " + recordStoreName + " create if nesescary: " + create, ex);
}
}
public static RMS openRecordStore(String recordStoreName, boolean create) {
return new RMS(recordStoreName, create);
}
public DataInputStream getRecord(int id) {
try {
return new DataInputStream(new ByteArrayInputStream(recordStore.getRecord(id)));
} catch (RecordStoreException ex) {
//#debug debug
ex.printStackTrace();
throw new ComcraftException("Exception while getting record in record store!", ex);
}
}
public void addRecord() {
try {
recordStore.addRecord(new byte[1], 0, 1);
} catch (RecordStoreException ex) {
//#debug debug
ex.printStackTrace();
throw new ComcraftException("Exception while adding record in record store!", ex);
}
}
public void setRecord(int id, ByteArrayOutputStream byteArrayOutputStream) {
byte[] byteArray = byteArrayOutputStream.toByteArray();
try {
recordStore.setRecord(id, byteArray, 0, byteArray.length);
} catch (RecordStoreException ex) {
//#debug debug
ex.printStackTrace();
throw new ComcraftException("Exception while setting record in record store! Record id: " + id, ex);
}
}
public boolean hasAnyRecord() {
try {
return recordStore.getNumRecords() != 0;
} catch (RecordStoreNotOpenException ex) {
//#debug debug
ex.printStackTrace();
throw new ComcraftException("Exception while checking if record store has any records! Record strore isn't opened.", ex);
}
}
public void closeRecordStore() {
try {
recordStore.closeRecordStore();
} catch (RecordStoreException ex) {
//#debug debug
ex.printStackTrace();
throw new ComcraftException("Exception while closing record store !", ex);
}
}
}
| simon816/ComcraftModLoader | src/net/comcraft/src/RMS.java | Java | gpl-3.0 | 2,746 |
/*
personal-genome-client Java client for the 23andMe Personal Genome API.
Copyright (c) 2012-2013 held jointly by the individual authors.
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
> http://www.fsf.org/licensing/licenses/lgpl.html
> http://www.opensource.org/licenses/lgpl-license.php
*/
package com.github.heuermh.personalgenome.client;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.concurrent.Immutable;
/**
* Drug response.
*/
@Immutable
public final class DrugResponse {
private final String profileId;
private final String reportId;
private final String description;
private final String status;
public DrugResponse(final String profileId, final String reportId, final String description, final String status) {
checkNotNull(profileId);
checkNotNull(reportId);
checkNotNull(description);
checkNotNull(status);
this.profileId = profileId;
this.reportId = reportId;
this.description = description;
this.status = status;
}
public String getProfileId() {
return profileId;
}
public String getReportId() {
return reportId;
}
public String getDescription() {
return description;
}
public String getStatus() {
return status;
}
} | heuermh/personal-genome-client | client/src/main/java/com/github/heuermh/personalgenome/client/DrugResponse.java | Java | gpl-3.0 | 2,053 |
__author__ = "jing"
from scrapy.cmdline import execute
execute()
| BitTigerInst/Kumamon | zhihu/manage.py | Python | gpl-3.0 | 68 |
package matteroverdrive.util;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EntityDamageSource;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
/**
* Created by Simeon on 4/16/2015.
*/
public class EntityDamageSourcePhaser extends EntityDamageSource
{
protected final Entity damageSourceEntity;
public EntityDamageSourcePhaser(Entity p_i1567_2_)
{
super("phaser", p_i1567_2_);
this.damageSourceEntity = p_i1567_2_;
this.setProjectile();
}
public Entity getEntity()
{
return damageSourceEntity;
}
public ITextComponent func_151519_b(EntityLivingBase entity)
{
String normalMsg = "death.attack." + damageType;
String itemMsg = normalMsg + ".item";
if (damageSourceEntity instanceof EntityLivingBase)
{
ItemStack itemStack = ((EntityLivingBase)damageSourceEntity).getActiveItemStack();
if (itemStack != null &&
itemStack.hasDisplayName() &&
MOStringHelper.hasTranslation(itemMsg))
{
return new TextComponentTranslation(itemMsg, entity.getDisplayName().getFormattedText(), damageSourceEntity.getDisplayName().getFormattedText(), itemStack.getTextComponent());
}
}
return new TextComponentTranslation(normalMsg, entity.getDisplayName(), damageSourceEntity.getDisplayName());
}
/**
* Return whether this damage source will have its damage amount scaled based on the current difficulty.
*/
public boolean isDifficultyScaled()
{
return this.damageSourceEntity != null && this.damageSourceEntity instanceof EntityLivingBase && !(this.damageSourceEntity instanceof EntityPlayer);
}
}
| nacjm/MatterOverdrive | src/main/java/matteroverdrive/util/EntityDamageSourcePhaser.java | Java | gpl-3.0 | 1,754 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source 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 ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using ClearCanvas.Common;
using ClearCanvas.Dicom;
using ClearCanvas.Dicom.Iod;
using ClearCanvas.Dicom.Utilities;
using ClearCanvas.ImageViewer.AdvancedImaging.Fusion.Utilities;
using ClearCanvas.ImageViewer.Comparers;
using ClearCanvas.ImageViewer.Mathematics;
using ClearCanvas.ImageViewer.StudyManagement;
namespace ClearCanvas.ImageViewer.AdvancedImaging.Fusion
{
public class PETFusionDisplaySetFactory : DisplaySetFactory
{
private const float _halfPi = (float) Math.PI/2;
private const float _gantryTiltTolerance = 0.1f; // allowed tolerance for gantry tilt (in radians)
private const float _orientationTolerance = 0.01f; // allowed tolerance for image orientation (direction cosine values)
private const float _minimumSliceSpacing = 0.01f; // minimum spacing required between slices (in mm)
private const float _sliceSpacingTolerance = 0.001f; // allowed tolerance for slice spacing (in mm)
private const string _attenuationCorrectionCode = "ATTN";
private const string _petModality = "PT";
private readonly PETFusionType _fusionType;
public PETFusionDisplaySetFactory(PETFusionType fusionType)
{
_fusionType = fusionType;
}
public PETFusionType FusionType
{
get { return _fusionType; }
}
private static bool IsAttenuationCorrected(Sop sop)
{
var correctionTypes = DicomStringHelper.GetStringArray(sop[DicomTags.CorrectedImage].ToString().ToUpperInvariant());
return (Array.FindIndex(correctionTypes, s => s == _attenuationCorrectionCode) >= 0);
}
public override List<IDisplaySet> CreateDisplaySets(Series series)
{
List<IDisplaySet> displaySets = new List<IDisplaySet>();
if (IsValidPETFusionSeries(series))
{
var fuseableBaseSeries = new List<Series>(FindFuseableBaseSeries(series));
if (fuseableBaseSeries.Count > 0)
{
string error;
if (!CheckPETFusionSeries(series, out error))
{
// if there is an error with the PET series, avoid trying to generate the volume entirely
// instead, generate a placeholder series for each base series
foreach (var baseSeries in fuseableBaseSeries)
displaySets.Add(CreateFusionErrorDisplaySet(baseSeries, series, error));
return displaySets;
}
using (var fusionOverlayData = new FusionOverlayData(GetFrames(series.Sops)))
{
foreach (var baseSeries in fuseableBaseSeries)
{
if (!CheckBaseSeries(baseSeries, out error))
{
// if there is an error with a single base series, generate a placeholder series
displaySets.Add(CreateFusionErrorDisplaySet(baseSeries, series, error));
continue;
}
var descriptor = new PETFusionDisplaySetDescriptor(baseSeries.GetIdentifier(), series.GetIdentifier(), IsAttenuationCorrected(series.Sops[0]));
var displaySet = new DisplaySet(descriptor);
foreach (var baseFrame in GetFrames(baseSeries.Sops))
{
using (var fusionOverlaySlice = fusionOverlayData.CreateOverlaySlice(baseFrame))
{
var fus = new FusionPresentationImage(baseFrame, fusionOverlaySlice);
displaySet.PresentationImages.Add(fus);
}
}
displaySet.PresentationImages.Sort();
displaySets.Add(displaySet);
}
}
}
}
return displaySets;
}
private static DisplaySet CreateFusionErrorDisplaySet(Series baseSeries, Series fusionSeries, string error)
{
// create a basic descriptor that's templated from the real PET fusion display descriptor
var baseDescriptor = new PETFusionDisplaySetDescriptor(baseSeries.GetIdentifier(), fusionSeries.GetIdentifier(), IsAttenuationCorrected(fusionSeries.Sops[0]));
var descriptor = new BasicDisplaySetDescriptor {Description = baseDescriptor.Description, Name = baseDescriptor.Name, Number = baseDescriptor.Number, Uid = baseDescriptor.Uid};
var displaySet = new DisplaySet(descriptor);
displaySet.PresentationImages.Add(new ErrorPresentationImage(SR.MessageFusionError + Environment.NewLine + string.Format(SR.FormatReason, error)));
return displaySet;
}
public bool IsValidBaseSeries(Series series)
{
switch (_fusionType)
{
case PETFusionType.CT:
if (series.Modality != _fusionType.ToString())
return false;
var frames = GetFrames(series.Sops);
if (frames.Count < 5)
return false;
return true;
}
return false;
}
public bool CheckBaseSeries(Series series, out string error)
{
if (!IsValidBaseSeries(series))
{
error = SR.MessageInvalidSeries;
return false;
}
var frames = GetFrames(series.Sops);
if (!AssertSameSeriesFrameOfReference(frames))
{
error = SR.MessageInconsistentFramesOfReference;
return false;
}
foreach (Frame frame in frames)
{
if (frame.ImageOrientationPatient.IsNull)
{
error = SR.MessageMissingImageOrientation;
return false;
}
//TODO (CR Sept 2010): ImagePositionPatient?
if (frame.NormalizedPixelSpacing.IsNull)
{
error = SR.MessageMissingPixelSpacing;
return false;
}
}
error = null;
return true;
}
public bool IsValidPETFusionSeries(Series series)
{
if (series.Modality != _petModality)
return false;
var frames = GetFrames(series.Sops);
if (frames.Count < 5)
return false;
return true;
}
public bool CheckPETFusionSeries(Series series, out string error)
{
if (!IsValidPETFusionSeries(series))
{
error = SR.MessageInvalidSeries;
return false;
}
var frames = GetFrames(series.Sops);
if (!AssertSameSeriesFrameOfReference(frames))
{
error = SR.MessageInconsistentFramesOfReference;
return false;
}
// ensure all frames have the same orientation
ImageOrientationPatient orient = frames[0].ImageOrientationPatient;
double minColumnSpacing = double.MaxValue, minRowSpacing = double.MaxValue;
double maxColumnSpacing = double.MinValue, maxRowSpacing = double.MinValue;
foreach (Frame frame in frames)
{
if (frame.ImageOrientationPatient.IsNull)
{
error = SR.MessageMissingImageOrientation;
return false;
}
if (!frame.ImageOrientationPatient.EqualsWithinTolerance(orient, _orientationTolerance))
{
error = SR.MessageInconsistentImageOrientation;
return false;
}
PixelSpacing pixelSpacing = frame.NormalizedPixelSpacing;
if (pixelSpacing.IsNull)
{
error = SR.MessageMissingPixelSpacing;
return false;
}
minColumnSpacing = Math.Min(minColumnSpacing, pixelSpacing.Column);
maxColumnSpacing = Math.Max(maxColumnSpacing, pixelSpacing.Column);
minRowSpacing = Math.Min(minRowSpacing, pixelSpacing.Row);
maxRowSpacing = Math.Max(maxRowSpacing, pixelSpacing.Row);
}
//Aren't many of these rules taken from MPR? If so, we should create a rule object.
// ensure all frames have consistent pixel spacing
if (maxColumnSpacing - minColumnSpacing > _sliceSpacingTolerance || maxRowSpacing - minRowSpacing > _sliceSpacingTolerance)
{
error = SR.MessageInconsistentPixelSpacing;
return false;
}
// ensure all frames are sorted by slice location
frames.Sort(new SliceLocationComparer().Compare);
// ensure all frames are equally spaced
float? nominalSpacing = null;
for (int i = 1; i < frames.Count; i++)
{
float currentSpacing = CalcSpaceBetweenPlanes(frames[i], frames[i - 1]);
if (currentSpacing < _minimumSliceSpacing)
{
error = SR.MessageInconsistentImageSpacing;
return false;
}
if (!nominalSpacing.HasValue)
nominalSpacing = currentSpacing;
if (!FloatComparer.AreEqual(currentSpacing, nominalSpacing.Value, _sliceSpacingTolerance))
{
error = SR.MessageInconsistentImageSpacing;
return false;
}
}
// ensure frames are not tilted about unsupposed axis combinations (the gantry correction algorithm only supports rotations about X)
if (!IsSupportedGantryTilt(frames)) // suffices to check first one... they're all co-planar now!!
{
error = SR.MessageUnsupportedGantryTilt;
return false;
}
error = null;
return true;
}
public bool CanFuse(Series baseSeries, Series petSeries)
{
if (!IsValidBaseSeries(baseSeries))
return false;
if (!IsValidPETFusionSeries(petSeries))
return false;
var baseFrames = GetFrames(baseSeries.Sops);
var petFrames = GetFrames(petSeries.Sops);
if (baseFrames[0].StudyInstanceUid != petFrames[0].StudyInstanceUid)
return false;
return true;
}
private IEnumerable<Series> FindFuseableBaseSeries(Series petSeries)
{
var petStudy = petSeries.ParentStudy;
if (petStudy == null)
yield break;
foreach (var series in petStudy.Series)
{
if (CanFuse(series, petSeries))
yield return series;
}
}
private static bool AssertSameSeriesFrameOfReference(IList<Frame> frames)
{
// ensure all frames have are from the same series, and have the same frame of reference
string studyInstanceUid = frames[0].StudyInstanceUid;
string seriesInstanceUid = frames[0].SeriesInstanceUid;
string frameOfReferenceUid = frames[0].FrameOfReferenceUid;
foreach (Frame frame in frames)
{
if (frame.StudyInstanceUid != studyInstanceUid)
return false;
if (frame.SeriesInstanceUid != seriesInstanceUid)
return false;
if (frame.FrameOfReferenceUid != frameOfReferenceUid)
return false;
}
return true;
}
private static List<Frame> GetFrames(IEnumerable<Sop> sops)
{
List<Frame> list = new List<Frame>();
foreach (var sop in sops)
if (sop is ImageSop)
list.AddRange(((ImageSop) sop).Frames);
return list;
}
private static float CalcSpaceBetweenPlanes(Frame frame1, Frame frame2)
{
Vector3D point1 = frame1.ImagePlaneHelper.ConvertToPatient(new PointF(0, 0));
Vector3D point2 = frame2.ImagePlaneHelper.ConvertToPatient(new PointF(0, 0));
Vector3D delta = point1 - point2;
return delta.IsNull ? 0f : delta.Magnitude;
}
private static bool IsSupportedGantryTilt(IList<Frame> frames)
{
try
{
// neither of these should return null since we already checked for image orientation and position (patient)
var firstImagePlane = frames[0].ImagePlaneHelper;
var lastImagePlane = frames[frames.Count - 1].ImagePlaneHelper;
Vector3D stackZ = lastImagePlane.ImageTopLeftPatient - firstImagePlane.ImageTopLeftPatient;
Vector3D imageX = firstImagePlane.ImageTopRightPatient - firstImagePlane.ImageTopLeftPatient;
if (!stackZ.IsOrthogonalTo(imageX, _gantryTiltTolerance))
{
// this is a gantry slew (gantry tilt about Y axis)
return false;
}
return true;
}
catch (Exception ex)
{
Platform.Log(LogLevel.Debug, ex, "Unexpected exception encountered while checking for supported gantry tilts");
return false;
}
}
}
} | chinapacs/ImageViewer | ImageViewer/AdvancedImaging/Fusion/PETFusionDisplaySetFactory.cs | C# | gpl-3.0 | 12,218 |
/**
* @license
* Copyright 2012 Dan Vanderkam (danvdk@gmail.com)
* MIT-licensed (http://opensource.org/licenses/MIT)
*/
Dygraph.Plugins.Annotations = (function() {
"use strict";
/**
Current bits of jankiness:
- Uses dygraph.layout_ to get the parsed annotations.
- Uses dygraph.plotter_.area
It would be nice if the plugin didn't require so much special support inside
the core dygraphs classes, but annotations involve quite a bit of parsing and
layout.
TODO(danvk): cache DOM elements.
*/
var annotations = function() {
this.annotations_ = [];
};
annotations.prototype.toString = function() {
return "Annotations Plugin";
};
annotations.prototype.activate = function(g) {
return {
clearChart: this.clearChart,
didDrawChart: this.didDrawChart
};
};
annotations.prototype.detachLabels = function() {
for (var i = 0; i < this.annotations_.length; i++) {
var a = this.annotations_[i];
if (a.parentNode) a.parentNode.removeChild(a);
this.annotations_[i] = null;
}
this.annotations_ = [];
};
annotations.prototype.clearChart = function(e) {
this.detachLabels();
};
annotations.prototype.didDrawChart = function(e) {
var g = e.dygraph;
// Early out in the (common) case of zero annotations.
var points = g.layout_.annotated_points;
if (!points || points.length === 0) return;
var containerDiv = e.canvas.parentNode;
var annotationStyle = {
"position": "absolute",
"fontSize": g.getOption('axisLabelFontSize') + "px",
"zIndex": 10,
"overflow": "hidden"
};
var bindEvt = function(eventName, classEventName, pt) {
return function(annotation_event) {
var a = pt.annotation;
if (a.hasOwnProperty(eventName)) {
a[eventName](a, pt, g, annotation_event);
} else if (g.getOption(classEventName)) {
g.getOption(classEventName)(a, pt, g, annotation_event );
}
};
};
// Add the annotations one-by-one.
var area = e.dygraph.plotter_.area;
for (var i = 0; i < points.length; i++) {
var p = points[i];
if (p.canvasx < area.x || p.canvasx > area.x + area.w ||
p.canvasy < area.y || p.canvasy > area.y + area.h) {
continue;
}
var a = p.annotation;
var tick_height = 6;
if (a.hasOwnProperty("tickHeight")) {
tick_height = a.tickHeight;
}
var div = document.createElement("div");
for (var name in annotationStyle) {
if (annotationStyle.hasOwnProperty(name)) {
div.style[name] = annotationStyle[name];
}
}
if (!a.hasOwnProperty('icon')) {
div.className = "dygraphDefaultAnnotation";
}
if (a.hasOwnProperty('cssClass')) {
div.className += " " + a.cssClass;
}
var width = a.hasOwnProperty('width') ? a.width : 16;
var height = a.hasOwnProperty('height') ? a.height : 16;
if (a.hasOwnProperty('icon')) {
var img = document.createElement("img");
img.src = a.icon;
img.width = width;
img.height = height;
div.appendChild(img);
} else if (p.annotation.hasOwnProperty('shortText')) {
div.appendChild(document.createTextNode(p.annotation.shortText));
}
div.style.left = (p.canvasx - width / 2) + "px";
if (a.attachAtBottom) {
div.style.top = (area.h - height - tick_height) + "px";
} else {
div.style.top = (p.canvasy - height - tick_height) + "px";
}
div.style.width = width + "px";
div.style.height = height + "px";
div.title = p.annotation.text;
div.style.color = g.colorsMap_[p.name];
div.style.borderColor = g.colorsMap_[p.name];
a.div = div;
g.addEvent(div, 'click',
bindEvt('clickHandler', 'annotationClickHandler', p, this));
g.addEvent(div, 'mouseover',
bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
g.addEvent(div, 'mouseout',
bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
g.addEvent(div, 'dblclick',
bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
containerDiv.appendChild(div);
this.annotations_.push(div);
var ctx = e.drawingContext;
ctx.save();
ctx.strokeStyle = g.colorsMap_[p.name];
ctx.beginPath();
if (!a.attachAtBottom) {
ctx.moveTo(p.canvasx, p.canvasy);
ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
} else {
ctx.moveTo(p.canvasx, area.h);
ctx.lineTo(p.canvasx, area.h - 2 - tick_height);
}
ctx.closePath();
ctx.stroke();
ctx.restore();
}
};
annotations.prototype.destroy = function() {
this.detachLabels();
};
return annotations;
})();
| CINF/DataPresentationWebsite | sym-files2/dygraph/plugins/annotations.js | JavaScript | gpl-3.0 | 4,587 |
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "graph_filtering.hh"
#include <boost/python.hpp>
#include "graph.hh"
#include "graph_selectors.hh"
#include "graph_katz.hh"
using namespace std;
using namespace boost;
using namespace graph_tool;
void katz(GraphInterface& g, boost::any w, boost::any c, boost::any beta,
long double alpha, double epsilon, size_t max_iter)
{
if (!w.empty() && !belongs<writable_edge_scalar_properties>()(w))
throw ValueException("edge property must be writable");
if (!belongs<vertex_floating_properties>()(c))
throw ValueException("centrality vertex property must be of floating point"
" value type");
if (!beta.empty() && !belongs<vertex_floating_properties>()(beta))
throw ValueException("personalization vertex property must be of floating point"
" value type");
typedef ConstantPropertyMap<double, GraphInterface::edge_t> weight_map_t;
typedef boost::mpl::push_back<writable_edge_scalar_properties, weight_map_t>::type
weight_props_t;
if(w.empty())
w = weight_map_t(1.);
typedef ConstantPropertyMap<double, GraphInterface::vertex_t> beta_map_t;
typedef boost::mpl::push_back<vertex_floating_properties, beta_map_t>::type
beta_props_t;
if(beta.empty())
beta = beta_map_t(1.);
run_action<>()(g, std::bind(get_katz(), placeholders::_1, g.GetVertexIndex(),
placeholders::_2, placeholders::_3,
placeholders::_4, alpha, epsilon, max_iter),
weight_props_t(),
vertex_floating_properties(),
beta_props_t())(w, c, beta);
}
void export_katz()
{
using namespace boost::python;
def("get_katz", &katz);
}
| antmd/graph-tool | src/graph/centrality/graph_katz.cc | C++ | gpl-3.0 | 2,580 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.