code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
-- change taskid to be new patavi URIs
UPDATE model SET taskid = NULL ;
ALTER TABLE model ALTER COLUMN taskid TYPE VARCHAR(128) ;
ALTER TABLE model RENAME COLUMN taskid TO taskUrl ;
| gertvv/gemtc-web | changesets/create-database-changeset-10.sql | SQL | gpl-3.0 | 182 |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// UserDetails Data Structure.
/// </summary>
[Serializable]
public class UserDetails : AopObject
{
/// <summary>
/// 用户变更手机号,替换旧的手机号
/// </summary>
[XmlElement("user_change_mobile")]
public string UserChangeMobile { get; set; }
/// <summary>
/// 孩子家长的手机号
/// </summary>
[XmlElement("user_mobile")]
public string UserMobile { get; set; }
/// <summary>
/// 张三
/// </summary>
[XmlElement("user_name")]
public string UserName { get; set; }
/// <summary>
/// 孩子与家长的关系: 1、爸爸 2、妈妈 3、爷爷 4、奶奶 5、外公 6、外婆 7、家长
/// </summary>
[XmlElement("user_relation")]
public string UserRelation { get; set; }
}
}
| ColgateKas/cms | source/BaiRong.Core/ThirdParty/Alipay/openapi/Domain/UserDetails.cs | C# | gpl-3.0 | 986 |
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Exceptions.h
* @author Gav Wood <[email protected]>
* @date 2014
*/
#pragma once
#include <exception>
#include <string>
#include <boost/exception/all.hpp>
#include <boost/throw_exception.hpp>
#include "CommonData.h"
#include "FixedHash.h"
namespace dev
{
/// Base class for all exceptions.
struct Exception: virtual std::exception, virtual boost::exception
{
Exception(std::string _message = std::string()): m_message(std::move(_message)) {}
const char* what() const noexcept override { return m_message.empty() ? std::exception::what() : m_message.c_str(); }
private:
std::string m_message;
};
#define DEV_SIMPLE_EXCEPTION(X) struct X: virtual Exception { const char* what() const noexcept override { return #X; } }
/// Base class for all RLP exceptions.
struct RLPException: virtual Exception { RLPException(std::string _message = std::string()): Exception(_message) {} };
#define DEV_SIMPLE_EXCEPTION_RLP(X) struct X: virtual RLPException { const char* what() const noexcept override { return #X; } }
DEV_SIMPLE_EXCEPTION_RLP(BadCast);
DEV_SIMPLE_EXCEPTION_RLP(BadRLP);
DEV_SIMPLE_EXCEPTION_RLP(OversizeRLP);
DEV_SIMPLE_EXCEPTION_RLP(UndersizeRLP);
DEV_SIMPLE_EXCEPTION(BadHexCharacter);
DEV_SIMPLE_EXCEPTION(NoNetworking);
DEV_SIMPLE_EXCEPTION(NoUPnPDevice);
DEV_SIMPLE_EXCEPTION(RootNotFound);
struct BadRoot: virtual Exception { public: BadRoot(h256 const& _root): Exception("BadRoot " + _root.hex()), root(_root) {} h256 root; };
DEV_SIMPLE_EXCEPTION(FileError);
DEV_SIMPLE_EXCEPTION(Overflow);
DEV_SIMPLE_EXCEPTION(FailedInvariant);
struct InterfaceNotSupported: virtual Exception { public: InterfaceNotSupported(std::string _f): Exception("Interface " + _f + " not supported.") {} };
struct ExternalFunctionFailure: virtual Exception { public: ExternalFunctionFailure(std::string _f): Exception("Function " + _f + "() failed.") {} };
// error information to be added to exceptions
using errinfo_invalidSymbol = boost::error_info<struct tag_invalidSymbol, char>;
using errinfo_wrongAddress = boost::error_info<struct tag_address, std::string>;
using errinfo_comment = boost::error_info<struct tag_comment, std::string>;
using errinfo_required = boost::error_info<struct tag_required, bigint>;
using errinfo_got = boost::error_info<struct tag_got, bigint>;
using errinfo_min = boost::error_info<struct tag_min, bigint>;
using errinfo_max = boost::error_info<struct tag_max, bigint>;
using RequirementError = boost::tuple<errinfo_required, errinfo_got>;
using errinfo_hash256 = boost::error_info<struct tag_hash, h256>;
using errinfo_required_h256 = boost::error_info<struct tag_required_h256, h256>;
using errinfo_got_h256 = boost::error_info<struct tag_get_h256, h256>;
using Hash256RequirementError = boost::tuple<errinfo_required_h256, errinfo_got_h256>;
using errinfo_extraData = boost::error_info<struct tag_extraData, bytes>;
}
| hanyoungpark/cpp-ethereum | libdevcore/Exceptions.h | C | gpl-3.0 | 3,529 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Using Transactions</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Berkeley DB Collections Tutorial" />
<link rel="up" href="BasicProgram.html" title="Chapter 2. The Basic Program" />
<link rel="prev" href="implementingmain.html" title="Implementing the Main Program" />
<link rel="next" href="addingdatabaseitems.html" title="Adding Database Items" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.1.6.1</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">
Using Transactions
</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="implementingmain.html">Prev</a> </td>
<th width="60%" align="center">Chapter 2.
The Basic Program
</th>
<td width="20%" align="right"> <a accesskey="n" href="addingdatabaseitems.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="usingtransactions"></a>
Using Transactions
</h2>
</div>
</div>
</div>
<p>
DB transactional applications have standard
transactional characteristics: recoverability, atomicity and
integrity (this is sometimes also referred to generically as <span class="emphasis"><em>ACID
properties</em></span>). The DB Java Collections API provides these
transactional capabilities using a <span class="emphasis"><em>transaction-per-thread</em></span>
model. Once a transaction is begun, it is implicitly associated
with the current thread until it is committed or aborted. This
model is used for the following reasons.
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
The transaction-per-thread model is commonly used in other Java
APIs such as J2EE.
</p>
</li>
<li>
<p>
Since the Java collections API is used for data access, there
is no way to pass a transaction object to methods such
as
<a class="ulink" href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/Map.html#put(K, V)" target="_top">Map.put</a>.
</p>
</li>
</ul>
</div>
<p>
The DB Java Collections API provides two transaction APIs. The
lower-level API is the
<a class="ulink" href="../../java/com/sleepycat/collections/CurrentTransaction.html" target="_top">CurrentTransaction</a>
class. It provides a way to get the transaction for the current
thread, and to begin, commit and abort transactions. It also
provides access to the Berkeley DB core API
<a class="ulink" href="../../java/com/sleepycat/db/Transaction.html" target="_top">Transaction</a>
object. With
<a class="ulink" href="../../java/com/sleepycat/collections/CurrentTransaction.html" target="_top">CurrentTransaction</a>,
just as in the
<span>com.sleepycat.db</span>
API, the application is responsible
for beginning, committing and aborting transactions, and for
handling deadlock exceptions and retrying operations. This API may
be needed for some applications, but it is not used in the
example.
</p>
<p>
The example uses the higher-level
<a class="ulink" href="../../java/com/sleepycat/collections/TransactionRunner.html" target="_top">TransactionRunner</a>
and
<a class="ulink" href="../../java/com/sleepycat/collections/TransactionWorker.html" target="_top">TransactionWorker</a>
APIs, which are build on top of
<a class="ulink" href="../../java/com/sleepycat/collections/CurrentTransaction.html" target="_top">CurrentTransaction</a>.
<code class="methodname">TransactionRunner.run()</code> automatically begins a transaction and
then calls the <code class="methodname">TransactionWorker.doWork()</code> method, which is
implemented by the application.
</p>
<p>
The <code class="methodname">TransactionRunner.run()</code> method automatically detects
deadlock exceptions and performs retries by repeatedly calling the
<code class="methodname">TransactionWorker.doWork()</code> method until the operation succeeds
or the maximum retry count is reached. If the maximum retry count
is reached or if another exception (other than
<span>
<a class="ulink" href="../../java/com/sleepycat/db/DeadlockException.html" target="_top">DeadlockException</a>)
</span>
is thrown by <code class="methodname">TransactionWorker.doWork()</code>, then the transaction
will be automatically aborted. Otherwise, the transaction will be
automatically committed.
</p>
<p>
Using this high-level API, if <code class="methodname">TransactionRunner.run()</code>
throws an exception, the application can assume that the operation
failed and the transaction was aborted; otherwise, when an
exception is not thrown, the application can assume the operation
succeeded and the transaction was committed.
</p>
<p>
The <code class="methodname">Sample.run()</code> method creates a <code class="classname">TransactionRunner</code>
object and calls its <code class="methodname">run()</code> method.
</p>
<a id="cb_sample1"></a>
<pre class="programlisting"><strong class="userinput"><code>import com.sleepycat.collections.TransactionRunner;
import com.sleepycat.collections.TransactionWorker;</code></strong>
...
public class Sample
{
private SampleDatabase db;
...
<strong class="userinput"><code> private void run()
throws Exception
{
TransactionRunner runner =
new TransactionRunner(db.getEnvironment());
runner.run(new PopulateDatabase());
runner.run(new PrintDatabase());
}
...
private class PopulateDatabase implements TransactionWorker
{
public void doWork()
throws Exception
{
}
}
private class PrintDatabase implements TransactionWorker
{
public void doWork()
throws Exception
{
}
}</code></strong>
} </pre>
<p>
The <code class="methodname">run()</code> method is called by <code class="methodname">main()</code> and was outlined
in the previous section. It first creates a
<code class="classname">TransactionRunner</code>, passing the database environment to its
constructor.
</p>
<p>
It then calls <code class="methodname">TransactionRunner.run()</code> to execute two
transactions, passing instances of the application-defined
<code class="classname">PopulateDatabase</code> and
<code class="classname">PrintDatabase</code> nested classes.
These classes implement the <code class="methodname">TransactionWorker.doWork()</code> method
and will be fully described in the next two sections.
</p>
<p>
For each call to <code class="methodname">TransactionRunner.run()</code>, a separate
transaction will be performed. The use of two transactions in the
example — one for populating the database and another for printing
its contents — is arbitrary. A real-life application should be
designed to create transactions for each group of operations that
should have ACID properties, while also
taking into account the impact of transactions on performance.
</p>
<p>
The advantage of using <code class="classname">TransactionRunner</code> is that deadlock
retries and transaction begin, commit and abort are handled
automatically. However, a <code class="classname">TransactionWorker</code> class must be
implemented for each type of transaction. If desired, anonymous
inner classes can be used to implement the <code class="classname">TransactionWorker</code>
interface.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="implementingmain.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="BasicProgram.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="addingdatabaseitems.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">
Implementing the Main Program
</td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top">
Adding Database Items
</td>
</tr>
</table>
</div>
</body>
</html>
| malin1993ml/h-store | third_party/cpp/berkeleydb/docs/collections/tutorial/usingtransactions.html | HTML | gpl-3.0 | 9,191 |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipaySecurityRiskAntifraudBatchqueryModel Data Structure.
/// </summary>
[Serializable]
public class AlipaySecurityRiskAntifraudBatchqueryModel : AopObject
{
/// <summary>
/// company_list+传入的一批待检查的企业名单+用户传入+还可以传入{"creditCode":"企业信用代码"}或者{"regNo":"企业工商注册号"}
/// </summary>
[XmlArray("company_list")]
[XmlArrayItem("string")]
public List<string> CompanyList { get; set; }
/// <summary>
/// partner_name+唯一+作为标识调用者身份的字段+用户填入
/// </summary>
[XmlElement("partner_name")]
public string PartnerName { get; set; }
/// <summary>
/// staff_list+传入的一批待检查员工信息+用户传入+手机号/身份证姓名二选一+还可以传入{"name":"姓名","phone":"手机号码"}
/// </summary>
[XmlArray("staff_list")]
[XmlArrayItem("string")]
public List<string> StaffList { get; set; }
}
}
| ColgateKas/cms | source/BaiRong.Core/ThirdParty/Alipay/openapi/Domain/AlipaySecurityRiskAntifraudBatchqueryModel.cs | C# | gpl-3.0 | 1,193 |
/* radare - LGPL - Copyright 2013-2015 - pancake */
#include <r_bin.h>
R_API bool r_bin_lang_swift(RBinFile *binfile) {
RBinObject *o = binfile ? binfile->o : NULL;
RBinInfo *info = o ? o->info : NULL;
RBinSymbol *sym;
RListIter *iter;
if (info) {
r_list_foreach (o->symbols, iter, sym) {
if (strstr (sym->name, "swift_release")) {
info->lang = "swift";
return true;
}
}
}
return false;
}
| ricardoquesada/radare2 | libr/bin/mangling/swift.c | C | gpl-3.0 | 416 |
<?php
/*
* Copyright (c) 2011-2015 Lp digital system
*
* This file is part of BackBee.
*
* BackBee 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.
*
* BackBee 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 BackBee. If not, see <http://www.gnu.org/licenses/>.
*
* @author Charles Rouillon <[email protected]>
*/
namespace BackBee\Rest\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;
use BackBee\Rest\Controller\Annotations as Rest;
use BackBee\Rest\Exception\ValidationException;
use BackBee\Security\Group;
/**
* User Controller.
*
* @category BackBee
*
* @copyright Lp digital system
* @author k.golovin
*/
class GroupController extends AbstractRestController
{
/**
* Get all records.
* @Rest\Security("is_fully_authenticated() & has_role('ROLE_API_USER')")
*/
public function getCollectionAction(Request $request)
{
if ($request->request->has('site_uid')) {
$site_uid = $request->request->get('site_uid');
$this->checkSiteUid($site_uid);
} else {
$site_uid = $this->getApplication()->getSite()->getUid();
}
$groups = $this->getEntityManager()
->getRepository('BackBee\Security\Group')
->createQueryBuilder('g')
->where('g._site = :siteUid')
->orWhere('g._site IS NULL')
->setParameter(':siteUid', $site_uid)
->getQuery()
->getResult();
return new Response($this->formatCollection($groups), 200, ['Content-Type' => 'application/json']);
}
/**
* GET Group.
*
* @Rest\ParamConverter(name="group", id_name = "id", class="BackBee\Security\Group")
* @Rest\Security("is_fully_authenticated() & has_role('ROLE_API_USER') & is_granted('VIEW', group)")
*/
public function getAction(Group $group)
{
return new Response($this->formatItem($group), 200, ['Content-Type' => 'application/json']);
}
/**
* DELETE.
*
* @Rest\ParamConverter(name="group", id_name = "id", class="BackBee\Security\Group")
* @Rest\Security("is_fully_authenticated() & has_role('ROLE_API_USER') & is_granted('DELETE', group)")
*/
public function deleteAction(Group $group)
{
$this->getEntityManager()->remove($group);
$this->getEntityManager()->flush();
return new Response("", 204);
}
/**
* UPDATE.
*
* @Rest\RequestParam(name = "name", requirements = {
* @Assert\NotBlank(message="Name is required"),
* @Assert\Length(max=50, minMessage="Maximum length of name is 50 characters")
* })
*
* @Rest\ParamConverter(name="group", id_name = "id", class="BackBee\Security\Group")
* @Rest\Security("is_fully_authenticated() & has_role('ROLE_API_USER') & is_granted('EDIT', group) & is_granted('VIEW', group)")
*/
public function putAction(Group $group, Request $request)
{
$site = $this->getSite($request);
if ($this->isDuplicated($request->request->get('name'), $site)) {
return new JsonResponse([
'errors' => [
'name' => 'Group already exists.',
],
], 400);
}
$this->deserializeEntity($request->request->all(), $group);
$this->getEntityManager()->persist($group);
$this->getEntityManager()->flush();
return new Response("", 204);
}
/**
* Create.
*
* @Rest\RequestParam(name = "name", requirements = {
* @Assert\NotBlank(message="Name is required"),
* @Assert\Length(max=50, minMessage="Maximum length of name is 50 characters")
* })
* @Rest\Security("is_fully_authenticated() & has_role('ROLE_API_USER') & is_granted('CREATE', '\BackBee\Security\Group')")
*/
public function postAction(Request $request)
{
$group = new Group();
$site = $this->getSite($request);
if ($this->isDuplicated($request->request->get('name'), $site)) {
return new JsonResponse([
'errors' => [
'name' => 'Group already exists.',
],
], 400);
}
$group->setName($request->request->get('name'));
$group->setSite($site);
$group = $this->deserializeEntity($request->request->all(), $group);
$this->getEntityManager()->persist($group);
$this->getEntityManager()->flush();
return new Response($this->formatItem($group), 200, ['Content-Type' => 'application/json']);
}
private function getSite(Request $request)
{
if ($request->request->has('site_uid')) {
$this->checkSiteUid($request->request->get('site_uid'));
$site = $this->getEntityManager()->find('BackBee\Site\Site', $request->request->get('site_uid'));
} else {
$site = $this->getApplication()->getSite();
}
return $site;
}
private function checkSiteUid($site_uid)
{
$site = $this->getEntityManager()->find('BackBee\Site\Site', $site_uid);
$validator = Validation::createValidator();
$constraint = new Assert\NotNull(['message' => 'Invalid site identifier']);
$violations = $validator->validateValue($site, $constraint);
if (count($violations) > 0) {
throw new ValidationException($violations);
}
}
private function isDuplicated($name, $site) {
$duplicate = $this->getEntityManager()->getRepository('BackBee\Security\Group')->findOneBy([
'_name' => $name,
'_site' => $site,
]);
return $duplicate !== null;
}
}
| DVSB/BackBee | Rest/Controller/GroupController.php | PHP | gpl-3.0 | 6,379 |
/*********************************************************************
Author: Roberto Bruttomesso <[email protected]>
OpenSMT -- Copyright (C) 2009, Roberto Bruttomesso
OpenSMT 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.
OpenSMT 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 OpenSMT. If not, see <http://www.gnu.org/licenses/>.
*********************************************************************/
#ifndef GLOBAL_H
#define GLOBAL_H
#include <cassert>
#include <chrono>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <sstream>
#include <iostream>
#include <fstream>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#include <utility>
#include <sys/time.h>
#include <unistd.h>
#include <stdint.h>
#include <limits.h>
#define NEW_SPLIT 0
#define NEW_SIMPLIFICATIONS 0
#define opensmt_error( S ) { std::cerr << "# Error: " << S << " (triggered at " << __FILE__ << ", " << __LINE__ << ")" << std::endl; exit( 1 ); }
#define opensmt_error2( S, T ) { std::cerr << "# Error: " << S << " " << T << " (triggered at " << __FILE__ << ", " << __LINE__ << ")" << std::endl; exit( 1 ); }
#define opensmt_warning( S ) { std::cerr << "# Warning: " << S << std::endl; }
#define opensmt_warning2( S, T ) { std::cerr << "# Warning: " << S << " " << T << std::endl; }
#if ( __WORDSIZE == 64 )
#define BUILD_64
#endif
/* #if defined( __GNUC__ ) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) */
/* using __gnu_pbds::priority_queue; */
/* using __gnu_pbds::pairing_heap_tag; */
/* #else */
/* #error "This version of OpenSMT requires at least gcc 4.3" */
/* using pb_ds::priority_queue; */
/* using pb_ds::pairing_heap_tag; */
/* #endif */
#define USE_GMP 0
#define FAST_RATIONALS 0
#if FAST_RATIONALS
#include "FastRationals.h"
#endif
namespace opensmt {
#if FAST_RATIONALS
typedef FastRational Real;
typedef FastInteger Integer;
#elif USE_GMP
typedef mpq_class Real;
typedef mpz_class Integer;
#else
typedef double Real;
typedef long Integer;
#endif
#define Pair( T ) std::pair< T, T >
typedef int enodeid_t;
typedef enodeid_t snodeid_t;
#ifdef BUILD_64
typedef long enodeid_pair_t;
inline enodeid_pair_t encode( enodeid_t car, enodeid_t cdr )
{
enodeid_pair_t p = car;
p = p<<(sizeof(enodeid_t)*8);
enodeid_pair_t q = cdr;
p |= q;
return p;
}
#else
typedef Pair( enodeid_t ) enodeid_pair_t;
inline enodeid_pair_t encode( enodeid_t car, enodeid_t cdr )
{ return std::make_pair( car, cdr ); }
#endif
typedef enodeid_pair_t snodeid_pair_t;
#ifndef SMTCOMP
#define STATISTICS
#endif
// Set the bit B to 1 and leaves the others to 0
#define SETBIT( B ) ( 1 << (B) )
typedef enum
{
UNDEF // Undefined logic
, EMPTY // Empty, for the template solver
, QF_NRA // Non-Linear Real Arithmetic (added for dReal2)
, QF_NRA_ODE // Non-Linear Real Arithmetic with ODE (added for dReal2)
, QF_UF // Uninterpreted Functions
, QF_BV // BitVectors
, QF_RDL // Real difference logics
, QF_IDL // Integer difference logics
, QF_LRA // Real linear arithmetic
, QF_LIA // Integer linear arithmetic
, QF_UFRDL // UF + RDL
, QF_UFIDL // UF + IDL
, QF_UFLRA // UF + LRA
, QF_UFLIA // UF + LIA
, QF_UFBV // UF + BV
, QF_AUFBV // Arrays + UF + BV
, QF_AX // Arrays with extensionality
, QF_BOOL // Purely SAT instances
, QF_CT // Cost
// DO NOT REMOVE THIS COMMENT !!
// IT IS USED BY CREATE_THEORY.SH SCRIPT !!
// NEW_THEORY_INIT
} logic_t;
extern std::chrono::time_point<std::chrono::high_resolution_clock> g_epoch_time;
static inline double cpuTime(void)
{
auto now = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = now - g_epoch_time;
return diff.count();
}
#if defined(__linux__)
static inline int memReadStat(int field)
{
char name[256];
pid_t pid = getpid();
sprintf(name, "/proc/%d/statm", pid);
FILE* in = fopen(name, "rb");
if (in == NULL) return 0;
int value;
for (; field >= 0; field--) {
if(fscanf(in, "%d", &value) != 1) {
opensmt_error("memReadStat failed to read.");
}
}
fclose(in);
return value;
}
static inline uint64_t memUsed() { return (uint64_t)memReadStat(0) * (uint64_t)getpagesize(); }
#elif defined(__FreeBSD__) || defined(__OSX__) || defined(__APPLE__)
static inline uint64_t memUsed()
{
char name[256];
FILE *pipe;
char buf[1024];
uint64_t value=0;
pid_t pid = getpid();
sprintf(name,"ps -o rss -p %d | grep -v RSS", pid);
pipe = popen(name, "r");
if (pipe)
{
fgets(buf, 1024, pipe);
value = 1024 * strtoul(buf, NULL, 10);
pclose(pipe);
}
return value;
}
#else // stub to support every platform
static inline uint64_t memUsed() {return 0; }
#endif
#define CNF_STR "CNF_%d_%d"
#define ITE_STR "ITE_%d"
#define SPL_STR "SPL_%d"
#define UNC_STR "UNC_%d"
#define IND_STR "IND_%d_%d"
#define ELE_STR "ELE_%d"
#define ARR_STR "ARR_%d"
#ifdef PRODUCE_PROOF
// Used by graph-based algorithms
// to compute interpolants
enum CGCOLOR
{
CG_UNDEF = 0x0
, CG_A = 0x1
, CG_B = 0x2
, CG_AB = CG_A | CG_B
};
typedef uint64_t cgcolor_t;
#endif
} // namespace opensmt
using opensmt::Real;
using opensmt::Integer;
using opensmt::enodeid_t;
using opensmt::snodeid_t;
using opensmt::enodeid_pair_t;
using opensmt::encode;
using opensmt::logic_t;
using opensmt::UNDEF;
using opensmt::EMPTY;
using opensmt::QF_NRA;
using opensmt::QF_NRA_ODE;
using opensmt::QF_UF;
using opensmt::QF_BV;
using opensmt::QF_RDL;
using opensmt::QF_IDL;
using opensmt::QF_LRA;
using opensmt::QF_LIA;
using opensmt::QF_UFRDL;
using opensmt::QF_UFIDL;
using opensmt::QF_UFLRA;
using opensmt::QF_UFLIA;
using opensmt::QF_UFBV;
using opensmt::QF_AUFBV;
using opensmt::QF_AX;
using opensmt::QF_BOOL;
using opensmt::QF_CT;
using opensmt::cpuTime;
using opensmt::memUsed;
#ifdef PRODUCE_PROOF
using opensmt::cgcolor_t;
using opensmt::CG_UNDEF;
using opensmt::CG_A;
using opensmt::CG_B;
using opensmt::CG_AB;
#endif
#endif
| dreal/dreal-next | src/opensmt/common/Global.h | C | gpl-3.0 | 6,621 |
/**
* EQEmulator: Everquest Server Emulator
* Copyright (C) 2001-2020 EQEmulator Development Team (https://github.com/EQEmu/Server)
*
* 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; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY except by those people which sell it, which
* are required to give you total support for your newly bought product;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef EQEMU_AA_RANK_PREREQS_REPOSITORY_H
#define EQEMU_AA_RANK_PREREQS_REPOSITORY_H
#include "../database.h"
#include "../string_util.h"
#include "base/base_aa_rank_prereqs_repository.h"
class AaRankPrereqsRepository: public BaseAaRankPrereqsRepository {
public:
/**
* This file was auto generated and can be modified and extended upon
*
* Base repository methods are automatically
* generated in the "base" version of this repository. The base repository
* is immutable and to be left untouched, while methods in this class
* are used as extension methods for more specific persistence-layer
* accessors or mutators.
*
* Base Methods (Subject to be expanded upon in time)
*
* Note: Not all tables are designed appropriately to fit functionality with all base methods
*
* InsertOne
* UpdateOne
* DeleteOne
* FindOne
* GetWhere(std::string where_filter)
* DeleteWhere(std::string where_filter)
* InsertMany
* All
*
* Example custom methods in a repository
*
* AaRankPrereqsRepository::GetByZoneAndVersion(int zone_id, int zone_version)
* AaRankPrereqsRepository::GetWhereNeverExpires()
* AaRankPrereqsRepository::GetWhereXAndY()
* AaRankPrereqsRepository::DeleteWhereXAndY()
*
* Most of the above could be covered by base methods, but if you as a developer
* find yourself re-using logic for other parts of the code, its best to just make a
* method that can be re-used easily elsewhere especially if it can use a base repository
* method and encapsulate filters there
*/
// Custom extended repository methods here
};
#endif //EQEMU_AA_RANK_PREREQS_REPOSITORY_H
| af4t/Server | common/repositories/aa_rank_prereqs_repository.h | C | gpl-3.0 | 2,661 |
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2009 Laurent Gomila ([email protected])
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/Cocoa/VideoModeSupport.hpp>
#include <ApplicationServices/ApplicationServices.h>
#include <algorithm>
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
/// Get supported video modes
////////////////////////////////////////////////////////////
void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& Modes)
{
// Ceylo -- using same implementation as in OSXCarbon
// First, clear array to fill
Modes.clear();
// Enumerate all available video modes for primary display adapter
CFArrayRef DisplayModes = CGDisplayAvailableModes( kCGDirectMainDisplay );
CFIndex DisplayModeCount = CFArrayGetCount( DisplayModes );
CFDictionaryRef CurrentMode;
for (int Count = 0; Count < DisplayModeCount; ++Count)
{
CurrentMode = (CFDictionaryRef)CFArrayGetValueAtIndex( DisplayModes, Count );
VideoMode Mode;
CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentMode, kCGDisplayWidth), kCFNumberIntType, &(Mode.Width));
CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentMode, kCGDisplayHeight), kCFNumberIntType, &(Mode.Height));
CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentMode, kCGDisplayBitsPerPixel), kCFNumberIntType, &(Mode.BitsPerPixel));
// Add it only if it is not already in the array
if (std::find(Modes.begin(), Modes.end(), Mode) == Modes.end())
Modes.push_back(Mode);
}
}
////////////////////////////////////////////////////////////
/// Get current desktop video mode
////////////////////////////////////////////////////////////
VideoMode VideoModeSupport::GetDesktopVideoMode()
{
// Ceylo -- using same implementation as in OSXCarbon
CFDictionaryRef CurrentVideoMode = CGDisplayCurrentMode(kCGDirectMainDisplay);
VideoMode DesktopMode;
// Get video mode width
CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentVideoMode, kCGDisplayWidth),
kCFNumberIntType,
&(DesktopMode.Width));
// Get video mode height
CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentVideoMode, kCGDisplayHeight),
kCFNumberIntType,
&(DesktopMode.Height));
// Get video mode depth
CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentVideoMode, kCGDisplayBitsPerPixel),
kCFNumberIntType,
&(DesktopMode.BitsPerPixel));
return DesktopMode;
}
} // namespace priv
} // namespace sf
| CarlosManuelRodr/wxChaos | libs/SFML_1.6/src/SFML/Window/Cocoa/VideoModeSupport.cpp | C++ | gpl-3.0 | 3,700 |
/*
* Copyright (c) 2015 Jean-Christophe Dubois <[email protected]>
*
* i.MX6 SOC emulation.
*
* Based on hw/arm/fsl-imx31.c
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "qemu-common.h"
#include "hw/arm/fsl-imx6.h"
#include "sysemu/sysemu.h"
#include "sysemu/char.h"
#include "qemu/error-report.h"
#define NAME_SIZE 20
static void fsl_imx6_init(Object *obj)
{
FslIMX6State *s = FSL_IMX6(obj);
char name[NAME_SIZE];
int i;
if (smp_cpus > FSL_IMX6_NUM_CPUS) {
error_report("%s: Only %d CPUs are supported (%d requested)",
TYPE_FSL_IMX6, FSL_IMX6_NUM_CPUS, smp_cpus);
exit(1);
}
for (i = 0; i < smp_cpus; i++) {
object_initialize(&s->cpu[i], sizeof(s->cpu[i]),
"cortex-a9-" TYPE_ARM_CPU);
snprintf(name, NAME_SIZE, "cpu%d", i);
object_property_add_child(obj, name, OBJECT(&s->cpu[i]), NULL);
}
object_initialize(&s->a9mpcore, sizeof(s->a9mpcore), TYPE_A9MPCORE_PRIV);
qdev_set_parent_bus(DEVICE(&s->a9mpcore), sysbus_get_default());
object_property_add_child(obj, "a9mpcore", OBJECT(&s->a9mpcore), NULL);
object_initialize(&s->ccm, sizeof(s->ccm), TYPE_IMX6_CCM);
qdev_set_parent_bus(DEVICE(&s->ccm), sysbus_get_default());
object_property_add_child(obj, "ccm", OBJECT(&s->ccm), NULL);
object_initialize(&s->src, sizeof(s->src), TYPE_IMX6_SRC);
qdev_set_parent_bus(DEVICE(&s->src), sysbus_get_default());
object_property_add_child(obj, "src", OBJECT(&s->src), NULL);
for (i = 0; i < FSL_IMX6_NUM_UARTS; i++) {
object_initialize(&s->uart[i], sizeof(s->uart[i]), TYPE_IMX_SERIAL);
qdev_set_parent_bus(DEVICE(&s->uart[i]), sysbus_get_default());
snprintf(name, NAME_SIZE, "uart%d", i + 1);
object_property_add_child(obj, name, OBJECT(&s->uart[i]), NULL);
}
object_initialize(&s->gpt, sizeof(s->gpt), TYPE_IMX6_GPT);
qdev_set_parent_bus(DEVICE(&s->gpt), sysbus_get_default());
object_property_add_child(obj, "gpt", OBJECT(&s->gpt), NULL);
for (i = 0; i < FSL_IMX6_NUM_EPITS; i++) {
object_initialize(&s->epit[i], sizeof(s->epit[i]), TYPE_IMX_EPIT);
qdev_set_parent_bus(DEVICE(&s->epit[i]), sysbus_get_default());
snprintf(name, NAME_SIZE, "epit%d", i + 1);
object_property_add_child(obj, name, OBJECT(&s->epit[i]), NULL);
}
for (i = 0; i < FSL_IMX6_NUM_I2CS; i++) {
object_initialize(&s->i2c[i], sizeof(s->i2c[i]), TYPE_IMX_I2C);
qdev_set_parent_bus(DEVICE(&s->i2c[i]), sysbus_get_default());
snprintf(name, NAME_SIZE, "i2c%d", i + 1);
object_property_add_child(obj, name, OBJECT(&s->i2c[i]), NULL);
}
for (i = 0; i < FSL_IMX6_NUM_GPIOS; i++) {
object_initialize(&s->gpio[i], sizeof(s->gpio[i]), TYPE_IMX_GPIO);
qdev_set_parent_bus(DEVICE(&s->gpio[i]), sysbus_get_default());
snprintf(name, NAME_SIZE, "gpio%d", i + 1);
object_property_add_child(obj, name, OBJECT(&s->gpio[i]), NULL);
}
for (i = 0; i < FSL_IMX6_NUM_ESDHCS; i++) {
object_initialize(&s->esdhc[i], sizeof(s->esdhc[i]), TYPE_SYSBUS_SDHCI);
qdev_set_parent_bus(DEVICE(&s->esdhc[i]), sysbus_get_default());
snprintf(name, NAME_SIZE, "sdhc%d", i + 1);
object_property_add_child(obj, name, OBJECT(&s->esdhc[i]), NULL);
}
for (i = 0; i < FSL_IMX6_NUM_ECSPIS; i++) {
object_initialize(&s->spi[i], sizeof(s->spi[i]), TYPE_IMX_SPI);
qdev_set_parent_bus(DEVICE(&s->spi[i]), sysbus_get_default());
snprintf(name, NAME_SIZE, "spi%d", i + 1);
object_property_add_child(obj, name, OBJECT(&s->spi[i]), NULL);
}
object_initialize(&s->eth, sizeof(s->eth), TYPE_IMX_ENET);
qdev_set_parent_bus(DEVICE(&s->eth), sysbus_get_default());
object_property_add_child(obj, "eth", OBJECT(&s->eth), NULL);
}
static void fsl_imx6_realize(DeviceState *dev, Error **errp)
{
FslIMX6State *s = FSL_IMX6(dev);
uint16_t i;
Error *err = NULL;
for (i = 0; i < smp_cpus; i++) {
/* On uniprocessor, the CBAR is set to 0 */
if (smp_cpus > 1) {
object_property_set_int(OBJECT(&s->cpu[i]), FSL_IMX6_A9MPCORE_ADDR,
"reset-cbar", &error_abort);
}
/* All CPU but CPU 0 start in power off mode */
if (i) {
object_property_set_bool(OBJECT(&s->cpu[i]), true,
"start-powered-off", &error_abort);
}
object_property_set_bool(OBJECT(&s->cpu[i]), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
}
object_property_set_int(OBJECT(&s->a9mpcore), smp_cpus, "num-cpu",
&error_abort);
object_property_set_int(OBJECT(&s->a9mpcore),
FSL_IMX6_MAX_IRQ + GIC_INTERNAL, "num-irq",
&error_abort);
object_property_set_bool(OBJECT(&s->a9mpcore), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->a9mpcore), 0, FSL_IMX6_A9MPCORE_ADDR);
for (i = 0; i < smp_cpus; i++) {
sysbus_connect_irq(SYS_BUS_DEVICE(&s->a9mpcore), i,
qdev_get_gpio_in(DEVICE(&s->cpu[i]), ARM_CPU_IRQ));
sysbus_connect_irq(SYS_BUS_DEVICE(&s->a9mpcore), i + smp_cpus,
qdev_get_gpio_in(DEVICE(&s->cpu[i]), ARM_CPU_FIQ));
}
object_property_set_bool(OBJECT(&s->ccm), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->ccm), 0, FSL_IMX6_CCM_ADDR);
object_property_set_bool(OBJECT(&s->src), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->src), 0, FSL_IMX6_SRC_ADDR);
/* Initialize all UARTs */
for (i = 0; i < FSL_IMX6_NUM_UARTS; i++) {
static const struct {
hwaddr addr;
unsigned int irq;
} serial_table[FSL_IMX6_NUM_UARTS] = {
{ FSL_IMX6_UART1_ADDR, FSL_IMX6_UART1_IRQ },
{ FSL_IMX6_UART2_ADDR, FSL_IMX6_UART2_IRQ },
{ FSL_IMX6_UART3_ADDR, FSL_IMX6_UART3_IRQ },
{ FSL_IMX6_UART4_ADDR, FSL_IMX6_UART4_IRQ },
{ FSL_IMX6_UART5_ADDR, FSL_IMX6_UART5_IRQ },
};
if (i < MAX_SERIAL_PORTS) {
CharDriverState *chr;
chr = serial_hds[i];
if (!chr) {
char *label = g_strdup_printf("imx6.uart%d", i + 1);
chr = qemu_chr_new(label, "null");
g_free(label);
serial_hds[i] = chr;
}
qdev_prop_set_chr(DEVICE(&s->uart[i]), "chardev", chr);
}
object_property_set_bool(OBJECT(&s->uart[i]), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->uart[i]), 0, serial_table[i].addr);
sysbus_connect_irq(SYS_BUS_DEVICE(&s->uart[i]), 0,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
serial_table[i].irq));
}
s->gpt.ccm = IMX_CCM(&s->ccm);
object_property_set_bool(OBJECT(&s->gpt), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->gpt), 0, FSL_IMX6_GPT_ADDR);
sysbus_connect_irq(SYS_BUS_DEVICE(&s->gpt), 0,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
FSL_IMX6_GPT_IRQ));
/* Initialize all EPIT timers */
for (i = 0; i < FSL_IMX6_NUM_EPITS; i++) {
static const struct {
hwaddr addr;
unsigned int irq;
} epit_table[FSL_IMX6_NUM_EPITS] = {
{ FSL_IMX6_EPIT1_ADDR, FSL_IMX6_EPIT1_IRQ },
{ FSL_IMX6_EPIT2_ADDR, FSL_IMX6_EPIT2_IRQ },
};
s->epit[i].ccm = IMX_CCM(&s->ccm);
object_property_set_bool(OBJECT(&s->epit[i]), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->epit[i]), 0, epit_table[i].addr);
sysbus_connect_irq(SYS_BUS_DEVICE(&s->epit[i]), 0,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
epit_table[i].irq));
}
/* Initialize all I2C */
for (i = 0; i < FSL_IMX6_NUM_I2CS; i++) {
static const struct {
hwaddr addr;
unsigned int irq;
} i2c_table[FSL_IMX6_NUM_I2CS] = {
{ FSL_IMX6_I2C1_ADDR, FSL_IMX6_I2C1_IRQ },
{ FSL_IMX6_I2C2_ADDR, FSL_IMX6_I2C2_IRQ },
{ FSL_IMX6_I2C3_ADDR, FSL_IMX6_I2C3_IRQ }
};
object_property_set_bool(OBJECT(&s->i2c[i]), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->i2c[i]), 0, i2c_table[i].addr);
sysbus_connect_irq(SYS_BUS_DEVICE(&s->i2c[i]), 0,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
i2c_table[i].irq));
}
/* Initialize all GPIOs */
for (i = 0; i < FSL_IMX6_NUM_GPIOS; i++) {
static const struct {
hwaddr addr;
unsigned int irq_low;
unsigned int irq_high;
} gpio_table[FSL_IMX6_NUM_GPIOS] = {
{
FSL_IMX6_GPIO1_ADDR,
FSL_IMX6_GPIO1_LOW_IRQ,
FSL_IMX6_GPIO1_HIGH_IRQ
},
{
FSL_IMX6_GPIO2_ADDR,
FSL_IMX6_GPIO2_LOW_IRQ,
FSL_IMX6_GPIO2_HIGH_IRQ
},
{
FSL_IMX6_GPIO3_ADDR,
FSL_IMX6_GPIO3_LOW_IRQ,
FSL_IMX6_GPIO3_HIGH_IRQ
},
{
FSL_IMX6_GPIO4_ADDR,
FSL_IMX6_GPIO4_LOW_IRQ,
FSL_IMX6_GPIO4_HIGH_IRQ
},
{
FSL_IMX6_GPIO5_ADDR,
FSL_IMX6_GPIO5_LOW_IRQ,
FSL_IMX6_GPIO5_HIGH_IRQ
},
{
FSL_IMX6_GPIO6_ADDR,
FSL_IMX6_GPIO6_LOW_IRQ,
FSL_IMX6_GPIO6_HIGH_IRQ
},
{
FSL_IMX6_GPIO7_ADDR,
FSL_IMX6_GPIO7_LOW_IRQ,
FSL_IMX6_GPIO7_HIGH_IRQ
},
};
object_property_set_bool(OBJECT(&s->gpio[i]), true, "has-edge-sel",
&error_abort);
object_property_set_bool(OBJECT(&s->gpio[i]), true, "has-upper-pin-irq",
&error_abort);
object_property_set_bool(OBJECT(&s->gpio[i]), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->gpio[i]), 0, gpio_table[i].addr);
sysbus_connect_irq(SYS_BUS_DEVICE(&s->gpio[i]), 0,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
gpio_table[i].irq_low));
sysbus_connect_irq(SYS_BUS_DEVICE(&s->gpio[i]), 1,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
gpio_table[i].irq_high));
}
/* Initialize all SDHC */
for (i = 0; i < FSL_IMX6_NUM_ESDHCS; i++) {
static const struct {
hwaddr addr;
unsigned int irq;
} esdhc_table[FSL_IMX6_NUM_ESDHCS] = {
{ FSL_IMX6_uSDHC1_ADDR, FSL_IMX6_uSDHC1_IRQ },
{ FSL_IMX6_uSDHC2_ADDR, FSL_IMX6_uSDHC2_IRQ },
{ FSL_IMX6_uSDHC3_ADDR, FSL_IMX6_uSDHC3_IRQ },
{ FSL_IMX6_uSDHC4_ADDR, FSL_IMX6_uSDHC4_IRQ },
};
object_property_set_bool(OBJECT(&s->esdhc[i]), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->esdhc[i]), 0, esdhc_table[i].addr);
sysbus_connect_irq(SYS_BUS_DEVICE(&s->esdhc[i]), 0,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
esdhc_table[i].irq));
}
/* Initialize all ECSPI */
for (i = 0; i < FSL_IMX6_NUM_ECSPIS; i++) {
static const struct {
hwaddr addr;
unsigned int irq;
} spi_table[FSL_IMX6_NUM_ECSPIS] = {
{ FSL_IMX6_eCSPI1_ADDR, FSL_IMX6_ECSPI1_IRQ },
{ FSL_IMX6_eCSPI2_ADDR, FSL_IMX6_ECSPI2_IRQ },
{ FSL_IMX6_eCSPI3_ADDR, FSL_IMX6_ECSPI3_IRQ },
{ FSL_IMX6_eCSPI4_ADDR, FSL_IMX6_ECSPI4_IRQ },
{ FSL_IMX6_eCSPI5_ADDR, FSL_IMX6_ECSPI5_IRQ },
};
/* Initialize the SPI */
object_property_set_bool(OBJECT(&s->spi[i]), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->spi[i]), 0, spi_table[i].addr);
sysbus_connect_irq(SYS_BUS_DEVICE(&s->spi[i]), 0,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
spi_table[i].irq));
}
object_property_set_bool(OBJECT(&s->eth), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
sysbus_mmio_map(SYS_BUS_DEVICE(&s->eth), 0, FSL_IMX6_ENET_ADDR);
sysbus_connect_irq(SYS_BUS_DEVICE(&s->eth), 0,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
FSL_IMX6_ENET_MAC_IRQ));
sysbus_connect_irq(SYS_BUS_DEVICE(&s->eth), 1,
qdev_get_gpio_in(DEVICE(&s->a9mpcore),
FSL_IMX6_ENET_MAC_1588_IRQ));
/* ROM memory */
memory_region_init_rom(&s->rom, NULL, "imx6.rom",
FSL_IMX6_ROM_SIZE, &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(get_system_memory(), FSL_IMX6_ROM_ADDR,
&s->rom);
/* CAAM memory */
memory_region_init_rom(&s->caam, NULL, "imx6.caam",
FSL_IMX6_CAAM_MEM_SIZE, &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(get_system_memory(), FSL_IMX6_CAAM_MEM_ADDR,
&s->caam);
/* OCRAM memory */
memory_region_init_ram(&s->ocram, NULL, "imx6.ocram", FSL_IMX6_OCRAM_SIZE,
&err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(get_system_memory(), FSL_IMX6_OCRAM_ADDR,
&s->ocram);
vmstate_register_ram_global(&s->ocram);
/* internal OCRAM (256 KB) is aliased over 1 MB */
memory_region_init_alias(&s->ocram_alias, NULL, "imx6.ocram_alias",
&s->ocram, 0, FSL_IMX6_OCRAM_ALIAS_SIZE);
memory_region_add_subregion(get_system_memory(), FSL_IMX6_OCRAM_ALIAS_ADDR,
&s->ocram_alias);
}
static void fsl_imx6_class_init(ObjectClass *oc, void *data)
{
DeviceClass *dc = DEVICE_CLASS(oc);
dc->realize = fsl_imx6_realize;
/*
* Reason: creates an ARM CPU, thus use after free(), see
* arm_cpu_class_init()
*/
dc->cannot_destroy_with_object_finalize_yet = true;
dc->desc = "i.MX6 SOC";
}
static const TypeInfo fsl_imx6_type_info = {
.name = TYPE_FSL_IMX6,
.parent = TYPE_DEVICE,
.instance_size = sizeof(FslIMX6State),
.instance_init = fsl_imx6_init,
.class_init = fsl_imx6_class_init,
};
static void fsl_imx6_register_types(void)
{
type_register_static(&fsl_imx6_type_info);
}
type_init(fsl_imx6_register_types)
| SurajAnil/KernelVirtualMachine | qemu/hw/arm/fsl-imx6.c | C | gpl-3.0 | 16,731 |
# -*- coding: utf-8 -*-
"""
pygments.lexers.qvt
~~~~~~~~~~~~~~~~~~~
Lexer for QVT Operational language.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups, include, combined, default, \
words
from pygments.token import Text, Comment, Operator, Keyword, Punctuation, \
Name, String, Number
__all__ = ['QVToLexer']
class QVToLexer(RegexLexer):
u"""
For the `QVT Operational Mapping language <http://www.omg.org/spec/QVT/1.1/>`_.
Reference for implementing this: «Meta Object Facility (MOF) 2.0
Query/View/Transformation Specification», Version 1.1 - January 2011
(http://www.omg.org/spec/QVT/1.1/), see §8.4, «Concrete Syntax» in
particular.
Notable tokens assignments:
- Name.Class is assigned to the identifier following any of the following
keywords: metamodel, class, exception, primitive, enum, transformation
or library
- Name.Function is assigned to the names of mappings and queries
- Name.Builtin.Pseudo is assigned to the pre-defined variables 'this',
'self' and 'result'.
"""
# With obvious borrowings & inspiration from the Java, Python and C lexers
name = 'QVTO'
aliases = ['qvto', 'qvt']
filenames = ['*.qvto']
tokens = {
'root': [
(r'\n', Text),
(r'[^\S\n]+', Text),
(r'(--|//)(\s*)(directive:)?(.*)$',
bygroups(Comment, Comment, Comment.Preproc, Comment)),
# Uncomment the following if you want to distinguish between
# '/*' and '/**', à la javadoc
# (r'/[*]{2}(.|\n)*?[*]/', Comment.Multiline),
(r'/[*](.|\n)*?[*]/', Comment.Multiline),
(r'\\\n', Text),
(r'(and|not|or|xor|##?)\b', Operator.Word),
(r'(:{1,2}=|[-+]=)\b', Operator.Word),
(r'(@|<<|>>)\b', Keyword), # stereotypes
(r'!=|<>|==|=|!->|->|>=|<=|[.]{3}|[+/*%=<>&|.~]', Operator),
(r'[]{}:(),;[]', Punctuation),
(r'(true|false|unlimited|null)\b', Keyword.Constant),
(r'(this|self|result)\b', Name.Builtin.Pseudo),
(r'(var)\b', Keyword.Declaration),
(r'(from|import)\b', Keyword.Namespace, 'fromimport'),
(r'(metamodel|class|exception|primitive|enum|transformation|'
r'library)(\s+)(\w+)',
bygroups(Keyword.Word, Text, Name.Class)),
(r'(exception)(\s+)(\w+)',
bygroups(Keyword.Word, Text, Name.Exception)),
(r'(main)\b', Name.Function),
(r'(mapping|helper|query)(\s+)',
bygroups(Keyword.Declaration, Text), 'operation'),
(r'(assert)(\s+)\b', bygroups(Keyword, Text), 'assert'),
(r'(Bag|Collection|Dict|OrderedSet|Sequence|Set|Tuple|List)\b',
Keyword.Type),
include('keywords'),
('"', String, combined('stringescape', 'dqs')),
("'", String, combined('stringescape', 'sqs')),
include('name'),
include('numbers'),
# (r'([a-zA-Z_]\w*)(::)([a-zA-Z_]\w*)',
# bygroups(Text, Text, Text)),
],
'fromimport': [
(r'(?:[ \t]|\\\n)+', Text),
(r'[a-zA-Z_][\w.]*', Name.Namespace),
default('#pop'),
],
'operation': [
(r'::', Text),
(r'(.*::)([a-zA-Z_]\w*)([ \t]*)(\()',
bygroups(Text, Name.Function, Text, Punctuation), '#pop')
],
'assert': [
(r'(warning|error|fatal)\b', Keyword, '#pop'),
default('#pop'), # all else: go back
],
'keywords': [
(words((
'abstract', 'access', 'any', 'assert', 'blackbox', 'break',
'case', 'collect', 'collectNested', 'collectOne', 'collectselect',
'collectselectOne', 'composes', 'compute', 'configuration',
'constructor', 'continue', 'datatype', 'default', 'derived',
'disjuncts', 'do', 'elif', 'else', 'end', 'endif', 'except',
'exists', 'extends', 'forAll', 'forEach', 'forOne', 'from', 'if',
'implies', 'in', 'inherits', 'init', 'inout', 'intermediate',
'invresolve', 'invresolveIn', 'invresolveone', 'invresolveoneIn',
'isUnique', 'iterate', 'late', 'let', 'literal', 'log', 'map',
'merges', 'modeltype', 'new', 'object', 'one', 'ordered', 'out',
'package', 'population', 'property', 'raise', 'readonly',
'references', 'refines', 'reject', 'resolve', 'resolveIn',
'resolveone', 'resolveoneIn', 'return', 'select', 'selectOne',
'sortedBy', 'static', 'switch', 'tag', 'then', 'try', 'typedef',
'unlimited', 'uses', 'when', 'where', 'while', 'with', 'xcollect',
'xmap', 'xselect'), suffix=r'\b'), Keyword),
],
# There is no need to distinguish between String.Single and
# String.Double: 'strings' is factorised for 'dqs' and 'sqs'
'strings': [
(r'[^\\\'"\n]+', String),
# quotes, percents and backslashes must be parsed one at a time
(r'[\'"\\]', String),
],
'stringescape': [
(r'\\([\\btnfr"\']|u[0-3][0-7]{2}|u[0-7]{1,2})', String.Escape)
],
'dqs': [ # double-quoted string
(r'"', String, '#pop'),
(r'\\\\|\\"', String.Escape),
include('strings')
],
'sqs': [ # single-quoted string
(r"'", String, '#pop'),
(r"\\\\|\\'", String.Escape),
include('strings')
],
'name': [
(r'[a-zA-Z_]\w*', Name),
],
# numbers: excerpt taken from the python lexer
'numbers': [
(r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float),
(r'\d+[eE][+-]?[0-9]+', Number.Float),
(r'\d+', Number.Integer)
],
}
| unreal666/outwiker | plugins/source/source/pygments/lexers/qvt.py | Python | gpl-3.0 | 6,097 |
//--- Aura Script -----------------------------------------------------------
// [PQ] Hunt Down the Brown Bears (10)
//--- Description -----------------------------------------------------------
// Party quest to kill certain monsters.
//---------------------------------------------------------------------------
public class BrownBear10PartyQuest : QuestScript
{
public override void Load()
{
SetId(100019);
SetScrollId(70025);
SetName(L("[PQ] Hunt Down the Brown Bears"));
SetDescription(L("They say that there is a [brown bear in the plains far away from town]. Supposedly, the Brown Bears have tremendous power. Will you please hunt [10 brown bears]?"));
SetType(QuestType.Collect);
SetCancelable(true);
SetIcon(QuestIcon.Party);
if (IsEnabled("QuestViewRenewal"))
SetCategory(QuestCategory.Repeat);
AddObjective("obj", L("Hunt 10 Brown Bears"), 0, 0, 0, Kill(10, "/brownbear/"));
AddReward(Exp(255));
AddReward(Gold(564));
AddReward(QuestScroll(100020)); // [PQ] Hunt Down the Brown Bears (30)
}
}
| piersonjon/aura | system/scripts/quests/party/100019_brown_bear_10.cs | C# | gpl-3.0 | 1,038 |
/*
* transform: A jQuery cssHooks adding cross-browser 2d transform capabilities to $.fn.css() and $.fn.animate()
*
* limitations:
* - requires jQuery 1.4.3+
* - Should you use the *translate* property, then your elements need to be absolutely positionned in a relatively positionned wrapper **or it will fail in IE678**.
* - transformOrigin is not accessible
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery.transform.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*
* This saved you an hour of work?
* Send me music http://www.amazon.co.uk/wishlist/HNTU0468LQON
*
*/
(function( $ ) {
/*
* Feature tests and global variables
*/
var div = document.createElement('div'),
divStyle = div.style,
propertyName = 'transform',
suffix = 'Transform',
testProperties = [
'O' + suffix,
'ms' + suffix,
'Webkit' + suffix,
'Moz' + suffix,
// prefix-less property
propertyName
],
i = testProperties.length,
supportProperty,
supportMatrixFilter,
propertyHook,
propertyGet,
rMatrix = /Matrix([^)]*)/;
// test different vendor prefixes of this property
while ( i-- ) {
if ( testProperties[i] in divStyle ) {
$.support[propertyName] = supportProperty = testProperties[i];
continue;
}
}
// IE678 alternative
if ( !supportProperty ) {
$.support.matrixFilter = supportMatrixFilter = divStyle.filter === '';
}
// prevent IE memory leak
div = divStyle = null;
// px isn't the default unit of this property
$.cssNumber[propertyName] = true;
/*
* fn.css() hooks
*/
if ( supportProperty && supportProperty != propertyName ) {
// Modern browsers can use jQuery.cssProps as a basic hook
$.cssProps[propertyName] = supportProperty;
// Firefox needs a complete hook because it stuffs matrix with 'px'
if ( supportProperty == 'Moz' + suffix ) {
propertyHook = {
get: function( elem, computed ) {
return (computed ?
// remove 'px' from the computed matrix
$.css( elem, supportProperty ).split('px').join(''):
elem.style[supportProperty]
)
},
set: function( elem, value ) {
// remove 'px' from matrices
elem.style[supportProperty] = /matrix[^)p]*\)/.test(value) ?
value.replace(/matrix((?:[^,]*,){4})([^,]*),([^)]*)/, 'matrix$1$2px,$3px'):
value;
}
}
/* Fix two jQuery bugs still present in 1.5.1
* - rupper is incompatible with IE9, see http://jqbug.com/8346
* - jQuery.css is not really jQuery.cssProps aware, see http://jqbug.com/8402
*/
} else if ( /^1\.[0-5](?:\.|$)/.test($.fn.jquery) ) {
propertyHook = {
get: function( elem, computed ) {
return (computed ?
$.css( elem, supportProperty.replace(/^ms/, 'Ms') ):
elem.style[supportProperty]
)
}
}
}
/* TODO: leverage hardware acceleration of 3d transform in Webkit only
else if ( supportProperty == 'Webkit' + suffix && support3dTransform ) {
propertyHook = {
set: function( elem, value ) {
elem.style[supportProperty] =
value.replace();
}
}
}*/
} else if ( supportMatrixFilter ) {
propertyHook = {
get: function( elem, computed ) {
var elemStyle = ( computed && elem.currentStyle ? elem.currentStyle : elem.style ),
matrix;
if ( elemStyle && rMatrix.test( elemStyle.filter ) ) {
matrix = RegExp.$1.split(',');
matrix = [
matrix[0].split('=')[1],
matrix[2].split('=')[1],
matrix[1].split('=')[1],
matrix[3].split('=')[1]
];
} else {
matrix = [1,0,0,1];
}
matrix[4] = elemStyle ? elemStyle.left : 0;
matrix[5] = elemStyle ? elemStyle.top : 0;
return "matrix(" + matrix + ")";
},
set: function( elem, value, animate ) {
var elemStyle = elem.style,
currentStyle,
Matrix,
filter;
if ( !animate ) {
elemStyle.zoom = 1;
}
value = matrix(value);
// rotate, scale and skew
if ( !animate || animate.M ) {
Matrix = [
"Matrix("+
"M11="+value[0],
"M12="+value[2],
"M21="+value[1],
"M22="+value[3],
"SizingMethod='auto expand'"
].join();
filter = ( currentStyle = elem.currentStyle ) && currentStyle.filter || elemStyle.filter || "";
elemStyle.filter = rMatrix.test(filter) ?
filter.replace(rMatrix, Matrix) :
filter + " progid:DXImageTransform.Microsoft." + Matrix + ")";
// center the transform origin, from pbakaus's Transformie http://github.com/pbakaus/transformie
if ( (centerOrigin = $.transform.centerOrigin) ) {
elemStyle[centerOrigin == 'margin' ? 'marginLeft' : 'left'] = -(elem.offsetWidth/2) + (elem.clientWidth/2) + 'px';
elemStyle[centerOrigin == 'margin' ? 'marginTop' : 'top'] = -(elem.offsetHeight/2) + (elem.clientHeight/2) + 'px';
}
}
// translate
if ( !animate || animate.T ) {
// We assume that the elements are absolute positionned inside a relative positionned wrapper
elemStyle.left = value[4] + 'px';
elemStyle.top = value[5] + 'px';
}
}
}
}
// populate jQuery.cssHooks with the appropriate hook if necessary
if ( propertyHook ) {
$.cssHooks[propertyName] = propertyHook;
}
// we need a unique setter for the animation logic
propertyGet = propertyHook && propertyHook.get || $.css;
/*
* fn.animate() hooks
*/
$.fx.step.transform = function( fx ) {
var elem = fx.elem,
start = fx.start,
end = fx.end,
split,
pos = fx.pos,
transform,
translate,
rotate,
scale,
skew,
T = false,
M = false,
prop;
translate = rotate = scale = skew = '';
// fx.end and fx.start need to be converted to their translate/rotate/scale/skew components
// so that we can interpolate them
if ( !start || typeof start === "string" ) {
// the following block can be commented out with jQuery 1.5.1+, see #7912
if (!start) {
start = propertyGet( elem, supportProperty );
}
// force layout only once per animation
if ( supportMatrixFilter ) {
elem.style.zoom = 1;
}
// if the start computed matrix is in end, we are doing a relative animation
split = end.split(start);
if ( split.length == 2 ) {
// remove the start computed matrix to make animations more accurate
end = split.join('');
fx.origin = start;
start = 'none';
}
// start is either 'none' or a matrix(...) that has to be parsed
fx.start = start = start == 'none'?
{
translate: [0,0],
rotate: 0,
scale: [1,1],
skew: [0,0]
}:
unmatrix( toArray(start) );
// fx.end has to be parsed and decomposed
fx.end = end = ~end.indexOf('matrix')?
// bullet-proof parser
unmatrix(matrix(end)):
// faster and more precise parser
components(end);
// get rid of properties that do not change
for ( prop in start) {
if ( prop == 'rotate' ?
start[prop] == end[prop]:
start[prop][0] == end[prop][0] && start[prop][1] == end[prop][1]
) {
delete start[prop];
}
}
}
/*
* We want a fast interpolation algorithm.
* This implies avoiding function calls and sacrifying DRY principle:
* - avoid $.each(function(){})
* - round values using bitewise hacks, see http://jsperf.com/math-round-vs-hack/3
*/
if ( start.translate ) {
// round translate to the closest pixel
translate = ' translate('+
((start.translate[0] + (end.translate[0] - start.translate[0]) * pos + .5) | 0) +'px,'+
((start.translate[1] + (end.translate[1] - start.translate[1]) * pos + .5) | 0) +'px'+
')';
T = true;
}
if ( start.rotate != undefined ) {
rotate = ' rotate('+ (start.rotate + (end.rotate - start.rotate) * pos) +'rad)';
M = true;
}
if ( start.scale ) {
scale = ' scale('+
(start.scale[0] + (end.scale[0] - start.scale[0]) * pos) +','+
(start.scale[1] + (end.scale[1] - start.scale[1]) * pos) +
')';
M = true;
}
if ( start.skew ) {
skew = ' skew('+
(start.skew[0] + (end.skew[0] - start.skew[0]) * pos) +'rad,'+
(start.skew[1] + (end.skew[1] - start.skew[1]) * pos) +'rad'+
')';
M = true;
}
// In case of relative animation, restore the origin computed matrix here.
transform = fx.origin ?
fx.origin + translate + skew + scale + rotate:
translate + rotate + scale + skew;
propertyHook && propertyHook.set ?
propertyHook.set( elem, transform, {M: M, T: T} ):
elem.style[supportProperty] = transform;
};
/*
* Utility functions
*/
// turns a transform string into its 'matrix(A,B,C,D,X,Y)' form (as an array, though)
function matrix( transform ) {
transform = transform.split(')');
var
trim = $.trim
// last element of the array is an empty string, get rid of it
, i = transform.length -1
, split, prop, val
, A = 1
, B = 0
, C = 0
, D = 1
, A_, B_, C_, D_
, tmp1, tmp2
, X = 0
, Y = 0
;
// Loop through the transform properties, parse and multiply them
while (i--) {
split = transform[i].split('(');
prop = trim(split[0]);
val = split[1];
A_ = B_ = C_ = D_ = 0;
switch (prop) {
case 'translateX':
X += parseInt(val, 10);
continue;
case 'translateY':
Y += parseInt(val, 10);
continue;
case 'translate':
val = val.split(',');
X += parseInt(val[0], 10);
Y += parseInt(val[1] || 0, 10);
continue;
case 'rotate':
val = toRadian(val);
A_ = Math.cos(val);
B_ = Math.sin(val);
C_ = -Math.sin(val);
D_ = Math.cos(val);
break;
case 'scaleX':
A_ = val;
D_ = 1;
break;
case 'scaleY':
A_ = 1;
D_ = val;
break;
case 'scale':
val = val.split(',');
A_ = val[0];
D_ = val.length>1 ? val[1] : val[0];
break;
case 'skewX':
A_ = D_ = 1;
C_ = Math.tan(toRadian(val));
break;
case 'skewY':
A_ = D_ = 1;
B_ = Math.tan(toRadian(val));
break;
case 'skew':
A_ = D_ = 1;
val = val.split(',');
C_ = Math.tan(toRadian(val[0]));
B_ = Math.tan(toRadian(val[1] || 0));
break;
case 'matrix':
val = val.split(',');
A_ = +val[0];
B_ = +val[1];
C_ = +val[2];
D_ = +val[3];
X += parseInt(val[4], 10);
Y += parseInt(val[5], 10);
}
// Matrix product
tmp1 = A * A_ + B * C_;
B = A * B_ + B * D_;
tmp2 = C * A_ + D * C_;
D = C * B_ + D * D_;
A = tmp1;
C = tmp2;
}
return [A,B,C,D,X,Y];
}
// turns a matrix into its rotate, scale and skew components
// algorithm from http://hg.mozilla.org/mozilla-central/file/7cb3e9795d04/layout/style/nsStyleAnimation.cpp
function unmatrix(matrix) {
var
scaleX
, scaleY
, skew
, A = matrix[0]
, B = matrix[1]
, C = matrix[2]
, D = matrix[3]
;
// Make sure matrix is not singular
if ( A * D - B * C ) {
// step (3)
scaleX = Math.sqrt( A * A + B * B );
A /= scaleX;
B /= scaleX;
// step (4)
skew = A * C + B * D;
C -= A * skew;
D -= B * skew;
// step (5)
scaleY = Math.sqrt( C * C + D * D );
C /= scaleY;
D /= scaleY;
skew /= scaleY;
// step (6)
if ( A * D < B * C ) {
//scaleY = -scaleY;
//skew = -skew;
A = -A;
B = -B;
skew = -skew;
scaleX = -scaleX;
}
// matrix is singular and cannot be interpolated
} else {
rotate = scaleX = scaleY = skew = 0;
}
return {
translate: [+matrix[4], +matrix[5]],
rotate: Math.atan2(B, A),
scale: [scaleX, scaleY],
skew: [skew, 0]
}
}
// parse tranform components of a transform string not containing 'matrix(...)'
function components( transform ) {
// split the != transforms
transform = transform.split(')');
var translate = [0,0],
rotate = 0,
scale = [1,1],
skew = [0,0],
i = transform.length -1,
trim = $.trim,
split, name, value;
// add components
while ( i-- ) {
split = transform[i].split('(');
name = trim(split[0]);
value = split[1];
if (name == 'translateX') {
translate[0] += parseInt(value, 10);
} else if (name == 'translateY') {
translate[1] += parseInt(value, 10);
} else if (name == 'translate') {
value = value.split(',');
translate[0] += parseInt(value[0], 10);
translate[1] += parseInt(value[1] || 0, 10);
} else if (name == 'rotate') {
rotate += toRadian(value);
} else if (name == 'scaleX') {
scale[0] *= value;
} else if (name == 'scaleY') {
scale[1] *= value;
} else if (name == 'scale') {
value = value.split(',');
scale[0] *= value[0];
scale[1] *= (value.length>1? value[1] : value[0]);
} else if (name == 'skewX') {
skew[0] += toRadian(value);
} else if (name == 'skewY') {
skew[1] += toRadian(value);
} else if (name == 'skew') {
value = value.split(',');
skew[0] += toRadian(value[0]);
skew[1] += toRadian(value[1] || '0');
}
}
return {
translate: translate,
rotate: rotate,
scale: scale,
skew: skew
};
}
// converts an angle string in any unit to a radian Float
function toRadian(value) {
return ~value.indexOf('deg') ?
parseInt(value,10) * (Math.PI * 2 / 360):
~value.indexOf('grad') ?
parseInt(value,10) * (Math.PI/200):
parseFloat(value);
}
// Converts 'matrix(A,B,C,D,X,Y)' to [A,B,C,D,X,Y]
function toArray(matrix) {
// Fremove the unit of X and Y for Firefox
matrix = /\(([^,]*),([^,]*),([^,]*),([^,]*),([^,p]*)(?:px)?,([^)p]*)(?:px)?/.exec(matrix);
return [matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6]];
}
$.transform = {
centerOrigin: 'margin'
};
})( jQuery ); | miracee/rasdaman | applications/raswct/lib/gauges/transform.js | JavaScript | gpl-3.0 | 13,790 |
/* $OpenBSD: authfile.c,v 1.92 2011/06/14 22:49:18 markus Exp $ */
/*
* Author: Tatu Ylonen <[email protected]>
* Copyright (c) 1995 Tatu Ylonen <[email protected]>, Espoo, Finland
* All rights reserved
* This file contains functions for reading and writing identity files, and
* for reading the passphrase from the user.
*
* As far as I am concerned, the code I have written for this software
* can be used freely for any purpose. Any derived versions of this
* software must be clearly marked as such, and if the derived work is
* incompatible with the protocol description in the RFC file, it must be
* called by a name other than "ssh" or "Secure Shell".
*
*
* Copyright (c) 2000 Markus Friedl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#include "includes.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/uio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
/* compatibility with old or broken OpenSSL versions */
#include "openbsd-compat/openssl-compat.h"
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "xmalloc.h"
#include "cipher.h"
#include "buffer.h"
#include "key.h"
#include "ssh.h"
#include "log.h"
#include "authfile.h"
#include "rsa.h"
#include "misc.h"
#include "atomicio.h"
#define MAX_KEY_FILE_SIZE (1024 * 1024)
/* Version identification string for SSH v1 identity files. */
static const char authfile_id_string[] =
"SSH PRIVATE KEY FILE FORMAT 1.1\n";
/*
* Serialises the authentication (private) key to a blob, encrypting it with
* passphrase. The identification of the blob (lowest 64 bits of n) will
* precede the key to provide identification of the key without needing a
* passphrase.
*/
static int
key_private_rsa1_to_blob(Key *key, Buffer *blob, const char *passphrase,
const char *comment)
{
Buffer buffer, encrypted;
u_char buf[100], *cp;
int i, cipher_num;
CipherContext ciphercontext;
Cipher *cipher;
u_int32_t rnd;
/*
* If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
* to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
*/
cipher_num = (strcmp(passphrase, "") == 0) ?
SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
if ((cipher = cipher_by_number(cipher_num)) == NULL)
fatal("save_private_key_rsa: bad cipher");
/* This buffer is used to built the secret part of the private key. */
buffer_init(&buffer);
/* Put checkbytes for checking passphrase validity. */
rnd = arc4random();
buf[0] = rnd & 0xff;
buf[1] = (rnd >> 8) & 0xff;
buf[2] = buf[0];
buf[3] = buf[1];
buffer_append(&buffer, buf, 4);
/*
* Store the private key (n and e will not be stored because they
* will be stored in plain text, and storing them also in encrypted
* format would just give known plaintext).
*/
buffer_put_bignum(&buffer, key->rsa->d);
buffer_put_bignum(&buffer, key->rsa->iqmp);
buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
/* Pad the part to be encrypted until its size is a multiple of 8. */
while (buffer_len(&buffer) % 8 != 0)
buffer_put_char(&buffer, 0);
/* This buffer will be used to contain the data in the file. */
buffer_init(&encrypted);
/* First store keyfile id string. */
for (i = 0; authfile_id_string[i]; i++)
buffer_put_char(&encrypted, authfile_id_string[i]);
buffer_put_char(&encrypted, 0);
/* Store cipher type. */
buffer_put_char(&encrypted, cipher_num);
buffer_put_int(&encrypted, 0); /* For future extension */
/* Store public key. This will be in plain text. */
buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
buffer_put_bignum(&encrypted, key->rsa->n);
buffer_put_bignum(&encrypted, key->rsa->e);
buffer_put_cstring(&encrypted, comment);
/* Allocate space for the private part of the key in the buffer. */
cp = buffer_append_space(&encrypted, buffer_len(&buffer));
cipher_set_key_string(&ciphercontext, cipher, passphrase,
CIPHER_ENCRYPT);
cipher_crypt(&ciphercontext, cp,
buffer_ptr(&buffer), buffer_len(&buffer));
cipher_cleanup(&ciphercontext);
memset(&ciphercontext, 0, sizeof(ciphercontext));
/* Destroy temporary data. */
memset(buf, 0, sizeof(buf));
buffer_free(&buffer);
buffer_append(blob, buffer_ptr(&encrypted), buffer_len(&encrypted));
buffer_free(&encrypted);
return 1;
}
/* convert SSH v2 key in OpenSSL PEM format */
static int
key_private_pem_to_blob(Key *key, Buffer *blob, const char *_passphrase,
const char *comment)
{
int success = 0;
int blen, len = strlen(_passphrase);
u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
#if (OPENSSL_VERSION_NUMBER < 0x00907000L)
const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
#else
const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
#endif
const u_char *bptr;
BIO *bio;
if (len > 0 && len <= 4) {
error("passphrase too short: have %d bytes, need > 4", len);
return 0;
}
if ((bio = BIO_new(BIO_s_mem())) == NULL) {
error("%s: BIO_new failed", __func__);
return 0;
}
switch (key->type) {
case KEY_DSA:
success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
cipher, passphrase, len, NULL, NULL);
break;
#ifdef OPENSSL_HAS_ECC
case KEY_ECDSA:
success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
cipher, passphrase, len, NULL, NULL);
break;
#endif
case KEY_RSA:
success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
cipher, passphrase, len, NULL, NULL);
break;
}
if (success) {
if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0)
success = 0;
else
buffer_append(blob, bptr, blen);
}
BIO_free(bio);
return success;
}
/* Save a key blob to a file */
static int
key_save_private_blob(Buffer *keybuf, const char *filename)
{
int fd;
if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) {
error("open %s failed: %s.", filename, strerror(errno));
return 0;
}
if (atomicio(vwrite, fd, buffer_ptr(keybuf),
buffer_len(keybuf)) != buffer_len(keybuf)) {
error("write to key file %s failed: %s", filename,
strerror(errno));
close(fd);
unlink(filename);
return 0;
}
close(fd);
return 1;
}
/* Serialise "key" to buffer "blob" */
static int
key_private_to_blob(Key *key, Buffer *blob, const char *passphrase,
const char *comment)
{
switch (key->type) {
case KEY_RSA1:
return key_private_rsa1_to_blob(key, blob, passphrase, comment);
case KEY_DSA:
case KEY_ECDSA:
case KEY_RSA:
return key_private_pem_to_blob(key, blob, passphrase, comment);
default:
error("%s: cannot save key type %d", __func__, key->type);
return 0;
}
}
int
key_save_private(Key *key, const char *filename, const char *passphrase,
const char *comment)
{
Buffer keyblob;
int success = 0;
buffer_init(&keyblob);
if (!key_private_to_blob(key, &keyblob, passphrase, comment))
goto out;
if (!key_save_private_blob(&keyblob, filename))
goto out;
success = 1;
out:
buffer_free(&keyblob);
return success;
}
/*
* Parse the public, unencrypted portion of a RSA1 key.
*/
static Key *
key_parse_public_rsa1(Buffer *blob, char **commentp)
{
Key *pub;
Buffer copy;
/* Check that it is at least big enough to contain the ID string. */
if (buffer_len(blob) < sizeof(authfile_id_string)) {
debug3("Truncated RSA1 identifier");
return NULL;
}
/*
* Make sure it begins with the id string. Consume the id string
* from the buffer.
*/
if (memcmp(buffer_ptr(blob), authfile_id_string,
sizeof(authfile_id_string)) != 0) {
debug3("Incorrect RSA1 identifier");
return NULL;
}
buffer_init(©);
buffer_append(©, buffer_ptr(blob), buffer_len(blob));
buffer_consume(©, sizeof(authfile_id_string));
/* Skip cipher type and reserved data. */
(void) buffer_get_char(©); /* cipher type */
(void) buffer_get_int(©); /* reserved */
/* Read the public key from the buffer. */
(void) buffer_get_int(©);
pub = key_new(KEY_RSA1);
buffer_get_bignum(©, pub->rsa->n);
buffer_get_bignum(©, pub->rsa->e);
if (commentp)
*commentp = buffer_get_string(©, NULL);
/* The encrypted private part is not parsed by this function. */
buffer_free(©);
return pub;
}
/* Load a key from a fd into a buffer */
int
key_load_file(int fd, const char *filename, Buffer *blob)
{
u_char buf[1024];
size_t len;
struct stat st;
if (fstat(fd, &st) < 0) {
error("%s: fstat of key file %.200s%sfailed: %.100s", __func__,
filename == NULL ? "" : filename,
filename == NULL ? "" : " ",
strerror(errno));
return 0;
}
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size > MAX_KEY_FILE_SIZE) {
toobig:
error("%s: key file %.200s%stoo large", __func__,
filename == NULL ? "" : filename,
filename == NULL ? "" : " ");
return 0;
}
buffer_init(blob);
for (;;) {
if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
if (errno == EPIPE)
break;
debug("%s: read from key file %.200s%sfailed: %.100s",
__func__, filename == NULL ? "" : filename,
filename == NULL ? "" : " ", strerror(errno));
buffer_clear(blob);
bzero(buf, sizeof(buf));
return 0;
}
buffer_append(blob, buf, len);
if (buffer_len(blob) > MAX_KEY_FILE_SIZE) {
buffer_clear(blob);
bzero(buf, sizeof(buf));
goto toobig;
}
}
bzero(buf, sizeof(buf));
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size != buffer_len(blob)) {
debug("%s: key file %.200s%schanged size while reading",
__func__, filename == NULL ? "" : filename,
filename == NULL ? "" : " ");
buffer_clear(blob);
return 0;
}
return 1;
}
/*
* Loads the public part of the ssh v1 key file. Returns NULL if an error was
* encountered (the file does not exist or is not readable), and the key
* otherwise.
*/
static Key *
key_load_public_rsa1(int fd, const char *filename, char **commentp)
{
Buffer buffer;
Key *pub;
buffer_init(&buffer);
if (!key_load_file(fd, filename, &buffer)) {
buffer_free(&buffer);
return NULL;
}
pub = key_parse_public_rsa1(&buffer, commentp);
if (pub == NULL)
debug3("Could not load \"%s\" as a RSA1 public key", filename);
buffer_free(&buffer);
return pub;
}
/* load public key from private-key file, works only for SSH v1 */
Key *
key_load_public_type(int type, const char *filename, char **commentp)
{
Key *pub;
int fd;
if (type == KEY_RSA1) {
fd = open(filename, O_RDONLY);
if (fd < 0)
return NULL;
pub = key_load_public_rsa1(fd, filename, commentp);
close(fd);
return pub;
}
return NULL;
}
static Key *
key_parse_private_rsa1(Buffer *blob, const char *passphrase, char **commentp)
{
int check1, check2, cipher_type;
Buffer decrypted;
u_char *cp;
CipherContext ciphercontext;
Cipher *cipher;
Key *prv = NULL;
Buffer copy;
/* Check that it is at least big enough to contain the ID string. */
if (buffer_len(blob) < sizeof(authfile_id_string)) {
debug3("Truncated RSA1 identifier");
return NULL;
}
/*
* Make sure it begins with the id string. Consume the id string
* from the buffer.
*/
if (memcmp(buffer_ptr(blob), authfile_id_string,
sizeof(authfile_id_string)) != 0) {
debug3("Incorrect RSA1 identifier");
return NULL;
}
buffer_init(©);
buffer_append(©, buffer_ptr(blob), buffer_len(blob));
buffer_consume(©, sizeof(authfile_id_string));
/* Read cipher type. */
cipher_type = buffer_get_char(©);
(void) buffer_get_int(©); /* Reserved data. */
/* Read the public key from the buffer. */
(void) buffer_get_int(©);
prv = key_new_private(KEY_RSA1);
buffer_get_bignum(©, prv->rsa->n);
buffer_get_bignum(©, prv->rsa->e);
if (commentp)
*commentp = buffer_get_string(©, NULL);
else
(void)buffer_get_string_ptr(©, NULL);
/* Check that it is a supported cipher. */
cipher = cipher_by_number(cipher_type);
if (cipher == NULL) {
debug("Unsupported RSA1 cipher %d", cipher_type);
buffer_free(©);
goto fail;
}
/* Initialize space for decrypted data. */
buffer_init(&decrypted);
cp = buffer_append_space(&decrypted, buffer_len(©));
/* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
cipher_set_key_string(&ciphercontext, cipher, passphrase,
CIPHER_DECRYPT);
cipher_crypt(&ciphercontext, cp,
buffer_ptr(©), buffer_len(©));
cipher_cleanup(&ciphercontext);
memset(&ciphercontext, 0, sizeof(ciphercontext));
buffer_free(©);
check1 = buffer_get_char(&decrypted);
check2 = buffer_get_char(&decrypted);
if (check1 != buffer_get_char(&decrypted) ||
check2 != buffer_get_char(&decrypted)) {
if (strcmp(passphrase, "") != 0)
debug("Bad passphrase supplied for RSA1 key");
/* Bad passphrase. */
buffer_free(&decrypted);
goto fail;
}
/* Read the rest of the private key. */
buffer_get_bignum(&decrypted, prv->rsa->d);
buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
/* in SSL and SSH v1 p and q are exchanged */
buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
/* calculate p-1 and q-1 */
rsa_generate_additional_parameters(prv->rsa);
buffer_free(&decrypted);
/* enable blinding */
if (RSA_blinding_on(prv->rsa, NULL) != 1) {
error("%s: RSA_blinding_on failed", __func__);
goto fail;
}
return prv;
fail:
if (commentp)
xfree(*commentp);
key_free(prv);
return NULL;
}
static Key *
key_parse_private_pem(Buffer *blob, int type, const char *passphrase,
char **commentp)
{
EVP_PKEY *pk = NULL;
Key *prv = NULL;
char *name = "<no key>";
BIO *bio;
if ((bio = BIO_new_mem_buf(buffer_ptr(blob),
buffer_len(blob))) == NULL) {
error("%s: BIO_new_mem_buf failed", __func__);
return NULL;
}
pk = PEM_read_bio_PrivateKey(bio, NULL, NULL, (char *)passphrase);
BIO_free(bio);
if (pk == NULL) {
debug("%s: PEM_read_PrivateKey failed", __func__);
(void)ERR_get_error();
} else if (pk->type == EVP_PKEY_RSA &&
(type == KEY_UNSPEC||type==KEY_RSA)) {
prv = key_new(KEY_UNSPEC);
prv->rsa = EVP_PKEY_get1_RSA(pk);
prv->type = KEY_RSA;
name = "rsa w/o comment";
#ifdef DEBUG_PK
RSA_print_fp(stderr, prv->rsa, 8);
#endif
if (RSA_blinding_on(prv->rsa, NULL) != 1) {
error("%s: RSA_blinding_on failed", __func__);
key_free(prv);
prv = NULL;
}
} else if (pk->type == EVP_PKEY_DSA &&
(type == KEY_UNSPEC||type==KEY_DSA)) {
prv = key_new(KEY_UNSPEC);
prv->dsa = EVP_PKEY_get1_DSA(pk);
prv->type = KEY_DSA;
name = "dsa w/o comment";
#ifdef DEBUG_PK
DSA_print_fp(stderr, prv->dsa, 8);
#endif
#ifdef OPENSSL_HAS_ECC
} else if (pk->type == EVP_PKEY_EC &&
(type == KEY_UNSPEC||type==KEY_ECDSA)) {
prv = key_new(KEY_UNSPEC);
prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
prv->type = KEY_ECDSA;
if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 ||
key_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
key_ec_validate_private(prv->ecdsa) != 0) {
error("%s: bad ECDSA key", __func__);
key_free(prv);
prv = NULL;
}
name = "ecdsa w/o comment";
#ifdef DEBUG_PK
if (prv != NULL && prv->ecdsa != NULL)
key_dump_ec_key(prv->ecdsa);
#endif
#endif /* OPENSSL_HAS_ECC */
} else {
error("%s: PEM_read_PrivateKey: mismatch or "
"unknown EVP_PKEY save_type %d", __func__, pk->save_type);
}
if (pk != NULL)
EVP_PKEY_free(pk);
if (prv != NULL && commentp)
*commentp = xstrdup(name);
debug("read PEM private key done: type %s",
prv ? key_type(prv) : "<unknown>");
return prv;
}
Key *
key_load_private_pem(int fd, int type, const char *passphrase,
char **commentp)
{
Buffer buffer;
Key *prv;
buffer_init(&buffer);
if (!key_load_file(fd, NULL, &buffer)) {
buffer_free(&buffer);
return NULL;
}
prv = key_parse_private_pem(&buffer, type, passphrase, commentp);
buffer_free(&buffer);
return prv;
}
int
key_perm_ok(int fd, const char *filename)
{
struct stat st;
if (fstat(fd, &st) < 0)
return 0;
/*
* if a key owned by the user is accessed, then we check the
* permissions of the file. if the key owned by a different user,
* then we don't care.
*/
#ifdef HAVE_CYGWIN
if (check_ntsec(filename))
#endif
if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
error("Permissions 0%3.3o for '%s' are too open.",
(u_int)st.st_mode & 0777, filename);
error("It is required that your private key files are NOT accessible by others.");
error("This private key will be ignored.");
return 0;
}
return 1;
}
static Key *
key_parse_private_type(Buffer *blob, int type, const char *passphrase,
char **commentp)
{
switch (type) {
case KEY_RSA1:
return key_parse_private_rsa1(blob, passphrase, commentp);
case KEY_DSA:
case KEY_ECDSA:
case KEY_RSA:
case KEY_UNSPEC:
return key_parse_private_pem(blob, type, passphrase, commentp);
default:
error("%s: cannot parse key type %d", __func__, type);
break;
}
return NULL;
}
Key *
key_load_private_type(int type, const char *filename, const char *passphrase,
char **commentp, int *perm_ok)
{
int fd;
Key *ret;
Buffer buffer;
fd = open(filename, O_RDONLY);
if (fd < 0) {
debug("could not open key file '%s': %s", filename,
strerror(errno));
if (perm_ok != NULL)
*perm_ok = 0;
return NULL;
}
if (!key_perm_ok(fd, filename)) {
if (perm_ok != NULL)
*perm_ok = 0;
error("bad permissions: ignore key: %s", filename);
close(fd);
return NULL;
}
if (perm_ok != NULL)
*perm_ok = 1;
buffer_init(&buffer);
if (!key_load_file(fd, filename, &buffer)) {
buffer_free(&buffer);
close(fd);
return NULL;
}
close(fd);
ret = key_parse_private_type(&buffer, type, passphrase, commentp);
buffer_free(&buffer);
return ret;
}
Key *
key_parse_private(Buffer *buffer, const char *filename,
const char *passphrase, char **commentp)
{
Key *pub, *prv;
/* it's a SSH v1 key if the public key part is readable */
pub = key_parse_public_rsa1(buffer, commentp);
if (pub == NULL) {
prv = key_parse_private_type(buffer, KEY_UNSPEC,
passphrase, NULL);
/* use the filename as a comment for PEM */
if (commentp && prv)
*commentp = xstrdup(filename);
} else {
key_free(pub);
/* key_parse_public_rsa1() has already loaded the comment */
prv = key_parse_private_type(buffer, KEY_RSA1, passphrase,
NULL);
}
return prv;
}
Key *
key_load_private(const char *filename, const char *passphrase,
char **commentp)
{
Key *prv;
Buffer buffer;
int fd;
fd = open(filename, O_RDONLY);
if (fd < 0) {
debug("could not open key file '%s': %s", filename,
strerror(errno));
return NULL;
}
if (!key_perm_ok(fd, filename)) {
error("bad permissions: ignore key: %s", filename);
close(fd);
return NULL;
}
buffer_init(&buffer);
if (!key_load_file(fd, filename, &buffer)) {
buffer_free(&buffer);
close(fd);
return NULL;
}
close(fd);
prv = key_parse_private(&buffer, filename, passphrase, commentp);
buffer_free(&buffer);
return prv;
}
static int
key_try_load_public(Key *k, const char *filename, char **commentp)
{
FILE *f;
char line[SSH_MAX_PUBKEY_BYTES];
char *cp;
u_long linenum = 0;
f = fopen(filename, "r");
if (f != NULL) {
while (read_keyfile_line(f, filename, line, sizeof(line),
&linenum) != -1) {
cp = line;
switch (*cp) {
case '#':
case '\n':
case '\0':
continue;
}
/* Abort loading if this looks like a private key */
if (strncmp(cp, "-----BEGIN", 10) == 0)
break;
/* Skip leading whitespace. */
for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
;
if (*cp) {
if (key_read(k, &cp) == 1) {
cp[strcspn(cp, "\r\n")] = '\0';
if (commentp) {
*commentp = xstrdup(*cp ?
cp : filename);
}
fclose(f);
return 1;
}
}
}
fclose(f);
}
return 0;
}
/* load public key from ssh v1 private or any pubkey file */
Key *
key_load_public(const char *filename, char **commentp)
{
Key *pub;
char file[MAXPATHLEN];
/* try rsa1 private key */
pub = key_load_public_type(KEY_RSA1, filename, commentp);
if (pub != NULL)
return pub;
/* try rsa1 public key */
pub = key_new(KEY_RSA1);
if (key_try_load_public(pub, filename, commentp) == 1)
return pub;
key_free(pub);
/* try ssh2 public key */
pub = key_new(KEY_UNSPEC);
if (key_try_load_public(pub, filename, commentp) == 1)
return pub;
if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
(strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
(key_try_load_public(pub, file, commentp) == 1))
return pub;
key_free(pub);
return NULL;
}
/* Load the certificate associated with the named private key */
Key *
key_load_cert(const char *filename)
{
Key *pub;
char *file;
pub = key_new(KEY_UNSPEC);
xasprintf(&file, "%s-cert.pub", filename);
if (key_try_load_public(pub, file, NULL) == 1) {
xfree(file);
return pub;
}
xfree(file);
key_free(pub);
return NULL;
}
/* Load private key and certificate */
Key *
key_load_private_cert(int type, const char *filename, const char *passphrase,
int *perm_ok)
{
Key *key, *pub;
switch (type) {
case KEY_RSA:
case KEY_DSA:
case KEY_ECDSA:
break;
default:
error("%s: unsupported key type", __func__);
return NULL;
}
if ((key = key_load_private_type(type, filename,
passphrase, NULL, perm_ok)) == NULL)
return NULL;
if ((pub = key_load_cert(filename)) == NULL) {
key_free(key);
return NULL;
}
/* Make sure the private key matches the certificate */
if (key_equal_public(key, pub) == 0) {
error("%s: certificate does not match private key %s",
__func__, filename);
} else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
error("%s: key_to_certified failed", __func__);
} else {
key_cert_copy(pub, key);
key_free(pub);
return key;
}
key_free(key);
key_free(pub);
return NULL;
}
/*
* Returns 1 if the specified "key" is listed in the file "filename",
* 0 if the key is not listed or -1 on error.
* If strict_type is set then the key type must match exactly,
* otherwise a comparison that ignores certficiate data is performed.
*/
int
key_in_file(Key *key, const char *filename, int strict_type)
{
FILE *f;
char line[SSH_MAX_PUBKEY_BYTES];
char *cp;
u_long linenum = 0;
int ret = 0;
Key *pub;
int (*key_compare)(const Key *, const Key *) = strict_type ?
key_equal : key_equal_public;
if ((f = fopen(filename, "r")) == NULL) {
if (errno == ENOENT) {
debug("%s: keyfile \"%s\" missing", __func__, filename);
return 0;
} else {
error("%s: could not open keyfile \"%s\": %s", __func__,
filename, strerror(errno));
return -1;
}
}
while (read_keyfile_line(f, filename, line, sizeof(line),
&linenum) != -1) {
cp = line;
/* Skip leading whitespace. */
for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
;
/* Skip comments and empty lines */
switch (*cp) {
case '#':
case '\n':
case '\0':
continue;
}
pub = key_new(KEY_UNSPEC);
if (key_read(pub, &cp) != 1) {
key_free(pub);
continue;
}
if (key_compare(key, pub)) {
ret = 1;
key_free(pub);
break;
}
key_free(pub);
}
fclose(f);
return ret;
}
| thispc/psiphon | openssh-5.9p1/authfile.c | C | gpl-3.0 | 24,711 |
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 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.
*
* Applied Energistics 2 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 Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.integration.modules;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import appeng.api.AEApi;
import appeng.api.storage.IMEInventory;
import appeng.integration.IIntegrationModule;
import appeng.integration.abstraction.IFZ;
import appeng.integration.modules.helpers.FactorizationBarrel;
import appeng.integration.modules.helpers.FactorizationHandler;
import appeng.util.Platform;
/**
* 100% Hacks.
*/
public class FZ implements IFZ, IIntegrationModule
{
public static FZ instance;
private static Class<?> day_BarrelClass;
private static Method day_getItemCount;
private static Method day_setItemCount;
private static Method day_getMaxSize;
private static Field day_item;
@Override
public ItemStack barrelGetItem( TileEntity te )
{
try
{
ItemStack i = null;
if( day_BarrelClass.isInstance( te ) )
{
i = (ItemStack) day_item.get( te );
}
if( i != null )
{
i = Platform.cloneItemStack( i );
}
return i;
}
catch( IllegalArgumentException ignored )
{
}
catch( IllegalAccessException ignored )
{
}
return null;
}
@Override
public int barrelGetMaxItemCount( TileEntity te )
{
try
{
if( day_BarrelClass.isInstance( te ) )
{
return (Integer) day_getMaxSize.invoke( te );
}
}
catch( IllegalAccessException ignored )
{
}
catch( IllegalArgumentException ignored )
{
}
catch( InvocationTargetException ignored )
{
}
return 0;
}
@Override
public int barrelGetItemCount( TileEntity te )
{
try
{
if( day_BarrelClass.isInstance( te ) )
{
return (Integer) day_getItemCount.invoke( te );
}
}
catch( IllegalAccessException ignored )
{
}
catch( IllegalArgumentException ignored )
{
}
catch( InvocationTargetException ignored )
{
}
return 0;
}
@Override
public void setItemType( TileEntity te, ItemStack input )
{
try
{
if( day_BarrelClass.isInstance( te ) )
{
day_item.set( te, input == null ? null : input.copy() );
}
}
catch( IllegalArgumentException ignored )
{
}
catch( IllegalAccessException ignored )
{
}
}
@Override
public void barrelSetCount( TileEntity te, int max )
{
try
{
if( day_BarrelClass.isInstance( te ) )
{
day_setItemCount.invoke( te, max );
}
te.markDirty();
}
catch( IllegalAccessException ignored )
{
}
catch( IllegalArgumentException ignored )
{
}
catch( InvocationTargetException ignored )
{
}
}
@Override
public IMEInventory getFactorizationBarrel( TileEntity te )
{
return new FactorizationBarrel( this, te );
}
@Override
public boolean isBarrel( TileEntity te )
{
return day_BarrelClass.isAssignableFrom( te.getClass() );
}
@Override
public void grinderRecipe( ItemStack in, ItemStack out )
{
try
{
Class<?> c = Class.forName( "factorization.oreprocessing.TileEntityGrinder" );
Method m = c.getMethod( "addRecipe", Object.class, ItemStack.class, float.class );
float amt = out.stackSize;
out.stackSize = 1;
m.invoke( c, in, out, amt );
}
catch( Throwable t )
{
// AELog.info( "" );
// throw new RuntimeException( t );
}
}
@Override
public void init() throws Throwable
{
day_BarrelClass = Class.forName( "factorization.weird.TileEntityDayBarrel" );
day_getItemCount = day_BarrelClass.getDeclaredMethod( "getItemCount" );
day_setItemCount = day_BarrelClass.getDeclaredMethod( "setItemCount", int.class );
day_getMaxSize = day_BarrelClass.getDeclaredMethod( "getMaxSize" );
day_item = day_BarrelClass.getDeclaredField( "item" );
}
@Override
public void postInit()
{
AEApi.instance().registries().externalStorage().addExternalStorageInterface( new FactorizationHandler() );
}
}
| SKCraft/Applied-Energistics-2 | src/main/java/appeng/integration/modules/FZ.java | Java | gpl-3.0 | 4,687 |
/**
* 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 edu.dfci.cccb.mev.dataset.domain.jooq;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.log4j.Log4j;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Table;
import edu.dfci.cccb.mev.dataset.domain.contract.InvalidCoordinateException;
import edu.dfci.cccb.mev.dataset.domain.prototype.AbstractDataSourceValues;
/**
* @author levk
*
*/
@ToString (of = "table")
@EqualsAndHashCode (callSuper = true)
@Log4j
public class JooqBasedDataSourceValues extends AbstractDataSourceValues {
private final DSLContext context;
private final Table<?> table;
private final Field<String> row;
private final Field<String> column;
private final Field<Double> value;
private final boolean isTemporary;
public JooqBasedDataSourceValues (DSLContext context,
Table<?> table,
Field<String> row,
Field<String> column,
Field<Double> value,
boolean isTemporary) {
this.context = context;
this.table = table;
this.row = row;
this.column = column;
this.value = value;
this.isTemporary = isTemporary;
}
@Override
public double get (String row, String column) throws InvalidCoordinateException {
try {
return context.select (value)
.from (table)
.where (this.row.eq (row))
.and (this.column.eq (column))
.fetchOne ()
.getValue (value);
} catch (RuntimeException e) {
throw new RuntimeException (" Failed to fetch row " + row + ", column " + column + " from " + table, e);
}
}
@Override
public void close () throws Exception {
if(isTemporary){
if (log.isDebugEnabled ())
log.debug ("Dropping table " + table);
context.query ("DROP TABLE IF EXISTS {0}", table);
}
}
/* (non-Javadoc)
* @see java.lang.Object#finalize() */
@Override
protected void finalize () throws Throwable {
close ();
}
}
| apartensky/mev | dataset/domain/src/main/java/edu/dfci/cccb/mev/dataset/domain/jooq/JooqBasedDataSourceValues.java | Java | gpl-3.0 | 2,778 |
/****************************************************************************
**
** Copyright (C) 2016 Denis Mingulov, The Qt Company Ltd.
** Copyright (C) 2016 Denis Mingulov, The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "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 Qt Company Ltd 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."
**
****************************************************************************/
#include "vcsconfigurationpage.h"
#include "../vcsbaseconstants.h"
#include <coreplugin/icore.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
#include <projectexplorer/jsonwizard/jsonwizard.h>
#include <projectexplorer/jsonwizard/jsonwizardfactory.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/algorithm.h>
#include <utils/qtcassert.h>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWizardPage>
using namespace Core;
using namespace ProjectExplorer;
namespace VcsBase {
namespace Internal {
VcsConfigurationPageFactory::VcsConfigurationPageFactory()
{
setTypeIdsSuffix(QLatin1String("VcsConfiguration"));
}
Utils::WizardPage *VcsConfigurationPageFactory::create(JsonWizard *wizard, Id typeId,
const QVariant &data)
{
Q_UNUSED(wizard);
QTC_ASSERT(canCreate(typeId), return 0);
QVariantMap tmp = data.toMap();
const QString vcsId = tmp.value(QLatin1String("vcsId")).toString();
QTC_ASSERT(!vcsId.isEmpty(), return 0);
auto page = new VcsConfigurationPage;
page->setVersionControlId(vcsId);
return page;
}
bool VcsConfigurationPageFactory::validateData(Id typeId, const QVariant &data,
QString *errorMessage)
{
QTC_ASSERT(canCreate(typeId), return false);
if (data.isNull() || data.type() != QVariant::Map) {
//: Do not translate "VcsConfiguration", because it is the id of a page.
*errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizard",
"\"data\" must be a JSON object for \"VcsConfiguration\" pages.");
return false;
}
QVariantMap tmp = data.toMap();
const QString vcsId = tmp.value(QLatin1String("vcsId")).toString();
if (vcsId.isEmpty()) {
//: Do not translate "VcsConfiguration", because it is the id of a page.
*errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizard",
"\"VcsConfiguration\" page requires a \"vcsId\" set.");
return false;
}
return true;
}
class VcsConfigurationPagePrivate
{
public:
const IVersionControl *m_versionControl;
QString m_versionControlId;
QPushButton *m_configureButton;
};
} // namespace Internal
VcsConfigurationPage::VcsConfigurationPage() : d(new Internal::VcsConfigurationPagePrivate)
{
setTitle(tr("Configuration"));
d->m_versionControl = 0;
d->m_configureButton = new QPushButton(ICore::msgShowOptionsDialog(), this);
d->m_configureButton->setEnabled(false);
auto verticalLayout = new QVBoxLayout(this);
verticalLayout->addWidget(d->m_configureButton);
connect(d->m_configureButton, &QAbstractButton::clicked,
this, &VcsConfigurationPage::openConfiguration);
}
VcsConfigurationPage::~VcsConfigurationPage()
{
delete d;
}
void VcsConfigurationPage::setVersionControl(const IVersionControl *vc)
{
if (vc)
d->m_versionControlId = vc->id().toString();
else
d->m_versionControlId.clear();
d->m_versionControl = 0;
}
void VcsConfigurationPage::setVersionControlId(const QString &id)
{
d->m_versionControlId = id;
}
void VcsConfigurationPage::initializePage()
{
if (d->m_versionControl) {
disconnect(d->m_versionControl, &IVersionControl::configurationChanged,
this, &QWizardPage::completeChanged);
}
if (!d->m_versionControlId.isEmpty()) {
auto jw = qobject_cast<JsonWizard *>(wizard());
if (!jw) {
//: Do not translate "VcsConfiguration", because it is the id of a page.
emit reportError(tr("No version control set on \"VcsConfiguration\" page."));
}
const QString vcsId = jw ? jw->expander()->expand(d->m_versionControlId) : d->m_versionControlId;
d->m_versionControl = VcsManager::versionControl(Id::fromString(vcsId));
if (!d->m_versionControl) {
emit reportError(
//: Do not translate "VcsConfiguration", because it is the id of a page.
tr("\"vcsId\" (\"%1\") is invalid for \"VcsConfiguration\" page. "
"Possible values are: %2.")
.arg(vcsId)
.arg(QStringList(Utils::transform(VcsManager::versionControls(), [](const IVersionControl *vc) {
return vc->id().toString();
})).join(QLatin1String(", "))));
}
}
connect(d->m_versionControl, &IVersionControl::configurationChanged,
this, &QWizardPage::completeChanged);
d->m_configureButton->setEnabled(d->m_versionControl);
if (d->m_versionControl)
setSubTitle(tr("Please configure <b>%1</b> now.").arg(d->m_versionControl->displayName()));
else
setSubTitle(tr("No known version control selected."));
}
bool VcsConfigurationPage::isComplete() const
{
return d->m_versionControl ? d->m_versionControl->isConfigured() : false;
}
void VcsConfigurationPage::openConfiguration()
{
ICore::showOptionsDialog(d->m_versionControl->id(), this);
}
} // namespace VcsBase
| Philips14171/qt-creator-opensource-src-4.2.1 | src/plugins/vcsbase/wizard/vcsconfigurationpage.cpp | C++ | gpl-3.0 | 7,676 |
Once you have a [Shareabouts map](https://github.com/openplans/shareabouts/blob/master/README.md#a-short-guide-to-setting-up-shareabouts) collecting data, you can explore the data via the Django admin interface, and via the web-based RESTful API browser.
## Viewing data via the Django admin interface
Shareabouts data is accessible via the regular Django interface, at
https://SERVER/admin/
e.g.
http://data.shareabouts.org/admin/
The trailing slash after `admin` is necessary, don't forget it.
### What can I do with the Django admin interface?
Using the Django interface, you can
* create new datasets and API keys
* view places by date
* view places in a particular dataset
* hide or show places with the Visibility checkbox in list view
* edit place data via the json blob editor
You cannot
* download data in a csv
* easily browse through data
## Viewing and downloading data via the API
You can explore your datasets here:
https://SERVER/api/v2/USER/datasets/
e.g.
http://data.shareabouts.org/api/v2/openplans/datasets
At that URL, you'll see a list of datasets, with links to each dataset's places, supports, and surveys (which are comments).
### Where's my private data?
Private data in Shareabouts can only be accessed by an authenticated user.
If you have fields prefixed with `private-` in your config, those fields aren't
accessible unless you log in to the Django admin interface before using the API browser.
Use your admin account for `https://SERVER/admin/` (e.g. `http://data.shareabouts.org/admin/`)
to add yourself as a superuser OR to set a password for the dataset owner.
Then, log in via `https://SERVER/admin/`, then use the API browser in another tab. Private data shows up if you include `?include_private` in the url, e.g.
http://data.shareabouts.org/api/v2/openplans/datasets/test-data/places?include_private
### Downloading snapshots
Data from the API can be paginated (using the `page_size` and `page` parameters), but it's tedious to assemble files offline, and if you make the page size too large, the page won't get generated before the server times out.
Instead, use the `/snapshots` endpoint. This will queue up the process of generating an entire file on request, which you can download once it has been created.
To generate a snapshot, visit `server/api/v2/user/datasets/datasets/places/snapshots?new` e.g.
https://data.shareabouts.org/api/v2/openplans/datasets/test-data/places/snapshots?new
Swap `surveys` for `places` to download comments.
If you are logged in as the dataset owner or a server administrator you can download a snapshot with private data included as well by including the `include_private` querystring parameter, i.e. `server/api/v2/user/datasets/datasets/places/snapshots?include_private&new`
Refresh the provided link, if the file isn't ready you'll see 'You can download the data at the given URL when it is done being generated'.
Once you have the download link, you most likely want it as a csv. Add `.csv` to the end of the url, and then do a "Save Page As" from your browser. E.g.
* generate a snapshot
* load the provided URL, like `https://data.shareabouts.org/api/v2/openplans/datasets/test-data/places/snapshots/dac284a6-734a-0b31314e3505`
* reload it with `.csv` on the end, `https://data.shareabouts.org/api/v2/openplans/datasets/test-data/places/snapshots/dac284a6-734a-0b31314e3505.csv`
* save the file (copying it out to a file will give you something with weird line breaks)
## Getting data via the Shareabouts CLI tools
You can use the separate [Shareabouts command line tools](https://github.com/openplans/shareabouts-cli-tools) to import and export data from a Shareabouts dataset. These python scripts make it easy to generate nightly reports, upload polygons, get custom CSV exports, and more.
## Transferring data from one API to another
1. **Create a new dataset with keys/origins the same as the old dataset.**
This can either be done through the API at */api/v2/<owner>/datasets*, or
through the Django admin interface at */admin/sa_api_v2/dataset/add/*. You
will have to set the keys and origins through the Django admin interface.
2. **Switch the dataset root URL to the new dataset.**
You can do this through with the Heroku command line client:
heroku config:set DATASET_ROOT=<path-to-new-dataset>
You can also now do this through Heroku's web dashboard interface. Navigate
to the **Settings** tab for your app, and find the **Reveal Config Vars**
button. Click **Edit** to change a value.
3. **Make a snapshot of the old dataset.**
The places snapshot should include all private data, invisible data, and
submissions on each place. First, navigate to
*/api/v2/<old-owner>/datasets/<old-slug>/places/snapshots?include_private&include_invisible&include_submissions&new*.
Next, remove the *new* parameter from the URL and wait until the snapshot
is ready (until the status is `'success'`). When it is done, copy the given
URL.
4. **Load the old data into the new dataset.**
Navigate to */api/v2/<owner>/datasets/<slug>* and paste the URL from step
3 in to the *Load from URL* field. Click **PUT** and the data should begin
to load. You won't see the results until the data has completed. It may
take a while. **Note** that it will note all data as new data; i.e., if you
do step #4 twice, it may load twice as many points as you expect. So **do
not retry** unless you know something went wrong. You can check whether
something went wrong by inspecting the server logs (not ideal, I know).
| openplans/shareabouts-api | doc/GETTING_YOUR_DATA.md | Markdown | gpl-3.0 | 5,636 |
/* -*- C++ -*-
* File: var_defines.h
* Copyright 2008-2013 LibRaw LLC ([email protected])
* Created: Sat Mar 8, 2008
*
* LibRaw redefinitions of dcraw internal variables
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of three licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
3. LibRaw Software License 27032010
(See file LICENSE.LibRaw.pdf provided in LibRaw distribution archive for details).
*/
#ifndef VAR_DEFINES_H
#define VAR_DEFINES_H
// imgdata.idata
#define make (imgdata.idata.make)
#define model (imgdata.idata.model)
#define software (imgdata.idata.software)
#define is_raw (imgdata.idata.raw_count)
#define dng_version (imgdata.idata.dng_version)
#define is_foveon (imgdata.idata.is_foveon)
#define colors (imgdata.idata.colors)
#define cdesc (imgdata.idata.cdesc)
#define filters (imgdata.idata.filters)
#define xtrans (imgdata.idata.xtrans)
#define xtrans_abs (imgdata.idata.xtrans_abs)
#define xmpdata (imgdata.idata.xmpdata)
#define xmplen (imgdata.idata.xmplen)
//imgdata image
#define image (imgdata.image)
#define raw_image (imgdata.rawdata.raw_image)
#define color_image (imgdata.rawdata.color_image)
// imgdata.sizes
#define raw_height (imgdata.sizes.raw_height)
#define raw_width (imgdata.sizes.raw_width)
#define raw_pitch (imgdata.sizes.raw_pitch)
#define height (imgdata.sizes.height)
#define width (imgdata.sizes.width)
#define top_margin (imgdata.sizes.top_margin)
#define left_margin (imgdata.sizes.left_margin)
#define bottom_margin (imgdata.sizes.bottom_margin)
#define right_margin (imgdata.sizes.right_margin)
#define iheight (imgdata.sizes.iheight)
#define iwidth (imgdata.sizes.iwidth)
#define pixel_aspect (imgdata.sizes.pixel_aspect)
#define flip (imgdata.sizes.flip)
#define mask (imgdata.sizes.mask)
//imgdata.color
#define white (imgdata.color.white)
#define cam_mul (imgdata.color.cam_mul)
#define pre_mul (imgdata.color.pre_mul)
#define cmatrix (imgdata.color.cmatrix)
#define rgb_cam (imgdata.color.rgb_cam)
#ifndef SRC_USES_CURVE
#define curve (imgdata.color.curve)
#endif
#ifndef SRC_USES_BLACK
#define black (imgdata.color.black)
#define cblack (imgdata.color.cblack)
#endif
#define maximum (imgdata.color.maximum)
#define channel_maximum (imgdata.color.channel_maximum)
#define profile_length (imgdata.color.profile_length)
#define color_flags (imgdata.color.color_flags)
#define ph1 (imgdata.color.phase_one_data)
#define flash_used (imgdata.color.flash_used)
#define canon_ev (imgdata.color.canon_ev)
#define model2 (imgdata.color.model2)
#define baseline_exposure (imgdata.color.baseline_exposure)
//imgdata.thumbnail
#define thumb_width (imgdata.thumbnail.twidth)
#define thumb_height (imgdata.thumbnail.theight)
#define thumb_length (imgdata.thumbnail.tlength)
//imgdata.others
#define iso_speed (imgdata.other.iso_speed)
#define shutter (imgdata.other.shutter)
#define aperture (imgdata.other.aperture)
#define focal_len (imgdata.other.focal_len)
#define timestamp (imgdata.other.timestamp)
#define shot_order (imgdata.other.shot_order)
#define gpsdata (imgdata.other.gpsdata)
#define desc (imgdata.other.desc)
#define artist (imgdata.other.artist)
//imgdata.output
#define greybox (imgdata.params.greybox)
#define cropbox (imgdata.params.cropbox)
#define aber (imgdata.params.aber)
#define gamm (imgdata.params.gamm)
#define user_mul (imgdata.params.user_mul)
#define shot_select (imgdata.params.shot_select)
#define bright (imgdata.params.bright)
#define threshold (imgdata.params.threshold)
#define half_size (imgdata.params.half_size)
#define four_color_rgb (imgdata.params.four_color_rgb)
#define highlight (imgdata.params.highlight)
//#define verbose (imgdata.params.verbose)
#define use_auto_wb (imgdata.params.use_auto_wb)
#define use_camera_wb (imgdata.params.use_camera_wb)
#define use_camera_matrix (imgdata.params.use_camera_matrix)
#define output_color (imgdata.params.output_color)
#define output_bps (imgdata.params.output_bps)
#define gamma_16bit (imgdata.params.gamma_16bit)
#define output_tiff (imgdata.params.output_tiff)
#define med_passes (imgdata.params.med_passes)
#define no_auto_bright (imgdata.params.no_auto_bright)
#define auto_bright_thr (imgdata.params.auto_bright_thr)
#define use_fuji_rotate (imgdata.params.use_fuji_rotate)
#define filtering_mode (imgdata.params.filtering_mode)
// Demosaic packs
//AFD
//#define afd_noise_att (imgdata.params.afd_noise_att)
//#define afd_noise_thres (imgdata.params.afd_noise_thres)
//#define afd_luminance_passes (imgdata.params.afd_luminance_passes)
//#define afd_chrominance_method (imgdata.params.afd_chrominance_method)
//#define afd_luminance_only (imgdata.params.afd_luminance_only)
// DCB
#define dcb_iterations (imgdata.params.iterations)
#define dcb_enhance_fl (imgdata.params.dcb_enhance)
#define fbdd_noiserd (imgdata.params.fbdd_noiserd)
// VCD
#define eeci_refine (imgdata.params.eeci_refine)
#define es_med_passes (imgdata.params.es_med_passes)
//rgb_constants
#define xyz_rgb (rgb_constants.xyz_rgb)
#define d65_white (rgb_constants.d65_white)
//libraw_internal_data.internal_data
#define meta_data (libraw_internal_data.internal_data.meta_data)
#define ifp libraw_internal_data.internal_data.input
#define ifname ((char*)libraw_internal_data.internal_data.input->fname())
#define ofp libraw_internal_data.internal_data.output
#define profile_offset (libraw_internal_data.internal_data.profile_offset)
#define thumb_offset (libraw_internal_data.internal_data.toffset)
#define pana_black (libraw_internal_data.internal_data.pana_black)
//libraw_internal_data.internal_output_params
#define mix_green (libraw_internal_data.internal_output_params.mix_green)
#define raw_color (libraw_internal_data.internal_output_params.raw_color)
#define use_gamma (libraw_internal_data.internal_output_params.use_gamma)
#define zero_is_bad (libraw_internal_data.internal_output_params.zero_is_bad)
#ifndef SRC_USES_SHRINK
#define shrink (libraw_internal_data.internal_output_params.shrink)
#endif
#define fuji_width (libraw_internal_data.internal_output_params.fuji_width)
//libraw_internal_data.output_data
#define histogram (libraw_internal_data.output_data.histogram)
#define oprof (libraw_internal_data.output_data.oprof)
//libraw_internal_data.identify_data
#define exif_cfa (libraw_internal_data.identify_data.olympus_exif_cfa)
#define unique_id (libraw_internal_data.identify_data.unique_id)
#define tiff_nifds (libraw_internal_data.identify_data.tiff_nifds)
#define tiff_flip (libraw_internal_data.identify_data.tiff_flip)
//libraw_internal_data.unpacker_data
#define order (libraw_internal_data.unpacker_data.order)
#define data_error (libraw_internal_data.unpacker_data.data_error)
#define cr2_slice (libraw_internal_data.unpacker_data.cr2_slice)
#define sraw_mul (libraw_internal_data.unpacker_data.sraw_mul)
#define kodak_cbpp (libraw_internal_data.unpacker_data.kodak_cbpp)
#define strip_offset (libraw_internal_data.unpacker_data.strip_offset)
#define data_offset (libraw_internal_data.unpacker_data.data_offset)
#define data_size (libraw_internal_data.unpacker_data.data_size)
#define meta_offset (libraw_internal_data.unpacker_data.meta_offset)
#define meta_length (libraw_internal_data.unpacker_data.meta_length)
#define thumb_misc (libraw_internal_data.unpacker_data.thumb_misc)
#define fuji_layout (libraw_internal_data.unpacker_data.fuji_layout)
#define tiff_samples (libraw_internal_data.unpacker_data.tiff_samples)
#define tiff_bps (libraw_internal_data.unpacker_data.tiff_bps)
#define tiff_compress (libraw_internal_data.unpacker_data.tiff_compress)
#define zero_after_ff (libraw_internal_data.unpacker_data.zero_after_ff)
#define tile_width (libraw_internal_data.unpacker_data.tile_width)
#define tile_length (libraw_internal_data.unpacker_data.tile_length)
#define load_flags (libraw_internal_data.unpacker_data.load_flags)
#ifdef LIBRAW_IO_REDEFINED
#define fread(ptr,size,n,stream) stream->read(ptr,size,n)
#define fseek(stream,o,w) stream->seek(o,w)
#define fseeko(stream,o,w) stream->seek(o,w)
#define ftell(stream) stream->tell()
#define ftello(stream) stream->tell()
#define feof(stream) stream->eof()
#ifdef getc
#undef getc
#endif
#define getc(stream) stream->get_char()
#define fgetc(stream) stream->get_char()
#define fgetcb(stream) stream->get_char_buf()
#define fgets(str,n,stream) stream->gets(str,n)
#define fscanf(stream,fmt,ptr) stream->scanf_one(fmt,ptr)
#endif
#endif
| NMCity/SPL-for-C | resources/FreeImage/Source/LibRawLite/internal/var_defines.h | C | gpl-3.0 | 9,660 |
<?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de http://trad.spip.org/tradlang_module/paquet-dump?lang_cible=it
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) return;
$GLOBALS[$GLOBALS['idx_lang']] = array(
// D
'dump_description' => 'Backup e ripristino della base dati SQLite',
'dump_slogan' => 'Backup e ripristino del database di SPIP'
);
?>
| phenix-factory/fci-obedience | plugins-dist/dump/lang/paquet-dump_it.php | PHP | gpl-3.0 | 438 |
import datetime
import logging
import re
from django.db import models
from django.db.backends.dummy.base import IntegrityError
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
from django.contrib.auth.models import Group as AuthGroup
from django.core import exceptions
from django.forms import EmailField, URLField
from django.utils import translation
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
from django.utils.html import strip_tags
from askbot import const
from askbot.conf import settings as askbot_settings
from askbot.utils import functions
from askbot.models.base import BaseQuerySetManager
from collections import defaultdict
PERSONAL_GROUP_NAME_PREFIX = '_personal_'
class ResponseAndMentionActivityManager(models.Manager):
def get_query_set(self):
response_types = const.RESPONSE_ACTIVITY_TYPES_FOR_DISPLAY
response_types += (const.TYPE_ACTIVITY_MENTION, )
return super(
ResponseAndMentionActivityManager,
self
).get_query_set().filter(
activity_type__in = response_types
)
class ActivityQuerySet(models.query.QuerySet):
"""query set for the `Activity` model"""
def get_all_origin_posts(self):
#todo: redo this with query sets
origin_posts = set()
for m in self.all():
post = m.content_object
if post and hasattr(post, 'get_origin_post'):
origin_posts.add(post.get_origin_post())
else:
logging.debug(
'method get_origin_post() not implemented for %s' \
% unicode(post)
)
return list(origin_posts)
def fetch_content_objects_dict(self):
"""return a dictionary where keys are activity ids
and values - content objects"""
content_object_ids = defaultdict(list)# lists of c.object ids by c.types
activity_type_ids = dict()#links c.objects back to activity objects
for act in self:
content_type_id = act.content_type_id
object_id = act.object_id
content_object_ids[content_type_id].append(object_id)
activity_type_ids[(content_type_id, object_id)] = act.id
#3) get links from activity objects to content objects
objects_by_activity = dict()
for content_type_id, object_id_list in content_object_ids.items():
content_type = ContentType.objects.get_for_id(content_type_id)
model_class = content_type.model_class()
content_objects = model_class.objects.filter(id__in=object_id_list)
for content_object in content_objects:
key = (content_type_id, content_object.id)
activity_id = activity_type_ids[key]
objects_by_activity[activity_id] = content_object
return objects_by_activity
class ActivityManager(BaseQuerySetManager):
"""manager class for the `Activity` model"""
def get_query_set(self):
return ActivityQuerySet(self.model)
def create_new_mention(
self,
mentioned_by = None,
mentioned_whom = None,
mentioned_at = None,
mentioned_in = None,
reported = None
):
#todo: automate this using python inspect module
kwargs = dict()
kwargs['activity_type'] = const.TYPE_ACTIVITY_MENTION
if mentioned_at:
#todo: handle cases with rich lookups here like __lt
kwargs['active_at'] = mentioned_at
if mentioned_by:
kwargs['user'] = mentioned_by
if mentioned_in:
if functions.is_iterable(mentioned_in):
raise NotImplementedError('mentioned_in only works for single items')
else:
post_content_type = ContentType.objects.get_for_model(mentioned_in)
kwargs['content_type'] = post_content_type
kwargs['object_id'] = mentioned_in.id
if reported == True:
kwargs['is_auditted'] = True
else:
kwargs['is_auditted'] = False
mention_activity = Activity(**kwargs)
mention_activity.question = mentioned_in.get_origin_post()
mention_activity.save()
if mentioned_whom:
assert(isinstance(mentioned_whom, User))
mention_activity.add_recipients([mentioned_whom])
mentioned_whom.update_response_counts()
return mention_activity
def get_mentions(
self,
mentioned_by = None,
mentioned_whom = None,
mentioned_at = None,
mentioned_in = None,
reported = None,
mentioned_at__lt = None,
):
"""extract mention-type activity objects
todo: implement better rich field lookups
"""
kwargs = dict()
kwargs['activity_type'] = const.TYPE_ACTIVITY_MENTION
if mentioned_at:
#todo: handle cases with rich lookups here like __lt, __gt and others
kwargs['active_at'] = mentioned_at
elif mentioned_at__lt:
kwargs['active_at__lt'] = mentioned_at__lt
if mentioned_by:
kwargs['user'] = mentioned_by
if mentioned_whom:
if functions.is_iterable(mentioned_whom):
kwargs['recipients__in'] = mentioned_whom
else:
kwargs['recipients__in'] = (mentioned_whom,)
if mentioned_in:
if functions.is_iterable(mentioned_in):
it = iter(mentioned_in)
raise NotImplementedError('mentioned_in only works for single items')
else:
post_content_type = ContentType.objects.get_for_model(mentioned_in)
kwargs['content_type'] = post_content_type
kwargs['object_id'] = mentioned_in.id
if reported == True:
kwargs['is_auditted'] = True
else:
kwargs['is_auditted'] = False
return self.filter(**kwargs)
class ActivityAuditStatus(models.Model):
"""bridge "through" relation between activity and users"""
STATUS_NEW = 0
STATUS_SEEN = 1
STATUS_CHOICES = (
(STATUS_NEW, 'new'),
(STATUS_SEEN, 'seen')
)
user = models.ForeignKey(User)
activity = models.ForeignKey('Activity')
status = models.SmallIntegerField(choices=STATUS_CHOICES, default=STATUS_NEW)
class Meta:
unique_together = ('user', 'activity')
app_label = 'askbot'
db_table = 'askbot_activityauditstatus'
def is_new(self):
return (self.status == self.STATUS_NEW)
class Activity(models.Model):
"""
We keep some history data for user activities
"""
user = models.ForeignKey(User)
receiving_users = models.ManyToManyField(User, related_name='received_activity')
recipients = models.ManyToManyField(User, through=ActivityAuditStatus, related_name='incoming_activity')
activity_type = models.SmallIntegerField(choices = const.TYPE_ACTIVITY)
active_at = models.DateTimeField(default=datetime.datetime.now)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
#todo: remove this denorm question field when Post model is set up
question = models.ForeignKey('Post', null=True)
is_auditted = models.BooleanField(default=False)
#add summary field.
summary = models.TextField(default='')
objects = ActivityManager()
responses_and_mentions = ResponseAndMentionActivityManager()
def __unicode__(self):
return u'[%s] was active at %s' % (self.user.username, self.active_at)
class Meta:
app_label = 'askbot'
db_table = u'activity'
def add_recipients(self, recipients):
"""have to use a special method, because django does not allow
auto-adding to M2M with "through" model
"""
for recipient in recipients:
#todo: may optimize for bulk addition
aas = ActivityAuditStatus(user = recipient, activity = self)
aas.save()
def get_mentioned_user(self):
assert(self.activity_type == const.TYPE_ACTIVITY_MENTION)
user_qs = self.recipients.all()
user_count = len(user_qs)
if user_count == 0:
return None
assert(user_count == 1)
return user_qs[0]
def get_snippet(self, max_length = 120):
return self.content_object.get_snippet(max_length)
def get_absolute_url(self):
return self.content_object.get_absolute_url()
class EmailFeedSettingManager(models.Manager):
def filter_subscribers(
self,
potential_subscribers = None,
feed_type = None,
frequency = None
):
"""returns set of users who have matching subscriptions
and if potential_subscribers is not none, search will
be limited to only potential subscribers,
otherwise search is unrestricted
todo: when EmailFeedSetting is merged into user table
this method may become unnecessary
"""
matching_feeds = self.filter(
feed_type = feed_type,
frequency = frequency
)
if potential_subscribers is not None:
matching_feeds = matching_feeds.filter(
subscriber__in = potential_subscribers
)
subscriber_set = set()
for feed in matching_feeds:
subscriber_set.add(feed.subscriber)
return subscriber_set
class EmailFeedSetting(models.Model):
#definitions of delays before notification for each type of notification frequency
DELTA_TABLE = {
'i':datetime.timedelta(-1),#instant emails are processed separately
'd':datetime.timedelta(1),
'w':datetime.timedelta(7),
'n':datetime.timedelta(-1),
}
#definitions of feed schedule types
FEED_TYPES = (
'q_ask', #questions that user asks
'q_all', #enture forum, tag filtered
'q_ans', #questions that user answers
'q_sel', #questions that user decides to follow
'm_and_c' #comments and mentions of user anywhere
)
#email delivery schedule when no email is sent at all
NO_EMAIL_SCHEDULE = {
'q_ask': 'n',
'q_ans': 'n',
'q_all': 'n',
'q_sel': 'n',
'm_and_c': 'n'
}
MAX_EMAIL_SCHEDULE = {
'q_ask': 'i',
'q_ans': 'i',
'q_all': 'i',
'q_sel': 'i',
'm_and_c': 'i'
}
#todo: words
FEED_TYPE_CHOICES = (
('q_all', ugettext_lazy('Entire forum')),
('q_ask', ugettext_lazy('Questions that I asked')),
('q_ans', ugettext_lazy('Questions that I answered')),
('q_sel', ugettext_lazy('Individually selected questions')),
('m_and_c', ugettext_lazy('Mentions and comment responses')),
)
UPDATE_FREQUENCY = (
('i', ugettext_lazy('Instantly')),
('d', ugettext_lazy('Daily')),
('w', ugettext_lazy('Weekly')),
('n', ugettext_lazy('No email')),
)
subscriber = models.ForeignKey(User, related_name='notification_subscriptions')
feed_type = models.CharField(max_length=16, choices=FEED_TYPE_CHOICES)
frequency = models.CharField(
max_length=8,
choices=const.NOTIFICATION_DELIVERY_SCHEDULE_CHOICES,
default='n',
)
added_at = models.DateTimeField(auto_now_add=True)
reported_at = models.DateTimeField(null=True)
objects = EmailFeedSettingManager()
class Meta:
#added to make account merges work properly
unique_together = ('subscriber', 'feed_type')
app_label = 'askbot'
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
if self.reported_at is None:
reported_at = "'not yet'"
else:
reported_at = '%s' % self.reported_at.strftime('%d/%m/%y %H:%M')
return u'Email feed for %s type=%s, frequency=%s, reported_at=%s' % (
self.subscriber,
self.feed_type,
self.frequency,
reported_at
)
def save(self,*args,**kwargs):
type = self.feed_type
subscriber = self.subscriber
similar = self.__class__.objects.filter(
feed_type=type,
subscriber=subscriber
).exclude(pk=self.id)
if len(similar) > 0:
raise IntegrityError('email feed setting already exists')
super(EmailFeedSetting,self).save(*args,**kwargs)
def get_previous_report_cutoff_time(self):
now = datetime.datetime.now()
return now - self.DELTA_TABLE[self.frequency]
def should_send_now(self):
now = datetime.datetime.now()
cutoff_time = self.get_previous_report_cutoff_time()
if self.reported_at == None or self.reported_at <= cutoff_time:
return True
else:
return False
def mark_reported_now(self):
self.reported_at = datetime.datetime.now()
self.save()
class AuthUserGroups(models.Model):
"""explicit model for the auth_user_groups bridge table.
"""
group = models.ForeignKey(AuthGroup)
user = models.ForeignKey(User)
class Meta:
app_label = 'auth'
unique_together = ('group', 'user')
db_table = 'auth_user_groups'
managed = False
class GroupMembershipManager(models.Manager):
def create(self, **kwargs):
user = kwargs['user']
group = kwargs['group']
try:
#need this for the cases where auth User_groups is there,
#but ours is not
auth_gm = AuthUserGroups.objects.get(user=user, group=group)
#use this as link for the One to One relation
kwargs['authusergroups_ptr'] = auth_gm
except AuthUserGroups.DoesNotExist:
pass
super(GroupMembershipManager, self).create(**kwargs)
class GroupMembership(AuthUserGroups):
"""contains one-to-one relation to ``auth_user_group``
and extra membership profile fields"""
#note: this may hold info on when user joined, etc
NONE = -1#not part of the choices as for this records should be just missing
PENDING = 0
FULL = 1
LEVEL_CHOICES = (#'none' is by absence of membership
(PENDING, 'pending'),
(FULL, 'full')
)
ALL_LEVEL_CHOICES = LEVEL_CHOICES + ((NONE, 'none'),)
level = models.SmallIntegerField(
default=FULL,
choices=LEVEL_CHOICES,
)
objects = GroupMembershipManager()
class Meta:
app_label = 'askbot'
@classmethod
def get_level_value_display(cls, level):
"""returns verbose value given a numerical value
includes the "fanthom" NONE
"""
values_dict = dict(cls.ALL_LEVEL_CHOICES)
return values_dict[level]
class GroupQuerySet(models.query.QuerySet):
"""Custom query set for the group"""
def exclude_personal(self):
"""excludes the personal groups"""
return self.exclude(
name__startswith=PERSONAL_GROUP_NAME_PREFIX
)
def get_personal(self):
"""filters for the personal groups"""
return self.filter(
name__startswith=PERSONAL_GROUP_NAME_PREFIX
)
def get_for_user(self, user=None, private=False):
if private:
global_group = Group.objects.get_global_group()
return self.filter(
user=user
).exclude(id=global_group.id)
else:
return self.filter(user=user)
def get_by_name(self, group_name = None):
from askbot.models.tag import clean_group_name#todo - delete this
return self.get(name = clean_group_name(group_name))
class GroupManager(BaseQuerySetManager):
"""model manager for askbot groups"""
def get_query_set(self):
return GroupQuerySet(self.model)
def get_global_group(self):
"""Returns the global group,
if necessary, creates one
"""
#todo: when groups are disconnected from tags,
#find comment as shown below in the test cases and
#revert the values
#todo: change groups to django groups
group_name = askbot_settings.GLOBAL_GROUP_NAME
try:
return self.get_query_set().get(name=group_name)
except Group.DoesNotExist:
return self.get_query_set().create(name=group_name)
def create(self, **kwargs):
name = kwargs['name']
try:
group_ptr = AuthGroup.objects.get(name=name)
kwargs['group_ptr'] = group_ptr
except AuthGroup.DoesNotExist:
pass
return super(GroupManager, self).create(**kwargs)
def get_or_create(self, name = None, user = None, openness=None):
"""creates a group tag or finds one, if exists"""
#todo: here we might fill out the group profile
try:
#iexact is important!!! b/c we don't want case variants
#of tags
group = self.get(name__iexact = name)
except self.model.DoesNotExist:
if openness is None:
group = self.create(name=name)
else:
group = self.create(name=name, openness=openness)
return group
class Group(AuthGroup):
"""group profile for askbot"""
OPEN = 0
MODERATED = 1
CLOSED = 2
OPENNESS_CHOICES = (
(OPEN, 'open'),
(MODERATED, 'moderated'),
(CLOSED, 'closed'),
)
logo_url = models.URLField(null=True)
description = models.OneToOneField(
'Post', related_name='described_group',
null=True, blank=True
)
moderate_email = models.BooleanField(default=True)
moderate_answers_to_enquirers = models.BooleanField(
default=False,
help_text='If true, answers to outsiders questions '
'will be shown to the enquirers only when '
'selected by the group moderators.'
)
openness = models.SmallIntegerField(default=CLOSED, choices=OPENNESS_CHOICES)
#preapproved email addresses and domain names to auto-join groups
#trick - the field is padded with space and all tokens are space separated
preapproved_emails = models.TextField(
null = True, blank = True, default = ''
)
#only domains - without the '@' or anything before them
preapproved_email_domains = models.TextField(
null = True, blank = True, default = ''
)
is_vip = models.BooleanField(
default=False,
help_text='Check to make members of this group site moderators'
)
read_only = models.BooleanField(default=False)
objects = GroupManager()
class Meta:
app_label = 'askbot'
db_table = 'askbot_group'
def get_moderators(self):
"""returns group moderators"""
user_filter = models.Q(is_superuser=True) | models.Q(status='m')
user_filter = user_filter & models.Q(groups__in=[self])
return User.objects.filter(user_filter)
def has_moderator(self, user):
"""true, if user is a group moderator"""
mod_ids = self.get_moderators().values_list('id', flat=True)
return user.id in mod_ids
def get_openness_choices(self):
"""gives answers to question
"How can users join this group?"
"""
return (
(Group.OPEN, _('Can join when they want')),
(Group.MODERATED, _('Users ask permission')),
(Group.CLOSED, _('Moderator adds users'))
)
def get_openness_level_for_user(self, user):
"""returns descriptive value, because it is to be used in the
templates. The value must match the verbose versions of the
openness choices!!!
"""
if user.is_anonymous():
return 'closed'
#a special case - automatic global group cannot be joined or left
if self.name == askbot_settings.GLOBAL_GROUP_NAME:
return 'closed'
#todo - return 'closed' for internal per user groups too
if self.openness == Group.OPEN:
return 'open'
if user.is_administrator_or_moderator():
return 'open'
#relying on a specific method of storage
from askbot.utils.forms import email_is_allowed
if email_is_allowed(
user.email,
allowed_emails=self.preapproved_emails,
allowed_email_domains=self.preapproved_email_domains
):
return 'open'
if self.openness == Group.MODERATED:
return 'moderated'
return 'closed'
def is_personal(self):
"""``True`` if the group is personal"""
return self.name.startswith(PERSONAL_GROUP_NAME_PREFIX)
def clean(self):
"""called in `save()`
"""
emails = functions.split_list(self.preapproved_emails)
email_field = EmailField()
try:
map(lambda v: email_field.clean(v), emails)
except exceptions.ValidationError:
raise exceptions.ValidationError(
_('Please give a list of valid email addresses.')
)
self.preapproved_emails = ' ' + '\n'.join(emails) + ' '
domains = functions.split_list(self.preapproved_email_domains)
from askbot.forms import DomainNameField
domain_field = DomainNameField()
try:
map(lambda v: domain_field.clean(v), domains)
except exceptions.ValidationError:
raise exceptions.ValidationError(
_('Please give a list of valid email domain names.')
)
self.preapproved_email_domains = ' ' + '\n'.join(domains) + ' '
def save(self, *args, **kwargs):
self.clean()
super(Group, self).save(*args, **kwargs)
class BulkTagSubscriptionManager(BaseQuerySetManager):
def create(
self,
tag_names=None,
user_list=None,
group_list=None,
tag_author=None,
language_code=None,
**kwargs
):
tag_names = tag_names or []
user_list = user_list or []
group_list = group_list or []
new_object = super(BulkTagSubscriptionManager, self).create(**kwargs)
tag_name_list = []
if tag_names:
from askbot.models.tag import get_tags_by_names
tags, new_tag_names = get_tags_by_names(tag_names, language_code)
if new_tag_names:
assert(tag_author)
tags_id_list= [tag.id for tag in tags]
tag_name_list = [tag.name for tag in tags]
from askbot.models.tag import Tag
new_tags = Tag.objects.create_in_bulk(
tag_names=new_tag_names,
user=tag_author,
language_code=translation.get_language()
)
tags_id_list.extend([tag.id for tag in new_tags])
tag_name_list.extend([tag.name for tag in new_tags])
new_object.tags.add(*tags_id_list)
if user_list:
user_ids = []
for user in user_list:
user_ids.append(user.id)
user.mark_tags(tagnames=tag_name_list,
reason='subscribed',
action='add')
new_object.users.add(*user_ids)
if group_list:
group_ids = []
for group in group_list:
#TODO: do the group marked tag thing here
group_ids.append(group.id)
new_object.groups.add(*group_ids)
return new_object
class BulkTagSubscription(models.Model):
date_added = models.DateField(auto_now_add=True)
tags = models.ManyToManyField('Tag')
users = models.ManyToManyField(User)
groups = models.ManyToManyField(Group)
objects = BulkTagSubscriptionManager()
def tag_list(self):
return [tag.name for tag in self.tags.all()]
class Meta:
app_label = 'askbot'
ordering = ['-date_added']
| coffenbacher/askbot-devel | askbot/models/user.py | Python | gpl-3.0 | 25,538 |
package eu.siacs.conversations.entities;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import rocks.xmpp.addr.Jid;
public class ReadByMarker {
private ReadByMarker() {
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ReadByMarker marker = (ReadByMarker) o;
if (fullJid != null ? !fullJid.equals(marker.fullJid) : marker.fullJid != null)
return false;
return realJid != null ? realJid.equals(marker.realJid) : marker.realJid == null;
}
@Override
public int hashCode() {
int result = fullJid != null ? fullJid.hashCode() : 0;
result = 31 * result + (realJid != null ? realJid.hashCode() : 0);
return result;
}
private Jid fullJid;
private Jid realJid;
public Jid getFullJid() {
return fullJid;
}
public Jid getRealJid() {
return realJid;
}
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
if (fullJid != null) {
try {
jsonObject.put("fullJid", fullJid.toString());
} catch (JSONException e) {
//ignore
}
}
if (realJid != null) {
try {
jsonObject.put("realJid", realJid.toString());
} catch (JSONException e) {
//ignore
}
}
return jsonObject;
}
public static Set<ReadByMarker> fromJson(JSONArray jsonArray) {
HashSet<ReadByMarker> readByMarkers = new HashSet<>();
for(int i = 0; i < jsonArray.length(); ++i) {
try {
readByMarkers.add(fromJson(jsonArray.getJSONObject(i)));
} catch (JSONException e) {
//ignored
}
}
return readByMarkers;
}
public static ReadByMarker from(Jid fullJid, Jid realJid) {
final ReadByMarker marker = new ReadByMarker();
marker.fullJid = fullJid;
marker.realJid = realJid == null ? null : realJid.asBareJid();
return marker;
}
public static ReadByMarker from(Message message) {
final ReadByMarker marker = new ReadByMarker();
marker.fullJid = message.getCounterpart();
marker.realJid = message.getTrueCounterpart();
return marker;
}
public static ReadByMarker from(MucOptions.User user) {
final ReadByMarker marker = new ReadByMarker();
marker.fullJid = user.getFullJid();
marker.realJid = user.getRealJid();
return marker;
}
public static Set<ReadByMarker> from(Collection<MucOptions.User> users) {
final HashSet<ReadByMarker> markers = new HashSet<>();
for(MucOptions.User user : users) {
markers.add(from(user));
}
return markers;
}
public static ReadByMarker fromJson(JSONObject jsonObject) {
ReadByMarker marker = new ReadByMarker();
try {
marker.fullJid = Jid.of(jsonObject.getString("fullJid"));
} catch (JSONException | IllegalArgumentException e) {
marker.fullJid = null;
}
try {
marker.realJid = Jid.of(jsonObject.getString("realJid"));
} catch (JSONException | IllegalArgumentException e) {
marker.realJid = null;
}
return marker;
}
public static Set<ReadByMarker> fromJsonString(String json) {
try {
return fromJson(new JSONArray(json));
} catch (JSONException | NullPointerException e) {
return new HashSet<>();
}
}
public static JSONArray toJson(Set<ReadByMarker> readByMarkers) {
JSONArray jsonArray = new JSONArray();
for(ReadByMarker marker : readByMarkers) {
jsonArray.put(marker.toJson());
}
return jsonArray;
}
public static boolean contains(ReadByMarker needle, Set<ReadByMarker> readByMarkers) {
for(ReadByMarker marker : readByMarkers) {
if (marker.realJid != null && needle.realJid != null) {
if (marker.realJid.asBareJid().equals(needle.realJid.asBareJid())) {
return true;
}
} else if (marker.fullJid != null && needle.fullJid != null) {
if (marker.fullJid.equals(needle.fullJid)) {
return true;
}
}
}
return false;
}
public static boolean allUsersRepresented(Collection<MucOptions.User> users, Set<ReadByMarker> markers) {
for(MucOptions.User user : users) {
if (!contains(from(user),markers)) {
return false;
}
}
return true;
}
public static boolean allUsersRepresented(Collection<MucOptions.User> users, Set<ReadByMarker> markers, ReadByMarker marker) {
HashSet<ReadByMarker> markersCopy = new HashSet<>(markers);
markersCopy.add(marker);
return allUsersRepresented(users, markersCopy);
}
}
| kriztan/Conversations | src/main/java/eu/siacs/conversations/entities/ReadByMarker.java | Java | gpl-3.0 | 4,397 |
/*
* Copyright (c) 2009, 2010, 2011, 2012 Brendon J. Brewer.
*
* This file is part of DNest3.
*
* DNest3 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.
*
* DNest3 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 DNest3. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _Data_
#define _Data_
#include <vector>
/*
* A dataset to fit sine waves to.
* Also contains a static singleton for the one-data-set case
*/
class Data
{
private:
// A flag
bool loaded;
// The data
std::vector<double> t, y, sig, inverseVariance;
// Summary statistics
double tRange, yMean, ySig;
// Compute the summary statistics from the data
void computeSummaries();
public:
// Default constructor: Empty data
Data();
// Load the data from file
void load(const char* filename);
// Getters
bool get_loaded() { return loaded; }
double get_t(int i) { return t[i]; }
double get_y(int i) { return y[i]; }
double get_sig(int i) { return sig[i]; }
double get_tRange() { return tRange; }
double get_yMean() { return yMean; }
double get_ySig() { return ySig; }
int get_N() { return static_cast<int>(y.size()); }
// Static stuff for singleton use
private:
static Data instance;
public:
// Access to the instance
static Data& get_instance() { return instance; }
};
#endif
| eggplantbren/Oscillations | FitSine/Data.h | C | gpl-3.0 | 1,751 |
/* Conversion to UTF-16 from legacy encodings.
Copyright (C) 2002, 2006-2007, 2009-2013 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <[email protected]>. */
#include <config.h>
/* Specification. */
#include "uniconv.h"
#include <errno.h>
#include <stdlib.h>
#include "striconveha.h"
#include "unistr.h"
/* Name of UTF-16 encoding with machine dependent endianness and alignment. */
#if defined _LIBICONV_VERSION || (((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) && !defined __UCLIBC__)
# ifdef WORDS_BIGENDIAN
# define UTF16_NAME "UTF-16BE"
# else
# define UTF16_NAME "UTF-16LE"
# endif
#endif
#define FUNC u16_conv_from_encoding
#define UNIT uint16_t
#define U8_TO_U u8_to_u16
#define U_MBLEN u16_mblen
#if defined UTF16_NAME
# define UTF_NAME UTF16_NAME
# define HAVE_UTF_NAME 1
#endif
#include "u-conv-from-enc.h"
| Distrotech/libunistring | lib/uniconv/u16-conv-from-enc.c | C | gpl-3.0 | 1,527 |
url: http://sanskrit.inria.fr/cgi-bin/SKT/sktreader?t=VH;lex=SH;cache=f;st=t;us=f;cp=t;text=svaaheti;topic=;abs=f;allSol=2;mode=p;cpts=<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>Sanskrit Reader Companion</title>
<meta name="author" content="Gérard Huet">
<meta property="dc:datecopyrighted" content="2016">
<meta property="dc:rightsholder" content="Gérard Huet">
<meta name="keywords" content="dictionary,sanskrit,heritage,dictionnaire,sanscrit,india,inde,indology,linguistics,panini,digital humanities,cultural heritage,computational linguistics,hypertext lexicon">
<link rel="stylesheet" type="text/css" href="http://sanskrit.inria.fr/DICO/style.css" media="screen,tv">
<link rel="shortcut icon" href="http://sanskrit.inria.fr/IMAGES/favicon.ico">
<script type="text/javascript" src="http://sanskrit.inria.fr/DICO/utf82VH.js"></script>
</head>
<body class="chamois_back">
<br><h1 class="title">The Sanskrit Reader Companion</h1>
<table class="chamois_back" border="0" cellpadding="0%" cellspacing="15pt" width="100%">
<tr><td>
<p align="center">
<div class="latin16"><a class="green" href="/cgi-bin/SKT/sktgraph?t=VH;lex=SH;cache=f;st=t;us=f;cp=t;text=svaaheti;topic=;abs=f;cpts=;mode=g">✓</a> Show Summary of Solutions
</p>
Input:
<span class="red16">svāheti</span><hr>
<br>
Sentence:
<span class="deva16" lang="sa">स्वाहेति</span><br>
may be analysed as:</div><br>
<hr>
<span class="blue">Solution 1 : <a class="green" href="/cgi-bin/SKT/sktparser?t=VH;lex=SH;cache=f;st=t;us=f;cp=t;text=svaaheti;topic=;abs=f;cpts=;mode=p;n=1">✓</a></span><br>
[ <span class="blue" title="0"><b>svāhā</b></span><table class="mauve_back">
<tr><th><span class="latin12"><tr><th><span class="latin12">{ ind. }[<a class="navy" href="http://sanskrit.inria.fr/DICO/72.html#svaahaa"><i>svāhā</i></a>]</span></th></tr></span></th></tr></table>⟨<span class="magenta">ā</span><span class="green">|</span><span class="magenta">i</span><span class="blue"> → </span><span class="red">e</span>⟩]
<br>
[ <span class="blue" title="4"><b>iti</b></span><table class="mauve_back">
<tr><th><span class="latin12"><tr><th><span class="latin12">{ part. }[<a class="navy" href="http://sanskrit.inria.fr/DICO/11.html#iti"><i>iti</i></a>]</span></th></tr></span></th></tr></table>⟨⟩]
<br>
<br>
<hr>
<span class="magenta">1</span><span class="blue"> solution</span><span class="blue"> kept among </span><span class="magenta">5</span><br>
<span class="blue">Filtering efficiency: </span>
<span class="magenta">100%</span>
<br>
<hr>
<br>
<br>
</td></tr></table>
<table class="pad60">
<tr><td></td></tr></table>
<div class="enpied">
<table class="bandeau"><tr><td>
<a href="http://ocaml.org"><img src="http://sanskrit.inria.fr/IMAGES/ocaml.gif" alt="Le chameau Ocaml" height="50"></a>
</td><td>
<table class="center">
<tr><td>
<a href="http://sanskrit.inria.fr/index.fr.html"><b>Top</b></a> |
<a href="http://sanskrit.inria.fr/DICO/index.fr.html"><b>Index</b></a> |
<a href="http://sanskrit.inria.fr/DICO/index.fr.html#stemmer"><b>Stemmer</b></a> |
<a href="http://sanskrit.inria.fr/DICO/grammar.fr.html"><b>Grammar</b></a> |
<a href="http://sanskrit.inria.fr/DICO/sandhi.fr.html"><b>Sandhi</b></a> |
<a href="http://sanskrit.inria.fr/DICO/reader.fr.html"><b>Reader</b></a> |
<a href="http://sanskrit.inria.fr/faq.fr.html"><b>Help</b></a> |
<a href="http://sanskrit.inria.fr/portal.fr.html"><b>Portal</b></a>
</td></tr><tr><td>
© Gérard Huet 1994-2016</td></tr></table></td><td>
<a href="http://www.inria.fr/"><img src="http://sanskrit.inria.fr/IMAGES/logo_inria.png" alt="Logo Inria" height="50"></a>
<br></td></tr></table></div>
</body>
</html>
| sanskritiitd/sanskrit | uohCorpus.fil/uoh/uoh.filteredcorpus.txt_output/agnipuran-1-111-sandhi_ext.txt.out.dict_3614_inr.html | HTML | gpl-3.0 | 3,774 |
/*-
*/
#ifndef _CRYPTO_SCRYPT_H_
#define _CRYPTO_SCRYPT_H_
#include <stdint.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C"{
#endif
/**
* crypto_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):
* Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,
* p, buflen) and write the result into buf. The parameters r, p, and buflen
* must satisfy r * p < 2^30 and buflen <= (2^32 - 1) * 32. The parameter N
* must be a power of 2 greater than 1.
*
* libscrypt_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):
* password; duh
* N: CPU AND RAM cost (first modifier)
* r: RAM Cost
* p: CPU cost (parallelisation)
* In short, N is your main performance modifier. Values of r = 8, p = 1 are
* standard unless you want to modify the CPU/RAM ratio.
* Return 0 on success; or -1 on error.
*/
int libscrypt_scrypt(const uint8_t *, size_t, const uint8_t *, size_t, uint64_t,
uint32_t, uint32_t, /*@out@*/ uint8_t *, size_t);
/* Converts a series of input parameters to a MCF form for storage */
int libscrypt_mcf(uint32_t N, uint32_t r, uint32_t p, const char *salt,
const char *hash, char *mcf);
#ifndef _MSC_VER
/* Generates a salt. Uses /dev/urandom/
*/
int libscrypt_salt_gen(/*@out@*/ uint8_t *rand, size_t len);
/* Creates a hash of a passphrase using a randomly generated salt */
/* Returns >0 on success, or 0 for fail */
int libscrypt_hash(char *dst, const char* passphrase, uint32_t N, uint8_t r,
uint8_t p);
#endif
/* Checks a given MCF against a password */
int libscrypt_check(char *mcf, const char *password);
#ifdef __cplusplus
}
#endif
/* Sane default values */
#define SCRYPT_HASH_LEN 64 /* This can be user defined -
*but 64 is the reference size
*/
#define SCRYPT_SAFE_N 30 /* This is much higher than you want. It's just
* a blocker for insane defines
*/
#define SCRYPT_SALT_LEN 16 /* This is just a recommended size */
/* Standard MCF is:
$s1 Identifier, three chars
$0e0810 Work order and separator, six chars
Formula for binary to base64 length = ceil(n/3)*4
$pcL+DWle903AXcKJVwMffA== Salt is 16 bytes, or 24 in Base64
$dn+9ujljVc5JTJMC2fYu1ZEHdJyqYkOurmcrBQbMHUfnD6qxbTmNiR075ohNBZjvp66E2aV1pfOrmyNHUefjMg== Hash is 64 bytes, or 88 in Base64.
Work order, salt and hash have separators (3)
3 + 6 + 24 + 88 + 3 + null byte = 125
This is rounded up to a multiple of four for alignment
*/
#define SCRYPT_MCF_LEN 128
#define SCRYPT_MCF_ID "$s1"
#define SCRYPT_N 16384
#define SCRYPT_r 8
#define SCRYPT_p 16
#endif /* !_CRYPTO_SCRYPT_H_ */
| drangob/alternativetoqkd | src/main/randombitlib/scrypt/libscrypt.h | C | gpl-3.0 | 2,568 |
/*
* Opus decoder/demuxer common functions
* Copyright (c) 2012 Andrew D'Addesio
* Copyright (c) 2013-2014 Mozilla Corporation
* Copyright (c) 2016 Rostislav Pehlivanov <[email protected]>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_OPUS_CELT_H
#define AVCODEC_OPUS_CELT_H
#include <float.h>
#include "opus.h"
#include "mdct15.h"
#include "libavutil/float_dsp.h"
#include "libavutil/libm.h"
#define CELT_VECTORS 11
#define CELT_ALLOC_STEPS 6
#define CELT_FINE_OFFSET 21
#define CELT_MAX_FINE_BITS 8
#define CELT_NORM_SCALE 16384
#define CELT_QTHETA_OFFSET 4
#define CELT_QTHETA_OFFSET_TWOPHASE 16
#define CELT_EMPH_COEFF 0.85000610f
#define CELT_POSTFILTER_MINPERIOD 15
#define CELT_ENERGY_SILENCE (-28.0f)
enum CeltSpread {
CELT_SPREAD_NONE,
CELT_SPREAD_LIGHT,
CELT_SPREAD_NORMAL,
CELT_SPREAD_AGGRESSIVE
};
enum CeltBlockSize {
CELT_BLOCK_120,
CELT_BLOCK_240,
CELT_BLOCK_480,
CELT_BLOCK_960,
CELT_BLOCK_NB
};
typedef struct CeltBlock {
float energy[CELT_MAX_BANDS];
float lin_energy[CELT_MAX_BANDS];
float error_energy[CELT_MAX_BANDS];
float prev_energy[2][CELT_MAX_BANDS];
uint8_t collapse_masks[CELT_MAX_BANDS];
int band_bins[CELT_MAX_BANDS]; /* MDCT bins per band */
float *band_coeffs[CELT_MAX_BANDS];
/* buffer for mdct output + postfilter */
DECLARE_ALIGNED(32, float, buf)[2048];
DECLARE_ALIGNED(32, float, coeffs)[CELT_MAX_FRAME_SIZE];
/* Used by the encoder */
DECLARE_ALIGNED(32, float, overlap)[120];
DECLARE_ALIGNED(32, float, samples)[CELT_MAX_FRAME_SIZE];
/* postfilter parameters */
int pf_period_new;
float pf_gains_new[3];
int pf_period;
float pf_gains[3];
int pf_period_old;
float pf_gains_old[3];
float emph_coeff;
} CeltBlock;
struct CeltFrame {
// constant values that do not change during context lifetime
AVCodecContext *avctx;
MDCT15Context *imdct[4];
AVFloatDSPContext *dsp;
CeltBlock block[2];
int channels;
int output_channels;
enum CeltBlockSize size;
int start_band;
int end_band;
int coded_bands;
int transient;
int intra;
int pfilter;
int skip_band_floor;
int tf_select;
int alloc_trim;
int alloc_boost[CELT_MAX_BANDS];
int blocks; /* number of iMDCT blocks in the frame, depends on transient */
int blocksize; /* size of each block */
int silence; /* Frame is filled with silence */
int anticollapse_needed; /* Whether to expect an anticollapse bit */
int anticollapse; /* Encoded anticollapse bit */
int intensity_stereo;
int dual_stereo;
int flushed;
uint32_t seed;
enum CeltSpread spread;
/* Bit allocation */
int framebits;
int remaining;
int remaining2;
int caps [CELT_MAX_BANDS];
int fine_bits [CELT_MAX_BANDS];
int fine_priority[CELT_MAX_BANDS];
int pulses [CELT_MAX_BANDS];
int tf_change [CELT_MAX_BANDS];
DECLARE_ALIGNED(32, float, scratch)[22 * 8]; // MAX(ff_celt_freq_range) * 1<<CELT_MAX_LOG_BLOCKS
};
/* LCG for noise generation */
static av_always_inline uint32_t celt_rng(CeltFrame *f)
{
f->seed = 1664525 * f->seed + 1013904223;
return f->seed;
}
static av_always_inline void celt_renormalize_vector(float *X, int N, float gain)
{
int i;
float g = 1e-15f;
for (i = 0; i < N; i++)
g += X[i] * X[i];
g = gain / sqrtf(g);
for (i = 0; i < N; i++)
X[i] *= g;
}
int ff_celt_init(AVCodecContext *avctx, CeltFrame **f, int output_channels);
void ff_celt_free(CeltFrame **f);
void ff_celt_flush(CeltFrame *f);
int ff_celt_decode_frame(CeltFrame *f, OpusRangeCoder *rc, float **output,
int coded_channels, int frame_size, int startband, int endband);
#endif /* AVCODEC_OPUS_CELT_H */
| OshinKaramian/jsmc | server/ffmpeg/linux/libavcodec/opus_celt.h | C | gpl-3.0 | 4,698 |
<?php
/**
* -----------------------------------------------------------------------------
* @package smartVISU
* @author Martin Gleiß
* @copyright 2012 - 2015
* @license GPL [http://www.gnu.de]
* -----------------------------------------------------------------------------
*/
require_once '../../../lib/includes.php';
require_once const_path_system.'calendar/calendar.php';
/**
* This class creates some calendar entries
*/
class calendar_offline extends calendar
{
/**
* Check if the cache-file exists
*/
public function run()
{
for ($i = 1; $i <= $this->count; $i++)
{
$tag = $tag + rand(1, 3);
$event = array('Meeting', 'Doctor', 'Waste');
$waste = array('#222266', '#664422', '#555555', '#666600');
$title = $event[rand(0, 2)];
$this->data[] = array(
'pos' => $i,
'start' => date('y-m-d', time() + $tag * 24 * 60 * 60).' '.rand(8, 14).':00:00',
'end' => date('y-m-d', time() + $tag * 24 * 60 * 60).' '.rand(15, 20).':00:00',
'title' => $title,
'where' => ($title == 'Doctor' ? 'Würzburg' : ''),
'icon' => ($title == 'Waste' ? 'icons/ws/message_garbage.png' : ''),
'color' => ($title == 'Waste' ? $waste[rand(0, 3)] : '')
);
}
}
}
// -----------------------------------------------------------------------------
// call the service
// -----------------------------------------------------------------------------
$service = new calendar_offline(array_merge($_GET, $_POST));
echo $service->json();
?>
| glueckm/smartvisu | lib/calendar/service/offline.php | PHP | gpl-3.0 | 1,500 |
<?php
/*
+ ------------------------------------------------------------------------------+
| Русский языковой пакет для e107 0.7.26 |
| Сайт: http://www.e107club.ru |
| Почта: [email protected] |
| Ревизия: 1.0 |
| Кодировка: utf-8 |
| Дата: 25.09.2011 05:05:05 |
| Автор: © Кадников Александр [Predator] |
| © е107 Клуб 2010-2011. Все права защищены. |
| |
| Russian Language Pack for e107 0.7.26 |
| Site: http://www.e107club.ru |
| Email: [email protected] |
| Revision: 1.0 |
| Charset: utf-8 |
| Date: 25.09.2011 05:05:05 |
| Author: © Alexander Kadnikov [Predator] |
| © е107 Club 2010-2011. All Rights Reserved. |
+-------------------------------------------------------------------------------+
*/
define('CLOCK_MENU_L1', 'Конфигурация сохранена');
define('CLOCK_MENU_L2', 'Заголовок');
define('CLOCK_MENU_L3', 'Обновить настройки');
define('CLOCK_MENU_L4', 'Настройки меню Часов');
define('CLOCK_MENU_L5', 'Понедельник,');
define('CLOCK_MENU_L6', 'Вторник,');
define('CLOCK_MENU_L7', 'Среда,');
define('CLOCK_MENU_L8', 'Четверг,');
define('CLOCK_MENU_L9', 'Пятница,');
define('CLOCK_MENU_L10', 'Суббота,');
define('CLOCK_MENU_L11', 'Воскресенье,');
define('CLOCK_MENU_L12', 'Января');
define('CLOCK_MENU_L13', 'Февраля');
define('CLOCK_MENU_L14', 'Марта');
define('CLOCK_MENU_L15', 'Апреля');
define('CLOCK_MENU_L16', 'Мая');
define('CLOCK_MENU_L17', 'Июня');
define('CLOCK_MENU_L18', 'Июля');
define('CLOCK_MENU_L19', 'Августа');
define('CLOCK_MENU_L20', 'Сентября');
define('CLOCK_MENU_L21', 'Октября');
define('CLOCK_MENU_L22', 'Ноября');
define('CLOCK_MENU_L23', 'Декабря');
define('CLOCK_MENU_L24', '');
?> | kazancevsm/r107 | 0.1.5/plugins/clock_menu/languages/Russian.php | PHP | gpl-3.0 | 2,165 |
/*
* This file is part of ACADO Toolkit.
*
* ACADO Toolkit -- A Toolkit for Automatic Control and Dynamic Optimization.
* Copyright (C) 2008-2014 by Boris Houska, Hans Joachim Ferreau,
* Milan Vukov, Rien Quirynen, KU Leuven.
* Developed within the Optimization in Engineering Center (OPTEC)
* under supervision of Moritz Diehl. All rights reserved.
*
* ACADO Toolkit 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.
*
* ACADO Toolkit 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 ACADO Toolkit; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/acado/code_generation/integrators/irk_lifted_adjoint_export.hpp
* \author Rien Quirynen
* \date 2015
*/
#ifndef ACADO_TOOLKIT_LIFTED_IRK_ADJOINT_EXPORT_HPP
#define ACADO_TOOLKIT_LIFTED_IRK_ADJOINT_EXPORT_HPP
#include <acado/code_generation/integrators/irk_lifted_forward_export.hpp>
BEGIN_NAMESPACE_ACADO
/**
* \brief Allows to export a tailored lifted implicit Runge-Kutta integrator with adjoint sensitivity generation for extra fast model predictive control.
*
* \ingroup NumericalAlgorithms
*
* The class AdjointLiftedIRKExport allows to export a tailored lifted implicit Runge-Kutta integrator
* with adjoint sensitivity generation for extra fast model predictive control.
*
* \author Rien Quirynen
*/
class AdjointLiftedIRKExport : public ForwardLiftedIRKExport
{
//
// PUBLIC MEMBER FUNCTIONS:
//
public:
/** Default constructor.
*
* @param[in] _userInteraction Pointer to corresponding user interface.
* @param[in] _commonHeaderName Name of common header file to be included.
*/
AdjointLiftedIRKExport( UserInteraction* _userInteraction = 0,
const std::string& _commonHeaderName = ""
);
/** Copy constructor (deep copy).
*
* @param[in] arg Right-hand side object.
*/
AdjointLiftedIRKExport( const AdjointLiftedIRKExport& arg
);
/** Destructor.
*/
virtual ~AdjointLiftedIRKExport( );
/** Assignment operator (deep copy).
*
* @param[in] arg Right-hand side object.
*/
AdjointLiftedIRKExport& operator=( const AdjointLiftedIRKExport& arg
);
/** Initializes export of a tailored integrator.
*
* \return SUCCESSFUL_RETURN
*/
virtual returnValue setup( );
/** Assigns Differential Equation to be used by the integrator.
*
* @param[in] rhs Right-hand side expression.
*
* \return SUCCESSFUL_RETURN
*/
virtual returnValue setDifferentialEquation( const Expression& rhs );
/** Adds all data declarations of the auto-generated integrator to given list of declarations.
*
* @param[in] declarations List of declarations.
*
* \return SUCCESSFUL_RETURN
*/
virtual returnValue getDataDeclarations( ExportStatementBlock& declarations,
ExportStruct dataStruct = ACADO_ANY
) const;
/** Adds all function (forward) declarations of the auto-generated integrator to given list of declarations.
*
* @param[in] declarations List of declarations.
*
* \return SUCCESSFUL_RETURN
*/
virtual returnValue getFunctionDeclarations( ExportStatementBlock& declarations
) const;
/** Exports source code of the auto-generated integrator into the given directory.
*
* @param[in] code Code block containing the auto-generated integrator.
*
* \return SUCCESSFUL_RETURN
*/
virtual returnValue getCode( ExportStatementBlock& code
);
protected:
Expression returnLowerTriangular( const Expression& expr );
virtual returnValue evaluateRhsSensitivities( ExportStatementBlock* block,
const ExportIndex& index1,
const ExportIndex& index2,
const ExportIndex& index3,
const ExportIndex& tmp_index1,
const ExportIndex& tmp_index2 );
virtual returnValue updateImplicitSystem( ExportStatementBlock* block,
const ExportIndex& index1,
const ExportIndex& index2,
const ExportIndex& tmp_index );
/** Returns the largest global export variable.
*
* \return SUCCESSFUL_RETURN
*/
ExportVariable getAuxVariable() const;
protected:
ExportAcadoFunction diffs_sweep; /**< Module to export the evaluation of a forward sweep of the derivatives of the ordinary differential equations. */
ExportVariable rk_diffsTemp2_full;
ExportVariable rk_S_traj; /**< Variable containing the forward trajectory of the first order sensitivities. */
// ExportVariable rk_A_traj; /**< Variable containing the factorized matrix of the linear system over the forward trajectory. */
// ExportVariable rk_aux_traj; /**< Variable containing the factorized matrix of the linear system over the forward trajectory. */
};
CLOSE_NAMESPACE_ACADO
#endif // ACADO_TOOLKIT_LIFTED_IRK_ADJOINT_EXPORT_HPP
// end of file.
| clearpathrobotics/acado | acado/code_generation/integrators/irk_lifted_adjoint_export.hpp | C++ | gpl-3.0 | 5,512 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Library\PhpParser;
use Magento\TestFramework\Integrity\Library\PhpParser\Uses;
/**
*/
class UsesTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Uses
*/
protected $uses;
/**
* @inheritdoc
*/
public function setUp()
{
$this->uses = new Uses();
}
/**
* Covered hasUses method
*
* @dataProvider usesDataProvider
* @test
*
* @param array $tokens
*/
public function testHasUses($tokens)
{
foreach ($tokens as $k => $token) {
$this->uses->parse($token, $k);
}
$this->assertTrue($this->uses->hasUses());
}
/**
* Example tokenizer results
*
* @return array
*/
public function usesDataProvider()
{
return [
'simple' => [
[
0 => [T_USE, 'use '],
1 => [T_STRING, 'Magento'],
2 => [T_NS_SEPARATOR, '\\'],
3 => [T_STRING, 'Core'],
4 => [T_NS_SEPARATOR, '\\'],
5 => [T_STRING, 'Model'],
6 => [T_NS_SEPARATOR, '\\'],
7 => [T_STRING, 'Object'],
8 => ';',
],
],
'several_simple' => [
[
0 => [T_USE, 'use '],
1 => [T_STRING, 'Magento'],
2 => [T_NS_SEPARATOR, '\\'],
3 => [T_STRING, 'Core'],
4 => [T_NS_SEPARATOR, '\\'],
5 => [T_STRING, 'Model'],
6 => [T_NS_SEPARATOR, '\\'],
7 => [T_STRING, 'Object'],
8 => ';',
9 => [T_USE, 'use '],
10 => [T_STRING, 'Magento'],
11 => [T_NS_SEPARATOR, '\\'],
12 => [T_STRING, 'Core'],
13 => [T_NS_SEPARATOR, '\\'],
14 => [T_STRING, 'Model'],
15 => [T_NS_SEPARATOR, '\\'],
16 => [T_STRING, 'Object2 '],
17 => [T_AS, 'as '],
18 => [T_STRING, 'OtherObject'],
19 => ';',
],
],
'several_with_comma_separate' => [
[
0 => [T_USE, 'use '],
1 => [T_STRING, 'Magento'],
2 => [T_NS_SEPARATOR, '\\'],
3 => [T_STRING, 'Core'],
4 => [T_NS_SEPARATOR, '\\'],
5 => [T_STRING, 'Model'],
6 => [T_NS_SEPARATOR, '\\'],
7 => [T_STRING, 'Object'],
8 => ',',
9 => [T_STRING, 'Magento'],
10 => [T_NS_SEPARATOR, '\\'],
11 => [T_STRING, 'Core'],
12 => [T_NS_SEPARATOR, '\\'],
13 => [T_STRING, 'Model'],
14 => [T_NS_SEPARATOR, '\\'],
15 => [T_STRING, 'Object2 '],
16 => [T_AS, 'as '],
17 => [T_STRING, 'OtherObject'],
18 => ';',
],
]
];
}
/**
* Covered getClassNameWithNamespace for global classes
*
* @test
*/
public function testGetClassNameWithNamespaceForGlobalClass()
{
$this->assertEquals(
'\Magento\Core\Model\Object2',
$this->uses->getClassNameWithNamespace('\Magento\Core\Model\Object2')
);
}
/**
* Covered getClassNameWithNamespace
*
* @test
* @dataProvider classNamesDataProvider
*/
public function testGetClassNameWithNamespace($className, $tokens)
{
foreach ($tokens as $k => $token) {
$this->uses->parse($token, $k);
}
$this->assertEquals('Magento\Core\Model\Object2', $this->uses->getClassNameWithNamespace($className));
}
/**
* Return different uses token list and class name
*
* @return array
*/
public function classNamesDataProvider()
{
return [
'class_from_uses' => [
'Object2',
[
0 => [T_USE, 'use '],
1 => [T_STRING, 'Magento'],
2 => [T_NS_SEPARATOR, '\\'],
3 => [T_STRING, 'Core'],
4 => [T_NS_SEPARATOR, '\\'],
5 => [T_STRING, 'Model'],
6 => [T_NS_SEPARATOR, '\\'],
7 => [T_STRING, 'Object2'],
8 => ';'
],
],
'class_from_uses_with_as' => [
'ObjectOther',
[
0 => [T_USE, 'use '],
1 => [T_STRING, 'Magento'],
2 => [T_NS_SEPARATOR, '\\'],
3 => [T_STRING, 'Core'],
4 => [T_NS_SEPARATOR, '\\'],
5 => [T_STRING, 'Model'],
6 => [T_NS_SEPARATOR, '\\'],
7 => [T_STRING, 'Object2 '],
8 => [T_AS, 'as '],
9 => [T_STRING, 'ObjectOther'],
10 => ';'
],
]
];
}
}
| rajmahesh/magento2-master | vendor/magento/magento2-base/dev/tests/static/framework/tests/unit/testsuite/Magento/Test/Integrity/Library/PhpParser/UsesTest.php | PHP | gpl-3.0 | 5,480 |
/**********************************************************************
* $Id$ lpc17xx_qei.h 2010-05-21
*//**
* @file lpc17xx_qei.h
* @brief Contains all macro definitions and function prototypes
* support for QEI firmware library on LPC17xx
* @version 2.0
* @date 21. May. 2010
* @author NXP MCU SW Application Team
*
* Copyright(C) 2010, NXP Semiconductor
* All rights reserved.
*
***********************************************************************
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* products. This software is supplied "AS IS" without any warranties.
* NXP Semiconductors assumes no responsibility or liability for the
* use of the software, conveys no license or title under any patent,
* copyright, or mask work right to the product. NXP Semiconductors
* reserves the right to make changes in the software without
* notification. NXP Semiconductors also make no representation or
* warranty that such application will be suitable for the specified
* use without further testing or modification.
**********************************************************************/
/* Peripheral group ----------------------------------------------------------- */
/** @defgroup QEI QEI (Quadrature Encoder Interface)
* @ingroup LPC1700CMSIS_FwLib_Drivers
* @{
*/
#ifndef LPC17XX_QEI_H_
#define LPC17XX_QEI_H_
/* Includes ------------------------------------------------------------------- */
#include "LPC17xx.h"
#include "lpc_types.h"
#ifdef __cplusplus
extern "C"
{
#endif
/* Public Macros -------------------------------------------------------------- */
/** @defgroup QEI_Public_Macros QEI Public Macros
* @{
*/
/* QEI Reset types */
#define QEI_RESET_POS QEI_CON_RESP /**< Reset position counter */
#define QEI_RESET_POSOnIDX QEI_CON_RESPI /**< Reset Posistion Counter on Index */
#define QEI_RESET_VEL QEI_CON_RESV /**< Reset Velocity */
#define QEI_RESET_IDX QEI_CON_RESI /**< Reset Index Counter */
/* QEI Direction Invert Type Option */
#define QEI_DIRINV_NONE ((uint32_t)(0)) /**< Direction is not inverted */
#define QEI_DIRINV_CMPL ((uint32_t)(1)) /**< Direction is complemented */
/* QEI Signal Mode Option */
#define QEI_SIGNALMODE_QUAD ((uint32_t)(0)) /**< Signal operation: Quadrature phase mode */
#define QEI_SIGNALMODE_CLKDIR ((uint32_t)(1)) /**< Signal operation: Clock/Direction mode */
/* QEI Capture Mode Option */
#define QEI_CAPMODE_2X ((uint32_t)(0)) /**< Capture mode: Only Phase-A edges are counted (2X) */
#define QEI_CAPMODE_4X ((uint32_t)(1)) /**< Capture mode: BOTH PhA and PhB edges are counted (4X)*/
/* QEI Invert Index Signal Option */
#define QEI_INVINX_NONE ((uint32_t)(0)) /**< Invert Index signal option: None */
#define QEI_INVINX_EN ((uint32_t)(1)) /**< Invert Index signal option: Enable */
/* QEI timer reload option */
#define QEI_TIMERRELOAD_TICKVAL ((uint8_t)(0)) /**< Reload value in absolute value */
#define QEI_TIMERRELOAD_USVAL ((uint8_t)(1)) /**< Reload value in microsecond value */
/* QEI Flag Status type */
#define QEI_STATUS_DIR ((uint32_t)(1<<0)) /**< Direction status */
/* QEI Compare Position channel option */
#define QEI_COMPPOS_CH_0 ((uint8_t)(0)) /**< QEI compare position channel 0 */
#define QEI_COMPPOS_CH_1 ((uint8_t)(1)) /**< QEI compare position channel 1 */
#define QEI_COMPPOS_CH_2 ((uint8_t)(2)) /**< QEI compare position channel 2 */
/* QEI interrupt flag type */
#define QEI_INTFLAG_INX_Int ((uint32_t)(1<<0)) /**< index pulse was detected interrupt */
#define QEI_INTFLAG_TIM_Int ((uint32_t)(1<<1)) /**< Velocity timer over flow interrupt */
#define QEI_INTFLAG_VELC_Int ((uint32_t)(1<<2)) /**< Capture velocity is less than compare interrupt */
#define QEI_INTFLAG_DIR_Int ((uint32_t)(1<<3)) /**< Change of direction interrupt */
#define QEI_INTFLAG_ERR_Int ((uint32_t)(1<<4)) /**< An encoder phase error interrupt */
#define QEI_INTFLAG_ENCLK_Int ((uint32_t)(1<<5)) /**< An encoder clock pulse was detected interrupt */
#define QEI_INTFLAG_POS0_Int ((uint32_t)(1<<6)) /**< position 0 compare value is equal to the
current position interrupt */
#define QEI_INTFLAG_POS1_Int ((uint32_t)(1<<7)) /**< position 1 compare value is equal to the
current position interrupt */
#define QEI_INTFLAG_POS2_Int ((uint32_t)(1<<8)) /**< position 2 compare value is equal to the
current position interrupt */
#define QEI_INTFLAG_REV_Int ((uint32_t)(1<<9)) /**< Index compare value is equal to the current
index count interrupt */
#define QEI_INTFLAG_POS0REV_Int ((uint32_t)(1<<10)) /**< Combined position 0 and revolution count interrupt */
#define QEI_INTFLAG_POS1REV_Int ((uint32_t)(1<<11)) /**< Combined position 1 and revolution count interrupt */
#define QEI_INTFLAG_POS2REV_Int ((uint32_t)(1<<12)) /**< Combined position 2 and revolution count interrupt */
/**
* @}
*/
/* Private Macros ------------------------------------------------------------- */
/** @defgroup QEI_Private_Macros QEI Private Macros
* @{
*/
/* --------------------- BIT DEFINITIONS -------------------------------------- */
/* Quadrature Encoder Interface Control Register Definition --------------------- */
/*********************************************************************//**
* Macro defines for QEI Control register
**********************************************************************/
#define QEI_CON_RESP ((uint32_t)(1<<0)) /**< Reset position counter */
#define QEI_CON_RESPI ((uint32_t)(1<<1)) /**< Reset Posistion Counter on Index */
#define QEI_CON_RESV ((uint32_t)(1<<2)) /**< Reset Velocity */
#define QEI_CON_RESI ((uint32_t)(1<<3)) /**< Reset Index Counter */
#define QEI_CON_BITMASK ((uint32_t)(0x0F)) /**< QEI Control register bit-mask */
/*********************************************************************//**
* Macro defines for QEI Configuration register
**********************************************************************/
#define QEI_CONF_DIRINV ((uint32_t)(1<<0)) /**< Direction Invert */
#define QEI_CONF_SIGMODE ((uint32_t)(1<<1)) /**< Signal mode */
#define QEI_CONF_CAPMODE ((uint32_t)(1<<2)) /**< Capture mode */
#define QEI_CONF_INVINX ((uint32_t)(1<<3)) /**< Invert index */
#define QEI_CONF_BITMASK ((uint32_t)(0x0F)) /**< QEI Configuration register bit-mask */
/*********************************************************************//**
* Macro defines for QEI Status register
**********************************************************************/
#define QEI_STAT_DIR ((uint32_t)(1<<0)) /**< Direction bit */
#define QEI_STAT_BITMASK ((uint32_t)(1<<0)) /**< QEI status register bit-mask */
/* Quadrature Encoder Interface Interrupt registers definitions --------------------- */
/*********************************************************************//**
* Macro defines for QEI Interrupt Status register
**********************************************************************/
#define QEI_INTSTAT_INX_Int ((uint32_t)(1<<0)) /**< Indicates that an index pulse was detected */
#define QEI_INTSTAT_TIM_Int ((uint32_t)(1<<1)) /**< Indicates that a velocity timer overflow occurred */
#define QEI_INTSTAT_VELC_Int ((uint32_t)(1<<2)) /**< Indicates that capture velocity is less than compare velocity */
#define QEI_INTSTAT_DIR_Int ((uint32_t)(1<<3)) /**< Indicates that a change of direction was detected */
#define QEI_INTSTAT_ERR_Int ((uint32_t)(1<<4)) /**< Indicates that an encoder phase error was detected */
#define QEI_INTSTAT_ENCLK_Int ((uint32_t)(1<<5)) /**< Indicates that and encoder clock pulse was detected */
#define QEI_INTSTAT_POS0_Int ((uint32_t)(1<<6)) /**< Indicates that the position 0 compare value is equal to the
current position */
#define QEI_INTSTAT_POS1_Int ((uint32_t)(1<<7)) /**< Indicates that the position 1compare value is equal to the
current position */
#define QEI_INTSTAT_POS2_Int ((uint32_t)(1<<8)) /**< Indicates that the position 2 compare value is equal to the
current position */
#define QEI_INTSTAT_REV_Int ((uint32_t)(1<<9)) /**< Indicates that the index compare value is equal to the current
index count */
#define QEI_INTSTAT_POS0REV_Int ((uint32_t)(1<<10)) /**< Combined position 0 and revolution count interrupt. Set when
both the POS0_Int bit is set and the REV_Int is set */
#define QEI_INTSTAT_POS1REV_Int ((uint32_t)(1<<11)) /**< Combined position 1 and revolution count interrupt. Set when
both the POS1_Int bit is set and the REV_Int is set */
#define QEI_INTSTAT_POS2REV_Int ((uint32_t)(1<<12)) /**< Combined position 2 and revolution count interrupt. Set when
both the POS2_Int bit is set and the REV_Int is set */
#define QEI_INTSTAT_BITMASK ((uint32_t)(0x1FFF)) /**< QEI Interrupt Status register bit-mask */
/*********************************************************************//**
* Macro defines for QEI Interrupt Set register
**********************************************************************/
#define QEI_INTSET_INX_Int ((uint32_t)(1<<0)) /**< Set Bit Indicates that an index pulse was detected */
#define QEI_INTSET_TIM_Int ((uint32_t)(1<<1)) /**< Set Bit Indicates that a velocity timer overflow occurred */
#define QEI_INTSET_VELC_Int ((uint32_t)(1<<2)) /**< Set Bit Indicates that capture velocity is less than compare velocity */
#define QEI_INTSET_DIR_Int ((uint32_t)(1<<3)) /**< Set Bit Indicates that a change of direction was detected */
#define QEI_INTSET_ERR_Int ((uint32_t)(1<<4)) /**< Set Bit Indicates that an encoder phase error was detected */
#define QEI_INTSET_ENCLK_Int ((uint32_t)(1<<5)) /**< Set Bit Indicates that and encoder clock pulse was detected */
#define QEI_INTSET_POS0_Int ((uint32_t)(1<<6)) /**< Set Bit Indicates that the position 0 compare value is equal to the
current position */
#define QEI_INTSET_POS1_Int ((uint32_t)(1<<7)) /**< Set Bit Indicates that the position 1compare value is equal to the
current position */
#define QEI_INTSET_POS2_Int ((uint32_t)(1<<8)) /**< Set Bit Indicates that the position 2 compare value is equal to the
current position */
#define QEI_INTSET_REV_Int ((uint32_t)(1<<9)) /**< Set Bit Indicates that the index compare value is equal to the current
index count */
#define QEI_INTSET_POS0REV_Int ((uint32_t)(1<<10)) /**< Set Bit that combined position 0 and revolution count interrupt */
#define QEI_INTSET_POS1REV_Int ((uint32_t)(1<<11)) /**< Set Bit that Combined position 1 and revolution count interrupt */
#define QEI_INTSET_POS2REV_Int ((uint32_t)(1<<12)) /**< Set Bit that Combined position 2 and revolution count interrupt */
#define QEI_INTSET_BITMASK ((uint32_t)(0x1FFF)) /**< QEI Interrupt Set register bit-mask */
/*********************************************************************//**
* Macro defines for QEI Interrupt Clear register
**********************************************************************/
#define QEI_INTCLR_INX_Int ((uint32_t)(1<<0)) /**< Clear Bit Indicates that an index pulse was detected */
#define QEI_INTCLR_TIM_Int ((uint32_t)(1<<1)) /**< Clear Bit Indicates that a velocity timer overflow occurred */
#define QEI_INTCLR_VELC_Int ((uint32_t)(1<<2)) /**< Clear Bit Indicates that capture velocity is less than compare velocity */
#define QEI_INTCLR_DIR_Int ((uint32_t)(1<<3)) /**< Clear Bit Indicates that a change of direction was detected */
#define QEI_INTCLR_ERR_Int ((uint32_t)(1<<4)) /**< Clear Bit Indicates that an encoder phase error was detected */
#define QEI_INTCLR_ENCLK_Int ((uint32_t)(1<<5)) /**< Clear Bit Indicates that and encoder clock pulse was detected */
#define QEI_INTCLR_POS0_Int ((uint32_t)(1<<6)) /**< Clear Bit Indicates that the position 0 compare value is equal to the
current position */
#define QEI_INTCLR_POS1_Int ((uint32_t)(1<<7)) /**< Clear Bit Indicates that the position 1compare value is equal to the
current position */
#define QEI_INTCLR_POS2_Int ((uint32_t)(1<<8)) /**< Clear Bit Indicates that the position 2 compare value is equal to the
current position */
#define QEI_INTCLR_REV_Int ((uint32_t)(1<<9)) /**< Clear Bit Indicates that the index compare value is equal to the current
index count */
#define QEI_INTCLR_POS0REV_Int ((uint32_t)(1<<10)) /**< Clear Bit that combined position 0 and revolution count interrupt */
#define QEI_INTCLR_POS1REV_Int ((uint32_t)(1<<11)) /**< Clear Bit that Combined position 1 and revolution count interrupt */
#define QEI_INTCLR_POS2REV_Int ((uint32_t)(1<<12)) /**< Clear Bit that Combined position 2 and revolution count interrupt */
#define QEI_INTCLR_BITMASK ((uint32_t)(0x1FFF)) /**< QEI Interrupt Clear register bit-mask */
/*********************************************************************//**
* Macro defines for QEI Interrupt Enable register
**********************************************************************/
#define QEI_INTEN_INX_Int ((uint32_t)(1<<0)) /**< Enabled Interrupt Bit Indicates that an index pulse was detected */
#define QEI_INTEN_TIM_Int ((uint32_t)(1<<1)) /**< Enabled Interrupt Bit Indicates that a velocity timer overflow occurred */
#define QEI_INTEN_VELC_Int ((uint32_t)(1<<2)) /**< Enabled Interrupt Bit Indicates that capture velocity is less than compare velocity */
#define QEI_INTEN_DIR_Int ((uint32_t)(1<<3)) /**< Enabled Interrupt Bit Indicates that a change of direction was detected */
#define QEI_INTEN_ERR_Int ((uint32_t)(1<<4)) /**< Enabled Interrupt Bit Indicates that an encoder phase error was detected */
#define QEI_INTEN_ENCLK_Int ((uint32_t)(1<<5)) /**< Enabled Interrupt Bit Indicates that and encoder clock pulse was detected */
#define QEI_INTEN_POS0_Int ((uint32_t)(1<<6)) /**< Enabled Interrupt Bit Indicates that the position 0 compare value is equal to the
current position */
#define QEI_INTEN_POS1_Int ((uint32_t)(1<<7)) /**< Enabled Interrupt Bit Indicates that the position 1compare value is equal to the
current position */
#define QEI_INTEN_POS2_Int ((uint32_t)(1<<8)) /**< Enabled Interrupt Bit Indicates that the position 2 compare value is equal to the
current position */
#define QEI_INTEN_REV_Int ((uint32_t)(1<<9)) /**< Enabled Interrupt Bit Indicates that the index compare value is equal to the current
index count */
#define QEI_INTEN_POS0REV_Int ((uint32_t)(1<<10)) /**< Enabled Interrupt Bit that combined position 0 and revolution count interrupt */
#define QEI_INTEN_POS1REV_Int ((uint32_t)(1<<11)) /**< Enabled Interrupt Bit that Combined position 1 and revolution count interrupt */
#define QEI_INTEN_POS2REV_Int ((uint32_t)(1<<12)) /**< Enabled Interrupt Bit that Combined position 2 and revolution count interrupt */
#define QEI_INTEN_BITMASK ((uint32_t)(0x1FFF)) /**< QEI Interrupt Enable register bit-mask */
/*********************************************************************//**
* Macro defines for QEI Interrupt Enable Set register
**********************************************************************/
#define QEI_IESET_INX_Int ((uint32_t)(1<<0)) /**< Set Enable Interrupt Bit Indicates that an index pulse was detected */
#define QEI_IESET_TIM_Int ((uint32_t)(1<<1)) /**< Set Enable Interrupt Bit Indicates that a velocity timer overflow occurred */
#define QEI_IESET_VELC_Int ((uint32_t)(1<<2)) /**< Set Enable Interrupt Bit Indicates that capture velocity is less than compare velocity */
#define QEI_IESET_DIR_Int ((uint32_t)(1<<3)) /**< Set Enable Interrupt Bit Indicates that a change of direction was detected */
#define QEI_IESET_ERR_Int ((uint32_t)(1<<4)) /**< Set Enable Interrupt Bit Indicates that an encoder phase error was detected */
#define QEI_IESET_ENCLK_Int ((uint32_t)(1<<5)) /**< Set Enable Interrupt Bit Indicates that and encoder clock pulse was detected */
#define QEI_IESET_POS0_Int ((uint32_t)(1<<6)) /**< Set Enable Interrupt Bit Indicates that the position 0 compare value is equal to the
current position */
#define QEI_IESET_POS1_Int ((uint32_t)(1<<7)) /**< Set Enable Interrupt Bit Indicates that the position 1compare value is equal to the
current position */
#define QEI_IESET_POS2_Int ((uint32_t)(1<<8)) /**< Set Enable Interrupt Bit Indicates that the position 2 compare value is equal to the
current position */
#define QEI_IESET_REV_Int ((uint32_t)(1<<9)) /**< Set Enable Interrupt Bit Indicates that the index compare value is equal to the current
index count */
#define QEI_IESET_POS0REV_Int ((uint32_t)(1<<10)) /**< Set Enable Interrupt Bit that combined position 0 and revolution count interrupt */
#define QEI_IESET_POS1REV_Int ((uint32_t)(1<<11)) /**< Set Enable Interrupt Bit that Combined position 1 and revolution count interrupt */
#define QEI_IESET_POS2REV_Int ((uint32_t)(1<<12)) /**< Set Enable Interrupt Bit that Combined position 2 and revolution count interrupt */
#define QEI_IESET_BITMASK ((uint32_t)(0x1FFF)) /**< QEI Interrupt Enable Set register bit-mask */
/*********************************************************************//**
* Macro defines for QEI Interrupt Enable Clear register
**********************************************************************/
#define QEI_IECLR_INX_Int ((uint32_t)(1<<0)) /**< Clear Enabled Interrupt Bit Indicates that an index pulse was detected */
#define QEI_IECLR_TIM_Int ((uint32_t)(1<<1)) /**< Clear Enabled Interrupt Bit Indicates that a velocity timer overflow occurred */
#define QEI_IECLR_VELC_Int ((uint32_t)(1<<2)) /**< Clear Enabled Interrupt Bit Indicates that capture velocity is less than compare velocity */
#define QEI_IECLR_DIR_Int ((uint32_t)(1<<3)) /**< Clear Enabled Interrupt Bit Indicates that a change of direction was detected */
#define QEI_IECLR_ERR_Int ((uint32_t)(1<<4)) /**< Clear Enabled Interrupt Bit Indicates that an encoder phase error was detected */
#define QEI_IECLR_ENCLK_Int ((uint32_t)(1<<5)) /**< Clear Enabled Interrupt Bit Indicates that and encoder clock pulse was detected */
#define QEI_IECLR_POS0_Int ((uint32_t)(1<<6)) /**< Clear Enabled Interrupt Bit Indicates that the position 0 compare value is equal to the
current position */
#define QEI_IECLR_POS1_Int ((uint32_t)(1<<7)) /**< Clear Enabled Interrupt Bit Indicates that the position 1compare value is equal to the
current position */
#define QEI_IECLR_POS2_Int ((uint32_t)(1<<8)) /**< Clear Enabled Interrupt Bit Indicates that the position 2 compare value is equal to the
current position */
#define QEI_IECLR_REV_Int ((uint32_t)(1<<9)) /**< Clear Enabled Interrupt Bit Indicates that the index compare value is equal to the current
index count */
#define QEI_IECLR_POS0REV_Int ((uint32_t)(1<<10)) /**< Clear Enabled Interrupt Bit that combined position 0 and revolution count interrupt */
#define QEI_IECLR_POS1REV_Int ((uint32_t)(1<<11)) /**< Clear Enabled Interrupt Bit that Combined position 1 and revolution count interrupt */
#define QEI_IECLR_POS2REV_Int ((uint32_t)(1<<12)) /**< Clear Enabled Interrupt Bit that Combined position 2 and revolution count interrupt */
#define QEI_IECLR_BITMASK ((uint32_t)(0x1FFF)) /**< QEI Interrupt Enable Clear register bit-mask */
/* ---------------- CHECK PARAMETER DEFINITIONS ---------------------------- */
/* Macro check QEI peripheral */
#define PARAM_QEIx(n) ((n==LPC_QEI))
/* Macro check QEI reset type */
#define PARAM_QEI_RESET(n) ((n==QEI_CON_RESP) \
|| (n==QEI_RESET_POSOnIDX) \
|| (n==QEI_RESET_VEL) \
|| (n==QEI_RESET_IDX))
/* Macro check QEI Direction invert mode */
#define PARAM_QEI_DIRINV(n) ((n==QEI_DIRINV_NONE) || (n==QEI_DIRINV_CMPL))
/* Macro check QEI signal mode */
#define PARAM_QEI_SIGNALMODE(n) ((n==QEI_SIGNALMODE_QUAD) || (n==QEI_SIGNALMODE_CLKDIR))
/* Macro check QEI Capture mode */
#define PARAM_QEI_CAPMODE(n) ((n==QEI_CAPMODE_2X) || (n==QEI_CAPMODE_4X))
/* Macro check QEI Invert index mode */
#define PARAM_QEI_INVINX(n) ((n==QEI_INVINX_NONE) || (n==QEI_INVINX_EN))
/* Macro check QEI Direction invert mode */
#define PARAM_QEI_TIMERRELOAD(n) ((n==QEI_TIMERRELOAD_TICKVAL) || (n==QEI_TIMERRELOAD_USVAL))
/* Macro check QEI status type */
#define PARAM_QEI_STATUS(n) ((n==QEI_STATUS_DIR))
/* Macro check QEI combine position type */
#define PARAM_QEI_COMPPOS_CH(n) ((n==QEI_COMPPOS_CH_0) || (n==QEI_COMPPOS_CH_1) || (n==QEI_COMPPOS_CH_2))
/* Macro check QEI interrupt flag type */
#define PARAM_QEI_INTFLAG(n) ((n==QEI_INTFLAG_INX_Int) \
|| (n==QEI_INTFLAG_TIM_Int) \
|| (n==QEI_INTFLAG_VELC_Int) \
|| (n==QEI_INTFLAG_DIR_Int) \
|| (n==QEI_INTFLAG_ERR_Int) \
|| (n==QEI_INTFLAG_ENCLK_Int) \
|| (n==QEI_INTFLAG_POS0_Int) \
|| (n==QEI_INTFLAG_POS1_Int) \
|| (n==QEI_INTFLAG_POS2_Int) \
|| (n==QEI_INTFLAG_REV_Int) \
|| (n==QEI_INTFLAG_POS0REV_Int) \
|| (n==QEI_INTFLAG_POS1REV_Int) \
|| (n==QEI_INTFLAG_POS2REV_Int))
/**
* @}
*/
/* Public Types --------------------------------------------------------------- */
/** @defgroup QEI_Public_Types QEI Public Types
* @{
*/
/**
* @brief QEI Configuration structure type definition
*/
typedef struct {
uint32_t DirectionInvert :1; /**< Direction invert option:
- QEI_DIRINV_NONE: QEI Direction is normal
- QEI_DIRINV_CMPL: QEI Direction is complemented
*/
uint32_t SignalMode :1; /**< Signal mode Option:
- QEI_SIGNALMODE_QUAD: Signal is in Quadrature phase mode
- QEI_SIGNALMODE_CLKDIR: Signal is in Clock/Direction mode
*/
uint32_t CaptureMode :1; /**< Capture Mode Option:
- QEI_CAPMODE_2X: Only Phase-A edges are counted (2X)
- QEI_CAPMODE_4X: BOTH Phase-A and Phase-B edges are counted (4X)
*/
uint32_t InvertIndex :1; /**< Invert Index Option:
- QEI_INVINX_NONE: the sense of the index input is normal
- QEI_INVINX_EN: inverts the sense of the index input
*/
} QEI_CFG_Type;
/**
* @brief Timer Reload Configuration structure type definition
*/
typedef struct {
uint8_t ReloadOption; /**< Velocity Timer Reload Option, should be:
- QEI_TIMERRELOAD_TICKVAL: Reload value in absolute value
- QEI_TIMERRELOAD_USVAL: Reload value in microsecond value
*/
uint8_t Reserved[3];
uint32_t ReloadValue; /**< Velocity Timer Reload Value, 32-bit long, should be matched
with Velocity Timer Reload Option
*/
} QEI_RELOADCFG_Type;
/**
* @}
*/
/* Public Functions ----------------------------------------------------------- */
/** @defgroup QEI_Public_Functions QEI Public Functions
* @{
*/
void QEI_Reset(LPC_QEI_TypeDef *QEIx, uint32_t ulResetType);
void QEI_Init(LPC_QEI_TypeDef *QEIx, QEI_CFG_Type *QEI_ConfigStruct);
void QEI_ConfigStructInit(QEI_CFG_Type *QIE_InitStruct);
void QEI_DeInit(LPC_QEI_TypeDef *QEIx);
FlagStatus QEI_GetStatus(LPC_QEI_TypeDef *QEIx, uint32_t ulFlagType);
uint32_t QEI_GetPosition(LPC_QEI_TypeDef *QEIx);
void QEI_SetMaxPosition(LPC_QEI_TypeDef *QEIx, uint32_t ulMaxPos);
void QEI_SetPositionComp(LPC_QEI_TypeDef *QEIx, uint8_t bPosCompCh, uint32_t ulPosComp);
uint32_t QEI_GetIndex(LPC_QEI_TypeDef *QEIx);
void QEI_SetIndexComp(LPC_QEI_TypeDef *QEIx, uint32_t ulIndexComp);
void QEI_SetTimerReload(LPC_QEI_TypeDef *QEIx, QEI_RELOADCFG_Type *QEIReloadStruct);
uint32_t QEI_GetTimer(LPC_QEI_TypeDef *QEIx);
uint32_t QEI_GetVelocity(LPC_QEI_TypeDef *QEIx);
uint32_t QEI_GetVelocityCap(LPC_QEI_TypeDef *QEIx);
void QEI_SetVelocityComp(LPC_QEI_TypeDef *QEIx, uint32_t ulVelComp);
void QEI_SetDigiFilter(LPC_QEI_TypeDef *QEIx, uint32_t ulSamplingPulse);
FlagStatus QEI_GetIntStatus(LPC_QEI_TypeDef *QEIx, uint32_t ulIntType);
void QEI_IntCmd(LPC_QEI_TypeDef *QEIx, uint32_t ulIntType, FunctionalState NewState);
void QEI_IntSet(LPC_QEI_TypeDef *QEIx, uint32_t ulIntType);
void QEI_IntClear(LPC_QEI_TypeDef *QEIx, uint32_t ulIntType);
uint32_t QEI_CalculateRPM(LPC_QEI_TypeDef *QEIx, uint32_t ulVelCapValue, uint32_t ulPPR);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* LPC17XX_QEI_H_ */
/**
* @}
*/
/* --------------------------------- End Of File ------------------------------ */
| Smoothieware/Smoothieware | src/libs/LPC17xx/LPC17xxLib/inc/lpc17xx_qei.h | C | gpl-3.0 | 24,817 |
.multilevelpushmenu_wrapper {
position: absolute;
z-index: 10;
height: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
.multilevelpushmenu_wrapper .levelHolderClass {
position: absolute;
top: 0;
width: auto;
min-height: 100%;
overflow: hidden;
font-family: 'Open Sans Condensed', sans-serif;
font-size: 1em;
zoom: 1;
}
.multilevelpushmenu_wrapper h2 {
padding: 0 .4em 0 .4em;
font-size: 1.5em;
font-weight: bold;
line-height: 1em;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
.multilevelpushmenu_wrapper h2 a {
padding: 0!important;
text-decoration: none!important;
}
.multilevelpushmenu_wrapper ul {
padding: 0;
margin: 0;
list-style: none;
}
.multilevelpushmenu_wrapper ul li {
cursor: pointer;
border-top: 1px solid #295685;
}
.multilevelpushmenu_wrapper ul li:last-child {
border-bottom: 1px solid #295685;
}
.multilevelpushmenu_wrapper a {
display: block;
overflow: hidden;
font-size: 1em;
line-height: 1em;
color: inherit;
text-decoration: none;
outline: none;
text-overflow: ellipsis;
white-space: nowrap;
}
.multilevelpushmenu_wrapper ul li a{
padding: .5em 0 .5em .4em;
}
.multilevelpushmenu_wrapper ul li a:hover { text-decoration: underline;}
.multilevelpushmenu_wrapper a span { margin-right: 0.5em;}
.multilevelpushmenu_wrapper .backItemClass {
display: block;
padding: .4em .4em .4em .4em;
}
.multilevelpushmenu_wrapper .invisible {
visibility: hidden;
}
.multilevelpushmenu_wrapper .visible {
visibility: visible;
}
.multilevelpushmenu_wrapper .cursorPointer {
cursor: pointer;
}
.multilevelpushmenu_wrapper.ltr .levelHolderClass {
left: 0;
margin-left: 0;
}
.multilevelpushmenu_wrapper .iconSpacing {
background: rgba(0, 0, 0, 0.075);
padding: 0.5em 0.8em;
}
.multilevelpushmenu_wrapper.ltr .itemIcon {
float: right;
}
.multilevelpushmenu_wrapper.ltr .floatRight {
float: right;
}
.multilevelpushmenu_wrapper.ltr .floatLeft {
float: left;
}
.multilevelpushmenu_wrapper.rtl {
/*right: 0;*/
text-align: right;
}
.multilevelpushmenu_wrapper.rtl .levelHolderClass {
left: 0;
margin-right: 0;
/*-webkit-box-shadow: 5px 0 5px 5px #1f4164;
-moz-box-shadow: 5px 0 5px 5px #1f4164;
box-shadow: 5px 0 5px 5px #1f4164;*/
}
.multilevelpushmenu_wrapper.rtl .multilevelpushmenu_collapse {
margin-right: -225px;
}
.multilevelpushmenu_wrapper.rtl .floatRight {
float: left;
}
.multilevelpushmenu_wrapper.rtl .floatLeft {
float: right;
}
.multilevelpushmenu_wrapper.rtl .levelHolderClass>h2 {
text-align: left;
}
.multilevelpushmenu_wrapper.rtl .levelHolderClass>h2 .floatRight {
float: right;
}
.multilevelpushmenu_wrapper.rtl .levelHolderClass>h2 .floatLeft {
float: left;
} | remytms/Distribution | plugin/website/Resources/public/css/angular/pushmenu.css | CSS | gpl-3.0 | 2,768 |
/*
* poolWritePose3d.cpp
*
* Created on: 10/05/2013
* Author: frivas
*/
#include "poolWritePose3d.h"
#include <logger/Logger.h>
namespace recorder{
poolWritePose3d::poolWritePose3d(Ice::ObjectPrx prx, int freq, size_t poolSize, int pose3dID, const std::string& baseLogPath):
RecorderPool(freq,poolSize,pose3dID),
PoolPaths(baseLogPath)
{
this->pose3DPrx = jderobot::Pose3DPrx::checkedCast(prx);
if (0== this->pose3DPrx) {
LOG(ERROR) << "Invalid proxy";
}
createDevicePath(POSE3D, deviceID);
this->setLogFile(getDeviceLogFilePath(POSE3D, deviceID));
}
poolWritePose3d::~poolWritePose3d() {
}
void poolWritePose3d::consumer_thread(){
pthread_mutex_lock(&(this->mutex));
if (this->pose3dVec.size()>0){
recorder::pose3d data2Save;
data2Save = this->pose3dVec[0];
this->pose3dVec.erase(this->pose3dVec.begin());
long long int relative;
relative=*(this->its.begin());
this->its.erase(this->its.begin());
pthread_mutex_unlock(&(this->mutex));
std::stringstream relativeString;//create a stringstream
relativeString << relative;//add number to the stream
std::string Path= getDeviceLogPath(POSE3D,deviceID) + relativeString.str();
std::ofstream outfileBinary(Path.c_str(), std::ios::out | std::ios::binary);
outfileBinary.write((const char *)&data2Save, sizeof(recorder::pose3d));
outfileBinary.close();
this->logfile << relative << std::endl;
}
else
pthread_mutex_unlock(&(this->mutex));
usleep(1000);
}
void poolWritePose3d::producer_thread(){
jderobot::Pose3DDataPtr dataPtr=this->pose3DPrx->getPose3DData();
recorder::pose3d data;
data.q0=dataPtr->q0;
data.q1=dataPtr->q1;
data.q2=dataPtr->q2;
data.q3=dataPtr->q3;
data.x=dataPtr->x;
data.y=dataPtr->y;
data.z=dataPtr->z;
data.h=dataPtr->h;
struct timeval now;
gettimeofday(&now,NULL);
long long int relative;
relative=((now.tv_sec*1000000+now.tv_usec) - (syncInitialTime.tv_sec*1000000+syncInitialTime.tv_usec))/1000;
pthread_mutex_lock(&(this->mutex));
while (this->pose3dVec.size() > this->poolSize){
pthread_mutex_unlock(&(this->mutex));
usleep(100);
pthread_mutex_lock(&(this->mutex));
}
this->pose3dVec.push_back(data);
this->its.push_back(relative);
pthread_mutex_unlock(&(this->mutex));
gettimeofday(&now,NULL);
long long int totalNow=now.tv_sec*1000000+now.tv_usec;
long long int totalLast=lastTime.tv_sec*1000000+lastTime.tv_usec;
double sleepTime =this->cycle - (totalNow-totalLast)/1000.;
if(sleepTime < 0 )
sleepTime = 0;
usleep(sleepTime*1000);
gettimeofday(&lastTime,NULL);
}
void* poolWritePose3d::producer_thread_imp(){
while (this->getActive()){
if (this->getRecording())
this->producer_thread();
else
usleep(1000);
}
pthread_exit(NULL);
}
void* poolWritePose3d::consumer_thread_imp(){
while (this->getActive()){
if (this->getRecording())
this->consumer_thread();
else
usleep(1000);
}
pthread_exit(NULL);
return NULL;
}
} //namespace
| fqez/JdeRobot | src/tools/recorder2/pools/poolWritePose3d.cpp | C++ | gpl-3.0 | 2,959 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
define([
'chai',
'sinon',
'models/reliers/oauth',
'models/user',
'lib/session',
'lib/oauth-client',
'lib/oauth-errors',
'lib/promise',
'lib/relier-keys',
'lib/url',
'../../../mocks/window',
'../../../lib/helpers'
], function (chai, sinon, OAuthRelier, User, Session, OAuthClient, OAuthErrors,
p, RelierKeys, Url, WindowMock, TestHelpers) {
'use strict';
/*eslint-disable camelcase */
var assert = chai.assert;
describe('models/reliers/oauth', function () {
var relier;
var oAuthClient;
var windowMock;
var user;
var STATE = 'fakestatetoken';
var SERVICE = 'service';
var SERVICE_NAME = '123Done';
var CLIENT_ID = 'dcdb5ae7add825d2';
var REDIRECT_URI = 'http://redirect.here';
var SERVER_REDIRECT_URI = 'http://127.0.0.1:8080/api/oauth';
var SCOPE = 'profile:email profile:uid';
var SCOPE_WITH_EXTRAS = 'profile:email profile:uid profile:non_whitelisted';
var PERMISSIONS = ['profile:email', 'profile:uid'];
var ACTION = 'signup';
var PREVERIFY_TOKEN = 'abigtoken';
var ACCESS_TYPE = 'offline';
var RESUME_INFO = {
state: STATE,
client_id: CLIENT_ID,
scope: SCOPE,
action: ACTION,
access_type: ACCESS_TYPE
};
beforeEach(function () {
windowMock = new WindowMock();
oAuthClient = new OAuthClient();
sinon.stub(oAuthClient, 'getClientInfo', function () {
return p({
name: SERVICE_NAME,
redirect_uri: SERVER_REDIRECT_URI
});
});
user = new User();
relier = new OAuthRelier({
window: windowMock,
oAuthClient: oAuthClient,
session: Session
});
});
describe('fetch', function () {
it('populates expected fields from the search parameters', function () {
windowMock.location.search = TestHelpers.toSearchString({
preVerifyToken: PREVERIFY_TOKEN,
service: SERVICE,
state: STATE,
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
scope: SCOPE,
action: ACTION,
access_type: ACCESS_TYPE
});
return relier.fetch()
.then(function () {
assert.equal(relier.get('preVerifyToken'), PREVERIFY_TOKEN);
assert.equal(relier.get('service'), SERVICE);
assert.equal(relier.get('state'), STATE);
// client_id and redirect_uri are converted to camelCase
// for consistency with other variables in the app.
assert.equal(relier.get('clientId'), CLIENT_ID);
assert.equal(relier.get('accessType'), ACCESS_TYPE);
// The redirect_uri passed in is ignored, we only care about
// the redirect_uri returned by the oauth server
assert.notEqual(relier.get('redirectUri'), REDIRECT_URI);
// Encryption keys are not fetched by default.
assert.equal(relier.get('keys'), false);
});
});
it('sets serviceName, redirectUri, and origin from parameters returned by the server', function () {
windowMock.location.search = TestHelpers.toSearchString({
preVerifyToken: PREVERIFY_TOKEN,
service: SERVICE,
state: STATE,
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
scope: SCOPE,
action: ACTION
});
return relier.fetch()
.then(function () {
assert.equal(relier.get('serviceName'), SERVICE_NAME);
assert.equal(relier.get('redirectUri'), SERVER_REDIRECT_URI);
assert.equal(relier.get('origin'), Url.getOrigin(SERVER_REDIRECT_URI));
});
});
it('populates OAuth information from Session to allow a user to verify', function () {
windowMock.location.search = TestHelpers.toSearchString({
code: '123'
});
Session.set('oauth', RESUME_INFO);
return relier.fetch()
.then(function () {
assert.equal(relier.get('state'), STATE);
assert.equal(relier.get('clientId'), CLIENT_ID);
assert.equal(relier.get('scope'), SCOPE);
assert.equal(relier.get('accessType'), ACCESS_TYPE);
});
});
it('errors in verification flow if `client_id` is missing', function () {
windowMock.location.search = TestHelpers.toSearchString({
code: '123'
});
Session.set('oauth', {
state: STATE,
scope: SCOPE,
action: ACTION
});
return relier.fetch()
.then(assert.fail, function (err) {
assert.isTrue(OAuthErrors.is(err, 'MISSING_PARAMETER'));
assert.equal(err.param, 'client_id');
});
});
it('populates `clientId` and `service` from the `service` URL search parameter if verifying in a second browser', function () {
windowMock.location.search = TestHelpers.toSearchString({
code: '123',
service: CLIENT_ID,
scope: SCOPE
});
return relier.fetch()
.then(function () {
assert.equal(relier.get('clientId'), CLIENT_ID);
assert.equal(relier.get('service'), CLIENT_ID);
});
});
it('populates `keys` from the URL search parameter if given', function () {
windowMock.location.search = TestHelpers.toSearchString({
keys: 'true',
client_id: CLIENT_ID,
scope: SCOPE
});
return relier.fetch()
.then(function () {
assert.equal(relier.get('keys'), true);
});
});
it('populates service with client_id if service is not set', function () {
windowMock.location.search = TestHelpers.toSearchString({
client_id: CLIENT_ID,
scope: SCOPE
});
return relier.fetch()
.then(function () {
assert.equal(relier.get('service'), CLIENT_ID);
});
});
it('populates permissions from scope', function () {
windowMock.location.search = TestHelpers.toSearchString({
client_id: CLIENT_ID,
scope: SCOPE
});
return relier.fetch()
.then(function () {
assert.deepEqual(relier.get('permissions'), PERMISSIONS);
});
});
it('sanitizes the scope of untrusted reliers', function () {
windowMock.location.search = TestHelpers.toSearchString({
client_id: CLIENT_ID,
scope: SCOPE_WITH_EXTRAS
});
sinon.stub(relier, 'isTrusted', function () {
return false;
});
return relier.fetch()
.then(function () {
assert.equal(relier.get('scope'), SCOPE);
assert.deepEqual(relier.get('permissions'), PERMISSIONS);
});
});
it('does not sanitize the scope of trusted reliers', function () {
windowMock.location.search = TestHelpers.toSearchString({
client_id: CLIENT_ID,
scope: SCOPE_WITH_EXTRAS
});
sinon.stub(relier, 'isTrusted', function () {
return true;
});
return relier.fetch()
.then(function () {
assert.equal(relier.get('scope'), SCOPE_WITH_EXTRAS);
assert.isFalse(relier.has('permissions'), 'permissions not set for trusted reliers');
});
});
it('errors if `client_id` is missing', function () {
windowMock.location.search = TestHelpers.toSearchString({
scope: SCOPE
});
return relier.fetch()
.then(assert.fail, function (err) {
assert.isTrue(OAuthErrors.is(err, 'MISSING_PARAMETER'));
assert.equal(err.param, 'client_id');
});
});
it('errors if the `client_id` is unknown or invalid', function () {
windowMock.location.search = TestHelpers.toSearchString({
client_id: 'BAD_CLIENT_ID',
scope: SCOPE
});
oAuthClient.getClientInfo.restore();
sinon.stub(oAuthClient, 'getClientInfo', function () {
var err = OAuthErrors.toError('INVALID_REQUEST_PARAMETER');
err.validation = {
keys: ['client_id']
};
return p.reject(err);
});
return relier.fetch()
.then(assert.fail, function (err) {
// INVALID_REQUEST_PARAMETER should be converted to
// UNKNOWN_CLIENT
assert.isTrue(OAuthErrors.is(err, 'UNKNOWN_CLIENT'));
});
});
it('errors if `scope` is missing', function () {
windowMock.location.search = TestHelpers.toSearchString({
client_id: CLIENT_ID
});
return relier.fetch()
.then(assert.fail, function (err) {
assert.isTrue(OAuthErrors.is(err, 'MISSING_PARAMETER'));
assert.equal(err.param, 'scope');
});
});
it('isTrusted when `trusted` is true', function () {
windowMock.location.search = TestHelpers.toSearchString({
client_id: CLIENT_ID,
scope: SCOPE
});
oAuthClient.getClientInfo.restore();
sinon.stub(oAuthClient, 'getClientInfo', function () {
return p({
name: SERVICE_NAME,
redirect_uri: SERVER_REDIRECT_URI,
trusted: true
});
});
return relier.fetch()
.then(function () {
assert.isTrue(relier.isTrusted());
});
});
it('! isTrusted when `trusted` is false', function () {
windowMock.location.search = TestHelpers.toSearchString({
client_id: CLIENT_ID,
scope: SCOPE
});
oAuthClient.getClientInfo.restore();
sinon.stub(oAuthClient, 'getClientInfo', function () {
return p({
name: SERVICE_NAME,
redirect_uri: SERVER_REDIRECT_URI,
trusted: false
});
});
return relier.fetch()
.then(function () {
assert.isFalse(relier.isTrusted());
});
});
});
describe('isOAuth', function () {
it('returns `true`', function () {
assert.isTrue(relier.isOAuth());
});
});
describe('pickResumeTokenInfo', function () {
it('returns an object with info to be passed along with email verification links', function () {
var CAMPAIGN = 'campaign id';
var ENTRYPOINT = 'entry point';
var STATE = 'some long opaque state token';
var VERIFICATION_REDIRECT = 'https://redirect.here.org';
relier.set({
campaign: CAMPAIGN,
entrypoint: ENTRYPOINT,
notPassed: 'this should not be picked',
state: STATE,
verificationRedirect: VERIFICATION_REDIRECT,
});
assert.deepEqual(relier.pickResumeTokenInfo(), {
// ensure campaign and entrypoint from
// the Relier are still passed.
campaign: CAMPAIGN,
entrypoint: ENTRYPOINT,
state: STATE,
verificationRedirect: VERIFICATION_REDIRECT
});
});
});
describe('wantsKeys', function () {
it('returns `true` only when keys are explicitly asked for', function () {
assert.isFalse(relier.wantsKeys());
relier.set('keys', true);
assert.isTrue(relier.wantsKeys());
});
});
describe('deriveRelierKeys', function () {
it('derives `kAr` and `kBr` account master keys', function () {
sinon.stub(RelierKeys, 'deriveRelierKeys', function () {
return p({ kAr: 'kAr', kBr: 'kBr' });
});
var mockKeys = { kA: 'kA', kB: 'kB' };
return relier.deriveRelierKeys(mockKeys, 'uid')
.then(function (keys) {
assert.isTrue(RelierKeys.deriveRelierKeys.calledWith(mockKeys, 'uid'));
assert.equal(keys.kAr, 'kAr');
assert.equal(keys.kBr, 'kBr');
});
});
});
describe('accountNeedsPermissions', function () {
it('should not prompt when relier is trusted', function () {
sinon.stub(relier, 'isTrusted', function () {
return true;
});
assert.isFalse(relier.accountNeedsPermissions(user.initAccount()));
assert.isTrue(relier.isTrusted.called);
});
it('should not prompt when relier is untrusted and has permissions', function () {
var account = user.initAccount();
sinon.stub(relier, 'isTrusted', function () {
return false;
});
sinon.stub(account, 'hasGrantedPermissions', function () {
return true;
});
relier.set('permissions', ['profile:email']);
assert.isFalse(relier.accountNeedsPermissions(account));
assert.isTrue(relier.isTrusted.called);
assert.isTrue(account.hasGrantedPermissions.calledWith(relier.get('clientId'), ['profile:email']));
});
it('returns true when relier is untrusted and at least one permission is needed', function () {
var account = user.initAccount();
sinon.stub(relier, 'isTrusted', function () {
return false;
});
sinon.stub(account, 'hasGrantedPermissions', function () {
return false;
});
relier.set('permissions', ['profile:email']);
assert.isTrue(relier.accountNeedsPermissions(account));
assert.isTrue(relier.isTrusted.called);
assert.isTrue(account.hasGrantedPermissions.calledWith(relier.get('clientId'), ['profile:email']));
});
});
});
});
| ofer43211/fxa-content-server | app/tests/spec/models/reliers/oauth.js | JavaScript | mpl-2.0 | 13,822 |
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by referrer-policy/generic/tools/generate.py using referrer-policy/generic/template/test.release.html.template. -->
<html>
<head>
<title>Referrer-Policy: Referrer Policy is set to 'origin'</title>
<meta name="description" content="Check that all subresources in all casses get only the origin portion of the referrer URL.">
<link rel="author" title="Kristijan Burnik" href="[email protected]">
<link rel="help" href="https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-origin">
<meta name="assert" content="The referrer URL is origin when a
document served over http requires an http
sub-resource via iframe-tag using the attr-referrer
delivery method with swap-origin-redirect and when
the target request is same-origin.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/security-features/resources/common.js"></script>
<script src="/referrer-policy/generic/referrer-policy-test-case.js?pipe=sub"></script>
</head>
<body>
<script>
ReferrerPolicyTestCase(
{
"referrer_policy": "origin",
"delivery_method": "attr-referrer",
"redirection": "swap-origin-redirect",
"origin": "same-origin",
"source_protocol": "http",
"target_protocol": "http",
"subresource": "iframe-tag",
"referrer_url": "origin"
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html>
| peterjoel/servo | tests/wpt/web-platform-tests/referrer-policy/origin/attr-referrer/same-origin/http-http/iframe-tag/swap-origin-redirect/generic.http.html | HTML | mpl-2.0 | 1,781 |
/*-------------------------------------------------------------------------
*
* plancache.h
* Plan cache definitions.
*
* See plancache.c for comments.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Portions Copyright (c) 2012-2014, TransLattice, Inc.
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/include/utils/plancache.h
*
*-------------------------------------------------------------------------
*/
#ifndef PLANCACHE_H
#define PLANCACHE_H
#include "access/tupdesc.h"
#include "nodes/params.h"
#define CACHEDPLANSOURCE_MAGIC 195726186
#define CACHEDPLAN_MAGIC 953717834
/*
* CachedPlanSource (which might better have been called CachedQuery)
* represents a SQL query that we expect to use multiple times. It stores
* the query source text, the raw parse tree, and the analyzed-and-rewritten
* query tree, as well as adjunct data. Cache invalidation can happen as a
* result of DDL affecting objects used by the query. In that case we discard
* the analyzed-and-rewritten query tree, and rebuild it when next needed.
*
* An actual execution plan, represented by CachedPlan, is derived from the
* CachedPlanSource when we need to execute the query. The plan could be
* either generic (usable with any set of plan parameters) or custom (for a
* specific set of parameters). plancache.c contains the logic that decides
* which way to do it for any particular execution. If we are using a generic
* cached plan then it is meant to be re-used across multiple executions, so
* callers must always treat CachedPlans as read-only.
*
* Once successfully built and "saved", CachedPlanSources typically live
* for the life of the backend, although they can be dropped explicitly.
* CachedPlans are reference-counted and go away automatically when the last
* reference is dropped. A CachedPlan can outlive the CachedPlanSource it
* was created from.
*
* An "unsaved" CachedPlanSource can be used for generating plans, but it
* lives in transient storage and will not be updated in response to sinval
* events.
*
* CachedPlans made from saved CachedPlanSources are likewise in permanent
* storage, so to avoid memory leaks, the reference-counted references to them
* must be held in permanent data structures or ResourceOwners. CachedPlans
* made from unsaved CachedPlanSources are in children of the caller's
* memory context, so references to them should not be longer-lived than
* that context. (Reference counting is somewhat pro forma in that case,
* though it may be useful if the CachedPlan can be discarded early.)
*
* A CachedPlanSource has two associated memory contexts: one that holds the
* struct itself, the query source text and the raw parse tree, and another
* context that holds the rewritten query tree and associated data. This
* allows the query tree to be discarded easily when it is invalidated.
*
* Note: the string referenced by commandTag is not subsidiary storage;
* it is assumed to be a compile-time-constant string. As with portals,
* commandTag shall be NULL if and only if the original query string (before
* rewriting) was an empty string.
*/
typedef struct CachedPlanSource
{
int magic; /* should equal CACHEDPLANSOURCE_MAGIC */
Node *raw_parse_tree; /* output of raw_parser() */
char *query_string; /* source text of query */
const char *commandTag; /* command tag (a constant!), or NULL */
Oid *param_types; /* array of parameter type OIDs, or NULL */
int num_params; /* length of param_types array */
ParserSetupHook parserSetup; /* alternative parameter spec method */
void *parserSetupArg;
int cursor_options; /* cursor options used for planning */
bool fixed_result; /* disallow change in result tupdesc? */
TupleDesc resultDesc; /* result type; NULL = doesn't return tuples */
struct OverrideSearchPath *search_path; /* saved search_path */
MemoryContext context; /* memory context holding all above */
/* These fields describe the current analyzed-and-rewritten query tree: */
List *query_list; /* list of Query nodes, or NIL if not valid */
List *relationOids; /* OIDs of relations the queries depend on */
List *invalItems; /* other dependencies, as PlanInvalItems */
MemoryContext query_context; /* context holding the above, or NULL */
/* If we have a generic plan, this is a reference-counted link to it: */
struct CachedPlan *gplan; /* generic plan, or NULL if not valid */
/* Some state flags: */
bool is_complete; /* has CompleteCachedPlan been done? */
bool is_saved; /* has CachedPlanSource been "saved"? */
bool is_valid; /* is the query_list currently valid? */
int generation; /* increments each time we create a plan */
/* If CachedPlanSource has been saved, it is a member of a global list */
struct CachedPlanSource *next_saved; /* list link, if so */
/* State kept to help decide whether to use custom or generic plans: */
double generic_cost; /* cost of generic plan, or -1 if not known */
double total_custom_cost; /* total cost of custom plans so far */
int num_custom_plans; /* number of plans included in total */
#ifdef PGXC
char *stmt_name; /* If set, this is a copy of prepared stmt name */
#endif
} CachedPlanSource;
/*
* CachedPlan represents an execution plan derived from a CachedPlanSource.
* The reference count includes both the link from the parent CachedPlanSource
* (if any), and any active plan executions, so the plan can be discarded
* exactly when refcount goes to zero. Both the struct itself and the
* subsidiary data live in the context denoted by the context field.
* This makes it easy to free a no-longer-needed cached plan.
*/
typedef struct CachedPlan
{
int magic; /* should equal CACHEDPLAN_MAGIC */
List *stmt_list; /* list of statement nodes (PlannedStmts and
* bare utility statements) */
bool is_saved; /* is CachedPlan in a long-lived context? */
bool is_valid; /* is the stmt_list currently valid? */
TransactionId saved_xmin; /* if valid, replan when TransactionXmin
* changes from this value */
int generation; /* parent's generation number for this plan */
int refcount; /* count of live references to this struct */
MemoryContext context; /* context containing this CachedPlan */
} CachedPlan;
extern void InitPlanCache(void);
extern void ResetPlanCache(void);
extern CachedPlanSource *CreateCachedPlan(Node *raw_parse_tree,
const char *query_string,
#ifdef PGXC
const char *stmt_name,
#endif
const char *commandTag);
extern void CompleteCachedPlan(CachedPlanSource *plansource,
List *querytree_list,
MemoryContext querytree_context,
Oid *param_types,
int num_params,
ParserSetupHook parserSetup,
void *parserSetupArg,
int cursor_options,
bool fixed_result);
extern void SaveCachedPlan(CachedPlanSource *plansource);
extern void DropCachedPlan(CachedPlanSource *plansource);
extern void CachedPlanSetParentContext(CachedPlanSource *plansource,
MemoryContext newcontext);
extern CachedPlanSource *CopyCachedPlan(CachedPlanSource *plansource);
extern bool CachedPlanIsValid(CachedPlanSource *plansource);
extern List *CachedPlanGetTargetList(CachedPlanSource *plansource);
extern CachedPlan *GetCachedPlan(CachedPlanSource *plansource,
ParamListInfo boundParams,
bool useResOwner);
extern void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner);
#ifdef XCP
extern void SetRemoteSubplan(CachedPlanSource *plansource,
const char *plan_string);
#endif
#endif /* PLANCACHE_H */
| arcivanov/postgres-xl | src/include/utils/plancache.h | C | mpl-2.0 | 7,855 |
<?php
/**
* Kodekit Platform - http://www.timble.net/kodekit
*
* @copyright Copyright (C) 2011 - 2016 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
* @link https://github.com/timble/kodekit-platform for the canonical source repository
*/
namespace Kodekit\Platform\Articles;
use Kodekit\Library;
/**
* Default Dispatcher
*
* @author Johan Janssens <http://github.com/johanjanssens>
* @package Kodekit\Platform\Articles
*/
class Dispatcher extends Library\Dispatcher
{
public function canDispatch()
{
return true;
}
} | timble/kodekit-platform | application/site/component/articles/dispatcher/dispatcher.php | PHP | mpl-2.0 | 623 |
# encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski ([email protected])
#
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from pyLibrary.collections import PRODUCT, reverse, MAX, MIN, OR
from pyLibrary import convert
from pyLibrary.debugs.logs import Log
from pyLibrary.dot import Null, Dict, coalesce
from pyLibrary.meta import use_settings
class Matrix(object):
"""
SIMPLE n-DIMENSIONAL ARRAY OF OBJECTS
"""
ZERO = None
@use_settings
def __init__(self, dims=[], list=None, value=None, zeros=False, settings=None):
if list:
self.num = 1
self.dims = (len(list), )
self.cube = list
return
if value != None:
self.num = 0
self.dims = tuple()
self.cube = value
return
self.num = len(dims)
self.dims = tuple(dims)
if zeros:
if self.num == 0 or OR(d == 0 for d in dims): #NO DIMS, OR HAS A ZERO DIM, THEN IT IS A NULL CUBE
self.cube = None
else:
self.cube = _zeros(*dims)
else:
if self.num == 0 or OR(d == 0 for d in dims): #NO DIMS, OR HAS A ZERO DIM, THEN IT IS A NULL CUBE
self.cube = Null
else:
self.cube = _null(*dims)
@staticmethod
def wrap(array):
output = Matrix(dims=(1,))
output.dims = (len(array), )
output.cube = array
return output
def __getitem__(self, index):
if not isinstance(index, (list, tuple)):
if isinstance(index, slice):
sub = self.cube[index]
output = Matrix()
output.num = 1
output.dims = (len(sub), )
output.cube = sub
return output
else:
return self.cube[index]
if len(index) == 0:
return self.cube
dims, cube = _getitem(self.cube, index)
if len(dims) == 0:
return cube # SIMPLE VALUE
output = Matrix(dims=[])
output.num = len(dims)
output.dims = dims
output.cube = cube
return output
def __setitem__(self, key, value):
try:
if len(key) != self.num:
Log.error("Expecting coordinates to match the number of dimensions")
if self.num == 0:
self.cube = value
return
last = self.num - 1
m = self.cube
for k in key[0:last:]:
m = m[k]
m[key[last]] = value
except Exception, e:
Log.error("can not set item", e)
def __bool__(self):
return self.cube != None
def __nonzero__(self):
return self.cube != None
def __len__(self):
if self.num == 0:
return 0
return PRODUCT(self.dims)
@property
def value(self):
if self.num:
Log.error("can not get value of with dimension")
return self.cube
def __lt__(self, other):
return self.value < other
def __gt__(self, other):
return self.value > other
def __eq__(self, other):
if other == None:
return False
return self.value == other
def __add__(self, other):
return self.value + other
def __radd__(self, other):
return other + self.value
def __sub__(self, other):
return self.value - other
def __rsub__(self, other):
return other - self.value
def __mul__(self, other):
return self.value * other
def __rmul__(self, other):
return other * self.value
def __div__(self, other):
return self.value / other
def __rdiv__(self, other):
return other / self.value
def __truediv__(self, other):
return self.value / other
def __rtruediv__(self, other):
return other / self.value
def __iter__(self):
# TODO: MAKE THIS FASTER BY NOT CALLING __getitem__ (MAKES CUBE OBJECTS)
return ((c, self[c]) for c in self._all_combos())
def __float__(self):
return self.value
def groupby(self, io_select):
"""
SLICE THIS MATRIX INTO ONES WITH LESS DIMENSIONALITY
io_select - 1 IF GROUPING BY THIS DIMENSION, 0 IF FLATTENING
return -
"""
# offsets WILL SERVE TO MASK DIMS WE ARE NOT GROUPING BY, AND SERVE AS RELATIVE INDEX FOR EACH COORDINATE
offsets = []
new_dim = []
acc = 1
for i, d in reverse(enumerate(self.dims)):
if not io_select[i]:
new_dim.insert(0, d)
offsets.insert(0, acc * io_select[i])
acc *= d
if not new_dim:
# WHEN groupby ALL DIMENSIONS, ONLY THE VALUES REMAIN
# RETURN AN ITERATOR OF PAIRS (c, v), WHERE
# c - COORDINATES INTO THE CUBE
# v - VALUE AT GIVEN COORDINATES
return ((c, self[c]) for c in self._all_combos())
else:
output = [[None, Matrix(dims=new_dim)] for i in range(acc)]
_groupby(self.cube, 0, offsets, 0, output, tuple(), [])
return output
def aggregate(self, type):
func = aggregates[type]
if not type:
Log.error("Aggregate of type {{type}} is not supported yet", type= type)
return func(self.num, self.cube)
def forall(self, method):
"""
IT IS EXPECTED THE method ACCEPTS (value, coord, cube), WHERE
value - VALUE FOUND AT ELEMENT
coord - THE COORDINATES OF THE ELEMENT (PLEASE, READ ONLY)
cube - THE WHOLE CUBE, FOR USE IN WINDOW FUNCTIONS
"""
for c in self._all_combos():
method(self[c], c, self.cube)
def items(self):
"""
ITERATE THROUGH ALL coord, value PAIRS
"""
for c in self._all_combos():
_, value = _getitem(self.cube, c)
yield c, value
def _all_combos(self):
"""
RETURN AN ITERATOR OF ALL COORDINATES
"""
combos = PRODUCT(self.dims)
if not combos:
return
calc = [(coalesce(PRODUCT(self.dims[i+1:]), 1), mm) for i, mm in enumerate(self.dims)]
for c in xrange(combos):
yield tuple(int(c / dd) % mm for dd, mm in calc)
def __str__(self):
return "Matrix " + convert.value2json(self.dims) + ": " + str(self.cube)
def __json__(self):
return convert.value2json(self.cube)
Matrix.ZERO = Matrix(value=None)
def _max(depth, cube):
if depth == 0:
return cube
elif depth == 1:
return MAX(cube)
else:
return MAX(_max(depth - 1, c) for c in cube)
def _min(depth, cube):
if depth == 0:
return cube
elif depth == 1:
return MIN(cube)
else:
return MIN(_min(depth - 1, c) for c in cube)
aggregates = Dict(
max=_max,
maximum=_max,
min=_min,
minimum=_min
)
def _iter(cube, depth):
if depth == 1:
return cube.__iter__()
else:
def iterator():
for c in cube:
for b in _iter(c, depth - 1):
yield b
return iterator()
def _null(*dims):
d0 = dims[0]
if d0 == 0:
Log.error("Zero dimensions not allowed")
if len(dims) == 1:
return [Null for i in range(d0)]
else:
return [_null(*dims[1::]) for i in range(d0)]
def _zeros(*dims):
d0 = dims[0]
if d0 == 0:
Log.error("Zero dimensions not allowed")
if len(dims) == 1:
return [0] * d0
else:
return [_zeros(*dims[1::]) for _ in range(d0)]
def _groupby(cube, depth, intervals, offset, output, group, new_coord):
if depth == len(intervals):
output[offset][0] = group
output[offset][1][new_coord] = cube
return
interval = intervals[depth]
if interval:
for i, c in enumerate(cube):
_groupby(c, depth + 1, intervals, offset + i * interval, output, group + (i, ), new_coord)
else:
for i, c in enumerate(cube):
_groupby(c, depth + 1, intervals, offset, output, group + (-1, ), new_coord + [i])
def _getitem(c, i):
if len(i)==1:
select = i[0]
if select == None:
return (len(c), ), c
elif isinstance(select, slice):
sub = c[select]
dims, cube = zip(*[_getitem(cc, i[1::]) for cc in sub])
return (len(cube),) + dims[0], cube
else:
return (), c[select]
else:
select = i[0]
if select == None:
dims, cube = zip(*[_getitem(cc, i[1::]) for cc in c])
return (len(cube),)+dims[0], cube
elif isinstance(select, slice):
sub = c[select]
dims, cube = zip(*[_getitem(cc, i[1::]) for cc in sub])
return (len(cube),)+dims[0], cube
else:
try:
return _getitem(c[select], i[1::])
except Exception, _:
pass
| mozilla/ChangeDetector | pyLibrary/collections/matrix.py | Python | mpl-2.0 | 9,324 |
package plugin_test
import (
"context"
"fmt"
"os"
"testing"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/builtin/plugin"
vaulthttp "github.com/hashicorp/vault/http"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/helper/logging"
"github.com/hashicorp/vault/sdk/helper/pluginutil"
"github.com/hashicorp/vault/sdk/logical"
logicalPlugin "github.com/hashicorp/vault/sdk/plugin"
"github.com/hashicorp/vault/sdk/plugin/mock"
"github.com/hashicorp/vault/vault"
)
func TestBackend_impl(t *testing.T) {
var _ logical.Backend = &plugin.PluginBackend{}
}
func TestBackend(t *testing.T) {
config, cleanup := testConfig(t)
defer cleanup()
_, err := plugin.Backend(context.Background(), config)
if err != nil {
t.Fatal(err)
}
}
func TestBackend_Factory(t *testing.T) {
config, cleanup := testConfig(t)
defer cleanup()
_, err := plugin.Factory(context.Background(), config)
if err != nil {
t.Fatal(err)
}
}
func TestBackend_PluginMain(t *testing.T) {
args := []string{}
if os.Getenv(pluginutil.PluginUnwrapTokenEnv) == "" && os.Getenv(pluginutil.PluginMetadataModeEnv) != "true" {
return
}
caPEM := os.Getenv(pluginutil.PluginCACertPEMEnv)
if caPEM == "" {
t.Fatal("CA cert not passed in")
}
args = append(args, fmt.Sprintf("--ca-cert=%s", caPEM))
apiClientMeta := &api.PluginAPIClientMeta{}
flags := apiClientMeta.FlagSet()
flags.Parse(args)
tlsConfig := apiClientMeta.GetTLSConfig()
tlsProviderFunc := api.VaultPluginTLSProvider(tlsConfig)
err := logicalPlugin.Serve(&logicalPlugin.ServeOpts{
BackendFactoryFunc: mock.Factory,
TLSProviderFunc: tlsProviderFunc,
})
if err != nil {
t.Fatal(err)
}
}
func testConfig(t *testing.T) (*logical.BackendConfig, func()) {
cluster := vault.NewTestCluster(t, nil, &vault.TestClusterOptions{
HandlerFunc: vaulthttp.Handler,
})
cluster.Start()
cores := cluster.Cores
core := cores[0]
sys := vault.TestDynamicSystemView(core.Core)
config := &logical.BackendConfig{
Logger: logging.NewVaultLogger(log.Debug),
System: sys,
Config: map[string]string{
"plugin_name": "mock-plugin",
"plugin_type": "database",
},
}
os.Setenv(pluginutil.PluginCACertPEMEnv, cluster.CACertPEMFile)
vault.TestAddTestPlugin(t, core.Core, "mock-plugin", consts.PluginTypeDatabase, "TestBackend_PluginMain", []string{}, "")
return config, func() {
cluster.Cleanup()
}
}
| joelthompson/vault | builtin/plugin/backend_test.go | GO | mpl-2.0 | 2,456 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use document_loader::DocumentLoader;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::XMLDocumentBinding::{self, XMLDocumentMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::nonnull::NonNullJSObjectPtr;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString;
use dom::document::{Document, DocumentSource, HasBrowsingContext, IsHTMLDocument};
use dom::location::Location;
use dom::node::Node;
use dom::window::Window;
use dom_struct::dom_struct;
use js::jsapi::JSContext;
use script_traits::DocumentActivity;
use servo_url::{MutableOrigin, ServoUrl};
// https://dom.spec.whatwg.org/#xmldocument
#[dom_struct]
pub struct XMLDocument {
document: Document,
}
impl XMLDocument {
fn new_inherited(window: &Window,
has_browsing_context: HasBrowsingContext,
url: Option<ServoUrl>,
origin: MutableOrigin,
is_html_document: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<String>,
activity: DocumentActivity,
source: DocumentSource,
doc_loader: DocumentLoader) -> XMLDocument {
XMLDocument {
document: Document::new_inherited(window,
has_browsing_context,
url,
origin,
is_html_document,
content_type,
last_modified,
activity,
source,
doc_loader,
None,
None,
Default::default()),
}
}
pub fn new(window: &Window,
has_browsing_context: HasBrowsingContext,
url: Option<ServoUrl>,
origin: MutableOrigin,
doctype: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<String>,
activity: DocumentActivity,
source: DocumentSource,
doc_loader: DocumentLoader)
-> DomRoot<XMLDocument> {
let doc = reflect_dom_object(
Box::new(XMLDocument::new_inherited(
window,
has_browsing_context,
url,
origin,
doctype,
content_type,
last_modified,
activity,
source,
doc_loader
)),
window,
XMLDocumentBinding::Wrap
);
{
let node = doc.upcast::<Node>();
node.set_owner_doc(&doc.document);
}
doc
}
}
impl XMLDocumentMethods for XMLDocument {
// https://html.spec.whatwg.org/multipage/#dom-document-location
fn GetLocation(&self) -> Option<DomRoot<Location>> {
self.upcast::<Document>().GetLocation()
}
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names
fn SupportedPropertyNames(&self) -> Vec<DOMString> {
self.upcast::<Document>().SupportedPropertyNames()
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter
unsafe fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString) -> Option<NonNullJSObjectPtr> {
self.upcast::<Document>().NamedGetter(_cx, name)
}
}
| dsandeephegde/servo | components/script/dom/xmldocument.rs | Rust | mpl-2.0 | 4,097 |
echo Uninstalling Fabric Engine Windows plugin
echo Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.
rmdir /S /Q %APPDATA%\Fabric
regsvr32 -u /s npFabricPlugin.dll
echo Uninstallation complete
pause
| chbfiv/fabric-engine-old | Native/Clients/NPAPI/Windows/uninstall.bat | Batchfile | agpl-3.0 | 216 |
/*
* Copyright (c) 2010 The WebM 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef VP8_COMMON_BLOCKD_H_
#define VP8_COMMON_BLOCKD_H_
void vpx_log(const char *format, ...);
#include "vpx_config.h"
#include "vpx_scale/yv12config.h"
#include "mv.h"
#include "treecoder.h"
#include "vpx_ports/mem.h"
#ifdef __cplusplus
extern "C" {
#endif
/*#define DCPRED 1*/
#define DCPREDSIMTHRESH 0
#define DCPREDCNTTHRESH 3
#define MB_FEATURE_TREE_PROBS 3
#define MAX_MB_SEGMENTS 4
#define MAX_REF_LF_DELTAS 4
#define MAX_MODE_LF_DELTAS 4
/* Segment Feature Masks */
#define SEGMENT_DELTADATA 0
#define SEGMENT_ABSDATA 1
typedef struct { int r, c; } POS;
#define PLANE_TYPE_Y_NO_DC 0
#define PLANE_TYPE_Y2 1
#define PLANE_TYPE_UV 2
#define PLANE_TYPE_Y_WITH_DC 3
typedef char ENTROPY_CONTEXT;
typedef struct {
ENTROPY_CONTEXT y1[4];
ENTROPY_CONTEXT u[2];
ENTROPY_CONTEXT v[2];
ENTROPY_CONTEXT y2;
} ENTROPY_CONTEXT_PLANES;
extern const unsigned char vp8_block2left[25];
extern const unsigned char vp8_block2above[25];
#define VP8_COMBINEENTROPYCONTEXTS(Dest, A, B) Dest = (A) + (B);
typedef enum { KEY_FRAME = 0, INTER_FRAME = 1 } FRAME_TYPE;
typedef enum {
DC_PRED, /* average of above and left pixels */
V_PRED, /* vertical prediction */
H_PRED, /* horizontal prediction */
TM_PRED, /* Truemotion prediction */
B_PRED, /* block based prediction, each block has its own prediction mode */
NEARESTMV,
NEARMV,
ZEROMV,
NEWMV,
SPLITMV,
MB_MODE_COUNT
} MB_PREDICTION_MODE;
/* Macroblock level features */
typedef enum {
MB_LVL_ALT_Q = 0, /* Use alternate Quantizer .... */
MB_LVL_ALT_LF = 1, /* Use alternate loop filter value... */
MB_LVL_MAX = 2 /* Number of MB level features supported */
} MB_LVL_FEATURES;
/* Segment Feature Masks */
#define SEGMENT_ALTQ 0x01
#define SEGMENT_ALT_LF 0x02
#define VP8_YMODES (B_PRED + 1)
#define VP8_UV_MODES (TM_PRED + 1)
#define VP8_MVREFS (1 + SPLITMV - NEARESTMV)
typedef enum {
B_DC_PRED, /* average of above and left pixels */
B_TM_PRED,
B_VE_PRED, /* vertical prediction */
B_HE_PRED, /* horizontal prediction */
B_LD_PRED,
B_RD_PRED,
B_VR_PRED,
B_VL_PRED,
B_HD_PRED,
B_HU_PRED,
LEFT4X4,
ABOVE4X4,
ZERO4X4,
NEW4X4,
B_MODE_COUNT
} B_PREDICTION_MODE;
#define VP8_BINTRAMODES (B_HU_PRED + 1) /* 10 */
#define VP8_SUBMVREFS (1 + NEW4X4 - LEFT4X4)
/* For keyframes, intra block modes are predicted by the (already decoded)
modes for the Y blocks to the left and above us; for interframes, there
is a single probability table. */
union b_mode_info {
B_PREDICTION_MODE as_mode;
int_mv mv;
};
typedef enum {
INTRA_FRAME = 0,
LAST_FRAME = 1,
GOLDEN_FRAME = 2,
ALTREF_FRAME = 3,
MAX_REF_FRAMES = 4
} MV_REFERENCE_FRAME;
typedef struct {
uint8_t mode, uv_mode;
uint8_t ref_frame;
uint8_t is_4x4;
int_mv mv;
uint8_t partitioning;
/* does this mb has coefficients at all, 1=no coefficients, 0=need decode
tokens */
uint8_t mb_skip_coeff;
uint8_t need_to_clamp_mvs;
/* Which set of segmentation parameters should be used for this MB */
uint8_t segment_id;
} MB_MODE_INFO;
typedef struct modeinfo {
MB_MODE_INFO mbmi;
union b_mode_info bmi[16];
} MODE_INFO;
#if CONFIG_MULTI_RES_ENCODING
/* The mb-level information needed to be stored for higher-resolution encoder */
typedef struct {
MB_PREDICTION_MODE mode;
MV_REFERENCE_FRAME ref_frame;
int_mv mv;
int dissim; /* dissimilarity level of the macroblock */
} LOWER_RES_MB_INFO;
/* The frame-level information needed to be stored for higher-resolution
* encoder */
typedef struct {
FRAME_TYPE frame_type;
int is_frame_dropped;
// If frame is dropped due to overshoot after encode_frame. This triggers a
// drop and resets rate control with Q forced to max for following frame.
// The check for this dropping due to overshoot is only done on lowest stream,
// and if set will force drop on all spatial streams for that current frame.
int is_frame_dropped_overshoot_maxqp;
// The frame rate for the lowest resolution.
double low_res_framerate;
/* The frame number of each reference frames */
unsigned int low_res_ref_frames[MAX_REF_FRAMES];
// The video frame counter value for the key frame, for lowest resolution.
unsigned int key_frame_counter_value;
LOWER_RES_MB_INFO *mb_info;
} LOWER_RES_FRAME_INFO;
#endif
typedef struct blockd {
short *qcoeff;
short *dqcoeff;
unsigned char *predictor;
short *dequant;
int offset;
char *eob;
union b_mode_info bmi;
} BLOCKD;
typedef void (*vp8_subpix_fn_t)(unsigned char *src, int src_pitch, int xofst,
int yofst, unsigned char *dst, int dst_pitch);
typedef struct macroblockd {
DECLARE_ALIGNED(16, unsigned char, predictor[384]);
DECLARE_ALIGNED(16, short, qcoeff[400]);
DECLARE_ALIGNED(16, short, dqcoeff[400]);
DECLARE_ALIGNED(16, char, eobs[25]);
DECLARE_ALIGNED(16, short, dequant_y1[16]);
DECLARE_ALIGNED(16, short, dequant_y1_dc[16]);
DECLARE_ALIGNED(16, short, dequant_y2[16]);
DECLARE_ALIGNED(16, short, dequant_uv[16]);
/* 16 Y blocks, 4 U, 4 V, 1 DC 2nd order block, each with 16 entries. */
BLOCKD block[25];
int fullpixel_mask;
YV12_BUFFER_CONFIG pre; /* Filtered copy of previous frame reconstruction */
YV12_BUFFER_CONFIG dst;
MODE_INFO *mode_info_context;
int mode_info_stride;
FRAME_TYPE frame_type;
int up_available;
int left_available;
unsigned char *recon_above[3];
unsigned char *recon_left[3];
int recon_left_stride[2];
/* Y,U,V,Y2 */
ENTROPY_CONTEXT_PLANES *above_context;
ENTROPY_CONTEXT_PLANES *left_context;
/* 0 indicates segmentation at MB level is not enabled. Otherwise the
* individual bits indicate which features are active. */
unsigned char segmentation_enabled;
/* 0 (do not update) 1 (update) the macroblock segmentation map. */
unsigned char update_mb_segmentation_map;
/* 0 (do not update) 1 (update) the macroblock segmentation feature data. */
unsigned char update_mb_segmentation_data;
/* 0 (do not update) 1 (update) the macroblock segmentation feature data. */
unsigned char mb_segement_abs_delta;
/* Per frame flags that define which MB level features (such as quantizer or
* loop filter level) */
/* are enabled and when enabled the proabilities used to decode the per MB
* flags in MB_MODE_INFO */
/* Probability Tree used to code Segment number */
vp8_prob mb_segment_tree_probs[MB_FEATURE_TREE_PROBS];
/* Segment parameters */
signed char segment_feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
/* mode_based Loop filter adjustment */
unsigned char mode_ref_lf_delta_enabled;
unsigned char mode_ref_lf_delta_update;
/* Delta values have the range +/- MAX_LOOP_FILTER */
signed char
last_ref_lf_deltas[MAX_REF_LF_DELTAS]; /* 0 = Intra, Last, GF, ARF */
signed char ref_lf_deltas[MAX_REF_LF_DELTAS]; /* 0 = Intra, Last, GF, ARF */
/* 0 = BPRED, ZERO_MV, MV, SPLIT */
signed char last_mode_lf_deltas[MAX_MODE_LF_DELTAS];
signed char
mode_lf_deltas[MAX_MODE_LF_DELTAS]; /* 0 = BPRED, ZERO_MV, MV, SPLIT */
/* Distance of MB away from frame edges */
int mb_to_left_edge;
int mb_to_right_edge;
int mb_to_top_edge;
int mb_to_bottom_edge;
vp8_subpix_fn_t subpixel_predict;
vp8_subpix_fn_t subpixel_predict8x4;
vp8_subpix_fn_t subpixel_predict8x8;
vp8_subpix_fn_t subpixel_predict16x16;
void *current_bc;
int corrupted;
#if ARCH_X86 || ARCH_X86_64
/* This is an intermediate buffer currently used in sub-pixel motion search
* to keep a copy of the reference area. This buffer can be used for other
* purpose.
*/
DECLARE_ALIGNED(32, unsigned char, y_buf[22 * 32]);
#endif
} MACROBLOCKD;
extern void vp8_build_block_doffsets(MACROBLOCKD *x);
extern void vp8_setup_block_dptrs(MACROBLOCKD *x);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // VP8_COMMON_BLOCKD_H_
| artclarke/humble-video | humble-video-captive/src/main/gnu/libvpx/csrc/vp8/common/blockd.h | C | agpl-3.0 | 8,259 |
/**
* Odoo, Open Source Management Solution
* Copyright (C) 2012-today Odoo SA (<http:www.odoo.com>)
* <p/>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version
* <p/>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details
* <p/>
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:www.gnu.org/licenses/>
* <p/>
* Created on 17/12/14 6:06 PM
*/
package com.odoo;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.odoo.core.orm.ModelRegistryUtils;
import com.odoo.core.orm.OModel;
import com.odoo.core.orm.OSQLite;
import com.odoo.core.rpc.Odoo;
import com.odoo.core.support.OUser;
import java.lang.reflect.Constructor;
import java.util.HashMap;
public class App extends Application {
public static final String TAG = App.class.getSimpleName();
public static String APPLICATION_NAME;
private static HashMap<String, Odoo> mOdooInstances = new HashMap<>();
private static HashMap<String, OSQLite> mSQLiteObjecs = new HashMap<>();
private static ModelRegistryUtils modelRegistryUtils = new ModelRegistryUtils();
@Override
public void onCreate() {
super.onCreate();
App.APPLICATION_NAME = getPackageManager().getApplicationLabel(getApplicationInfo()).toString();
App.modelRegistryUtils.makeReady(getApplicationContext());
}
public static OSQLite getSQLite(String userName) {
return mSQLiteObjecs.containsKey(userName) ? mSQLiteObjecs.get(userName) : null;
}
public static void setSQLite(String userName, OSQLite sqLite) {
mSQLiteObjecs.put(userName, sqLite);
}
public Odoo getOdoo(OUser user) {
if (mOdooInstances.containsKey(user.getAndroidName())) {
return mOdooInstances.get(user.getAndroidName());
}
return null;
}
public void setOdoo(Odoo odoo, OUser user) {
if (user != null)
mOdooInstances.put(user.getAndroidName(), odoo);
}
/**
* Checks for network availability
*
* @return true, if network available
*/
public boolean inNetwork() {
boolean isConnected = false;
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = manager.getActiveNetworkInfo();
if (nInfo != null && nInfo.isConnectedOrConnecting()) {
isConnected = true;
}
return isConnected;
}
/**
* Checks for installed application
*
* @param appPackage
* @return true, if application installed on device
*/
public boolean appInstalled(String appPackage) {
boolean mInstalled = false;
try {
PackageManager mPackage = getPackageManager();
mPackage.getPackageInfo(appPackage, PackageManager.GET_ACTIVITIES);
mInstalled = true;
} catch (Exception e) {
e.printStackTrace();
}
return mInstalled;
}
public static <T> T getModel(Context context, String modelName, OUser user) {
Class<? extends OModel> modelCls = App.modelRegistryUtils.getModel(modelName);
if (modelCls != null) {
try {
Constructor constructor = modelCls.getConstructor(Context.class, OUser.class);
return (T) constructor.newInstance(context, user);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public ModelRegistryUtils getModelRegistry() {
return modelRegistryUtils;
}
}
| Odoo-mobile/framework | app/src/main/java/com/odoo/App.java | Java | agpl-3.0 | 4,128 |
<b>Task Summary Filter</b>
<br><br>
This filter will allow you to filter a list of Tasks and manipulate how
they are displayed on this screen.
<br><br> Also note that you can print this report from within your browser and it should render nicely.
| mattcen/alloc | help/taskList_filter.html | HTML | agpl-3.0 | 251 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# address_name_inc.py
# address_name_inc
# First author: Mag Guevara <[email protected]> (ClearCorp S.A.)
# Copyright (c) 2011-TODAY ClearCorp S.A. (http://clearcorp.co.cr). All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are
# permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# conditions and the following disclaimer.
#
# 2. 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.
#
# THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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 <COPYRIGHT HOLDER> 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.
#
# The views and conclusions contained in the software and documentation are those of the
# authors and should not be interpreted as representing official policies, either expressed
# or implied, of ClearCorp S.A..
#
##############################################################################
from osv import osv, fields
from tools import debug
from tools.translate import _
class sale_payment(osv.osv):
_name = 'sale.order'
_inherit = 'sale.order'
_columns = {
'payment_term': fields.many2one('account.payment.term', 'Payment Term', required=True),
}
sale_payment()
| ClearCorp/odoo-clearcorp | TODO-6.1/ccorp_sale_payment_term/ccorp_sale_payment_term.py | Python | agpl-3.0 | 2,263 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2016 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.icmp.proxy;
import java.util.Arrays;
import java.util.Collection;
import org.junit.runners.Parameterized;
import org.opennms.core.test.xml.XmlTestNoCastor;
public class PingResponseDTOTest extends XmlTestNoCastor<PingResponseDTO> {
public PingResponseDTOTest(PingResponseDTO sampleObject, Object sampleXml) {
super(sampleObject, sampleXml, null);
}
@Parameterized.Parameters
public static Collection<Object[]> data() throws Exception {
return Arrays.asList(new Object[][] {
{
createResponse(),
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<ping-response>\n" +
" <rtt>10.253</rtt>\n" +
"</ping-response>"
}
});
}
private static PingResponseDTO createResponse() {
PingResponseDTO responseDTO = new PingResponseDTO();
responseDTO.setRtt(10.253);
return responseDTO;
}
}
| aihua/opennms | opennms-icmp/opennms-icmp-proxy-rpc-impl/src/test/java/org/opennms/netmgt/icmp/proxy/PingResponseDTOTest.java | Java | agpl-3.0 | 2,259 |
/****************************************************************************
*
* (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <[email protected]>
#ifndef AIRFRAMECOMPONENTCONTROLLER_H
#define AIRFRAMECOMPONENTCONTROLLER_H
#include <QObject>
#include <QQuickItem>
#include <QList>
#include "UASInterface.h"
#include "AutoPilotPlugin.h"
#include "FactPanelController.h"
/// MVC Controller for AirframeComponent.qml.
class AirframeComponentController : public FactPanelController
{
Q_OBJECT
public:
AirframeComponentController(void);
~AirframeComponentController();
Q_PROPERTY(bool showCustomConfigPanel MEMBER _showCustomConfigPanel NOTIFY showCustomConfigPanelChanged)
Q_PROPERTY(QVariantList airframeTypes MEMBER _airframeTypes CONSTANT)
Q_PROPERTY(QString currentAirframeType MEMBER _currentAirframeType CONSTANT)
Q_PROPERTY(QString currentVehicleName MEMBER _currentVehicleName CONSTANT)
Q_PROPERTY(int currentVehicleIndex MEMBER _currentVehicleIndex CONSTANT)
Q_PROPERTY(int autostartId MEMBER _autostartId NOTIFY autostartIdChanged)
Q_INVOKABLE void changeAutostart(void);
int currentAirframeIndex(void);
void setCurrentAirframeIndex(int newIndex);
signals:
void autostartIdChanged(int newAutostartId);
void showCustomConfigPanelChanged(bool show);
private slots:
void _waitParamWriteSignal(QVariant value);
void _rebootAfterStackUnwind(void);
private:
static bool _typesRegistered;
QVariantList _airframeTypes;
QString _currentAirframeType;
QString _currentVehicleName;
int _currentVehicleIndex;
int _autostartId;
bool _showCustomConfigPanel;
int _waitParamWriteSignalCount;
};
class Airframe : public QObject
{
Q_OBJECT
public:
Airframe(const QString& name, int autostartId, QObject* parent = nullptr);
~Airframe();
Q_PROPERTY(QString text MEMBER _name CONSTANT)
Q_PROPERTY(int autostartId MEMBER _autostartId CONSTANT)
private:
QString _name;
int _autostartId;
};
class AirframeType : public QObject
{
Q_OBJECT
public:
AirframeType(const QString& name, const QString& imageResource, QObject* parent = nullptr);
~AirframeType();
Q_PROPERTY(QString name MEMBER _name CONSTANT)
Q_PROPERTY(QString imageResource MEMBER _imageResource CONSTANT)
Q_PROPERTY(QVariantList airframes MEMBER _airframes CONSTANT)
void addAirframe(const QString& name, int autostartId);
private:
QString _name;
QString _imageResource;
QVariantList _airframes;
};
#endif
| Hunter522/qgroundcontrol | src/AutoPilotPlugins/PX4/AirframeComponentController.h | C | agpl-3.0 | 2,969 |
/* */
'use strict';
var _classCallCheck = function(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function');
}
};
var _createClass = (function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ('value' in descriptor)
descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
if (protoProps)
defineProperties(Constructor.prototype, protoProps);
if (staticProps)
defineProperties(Constructor, staticProps);
return Constructor;
};
})();
var invariant = require("react/lib/invariant");
var LocationActions = require("../actions/LocationActions");
var History = require("../History");
var TestLocation = (function() {
function TestLocation(history) {
_classCallCheck(this, TestLocation);
this.history = history || [];
this.listeners = [];
this._updateHistoryLength();
}
_createClass(TestLocation, [{
key: 'needsDOM',
get: function() {
return false;
}
}, {
key: '_updateHistoryLength',
value: function _updateHistoryLength() {
History.length = this.history.length;
}
}, {
key: '_notifyChange',
value: function _notifyChange(type) {
var change = {
path: this.getCurrentPath(),
type: type
};
for (var i = 0,
len = this.listeners.length; i < len; ++i)
this.listeners[i].call(this, change);
}
}, {
key: 'addChangeListener',
value: function addChangeListener(listener) {
this.listeners.push(listener);
}
}, {
key: 'removeChangeListener',
value: function removeChangeListener(listener) {
this.listeners = this.listeners.filter(function(l) {
return l !== listener;
});
}
}, {
key: 'push',
value: function push(path) {
this.history.push(path);
this._updateHistoryLength();
this._notifyChange(LocationActions.PUSH);
}
}, {
key: 'replace',
value: function replace(path) {
invariant(this.history.length, 'You cannot replace the current path with no history');
this.history[this.history.length - 1] = path;
this._notifyChange(LocationActions.REPLACE);
}
}, {
key: 'pop',
value: function pop() {
this.history.pop();
this._updateHistoryLength();
this._notifyChange(LocationActions.POP);
}
}, {
key: 'getCurrentPath',
value: function getCurrentPath() {
return this.history[this.history.length - 1];
}
}, {
key: 'toString',
value: function toString() {
return '<TestLocation>';
}
}]);
return TestLocation;
})();
module.exports = TestLocation;
| elsiklab/sequenceserver | public/vendor/npm/[email protected]/lib/locations/TestLocation.js | JavaScript | agpl-3.0 | 2,940 |
<?php
/*********************************************************************************
* TimeTrex is a Payroll and Time Management program developed by
* TimeTrex Software Inc. Copyright (C) 2003 - 2014 TimeTrex Software Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY TIMETREX, TIMETREX DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact TimeTrex headquarters at Unit 22 - 2475 Dobbin Rd. Suite
* #292 Westbank, BC V4T 2E9, Canada or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by TimeTrex" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by TimeTrex".
********************************************************************************/
/**
* @package Modules\PayPeriod
*/
class PayPeriodScheduleListFactory extends PayPeriodScheduleFactory implements IteratorAggregate {
function getAll($limit = NULL, $page = NULL, $where = NULL, $order = NULL) {
$query = '
select *
from '. $this->getTable() .'
WHERE deleted=0';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, NULL, $limit, $page );
return $this;
}
function getById($id, $where = NULL, $order = NULL) {
if ( $id == '') {
return FALSE;
}
$this->rs = $this->getCache($id);
if ( $this->rs === FALSE ) {
$ph = array(
'id' => $id,
);
$query = '
select *
from '. $this->getTable() .'
where id = ?
AND deleted=0';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph );
$this->saveCache($this->rs, $id);
}
return $this;
}
function getByUserId($user_id, $where = NULL, $order = NULL) {
if ( $user_id == '') {
return FALSE;
}
$ppsulf = new PayPeriodScheduleUserListFactory();
$ph = array(
'user_id' => $user_id,
);
$query = '
select a.*
from '. $this->getTable() .' as a,
'. $ppsulf->getTable() .' as b
where a.id = b.pay_period_schedule_id
AND b.user_id = ?
AND a.deleted=0';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph );
return $this;
}
function getByCompanyId($id, $limit = NULL, $page = NULL, $where = NULL, $order = NULL) {
if ( $id == '') {
return FALSE;
}
$ph = array(
'id' => $id,
);
$query = '
select *
from '. $this->getTable() .' as a
where company_id = ?
AND deleted=0';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph, $limit, $page );
return $this;
}
function getByCompanyIdAndUserId($company_id, $user_ids, $where = NULL, $order = NULL) {
if ( $company_id == '') {
return FALSE;
}
if ( $user_ids == '') {
return FALSE;
}
/*
if ( $order == NULL ) {
$order = array( 'type_id' => 'asc' );
$strict = FALSE;
} else {
$strict = TRUE;
}
*/
$ppsuf = new PayPeriodScheduleUserFactory();
$ph = array( 'company_id' => $company_id );
$query = '
select a.*,
b.user_id as user_id
from '. $this->getTable() .' as a,
'. $ppsuf->getTable() .' as b
where a.id = b.pay_period_schedule_id
AND a.company_id = ? ';
if ( isset($user_ids) AND ( $user_ids != '' OR ( is_array($user_ids) AND isset($user_ids[0]) ) ) ) {
$query .= ' AND b.user_id in ('. $this->getListSQL($user_ids, $ph) .') ';
}
$query .= ' AND a.deleted = 0';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph );
return $this;
}
function getByIdAndCompanyId($id, $company_id, $order = NULL) {
if ( $id == '' ) {
return FALSE;
}
if ( $company_id == '' ) {
return FALSE;
}
$ph = array(
'company_id' => $company_id,
'id' => $id,
);
$query = '
select *
from '. $this->getTable() .'
where company_id = ?
AND id = ?
AND deleted=0';
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph );
return $this;
}
function getByPayPeriodIdAndCompanyId($id, $company_id, $limit = NULL, $page = NULL, $where = NULL, $order = NULL) {
if ( $id == '' ) {
return FALSE;
}
if ( $company_id == '' ) {
return FALSE;
}
$ph = array(
'company_id' => $company_id,
);
$ppf = new PayPeriodFactory();
$query = '
select _ADODB_COUNT
*
_ADODB_COUNT
from '. $this->getTable() .'
where company_id = ?
AND id in ( select ppf.pay_period_schedule_id from '. $ppf->getTable() .' as ppf where ppf.id in ('. $this->getListSQL($id, $ph) .') )
AND deleted=0';
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph, $limit, $page );
return $this;
}
function getByCompanyIdArray($company_id, $include_blank = TRUE ) {
$ppslf = new PayPeriodScheduleListFactory();
$ppslf->getByCompanyId($company_id);
if ( $include_blank == TRUE ) {
$list[0] = '--';
}
foreach ($ppslf as $pps_obj) {
$list[$pps_obj->getID()] = $pps_obj->getName();
}
if ( isset($list) ) {
return $list;
}
return FALSE;
}
function getArrayByListFactory($lf, $include_blank = TRUE) {
if ( !is_object($lf) ) {
return FALSE;
}
if ( $include_blank == TRUE ) {
$list[0] = '--';
}
foreach ($lf as $obj) {
$list[$obj->getID()] = $obj->getName();
}
if ( isset($list) ) {
return $list;
}
return FALSE;
}
function getUserToPayPeriodScheduleMapArrayByListFactory( $lf ) {
if ( !is_object($lf) ) {
return FALSE;
}
foreach ($lf as $obj) {
$retarr[$obj->getColumn('user_id')] = $obj->getId();
}
if ( isset($retarr) ) {
return $retarr;
}
return FALSE;
}
function getAPISearchByCompanyIdAndArrayCriteria( $company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL ) {
if ( $company_id == '') {
return FALSE;
}
if ( !is_array($order) ) {
//Use Filter Data ordering if its set.
if ( isset($filter_data['sort_column']) AND $filter_data['sort_order']) {
$order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
}
}
$additional_order_fields = array( 'total_users' );
if ( $order == NULL ) {
$order = array( 'name' => 'asc' );
$strict = FALSE;
} else {
//Always sort by last name, first name after other columns
if ( !isset($order['name']) ) {
$order['name'] = 'asc';
}
$strict = TRUE;
}
//Debug::Arr($order, 'Order Data:', __FILE__, __LINE__, __METHOD__, 10);
//Debug::Arr($filter_data, 'Filter Data:', __FILE__, __LINE__, __METHOD__, 10);
$uf = new UserFactory();
$ppsuf = new PayPeriodScheduleUserFactory();
$ph = array(
'company_id' => $company_id,
);
$query = '
select
_ADODB_COUNT
a.*,
(select count(*) from '. $ppsuf->getTable() .' as ppsuf_tmp where ppsuf_tmp.pay_period_schedule_id = a.id ) as total_users,
y.first_name as created_by_first_name,
y.middle_name as created_by_middle_name,
y.last_name as created_by_last_name,
z.first_name as updated_by_first_name,
z.middle_name as updated_by_middle_name,
z.last_name as updated_by_last_name
_ADODB_COUNT
from '. $this->getTable() .' as a
LEFT JOIN '. $uf->getTable() .' as y ON ( a.created_by = y.id AND y.deleted = 0 )
LEFT JOIN '. $uf->getTable() .' as z ON ( a.updated_by = z.id AND z.deleted = 0 )
where a.company_id = ?
';
$query .= ( isset($filter_data['permission_children_ids']) ) ? $this->getWhereClauseSQL( 'a.created_by', $filter_data['permission_children_ids'], 'numeric_list', $ph ) : NULL;
$query .= ( isset($filter_data['id']) ) ? $this->getWhereClauseSQL( 'a.id', $filter_data['id'], 'numeric_list', $ph ) : NULL;
$query .= ( isset($filter_data['exclude_id']) ) ? $this->getWhereClauseSQL( 'a.id', $filter_data['exclude_id'], 'not_numeric_list', $ph ) : NULL;
if ( isset($filter_data['type']) AND !is_array($filter_data['type']) AND trim($filter_data['type']) != '' AND !isset($filter_data['type_id']) ) {
$filter_data['type_id'] = Option::getByFuzzyValue( $filter_data['type'], $this->getOptions('type') );
}
$query .= ( isset($filter_data['type_id']) ) ? $this->getWhereClauseSQL( 'a.type_id', $filter_data['type_id'], 'numeric_list', $ph ) : NULL;
$query .= ( isset($filter_data['name']) ) ? $this->getWhereClauseSQL( 'a.name', $filter_data['name'], 'text', $ph ) : NULL;
$query .= ( isset($filter_data['description']) ) ? $this->getWhereClauseSQL( 'a.description', $filter_data['description'], 'text', $ph ) : NULL;
$query .= ( isset($filter_data['created_by']) ) ? $this->getWhereClauseSQL( array('a.created_by', 'y.first_name', 'y.last_name'), $filter_data['created_by'], 'user_id_or_name', $ph ) : NULL;
$query .= ( isset($filter_data['updated_by']) ) ? $this->getWhereClauseSQL( array('a.updated_by', 'z.first_name', 'z.last_name'), $filter_data['updated_by'], 'user_id_or_name', $ph ) : NULL;
$query .= '
AND a.deleted = 0
';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order, $strict, $additional_order_fields );
$this->ExecuteSQL( $query, $ph, $limit, $page );
return $this;
}
}
?>
| maestrano/timetrex | classes/modules/payperiod/PayPeriodScheduleListFactory.class.php | PHP | agpl-3.0 | 10,605 |
<?php
namespace MOC\V\Core\SecureKernel\Component\Bridge\Repository\SFTP;
use MOC\V\Core\SecureKernel\Component\Bridge\Bridge;
use MOC\V\Core\SecureKernel\Component\Bridge\Repository\SFTP;
use MOC\V\Core\SecureKernel\Component\Exception\ComponentException;
use MOC\V\Core\SecureKernel\Component\IBridgeInterface;
use phpseclib\Crypt\RSA;
/**
* Class Connection
*
* @package MOC\V\Core\SecureKernel\Component\Bridge\Repository\SFTP
*/
abstract class Connection extends Bridge implements IBridgeInterface
{
/** @var null|\phpseclib\Net\SFTP */
protected $Connection = null;
/** @var string $Host */
private $Host = 'localhost';
/** @var int $Port */
private $Port = 22;
/** @var int $Timeout */
private $Timeout = 10;
/** @var string $Username */
private $Username = '';
/** @var null|string $Password */
private $Password = null;
/** @var null|string $Key */
private $Key = null;
/**
* @return SFTP
*/
public function closeConnection()
{
if ($this->Connection->isConnected()) {
$this->Connection->disconnect();
}
$this->Connection = null;
return $this;
}
/**
* @return SFTP
* @throws ComponentException
*/
public function persistConnection()
{
if (!$this->Connection->isConnected()) {
$this->openConnection($this->Host, $this->Port, $this->Timeout);
if (null === $this->Key) {
$this->loginCredential($this->Username, $this->Password);
} else {
$this->loginCredentialKey($this->Username, $this->Key, $this->Password);
}
}
return $this;
}
/**
* @param string $Host
* @param int $Port
* @param int $Timeout
*
* @return SFTP
*/
public function openConnection($Host, $Port = 22, $Timeout = 10)
{
$this->Host = $Host;
$this->Port = $Port;
$this->Timeout = $Timeout;
$this->Connection = new \phpseclib\Net\SFTP($Host, $Port, $Timeout);
return $this;
}
/**
* @param string $Username
* @param null|string $Password
*
* @return SFTP
* @throws ComponentException
*/
public function loginCredential($Username, $Password = null)
{
$this->Username = $Username;
$this->Password = $Password;
if (null === $Password) {
if (!$this->Connection->login($Username)) {
throw new ComponentException(__METHOD__.': Login failed');
}
} else {
if (!$this->Connection->login($Username, $Password)) {
throw new ComponentException(__METHOD__.': Login failed');
}
}
return $this;
}
/**
* @param string $Username
* @param string $File
* @param null|string $Password
*
* @return SFTP
* @throws ComponentException
*/
public function loginCredentialKey($Username, $File, $Password = null)
{
$this->Username = $Username;
$this->Key = $File;
$this->Password = $Password;
$Key = new RSA();
if (null !== $Password) {
$Key->setPassword($Password);
}
if (!$Key->loadKey(file_get_contents($File))) {
throw new ComponentException(__METHOD__.': Key failed');
}
if (!$this->Connection->login($Username, $Key)) {
throw new ComponentException(__METHOD__.': Login failed');
}
return $this;
}
}
| DerDu/SPHERE-Framework | Library/MOC-V/Core/SecureKernel/Component/Bridge/Repository/SFTP/Connection.php | PHP | agpl-3.0 | 3,580 |
package tc.oc.pgm.match;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nullable;
import org.bukkit.entity.Player;
import tc.oc.api.bukkit.users.Users;
import tc.oc.api.docs.PlayerId;
import tc.oc.commons.core.chat.AbstractMultiAudience;
import tc.oc.commons.core.chat.Audience;
public abstract class MultiPlayerParty implements Party {
protected final Match match;
private final Set<MatchPlayer> players = new HashSet<>();
private final Audience audience = new AbstractMultiAudience() {
@Override
protected Iterable<? extends Audience> getAudiences() {
return getPlayers();
}
};
public MultiPlayerParty(Match match) {
this.match = match;
}
/** Gets the match that this team is tied to.
* @return Match this team is tied to.
*/
@Override
public Match getMatch() {
return this.match;
}
@Override
public boolean addPlayerInternal(MatchPlayer player) {
return players.add(player);
}
@Override
public boolean removePlayerInternal(MatchPlayer player) {
return players.remove(player);
}
@Override
public Set<MatchPlayer> getPlayers() {
return players;
}
/**
* Return the member of this team matching the given ID, or null if there
* is no matching player currently on this team.
*/
@Override
public @Nullable MatchPlayer getPlayer(PlayerId playerId) {
Player player = Users.player(playerId);
if(player == null) return null;
for(MatchPlayer teamPlayer : this.getPlayers()) {
if(player == teamPlayer.getBukkit()) return teamPlayer;
}
return null;
}
@Override
public Audience audience() {
return audience;
}
}
| OvercastNetwork/ProjectAres | PGM/src/main/java/tc/oc/pgm/match/MultiPlayerParty.java | Java | agpl-3.0 | 1,803 |
<?php
/*
* eyeos - The Open Source Cloud's Web Desktop
* Version 2.0
* Copyright (C) 2007 - 2010 eyeos Team
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* version 3 along with this program in the file "LICENSE". If not, see
* <http://www.gnu.org/licenses/agpl-3.0.txt>.
*
* See www.eyeos.org for more details. All requests should be sent to [email protected]
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* eyeos" logo and retain the original copyright notice. If the display of the
* logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices
* must display the words "Powered by eyeos" and retain the original copyright notice.
*/
interface IImpressionsProvider {
public function storeImpressionTO(ImpressionTO $impressionTO);
public function deleteImpressionTO(ImpressionTO $impressionTO) ;
public function retrieveAllImpressionsTO(ImpressionTO $impressionTO);
public function retrieveImpressionTOByTarget($sourceId, $targetId);
}
interface IRelationsProvider {
public function storeRelation(Relation $relation);
public function updateRelation(Relation $relation);
public function deleteRelation(Relation $relation);
public function searchRelation(Relation $relation);
public function retrieveAllRelationsByUserId(IUser $user);
public function retrieveLastRelationsByUserId(IUser $user, $limit);
}
interface IPeopleTagProvider {
public function storeTag(PeopleTag $tag);
public function deleteTag(PeopleTag $tag);
public function updateTag(PeopleTag $tag);
public function retrieveAllTags($userId);
public function getTagName($tagId);
}
interface IImpressionTagProvider {
public function storeTagPerImpressionTO(TagPerImpressionTO $tagPerImpression);
public function deleteTagPerImpressionTO(TagPerImpressionTO $tagPerImpressionTO);
public function retrieveAllTagPerImpressionTO($impressionId);
}
class PeopleEvent extends EventObject {
public function __construct($source, $relatedSource = null) {
parent::__construct($source, $relatedSource);
}
}
interface IPeopleListener extends IEventListener {
public function contactCreated(PeopleEvent $e);
public function contactConfirmed(PeopleEvent $e);
public function contactBeforeDeletion(PeopleEvent $e);
public function contactDeleted(PeopleEvent $e);
public function tagAddedToContact(PeopleEvent $e);
public function beforeTagDeletionToContact(PeopleEvent $e);
public function tagDeletedToContact(PeopleEvent $e);
public function tagCreated(PeopleEvent $e);
public function tagModified(PeopleEvent $e);
public function tagRemoved(PeopleEvent $e);
}
abstract class AbstractPeopleAdapter implements IPeopleListener {
public function contactCreated(PeopleEvent $e) {}
public function contactConfirmed(PeopleEvent $e) {}
public function contactBeforeDeletion(PeopleEvent $e) {}
public function contactDeleted(PeopleEvent $e) {}
public function tagAddedToContact(PeopleEvent $e) {}
public function beforeTagDeletionToContact(PeopleEvent $e) {}
public function tagDeletedToContact(PeopleEvent $e) {}
public function tagCreated(PeopleEvent $e) {}
public function tagModified(PeopleEvent $e) {}
public function beforeTagDeletion(PeopleEvent $e) {}
public function tagRemoved(PeopleEvent $e) {}
}
interface IObservablePeopleManager {
public function addPeopleListener(IPeopleListener $listener, $currentRequestOnly = true);
public function fireEvent($type, PeopleEvent $event);
public function getAllPeopleListeners();
public function removePeopleListener(IPeopleListener $listener);
}
?> | Seldaiendil/meyeOS | eyeos/system/Frameworks/People/interfaces.php | PHP | agpl-3.0 | 4,517 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2002-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.spring.BeanUtils;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.test.db.annotations.JUnitTemporaryDatabase;
import org.opennms.netmgt.dao.api.DistPollerDao;
import org.opennms.netmgt.dao.api.MonitoringLocationDao;
import org.opennms.netmgt.model.OnmsDistPoller;
import org.opennms.netmgt.model.OnmsMonitoringSystem;
import org.opennms.test.JUnitConfigurationEnvironment;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"classpath:/META-INF/opennms/applicationContext-soa.xml",
"classpath:/META-INF/opennms/applicationContext-dao.xml",
"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml",
"classpath*:/META-INF/opennms/component-dao.xml",
"classpath:/META-INF/opennms/applicationContext-commonConfigs.xml",
"classpath:/META-INF/opennms/applicationContext-minimal-conf.xml"
})
@JUnitConfigurationEnvironment
@JUnitTemporaryDatabase
public class DistPollerDaoIT implements InitializingBean {
@Autowired
private DistPollerDao m_distPollerDao;
@Override
public void afterPropertiesSet() throws Exception {
BeanUtils.assertAutowiring(this);
}
@Test
@Transactional
public void testCreate() {
OnmsDistPoller distPoller = new OnmsDistPoller("otherpoller");
distPoller.setLabel("otherpoller");
distPoller.setLocation(MonitoringLocationDao.DEFAULT_MONITORING_LOCATION_ID);
distPoller.setType(OnmsMonitoringSystem.TYPE_OPENNMS);
getDistPollerDao().save(distPoller);
}
@Test
@Transactional
public void testGet() {
assertNull(getDistPollerDao().get("otherpoller"));
testCreate();
OnmsDistPoller distPoller = getDistPollerDao().get("otherpoller");
assertNotNull(distPoller);
}
private DistPollerDao getDistPollerDao() {
return m_distPollerDao;
}
}
| aihua/opennms | opennms-dao/src/test/java/org/opennms/netmgt/dao/DistPollerDaoIT.java | Java | agpl-3.0 | 3,567 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Rgaa30 Test.1.9.4 NA 02</title>
</head>
<body>
<div>
<h1>Rgaa30 Test.1.9.4 NA 02</h1>
<div class="test-detail" lang="fr"> Chaque
<a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mImgTextObj">image texte objet</a> (balise
<code>object</code> avec l'attribut
<code>type="image/..."</code>) doit si possible être remplacée par du
<a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mTexteStyle">texte stylé</a>. Cette règle est-elle respectée (
<a href="http://references.modernisation.gouv.fr/referentiel-technique-0#cpCrit19-" title="Cas particuliers pour le critère 1.9">hors cas particuliers</a>) ?
</div>
<div class="testcase">
<object data="mock_image.gif" type="ima/gif"> Some text can be added here. </object>
</div>
<div class="test-explanation">
NA : The html element implied by the test is not present on the page
</div>
</div>
</body>
</html> | dzc34/Asqatasun | rules/rules-rgaa3.0/src/test/resources/testcases/rgaa30/Rgaa30Rule010904/Rgaa30.Test.01.09.04-4NA-02.html | HTML | agpl-3.0 | 1,443 |
<?php
/**
* @author Andreas Fischer <[email protected]>
* @copyright 2013 Andreas Fischer
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
class Unit_Math_BigInteger_BCMathTest extends Unit_Math_BigInteger_TestCase
{
public static function setUpBeforeClass()
{
if (!extension_loaded('bcmath')) {
self::markTestSkipped('BCMath extension is not available.');
}
parent::setUpBeforeClass();
self::ensureConstant('MATH_BIGINTEGER_MODE', \phpseclib\Math\BigInteger::MODE_BCMATH);
}
}
| hannesk001/SPHERE-Framework | Library/MOC-V/Core/SecureKernel/Vendor/PhpSecLib/2.0.0/tests/Unit/Math/BigInteger/BCMathTest.php | PHP | agpl-3.0 | 576 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2002-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.spring.BeanUtils;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.test.db.annotations.JUnitTemporaryDatabase;
import org.opennms.netmgt.dao.api.AssetRecordDao;
import org.opennms.netmgt.dao.api.DistPollerDao;
import org.opennms.netmgt.dao.api.MonitoringLocationDao;
import org.opennms.netmgt.dao.api.NodeDao;
import org.opennms.netmgt.model.OnmsAssetRecord;
import org.opennms.netmgt.model.OnmsGeolocation;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.test.JUnitConfigurationEnvironment;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"classpath:/META-INF/opennms/applicationContext-soa.xml",
"classpath:/META-INF/opennms/applicationContext-dao.xml",
"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml",
"classpath*:/META-INF/opennms/component-dao.xml",
"classpath:/META-INF/opennms/applicationContext-commonConfigs.xml",
"classpath:/META-INF/opennms/applicationContext-minimal-conf.xml"
})
@JUnitConfigurationEnvironment
@JUnitTemporaryDatabase(dirtiesContext=false)
public class AssetRecordDaoIT implements InitializingBean {
@Autowired
private DistPollerDao m_distPollerDao;
@Autowired
private MonitoringLocationDao m_locationDao;
@Autowired
private NodeDao m_nodeDao;
@Autowired
private AssetRecordDao m_assetRecordDao;
@Autowired
private DatabasePopulator m_databasePopulator;
@Override
public void afterPropertiesSet() throws Exception {
BeanUtils.assertAutowiring(this);
}
private static boolean m_populated = false;
@BeforeTransaction
public void setUp() {
if (!m_populated) {
m_databasePopulator.populateDatabase();
m_populated = true;
}
}
@Test
@Transactional
public void testCreateAndGets() {
OnmsNode onmsNode = new OnmsNode(m_locationDao.getDefaultLocation(), "myNode");
m_nodeDao.save(onmsNode);
OnmsAssetRecord assetRecord = onmsNode.getAssetRecord();
assetRecord.setAssetNumber("imported-id: 7");
m_assetRecordDao.update(assetRecord);
m_assetRecordDao.flush();
//Test findAll method
Collection<OnmsAssetRecord> assetRecords = m_assetRecordDao.findAll();
assertEquals(7, assetRecords.size());
//Test countAll method
assertEquals(7, m_assetRecordDao.countAll());
}
@Test
@Transactional
public void testAddUserName() {
OnmsNode onmsNode = new OnmsNode(m_locationDao.getDefaultLocation(), "myNode");
m_nodeDao.save(onmsNode);
OnmsAssetRecord assetRecord = onmsNode.getAssetRecord();
assetRecord.setAssetNumber("imported-id: 7");
assetRecord.setUsername("antonio");
assetRecord.setPassword("password");
assetRecord.setEnable("cisco");
assetRecord.setConnection(OnmsAssetRecord.TELNET_CONNECTION);
m_assetRecordDao.update(assetRecord);
m_assetRecordDao.flush();
//Test findAll method
int id = assetRecord.getId();
OnmsAssetRecord assetRecordFromDb = m_assetRecordDao.get(id);
assertEquals(assetRecord.getUsername(), assetRecordFromDb.getUsername());
assertEquals(assetRecord.getPassword(), assetRecordFromDb.getPassword());
assertEquals(assetRecord.getEnable(), assetRecordFromDb.getEnable());
assertEquals(assetRecord.getConnection(), assetRecordFromDb.getConnection());
}
@Test
@Transactional
public void testAddAutoenable() {
OnmsNode onmsNode = new OnmsNode(m_locationDao.getDefaultLocation(), "myNode");
m_nodeDao.save(onmsNode);
OnmsAssetRecord assetRecord = onmsNode.getAssetRecord();
assetRecord.setAssetNumber("imported-id: 7");
assetRecord.setUsername("antonio");
assetRecord.setPassword("password");
assetRecord.setAutoenable(OnmsAssetRecord.AUTOENABLED);
assetRecord.setConnection(OnmsAssetRecord.TELNET_CONNECTION);
m_assetRecordDao.update(assetRecord);
m_assetRecordDao.flush();
//Test findAll method
int id = assetRecord.getId();
OnmsAssetRecord assetRecordFromDb = m_assetRecordDao.get(id);
assertEquals(assetRecord.getUsername(), assetRecordFromDb.getUsername());
assertEquals(assetRecord.getPassword(), assetRecordFromDb.getPassword());
assertEquals(assetRecord.getAutoenable(), assetRecordFromDb.getAutoenable());
assertEquals(assetRecord.getConnection(), assetRecordFromDb.getConnection());
}
@Test
@Transactional
public void testFindByNodeId() {
OnmsNode onmsNode = new OnmsNode(m_locationDao.getDefaultLocation(), "myNode");
m_nodeDao.save(onmsNode);
OnmsAssetRecord assetRecord = onmsNode.getAssetRecord();
assetRecord.setAssetNumber("imported-id: 7");
m_assetRecordDao.update(assetRecord);
m_assetRecordDao.flush();
//Test findByNodeId method
OnmsAssetRecord a = m_assetRecordDao.findByNodeId(onmsNode.getId());
assertTrue(a.equals(assetRecord));
}
@Test
@Transactional
public void testGeolocation() {
OnmsNode onmsNode = new OnmsNode(m_locationDao.getDefaultLocation(), "myNode");
m_nodeDao.save(onmsNode);
OnmsAssetRecord assetRecord = onmsNode.getAssetRecord();
OnmsGeolocation geo = assetRecord.getGeolocation();
if (geo == null) {
geo = new OnmsGeolocation();
assetRecord.setGeolocation(geo);
}
geo.setAddress1("220 Chatham Business Drive");
geo.setCity("Pittsboro");
geo.setState("NC");
geo.setZip("27312");
geo.setCountry("US");
m_assetRecordDao.update(assetRecord);
m_assetRecordDao.flush();
//Test findAll method
int id = assetRecord.getId();
OnmsAssetRecord assetRecordFromDb = m_assetRecordDao.get(id);
assertNotNull(assetRecordFromDb.getGeolocation());
assertEquals(geo.getAddress1(), assetRecordFromDb.getGeolocation().getAddress1());
assertEquals(geo.getCity(), assetRecordFromDb.getGeolocation().getCity());
assertEquals(geo.getState(), assetRecordFromDb.getGeolocation().getState());
assertEquals(geo.getZip(), assetRecordFromDb.getGeolocation().getZip());
assertEquals(geo.getCountry(), assetRecordFromDb.getGeolocation().getCountry());
}
}
| aihua/opennms | opennms-dao/src/test/java/org/opennms/netmgt/dao/AssetRecordDaoIT.java | Java | agpl-3.0 | 8,386 |
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace Shopware\Components\Emotion;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
class DeviceConfiguration
{
/**
* @var Connection
*/
private $connection;
/**
* @param Connection $connection
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
/**
* @param int $categoryId
*
* @throws \Exception
*
* @return array
*/
public function get($categoryId)
{
$query = $this->connection->createQueryBuilder();
$query->select([
'emotion.id',
'emotion.device as devices',
'emotion.show_listing as showListing',
'emotion.fullscreen',
]);
$query->from('s_emotion', 'emotion')
->where('emotion.active = 1')
->andWhere('emotion.is_landingpage = 0')
->andWhere('(emotion.valid_to >= NOW() OR emotion.valid_to IS NULL)')
->andWhere('(emotion.valid_from <= NOW() OR emotion.valid_from IS NULL)')
->addOrderBy('emotion.position', 'ASC')
->addOrderBy('emotion.id', 'ASC')
->setParameter(':categoryId', $categoryId);
$query->innerJoin(
'emotion',
's_emotion_categories',
'category',
'category.emotion_id = emotion.id
AND category.category_id = :categoryId'
);
/** @var $statement \PDOStatement */
$statement = $query->execute();
$emotions = $statement->fetchAll(\PDO::FETCH_ASSOC);
$emotions = array_map(function ($emotion) {
$emotion['devicesArray'] = explode(',', $emotion['devices']);
return $emotion;
}, $emotions);
return $emotions;
}
/**
* @param $emotionId
*
* @throws \Exception
*
* @return array
*/
public function getById($emotionId)
{
$query = $this->connection->createQueryBuilder();
$query->select([
'emotion.id',
'emotion.device as devices',
'emotion.show_listing as showListing',
]);
$query->from('s_emotion', 'emotion')
->where('emotion.id = :emotionId')
->setParameter(':emotionId', $emotionId);
/** @var $statement \PDOStatement */
$statement = $query->execute();
return $statement->fetch(\PDO::FETCH_ASSOC);
}
/**
* @param $id
*
* @throws \Exception
*
* @return array
*/
public function getLandingPage($id)
{
$master = $this->getMasterLandingPage($id);
if (!$master) {
return null;
}
$children = $this->getChildrenLandingPages($id);
$children = array_merge([$master], $children);
$children = array_map(function ($emotion) {
$emotion['devicesArray'] = explode(',', $emotion['devices']);
return $emotion;
}, $children);
$master['emotions'] = $children;
return $master;
}
/**
* Get shops of landingpage by emotion id.
*
* @param $emotionId
*
* @return array
*/
public function getLandingPageShops($emotionId)
{
$query = $this->getLandingpageShopsQuery();
$query->setParameter(':id', $emotionId);
/** @var $statement \PDOStatement */
$statement = $query->execute();
$shops = $statement->fetchAll(\PDO::FETCH_COLUMN);
return $shops;
}
/**
* @param $id
*
* @return array|null
*/
private function getMasterLandingPage($id)
{
$query = $this->getLandingPageQuery()
->andWhere('emotion.id = :id')
->setParameter('id', $id);
/** @var $statement \PDOStatement */
$statement = $query->execute();
return $statement->fetch(\PDO::FETCH_ASSOC);
}
/**
* @param int $parentId
*
* @return array
*/
private function getChildrenLandingPages($parentId)
{
$query = $this->getLandingPageQuery()
->andWhere('emotion.parent_id = :id')
->setParameter(':id', $parentId);
/** @var $statement \PDOStatement */
$statement = $query->execute();
return $statement->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* @return QueryBuilder
*/
private function getLandingPageQuery()
{
$query = $this->connection->createQueryBuilder();
$query->select([
'emotion.id',
'emotion.device as devices',
'emotion.name',
'emotion.seo_title',
'emotion.seo_keywords',
'emotion.seo_description',
'emotion.valid_from',
'emotion.valid_to',
'now()',
]);
$query->from('s_emotion', 'emotion')
->andWhere('emotion.active = 1')
->andWhere('emotion.is_landingpage = 1')
->andWhere('(emotion.valid_from IS NULL OR emotion.valid_from <= now())')
->andWhere('(emotion.valid_to IS NULL OR emotion.valid_to >= now())')
->orderBy('emotion.position', 'ASC')
->addOrderBy('emotion.id', 'ASC')
;
return $query;
}
/**
* Get QueryBuilder for shops of an emotion.
*
* @return QueryBuilder
*/
private function getLandingpageShopsQuery()
{
$query = $this->connection->createQueryBuilder();
$query->select(['shops.shop_id'])
->from('s_emotion_shops', 'shops')
->where('shops.emotion_id = :id');
return $query;
}
}
| JonidBendo/shopware | engine/Shopware/Components/Emotion/DeviceConfiguration.php | PHP | agpl-3.0 | 6,614 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$subpanel_layout = array(
//Removed button because this layout def is a component of
//the activities sub-panel.
'where' => "(tasks.status != 'Completed' AND tasks.status != 'Deferred')",
'list_fields' => array(
'object_image'=>array(
'vname' => 'LBL_OBJECT_IMAGE',
'widget_class' => 'SubPanelIcon',
'width' => '2%',
),
'close_button'=>array(
'widget_class' => 'SubPanelCloseButton',
'vname' => 'LBL_LIST_CLOSE',
'width' => '6%',
'sortable'=>false,
),
'name'=>array(
'vname' => 'LBL_LIST_SUBJECT',
'widget_class' => 'SubPanelDetailViewLink',
'width' => '30%',
),
'status'=>array(
'widget_class' => 'SubPanelActivitiesStatusField',
'vname' => 'LBL_LIST_STATUS',
'width' => '15%',
),
'contact_name'=>array(
'widget_class' => 'SubPanelDetailViewLink',
'target_record_key' => 'contact_id',
'target_module' => 'Contacts',
'module' => 'Contacts',
'vname' => 'LBL_LIST_CONTACT',
'width' => '11%',
),
'date_due'=>array(
'vname' => 'LBL_LIST_DUE_DATE',
'width' => '10%',
'alias' => 'date_start',
'sort_by' => 'date_start',
),
'assigned_user_name' => array (
'name' => 'assigned_user_name',
'vname' => 'LBL_LIST_ASSIGNED_TO_NAME',
'widget_class' => 'SubPanelDetailViewLink',
'target_record_key' => 'assigned_user_id',
'target_module' => 'Employees',
'width' => '22%',
),
'edit_button'=>array(
'vname' => 'LBL_EDIT_BUTTON',
'widget_class' => 'SubPanelEditButton',
'width' => '2%',
),
'remove_button'=>array(
'vname' => 'LBL_REMOVE',
'widget_class' => 'SubPanelRemoveButton',
'width' => '2%',
),
'time_due'=>array(
'usage'=>'query_only',
'alias' => 'time_start'
) ,
),
);
?>
| jmertic/sugarplatformdemo | upload/upgrades/patch/SugarCE-Upgrade-6.4.x-to-6.5.0RC1-restore/modules/Tasks/metadata/subpanels/ForActivities.php | PHP | agpl-3.0 | 3,860 |
# frozen_string_literal: true
class Form::AdminSettings
include ActiveModel::Model
delegate(
:site_contact_username,
:site_contact_username=,
:site_contact_email,
:site_contact_email=,
:site_title,
:site_title=,
:site_description,
:site_description=,
:site_extended_description,
:site_extended_description=,
:site_terms,
:site_terms=,
:open_registrations,
:open_registrations=,
:closed_registrations_message,
:closed_registrations_message=,
:open_deletion,
:open_deletion=,
:timeline_preview,
:timeline_preview=,
:show_staff_badge,
:show_staff_badge=,
:bootstrap_timeline_accounts,
:bootstrap_timeline_accounts=,
:min_invite_role,
:min_invite_role=,
:activity_api_enabled,
:activity_api_enabled=,
:peers_api_enabled,
:peers_api_enabled=,
to: Setting
)
end
| Craftodon/Craftodon | app/models/form/admin_settings.rb | Ruby | agpl-3.0 | 888 |
<?php
/*
http://www.smrealms.de/sms/dlr.php?message_id=%message_id%&send=%send%&receive=%receive%&status=%status%&ref=%ref%&to=%to%
%message_id% Message ID of outgoing text from gateway
%send% sending time as timestamp
%receive% receiving time as timestamp
%status% sending result
%ref% reference (can be given when sending)
%to% where text was being send to
*/
include('../config.inc');
include(LIB . 'Default/SmrMySqlDatabase.class.inc');
include(ENGINE . '/Default/smr.inc');
// database object
$db = new SmrMySqlDatabase();
// get input
$message_id = (int)$_GET['message_id'];
$send_time = (int)$_GET['send'];
$receive_time = (int)$_GET['receive'];
$status = $_GET['status'];
// add dlr to database
$db->query(
'INSERT INTO account_sms_dlr ' .
'(message_id, send_time, receive_time, status) ' .
'VALUES (' . $db->escapeNumber($message_id) . ', ' . $db->escapeNumber($send_time) . ', ' . $db->escapeNumber($receive_time) . ', ' . $db->escapeString($status) . ')');
?> | tmaus/smr | htdocs/sms/dlr.php | PHP | agpl-3.0 | 1,038 |
/*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import _ from 'underscore'
import I18n from 'i18n!modules'
import React from 'react'
import assignmentUtils from './assignmentUtils'
import classnames from 'classnames'
class AssignmentCorrectionRow extends React.Component {
componentDidMount() {
this.initDueAtDateTimeField()
}
handleDateChanged = e => {
// send date chosen in jquery date-picker so that
// the assignment or assignment override due_at is set
const $picker = $(this.refs.due_at)
this.props.onDateChanged($picker.data('date'))
}
initDueAtDateTimeField = () => {
const $picker = $(this.refs.due_at)
$picker.datetime_field().change(this.handleDateChanged)
}
ignoreAssignment = e => {
e.preventDefault()
this.props.updateAssignment({please_ignore: true})
}
// The real 'change' event for due_at happens in initDueAtDateTimeField,
// but we need to check a couple of things during keypress events to
// maintain assignment state consistency
checkDueAtChange = e => {
if (this.props.assignment.overrideForThisSection != undefined) {
if (e.target.value == '') {
$picker = $(this.refs.due_at).data('date', null)
this.props.assignment.due_at = null
}
// When a user edits the due_at datetime field, we should reset any
// previous "please_ignore" request
this.props.updateAssignment({please_ignore: false})
} else {
if (e.target.value == '') {
$picker = $(this.refs.due_at).data('date', null)
this.props.updateAssignment({due_at: null})
}
// When a user edits the due_at datetime field, we should reset any
// previous "please_ignore" request
this.props.updateAssignment({please_ignore: false})
}
}
updateAssignmentName = e => {
this.props.updateAssignment({name: e.target.value, please_ignore: false})
}
currentSectionforOverride = a => {
if (
_.isEmpty(_.where(a.overrides, {course_section_id: a.currentlySelected.id.toString()})) ||
a.currentlySelected.type == 'course'
) {
return true
} else {
return false
}
}
validCheck = a => {
if (a.overrideForThisSection != undefined && a.currentlySelected.type == 'course') {
return a.due_at != null
} else if (
a.overrideForThisSection != undefined &&
a.currentlySelected.type == 'section' &&
a.currentlySelected.id.toString() == a.overrideForThisSection.course_section_id
) {
return a.overrideForThisSection.due_at != null
} else {
return true
}
}
render() {
const assignment = this.props.assignment
const assignmentList = this.props.assignmentList
const rowClass = classnames({
row: true,
'correction-row': true,
'ignore-row': assignment.please_ignore
})
const nameEmptyError = assignmentUtils.nameEmpty(assignment) && !assignment.please_ignore
const nameTooLongError = assignmentUtils.nameTooLong(assignment) && !assignment.please_ignore
const nameError =
assignmentUtils.notUniqueName(assignmentList, assignment) && !assignment.please_ignore
let dueAtError = !assignment.due_at && !assignment.please_ignore
let default_value = null
let place_holder = null
// dueAtError will always return true when assignments have overrides so we want to check and see if the
// assignment override in the section has a due_at date
if (
assignment.overrideForThisSection != undefined &&
assignment.overrideForThisSection.due_at != null
) {
dueAtError = false
}
// handles data being filled in the inputs if there are name issues on an assignment with an assignment override
if (assignment.overrideForThisSection != undefined) {
default_value = $.datetimeString(assignment.overrideForThisSection.due_at, {format: 'medium'})
place_holder = assignment.overrideForThisSection.due_at ? null : I18n.t('No Due Date')
} else {
default_value = $.datetimeString(assignment.due_at, {format: 'medium'})
place_holder = assignment.due_at ? null : I18n.t('No Due Date')
}
// handles 'Everyone Else' scenario
if (
assignmentUtils.noDueDateForEveryoneElseOverride(assignment) &&
this.currentSectionforOverride(assignment)
) {
default_value = $.datetimeString(assignment.due_at, {format: 'medium'})
dueAtError = true
}
const anyError = nameError || dueAtError || nameTooLongError || nameEmptyError
return (
<div className={rowClass}>
<div className="span3 input-container">
{anyError || assignment.please_ignore ? null : <i className="success-mark icon-check" />}
<div
className={classnames({
'error-circle': nameError || nameTooLongError || nameEmptyError
})}
>
<label className="screenreader-only">{I18n.t('Name Error')}</label>
</div>
<input
ref="name"
type="text"
aria-label={I18n.t('Assignment Name')}
className="input-mlarge assignment-name"
placeholder={assignment.name ? null : I18n.t('No Assignment Name')}
defaultValue={_.unescape(assignment.name)}
onChange={this.updateAssignmentName}
/>
{nameError ? <div className="hint-text">The assignment name must be unique</div> : ''}
{nameTooLongError ? (
<div className="hint-text">The name must be under 30 characters</div>
) : (
''
)}
{nameEmptyError ? <div className="hint-text">The name must not be empty</div> : ''}
</div>
<div className="span2 date_field_container input-container assignment_correction_input">
<div
className={classnames({
'error-circle': dueAtError
})}
>
<label className="screenreader-only">{I18n.t('Date Error')}</label>
</div>
<input
ref="due_at"
type="text"
aria-label={I18n.t('Due Date')}
className="input-medium assignment-due-at"
placeholder={place_holder}
defaultValue={default_value}
onChange={this.checkDueAtChange}
/>
<button
style={{visibility: assignment.please_ignore ? 'hidden' : ''}}
className="btn btn-link btn-ignore assignment_correction_ignore"
aria-label={I18n.t('Ignore %{name}', {name: assignment.name})}
title={I18n.t('Ignore Assignment')}
onClick={this.ignoreAssignment}
>
<i className="icon-minimize" />
</button>
</div>
</div>
)
}
}
export default AssignmentCorrectionRow
| djbender/canvas-lms | app/jsx/gradebook/SISGradePassback/AssignmentCorrectionRow.js | JavaScript | agpl-3.0 | 7,441 |
Fabricator(:account_warning) do
account
target_account(fabricator: :account)
text { Faker::Lorem.paragraph }
action 'suspend'
end
| im-in-space/mastodon | spec/fabricators/account_warning_fabricator.rb | Ruby | agpl-3.0 | 138 |
# -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields
class adhoc_base_configuration(models.TransientModel):
_inherit = 'adhoc.base.config.settings'
# Fixes
# Product modules
module_product_share_father_son = fields.Boolean(
'Share products between fother and son companies',
help="""Installs the product_share_father_son module: It allowes to see products with company set as a father company.""")
module_product_template_search_by_ean13 = fields.Boolean(
'Product Search by ean13 on product template',
help="""Installs the product_template_search_by_ean13 module: It allows to search products by ean13 in Product Tree view""")
module_product_pack = fields.Boolean(
'Mange product packs',
help="""Installs the product_pack module: I allows to set product combos with prices based on products components or special prices for the combo""")
module_product_price_currency = fields.Boolean(
'Manage different currencies on product sale price',
help="""Installs the product_price_currency module.""")
module_product_dimensions = fields.Boolean(
'Manage product logistic dimmensions',
help="""Installs the product_dimensions moduele: Add dimensions (length, width and height) products.""")
module_product_supplier_pricelist = fields.Boolean(
'Mange easier supplier pricelist',
help="""Installs the product_supplier_pricelist module: Add sql constraint to restrict: 1. That you can only add one supplier to a product per company 2. That you can add olny one record of same quantity for a supplier pricelist""")
module_product_unique = fields.Boolean(
'Validate product unicity per company on ean13 and interal reference fields',
help="""Installs the product_unique module: It forbides ean13 an internal reference duplications .""")
module_product_historical_price = fields.Boolean(
'Historical price for product in a product tab',
help="""Installs the product_historical_price module.""")
module_product_salesman_group = fields.Boolean(
'Restrict salesman to see only authorized products by using salesman groups.',
help="""Installs the product_salesman_group module.""")
module_product_uom_prices = fields.Boolean(
'Allow to define different prices for different UOMs',
help="""Installs the product_uom_prices module.""")
module_product_force_create_variants = fields.Boolean(
'Allow to force create variants on product templates',
help="""Installs the product_force_create_variants module.""")
module_product_variant_imp = fields.Boolean(
'Make Some Improovements in Variants and Attributes management',
help="""Installs the product_variant_imp module.""")
module_product_prices_update = fields.Boolean(
'Update product prices',
help="""Installs the product_prices_update: It allows to update selected products prices at once by applying a calculation rule.""")
module_product_catalog_aeroo_report = fields.Boolean(
'Report Product catalog.',
help="""Installs the product_catalog_aeroo_report module.""")
module_product_customer_price = fields.Boolean(
'Allow to define different prices for different Customers.',
help="""Installs the product_customer_price module.""")
module_product_website_categ_search = fields.Boolean(
'Product Search by Website Category.',
help="""Installs the product_website_categ_search module: It allows to search products by Website Category in Product Tree view""")
module_product_variant_csv_import = fields.Boolean(
'Add a menu entry in *Sales > Configuration > Product Categories and attributes > Product Template CSV Import".',
help="""Installs the product_variant_csv_import module.""")
module_product_no_translation = fields.Boolean(
'Set the translatable fields of the product object (name,descriptions) to non-translatable fields.',
help="""Installs the product_no_translation module.""")
module_partner_samples = fields.Boolean(
'Manage Samples Given to Customers.',
help="""Installs the partner_samples module.""")
module_product_reference_required = fields.Boolean(
'Add required in field reference.',
help="""Installs the product_reference_required: It makes Reference a mandatory field""") | adhoc-dev/odoo-setup | adhoc_base_product/res_config.py | Python | agpl-3.0 | 4,695 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2016 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.features.topology.plugins.topo.bsm.simulate;
/**
* This criteria is set when simulation mode is enabled.
*
* @author jwhite
*/
public class SimulationEnabledCriteria extends SimulationCriteria {
}
| aihua/opennms | features/topology-map/plugins/org.opennms.features.topology.plugins.topo.bsm/src/main/java/org/opennms/features/topology/plugins/topo/bsm/simulate/SimulationEnabledCriteria.java | Java | agpl-3.0 | 1,425 |
/**
Dynamically enhance the links "Resulting page" from the report to provide a simplified visualisation of the captured responses
*/
var tabResultLinks = [];
var mapHRef2Links = new Object(); // main link href -> link object
function loadJob()
{
var baseUrl = readBaseUrl();
var cookie = readCookie();
var colLinks = document.getElementsByTagName("A");
var nb = 0;
for (var i=0; i<colLinks.length; ++i)
{
var oLink = colLinks[i];
// improve XSL to have an other criterium, eg a class
var bResultPageLink = (oLink.innerHTML == "Resulting page")
var bGroupResultPageLink = (oLink.innerHTML == "last result page of this group")
if (bResultPageLink || bGroupResultPageLink)
{
oLink.onclick = handleResultLinkClick;
oLink.title += " (Ctrl+mouse over: preview floating over this page, Ctrl+Click: opens in results browser)";
oLink.onmouseover = handleResultMouseOver;
oLink.onmouseout = handleResultMouseOut;
addReferenceParameters(oLink, baseUrl, cookie);
if (bResultPageLink)
{
var newResult = {
resultFilename: oLink.href,
link: oLink,
index: tabResultLinks.length,
tabResultLinks: tabResultLinks
};
tabResultLinks[tabResultLinks.length] = newResult;
mapHRef2Links[oLink.href] = oLink
}
++nb;
}
}
}
function addEvent(_obj, _eventType, _function)
{
if (_obj.addEventListener)
_obj.addEventListener(_eventType, _function, false);
else if (_obj.attachEvent)
_obj.attachEvent("on" + _eventType, _function);
}
addEvent(window, 'load', loadJob);
/**
Handles the click on a link to a result file
If no special key is pressed, nothing special is done and the link can be normally opened
*/
function handleResultLinkClick(_event)
{
var event = _event ? _event : window.event;
if (event.ctrlKey)
{
window.selectedLink = mapHRef2Links[this.href];
// compute the location of the html file: in the same dir as this js file but maybe not in the same dir as the report
var oScript = document.getElementById("scriptResponseBrowser");
var strResponseBrowserHref = oScript.src.replace(".js", ".html"); // -> responseBrowser.html in the right dir
// Shift gives the possibility to open a new Overview window. This may be usefull to compare 2 results films
var targetWindowName = event.shiftKey ? "_blank" : "overview";
window.open(strResponseBrowserHref, targetWindowName);
event.cancelBubble = true;
return false;
}
// normal click, do nothing
return true;
}
/**
Shows a preview in a floating div if the ctr key is pressed while moving the pointer on a link
*/
function handleResultMouseOver(_event)
{
var event = _event ? _event : window.event;
if (event.ctrlKey)
{
showPreview(this);
}
}
/**
Hides the preview (if it was visible)
*/
function handleResultMouseOut(_event)
{
if (window.oPreviewDiv != null)
{
window.oPreviewDiv.style.visibility = "hidden";
}
}
/**
Load the href of the link in a floating preview frame
*/
function showPreview(_oLink)
{
var bIsIE = (document.all != null); // IE CSS support is not that good
if (window.oPreviewDiv == null)
{
window.oPreviewDiv = document.createElement("div");
oPreviewDiv.id = "previewDiv";
document.body.appendChild(oPreviewDiv);
oPreviewDiv.style.position = "fixed";
oPreviewDiv.style.backgroundColor = "white";
oPreviewDiv.style.borderStyle = "solid";
oPreviewDiv.style.borderWidth = "5pt";
oPreviewDiv.style.borderColor = "blue";
oPreviewDiv.style.width = "70%";
oPreviewDiv.style.height = "90%";
oPreviewDiv.style.left = "28%";
oPreviewDiv.style.top = "5%";
oPreviewDiv.style.zIndex = 100;
window.oIframe = document.createElement("iframe");
oPreviewDiv.appendChild(oIframe);
oIframe.style.width = "100%";
oIframe.style.height = "100%";
oIframe.style.overflow = "hidden";
if (bIsIE)
{
oPreviewDiv.style.position = "absolute";
oPreviewDiv.style.width = screen.width * 0.7;
oPreviewDiv.style.height = screen.height * 0.9;
oIframe.style.overflowY = "hidden";
oIframe.style.overflowX = "hidden";
}
}
oIframe.src = _oLink.href;
oPreviewDiv.style.visibility = "visible";
if (bIsIE)
{
oPreviewDiv.style.top = document.body.parentElement.scrollTop + screen.height * 0.05;
}
}
/**
Reads the value of the (first) base url
*/
function readBaseUrl()
{
return evaluateXPath("//a[@class='baseUrl']/@href");
}
/**
Read the name and value of the session cookie of the WebTest (if any).
This cookie need to have been read with <storeCookie property="wtCookie" .../>
*/
function readCookie()
{
var cookieProperty = "wtSessionCookie";
var baseXpath = "//td[@class = 'parameterValue' and text() = '" + cookieProperty + "']/../../tr/td[@class = 'parameterName' and text() = '@myParam@']/following-sibling::td/text()";
var value = evaluateXPath(baseXpath.replace("@myParam@", "-> cookie value"));
if (!value)
return null;
var name = evaluateXPath(baseXpath.replace("@myParam@", "name"));
return {'name': name, 'value': value};
}
/**
Evaluates the string value of the xpath expression
*/
function evaluateXPath(_strXPath)
{
if (document.evaluate)
return document.evaluate(_strXPath, document, null, XPathResult.STRING_TYPE, null).stringValue;
// TODO: make it for IE too
return null;
}
/**
Adds the base url for the test and the session cookie information (if any) to the link.
These information may be read afterwards, for instance by the WebTestRecorder to allow to jump into the session
*/
function addReferenceParameters(_oLink, _baseUrl, _cookie)
{
if (!_baseUrl)
return;
var newHref = _oLink.getAttribute("href") + "?baseUrl=" + escape(_baseUrl)
if (_cookie)
{
newHref += "&cookieName=" + escape(_cookie.name)
newHref += "&cookieValue=" + escape(_cookie.value)
}
_oLink.setAttribute("href", newHref)
} | henning/timetracker | webtest/home/resources/responseBrowser.js | JavaScript | agpl-3.0 | 5,757 |
<?php $TRANSLATIONS = array(
"Welcome to ownCloud" => "Добре дошли в ownCloud"
);
| ipit-international/learning-environment | owncloud/apps/thirstrunwizard/l10n/bg_BG.php | PHP | agpl-3.0 | 93 |
/* Copyright (c) 2001-2009, The HSQL Development Group
* 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 HSQL Development Group 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* 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.
*/
package org.hsqldb_voltpatches.types;
import org.hsqldb_voltpatches.Error;
import org.hsqldb_voltpatches.ErrorCode;
import org.hsqldb_voltpatches.HsqlNameManager.HsqlName;
import org.hsqldb_voltpatches.SchemaObject;
import org.hsqldb_voltpatches.Session;
import org.hsqldb_voltpatches.SessionInterface;
import org.hsqldb_voltpatches.Types;
import org.hsqldb_voltpatches.lib.HashSet;
import org.hsqldb_voltpatches.lib.IntValueHashMap;
import org.hsqldb_voltpatches.lib.OrderedHashSet;
import org.hsqldb_voltpatches.rights.Grantee;
import org.hsqldb_voltpatches.store.ValuePool;
/**
* Base class for type objects.<p>
*
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 1.9.0
* @since 1.9.0
*/
public abstract class Type implements SchemaObject, Cloneable {
public final static Type[] emptyArray = new Type[]{};
//
public final int typeComparisonGroup;
public final int typeCode;
public final long precision;
public final int scale;
public UserTypeModifier userTypeModifier;
//
Type(int typeGroup, int type, long precision, int scale) {
this.typeComparisonGroup = typeGroup;
this.typeCode = type;
this.precision = precision;
this.scale = scale;
}
// interface specific methods
@Override
public final int getType() {
if (userTypeModifier == null) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
return userTypeModifier.getType();
}
@Override
public final HsqlName getName() {
if (userTypeModifier == null) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
return userTypeModifier.getName();
}
@Override
public final HsqlName getCatalogName() {
if (userTypeModifier == null) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
return userTypeModifier.getSchemaName().schema;
}
@Override
public final HsqlName getSchemaName() {
if (userTypeModifier == null) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
return userTypeModifier.getSchemaName();
}
@Override
public final Grantee getOwner() {
if (userTypeModifier == null) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
return userTypeModifier.getOwner();
}
@Override
public final OrderedHashSet getReferences() {
if (userTypeModifier == null) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
return userTypeModifier.getReferences();
}
@Override
public final OrderedHashSet getComponents() {
if (userTypeModifier == null) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
return userTypeModifier.getComponents();
}
@Override
public final void compile(Session session) {
if (userTypeModifier == null) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
userTypeModifier.compile(session);
}
/**
* Retrieves the SQL character sequence required to (re)create the
* trigger, as a StringBuffer
*
* @return the SQL character sequence required to (re)create the
* trigger
*/
@Override
public String getSQL() {
if (userTypeModifier == null) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
return userTypeModifier.getSQL();
}
public Type duplicate() {
try {
return (Type) clone();
} catch (CloneNotSupportedException e) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
}
public abstract int displaySize();
/**
* Returns the JDBC type number of type, if it exists,
* otherwise the HSQLDB / SQL type.
*/
public abstract int getJDBCTypeCode();
/**
* Returns the JDBC class name of type, if it exists,
* otherwise the HSQLDB class name.
*/
public abstract String getJDBCClassName();
public Integer getJDBCScale() {
return acceptsScale() ? ValuePool.getInt(scale)
: null;
}
public Integer getJDBCPrecision() {
return precision > Integer.MAX_VALUE
? ValuePool.getInt(Integer.MAX_VALUE)
: ValuePool.INTEGER_0;
}
/**
* Returns the generic SQL CLI type number of type, if it exists,
* otherwise the HSQLDB type. The generic type is returned for DATETIME
* and INTERVAL types.
*/
public int getSQLGenericTypeCode() {
return typeCode;
}
/**
* Returns the name of the type
*/
public abstract String getNameString();
/**
* Returns the name of the type
*/
public String getFullNameString() {
return getNameString();
}
/**
* Returns the full definition of the type, including parameters
*/
abstract String getDefinition();
public final String getTypeDefinition() {
if (userTypeModifier == null) {
return getDefinition();
}
return getName().getSchemaQualifiedStatementName();
}
public abstract int compare(Object a, Object b);
public abstract Object convertToTypeLimits(SessionInterface session,
Object a);
/**
* Explicit casts are handled by this method.
* SQL standard 6.12 rules for enforcement of size, precision and scale
* are implemented. For CHARACTER values, it performs truncation in all
* cases of long strings.
*/
public Object castToType(SessionInterface session, Object a, Type type) {
return convertToType(session, a, type);
}
/**
* Same as castToType except for CHARACTER values. Perform string
* truncation of trailing spaces only. For other long strings, it raises
* an exception.
*/
public abstract Object convertToType(SessionInterface session, Object a,
Type type);
/**
* Convert type for JDBC. Same as convertToType, but supports non-standard
* SQL conversions supported by JDBC
*/
public Object convertToTypeJDBC(SessionInterface session, Object a,
Type type) {
return convertToType(session, a, type);
}
public Object convertJavaToSQL(SessionInterface session, Object a) {
return a;
}
public Object convertSQLToJava(SessionInterface session, Object a) {
return a;
}
/**
* Converts the object to the given type. Used for JDBC conversions.
*/
public abstract Object convertToDefaultType(
SessionInterface sessionInterface, Object o);
public abstract String convertToString(Object a);
public abstract String convertToSQLString(Object a);
public abstract boolean canConvertFrom(Type otherType);
public boolean isDistinctType() {
return userTypeModifier == null ? false
: userTypeModifier.schemaObjectType
== SchemaObject.TYPE;
}
public boolean isStructuredType() {
return false;
}
public boolean isDomainType() {
return userTypeModifier == null ? false
: userTypeModifier.schemaObjectType
== SchemaObject.DOMAIN;
}
public boolean isCharacterType() {
return false;
}
public boolean isNumberType() {
return false;
}
public boolean isIntegralType() {
return false;
}
public boolean isExactNumberType() {
return false;
}
public boolean isDateTimeType() {
return false;
}
public boolean isDateTimeTypeWithZone() {
return false;
}
public boolean isIntervalType() {
return false;
}
public boolean isBinaryType() {
return false;
}
public boolean isBooleanType() {
return false;
}
public boolean isLobType() {
return false;
}
public boolean isBitType() {
return false;
}
public boolean isObjectType() {
return false;
}
public boolean isGeographyPointType() {
return false;
}
public boolean isGeographyType() {
return false;
}
public boolean acceptsPrecision() {
return false;
}
public boolean requiresPrecision() {
return false;
}
public boolean acceptsFractionalPrecision() {
return false;
}
public boolean acceptsScale() {
return false;
}
public int precedenceDegree(Type other) {
if (other.typeCode == typeCode) {
return 0;
}
return Integer.MIN_VALUE;
}
/**
* Common type used in comparison opertions. other must be comparable
* with this.
*/
public abstract Type getAggregateType(Type other);
/**
* Result type of combining values of two types in different opertions.
* other type is not allways comparable with this, but a operation should
* be valid without any explicit CAST
*/
public abstract Type getCombinedType(Type other, int operation);
public int compareToTypeRange(Object o) {
return 0;
}
/**
* All arithmetic ops are called on the pre-determined Type object of the result
*/
public Object absolute(Object a) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
public Object negate(Object a) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
public Object add(Object a, Object b, Type otherType) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
public Object subtract(Object a, Object b, Type otherType) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
public Object multiply(Object a, Object b) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
public Object divide(Object a, Object b) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
public Object concat(Session session, Object a, Object b) {
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof Type) {
return ((Type) other).typeCode == typeCode
&& ((Type) other).precision == precision
&& ((Type) other).scale == scale
&& ((Type) other).userTypeModifier == userTypeModifier;
}
return false;
}
@Override
public int hashCode() {
return typeCode + (int) precision << 8 + scale << 16;
}
/** @todo 1.9.0 - review all needs max implementation defined lengths, used for parameters */
// null type
public static final Type SQL_ALL_TYPES = NullType.getNullType();
// character types
public static final Type SQL_CHAR = new CharacterType(Types.SQL_CHAR, 0);
public static final Type SQL_VARCHAR = new CharacterType(Types.SQL_VARCHAR,
0);
public static final Type SQL_CHAR_DEFAULT =
new CharacterType(Types.SQL_CHAR, 32 * 1024);
public static final Type SQL_VARCHAR_DEFAULT =
new CharacterType(Types.SQL_VARCHAR, 32 * 1024);
public static final ClobType SQL_CLOB = new ClobType();
public static final Type VARCHAR_IGNORECASE =
new CharacterType(Types.VARCHAR_IGNORECASE, 0);
// binary types
public static final BitType SQL_BIT = new BitType(Types.SQL_BIT, 0);
public static final BitType SQL_BIT_VARYING =
new BitType(Types.SQL_BIT_VARYING, 0);
public static final BitType SQL_BIT_VARYING_MAX_LENGTH =
new BitType(Types.SQL_BIT_VARYING, 32 * 1024);
// binary types
public static final BinaryType SQL_BINARY =
new BinaryType(Types.SQL_BINARY, 0);
public static final BinaryType SQL_BINARY_DEFAULT =
new BinaryType(Types.SQL_BINARY, 32 * 1024);
public static final BinaryType SQL_VARBINARY =
new BinaryType(Types.SQL_VARBINARY, 0);
public static final BinaryType SQL_VARBINARY_DEFAULT =
new BinaryType(Types.SQL_VARBINARY, 32 * 1024);
public static final BlobType SQL_BLOB = new BlobType();
// other type
public static final OtherType OTHER = OtherType.getOtherType();
// boolean type
public static final BooleanType SQL_BOOLEAN = BooleanType.getBooleanType();
// number types
public static final NumberType SQL_NUMERIC =
new NumberType(Types.SQL_NUMERIC, NumberType.defaultNumericPrecision,
0);
public static final NumberType SQL_DECIMAL =
new NumberType(Types.SQL_DECIMAL, NumberType.defaultNumericPrecision,
// VoltDB BEGIN Cherry-picked code change from hsqldb-2.2.8
7);
public static final NumberType SQL_DECIMAL_DEFAULT =
new NumberType(Types.SQL_DECIMAL, NumberType.defaultNumericPrecision,
NumberType.defaultNumericScale);
/* disable 1 line ...
0);
... disabled 1 line */
// VoltDB END Cherry-picked code change from hsqldb-2.2.8
public static final NumberType SQL_DECIMAL_BIGINT_SQR =
// A VoltDB extension to disable use of giant types in sums
new NumberType(Types.SQL_BIGINT, NumberType.bigintPrecision, 8);
/* disable 2 lines ...
new NumberType(Types.SQL_DECIMAL,
NumberType.bigintSquareNumericPrecision, 0);
... disabled 2 lines */
// End of VoltDB extension
public static final NumberType SQL_DOUBLE =
// A VoltDB extension -- mysterious
new NumberType(Types.SQL_DOUBLE, NumberType.doublePrecision, 8);
/* disable 1 line ...
new NumberType(Types.SQL_DOUBLE, 0, 0);
... disabled 1 line */
// End of VoltDB extension
//
public static final NumberType TINYINT = new NumberType(Types.TINYINT,
// A VoltDB extension -- mysterious
NumberType.tinyintPrecision, 1);
/* disable 1 line ...
NumberType.tinyintPrecision, 0);
... disabled 1 line */
// End of VoltDB extension
public static final NumberType SQL_SMALLINT =
// A VoltDB extension -- mysterious
new NumberType(Types.SQL_SMALLINT, NumberType.smallintPrecision, 2);
/* disable 1 line ...
new NumberType(Types.SQL_SMALLINT, NumberType.smallintPrecision, 0);
... disabled 1 line */
// End of VoltDB extension
public static final NumberType SQL_INTEGER =
// A VoltDB extension -- mysterious
new NumberType(Types.SQL_INTEGER, NumberType.integerPrecision, 4);
/* disable 1 line ...
new NumberType(Types.SQL_INTEGER, NumberType.integerPrecision, 0);
... disabled 1 line */
// End of VoltDB extension
public static final NumberType SQL_BIGINT =
// A VoltDB extension -- mysterious
new NumberType(Types.SQL_BIGINT, NumberType.bigintPrecision, 8);
/* disable 1 line ...
new NumberType(Types.SQL_BIGINT, NumberType.bigintPrecision, 0);
... disabled 1 line */
// End of VoltDB extension
// date time
public static final DateTimeType SQL_DATE =
new DateTimeType(Types.SQL_TIMESTAMP, Types.SQL_DATE, 0);
public static final DateTimeType SQL_TIME =
new DateTimeType(Types.SQL_TIME, Types.SQL_TIME,
DTIType.defaultTimeFractionPrecision);
public static final DateTimeType SQL_TIME_WITH_TIME_ZONE =
new DateTimeType(Types.SQL_TIME, Types.SQL_TIME_WITH_TIME_ZONE,
DTIType.defaultTimeFractionPrecision);
public static final DateTimeType SQL_TIMESTAMP =
new DateTimeType(Types.SQL_TIMESTAMP, Types.SQL_TIMESTAMP,
DTIType.defaultTimestampFractionPrecision);
public static final DateTimeType SQL_TIMESTAMP_WITH_TIME_ZONE =
new DateTimeType(Types.SQL_TIMESTAMP,
Types.SQL_TIMESTAMP_WITH_TIME_ZONE,
DTIType.defaultTimestampFractionPrecision);
public static final DateTimeType SQL_TIMESTAMP_NO_FRACTION =
new DateTimeType(Types.SQL_TIMESTAMP, Types.SQL_TIMESTAMP, 0);
// interval
public static final IntervalType SQL_INTERVAL_YEAR =
IntervalType.newIntervalType(Types.SQL_INTERVAL_YEAR,
DTIType.defaultIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_MONTH =
IntervalType.newIntervalType(Types.SQL_INTERVAL_MONTH,
DTIType.defaultIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_DAY =
IntervalType.newIntervalType(Types.SQL_INTERVAL_DAY,
DTIType.defaultIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_HOUR =
IntervalType.newIntervalType(Types.SQL_INTERVAL_HOUR,
DTIType.defaultIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_MINUTE =
IntervalType.newIntervalType(Types.SQL_INTERVAL_MINUTE,
DTIType.defaultIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_SECOND =
IntervalType.newIntervalType(Types.SQL_INTERVAL_SECOND,
DTIType.defaultIntervalPrecision,
DTIType.defaultIntervalFractionPrecision);
public static final IntervalType SQL_INTERVAL_SECOND_MAX_FRACTION =
IntervalType.newIntervalType(Types.SQL_INTERVAL_SECOND,
DTIType.defaultIntervalPrecision,
DTIType.maxFractionPrecision);
public static final IntervalType SQL_INTERVAL_YEAR_TO_MONTH =
IntervalType.newIntervalType(Types.SQL_INTERVAL_YEAR_TO_MONTH,
DTIType.defaultIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_DAY_TO_HOUR =
IntervalType.newIntervalType(Types.SQL_INTERVAL_DAY_TO_HOUR,
DTIType.defaultIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_DAY_TO_MINUTE =
IntervalType.newIntervalType(Types.SQL_INTERVAL_DAY_TO_MINUTE,
DTIType.defaultIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_DAY_TO_SECOND =
IntervalType.newIntervalType(Types.SQL_INTERVAL_DAY_TO_SECOND,
DTIType.defaultIntervalPrecision,
DTIType.defaultIntervalFractionPrecision);
public static final IntervalType SQL_INTERVAL_HOUR_TO_MINUTE =
IntervalType.newIntervalType(Types.SQL_INTERVAL_HOUR_TO_MINUTE,
DTIType.defaultIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_HOUR_TO_SECOND =
IntervalType.newIntervalType(Types.SQL_INTERVAL_HOUR_TO_SECOND,
DTIType.defaultIntervalPrecision,
DTIType.defaultIntervalFractionPrecision);
public static final IntervalType SQL_INTERVAL_MINUTE_TO_SECOND =
IntervalType.newIntervalType(Types.SQL_INTERVAL_MINUTE_TO_SECOND,
DTIType.defaultIntervalPrecision,
DTIType.defaultIntervalFractionPrecision);
//
public static final IntervalType SQL_INTERVAL_YEAR_MAX_PRECISION =
IntervalType.newIntervalType(Types.SQL_INTERVAL_YEAR,
DTIType.maxIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_MONTH_MAX_PRECISION =
IntervalType.newIntervalType(Types.SQL_INTERVAL_MONTH,
DTIType.maxIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_DAY_MAX_PRECISION =
IntervalType.newIntervalType(Types.SQL_INTERVAL_DAY,
DTIType.maxIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_HOUR_MAX_PRECISION =
IntervalType.newIntervalType(Types.SQL_INTERVAL_HOUR,
DTIType.maxIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_MINUTE_MAX_PRECISION =
IntervalType.newIntervalType(Types.SQL_INTERVAL_MINUTE,
DTIType.maxIntervalPrecision, 0);
public static final IntervalType SQL_INTERVAL_SECOND_MAX_PRECISION =
IntervalType.newIntervalType(Types.SQL_INTERVAL_SECOND,
DTIType.maxIntervalPrecision,
DTIType.defaultIntervalFractionPrecision);
public static final IntervalType SQL_INTERVAL_SECOND_MAX_FRACTION_MAX_PRECISION =
IntervalType.newIntervalType(Types.SQL_INTERVAL_SECOND,
DTIType.maxIntervalPrecision,
DTIType.maxFractionPrecision);
public static final VoltGeographyPointType VOLT_GEOGRAPHY_POINT = new VoltGeographyPointType();
public static final VoltGeographyType VOLT_GEOGRAPHY = new VoltGeographyType();
public static Type getDefaultType(int type) {
try {
return getType(type, 0, 0, 0);
} catch (Exception e) {
return null;
}
}
public static Type getDefaultTypeWithSize(int type) {
switch (type) {
case Types.SQL_ALL_TYPES :
return SQL_ALL_TYPES;
// return SQL_ALL_TYPES; // needs changes to Expression type resolution
case Types.SQL_CHAR :
return SQL_CHAR_DEFAULT;
case Types.SQL_VARCHAR :
return SQL_VARCHAR_DEFAULT;
case Types.VARCHAR_IGNORECASE :
return VARCHAR_IGNORECASE;
case Types.SQL_CLOB :
return SQL_CLOB;
case Types.SQL_INTEGER :
return SQL_INTEGER;
case Types.SQL_SMALLINT :
return SQL_SMALLINT;
case Types.SQL_BIGINT :
return SQL_BIGINT;
case Types.TINYINT :
return TINYINT;
case Types.SQL_FLOAT :
case Types.SQL_REAL :
case Types.SQL_DOUBLE :
return SQL_DOUBLE;
case Types.SQL_NUMERIC :
return SQL_NUMERIC;
case Types.SQL_DECIMAL :
return SQL_DECIMAL;
case Types.SQL_BOOLEAN :
return SQL_BOOLEAN;
case Types.SQL_BINARY :
return SQL_BINARY_DEFAULT;
case Types.SQL_VARBINARY :
return SQL_VARBINARY_DEFAULT;
case Types.SQL_BLOB :
return SQL_BLOB;
case Types.SQL_BIT :
return SQL_BIT;
case Types.SQL_BIT_VARYING :
return SQL_BIT_VARYING;
case Types.SQL_DATE :
return SQL_DATE;
case Types.SQL_TIME :
return SQL_TIME;
case Types.SQL_TIME_WITH_TIME_ZONE :
return SQL_TIME_WITH_TIME_ZONE;
case Types.SQL_TIMESTAMP :
return SQL_TIMESTAMP;
case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
return SQL_TIMESTAMP_WITH_TIME_ZONE;
case Types.SQL_INTERVAL_YEAR :
return SQL_INTERVAL_YEAR;
case Types.SQL_INTERVAL_YEAR_TO_MONTH :
return SQL_INTERVAL_YEAR_TO_MONTH;
case Types.SQL_INTERVAL_MONTH :
return SQL_INTERVAL_MONTH;
case Types.SQL_INTERVAL_DAY :
return SQL_INTERVAL_DAY;
case Types.SQL_INTERVAL_DAY_TO_HOUR :
return SQL_INTERVAL_DAY_TO_HOUR;
case Types.SQL_INTERVAL_DAY_TO_MINUTE :
return SQL_INTERVAL_DAY_TO_MINUTE;
case Types.SQL_INTERVAL_DAY_TO_SECOND :
return SQL_INTERVAL_DAY_TO_SECOND;
case Types.SQL_INTERVAL_HOUR :
return SQL_INTERVAL_HOUR;
case Types.SQL_INTERVAL_HOUR_TO_MINUTE :
return SQL_INTERVAL_HOUR_TO_MINUTE;
case Types.SQL_INTERVAL_HOUR_TO_SECOND :
return SQL_INTERVAL_HOUR_TO_SECOND;
case Types.SQL_INTERVAL_MINUTE :
return SQL_INTERVAL_MINUTE;
case Types.SQL_INTERVAL_MINUTE_TO_SECOND :
return SQL_INTERVAL_MINUTE_TO_SECOND;
case Types.SQL_INTERVAL_SECOND :
return SQL_INTERVAL_SECOND;
case Types.OTHER :
return OTHER;
case Types.VOLT_GEOGRAPHY :
return VOLT_GEOGRAPHY;
case Types.VOLT_GEOGRAPHY_POINT :
return VOLT_GEOGRAPHY_POINT;
default :
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
}
public static int getHSQLDBTypeCode(int jdbcTypeNumber) {
switch (jdbcTypeNumber) {
case Types.BIGINT :
return Types.SQL_BIGINT;
case Types.LONGVARCHAR :
return Types.SQL_VARCHAR;
case Types.CLOB :
return Types.SQL_CLOB;
case Types.BINARY :
return Types.SQL_BINARY;
case Types.BIT :
return Types.SQL_BIT_VARYING;
case Types.VARBINARY :
case Types.LONGVARBINARY :
return Types.SQL_VARBINARY;
case Types.BLOB :
return Types.SQL_BLOB;
default :
return jdbcTypeNumber;
}
}
/**
* translate an internal type number to JDBC type number if a type is not
* supported internally, it is returned without translation
*
* @param type int
* @return int
*/
public static int getJDBCTypeCode(int type) {
switch (type) {
case Types.SQL_BLOB :
return Types.BLOB;
case Types.SQL_CLOB :
return Types.CLOB;
case Types.SQL_BIGINT :
return Types.BIGINT;
case Types.SQL_BINARY :
return Types.BINARY;
case Types.SQL_VARBINARY :
return Types.VARBINARY;
case Types.SQL_BIT :
case Types.SQL_BIT_VARYING :
return Types.BIT;
default :
return type;
}
}
/**
* Enforces precision and scale limits on type
*/
public static Type getType(int type, int collation, long precision,
int scale) {
switch (type) {
case Types.SQL_ALL_TYPES :
return SQL_ALL_TYPES;
// return SQL_ALL_TYPES; // needs changes to Expression type resolution
case Types.SQL_CHAR :
case Types.SQL_VARCHAR :
case Types.VARCHAR_IGNORECASE :
case Types.SQL_CLOB :
return CharacterType.getCharacterType(type, precision);
case Types.SQL_INTEGER :
return SQL_INTEGER;
case Types.SQL_SMALLINT :
return SQL_SMALLINT;
case Types.SQL_BIGINT :
return SQL_BIGINT;
case Types.TINYINT :
return TINYINT;
case Types.SQL_FLOAT :
if (precision > 53) {
throw Error.error(ErrorCode.X_42592, "" + precision);
}
// $FALL-THROUGH$
case Types.SQL_REAL :
case Types.SQL_DOUBLE :
return SQL_DOUBLE;
case Types.SQL_NUMERIC :
case Types.SQL_DECIMAL :
if (precision == 0) {
precision = NumberType.defaultNumericPrecision;
}
// A VoltDB extension to disable variable scale decimals
scale = 12;
// End of VoltDB extension
return NumberType.getNumberType(type, precision, scale);
case Types.SQL_BOOLEAN :
return SQL_BOOLEAN;
case Types.SQL_BINARY :
case Types.SQL_VARBINARY :
case Types.SQL_BLOB :
return BinaryType.getBinaryType(type, precision);
case Types.SQL_BIT :
case Types.SQL_BIT_VARYING :
return BitType.getBitType(type, precision);
case Types.SQL_DATE :
case Types.SQL_TIME :
case Types.SQL_TIME_WITH_TIME_ZONE :
case Types.SQL_TIMESTAMP :
case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
return DateTimeType.getDateTimeType(type, scale);
case Types.SQL_INTERVAL_YEAR :
case Types.SQL_INTERVAL_YEAR_TO_MONTH :
case Types.SQL_INTERVAL_MONTH :
case Types.SQL_INTERVAL_DAY :
case Types.SQL_INTERVAL_DAY_TO_HOUR :
case Types.SQL_INTERVAL_DAY_TO_MINUTE :
case Types.SQL_INTERVAL_DAY_TO_SECOND :
case Types.SQL_INTERVAL_HOUR :
case Types.SQL_INTERVAL_HOUR_TO_MINUTE :
case Types.SQL_INTERVAL_HOUR_TO_SECOND :
case Types.SQL_INTERVAL_MINUTE :
case Types.SQL_INTERVAL_MINUTE_TO_SECOND :
case Types.SQL_INTERVAL_SECOND :
return IntervalType.getIntervalType(type, precision, scale);
case Types.VOLT_GEOGRAPHY_POINT :
return VOLT_GEOGRAPHY_POINT;
case Types.VOLT_GEOGRAPHY :
return new VoltGeographyType(precision);
case Types.OTHER :
return OTHER;
default :
throw Error.runtimeError(ErrorCode.U_S0500, "Type");
}
}
public static Type getAggregateType(Type add, Type existing) {
if (existing == null || existing.typeCode == Types.SQL_ALL_TYPES) {
return add;
}
if (add == null || add.typeCode == Types.SQL_ALL_TYPES) {
return existing;
}
return existing.getAggregateType(add);
}
public static final IntValueHashMap typeAliases;
public static final IntValueHashMap typeNames;
public static final HashSet basicTypes;
static {
typeNames = new IntValueHashMap(37);
// A VoltDB extension to disable unsupported types
typeNames.put("TINYINT", Types.TINYINT);
typeNames.put("SMALLINT", Types.SQL_SMALLINT);
typeNames.put("INTEGER", Types.SQL_INTEGER);
typeNames.put("BIGINT", Types.SQL_BIGINT);
typeNames.put("FLOAT", Types.SQL_DOUBLE);
typeNames.put("DECIMAL", Types.SQL_DECIMAL);
typeNames.put("VARCHAR", Types.SQL_VARCHAR);
typeNames.put("TIMESTAMP", Types.SQL_TIMESTAMP);
typeNames.put("VARBINARY", Types.SQL_VARBINARY);
typeNames.put("GEOGRAPHY_POINT", Types.VOLT_GEOGRAPHY_POINT);
typeNames.put("GEOGRAPHY", Types.VOLT_GEOGRAPHY);
typeAliases = new IntValueHashMap(64);
typeAliases.put("INT", Types.SQL_INTEGER);
typeAliases.put("REAL", Types.SQL_DOUBLE);
typeAliases.put("CHARACTER", Types.SQL_CHAR);
/* disable 28 lines ...
typeNames.put("CHARACTER", Types.SQL_CHAR);
typeNames.put("VARCHAR", Types.SQL_VARCHAR);
typeNames.put("VARCHAR_IGNORECASE", Types.VARCHAR_IGNORECASE);
typeNames.put("DATE", Types.SQL_DATE);
typeNames.put("TIME", Types.SQL_TIME);
typeNames.put("TIMESTAMP", Types.SQL_TIMESTAMP);
typeNames.put("INTERVAL", Types.SQL_INTERVAL);
typeNames.put("TINYINT", Types.TINYINT);
typeNames.put("SMALLINT", Types.SQL_SMALLINT);
typeNames.put("INTEGER", Types.SQL_INTEGER);
typeNames.put("BIGINT", Types.SQL_BIGINT);
typeNames.put("REAL", Types.SQL_REAL);
typeNames.put("FLOAT", Types.SQL_FLOAT);
typeNames.put("DOUBLE", Types.SQL_DOUBLE);
typeNames.put("NUMERIC", Types.SQL_NUMERIC);
typeNames.put("DECIMAL", Types.SQL_DECIMAL);
typeNames.put("BOOLEAN", Types.SQL_BOOLEAN);
typeNames.put("BINARY", Types.SQL_BINARY);
typeNames.put("VARBINARY", Types.SQL_VARBINARY);
typeNames.put("CLOB", Types.SQL_CLOB);
typeNames.put("BLOB", Types.SQL_BLOB);
typeNames.put("BIT", Types.SQL_BIT);
typeNames.put("OTHER", Types.OTHER);
//
typeAliases = new IntValueHashMap(64);
typeAliases.put("CHAR", Types.SQL_CHAR);
... disabled 28 lines */
// End of VoltDB extension
/*
typeAliases.put("CHAR VARYING", Types.SQL_VARCHAR);
typeAliases.put("CHARACTER VARYING", Types.SQL_VARCHAR);
typeAliases.put("CHARACTER LARGE OBJECT", Types.SQL_CLOB);
*/
/* disable 6 lines ...
typeAliases.put("INT", Types.SQL_INTEGER);
typeAliases.put("DEC", Types.SQL_DECIMAL);
typeAliases.put("LONGVARCHAR", Types.SQL_VARCHAR);
typeAliases.put("DATETIME", Types.SQL_TIMESTAMP);
typeAliases.put("LONGVARBINARY", Types.SQL_VARBINARY);
typeAliases.put("OBJECT", Types.OTHER);
... disabled 6 lines */
// End of VoltDB extension
//
basicTypes = new HashSet(37);
basicTypes.add(SQL_CHAR_DEFAULT);
basicTypes.add(SQL_VARCHAR_DEFAULT);
basicTypes.add(SQL_DATE);
basicTypes.add(SQL_TIME);
basicTypes.add(SQL_TIMESTAMP);
basicTypes.add(SQL_INTERVAL_YEAR);
basicTypes.add(SQL_INTERVAL_YEAR_TO_MONTH);
basicTypes.add(SQL_INTERVAL_MONTH);
basicTypes.add(SQL_INTERVAL_DAY);
basicTypes.add(SQL_INTERVAL_DAY_TO_HOUR);
basicTypes.add(SQL_INTERVAL_DAY_TO_MINUTE);
basicTypes.add(SQL_INTERVAL_DAY_TO_SECOND);
basicTypes.add(SQL_INTERVAL_HOUR);
basicTypes.add(SQL_INTERVAL_HOUR_TO_MINUTE);
basicTypes.add(SQL_INTERVAL_HOUR_TO_SECOND);
basicTypes.add(SQL_INTERVAL_MINUTE);
basicTypes.add(SQL_INTERVAL_MINUTE_TO_SECOND);
basicTypes.add(SQL_INTERVAL_SECOND);
basicTypes.add(TINYINT);
basicTypes.add(SQL_SMALLINT);
basicTypes.add(SQL_INTEGER);
basicTypes.add(SQL_BIGINT);
basicTypes.add(SQL_DOUBLE);
}
public static int getTypeNr(String name) {
int i = typeNames.get(name, Integer.MIN_VALUE);
if (i == Integer.MIN_VALUE) {
i = typeAliases.get(name, Integer.MIN_VALUE);
}
return i;
}
public static boolean isSupportedSQLType(int typeNumber) {
if (getDefaultType(typeNumber) == null) {
return false;
}
return true;
}
public static boolean matches(Type[] one, Type[] other) {
for (int i = 0; i < one.length; i++) {
if (one[i].typeCode != other[i].typeCode) {
return false;
}
}
return true;
}
}
| simonzhangsm/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/types/Type.java | Java | agpl-3.0 | 37,064 |
require 'hashery/fuzzy_hash'
| BibNumUMontreal/DMPonline_v4 | vendor/ruby/2.1.0/gems/hashery-2.1.2/alt/hashery/fuzzyhash.rb | Ruby | agpl-3.0 | 29 |
/*
* Copyright 2004 Sun Microsystems, Inc.
*
* 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.
*
*/
package com.sun.syndication.io;
import com.sun.syndication.feed.WireFeed;
import com.sun.syndication.io.FeedException;
import org.jdom.Document;
/**
* Parses an XML document (JDOM) into a feed bean.
* <p>
* WireFeedParser instances must thread safe.
* <p>
* TODO: explain how developers can plugin their own implementations.
* <p>
* @author Alejandro Abdelnur
*
*/
public interface WireFeedParser {
/**
* Returns the type of feed the parser handles.
* <p>
* @see WireFeed for details on the format of this string.
* <p>
* @return the type of feed the parser handles.
*
*/
public String getType();
/**
* Inspects an XML Document (JDOM) to check if it can parse it.
* <p>
* It checks if the given document if the type of feeds the parser understands.
* <p>
* @param document XML Document (JDOM) to check if it can be parsed by this parser.
* @return <b>true</b> if the parser know how to parser this feed, <b>false</b> otherwise.
*
*/
public boolean isMyType(Document document);
/**
* Parses an XML document (JDOM Document) into a feed bean.
* <p>
* @param document XML document (JDOM) to parse.
* @param validate indicates if the feed should be strictly validated (NOT YET IMPLEMENTED).
* @return the resulting feed bean.
* @throws IllegalArgumentException thrown if the parser cannot handle the given feed type.
* @throws FeedException thrown if a feed bean cannot be created out of the XML document (JDOM).
*
*/
public WireFeed parse(Document document, boolean validate) throws IllegalArgumentException,FeedException;
}
| 4thline/feeds | src/main/java/com/sun/syndication/io/WireFeedParser.java | Java | agpl-3.0 | 2,290 |
/*
* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package org.pentaho.di.ui.i18n;
import org.apache.commons.vfs.FileObject;
/**
* Contains the occurrence of a key in a java source code file
*
* @author matt
* @since 2007-09-29
*
*/
public class KeyOccurrence implements Comparable<KeyOccurrence> {
/**
* The java source file
*/
private FileObject fileObject;
/**
* The location of the messages file, derived from "^import .*Messages;"
*/
private String messagesPackage;
/**
* The row on which the occurrence takes place
*/
private int row;
/**
* The column on which the occurrence takes place
*/
private int column;
/**
* The i18n key
*/
private String key;
/**
* The arguments from the source code
*/
private String arguments;
/**
* The number of occurrences
*/
private int occurrences;
/**
* line of source code on which the key occurs.
*/
private String sourceLine;
/**
*
*/
public KeyOccurrence() {
occurrences=0;
}
/**
* @param fileObject The java source file
* @param messagesPackage The location of the messages file, derived from "^import .*Messages;"
* @param row The row on which the occurrence takes place
* @param column The column on which the occurrence takes place
* @param key The i18n key
* @param arguments The arguments from the source code
*/
public KeyOccurrence(FileObject fileObject, String messagesPackage, int row, int column, String key, String arguments, String sourceLine) {
this();
this.fileObject = fileObject;
this.messagesPackage = messagesPackage;
this.row = row;
this.column = column;
this.key = key;
this.arguments = arguments;
this.occurrences = 1;
this.sourceLine = sourceLine;
}
public String toString() {
return "[key="+key+", messages package="+messagesPackage+"]";
}
public boolean equals(Object occ) {
if (occ==null) return false;
if (this==occ) return true;
return key.equals(((KeyOccurrence)occ).key) && messagesPackage.equals(((KeyOccurrence)occ).messagesPackage);
}
public int compareTo(KeyOccurrence occ) {
int cmp = key.compareTo(occ.key);
if (cmp!=0) return cmp;
cmp = messagesPackage.compareTo(occ.messagesPackage);
return cmp;
}
/**
* @return The java source file
*/
public FileObject getFileObject() {
return fileObject;
}
/**
* @param fileObject The java source file
*/
public void setFileObject(FileObject fileObject) {
this.fileObject = fileObject;
}
/**
* @return The location of the messages file
*/
public String getMessagesPackage() {
return messagesPackage;
}
/**
* @param messagesPackage The location of the messages file
*/
public void setMessagesPackage(String messagesPackage) {
this.messagesPackage = messagesPackage;
}
/**
* @return The row on which the occurrence takes place
*/
public int getRow() {
return row;
}
/**
* @param row The row on which the occurrence takes place
*/
public void setRow(int row) {
this.row = row;
}
/**
* @return The column on which the occurrence takes place
*/
public int getColumn() {
return column;
}
/**
* @param column The column on which the occurrence takes place
*/
public void setColumn(int column) {
this.column = column;
}
/**
* @return The i18n key
*/
public String getKey() {
return key;
}
/**
* @param key The i18n key
*/
public void setKey(String key) {
this.key = key;
}
/**
* @return The arguments from the source code
*/
public String getArguments() {
return arguments;
}
/**
* @param arguments The arguments from the source code
*/
public void setArguments(String arguments) {
this.arguments = arguments;
}
/**
* @return The number of occurrences
*/
public int getOccurrences() {
return occurrences;
}
/**
* @param occurrences The number of occurrences
*/
public void setOccurrences(int occurrences) {
this.occurrences = occurrences;
}
/**
* Increment the number of occurrences with one.
*/
public void incrementOccurrences() {
this.occurrences++;
}
/**
* @return the line of source code on which the key occurs.
*/
public String getSourceLine() {
return sourceLine;
}
/**
* @param sourceLine the line of source code on which the key occurs.
*/
public void setSourceLine(String sourceLine) {
this.sourceLine = sourceLine;
}
}
| icholy/geokettle-2.0 | src-ui/org/pentaho/di/ui/i18n/KeyOccurrence.java | Java | lgpl-2.1 | 5,088 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<title>CURLMOPT_SOCKETFUNCTION man page</title>
<meta name="generator" content="roffit">
<STYLE type="text/css">
P.level0 {
padding-left: 2em;
}
P.level1 {
padding-left: 4em;
}
P.level2 {
padding-left: 6em;
}
span.emphasis {
font-style: italic;
}
span.bold {
font-weight: bold;
}
span.manpage {
font-weight: bold;
}
h2.nroffsh {
background-color: #e0e0e0;
}
span.nroffip {
font-weight: bold;
font-size: 120%;
font-family: monospace;
}
p.roffit {
text-align: center;
font-size: 80%;
}
</STYLE>
</head><body>
<p class="level0"><a name="NAME"></a><h2 class="nroffsh">NAME</h2>
<p class="level0">CURLMOPT_SOCKETFUNCTION - callback informed about what to wait for <a name="SYNOPSIS"></a><h2 class="nroffsh">SYNOPSIS</h2>
<p class="level0"><pre>
<p class="level0">#include <curl/curl.h>
<p class="level0">int socket_callback(CURL *easy, /* easy handle */
curl_socket_t s, /* socket */
int what, /* see above */
void *userp, /* private callback pointer */
void *socketp); /* private socket pointer */
<p class="level0">CURLMcode curl_multi_setopt(CURLM *handle, CURLMOPT_SOCKETFUNCTION, socket_callback);
</pre>
<a name="DESCRIPTION"></a><h2 class="nroffsh">DESCRIPTION</h2>
<p class="level0">Pass a pointer to your callback function, which should match the prototype shown above.
<p class="level0">When the <span Class="emphasis">curl_multi_socket_action(3)</span> function runs, it informs the application about updates in the socket (file descriptor) status by doing none, one, or multiple calls to the <span Class="bold">socket_callback</span>. The callback gets status updates with changes since the previous time the callback was called. If the given callback pointer is NULL, no callback will be called. Set the callback's <span Class="bold">userp</span> argument with <a Class="emphasis" href="./CURLMOPT_SOCKETDATA.html">CURLMOPT_SOCKETDATA</a>. See <span Class="emphasis">curl_multi_socket_action(3)</span> for more details on how the callback is used and should work. <a name="DEFAULT"></a><h2 class="nroffsh">DEFAULT</h2>
<p class="level0">NULL (no callback) <a name="PROTOCOLS"></a><h2 class="nroffsh">PROTOCOLS</h2>
<p class="level0">All <a name="EXAMPLE"></a><h2 class="nroffsh">EXAMPLE</h2>
<p class="level0">TODO <a name="AVAILABILITY"></a><h2 class="nroffsh">AVAILABILITY</h2>
<p class="level0">Added in 7.15.4 <a name="RETURN"></a><h2 class="nroffsh">RETURN VALUE</h2>
<p class="level0">Returns CURLM_OK. <a name="SEE"></a><h2 class="nroffsh">SEE ALSO</h2>
<p class="level0"><a Class="manpage" href="./CURLMOPT_SOCKETDATA.html">CURLMOPT_SOCKETDATA</a>, <span Class="manpage"> curl_multi_socket_action (3)</span> <span Class="manpage"> </span> <a Class="manpage" href="./CURLMOPT_TIMERFUNCTION.html">CURLMOPT_TIMERFUNCTION</a>,
<p class="level0"><p class="roffit">
This HTML page was made with <a href="http://daniel.haxx.se/projects/roffit/">roffit</a>.
</body></html>
| woimalabs/laserwire | thirdparty/curl-7.41.0/docs/libcurl/opts/CURLMOPT_SOCKETFUNCTION.html | HTML | lgpl-2.1 | 3,154 |
/*
Kopete Oscar Protocol
icquserinfoupdatetask.cpp - SNAC 0x15 update user info
Copyright (c) 2006 Roman Jarosz <[email protected]>
Kopete (c) 2006 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "icquserinfoupdatetask.h"
#include <kdebug.h>
#include "connection.h"
#include "transfer.h"
#include "buffer.h"
ICQUserInfoUpdateTask::ICQUserInfoUpdateTask( Task* parent ) : ICQTask( parent )
{
m_goSequence = 0;
}
ICQUserInfoUpdateTask::~ICQUserInfoUpdateTask()
{
qDeleteAll( m_infoList );
}
bool ICQUserInfoUpdateTask::forMe( const Transfer* transfer ) const
{
const SnacTransfer * st = dynamic_cast<const SnacTransfer*>( transfer );
if ( !st )
return false;
if ( st->snacService() != 0x0015 || st->snacSubtype() != 0x0003 || st->snacRequest() != m_goSequence )
return false;
Buffer buf( *( st->buffer() ) );
const_cast<ICQUserInfoUpdateTask*>( this )->parseInitialData( buf );
if ( requestType() == 0x07DA && requestSubType() == 0x0C3F )
return true;
return false;
}
bool ICQUserInfoUpdateTask::take( Transfer* transfer )
{
if ( forMe( transfer ) )
{
setTransfer( transfer );
TLV tlv1 = transfer->buffer()->getTLV();
Buffer buffer( tlv1.data, tlv1.length );
//FIXME this is silly. parseInitialData should take care of this for me.
buffer.skipBytes( 12 );
if ( buffer.getByte() == 0x0A )
{
kDebug(OSCAR_RAW_DEBUG) << "Own user info was saved.";
setSuccess( 0, QString() );
}
else
{
kDebug(OSCAR_RAW_DEBUG) << "Error saving own user info!!!";
setError( 0, QString() );
}
setTransfer( 0 );
return true;
}
return false;
}
void ICQUserInfoUpdateTask::onGo()
{
kDebug(OSCAR_RAW_DEBUG) << "Saving own user info.";
setSequence( client()->snacSequence() );
setRequestType( 0x07D0 );
setRequestSubType( 0x0C3A );
Buffer b;
for ( int i = 0; i < m_infoList.size(); ++i )
m_infoList.at(i)->store( &b );
if ( b.length() == 0 )
{
setSuccess( 0, QString() );
return;
}
m_goSequence = client()->snacSequence();
Buffer *sendBuf = addInitialData( &b );
FLAP f = { 0x02, 0, 0 };
SNAC s = { 0x0015, 0x0002, 0, m_goSequence };
Transfer* t = createTransfer( f, s, sendBuf );
send( t );
}
void ICQUserInfoUpdateTask::setInfo( const QList<ICQInfoBase*>& infoList )
{
m_infoList = infoList;
}
| Jtalk/kopete-fork-xep0136 | protocols/oscar/liboscar/tasks/icquserinfoupdatetask.cpp | C++ | lgpl-2.1 | 2,905 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#define _USE_MATH_DEFINES
#include <math.h>
#include <QDebug>
#include <QRect>
#include <QRectF>
#include <QLine>
#include <QLineF>
#include <QPoint>
#include <QPointF>
#include <QSize>
#include <QSizeF>
#include <QThread>
#include <string>
#include <set>
#include <QLibrary>
#include <QLibraryInfo>
#include <QFileInfo>
#include <QSharedPointer>
#include <QDir>
#include <QLinkedList>
#include <QStandardItemModel>
struct TestClass {
TestClass();
int m_i;
float m_f;
};
TestClass::TestClass() :
m_i(1),
m_f((float)M_E)
{
}
namespace Foo {
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindowClass),
m_w(-42), m_wc("Hallo"), m_wqs("quallo"),
m_thread1(0),m_thread2(0),m_fastThread(0)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
terminateThread();
}
void MainWindow::simpleBP(int inc, const QString &inx)
{
int array[2] = {1,2};
m_w++;
QString x = QLatin1String("h\344all\366");
QString *xp = &x;
qDebug() << inc << inx << *xp;
Q_UNUSED(array)
}
void MainWindow::on_actionDialog_triggered()
{
complexBP(0, "ahh");
}
void MainWindow::complexBP(int *inc, QString inx)
{
m_w++;
const char *cc = "hallo";
const char *np = 0;
char c = 'c';
unsigned char uc = 'u';
short s = 5;
unsigned short us = 56;
int i = 5;
int *ip = &i;
const int * const ipc = &i;
unsigned int ui = 56;
long l = 5;
unsigned long ul = 55;
qint64 i64 = 54354;
quint64 iu64 = 54354;
float r = (float)M_PI;
double d = M_PI;
QString x = "Hallo ";
x += QDateTime::currentDateTime().toString();
const QString &xr = x;
std::string stdString = "SHallo";
std::list<std::string> stdList;
stdList.push_back(stdString);
std::list<int> intList;
intList.push_back(1);
intList.push_back(2);
TestClass tc;
++i;
qDebug() << i;
++i;
qDebug() << i;
QFileInfo dir(QDir::tempPath());
QDebug nsp = qDebug().nospace();
for (int j = 0; j < 80; j++) {
nsp << 'x';
}
QStringList sl;
sl << "one" << "two" << "three";
QList<int> qintList;
qintList << 4 << 6;
qDebug() << inc << inx << dir.absoluteFilePath();
//statusBar()->showMessage(x);
Q_UNUSED(cc)
Q_UNUSED(np)
Q_UNUSED(c)
Q_UNUSED(uc)
Q_UNUSED(s)
Q_UNUSED(us)
Q_UNUSED(ip)
Q_UNUSED(ipc)
Q_UNUSED(ui)
Q_UNUSED(l)
Q_UNUSED(ul)
Q_UNUSED(i64)
Q_UNUSED(iu64)
Q_UNUSED(r)
Q_UNUSED(d)
Q_UNUSED(xr)
}
void MainWindow::on_actionCrash_triggered()
{
QString h = "Hallo";
// fsdfd
QString *s = 0;
qDebug() << *s;
}
void MainWindow::on_actionSimpleBP_triggered()
{
simpleBP(42, "Hallo");
}
void MainWindow::on_actionIncr_watch_triggered()
{
m_w++;
}
class MyThread : public QThread {
public:
MyThread(int base, QObject *parent) : QThread(parent), m_base(base) {}
void run();
private:
int m_base;
};
void MyThread::run()
{
QString x;
const int end = m_base + 20;
for (int i = m_base; i < end; i++) {
qDebug() << "L" << currentThreadId() << i << '/' << end;
QThread::msleep(100);
if (i < 10) {
x += QString::number(i);
qDebug() << "lt 10";
x += ',';
}
}
qDebug() << "Terminating" << currentThreadId();
}
class MyFastThread : public QThread {
public:
MyFastThread(QObject *parent) : QThread(parent) {}
void run() { qDebug() << "Done" << currentThreadId(); }
};
void MainWindow::terminateThread()
{
if (m_thread1 && m_thread1->isRunning())
m_thread1->terminate();
if (m_thread2 && m_thread2->isRunning())
m_thread2->terminate();
}
void MainWindow::on_actionThread_triggered()
{
if (!m_fastThread)
m_fastThread = new MyFastThread(this);
m_fastThread->start();
if (!m_thread1)
m_thread1 = new MyThread(0, this);
if (!m_thread1->isRunning())
m_thread1->start();
if (!m_thread2)
m_thread2 = new MyThread(20, this);
if (!m_thread2->isRunning())
m_thread2->start();
}
void MainWindow::on_actionException_triggered()
{
try {
throw (5) ;
} catch(int e) {
qDebug() << "caught "<< e;
}
}
void MainWindow::on_actionUncaughtException_triggered()
{
throw QString("eeh!") ;
}
void MainWindow::on_actionDumperBP_triggered()
{
m_w++;
std::string stdS;
std::list<int> sil;
QList<int> il;
std::list<std::string> stdStringList;
std::list<std::wstring> stdWStringList;
QStringList sl;
QString s = "hallo";
for (int c = 'a'; c < 'c'; c++) {
s += c + 23;
stdS += c;
sl.push_back(s);
stdStringList.push_back(std::string(1, c));
stdWStringList.push_back(std::wstring(1, c));
il.push_back(c);
sil.push_back(c);
qDebug() << s;
}
}
void MainWindow::on_actionExtTypes_triggered()
{
QVariant v1(QLatin1String("hallo"));
QVariant v2(QStringList(QLatin1String("hallo")));
QVector<QString> vec;
vec.push_back("Hallo");
vec.push_back("Hallo2");
std::set<std::string> stdSet;
stdSet.insert("s1");
QWidget *ww = this;
QWidget &wwr = *ww;
QSharedPointer<QString> sps(new QString("hallo"));
QList<QSharedPointer<QString> > spsl;
spsl.push_back(sps);
QMap<QString,QString> stringmap;
QMap<int,int> intmap;
std::map<std::string, std::string> stdstringmap;
stdstringmap[std::string("A")] = std::string("B");
int hidden = 45;
if (1 == 1 ) {
int hidden = 7;
qDebug() << hidden;
}
QLinkedList<QString> lls;
lls << "link1" << "link2";
QStandardItemModel *model =new QStandardItemModel;
model->appendRow(new QStandardItem("i1"));
QList <QList<int> > nestedIntList;
nestedIntList << QList<int>();
nestedIntList.front() << 1 << 2;
QVariantList vList;
vList.push_back(QVariant(42));
vList.push_back(QVariant("HALLO"));
stringmap.insert("A", "B");
intmap.insert(3,4);
QSet<QString> stringSet;
stringSet.insert("S1");
stringSet.insert("S2");
qDebug() << *(spsl.front()) << hidden;
Q_UNUSED(wwr)
}
void MainWindow::on_actionForeach_triggered()
{
QStringList sl;
sl << "1" << "2" << "3";
foreach(const QString &s, sl)
qDebug() << s;
sl.clear();
qDebug() << sl;
}
void MainWindow::on_actionAssert_triggered()
{
Q_ASSERT(0);
}
}
void Foo::MainWindow::on_actionScopes_triggered()
{
int x = 0;
if (x == 0) {
int x = 1;
Q_UNUSED(x)
} else {
int x = 2;
Q_UNUSED(x)
}
qDebug() << x;
}
void Foo::MainWindow::on_actionLongString_triggered()
{
QString incr = QString::fromLatin1("0123456789").repeated(4);
QString s = incr;
for (int i = 0; i < 5; i++) {
s += incr;
qDebug() <<s;
}
}
void Foo::MainWindow::on_actionStdTypes_triggered()
{
std::string stdString = "s";
std::wstring stdWString = L"ws";
std::map<std::string, std::string> stdStringStringMap;
stdStringStringMap.insert(std::map<std::string, std::string>::value_type(stdString, stdString));
std::map<std::wstring, std::wstring> stdStringWStringMap;
stdStringWStringMap.insert(std::map<std::wstring, std::wstring>::value_type(stdWString, stdWString));
std::set<std::string> stringSet;
std::list<std::string> stringList;
std::vector<std::string> stringVector(1, "bla");
std::vector<std::wstring> wStringVector(1, L"bla");
}
void Foo::MainWindow::on_actionVariousQtTypes_triggered()
{
const QByteArray ba = "hallo\t";
QSize size = QSize(42, 43);
QSizeF sizeF(size);
QPoint p1 = QPoint(42, 43);
QPoint p2 = QPoint(100, 100);
QLine line(p1, p2);
QPointF p1f(p1);
QPointF p2f(p2);
QLineF linef(p1f, p2f);
QRect rect(p1, p2);
QRectF rectf(rect);
qDebug() << sizeF << linef << rectf;
}
| duythanhphan/qt-creator | tests/manual/debugger/gui/mainwindow.cpp | C++ | lgpl-2.1 | 9,546 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2015 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#ifndef dealii_fe_p1nc_h
#define dealii_fe_p1nc_h
#include <deal.II/base/config.h>
#include <deal.II/fe/fe.h>
#include <deal.II/base/quadrature.h>
#include <deal.II/base/qprojector.h>
DEAL_II_NAMESPACE_OPEN
/*!@addtogroup fe */
/*@{*/
/**
* Implementation of the scalar version of the P1 nonconforming finite
* element, a piecewise linear element on quadrilaterals in 2D.
* This implementation is only for 2D cells in a 2D space (i.e., codimension 0).
*
* Unlike the usual continuous, $H^1$ conforming finite elements,
* the P1 nonconforming element does not enforce continuity across edges.
* However, it requires the continuity in an integral sense:
* any function in the space should have the same integral values
* on two sides of the common edge shared by two adjacent elements.
*
* Thus, each function in the nonconforming element space can be
* discontinuous, and consequently not included in $H^1_0$, just like
* the basis functions in Discontinuous Galerkin (DG) finite element
* spaces. On the other hand, basis functions in DG spaces are
* completely discontinuous across edges without any relation between
* the values from both sides. This is a reason why usual weak
* formulations for DG schemes contain additional penalty terms for
* jump across edges to control discontinuity. However, nonconforming
* elements usually do not need additional terms in their weak
* formulations because their integrals along edges are the same from
* both sides, i.e., there is <i>some level</i> of continuity.
*
* <h3>Dice Rule</h3>
* Since any function in the P1 nonconforming space is piecewise linear on each element,
* the function value at the midpoint of each edge is same as the mean value on the edge.
* Thus the continuity of the integral value across each edge is equivalent to
* the continuity of the midpoint value of each edge in this case.
*
* Thus for the P1 nonconforming element, the function values at midpoints on edges of a cell are important.
* The first attempt to define (local) degrees of freedom (DoFs) on a quadrilateral
* is by using midpoint values of a function.
*
* However, these 4 functionals are not linearly independent
* because a linear function on 2D is uniquely determined by only 3 independent values.
* A simple observation reads that any linear function on a quadrilateral should satisfy the 'dice rule':
* the sum of two function values at the midpoints of the edge pair on opposite
* sides of a cell is equal to the sum of those at the midpoints of the other edge pair.
* This is called the 'dice rule' because the number of points on opposite sides of a dice always
* adds up to the same number as well (in the case of dice, to seven).
*
* In formulas, the dice rule is written as $\phi(m_0) + \phi(m_1) = \phi(m_2) + \phi(m_3)$
* for all $\phi$ in the function space where $m_j$ is the midpoint of the edge $e_j$.
* Here, we assume the standard numbering convention for edges used in deal.II
* and described in class GeometryInfo.
*
* Conversely if 4 values at midpoints satisfying the dice rule are given,
* then there always exists the unique linear function which coincides with 4 midpoints values.
*
* Due to the dice rule, three values at any three midpoints can determine
* the last value at the last midpoint.
* It means that the number of independent local functionals on a cell is 3,
* and this is also the dimension of the linear polynomial space on a cell in 2D.
*
* <h3>Shape functions</h3>
* Before introducing the degrees of freedom, we present 4 local shape functions on a cell.
* Due to the dice rule, we need a special construction for shape functions.
* Although the following 4 shape functions are not linearly independent within a cell,
* they are helpful to define the global basis functions which are linearly independent on the whole domain.
* Again, we assume the standard numbering for vertices used in deal.II.
*
* @verbatim
* 2---------|---------3
* | |
* | |
* | |
* | |
* - -
* | |
* | |
* | |
* | |
* 0---------|---------1
* @endverbatim
*
* For each vertex $v_j$ of given cell, there are two edges of which $v_j$ is one of end points.
* Consider a linear function such that it has value 0.5 at the midpoints of two adjacent edges,
* and 0.0 at the two midpoints of the other edges.
* Note that the set of these values satisfies the dice rule which is described above.
* We denote such a function associated with vertex $v_j$ by $\phi_j$.
* Then the set of 4 shape functions is a partition of unity on a cell: $\sum_{j=0}^{3} \phi_j = 1$.
* (This is easy to see: at each edge midpoint, the sum of the four function adds up to one
* because two functions have value 0.5 and the other value 0.0. Because the function is globally
* linear, the only function that can have value 1 at four points must also be globally
* equal to one.)
*
* The following figures represent $\phi_j$ for $j=0,\cdots,3$ with their midpoint values:
*
* <ul>
* <li> shape function $\phi_0$:
* @verbatim
* +--------0.0--------+
* | |
* | |
* | |
* | |
* 0.5 0.0
* | |
* | |
* | |
* | |
* +--------0.5--------+
* @endverbatim
*
* <li> shape function $\phi_1$:
* @verbatim
* +--------0.0--------+
* | |
* | |
* | |
* | |
* 0.0 0.5
* | |
* | |
* | |
* | |
* +--------0.5--------+
* @endverbatim
*
* <li> shape function $\phi_2$:
* @verbatim
* +--------0.5--------+
* | |
* | |
* | |
* | |
* 0.5 0.0
* | |
* | |
* | |
* | |
* +--------0.0--------+
* @endverbatim
*
* <li> shape function $\phi_3$:
* @verbatim
* +--------0.5--------+
* | |
* | |
* | |
* | |
* 0.0 0.5
* | |
* | |
* | |
* | |
* +--------0.0--------+
* @endverbatim
*
* </ul>
*
* The local DoFs are defined by the coefficients of the shape functions associated with vertices, respectively.
* Although these 4 local DoFs are not linearly independent within a single cell,
* this definition is a good start point for the definition of the global DoFs.
*
* We want to emphasize that the shape functions are constructed on each cell, not on the reference cell only.
* Usual finite elements are defined based on a 'parametric' concept.
* It means that a function space for a finite element is defined on one reference cell, and it is transformed
* into each cell via a mapping from the reference cell.
* However the P1 nonconforming element does not follow such concept. It defines a function space with
* linear shape functions on each cell without any help of a function space on the reference cell.
* In other words, the element is defined in real space, not via a mapping from a reference cell.
* In this, it is similar to the FE_DGPNonparametric element.
*
* Thus this implementation does not have to compute shape values on the reference cell.
* Rather, the shape values are computed by construction of the shape functions
* on each cell independently.
*
* <h3>Degrees of freedom</h3>
* We next have to consider the <i>global</i> basis functions for the element
* because the system of equations which we ultimately have to solve is for a global system, not local.
* The global basis functions associated with a node are defined by a cell-wise composition of
* local shape functions associated with the node on each element.
*
* There is a theoretical result about the linear independency of the global basis functions
* depending on the type of the boundary condition we consider.
*
* When homogeneous Dirichlet boundary conditions are given,
* the global basis functions associated with interior nodes are linearly independent.
* Then, the number of DoFs is equal to the number of interior nodes,
* and consequently the same as the number of DoFs for the standard bilinear $Q_1$ finite element.
*
* When Neumann boundary conditions are given,
* the global basis functions associated with all nodes (including boundary nodes)
* are actually not linearly independent. There exists one redundancy.
* Thus in this case, the number of DoFs is equal to the number of all nodes minus 1. This is, again
* as for the regular $Q_1$ element.
*
* <h3>Unit support points</h3>
* For a smooth function, we construct a piecewise linear function which belongs to the element space by
* using its nodal values as DoF values.
*
* Note that for the P1 nonconforming element two nodal values of a smooth function and its interpolant do not
* coincide in general, in contrast with ordinary Lagrange finite elements.
* Of course, it is meaningless to refer 'nodal value' because the element space has nonconformity.
* But it is also true even though the single global basis function associated with a node is considered
* the unique 'nodal value' at the node.
* For instance, consider the basis function associated with a node.
* Consider two lines representing the level sets for value 0.5 and 0, respectively, by connecting two midpoints.
* Then we cut the quad into two sub-triangles by the diagonal which is placed along those two lines.
* It gives another level set for value 0.25 which coincides with the cutting diagonal.
* Therefore these three level sets are all parallel in the quad and it gives the value 0.75 at the base node, not value 1.
* This is true whether the quadrilateral is a rectangle, parallelogram, or any other shape.
*
* <h3>References</h3>
* The original paper for the P1 nonconforming element is
* accessible at http://epubs.siam.org/doi/abs/10.1137/S0036142902404923
* and has the following complete reference:
* @code(.bib)
* @article{park2003p,
* title = {P 1-nonconforming quadrilateral finite element methods for second-order elliptic problems},
* author = {Park, Chunjae and Sheen, Dongwoo},
* journal = {SIAM Journal on Numerical Analysis},
* volume = {41},
* number = {2},
* pages = {624--640},
* year = {2003},
* publisher = {SIAM}
* }
* @endcode
*
* @author Jaeryun Yim, 2015, 2016.
*/
class FE_P1NC : public FiniteElement<2,2>
{
public:
/**
* Constructor for the P1 nonconforming element.
* It is only for 2D and codimension = 0.
*/
FE_P1NC();
virtual std::string get_name () const;
virtual UpdateFlags requires_update_flags (const UpdateFlags flags) const;
virtual
std::unique_ptr<FiniteElement<2,2>>
clone() const;
/**
* Destructor.
*/
virtual ~FE_P1NC () = default;
private:
/**
* Return the vector consists of the numbers of degrees of freedom per objects.
*/
static std::vector<unsigned int> get_dpo_vector ();
/**
* Return the coefficients of 4 local linear shape functions $\phi_j(x,y) = a x + b y + c$ on given cell.
* For each local shape function, the array consists of three coefficients is in order of a,b and c.
*/
static std::array<std::array<double,3>,4>
get_linear_shape_coefficients (const Triangulation<2,2>::cell_iterator &cell);
/**
* Do the work which is needed before cellwise data computation.
* Since the shape functions are constructed independently on each cell,
* the data on the reference cell is not necessary.
* It returns an empty variable type of @ InternalDataBase and updates @ update_flags,
* and computes trivially zero Hessian for each cell if it is needed.
*/
virtual FiniteElement<2,2>::InternalDataBase *
get_data (const UpdateFlags update_flags,
const Mapping<2,2> &,
const Quadrature<2> &quadrature,
dealii::internal::FEValues::FiniteElementRelatedData<2,2> &output_data) const;
virtual FiniteElement<2,2>::InternalDataBase *
get_face_data (const UpdateFlags update_flags,
const Mapping<2,2> &,
const Quadrature<1> &quadrature,
dealii::internal::FEValues::FiniteElementRelatedData<2,2> &output_data) const;
virtual FiniteElement<2,2>::InternalDataBase *
get_subface_data (const UpdateFlags update_flags,
const Mapping<2,2> &,
const Quadrature<1> &quadrature,
dealii::internal::FEValues::FiniteElementRelatedData<2,2> &output_data) const;
/**
* Compute the data on the current cell.
*/
virtual void
fill_fe_values (const Triangulation<2,2>::cell_iterator &cell,
const CellSimilarity::Similarity cell_similarity,
const Quadrature<2> &quadrature,
const Mapping<2,2> &mapping,
const Mapping<2,2>::InternalDataBase &mapping_internal,
const internal::FEValues::MappingRelatedData<2,2> &mapping_data,
const FiniteElement<2,2>::InternalDataBase &fe_internal,
internal::FEValues::FiniteElementRelatedData<2,2> &output_data) const;
/**
* Compute the data on the face of the current cell.
*/
virtual void
fill_fe_face_values (const Triangulation<2,2>::cell_iterator &cell,
const unsigned int face_no,
const Quadrature<1> &quadrature,
const Mapping<2,2> &mapping,
const Mapping<2,2>::InternalDataBase &mapping_internal,
const dealii::internal::FEValues::MappingRelatedData<2,2> &mapping_data,
const InternalDataBase &fe_internal,
dealii::internal::FEValues::FiniteElementRelatedData<2,2> &output_data) const;
/**
* Compute the data on the subface of the current cell.
*/
virtual void
fill_fe_subface_values (const Triangulation<2,2>::cell_iterator &cell,
const unsigned int face_no,
const unsigned int sub_no,
const Quadrature<1> &quadrature,
const Mapping<2,2> &mapping,
const Mapping<2,2>::InternalDataBase &mapping_internal,
const dealii::internal::FEValues::MappingRelatedData<2,2> &mapping_data,
const InternalDataBase &fe_internal,
dealii::internal::FEValues::FiniteElementRelatedData<2,2> &output_data) const;
/**
* Create the constraints matrix for hanging edges.
*/
void initialize_constraints ();
};
/*@}*/
DEAL_II_NAMESPACE_CLOSE
#endif
| danshapero/dealii | include/deal.II/fe/fe_p1nc.h | C | lgpl-2.1 | 16,352 |
/**
* This is a simple mechanism to bind Inkscape to Java, and thence
* to all of the nice things that can be layered upon that.
*
* Authors:
* Bob Jamison
*
* Copyright (c) 2007-2008 Inkscape.org
*
* 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; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Note that the SMIL files are implementations of the Java
* interface package found here:
* http://www.w3.org/TR/smil-boston-dom/java-binding.html
*/
package org.inkscape.dom.smil;
import org.w3c.dom.DOMException;
public class ElementParallelTimeContainerImpl
extends ElementTimeContainerImpl
implements org.w3c.dom.smil.ElementParallelTimeContainer
{
public native String getEndSync();
public native void setEndSync(String endSync)
throws DOMException;
public native float getImplicitDuration();
}
| step21/inkscape-osx-packaging-native | src/bind/java/org/inkscape/dom/smil/ElementParallelTimeContainerImpl.java | Java | lgpl-2.1 | 1,528 |
<?php
/*
* Limb PHP Framework
*
* @link http://limb-project.com
* @copyright Copyright © 2004-2009 BIT(http://bit-creative.com)
* @license LGPL http://www.gnu.org/copyleft/lesser.html
*/
/**
* class lmbMacroTagInfo.
*
* @package macro
* @version $Id$
*/
class lmbMacroTagInfo
{
protected $tag;
protected $class;
protected $file;
protected $aliases = array();
protected $req_attributes = array();
protected $parent_class;
protected $restrict_self_nesting = false;
protected $require_endtag = true;
function __construct($tag, $class, $require_endtag = true)
{
$this->tag = $tag;
$this->class = $class;
$this->require_endtag = $require_endtag;
}
static function createByAnnotations($file, $class, $annotations)
{
if(!isset($annotations['tag']))
throw new lmbMacroException("@tag annotation is missing for class '$class'");
$tag = $annotations['tag'];
$info = new lmbMacroTagInfo($tag, $class);
$info->setFile($file);
if(isset($annotations['forbid_end_tag']))
$info->setForbidEndtag(true);
if(isset($annotations['restrict_self_nesting']))
$info->setRestrictSelfNesting(true);
if(isset($annotations['parent_tag_class']))
$info->setParentClass(trim($annotations['parent_tag_class']));
if(isset($annotations['req_attributes']))
{
$req_attributes = explode(',' , $annotations['req_attributes']);
$req_attributes = array_map('trim', $req_attributes);
$info->setRequiredAttributes($req_attributes);
}
if(isset($annotations['aliases']))
{
$filter_aliases = explode(',' , $annotations['aliases']);
$filter_aliases = array_map('trim', $filter_aliases);
$info->setAliases($filter_aliases);
}
return $info;
}
function getTag()
{
return $this->tag;
}
function getClass()
{
return $this->class;
}
function setFile($file)
{
$this->file = $file;
}
function getFile()
{
return $this->file;
}
function setForbidEndtag($flag = true)
{
$this->require_endtag = !$flag;
}
function isEndtagForbidden()
{
return !$this->require_endtag;
}
function setRequiredAttributes($attributes)
{
$this->req_attributes = $attributes;
}
function getRequiredAttributes()
{
return $this->req_attributes;
}
function setParentClass($parent_tag_class)
{
$this->parent_class = $parent_tag_class;
}
function getParentClass()
{
return $this->parent_class;
}
function setAliases($aliases)
{
$this->aliases = $aliases;
}
function getAliases()
{
return $this->aliases;
}
function setRestrictSelfNesting($flag = true)
{
$this->restrict_self_nesting = $flag;
}
function isRestrictSelfNesting()
{
return $this->restrict_self_nesting;
}
function setForbidParsing($flag = true)
{
$this->forbid_parsing = $flag;
}
function isParsingForbidden()
{
return $this->forbid_parsing;
}
function load()
{
if(!class_exists($this->class) && isset($this->file))
require_once($this->file);
}
}
| limb-php-framework/limb | macro/src/compiler/lmbMacroTagInfo.class.php | PHP | lgpl-2.1 | 3,116 |
/*
* Hibernate OGM, Domain model persistence for NoSQL datastores
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.ogm.datastore.infinispanremote.utils;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunListener.ThreadSafe;
/**
* This JUnit listener is registered in the Maven build as a global listener,
* making sure that the Hot Rod server is running and ready to serve
* requests when running the testsuite.
* As an alternative RemoteHotRodServerRule can be used as a JUnit Rule.
*
* @author Sanne Grinovero
*/
@ThreadSafe
public class HotrodServerLifecycle extends RunListener {
private volatile RemoteHotRodServerRule server;
@Override
public void testRunStarted(Description description) throws Exception {
printEvent( "Test suite start detected" );
if ( server == null ) {
startHotRodServer();
}
}
@Override
public void testRunFinished(Result result) throws Exception {
if ( server != null ) {
printEvent( "Test suite end detected" );
shutdownServer();
}
}
@Override
public void testFinished(Description description) throws Exception {
if ( server != null ) {
// I'd like to do this, but in some cases currently OGM's tests
// are bit always fully independent in the same class.
// Not least, this would wipe out the schema.
// resetServer();
}
}
private synchronized void startHotRodServer() {
if ( server == null ) {
server = new RemoteHotRodServerRule();
try {
printEvent( "Starting HotRod Server" );
server.before();
}
catch (Throwable e) {
throw new RuntimeException( e );
}
}
}
private synchronized void shutdownServer() {
final RemoteHotRodServerRule serverLocal = server;
if ( serverLocal != null ) {
printEvent( "Terminating HotRod Server" );
serverLocal.after();
}
}
private void printEvent(String message) {
System.out.println( getClass().getCanonicalName() + ": " + message );
}
}
| DavideD/hibernate-ogm | infinispan-remote/src/test/java/org/hibernate/ogm/datastore/infinispanremote/utils/HotrodServerLifecycle.java | Java | lgpl-2.1 | 2,173 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Torque(Package):
"""TORQUE (Terascale Open-source Resource and QUEue Manager) is an open
source project based on the original PBS resource manager developed by NASA,
LLNL, and MRJ."""
homepage = "https://github.com/abarbu/torque"
has_code = False
maintainers = ['sethrj']
version('3.0.4')
version('3.0.2')
provides('pbs')
# TORQUE needs to be added as an external package to SPACK. For this, the
# config file packages.yaml needs to be adjusted:
#
# packages:
# torque:
# buildable: False
# externals:
# - spec: [email protected]
# prefix: /opt/torque (path to your TORQUE installation)
def install(self, spec, prefix):
raise InstallError(
self.spec.format('{name} is not installable, you need to specify '
'it as an external package in packages.yaml'))
| LLNL/spack | var/spack/repos/builtin/packages/torque/package.py | Python | lgpl-2.1 | 1,126 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* --------------------
* PowerFunction2D.java
* --------------------
* (C) Copyright 2002-2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 01-Oct-2002 : Version 1 (DG);
* 28-May-2009 : Added accessor methods for co-efficients, implemented
* equals() and hashCode(), and added Serialization support (DG);
*
*/
package org.jfree.data.function;
import java.io.Serializable;
import org.jfree.chart.HashUtilities;
/**
* A function of the form y = a * x ^ b.
*/
public class PowerFunction2D implements Function2D, Serializable {
/** The 'a' coefficient. */
private double a;
/** The 'b' coefficient. */
private double b;
/**
* Creates a new power function.
*
* @param a the 'a' coefficient.
* @param b the 'b' coefficient.
*/
public PowerFunction2D(double a, double b) {
this.a = a;
this.b = b;
}
/**
* Returns the 'a' coefficient that was specified in the constructor.
*
* @return The 'a' coefficient.
*
* @since 1.0.14
*/
public double getA() {
return this.a;
}
/**
* Returns the 'b' coefficient that was specified in the constructor.
*
* @return The 'b' coefficient.
*
* @since 1.0.14
*/
public double getB() {
return this.b;
}
/**
* Returns the value of the function for a given input ('x').
*
* @param x the x-value.
*
* @return The value.
*/
public double getValue(double x) {
return this.a * Math.pow(x, this.b);
}
/**
* Tests this function for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (!(obj instanceof PowerFunction2D)) {
return false;
}
PowerFunction2D that = (PowerFunction2D) obj;
if (this.a != that.a) {
return false;
}
if (this.b != that.b) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
public int hashCode() {
int result = 29;
result = HashUtilities.hashCode(result, this.a);
result = HashUtilities.hashCode(result, this.b);
return result;
}
}
| fluidware/Eastwood-Charts | source/org/jfree/data/function/PowerFunction2D.java | Java | lgpl-2.1 | 3,862 |
/*
Crystal Space 3D engine
Copyright (C) 2000-2007 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __CS_IGEOM_TRIMESH_H__
#define __CS_IGEOM_TRIMESH_H__
#include "csutil/scf_interface.h"
class csFlags;
/**\file
* Triangle mesh interface
*/
/**
* \addtogroup geom_utils
* @{ */
/** \name Flags for iTriangleMesh
* @{ */
enum
{
/**
* The object is closed, if set.
* With closed we mean that if you run a beam of light through the object
* (through any point outside the mesh to another point outside) it will
* always hit an even amount of faces (one going in, and one going out).
* If you don't set CLOSED or NOTCLOSED then the state is not known and
* the engine may test it if it wants.
*/
CS_TRIMESH_CLOSED = 1,
/**
* The object is not closed, if set.
* This is the opposite of #CS_TRIMESH_CLOSED. Use this flag if you are
* absolutely certain that the object is not closed. The engine will not
* attempt to test if the object is really closed or not. If you don't
* set CLOSED or NOTCLOSED then the state is not known and the engine
* may test it if it wants.
*/
CS_TRIMESH_NOTCLOSED = 2,
/**
* The object is convex, if set.
* With convex we mean that if you run a beam of light through the object
* (through any point outside the mesh to another point outside) it will
* always hit exactly two faces (one going in, and one going out). If you
* don't * set CONVEX or NOTCONVEX then the state is not known and the
* engine may test it if it wants.
*/
CS_TRIMESH_CONVEX = 4,
/**
* The object is not convex, if set.
* This is the opposite of #CS_TRIMESH_CONVEX. Use this flag if you are
* absolutely certain that the object is not convex. The engine will not
* attempt to test if the object is really convex or not. If you don't
* set CONVEX or NOTCONVEX then the state is not known and the engine
* may test it if it wants.
*/
CS_TRIMESH_NOTCONVEX = 8,
/**
* Set this flag if the triangle mesh is deformable.
*/
CS_TRIMESH_DEFORMABLE = 16
};
/** @} */
class csVector3;
struct csTriangle;
/**
* This interface reprents a mesh of triangles. It is useful to communicate
* geometry information outside of the engine. One place where this will
* be useful is for communicating geometry information to the collision
* detection plugin.<br>
* All Crystal Space mesh objects (things, sprites, ...)
* should implement and/or embed an implementation of this interface.
*
* A triangle mesh has the concept of a vertex buffer and an array of
* triangles.
*
* Main creators of instances implementing this interface:
* - Almost all mesh objects have several implementations of this
* interface.
*
* Main ways to get pointers to this interface:
* - iObjectModel::GetTriangleData()
*
* Main users of this interface:
* - Collision detection plugins (iCollideSystem)
* - Visibility culler plugins (iVisibilityCuller)
* - Shadow stencil plugin
*/
struct iTriangleMesh : public virtual iBase
{
SCF_INTERFACE(iTriangleMesh, 1, 0, 0);
/// Get the number of vertices for this mesh.
virtual size_t GetVertexCount () = 0;
/// Get the pointer to the array of vertices.
virtual csVector3* GetVertices () = 0;
/// Get the number of triangles for this mesh.
virtual size_t GetTriangleCount () = 0;
/// Get the triangle table for this mesh.
virtual csTriangle* GetTriangles () = 0;
/**
* Lock the triangle mesh. This prevents the triangle
* data from being cleaned up.
*/
virtual void Lock () = 0;
/**
* Unlock the triangle mesh. This allows clean up again.
*/
virtual void Unlock () = 0;
/**
* Get flags for this triangle mesh. This is zero or a combination of the
* following flags:
* - #CS_TRIMESH_CLOSED: mesh is closed.
* - #CS_TRIMESH_NOTCLOSED: mesh is not closed.
* - #CS_TRIMESH_CONVEX: mesh is convex.
* - #CS_TRIMESH_NOTCONVEX: mesh is not convex.
* - #CS_TRIMESH_DEFORMABLE: mesh is deformable.
*
* Note that if neither #CS_TRIMESH_CLOSED nor #CS_TRIMESH_NOTCLOSED
* are set then the closed state is not known. Setting both is illegal.
* Note that if neither #CS_TRIMESH_CONVEX nor #CS_TRIMESH_NOTCONVEX
* are set then the convex state is not known. Setting both is illegal.
*/
virtual csFlags& GetFlags () = 0;
/**
* When this number changes you know the triangle mesh has changed
* (deformation has occured) since the last time you got another
* number from this function.
*/
virtual uint32 GetChangeNumber () const = 0;
};
/** @} */
#endif // __CS_IGEOM_TRIMESH_H__
| garinh/cs | include/igeom/trimesh.h | C | lgpl-2.1 | 5,304 |
/****************************************************************************
**
** Copyright (C) 2013 David Faure <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qlockfile.h"
#include "qlockfile_p.h"
#include <QtCore/qthread.h>
#include <QtCore/qelapsedtimer.h>
#include <QtCore/qdatetime.h>
QT_BEGIN_NAMESPACE
class QLockFileThread : public QThread
{
public:
static void msleep(unsigned long msecs) { QThread::msleep(msecs); }
};
/*!
\class QLockFile
\inmodule QtCore
\brief The QLockFile class provides locking between processes using a file.
\since 5.1
A lock file can be used to prevent multiple processes from accessing concurrently
the same resource. For instance, a configuration file on disk, or a socket, a port,
a region of shared memory...
Serialization is only guaranteed if all processes that access the shared resource
use QLockFile, with the same file path.
QLockFile supports two use cases:
to protect a resource for a short-term operation (e.g. verifying if a configuration
file has changed before saving new settings), and for long-lived protection of a
resource (e.g. a document opened by a user in an editor) for an indefinite amount of time.
When protecting for a short-term operation, it is acceptable to call lock() and wait
until any running operation finishes.
When protecting a resource over a long time, however, the application should always
call setStaleLockTime(0) and then tryLock() with a short timeout, in order to
warn the user that the resource is locked.
If the process holding the lock crashes, the lock file stays on disk and can prevent
any other process from accessing the shared resource, ever. For this reason, QLockFile
tries to detect such a "stale" lock file, based on the process ID written into the file,
and (in case that process ID got reused meanwhile), on the last modification time of
the lock file (30s by default, for the use case of a short-lived operation).
If the lock file is found to be stale, it will be deleted.
For the use case of protecting a resource over a long time, you should therefore call
setStaleLockTime(0), and when tryLock() returns LockFailedError, inform the user
that the document is locked, possibly using getLockInfo() for more details.
*/
/*!
\enum QLockFile::LockError
This enum describes the result of the last call to lock() or tryLock().
\value NoError The lock was acquired successfully.
\value LockFailedError The lock could not be acquired because another process holds it.
\value PermissionError The lock file could not be created, for lack of permissions
in the parent directory.
\value UnknownError Another error happened, for instance a full partition
prevented writing out the lock file.
*/
/*!
Constructs a new lock file object.
The object is created in an unlocked state.
When calling lock() or tryLock(), a lock file named \a fileName will be created,
if it doesn't already exist.
\sa lock(), unlock()
*/
QLockFile::QLockFile(const QString &fileName)
: d_ptr(new QLockFilePrivate(fileName))
{
}
/*!
Destroys the lock file object.
If the lock was acquired, this will release the lock, by deleting the lock file.
*/
QLockFile::~QLockFile()
{
unlock();
}
/*!
Sets \a staleLockTime to be the time in milliseconds after which
a lock file is considered stale.
The default value is 30000, i.e. 30 seconds.
If your application typically keeps the file locked for more than 30 seconds
(for instance while saving megabytes of data for 2 minutes), you should set
a bigger value using setStaleLockTime().
The value of \a staleLockTime is used by lock() and tryLock() in order
to determine when an existing lock file is considered stale, i.e. left over
by a crashed process. This is useful for the case where the PID got reused
meanwhile, so the only way to detect a stale lock file is by the fact that
it has been around for a long time.
\sa staleLockTime()
*/
void QLockFile::setStaleLockTime(int staleLockTime)
{
Q_D(QLockFile);
d->staleLockTime = staleLockTime;
}
/*!
Returns the time in milliseconds after which
a lock file is considered stale.
\sa setStaleLockTime()
*/
int QLockFile::staleLockTime() const
{
Q_D(const QLockFile);
return d->staleLockTime;
}
/*!
Returns \c true if the lock was acquired by this QLockFile instance,
otherwise returns \c false.
\sa lock(), unlock(), tryLock()
*/
bool QLockFile::isLocked() const
{
Q_D(const QLockFile);
return d->isLocked;
}
/*!
Creates the lock file.
If another process (or another thread) has created the lock file already,
this function will block until that process (or thread) releases it.
Calling this function multiple times on the same lock from the same
thread without unlocking first is not allowed. This function will
\e dead-lock when the file is locked recursively.
Returns \c true if the lock was acquired, false if it could not be acquired
due to an unrecoverable error, such as no permissions in the parent directory.
\sa unlock(), tryLock()
*/
bool QLockFile::lock()
{
return tryLock(-1);
}
/*!
Attempts to create the lock file. This function returns \c true if the
lock was obtained; otherwise it returns \c false. If another process (or
another thread) has created the lock file already, this function will
wait for at most \a timeout milliseconds for the lock file to become
available.
Note: Passing a negative number as the \a timeout is equivalent to
calling lock(), i.e. this function will wait forever until the lock
file can be locked if \a timeout is negative.
If the lock was obtained, it must be released with unlock()
before another process (or thread) can successfully lock it.
Calling this function multiple times on the same lock from the same
thread without unlocking first is not allowed, this function will
\e always return false when attempting to lock the file recursively.
\sa lock(), unlock()
*/
bool QLockFile::tryLock(int timeout)
{
Q_D(QLockFile);
QElapsedTimer timer;
if (timeout > 0)
timer.start();
int sleepTime = 100;
forever {
d->lockError = d->tryLock_sys();
switch (d->lockError) {
case NoError:
d->isLocked = true;
return true;
case PermissionError:
case UnknownError:
return false;
case LockFailedError:
if (!d->isLocked && d->isApparentlyStale()) {
// Stale lock from another thread/process
// Ensure two processes don't remove it at the same time
QLockFile rmlock(d->fileName + QLatin1String(".rmlock"));
if (rmlock.tryLock()) {
if (d->isApparentlyStale() && d->removeStaleLock())
continue;
}
}
break;
}
if (timeout == 0 || (timeout > 0 && timer.hasExpired(timeout)))
return false;
QLockFileThread::msleep(sleepTime);
if (sleepTime < 5 * 1000)
sleepTime *= 2;
}
// not reached
return false;
}
/*!
\fn void QLockFile::unlock()
Releases the lock, by deleting the lock file.
Calling unlock() without locking the file first, does nothing.
\sa lock(), tryLock()
*/
/*!
Retrieves information about the current owner of the lock file.
If tryLock() returns \c false, and error() returns LockFailedError,
this function can be called to find out more information about the existing
lock file:
\list
\li the PID of the application (returned in \a pid)
\li the \a hostname it's running on (useful in case of networked filesystems),
\li the name of the application which created it (returned in \a appname),
\endlist
Note that tryLock() automatically deleted the file if there is no
running application with this PID, so LockFailedError can only happen if there is
an application with this PID (it could be unrelated though).
This can be used to inform users about the existing lock file and give them
the choice to delete it. After removing the file using removeStaleLockFile(),
the application can call tryLock() again.
This function returns \c true if the information could be successfully retrieved, false
if the lock file doesn't exist or doesn't contain the expected data.
This can happen if the lock file was deleted between the time where tryLock() failed
and the call to this function. Simply call tryLock() again if this happens.
*/
bool QLockFile::getLockInfo(qint64 *pid, QString *hostname, QString *appname) const
{
Q_D(const QLockFile);
return d->getLockInfo(pid, hostname, appname);
}
bool QLockFilePrivate::getLockInfo(qint64 *pid, QString *hostname, QString *appname) const
{
QFile reader(fileName);
if (!reader.open(QIODevice::ReadOnly))
return false;
QByteArray pidLine = reader.readLine();
pidLine.chop(1);
QByteArray appNameLine = reader.readLine();
appNameLine.chop(1);
QByteArray hostNameLine = reader.readLine();
hostNameLine.chop(1);
if (pidLine.isEmpty() || appNameLine.isEmpty())
return false;
qint64 thePid = pidLine.toLongLong();
if (pid)
*pid = thePid;
if (appname)
*appname = QString::fromUtf8(appNameLine);
if (hostname)
*hostname = QString::fromUtf8(hostNameLine);
return thePid > 0;
}
/*!
Attempts to forcefully remove an existing lock file.
Calling this is not recommended when protecting a short-lived operation: QLockFile
already takes care of removing lock files after they are older than staleLockTime().
This method should only be called when protecting a resource for a long time, i.e.
with staleLockTime(0), and after tryLock() returned LockFailedError, and the user
agreed on removing the lock file.
Returns \c true on success, false if the lock file couldn't be removed. This happens
on Windows, when the application owning the lock is still running.
*/
bool QLockFile::removeStaleLockFile()
{
Q_D(QLockFile);
if (d->isLocked) {
qWarning("removeStaleLockFile can only be called when not holding the lock");
return false;
}
return d->removeStaleLock();
}
/*!
Returns the lock file error status.
If tryLock() returns \c false, this function can be called to find out
the reason why the locking failed.
*/
QLockFile::LockError QLockFile::error() const
{
Q_D(const QLockFile);
return d->lockError;
}
QT_END_NAMESPACE
| kobolabs/qtserialport | src/serialport/qt4support/src/qlockfile.cpp | C++ | lgpl-2.1 | 12,637 |
var searchData=
[
['handlerdelegate',['HandlerDelegate',['../classCqrs_1_1Configuration_1_1HandlerDelegate.html',1,'Cqrs::Configuration']]],
['helloworld',['HelloWorld',['../classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Aggregates_1_1HelloWorld.html',1,'Cqrs::Akka::Tests::Unit::Aggregates']]],
['helloworldrepliedto',['HelloWorldRepliedTo',['../classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1HelloWorldRepliedTo.html',1,'Cqrs::Akka::Tests::Unit::Events']]],
['helloworldrepliedtoeventhandler',['HelloWorldRepliedToEventHandler',['../classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandler.html',1,'Cqrs::Akka::Tests::Unit::Events::Handlers']]],
['helloworldrepliedtoeventhandleractor',['HelloWorldRepliedToEventHandlerActor',['../classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor.html',1,'Cqrs::Akka::Tests::Unit::Events::Handlers']]],
['helloworldrepliedtosendendconversationcommandeventhandler',['HelloWorldRepliedToSendEndConversationCommandEventHandler',['../classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToSendEndConversationCommandEventHandler.html',1,'Cqrs::Akka::Tests::Unit::Events::Handlers']]],
['helloworldsaid',['HelloWorldSaid',['../classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1HelloWorldSaid.html',1,'Cqrs::Akka::Tests::Unit::Events']]],
['helloworldsaideventhandler',['HelloWorldSaidEventHandler',['../classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldSaidEventHandler.html',1,'Cqrs::Akka::Tests::Unit::Events::Handlers']]],
['helppageconfig',['HelpPageConfig',['../classCqrs_1_1WebApi_1_1HelpPageConfig.html',1,'Cqrs::WebApi']]],
['httpcontenttoformdataconverter',['HttpContentToFormDataConverter',['../classCqrs_1_1WebApi_1_1Formatters_1_1FormMultipart_1_1Converters_1_1HttpContentToFormDataConverter.html',1,'Cqrs::WebApi::Formatters::FormMultipart::Converters']]],
['httpfile',['HttpFile',['../classCqrs_1_1WebApi_1_1Formatters_1_1FormMultipart_1_1Infrastructure_1_1HttpFile.html',1,'Cqrs::WebApi::Formatters::FormMultipart::Infrastructure']]]
];
| Chinchilla-Software-Com/CQRS | wiki/docs/2.1/html/search/classes_7.js | JavaScript | lgpl-2.1 | 2,120 |
/***************************************************************************
$RCSfile$
-------------------
cvs : $Id$
begin : Tue Oct 02 2002
copyright : (C) 2002 by Martin Preuss
email : [email protected]
***************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
* MA 02111-1307 USA *
* *
***************************************************************************/
#ifndef GWEN_SOCKET_L_H
#define GWEN_SOCKET_L_H
#include <gwenhywfar/inetsocket.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Initializes this module.
*/
int GWEN_Socket_ModuleInit(void);
/**
* Deinitializes this module.
*/
int GWEN_Socket_ModuleFini(void);
#ifdef __cplusplus
}
#endif
#endif /* #ifndef GWEN_SOCKET_H */
| Zauberstuhl/gwenhywfar | src/os/inetsocket_l.h | C | lgpl-2.1 | 2,004 |
/*
* (C) 2001 Clemson University and The University of Chicago
*
* See COPYING in top-level directory.
*/
#define __PINT_PROTO_ENCODE_OPAQUE_HANDLE
#include "pvfs2-kernel.h"
#include "pvfs2-types.h"
#include "pint-dev-shared.h"
#include "pvfs2-dev-proto.h"
#include "pvfs2-bufmap.h"
#include "pvfs2-internal.h"
int pvfs2_gen_credentials(
PVFS_credentials *credentials)
{
int ret = -1;
if (credentials)
{
memset(credentials, 0, sizeof(PVFS_credentials));
#ifdef HAVE_CURRENT_FSUID
credentials->uid = current_fsuid();
credentials->gid = current_fsgid();
#else
credentials->uid = current->fsuid;
credentials->gid = current->fsgid;
#endif
ret = 0;
}
return ret;
}
PVFS_fs_id fsid_of_op(pvfs2_kernel_op_t *op)
{
PVFS_fs_id fsid = PVFS_FS_ID_NULL;
if (op)
{
switch (op->upcall.type)
{
case PVFS2_VFS_OP_FILE_IO:
fsid = op->upcall.req.io.refn.fs_id;
break;
case PVFS2_VFS_OP_LOOKUP:
fsid = op->upcall.req.lookup.parent_refn.fs_id;
break;
case PVFS2_VFS_OP_CREATE:
fsid = op->upcall.req.create.parent_refn.fs_id;
break;
case PVFS2_VFS_OP_GETATTR:
fsid = op->upcall.req.getattr.refn.fs_id;
break;
case PVFS2_VFS_OP_REMOVE:
fsid = op->upcall.req.remove.parent_refn.fs_id;
break;
case PVFS2_VFS_OP_MKDIR:
fsid = op->upcall.req.mkdir.parent_refn.fs_id;
break;
case PVFS2_VFS_OP_READDIR:
fsid = op->upcall.req.readdir.refn.fs_id;
break;
case PVFS2_VFS_OP_SETATTR:
fsid = op->upcall.req.setattr.refn.fs_id;
break;
case PVFS2_VFS_OP_SYMLINK:
fsid = op->upcall.req.sym.parent_refn.fs_id;
break;
case PVFS2_VFS_OP_RENAME:
fsid = op->upcall.req.rename.old_parent_refn.fs_id;
break;
case PVFS2_VFS_OP_STATFS:
fsid = op->upcall.req.statfs.fs_id;
break;
case PVFS2_VFS_OP_TRUNCATE:
fsid = op->upcall.req.truncate.refn.fs_id;
break;
case PVFS2_VFS_OP_MMAP_RA_FLUSH:
fsid = op->upcall.req.ra_cache_flush.refn.fs_id;
break;
case PVFS2_VFS_OP_FS_UMOUNT:
fsid = op->upcall.req.fs_umount.fs_id;
break;
case PVFS2_VFS_OP_GETXATTR:
fsid = op->upcall.req.getxattr.refn.fs_id;
break;
case PVFS2_VFS_OP_SETXATTR:
fsid = op->upcall.req.setxattr.refn.fs_id;
break;
case PVFS2_VFS_OP_LISTXATTR:
fsid = op->upcall.req.listxattr.refn.fs_id;
break;
case PVFS2_VFS_OP_REMOVEXATTR:
fsid = op->upcall.req.removexattr.refn.fs_id;
break;
case PVFS2_VFS_OP_FSYNC:
fsid = op->upcall.req.fsync.refn.fs_id;
break;
default:
break;
}
}
return fsid;
}
static void pvfs2_set_inode_flags(struct inode *inode,
PVFS_sys_attr *attrs)
{
if (attrs->flags & PVFS_IMMUTABLE_FL) {
inode->i_flags |= S_IMMUTABLE;
}
else {
inode->i_flags &= ~S_IMMUTABLE;
}
if (attrs->flags & PVFS_APPEND_FL) {
inode->i_flags |= S_APPEND;
}
else {
inode->i_flags &= ~S_APPEND;
}
if (attrs->flags & PVFS_NOATIME_FL) {
inode->i_flags |= S_NOATIME;
}
else {
inode->i_flags &= ~S_NOATIME;
}
return;
}
/* NOTE: symname is ignored unless the inode is a sym link */
int copy_attributes_to_inode(
struct inode *inode,
PVFS_sys_attr *attrs,
char *symname)
{
int ret = -1;
int perm_mode = 0;
pvfs2_inode_t *pvfs2_inode = NULL;
loff_t inode_size = 0, rounded_up_size = 0;
if (inode && attrs)
{
pvfs2_inode = PVFS2_I(inode);
/*
arbitrarily set the inode block size; FIXME: we need to
resolve the difference between the reported inode blocksize
and the PAGE_CACHE_SIZE, since our block count will always
be wrong.
For now, we're setting the block count to be the proper
number assuming the block size is 512 bytes, and the size is
rounded up to the nearest 4K. This is apparently required
to get proper size reports from the 'du' shell utility.
changing the inode->i_blkbits to something other than
PAGE_CACHE_SHIFT breaks mmap/execution as we depend on that.
*/
#ifdef HAVE_I_BLKSIZE_IN_STRUCT_INODE
inode->i_blksize = pvfs_bufmap_size_query();
#endif
inode->i_blkbits = PAGE_CACHE_SHIFT;
gossip_debug(GOSSIP_UTILS_DEBUG, "attrs->mask = %x (objtype = %s)\n",
attrs->mask,
attrs->objtype == PVFS_TYPE_METAFILE ? "file" :
attrs->objtype == PVFS_TYPE_DIRECTORY ? "directory" :
attrs->objtype == PVFS_TYPE_SYMLINK ? "symlink" :
"invalid/unknown");
if (attrs->objtype == PVFS_TYPE_METAFILE)
{
pvfs2_set_inode_flags(inode, attrs);
if (attrs->mask & PVFS_ATTR_SYS_SIZE)
{
inode_size = (loff_t)attrs->size;
rounded_up_size =
(inode_size + (4096 - (inode_size % 4096)));
pvfs2_lock_inode(inode);
#ifdef PVFS2_LINUX_KERNEL_2_4
#if (PVFS2_LINUX_KERNEL_2_4_MINOR_VER > 21)
inode->i_bytes = inode_size;
#endif
#else
/* this is always ok for 2.6.x */
inode->i_bytes = inode_size;
#endif
inode->i_blocks = (unsigned long)(rounded_up_size / 512);
pvfs2_unlock_inode(inode);
/*
NOTE: make sure all the places we're called from have
the inode->i_sem lock. we're fine in 99% of the cases
since we're mostly called from a lookup.
*/
inode->i_size = inode_size;
}
}
else if ((attrs->objtype == PVFS_TYPE_SYMLINK) &&
(symname != NULL))
{
inode->i_size = (loff_t)strlen(symname);
}
else
{
pvfs2_lock_inode(inode);
#ifdef PVFS2_LINUX_KERNEL_2_4
#if (PVFS2_LINUX_KERNEL_2_4_MINOR_VER > 21)
inode->i_bytes = PAGE_CACHE_SIZE;
#endif
#else
/* always ok for 2.6.x */
inode->i_bytes = PAGE_CACHE_SIZE;
#endif
inode->i_blocks = (unsigned long)(PAGE_CACHE_SIZE / 512);
pvfs2_unlock_inode(inode);
inode->i_size = PAGE_CACHE_SIZE;
}
inode->i_uid = attrs->owner;
inode->i_gid = attrs->group;
#ifdef PVFS2_LINUX_KERNEL_2_4
inode->i_atime = (time_t)attrs->atime;
inode->i_mtime = (time_t)attrs->mtime;
inode->i_ctime = (time_t)attrs->ctime;
#else
inode->i_atime.tv_sec = (time_t)attrs->atime;
inode->i_mtime.tv_sec = (time_t)attrs->mtime;
inode->i_ctime.tv_sec = (time_t)attrs->ctime;
inode->i_atime.tv_nsec = 0;
inode->i_mtime.tv_nsec = 0;
inode->i_ctime.tv_nsec = 0;
#endif
if (attrs->perms & PVFS_O_EXECUTE)
perm_mode |= S_IXOTH;
if (attrs->perms & PVFS_O_WRITE)
perm_mode |= S_IWOTH;
if (attrs->perms & PVFS_O_READ)
perm_mode |= S_IROTH;
if (attrs->perms & PVFS_G_EXECUTE)
perm_mode |= S_IXGRP;
if (attrs->perms & PVFS_G_WRITE)
perm_mode |= S_IWGRP;
if (attrs->perms & PVFS_G_READ)
perm_mode |= S_IRGRP;
if (attrs->perms & PVFS_U_EXECUTE)
perm_mode |= S_IXUSR;
if (attrs->perms & PVFS_U_WRITE)
perm_mode |= S_IWUSR;
if (attrs->perms & PVFS_U_READ)
perm_mode |= S_IRUSR;
if (attrs->perms & PVFS_G_SGID)
perm_mode |= S_ISGID;
/* Should we honor the suid bit of the file? */
if (get_suid_flag(inode) == 1 && (attrs->perms & PVFS_U_SUID))
perm_mode |= S_ISUID;
inode->i_mode = perm_mode;
if (is_root_handle(inode))
{
/* special case: mark the root inode as sticky */
inode->i_mode |= S_ISVTX;
gossip_debug(GOSSIP_UTILS_DEBUG, "Marking inode %llu as sticky\n",
llu(get_handle_from_ino(inode)));
}
switch (attrs->objtype)
{
case PVFS_TYPE_METAFILE:
inode->i_mode |= S_IFREG;
inode->i_op = &pvfs2_file_inode_operations;
inode->i_fop = &pvfs2_file_operations;
ret = 0;
break;
case PVFS_TYPE_DIRECTORY:
inode->i_mode |= S_IFDIR;
inode->i_op = &pvfs2_dir_inode_operations;
inode->i_fop = &pvfs2_dir_operations;
/* NOTE: we have no good way to keep nlink consistent for
* directories across clients; keep constant at 1. Why 1? If
* we go with 2, then find(1) gets confused and won't work
* properly withouth the -noleaf option */
inode->i_nlink = 1;
ret = 0;
break;
case PVFS_TYPE_SYMLINK:
inode->i_mode |= S_IFLNK;
inode->i_op = &pvfs2_symlink_inode_operations;
inode->i_fop = NULL;
/* copy link target to inode private data */
if (pvfs2_inode && symname)
{
strncpy(pvfs2_inode->link_target, symname, PVFS_NAME_MAX);
gossip_debug(GOSSIP_UTILS_DEBUG, "Copied attr link target %s\n",
pvfs2_inode->link_target);
}
gossip_debug(GOSSIP_UTILS_DEBUG, "symlink mode %o\n", inode->i_mode);
ret = 0;
break;
default:
gossip_err("pvfs2:copy_attributes_to_inode: got invalid "
"attribute type %x\n", attrs->objtype);
}
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2: copy_attributes_to_inode: setting i_mode to %o, i_size to %lu\n",
inode->i_mode, (unsigned long)pvfs2_i_size_read(inode));
}
return ret;
}
static inline void convert_attribute_mode_to_pvfs_sys_attr(
int mode,
PVFS_sys_attr *attrs,
int suid)
{
attrs->perms = PVFS_util_translate_mode(mode, suid);
attrs->mask |= PVFS_ATTR_SYS_PERM;
gossip_debug(GOSSIP_UTILS_DEBUG, "mode is %o | translated perms is %o\n", mode,
attrs->perms);
/* NOTE: this function only called during setattr. Setattr must not mess
* with object type */
}
/*
NOTE: in kernel land, we never use the sys_attr->link_target for
anything, so don't bother copying it into the sys_attr object here.
*/
static inline int copy_attributes_from_inode(
struct inode *inode,
PVFS_sys_attr *attrs,
struct iattr *iattr)
{
umode_t tmp_mode;
if (!iattr || !inode || !attrs)
{
gossip_err("NULL iattr (%p), inode (%p), attrs (%p) in copy_attributes_from_inode!\n",
iattr, inode, attrs);
return -EINVAL;
}
/*
we need to be careful
to only copy the attributes out of the iattr object that we
know are valid
*/
attrs->mask = 0;
if (iattr->ia_valid & ATTR_UID)
{
attrs->owner = iattr->ia_uid;
attrs->mask |= PVFS_ATTR_SYS_UID;
gossip_debug(GOSSIP_UTILS_DEBUG, "(UID) %d\n", attrs->owner);
}
if (iattr->ia_valid & ATTR_GID)
{
attrs->group = iattr->ia_gid;
attrs->mask |= PVFS_ATTR_SYS_GID;
gossip_debug(GOSSIP_UTILS_DEBUG, "(GID) %d\n", attrs->group);
}
if (iattr->ia_valid & ATTR_ATIME)
{
attrs->mask |= PVFS_ATTR_SYS_ATIME;
if (iattr->ia_valid & ATTR_ATIME_SET)
{
attrs->atime = pvfs2_convert_time_field((void *)&iattr->ia_atime);
attrs->mask |= PVFS_ATTR_SYS_ATIME_SET;
}
}
if (iattr->ia_valid & ATTR_MTIME)
{
attrs->mask |= PVFS_ATTR_SYS_MTIME;
if (iattr->ia_valid & ATTR_MTIME_SET)
{
attrs->mtime = pvfs2_convert_time_field((void *)&iattr->ia_mtime);
attrs->mask |= PVFS_ATTR_SYS_MTIME_SET;
}
}
if (iattr->ia_valid & ATTR_CTIME)
{
attrs->mask |= PVFS_ATTR_SYS_CTIME;
}
/* PVFS2 cannot set size with a setattr operation. Probably not likely
* to be requested through the VFS, but just in case, don't worry about
* ATTR_SIZE */
if (iattr->ia_valid & ATTR_MODE)
{
tmp_mode = iattr->ia_mode;
if (tmp_mode & (S_ISVTX))
{
if (is_root_handle(inode))
{
/* allow sticky bit to be set on root (since it shows up that
* way by default anyhow), but don't show it to
* the server
*/
tmp_mode -= S_ISVTX;
}
else
{
gossip_debug(GOSSIP_UTILS_DEBUG, "User attempted to set sticky bit"
"on non-root directory; returning EINVAL.\n");
return(-EINVAL);
}
}
if (tmp_mode & (S_ISUID))
{
gossip_debug(GOSSIP_UTILS_DEBUG, "Attempting to set setuid bit "
"(not supported); returning EINVAL.\n");
return(-EINVAL);
}
convert_attribute_mode_to_pvfs_sys_attr(
tmp_mode, attrs, get_suid_flag(inode));
}
return 0;
}
/*
issues a pvfs2 getattr request and fills in the appropriate inode
attributes if successful. returns 0 on success; -errno otherwise
*/
int pvfs2_inode_getattr(struct inode *inode, uint32_t getattr_mask)
{
int ret = -EINVAL;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *pvfs2_inode = NULL;
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_inode_getattr: called on inode %llu\n",
llu(get_handle_from_ino(inode)));
if (inode)
{
pvfs2_inode = PVFS2_I(inode);
if (!pvfs2_inode)
{
gossip_debug(GOSSIP_UTILS_DEBUG, "%s:%s:%d failed to resolve to pvfs2_inode\n", __FILE__, __func__, __LINE__);
return ret;
}
/*
in the case of being called from s_op->read_inode, the
pvfs2_inode private data hasn't been initialized yet, so we
need to use the inode number as the handle and query the
superblock for the fs_id. Further, we assign that private
data here.
that call flow looks like:
lookup --> iget --> read_inode --> here
In the case we are doing an iget4 or an iget5_locked, there
is no call made to read_inode so we actually have valid fields
in pvfs2_inode->refn
if the inode were already in the inode cache, it looks like:
lookup --> revalidate --> here
*/
if (pvfs2_inode->refn.handle == PVFS_HANDLE_NULL)
{
#if defined(HAVE_IGET4_LOCKED) || defined(HAVE_IGET5_LOCKED)
gossip_lerr("Critical error: Invalid handle despite using iget4/iget5\n");
return -EINVAL;
#endif
pvfs2_inode->refn.handle = get_handle_from_ino(inode);
}
if (pvfs2_inode->refn.fs_id == PVFS_FS_ID_NULL)
{
#if defined(HAVE_IGET4_LOCKED) || defined(HAVE_IGET5_LOCKED)
gossip_lerr("Critical error: Invalid fsid despite using iget4/iget5\n");
return -EINVAL;
#endif
pvfs2_inode->refn.fs_id = PVFS2_SB(inode->i_sb)->fs_id;
}
/*
post a getattr request here; make dentry valid if getattr
passes
*/
new_op = op_alloc(PVFS2_VFS_OP_GETATTR);
if (!new_op)
{
return -ENOMEM;
}
new_op->upcall.req.getattr.refn = pvfs2_inode->refn;
new_op->upcall.req.getattr.mask = getattr_mask;
ret = service_operation(
new_op, "pvfs2_inode_getattr",
get_interruptible_flag(inode));
/* check what kind of goodies we got */
if (ret == 0)
{
if (copy_attributes_to_inode
(inode, &new_op->downcall.resp.getattr.attributes,
new_op->downcall.resp.getattr.link_target))
{
gossip_err("pvfs2_inode_getattr: failed to copy "
"attributes\n");
ret = -ENOENT;
goto copy_attr_failure;
}
/* store blksize in pvfs2 specific part of inode structure; we
* are only going to use this to report to stat to make sure it
* doesn't perturb any inode related code paths
*/
if(new_op->downcall.resp.getattr.attributes.objtype
== PVFS_TYPE_METAFILE)
{
pvfs2_inode->blksize =
new_op->downcall.resp.getattr.attributes.blksize;
}
else
{
/* mimic behavior of generic_fillattr() for other types */
pvfs2_inode->blksize = (1 << inode->i_blkbits);
}
}
copy_attr_failure:
gossip_debug(GOSSIP_UTILS_DEBUG, "Getattr on handle %llu, fsid %d\n (inode ct = %d) "
"returned %d\n",
llu(pvfs2_inode->refn.handle), pvfs2_inode->refn.fs_id,
(int)atomic_read(&inode->i_count), ret);
/* store error code in the inode so that we can retrieve it later if
* needed
*/
if(ret < 0)
{
pvfs2_inode->error_code = ret;
}
op_release(new_op);
}
return ret;
}
/*
issues a pvfs2 setattr request to make sure the new attribute values
take effect if successful. returns 0 on success; -errno otherwise
*/
int pvfs2_inode_setattr(
struct inode *inode,
struct iattr *iattr)
{
int ret = -ENOMEM;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *pvfs2_inode = NULL;
if (inode)
{
pvfs2_inode = PVFS2_I(inode);
new_op = op_alloc(PVFS2_VFS_OP_SETATTR);
if (!new_op)
{
return ret;
}
new_op->upcall.req.setattr.refn = pvfs2_inode->refn;
if ((new_op->upcall.req.setattr.refn.handle == PVFS_HANDLE_NULL) &&
(new_op->upcall.req.setattr.refn.fs_id == PVFS_FS_ID_NULL))
{
struct super_block *sb = inode->i_sb;
new_op->upcall.req.setattr.refn.handle =
PVFS2_SB(sb)->root_handle;
new_op->upcall.req.setattr.refn.fs_id =
PVFS2_SB(sb)->fs_id;
}
ret = copy_attributes_from_inode(
inode, &new_op->upcall.req.setattr.attributes, iattr);
if(ret < 0)
{
op_release(new_op);
return(ret);
}
ret = service_operation(
new_op, "pvfs2_inode_setattr",
get_interruptible_flag(inode));
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_inode_setattr: returning %d\n", ret);
/* when request is serviced properly, free req op struct */
op_release(new_op);
/* successful setattr should clear the atime, mtime and ctime flags */
if (ret == 0) {
ClearAtimeFlag(pvfs2_inode);
ClearMtimeFlag(pvfs2_inode);
ClearCtimeFlag(pvfs2_inode);
ClearModeFlag(pvfs2_inode);
}
}
return ret;
}
int pvfs2_flush_inode(struct inode *inode)
{
/*
* If it is a dirty inode, this function gets called.
* Gather all the information that needs to be setattr'ed
* Right now, this will only be used for mode, atime, mtime
* and/or ctime.
*/
struct iattr wbattr;
int ret;
int mtime_flag, ctime_flag, atime_flag, mode_flag;
pvfs2_inode_t *pvfs2_inode = PVFS2_I(inode);
memset(&wbattr, 0, sizeof(wbattr));
/* check inode flags up front, and clear them if they are set. This
* will prevent multiple processes from all trying to flush the same
* inode if they call close() simultaneously
*/
mtime_flag = MtimeFlag(pvfs2_inode);
ClearMtimeFlag(pvfs2_inode);
ctime_flag = CtimeFlag(pvfs2_inode);
ClearCtimeFlag(pvfs2_inode);
atime_flag = AtimeFlag(pvfs2_inode);
ClearAtimeFlag(pvfs2_inode);
mode_flag = ModeFlag(pvfs2_inode);
ClearModeFlag(pvfs2_inode);
/* -- Lazy atime,mtime and ctime update --
* Note: all times are dictated by server in the new scheme
* and not by the clients
*
* Also mode updates are being handled now..
*/
if (mtime_flag)
wbattr.ia_valid |= ATTR_MTIME;
if (ctime_flag)
wbattr.ia_valid |= ATTR_CTIME;
/*
* We do not need to honor atime flushes if
* a) object has a noatime marker
* b) object is a directory and has a nodiratime marker on the fs
* c) entire file system is mounted with noatime option
*/
if (!((inode->i_flags & S_NOATIME)
|| (inode->i_sb->s_flags & MS_NOATIME)
|| ((inode->i_sb->s_flags & MS_NODIRATIME) && S_ISDIR(inode->i_mode))) && atime_flag)
{
wbattr.ia_valid |= ATTR_ATIME;
}
if (mode_flag)
{
wbattr.ia_mode = inode->i_mode;
wbattr.ia_valid |= ATTR_MODE;
}
gossip_debug(GOSSIP_UTILS_DEBUG, "*********** pvfs2_flush_inode: %llu "
"(ia_valid %d)\n", llu(get_handle_from_ino(inode)), wbattr.ia_valid);
if (wbattr.ia_valid == 0)
{
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_flush_inode skipping setattr()\n");
return 0;
}
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_flush_inode (%llu) writing mode %o\n",
llu(get_handle_from_ino(inode)), inode->i_mode);
ret = pvfs2_inode_setattr(inode, &wbattr);
return ret;
}
/* metafile distribution */
#define DIST_KEY "system.pvfs2." METAFILE_DIST_KEYSTR
/* datafile handles */
#define DFILE_KEY "system.pvfs2." DATAFILE_HANDLES_KEYSTR
/* symlink */
#define SYMLINK_KEY "system.pvfs2." SYMLINK_TARGET_KEYSTR
/* root handle */
#define ROOT_KEY "system.pvfs2." ROOT_HANDLE_KEYSTR
/* directory entry key */
#define DIRENT_KEY "system.pvfs2." DIRECTORY_ENTRY_KEYSTR
/* Extended attributes helper functions */
static char *xattr_non_zero_terminated[] = {
DFILE_KEY,
DIST_KEY,
ROOT_KEY,
};
/* Extended attributes helper functions */
/*
* this function returns
* 0 if the val corresponding to name is known to be not terminated with an explicit \0
* 1 if the val corresponding to name is known to be \0 terminated
*/
static int xattr_zero_terminated(const char *name)
{
int i;
static int xattr_count = sizeof(xattr_non_zero_terminated)/sizeof(char *);
for (i = 0;i < xattr_count; i++)
{
if (strcmp(name, xattr_non_zero_terminated[i]) == 0)
return 0;
}
return 1;
}
static char *xattr_resvd_keys[] = {
DFILE_KEY,
DIST_KEY,
DIRENT_KEY,
SYMLINK_KEY,
ROOT_KEY,
};
/*
* this function returns
* 0 if the key corresponding to name is not meant to be printed as part of a listxattr
* 1 if the key corresponding to name is meant to be returned as part of a listxattr.
* Currently xattr_resvd_keys[] is the array that holds the reserved entries
*/
static int is_reserved_key(const char *key, size_t size)
{
int i;
static int resv_count = sizeof(xattr_resvd_keys)/sizeof(char *);
for (i = 0; i < resv_count; i++)
{
if (strncmp(key, xattr_resvd_keys[i], size) == 0)
return 1;
}
return 0;
}
/*
* Tries to get a specified key's attributes of a given
* file into a user-specified buffer. Note that the getxattr
* interface allows for the users to probe the size of an
* extended attribute by passing in a value of 0 to size.
* Thus our return value is always the size of the attribute
* unless the key does not exist for the file and/or if
* there were errors in fetching the attribute value.
*/
ssize_t pvfs2_inode_getxattr(struct inode *inode, const char* prefix,
const char *name, void *buffer, size_t size)
{
ssize_t ret = -ENOMEM;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *pvfs2_inode = NULL;
ssize_t length = 0;
int fsuid, fsgid;
if (name == NULL || (size > 0 && buffer == NULL))
{
gossip_err("pvfs2_inode_getxattr: bogus NULL pointers\n");
return -EINVAL;
}
if (size < 0 || (strlen(name)+strlen(prefix)) >= PVFS_MAX_XATTR_NAMELEN)
{
gossip_err("Invalid size (%d) or key length (%d)\n",
(int) size, (int)(strlen(name)+strlen(prefix)));
return -EINVAL;
}
if (inode)
{
#ifdef HAVE_CURRENT_FSUID
fsuid = current_fsuid();
fsgid = current_fsgid();
#else
fsuid = current->fsuid;
fsgid = current->fsgid;
#endif
gossip_debug(GOSSIP_XATTR_DEBUG, "getxattr on inode %llu, name %s (uid %o, gid %o)\n",
llu(get_handle_from_ino(inode)), name, fsuid, fsgid);
pvfs2_inode = PVFS2_I(inode);
/* obtain the xattr semaphore */
down_read(&pvfs2_inode->xattr_sem);
new_op = op_alloc(PVFS2_VFS_OP_GETXATTR);
if (!new_op)
{
up_read(&pvfs2_inode->xattr_sem);
return ret;
}
new_op->upcall.req.getxattr.refn = pvfs2_inode->refn;
ret = snprintf((char*)new_op->upcall.req.getxattr.key,
PVFS_MAX_XATTR_NAMELEN, "%s%s", prefix, name);
/*
* NOTE: Although keys are meant to be NULL terminated textual strings,
* I am going to explicitly pass the length just in case we change this
* later on...
*/
new_op->upcall.req.getxattr.key_sz = ret + 1;
ret = service_operation(
new_op, "pvfs2_inode_getxattr",
get_interruptible_flag(inode));
/* Upon success, we need to get the value length
* from downcall and return that.
* and also copy the value out to the requester
*/
if (ret == 0)
{
ssize_t new_length;
length = new_op->downcall.resp.getxattr.val_sz;
/*
* if the xattr corresponding to name was not terminated with a \0
* then we return the entire response length
*/
if (xattr_zero_terminated(name) == 0)
{
new_length = length;
}
/*
* if it was terminated by a \0 then we return 1 less for the getfattr
* programs to play nicely with displaying it
*/
else {
new_length = length - 1;
}
/* Just return the length of the queried attribute after
* subtracting the \0 thingie */
if (size == 0)
{
ret = new_length;
}
else
{
/* check to see if key length is > provided buffer size */
if (new_length > size)
{
ret = -ERANGE;
}
else
{
/* No size problems */
memset(buffer, 0, size);
memcpy(buffer, new_op->downcall.resp.getxattr.val,
new_length);
ret = new_length;
gossip_debug(GOSSIP_XATTR_DEBUG, "pvfs2_inode_getxattr: inode %llu key %s "
" key_sz %d, val_length %d\n",
llu(get_handle_from_ino(inode)),
(char*)new_op->upcall.req.getxattr.key,
(int) new_op->upcall.req.getxattr.key_sz, (int) ret);
}
}
}
else if (ret == -ENOENT)
{
ret = -ENODATA; /* if no such keys exists we set this to be errno */
gossip_debug(GOSSIP_XATTR_DEBUG, "pvfs2_inode_getxattr: inode %llu key %s does not exist!\n",
llu(get_handle_from_ino(inode)), (char *) new_op->upcall.req.getxattr.key);
}
/* when request is serviced properly, free req op struct */
op_release(new_op);
up_read(&pvfs2_inode->xattr_sem);
}
return ret;
}
/*
* tries to set an attribute for a given key on a file.
* Returns a -ve number on error and 0 on success.
* Key is text, but value can be binary!
*/
int pvfs2_inode_setxattr(struct inode *inode, const char* prefix,
const char *name, const void *value, size_t size, int flags)
{
int ret = -ENOMEM;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *pvfs2_inode = NULL;
if (size < 0 || size >= PVFS_MAX_XATTR_VALUELEN || flags < 0)
{
gossip_err("pvfs2_inode_setxattr: bogus values of size(%d), flags(%d)\n",
(int) size, flags);
return -EINVAL;
}
if (name == NULL || (size > 0 && value == NULL))
{
gossip_err("pvfs2_inode_setxattr: bogus NULL pointers!\n");
return -EINVAL;
}
if (prefix)
{
if(strlen(name)+strlen(prefix) >= PVFS_MAX_XATTR_NAMELEN)
{
gossip_err("pvfs2_inode_setxattr: bogus key size (%d)\n",
(int)(strlen(name)+strlen(prefix)));
return -EINVAL;
}
}
else
{
if(strlen(name) >= PVFS_MAX_XATTR_NAMELEN)
{
gossip_err("pvfs2_inode_setxattr: bogus key size (%d)\n",
(int)(strlen(name)));
return -EINVAL;
}
}
/* This is equivalent to a removexattr */
if (size == 0 && value == NULL)
{
gossip_debug(GOSSIP_XATTR_DEBUG, "removing xattr (%s%s)\n", prefix, name);
return pvfs2_inode_removexattr(inode, prefix, name, flags);
}
if (inode)
{
gossip_debug(GOSSIP_XATTR_DEBUG, "setxattr on inode %llu, name %s\n",
llu(get_handle_from_ino(inode)), name);
if (IS_RDONLY(inode))
{
gossip_err("pvfs2_inode_setxattr: Read-only file system\n");
return -EROFS;
}
if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
{
gossip_err("pvfs2_inode_setxattr: Immutable inode or append-only "
"inode; operation not permitted\n");
return -EPERM;
}
pvfs2_inode = PVFS2_I(inode);
down_write(&pvfs2_inode->xattr_sem);
new_op = op_alloc(PVFS2_VFS_OP_SETXATTR);
if (!new_op)
{
up_write(&pvfs2_inode->xattr_sem);
return ret;
}
new_op->upcall.req.setxattr.refn = pvfs2_inode->refn;
new_op->upcall.req.setxattr.flags = flags;
/*
* NOTE: Although keys are meant to be NULL terminated textual strings,
* I am going to explicitly pass the length just in case we change this
* later on...
*/
ret = snprintf((char*)new_op->upcall.req.setxattr.keyval.key,
PVFS_MAX_XATTR_NAMELEN, "%s%s", prefix, name);
new_op->upcall.req.setxattr.keyval.key_sz =
ret + 1;
memcpy(new_op->upcall.req.setxattr.keyval.val, value, size);
new_op->upcall.req.setxattr.keyval.val[size] = '\0';
/* For some reason, val_sz should include the \0 at the end as well */
new_op->upcall.req.setxattr.keyval.val_sz = size + 1;
gossip_debug(GOSSIP_XATTR_DEBUG, "pvfs2_inode_setxattr: key %s, key_sz %d "
" value size %zd\n",
(char*)new_op->upcall.req.setxattr.keyval.key,
(int) new_op->upcall.req.setxattr.keyval.key_sz,
size + 1);
ret = service_operation(
new_op, "pvfs2_inode_setxattr",
get_interruptible_flag(inode));
gossip_debug(GOSSIP_XATTR_DEBUG, "pvfs2_inode_setxattr: returning %d\n", ret);
/* when request is serviced properly, free req op struct */
op_release(new_op);
up_write(&pvfs2_inode->xattr_sem);
}
return ret;
}
int pvfs2_inode_removexattr(struct inode *inode, const char* prefix,
const char *name, int flags)
{
int ret = -ENOMEM;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *pvfs2_inode = NULL;
if(!name)
{
gossip_err("pvfs2_inode_removexattr: xattr key is NULL\n");
return -EINVAL;
}
if (prefix)
{
if((strlen(name)+strlen(prefix)) >= PVFS_MAX_XATTR_NAMELEN)
{
gossip_err("pvfs2_inode_removexattr: Invalid key length(%d)\n",
(int)(strlen(name)+strlen(prefix)));
return -EINVAL;
}
}
else
{
if(strlen(name) >= PVFS_MAX_XATTR_NAMELEN)
{
gossip_err("pvfs2_inode_removexattr: Invalid key length(%d)\n",
(int)(strlen(name)));
return -EINVAL;
}
}
if (inode)
{
pvfs2_inode = PVFS2_I(inode);
down_write(&pvfs2_inode->xattr_sem);
new_op = op_alloc(PVFS2_VFS_OP_REMOVEXATTR);
if (!new_op)
{
up_write(&pvfs2_inode->xattr_sem);
return ret;
}
new_op->upcall.req.removexattr.refn = pvfs2_inode->refn;
/*
* NOTE: Although keys are meant to be NULL terminated textual strings,
* I am going to explicitly pass the length just in case we change this
* later on...
*/
ret = snprintf((char*)new_op->upcall.req.removexattr.key,
PVFS_MAX_XATTR_NAMELEN, "%s%s",
(prefix ? prefix : ""), name);
new_op->upcall.req.removexattr.key_sz = ret + 1;
gossip_debug(GOSSIP_XATTR_DEBUG, "pvfs2_inode_removexattr: key %s, key_sz %d\n",
(char*)new_op->upcall.req.removexattr.key,
(int) new_op->upcall.req.removexattr.key_sz);
ret = service_operation(
new_op, "pvfs2_inode_removexattr",
get_interruptible_flag(inode));
if (ret == -ENOENT)
{
/* Request to replace a non-existent attribute is an error */
if (flags & XATTR_REPLACE)
ret = -ENODATA;
else
ret = 0;
}
gossip_debug(GOSSIP_XATTR_DEBUG, "pvfs2_inode_removexattr: returning %d\n",
ret);
/* when request is serviced properly, free req op struct */
op_release(new_op);
up_write(&pvfs2_inode->xattr_sem);
}
return ret;
}
/*
* Tries to get a specified object's keys into a user-specified
* buffer of a given size.
* Note that like the previous instances of xattr routines,
* this also allows you to pass in a NULL pointer and 0 size
* to probe the size for subsequent memory allocations.
* Thus our return value is always the size of all the keys
* unless there were errors in fetching the keys!
*/
int pvfs2_inode_listxattr(struct inode *inode, char *buffer, size_t size)
{
ssize_t ret = -ENOMEM, total = 0;
int i = 0, count_keys = 0;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *pvfs2_inode = NULL;
ssize_t length = 0;
if (size > 0 && buffer == NULL)
{
gossip_err("pvfs2_inode_listxattr: bogus NULL pointers\n");
return -EINVAL;
}
if (size < 0)
{
gossip_err("Invalid size (%d)\n", (int) size);
return -EINVAL;
}
if (inode)
{
PVFS_ds_position token = PVFS_ITERATE_START;
pvfs2_inode = PVFS2_I(inode);
/* obtain the xattr semaphore */
down_read(&pvfs2_inode->xattr_sem);
new_op = op_alloc(PVFS2_VFS_OP_LISTXATTR);
if (!new_op)
{
up_read(&pvfs2_inode->xattr_sem);
return ret;
}
if (buffer && size > 0)
{
memset(buffer, 0, size);
}
try_again:
new_op->upcall.req.listxattr.refn = pvfs2_inode->refn;
new_op->upcall.req.listxattr.token = token;
new_op->upcall.req.listxattr.requested_count = (size == 0) ? 0 : PVFS_MAX_XATTR_LISTLEN;
ret = service_operation(
new_op, "pvfs2_inode_listxattr",
get_interruptible_flag(inode));
if (ret == 0)
{
if (size == 0)
{
/*
* This is a bit of a big upper limit, but I did not want to spend too
* much time getting this correct, since users end up allocating memory
* rather than us...
*/
total = new_op->downcall.resp.listxattr.returned_count * PVFS_MAX_XATTR_NAMELEN;
goto done;
}
length = new_op->downcall.resp.listxattr.keylen;
if (length == 0)
{
goto done;
}
else
{
int key_size = 0;
/* check to see how much can be fit in the buffer. fit only whole keys */
for (i = 0; i < new_op->downcall.resp.listxattr.returned_count; i++)
{
if (total + new_op->downcall.resp.listxattr.lengths[i] <= size)
{
/* Since many dumb programs try to setxattr() on our reserved xattrs
* this is a feeble attempt at defeating those by not listing them
* in the output of listxattr.. sigh
*/
if (is_reserved_key(new_op->downcall.resp.listxattr.key + key_size,
new_op->downcall.resp.listxattr.lengths[i]) == 0)
{
gossip_debug(GOSSIP_XATTR_DEBUG, "Copying key %d -> %s\n",
i, new_op->downcall.resp.listxattr.key + key_size);
memcpy(buffer + total, new_op->downcall.resp.listxattr.key + key_size,
new_op->downcall.resp.listxattr.lengths[i]);
total += new_op->downcall.resp.listxattr.lengths[i];
count_keys++;
}
else {
gossip_debug(GOSSIP_XATTR_DEBUG, "[RESERVED] key %d -> %s\n",
i, new_op->downcall.resp.listxattr.key + key_size);
}
key_size += new_op->downcall.resp.listxattr.lengths[i];
}
else {
goto done;
}
}
/* Since the buffer was large enough, we might have to continue fetching more keys! */
token = new_op->downcall.resp.listxattr.token;
if (token != PVFS_ITERATE_END)
goto try_again;
}
}
done:
gossip_debug(GOSSIP_XATTR_DEBUG, "pvfs2_inode_listxattr: returning %d [size of buffer %ld] "
"(filled in %d keys)\n",
ret ? (int) ret : (int) total, (long) size, count_keys);
/* when request is serviced properly, free req op struct */
op_release(new_op);
up_read(&pvfs2_inode->xattr_sem);
if (ret == 0)
ret = total;
}
return ret;
}
static inline struct inode *pvfs2_create_file(
struct inode *dir,
struct dentry *dentry,
int mode,
int *error_code)
{
int ret = -1;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *parent = PVFS2_I(dir);
struct inode *inode = NULL;
new_op = op_alloc(PVFS2_VFS_OP_CREATE);
if (!new_op)
{
*error_code = -ENOMEM;
return NULL;
}
if (parent && parent->refn.handle != PVFS_HANDLE_NULL && parent->refn.fs_id != PVFS_FS_ID_NULL)
{
new_op->upcall.req.create.parent_refn = parent->refn;
}
else
{
#if defined(HAVE_IGET5_LOCKED) || defined(HAVE_IGET4_LOCKED)
gossip_lerr("Critical error: i_ino cannot be relied on when using iget4/5\n");
*error_code = -EINVAL;
op_release(new_op);
return NULL;
#endif
new_op->upcall.req.create.parent_refn.handle =
get_handle_from_ino(dir);
new_op->upcall.req.create.parent_refn.fs_id =
PVFS2_SB(dir->i_sb)->fs_id;
}
/* macro defined in pvfs2-kernel.h */
fill_default_sys_attrs(new_op->upcall.req.create.attributes,
PVFS_TYPE_METAFILE, mode);
strncpy(new_op->upcall.req.create.d_name,
dentry->d_name.name, PVFS2_NAME_LEN);
ret = service_operation(
new_op, "pvfs2_create_file",
get_interruptible_flag(dir));
gossip_debug(GOSSIP_UTILS_DEBUG, "Create Got PVFS2 handle %llu on fsid %d (ret=%d)\n",
llu(new_op->downcall.resp.create.refn.handle),
new_op->downcall.resp.create.refn.fs_id, ret);
if (ret > -1)
{
inode = pvfs2_get_custom_inode(
dir->i_sb, dir, (S_IFREG | mode), 0, new_op->downcall.resp.create.refn);
if (!inode)
{
gossip_err("*** Failed to allocate pvfs2 file inode\n");
op_release(new_op);
*error_code = -ENOMEM;
return NULL;
}
gossip_debug(GOSSIP_UTILS_DEBUG, "Assigned file inode new number of %llu\n",
llu(get_handle_from_ino(inode)));
/* finally, add dentry with this new inode to the dcache */
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_create_file: Instantiating\n *negative* "
"dentry %p for %s\n", dentry,
dentry->d_name.name);
dentry->d_op = &pvfs2_dentry_operations;
d_instantiate(dentry, inode);
gossip_debug(GOSSIP_UTILS_DEBUG, "Inode (Regular File) %llu -> %s\n",
llu(get_handle_from_ino(inode)), dentry->d_name.name);
}
else
{
*error_code = ret;
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_create_file: failed with error code %d\n",
*error_code);
}
op_release(new_op);
return inode;
}
static inline struct inode *pvfs2_create_dir(
struct inode *dir,
struct dentry *dentry,
int mode,
int *error_code)
{
int ret = -1;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *parent = PVFS2_I(dir);
struct inode *inode = NULL;
new_op = op_alloc(PVFS2_VFS_OP_MKDIR);
if (!new_op)
{
*error_code = -ENOMEM;
return NULL;
}
if (parent && parent->refn.handle != PVFS_HANDLE_NULL && parent->refn.fs_id != PVFS_FS_ID_NULL)
{
new_op->upcall.req.mkdir.parent_refn = parent->refn;
}
else
{
#if defined(HAVE_IGET5_LOCKED) || defined(HAVE_IGET4_LOCKED)
gossip_lerr("Critical error: i_ino cannot be relied on when using iget4/5\n");
*error_code = -EINVAL;
op_release(new_op);
return NULL;
#endif
new_op->upcall.req.mkdir.parent_refn.handle =
get_handle_from_ino(dir);
new_op->upcall.req.mkdir.parent_refn.fs_id =
PVFS2_SB(dir->i_sb)->fs_id;
}
/* macro defined in pvfs2-kernel.h */
fill_default_sys_attrs(new_op->upcall.req.mkdir.attributes,
PVFS_TYPE_DIRECTORY, mode);
strncpy(new_op->upcall.req.mkdir.d_name,
dentry->d_name.name, PVFS2_NAME_LEN);
ret = service_operation(
new_op, "pvfs2_create_dir",
get_interruptible_flag(dir));
gossip_debug(GOSSIP_UTILS_DEBUG, "Mkdir Got PVFS2 handle %llu on fsid %d\n",
llu(new_op->downcall.resp.mkdir.refn.handle),
new_op->downcall.resp.mkdir.refn.fs_id);
if (ret > -1)
{
inode = pvfs2_get_custom_inode(
dir->i_sb, dir, (S_IFDIR | mode), 0, new_op->downcall.resp.mkdir.refn);
if (!inode)
{
gossip_err("*** Failed to allocate pvfs2 dir inode\n");
op_release(new_op);
*error_code = -ENOMEM;
return NULL;
}
gossip_debug(GOSSIP_UTILS_DEBUG, "Assigned dir inode new number of %llu\n",
llu(get_handle_from_ino(inode)));
/* finally, add dentry with this new inode to the dcache */
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_create_dir: Instantiating\n *negative* "
"dentry %p for %s\n", dentry,
dentry->d_name.name);
dentry->d_op = &pvfs2_dentry_operations;
d_instantiate(dentry, inode);
gossip_debug(GOSSIP_UTILS_DEBUG, "Inode (Directory) %llu -> %s\n",
llu(get_handle_from_ino(inode)), dentry->d_name.name);
}
else
{
*error_code = ret;
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_create_dir: failed with error code %d\n",
*error_code);
}
op_release(new_op);
return inode;
}
static inline struct inode *pvfs2_create_symlink(
struct inode *dir,
struct dentry *dentry,
const char *symname,
int mode,
int *error_code)
{
int ret = -1;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *parent = PVFS2_I(dir);
struct inode *inode = NULL;
if(!symname)
{
*error_code = -EINVAL;
return NULL;
}
new_op = op_alloc(PVFS2_VFS_OP_SYMLINK);
if (!new_op)
{
*error_code = -ENOMEM;
return NULL;
}
if (parent && parent->refn.handle != PVFS_HANDLE_NULL && parent->refn.fs_id != PVFS_FS_ID_NULL)
{
new_op->upcall.req.sym.parent_refn = parent->refn;
}
else
{
#if defined(HAVE_IGET5_LOCKED) || defined(HAVE_IGET4_LOCKED)
gossip_lerr("Critical error: i_ino cannot be relied on when using iget4/5\n");
*error_code = -EINVAL;
op_release(new_op);
return NULL;
#endif
new_op->upcall.req.sym.parent_refn.handle =
get_handle_from_ino(dir);
new_op->upcall.req.sym.parent_refn.fs_id =
PVFS2_SB(dir->i_sb)->fs_id;
}
/* macro defined in pvfs2-kernel.h */
fill_default_sys_attrs(new_op->upcall.req.sym.attributes,
PVFS_TYPE_SYMLINK, mode);
strncpy(new_op->upcall.req.sym.entry_name, dentry->d_name.name,
PVFS2_NAME_LEN);
strncpy(new_op->upcall.req.sym.target, symname, PVFS2_NAME_LEN);
ret = service_operation(
new_op, "pvfs2_symlink_file",
get_interruptible_flag(dir));
gossip_debug(GOSSIP_UTILS_DEBUG, "Symlink Got PVFS2 handle %llu on fsid %d (ret=%d)\n",
llu(new_op->downcall.resp.sym.refn.handle),
new_op->downcall.resp.sym.refn.fs_id, ret);
if (ret > -1)
{
inode = pvfs2_get_custom_inode(
dir->i_sb, dir, (S_IFLNK | mode), 0, new_op->downcall.resp.sym.refn);
if (!inode)
{
gossip_err("*** Failed to allocate pvfs2 symlink inode\n");
op_release(new_op);
*error_code = -ENOMEM;
return NULL;
}
gossip_debug(GOSSIP_UTILS_DEBUG, "Assigned symlink inode new number of %llu\n",
llu(get_handle_from_ino(inode)));
/* finally, add dentry with this new inode to the dcache */
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_create_symlink: Instantiating\n "
"*negative* dentry %p for %s\n", dentry,
dentry->d_name.name);
dentry->d_op = &pvfs2_dentry_operations;
d_instantiate(dentry, inode);
gossip_debug(GOSSIP_UTILS_DEBUG, "Inode (Symlink) %llu -> %s\n",
llu(get_handle_from_ino(inode)), dentry->d_name.name);
}
else
{
*error_code = ret;
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_create_symlink: failed with error code %d\n",
*error_code);
}
op_release(new_op);
return inode;
}
/*
create a pvfs2 entry; returns a properly populated inode
pointer on success; NULL on failure.
the required error_code value will contain an error code ONLY if an
error occurs (i.e. NULL is returned) and is set to 0 otherwise.
if op_type is PVFS_VFS_OP_CREATE, a file is created
if op_type is PVFS_VFS_OP_MKDIR, a directory is created
if op_type is PVFS_VFS_OP_SYMLINK, a symlink is created
symname should be null unless mode is PVFS_VFS_OP_SYMLINK
*/
struct inode *pvfs2_create_entry(
struct inode *dir,
struct dentry *dentry,
const char *symname,
int mode,
int op_type,
int *error_code)
{
if (dir && dentry && error_code)
{
if(strlen(dentry->d_name.name) > (PVFS2_NAME_LEN - 1))
{
*error_code = -ENAMETOOLONG;
return(NULL);
}
switch (op_type)
{
case PVFS2_VFS_OP_CREATE:
return pvfs2_create_file(
dir, dentry, mode, error_code);
case PVFS2_VFS_OP_MKDIR:
return pvfs2_create_dir(
dir, dentry, mode, error_code);
case PVFS2_VFS_OP_SYMLINK:
return pvfs2_create_symlink(
dir, dentry, symname, mode, error_code);
}
}
if (error_code)
{
gossip_err("pvfs2_create_entry: invalid op_type %d\n", op_type);
*error_code = -EINVAL;
}
return NULL;
}
int pvfs2_remove_entry(
struct inode *dir,
struct dentry *dentry)
{
int ret = -EINVAL;
pvfs2_kernel_op_t *new_op = NULL;
pvfs2_inode_t *parent = PVFS2_I(dir);
struct inode *inode = dentry->d_inode;
if (inode && parent && dentry)
{
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_remove_entry: called on %s\n (inode %llu): "
"Parent is %llu | fs_id %d\n", dentry->d_name.name,
llu(get_handle_from_ino(inode)), llu(parent->refn.handle),
parent->refn.fs_id);
new_op = op_alloc(PVFS2_VFS_OP_REMOVE);
if (!new_op)
{
return -ENOMEM;
}
if (parent && parent->refn.handle != PVFS_HANDLE_NULL && parent->refn.fs_id != PVFS_FS_ID_NULL)
{
new_op->upcall.req.remove.parent_refn = parent->refn;
}
else
{
#if defined(HAVE_IGET5_LOCKED) || defined(HAVE_IGET4_LOCKED)
gossip_lerr("Critical error: i_ino cannot be relied on when using iget4/5\n");
op_release(new_op);
return -ENOMEM;
#endif
new_op->upcall.req.remove.parent_refn.handle =
get_handle_from_ino(dir);
new_op->upcall.req.remove.parent_refn.fs_id =
PVFS2_SB(dir->i_sb)->fs_id;
}
strncpy(new_op->upcall.req.remove.d_name,
dentry->d_name.name, PVFS2_NAME_LEN);
ret = service_operation(
new_op, "pvfs2_remove_entry",
get_interruptible_flag(inode));
/* when request is serviced properly, free req op struct */
op_release(new_op);
}
return ret;
}
int pvfs2_truncate_inode(
struct inode *inode,
loff_t size)
{
int ret = -EINVAL;
pvfs2_inode_t *pvfs2_inode = PVFS2_I(inode);
pvfs2_kernel_op_t *new_op = NULL;
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2: pvfs2_truncate_inode %llu: "
"Handle is %llu | fs_id %d | size is %lu\n",
llu(get_handle_from_ino(inode)), llu(pvfs2_inode->refn.handle),
pvfs2_inode->refn.fs_id, (unsigned long)size);
new_op = op_alloc(PVFS2_VFS_OP_TRUNCATE);
if (!new_op)
{
return -ENOMEM;
}
new_op->upcall.req.truncate.refn = pvfs2_inode->refn;
new_op->upcall.req.truncate.size = (PVFS_size)size;
ret = service_operation(
new_op, "pvfs2_truncate_inode",
get_interruptible_flag(inode));
/*
the truncate has no downcall members to retrieve, but
the status value tells us if it went through ok or not
*/
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2: pvfs2_truncate got return value of %d\n",ret);
op_release(new_op);
return ret;
}
#ifdef HAVE_FIND_INODE_HANDLE_SUPER_OPERATIONS
typedef enum {
HANDLE_CHECK_LENGTH = 1,
HANDLE_CHECK_MAGIC = 2,
HANDLE_CHECK_FSID = 4,
} handle_check_t;
/* Perform simple sanity checks on the obtained handle */
static inline int perform_handle_checks(const struct file_handle *fhandle,
handle_check_t check, void *p)
{
if (!fhandle)
{
return -EINVAL;
}
/* okay good. now check if magic_nr matches */
if (check & HANDLE_CHECK_LENGTH)
{
/* Make sure that handle length matches our opaque handle structure */
if (fhandle->fh_private_length != sizeof(pvfs2_opaque_handle_t))
{
gossip_err("perform_handle_checks: length mismatch (%ld) "
" instead of (%ld)\n", (unsigned long) fhandle->fh_private_length,
(unsigned long) sizeof(pvfs2_opaque_handle_t));
return 0;
}
}
if (check & HANDLE_CHECK_MAGIC)
{
u32 magic;
get_fh_field(&fhandle->fh_generic, magic, magic);
if (magic != PVFS2_SUPER_MAGIC)
{
gossip_err("perform_handle_checks: mismatched magic number "
" (%x) instead of (%x)\n",
magic, PVFS2_SUPER_MAGIC);
return 0;
}
}
if (check & HANDLE_CHECK_FSID)
{
pvfs2_sb_info_t *pvfs2_sbp = NULL;
struct super_block *sb = (struct super_block *) p;
u32 fsid;
if (!sb)
return 0;
pvfs2_sbp = PVFS2_SB(sb);
get_fh_field(&fhandle->fh_generic, fsid, fsid);
if (fsid != pvfs2_sbp->fs_id)
{
gossip_err("perform_handle_checks: FSID did not match "
" (%d) instead of (%d)\n",
fsid, pvfs2_sbp->fs_id);
return 0;
}
gossip_debug(GOSSIP_UTILS_DEBUG, "perform_handle_checks : fsid = %d\n", fsid);
}
return 1;
}
/*
* convert an opaque handle to a PVFS_sys_attr structure so that we could
* call copy_attributes_to_inode() to initialize the VFS inode structure.
*/
static void convert_opaque_handle_to_sys_attr(
PVFS_sys_attr *dst, pvfs2_opaque_handle_t *src)
{
dst->owner = src->owner;
dst->group = src->group;
dst->perms = src->perms;
dst->atime = src->atime;
dst->mtime = src->mtime;
dst->ctime = src->ctime;
dst->size = src->size;
dst->link_target = NULL;
dst->dfile_count = 0;
dst->dirent_count = 0;
dst->objtype = src->objtype;
dst->mask = src->mask;
return;
}
static inline void do_decode_opaque_handle(pvfs2_opaque_handle_t *h, char *src)
{
char *ptr = src;
char **pptr = &ptr;
memset(h, 0, sizeof(pvfs2_opaque_handle_t));
/* Deserialize the buffer */
decode_pvfs2_opaque_handle_t(pptr, h);
return;
}
static int get_opaque_handle(struct super_block *sb,
const struct file_handle *fhandle,
pvfs2_opaque_handle_t *opaque_handle)
{
/* Make sure that we actually get a valid handle */
if (perform_handle_checks(fhandle,
HANDLE_CHECK_LENGTH | HANDLE_CHECK_MAGIC
| HANDLE_CHECK_FSID, sb) == 0)
{
gossip_err("get_handle: got invalid handle buffer!? "
"Impossible happened\n");
return -EINVAL;
}
do_decode_opaque_handle(opaque_handle, (char *) fhandle->fh_private);
/* make sure that fsid in private buffer also matches */
if (opaque_handle->fsid != PVFS2_SB(sb)->fs_id) {
gossip_err("get_handle: invalid fsid in private buffer "
" (%d) instead of (%d)\n",
opaque_handle->fsid, PVFS2_SB(sb)->fs_id);
return -EINVAL;
}
gossip_debug(GOSSIP_UTILS_DEBUG, "get_handle: decoded fsid %d handle %lu\n",
opaque_handle->fsid, (unsigned long) opaque_handle->handle);
return 0;
}
/*
* called by openfh() system call.
* Given a handle that ostensibly belongs to this PVFS2 superblock,
* we either find an inode
* in the icache already matching the given handle or we allocate
* and place a new struct inode in the icache and fill it up based on
* the buffer that we obtained from user. Presumably enough checks
* at the upper-level (VFS) has been done to make sure that this is
* indeed a buffer filled upon a successful openg().
* Returns ERR_PTR(-errno) in case of error
* valid pointer to struct inode in case it was a success
*/
struct inode *pvfs2_sb_find_inode_handle(struct super_block *sb,
const struct file_handle *fhandle)
{
struct inode *inode = NULL;
int err = 0;
pvfs2_opaque_handle_t opaque_handle;
PVFS_sys_attr attrs;
PVFS_object_ref ref;
/* Decode the buffer */
err = get_opaque_handle(sb, fhandle, &opaque_handle);
if (err)
return ERR_PTR(err);
/* and convert the opaque handle structure to the PVFS_sys_attr structure */
convert_opaque_handle_to_sys_attr(&attrs, &opaque_handle);
ref.handle = opaque_handle.handle;
ref.fs_id = opaque_handle.fsid;
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_sb_find_inode_handle: obtained inode number %llu\n",
llu(opaque_handle.handle));
/*
* NOTE: Locate the inode number in the icache if possible.
* If not allocate a new inode that is returned locked and
* hashed. Since, we don't issue a getattr/read_inode() callback
* the pvfs2 specific inode is almost guaranteed to be
* uninitialized or invalid. Therefore, we need to
* fill it up based on the information in opaque_handle!
* Consequently, this approach should scale well since openfh()
* does not require any network messages.
*/
inode = pvfs2_iget_locked(sb, &ref);
if (!inode) {
gossip_err("Could not allocate inode\n");
return ERR_PTR(-ENOMEM);
}
else {
if (is_bad_inode(inode)) {
iput(inode);
gossip_err("bad inode obtained from iget_locked\n");
return ERR_PTR(-EINVAL);
}
/* Initialize and/or verify struct inode as well as pvfs2_inode */
if ((err = copy_attributes_to_inode(inode, &attrs, NULL)) < 0) {
gossip_err("copy_attributes_to_inode failed with err %d\n", err);
iput(inode);
return ERR_PTR(err);
}
/* this inode was allocated afresh */
if (inode->i_state & I_NEW) {
pvfs2_inode_t *pvfs2_inode = PVFS2_I(inode);
pvfs2_inode_initialize(pvfs2_inode);
pvfs2_inode->refn.handle = opaque_handle.handle;
pvfs2_inode->refn.fs_id = opaque_handle.fsid;
inode->i_mapping->host = inode;
inode->i_rdev = 0;
inode->i_bdev = NULL;
inode->i_cdev = NULL;
inode->i_mapping->a_ops = &pvfs2_address_operations;
inode->i_mapping->backing_dev_info = &pvfs2_backing_dev_info;
/* Make sure that we unlock the inode */
unlock_new_inode(inode);
}
return inode;
}
}
#endif
#ifdef HAVE_FILL_HANDLE_INODE_OPERATIONS
/*
* dst would be encoded
*/
static int do_encode_opaque_handle(char *dst, struct inode *inode)
{
char *ptr = dst;
char **pptr = &ptr;
pvfs2_inode_t *pvfs2_inode = PVFS2_I(inode);
pvfs2_opaque_handle_t h;
/* only metafile allowed */
if (!S_ISREG(inode->i_mode))
return -EINVAL;
memset(&h, 0, sizeof(h));
h.handle = pvfs2_inode->refn.handle;
h.fsid = pvfs2_inode->refn.fs_id;
h.owner = inode->i_uid;
h.group = inode->i_gid;
h.perms = PVFS_util_translate_mode(inode->i_mode, 0);
h.mask |= PVFS_ATTR_SYS_PERM;
h.atime = pvfs2_convert_time_field(&inode->i_atime);
h.mtime = pvfs2_convert_time_field(&inode->i_mtime);
h.ctime = pvfs2_convert_time_field(&inode->i_ctime);
h.size = pvfs2_i_size_read(inode);
h.mask |= PVFS_ATTR_SYS_SIZE;
h.objtype = PVFS_TYPE_METAFILE;
/* Serialize into the buffer */
gossip_debug(GOSSIP_UTILS_DEBUG, "encoded fsid %d handle %lu\n",
h.fsid, (unsigned long) h.handle);
encode_pvfs2_opaque_handle_t(pptr, &h);
return 0;
}
static void *pvfs2_fh_ctor(void)
{
void *buf;
buf = kmalloc(sizeof(pvfs2_opaque_handle_t),
PVFS2_BUFMAP_GFP_FLAGS);
return buf;
}
static void pvfs2_fh_dtor(void *buf)
{
if (buf)
kfree(buf);
return;
}
/*
* This routine is called by openg() system call.
* Given an inode (which has been looked up previously),
* we fill in the attributes of the inode in an opaque buffer
* and hand it back to user.
* Note: We need to make it a fixed
* endian ordering so that it would work on all homogenous platforms.
* Hence the need to encode the handle buffer.
*/
int pvfs2_fill_handle(struct inode *inode, struct file_handle *fhandle)
{
size_t pvfs2_opaque_handle_size = sizeof(pvfs2_opaque_handle_t);
if (!inode || !fhandle)
{
return -EINVAL;
}
/* querying the size of PVFS2 specific opaque handle buffer */
if (fhandle->fh_private_length == 0)
{
fhandle->fh_private_length = pvfs2_opaque_handle_size;
return 0;
}
else if (fhandle->fh_private_length < pvfs2_opaque_handle_size)
{
return -ERANGE; /* too small a buffer length */
}
else
{
fhandle->fh_private = pvfs2_fh_ctor();
if (fhandle->fh_private == NULL)
{
return -ENOMEM;
}
/* encode the opaque handle information */
if (do_encode_opaque_handle((char *) fhandle->fh_private, inode) < 0)
{
pvfs2_fh_dtor(fhandle->fh_private);
fhandle->fh_private = NULL;
return -EINVAL;
}
/* Set a destructor function for the fh_private */
fhandle->fh_private_dtor = pvfs2_fh_dtor;
/* and the length */
fhandle->fh_private_length = pvfs2_opaque_handle_size;
gossip_debug(GOSSIP_UTILS_DEBUG, "Returning handle length %ld\n",
(unsigned long) pvfs2_opaque_handle_size);
return 0;
}
}
#endif /* HAVE_FILL_HANDLE_INODE_OPERATIONS */
#ifdef USE_MMAP_RA_CACHE
int pvfs2_flush_mmap_racache(struct inode *inode)
{
int ret = -EINVAL;
pvfs2_inode_t *pvfs2_inode = PVFS2_I(inode);
pvfs2_kernel_op_t *new_op = NULL;
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_flush_mmap_racache %llu: Handle is %llu "
"| fs_id %d\n", llu(get_handle_from_ino(inode)),
pvfs2_inode->refn.handle, pvfs2_inode->refn.fs_id);
new_op = op_alloc(PVFS2_VFS_OP_MMAP_RA_FLUSH);
if (!new_op)
{
return -ENOMEM;
}
new_op->upcall.req.ra_cache_flush.refn = pvfs2_inode->refn;
ret = service_operation(new_op, "pvfs2_flush_mmap_racache",
get_interruptible_flag(inode));
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_flush_mmap_racache got return "
"value of %d\n",ret);
op_release(new_op);
return ret;
}
#endif
int pvfs2_unmount_sb(struct super_block *sb)
{
int ret = -EINVAL;
pvfs2_kernel_op_t *new_op = NULL;
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_unmount_sb called on sb %p\n", sb);
new_op = op_alloc(PVFS2_VFS_OP_FS_UMOUNT);
if (!new_op)
{
return -ENOMEM;
}
new_op->upcall.req.fs_umount.id = PVFS2_SB(sb)->id;
new_op->upcall.req.fs_umount.fs_id = PVFS2_SB(sb)->fs_id;
strncpy(new_op->upcall.req.fs_umount.pvfs2_config_server,
PVFS2_SB(sb)->devname, PVFS_MAX_SERVER_ADDR_LEN);
gossip_debug(GOSSIP_UTILS_DEBUG, "Attempting PVFS2 Unmount via host %s\n",
new_op->upcall.req.fs_umount.pvfs2_config_server);
ret = service_operation(new_op, "pvfs2_fs_umount", 0);
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_unmount: got return value of %d\n", ret);
if (ret)
{
sb = ERR_PTR(ret);
}
else {
PVFS2_SB(sb)->mount_pending = 1;
}
op_release(new_op);
return ret;
}
/*
NOTE: on successful cancellation, be sure to return -EINTR, as
that's the return value the caller expects
*/
int pvfs2_cancel_op_in_progress(unsigned long tag)
{
int ret = -EINVAL;
pvfs2_kernel_op_t *new_op = NULL;
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_cancel_op_in_progress called on tag %lu\n", tag);
new_op = op_alloc(PVFS2_VFS_OP_CANCEL);
if (!new_op)
{
return -ENOMEM;
}
new_op->upcall.req.cancel.op_tag = tag;
gossip_debug(GOSSIP_UTILS_DEBUG, "Attempting PVFS2 operation cancellation of tag %llu\n",
llu(new_op->upcall.req.cancel.op_tag));
ret = service_operation(new_op, "pvfs2_cancel", PVFS2_OP_CANCELLATION);
gossip_debug(GOSSIP_UTILS_DEBUG, "pvfs2_cancel_op_in_progress: got return "
"value of %d\n", ret);
op_release(new_op);
return (ret);
}
void pvfs2_inode_initialize(pvfs2_inode_t *pvfs2_inode)
{
if (!InitFlag(pvfs2_inode))
{
pvfs2_inode->refn.handle = PVFS_HANDLE_NULL;
pvfs2_inode->refn.fs_id = PVFS_FS_ID_NULL;
pvfs2_inode->last_failed_block_index_read = 0;
memset(pvfs2_inode->link_target, 0, sizeof(pvfs2_inode->link_target));
pvfs2_inode->error_code = 0;
SetInitFlag(pvfs2_inode);
}
}
/*
this is called from super:pvfs2_destroy_inode.
*/
void pvfs2_inode_finalize(pvfs2_inode_t *pvfs2_inode)
{
pvfs2_inode->refn.handle = PVFS_HANDLE_NULL;
pvfs2_inode->refn.fs_id = PVFS_FS_ID_NULL;
pvfs2_inode->last_failed_block_index_read = 0;
pvfs2_inode->error_code = 0;
}
void pvfs2_op_initialize(pvfs2_kernel_op_t *op)
{
op->io_completed = 0;
op->upcall.type = PVFS2_VFS_OP_INVALID;
op->downcall.type = PVFS2_VFS_OP_INVALID;
op->downcall.status = -1;
op->op_state = OP_VFS_STATE_UNKNOWN;
op->tag = 0;
}
void pvfs2_make_bad_inode(struct inode *inode)
{
if (is_root_handle(inode))
{
/*
if this occurs, the pvfs2-client-core was killed but we
can't afford to lose the inode operations and such
associated with the root handle in any case
*/
gossip_debug(GOSSIP_UTILS_DEBUG, "*** NOT making bad root inode %llu\n", llu(get_handle_from_ino(inode)));
}
else
{
gossip_debug(GOSSIP_UTILS_DEBUG, "*** making bad inode %llu\n", llu(get_handle_from_ino(inode)));
make_bad_inode(inode);
}
}
/* this code is based on linux/net/sunrpc/clnt.c:rpc_clnt_sigmask */
void mask_blocked_signals(sigset_t *orig_sigset)
{
unsigned long sigallow = sigmask(SIGKILL);
unsigned long irqflags = 0;
struct k_sigaction *action = pvfs2_current_sigaction;
sigallow |= ((action[SIGINT-1].sa.sa_handler == SIG_DFL) ?
sigmask(SIGINT) : 0);
sigallow |= ((action[SIGQUIT-1].sa.sa_handler == SIG_DFL) ?
sigmask(SIGQUIT) : 0);
spin_lock_irqsave(&pvfs2_current_signal_lock, irqflags);
*orig_sigset = current->blocked;
siginitsetinv(¤t->blocked, sigallow & ~orig_sigset->sig[0]);
pvfs2_recalc_sigpending();
spin_unlock_irqrestore(&pvfs2_current_signal_lock, irqflags);
}
/* this code is based on linux/net/sunrpc/clnt.c:rpc_clnt_sigunmask */
void unmask_blocked_signals(sigset_t *orig_sigset)
{
unsigned long irqflags = 0;
spin_lock_irqsave(&pvfs2_current_signal_lock, irqflags);
current->blocked = *orig_sigset;
pvfs2_recalc_sigpending();
spin_unlock_irqrestore(&pvfs2_current_signal_lock, irqflags);
}
PVFS_time pvfs2_convert_time_field(void *time_ptr)
{
PVFS_time pvfs2_time;
#ifdef PVFS2_LINUX_KERNEL_2_4
pvfs2_time = (PVFS_time)(*(time_t *)time_ptr);
#else
struct timespec *tspec = (struct timespec *)time_ptr;
pvfs2_time = (PVFS_time)((time_t)tspec->tv_sec);
#endif
return pvfs2_time;
}
/* macro defined in include/pvfs2-types.h */
DECLARE_ERRNO_MAPPING_AND_FN();
int pvfs2_normalize_to_errno(PVFS_error error_code)
{
if(error_code > 0)
{
gossip_err("pvfs2: error status receieved.\n");
gossip_err("pvfs2: assuming error code is inverted.\n");
error_code = -error_code;
}
/* convert any error codes that are in pvfs2 format */
if(IS_PVFS_NON_ERRNO_ERROR(-error_code))
{
if(PVFS_NON_ERRNO_ERROR_CODE(-error_code) == PVFS_ECANCEL)
{
/* cancellation error codes generally correspond to a timeout
* from the client's perspective
*/
error_code = -ETIMEDOUT;
}
else
{
/* assume a default error code */
gossip_err("pvfs2: warning: "
"got error code without errno equivalent: %d.\n", error_code);
error_code = -EINVAL;
}
}
else if(IS_PVFS_ERROR(-error_code))
{
error_code = -PVFS_ERROR_TO_ERRNO(-error_code);
}
return(error_code);
}
int32_t PVFS_util_translate_mode(int mode, int suid)
{
int ret = 0, i = 0;
#define NUM_MODES 11
static int modes[NUM_MODES] =
{
S_IXOTH, S_IWOTH, S_IROTH,
S_IXGRP, S_IWGRP, S_IRGRP,
S_IXUSR, S_IWUSR, S_IRUSR,
S_ISGID, S_ISUID
};
static int pvfs2_modes[NUM_MODES] =
{
PVFS_O_EXECUTE, PVFS_O_WRITE, PVFS_O_READ,
PVFS_G_EXECUTE, PVFS_G_WRITE, PVFS_G_READ,
PVFS_U_EXECUTE, PVFS_U_WRITE, PVFS_U_READ,
PVFS_G_SGID, PVFS_U_SUID
};
for(i = 0; i < NUM_MODES; i++)
{
if (mode & modes[i])
{
ret |= pvfs2_modes[i];
}
}
if (suid == 0 && (ret & PVFS_U_SUID))
{
ret &= ~PVFS_U_SUID;
}
return ret;
#undef NUM_MODES
}
/*
* Local variables:
* c-indent-level: 4
* c-basic-offset: 4
* End:
*
* vim: ts=8 sts=4 sw=4 expandtab
*/
| Goon83/SALB | src/kernel/linux-2.6/pvfs2-utils.c | C | lgpl-2.1 | 70,100 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "bytearrayinputstream.h"
#include <ctype.h>
namespace Debugger {
namespace Internal {
ByteArrayInputStream::ByteArrayInputStream(QByteArray &ba) :
m_target(ba), m_integerBase(10), m_hexPrefix(false), m_width(0)
{
}
void ByteArrayInputStream::appendSeparator(char c)
{
if (!m_target.isEmpty() && !m_target.endsWith(c))
m_target.append(c);
}
void hexPrefixOn(ByteArrayInputStream &bs)
{
bs.setHexPrefix(true);
}
void hexPrefixOff(ByteArrayInputStream &bs)
{
bs.setHexPrefix(false);
}
void hex(ByteArrayInputStream &bs)
{
bs.setIntegerBase(16);
}
void dec(ByteArrayInputStream &bs)
{
bs.setIntegerBase(10);
}
void blankSeparator(ByteArrayInputStream &bs)
{
bs.appendSeparator();
}
QByteArray trimFront(QByteArray in)
{
if (in.isEmpty())
return in;
const int size = in.size();
int pos = 0;
for ( ; pos < size && isspace(in.at(pos)); pos++) ;
if (pos)
in.remove(0, pos);
return in;
}
QByteArray trimBack(QByteArray in)
{
if (in.isEmpty())
return in;
const int size = in.size();
int pos = size - 1;
for ( ; pos >= 0 && isspace(in.at(pos)); pos--) ;
if (pos != size - 1)
in.truncate(pos + 1);
return in;
}
// Simplify: replace tabs, find all occurrences
// of 2 blanks, check further up for blanks and remove that bit.
QByteArray simplify(const QByteArray &inIn)
{
if (inIn.isEmpty())
return inIn;
QByteArray in = trimFront(trimBack(inIn));
in.replace('\t', ' ');
in.replace('\n', ' ');
in.replace('\r', ' ');
const QByteArray twoBlanks = " ";
while (true) {
const int pos = in.indexOf(twoBlanks);
if (pos != -1) {
const int size = in.size();
int endPos = pos + twoBlanks.size();
for ( ; endPos < size && in.at(endPos) == ' '; endPos++) ;
in.remove(pos + 1, endPos - pos - 1);
} else {
break;
}
}
return in;
}
} // namespace Internal
} // namespace Debugger
| farseerri/git_code | src/plugins/debugger/cdb/bytearrayinputstream.cpp | C++ | lgpl-2.1 | 3,544 |
// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh/side.h"
#include "libmesh/cell_pyramid5.h"
#include "libmesh/edge_edge2.h"
#include "libmesh/face_tri3.h"
#include "libmesh/face_quad4.h"
namespace libMesh
{
// ------------------------------------------------------------
// Pyramid5 class static member initializations
const unsigned int Pyramid5::side_nodes_map[5][4] =
{
{0, 1, 4, 99}, // Side 0
{1, 2, 4, 99}, // Side 1
{2, 3, 4, 99}, // Side 2
{3, 0, 4, 99}, // Side 3
{0, 3, 2, 1} // Side 4
};
const unsigned int Pyramid5::edge_nodes_map[8][2] =
{
{0, 1}, // Side 0
{1, 2}, // Side 1
{2, 3}, // Side 2
{0, 3}, // Side 3
{0, 4}, // Side 4
{1, 4}, // Side 5
{2, 4}, // Side 6
{3, 4} // Side 7
};
// ------------------------------------------------------------
// Pyramid5 class member functions
bool Pyramid5::is_vertex(const unsigned int) const
{
return true;
}
bool Pyramid5::is_edge(const unsigned int) const
{
return false;
}
bool Pyramid5::is_face(const unsigned int) const
{
return false;
}
bool Pyramid5::is_node_on_side(const unsigned int n,
const unsigned int s) const
{
libmesh_assert_less (s, n_sides());
for (unsigned int i = 0; i != 4; ++i)
if (side_nodes_map[s][i] == n)
return true;
return false;
}
bool Pyramid5::is_node_on_edge(const unsigned int n,
const unsigned int e) const
{
libmesh_assert_less (e, n_edges());
for (unsigned int i = 0; i != 2; ++i)
if (edge_nodes_map[e][i] == n)
return true;
return false;
}
bool Pyramid5::has_affine_map() const
{
// Point v = this->point(3) - this->point(0);
// return (v.relative_fuzzy_equals(this->point(2) - this->point(1)));
return false;
}
UniquePtr<Elem> Pyramid5::build_side_ptr (const unsigned int i,
bool proxy)
{
libmesh_assert_less (i, this->n_sides());
if (proxy)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
return UniquePtr<Elem>(new Side<Tri3,Pyramid5>(this,i));
case 4:
return UniquePtr<Elem>(new Side<Quad4,Pyramid5>(this,i));
default:
libmesh_error_msg("Invalid side i = " << i);
}
}
else
{
// Create NULL pointer to be initialized, returned later.
Elem * face = libmesh_nullptr;
switch (i)
{
case 0: // triangular face 1
case 1: // triangular face 2
case 2: // triangular face 3
case 3: // triangular face 4
{
face = new Tri3;
break;
}
case 4: // the quad face at z=0
{
face = new Quad4;
break;
}
default:
libmesh_error_msg("Invalid side i = " << i);
}
face->subdomain_id() = this->subdomain_id();
// Set the nodes
for (unsigned n=0; n<face->n_nodes(); ++n)
face->set_node(n) = this->node_ptr(Pyramid5::side_nodes_map[i][n]);
return UniquePtr<Elem>(face);
}
libmesh_error_msg("We'll never get here!");
return UniquePtr<Elem>();
}
UniquePtr<Elem> Pyramid5::build_edge_ptr (const unsigned int i)
{
libmesh_assert_less (i, this->n_edges());
return UniquePtr<Elem>(new SideEdge<Edge2,Pyramid5>(this,i));
}
void Pyramid5::connectivity(const unsigned int libmesh_dbg_var(sc),
const IOPackage iop,
std::vector<dof_id_type> & conn) const
{
libmesh_assert(_nodes);
libmesh_assert_less (sc, this->n_sub_elem());
libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);
switch (iop)
{
case TECPLOT:
{
conn.resize(8);
conn[0] = this->node_id(0)+1;
conn[1] = this->node_id(1)+1;
conn[2] = this->node_id(2)+1;
conn[3] = this->node_id(3)+1;
conn[4] = this->node_id(4)+1;
conn[5] = this->node_id(4)+1;
conn[6] = this->node_id(4)+1;
conn[7] = this->node_id(4)+1;
return;
}
case VTK:
{
conn.resize(5);
conn[0] = this->node_id(3);
conn[1] = this->node_id(2);
conn[2] = this->node_id(1);
conn[3] = this->node_id(0);
conn[4] = this->node_id(4);
return;
}
default:
libmesh_error_msg("Unsupported IO package " << iop);
}
}
Real Pyramid5::volume () const
{
// The pyramid with a bilinear base has volume given by the
// formula in: "Calculation of the Volume of a General Hexahedron
// for Flow Predictions", AIAA Journal v.23, no.6, 1984, p.954-
Point
x0 = point(0), x1 = point(1), x2 = point(2),
x3 = point(3), x4 = point(4);
// Construct various edge and diagonal vectors.
Point v40 = x0 - x4;
Point v13 = x3 - x1;
Point v02 = x2 - x0;
Point v03 = x3 - x0;
Point v01 = x1 - x0;
// Finally, ready to return the volume!
return
triple_product(v40, v13, v02) / 6. +
triple_product(v02, v01, v03) / 12.;
}
} // namespace libMesh
| aeslaughter/libmesh | src/geom/cell_pyramid5.C | C++ | lgpl-2.1 | 5,928 |
/* Тема оформления "Зеленый стандарт" */
/* Плагин RECALL */
/* WA-PRO, 2014 */
/* Контейнер окна запроса */
#recall_plugin
{
width: 450px;
font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
-webkit-box-shadow: 0px 1px 5px 0px rgba(50, 50, 50, 0.75);
-moz-box-shadow: 0px 1px 5px 0px rgba(50, 50, 50, 0.75);
box-shadow: 0px 1px 5px 0px rgba(50, 50, 50, 0.75);
}
/* Шапка окна запроса */
#recall_plugin .recall_hat
{
line-height: 30px;
height: 30px;
background: url('./img/hat.png');
color: #ffe;
padding-left: 10px;
font-size: 1.4em;
font-weight: normal;
text-shadow: 0 1px 1px rgba(0,0,0,0.5);
border-bottom: 1px solid rgba(0,0,0,0.1);
}
/* Кнопка закрытия */
#recall_plugin .recall_close
{
width: 30px;
height: 30px;
float: right;
background: url('./img/close.png');
cursor: pointer;
}
#recall_plugin .recall_close:hover
{
background: url('./img/close_hover.png');
}
/* Рабочая область */
#recall_plugin .recall_body
{
background: white;
position: relative;
box-sizing: border-box;
padding: 15px;
padding-top: 10px;
padding-bottom: 30px;
}
/* Картинка в верхней части рабочей области */
#recall_plugin .recall_header
{
position: absolute;
top: 0px;
left: 0px;
background: url('./img/header.png');
height: 30px;
width: 450px;
}
/* Заголовок рабочей области */
#recall_plugin .recall_disclaimer
{
font-size: 1.2em;
font-weight: bold;
text-align: center;
margin-bottom: 10px;
}
/* Информационное поле (описание и значение) */
#recall_plugin .recall_field
{
clear: both;
margin: 0;
padding-top: 3px;
}
/* Описание поля */
#recall_plugin .recall_name
{
float: left;
width: 220px;
padding-top: 0.05em;
padding-bottom: 10px;
font-size: 0.95em;
color: #888;
}
/* Значение поля */
#recall_plugin .recall_value
{
margin-left: 220px;
margin-bottom: 5px;
position: relative;
}
/* Значение поля c кратким описанием вопроса */
#recall_plugin .recall_value_textarea
{
margin-left: 0px;
}
/* Значения дополнительных полей */
/* Тип RANGE */
#recall_plugin .recall_field_extra_range input
{
width: 93px;
}
/* Тип CHECKBOX */
#recall_plugin .recall_field_extra_checkbox .recall_value_checkbox
{
margin-bottom: 3px;
}
#recall_plugin .recall_field_extra_checkbox .recall_value_checkbox_val
{
display: inline-block;
vertical-align: top;
margin-top: -2px;
margin-left: 5px;
}
/* Тип SELECT */
#recall_plugin .recall_field_extra_select select
{
box-sizing: border-box;
width: 198px;
}
/* Стили элементов textarea в форме запроса */
#recall_plugin .recall_textarea
{
width: 418px;
height: 120px;
resize: none;
border: 1px solid #a9a9a9;
box-sizing: border-box;
}
/* Стили элементов input в форме запроса */
#recall_plugin .recall_input_text
{
width: 198px;
border: 1px solid #a9a9a9;
box-sizing: border-box;
padding-left: 5px;
background: white;
height: 20px;
}
/* Картинка в нижней части рабочей области */
#recall_plugin .recall_footer
{
position: absolute;
bottom: 0px;
left: 0px;
background: url('./img/footer.png');
height: 30px;
width: 450px;
}
/* Кнопка отправки запроса */
#recall_plugin .recall_submit
{
font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 1.1em;
background: #fcd630;
color: #000;
outline: 0;
padding: 4px 7px;
border: 1px solid rgba(0,0,0,0.3);
border-color: rgba(0,0,0,0.2) rgba(0,0,0,0.3) rgba(0,0,0,0.3) rgba(0,0,0,0.3);
-webkit-appearance: none;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
border-radius: 3px;
text-shadow: 0 1px 0px rgba(255,255,255,0.5);
background: #fcd630 -moz-linear-gradient(top, rgba(255,255,255,0.5) 0%, rgba(255,255,255,0.0) 100%);
background: #fcd630 -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,0.5)), color-stop(100%,rgba(255,255,255,0.0)));
background: #fcd630 -webkit-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.0) 100%);
background: #fcd630 -o-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.0) 100%);
background: #fcd630 -ms-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.0) 100%);
background: #fcd630 linear-gradient(to bottom, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.0) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fde992', endColorstr='#fcd630',GradientType=0 );
}
#recall_plugin .recall_submit:hover
{
cursor: pointer;
background: #fcd630 linear-gradient(to bottom, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.3) 100%);
}
/* Текст ошибки ввода */
#recall_plugin .recall_error
{
clear: both;
text-align: center;
margin-bottom: 10px;
color: red;
font-style: italic;
}
/* Контейнер сообщения об успешной отправке */
#recall_plugin .recall_success_container
{
display:none;
}
/* Сообщение об успешной отправке */
#recall_plugin .recall_success
{
color: #499756;
text-align: center;
font-weight: bold;
margin-bottom: 50px;
margin-top: 20px;
}
/* Ярлык вызова окна */
.recall_deploy_window
{
width: 30px;
height: 150px;
position: fixed;
top: 100px;
right: 0px;
cursor: pointer;
background: url('./img/label.png');
z-index: 9999;
}
/* Фон затенения страницы */
.b-modal
{
background-color: #efe !important;
}
/* Кнопка отправки "Спросить о товаре" */
.recall_ask_about_the_product
{
background: #fcd630;
color: #000;
outline: 0;
padding: 4px 7px;
font-size: 1.1em;
border: 1px solid rgba(0,0,0,0.3);
border-color: rgba(0,0,0,0.2) rgba(0,0,0,0.3) rgba(0,0,0,0.3) rgba(0,0,0,0.3);
-webkit-appearance: none;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
border-radius: 3px;
text-shadow: 0 1px 0px rgba(255,255,255,0.5);
background: #fcd630 -moz-linear-gradient(top, rgba(255,255,255,0.5) 0%, rgba(255,255,255,0.0) 100%);
background: #fcd630 -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,0.5)), color-stop(100%,rgba(255,255,255,0.0)));
background: #fcd630 -webkit-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.0) 100%);
background: #fcd630 -o-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.0) 100%);
background: #fcd630 -ms-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.0) 100%);
background: #fcd630 linear-gradient(to bottom, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.0) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fde992', endColorstr='#fcd630',GradientType=0 );
}
.recall_ask_about_the_product:hover
{
cursor: pointer;
background: #fcd630 linear-gradient(to bottom, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0.3) 100%);
}
#recall_plugin .wa-captcha-refresh
{
font-size: 13px;
color: #a9a9a9;
}
#recall_plugin .wa-captcha input
{
display: inline-block;
vertical-align: top;
margin-top: 10px;
border: 1px solid #a9a9a9;
outline: none;
}
#recall_plugin .wa-captcha strong
{
display: inline-block;
vertical-align: top;
margin-top: 10px;
} | situxe/carotics | wa-data/public/shop/plugins/recall/themes/default20/theme_default.css | CSS | lgpl-3.0 | 7,391 |
<?php
class siteRoutingDeleteController extends waJsonController
{
public function execute()
{
$domain = siteHelper::getDomain();
$routes = wa()->getRouting()->getRoutes($domain);
$route_id = waRequest::post('route');
if (isset($routes[$route_id])) {
if (isset($routes[$route_id]['app'])) {
$robots = new siteRobots($domain);
$robots->delete($routes[$route_id]['app'], $routes[$route_id]['url']);
}
unset($routes[$route_id]);
// save
$path = $this->getConfig()->getPath('config', 'routing');
$all_routes = file_exists($path) ? include($path) : array();
$all_routes[$domain] = $routes;
waUtils::varExportToFile($all_routes, $path);
$this->log('route_delete');
}
}
} | dmitriyzhdankin/avantmarketcom | wa-apps/site/lib/actions/routing/siteRoutingDelete.controller.php | PHP | lgpl-3.0 | 867 |
<?php
namespace Swoole\Cache;
use Swoole;
/**
* 使用Redis作为Cache
* Class Redis
*
* @package Swoole\Cache
*/
class Redis implements Swoole\IFace\Cache
{
protected $config;
protected $redis;
function __construct($config)
{
if (empty($config['redis_id']))
{
$config['redis_id'] = 'master';
}
$this->config = $config;
$this->redis = \Swoole::$php->redis($config['redis_id']);
}
/**
* 设置缓存
* @param $key
* @param $value
* @param $expire
* @return bool
*/
function set($key, $value, $expire = 0)
{
if ($expire <= 0)
{
$expire = 0x7fffffff;
}
return $this->redis->setex($key, $expire, serialize($value));
}
/**
* 获取缓存值
* @param $key
* @return mixed
*/
function get($key)
{
return unserialize($this->redis->get($key));
}
/**
* 删除缓存值
* @param $key
* @return bool
*/
function delete($key)
{
return $this->redis->del($key);
}
}
| naryn/swoole_lottery | libs/Swoole/Cache/Redis.php | PHP | lgpl-3.0 | 1,111 |
// Copyright (C) 2000, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#ifndef OsiCollections_H
#define OsiCollections_H
#include <vector>
//Forward declarations
class OsiColCut;
class OsiRowCut;
class OsiCut;
/* Collection Classes */
/**@name Typedefs for Standard Template Library collections of Osi Objects. */
//@{
/// Vector of int
typedef std::vector<int> OsiVectorInt;
/// Vector of double
typedef std::vector<double> OsiVectorDouble;
/// Vector of OsiColCut pointers
typedef std::vector<OsiColCut *> OsiVectorColCutPtr;
/// Vector of OsiRowCut pointers
typedef std::vector<OsiRowCut *> OsiVectorRowCutPtr;
/// Vector of OsiCut pointers
typedef std::vector<OsiCut *> OsiVectorCutPtr;
//@}
#endif
| tulip5/tulip | thirdparty/OGDF/include/coin/OsiCollections.hpp | C++ | lgpl-3.0 | 865 |
# -*- coding: utf-8 -*-
"""
pygments.lexers._mapping
~~~~~~~~~~~~~~~~~~~~~~~~
Lexer mapping defintions. This file is generated by itself. Everytime
you change something on a builtin lexer defintion, run this script from
the lexers folder to update it.
Do not alter the LEXERS dictionary by hand.
:copyright: Copyright 2006-2009 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
LEXERS = {
'ABAPLexer': ('pygments.lexers.other', 'ABAP', ('abap',), ('*.abap',), ('text/x-abap',)),
'ActionScript3Lexer': ('pygments.lexers.web', 'ActionScript 3', ('as3', 'actionscript3'), ('*.as',), ('application/x-actionscript', 'text/x-actionscript', 'text/actionscript')),
'ActionScriptLexer': ('pygments.lexers.web', 'ActionScript', ('as', 'actionscript'), ('*.as',), ('application/x-actionscript', 'text/x-actionscript', 'text/actionscript')),
'AntlrActionScriptLexer': ('pygments.lexers.parsers', 'ANTLR With ActionScript Target', ('antlr-as', 'antlr-actionscript'), ('*.G', '*.g'), ()),
'AntlrCSharpLexer': ('pygments.lexers.parsers', 'ANTLR With C# Target', ('antlr-csharp', 'antlr-c#'), ('*.G', '*.g'), ()),
'AntlrCppLexer': ('pygments.lexers.parsers', 'ANTLR With CPP Target', ('antlr-cpp',), ('*.G', '*.g'), ()),
'AntlrJavaLexer': ('pygments.lexers.parsers', 'ANTLR With Java Target', ('antlr-java',), ('*.G', '*.g'), ()),
'AntlrLexer': ('pygments.lexers.parsers', 'ANTLR', ('antlr',), (), ()),
'AntlrObjectiveCLexer': ('pygments.lexers.parsers', 'ANTLR With ObjectiveC Target', ('antlr-objc',), ('*.G', '*.g'), ()),
'AntlrPerlLexer': ('pygments.lexers.parsers', 'ANTLR With Perl Target', ('antlr-perl',), ('*.G', '*.g'), ()),
'AntlrPythonLexer': ('pygments.lexers.parsers', 'ANTLR With Python Target', ('antlr-python',), ('*.G', '*.g'), ()),
'AntlrRubyLexer': ('pygments.lexers.parsers', 'ANTLR With Ruby Target', ('antlr-ruby', 'antlr-rb'), ('*.G', '*.g'), ()),
'ApacheConfLexer': ('pygments.lexers.text', 'ApacheConf', ('apacheconf', 'aconf', 'apache'), ('.htaccess', 'apache.conf', 'apache2.conf'), ('text/x-apacheconf',)),
'AppleScriptLexer': ('pygments.lexers.other', 'AppleScript', ('applescript',), ('*.applescript',), ()),
'BBCodeLexer': ('pygments.lexers.text', 'BBCode', ('bbcode',), (), ('text/x-bbcode',)),
'BaseMakefileLexer': ('pygments.lexers.text', 'Makefile', ('basemake',), (), ()),
'BashLexer': ('pygments.lexers.other', 'Bash', ('bash', 'sh'), ('*.sh', '*.ebuild', '*.eclass'), ('application/x-sh', 'application/x-shellscript')),
'BashSessionLexer': ('pygments.lexers.other', 'Bash Session', ('console',), ('*.sh-session',), ('application/x-shell-session',)),
'BatchLexer': ('pygments.lexers.other', 'Batchfile', ('bat',), ('*.bat', '*.cmd'), ('application/x-dos-batch',)),
'BefungeLexer': ('pygments.lexers.other', 'Befunge', ('befunge',), ('*.befunge',), ('application/x-befunge',)),
'BooLexer': ('pygments.lexers.dotnet', 'Boo', ('boo',), ('*.boo',), ('text/x-boo',)),
'BrainfuckLexer': ('pygments.lexers.other', 'Brainfuck', ('brainfuck', 'bf'), ('*.bf', '*.b'), ('application/x-brainfuck',)),
'CLexer': ('pygments.lexers.compiled', 'C', ('c',), ('*.c', '*.h'), ('text/x-chdr', 'text/x-csrc')),
'CObjdumpLexer': ('pygments.lexers.asm', 'c-objdump', ('c-objdump',), ('*.c-objdump',), ('text/x-c-objdump',)),
'CSharpAspxLexer': ('pygments.lexers.dotnet', 'aspx-cs', ('aspx-cs',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()),
'CSharpLexer': ('pygments.lexers.dotnet', 'C#', ('csharp', 'c#'), ('*.cs',), ('text/x-csharp',)),
'CheetahHtmlLexer': ('pygments.lexers.templates', 'HTML+Cheetah', ('html+cheetah', 'html+spitfire'), (), ('text/html+cheetah', 'text/html+spitfire')),
'CheetahJavascriptLexer': ('pygments.lexers.templates', 'JavaScript+Cheetah', ('js+cheetah', 'javascript+cheetah', 'js+spitfire', 'javascript+spitfire'), (), ('application/x-javascript+cheetah', 'text/x-javascript+cheetah', 'text/javascript+cheetah', 'application/x-javascript+spitfire', 'text/x-javascript+spitfire', 'text/javascript+spitfire')),
'CheetahLexer': ('pygments.lexers.templates', 'Cheetah', ('cheetah', 'spitfire'), ('*.tmpl', '*.spt'), ('application/x-cheetah', 'application/x-spitfire')),
'CheetahXmlLexer': ('pygments.lexers.templates', 'XML+Cheetah', ('xml+cheetah', 'xml+spitfire'), (), ('application/xml+cheetah', 'application/xml+spitfire')),
'ClojureLexer': ('pygments.lexers.agile', 'Clojure', ('clojure', 'clj'), ('*.clj',), ('text/x-clojure', 'application/x-clojure')),
'CommonLispLexer': ('pygments.lexers.functional', 'Common Lisp', ('common-lisp', 'cl'), ('*.cl', '*.lisp', '*.el'), ('text/x-common-lisp',)),
'CppLexer': ('pygments.lexers.compiled', 'C++', ('cpp', 'c++'), ('*.cpp', '*.hpp', '*.c++', '*.h++', '*.cc', '*.hh', '*.cxx', '*.hxx'), ('text/x-c++hdr', 'text/x-c++src')),
'CppObjdumpLexer': ('pygments.lexers.asm', 'cpp-objdump', ('cpp-objdump', 'c++-objdumb', 'cxx-objdump'), ('*.cpp-objdump', '*.c++-objdump', '*.cxx-objdump'), ('text/x-cpp-objdump',)),
'CssDjangoLexer': ('pygments.lexers.templates', 'CSS+Django/Jinja', ('css+django', 'css+jinja'), (), ('text/css+django', 'text/css+jinja')),
'CssErbLexer': ('pygments.lexers.templates', 'CSS+Ruby', ('css+erb', 'css+ruby'), (), ('text/css+ruby',)),
'CssGenshiLexer': ('pygments.lexers.templates', 'CSS+Genshi Text', ('css+genshitext', 'css+genshi'), (), ('text/css+genshi',)),
'CssLexer': ('pygments.lexers.web', 'CSS', ('css',), ('*.css',), ('text/css',)),
'CssPhpLexer': ('pygments.lexers.templates', 'CSS+PHP', ('css+php',), (), ('text/css+php',)),
'CssSmartyLexer': ('pygments.lexers.templates', 'CSS+Smarty', ('css+smarty',), (), ('text/css+smarty',)),
'CythonLexer': ('pygments.lexers.compiled', 'Cython', ('cython', 'pyx'), ('*.pyx', '*.pxd', '*.pxi'), ('text/x-cython', 'application/x-cython')),
'DLexer': ('pygments.lexers.compiled', 'D', ('d',), ('*.d', '*.di'), ('text/x-dsrc',)),
'DObjdumpLexer': ('pygments.lexers.asm', 'd-objdump', ('d-objdump',), ('*.d-objdump',), ('text/x-d-objdump',)),
'DarcsPatchLexer': ('pygments.lexers.text', 'Darcs Patch', ('dpatch',), ('*.dpatch', '*.darcspatch'), ()),
'DebianControlLexer': ('pygments.lexers.text', 'Debian Control file', ('control',), ('control',), ()),
'DelphiLexer': ('pygments.lexers.compiled', 'Delphi', ('delphi', 'pas', 'pascal', 'objectpascal'), ('*.pas',), ('text/x-pascal',)),
'DiffLexer': ('pygments.lexers.text', 'Diff', ('diff', 'udiff'), ('*.diff', '*.patch'), ('text/x-diff', 'text/x-patch')),
'DjangoLexer': ('pygments.lexers.templates', 'Django/Jinja', ('django', 'jinja'), (), ('application/x-django-templating', 'application/x-jinja')),
'DylanLexer': ('pygments.lexers.compiled', 'Dylan', ('dylan',), ('*.dylan',), ('text/x-dylan',)),
'ErbLexer': ('pygments.lexers.templates', 'ERB', ('erb',), (), ('application/x-ruby-templating',)),
'ErlangLexer': ('pygments.lexers.functional', 'Erlang', ('erlang',), ('*.erl', '*.hrl'), ('text/x-erlang',)),
'ErlangShellLexer': ('pygments.lexers.functional', 'Erlang erl session', ('erl',), ('*.erl-sh',), ('text/x-erl-shellsession',)),
'EvoqueHtmlLexer': ('pygments.lexers.templates', 'HTML+Evoque', ('html+evoque',), ('*.html',), ('text/html+evoque',)),
'EvoqueLexer': ('pygments.lexers.templates', 'Evoque', ('evoque',), ('*.evoque',), ('application/x-evoque',)),
'EvoqueXmlLexer': ('pygments.lexers.templates', 'XML+Evoque', ('xml+evoque',), ('*.xml',), ('application/xml+evoque',)),
'FortranLexer': ('pygments.lexers.compiled', 'Fortran', ('fortran',), ('*.f', '*.f90'), ('text/x-fortran',)),
'GLShaderLexer': ('pygments.lexers.compiled', 'GLSL', ('glsl',), ('*.vert', '*.frag', '*.geo'), ('text/x-glslsrc',)),
'GasLexer': ('pygments.lexers.asm', 'GAS', ('gas',), ('*.s', '*.S'), ('text/x-gas',)),
'GenshiLexer': ('pygments.lexers.templates', 'Genshi', ('genshi', 'kid', 'xml+genshi', 'xml+kid'), ('*.kid',), ('application/x-genshi', 'application/x-kid')),
'GenshiTextLexer': ('pygments.lexers.templates', 'Genshi Text', ('genshitext',), (), ('application/x-genshi-text', 'text/x-genshi')),
'GettextLexer': ('pygments.lexers.text', 'Gettext Catalog', ('pot', 'po'), ('*.pot', '*.po'), ('application/x-gettext', 'text/x-gettext', 'text/gettext')),
'GnuplotLexer': ('pygments.lexers.other', 'Gnuplot', ('gnuplot',), ('*.plot', '*.plt'), ('text/x-gnuplot',)),
'GroffLexer': ('pygments.lexers.text', 'Groff', ('groff', 'nroff', 'man'), ('*.[1234567]', '*.man'), ('application/x-troff', 'text/troff')),
'HaskellLexer': ('pygments.lexers.functional', 'Haskell', ('haskell', 'hs'), ('*.hs',), ('text/x-haskell',)),
'HtmlDjangoLexer': ('pygments.lexers.templates', 'HTML+Django/Jinja', ('html+django', 'html+jinja'), (), ('text/html+django', 'text/html+jinja')),
'HtmlGenshiLexer': ('pygments.lexers.templates', 'HTML+Genshi', ('html+genshi', 'html+kid'), (), ('text/html+genshi',)),
'HtmlLexer': ('pygments.lexers.web', 'HTML', ('html',), ('*.html', '*.htm', '*.xhtml', '*.xslt'), ('text/html', 'application/xhtml+xml')),
'HtmlPhpLexer': ('pygments.lexers.templates', 'HTML+PHP', ('html+php',), ('*.phtml',), ('application/x-php', 'application/x-httpd-php', 'application/x-httpd-php3', 'application/x-httpd-php4', 'application/x-httpd-php5')),
'HtmlSmartyLexer': ('pygments.lexers.templates', 'HTML+Smarty', ('html+smarty',), (), ('text/html+smarty',)),
'IniLexer': ('pygments.lexers.text', 'INI', ('ini', 'cfg'), ('*.ini', '*.cfg', '*.properties'), ('text/x-ini',)),
'IoLexer': ('pygments.lexers.agile', 'Io', ('io',), ('*.io',), ('text/x-iosrc',)),
'IrcLogsLexer': ('pygments.lexers.text', 'IRC logs', ('irc',), ('*.weechatlog',), ('text/x-irclog',)),
'JavaLexer': ('pygments.lexers.compiled', 'Java', ('java',), ('*.java',), ('text/x-java',)),
'JavascriptDjangoLexer': ('pygments.lexers.templates', 'JavaScript+Django/Jinja', ('js+django', 'javascript+django', 'js+jinja', 'javascript+jinja'), (), ('application/x-javascript+django', 'application/x-javascript+jinja', 'text/x-javascript+django', 'text/x-javascript+jinja', 'text/javascript+django', 'text/javascript+jinja')),
'JavascriptErbLexer': ('pygments.lexers.templates', 'JavaScript+Ruby', ('js+erb', 'javascript+erb', 'js+ruby', 'javascript+ruby'), (), ('application/x-javascript+ruby', 'text/x-javascript+ruby', 'text/javascript+ruby')),
'JavascriptGenshiLexer': ('pygments.lexers.templates', 'JavaScript+Genshi Text', ('js+genshitext', 'js+genshi', 'javascript+genshitext', 'javascript+genshi'), (), ('application/x-javascript+genshi', 'text/x-javascript+genshi', 'text/javascript+genshi')),
'JavascriptLexer': ('pygments.lexers.web', 'JavaScript', ('js', 'javascript'), ('*.js',), ('application/x-javascript', 'text/x-javascript', 'text/javascript')),
'JavascriptPhpLexer': ('pygments.lexers.templates', 'JavaScript+PHP', ('js+php', 'javascript+php'), (), ('application/x-javascript+php', 'text/x-javascript+php', 'text/javascript+php')),
'JavascriptSmartyLexer': ('pygments.lexers.templates', 'JavaScript+Smarty', ('js+smarty', 'javascript+smarty'), (), ('application/x-javascript+smarty', 'text/x-javascript+smarty', 'text/javascript+smarty')),
'JspLexer': ('pygments.lexers.templates', 'Java Server Page', ('jsp',), ('*.jsp',), ('application/x-jsp',)),
'LighttpdConfLexer': ('pygments.lexers.text', 'Lighttpd configuration file', ('lighty', 'lighttpd'), (), ('text/x-lighttpd-conf',)),
'LiterateHaskellLexer': ('pygments.lexers.functional', 'Literate Haskell', ('lhs', 'literate-haskell'), ('*.lhs',), ('text/x-literate-haskell',)),
'LlvmLexer': ('pygments.lexers.asm', 'LLVM', ('llvm',), ('*.ll',), ('text/x-llvm',)),
'LogtalkLexer': ('pygments.lexers.other', 'Logtalk', ('logtalk',), ('*.lgt',), ('text/x-logtalk',)),
'LuaLexer': ('pygments.lexers.agile', 'Lua', ('lua',), ('*.lua',), ('text/x-lua', 'application/x-lua')),
'MOOCodeLexer': ('pygments.lexers.other', 'MOOCode', ('moocode',), ('*.moo',), ('text/x-moocode',)),
'MakefileLexer': ('pygments.lexers.text', 'Makefile', ('make', 'makefile', 'mf', 'bsdmake'), ('*.mak', 'Makefile', 'makefile', 'Makefile.*', 'GNUmakefile'), ('text/x-makefile',)),
'MakoCssLexer': ('pygments.lexers.templates', 'CSS+Mako', ('css+mako',), (), ('text/css+mako',)),
'MakoHtmlLexer': ('pygments.lexers.templates', 'HTML+Mako', ('html+mako',), (), ('text/html+mako',)),
'MakoJavascriptLexer': ('pygments.lexers.templates', 'JavaScript+Mako', ('js+mako', 'javascript+mako'), (), ('application/x-javascript+mako', 'text/x-javascript+mako', 'text/javascript+mako')),
'MakoLexer': ('pygments.lexers.templates', 'Mako', ('mako',), ('*.mao',), ('application/x-mako',)),
'MakoXmlLexer': ('pygments.lexers.templates', 'XML+Mako', ('xml+mako',), (), ('application/xml+mako',)),
'MatlabLexer': ('pygments.lexers.math', 'Matlab', ('matlab', 'octave'), ('*.m',), ('text/matlab',)),
'MatlabSessionLexer': ('pygments.lexers.math', 'Matlab session', ('matlabsession',), (), ()),
'MiniDLexer': ('pygments.lexers.agile', 'MiniD', ('minid',), ('*.md',), ('text/x-minidsrc',)),
'ModelicaLexer': ('pygments.lexers.other', 'Modelica', ('modelica',), ('*.mo',), ('text/x-modelica',)),
'MoinWikiLexer': ('pygments.lexers.text', 'MoinMoin/Trac Wiki markup', ('trac-wiki', 'moin'), (), ('text/x-trac-wiki',)),
'MuPADLexer': ('pygments.lexers.math', 'MuPAD', ('mupad',), ('*.mu',), ()),
'MxmlLexer': ('pygments.lexers.web', 'MXML', ('mxml',), ('*.mxml',), ()),
'MySqlLexer': ('pygments.lexers.other', 'MySQL', ('mysql',), (), ('text/x-mysql',)),
'MyghtyCssLexer': ('pygments.lexers.templates', 'CSS+Myghty', ('css+myghty',), (), ('text/css+myghty',)),
'MyghtyHtmlLexer': ('pygments.lexers.templates', 'HTML+Myghty', ('html+myghty',), (), ('text/html+myghty',)),
'MyghtyJavascriptLexer': ('pygments.lexers.templates', 'JavaScript+Myghty', ('js+myghty', 'javascript+myghty'), (), ('application/x-javascript+myghty', 'text/x-javascript+myghty', 'text/javascript+mygthy')),
'MyghtyLexer': ('pygments.lexers.templates', 'Myghty', ('myghty',), ('*.myt', 'autodelegate'), ('application/x-myghty',)),
'MyghtyXmlLexer': ('pygments.lexers.templates', 'XML+Myghty', ('xml+myghty',), (), ('application/xml+myghty',)),
'NasmLexer': ('pygments.lexers.asm', 'NASM', ('nasm',), ('*.asm', '*.ASM'), ('text/x-nasm',)),
'NewspeakLexer': ('pygments.lexers.other', 'Newspeak', ('newspeak',), ('*.ns2',), ('text/x-newspeak',)),
'NginxConfLexer': ('pygments.lexers.text', 'Nginx configuration file', ('nginx',), (), ('text/x-nginx-conf',)),
'NumPyLexer': ('pygments.lexers.math', 'NumPy', ('numpy',), (), ()),
'ObjdumpLexer': ('pygments.lexers.asm', 'objdump', ('objdump',), ('*.objdump',), ('text/x-objdump',)),
'ObjectiveCLexer': ('pygments.lexers.compiled', 'Objective-C', ('objective-c', 'objectivec', 'obj-c', 'objc'), ('*.m',), ('text/x-objective-c',)),
'OcamlLexer': ('pygments.lexers.compiled', 'OCaml', ('ocaml',), ('*.ml', '*.mli', '*.mll', '*.mly'), ('text/x-ocaml',)),
'OcamlLexer': ('pygments.lexers.functional', 'OCaml', ('ocaml',), ('*.ml', '*.mli', '*.mll', '*.mly'), ('text/x-ocaml',)),
'PerlLexer': ('pygments.lexers.agile', 'Perl', ('perl', 'pl'), ('*.pl', '*.pm'), ('text/x-perl', 'application/x-perl')),
'PhpLexer': ('pygments.lexers.web', 'PHP', ('php', 'php3', 'php4', 'php5'), ('*.php', '*.php[345]'), ('text/x-php',)),
'PovrayLexer': ('pygments.lexers.other', 'POVRay', ('pov',), ('*.pov', '*.inc'), ('text/x-povray',)),
'PrologLexer': ('pygments.lexers.compiled', 'Prolog', ('prolog',), ('*.prolog', '*.pro', '*.pl'), ('text/x-prolog',)),
'Python3Lexer': ('pygments.lexers.agile', 'Python 3', ('python3', 'py3'), (), ('text/x-python3', 'application/x-python3')),
'Python3TracebackLexer': ('pygments.lexers.agile', 'Python 3.0 Traceback', ('py3tb',), ('*.py3tb',), ('text/x-python3-traceback',)),
'PythonConsoleLexer': ('pygments.lexers.agile', 'Python console session', ('pycon',), (), ('text/x-python-doctest',)),
'PythonLexer': ('pygments.lexers.agile', 'Python', ('python', 'py'), ('*.py', '*.pyw', '*.sc', 'SConstruct', 'SConscript'), ('text/x-python', 'application/x-python')),
'PythonTracebackLexer': ('pygments.lexers.agile', 'Python Traceback', ('pytb',), ('*.pytb',), ('text/x-python-traceback',)),
'RagelCLexer': ('pygments.lexers.parsers', 'Ragel in C Host', ('ragel-c',), ('*.rl',), ()),
'RagelCppLexer': ('pygments.lexers.parsers', 'Ragel in CPP Host', ('ragel-cpp',), ('*.rl',), ()),
'RagelDLexer': ('pygments.lexers.parsers', 'Ragel in D Host', ('ragel-d',), ('*.rl',), ()),
'RagelEmbeddedLexer': ('pygments.lexers.parsers', 'Embedded Ragel', ('ragel-em',), ('*.rl',), ()),
'RagelJavaLexer': ('pygments.lexers.parsers', 'Ragel in Java Host', ('ragel-java',), ('*.rl',), ()),
'RagelLexer': ('pygments.lexers.parsers', 'Ragel', ('ragel',), (), ()),
'RagelObjectiveCLexer': ('pygments.lexers.parsers', 'Ragel in Objective C Host', ('ragel-objc',), ('*.rl',), ()),
'RagelRubyLexer': ('pygments.lexers.parsers', 'Ragel in Ruby Host', ('ragel-ruby', 'ragel-rb'), ('*.rl',), ()),
'RawTokenLexer': ('pygments.lexers.special', 'Raw token data', ('raw',), (), ('application/x-pygments-tokens',)),
'RebolLexer': ('pygments.lexers.other', 'REBOL', ('rebol',), ('*.r', '*.r3'), ('text/x-rebol',)),
'RedcodeLexer': ('pygments.lexers.other', 'Redcode', ('redcode',), ('*.cw',), ()),
'RhtmlLexer': ('pygments.lexers.templates', 'RHTML', ('rhtml', 'html+erb', 'html+ruby'), ('*.rhtml',), ('text/html+ruby',)),
'RstLexer': ('pygments.lexers.text', 'reStructuredText', ('rst', 'rest', 'restructuredtext'), ('*.rst', '*.rest'), ('text/x-rst', 'text/prs.fallenstein.rst')),
'RubyConsoleLexer': ('pygments.lexers.agile', 'Ruby irb session', ('rbcon', 'irb'), (), ('text/x-ruby-shellsession',)),
'RubyLexer': ('pygments.lexers.agile', 'Ruby', ('rb', 'ruby'), ('*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec', '*.rbx'), ('text/x-ruby', 'application/x-ruby')),
'SLexer': ('pygments.lexers.math', 'S', ('splus', 's', 'r'), ('*.S', '*.R'), ('text/S-plus', 'text/S', 'text/R')),
'ScalaLexer': ('pygments.lexers.compiled', 'Scala', ('scala',), ('*.scala',), ('text/x-scala',)),
'SchemeLexer': ('pygments.lexers.functional', 'Scheme', ('scheme', 'scm'), ('*.scm',), ('text/x-scheme', 'application/x-scheme')),
'SmalltalkLexer': ('pygments.lexers.other', 'Smalltalk', ('smalltalk', 'squeak'), ('*.st',), ('text/x-smalltalk',)),
'SmartyLexer': ('pygments.lexers.templates', 'Smarty', ('smarty',), ('*.tpl',), ('application/x-smarty',)),
'SourcesListLexer': ('pygments.lexers.text', 'Debian Sourcelist', ('sourceslist', 'sources.list'), ('sources.list',), ()),
'SqlLexer': ('pygments.lexers.other', 'SQL', ('sql',), ('*.sql',), ('text/x-sql',)),
'SqliteConsoleLexer': ('pygments.lexers.other', 'sqlite3con', ('sqlite3',), ('*.sqlite3-console',), ('text/x-sqlite3-console',)),
'SquidConfLexer': ('pygments.lexers.text', 'SquidConf', ('squidconf', 'squid.conf', 'squid'), ('squid.conf',), ('text/x-squidconf',)),
'TclLexer': ('pygments.lexers.agile', 'Tcl', ('tcl',), ('*.tcl',), ('text/x-tcl', 'text/x-script.tcl', 'application/x-tcl')),
'TcshLexer': ('pygments.lexers.other', 'Tcsh', ('tcsh', 'csh'), ('*.tcsh', '*.csh'), ('application/x-csh',)),
'TexLexer': ('pygments.lexers.text', 'TeX', ('tex', 'latex'), ('*.tex', '*.aux', '*.toc'), ('text/x-tex', 'text/x-latex')),
'TextLexer': ('pygments.lexers.special', 'Text only', ('text',), ('*.txt',), ('text/plain',)),
'ValaLexer': ('pygments.lexers.compiled', 'Vala', ('vala', 'vapi'), ('*.vala', '*.vapi'), ('text/x-vala',)),
'VbNetAspxLexer': ('pygments.lexers.dotnet', 'aspx-vb', ('aspx-vb',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()),
'VbNetLexer': ('pygments.lexers.dotnet', 'VB.net', ('vb.net', 'vbnet'), ('*.vb', '*.bas'), ('text/x-vbnet', 'text/x-vba')),
'VimLexer': ('pygments.lexers.text', 'VimL', ('vim',), ('*.vim', '.vimrc'), ('text/x-vim',)),
'XmlDjangoLexer': ('pygments.lexers.templates', 'XML+Django/Jinja', ('xml+django', 'xml+jinja'), (), ('application/xml+django', 'application/xml+jinja')),
'XmlErbLexer': ('pygments.lexers.templates', 'XML+Ruby', ('xml+erb', 'xml+ruby'), (), ('application/xml+ruby',)),
'XmlLexer': ('pygments.lexers.web', 'XML', ('xml',), ('*.xml', '*.xsl', '*.rss', '*.xslt', '*.xsd', '*.wsdl'), ('text/xml', 'application/xml', 'image/svg+xml', 'application/rss+xml', 'application/atom+xml', 'application/xsl+xml', 'application/xslt+xml')),
'XmlPhpLexer': ('pygments.lexers.templates', 'XML+PHP', ('xml+php',), (), ('application/xml+php',)),
'XmlSmartyLexer': ('pygments.lexers.templates', 'XML+Smarty', ('xml+smarty',), (), ('application/xml+smarty',)),
'XsltLexer': ('pygments.lexers.web', 'XSLT', ('xslt',), ('*.xsl', '*.xslt'), ('text/xml', 'application/xml', 'image/svg+xml', 'application/rss+xml', 'application/atom+xml', 'application/xsl+xml', 'application/xslt+xml')),
'YamlLexer': ('pygments.lexers.text', 'YAML', ('yaml',), ('*.yaml', '*.yml'), ('text/x-yaml',))
}
if __name__ == '__main__':
import sys
import os
# lookup lexers
found_lexers = []
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
for filename in os.listdir('.'):
if filename.endswith('.py') and not filename.startswith('_'):
module_name = 'pygments.lexers.%s' % filename[:-3]
print module_name
module = __import__(module_name, None, None, [''])
for lexer_name in module.__all__:
lexer = getattr(module, lexer_name)
found_lexers.append(
'%r: %r' % (lexer_name,
(module_name,
lexer.name,
tuple(lexer.aliases),
tuple(lexer.filenames),
tuple(lexer.mimetypes))))
# sort them, that should make the diff files for svn smaller
found_lexers.sort()
# extract useful sourcecode from this file
f = open(__file__)
try:
content = f.read()
finally:
f.close()
header = content[:content.find('LEXERS = {')]
footer = content[content.find("if __name__ == '__main__':"):]
# write new file
f = open(__file__, 'w')
f.write(header)
f.write('LEXERS = {\n %s\n}\n\n' % ',\n '.join(found_lexers))
f.write(footer)
f.close()
| KeyIngredient/gaepaste | pygments/lexers/_mapping.py | Python | lgpl-3.0 | 22,677 |
/*
Copyright (C) 2007 National Institute For Space Research (INPE) - Brazil.
This file is part of TerraMA2 - a free and open source computational
platform for analysis, monitoring, and alert of geo-environmental extremes.
TerraMA2 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.
TerraMA2 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 TerraMA2. See LICENSE. If not, write to
TerraMA2 Team at <[email protected]>.
*/
/*!
\file src/terrama2/services/view/core/JSonUtils.hpp
\brief Methods to convertion between a View and JSon object
\author Vinicius Campanha
*/
// TerraMa2
#include "View.hpp"
#include "Shared.hpp"
// Qt
#include <QJsonObject>
namespace terrama2
{
namespace services
{
namespace view
{
namespace core
{
/*!
\brief Creates a View from a QJsonObject.
\see View for json structure
*/
TMVIEWEXPORT ViewPtr fromViewJson(QJsonObject json);
/*!
\brief Creates a Json object from a View
*/
TMVIEWEXPORT QJsonObject toJson(ViewPtr view);
TMVIEWEXPORT View::Legend* fromLegendJson(QJsonObject json);
TMVIEWEXPORT QJsonObject toJson(View::Legend legend);
TMVIEWEXPORT QJsonObject toJson(View::Legend::Rule rule);
} // end namespace core
} // end namespace view
} // end namespace services
} // end namespace terrama2
| TerraMA2/terrama2 | src/terrama2/services/view/core/JSonUtils.hpp | C++ | lgpl-3.0 | 1,883 |
package co.shift.generators.domain;
import org.eclipse.xtext.resource.generic.AbstractGenericResourceSupport;
import com.google.inject.Module;
public class DomainCodeSupport extends AbstractGenericResourceSupport{
@Override
protected Module createGuiceModule() {
return new DomainCodeModule();
}
}
| unicesi/QD-SPL | ToolSupport/co.edu.icesi.shift.generator/src/co/shift/generators/domain/DomainCodeSupport.java | Java | lgpl-3.0 | 309 |
/*-
* #%L
* Alfresco Remote API
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.framework.tools;
import org.alfresco.rest.framework.core.exceptions.ApiException;
import org.alfresco.rest.framework.core.exceptions.InvalidArgumentException;
import org.alfresco.rest.framework.jacksonextensions.JacksonHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.extensions.webscripts.WebScriptRequest;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
/*
* Reads information from the request
*
* @author Gethin James
*/
public interface RequestReader
{
/**
* Extracts the body contents from the request
*
* @param req the request
* @param jsonHelper Jackson Helper
* @param requiredType the type to return
* @return the Object in the required type
*/
default <T> T extractJsonContent(WebScriptRequest req, JacksonHelper jsonHelper, Class<T> requiredType)
{
Reader reader;
try
{
reader = req.getContent().getReader();
return jsonHelper.construct(reader, requiredType);
}
catch (JsonMappingException e)
{
rrLogger().warn("Could not read content from HTTP request body.", e);
throw new InvalidArgumentException("Could not read content from HTTP request body.");
}
catch (IOException e)
{
throw new ApiException("Could not read content from HTTP request body.", e.getCause());
}
}
/**
* Extracts the body contents from the request as a List, the JSON can be an array or just a single value without the [] symbols
*
* @param req the request
* @param jsonHelper Jackson Helper
* @param requiredType the type to return (without the List param)
* @return A List of "Object" as the required type
*/
default <T> List<T> extractJsonContentAsList(WebScriptRequest req, JacksonHelper jsonHelper, Class<T> requiredType)
{
Reader reader;
try
{
reader = req.getContent().getReader();
return jsonHelper.constructList(reader, requiredType);
}
catch (IOException e)
{
throw new ApiException("Could not read content from HTTP request body.", e.getCause());
}
}
default Log rrLogger()
{
return LogFactory.getLog(this.getClass());
}
}
| Alfresco/community-edition | projects/remote-api/source/java/org/alfresco/rest/framework/tools/RequestReader.java | Java | lgpl-3.0 | 3,511 |
package co.shift.pcs.project.control;
import java.util.List;
import javax.ejb.Remote;
import co.shift.pcs.to.ProjectTO;
@Remote
public interface IProjectBasicFLR {
public List<ProjectTO> getAllProjects() throws Exception;
}
| unicesi/QD-SPL | ToolSupport/co.edu.icesi.shift.generator/src-gen/co/shift/pcs/project/control/IProjectBasicFLR.java | Java | lgpl-3.0 | 228 |
crossref_200_ok = {
'message': {
'DOI':
'10.1002/ecy.1625',
'ISSN': ['0012-9658'],
'URL':
'http://dx.doi.org/10.1002/ecy.1625',
'archive': ['Portico'],
'author': [{
'affiliation': [{
'name':
'U.S. Geological Survey; 700 Cajundome Blvd. Lafayette Louisiana 70506 USA'
}],
'family':
'Osland',
'given':
'Michael J.'
}, {
'affiliation': [{
'name':
'U.S. Geological Survey; 700 Cajundome Blvd. Lafayette Louisiana 70506 USA'
}],
'family':
'Day',
'given':
'Richard H.'
}, {
'affiliation': [{
'name':
'U.S. Geological Survey; 700 Cajundome Blvd. Lafayette Louisiana 70506 USA'
}],
'family':
'Hall',
'given':
'Courtney T.'
}, {
'affiliation': [{
'name':
'University of Oklahoma; Norman Oklahoma 73019-0390 USA'
}],
'family':
'Brumfield',
'given':
'Marisa D.'
}, {
'affiliation': [{
'name':
'U.S. Geological Survey; 700 Cajundome Blvd. Lafayette Louisiana 70506 USA'
}],
'family':
'Dugas',
'given':
'Jason L.'
}, {
'affiliation': [{
'name':
'U.S. Geological Survey; 700 Cajundome Blvd. Lafayette Louisiana 70506 USA'
}],
'family':
'Jones',
'given':
'William R.'
}],
'container-title': ['Ecology'],
'content-domain': {
'crossmark-restriction': False,
'domain': []
},
'created': {
'date-parts': [[2016, 10, 17]],
'date-time': '2016-10-17T13:33:09Z',
'timestamp': 1476711189000
},
'deposited': {
'date-parts': [[2017, 6, 15]],
'date-time': '2017-06-15T01:27:37Z',
'timestamp': 1497490057000
},
'funder': [{
'DOI': '10.13039/100000203',
'award': [],
'doi-asserted-by': 'publisher',
'name': 'U.S. Geological Survey'
}, {
'DOI': '10.13039/501100001589',
'award': [],
'doi-asserted-by': 'publisher',
'name': 'Environmental Protection Agency'
}, {
'award': [],
'name':
'Department of Interior Southeast Climate Science Center'
}, {
'award': [],
'name':
'Department of Interior South Central Climate Science Center'
}, {
'award': [],
'name': 'Southern Climate Impacts Planning Program'
}],
'indexed': {
'date-parts': [[2017, 10, 5]],
'date-time': '2017-10-05T13:42:23Z',
'timestamp': 1507210943579
},
'is-referenced-by-count':
10,
'issn-type': [{
'type': 'print',
'value': '0012-9658'
}],
'issue':
'1',
'issued': {
'date-parts': [[2016, 12, 9]]
},
'license': [{
'URL': 'http://doi.wiley.com/10.1002/tdm_license_1',
'content-version': 'tdm',
'delay-in-days': 0,
'start': {
'date-parts': [[2016, 12, 9]],
'date-time': '2016-12-09T00:00:00Z',
'timestamp': 1481241600000
}
}, {
'URL':
'http://onlinelibrary.wiley.com/termsAndConditions',
'content-version':
'am',
'delay-in-days':
365,
'start': {
'date-parts': [[2017, 12, 9]],
'date-time': '2017-12-09T00:00:00Z',
'timestamp': 1512777600000
}
}, {
'URL':
'http://onlinelibrary.wiley.com/termsAndConditions',
'content-version':
'vor',
'delay-in-days':
0,
'start': {
'date-parts': [[2016, 12, 9]],
'date-time': '2016-12-09T00:00:00Z',
'timestamp': 1481241600000
}
}],
'link': [{
'URL':
'https://api.wiley.com/onlinelibrary/tdm/v1/articles/10.1002%2Fecy.1625',
'content-type':
'application/pdf',
'content-version':
'vor',
'intended-application':
'text-mining'
}, {
'URL':
'https://api.wiley.com/onlinelibrary/tdm/v1/articles/10.1002%2Fecy.1625',
'content-type':
'unspecified',
'content-version':
'vor',
'intended-application':
'text-mining'
}, {
'URL':
'http://api.wiley.com/onlinelibrary/chorus/v1/articles/10.1002%2Fecy.1625',
'content-type':
'application/pdf',
'content-version':
'am',
'intended-application':
'syndication'
}, {
'URL':
'http://onlinelibrary.wiley.com/wol1/doi/10.1002/ecy.1625/fullpdf',
'content-type':
'unspecified',
'content-version':
'vor',
'intended-application':
'similarity-checking'
}],
'member':
'311',
'original-title': [],
'page':
'125-137',
'prefix':
'10.1002',
'published-online': {
'date-parts': [[2016, 12, 9]]
},
'published-print': {
'date-parts': [[2017, 1]]
},
'publisher':
'Wiley-Blackwell',
'reference': [{
'author':
'Ackerman',
'first-page':
'223',
'key':
'10.1002/ecy.1625-BIB0001|ecy1625-cit-0001',
'volume-title':
'Population biology of the Florida manatee. Information and technology report 1',
'year':
'1995'
}, {
'DOI': '10.1017/CBO9780511565328',
'author': 'Adam',
'doi-asserted-by': 'crossref',
'key': '10.1002/ecy.1625-BIB0002|ecy1625-cit-0002',
'volume-title': 'Saltmarsh ecology',
'year': '1990'
}, {
'DOI':
'10.1016/j.foreco.2009.09.001',
'article-title':
'A global overview of drought and heat-induced tree mortality reveals emerging climate change risks for forests',
'author':
'Allen',
'doi-asserted-by':
'crossref',
'first-page':
'660',
'journal-title':
'Forest Ecology and Management',
'key':
'10.1002/ecy.1625-BIB0003|ecy1625-cit-0003',
'volume':
'259',
'year':
'2010'
}, {
'author': 'Alongi',
'key': '10.1002/ecy.1625-BIB0004|ecy1625-cit-0004',
'volume-title': 'The energetics of mangrove forests',
'year': '2009'
}, {
'DOI':
'10.1007/s40641-015-0002-x',
'article-title':
'The impact of climate change on mangrove forests',
'author':
'Alongi',
'doi-asserted-by':
'crossref',
'first-page':
'30',
'journal-title':
'Current Climate Change Reports',
'key':
'10.1002/ecy.1625-BIB0005|ecy1625-cit-0005',
'volume':
'1',
'year':
'2015'
}, {
'DOI':
'10.1371/journal.pone.0125404',
'article-title':
'The contribution of mangrove expansion to salt marsh loss on the Texas Gulf Coast',
'author':
'Armitage',
'doi-asserted-by':
'crossref',
'first-page':
'e0125404',
'journal-title':
'PLoS ONE',
'key':
'10.1002/ecy.1625-BIB0006|ecy1625-cit-0006',
'volume':
'10',
'year':
'2015'
}, {
'DOI':
'10.1016/j.ecss.2012.12.007',
'article-title':
'Historical reconstruction of mangrove expansion in the Gulf of Mexico: linking climate change with carbon sequestration in coastal wetlands',
'author':
'Bianchi',
'doi-asserted-by':
'crossref',
'first-page':
'7',
'journal-title':
'Estuarine, Coastal and Shelf Science',
'key':
'10.1002/ecy.1625-BIB0007|ecy1625-cit-0007',
'volume':
'119',
'year':
'2013'
}, {
'DOI':
'10.1111/gcb.12574',
'article-title':
'Climate extremes drive changes in functional community structure',
'author':
'Boucek',
'doi-asserted-by':
'crossref',
'first-page':
'1821',
'journal-title':
'Global Change Biology',
'key':
'10.1002/ecy.1625-BIB0008|ecy1625-cit-0008',
'volume':
'20',
'year':
'2014'
}, {
'DOI':
'10.1002/ecs2.1455',
'article-title':
'A\xa0review of subtropical community resistance and resilience\xa0to extreme cold spells',
'author':
'Boucek',
'doi-asserted-by':
'publisher',
'first-page':
'e01455',
'journal-title':
'Ecosphere',
'key':
'10.1002/ecy.1625-BIB0009|ecy1625-cit-0009',
'volume':
'7'
}, {
'DOI':
'10.1007/s13157-016-0793-0',
'article-title':
'Allometric models for estimating aboveground biomass, carbon and nitrogen stocks in temperate Avicennia marina',
'author':
'Bulmer',
'doi-asserted-by':
'crossref',
'first-page':
'841',
'journal-title':
'Wetlands',
'key':
'10.1002/ecy.1625-BIB0010|ecy1625-cit-0010',
'volume':
'36',
'year':
'2016'
}, {
'DOI':
'10.1073/pnas.1315800111',
'article-title':
'Poleward expansion of mangroves is a threshold response to decreased frequency of extreme cold events',
'author':
'Cavanaugh',
'doi-asserted-by':
'crossref',
'first-page':
'723',
'journal-title':
'Proceedings of the National Academy of Sciences',
'key':
'10.1002/ecy.1625-BIB0011|ecy1625-cit-0011',
'volume':
'111',
'year':
'2014'
}, {
'DOI':
'10.1111/gcb.12843',
'article-title':
"Integrating physiological threshold experiments with climate modeling to project mangrove species' range expansion",
'author':
'Cavanaugh',
'doi-asserted-by':
'crossref',
'first-page':
'1928',
'journal-title':
'Global Change Biology',
'key':
'10.1002/ecy.1625-BIB0012|ecy1625-cit-0012',
'volume':
'21',
'year':
'2015'
}, {
'DOI': '10.1029/CE041p0225',
'author': 'Clough',
'doi-asserted-by': 'crossref',
'first-page': '225',
'key': '10.1002/ecy.1625-BIB0013|ecy1625-cit-0013',
'volume-title': 'Tropical mangrove ecosystems',
'year': '1992'
}, {
'DOI':
'10.1111/1365-2435.12443',
'article-title':
'Convergence of three mangrove species towards freeze-tolerant phenotypes at an expanding range edge',
'author':
'Cook-Patton',
'doi-asserted-by':
'crossref',
'first-page':
'1332',
'journal-title':
'Functional Ecology',
'key':
'10.1002/ecy.1625-BIB0014|ecy1625-cit-0014',
'volume':
'29',
'year':
'2015'
}, {
'key':
'10.1002/ecy.1625-BIB0015|ecy1625-cit-0015',
'unstructured':
'Couvillion , B. R. J. A. Barras G. D. Steyer W. Sleavin M. \xa0 Fischer H. Beck N. Trahan B. Griffin D. Heckman 2011 Land area change in coastal Louisiana from 1932 to 2010: U.S. Geological Survey Scientific Investigations Map 3164, scale 1:265,000'
}, {
'DOI':
'10.1002/joc.937',
'article-title':
'Mapping the climate of Puerto Rico, Vieques and Culebra',
'author':
'Daly',
'doi-asserted-by':
'crossref',
'first-page':
'1359',
'journal-title':
'International Journal of Climatology',
'key':
'10.1002/ecy.1625-BIB0016|ecy1625-cit-0016',
'volume':
'23',
'year':
'2003'
}, {
'DOI':
'10.1002/joc.1688',
'article-title':
'Physiographically sensitive mapping of climatological temperature and precipitation across the conterminous United States',
'author':
'Daly',
'doi-asserted-by':
'crossref',
'first-page':
'2031',
'journal-title':
'International Journal of Climatology',
'key':
'10.1002/ecy.1625-BIB0017|ecy1625-cit-0017',
'volume':
'28',
'year':
'2008'
}, {
'DOI':
'10.1175/2010JAMC2536.1',
'article-title':
'Development of a new USDA plant hardiness zone map for the United States',
'author':
'Daly',
'doi-asserted-by':
'crossref',
'first-page':
'242',
'journal-title':
'Journal of Applied Meteorology and Climatology',
'key':
'10.1002/ecy.1625-BIB0018|ecy1625-cit-0018',
'volume':
'51',
'year':
'2012'
}, {
'DOI':
'10.1002/ece3.2270',
'article-title':
'Precocious reproduction increases at the leading edge of a mangrove range expansion',
'author':
'Dangremond',
'doi-asserted-by':
'crossref',
'first-page':
'5087',
'journal-title':
'Ecology and Evolution',
'key':
'10.1002/ecy.1625-BIB0019|ecy1625-cit-0019',
'volume':
'6',
'year':
'2016'
}, {
'article-title':
'The ecology and geologic role of mangroves in Florida. Carnegie Institute of Washington Publications',
'author':
'Davis',
'first-page':
'303',
'journal-title':
'Papers from Tortugas Laboratory',
'key':
'10.1002/ecy.1625-BIB0020|ecy1625-cit-0020',
'volume':
'32',
'year':
'1940'
}, {
'DOI':
'10.1111/geb.12000',
'article-title':
'Vegetation-microclimate feedbacks in woodland-grassland ecotones',
'author':
"D'Odorico",
'doi-asserted-by':
'crossref',
'first-page':
'364',
'journal-title':
'Global Ecology and Biogeography',
'key':
'10.1002/ecy.1625-BIB0021|ecy1625-cit-0021',
'volume':
'22',
'year':
'2013'
}, {
'DOI':
'10.1007/s12237-015-9993-8',
'article-title':
'Mangrove range expansion rapidly increases coastal wetland carbon storage',
'author':
'Doughty',
'doi-asserted-by':
'crossref',
'first-page':
'385',
'journal-title':
'Estuaries and Coasts',
'key':
'10.1002/ecy.1625-BIB0022|ecy1625-cit-0022',
'volume':
'39',
'year':
'2016'
}, {
'DOI':
'10.1002/ecs2.1302',
'article-title':
'Differential impacts from an extreme cold spell on subtropical vs. tropical specialist bees in southern Florida',
'author':
'Downing',
'doi-asserted-by':
'crossref',
'first-page':
'e01302',
'journal-title':
'Ecosphere',
'key':
'10.1002/ecy.1625-BIB0023|ecy1625-cit-0023',
'volume':
'7',
'year':
'2016'
}, {
'DOI':
'10.1126/science.289.5487.2068',
'article-title':
'Climate extremes: observations, modeling, and impacts',
'author':
'Easterling',
'doi-asserted-by':
'crossref',
'first-page':
'2068',
'journal-title':
'Science',
'key':
'10.1002/ecy.1625-BIB0024|ecy1625-cit-0024',
'volume':
'289',
'year':
'2000'
}, {
'article-title':
'Integration of remote sensing and spatial information technologies for mapping black mangrove on the Texas gulf coast',
'author':
'Everitt',
'first-page':
'64',
'journal-title':
'Journal of Coastal Research',
'key':
'10.1002/ecy.1625-BIB0025|ecy1625-cit-0025',
'volume':
'12',
'year':
'1996'
}, {
'article-title':
'Macroclimatic change expected to transform coastal wetland ecosystems this century',
'author':
'Gabler',
'journal-title':
'Nature Climate Change',
'key':
'10.1002/ecy.1625-BIB0026|ecy1625-cit-0026'
}, {
'DOI':
'10.1098/rspb.2008.1480',
'article-title':
'Geographic range limits: achieving synthesis',
'author':
'Gaston',
'doi-asserted-by':
'crossref',
'first-page':
'1395',
'journal-title':
'Proceedings of the Royal Society of London B: Biological Sciences',
'key':
'10.1002/ecy.1625-BIB0027|ecy1625-cit-0027',
'volume':
'276',
'year':
'2009'
}, {
'DOI':
'10.1073/pnas.1400687111',
'article-title':
'Mangrove reemergence in the northernmost range limit of eastern Florida',
'author':
'Giri',
'doi-asserted-by':
'crossref',
'first-page':
'E1447',
'journal-title':
'Proceedings of the National Academy of Sciences',
'key':
'10.1002/ecy.1625-BIB0028|ecy1625-cit-0028',
'volume':
'111',
'year':
'2014'
}, {
'DOI':
'10.2112/JCOASTRES-D-11-00028.1',
'article-title':
"Mapping and monitoring Louisiana's mangroves in the aftermath of the 2010 Gulf of Mexico oil spill",
'author':
'Giri',
'doi-asserted-by':
'crossref',
'first-page':
'1059',
'journal-title':
'Journal of Coastal Research',
'key':
'10.1002/ecy.1625-BIB0029|ecy1625-cit-0029',
'volume':
'27',
'year':
'2011'
}, {
'article-title':
"On the evolutionary ecology of species' ranges",
'author':
'Holt',
'first-page':
'159',
'journal-title':
'Evolutionary Ecology Research',
'key':
'10.1002/ecy.1625-BIB0030|ecy1625-cit-0030',
'volume':
'5',
'year':
'2003'
}, {
'DOI':
'10.1890/13-2186.1',
'article-title':
'Resistance and resilience of a grassland ecosystem to climate extremes',
'author':
'Hoover',
'doi-asserted-by':
'crossref',
'first-page':
'2646',
'journal-title':
'Ecology',
'key':
'10.1002/ecy.1625-BIB0031|ecy1625-cit-0031',
'volume':
'95',
'year':
'2014'
}, {
'DOI': '10.1002/9781118412787.ch6',
'author': 'Ib\xe1\xf1ez',
'doi-asserted-by': 'crossref',
'edition': '2',
'first-page': '129',
'key': '10.1002/ecy.1625-BIB0032|ecy1625-cit-0032',
'volume-title': 'Estuarine ecology',
'year': '2012'
}, {
'author':
'IPCC',
'key':
'10.1002/ecy.1625-BIB0033|ecy1625-cit-0033',
'volume-title':
'Climate change 2013: the physical science basis. Contribution of working group I to the fifth assessment report of the intergovernmental panel on climate change',
'year':
'2013'
}, {
'DOI':
'10.1016/j.crte.2008.07.002',
'article-title':
'Research frontiers in climate change: effects of extreme meteorological events on ecosystems',
'author':
'Jentsch',
'doi-asserted-by':
'crossref',
'first-page':
'621',
'journal-title':
'Comptes Rendus Geoscience',
'key':
'10.1002/ecy.1625-BIB0034|ecy1625-cit-0034',
'volume':
'340',
'year':
'2008'
}, {
'DOI':
'10.1890/1540-9295(2007)5[365:ANGOCE]2.0.CO;2',
'article-title':
'A new generation of climate-change experiments: events, not trends',
'author':
'Jentsch',
'doi-asserted-by':
'crossref',
'first-page':
'365',
'journal-title':
'Frontiers in Ecology and the Environment',
'key':
'10.1002/ecy.1625-BIB0035|ecy1625-cit-0035',
'volume':
'5',
'year':
'2007'
}, {
'DOI':
'10.1016/j.ecolmodel.2015.04.013',
'article-title':
'Defining the next generation modeling of coastal ecotone dynamics in response to global change',
'author':
'Jiang',
'doi-asserted-by':
'crossref',
'first-page':
'168',
'journal-title':
'Ecological Modelling',
'key':
'10.1002/ecy.1625-BIB0036|ecy1625-cit-0036',
'volume':
'326',
'year':
'2016'
}, {
'DOI':
'10.1111/jbi.12813',
'article-title':
'Contrasting genetic effects of red mangrove (Rhizophora mangle L.) range expansion along West and East Florida',
'author':
'Kennedy',
'doi-asserted-by':
'publisher',
'journal-title':
'Journal of Biogeography',
'key':
'10.1002/ecy.1625-BIB0037|ecy1625-cit-0037'
}, {
'DOI':
'10.1007/978-3-662-05214-3',
'author':
'Larcher',
'doi-asserted-by':
'crossref',
'key':
'10.1002/ecy.1625-BIB0038|ecy1625-cit-0038',
'volume-title':
'Physiological plant ecology: ecophysiology and stress physiology of functional groups',
'year':
'2003'
}, {
'DOI':
'10.1371/journal.pone.0023047',
'article-title':
'Severe 2010 cold-water event caused unprecedented mortality to corals of the Florida reef tract and reversed previous survivorship patterns',
'author':
'Lirman',
'doi-asserted-by':
'crossref',
'first-page':
'e23047',
'journal-title':
'PLoS ONE',
'key':
'10.1002/ecy.1625-BIB0039|ecy1625-cit-0039',
'volume':
'6',
'year':
'2011'
}, {
'DOI':
'10.2307/3671923',
'article-title':
'Comparison of the effects of the severe freezes of 1983 and 1989 on native woody plants in the Lower Rio Grande Valley, Texas',
'author':
'Lonard',
'doi-asserted-by':
'crossref',
'first-page':
'213',
'journal-title':
'The Southwestern Naturalist',
'key':
'10.1002/ecy.1625-BIB0040|ecy1625-cit-0040',
'volume':
'36',
'year':
'1991'
}, {
'DOI':
'10.1007/978-3-319-27422-5_7',
'author':
'Lovelock',
'doi-asserted-by':
'crossref',
'first-page':
'149',
'key':
'10.1002/ecy.1625-BIB0041|ecy1625-cit-0041',
'volume-title':
'Tropical tree physiology: adaptations and responses in a changing environment',
'year':
'2016'
}, {
'article-title':
'The impact of low temperature stress on mangrove structure and growth',
'author':
'Lugo',
'first-page':
'149',
'journal-title':
'Tropical Ecology',
'key':
'10.1002/ecy.1625-BIB0042|ecy1625-cit-0042',
'volume':
'18',
'year':
'1977'
}, {
'author':
'MacArthur',
'key':
'10.1002/ecy.1625-BIB0043|ecy1625-cit-0043',
'volume-title':
'Geographical ecology: patterns in the distribution of species',
'year':
'1972'
}, {
'DOI':
'10.3389/fpls.2014.00503',
'article-title':
'Avicennia germinans (black mangrove) vessel architecture is linked to chilling and salinity tolerance in the Gulf of Mexico',
'author':
'Madrid',
'doi-asserted-by':
'crossref',
'first-page':
'503',
'journal-title':
'Frontiers in Plant Science',
'key':
'10.1002/ecy.1625-BIB0044|ecy1625-cit-0044',
'volume':
'5',
'year':
'2014'
}, {
'key':
'10.1002/ecy.1625-BIB0045|ecy1625-cit-0045',
'unstructured':
'Martin , J. H. L. W. McEachron 1996 Historical annotated review of winter kills of marine organisms in Texas bays'
}, {
'DOI':
'10.1002/ecs2.1439',
'article-title':
'Large reptiles and cold temperatures: Do extreme cold spells set distributional limits for tropical reptiles in Florida?',
'author':
'Mazzotti',
'doi-asserted-by':
'crossref',
'first-page':
'e01439',
'journal-title':
'Ecosphere',
'key':
'10.1002/ecy.1625-BIB0046|ecy1625-cit-0046',
'volume':
'7',
'year':
'2016'
}, {
'key':
'10.1002/ecy.1625-BIB0047|ecy1625-cit-0047',
'unstructured':
'Michot , T. C. R. H. Day C. J. Wells 2010 Increase in black mangrove abundance in coastal Louisiana'
}, {
'author':
'Montagna',
'edition':
'2',
'first-page':
'96',
'key':
'10.1002/ecy.1625-BIB0048|ecy1625-cit-0048',
'volume-title':
'The impact of global warming on Texas',
'year':
'2011'
}, {
'article-title':
'Effects of freezes on tropical trees in Everglades National Park Florida, USA',
'author':
'Olmsted',
'first-page':
'17',
'journal-title':
'Tropical Ecology',
'key':
'10.1002/ecy.1625-BIB0049|ecy1625-cit-0049',
'volume':
'34',
'year':
'1993'
}, {
'DOI':
'10.1111/gcb.12126',
'article-title':
'Winter climate change and coastal wetland foundation species: salt marshes vs. mangrove forests in the southeastern United States',
'author':
'Osland',
'doi-asserted-by':
'crossref',
'first-page':
'1482',
'journal-title':
'Global Change Biology',
'key':
'10.1002/ecy.1625-BIB0050|ecy1625-cit-0050',
'volume':
'19',
'year':
'2013'
}, {
'DOI':
'10.1371/journal.pone.0099604',
'article-title':
'Aboveground allometric models for freeze-affected black mangroves (Avicennia germinans): equations for a climate sensitive mangrove-marsh ecotone',
'author':
'Osland',
'doi-asserted-by':
'crossref',
'first-page':
'e99604',
'journal-title':
'PLoS ONE',
'key':
'10.1002/ecy.1625-BIB0051|ecy1625-cit-0051',
'volume':
'9',
'year':
'2014'
}, {
'DOI':
'10.1890/ES15-00042.1',
'article-title':
'Life stage influences the resistance and resilience of black mangrove forests to winter climate extremes',
'author':
'Osland',
'doi-asserted-by':
'crossref',
'first-page':
'art160',
'journal-title':
'Ecosphere',
'key':
'10.1002/ecy.1625-BIB0052|ecy1625-cit-0052',
'volume':
'6',
'year':
'2015'
}, {
'DOI':
'10.1111/gcb.13084',
'article-title':
'Beyond just sea-level rise: considering macroclimatic drivers within coastal wetland vulnerability assessments to climate change',
'author':
'Osland',
'doi-asserted-by':
'crossref',
'first-page':
'1',
'journal-title':
'Global Change Biology',
'key':
'10.1002/ecy.1625-BIB0053|ecy1625-cit-0053',
'volume':
'22',
'year':
'2016'
}, {
'DOI':
'10.1146/annurev.ecolsys.37.091305.110100',
'article-title':
'Ecological and evolutionary responses to recent climate change',
'author':
'Parmesan',
'doi-asserted-by':
'crossref',
'first-page':
'637',
'journal-title':
'Annual Review of Ecology, Evolution, and Systematics',
'key':
'10.1002/ecy.1625-BIB0054|ecy1625-cit-0054',
'volume':
'37',
'year':
'2006'
}, {
'DOI':
'10.2307/1943020',
'article-title':
'Plant communities in the marshlands of southeastern Louisiana',
'author':
'Penfound',
'doi-asserted-by':
'crossref',
'first-page':
'1',
'journal-title':
'Ecological Monographs',
'key':
'10.1002/ecy.1625-BIB0055|ecy1625-cit-0055',
'volume':
'8',
'year':
'1938'
}, {
'DOI':
'10.1007/s12237-010-9358-2',
'article-title':
'Temperature tolerance of early life history stages of black mangrove Avicennia germinans: implications for range expansion',
'author':
'Pickens',
'doi-asserted-by':
'crossref',
'first-page':
'824',
'journal-title':
'Estuaries and Coasts',
'key':
'10.1002/ecy.1625-BIB0056|ecy1625-cit-0056',
'volume':
'34',
'year':
'2011'
}, {
'DOI':
'10.1038/307321a0',
'article-title':
'The complexity and stability of ecosystems',
'author':
'Pimm',
'doi-asserted-by':
'crossref',
'first-page':
'321',
'journal-title':
'Nature',
'key':
'10.1002/ecy.1625-BIB0057|ecy1625-cit-0057',
'volume':
'307',
'year':
'1984'
}, {
'DOI':
'10.1002/ecs2.1268',
'article-title':
'Knocking back invasions: variable resistance and resilience to multiple cold spells in native vs. nonnative fishes',
'author':
'Rehage',
'doi-asserted-by':
'crossref',
'first-page':
'e01268',
'journal-title':
'Ecosphere',
'key':
'10.1002/ecy.1625-BIB0058|ecy1625-cit-0058',
'volume':
'7',
'year':
'2016'
}, {
'DOI':
'10.1016/j.gecco.2016.07.005',
'article-title':
'Spatio-temporal changes of a mangrove-saltmarsh ecotone in the northeastern coast of Florida, USA',
'author':
'Rodriguez',
'doi-asserted-by':
'crossref',
'first-page':
'245',
'journal-title':
'Global Ecology and Conservation',
'key':
'10.1002/ecy.1625-BIB0059|ecy1625-cit-0059',
'volume':
'7',
'year':
'2016'
}, {
'DOI':
'10.1175/1520-0442(1991)004<1103:FCFAPA>2.0.CO;2',
'article-title':
'Florida citrus freezes and polar anticyclones in the Great Plains',
'author':
'Rogers',
'doi-asserted-by':
'crossref',
'first-page':
'1103',
'journal-title':
'Journal of Climate',
'key':
'10.1002/ecy.1625-BIB0060|ecy1625-cit-0060',
'volume':
'4',
'year':
'1991'
}, {
'DOI':
'10.1111/j.1365-2486.2009.01900.x',
'article-title':
'Chilling damage in a changing climate in coastal landscapes of the subtropical zone: a case study from south Florida',
'author':
'Ross',
'doi-asserted-by':
'crossref',
'first-page':
'1817',
'journal-title':
'Global Change Biology',
'key':
'10.1002/ecy.1625-BIB0061|ecy1625-cit-0061',
'volume':
'15',
'year':
'2009'
}, {
'DOI':
'10.1111/nph.13147',
'article-title':
'Woody plant encroachment of grasslands: a comparison of terrestrial and wetland settings',
'author':
'Saintilan',
'doi-asserted-by':
'crossref',
'first-page':
'1062',
'journal-title':
'New Phytologist',
'key':
'10.1002/ecy.1625-BIB0062|ecy1625-cit-0062',
'volume':
'205',
'year':
'2015'
}, {
'DOI':
'10.1111/gcb.12341',
'article-title':
'Mangrove expansion and salt marsh decline at\xa0mangrove poleward limits',
'author':
'Saintilan',
'doi-asserted-by':
'crossref',
'first-page':
'147',
'journal-title':
'Global Change Biology',
'key':
'10.1002/ecy.1625-BIB0063|ecy1625-cit-0063',
'volume':
'20',
'year':
'2014'
}, {
'DOI':
'10.1007/978-3-642-71745-1',
'author':
'Sakai',
'doi-asserted-by':
'crossref',
'key':
'10.1002/ecy.1625-BIB0064|ecy1625-cit-0064',
'volume-title':
'Frost survival of plants: responses and adaptation to freezing stress',
'year':
'1987'
}, {
'DOI':
'10.1146/annurev.ecolsys.110308.120317',
'article-title':
'Evolution and ecology of species range limits',
'author':
'Sexton',
'doi-asserted-by':
'crossref',
'first-page':
'415',
'journal-title':
'Annual Review of Ecology, Evolution, and Systematics',
'key':
'10.1002/ecy.1625-BIB0065|ecy1625-cit-0065',
'volume':
'40',
'year':
'2009'
}, {
'article-title':
'The distributional history and ecology of mangrove vegetation along the northern Gulf of Mexico coastal region',
'author':
'Sherrod',
'first-page':
'129',
'journal-title':
'Contributions in Marine Science',
'key':
'10.1002/ecy.1625-BIB0066|ecy1625-cit-0066',
'volume':
'28',
'year':
'1985'
}, {
'DOI':
'10.1111/j.1365-2745.2011.01833.x',
'article-title':
'The ecological role of climate extremes: current understanding and future prospects',
'author':
'Smith',
'doi-asserted-by':
'crossref',
'first-page':
'651',
'journal-title':
'Journal of Ecology',
'key':
'10.1002/ecy.1625-BIB0067|ecy1625-cit-0067',
'volume':
'99',
'year':
'2011'
}, {
'DOI':
'10.1890/09-2128.1',
'article-title':
'Controls on resilience and stability in a sediment-subsidized salt marsh',
'author':
'Stagg',
'doi-asserted-by':
'crossref',
'first-page':
'1731',
'journal-title':
'Ecological Applications',
'key':
'10.1002/ecy.1625-BIB0068|ecy1625-cit-0068',
'volume':
'21',
'year':
'2011'
}, {
'DOI':
'10.1007/s11273-006-0006-3',
'article-title':
'The interplay between mangroves and saltmarshes at the transition between temperate and subtropical climate in Florida',
'author':
'Stevens',
'doi-asserted-by':
'crossref',
'first-page':
'435',
'journal-title':
'Wetlands Ecology and Management',
'key':
'10.1002/ecy.1625-BIB0069|ecy1625-cit-0069',
'volume':
'14',
'year':
'2006'
}, {
'DOI':
'10.1002/ecs2.1400',
'article-title':
'Resilience of a tropical sport fish population to a severe cold event varies across five estuaries in southern Florida',
'author':
'Stevens',
'doi-asserted-by':
'crossref',
'first-page':
'e01400',
'journal-title':
'Ecosphere',
'key':
'10.1002/ecy.1625-BIB0070|ecy1625-cit-0070',
'volume':
'7',
'year':
'2016'
}, {
'DOI':
'10.1111/j.1469-8137.2006.01938.x',
'article-title':
'The role of freezing in setting the latitudinal limits of mangrove forests',
'author':
'Stuart',
'doi-asserted-by':
'crossref',
'first-page':
'576',
'journal-title':
'New Phytologist',
'key':
'10.1002/ecy.1625-BIB0071|ecy1625-cit-0071',
'volume':
'173',
'year':
'2007'
}, {
'DOI':
'10.1038/367363a0',
'article-title':
'Biodiversity and stability in grasslands',
'author':
'Tilman',
'doi-asserted-by':
'crossref',
'first-page':
'363',
'journal-title':
'Nature',
'key':
'10.1002/ecy.1625-BIB0072|ecy1625-cit-0072',
'volume':
'367',
'year':
'1994'
}, {
'author': 'Tomlinson',
'key': '10.1002/ecy.1625-BIB0073|ecy1625-cit-0073',
'volume-title': 'The botany of mangroves',
'year': '1986'
}, {
'DOI': '10.1002/9781118412787.ch7',
'author': 'Twilley',
'doi-asserted-by': 'crossref',
'edition': '2',
'first-page': '165',
'key': '10.1002/ecy.1625-BIB0074|ecy1625-cit-0074',
'volume-title': 'Estuarine ecology',
'year': '2012'
}, {
'DOI':
'10.1098/rspb.2014.0846',
'article-title':
'The tropicalization of temperate marine ecosystems: climate-mediated changes in herbivory and community phase shifts',
'author':
'Verg\xe9s',
'doi-asserted-by':
'crossref',
'first-page':
'20140846',
'journal-title':
'Proceedings of the Royal Society B: Biological Sciences',
'key':
'10.1002/ecy.1625-BIB0075|ecy1625-cit-0075',
'volume':
'281',
'year':
'2014'
}, {
'DOI':
'10.1002/ehs2.1211',
'article-title':
'Impacts of climate change on mangrove ecosystems: a region by region overview',
'author':
'Ward',
'doi-asserted-by':
'crossref',
'first-page':
'e012111',
'journal-title':
'Ecosystem Health and Sustainability',
'key':
'10.1002/ecy.1625-BIB0076|ecy1625-cit-0076',
'volume':
'2',
'year':
'2016'
}, {
'author': 'West',
'first-page': '193',
'key': '10.1002/ecy.1625-BIB0077|ecy1625-cit-0077',
'volume-title': 'Wet coastal ecosystems',
'year': '1977'
}, {
'DOI':
'10.1016/S0034-6667(00)00042-7',
'article-title':
'Pollen assemblages as paleoenvironmental proxies in the Florida Everglades',
'author':
'Willard',
'doi-asserted-by':
'crossref',
'first-page':
'213',
'journal-title':
'Review of Palaeobotany and Palynology',
'key':
'10.1002/ecy.1625-BIB0078|ecy1625-cit-0078',
'volume':
'113',
'year':
'2001'
}, {
'author': 'Woodward',
'key': '10.1002/ecy.1625-BIB0079|ecy1625-cit-0079',
'volume-title': 'Climate and plant distribution',
'year': '1987'
}, {
'DOI':
'10.1111/1365-2745.12571',
'article-title':
'Salt marsh-mangrove ecotones: using structural gradients to investigate the effects of woody plant encroachment on plant-soil interactions and ecosystem carbon pools',
'author':
'Yando',
'doi-asserted-by':
'crossref',
'first-page':
'1020',
'journal-title':
'Journal of Ecology',
'key':
'10.1002/ecy.1625-BIB0080|ecy1625-cit-0080',
'volume':
'104',
'year':
'2016'
}, {
'DOI':
'10.1016/j.yqres.2015.03.005',
'article-title':
'Palynological reconstruction of environmental changes in coastal wetlands of the Florida Everglades since the mid-Holocene',
'author':
'Yao',
'doi-asserted-by':
'crossref',
'first-page':
'449',
'journal-title':
'Quaternary Research',
'key':
'10.1002/ecy.1625-BIB0081|ecy1625-cit-0081',
'volume':
'83',
'year':
'2015'
}, {
'DOI':
'10.1002/ecs2.1366',
'article-title':
'Remote sensing of seasonal changes and disturbances in mangrove forest: a case study from South Florida',
'author':
'Zhang',
'doi-asserted-by':
'crossref',
'first-page':
'e01366',
'journal-title':
'Ecosphere',
'key':
'10.1002/ecy.1625-BIB0082|ecy1625-cit-0082',
'volume':
'7',
'year':
'2016'
}],
'reference-count':
82,
'references-count':
82,
'relation': {
'cites': []
},
'score':
1.0,
'short-container-title': ['Ecology'],
'short-title': [],
'source':
'Crossref',
'subject': ['Ecology, Evolution, Behavior and Systematics'],
'subtitle': [],
'title': [
'Mangrove expansion and contraction at a poleward range limit: climate extremes and land-ocean temperature gradients'
],
'type':
'journal-article',
'volume':
'98'
},
'message-type': 'work',
'message-version': '1.0.0',
'status': 'ok'
}
crossref_200_not_ok = {
'message': None,
'message-type': 'work',
'message-version': '1.0.0',
'status': 'error'
}
crossref_200_ok_2_date_parts = {
'message': {
'published-online': {
'date-parts': [[2016, 12]]
}
},
'message-type': 'work',
'message-version': '1.0.0',
'status': 'ok'
}
crossref_200_ok_1_date_part = {
'message': {
'published-online': {
'date-parts': [[2016]]
}
},
'message-type': 'work',
'message-version': '1.0.0',
'status': 'ok'
}
crossref_200_ok_message_empty = {
'message': {},
'message-type': 'work',
'message-version': '1.0.0',
'status': 'ok'
}
unpaywall_200_ok = {
"best_oa_location": {
"evidence": "open (via page says license)",
"host_type": "publisher",
"is_best": True,
"license": "cc-by-nc-nd",
"pmh_id": None,
"updated": "2017-09-10T13: 49: 11.765139",
"url": "http: //onlinelibrary.wiley.com/doi/10.1002/2015JB012376/pdf",
"url_for_landing_page": "http: //doi.org/10.1002/2015jb012376",
"url_for_pdf": "http: //onlinelibrary.wiley.com/doi/10.1002/2015JB012376/pdf",
"version": "publishedVersion",
},
"data_standard": 2,
"doi": "10.1002/2015jb012376",
"doi_url": "https: //doi.org/10.1002/2015jb012376",
"genre": "journal-article",
"is_oa": True,
"journal_is_in_doaj": False,
"journal_is_oa": False,
"journal_issns": "2169-9313",
"journal_name": "Journal of Geophysical Research: Solid Earth",
"oa_locations": [
{
"evidence": "open (via page says license)",
"host_type": "publisher",
"is_best": True,
"license": "cc-by-nc-nd",
"pmh_id": None,
"updated": "2017-09-10T13: 49: 11.765139",
"url": "http: //onlinelibrary.wiley.com/doi/10.1002/2015JB012376/pdf",
"url_for_landing_page": "http: //doi.org/10.1002/2015jb012376",
"url_for_pdf": "http: //onlinelibrary.wiley.com/doi/10.1002/2015JB012376/pdf",
"version": "publishedVersion",
}
],
"published_date": "2016-04-01",
"publisher": "Wiley-Blackwell",
"title": "Tomographic Rayleigh wave group velocities in the Central Valley, California, centered on the Sacramento/San Joaquin Delta",
"updated": "2018-06-17T06: 00: 55.215000",
"year": 2016,
"z_authors": [
{
"affiliation": [
{"name": "U.S. Geological Survey; Menlo Park California USA"}
],
"family": "Fletcher",
"given": "Jon B.",
},
{
"affiliation": [
{"name": "U.S. Geological Survey; Menlo Park California USA"}
],
"family": "Erdem",
"given": "Jemile",
},
{
"affiliation": [
{
"name": "Department of Geophysics; Stanford University; Stanford California USA"
}
],
"family": "Seats",
"given": "Kevin",
},
{
"affiliation": [
{
"name": "Department of Geophysics; Stanford University; Stanford California USA"
}
],
"family": "Lawrence",
"given": "Jesse",
},
],
}
landing_present = {
"doi": "1289018729847",
"best_oa_location": {
"url_for_landing_page": "https://wwww.good-example.gov/landingpage1",
"url_for_pdf": None,
"host_type": "publisher",
},
}
null_landing = {
"doi": "1289018729847",
"best_oa_location": {
"url_for_landing_page": None,
"url_for_pdf": "https://www.good-example.gov/my-file.pdf",
},
} | jkreft-usgs/PubsWarehouse_UI | server/pubs_ui/pubswh/tests/test_data.py | Python | unlicense | 51,959 |
.mocha {
position: absolute;
top: 0;
left: 0;
display: none;
overflow: hidden;
}
.mocha.isFocused {
}
.mochaOverlay {
position: absolute;
top: 0;
left: 0;
}
.mochaTitlebar {
width: 100%;
overflow: hidden;
}
.mochaTitlebar h3 {
font-size: 12px;
font-weight: normal;
line-height: 15px;
margin: 5px 10px 4px 10px;
padding: 0;
color: #CCCCCC;
}
.mocha.isFocused .mochaTitlebar h3 {
color: #ffffff;
}
.mochaToolbarWrapper {
width: 100%; /* For IE */
position: relative;
height: 29px;
background: #f1f1f1;
overflow: hidden;
border-top: 1px solid #d9d9d9;
}
div.mochaToolbarWrapper.bottom {
border: 0;
border-bottom: 1px solid #d9d9d9;
}
.mochaToolbar {
width: 100%; /* For IE */
border-top: 1px solid #fff;
}
.mochaContentBorder {
border-top: 1px solid #adb9c9;
border-bottom: 1px solid #b8c6d9;
}
.mochaContentWrapper { /* Has a fixed height and scrollbars if required. */
font-size: 12px;
overflow: auto;
}
.mochaContent {
padding: 10px 12px;
}
.mocha .handle {
position: absolute;
background: #0f0;
width: 3px;
height: 3px;
z-index: 2;
opacity: .0;
filter: alpha(opacity=0);
-moz-opacity: .0;
overflow: hidden;
font-size: 1px; /* For IE6 */
}
.mocha .corner { /* Corner resize handles */
background: #f00;
width: 10px;
height: 10px;
}
.mocha .cornerSE { /* Bottom right resize handle */
background: #f00;
width: 20px;
height: 20px;
}
.mochaCanvasHeader {
position: absolute;
top: 0;
left: 0;
background: transparent;
z-index: -1;
display: none;
overflow: hidden;
}
.mochaControls {
position: absolute;
width: 52px;
top: 8px;
right: 8px;
height: 14px;
z-index: 4;
background: transparent;
}
.mochaCanvasControls {
position: absolute;
top: 8px;
right: 8px;
z-index: 3;
background: transparent;
}
/*
To use images for these buttons:
1. Set the useCanvasControls window option to false.
2. If you use a different button size you may need to reposition the controls.
Modify the controlsOffset window option.
2. Add background images to each button.
*/
.mochaMinimizeButton, .mochaMaximizeButton, .mochaCloseButton {
float: right;
width: 14px;
height: 14px;
font-size: 1px;
cursor: pointer;
z-index: 4;
background: #f00;
margin-left: 5px;
}
.mochaMinimizeButton {
margin-left: 0;
}
.mochaMaximizeButton {
}
.mochaCloseButton {
}
.mochaSpinner {
visibility: hidden;
position: absolute;
bottom: 7px;
left: 6px;
width: 16px;
height: 16px;
background: url(../images/spinner.gif) no-repeat;
}
.mochaButtonbox {
padding: 4px;
}
.mochaButton {
background: #E5ECF9 url(../images/ui-bg_glass_100_E5ECF9_1x400.png) repeat-x scroll 50% 50%;
border: 1px solid #93B4D9;
cursor: pointer;
float: right;
line-height: 1.4em;
margin: 0 0.4em 0.5em 0;
overflow: visible;
padding: 0.1em 0.6em;
width: auto;
font-weight: bold;
}
.mochaImageButton {
padding: 0.1em 0.3em;
margin: 0 0.4em 0.4em 0;
vertical-align: middle;
}
.mochaImageButton img {
float: left;
margin-right: 5px;
}
.mochaImageButton div {
float: left;
line-height: 22px;
}
.mochaTabsNav {
border: 0 none;
list-style-image: none;
list-style-position: outside;
list-style-type: none;
position: relative;
display: block;
margin: 0;
padding: 0;
color: #000000;
font-weight: bold;
}
.mochaTabsNav li {
border-bottom-width:0 !important;
float:left;
margin:0 0.5em -1px 0;
padding:0;
position:relative;
-moz-border-radius-topleft: 3px;
-moz-border-radius-topright: 3px;
}
.mochaTabsNav a:link, .mochaTabsNav a:visited {
color: #000000;
text-decoration: none;
}
.mochaTabsNav li a {
float: left;
padding: 3px 8px;
text-decoration: none;
outline-style: none;
}
.mochaTab {
background: #E5ECF9 url(../images/ui-bg_glass_100_E5ECF9_1x400.png) repeat-x scroll 50% 50%;
border: 1px solid #93B4D9;
}
.mochaTabSelected {
background: #C3D9FF url(../images/ui-bg_glass_65_C3D9FF_1x400.png) repeat-x scroll 50% 50%;
padding-bottom: 1px !important;
border-bottom-width: 0;
}
.mochaTabContent {
clear: both;
background: #C8E2FB none repeat scroll 0 0;
border: 1px solid #93B4D9;
display: block;
padding: 8px;
-moz-border-radius-bottomleft: 3px;
-moz-border-radius-bottomright: 3px;
}
.mochaIframe {
width: 100%;
}
/* Fix for IE6 select z-index issue */
.zIndexFix {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: -1;
filter: mask();
width: 100px;
height: 100px;
border: 1px solid transparent;
}
/* Modals */
.modal2 {
border: 8px solid #fff;
}
.modal2 .mochaContentBorder {
border-width: 0px;
}
/* Overlay */
#modalOverlay {
background: #666666 url(../images/ui-bg_diagonals-thick_20_666666_40x40.png) repeat scroll 50% 50%;
display: none;
left: 0;
top: 0;
opacity: 0;
position: fixed;
width: 100%;
z-index: 10000;
}
| p2k/pygowave-legacy | media/css/mocha.css | CSS | apache-2.0 | 4,769 |
#
# Author:: Harlan Barnes (<[email protected]>)
# Cookbook Name:: lita
# Recipe:: default
#
# Installs and configures lita
#
# Copyright 2014, Harlan Barnes
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe "apt::default" if node["platform_family"] == "debian"
include_recipe "build-essential::default"
include_recipe "lita::ruby"
include_recipe "lita::redis"
include_recipe "lita::install"
include_recipe "lita::init_service"
| litaio/chef-lita | recipes/default.rb | Ruby | apache-2.0 | 942 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.