code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
APPLICATION = socket_zep
include ../Makefile.tests_common
BOARD_WHITELIST = native # socket_zep is only available on native
# Cannot run the test on `murdock`
# ZEP: Unable to connect socket: Cannot assign requested address
TEST_ON_CI_BLACKLIST += native
DISABLE_MODULE += auto_init
USEMODULE += od
USEMODULE += socket_zep
CFLAGS += -DDEVELHELP
TERMFLAGS ?= -z [::1]:17754
include $(RIOTBASE)/Makefile.include
| rfuentess/RIOT | tests/socket_zep/Makefile | Makefile | lgpl-2.1 | 422 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2009 - 2013 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.
//
// ---------------------------------------------------------------------
// check DoFTools::make_zero_boundary_constraints by comparing
// apply_boundary_values with a zero function to
// make_zero_boundary_constraints
//
// this is the version of the test with only one boundary
// indicator selected
#include "../tests.h"
#include <deal.II/base/function_lib.h>
#include <deal.II/lac/sparsity_pattern.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/numerics/vector_tools.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/fe/fe_q.h>
#include <fstream>
#include <iomanip>
template <int dim>
void test ()
{
deallog << dim << "D" << std::endl;
Triangulation<dim> triangulation;
const Point<dim> p2 = (dim == 1 ?
Point<dim>(1.) :
(dim == 2 ?
Point<dim>(1.,1.) :
Point<dim>(1.,1.,1.)));
GridGenerator::hyper_rectangle (triangulation,
Point<dim>(), p2, true);
// refine the mesh in a random way
triangulation.refine_global (4-dim);
for (unsigned int i=0; i<11-2*dim; ++i)
{
typename Triangulation<dim>::active_cell_iterator
cell = triangulation.begin_active();
for (unsigned int index=0; cell != triangulation.end(); ++cell, ++index)
if (index % (3*dim) == 0)
cell->set_refine_flag();
triangulation.execute_coarsening_and_refinement ();
}
deallog << "Number of cells: "
<< triangulation.n_active_cells() << std::endl;
// assign quadrature, set up a
// DoFHandler, and distribute dofs
FE_Q<dim> fe(1);
DoFHandler<dim> dof_handler (triangulation);
dof_handler.distribute_dofs (fe);
deallog << "Number of dofs : "
<< dof_handler.n_dofs() << std::endl;
// then set up a sparsity pattern
// and two matrices and vectors on
// top of it.
SparsityPattern sparsity (dof_handler.n_dofs(),
dof_handler.n_dofs(),
dof_handler.max_couplings_between_dofs());
DoFTools::make_sparsity_pattern (dof_handler, sparsity);
sparsity.compress ();
SparseMatrix<double> A(sparsity), B(sparsity);
Vector<double> a1 (dof_handler.n_dofs());
// initialize object denoting zero
// boundary values and boundary
// constraints
std::map<types::global_dof_index,double> boundary_values;
VectorTools::interpolate_boundary_values (dof_handler,
1,
ConstantFunction<dim>(1.),
boundary_values);
ConstraintMatrix constraints;
constraints.clear();
DoFTools::make_zero_boundary_constraints (dof_handler,
1,
constraints);
constraints.close();
// then fill two matrices by
// setting up bogus matrix entries
// and for A applying constraints
// right away and for B applying
// constraints later on
std::vector<types::global_dof_index> local_dofs (fe.dofs_per_cell);
FullMatrix<double> local_matrix (fe.dofs_per_cell, fe.dofs_per_cell);
Vector<double> local_vector (fe.dofs_per_cell);
for (typename DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active();
cell != dof_handler.end(); ++cell)
{
cell->get_dof_indices (local_dofs);
local_matrix = 0;
// create local matrices
for (unsigned int i=0; i<fe.dofs_per_cell; ++i)
for (unsigned int j=0; j<fe.dofs_per_cell; ++j)
for (unsigned int j=0; j<fe.dofs_per_cell; ++j)
local_matrix(i,j) = (i+1.)*(j+1.)*(local_dofs[i]+1.)*(local_dofs[j]+1.);
for (unsigned int i=0; i<fe.dofs_per_cell; ++i)
local_vector(i) = (i+1.)*(local_dofs[i]+1.);
// for matrix A and vector a1 apply boundary
// values
MatrixTools::local_apply_boundary_values (boundary_values, local_dofs,
local_matrix, local_vector,
true);
cell->distribute_local_to_global (local_matrix, A);
cell->distribute_local_to_global (local_vector, a1);
// for matrix B cast constraint
// matrix
constraints.distribute_local_to_global (local_matrix,
local_dofs,
B);
}
// here comes the check: compare
// the l1_norm of matrices A and B,
// their difference should be zero
deallog << "|A| = " << A.l1_norm() << std::endl;
deallog << "|B| = " << B.l1_norm() << std::endl;
Assert (A.l1_norm() - B.l1_norm() == 0,
ExcInternalError());
}
int main ()
{
std::ofstream logfile("output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
try
{
test<1> ();
test<2> ();
test<3> ();
}
catch (std::exception &exc)
{
deallog << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
deallog << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
deallog << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
deallog << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
};
}
| flow123d/dealii | tests/bits/make_boundary_constraints_02.cc | C++ | lgpl-2.1 | 6,684 |
<?xml version="1.0" encoding="UTF-8"?>
<!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" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Qt 4.8: main.cpp Example File (webkit/webftpclient/main.cpp)</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style/superfish.css" />
<link rel="stylesheet" type="text/css" href="style/narrow.css" />
<!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->
<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>
</head>
<body class="" onload="CheckEmptyAndLoadList();">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="narrowsearch"></div>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
<li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul>
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul>
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="supported-platforms.html">Supported Platforms</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul>
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search" id="sidebarsearch">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
<div id="resultdialog">
<a href="#" id="resultclose">Close</a>
<p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p>
<p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p>
<ul id="resultlist" class="all">
</ul>
</div>
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content mainContent">
<h1 class="title">main.cpp Example File</h1>
<span class="small-subtitle">webkit/webftpclient/main.cpp</span>
<!-- $$$webkit/webftpclient/main.cpp-description -->
<div class="descr"> <a name="details"></a>
<pre class="cpp"> <span class="comment">/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** 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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/</span>
<span class="preprocessor">#include <QtGui></span>
<span class="preprocessor">#include <QtWebKit></span>
<span class="preprocessor">#include "ftpview.h"</span>
<span class="type">int</span> main(<span class="type">int</span> argc<span class="operator">,</span> <span class="type">char</span> <span class="operator">*</span>argv<span class="operator">[</span><span class="operator">]</span>)
{
<span class="type"><a href="qapplication.html">QApplication</a></span> app(argc<span class="operator">,</span> argv);
FtpView view;
view<span class="operator">.</span>setUrl(<span class="type"><a href="qurl.html">QUrl</a></span>(<span class="string">"ftp://ftp.qt.nokia.com"</span>));
view<span class="operator">.</span>show();
<span class="keyword">return</span> app<span class="operator">.</span>exec();
}</pre>
</div>
<!-- @@@webkit/webftpclient/main.cpp -->
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2014 Digia Plc and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Digia, Qt and their respective logos are trademarks of Digia Plc
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
<script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>
| eric100lin/Qt-4.8.6 | doc/html/webkit-webftpclient-main-cpp.html | HTML | lgpl-2.1 | 12,196 |
/* Copyright (C) 1991,93,94,95,96,97,99,2000,03 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Based on strlen implementation by Torbjorn Granlund (tege@sics.se),
with help from Dan Sahlin (dan@sics.se) and
bug fix and commentary by Jim Blandy (jimb@ai.mit.edu);
adaptation to strchr suggested by Dick Karpinski (dick@cca.ucsf.edu),
and implemented by Roland McGrath (roland@ai.mit.edu).
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <string.h>
#include <stdlib.h>
/* Experimentally off - libc_hidden_proto(strchr) */
libc_hidden_proto(abort)
#include "memcopy.h"
/* Find the first occurrence of C in S. */
char *strchr (const char *s, int c_in)
{
const unsigned char *char_ptr;
const unsigned long int *longword_ptr;
unsigned long int longword, magic_bits, charmask;
unsigned reg_char c;
c = (unsigned char) c_in;
/* Handle the first few characters by reading one character at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
for (char_ptr = (const unsigned char *) s;
((unsigned long int) char_ptr & (sizeof (longword) - 1)) != 0;
++char_ptr)
if (*char_ptr == c)
return (void *) char_ptr;
else if (*char_ptr == '\0')
return NULL;
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to 8-byte longwords. */
longword_ptr = (unsigned long int *) char_ptr;
/* Bits 31, 24, 16, and 8 of this number are zero. Call these bits
the "holes." Note that there is a hole just to the left of
each byte, with an extra at the end:
bits: 01111110 11111110 11111110 11111111
bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
The 1-bits make sure that carries propagate to the next 0-bit.
The 0-bits provide holes for carries to fall into. */
switch (sizeof (longword))
{
case 4: magic_bits = 0x7efefeffL; break;
case 8: magic_bits = ((0x7efefefeL << 16) << 16) | 0xfefefeffL; break;
default:
abort ();
}
/* Set up a longword, each of whose bytes is C. */
charmask = c | (c << 8);
charmask |= charmask << 16;
if (sizeof (longword) > 4)
/* Do the shift in two steps to avoid a warning if long has 32 bits. */
charmask |= (charmask << 16) << 16;
if (sizeof (longword) > 8)
abort ();
/* Instead of the traditional loop which tests each character,
we will test a longword at a time. The tricky part is testing
if *any of the four* bytes in the longword in question are zero. */
for (;;)
{
/* We tentatively exit the loop if adding MAGIC_BITS to
LONGWORD fails to change any of the hole bits of LONGWORD.
1) Is this safe? Will it catch all the zero bytes?
Suppose there is a byte with all zeros. Any carry bits
propagating from its left will fall into the hole at its
least significant bit and stop. Since there will be no
carry from its most significant bit, the LSB of the
byte to the left will be unchanged, and the zero will be
detected.
2) Is this worthwhile? Will it ignore everything except
zero bytes? Suppose every byte of LONGWORD has a bit set
somewhere. There will be a carry into bit 8. If bit 8
is set, this will carry into bit 16. If bit 8 is clear,
one of bits 9-15 must be set, so there will be a carry
into bit 16. Similarly, there will be a carry into bit
24. If one of bits 24-30 is set, there will be a carry
into bit 31, so all of the hole bits will be changed.
The one misfire occurs when bits 24-30 are clear and bit
31 is set; in this case, the hole at bit 31 is not
changed. If we had access to the processor carry flag,
we could close this loophole by putting the fourth hole
at bit 32!
So it ignores everything except 128's, when they're aligned
properly.
3) But wait! Aren't we looking for C as well as zero?
Good point. So what we do is XOR LONGWORD with a longword,
each of whose bytes is C. This turns each byte that is C
into a zero. */
longword = *longword_ptr++;
/* Add MAGIC_BITS to LONGWORD. */
if ((((longword + magic_bits)
/* Set those bits that were unchanged by the addition. */
^ ~longword)
/* Look at only the hole bits. If any of the hole bits
are unchanged, most likely one of the bytes was a
zero. */
& ~magic_bits) != 0 ||
/* That caught zeroes. Now test for C. */
((((longword ^ charmask) + magic_bits) ^ ~(longword ^ charmask))
& ~magic_bits) != 0)
{
/* Which of the bytes was C or zero?
If none of them were, it was a misfire; continue the search. */
const unsigned char *cp = (const unsigned char *) (longword_ptr - 1);
if (*cp == c)
return (char *) cp;
else if (*cp == '\0')
return NULL;
if (*++cp == c)
return (char *) cp;
else if (*cp == '\0')
return NULL;
if (*++cp == c)
return (char *) cp;
else if (*cp == '\0')
return NULL;
if (*++cp == c)
return (char *) cp;
else if (*cp == '\0')
return NULL;
if (sizeof (longword) > 4)
{
if (*++cp == c)
return (char *) cp;
else if (*cp == '\0')
return NULL;
if (*++cp == c)
return (char *) cp;
else if (*cp == '\0')
return NULL;
if (*++cp == c)
return (char *) cp;
else if (*cp == '\0')
return NULL;
if (*++cp == c)
return (char *) cp;
else if (*cp == '\0')
return NULL;
}
}
}
return NULL;
}
libc_hidden_weak(strchr)
#ifdef __UCLIBC_SUSV3_LEGACY__
weak_alias(strchr,index)
#endif
| ystk/debian-uclibc | libc/string/generic/strchr.c | C | lgpl-2.1 | 6,281 |
/*
* filter_vignette.c -- vignette filter
* Copyright (c) 2007 Marco Gittler <g.marco@freenet.de>
*
* 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
*/
#include <framework/mlt_filter.h>
#include <framework/mlt_frame.h>
#include <framework/mlt_geometry.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MIN(a,b) (a<b?a:b)
#define MAX(a,b) (a<b?b:a)
#define SIGMOD_STEPS 1000
#define POSITION_VALUE(p,s,e) (s+((double)(e-s)*p ))
//static double pow2[SIGMOD_STEPS];
static float geometry_to_float(char *val, mlt_position pos )
{
float ret=0.0;
struct mlt_geometry_item_s item;
mlt_geometry geom=mlt_geometry_init();
mlt_geometry_parse(geom,val,-1,-1,-1);
mlt_geometry_fetch(geom,&item , pos );
ret=item.x;
mlt_geometry_close(geom);
return ret;
}
static int filter_get_image( mlt_frame this, uint8_t **image, mlt_image_format *format, int *width, int *height, int writable )
{
mlt_filter filter = mlt_frame_pop_service( this );
*format = mlt_image_yuv422;
int error = mlt_frame_get_image( this, image, format, width, height, 1 );
if ( error == 0 && *image )
{
float smooth, radius, cx, cy, opac;
mlt_properties filter_props = MLT_FILTER_PROPERTIES( filter ) ;
mlt_position pos = mlt_filter_get_position( filter, this );
smooth = geometry_to_float ( mlt_properties_get( filter_props , "smooth" ) , pos ) * 100.0 ;
radius = geometry_to_float ( mlt_properties_get( filter_props , "radius" ) , pos ) * *width;
cx = geometry_to_float ( mlt_properties_get( filter_props , "x" ) , pos ) * *width;
cy = geometry_to_float ( mlt_properties_get( filter_props , "y" ) , pos ) * *height;
opac = geometry_to_float ( mlt_properties_get( filter_props , "opacity" ) , pos );
int video_width = *width;
int video_height = *height;
int x,y;
int w2=cx,h2=cy;
double delta=1.0;
double max_opac=opac;
for (y=0;y<video_height;y++){
int h2_pow2=pow(y-h2,2.0);
for (x=0;x<video_width;x++){
uint8_t *pix=(*image+y*video_width*2+x*2);
int dx=sqrt(h2_pow2+pow(x-w2,2.0));
if (radius-smooth>dx){ //center, make not darker
continue;
}
else if (radius+smooth<=dx){//max dark after smooth area
delta=0.0;
}else{
//double sigx=5.0-10.0*(double)(dx-radius+smooth)/(2.0*smooth);//smooth >10 inner area, <-10 in dark area
//delta=pow2[((int)((sigx+10.0)*SIGMOD_STEPS/20.0))];//sigmoidal
delta = ((double)(radius+smooth-dx)/(2.0*smooth));//linear
}
delta=MAX(max_opac,delta);
*pix=(double)(*pix)*delta;
*(pix+1)=((double)(*(pix+1)-127.0)*delta)+127.0;
}
}
// short a, short b, short c, short d
// a= gray val pix 1
// b: +=blue, -=yellow
// c: =gray pix 2
// d: +=red,-=green
}
return error;
}
static mlt_frame filter_process( mlt_filter this, mlt_frame frame )
{
mlt_frame_push_service( frame, this );
mlt_frame_push_get_image( frame, filter_get_image );
return frame;
}
mlt_filter filter_vignette_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
{
mlt_filter this = mlt_filter_new( );
//int i=0;
if ( this != NULL )
{
/*
for (i=-SIGMOD_STEPS/2;i<SIGMOD_STEPS/2;i++){
pow2[i+SIGMOD_STEPS/2]=1.0/(1.0+pow(2.0,-((double)i)/((double)SIGMOD_STEPS/20.0)));
}
*/
this->process = filter_process;
mlt_properties_set( MLT_FILTER_PROPERTIES( this ), "smooth", "0.8" );
mlt_properties_set( MLT_FILTER_PROPERTIES( this ), "radius", "0.5" );
mlt_properties_set( MLT_FILTER_PROPERTIES( this ), "x", "0.5" );
mlt_properties_set( MLT_FILTER_PROPERTIES( this ), "y", "0.5" );
mlt_properties_set( MLT_FILTER_PROPERTIES( this ), "opacity", "0.0" );
//mlt_properties_set( MLT_FILTER_PROPERTIES( this ), "end", "" );
}
return this;
}
| ttill/MLT-roto-tracking | src/modules/oldfilm/filter_vignette.c | C | lgpl-2.1 | 4,428 |
/* GIO - GLib Input, Output and Streaming Library
*
* Copyright © 2008 Christian Kellner, Samuel Cormier-Iijima
* Copyright © 2009 codethink
* Copyright © 2009 Red Hat, Inc
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors: Christian Kellner <gicmo@gnome.org>
* Samuel Cormier-Iijima <sciyoshi@gmail.com>
* Ryan Lortie <desrt@desrt.ca>
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include "gsocketlistener.h"
#include <gio/gioenumtypes.h>
#include <gio/gtask.h>
#include <gio/gcancellable.h>
#include <gio/gsocketaddress.h>
#include <gio/ginetaddress.h>
#include <gio/gioerror.h>
#include <gio/gsocket.h>
#include <gio/gsocketconnection.h>
#include <gio/ginetsocketaddress.h>
#include "glibintl.h"
#include "gmarshal-internal.h"
/**
* SECTION:gsocketlistener
* @title: GSocketListener
* @short_description: Helper for accepting network client connections
* @include: gio/gio.h
* @see_also: #GThreadedSocketService, #GSocketService.
*
* A #GSocketListener is an object that keeps track of a set
* of server sockets and helps you accept sockets from any of the
* socket, either sync or async.
*
* Add addresses and ports to listen on using g_socket_listener_add_address()
* and g_socket_listener_add_inet_port(). These will be listened on until
* g_socket_listener_close() is called. Dropping your final reference to the
* #GSocketListener will not cause g_socket_listener_close() to be called
* implicitly, as some references to the #GSocketListener may be held
* internally.
*
* If you want to implement a network server, also look at #GSocketService
* and #GThreadedSocketService which are subclasses of #GSocketListener
* that make this even easier.
*
* Since: 2.22
*/
enum
{
PROP_0,
PROP_LISTEN_BACKLOG
};
enum
{
EVENT,
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };
static GQuark source_quark = 0;
struct _GSocketListenerPrivate
{
GPtrArray *sockets;
GMainContext *main_context;
int listen_backlog;
guint closed : 1;
};
G_DEFINE_TYPE_WITH_PRIVATE (GSocketListener, g_socket_listener, G_TYPE_OBJECT)
static void
g_socket_listener_finalize (GObject *object)
{
GSocketListener *listener = G_SOCKET_LISTENER (object);
if (listener->priv->main_context)
g_main_context_unref (listener->priv->main_context);
/* Do not explicitly close the sockets. Instead, let them close themselves if
* their final reference is dropped, but keep them open if a reference is
* held externally to the GSocketListener (which is possible if
* g_socket_listener_add_socket() was used).
*/
g_ptr_array_free (listener->priv->sockets, TRUE);
G_OBJECT_CLASS (g_socket_listener_parent_class)
->finalize (object);
}
static void
g_socket_listener_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GSocketListener *listener = G_SOCKET_LISTENER (object);
switch (prop_id)
{
case PROP_LISTEN_BACKLOG:
g_value_set_int (value, listener->priv->listen_backlog);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
}
}
static void
g_socket_listener_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GSocketListener *listener = G_SOCKET_LISTENER (object);
switch (prop_id)
{
case PROP_LISTEN_BACKLOG:
g_socket_listener_set_backlog (listener, g_value_get_int (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
}
}
static void
g_socket_listener_class_init (GSocketListenerClass *klass)
{
GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
gobject_class->finalize = g_socket_listener_finalize;
gobject_class->set_property = g_socket_listener_set_property;
gobject_class->get_property = g_socket_listener_get_property;
g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
g_param_spec_int ("listen-backlog",
P_("Listen backlog"),
P_("outstanding connections in the listen queue"),
0,
2000,
10,
G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GSocketListener::event:
* @listener: the #GSocketListener
* @event: the event that is occurring
* @socket: the #GSocket the event is occurring on
*
* Emitted when @listener's activity on @socket changes state.
* Note that when @listener is used to listen on both IPv4 and
* IPv6, a separate set of signals will be emitted for each, and
* the order they happen in is undefined.
*
* Since: 2.46
*/
signals[EVENT] =
g_signal_new (I_("event"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GSocketListenerClass, event),
NULL, NULL,
_g_cclosure_marshal_VOID__ENUM_OBJECT,
G_TYPE_NONE, 2,
G_TYPE_SOCKET_LISTENER_EVENT,
G_TYPE_SOCKET);
g_signal_set_va_marshaller (signals[EVENT],
G_TYPE_FROM_CLASS (gobject_class),
_g_cclosure_marshal_VOID__ENUM_OBJECTv);
source_quark = g_quark_from_static_string ("g-socket-listener-source");
}
static void
g_socket_listener_init (GSocketListener *listener)
{
listener->priv = g_socket_listener_get_instance_private (listener);
listener->priv->sockets =
g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
listener->priv->listen_backlog = 10;
}
/**
* g_socket_listener_new:
*
* Creates a new #GSocketListener with no sockets to listen for.
* New listeners can be added with e.g. g_socket_listener_add_address()
* or g_socket_listener_add_inet_port().
*
* Returns: a new #GSocketListener.
*
* Since: 2.22
*/
GSocketListener *
g_socket_listener_new (void)
{
return g_object_new (G_TYPE_SOCKET_LISTENER, NULL);
}
static gboolean
check_listener (GSocketListener *listener,
GError **error)
{
if (listener->priv->closed)
{
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
_("Listener is already closed"));
return FALSE;
}
return TRUE;
}
/**
* g_socket_listener_add_socket:
* @listener: a #GSocketListener
* @socket: a listening #GSocket
* @source_object: (nullable): Optional #GObject identifying this source
* @error: #GError for error reporting, or %NULL to ignore.
*
* Adds @socket to the set of sockets that we try to accept
* new clients from. The socket must be bound to a local
* address and listened to.
*
* @source_object will be passed out in the various calls
* to accept to identify this particular source, which is
* useful if you're listening on multiple addresses and do
* different things depending on what address is connected to.
*
* The @socket will not be automatically closed when the @listener is finalized
* unless the listener held the final reference to the socket. Before GLib 2.42,
* the @socket was automatically closed on finalization of the @listener, even
* if references to it were held elsewhere.
*
* Returns: %TRUE on success, %FALSE on error.
*
* Since: 2.22
*/
gboolean
g_socket_listener_add_socket (GSocketListener *listener,
GSocket *socket,
GObject *source_object,
GError **error)
{
if (!check_listener (listener, error))
return FALSE;
/* TODO: Check that socket it is bound & not closed? */
if (g_socket_is_closed (socket))
{
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
_("Added socket is closed"));
return FALSE;
}
g_object_ref (socket);
g_ptr_array_add (listener->priv->sockets, socket);
if (source_object)
g_object_set_qdata_full (G_OBJECT (socket), source_quark,
g_object_ref (source_object), g_object_unref);
if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
return TRUE;
}
/**
* g_socket_listener_add_address:
* @listener: a #GSocketListener
* @address: a #GSocketAddress
* @type: a #GSocketType
* @protocol: a #GSocketProtocol
* @source_object: (nullable): Optional #GObject identifying this source
* @effective_address: (out) (optional): location to store the address that was bound to, or %NULL.
* @error: #GError for error reporting, or %NULL to ignore.
*
* Creates a socket of type @type and protocol @protocol, binds
* it to @address and adds it to the set of sockets we're accepting
* sockets from.
*
* Note that adding an IPv6 address, depending on the platform,
* may or may not result in a listener that also accepts IPv4
* connections. For more deterministic behavior, see
* g_socket_listener_add_inet_port().
*
* @source_object will be passed out in the various calls
* to accept to identify this particular source, which is
* useful if you're listening on multiple addresses and do
* different things depending on what address is connected to.
*
* If successful and @effective_address is non-%NULL then it will
* be set to the address that the binding actually occurred at. This
* is helpful for determining the port number that was used for when
* requesting a binding to port 0 (ie: "any port"). This address, if
* requested, belongs to the caller and must be freed.
*
* Call g_socket_listener_close() to stop listening on @address; this will not
* be done automatically when you drop your final reference to @listener, as
* references may be held internally.
*
* Returns: %TRUE on success, %FALSE on error.
*
* Since: 2.22
*/
gboolean
g_socket_listener_add_address (GSocketListener *listener,
GSocketAddress *address,
GSocketType type,
GSocketProtocol protocol,
GObject *source_object,
GSocketAddress **effective_address,
GError **error)
{
GSocketAddress *local_address;
GSocketFamily family;
GSocket *socket;
if (!check_listener (listener, error))
return FALSE;
family = g_socket_address_get_family (address);
socket = g_socket_new (family, type, protocol, error);
if (socket == NULL)
return FALSE;
g_socket_set_listen_backlog (socket, listener->priv->listen_backlog);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BINDING, socket);
if (!g_socket_bind (socket, address, TRUE, error))
{
g_object_unref (socket);
return FALSE;
}
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BOUND, socket);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENING, socket);
if (!g_socket_listen (socket, error))
{
g_object_unref (socket);
return FALSE;
}
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENED, socket);
local_address = NULL;
if (effective_address)
{
local_address = g_socket_get_local_address (socket, error);
if (local_address == NULL)
{
g_object_unref (socket);
return FALSE;
}
}
if (!g_socket_listener_add_socket (listener, socket,
source_object,
error))
{
if (local_address)
g_object_unref (local_address);
g_object_unref (socket);
return FALSE;
}
if (effective_address)
*effective_address = local_address;
g_object_unref (socket); /* add_socket refs this */
return TRUE;
}
/**
* g_socket_listener_add_inet_port:
* @listener: a #GSocketListener
* @port: an IP port number (non-zero)
* @source_object: (nullable): Optional #GObject identifying this source
* @error: #GError for error reporting, or %NULL to ignore.
*
* Helper function for g_socket_listener_add_address() that
* creates a TCP/IP socket listening on IPv4 and IPv6 (if
* supported) on the specified port on all interfaces.
*
* @source_object will be passed out in the various calls
* to accept to identify this particular source, which is
* useful if you're listening on multiple addresses and do
* different things depending on what address is connected to.
*
* Call g_socket_listener_close() to stop listening on @port; this will not
* be done automatically when you drop your final reference to @listener, as
* references may be held internally.
*
* Returns: %TRUE on success, %FALSE on error.
*
* Since: 2.22
*/
gboolean
g_socket_listener_add_inet_port (GSocketListener *listener,
guint16 port,
GObject *source_object,
GError **error)
{
gboolean need_ipv4_socket = TRUE;
GSocket *socket4 = NULL;
GSocket *socket6;
g_return_val_if_fail (listener != NULL, FALSE);
g_return_val_if_fail (port != 0, FALSE);
if (!check_listener (listener, error))
return FALSE;
/* first try to create an IPv6 socket */
socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
G_SOCKET_TYPE_STREAM,
G_SOCKET_PROTOCOL_DEFAULT,
NULL);
if (socket6 != NULL)
/* IPv6 is supported on this platform, so if we fail now it is
* a result of being unable to bind to our port. Don't fail
* silently as a result of this!
*/
{
GInetAddress *inet_address;
GSocketAddress *address;
inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
address = g_inet_socket_address_new (inet_address, port);
g_object_unref (inet_address);
g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BINDING, socket6);
if (!g_socket_bind (socket6, address, TRUE, error))
{
g_object_unref (address);
g_object_unref (socket6);
return FALSE;
}
g_object_unref (address);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BOUND, socket6);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENING, socket6);
if (!g_socket_listen (socket6, error))
{
g_object_unref (socket6);
return FALSE;
}
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENED, socket6);
if (source_object)
g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
g_object_ref (source_object),
g_object_unref);
/* If this socket already speaks IPv4 then we are done. */
if (g_socket_speaks_ipv4 (socket6))
need_ipv4_socket = FALSE;
}
if (need_ipv4_socket)
/* We are here for exactly one of the following reasons:
*
* - our platform doesn't support IPv6
* - we successfully created an IPv6 socket but it's V6ONLY
*
* In either case, we need to go ahead and create an IPv4 socket
* and fail the call if we can't bind to it.
*/
{
socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
G_SOCKET_TYPE_STREAM,
G_SOCKET_PROTOCOL_DEFAULT,
error);
if (socket4 != NULL)
/* IPv4 is supported on this platform, so if we fail now it is
* a result of being unable to bind to our port. Don't fail
* silently as a result of this!
*/
{
GInetAddress *inet_address;
GSocketAddress *address;
inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
address = g_inet_socket_address_new (inet_address, port);
g_object_unref (inet_address);
g_socket_set_listen_backlog (socket4,
listener->priv->listen_backlog);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BINDING, socket4);
if (!g_socket_bind (socket4, address, TRUE, error))
{
g_object_unref (address);
g_object_unref (socket4);
if (socket6 != NULL)
g_object_unref (socket6);
return FALSE;
}
g_object_unref (address);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BOUND, socket4);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENING, socket4);
if (!g_socket_listen (socket4, error))
{
g_object_unref (socket4);
if (socket6 != NULL)
g_object_unref (socket6);
return FALSE;
}
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENED, socket4);
if (source_object)
g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
g_object_ref (source_object),
g_object_unref);
}
else
/* Ok. So IPv4 is not supported on this platform. If we
* succeeded at creating an IPv6 socket then that's OK, but
* otherwise we need to tell the user we failed.
*/
{
if (socket6 != NULL)
g_clear_error (error);
else
return FALSE;
}
}
g_assert (socket6 != NULL || socket4 != NULL);
if (socket6 != NULL)
g_ptr_array_add (listener->priv->sockets, socket6);
if (socket4 != NULL)
g_ptr_array_add (listener->priv->sockets, socket4);
if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
return TRUE;
}
static GList *
add_sources (GSocketListener *listener,
GSocketSourceFunc callback,
gpointer callback_data,
GCancellable *cancellable,
GMainContext *context)
{
GSocket *socket;
GSource *source;
GList *sources;
int i;
sources = NULL;
for (i = 0; i < listener->priv->sockets->len; i++)
{
socket = listener->priv->sockets->pdata[i];
source = g_socket_create_source (socket, G_IO_IN, cancellable);
g_source_set_callback (source,
(GSourceFunc) callback,
callback_data, NULL);
g_source_attach (source, context);
sources = g_list_prepend (sources, source);
}
return sources;
}
static void
free_sources (GList *sources)
{
GSource *source;
while (sources != NULL)
{
source = sources->data;
sources = g_list_delete_link (sources, sources);
g_source_destroy (source);
g_source_unref (source);
}
}
struct AcceptData {
GMainLoop *loop;
GSocket *socket;
};
static gboolean
accept_callback (GSocket *socket,
GIOCondition condition,
gpointer user_data)
{
struct AcceptData *data = user_data;
data->socket = socket;
g_main_loop_quit (data->loop);
return TRUE;
}
/**
* g_socket_listener_accept_socket:
* @listener: a #GSocketListener
* @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL.
* @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
* @error: #GError for error reporting, or %NULL to ignore.
*
* Blocks waiting for a client to connect to any of the sockets added
* to the listener. Returns the #GSocket that was accepted.
*
* If you want to accept the high-level #GSocketConnection, not a #GSocket,
* which is often the case, then you should use g_socket_listener_accept()
* instead.
*
* If @source_object is not %NULL it will be filled out with the source
* object specified when the corresponding socket or address was added
* to the listener.
*
* If @cancellable is not %NULL, then the operation can be cancelled by
* triggering the cancellable object from another thread. If the operation
* was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
*
* Returns: (transfer full): a #GSocket on success, %NULL on error.
*
* Since: 2.22
*/
GSocket *
g_socket_listener_accept_socket (GSocketListener *listener,
GObject **source_object,
GCancellable *cancellable,
GError **error)
{
GSocket *accept_socket, *socket;
g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
if (!check_listener (listener, error))
return NULL;
if (listener->priv->sockets->len == 1)
{
accept_socket = listener->priv->sockets->pdata[0];
if (!g_socket_condition_wait (accept_socket, G_IO_IN,
cancellable, error))
return NULL;
}
else
{
GList *sources;
struct AcceptData data;
GMainLoop *loop;
if (listener->priv->main_context == NULL)
listener->priv->main_context = g_main_context_new ();
loop = g_main_loop_new (listener->priv->main_context, FALSE);
data.loop = loop;
sources = add_sources (listener,
accept_callback,
&data,
cancellable,
listener->priv->main_context);
g_main_loop_run (loop);
accept_socket = data.socket;
free_sources (sources);
g_main_loop_unref (loop);
}
if (!(socket = g_socket_accept (accept_socket, cancellable, error)))
return NULL;
if (source_object)
*source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
return socket;
}
/**
* g_socket_listener_accept:
* @listener: a #GSocketListener
* @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL
* @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
* @error: #GError for error reporting, or %NULL to ignore.
*
* Blocks waiting for a client to connect to any of the sockets added
* to the listener. Returns a #GSocketConnection for the socket that was
* accepted.
*
* If @source_object is not %NULL it will be filled out with the source
* object specified when the corresponding socket or address was added
* to the listener.
*
* If @cancellable is not %NULL, then the operation can be cancelled by
* triggering the cancellable object from another thread. If the operation
* was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
*
* Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
*
* Since: 2.22
*/
GSocketConnection *
g_socket_listener_accept (GSocketListener *listener,
GObject **source_object,
GCancellable *cancellable,
GError **error)
{
GSocketConnection *connection;
GSocket *socket;
socket = g_socket_listener_accept_socket (listener,
source_object,
cancellable,
error);
if (socket == NULL)
return NULL;
connection = g_socket_connection_factory_create_connection (socket);
g_object_unref (socket);
return connection;
}
typedef struct
{
GList *sources; /* (element-type GSource) */
gboolean returned_yet;
} AcceptSocketAsyncData;
static void
accept_socket_async_data_free (AcceptSocketAsyncData *data)
{
free_sources (data->sources);
g_free (data);
}
static gboolean
accept_ready (GSocket *accept_socket,
GIOCondition condition,
gpointer user_data)
{
GTask *task = user_data;
GError *error = NULL;
GSocket *socket;
GObject *source_object;
AcceptSocketAsyncData *data = g_task_get_task_data (task);
/* Don’t call g_task_return_*() multiple times if we have multiple incoming
* connections in the same #GMainContext iteration. */
if (data->returned_yet)
return G_SOURCE_REMOVE;
socket = g_socket_accept (accept_socket, g_task_get_cancellable (task), &error);
if (socket)
{
source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
if (source_object)
g_object_set_qdata_full (G_OBJECT (task),
source_quark,
g_object_ref (source_object), g_object_unref);
g_task_return_pointer (task, socket, g_object_unref);
}
else
{
g_task_return_error (task, error);
}
data->returned_yet = TRUE;
g_object_unref (task);
return G_SOURCE_REMOVE;
}
/**
* g_socket_listener_accept_socket_async:
* @listener: a #GSocketListener
* @cancellable: (nullable): a #GCancellable, or %NULL
* @callback: (scope async): a #GAsyncReadyCallback
* @user_data: (closure): user data for the callback
*
* This is the asynchronous version of g_socket_listener_accept_socket().
*
* When the operation is finished @callback will be
* called. You can then call g_socket_listener_accept_socket_finish()
* to get the result of the operation.
*
* Since: 2.22
*/
void
g_socket_listener_accept_socket_async (GSocketListener *listener,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
GTask *task;
GError *error = NULL;
AcceptSocketAsyncData *data = NULL;
task = g_task_new (listener, cancellable, callback, user_data);
g_task_set_source_tag (task, g_socket_listener_accept_socket_async);
if (!check_listener (listener, &error))
{
g_task_return_error (task, error);
g_object_unref (task);
return;
}
data = g_new0 (AcceptSocketAsyncData, 1);
data->returned_yet = FALSE;
data->sources = add_sources (listener,
accept_ready,
task,
cancellable,
g_main_context_get_thread_default ());
g_task_set_task_data (task, g_steal_pointer (&data),
(GDestroyNotify) accept_socket_async_data_free);
}
/**
* g_socket_listener_accept_socket_finish:
* @listener: a #GSocketListener
* @result: a #GAsyncResult.
* @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
* @error: a #GError location to store the error occurring, or %NULL to
* ignore.
*
* Finishes an async accept operation. See g_socket_listener_accept_socket_async()
*
* Returns: (transfer full): a #GSocket on success, %NULL on error.
*
* Since: 2.22
*/
GSocket *
g_socket_listener_accept_socket_finish (GSocketListener *listener,
GAsyncResult *result,
GObject **source_object,
GError **error)
{
g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
g_return_val_if_fail (g_task_is_valid (result, listener), NULL);
if (source_object)
*source_object = g_object_get_qdata (G_OBJECT (result), source_quark);
return g_task_propagate_pointer (G_TASK (result), error);
}
/**
* g_socket_listener_accept_async:
* @listener: a #GSocketListener
* @cancellable: (nullable): a #GCancellable, or %NULL
* @callback: (scope async): a #GAsyncReadyCallback
* @user_data: (closure): user data for the callback
*
* This is the asynchronous version of g_socket_listener_accept().
*
* When the operation is finished @callback will be
* called. You can then call g_socket_listener_accept_socket()
* to get the result of the operation.
*
* Since: 2.22
*/
void
g_socket_listener_accept_async (GSocketListener *listener,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
g_socket_listener_accept_socket_async (listener,
cancellable,
callback,
user_data);
}
/**
* g_socket_listener_accept_finish:
* @listener: a #GSocketListener
* @result: a #GAsyncResult.
* @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
* @error: a #GError location to store the error occurring, or %NULL to
* ignore.
*
* Finishes an async accept operation. See g_socket_listener_accept_async()
*
* Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
*
* Since: 2.22
*/
GSocketConnection *
g_socket_listener_accept_finish (GSocketListener *listener,
GAsyncResult *result,
GObject **source_object,
GError **error)
{
GSocket *socket;
GSocketConnection *connection;
socket = g_socket_listener_accept_socket_finish (listener,
result,
source_object,
error);
if (socket == NULL)
return NULL;
connection = g_socket_connection_factory_create_connection (socket);
g_object_unref (socket);
return connection;
}
/**
* g_socket_listener_set_backlog:
* @listener: a #GSocketListener
* @listen_backlog: an integer
*
* Sets the listen backlog on the sockets in the listener. This must be called
* before adding any sockets, addresses or ports to the #GSocketListener (for
* example, by calling g_socket_listener_add_inet_port()) to be effective.
*
* See g_socket_set_listen_backlog() for details
*
* Since: 2.22
*/
void
g_socket_listener_set_backlog (GSocketListener *listener,
int listen_backlog)
{
GSocket *socket;
int i;
if (listener->priv->closed)
return;
listener->priv->listen_backlog = listen_backlog;
for (i = 0; i < listener->priv->sockets->len; i++)
{
socket = listener->priv->sockets->pdata[i];
g_socket_set_listen_backlog (socket, listen_backlog);
}
}
/**
* g_socket_listener_close:
* @listener: a #GSocketListener
*
* Closes all the sockets in the listener.
*
* Since: 2.22
*/
void
g_socket_listener_close (GSocketListener *listener)
{
GSocket *socket;
int i;
g_return_if_fail (G_IS_SOCKET_LISTENER (listener));
if (listener->priv->closed)
return;
for (i = 0; i < listener->priv->sockets->len; i++)
{
socket = listener->priv->sockets->pdata[i];
g_socket_close (socket, NULL);
}
listener->priv->closed = TRUE;
}
/**
* g_socket_listener_add_any_inet_port:
* @listener: a #GSocketListener
* @source_object: (nullable): Optional #GObject identifying this source
* @error: a #GError location to store the error occurring, or %NULL to
* ignore.
*
* Listens for TCP connections on any available port number for both
* IPv6 and IPv4 (if each is available).
*
* This is useful if you need to have a socket for incoming connections
* but don't care about the specific port number.
*
* @source_object will be passed out in the various calls
* to accept to identify this particular source, which is
* useful if you're listening on multiple addresses and do
* different things depending on what address is connected to.
*
* Returns: the port number, or 0 in case of failure.
*
* Since: 2.24
**/
guint16
g_socket_listener_add_any_inet_port (GSocketListener *listener,
GObject *source_object,
GError **error)
{
GSList *sockets_to_close = NULL;
guint16 candidate_port = 0;
GSocket *socket6 = NULL;
GSocket *socket4 = NULL;
gint attempts = 37;
/*
* multi-step process:
* - first, create an IPv6 socket.
* - if that fails, create an IPv4 socket and bind it to port 0 and
* that's it. no retries if that fails (why would it?).
* - if our IPv6 socket also speaks IPv4 then we are done.
* - if not, then we need to create a IPv4 socket with the same port
* number. this might fail, of course. so we try this a bunch of
* times -- leaving the old IPv6 sockets open so that we get a
* different port number to try each time.
* - if all that fails then just give up.
*/
while (attempts--)
{
GInetAddress *inet_address;
GSocketAddress *address;
gboolean result;
g_assert (socket6 == NULL);
socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
G_SOCKET_TYPE_STREAM,
G_SOCKET_PROTOCOL_DEFAULT,
NULL);
if (socket6 != NULL)
{
inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
address = g_inet_socket_address_new (inet_address, 0);
g_object_unref (inet_address);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BINDING, socket6);
result = g_socket_bind (socket6, address, TRUE, error);
g_object_unref (address);
if (!result ||
!(address = g_socket_get_local_address (socket6, error)))
{
g_object_unref (socket6);
socket6 = NULL;
break;
}
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BOUND, socket6);
g_assert (G_IS_INET_SOCKET_ADDRESS (address));
candidate_port =
g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
g_assert (candidate_port != 0);
g_object_unref (address);
if (g_socket_speaks_ipv4 (socket6))
break;
}
g_assert (socket4 == NULL);
socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
G_SOCKET_TYPE_STREAM,
G_SOCKET_PROTOCOL_DEFAULT,
socket6 ? NULL : error);
if (socket4 == NULL)
/* IPv4 not supported.
* if IPv6 is supported then candidate_port will be non-zero
* (and the error parameter above will have been NULL)
* if IPv6 is unsupported then candidate_port will be zero
* (and error will have been set by the above call)
*/
break;
inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
address = g_inet_socket_address_new (inet_address, candidate_port);
g_object_unref (inet_address);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BINDING, socket4);
/* a note on the 'error' clause below:
*
* if candidate_port is 0 then we report the error right away
* since it is strange that this binding would fail at all.
* otherwise, we ignore the error message (ie: NULL).
*
* the exception to this rule is the last time through the loop
* (ie: attempts == 0) in which case we want to set the error
* because failure here means that the entire call will fail and
* we need something to show to the user.
*
* an english summary of the situation: "if we gave a candidate
* port number AND we have more attempts to try, then ignore the
* error for now".
*/
result = g_socket_bind (socket4, address, TRUE,
(candidate_port && attempts) ? NULL : error);
g_object_unref (address);
if (candidate_port)
{
g_assert (socket6 != NULL);
if (result)
/* got our candidate port successfully */
{
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BOUND, socket4);
break;
}
else
/* we failed to bind to the specified port. try again. */
{
g_object_unref (socket4);
socket4 = NULL;
/* keep this open so we get a different port number */
sockets_to_close = g_slist_prepend (sockets_to_close,
socket6);
candidate_port = 0;
socket6 = NULL;
}
}
else
/* we didn't tell it a port. this means two things.
* - if we failed, then something really bad happened.
* - if we succeeded, then we need to find out the port number.
*/
{
g_assert (socket6 == NULL);
if (!result ||
!(address = g_socket_get_local_address (socket4, error)))
{
g_object_unref (socket4);
socket4 = NULL;
break;
}
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_BOUND, socket4);
g_assert (G_IS_INET_SOCKET_ADDRESS (address));
candidate_port =
g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
g_assert (candidate_port != 0);
g_object_unref (address);
break;
}
}
/* should only be non-zero if we have a socket */
g_assert ((candidate_port != 0) == (socket4 || socket6));
while (sockets_to_close)
{
g_object_unref (sockets_to_close->data);
sockets_to_close = g_slist_delete_link (sockets_to_close,
sockets_to_close);
}
/* now we actually listen() the sockets and add them to the listener */
if (socket6 != NULL)
{
g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENING, socket6);
if (!g_socket_listen (socket6, error))
{
g_object_unref (socket6);
if (socket4)
g_object_unref (socket4);
return 0;
}
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENED, socket6);
if (source_object)
g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
g_object_ref (source_object),
g_object_unref);
g_ptr_array_add (listener->priv->sockets, socket6);
}
if (socket4 != NULL)
{
g_socket_set_listen_backlog (socket4, listener->priv->listen_backlog);
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENING, socket4);
if (!g_socket_listen (socket4, error))
{
g_object_unref (socket4);
if (socket6)
g_object_unref (socket6);
return 0;
}
g_signal_emit (listener, signals[EVENT], 0,
G_SOCKET_LISTENER_LISTENED, socket4);
if (source_object)
g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
g_object_ref (source_object),
g_object_unref);
g_ptr_array_add (listener->priv->sockets, socket4);
}
if ((socket4 != NULL || socket6 != NULL) &&
G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
return candidate_port;
}
| ImageMagick/glib | gio/gsocketlistener.c | C | lgpl-2.1 | 39,483 |
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtXmlPatterns 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 "qxsdalternative_p.h"
QT_BEGIN_NAMESPACE
using namespace QPatternist;
void XsdAlternative::setTest(const XsdXPathExpression::Ptr &test)
{
m_test = test;
}
XsdXPathExpression::Ptr XsdAlternative::test() const
{
return m_test;
}
void XsdAlternative::setType(const SchemaType::Ptr &type)
{
m_type = type;
}
SchemaType::Ptr XsdAlternative::type() const
{
return m_type;
}
QT_END_NAMESPACE
| sicily/qt4.8.4 | src/xmlpatterns/schema/qxsdalternative.cpp | C++ | lgpl-2.1 | 2,393 |
<?xml version="1.0" encoding="UTF-8"?>
<!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">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Kortkommandon</title>
<link rel="stylesheet" type="text/css" href="../main.css" media="all">
</head>
<body>
<a name="Kortkommandos"></a>
<h1><img src="../Sequential.png" class="icon"> Kortkommandon</h1>
<table cellspacing=0 width=100%>
<tr class="header">
<td>Dokument och sessioner</td>
<td>Kortkommando</td>
</tr>
<tr>
<td>Öppna lokal fil</td>
<td>Kommando-O</td>
</tr>
<tr>
<td>Öppna URL</td>
<td>Kommando-Skift-O</td>
</tr>
<tr>
<td>Stäng fönstret</td>
<td>Kommando-W</td>
</tr>
<tr>
<td>Stäng alla dokument</td>
<td>Kommando-Alternativ-W</td>
</tr>
<tr>
<td>Pausa nuvarande session</td>
<td>Punkt (.)</td>
</tr>
<tr class="header">
<td>Skrollning</td>
<td>Kortkommando</td>
</tr>
<tr>
<td>Inom bilden</td>
<td>Arrow keys, Mouse wheel</td>
</tr>
<tr>
<td>En bild framåt, via kolumn och därefter rad</td>
<td>N, Mellanslag, 0 (Numeriska tangentbordet)</td>
</tr>
<tr>
<td>En bild bakåt, via kolumn och därefter rad</td>
<td>B, Skift-N, Skift-Mellanslag, Skift-0 (Numeriska tangentbordet)</td>
</tr>
<tr>
<td>En bild framåt, via rad och därefter kolumn</td>
<td>V, Enter (Numeriska tangentbordet)</td>
</tr>
<tr>
<td>En bild bakåt, via rad och därefter kolumn</td>
<td>C, Skift-V, Skift-Enter (Numeriska tangentbordet)</td>
</tr>
<tr>
<td>En bild upp</td>
<td>Page up</td>
</tr>
<tr>
<td>En bild ned</td>
<td>Page down</td>
</tr>
<tr>
<td>Sidans början</td>
<td>Home</td>
</tr>
<tr>
<td>Sidans slut</td>
<td>End</td>
</tr>
<tr>
<td>En bild åt det angivna hållet (exv. 8 för uppåt)</td>
<td>1-9 (Numeriska tangentbordet)</td>
</tr>
<tr class="header">
<td>Visning</td>
<td>Kortkommando</td>
</tr>
<tr>
<td>Helskärmsläge av/på</td>
<td>Kommando-F, Escape</td>
</tr>
<tr>
<td>Visa/göm info</td>
<td>I, Kommando-I</td>
</tr>
<tr>
<td>Visa/göm tumnaglar</td>
<td>T</td>
</tr>
<tr>
<td>Show/hide inspector panel</td>
<td>Kommando-I</td>
</tr>
<tr>
<td>Visa/göm timer-panelen</td>
<td>Kommando-T</td>
</tr>
<tr>
<td>Visa/göm aktivitetspanelen</td>
<td>Kommando-Skift-A</td>
</tr>
<tr>
<td>Läs från vänster till höger</td>
<td>Kommando-L</td>
</tr>
<tr>
<td>Läs från höger till vänster</td>
<td>Kommando-;</td>
</tr>
<tr>
<td>Rotera bild medsols</td>
<td>R</td>
</tr>
<tr>
<td>Rotera bild motsols</td>
<td>Skift-R</td>
</tr>
<tr>
<td>Använd orginalbildens orientation</td>
<td>O</td>
</tr>
<tr>
<td>Spela/pausa</td>
<td>M</td>
</tr>
<tr class="header">
<td>Skalning</td>
<td>Kortkommando</td>
</tr>
<tr>
<td>Verklig storlek</td>
<td>A</td>
</tr>
<tr>
<td>Automatisk anpassning</td>
<td>F</td>
</tr>
<tr>
<td>Anpassa till fönster/skärm</td>
<td>S</td>
</tr>
<tr>
<td>Zooma in</td>
<td>Plus (+), Command-Mouse wheel up</td>
</tr>
<tr>
<td>Zoom ut</td>
<td>Minus (-), Command-Mouse wheel down</td>
</tr>
<tr class="header">
<td>Sortering</td>
<td>Kortkommando</td>
</tr>
<tr>
<td>Sortera efter namn</td>
<td>Kommando-1</td>
</tr>
<tr>
<td>Sortera efter ändringsdatum</td>
<td>Kommando-2</td>
</tr>
<tr>
<td>Sortera efter skapelsedatum</td>
<td>Kommando-3</td>
</tr>
<tr>
<td>Sortera efter filstorlek</td>
<td>Kommando-4</td>
</tr>
<tr>
<td>Blanda</td>
<td>Kommando-0</td>
</tr>
<tr class="header">
<td>Navigation</td>
<td>Kortkommando</td>
</tr>
<tr>
<td>Gå till nästa/föregående sida</td>
<td>[, ]</td>
</tr>
<tr>
<td>Gå till sista/första sidan</td>
<td>Kommando-[, Kommando-]</td>
</tr>
<tr>
<td>Hoppa över före/efter mapp</td>
<td>K, Skift-K</td>
</tr>
<tr>
<td>Gå till första sida i nästa/förra mapp</td>
<td>J, Skift-J</td>
</tr>
<tr>
<td>Gå till sista/första sidan i nuvarande mapp</td>
<td>L, Skift-L</td>
</tr>
<tr>
<td>Sätt timer (i sekunder)</td>
<td>1-9 (inte på numeriska tangentbordet)</td>
</tr>
<tr>
<td>Sätt timer (i sekunder x10)</td>
<td>Alternativ-1-9 (inte på numeriska tangentbordet)</td>
</tr>
<tr>
<td>Stanna timern</td>
<td>0 (inte på numeriska tangentbordet)</td>
</tr>
<tr class="header">
<td>Sök</td>
<td>Kortkommando</td>
</tr>
<tr>
<td>Visa sökpanelen</td>
<td>Kommando-Skift-F</td>
</tr>
<tr>
<td>Sök nästa</td>
<td>Kommando-G</td>
</tr>
<tr>
<td>Sök föregående</td>
<td>Kommando-Skift-G</td>
</tr>
<tr class="header">
<td>Annat</td>
<td>Kortkommando</td>
</tr>
<tr>
<td>Växla till Finder</td>
<td>Kommando-Alternativ-F</td>
</tr>
<tr>
<td>Visa i Finder/webläsare</td>
<td>Kommando-R</td>
</tr>
<tr>
<td>Spara bilder</td>
<td>Kommando-S</td>
</tr>
<tr>
<td>Sätt nuvarande bild som skrivbordsbakgrund</td>
<td>Kommando-Skift-D</td>
</tr>
<tr>
<td>Spara kopia av nuvarande bild som skrivbordsbakgrund</td>
<td>Kommando-Skift-Alternativ-D</td>
</tr>
<tr>
<td>Flytta bilder till papperskorgen</td>
<td>Kommando-delete</td>
</tr>
<tr>
<td>Avsluta Sequential</td>
<td>Q, Kommando-Q</td>
</tr>
</table>
</body>
</html>
| johan/Sequential | Sequential.help/Contents/Resources/sv.lproj/shortcuts.html | HTML | lgpl-2.1 | 5,874 |
--TEST--
GtkWidget->get_app_paintable method
--SKIPIF--
<?php
if(!extension_loaded('php-gtk')) die('skip - PHP-GTK extension not available');
if(!method_exists('GtkWidget', 'get_app_paintable')) die('skip - GtkWidget->get_app_paintable not available, requires GTK 2.18 or higher');
?>
--FILE--
<?php
$window = new GtkWindow();
var_dump($window->get_app_paintable());
$window->set_app_paintable(true);
var_dump($window->get_app_paintable());
/* Wrong number args*/
$window->get_app_paintable(1);
/* Takes no args, so no arg type checking */
?>
--EXPECTF--
bool(false)
bool(true)
Warning: GtkWidget::get_app_paintable() expects exactly 0 parameters, 1 given in %s on line %d | marcosptf/php-gtk-src | tests/GtkWidget/get_app_paintable.phpt | PHP | lgpl-2.1 | 676 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS>
<context>
<name>TestGui::UnitTest</name>
<message>
<source>FreeCAD UnitTest</source>
<translation>Teste de unidade do FreeCAD</translation>
</message>
<message>
<source>Failures and errors</source>
<translation>Falhas e erros</translation>
</message>
<message>
<source>Description</source>
<translation>Descrição</translation>
</message>
<message>
<source>&Start</source>
<translation>&Início</translation>
</message>
<message>
<source>Alt+S</source>
<translation>Alt+I</translation>
</message>
<message>
<source>&Help</source>
<translation>A&juda</translation>
</message>
<message>
<source>F1</source>
<translation>F1</translation>
</message>
<message>
<source>&About</source>
<translation>S&obre</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+O</translation>
</message>
<message>
<source>&Close</source>
<translation>&Fechar</translation>
</message>
<message>
<source>Alt+C</source>
<translation>Alt+F</translation>
</message>
<message>
<source>Idle</source>
<translation>Ocioso</translation>
</message>
<message>
<source>Progress</source>
<translation>Progresso</translation>
</message>
<message>
<source><font color="#0000ff">0</font></source>
<translation><font color="#0000ff">0</font></translation>
</message>
<message>
<source>Remaining:</source>
<translation>Faltando:</translation>
</message>
<message>
<source>Errors:</source>
<translation>Erros:</translation>
</message>
<message>
<source>Failures:</source>
<translation>Falhas:</translation>
</message>
<message>
<source>Run:</source>
<translation>Executar:</translation>
</message>
<message>
<source>Test</source>
<translation>Teste</translation>
</message>
<message>
<source>Select test name:</source>
<translation>Selecione o nome do teste:</translation>
</message>
</context>
<context>
<name>TestGui::UnitTestDialog</name>
<message>
<source>Help</source>
<translation>Ajuda</translation>
</message>
<message>
<source>About FreeCAD UnitTest</source>
<translation>Sobre o teste de unidade do FreeCAD</translation>
</message>
<message>
<source>Copyright (c) Werner Mayer
FreeCAD UnitTest is part of FreeCAD and supports writing Unit Tests for own modules.</source>
<translation>Copyright (c) Werner Mayer
O teste de unidade do FreeCAD é parte do FreeCAD e suporta o desenvolvimento de testes de unidade para módulos próprios.</translation>
</message>
<message>
<source>Enter the name of a callable object which, when called, will return a TestCase.Click 'start', and the test thus produced will be run.
Double click on an error in the tree view to see more information about it,including the stack trace.</source>
<translation>Digite o nome de um objeto que pode ser chamado que, quando chamado, vai retornar um TestCase. Clique "Iniciar", e o teste assim produzido será executado. Dê um duplo clique sobre um erro na árvore para ver mais informações sobre ele, incluindo o rastreamento de pilha.</translation>
</message>
</context>
</TS>
| JonasThomas/free-cad | src/Mod/Test/Gui/Resources/translations/Test_pt.ts | TypeScript | lgpl-2.1 | 3,555 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2000 - 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.
//
// ---------------------------------------------------------------------
// The MatrixCreator::create_mass_matrix function overload that also assembles
// a right hand side vector had a bug in that the statement that assembled the
// rhs vector was nested in the wrong loop. this was fixed by Moritz' commit
// 14428
//
// the function internally has four branches, with different code used
// for the cases with/without coefficient and scalar/vector-valued
// finite element. we test these four cases through the _01, _02, _03,
// and _04 tests. the version without creating a right hand side vector is tested in the
// _0[1234]a tests, and versions without computing a right hand side
// vectors with and without coefficient in the _0[1234][bc] tests
#include "../tests.h"
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/logstream.h>
#include <deal.II/base/function_lib.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/hp/dof_handler.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/lac/constraint_matrix.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/hp/mapping_collection.h>
#include <deal.II/hp/fe_collection.h>
#include <deal.II/hp/q_collection.h>
#include <deal.II/numerics/matrix_tools.h>
#include <fstream>
template <int dim>
void
check ()
{
Triangulation<dim> tr;
if (dim==2)
GridGenerator::hyper_ball(tr, Point<dim>(), 1);
else
GridGenerator::hyper_cube(tr, -1,1);
tr.refine_global (1);
tr.begin_active()->set_refine_flag ();
tr.execute_coarsening_and_refinement ();
if (dim==1)
tr.refine_global(2);
hp::FECollection<dim> element;
element.push_back (FESystem<dim> (FE_Q<dim>(1), 1,
FE_Q<dim>(2), 1));
element.push_back (FESystem<dim> (FE_Q<dim>(2), 1,
FE_Q<dim>(QIterated<1>(QTrapez<1>(),3)), 1));
element.push_back (FESystem<dim> (FE_Q<dim>(QIterated<1>(QTrapez<1>(),3)), 1,
FE_Q<dim>(QIterated<1>(QTrapez<1>(),4)), 1));
hp::DoFHandler<dim> dof(tr);
for (typename hp::DoFHandler<dim>::active_cell_iterator
cell = dof.begin_active();
cell != dof.end(); ++cell)
cell->set_active_fe_index (Testing::rand() % element.size());
dof.distribute_dofs(element);
// use a more complicated mapping
// of the domain and a quadrature
// formula suited to the elements
// we have here
MappingQ<dim> mapping (3);
QGauss<dim> quadrature(6);
// create sparsity pattern. note
// that different components should
// not couple, so use pattern
SparsityPattern sparsity (dof.n_dofs(), dof.n_dofs());
Table<2,DoFTools::Coupling> mask (2, 2);
mask(0,0) = mask(1,1) = DoFTools::always;
mask(0,1) = mask(1,0) = DoFTools::none;
DoFTools::make_sparsity_pattern (dof, mask, sparsity);
ConstraintMatrix constraints;
DoFTools::make_hanging_node_constraints (dof, constraints);
constraints.close ();
constraints.condense (sparsity);
sparsity.compress ();
SparseMatrix<double> matrix;
matrix.reinit (sparsity);
MatrixTools::
create_mass_matrix (hp::MappingCollection<dim>(mapping), dof,
hp::QCollection<dim>(quadrature), matrix);
// since we only generate
// output with two digits after
// the dot, and since matrix
// entries are usually in the
// range of 1 or below,
// multiply matrix by 100 to
// make test more sensitive
deallog << "Matrix: " << std::endl;
for (SparseMatrix<double>::const_iterator p=matrix.begin();
p!=matrix.end(); ++p)
deallog << p->value() * 100
<< std::endl;
}
int main ()
{
std::ofstream logfile ("output");
deallog << std::setprecision (2);
deallog << std::fixed;
deallog.attach(logfile);
deallog.push ("1d");
check<1> ();
deallog.pop ();
deallog.push ("2d");
check<2> ();
deallog.pop ();
deallog.push ("3d");
check<3> ();
deallog.pop ();
}
| EGP-CIG-REU/dealii | tests/hp/create_mass_matrix_02b.cc | C++ | lgpl-2.1 | 4,738 |
/*
* Assorted DPCM codecs
* Copyright (c) 2003 The ffmpeg Project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file: dpcm.c
* Assorted DPCM (differential pulse code modulation) audio codecs
* by Mike Melanson (melanson@pcisys.net)
* Xan DPCM decoder by Mario Brito (mbrito@student.dei.uc.pt)
* for more information on the specific data formats, visit:
* http://www.pcisys.net/~melanson/codecs/simpleaudio.html
* SOL DPCMs implemented by Konstantin Shishkov
*
* Note about using the Xan DPCM decoder: Xan DPCM is used in AVI files
* found in the Wing Commander IV computer game. These AVI files contain
* WAVEFORMAT headers which report the audio format as 0x01: raw PCM.
* Clearly incorrect. To detect Xan DPCM, you will probably have to
* special-case your AVI demuxer to use Xan DPCM if the file uses 'Xxan'
* (Xan video) for its video codec. Alternately, such AVI files also contain
* the fourcc 'Axan' in the 'auds' chunk of the AVI header.
*/
#include "avcodec.h"
typedef struct DPCMContext {
int channels;
short roq_square_array[256];
long sample[2];//for SOL_DPCM
const int *sol_table;//for SOL_DPCM
} DPCMContext;
#define SATURATE_S16(x) if (x < -32768) x = -32768; \
else if (x > 32767) x = 32767;
#define SE_16BIT(x) if (x & 0x8000) x -= 0x10000;
static int interplay_delta_table[] = {
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 47, 51, 56, 61,
66, 72, 79, 86, 94, 102, 112, 122,
133, 145, 158, 173, 189, 206, 225, 245,
267, 292, 318, 348, 379, 414, 452, 493,
538, 587, 640, 699, 763, 832, 908, 991,
1081, 1180, 1288, 1405, 1534, 1673, 1826, 1993,
2175, 2373, 2590, 2826, 3084, 3365, 3672, 4008,
4373, 4772, 5208, 5683, 6202, 6767, 7385, 8059,
8794, 9597, 10472, 11428, 12471, 13609, 14851, 16206,
17685, 19298, 21060, 22981, 25078, 27367, 29864, 32589,
-29973, -26728, -23186, -19322, -15105, -10503, -5481, -1,
1, 1, 5481, 10503, 15105, 19322, 23186, 26728,
29973, -32589, -29864, -27367, -25078, -22981, -21060, -19298,
-17685, -16206, -14851, -13609, -12471, -11428, -10472, -9597,
-8794, -8059, -7385, -6767, -6202, -5683, -5208, -4772,
-4373, -4008, -3672, -3365, -3084, -2826, -2590, -2373,
-2175, -1993, -1826, -1673, -1534, -1405, -1288, -1180,
-1081, -991, -908, -832, -763, -699, -640, -587,
-538, -493, -452, -414, -379, -348, -318, -292,
-267, -245, -225, -206, -189, -173, -158, -145,
-133, -122, -112, -102, -94, -86, -79, -72,
-66, -61, -56, -51, -47, -43, -42, -41,
-40, -39, -38, -37, -36, -35, -34, -33,
-32, -31, -30, -29, -28, -27, -26, -25,
-24, -23, -22, -21, -20, -19, -18, -17,
-16, -15, -14, -13, -12, -11, -10, -9,
-8, -7, -6, -5, -4, -3, -2, -1
};
static const int sol_table_old[16] =
{ 0x0, 0x1, 0x2 , 0x3, 0x6, 0xA, 0xF, 0x15,
-0x15, -0xF, -0xA, -0x6, -0x3, -0x2, -0x1, 0x0};
static const int sol_table_new[16] =
{ 0x0, 0x1, 0x2, 0x3, 0x6, 0xA, 0xF, 0x15,
0x0, -0x1, -0x2, -0x3, -0x6, -0xA, -0xF, -0x15};
static const int sol_table_16[128] = {
0x000, 0x008, 0x010, 0x020, 0x030, 0x040, 0x050, 0x060, 0x070, 0x080,
0x090, 0x0A0, 0x0B0, 0x0C0, 0x0D0, 0x0E0, 0x0F0, 0x100, 0x110, 0x120,
0x130, 0x140, 0x150, 0x160, 0x170, 0x180, 0x190, 0x1A0, 0x1B0, 0x1C0,
0x1D0, 0x1E0, 0x1F0, 0x200, 0x208, 0x210, 0x218, 0x220, 0x228, 0x230,
0x238, 0x240, 0x248, 0x250, 0x258, 0x260, 0x268, 0x270, 0x278, 0x280,
0x288, 0x290, 0x298, 0x2A0, 0x2A8, 0x2B0, 0x2B8, 0x2C0, 0x2C8, 0x2D0,
0x2D8, 0x2E0, 0x2E8, 0x2F0, 0x2F8, 0x300, 0x308, 0x310, 0x318, 0x320,
0x328, 0x330, 0x338, 0x340, 0x348, 0x350, 0x358, 0x360, 0x368, 0x370,
0x378, 0x380, 0x388, 0x390, 0x398, 0x3A0, 0x3A8, 0x3B0, 0x3B8, 0x3C0,
0x3C8, 0x3D0, 0x3D8, 0x3E0, 0x3E8, 0x3F0, 0x3F8, 0x400, 0x440, 0x480,
0x4C0, 0x500, 0x540, 0x580, 0x5C0, 0x600, 0x640, 0x680, 0x6C0, 0x700,
0x740, 0x780, 0x7C0, 0x800, 0x900, 0xA00, 0xB00, 0xC00, 0xD00, 0xE00,
0xF00, 0x1000, 0x1400, 0x1800, 0x1C00, 0x2000, 0x3000, 0x4000
};
static int dpcm_decode_init(AVCodecContext *avctx)
{
DPCMContext *s = avctx->priv_data;
int i;
short square;
s->channels = avctx->channels;
s->sample[0] = s->sample[1] = 0;
switch(avctx->codec->id) {
case CODEC_ID_ROQ_DPCM:
/* initialize square table */
for (i = 0; i < 128; i++) {
square = i * i;
s->roq_square_array[i] = square;
s->roq_square_array[i + 128] = -square;
}
break;
case CODEC_ID_SOL_DPCM:
switch(avctx->codec_tag){
case 1:
s->sol_table=sol_table_old;
s->sample[0] = s->sample[1] = 0x80;
break;
case 2:
s->sol_table=sol_table_new;
s->sample[0] = s->sample[1] = 0x80;
break;
case 3:
s->sol_table=sol_table_16;
break;
default:
av_log(avctx, AV_LOG_ERROR, "Unknown SOL subcodec\n");
return -1;
}
break;
default:
break;
}
return 0;
}
static int dpcm_decode_frame(AVCodecContext *avctx,
void *data, int *data_size,
uint8_t *buf, int buf_size)
{
DPCMContext *s = avctx->priv_data;
int in, out = 0;
int predictor[2];
int channel_number = 0;
short *output_samples = data;
int shift[2];
unsigned char byte;
short diff;
if (!buf_size)
return 0;
switch(avctx->codec->id) {
case CODEC_ID_ROQ_DPCM:
if (s->channels == 1)
predictor[0] = LE_16(&buf[6]);
else {
predictor[0] = buf[7] << 8;
predictor[1] = buf[6] << 8;
}
SE_16BIT(predictor[0]);
SE_16BIT(predictor[1]);
/* decode the samples */
for (in = 8, out = 0; in < buf_size; in++, out++) {
predictor[channel_number] += s->roq_square_array[buf[in]];
SATURATE_S16(predictor[channel_number]);
output_samples[out] = predictor[channel_number];
/* toggle channel */
channel_number ^= s->channels - 1;
}
break;
case CODEC_ID_INTERPLAY_DPCM:
in = 6; /* skip over the stream mask and stream length */
predictor[0] = LE_16(&buf[in]);
in += 2;
SE_16BIT(predictor[0])
output_samples[out++] = predictor[0];
if (s->channels == 2) {
predictor[1] = LE_16(&buf[in]);
in += 2;
SE_16BIT(predictor[1])
output_samples[out++] = predictor[1];
}
while (in < buf_size) {
predictor[channel_number] += interplay_delta_table[buf[in++]];
SATURATE_S16(predictor[channel_number]);
output_samples[out++] = predictor[channel_number];
/* toggle channel */
channel_number ^= s->channels - 1;
}
break;
case CODEC_ID_XAN_DPCM:
in = 0;
shift[0] = shift[1] = 4;
predictor[0] = LE_16(&buf[in]);
in += 2;
SE_16BIT(predictor[0]);
if (s->channels == 2) {
predictor[1] = LE_16(&buf[in]);
in += 2;
SE_16BIT(predictor[1]);
}
while (in < buf_size) {
byte = buf[in++];
diff = (byte & 0xFC) << 8;
if ((byte & 0x03) == 3)
shift[channel_number]++;
else
shift[channel_number] -= (2 * (byte & 3));
/* saturate the shifter to a lower limit of 0 */
if (shift[channel_number] < 0)
shift[channel_number] = 0;
diff >>= shift[channel_number];
predictor[channel_number] += diff;
SATURATE_S16(predictor[channel_number]);
output_samples[out++] = predictor[channel_number];
/* toggle channel */
channel_number ^= s->channels - 1;
}
break;
case CODEC_ID_SOL_DPCM:
in = 0;
if (avctx->codec_tag != 3) {
while (in < buf_size) {
int n1, n2;
n1 = (buf[in] >> 4) & 0xF;
n2 = buf[in++] & 0xF;
s->sample[0] += s->sol_table[n1];
if (s->sample[0] < 0) s->sample[0] = 0;
if (s->sample[0] > 255) s->sample[0] = 255;
output_samples[out++] = (s->sample[0] - 128) << 8;
s->sample[s->channels - 1] += s->sol_table[n2];
if (s->sample[s->channels - 1] < 0) s->sample[s->channels - 1] = 0;
if (s->sample[s->channels - 1] > 255) s->sample[s->channels - 1] = 255;
output_samples[out++] = (s->sample[s->channels - 1] - 128) << 8;
}
} else {
while (in < buf_size) {
int n;
n = buf[in++];
if (n & 0x80) s->sample[channel_number] -= s->sol_table[n & 0x7F];
else s->sample[channel_number] += s->sol_table[n & 0x7F];
SATURATE_S16(s->sample[channel_number]);
output_samples[out++] = s->sample[channel_number];
/* toggle channel */
channel_number ^= s->channels - 1;
}
}
break;
}
*data_size = out * sizeof(short);
return buf_size;
}
AVCodec roq_dpcm_decoder = {
"roq_dpcm",
CODEC_TYPE_AUDIO,
CODEC_ID_ROQ_DPCM,
sizeof(DPCMContext),
dpcm_decode_init,
NULL,
NULL,
dpcm_decode_frame,
};
AVCodec interplay_dpcm_decoder = {
"interplay_dpcm",
CODEC_TYPE_AUDIO,
CODEC_ID_INTERPLAY_DPCM,
sizeof(DPCMContext),
dpcm_decode_init,
NULL,
NULL,
dpcm_decode_frame,
};
AVCodec xan_dpcm_decoder = {
"xan_dpcm",
CODEC_TYPE_AUDIO,
CODEC_ID_XAN_DPCM,
sizeof(DPCMContext),
dpcm_decode_init,
NULL,
NULL,
dpcm_decode_frame,
};
AVCodec sol_dpcm_decoder = {
"sol_dpcm",
CODEC_TYPE_AUDIO,
CODEC_ID_SOL_DPCM,
sizeof(DPCMContext),
dpcm_decode_init,
NULL,
NULL,
dpcm_decode_frame,
};
| achintsetia/ffmpeg0.4.9 | libavcodec/dpcm.c | C | lgpl-2.1 | 11,576 |
package org.skyve.metadata.view.model.chart;
import java.awt.Color;
import java.util.List;
public class ChartData {
private String title;
private List<Number> values;
private List<String> labels;
private List<Color> backgrounds;
private List<Color> borders;
private String label;
private Color background;
private Color border;
private String fullyQualifiedJFreeChartPostProcessorClassName;
private String fullyQualifiedPrimeFacesChartPostProcessorClassName;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Number> getValues() {
return values;
}
public void setValues(List<Number> values) {
this.values = values;
}
public List<String> getLabels() {
return labels;
}
public void setLabels(List<String> labels) {
this.labels = labels;
}
public List<Color> getBackgrounds() {
return backgrounds;
}
public void setBackgrounds(List<Color> backgrounds) {
this.backgrounds = backgrounds;
}
public List<Color> getBorders() {
return borders;
}
public void setBorders(List<Color> borders) {
this.borders = borders;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Color getBackground() {
return background;
}
public void setBackground(Color background) {
this.background = background;
}
public Color getBorder() {
return border;
}
public void setBorder(Color border) {
this.border = border;
}
public String getJFreeChartPostProcessorClassName() {
return fullyQualifiedJFreeChartPostProcessorClassName;
}
public void setJFreeChartPostProcessorClassName(String fullyQualifiedJFreeChartPostProcessorClassName) {
this.fullyQualifiedJFreeChartPostProcessorClassName = fullyQualifiedJFreeChartPostProcessorClassName;
}
public String getPrimeFacesChartPostProcessorClassName() {
return fullyQualifiedPrimeFacesChartPostProcessorClassName;
}
public void setPrimeFacesChartPostProcessorClassName(String fullyQualifiedPrimeFacesChartPostProcessorClassName) {
this.fullyQualifiedPrimeFacesChartPostProcessorClassName = fullyQualifiedPrimeFacesChartPostProcessorClassName;
}
}
| skyvers/skyve | skyve-core/src/main/java/org/skyve/metadata/view/model/chart/ChartData.java | Java | lgpl-2.1 | 2,177 |
/*
* HwDep Symbols
* Copyright (c) 2001 by Jaroslav Kysela <perex@perex.cz>
*
* 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 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef PIC
extern const char *_snd_module_hwdep_hw;
static const char **snd_hwdep_open_objects[] = {
&_snd_module_hwdep_hw
};
void *snd_hwdep_open_symbols(void)
{
return snd_hwdep_open_objects;
}
#endif
| takaswie/alsa-lib | src/hwdep/hwdep_symbols.c | C | lgpl-2.1 | 1,065 |
/////////////////////////////////////////////////////////////////////////////
// Name: tests/benchmarks/strings.cpp
// Purpose: String-related benchmarks
// Author: Vadim Zeitlin
// Created: 2008-07-19
// RCS-ID: $Id$
// Copyright: (c) 2008 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "bench.h"
#include "wx/tls.h"
#if defined(__UNIX__)
#define HAVE_PTHREAD
#include <pthread.h>
#elif defined(__WIN32__)
#define HAVE_WIN32_THREAD
#include "wx/msw/wrapwin.h"
#endif
#if wxCHECK_GCC_VERSION(3, 3)
#define HAVE_COMPILER_THREAD
#define wxTHREAD_SPECIFIC __thread
#elif wxCHECK_VISUALC_VERSION(7)
#define HAVE_COMPILER_THREAD
#define wxTHREAD_SPECIFIC __declspec(thread)
#endif
// uncomment this to also test Boost version (you will also need to link with
// libboost_threads)
//#define HAVE_BOOST_THREAD
#ifdef HAVE_BOOST_THREAD
#include <boost/thread/tss.hpp>
#endif
static const int NUM_ITER = 1000;
// this is just a baseline
BENCHMARK_FUNC(DummyTLS)
{
static int s_global = 0;
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
s_global = 0;
else
s_global = n;
}
return !s_global;
}
#ifdef HAVE_COMPILER_THREAD
BENCHMARK_FUNC(CompilerTLS)
{
static wxTHREAD_SPECIFIC int s_global = 0;
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
s_global = 0;
else
s_global = n;
}
return !s_global;
}
#endif // HAVE_COMPILER_THREAD
#ifdef HAVE_PTHREAD
class PthreadKey
{
public:
PthreadKey()
{
pthread_key_create(&m_key, NULL);
}
~PthreadKey()
{
pthread_key_delete(m_key);
}
operator pthread_key_t() const { return m_key; }
private:
pthread_key_t m_key;
DECLARE_NO_COPY_CLASS(PthreadKey)
};
BENCHMARK_FUNC(PosixTLS)
{
static PthreadKey s_key;
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
pthread_setspecific(s_key, 0);
else
pthread_setspecific(s_key, &n);
}
return !pthread_getspecific(s_key);
}
#endif // HAVE_PTHREAD
#ifdef HAVE_WIN32_THREAD
class TlsSlot
{
public:
TlsSlot()
{
m_slot = ::TlsAlloc();
}
~TlsSlot()
{
::TlsFree(m_slot);
}
operator DWORD() const { return m_slot; }
private:
DWORD m_slot;
DECLARE_NO_COPY_CLASS(TlsSlot)
};
BENCHMARK_FUNC(Win32TLS)
{
static TlsSlot s_slot;
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
::TlsSetValue(s_slot, 0);
else
::TlsSetValue(s_slot, &n);
}
return !::TlsGetValue(s_slot);
}
#endif // HAVE_WIN32_THREAD
#ifdef HAVE_BOOST_THREAD
BENCHMARK_FUNC(BoostTLS)
{
static boost::thread_specific_ptr<int> s_ptr;
if ( !s_ptr.get() )
s_ptr.reset(new int(0));
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
*s_ptr = 0;
else
*s_ptr = n;
}
return !*s_ptr;
}
#endif // HAVE_BOOST_THREAD
BENCHMARK_FUNC(wxTLS)
{
static wxTLS_TYPE(int) s_globalVar;
#define s_global wxTLS_VALUE(s_globalVar)
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
s_global = 0;
else
s_global = n;
}
return !s_global;
}
| enachb/freetel-code | src/wxWidgets-2.9.4/tests/benchmarks/tls.cpp | C++ | lgpl-2.1 | 3,439 |
package eu.europa.esig.dss.validation.process.qualification;
import java.util.Date;
import javax.xml.bind.DatatypeConverter;
public final class EIDASUtils {
private EIDASUtils() {
}
/**
* Start date of the eIDAS regulation
*
* Regulation was signed in Brussels : 1st of July 00:00 Brussels = 30th of June 22:00 UTC
*/
private static final Date EIDAS_DATE = DatatypeConverter.parseDateTime("2016-06-30T22:00:00.000Z").getTime();
/**
* End of the grace period for eIDAS regulation
*/
private static final Date EIDAS_GRACE_DATE = DatatypeConverter.parseDateTime("2017-06-30T22:00:00.000Z").getTime();
public static boolean isPostEIDAS(Date date) {
return date != null && date.compareTo(EIDAS_DATE) >= 0;
}
public static boolean isPreEIDAS(Date date) {
return date != null && date.compareTo(EIDAS_DATE) < 0;
}
public static boolean isPostGracePeriod(Date date) {
return date != null && date.compareTo(EIDAS_GRACE_DATE) >= 0;
}
}
| alisdev/dss | validation-policy/src/main/java/eu/europa/esig/dss/validation/process/qualification/EIDASUtils.java | Java | lgpl-2.1 | 966 |
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2014 LensKit Contributors. See CONTRIBUTORS.md.
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.lenskit.data.ratings;
import it.unimi.dsi.fastutil.longs.Long2DoubleMap;
import org.grouplens.lenskit.vectors.MutableSparseVector;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class RatingTest {
@Test
public void testGetValueOfRating() {
Rating rating = Rating.create(1, 2, 3.0, 3);
assertThat(rating.hasValue(), equalTo(true));
assertThat(rating.getValue(), equalTo(3.0));
}
@Test
public void testGetValueOfUnrate() {
Rating rating = Rating.createUnrate(1, 3, 5);
assertThat(rating.hasValue(), equalTo(false));
}
@Test
@SuppressWarnings("deprecation")
public void testDeprecatedFactories() {
Rating rating = Ratings.make(1, 2, 3.0);
Rating withTS = Ratings.make(1, 2, 3.0, 1030);
assertThat(rating.getUserId(), equalTo(1L));
assertThat(rating.getItemId(), equalTo(2L));
assertThat(rating.getValue(), equalTo(3.0));
assertThat(withTS.getUserId(), equalTo(1L));
assertThat(withTS.getItemId(), equalTo(2L));
assertThat(withTS.getValue(), equalTo(3.0));
assertThat(withTS.getTimestamp(), equalTo(1030L));
}
@Test
public void testSimpleEquality() {
Rating r1 = Rating.create(1, 2, 3.0, 0);
Rating r1a = Rating.create(1, 2, 3.0, 0);
Rating r2 = Rating.create(1, 3, 2.5, 1);
Rating rn = Rating.createUnrate(1, 2, 0);
assertThat(r1, equalTo(r1));
assertThat(r1a, equalTo(r1));
assertThat(r2, not(equalTo(r1)));
assertThat(r1, not(equalTo(r2)));
assertThat(rn, not(equalTo(r1)));
assertThat(r1, not(equalTo(rn)));
}
@Test
public void testEmptyURV() {
List<Rating> ratings = Collections.emptyList();
Long2DoubleMap urv = Ratings.userRatingVector(ratings);
assertThat(urv.isEmpty(), equalTo(true));
assertThat(urv.size(), equalTo(0));
}
@Test
public void testURVRatingsInOrder() {
List<Rating> ratings = new ArrayList<Rating>();
ratings.add(Rating.create(1, 2, 3.0, 3));
ratings.add(Rating.create(1, 3, 4.5, 7));
ratings.add(Rating.create(1, 5, 2.3, 10));
Long2DoubleMap urv = Ratings.userRatingVector(ratings);
assertThat(urv.isEmpty(), equalTo(false));
assertThat(urv.size(), equalTo(3));
assertThat(urv.get(2), closeTo(3.0, 1.0e-6));
assertThat(urv.get(3), closeTo(4.5, 1.0e-6));
assertThat(urv.get(5), closeTo(2.3, 1.0e-6));
assertThat(urv.containsKey(1), equalTo(false));
}
@Test
public void testURVRatingsOutOfOrder() {
List<Rating> ratings = new ArrayList<Rating>();
ratings.add(Rating.create(1, 2, 3.0, 3));
ratings.add(Rating.create(1, 5, 2.3, 7));
ratings.add(Rating.create(1, 3, 4.5, 10));
Long2DoubleMap urv = Ratings.userRatingVector(ratings);
assertThat(urv.isEmpty(), equalTo(false));
assertThat(urv.size(), equalTo(3));
assertThat(urv.get(2), closeTo(3.0, 1.0e-6));
assertThat(urv.get(3), closeTo(4.5, 1.0e-6));
assertThat(urv.get(5), closeTo(2.3, 1.0e-6));
assertThat(urv.containsKey(1), equalTo(false));
}
@Test
public void testURVRatingsDup() {
List<Rating> ratings = new ArrayList<Rating>();
ratings.add(Rating.create(1, 2, 3.0, 3));
ratings.add(Rating.create(1, 5, 2.3, 4));
ratings.add(Rating.create(1, 3, 4.5, 5));
ratings.add(Rating.create(1, 5, 3.7, 6));
Long2DoubleMap urv = Ratings.userRatingVector(ratings);
assertThat(urv.isEmpty(), equalTo(false));
assertThat(urv.size(), equalTo(3));
assertThat(urv.get(2), closeTo(3.0, 1.0e-6));
assertThat(urv.get(3), closeTo(4.5, 1.0e-6));
assertThat(urv.get(5), closeTo(3.7, 1.0e-6));
assertThat(urv.containsKey(1), equalTo(false));
}
@Test
public void testURVRatingsRmv() {
List<Rating> ratings = new ArrayList<Rating>();
ratings.add(Rating.create(1, 2, 3.0, 3));
ratings.add(Rating.create(1, 5, 2.3, 5));
ratings.add(Rating.createUnrate(1, 2, 7));
ratings.add(Rating.create(1, 3, 4.5, 8));
Long2DoubleMap urv = Ratings.userRatingVector(ratings);
assertThat(urv.isEmpty(), equalTo(false));
assertThat(urv.size(), equalTo(2));
assertThat(urv.get(3), closeTo(4.5, 1.0e-6));
assertThat(urv.get(5), closeTo(2.3, 1.0e-6));
assertThat(urv.containsKey(1), equalTo(false));
assertThat(urv.containsKey(2), equalTo(false));
}
@Test
public void testURVRatingsDupOutOfOrder() {
List<Rating> ratings = new ArrayList<Rating>();
ratings.add(Rating.create(1, 2, 3.0, 3));
ratings.add(Rating.create(1, 5, 2.3, 7));
ratings.add(Rating.create(1, 3, 4.5, 5));
ratings.add(Rating.create(1, 5, 3.7, 6));
Long2DoubleMap urv = Ratings.userRatingVector(ratings);
assertThat(urv.isEmpty(), equalTo(false));
assertThat(urv.size(), equalTo(3));
assertThat(urv.get(2), closeTo(3.0, 1.0e-6));
assertThat(urv.get(3), closeTo(4.5, 1.0e-6));
assertThat(urv.get(5), closeTo(2.3, 1.0e-6));
assertThat(urv.containsKey(1), equalTo(false));
}
@Test
public void testEmptyIRV() {
List<Rating> ratings = Collections.emptyList();
Long2DoubleMap urv = Ratings.itemRatingVector(ratings);
assertThat(urv.isEmpty(), equalTo(true));
assertThat(urv.size(), equalTo(0));
}
@Test
public void testIRVRatings() {
List<Rating> ratings = new ArrayList<Rating>();
ratings.add(Rating.create(1, 2, 3.0, 1));
ratings.add(Rating.create(3, 2, 4.5, 2));
ratings.add(Rating.create(2, 2, 2.3, 3));
ratings.add(Rating.create(3, 2, 4.5, 10));
Long2DoubleMap urv = Ratings.itemRatingVector(ratings);
assertThat(urv.isEmpty(), equalTo(false));
assertThat(urv.size(), equalTo(3));
assertThat(urv.get(1), closeTo(3.0, 1.0e-6));
assertThat(urv.get(3), closeTo(4.5, 1.0e-6));
assertThat(urv.get(2), closeTo(2.3, 1.0e-6));
assertThat(urv.containsKey(5), equalTo(false));
}
}
| amaliujia/lenskit | lenskit-core/src/test/java/org/lenskit/data/ratings/RatingTest.java | Java | lgpl-2.1 | 7,390 |
/*
* Automatically generated by jrpcgen 0.95.1 on 12/18/01 7:23 PM
* jrpcgen is part of the "Remote Tea" ONC/RPC package for Java
* See http://acplt.org/ks/remotetea.html for details
*/
package com.sleepycat.db.rpcserver;
import org.acplt.oncrpc.*;
import java.io.IOException;
public class __db_remove_reply implements XdrAble {
public int status;
public __db_remove_reply() {
}
public __db_remove_reply(XdrDecodingStream xdr)
throws OncRpcException, IOException {
xdrDecode(xdr);
}
public void xdrEncode(XdrEncodingStream xdr)
throws OncRpcException, IOException {
xdr.xdrEncodeInt(status);
}
public void xdrDecode(XdrDecodingStream xdr)
throws OncRpcException, IOException {
status = xdr.xdrDecodeInt();
}
}
// End of __db_remove_reply.java
| community-ssu/evolution-data-server | libdb/rpc_server/java/gen/__db_remove_reply.java | Java | lgpl-2.1 | 846 |
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_PALETTE_HPP
#define MAPNIK_PALETTE_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/global.hpp>
#include <mapnik/noncopyable.hpp>
#define USE_DENSE_HASH_MAP
#ifdef USE_DENSE_HASH_MAP
#include <mapnik/sparsehash/dense_hash_map>
using rgba_hash_table = google::dense_hash_map<unsigned int, unsigned char>;
#else
#include <boost/unordered_map.hpp>
using rgba_hash_table = boost::unordered_map<unsigned int, unsigned char>;
#endif
// stl
#include <vector>
#define U2RED(x) ((x)&0xff)
#define U2GREEN(x) (((x)>>8)&0xff)
#define U2BLUE(x) (((x)>>16)&0xff)
#define U2ALPHA(x) (((x)>>24)&0xff)
namespace mapnik {
struct rgba;
struct MAPNIK_DECL rgb {
byte r;
byte g;
byte b;
inline rgb(byte r_, byte g_, byte b_) : r(r_), g(g_), b(b_) {}
rgb(rgba const& c);
inline bool operator==(const rgb& y) const
{
return r == y.r && g == y.g && b == y.b;
}
};
struct MAPNIK_DECL rgba
{
byte r;
byte g;
byte b;
byte a;
inline rgba(byte r_, byte g_, byte b_, byte a_)
: r(r_),
g(g_),
b(b_),
a(a_) {}
inline rgba(rgb const& c)
: r(c.r),
g(c.g),
b(c.b),
a(0xFF) {}
inline rgba(unsigned const& c)
: r(U2RED(c)),
g(U2GREEN(c)),
b(U2BLUE(c)),
a(U2ALPHA(c)) {}
inline bool operator==(const rgba& y) const
{
return r == y.r && g == y.g && b == y.b && a == y.a;
}
// ordering by mean(a,r,g,b), a, r, g, b
struct MAPNIK_DECL mean_sort_cmp
{
bool operator() (const rgba& x, const rgba& y) const;
};
};
class MAPNIK_DECL rgba_palette : private mapnik::noncopyable {
public:
enum palette_type { PALETTE_RGBA = 0, PALETTE_RGB = 1, PALETTE_ACT = 2 };
explicit rgba_palette(std::string const& pal, palette_type type = PALETTE_RGBA);
rgba_palette();
const std::vector<rgb>& palette() const;
const std::vector<unsigned>& alphaTable() const;
unsigned char quantize(unsigned c) const;
bool valid() const;
std::string to_string() const;
private:
void parse(std::string const& pal, palette_type type);
private:
std::vector<rgba> sorted_pal_;
mutable rgba_hash_table color_hashmap_;
unsigned colors_;
std::vector<rgb> rgb_pal_;
std::vector<unsigned> alpha_pal_;
};
} // namespace mapnik
#endif // MAPNIK_PALETTE_HPP
| TemplateVoid/mapnik | include/mapnik/palette.hpp | C++ | lgpl-2.1 | 3,424 |
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
*
* Copyright (C) 2014-2015 Richard Hughes <richard@hughsie.com>
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <config.h>
#include <fnmatch.h>
#include <asb-plugin.h>
/**
* asb_plugin_get_name:
*/
const gchar *
asb_plugin_get_name (void)
{
return "gstreamer";
}
/**
* asb_plugin_add_globs:
*/
void
asb_plugin_add_globs (AsbPlugin *plugin, GPtrArray *globs)
{
asb_plugin_add_glob (globs, "/usr/lib64/gstreamer-1.0/libgst*.so");
}
typedef struct {
const gchar *path;
const gchar *text;
} AsbGstreamerDescData;
static const AsbGstreamerDescData data[] = {
{ "/usr/lib64/gstreamer-1.0/libgsta52dec.so", "AC-3" },
{ "/usr/lib64/gstreamer-1.0/libgstaiff.so", "AIFF" },
{ "/usr/lib64/gstreamer-1.0/libgstamrnb.so", "AMR-NB" },
{ "/usr/lib64/gstreamer-1.0/libgstamrwbdec.so", "AMR-WB" },
{ "/usr/lib64/gstreamer-1.0/libgstapetag.so", "APE" },
{ "/usr/lib64/gstreamer-1.0/libgstasf.so", "ASF" },
{ "/usr/lib64/gstreamer-1.0/libgstavi.so", "AVI" },
{ "/usr/lib64/gstreamer-1.0/libgstavidemux.so", "AVI" },
{ "/usr/lib64/gstreamer-1.0/libgstdecklink.so", "SDI" },
{ "/usr/lib64/gstreamer-1.0/libgstdtsdec.so", "DTS" },
{ "/usr/lib64/gstreamer-1.0/libgstdv.so", "DV" },
{ "/usr/lib64/gstreamer-1.0/libgstdvb.so", "DVB" },
{ "/usr/lib64/gstreamer-1.0/libgstdvdread.so", "DVD" },
{ "/usr/lib64/gstreamer-1.0/libgstdvdspu.so", "Bluray" },
{ "/usr/lib64/gstreamer-1.0/libgstespeak.so", "eSpeak" },
{ "/usr/lib64/gstreamer-1.0/libgstfaad.so", "MPEG-4|MPEG-2 AAC" },
{ "/usr/lib64/gstreamer-1.0/libgstflac.so", "FLAC" },
{ "/usr/lib64/gstreamer-1.0/libgstflv.so", "Flash" },
{ "/usr/lib64/gstreamer-1.0/libgstflxdec.so", "FLX" },
{ "/usr/lib64/gstreamer-1.0/libgstgsm.so", "GSM" },
{ "/usr/lib64/gstreamer-1.0/libgstid3tag.so", "ID3" },
{ "/usr/lib64/gstreamer-1.0/libgstisomp4.so", "MP4" },
{ "/usr/lib64/gstreamer-1.0/libgstmad.so", "MP3" },
{ "/usr/lib64/gstreamer-1.0/libgstmatroska.so", "MKV" },
{ "/usr/lib64/gstreamer-1.0/libgstmfc.so", "MFC" },
{ "/usr/lib64/gstreamer-1.0/libgstmidi.so", "MIDI" },
{ "/usr/lib64/gstreamer-1.0/libgstmimic.so", "Mimic" },
{ "/usr/lib64/gstreamer-1.0/libgstmms.so", "MMS" },
{ "/usr/lib64/gstreamer-1.0/libgstmpeg2dec.so", "MPEG-2" },
{ "/usr/lib64/gstreamer-1.0/libgstmpg123.so", "MP3" },
{ "/usr/lib64/gstreamer-1.0/libgstmxf.so", "MXF" },
{ "/usr/lib64/gstreamer-1.0/libgstogg.so", "Ogg" },
{ "/usr/lib64/gstreamer-1.0/libgstopus.so", "Opus" },
{ "/usr/lib64/gstreamer-1.0/libgstrmdemux.so", "RealMedia" },
{ "/usr/lib64/gstreamer-1.0/libgstschro.so", "Dirac" },
{ "/usr/lib64/gstreamer-1.0/libgstsiren.so", "Siren" },
{ "/usr/lib64/gstreamer-1.0/libgstspeex.so", "Speex" },
{ "/usr/lib64/gstreamer-1.0/libgsttheora.so", "Theora" },
{ "/usr/lib64/gstreamer-1.0/libgsttwolame.so", "MP2" },
{ "/usr/lib64/gstreamer-1.0/libgstvorbis.so", "Vorbis" },
{ "/usr/lib64/gstreamer-1.0/libgstvpx.so", "VP8|VP9" },
{ "/usr/lib64/gstreamer-1.0/libgstwavenc.so", "WAV" },
{ "/usr/lib64/gstreamer-1.0/libgstx264.so", "H.264/MPEG-4 AVC" },
{ NULL, NULL }
};
/**
* asb_utils_is_file_in_tmpdir:
*/
static gboolean
asb_utils_is_file_in_tmpdir (const gchar *tmpdir, const gchar *filename)
{
g_autofree gchar *tmp = NULL;
tmp = g_build_filename (tmpdir, filename, NULL);
return g_file_test (tmp, G_FILE_TEST_EXISTS);
}
/**
* asb_plugin_process_app:
*/
gboolean
asb_plugin_process_app (AsbPlugin *plugin,
AsbPackage *pkg,
AsbApp *app,
const gchar *tmpdir,
GError **error)
{
guint i;
guint j;
for (i = 0; data[i].path != NULL; i++) {
g_auto(GStrv) split = NULL;
if (!asb_utils_is_file_in_tmpdir (tmpdir, data[i].path))
continue;
split = g_strsplit (data[i].text, "|", -1);
for (j = 0; split[j] != NULL; j++)
as_app_add_keyword (AS_APP (app), NULL, split[j]);
}
return TRUE;
}
| mitya57/appstream-glib | libappstream-builder/plugins/asb-plugin-gstreamer.c | C | lgpl-2.1 | 4,634 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtGui 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 "qgraphicsscene_bsp_p.h"
#ifndef QT_NO_GRAPHICSVIEW
#include <QtCore/qstring.h>
#include <private/qgraphicsitem_p.h>
QT_BEGIN_NAMESPACE
class QGraphicsSceneInsertItemBspTreeVisitor : public QGraphicsSceneBspTreeVisitor
{
public:
QGraphicsItem *item;
void visit(QList<QGraphicsItem *> *items)
{ items->prepend(item); }
};
class QGraphicsSceneRemoveItemBspTreeVisitor : public QGraphicsSceneBspTreeVisitor
{
public:
QGraphicsItem *item;
void visit(QList<QGraphicsItem *> *items)
{ items->removeAll(item); }
};
class QGraphicsSceneFindItemBspTreeVisitor : public QGraphicsSceneBspTreeVisitor
{
public:
QList<QGraphicsItem *> *foundItems;
bool onlyTopLevelItems;
void visit(QList<QGraphicsItem *> *items)
{
for (int i = 0; i < items->size(); ++i) {
QGraphicsItem *item = items->at(i);
if (onlyTopLevelItems && item->d_ptr->parent)
item = item->topLevelItem();
if (!item->d_func()->itemDiscovered && item->d_ptr->visible) {
item->d_func()->itemDiscovered = 1;
foundItems->prepend(item);
}
}
}
};
QGraphicsSceneBspTree::QGraphicsSceneBspTree()
: leafCnt(0)
{
insertVisitor = new QGraphicsSceneInsertItemBspTreeVisitor;
removeVisitor = new QGraphicsSceneRemoveItemBspTreeVisitor;
findVisitor = new QGraphicsSceneFindItemBspTreeVisitor;
}
QGraphicsSceneBspTree::~QGraphicsSceneBspTree()
{
delete insertVisitor;
delete removeVisitor;
delete findVisitor;
}
void QGraphicsSceneBspTree::initialize(const QRectF &rect, int depth)
{
this->rect = rect;
leafCnt = 0;
nodes.resize((1 << (depth + 1)) - 1);
nodes.fill(Node());
leaves.resize(1 << depth);
leaves.fill(QList<QGraphicsItem *>());
initialize(rect, depth, 0);
}
void QGraphicsSceneBspTree::clear()
{
leafCnt = 0;
nodes.clear();
leaves.clear();
}
void QGraphicsSceneBspTree::insertItem(QGraphicsItem *item, const QRectF &rect)
{
insertVisitor->item = item;
climbTree(insertVisitor, rect);
}
void QGraphicsSceneBspTree::removeItem(QGraphicsItem *item, const QRectF &rect)
{
removeVisitor->item = item;
climbTree(removeVisitor, rect);
}
void QGraphicsSceneBspTree::removeItems(const QSet<QGraphicsItem *> &items)
{
for (int i = 0; i < leaves.size(); ++i) {
QList<QGraphicsItem *> newItemList;
const QList<QGraphicsItem *> &oldItemList = leaves[i];
for (int j = 0; j < oldItemList.size(); ++j) {
QGraphicsItem *item = oldItemList.at(j);
if (!items.contains(item))
newItemList << item;
}
leaves[i] = newItemList;
}
}
QList<QGraphicsItem *> QGraphicsSceneBspTree::items(const QRectF &rect, bool onlyTopLevelItems) const
{
QList<QGraphicsItem *> tmp;
findVisitor->foundItems = &tmp;
findVisitor->onlyTopLevelItems = onlyTopLevelItems;
climbTree(findVisitor, rect);
// Reset discovery bits.
for (int i = 0; i < tmp.size(); ++i)
tmp.at(i)->d_ptr->itemDiscovered = 0;
return tmp;
}
int QGraphicsSceneBspTree::leafCount() const
{
return leafCnt;
}
QString QGraphicsSceneBspTree::debug(int index) const
{
const Node *node = &nodes.at(index);
QString tmp;
if (node->type == Node::Leaf) {
QRectF rect = rectForIndex(index);
if (!leaves[node->leafIndex].isEmpty()) {
tmp += QString::fromLatin1("[%1, %2, %3, %4] contains %5 items\n")
.arg(rect.left()).arg(rect.top())
.arg(rect.width()).arg(rect.height())
.arg(leaves[node->leafIndex].size());
}
} else {
if (node->type == Node::Horizontal) {
tmp += debug(firstChildIndex(index));
tmp += debug(firstChildIndex(index) + 1);
} else {
tmp += debug(firstChildIndex(index));
tmp += debug(firstChildIndex(index) + 1);
}
}
return tmp;
}
void QGraphicsSceneBspTree::initialize(const QRectF &rect, int depth, int index)
{
Node *node = &nodes[index];
if (index == 0) {
node->type = Node::Horizontal;
node->offset = rect.center().x();
}
if (depth) {
Node::Type type;
QRectF rect1, rect2;
qreal offset1, offset2;
if (node->type == Node::Horizontal) {
type = Node::Vertical;
rect1.setRect(rect.left(), rect.top(), rect.width(), rect.height() / 2);
rect2.setRect(rect1.left(), rect1.bottom(), rect1.width(), rect.height() - rect1.height());
offset1 = rect1.center().x();
offset2 = rect2.center().x();
} else {
type = Node::Horizontal;
rect1.setRect(rect.left(), rect.top(), rect.width() / 2, rect.height());
rect2.setRect(rect1.right(), rect1.top(), rect.width() - rect1.width(), rect1.height());
offset1 = rect1.center().y();
offset2 = rect2.center().y();
}
int childIndex = firstChildIndex(index);
Node *child = &nodes[childIndex];
child->offset = offset1;
child->type = type;
child = &nodes[childIndex + 1];
child->offset = offset2;
child->type = type;
initialize(rect1, depth - 1, childIndex);
initialize(rect2, depth - 1, childIndex + 1);
} else {
node->type = Node::Leaf;
node->leafIndex = leafCnt++;
}
}
void QGraphicsSceneBspTree::climbTree(QGraphicsSceneBspTreeVisitor *visitor, const QRectF &rect, int index) const
{
if (nodes.isEmpty())
return;
const Node &node = nodes.at(index);
const int childIndex = firstChildIndex(index);
switch (node.type) {
case Node::Leaf: {
visitor->visit(const_cast<QList<QGraphicsItem*>*>(&leaves[node.leafIndex]));
break;
}
case Node::Vertical:
if (rect.left() < node.offset) {
climbTree(visitor, rect, childIndex);
if (rect.right() >= node.offset)
climbTree(visitor, rect, childIndex + 1);
} else {
climbTree(visitor, rect, childIndex + 1);
}
break;
case Node::Horizontal:
if (rect.top() < node.offset) {
climbTree(visitor, rect, childIndex);
if (rect.bottom() >= node.offset)
climbTree(visitor, rect, childIndex + 1);
} else {
climbTree(visitor, rect, childIndex + 1);
}
}
}
QRectF QGraphicsSceneBspTree::rectForIndex(int index) const
{
if (index <= 0)
return rect;
int parentIdx = parentIndex(index);
QRectF rect = rectForIndex(parentIdx);
const Node *parent = &nodes.at(parentIdx);
if (parent->type == Node::Horizontal) {
if (index & 1)
rect.setRight(parent->offset);
else
rect.setLeft(parent->offset);
} else {
if (index & 1)
rect.setBottom(parent->offset);
else
rect.setTop(parent->offset);
}
return rect;
}
QT_END_NAMESPACE
#endif // QT_NO_GRAPHICSVIEW
| eric100lin/Qt-4.8.6 | src/gui/graphicsview/qgraphicsscene_bsp.cpp | C++ | lgpl-2.1 | 9,073 |
<!DOCTYPE html>
<!--
* This file is part of Cockpit.
*
* Copyright (C) 2015 Red Hat, Inc.
*
* Cockpit 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.
*
* Cockpit 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 Cockpit; If not, see <http://www.gnu.org/licenses/>.
-->
<html>
<head>
<title translatable="yes">Storage</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../base1/cockpit.css" type="text/css" rel="stylesheet">
<link href="../system/journal.css" type="text/css" rel="stylesheet">
<link href="../shell/plot.css" type="text/css" rel="stylesheet">
<link href="storage.css" type="text/css" rel="stylesheet">
<script src="../base1/bundle.js"></script>
<script src="../system/bundle.js"></script>
<script src="../shell/shell.js"></script>
<script src="bundle.js"></script>
<script>
require([
"jquery",
"storage/devices",
"base1/bootstrap-select",
], function($, devices) {
$(devices);
});
</script>
</head>
<body hidden>
<!-- CURTAIN -->
<div id="unsupported" hidden>
<div class="blank-slate-pf">
<h1 translatable="yes">The "storaged" API is not available on this system.</h1>
</div>
</div>
<!-- ALERT FOR BROKEN MULTIPATH -->
<div id="multipath-broken" class="container-fluid" hidden>
<div class="alert alert-danger">
<span class="pficon pficon-error-circle-o"></span>
<button id="activate-multipath" translatable="yes"
class="btn btn-default pull-right">Start Multipath</button>
<span class="alert-message" translatable="yes">
There are devices with multiple paths on the system, but the multipath service is not running.
</span>
</div>
</div>
<!-- OVERVIEW -->
<script id="mdraids-tmpl" type="x-template/mustache">
<div class="panel panel-default">
<div class="panel-heading">
<span class="pull-right">
<button id="create-mdraid" class="btn btn-primary fa fa-plus"></button>
</span>
<span translatable="yes">RAID Devices</span>
</div>
{{#HasMDRaids}}
<table class="table table-hover">
{{#MDRaids}}
<tr data-goto-mdraid={{UUID}}>
<td style="width: 48px">
<div><img src="images/storage-array.png"></div>
</td>
<td class="row">
<span class="col-md-12 storage-disk-name">{{Name}}</span>
<br>
<span class="col-md-12 col-lg-5 storage-disk-size">{{Size}}</span>
</td>
<td style="width: 48px">
<div class="spinner spinner-sm" data-job-object="{{path}}"
style="visibility:hidden;margin-top:5px"></div>
</td>
</tr>
{{/MDRaids}}
</table>
{{/HasMDRaids}}
{{^HasMDRaids}}
<div translatable="yes" class="empty-panel-text">No storage set up as RAID</div>
{{/HasMDRaids}}
</div>
</script>
<script id="vgroups-tmpl" type="x-template/mustache">
<div class="panel panel-default">
<div class="panel-heading">
<span class="pull-right">
<button id="create-volume-group" class="btn btn-primary fa fa-plus"></button>
</span>
<span translatable="yes">Volume Groups</span>
</div>
{{#HasVGroups}}
<table class="table table-hover">
{{#VGroups}}
<tr data-goto-vgroup={{Name}}>
<td style="width: 48px">
<div><img src="images/storage-array.png"></div>
</td>
<td class="row">
<span class="col-md-12 storage-disk-name">{{Name}}</span>
<br>
<span class="col-md-12 col-lg-5 storage-disk-size">{{Size}}</span>
</td>
<td style="width: 48px">
<div class="spinner spinner-sm" data-job-object="{{path}}"
style="visibility:hidden;margin-top:5px"></div>
</td>
</tr>
{{/VGroups}}
</table>
{{/HasVGroups}}
{{^HasVGroups}}
<div translatable="yes" class="empty-panel-text">No volume groups created</div>
{{/HasVGroups}}
</div>
</script>
<script id="drives-tmpl" type="x-template/mustache">
<div class="panel panel-default">
<div class="panel-heading">
<span translatable="yes">Drives</span>
</div>
{{#HasDrives}}
<table class="table table-hover">
{{#Drives}}
<tr data-goto-block={{dev}} {{#Highlight}}class="highlight"{{/Highlight}}>
<td style="width: 48px">
<div><img src="images/storage-disk.png"></div>
</td>
<td class="row">
<span class="col-md-12">{{Name}}</span>
<br>
<span class="col-md-12 col-lg-5 storage-disk-size">{{Description}}</span>
<span class="col-md-12 col-lg-7">
<span>R: {{ReadRate}}</span>
<span style="display:inline-block;width:1em"></span>
<span>W: {{WriteRate}}</span>
</span>
</td>
<td style="width: 48px">
<div class="spinner spinner-sm" data-job-object="{{path}}"
style="visibility:hidden;margin-top:5px"></div>
</td>
</tr>
{{/Drives}}
</table>
{{/HasDrives}}
{{^HasDrives}}
<div translatable="yes" class="empty-panel-text">No drives attached</div>
{{/HasDrives}}
</div>
</script>
<script id="others-tmpl" type="x-template/mustache">
{{#HasOthers}}
<div class="panel panel-default">
<div class="panel-heading">
<span translatable="yes">Other Devices</span>
</div>
<table class="table table-hover">
{{#Others}}
<tr data-goto-block={{dev}}>
<td style="width: 48px">
<div class="spinner spinner-sm" data-job-object="{{path}}"
style="visibility:hidden;margin-top:5px"></div>
</td>
<td class="row">
<span class="col-md-12 storage-disk-name">{{Name}}</span>
<br>
<span class="col-md-12 col-lg-5 storage-disk-size">{{Description}}</span>
</td>
</tr>
{{/Others}}
</table>
</div>
{{/HasOthers}}
</script>
<script id="mounts-tmpl" type="x-template/mustache">
<div class="panel panel-default storage-mounts">
<div class="panel-heading">
<span translatable="yes">Filesystems</span>
</div>
<table class="table table-hover">
<thead>
<tr>
<th class="mount-name" translatable="yes">Name</th>
<th class="mount-point" translatable="yes">Mount Point</th>
<th class="mount-size-graph" translatable="yes">Size</th>
<th class="mount-size-number"> </th>
</tr>
</thead>
<tbody id="storage_mounts">
{{#Mounts}}
<tr {{#LinkTarget}}data-goto-{{type}}="{{target}}"{{/LinkTarget}}>
<td>
{{Name}}
</td>
{{#IsMounted}}
<td>
{{#MountPoints}}
<div>{{.}}</div>
{{/MountPoints}}
</td>
<td>
<div class="progress" style="width:100%">
<div class="progress-bar {{#UsageCritical}}progress-bar-danger{{/UsageCritical}}"
style="width:{{UsagePercent}}%">
</div>
</div>
</td>
<td style="text-align:right">
{{UsageText}}
</td>
{{/IsMounted}}
{{^IsMounted}}
<td>
-
</td>
<td>
</td>
<td style="text-align:right">
{{DeviceSize}}
</td>
{{/IsMounted}}
</tr>
{{/Mounts}}
</tbody>
</table>
</div>
</script>
<script id="jobs-tmpl" type="x-template/mustache">
{{#HasJobs}}
<div class="panel panel-default">
<div class="panel-heading">
<span translatable="yes">Jobs</span>
</div>
<table class="table">
{{#Jobs}}
<tr>
<td style="width:50%">{{Description}}</td>
<td style="width:15%;text-align:right">{{#Progress}}{{.}}{{/Progress}}</td>
<td style="width:15%;text-align:right">{{#RemainingTime}}{{.}}{{/RemainingTime}}</td>
<td style="text-align:right">
{{#Cancelable}}<button translatable="yes" class="btn btn-default" data-action="job_cancel" data-arg="{{path}}">Cancel</button>{{/Cancelable}}
</td>
</tr>
{{/Jobs}}
</table>
</div>
{{/HasJobs}}
</script>
<div id="storage" hidden>
<div class="col-md-8 col-lg-9">
<div id="storage-graph-toolbar" class="zoom-controls standard-zoom-controls">
<div class="dropdown" style="display:inline-block">
<button class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span style="width:6em;text-align:left;padding-left:5px;display:inline-block"></span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li role="presentation"><a role="menuitem" tabindex="-1" data-action="goto-now" translatable="yes">Go to now</a></li>
<li role="presentation" class="divider"></li>
<li role="presentation"><a role="menuitem" tabindex="-1" data-range="300" translatable="yes">5 minutes</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" data-range="3600" translatable="yes">1 hour</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" data-range="21600" translatable="yes">6 hours</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" data-range="86400" translatable="yes">1 day</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" data-range="604800" translatable="yes">1 week</a></li>
</ul>
</div>
<button class="btn btn-default" data-action="zoom-out">
<span class="glyphicon glyphicon-zoom-out"></span>
</button>
<div class="btn-group">
<button class="btn btn-default fa fa-angle-left" data-action="scroll-left"></button>
<button class="btn btn-default fa fa-angle-right" data-action="scroll-right"></button>
</div>
</div>
<div class="row">
<div class="col-sm-6 storage-reading-graph-container">
<div>
<span class="plot-unit" id="storage-reading-unit"></span><span class="plot-title" translatable="yes">Reading</span>
</div>
<div style="height:120px" id="storage-reading-graph" class="zoomable-plot"></div>
</div>
<div class="col-sm-6 storage-writing-graph-container">
<div>
<span class="plot-unit" id="storage-writing-unit"></span><span class="plot-title" translatable="yes">Writing</span>
</div>
<div style="height:120px" id="storage-writing-graph" class="zoomable-plot"></div>
</div>
</div>
<br/>
<div id="mounts"></div>
<div id="jobs"></div>
<div class="panel panel-default cockpit-log-panel">
<div class="panel-heading" translatable="yes">Storage Logs</div>
<div class="panel-body" id="storage-log"></div>
</div>
</div>
<div class="col-md-4 col-lg-3 storage-sidebar">
<div id="mdraids"></div>
<div id="vgroups"></div>
<div id="drives"></div>
<div id="others"></div>
<div id="jobs"></div>
</div>
</div>
<!-- DETAIL -->
<script id="action-btn-tmpl" type="x-template/mustache">
<div class="btn-group">
<button data-action="{{def.action}}" data-arg="{{arg}}" class="btn btn-default storage-privileged">{{def.title}}</button>
<button class="btn btn-default dropdown-toggle storage-privileged" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu"
style="right:0px;left:auto;min-width:0;text-align:left"
role="menu">
{{#actions}}
<li class="presentation {{#disabled}}disabled{{/disabled}}">
<a class=" storage-privileged" data-action="{{action}}" data-arg="{{arg}}" role="menuitem">{{title}}</a>
</li>
{{/actions}}
</ul>
</div>
</script>
<script id="content-tmpl" type="x-template/mustache">
<div class="panel panel-default" id="content">
<div class="panel-heading">
<span>{{Title}}</span>
{{#path}}
<button class="btn btn-default storage-privileged pull-right" translatable="yes"
data-action="format_disk" data-arg="{{path}}">Create partition table</button>
{{/path}}
</div>
<ul class="list-group">
{{#Entries}}
<li class="list-group-item">
<table style="width:100%">
<tr>
<td width="50%" style="padding-left:{{LevelWidth}}px">
{{{Description}}}
</td>
<td style="text-align:left">{{Name}}</td>
<td style="text-align:right">
<div style="display:inline-block;margin-right:5px;vertical-align:middle">
<div class="spinner spinner-sm" data-job-object="{{job_object}}"
style="visibility:hidden"></div>
</div>
{{{Button}}}
</td>
</tr>
</table>
{{/Entries}}
</ul>
</div>
</script>
<script id="block-detail-tmpl" type="x-template/mustache">
<div class="panel panel-default">
<div class="panel-heading">
{{#Drive}}
<span translatable="yes">Drive</span>
{{/Drive}}
{{^Drive}}
<span translatable="yes">Block Device</span>
{{/Drive}}
</div>
<div class="panel-body">
<table class="cockpit-info-table">
{{#Drive}}
<tr>
<td translatable="yes" context="storage">Model</td>
<td>{{dbus.Model}}</td>
</tr>
{{#dbus.Revision}}
<tr>
<td translatable="yes" context="storage">Firmware Version</td>
<td>{{.}}</td>
</tr>
{{/dbus.Revision}}
{{#dbus.Serial}}
<tr>
<td translatable="yes" context="storage">Serial Number</td>
<td>{{.}}</td>
</tr>
{{/dbus.Serial}}
{{#dbus.WWN}}
<tr>
<td translatable="yes" context="storage">World Wide Name</td>
<td>{{.}}</td>
</tr>
{{/dbus.WWN}}
<tr>
<td translatable="yes" context="storage">Capacity</td>
<td>
{{#Size}}{{.}}{{/Size}}
{{^Size}}<span translatable="yes">No media inserted</span>{{/Size}}
</td>
</tr>
{{#Assessment}}
<tr>
<td translatable="yes" context="storage">Assessment</td>
<td>
{{#Failing}}
<span translatable="yes" class="cockpit-disk-failing">DISK IS FAILING</span>
{{/Failing}}
{{^Failing}}
<span translatable="yes">Disk is OK</span>
{{/Failing}}
{{#Temperature}}
<span> ({{.}})</span>
{{/Temperature}}
</td>
</tr>
{{/Assessment}}
{{^Multipath}}
<tr>
<td translatable="yes" context="storage">Device File</td>
<td>{{Device}}</td>
</tr>
{{/Multipath}}
{{#Multipath}}
<tr>
<td translatable="yes" context="storage">Device File</td>
<td>
<!-- There are three interesting cases here for a
multipath device:
a) Everything is setup as expected and there is a
master device which we can show.
b) The multipathd service isn't running and there
is no master device. In this case, there is a
big alert at the top of the page that tells the
user about multipathd not running, so we just
show a "-" as the device.
c) The multipathd service _is_ running but there
_still_ is no master device. Something is
wrong, but we have no idea what and can't offer
any good advise or help with fixing it. Thus,
we also show "-" in this case. In the future,
with a richer multipath API, we can hopefully
offer better explanations and useful knobs for
fixing things.
Although case b) and c) show the same thing, we
keep them separate in the markup so that it is easy
to change our minds.
-->
{{#Device}}{{.}}{{/Device}} <!-- a) -->
{{^Device}}
{{^MultipathActive}}-{{/MultipathActive}} <!-- b) -->
{{#MultipathActive}}-{{/MultipathActive}} <!-- c) -->
{{/Device}}
</td>
</tr>
<tr>
<td translatable="yes" context="storage">Multipath Devices</td>
<td>{{#Devices}}{{.}} {{/Devices}}</td>
</tr>
{{/Multipath}}
{{/Drive}}
{{^Drive}}
<tr>
<td translatable="yes" context="storage">Device File</td>
<td>{{Block.Name}}</td>
</tr>
<tr>
<td translatable="yes" context="storage">Capacity</td>
<td>{{Block.Size}}</td>
</tr>
{{/Drive}}
</table>
</div>
</div>
{{{Content}}}
</script>
<script id="mdraid-detail-tmpl" type="x-template/mustache">
<div class="panel panel-default">
<div class="panel-heading">
<span translatable="yes">RAID Device</span>
<span style="float:right">{{{MDRaidButton}}}</span>
</div>
{{#MDRaid}}
<table class="cockpit-info-table">
<tr>
<td translatable="yes" context="storage">Device</td>
<td>{{Block.Device}}</td>
</tr>
<tr>
<td translatable="yes" context="storage">Name</td>
<td>{{Name}}</td>
</tr>
<tr>
<td translatable="yes" context="storage">UUID</td>
<td>{{dbus.UUID}}</td>
</tr>
<tr>
<td translatable="yes" context="storage">Capacity</td>
<td>{{Size}}</td>
</tr>
<tr>
<td translatable="yes" context="storage">RAID Level</td>
<td>{{Level}}</td>
</tr>
{{#Bitmap}}
<tr>
<td translatable="yes" context="storage">Bitmap</td>
<td>
<div class="btn-group btn-toggle"
data-action="mdraid_toggle_bitmap" data-arg="{{dbus.path}}">
<button translatable="yes" class="btn {{#Value}}btn-primary active{{/Value}} btn-default">On</button>
<button translatable="yes" class="btn {{^Value}}btn-primary active{{/Value}} btn-default">Off</button>
</div>
</td>
</tr>
{{/Bitmap}}
<tr>
<td translatable="yes" context="storage">State</td>
<td>
{{#Degraded}}
<div>
<span style="color:red" translatable="yes">ARRAY IS DEGRADED</span> -- {{.}}
</div>
{{/Degraded}}
{{#SyncAction}}
<div>
{{Progress}}
</div>
{{/SyncAction}}
<div>
{{State}}
</div>
</td>
</tr>
</table>
{{/MDRaid}}
</div>
<div class="panel panel-default" id="disks">
<div class="panel-heading">
<span translatable="yes">Disks</span>
{{#DynamicMembers}}
<button style="float:right" class="btn btn-default storage-privileged"
data-action="mdraid_add_disk" data-arg="{{MDRaid.dbus.path}}">
Add
</button>
{{/DynamicMembers}}
</div>
<ul class="list-group">
{{#Members}}
<li class="list-group-item">
<table style="width:100%">
<tr>
<td style="width:20px;text-align:center">{{#Slot}}{{.}}{{/Slot}}{{^Slot}}-{{/Slot}}</td>
<td>{{#LinkTarget}}{{{html}}}{{/LinkTarget}}</td>
<td style="width:100px;text-align:right">
{{#States}}
<div {{#Danger}}style="color:red"{{/Danger}}>{{Description}}</div>
{{/States}}
</td>
{{#DynamicMembers}}
<td style="text-align:right;width:10em">
<button translatable="yes" class="btn btn-default storage-privileged"
data-action="mdraid_remove_disk" data-arg="{{path}}">
Remove
</button>
</td>
{{/DynamicMembers}}
</tr>
</table>
</li>
{{/Members}}
</ul>
</div>
{{{Content}}}
</script>
<script id="vgroup-detail-tmpl" type="x-template/mustache">
<div class="panel panel-default">
<div class="panel-heading">
<span translatable="yes">Volume Group</span>
<span style="float:right">{{{VGroupButton}}}</span>
</div>
{{#VGroup}}
<table class="cockpit-info-table">
<tr>
<td translatable="yes" context="storage">Name</td>
<td>{{dbus.Name}}</td>
</tr>
<tr>
<td translatable="yes" context="storage">UUID</td>
<td>{{dbus.UUID}}</td>
</tr>
<tr>
<td translatable="yes" context="storage">Capacity</td>
<td>{{Size}}</td>
</tr>
</table>
{{/VGroup}}
</div>
<div class="panel panel-default" id="pvols">
<div class="panel-heading">
<span translatable="yes">Physical Volumes</span>
<button style="float:right" class="btn btn-default storage-privileged"
data-action="vgroup_add_disk" data-arg="{{VGroup.dbus.path}}"
translatable="yes">
Add
</button>
</div>
<ul class="list-group">
{{#PVols}}
<li class="list-group-item">
<table style="width:100%">
<tr>
<td>
<div>{{#LinkTarget}}{{{html}}}{{/LinkTarget}}</div>
<div>{{Sizes}}</div>
</td>
<td style="text-align:right">{{{Button}}}</td>
</tr>
</table>
</li>
{{/PVols}}
</ul>
</div>
{{{Content}}}
</script>
<div id="storage-detail" class="container-fluid" hidden>
<ol class="breadcrumb">
<li><a translatable="yes">Storage</a></li>
<li class="active"></li>
</ol>
<div id="detail"></div>
<div id="detail-jobs"></div>
<div class="panel panel-default cockpit-log-panel">
<div class="panel-heading" translatable="yes">Storage Log</div>
<div class="panel-body" id="storage-detail-log"></div>
</div>
</div>
<!-- DIALOGS -->
<div class="modal" id="error-popup"
tabindex="-1" role="dialog"
data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="error-popup-title"></h4>
</div>
<div class="modal-body">
<p id="error-popup-message"></p>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
<script id="storage-dialog-tmpl" type="x-template/mustache">
<div id="dialog" class="modal" tabindex="-1" role="dialog" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">{{Title}}</h4>
</div>
<div class="modal-body">
{{#Alerts}}
<div class="alert alert-danger">
<span class="pficon-layered">
<span class="pficon pficon-error-octagon"></span>
<span class="pficon pficon-error-exclamation"></span>
</span>
<span class="alert-message">{{Message}}</span>
</div>
{{/Alerts}}
<table class="cockpit-form-table">
{{#Fields}}
<tr>
{{#TextInput}}
<td class="top">{{Title}}</td>
<td>
<input class="form-control" type="text" {{#Value}}value="{{.}}"{{/Value}} data-field={{.}}>
</td>
{{/TextInput}}
{{#PassInput}}
<td class="top">{{Title}}</td>
<td>
<input class="form-control" type="password" {{#Value}}value="{{.}}"{{/Value}} data-field={{.}}>
</td>
{{/PassInput}}
{{#SizeInput}}
<td class="top">{{Title}} (MB)</td>
<td>
<input class="form-control" type="text" {{#ValueMB}}value="{{.}}"{{/ValueMB}} data-field={{.}}>
</td>
{{/SizeInput}}
{{#CheckBox}}
<td></td>
<td>
<div class="checkbox">
<label>
<input type="checkbox" data-field={{.}} {{#Value}}checked{{/Value}}>{{Title}}
</label>
</div>
</td>
{{/CheckBox}}
{{#SelectOne}}
<td class="top">{{Title}}</td>
<td>
<select class="form-control selectpicker" data-field={{.}}>
{{#Options}}
<option value="{{value}}" {{#selected}}selected="true"{{/selected}}
{{#disabled}}disabled="disabled"{{/disabled}}>{{Title}}</option>
{{/Options}}
</select>
</td>
{{/SelectOne}}
{{#SelectMany}}
<td class="top">{{Title}}</td>
<td>
<ul class="list-group available-disks-group" data-field={{.}}>
{{#Options}}
<li class="list-group-item">
<div class="checkbox" style="margin:0px">
<label><input type="checkbox">{{Title}}</label>
</div>
</li>
{{/Options}}
</ul>
</td>
{{/SelectMany}}
</tr>
{{/Fields}}
</table>
</div>
<div class="modal-footer">
{{#Action}}
{{#Danger}}<div style="margin-bottom:10px">{{.}}</div>{{/Danger}}
<div class="spinner spinner-sm pull-left" hidden></div>
<button class="btn btn-default" translatable="yes" data-dismiss="modal">
Cancel
</button>
<button class="btn {{#Danger}}btn-danger{{/Danger}}{{^Danger}}btn-primary{{/Danger}}"
data-action="apply">{{Title}}</button>
{{/Action}}
</div>
</div>
</div>
</div>
</script>
</body>
</html>
| haiyangd/cockpit_view | pkg/storaged/index.html | HTML | lgpl-2.1 | 28,134 |
/*
* Ext JS Library 2.3.0
* Copyright(c) 2006-2009, Ext JS, LLC.
* licensing@extjs.com
*
* http://extjs.com/license
*/
/**
* Finnish Translations
* <tuomas.salo (at) iki.fi>
* 'ä' should read as lowercase 'a' with two dots on top (ä)
*/
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">Ladataan...</div>';
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.GridPanel){
Ext.grid.GridPanel.prototype.ddText = "{0} rivi(ä) valittu";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "Sulje tämä välilehti";
}
if(Ext.LoadMask){
Ext.LoadMask.prototype.msg = "Ladataan...";
}
Date.monthNames = [
"tammikuu",
"helmikuu",
"maaliskuu",
"huhtikuu",
"toukokuu",
"kesäkuu",
"heinäkuu",
"elokuu",
"syyskuu",
"lokakuu",
"marraskuu",
"joulukuu"
];
Date.getShortMonthName = function(month) {
//return Date.monthNames[month].substring(0, 3);
return (month+1) + ".";
};
Date.monthNumbers = {
Jan : 0,
Feb : 1,
Mar : 2,
Apr : 3,
May : 4,
Jun : 5,
Jul : 6,
Aug : 7,
Sep : 8,
Oct : 9,
Nov : 10,
Dec : 11
};
Date.getMonthNumber = function(name) {
if(name.match(/^(1?\d)\./)) {
return -1+RegExp.$1;
} else {
return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
}
};
Date.dayNames = [
"sunnuntai",
"maanantai",
"tiistai",
"keskiviikko",
"torstai",
"perjantai",
"lauantai"
];
Date.getShortDayName = function(day) {
return Date.dayNames[day].substring(0, 2);
};
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "OK",
cancel : "Peruuta",
yes : "Kyllä",
no : "Ei"
};
}
if(Ext.util.Format){
Ext.util.Format.date = function(v, format){
if(!v) return "";
if(!(v instanceof Date)) v = new Date(Date.parse(v));
return v.dateFormat(format || "j.n.Y");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "Tänään",
minText : "Tämä päivämäärä on aikaisempi kuin ensimmäinen sallittu",
maxText : "Tämä päivämäärä on myöhäisempi kuin viimeinen sallittu",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : 'Seuraava kuukausi (Control+oikealle)',
prevText : 'Edellinen kuukausi (Control+vasemmalle)',
monthYearText : 'Valitse kuukausi (vaihda vuotta painamalla Control+ylös/alas)',
todayTip : "{0} (välilyönti)",
format : "j.n.Y",
okText : " OK ",
cancelText : "Peruuta",
startDay : 1 // viikko alkaa maanantaista
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "Sivu",
afterPageText : "/ {0}",
firstText : "Ensimmäinen sivu",
prevText : "Edellinen sivu",
nextText : "Seuraava sivu",
lastText : "Viimeinen sivu",
refreshText : "Päivitä",
displayMsg : "Näytetään {0} - {1} / {2}",
emptyMsg : 'Ei tietoja'
});
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "Tämän kentän arvo ei kelpaa";
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "Tämän kentän minimipituus on {0}",
maxLengthText : "Tämän kentän maksimipituus on {0}",
blankText : "Tämä kenttä on pakollinen",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "Tämän kentän pienin sallittu arvo on {0}",
maxText : "Tämän kentän suurin sallittu arvo on {0}",
nanText : "{0} ei ole numero"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "Ei käytössä",
disabledDatesText : "Ei käytössä",
minText : "Tämän kentän päivämäärän tulee olla {0} jälkeen",
maxText : "Tämän kentän päivämäärän tulee olla ennen {0}",
invalidText : "Päivämäärä {0} ei ole oikeassa muodossa - kirjoita päivämäärä muodossa {1}",
format : "j.n.Y",
altFormats : "j.n.|d.m.|mdy|mdY|d|Y-m-d|Y/m/d"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "Ladataan...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : 'Syötä tähän kenttään sähköpostiosoite, esim. "etunimi.sukunimi@osoite.fi"',
urlText : 'Syötä tähän kenttään URL-osoite, esim. "http:/'+'/www.osoite.fi"',
alphaText : 'Syötä tähän kenttään vain kirjaimia (a-z, A-Z) ja alaviivoja (_)',
alphanumText : 'Syötä tähän kenttään vain kirjaimia (a-z, A-Z), numeroita (0-9) ja alaviivoja (_)'
});
}
if(Ext.form.HtmlEditor){
Ext.apply(Ext.form.HtmlEditor.prototype, {
createLinkText : 'Anna linkin URL-osoite:',
buttonTips : {
bold : {
title: 'Lihavoi (Ctrl+B)',
text: 'Lihavoi valittu teksti.',
cls: 'x-html-editor-tip'
},
italic : {
title: 'Kursivoi (Ctrl+I)',
text: 'Kursivoi valittu teksti.',
cls: 'x-html-editor-tip'
},
underline : {
title: 'Alleviivaa (Ctrl+U)',
text: 'Alleviivaa valittu teksti.',
cls: 'x-html-editor-tip'
},
increasefontsize : {
title: 'Suurenna tekstiä',
text: 'Kasvata tekstin kirjasinkokoa.',
cls: 'x-html-editor-tip'
},
decreasefontsize : {
title: 'Pienennä tekstiä',
text: 'Pienennä tekstin kirjasinkokoa.',
cls: 'x-html-editor-tip'
},
backcolor : {
title: 'Tekstin korostusväri',
text: 'Vaihda valitun tekstin taustaväriä.',
cls: 'x-html-editor-tip'
},
forecolor : {
title: 'Tekstin väri',
text: 'Vaihda valitun tekstin väriä.',
cls: 'x-html-editor-tip'
},
justifyleft : {
title: 'Tasaa vasemmalle',
text: 'Tasaa teksti vasempaan reunaan.',
cls: 'x-html-editor-tip'
},
justifycenter : {
title: 'Keskitä',
text: 'Keskitä teksti.',
cls: 'x-html-editor-tip'
},
justifyright : {
title: 'Tasaa oikealle',
text: 'Tasaa teksti oikeaan reunaan.',
cls: 'x-html-editor-tip'
},
insertunorderedlist : {
title: 'Luettelo',
text: 'Luo luettelo.',
cls: 'x-html-editor-tip'
},
insertorderedlist : {
title: 'Numeroitu luettelo',
text: 'Luo numeroitu luettelo.',
cls: 'x-html-editor-tip'
},
createlink : {
title: 'Linkki',
text: 'Tee valitusta tekstistä hyperlinkki.',
cls: 'x-html-editor-tip'
},
sourceedit : {
title: 'Lähdekoodin muokkaus',
text: 'Vaihda lähdekoodin muokkausnäkymään.',
cls: 'x-html-editor-tip'
}
}
});
}
if(Ext.form.BasicForm){
Ext.form.BasicForm.prototype.waitTitle = "Odota...";
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "Järjestä A-Ö",
sortDescText : "Järjestä Ö-A",
lockText : "Lukitse sarake",
unlockText : "Vapauta sarakkeen lukitus",
columnsText : "Sarakkeet"
});
}
if(Ext.grid.GroupingView){
Ext.apply(Ext.grid.GroupingView.prototype, {
emptyGroupText : '(ei mitään)',
groupByText : 'Ryhmittele tämän kentän mukaan',
showGroupsText : 'Näytä ryhmissä'
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "Nimi",
valueText : "Arvo",
dateFormat : "j.m.Y"
});
}
if(Ext.layout.BorderLayout && Ext.layout.BorderLayout.SplitRegion){
Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
splitTip : "Muuta kokoa vetämällä.",
collapsibleSplitTip : "Muuta kokoa vetämällä. Piilota kaksoisklikkauksella."
});
}
| xwiki-contrib/sankoreorg | web/src/main/webapp/skins/curriki20/extjs/source/locale/ext-lang-fi.js | JavaScript | lgpl-2.1 | 8,135 |
// $Id$
// Author: Sergey Linev 4.03.2014
/*************************************************************************
* Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TBufferJSON
#define ROOT_TBufferJSON
#ifndef ROOT_TBuffer
#include "TBuffer.h"
#endif
#ifndef ROOT_TString
#include "TString.h"
#endif
#ifndef ROOT_TObjArray
#include "TObjArray.h"
#endif
#include <map>
class TVirtualStreamerInfo;
class TStreamerInfo;
class TStreamerElement;
class TObjArray;
class TMemberStreamer;
class TDataMember;
class TJSONStackObj;
class TBufferJSON : public TBuffer {
public:
TBufferJSON();
virtual ~TBufferJSON();
void SetCompact(int level);
static TString ConvertToJSON(const TObject *obj, Int_t compact = 0);
static TString ConvertToJSON(const void *obj, const TClass *cl, Int_t compact = 0);
static TString ConvertToJSON(const void *obj, TDataMember *member, Int_t compact = 0);
// suppress class writing/reading
virtual TClass *ReadClass(const TClass *cl = 0, UInt_t *objTag = 0);
virtual void WriteClass(const TClass *cl);
// redefined virtual functions of TBuffer
virtual Int_t CheckByteCount(UInt_t startpos, UInt_t bcnt, const TClass *clss); // SL
virtual Int_t CheckByteCount(UInt_t startpos, UInt_t bcnt, const char *classname); // SL
virtual void SetByteCount(UInt_t cntpos, Bool_t packInVersion = kFALSE); // SL
virtual void SkipVersion(const TClass *cl = 0);
virtual Version_t ReadVersion(UInt_t *start = 0, UInt_t *bcnt = 0, const TClass *cl = 0); // SL
virtual Version_t ReadVersionNoCheckSum(UInt_t *, UInt_t *)
{
return 0;
}
virtual UInt_t WriteVersion(const TClass *cl, Bool_t useBcnt = kFALSE); // SL
virtual void *ReadObjectAny(const TClass *clCast);
virtual void SkipObjectAny();
// these methods used in streamer info to indicate currently streamed element,
virtual void IncrementLevel(TVirtualStreamerInfo *);
virtual void SetStreamerElementNumber(TStreamerElement *elem, Int_t comp_type);
virtual void DecrementLevel(TVirtualStreamerInfo *);
virtual void ClassBegin(const TClass *, Version_t = -1);
virtual void ClassEnd(const TClass *);
virtual void ClassMember(const char *name, const char *typeName = 0, Int_t arrsize1 = -1, Int_t arrsize2 = -1);
virtual void WriteObject(const TObject *obj);
virtual void ReadFloat16(Float_t *f, TStreamerElement *ele = 0);
virtual void WriteFloat16(Float_t *f, TStreamerElement *ele = 0);
virtual void ReadDouble32(Double_t *d, TStreamerElement *ele = 0);
virtual void WriteDouble32(Double_t *d, TStreamerElement *ele = 0);
virtual void ReadWithFactor(Float_t *ptr, Double_t factor, Double_t minvalue);
virtual void ReadWithNbits(Float_t *ptr, Int_t nbits);
virtual void ReadWithFactor(Double_t *ptr, Double_t factor, Double_t minvalue);
virtual void ReadWithNbits(Double_t *ptr, Int_t nbits);
virtual Int_t ReadArray(Bool_t *&b);
virtual Int_t ReadArray(Char_t *&c);
virtual Int_t ReadArray(UChar_t *&c);
virtual Int_t ReadArray(Short_t *&h);
virtual Int_t ReadArray(UShort_t *&h);
virtual Int_t ReadArray(Int_t *&i);
virtual Int_t ReadArray(UInt_t *&i);
virtual Int_t ReadArray(Long_t *&l);
virtual Int_t ReadArray(ULong_t *&l);
virtual Int_t ReadArray(Long64_t *&l);
virtual Int_t ReadArray(ULong64_t *&l);
virtual Int_t ReadArray(Float_t *&f);
virtual Int_t ReadArray(Double_t *&d);
virtual Int_t ReadArrayFloat16(Float_t *&f, TStreamerElement *ele = 0);
virtual Int_t ReadArrayDouble32(Double_t *&d, TStreamerElement *ele = 0);
virtual Int_t ReadStaticArray(Bool_t *b);
virtual Int_t ReadStaticArray(Char_t *c);
virtual Int_t ReadStaticArray(UChar_t *c);
virtual Int_t ReadStaticArray(Short_t *h);
virtual Int_t ReadStaticArray(UShort_t *h);
virtual Int_t ReadStaticArray(Int_t *i);
virtual Int_t ReadStaticArray(UInt_t *i);
virtual Int_t ReadStaticArray(Long_t *l);
virtual Int_t ReadStaticArray(ULong_t *l);
virtual Int_t ReadStaticArray(Long64_t *l);
virtual Int_t ReadStaticArray(ULong64_t *l);
virtual Int_t ReadStaticArray(Float_t *f);
virtual Int_t ReadStaticArray(Double_t *d);
virtual Int_t ReadStaticArrayFloat16(Float_t *f, TStreamerElement *ele = 0);
virtual Int_t ReadStaticArrayDouble32(Double_t *d, TStreamerElement *ele = 0);
virtual void ReadFastArray(Bool_t *b, Int_t n);
virtual void ReadFastArray(Char_t *c, Int_t n);
virtual void ReadFastArrayString(Char_t *c, Int_t n);
virtual void ReadFastArray(UChar_t *c, Int_t n);
virtual void ReadFastArray(Short_t *h, Int_t n);
virtual void ReadFastArray(UShort_t *h, Int_t n);
virtual void ReadFastArray(Int_t *i, Int_t n);
virtual void ReadFastArray(UInt_t *i, Int_t n);
virtual void ReadFastArray(Long_t *l, Int_t n);
virtual void ReadFastArray(ULong_t *l, Int_t n);
virtual void ReadFastArray(Long64_t *l, Int_t n);
virtual void ReadFastArray(ULong64_t *l, Int_t n);
virtual void ReadFastArray(Float_t *f, Int_t n);
virtual void ReadFastArray(Double_t *d, Int_t n);
virtual void ReadFastArrayFloat16(Float_t *f, Int_t n, TStreamerElement *ele = 0);
virtual void ReadFastArrayDouble32(Double_t *d, Int_t n, TStreamerElement *ele = 0);
virtual void ReadFastArrayWithFactor(Float_t *ptr, Int_t n, Double_t factor, Double_t minvalue) ;
virtual void ReadFastArrayWithNbits(Float_t *ptr, Int_t n, Int_t nbits);
virtual void ReadFastArrayWithFactor(Double_t *ptr, Int_t n, Double_t factor, Double_t minvalue);
virtual void ReadFastArrayWithNbits(Double_t *ptr, Int_t n, Int_t nbits) ;
virtual void WriteArray(const Bool_t *b, Int_t n);
virtual void WriteArray(const Char_t *c, Int_t n);
virtual void WriteArray(const UChar_t *c, Int_t n);
virtual void WriteArray(const Short_t *h, Int_t n);
virtual void WriteArray(const UShort_t *h, Int_t n);
virtual void WriteArray(const Int_t *i, Int_t n);
virtual void WriteArray(const UInt_t *i, Int_t n);
virtual void WriteArray(const Long_t *l, Int_t n);
virtual void WriteArray(const ULong_t *l, Int_t n);
virtual void WriteArray(const Long64_t *l, Int_t n);
virtual void WriteArray(const ULong64_t *l, Int_t n);
virtual void WriteArray(const Float_t *f, Int_t n);
virtual void WriteArray(const Double_t *d, Int_t n);
virtual void WriteArrayFloat16(const Float_t *f, Int_t n, TStreamerElement *ele = 0);
virtual void WriteArrayDouble32(const Double_t *d, Int_t n, TStreamerElement *ele = 0);
virtual void ReadFastArray(void *start , const TClass *cl, Int_t n = 1, TMemberStreamer *s = 0, const TClass *onFileClass = 0);
virtual void ReadFastArray(void **startp, const TClass *cl, Int_t n = 1, Bool_t isPreAlloc = kFALSE, TMemberStreamer *s = 0, const TClass *onFileClass = 0);
virtual void WriteFastArray(const Bool_t *b, Int_t n);
virtual void WriteFastArray(const Char_t *c, Int_t n);
virtual void WriteFastArrayString(const Char_t *c, Int_t n);
virtual void WriteFastArray(const UChar_t *c, Int_t n);
virtual void WriteFastArray(const Short_t *h, Int_t n);
virtual void WriteFastArray(const UShort_t *h, Int_t n);
virtual void WriteFastArray(const Int_t *i, Int_t n);
virtual void WriteFastArray(const UInt_t *i, Int_t n);
virtual void WriteFastArray(const Long_t *l, Int_t n);
virtual void WriteFastArray(const ULong_t *l, Int_t n);
virtual void WriteFastArray(const Long64_t *l, Int_t n);
virtual void WriteFastArray(const ULong64_t *l, Int_t n);
virtual void WriteFastArray(const Float_t *f, Int_t n);
virtual void WriteFastArray(const Double_t *d, Int_t n);
virtual void WriteFastArrayFloat16(const Float_t *d, Int_t n, TStreamerElement *ele = 0);
virtual void WriteFastArrayDouble32(const Double_t *d, Int_t n, TStreamerElement *ele = 0);
virtual void WriteFastArray(void *start, const TClass *cl, Int_t n = 1, TMemberStreamer *s = 0);
virtual Int_t WriteFastArray(void **startp, const TClass *cl, Int_t n = 1, Bool_t isPreAlloc = kFALSE, TMemberStreamer *s = 0);
virtual void StreamObject(void *obj, const type_info &typeinfo, const TClass *onFileClass = 0);
virtual void StreamObject(void *obj, const char *className, const TClass *onFileClass = 0);
virtual void StreamObject(void *obj, const TClass *cl, const TClass *onFileClass = 0);
virtual void StreamObject(TObject *obj);
virtual void ReadBool(Bool_t &b);
virtual void ReadChar(Char_t &c);
virtual void ReadUChar(UChar_t &c);
virtual void ReadShort(Short_t &s);
virtual void ReadUShort(UShort_t &s);
virtual void ReadInt(Int_t &i);
virtual void ReadUInt(UInt_t &i);
virtual void ReadLong(Long_t &l);
virtual void ReadULong(ULong_t &l);
virtual void ReadLong64(Long64_t &l);
virtual void ReadULong64(ULong64_t &l);
virtual void ReadFloat(Float_t &f);
virtual void ReadDouble(Double_t &d);
virtual void ReadCharP(Char_t *c);
virtual void ReadTString(TString &s);
virtual void ReadStdString(std::string &s);
virtual void WriteBool(Bool_t b);
virtual void WriteChar(Char_t c);
virtual void WriteUChar(UChar_t c);
virtual void WriteShort(Short_t s);
virtual void WriteUShort(UShort_t s);
virtual void WriteInt(Int_t i);
virtual void WriteUInt(UInt_t i);
virtual void WriteLong(Long_t l);
virtual void WriteULong(ULong_t l);
virtual void WriteLong64(Long64_t l);
virtual void WriteULong64(ULong64_t l);
virtual void WriteFloat(Float_t f);
virtual void WriteDouble(Double_t d);
virtual void WriteCharP(const Char_t *c);
virtual void WriteTString(const TString &s);
virtual void WriteStdString(const std::string &s);
virtual Int_t WriteClones(TClonesArray *a, Int_t nobjects);
virtual Int_t WriteObjectAny(const void *obj, const TClass *ptrClass);
virtual Int_t WriteClassBuffer(const TClass *cl, void *pointer);
virtual Int_t ApplySequence(const TStreamerInfoActions::TActionSequence &sequence, void *object);
virtual Int_t ApplySequenceVecPtr(const TStreamerInfoActions::TActionSequence &sequence, void *start_collection, void *end_collection);
virtual Int_t ApplySequence(const TStreamerInfoActions::TActionSequence &sequence, void *start_collection, void *end_collection);
virtual void TagStreamerInfo(TVirtualStreamerInfo * /*info*/) {}
virtual Bool_t CheckObject(const TObject * /*obj*/);
virtual Bool_t CheckObject(const void * /*ptr*/, const TClass * /*cl*/);
// abstract virtual methods from TBuffer, which should be redefined
virtual Int_t ReadBuf(void * /*buf*/, Int_t /*max*/)
{
Error("ReadBuf", "useless");
return 0;
}
virtual void WriteBuf(const void * /*buf*/, Int_t /*max*/)
{
Error("WriteBuf", "useless");
}
virtual char *ReadString(char * /*s*/, Int_t /*max*/)
{
Error("ReadString", "useless");
return 0;
}
virtual void WriteString(const char * /*s*/)
{
Error("WriteString", "useless");
}
virtual Int_t GetVersionOwner() const
{
Error("GetVersionOwner", "useless");
return 0;
}
virtual Int_t GetMapCount() const
{
Error("GetMapCount", "useless");
return 0;
}
virtual void GetMappedObject(UInt_t /*tag*/, void *&/*ptr*/, TClass *&/*ClassPtr*/) const
{
Error("GetMappedObject", "useless");
}
virtual void MapObject(const TObject * /*obj*/, UInt_t /*offset*/ = 1)
{
Error("MapObject", "useless");
}
virtual void MapObject(const void * /*obj*/, const TClass * /*cl*/, UInt_t /*offset*/ = 1)
{
Error("MapObject", "useless");
}
virtual void Reset()
{
Error("Reset", "useless");
}
virtual void InitMap()
{
Error("InitMap", "useless");
}
virtual void ResetMap()
{
Error("ResetMap", "useless");
}
virtual void SetReadParam(Int_t /*mapsize*/)
{
Error("SetReadParam", "useless");
}
virtual void SetWriteParam(Int_t /*mapsize*/)
{
Error("SetWriteParam", "useless");
}
virtual Version_t ReadVersionForMemberWise(const TClass * /*cl*/ = 0)
{
Error("ReadVersionForMemberWise", "useless");
return 0;
}
virtual UInt_t WriteVersionMemberWise(const TClass * /*cl*/, Bool_t /*useBcnt*/ = kFALSE)
{
Error("WriteVersionMemberWise", "useless");
return 0;
}
virtual TVirtualStreamerInfo *GetInfo()
{
Error("GetInfo", "useless");
return 0;
}
virtual TObject *ReadObject(const TClass * /*cl*/)
{
Error("ReadObject", "useless");
return 0;
}
virtual UShort_t GetPidOffset() const
{
Error("GetPidOffset", "useless");
return 0;
}
virtual void SetPidOffset(UShort_t /*offset*/)
{
Error("SetPidOffset", "useless");
}
virtual Int_t GetBufferDisplacement() const
{
Error("GetBufferDisplacement", "useless");
return 0;
}
virtual void SetBufferDisplacement()
{
Error("SetBufferDisplacement", "useless");
}
virtual void SetBufferDisplacement(Int_t /*skipped*/)
{
Error("SetBufferDisplacement", "useless");
}
virtual TProcessID *GetLastProcessID(TRefTable * /*reftable*/) const
{
Error("GetLastProcessID", "useless");
return 0;
}
virtual UInt_t GetTRefExecId()
{
Error("GetTRefExecId", "useless");
return 0;
}
virtual TProcessID *ReadProcessID(UShort_t /*pidf*/)
{
Error("ReadProcessID", "useless");
return 0;
}
virtual UShort_t WriteProcessID(TProcessID * /*pid*/)
{
Error("WriteProcessID", "useless");
return 0;
}
// Utilities for TStreamerInfo
virtual void ForceWriteInfo(TVirtualStreamerInfo * /*info*/, Bool_t /*force*/)
{
Error("ForceWriteInfo", "useless");
}
virtual void ForceWriteInfoClones(TClonesArray * /*a*/)
{
Error("ForceWriteInfoClones", "useless");
}
virtual Int_t ReadClones(TClonesArray * /*a*/, Int_t /*nobjects*/, Version_t /*objvers*/)
{
Error("ReadClones", "useless");
return 0;
}
// Utilities for TClass
virtual Int_t ReadClassEmulated(const TClass * /*cl*/, void * /*object*/, const TClass * /*onfile_class*/ = 0)
{
Error("ReadClassEmulated", "useless");
return 0;
}
virtual Int_t ReadClassBuffer(const TClass * /*cl*/, void * /*pointer*/, const TClass * /*onfile_class*/ = 0)
{
Error("ReadClassBuffer", "useless");
return 0;
}
virtual Int_t ReadClassBuffer(const TClass * /*cl*/, void * /*pointer*/, Int_t /*version*/, UInt_t /*start*/, UInt_t /*count*/, const TClass * /*onfile_class*/ = 0)
{
Error("ReadClassBuffer", "useless");
return 0;
}
// end of redefined virtual functions
static void SetFloatFormat(const char *fmt = "%e");
static const char *GetFloatFormat();
protected:
// redefined protected virtual functions
virtual void WriteObjectClass(const void *actualObjStart, const TClass *actualClass);
// end redefined protected virtual functions
TString JsonWriteMember(const void *ptr, TDataMember *member, TClass *memberClass);
TJSONStackObj *PushStack(Int_t inclevel = 0);
TJSONStackObj *PopStack();
TJSONStackObj *Stack(Int_t depth = 0);
void WorkWithClass(TStreamerInfo *info, const TClass *cl = 0);
void WorkWithElement(TStreamerElement *elem, Int_t comp_type);
void JsonDisablePostprocessing();
Int_t JsonSpecialClass(const TClass *cl) const;
void JsonStartElement(const TStreamerElement *elem, const TClass *base_class = 0);
void PerformPostProcessing(TJSONStackObj *stack, const TStreamerElement *elem = 0);
void JsonWriteBasic(Char_t value);
void JsonWriteBasic(Short_t value);
void JsonWriteBasic(Int_t value);
void JsonWriteBasic(Long_t value);
void JsonWriteBasic(Long64_t value);
void JsonWriteBasic(Float_t value);
void JsonWriteBasic(Double_t value);
void JsonWriteBasic(Bool_t value);
void JsonWriteBasic(UChar_t value);
void JsonWriteBasic(UShort_t value);
void JsonWriteBasic(UInt_t value);
void JsonWriteBasic(ULong_t value);
void JsonWriteBasic(ULong64_t value);
void JsonWriteConstChar(const char* value, Int_t len = -1);
void JsonWriteObject(const void *obj, const TClass *objClass, Bool_t check_map = kTRUE);
void JsonStreamCollection(TCollection *obj, const TClass *objClass);
void AppendOutput(const char *line0, const char *line1 = 0);
TString fOutBuffer; //! main output buffer for json code
TString *fOutput; //! current output buffer for json code
TString fValue; //! buffer for current value
std::map<const void *, unsigned> fJsonrMap; //! map of recorded objects, used in JsonR to restore references
unsigned fJsonrCnt; //! counter for all objects and arrays
TObjArray fStack; //! stack of streamer infos
Bool_t fExpectedChain; //! flag to resolve situation when several elements of same basic type stored as FastArray
Int_t fCompact; //! 0 - no any compression, 1 - no spaces in the begin, 2 - no new lines, 3 - no spaces at all
TString fSemicolon; //! depending from compression level, " : " or ":"
TString fArraySepar; //! depending from compression level, ", " or ","
static const char *fgFloatFmt; //! printf argument for floats and doubles, either "%f" or "%e" or "%10f" and so on
ClassDef(TBufferJSON, 1) //a specialized TBuffer to only write objects into JSON format
};
#endif
| omazapa/root-old | net/http/inc/TBufferJSON.h | C | lgpl-2.1 | 19,417 |
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "uiloader.h"
#include <QtCore/QDir>
#include <QtCore/QProcess>
#include <QtCore/QSettings>
#include <QtCore/QCoreApplication>
#include <QtTest/QSignalSpy>
#include <QTest>
#include <QString>
#include <QHash>
#include <QFile>
#include <QFtp>
#include <QObject>
#include <QHostInfo>
#include <QWidget>
#include <QImage>
#include <QLibraryInfo>
/*
* Our own QVERIFY since the one from QTest can't be used in non-void functions.
* Just pass the desired return value as third argument.
*/
#define QVERIFY3(statement, description, returnValue) \
do {\
if (statement) {\
if (!QTest::qVerify(true, #statement, (description), __FILE__, __LINE__))\
return returnValue;\
} else {\
if (!QTest::qVerify(false, #statement, (description), __FILE__, __LINE__))\
return returnValue;\
}\
} while (0)
uiLoader::uiLoader(const QString &_pathToProgram)
: pathToProgram(_pathToProgram)
{
// initTests();
}
/*
* Load the configuration file for your machine.
* Return true if everything was loaded, else false.
*
* If the hostname is 'kayak', the config file should be 'kayak.ini':
*
* [General]
* ftpBaseDir=/arthurtest
* ftpHost=wartburg
* ftpPass=anonymouspass
* ftpUser=anonymous
* output=testresults
*
* [engines]
* 1\engine=uic
* size=1
*/
bool uiLoader::loadConfig(const QString &filePath, QString *errorMessage)
{
qDebug() << " ========== Loading config file " << filePath;
configPath = filePath;
// If there is no config file, dont proceed;
QSettings settings( filePath, QSettings::IniFormat, this );
// all keys available?
QStringList keyList;
keyList << QLatin1String("output") << QLatin1String("ftpUser") << QLatin1String("ftpPass") << QLatin1String("ftpHost") << QLatin1String("ftpBaseDir");
for (int i = 0; i < keyList.size(); ++i) {
const QString currentKey = keyList.at(i);
if (!settings.contains(currentKey)) {
*errorMessage = QString::fromLatin1("Config file '%1' does not contain the required key '%2'.").arg(filePath, currentKey);
return false;
}
qDebug() << "\t\t(I)" << currentKey << "\t" << settings.value(currentKey).toString();
}
const int size = settings.beginReadArray(QLatin1String("engines"));
if (!size) {
*errorMessage = QString::fromLatin1("Config file '%1' does not contain the necessary section engines.").arg(filePath);
return false;
}
// get the values
for ( int i = 0; i < size; ++i ) {
settings.setArrayIndex(i);
qDebug() << "\t\t(I)" << "engine" << "\t" << settings.value( "engine" ).toString();
enginesToTest.insert(settings.value(QLatin1String("engine")).toString(), QLatin1String("Info here please :p"));
}
settings.endArray();
output = settings.value(QLatin1String("output")).toString();
output += QDir::separator() + QLibraryInfo::buildKey() + QDir::separator() + QString( qVersion() );
ftpUser = settings.value( QLatin1String("ftpUser") ).toString();
ftpPass = settings.value( QLatin1String("ftpPass") ).toString();
ftpHost = settings.value( QLatin1String("ftpHost") ).toString();
ftpBaseDir = settings.value( QLatin1String("ftpBaseDir") ).toString() + QDir::separator() + QHostInfo::localHostName().split( QLatin1Char('.')).first();
threshold = settings.value( QLatin1String("threshold") ).toString();
qDebug() << "\t(I) Values adapted:";
qDebug() << "\t\t(I)" << "ftpBaseDir" << "\t" << ftpBaseDir;
qDebug() << "\t\t(I)" << "output" << "\t" << output;
return true;
}
/*
* Upload testresults to the server in order to create the new baseline.
*/
void uiLoader::createBaseline()
{
// can't use ftpUploadFile() here
qDebug() << " ========== Uploading baseline of only the latest test values ";
QFtp ftp;
ftp.connectToHost( ftpHost );
ftp.login( ftpUser, ftpPass );
ftp.cd( ftpBaseDir );
QDir dir( output );
// Upload all the latest test results to the FTP server's baseline directory.
QHashIterator<QString, QString> i(enginesToTest);
while ( i.hasNext() ) {
i.next();
dir.cd( i.key() );
ftp.cd( i.key() + ".baseline" );
dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
dir.setNameFilters( QStringList() << "*.png" );
QFileInfoList list = dir.entryInfoList();
dir.cd( ".." );
for (int n = 0; n < list.size(); n++) {
QFileInfo fileInfo = list.at( n );
QFile file( QString( output ) + "/" + i.key() + "/" + fileInfo.fileName() );
errorMsg = "could not open file " + fileInfo.fileName();
QVERIFY2( file.open(QIODevice::ReadOnly), qPrintable(errorMsg));
QByteArray fileData = file.readAll();
file.close();
ftp.put( fileData, fileInfo.fileName(), QFtp::Binary );
qDebug() << "\t(I) Uploading:" << fileInfo.fileName() << "with file size" << fileData.size();
}
ftp.cd( ".." );
}
ftp.close();
while ( ftp.hasPendingCommands() )
QCoreApplication::instance()->processEvents();
}
/*
* Download baseline from server in order to compare results.
*/
void uiLoader::downloadBaseline()
{
qDebug() << " ========== Downloading baseline...";
QHashIterator<QString, QString> i(enginesToTest);
while ( i.hasNext() ) {
i.next();
QString engineName = i.key();
QString dirWithFiles = ftpBaseDir + '/' + engineName + ".baseline";
QString ftpDir = ftpBaseDir + '/' + engineName + ".baseline";
QString saveToDir = QDir::currentPath() + '/' + output + '/' + engineName + ".baseline";
ftpList(dirWithFiles);
QList<QString> filesToDownload(lsDirList);
ftpGetFiles(filesToDownload, ftpDir, saveToDir);
}
}
/*
* Enter the dir pathDir local and remove all files (not recursive!)
*/
void uiLoader::clearDirectory(const QString& pathDir)
{
qDebug() << "\t(I) Clearing directory local: " << pathDir;
QDir dir(pathDir);
dir.setFilter(QDir::Files);
QStringList list = dir.entryList();
for (int n = 0; n < list.size(); n++) {
QString filePath = pathDir + "/" + list.at(n);
QFile file(filePath);
errorMsg = "could not remove file " + filePath;
QVERIFY2( file.remove(), qPrintable(errorMsg));
}
}
/*
* Setup the local environment.
*/
void uiLoader::setupLocal()
{
qDebug( " ========== Setting up local environment" );
QDir dir;
errorMsg = "could not create path " + output;
QVERIFY2( dir.mkpath(output), qPrintable(errorMsg) );
QHashIterator<QString, QString> j(enginesToTest);
while ( j.hasNext() ) {
j.next();
QString engineName = j.key();
QString engineDir = output + '/' + engineName;
// create <engine> or clean it
QString tmpPath = output + '/' + engineName;
if ( dir.exists(tmpPath) ) {
clearDirectory(tmpPath);
} else {
dir.mkdir(tmpPath);
}
// create *.baseline or clean it
tmpPath = output + '/' + engineName + ".baseline";
if ( dir.exists(tmpPath) ) {
clearDirectory(tmpPath);
} else {
dir.mkdir(tmpPath);
}
// create *.diff or clean it
tmpPath = output + '/' + engineName + ".diff";
if ( dir.exists(tmpPath) ) {
clearDirectory(tmpPath);
} else {
dir.mkdir(tmpPath);
}
// create *.failed or clean it
tmpPath = output + '/' + engineName + ".failed";
if ( dir.exists(tmpPath) ) {
clearDirectory(tmpPath);
} else {
dir.mkdir(tmpPath);
}
}
qDebug() << "\t(I) Created on local machine:" << output;
}
/*
* Setup the remote environment.
*/
void uiLoader::setupFTP()
{
qDebug( " ========== Setting up FTP environment" );
// create dirs on ftp server
ftpMkDir( ftpBaseDir );
ftpBaseDir += "/" + QLibraryInfo::buildKey();
ftpMkDir( ftpBaseDir );
ftpBaseDir += "/" + QString( qVersion() );
ftpMkDir( ftpBaseDir );
QString dir = "";
ftpList(ftpBaseDir + '/' + dir);
QList<QString> dirListing(lsDirList);
// create *.failed, *.diff if necessary, else remove the files in it
// if *.baseline does not exist, memorize it
QHashIterator<QString, QString> j(enginesToTest);
while ( j.hasNext() ) {
j.next();
QString curDir = QString( j.key() ) + ".failed";
if ( dirListing.contains( curDir ) ) {
ftpClearDirectory(ftpBaseDir + "/" + curDir + "/");
} else {
ftpMkDir(ftpBaseDir + "/" + curDir + "/");
}
curDir = QString( j.key() ) + ".diff";
if ( dirListing.contains( curDir ) ) {
ftpClearDirectory(ftpBaseDir + "/" + curDir + "/");
} else {
ftpMkDir(ftpBaseDir + "/" + curDir + "/");
}
curDir = QString( j.key() ) + ".baseline";
lsNeedBaseline.clear();
if ( !dirListing.contains( curDir ) ) {
ftpMkDir(ftpBaseDir + "/" + curDir + "/");
lsNeedBaseline << j.key();
} else {
qDebug() << "\t(I)" << curDir << "exists on server.";
}
}
}
/*
* Download files listed in fileLisiting from dir pathRemoteDir on sever and save
* them in pathSaveDir.
*/
void uiLoader::ftpGetFiles(QList<QString>& fileListing, const QString& pathRemoteDir, const QString& pathSaveDir)
{
QFtp ftp;
ftp.connectToHost( ftpHost );
ftp.login( ftpUser, ftpPass );
if ( !fileListing.empty() ) {
for ( int i = 0; i < fileListing.size(); ++i ) {
QFile file( pathSaveDir + "/" + fileListing.at(i) );
errorMsg = "could not open file for writing: " + file.fileName();
QVERIFY2( file.open(QIODevice::WriteOnly), qPrintable(errorMsg) );
QString ftpFileName = pathRemoteDir + '/' + fileListing.at(i);
ftp.get( ftpFileName, &file );
//qDebug() << "\t(I) Got" << file.fileName();
ftp.list(); //Only there to fill up a slot in the pendingCommands queue.
while ( ftp.hasPendingCommands() )
QCoreApplication::instance()->processEvents();
file.close();
}
}
ftp.close();
while ( ftp.hasPendingCommands() )
QCoreApplication::instance()->processEvents();
fileListing.clear();
}
/*
* Upload the file filePath to the server and save it there at filePathRemote.
*
* HINT: It seems you can't use this function in a loop, to many connections
* are established?!
*/
bool uiLoader::ftpUploadFile(const QString& filePathRemote, const QString& filePath)
{
QFile file(filePath);
errorMsg = "could not open file: " + filePath;
QVERIFY3( file.open(QIODevice::ReadOnly), qPrintable(errorMsg), false );
QByteArray contents = file.readAll();
file.close();
qDebug() << "\t(I) Uploading file to" << filePathRemote;
QFtp ftp;
ftp.connectToHost( ftpHost );
ftp.login( ftpUser, ftpPass );
ftp.put( contents, filePathRemote, QFtp::Binary );
ftp.close();
while ( ftp.hasPendingCommands() )
QCoreApplication::instance()->processEvents();
return true;
}
/*
* Enter the dir dir on the server and remove all files (not recursive!)
*/
void uiLoader::ftpClearDirectory(const QString& pathDir)
{
qDebug() << "\t(I) Clearing directory remote: " << pathDir;
ftpList(pathDir);
QList<QString> dirListing(lsDirList);
QFtp ftp;
ftp.connectToHost( ftpHost );
ftp.login( ftpUser, ftpPass );
for (int i = 0; i < dirListing.size(); ++i) {
QString file = dirListing.at(i);
qDebug() << "\t(I) Removing" << pathDir + file;
ftp.remove(pathDir + file);
}
ftp.close();
while ( ftp.hasPendingCommands() )
QCoreApplication::instance()->processEvents();
}
/*
* Get a directory listing from the server in the dir dir.
* You can access it via lsDirList.
*/
void uiLoader::ftpList(const QString & dir) {
qDebug() << "\t(I) Getting list of files in dir" << dir;
lsDirList.clear();
QFtp ftp;
QObject::connect( &ftp, SIGNAL( listInfo( const QUrlInfo & ) ), this, SLOT( ftpAddLsEntry(const QUrlInfo & ) ) );
//QObject::connect( &ftp, SIGNAL( done( bool ) ), this, SLOT( ftpAddLsDone( bool ) ) );
ftp.connectToHost( ftpHost );
ftp.login( ftpUser, ftpPass );
ftp.list( dir );
ftp.close();
while ( ftp.hasPendingCommands() )
QCoreApplication::instance()->processEvents();
}
/*
* Creates a dir on the ftp server.
*
* Hint: If the ftp.mkdir() fails we just assume the dir already exist.
*/
void uiLoader::ftpMkDir( QString pathDir )
{
QFtp ftp;
QSignalSpy commandSpy(&ftp, SIGNAL(commandFinished(int, bool)));
ftp.connectToHost( ftpHost );
ftp.login( ftpUser, ftpPass );
const int command = ftp.mkdir( pathDir );
ftp.close();
while ( ftp.hasPendingCommands() )
QCoreApplication::instance()->processEvents();
// check wheter there was an error or not
for (int i = 0; i < commandSpy.count(); ++i) {
if (commandSpy.at(i).at(0) == command) {
if ( !commandSpy.at(i).at(1).toBool() ) {
qDebug() << "\t(I) Created at remote machine:" << pathDir;
} else {
qDebug() << "\t(I) Could not create on remote machine - probably the dir exists";
}
}
}
}
/*
* Just a slot, needed for ftpList().
*/
void uiLoader::ftpAddLsEntry( const QUrlInfo &urlInfo )
{
//Just adding the file to the list
lsDirList << urlInfo.name();
}
/*
* Return a list of the test case ui files
*/
QStringList uiLoader::uiFiles() const
{
QString baselinePath = QDir::currentPath();
baselinePath += QLatin1String("/baseline");
QDir dir(baselinePath);
dir.setFilter(QDir::Files);
dir.setNameFilters(QStringList(QLatin1String("*.ui")));
const QFileInfoList list = dir.entryInfoList();
QStringList rc;
const QChar slash = QLatin1Char('/');
foreach (const QFileInfo &fi, list) {
QString fileAbsolutePath = baselinePath;
fileAbsolutePath += slash;
fileAbsolutePath += fi.fileName();
rc.push_back(fileAbsolutePath);
}
return rc;
}
/*
* The actual method for generating local files that will be compared
* to the baseline.
*
* The external program uiscreenshot/uiscreenshot is called to generate
* *.png files of *.ui files.
*/
void uiLoader::executeTests()
{
qDebug(" ========== Executing the tests...[generating pngs from uis]");
qDebug() << "Current Dir" << QDir::currentPath();
qDebug() << "\t(I) Using" << pathToProgram;
QProcess myProcess;
foreach(const QString &fileAbsolutePath, uiFiles()) {
qDebug() << "\t(I) Current file:" << fileAbsolutePath;
QHashIterator<QString, QString> j(enginesToTest);
while ( j.hasNext() ) {
j.next();
QString outputDirectory = output + '/' + j.key();
QStringList arguments;
arguments << fileAbsolutePath;
arguments << outputDirectory;
myProcess.start(pathToProgram, arguments);
// took too long?
errorMsg = "process does not exited normally (QProcess timeout) - " + pathToProgram;
QVERIFY2( myProcess.waitForFinished(), qPrintable(errorMsg) );
qDebug() << "\n" << myProcess.readAllStandardError();
// check exit code/status
errorMsg = "process does not exited normally - " + pathToProgram;
QVERIFY2( myProcess.exitStatus() == QProcess::NormalExit, qPrintable(errorMsg) );
QVERIFY2( myProcess.exitCode() == EXIT_SUCCESS, qPrintable(errorMsg) );
}
}
}
/*
* Comparing generated files to the baseline.
*/
bool uiLoader::compare()
{
qDebug( " ========== Now comparing the results to the baseline" );
QDir dir(output);
QHashIterator<QString, QString> i(enginesToTest);
while ( i.hasNext() ) {
i.next();
QString engineName = i.key();
// Perform comparisons between the two directories.
dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
dir.setNameFilters( QStringList() << "*.png" );
dir.cd( engineName + ".baseline" );
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
diff(output, engineName, fileInfo.fileName());
}
}
return true;
}
void uiLoader::diff(const QString& basedir, const QString& engine, const QString& fileName)
{
QString filePathBaseline = basedir + "/" + engine + ".baseline/" + fileName;
QString filePathGenerated = basedir + "/" + engine + '/' + fileName;
qDebug() << "\t(I) Comparing" << filePathBaseline;
qDebug() << "\t(I) Comparing" << filePathGenerated;
QString filePathDiffImage = basedir + "/" + engine + ".diff/" + fileName;
if ( QFile::exists(filePathGenerated) ) {
QString filePathDiffImage = basedir + "/" + engine + ".diff/" + fileName;
int pixelDiff = imgDiff(filePathBaseline, filePathGenerated, filePathDiffImage);
if ( pixelDiff <= threshold.toInt() ) {
qDebug() << "\t(I) TEST OK";
QVERIFY(true);
} else {
qDebug() << "\t(I) TEST FAILED";
qDebug() << "\t(I)\t...saving baseline in *.failed";
// local: save in *.failed
QString filePathFailed = basedir + "/" + engine + ".failed/" + fileName;
errorMsg = "Could not save " + filePathGenerated + " to " + filePathFailed;
QVERIFY2( QFile::copy(filePathGenerated, filePathFailed), qPrintable(errorMsg) );
// remote: save in *.failed
QString filePathFailedRemote = ftpBaseDir + "/" + engine + ".failed" + "/" + fileName;
ftpUploadFile(filePathFailedRemote, filePathGenerated);
errorMsg = "Something broke in the image comparison with " + filePathDiffImage;
QVERIFY2( (pixelDiff != -1), qPrintable(errorMsg) );
// remote: save in *.diff
QString filePathDiffRemote = ftpBaseDir + "/" + engine + ".diff" + "/" + fileName;
ftpUploadFile(filePathDiffRemote, filePathDiffImage);
QFAIL(qPrintable(fileName));
}
} else {
qWarning() << "\t(W) Expected generated file" << filePathGenerated << "does not exist.";
qWarning() << "\t(W) ...saving baseline in *.failed";
// save local
QString filePathMissing = basedir + '/' + engine + ".failed/" + fileName + "_missing";
errorMsg = "Could not save " + filePathMissing;
QVERIFY2( QFile::copy(filePathBaseline, filePathMissing), qPrintable(errorMsg) );
// save remote
QString filePathDiffRemote = ftpBaseDir + "/" + engine + ".diff" + "/" + fileName;
ftpUploadFile(filePathDiffRemote, filePathBaseline);
errorMsg = filePathGenerated + " was not generated, but baseline for this file exists";
QVERIFY2(false, qPrintable(errorMsg));
}
}
/*
* Execution starts here.
*/
uiLoader::TestResult uiLoader::runAutoTests(QString *errorMessage)
{
// SVG needs this widget...
QWidget dummy;
qDebug() << "Running test on buildkey:" << QLibraryInfo::buildKey() << " qt version:" << qVersion();
qDebug() << "Initializing tests...";
// load config
const QString configFileName = QHostInfo::localHostName().split(QLatin1Char('.')).first() + QLatin1String(".ini");
const QFileInfo fi(configFileName);
if (!fi.isFile() || !fi.isReadable()) {
*errorMessage = QString::fromLatin1("Config file '%1' does not exist or is not readable.").arg(configFileName);
return TestNoConfig;
}
if (!loadConfig(configFileName, errorMessage))
return TestConfigError;
// reset the local environment where the results are stored
setupLocal();
// reset the FTP environment where the results are stored
setupFTP();
// retrieve the latest test result baseline from the FTP server.
downloadBaseline();
// execute tests
executeTests();
// upload testresults as new baseline or compare results
if ( lsNeedBaseline.size() )
createBaseline();
else
compare();
return TestRunDone;
}
int uiLoader::imgDiff(const QString fileA, const QString fileB, const QString output)
{
// qDebug() << "Comparing " << fileA << " and " << fileB << " outputting to " << output;
QImage imageA(fileA);
QImage imageB(fileB);
// Invalid images
if (imageA.isNull() || imageB.isNull())
{
qDebug() << "Fatal error: unable to open one or more input images.";
return false;
}
//Choose the largest image size, so that the output can capture the entire diff.
QSize largestSize = imageA.size();
QSize otherSize = imageB.size();
if (largestSize.width() < otherSize.width())
largestSize.setWidth(otherSize.width());
if (largestSize.height() < otherSize.height())
largestSize.setHeight(otherSize.height());
QImage imageDiff(largestSize, QImage::Format_ARGB32);
imageA = imageA.convertToFormat(QImage::Format_ARGB32);
imageB = imageB.convertToFormat(QImage::Format_ARGB32);
int pixelDiff = 0;
for (int y = 0; y < imageDiff.height(); ++y)
{
for (int x = 0; x < imageDiff.width(); ++x)
{
//Are the pixels within range? Else, draw a black pixel in diff.
if (imageA.valid(x,y) && imageB.valid(x,y))
{
//Both images have a pixel at x,y - are they the same? If not, black pixel in diff.
if (imageA.pixel(x,y) != imageB.pixel(x,y))
{
imageDiff.setPixel(x,y,0xff000000);
pixelDiff++;
}
else
imageDiff.setPixel(x,y,0xffffffff);
}
else
{
imageDiff.setPixel(x,y,0xff000000);
pixelDiff++;
}
}
}
imageDiff.setText("comment", QString::number(pixelDiff));
if (!imageDiff.save(output, "PNG"))
pixelDiff = -1;
return pixelDiff;
}
| igor-sfdc/qt-wk | tests/auto/uiloader/uiloader/uiloader.cpp | C++ | lgpl-2.1 | 23,766 |
/*!
* \file codi_reverse_structure.hpp
* \brief Header for codi reverse type definition.
* \author T. Albring
* \version 5.0.0 "Raven"
*
* SU2 Original Developers: Dr. Francisco D. Palacios.
* Dr. Thomas D. Economon.
*
* SU2 Developers: Prof. Juan J. Alonso's group at Stanford University.
* Prof. Piero Colonna's group at Delft University of Technology.
* Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology.
* Prof. Alberto Guardone's group at Polytechnic University of Milan.
* Prof. Rafael Palacios' group at Imperial College London.
* Prof. Edwin van der Weide's group at the University of Twente.
* Prof. Vincent Terrapon's group at the University of Liege.
*
* Copyright (C) 2012-2017 SU2, the open-source CFD code.
*
* SU2 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.
*
* SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "codi.hpp"
#include "tools/dataStore.hpp"
#ifdef CODI_INDEX_TAPE
typedef codi::RealReverseIndex su2double;
#else
typedef codi::RealReverse su2double;
#endif
| pawhewitt/Dev | Common/include/datatypes/codi_reverse_structure.hpp | C++ | lgpl-2.1 | 1,712 |
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "newactiondialog_p.h"
#include "ui_newactiondialog.h"
#include "richtexteditor_p.h"
#include "actioneditor_p.h"
#include "formwindowbase_p.h"
#include "qdesigner_utils_p.h"
#include "iconloader_p.h"
#include <QtDesigner/abstractformwindow.h>
#include <QtDesigner/abstractformeditor.h>
#include <QtGui/QPushButton>
#include <QtCore/QRegExp>
QT_BEGIN_NAMESPACE
namespace qdesigner_internal {
// -------------------- ActionData
ActionData::ActionData() :
checkable(false)
{
}
// Returns a combination of ChangeMask flags
unsigned ActionData::compare(const ActionData &rhs) const
{
unsigned rc = 0;
if (text != rhs.text)
rc |= TextChanged;
if (name != rhs.name)
rc |= NameChanged;
if (toolTip != rhs.toolTip)
rc |= ToolTipChanged ;
if (icon != rhs.icon)
rc |= IconChanged ;
if (checkable != rhs.checkable)
rc |= CheckableChanged;
if (keysequence != rhs.keysequence)
rc |= KeysequenceChanged ;
return rc;
}
// -------------------- NewActionDialog
NewActionDialog::NewActionDialog(ActionEditor *parent) :
QDialog(parent, Qt::Sheet),
m_ui(new Ui::NewActionDialog),
m_actionEditor(parent)
{
m_ui->setupUi(this);
m_ui->tooltipEditor->setTextPropertyValidationMode(ValidationRichText);
connect(m_ui->toolTipToolButton, SIGNAL(clicked()), this, SLOT(slotEditToolTip()));
m_ui->keysequenceResetToolButton->setIcon(createIconSet(QLatin1String("resetproperty.png")));
connect(m_ui->keysequenceResetToolButton, SIGNAL(clicked()), this, SLOT(slotResetKeySequence()));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
m_ui->editActionText->setFocus();
m_auto_update_object_name = true;
updateButtons();
QDesignerFormWindowInterface *form = parent->formWindow();
m_ui->iconSelector->setFormEditor(form->core());
FormWindowBase *formBase = qobject_cast<FormWindowBase *>(form);
if (formBase) {
m_ui->iconSelector->setPixmapCache(formBase->pixmapCache());
m_ui->iconSelector->setIconCache(formBase->iconCache());
}
}
NewActionDialog::~NewActionDialog()
{
delete m_ui;
}
QString NewActionDialog::actionText() const
{
return m_ui->editActionText->text();
}
QString NewActionDialog::actionName() const
{
return m_ui->editObjectName->text();
}
ActionData NewActionDialog::actionData() const
{
ActionData rc;
rc.text = actionText();
rc.name = actionName();
rc.toolTip = m_ui->tooltipEditor->text();
rc.icon = m_ui->iconSelector->icon();
rc.checkable = m_ui->checkableCheckBox->checkState() == Qt::Checked;
rc.keysequence = PropertySheetKeySequenceValue(m_ui->keySequenceEdit->keySequence());
return rc;
}
void NewActionDialog::setActionData(const ActionData &d)
{
m_ui->editActionText->setText(d.text);
m_ui->editObjectName->setText(d.name);
m_ui->iconSelector->setIcon(d.icon);
m_ui->tooltipEditor->setText(d.toolTip);
m_ui->keySequenceEdit->setKeySequence(d.keysequence.value());
m_ui->checkableCheckBox->setCheckState(d.checkable ? Qt::Checked : Qt::Unchecked);
m_auto_update_object_name = false;
updateButtons();
}
void NewActionDialog::on_editActionText_textEdited(const QString &text)
{
if (text.isEmpty())
m_auto_update_object_name = true;
if (m_auto_update_object_name)
m_ui->editObjectName->setText(ActionEditor::actionTextToName(text));
updateButtons();
}
void NewActionDialog::on_editObjectName_textEdited(const QString&)
{
updateButtons();
m_auto_update_object_name = false;
}
void NewActionDialog::slotEditToolTip()
{
const QString oldToolTip = m_ui->tooltipEditor->text();
RichTextEditorDialog richTextDialog(m_actionEditor->core(), this);
richTextDialog.setText(oldToolTip);
if (richTextDialog.showDialog() == QDialog::Rejected)
return;
const QString newToolTip = richTextDialog.text();
if (newToolTip != oldToolTip)
m_ui->tooltipEditor->setText(newToolTip);
}
void NewActionDialog::slotResetKeySequence()
{
m_ui->keySequenceEdit->setKeySequence(QKeySequence());
m_ui->keySequenceEdit->setFocus(Qt::MouseFocusReason);
}
void NewActionDialog::updateButtons()
{
QPushButton *okButton = m_ui->buttonBox->button(QDialogButtonBox::Ok);
okButton->setEnabled(!actionText().isEmpty() && !actionName().isEmpty());
}
} // namespace qdesigner_internal
QT_END_NAMESPACE
| sunblithe/qt-everywhere-opensource-src-4.7.1 | tools/designer/src/lib/shared/newactiondialog.cpp | C++ | lgpl-2.1 | 6,383 |
/**
* \file mlt_parser.c
* \brief service parsing functionality
* \see mlt_parser_s
*
* Copyright (C) 2003-2014 Meltytech, LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mlt.h"
#include <stdlib.h>
static int on_invalid( mlt_parser self, mlt_service object )
{
return 0;
}
static int on_unknown( mlt_parser self, mlt_service object )
{
return 0;
}
static int on_start_producer( mlt_parser self, mlt_producer object )
{
return 0;
}
static int on_end_producer( mlt_parser self, mlt_producer object )
{
return 0;
}
static int on_start_playlist( mlt_parser self, mlt_playlist object )
{
return 0;
}
static int on_end_playlist( mlt_parser self, mlt_playlist object )
{
return 0;
}
static int on_start_tractor( mlt_parser self, mlt_tractor object )
{
return 0;
}
static int on_end_tractor( mlt_parser self, mlt_tractor object )
{
return 0;
}
static int on_start_multitrack( mlt_parser self, mlt_multitrack object )
{
return 0;
}
static int on_end_multitrack( mlt_parser self, mlt_multitrack object )
{
return 0;
}
static int on_start_track( mlt_parser self )
{
return 0;
}
static int on_end_track( mlt_parser self )
{
return 0;
}
static int on_start_filter( mlt_parser self, mlt_filter object )
{
return 0;
}
static int on_end_filter( mlt_parser self, mlt_filter object )
{
return 0;
}
static int on_start_transition( mlt_parser self, mlt_transition object )
{
return 0;
}
static int on_end_transition( mlt_parser self, mlt_transition object )
{
return 0;
}
mlt_parser mlt_parser_new( )
{
mlt_parser self = calloc( 1, sizeof( struct mlt_parser_s ) );
if ( self != NULL && mlt_properties_init( &self->parent, self ) == 0 )
{
self->on_invalid = on_invalid;
self->on_unknown = on_unknown;
self->on_start_producer = on_start_producer;
self->on_end_producer = on_end_producer;
self->on_start_playlist = on_start_playlist;
self->on_end_playlist = on_end_playlist;
self->on_start_tractor = on_start_tractor;
self->on_end_tractor = on_end_tractor;
self->on_start_multitrack = on_start_multitrack;
self->on_end_multitrack = on_end_multitrack;
self->on_start_track = on_start_track;
self->on_end_track = on_end_track;
self->on_start_filter = on_start_filter;
self->on_end_filter = on_end_filter;
self->on_start_transition = on_start_transition;
self->on_end_transition = on_end_transition;
}
return self;
}
mlt_properties mlt_parser_properties( mlt_parser self )
{
return &self->parent;
}
int mlt_parser_start( mlt_parser self, mlt_service object )
{
int error = 0;
mlt_service_type type = mlt_service_identify( object );
switch( type )
{
case invalid_type:
error = self->on_invalid( self, object );
break;
case unknown_type:
error = self->on_unknown( self, object );
break;
case producer_type:
if ( mlt_producer_is_cut( ( mlt_producer )object ) )
error = mlt_parser_start( self, ( mlt_service )mlt_producer_cut_parent( ( mlt_producer )object ) );
error = self->on_start_producer( self, ( mlt_producer )object );
if ( error == 0 )
{
int i = 0;
while ( error == 0 && mlt_producer_filter( ( mlt_producer )object, i ) != NULL )
error = mlt_parser_start( self, ( mlt_service )mlt_producer_filter( ( mlt_producer )object, i ++ ) );
}
error = self->on_end_producer( self, ( mlt_producer )object );
break;
case playlist_type:
error = self->on_start_playlist( self, ( mlt_playlist )object );
if ( error == 0 )
{
int i = 0;
while ( error == 0 && i < mlt_playlist_count( ( mlt_playlist )object ) )
mlt_parser_start( self, ( mlt_service )mlt_playlist_get_clip( ( mlt_playlist )object, i ++ ) );
i = 0;
while ( error == 0 && mlt_producer_filter( ( mlt_producer )object, i ) != NULL )
error = mlt_parser_start( self, ( mlt_service )mlt_producer_filter( ( mlt_producer )object, i ++ ) );
}
error = self->on_end_playlist( self, ( mlt_playlist )object );
break;
case tractor_type:
error = self->on_start_tractor( self, ( mlt_tractor )object );
if ( error == 0 )
{
int i = 0;
mlt_service next = mlt_service_producer( object );
mlt_parser_start( self, ( mlt_service )mlt_tractor_multitrack( ( mlt_tractor )object ) );
while ( next != ( mlt_service )mlt_tractor_multitrack( ( mlt_tractor )object ) )
{
mlt_parser_start( self, next );
next = mlt_service_producer( next );
}
while ( error == 0 && mlt_producer_filter( ( mlt_producer )object, i ) != NULL )
error = mlt_parser_start( self, ( mlt_service )mlt_producer_filter( ( mlt_producer )object, i ++ ) );
}
error = self->on_end_tractor( self, ( mlt_tractor )object );
break;
case multitrack_type:
error = self->on_start_multitrack( self, ( mlt_multitrack )object );
if ( error == 0 )
{
int i = 0;
while ( i < mlt_multitrack_count( ( mlt_multitrack )object ) )
{
self->on_start_track( self );
mlt_parser_start( self, ( mlt_service )mlt_multitrack_track( ( mlt_multitrack )object , i ++ ) );
self->on_end_track( self );
}
i = 0;
while ( error == 0 && mlt_producer_filter( ( mlt_producer )object, i ) != NULL )
error = mlt_parser_start( self, ( mlt_service )mlt_producer_filter( ( mlt_producer )object, i ++ ) );
}
error = self->on_end_multitrack( self, ( mlt_multitrack )object );
break;
case filter_type:
error = self->on_start_filter( self, ( mlt_filter )object );
if ( error == 0 )
{
int i = 0;
while ( error == 0 && mlt_producer_filter( ( mlt_producer )object, i ) != NULL )
error = mlt_parser_start( self, ( mlt_service )mlt_producer_filter( ( mlt_producer )object, i ++ ) );
}
error = self->on_end_filter( self, ( mlt_filter )object );
break;
case transition_type:
error = self->on_start_transition( self, ( mlt_transition )object );
if ( error == 0 )
{
int i = 0;
while ( error == 0 && mlt_producer_filter( ( mlt_producer )object, i ) != NULL )
error = mlt_parser_start( self, ( mlt_service )mlt_producer_filter( ( mlt_producer )object, i ++ ) );
}
error = self->on_end_transition( self, ( mlt_transition )object );
break;
case field_type:
break;
case consumer_type:
break;
}
return error;
}
void mlt_parser_close( mlt_parser self )
{
if ( self != NULL )
{
mlt_properties_close( &self->parent );
free( self );
}
}
| xzhavilla/mlt | src/framework/mlt_parser.c | C | lgpl-2.1 | 7,049 |
/***************************************************************************
* Copyright © 2004 Jason Kivlighn <jkivlighn@gmail.com> *
* Copyright © 2008 Montel Laurent <montel@kde.org> *
* Copyright © 2009 José Manuel Santamaría Lema <panfaust@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "ingredientactionshandler.h"
#include <KLocale>
#include <K3ListView>
#include <KMenu>
#include <QPointer>
#include <KMessageBox>
class Q3ListViewItem;
#include "datablocks/elementlist.h"
#include "backends/recipedb.h"
#include "widgets/dblistviewbase.h"
#include "dialogs/createelementdialog.h"
#include "dialogs/dependanciesdialog.h"
IngredientActionsHandler::IngredientActionsHandler( DBListViewBase *_parentListView, RecipeDB *db ):
ActionsHandlerBase( _parentListView, db )
{
}
void IngredientActionsHandler::createNew()
{
QPointer<CreateElementDialog> elementDialog = new CreateElementDialog( parentListView, i18n( "New Ingredient" ) );
if ( elementDialog->exec() == QDialog::Accepted ) {
QString result = elementDialog->newElementName();
//check bounds first
if ( checkBounds( result ) )
database->createNewIngredient( result ); // Create the new ingredient in the database
}
delete elementDialog;
}
void IngredientActionsHandler::remove()
{
Q3ListViewItem * item = parentListView->currentItem();
if ( item ) {
int id = item->text( 1 ).toInt();
ElementList dependingRecipes;
database->findIngredientDependancies( id, &dependingRecipes );
if ( dependingRecipes.isEmpty() )
database->removeIngredient( id );
else { // Need Warning!
ListInfo list;
list.list = dependingRecipes;
list.name = i18n( "Recipes" );
QPointer<DependanciesDialog> warnDialog = new DependanciesDialog( parentListView, list );
warnDialog->setCustomWarning( i18n("You are about to permanently delete recipes from your database.") );
if ( warnDialog->exec() == QDialog::Accepted )
database->removeIngredient( id );
delete warnDialog;
}
}
}
bool IngredientActionsHandler::checkBounds( const QString &name )
{
if ( name.length() > int(database->maxIngredientNameLength()) ) {
KMessageBox::error( parentListView,
i18np( "Ingredient name cannot be longer than 1 character.",
"Ingredient name cannot be longer than %1 characters.",
database->maxIngredientNameLength() ) );
return false;
}
return true;
}
void IngredientActionsHandler::saveElement( Q3ListViewItem* i )
{
if ( !checkBounds( i->text( 0 ) ) ) {
parentListView->reload(ForceReload); //reset the changed text
return ;
}
int existing_id = database->findExistingIngredientByName( i->text( 0 ) );
int ing_id = i->text( 1 ).toInt();
if ( existing_id != -1 && existing_id != ing_id ) //ingredient already exists with this label... merge the two
{
switch ( KMessageBox::warningContinueCancel( parentListView,
i18n( "This ingredient already exists. Continuing will merge these two ingredients into one. Are you sure?" ) ) )
{
case KMessageBox::Continue: {
database->mergeIngredients( existing_id, ing_id );
break;
}
default:
parentListView->reload(ForceReload);
break;
}
}
else {
database->modIngredient( ( i->text( 1 ) ).toInt(), i->text( 0 ) );
}
}
| eliovir/krecipes | src/actionshandlers/ingredientactionshandler.cpp | C++ | lgpl-2.1 | 3,686 |
/*
* RELIC is an Efficient LIbrary for Cryptography
* Copyright (C) 2007-2014 RELIC Authors
*
* This file is part of RELIC. RELIC is legal property of its developers,
* whose names are not listed here. Please refer to the COPYRIGHT file
* for contact information.
*
* RELIC 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.
*
* RELIC 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 RELIC. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file
*
* Implementation of squaring in a quadratic extension of a prime field.
*
* @version $Id$
* @ingroup fpx
*/
#include "relic_core.h"
#include "relic_fpx_low.h"
/*============================================================================*/
/* Public definitions */
/*============================================================================*/
#if FPX_QDR == BASIC || !defined(STRIP)
void fp2_sqr_basic(fp2_t c, fp2_t a) {
fp_t t0, t1, t2;
fp_null(t0);
fp_null(t1);
fp_null(t2);
TRY {
fp_new(t0);
fp_new(t1);
fp_new(t2);
/* t0 = (a_0 + a_1). */
fp_add(t0, a[0], a[1]);
/* t1 = (a_0 - a_1). */
fp_sub(t1, a[0], a[1]);
/* t1 = a_0 + u^2 * a_1. */
for (int i = -1; i > fp_prime_get_qnr(); i--) {
fp_sub(t1, t1, a[1]);
}
for (int i = 0; i <= fp_prime_get_qnr(); i++) {
fp_add(t1, t1, a[1]);
}
if (fp_prime_get_qnr() == -1) {
/* t2 = 2 * a_0. */
fp_dbl(t2, a[0]);
/* c_1 = 2 * a_0 * a_1. */
fp_mul(c[1], t2, a[1]);
/* c_0 = a_0^2 + a_1^2 * u^2. */
fp_mul(c[0], t0, t1);
} else {
/* c_1 = a_0 * a_1. */
fp_mul(c[1], a[0], a[1]);
/* c_0 = a_0^2 + a_1^2 * u^2. */
fp_mul(c[0], t0, t1);
for (int i = -1; i > fp_prime_get_qnr(); i--) {
fp_add(c[0], c[0], c[1]);
}
for (int i = 0; i <= fp_prime_get_qnr(); i++) {
fp_sub(c[0], c[0], c[1]);
}
/* c_1 = 2 * a_0 * a_1. */
fp_dbl(c[1], c[1]);
}
/* c = c_0 + c_1 * u. */
}
CATCH_ANY {
THROW(ERR_CAUGHT);
}
FINALLY {
fp_free(t0);
fp_free(t1);
fp_free(t2);
}
}
#endif
#if FPX_QDR == INTEG || !defined(STRIP)
void fp2_sqr_integ(fp2_t c, fp2_t a) {
fp2_sqrm_low(c, a);
}
#endif
| tectronics/relic-toolkit | src/fpx/relic_fp2_sqr.c | C | lgpl-2.1 | 2,640 |
using System;
using System.Collections.Generic;
using NCrawler.HtmlProcessor;
using NCrawler.Interfaces;
namespace NCrawler.Demo
{
public class IndexerDemo : IPipelineStep
{
#region IPipelineStep Members
public void Process(Crawler crawler, PropertyBag propertyBag)
{
string textContent = propertyBag.Text; // Filtered text content
// Here you can send downloaded filtered content to an index, database, filesystem or whatever
Console.Out.WriteLine(textContent);
}
#endregion
#region Class Methods
public static void Run()
{
NCrawlerModule.Setup();
Console.Out.WriteLine("\nSimple indexer demo");
// Setup crawler to crawl/index http://ncrawler.codeplex.com
// * Step 1 - The Html Processor, parses and extracts links, text and more from html
// * Step 2 - Custom step, that is supposed to send content to an Index or Database
using (Crawler c = new Crawler(new Uri("http://ncrawler.codeplex.com"),
new HtmlDocumentProcessor( // Process html, filter links and content
// Setup filter that removed all the text between <body and </body>
// This can be custom tags like <!--BeginTextFiler--> and <!--EndTextFiler-->
// or whatever you prefer. This way you can control what text is extracted on every page
// Most cases you want just to filter the header information or menu text
new Dictionary<string, string>
{
{"<body", "</body>"}
},
// Setup filter that tells the crawler not to follow links between tags
// that start with <head and ends with </head>. This can be custom tags like
// <!--BeginNoFollow--> and <!--EndNoFollow--> or whatever you prefer.
// This was you can control what links the crawler should not follow
new Dictionary<string, string>
{
{"<head", "</head>"}
}),
new IndexerDemo())
{
MaximumThreadCount = 2
}) // Custom Step to send filtered content to index
{
// Begin crawl
c.Crawl();
}
}
#endregion
}
} | nzaugg/ncrawler | Net 4.0/NCrawler.Demo/IndexerDemo.cs | C# | lgpl-2.1 | 1,999 |
/* include/linux/android_alarm.h
*
* Copyright (C) 2006-2007 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*
*/
#ifndef _LINUX_ANDROID_ALARM_H
#define _LINUX_ANDROID_ALARM_H
enum android_alarm_type {
/* return code bit numbers or set alarm arg */
ANDROID_ALARM_RTC_WAKEUP,
ANDROID_ALARM_RTC,
ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP,
ANDROID_ALARM_ELAPSED_REALTIME,
ANDROID_ALARM_SYSTEMTIME,
ANDROID_ALARM_TYPE_COUNT,
/* return code bit numbers */
/* ANDROID_ALARM_TIME_CHANGE = 16 */
};
enum android_alarm_return_flags {
ANDROID_ALARM_RTC_WAKEUP_MASK = 1U << ANDROID_ALARM_RTC_WAKEUP,
ANDROID_ALARM_RTC_MASK = 1U << ANDROID_ALARM_RTC,
ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP_MASK =
1U << ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP,
ANDROID_ALARM_ELAPSED_REALTIME_MASK =
1U << ANDROID_ALARM_ELAPSED_REALTIME,
ANDROID_ALARM_SYSTEMTIME_MASK = 1U << ANDROID_ALARM_SYSTEMTIME,
ANDROID_ALARM_TIME_CHANGE_MASK = 1U << 16
};
/* Disable alarm */
#define ANDROID_ALARM_CLEAR(type) _IO('a', 0 | ((type) << 4))
/* Ack last alarm and wait for next */
#define ANDROID_ALARM_WAIT _IO('a', 1)
#define ALARM_IOW(c, type, size) _IOW('a', (c) | ((type) << 4), size)
/* Set alarm */
#define ANDROID_ALARM_SET(type) ALARM_IOW(2, type, struct timespec)
#define ANDROID_ALARM_SET_AND_WAIT(type) ALARM_IOW(3, type, struct timespec)
#define ANDROID_ALARM_GET_TIME(type) ALARM_IOW(4, type, struct timespec)
#define ANDROID_ALARM_SET_RTC _IOW('a', 5, struct timespec)
#define ANDROID_ALARM_BASE_CMD(cmd) (cmd & ~(_IOC(0, 0, 0xf0, 0)))
#define ANDROID_ALARM_IOCTL_TO_TYPE(cmd) (_IOC_NR(cmd) >> 4)
#endif
| spiiroin/dsme | include/android/android_alarm.h | C | lgpl-2.1 | 2,113 |
/**
* Copyright (C) 2011 Orbeon, 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
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.xforms.xbl
import org.orbeon.css.CSSSelectorParser
import org.orbeon.css.CSSSelectorParser.Selector
import org.orbeon.oxf.xml.dom4j.Dom4jUtils
import org.dom4j.{Document, QName, Element}
import org.orbeon.oxf.xforms._
import analysis.ElementAnalysis.attSet
import org.orbeon.oxf.xforms.XFormsConstants._
import org.orbeon.oxf.xforms.event.XFormsEvents.XFORMS_FOCUS
import org.orbeon.oxf.common.OXFException
import org.orbeon.oxf.xml.Dom4j
import org.orbeon.oxf.util.ScalaUtils._
import org.orbeon.oxf.xforms.xbl.XBLResources.HeadElement
import org.orbeon.oxf.xforms.analysis.model.ThrowawayInstance
import scala.collection.JavaConverters._
trait IndexableBinding {
def selectors : List[Selector]
def selectorsNamespaces : Map[String, String]
def path : Option[String]
def lastModified : Long
}
// Inline binding details, which cannot be shared between forms
case class InlineBindingRef(
bindingPrefixedId : String,
selectors : List[Selector],
selectorsNamespaces : Map[String, String]
) extends IndexableBinding {
val path = None
val lastModified = -1L
}
// Holds details of an xbl:xbl/xbl:binding
case class AbstractBinding(
selectors : List[Selector],
cssName : Option[String],
bindingElement : Element,
path : Option[String],
lastModified : Long,
bindingId : Option[String],
scripts : Seq[HeadElement],
styles : Seq[HeadElement],
handlers : Seq[Element],
modelElements : Seq[Element],
global : Option[Document]
) extends IndexableBinding {
val containerElementName = // "div" by default
Option(bindingElement.attributeValue(XXBL_CONTAINER_QNAME)) getOrElse
"div"
// XBL modes
private val xblMode = attSet(bindingElement, XXBL_MODE_QNAME)
def modeBinding = xblMode("binding") // currently semantic is optional binding but need mandatory, optional, and prohibited
def modeValue = xblMode("value")
def modeLHHA = xblMode("lhha")
def modeFocus = xblMode("focus")
def modeLHHACustom = modeLHHA && xblMode("custom-lhha")
def modeItemset = xblMode("itemset") // NIY as of 2012-11-20
def modeHandlers = ! xblMode("nohandlers")
val labelFor = Option(bindingElement.attributeValue(XXBL_LABEL_FOR_QNAME))
// Printable name for the binding match
def debugBindingName = bindingElement.getQualifiedName
// CSS classes to put in the markup
val cssClasses =
"xbl-component" ::
(cssName map ("xbl-" +) toList) :::
(modeFocus list "xbl-focusable") :::
attSet(bindingElement, CLASS_QNAME).toList mkString " "
val allowedExternalEvents =
attSet(bindingElement, XXFORMS_EXTERNAL_EVENTS_ATTRIBUTE_NAME) ++ (modeFocus set XFORMS_FOCUS)
// Constant instance DocumentInfo by model and instance index
// We use the indexes because at this time, no id annotation has taken place yet
val constantInstances = (
for {
(m, mi) ← modelElements.zipWithIndex
(i, ii) ← Dom4j.elements(m, XFORMS_INSTANCE_QNAME).zipWithIndex
im = new ThrowawayInstance(i)
if im.readonly && im.useInlineContent
} yield
(mi, ii) → im.inlineContent
) toMap
def templateElement = Option(bindingElement.element(XBL_TEMPLATE_QNAME))
def supportAVTs = templateElement exists (_.attributeValue(XXBL_AVT_QNAME) == "true")
private def transformQNameOption = templateElement flatMap
(e ⇒ Option(Dom4jUtils.extractAttributeValueQName(e, XXBL_TRANSFORM_QNAME)))
private def templateRootOption = templateElement map { e ⇒
if (e.elements.size != 1)
throw new OXFException("xxbl:transform requires a single child element.")
e.elements.get(0).asInstanceOf[Element]
}
private lazy val transformConfig =
for {
transformQName ← transformQNameOption
templateRoot ← templateRootOption
} yield
Transform.createTransformConfig(transformQName, templateRoot, lastModified)
// A transform cannot be reused, so this creates a new one when called, based on the config
def newTransform(boundElement: Element) = transformConfig map {
case (pipelineConfig, domGenerator) ⇒
// Run the transformation
val generatedDocument = Transform.transformBoundElement(pipelineConfig, domGenerator, boundElement)
// Repackage the result
val generatedRootElement = generatedDocument.getRootElement.detach.asInstanceOf[Element]
generatedDocument.addElement(new QName("template", XBL_NAMESPACE, "xbl:template"))
val newRoot = generatedDocument.getRootElement
newRoot.add(XBL_NAMESPACE)
newRoot.add(generatedRootElement)
generatedDocument
}
def selectorsNamespaces =
Dom4jUtils.getNamespaceContext(bindingElement).asScala.toMap
}
object AbstractBinding {
def fromBindingElement(
bindingElement : Element,
path : Option[String],
lastModified : Long,
scripts : Seq[HeadElement]
): AbstractBinding = {
assert(bindingElement ne null)
val bindingId = Option(XFormsUtils.getElementId(bindingElement))
val styles =
for {
resourcesElement ← Dom4j.elements(bindingElement, XBL_RESOURCES_QNAME)
styleElement ← Dom4j.elements(resourcesElement, XBL_STYLE_QNAME)
} yield
HeadElement(styleElement)
val handlers =
for {
handlersElement ← Option(bindingElement.element(XBL_HANDLERS_QNAME)).toSeq
handlerElement ← Dom4j.elements(handlersElement, XBL_HANDLER_QNAME)
} yield
handlerElement
val modelElements =
for {
implementationElement ← Option(bindingElement.element(XBL_IMPLEMENTATION_QNAME)).toSeq
modelElement ← Dom4j.elements(implementationElement, XFORMS_MODEL_QNAME)
} yield
modelElement
val global = Option(bindingElement.element(XXBL_GLOBAL_QNAME)) map
(Dom4jUtils.createDocumentCopyParentNamespaces(_, true))
val selectors =
CSSSelectorParser.parseSelectors(bindingElement.attributeValue(ELEMENT_QNAME))
// Get CSS name from direct binding if there is one. In the other cases, we won't have a class for now.
val cssName = {
val ns = Dom4jUtils.getNamespaceContext(bindingElement).asScala.toMap
val qName = selectors collectFirst BindingDescriptor.directBindingPF(ns, None) flatMap (_.elementName)
qName map (_.getQualifiedName) map (_.replace(':', '-'))
}
AbstractBinding(
selectors,
cssName,
bindingElement,
path,
lastModified,
bindingId,
scripts,
styles,
handlers,
modelElements,
global
)
}
} | ajw625/orbeon-forms | src/main/scala/org/orbeon/oxf/xforms/xbl/AbstractBinding.scala | Scala | lgpl-2.1 | 7,924 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Debug Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">2.0</span>
</div>
<div id="projectbrief">A lightweight enterprise framework to write CQRS, event-sourced and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('dir_09951e24a6920d4f8b04d0185eafdc32.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Debug Directory Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a>
Files</h2></td></tr>
<tr class="memitem:Akka_8Net_2Cqrs_8Akka_8Tests_8Unit_2obj_2Debug_2TemporaryGeneratedFile__036C0B5B-1481-4323-8D20-8F5ADCB23D92_8cs"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>Akka.Net/Cqrs.Akka.Tests.Unit/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:Akka_8Net_2Cqrs_8Akka_8Tests_8Unit_2obj_2Debug_2TemporaryGeneratedFile__5937a670-0e60-4077-877b-f7221da3dda1_8cs"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>Akka.Net/Cqrs.Akka.Tests.Unit/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:Akka_8Net_2Cqrs_8Akka_8Tests_8Unit_2obj_2Debug_2TemporaryGeneratedFile__E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3_8cs"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>Akka.Net/Cqrs.Akka.Tests.Unit/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_cc3caa4a3888239b9b6c91334478a242.html">cqrs</a></li><li class="navelem"><a class="el" href="dir_327c1c0988602ee6e333400a7bf4d700.html">Framework</a></li><li class="navelem"><a class="el" href="dir_3599ee6e705e307de203dec3a605b5bb.html">Akka.Net</a></li><li class="navelem"><a class="el" href="dir_d83a3aeb572d7c7d72d3f2b8eb845095.html">Cqrs.Akka.Tests.Unit</a></li><li class="navelem"><a class="el" href="dir_1605205cd846efde91f9a4266f4898c1.html">obj</a></li><li class="navelem"><a class="el" href="dir_09951e24a6920d4f8b04d0185eafdc32.html">Debug</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
| cdmdotnet/CQRS | wiki/docs/2.0/html/dir_09951e24a6920d4f8b04d0185eafdc32.html | HTML | lgpl-2.1 | 6,069 |
/*
* tsd2.c
*
* Test Thread Specific Data (TSD) key creation and destruction.
*
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2012 Pthreads-win32 contributors
*
* Homepage1: http://sourceware.org/pthreads-win32/
* Homepage2: http://sourceforge.net/projects/pthreads4w/
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.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 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 in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
*
* --------------------------------------------------------------------------
*
* Description:
* -
*
* Test Method (validation or falsification):
* - validation
*
* Requirements Tested:
* - keys are created for each existing thread including the main thread
* - keys are created for newly created threads
* - keys are thread specific
* - destroy routine is called on each thread exit including the main thread
*
* Features Tested:
* -
*
* Cases Tested:
* -
*
* Environment:
* -
*
* Input:
* - none
*
* Output:
* - text to stdout
*
* Assumptions:
* - already validated: pthread_create()
* pthread_once()
* - main thread also has a POSIX thread identity
*
* Pass Criteria:
*
* Fail Criteria:
*/
#include <sched.h>
#include "test.h"
enum {
NUM_THREADS = 100
};
static pthread_key_t key = NULL;
static int accesscount[NUM_THREADS];
static int thread_set[NUM_THREADS];
static int thread_destroyed[NUM_THREADS];
static pthread_barrier_t startBarrier;
static void
destroy_key(void * arg)
{
int * j = (int *) arg;
(*j)++;
/*
* Set TSD key from the destructor to test destructor iteration.
* The key value will have been set to NULL by the library before
* calling the destructor (with the value that the key had). We
* reset the key value here which should cause the destructor to be
* called a second time.
*/
if (*j == 2)
assert(pthread_setspecific(key, arg) == 0);
else
assert(*j == 3);
thread_destroyed[j - accesscount] = 1;
}
static void
setkey(void * arg)
{
int * j = (int *) arg;
thread_set[j - accesscount] = 1;
assert(*j == 0);
assert(pthread_getspecific(key) == NULL);
assert(pthread_setspecific(key, arg) == 0);
assert(pthread_setspecific(key, arg) == 0);
assert(pthread_setspecific(key, arg) == 0);
assert(pthread_getspecific(key) == arg);
(*j)++;
assert(*j == 1);
}
static void *
mythread(void * arg)
{
(void) pthread_barrier_wait(&startBarrier);
setkey(arg);
return 0;
/* Exiting the thread will call the key destructor. */
}
int
main()
{
int i;
int fail = 0;
pthread_t thread[NUM_THREADS];
assert(pthread_barrier_init(&startBarrier, NULL, NUM_THREADS/2) == 0);
for (i = 1; i < NUM_THREADS/2; i++)
{
accesscount[i] = thread_set[i] = thread_destroyed[i] = 0;
assert(pthread_create(&thread[i], NULL, mythread, (void *)&accesscount[i]) == 0);
}
/*
* Here we test that existing threads will get a key created
* for them.
*/
assert(pthread_key_create(&key, destroy_key) == 0);
(void) pthread_barrier_wait(&startBarrier);
/*
* Test main thread key.
*/
accesscount[0] = 0;
setkey((void *) &accesscount[0]);
/*
* Here we test that new threads will get a key created
* for them.
*/
for (i = NUM_THREADS/2; i < NUM_THREADS; i++)
{
accesscount[i] = thread_set[i] = thread_destroyed[i] = 0;
assert(pthread_create(&thread[i], NULL, mythread, (void *)&accesscount[i]) == 0);
}
/*
* Wait for all threads to complete.
*/
for (i = 1; i < NUM_THREADS; i++)
{
assert(pthread_join(thread[i], NULL) == 0);
}
assert(pthread_key_delete(key) == 0);
assert(pthread_barrier_destroy(&startBarrier) == 0);
for (i = 1; i < NUM_THREADS; i++)
{
/*
* The counter is incremented once when the key is set to
* a value, and again when the key is destroyed. If the key
* doesn't get set for some reason then it will still be
* NULL and the destroy function will not be called, and
* hence accesscount will not equal 2.
*/
if (accesscount[i] != 3)
{
fail++;
fprintf(stderr, "Thread %d key, set = %d, destroyed = %d\n",
i, thread_set[i], thread_destroyed[i]);
}
}
fflush(stderr);
return (fail);
}
| G-P-S/pthreads-win32-cvs | tests/tsd2.c | C | lgpl-2.1 | 5,425 |
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.annotation.reference;
import org.xwiki.component.annotation.Role;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.EntityReference;
/**
* Typed version of the entity reference resolver from string representations which gets its type from the string
* serialization, in the form {@code type://} and, if no such type specification is found, it uses the default passed
* type. <br>
* For example, something like: {@code DOCUMENT://XWiki.TagClass[0]#tags} will result in parsing {@code
* XWiki.TagClass[0]#tags} as a document reference, while {OBJECT_PROPERTY://XWiki.TagClass[0]#tags} will result in
* parsing {@code XWiki.TagClass[0]#tags} as an object property reference.<br>
* Note that, although it roughly does the same thing, this is a different hierarchy than EntityReferenceResolver
* because it's a different strategy, different interpretation of the type parameter and resolvers and serializers of
* this type should be used together.
*
* @version $Id$
* @since 2.3M1
*/
@Role
public interface TypedStringEntityReferenceResolver
{
/**
* @param entityReferenceRepresentation representation of the entity, with or without a type (e.g. {@code
* DOCUMENT://wiki:Space.Page} or {@code wiki:Space.WebHome})
* @param type the default type to be used if none is specified in the serialization
* @return the resolved entity reference
*/
EntityReference resolve(String entityReferenceRepresentation, EntityType type);
}
| pbondoer/xwiki-platform | xwiki-platform-core/xwiki-platform-annotations/xwiki-platform-annotation-reference/src/main/java/org/xwiki/annotation/reference/TypedStringEntityReferenceResolver.java | Java | lgpl-2.1 | 2,407 |
var searchData=
[
['outgoingbandwidth',['outgoingBandwidth',['../structENetPeer.html#a38ca43b3ec9cd51b8120b7c50b03c5f0',1,'ENetPeer::outgoingBandwidth()'],['../structENetHost.html#ac72acde682f903beb2d9713538b6465c',1,'ENetHost::outgoingBandwidth()'],['../structENetProtocolConnect.html#a914f63aba14b68e1bb2dd91ad3b728b9',1,'ENetProtocolConnect::outgoingBandwidth()'],['../structENetProtocolVerifyConnect.html#aedeefa1a8476d74dc432dc8ced4a942e',1,'ENetProtocolVerifyConnect::outgoingBandwidth()'],['../structENetProtocolBandwidthLimit.html#a79205f196d170e6a6184c88d8dcbef76',1,'ENetProtocolBandwidthLimit::outgoingBandwidth()']]],
['outgoingbandwidththrottleepoch',['outgoingBandwidthThrottleEpoch',['../structENetPeer.html#aa5497f3812d0f3199da559be1fdfefc0',1,'ENetPeer']]],
['outgoingcommandlist',['outgoingCommandList',['../structENetOutgoingCommand.html#a599e31754d91aefbf6ca62abfb133828',1,'ENetOutgoingCommand']]],
['outgoingcommands',['outgoingCommands',['../structENetPeer.html#a8da2e97fe9ce360d781ae4977355788e',1,'ENetPeer']]],
['outgoingdatatotal',['outgoingDataTotal',['../structENetPeer.html#ab692fa3146864313986cf655f507bcfb',1,'ENetPeer']]],
['outgoingpeerid',['outgoingPeerID',['../structENetPeer.html#aa595b9bd1a22781cf7e03a41eac17e6b',1,'ENetPeer::outgoingPeerID()'],['../structENetProtocolConnect.html#a9aba2d69d08fd42efaa7e09fe5a8ca37',1,'ENetProtocolConnect::outgoingPeerID()'],['../structENetProtocolVerifyConnect.html#a45b9ebf11adbf8c73891de2279f6e4c4',1,'ENetProtocolVerifyConnect::outgoingPeerID()']]],
['outgoingreliablesequencenumber',['outgoingReliableSequenceNumber',['../structENetChannel.html#a469becdcf5464583b06b62fb93adf156',1,'ENetChannel::outgoingReliableSequenceNumber()'],['../structENetPeer.html#a24013f6a2ca4708beedf9708d7f2841c',1,'ENetPeer::outgoingReliableSequenceNumber()']]],
['outgoingsessionid',['outgoingSessionID',['../structENetPeer.html#a20da8fe27ea977e30428362c21425eb9',1,'ENetPeer::outgoingSessionID()'],['../structENetProtocolConnect.html#a425c602e41814a1fcea5b171ad4d33af',1,'ENetProtocolConnect::outgoingSessionID()'],['../structENetProtocolVerifyConnect.html#acf3d5ef09045248b0c065b4bf569f8f5',1,'ENetProtocolVerifyConnect::outgoingSessionID()']]],
['outgoingunreliablesequencenumber',['outgoingUnreliableSequenceNumber',['../structENetChannel.html#a2d80cfad0ae9fe809aa58c9e3770dd2e',1,'ENetChannel']]],
['outgoingunsequencedgroup',['outgoingUnsequencedGroup',['../structENetPeer.html#a623980756d5742862ff73c949a94a0a1',1,'ENetPeer']]]
];
| qianqians/abelkhan | cpp_component/3rdparty/enet/docs/html/search/variables_b.js | JavaScript | lgpl-2.1 | 2,516 |
using System;
using System.Data.Common;
using NHibernate.Engine;
using NHibernate.SqlTypes;
using NHibernate.Util;
namespace NHibernate.Type
{
/// <summary>
/// Superclass of single-column nullable types.
/// </summary>
/// <remarks>
/// Maps the Property to a single column that is capable of storing nulls in it. If a .net Struct is
/// used it will be created with its uninitialized value and then on Update the uninitialized value of
/// the Struct will be written to the column - not <see langword="null" />.
/// </remarks>
[Serializable]
public abstract partial class NullableType : AbstractType
{
private static readonly bool IsDebugEnabled;
static NullableType()
{
//cache this, because it was a significant performance cost
IsDebugEnabled = NHibernateLogger.For(typeof(IType).Namespace).IsDebugEnabled();
}
private INHibernateLogger Log
{
get { return NHibernateLogger.For(GetType()); }
}
private readonly SqlType _sqlType;
/// <summary>
/// Initialize a new instance of the NullableType class using a
/// <see cref="NHibernate.SqlTypes.SqlType"/>.
/// </summary>
/// <param name="sqlType">The underlying <see cref="NHibernate.SqlTypes.SqlType"/>.</param>
/// <remarks>This is used when the Property is mapped to a single column.</remarks>
protected NullableType(SqlType sqlType)
{
_sqlType = sqlType;
}
/// <summary>
/// When implemented by a class, put the value from the mapped
/// Property into to the <see cref="DbCommand"/>.
/// </summary>
/// <param name="cmd">The <see cref="DbCommand"/> to put the value into.</param>
/// <param name="value">The object that contains the value.</param>
/// <param name="index">The index of the <see cref="DbParameter"/> to start writing the values to.</param>
/// <param name="session">The session for which the operation is done.</param>
/// <remarks>
/// Implementors do not need to handle possibility of null values because this will
/// only be called from <see cref="NullSafeSet(DbCommand, object, int, ISessionImplementor)"/> after
/// it has checked for nulls.
/// </remarks>
public abstract void Set(DbCommand cmd, object value, int index, ISessionImplementor session);
/// <summary>
/// When implemented by a class, gets the object in the
/// <see cref="DbDataReader"/> for the Property.
/// </summary>
/// <param name="rs">The <see cref="DbDataReader"/> that contains the value.</param>
/// <param name="index">The index of the field to get the value from.</param>
/// <param name="session">The session for which the operation is done.</param>
/// <returns>An object with the value from the database.</returns>
public abstract object Get(DbDataReader rs, int index, ISessionImplementor session);
/// <summary>
/// When implemented by a class, gets the object in the
/// <see cref="DbDataReader"/> for the Property.
/// </summary>
/// <param name="rs">The <see cref="DbDataReader"/> that contains the value.</param>
/// <param name="name">The name of the field to get the value from.</param>
/// <param name="session">The session for which the operation is done.</param>
/// <returns>An object with the value from the database.</returns>
/// <remarks>
/// Most implementors just call the <see cref="Get(DbDataReader, int, ISessionImplementor)"/>
/// overload of this method.
/// </remarks>
public abstract object Get(DbDataReader rs, string name, ISessionImplementor session);
/// <summary>
/// A representation of the value to be embedded in an XML element
/// </summary>
/// <param name="val">The object that contains the values.
/// </param>
/// <returns>An Xml formatted string.</returns>
public abstract string ToString(object val);
/// <inheritdoc />
/// <remarks>
/// <para>
/// This implementation forwards the call to <see cref="ToString(object)"/> if the parameter
/// value is not null.
/// </para>
/// <para>
/// It has been "sealed" because the Types inheriting from <see cref="NullableType"/>
/// do not need and should not override this method. All of their implementation
/// should be in <see cref="ToString(object)"/>.
/// </para>
/// </remarks>
public override sealed string ToLoggableString(object value, ISessionFactoryImplementor factory)
{
return (value == null) ? null : ToString(value);
}
/// <summary>
/// Parse the XML representation of an instance
/// </summary>
/// <param name="xml">XML string to parse, guaranteed to be non-empty</param>
/// <returns></returns>
public abstract object FromStringValue(string xml);
public override void NullSafeSet(DbCommand st, object value, int index, bool[] settable, ISessionImplementor session)
{
if (settable[0]) NullSafeSet(st, value, index, session);
}
/// <inheritdoc />
/// <remarks>
/// <para>
/// This method has been "sealed" because the Types inheriting from <see cref="NullableType"/>
/// do not need to and should not override this method.
/// </para>
/// <para>
/// This method checks to see if value is null, if it is then the value of
/// <see cref="DBNull"/> is written to the <see cref="DbCommand"/>.
/// </para>
/// <para>
/// If the value is not null, then the method <see cref="Set(DbCommand, object, int, ISessionImplementor)"/>
/// is called and that method is responsible for setting the value.
/// </para>
/// </remarks>
public sealed override void NullSafeSet(DbCommand st, object value, int index, ISessionImplementor session)
{
if (value == null)
{
if (IsDebugEnabled)
{
Log.Debug("binding null to parameter: {0}", index);
}
//Do we check IsNullable?
// TODO: find out why a certain Parameter would not take a null value...
// From reading the .NET SDK the default is to NOT accept a null value.
// I definitely need to look into this more...
st.Parameters[index].Value = DBNull.Value;
}
else
{
if (IsDebugEnabled)
{
Log.Debug("binding '{0}' to parameter: {1}", ToString(value), index);
}
Set(st, value, index, session);
}
}
/// <inheritdoc />
/// <remarks>
/// This has been sealed because no other class should override it. This
/// method calls <see cref="NullSafeGet(DbDataReader, String, ISessionImplementor)" /> for a single value.
/// It only takes the first name from the string[] names parameter - that is a
/// safe thing to do because a Nullable Type only has one field.
/// </remarks>
public sealed override object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner)
{
return NullSafeGet(rs, names[0], session);
}
/// <summary>
/// Extracts the values of the fields from the DataReader
/// </summary>
/// <param name="rs">The DataReader positioned on the correct record</param>
/// <param name="names">An array of field names.</param>
/// <param name="session">The session for which the operation is done.</param>
/// <returns>The value off the field from the DataReader</returns>
/// <remarks>
/// In this class this just ends up passing the first name to the NullSafeGet method
/// that takes a string, not a string[].
///
/// I don't know why this method is in here - it doesn't look like anybody that inherits
/// from NullableType overrides this...
///
/// TODO: determine if this is needed
/// </remarks>
public virtual object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session)
{
return NullSafeGet(rs, names[0], session);
}
/// <summary>
/// Gets the value of the field from the <see cref="DbDataReader" />.
/// </summary>
/// <param name="rs">The <see cref="DbDataReader" /> positioned on the correct record.</param>
/// <param name="name">The name of the field to get the value from.</param>
/// <param name="session">The session for which the operation is done.</param>
/// <returns>The value of the field.</returns>
/// <remarks>
/// <para>
/// This method checks to see if value is null, if it is then the null is returned
/// from this method.
/// </para>
/// <para>
/// If the value is not null, then the method <see cref="Get(DbDataReader, Int32, ISessionImplementor)"/>
/// is called and that method is responsible for retrieving the value.
/// </para>
/// </remarks>
public virtual object NullSafeGet(DbDataReader rs, string name, ISessionImplementor session)
{
int index = rs.GetOrdinal(name);
if (rs.IsDBNull(index))
{
if (IsDebugEnabled)
{
Log.Debug("returning null as column: {0}", name);
}
// TODO: add a method to NullableType.GetNullValue - if we want to
// use "MAGIC" numbers to indicate null values...
return null;
}
else
{
object val;
try
{
val = Get(rs, index, session);
}
catch (InvalidCastException ice)
{
throw new ADOException(
string.Format(
"Could not cast the value in field {0} of type {1} to the Type {2}. Please check to make sure that the mapping is correct and that your DataProvider supports this Data Type.",
name, rs[index].GetType().Name, GetType().Name), ice);
}
if (IsDebugEnabled)
{
Log.Debug("returning '{0}' as column: {1}", ToString(val), name);
}
return val;
}
}
/// <inheritdoc />
/// <remarks>
/// <para>
/// This implementation forwards the call to <see cref="NullSafeGet(DbDataReader, String, ISessionImplementor)" />.
/// </para>
/// <para>
/// It has been "sealed" because the Types inheriting from <see cref="NullableType"/>
/// do not need to and should not override this method. All of their implementation
/// should be in <see cref="NullSafeGet(DbDataReader, String, ISessionImplementor)" />.
/// </para>
/// </remarks>
public sealed override object NullSafeGet(DbDataReader rs, string name, ISessionImplementor session, object owner)
{
return NullSafeGet(rs, name, session);
}
/// <summary>
/// Gets the underlying <see cref="NHibernate.SqlTypes.SqlType" /> for
/// the column mapped by this <see cref="NullableType" />.
/// </summary>
/// <value>The underlying <see cref="NHibernate.SqlTypes.SqlType"/>.</value>
/// <remarks>
/// This implementation should be suitable for all subclasses unless they need to
/// do some special things to get the value. There are no built in <see cref="NullableType"/>s
/// that override this Property.
/// </remarks>
public virtual SqlType SqlType
{
get { return _sqlType; }
}
/// <inheritdoc />
/// <remarks>
/// <para>
/// This implementation forwards the call to <see cref="NullableType.SqlType" />.
/// </para>
/// <para>
/// It has been "sealed" because the Types inheriting from <see cref="NullableType"/>
/// do not need to and should not override this method because they map to a single
/// column. All of their implementation should be in <see cref="NullableType.SqlType" />.
/// </para>
/// </remarks>
public sealed override SqlType[] SqlTypes(IMapping mapping)
{
return new[] { OverrideSqlType(mapping, SqlType) };
}
/// <summary>
/// Overrides the sql type.
/// </summary>
/// <param name="type">The type to override.</param>
/// <param name="mapping">The mapping for which to override <paramref name="type"/>.</param>
/// <returns>The refined types.</returns>
static SqlType OverrideSqlType(IMapping mapping, SqlType type)
{
return mapping != null ? mapping.Dialect.OverrideSqlType(type) : type;
}
/// <summary>
/// Returns the number of columns spanned by this <see cref="NullableType"/>
/// </summary>
/// <returns>A <see cref="NullableType"/> always returns 1.</returns>
/// <remarks>
/// This has the hard coding of 1 in there because, by definition of this class,
/// a NullableType can only map to one column in a table.
/// </remarks>
public override sealed int GetColumnSpan(IMapping session)
{
return 1;
}
public override bool IsDirty(object old, object current, bool[] checkable, ISessionImplementor session)
{
return checkable[0] && IsDirty(old, current, session);
}
public override bool[] ToColumnNullness(object value, IMapping mapping)
{
return value == null ? ArrayHelper.False : ArrayHelper.True;
}
public override bool IsEqual(object x, object y)
{
return Equals(x, y);
}
#region override of System.Object Members
/// <summary>
/// Determines whether the specified <see cref="Object"/> is equal to this
/// <see cref="NullableType"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare with this NullableType.</param>
/// <returns>true if the SqlType and Name properties are the same.</returns>
public override bool Equals(object obj)
{
/*
* Step 1: Perform an == test
* Step 2: Instance of check
* Step 3: Cast argument
* Step 4: For each important field, check to see if they are equal
* Step 5: Go back to equals()'s contract and ask yourself if the equals()
* method is reflexive, symmetric, and transitive
*/
if (this == obj)
return true;
NullableType rhsType = obj as NullableType;
if (rhsType == null)
return false;
if (Name.Equals(rhsType.Name) && SqlType.Equals(rhsType.SqlType))
return true;
return false;
}
/// <summary>
/// Serves as a hash function for the <see cref="NullableType"/>,
/// suitable for use in hashing algorithms and data structures like a hash table.
/// </summary>
/// <returns>
/// A hash code that is based on the <see cref="NullableType.SqlType"/>'s
/// hash code and the <see cref="AbstractType.Name"/>'s hash code.</returns>
public override int GetHashCode()
{
return (SqlType.GetHashCode() / 2) + (Name.GetHashCode() / 2);
}
#endregion
}
}
| lnu/nhibernate-core | src/NHibernate/Type/NullableType.cs | C# | lgpl-2.1 | 13,839 |
var searchData=
[
['yellowcolor',['yellowColor',['../interface_c_p_color.html#a76410df22a14d10a7e3a70d7b959f29c',1,'CPColor']]]
];
| davidsiaw/cappuccino-docs | search/functions_17.js | JavaScript | lgpl-2.1 | 133 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.collections.iterators;
import java.util.Iterator;
/**
* Provides basic behaviour for decorating an iterator with extra functionality.
* <p>
* All methods are forwarded to the decorated iterator.
*
* @since Commons Collections 3.0
* @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
*
* @author James Strachan
* @author Stephen Colebourne
*/
public class AbstractIteratorDecorator implements Iterator {
/** The iterator being decorated */
protected final Iterator iterator;
//-----------------------------------------------------------------------
/**
* Constructor that decorates the specified iterator.
*
* @param iterator the iterator to decorate, must not be null
* @throws IllegalArgumentException if the collection is null
*/
public AbstractIteratorDecorator(Iterator iterator) {
super();
if (iterator == null) {
throw new IllegalArgumentException("Iterator must not be null");
}
this.iterator = iterator;
}
/**
* Gets the iterator being decorated.
*
* @return the decorated iterator
*/
protected Iterator getIterator() {
return iterator;
}
//-----------------------------------------------------------------------
public boolean hasNext() {
return iterator.hasNext();
}
public Object next() {
return iterator.next();
}
public void remove() {
iterator.remove();
}
}
| leodmurillo/sonar | plugins/sonar-squid-java-plugin/test-resources/commons-collections-3.2.1/src/org/apache/commons/collections/iterators/AbstractIteratorDecorator.java | Java | lgpl-3.0 | 2,427 |
'''Simple utility functions that should really be in a C module'''
from math import *
from OpenGLContext.arrays import *
from OpenGLContext import vectorutilities
def rotMatrix( (x,y,z,a) ):
"""Given rotation as x,y,z,a (a in radians), return rotation matrix
Returns a 4x4 rotation matrix for the given rotation,
the matrix is a Numeric Python array.
x,y,z should be a unit vector.
"""
c = cos( a )
s = sin( a )
t = 1-c
R = array( [
[ t*x*x+c, t*x*y+s*z, t*x*z-s*y, 0],
[ t*x*y-s*z, t*y*y+c, t*y*z+s*x, 0],
[ t*x*z+s*y, t*y*z-s*x, t*z*z+c, 0],
[ 0, 0, 0, 1]
] )
return R
def crossProduct( first, second ):
"""Given 2 4-item vectors, return the cross product as a 4-item vector"""
x,y,z = vectorutilities.crossProduct( first, second )[0]
return [x,y,z,0]
def magnitude( vector ):
"""Given a 3 or 4-item vector, return the vector's magnitude"""
return vectorutilities.magnitude( vector[:3] )[0]
def normalise( vector ):
"""Given a 3 or 4-item vector, return a 3-item unit vector"""
return vectorutilities.normalise( vector[:3] )[0]
def pointNormal2Plane( point, normal ):
"""Create parametric equation of plane from point and normal
"""
point = asarray(point,'f')
normal = normalise(normal)
result = zeros((4,),'f')
result[:3] = normal
result[3] = - dot(normal, point)
return result
def plane2PointNormal( (a,b,c,d) ):
"""Get a point and normal from a plane equation"""
return asarray((-d*a,-d*b,-d*c),'f'), asarray((a,b,c),'f')
def combineNormals( normals, weights=None ):
"""Given set of N normals, return (weighted) combination"""
normals = asarray( normals,'d')
if weights:
weights = reshape(asarray( weights, 'f'),(len(weights),1))
final = sum(normals*weights, 0)
else:
final = sum(normals,0)
x,y,z = final
if x == y == z == 0.0:
x,y,z = normals[0]
if x or y:
x,y,z = -x,-y,z
else:
x,y,z = -x,y,-z
return normalise( (x,y,z) )
def coplanar( points ):
"""Determine if points are coplanar
All sets of points < 4 are coplanar
Otherwise, take the first two points and create vector
for all other points, take vector to second point,
calculate cross-product where the cross-product is
non-zero (not colinear), if the normalised cross-product
is all equal, the points are collinear...
"""
points = asarray( points, 'f' )
if len(points) < 4:
return True
a,b = points[:2]
vec1 = reshape(b-a,(1,3))
rest = points[2:] - b
vecs = vectorutilities.crossProduct(
rest,
vec1,
)
vecsNonZero = sometrue(vecs,1)
vecs = compress(vecsNonZero, vecs,0)
if not len(vecs):
return True
vecs = vectorutilities.normalise(vecs)
return allclose( vecs[0], vecs ) | stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGLContext/utilities.py | Python | lgpl-3.0 | 2,924 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ActiveUp.Net.Samples.CompactPPC
{
public partial class frmvToDo : Form
{
public frmvToDo()
{
InitializeComponent();
}
}
} | slavat/MailSystem.NET | Samples/PPC/ActiveUp.Net.Samples.CompactSmartPhone/Groupware/frmvToDo.cs | C# | lgpl-3.0 | 345 |
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_lair_bolma_lair_bolma_desert = object_tangible_lair_bolma_shared_lair_bolma_desert:new {
objectMenuComponent = {"cpp", "LairMenuComponent"},
}
ObjectTemplates:addTemplate(object_tangible_lair_bolma_lair_bolma_desert, "object/tangible/lair/bolma/lair_bolma_desert.iff")
| kidaa/Awakening-Core3 | bin/scripts/object/tangible/lair/bolma/lair_bolma_desert.lua | Lua | lgpl-3.0 | 2,288 |
package restwars.rest.resources;
import com.google.common.base.Preconditions;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import io.dropwizard.auth.Auth;
import restwars.model.building.Buildings;
import restwars.model.planet.Planet;
import restwars.model.player.Player;
import restwars.rest.mapper.BuildingMapper;
import restwars.restapi.dto.building.BuildingsResponse;
import restwars.service.building.BuildingService;
import restwars.service.planet.PlanetService;
import restwars.util.Functional;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Subresource for buildings on a planet.
*/
@Api(value = "/{location}/building", hidden = true)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class BuildingSubResource {
private final PlanetService planetService;
private final BuildingService buildingService;
@Inject
public BuildingSubResource(BuildingService buildingService, PlanetService planetService) {
this.planetService = Preconditions.checkNotNull(planetService, "planetService");
this.buildingService = Preconditions.checkNotNull(buildingService, "buildingService");
}
/**
* Lists all buildings on the planet with the given location.
*
* @param player Player.
* @param location Planet location.
* @return All buildings on the planet.
*/
@GET
@ApiOperation(value = "Get all buildings on a planet")
public BuildingsResponse getBuildings(
@Auth @ApiParam(access = "internal") Player player,
@PathParam("location") @ApiParam("Planet location") String location
) {
Preconditions.checkNotNull(player, "player");
Preconditions.checkNotNull(location, "location");
Planet planet = ResourceHelper.findPlanetWithLocationAndOwner(planetService, location, player);
Buildings buildings = buildingService.findBuildingsOnPlanet(planet);
return new BuildingsResponse(Functional.mapToList(buildings, BuildingMapper::fromBuilding));
}
}
| davidmc24/restwars | rest/src/main/java/restwars/rest/resources/BuildingSubResource.java | Java | lgpl-3.0 | 2,260 |
MCS_BUILD_DIR = ../../../build
thisdir = class/Facades/System.Linq
SUBDIRS =
include $(MCS_BUILD_DIR)/rules.make
LIBRARY_SUBDIR = Facades
LIBRARY_INSTALL_DIR = $(mono_libdir)/mono/$(FRAMEWORK_VERSION)/Facades
LIBRARY = System.Linq.dll
KEY_FILE = ../../msfinal.pub
SIGN_FLAGS = /delaysign /keyfile:$(KEY_FILE) /nowarn:1616,1699
LIB_MCS_FLAGS = $(SIGN_FLAGS) /r:mscorlib /r:System.Core
PLATFORM_DEBUG_FLAGS =
NO_TEST = yes
include $(MCS_BUILD_DIR)/library.make
| edwinspire/VSharp | class/Facades/System.Linq/Makefile | Makefile | lgpl-3.0 | 469 |
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2014 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 12.10Release
// Tag = $Name$
////////////////////////////////////////////////////////////////////////////////
package com.garmin.fit;
public class EventMesg extends Mesg implements MesgWithEvent {
protected static final Mesg eventMesg;
static {
int field_index = 0;
int subfield_index = 0;
// event
eventMesg = new Mesg("event", MesgNum.EVENT);
eventMesg.addField(new Field("timestamp", 253, 134, 1, 0, "s", false));
field_index++;
eventMesg.addField(new Field("event", 0, 0, 1, 0, "", false));
field_index++;
eventMesg.addField(new Field("event_type", 1, 0, 1, 0, "", false));
field_index++;
eventMesg.addField(new Field("data16", 2, 132, 1, 0, "", false));
eventMesg.fields.get(field_index).components.add(new FieldComponent(3, false, 16, 1, 0)); // data
field_index++;
eventMesg.addField(new Field("data", 3, 134, 1, 0, "", false));
subfield_index = 0;
eventMesg.fields.get(field_index).subFields.add(new SubField("timer_trigger", 0, 1, 0, ""));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 0);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("course_point_index", 132, 1, 0, ""));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 10);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("battery_level", 132, 1000, 0, "V"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 11);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("virtual_partner_speed", 132, 1000, 0, "m/s"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 12);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("hr_high_alert", 2, 1, 0, "bpm"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 13);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("hr_low_alert", 2, 1, 0, "bpm"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 14);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("speed_high_alert", 132, 1000, 0, "m/s"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 15);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("speed_low_alert", 132, 1000, 0, "m/s"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 16);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("cad_high_alert", 132, 1, 0, "rpm"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 17);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("cad_low_alert", 132, 1, 0, "rpm"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 18);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("power_high_alert", 132, 1, 0, "watts"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 19);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("power_low_alert", 132, 1, 0, "watts"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 20);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("time_duration_alert", 134, 1000, 0, "s"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 23);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("distance_duration_alert", 134, 100, 0, "m"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 24);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("calorie_duration_alert", 134, 1, 0, "calories"));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 25);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("fitness_equipment_state", 0, 1, 0, ""));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 27);
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("sport_point", 134, 1, 0, ""));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 33);
eventMesg.fields.get(field_index).subFields.get(subfield_index).addComponent(new FieldComponent(7, false, 16, 1, 0));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addComponent(new FieldComponent(8, false, 16, 1, 0));
subfield_index++;
eventMesg.fields.get(field_index).subFields.add(new SubField("gear_change_data", 134, 1, 0, ""));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 42);
eventMesg.fields.get(field_index).subFields.get(subfield_index).addMap(0, 43);
eventMesg.fields.get(field_index).subFields.get(subfield_index).addComponent(new FieldComponent(11, false, 8, 1, 0));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addComponent(new FieldComponent(12, false, 8, 1, 0));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addComponent(new FieldComponent(9, false, 8, 1, 0));
eventMesg.fields.get(field_index).subFields.get(subfield_index).addComponent(new FieldComponent(10, false, 8, 1, 0));
subfield_index++;
field_index++;
eventMesg.addField(new Field("event_group", 4, 2, 1, 0, "", false));
field_index++;
eventMesg.addField(new Field("score", 7, 132, 1, 0, "", false));
field_index++;
eventMesg.addField(new Field("opponent_score", 8, 132, 1, 0, "", false));
field_index++;
eventMesg.addField(new Field("front_gear_num", 9, 10, 1, 0, "", false));
field_index++;
eventMesg.addField(new Field("front_gear", 10, 10, 1, 0, "", false));
field_index++;
eventMesg.addField(new Field("rear_gear_num", 11, 10, 1, 0, "", false));
field_index++;
eventMesg.addField(new Field("rear_gear", 12, 10, 1, 0, "", false));
field_index++;
}
public EventMesg() {
super(Factory.createMesg(MesgNum.EVENT));
}
public EventMesg(final Mesg mesg) {
super(mesg);
}
/**
* Get timestamp field
* Units: s
*
* @return timestamp
*/
public DateTime getTimestamp() {
return timestampToDateTime(getFieldLongValue(253, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD));
}
/**
* Set timestamp field
* Units: s
*
* @param timestamp
*/
public void setTimestamp(DateTime timestamp) {
setFieldValue(253, 0, timestamp.getTimestamp(), Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get event field
*
* @return event
*/
public Event getEvent() {
Short value = getFieldShortValue(0, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
if (value == null)
return null;
return Event.getByValue(value);
}
/**
* Set event field
*
* @param event
*/
public void setEvent(Event event) {
setFieldValue(0, 0, event.value, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get event_type field
*
* @return event_type
*/
public EventType getEventType() {
Short value = getFieldShortValue(1, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
if (value == null)
return null;
return EventType.getByValue(value);
}
/**
* Set event_type field
*
* @param eventType
*/
public void setEventType(EventType eventType) {
setFieldValue(1, 0, eventType.value, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get data16 field
*
* @return data16
*/
public Integer getData16() {
return getFieldIntegerValue(2, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Set data16 field
*
* @param data16
*/
public void setData16(Integer data16) {
setFieldValue(2, 0, data16, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get data field
*
* @return data
*/
public Long getData() {
return getFieldLongValue(3, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Set data field
*
* @param data
*/
public void setData(Long data) {
setFieldValue(3, 0, data, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get timer_trigger field
*
* @return timer_trigger
*/
public TimerTrigger getTimerTrigger() {
Short value = getFieldShortValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_TIMER_TRIGGER);
if (value == null)
return null;
return TimerTrigger.getByValue(value);
}
/**
* Set timer_trigger field
*
* @param timerTrigger
*/
public void setTimerTrigger(TimerTrigger timerTrigger) {
setFieldValue(3, 0, timerTrigger.value, Profile.SubFields.EVENT_MESG_DATA_FIELD_TIMER_TRIGGER);
}
/**
* Get course_point_index field
*
* @return course_point_index
*/
public Integer getCoursePointIndex() {
return getFieldIntegerValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_COURSE_POINT_INDEX);
}
/**
* Set course_point_index field
*
* @param coursePointIndex
*/
public void setCoursePointIndex(Integer coursePointIndex) {
setFieldValue(3, 0, coursePointIndex, Profile.SubFields.EVENT_MESG_DATA_FIELD_COURSE_POINT_INDEX);
}
/**
* Get battery_level field
* Units: V
*
* @return battery_level
*/
public Float getBatteryLevel() {
return getFieldFloatValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_BATTERY_LEVEL);
}
/**
* Set battery_level field
* Units: V
*
* @param batteryLevel
*/
public void setBatteryLevel(Float batteryLevel) {
setFieldValue(3, 0, batteryLevel, Profile.SubFields.EVENT_MESG_DATA_FIELD_BATTERY_LEVEL);
}
/**
* Get virtual_partner_speed field
* Units: m/s
*
* @return virtual_partner_speed
*/
public Float getVirtualPartnerSpeed() {
return getFieldFloatValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_VIRTUAL_PARTNER_SPEED);
}
/**
* Set virtual_partner_speed field
* Units: m/s
*
* @param virtualPartnerSpeed
*/
public void setVirtualPartnerSpeed(Float virtualPartnerSpeed) {
setFieldValue(3, 0, virtualPartnerSpeed, Profile.SubFields.EVENT_MESG_DATA_FIELD_VIRTUAL_PARTNER_SPEED);
}
/**
* Get hr_high_alert field
* Units: bpm
*
* @return hr_high_alert
*/
public Short getHrHighAlert() {
return getFieldShortValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_HR_HIGH_ALERT);
}
/**
* Set hr_high_alert field
* Units: bpm
*
* @param hrHighAlert
*/
public void setHrHighAlert(Short hrHighAlert) {
setFieldValue(3, 0, hrHighAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_HR_HIGH_ALERT);
}
/**
* Get hr_low_alert field
* Units: bpm
*
* @return hr_low_alert
*/
public Short getHrLowAlert() {
return getFieldShortValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_HR_LOW_ALERT);
}
/**
* Set hr_low_alert field
* Units: bpm
*
* @param hrLowAlert
*/
public void setHrLowAlert(Short hrLowAlert) {
setFieldValue(3, 0, hrLowAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_HR_LOW_ALERT);
}
/**
* Get speed_high_alert field
* Units: m/s
*
* @return speed_high_alert
*/
public Float getSpeedHighAlert() {
return getFieldFloatValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_SPEED_HIGH_ALERT);
}
/**
* Set speed_high_alert field
* Units: m/s
*
* @param speedHighAlert
*/
public void setSpeedHighAlert(Float speedHighAlert) {
setFieldValue(3, 0, speedHighAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_SPEED_HIGH_ALERT);
}
/**
* Get speed_low_alert field
* Units: m/s
*
* @return speed_low_alert
*/
public Float getSpeedLowAlert() {
return getFieldFloatValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_SPEED_LOW_ALERT);
}
/**
* Set speed_low_alert field
* Units: m/s
*
* @param speedLowAlert
*/
public void setSpeedLowAlert(Float speedLowAlert) {
setFieldValue(3, 0, speedLowAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_SPEED_LOW_ALERT);
}
/**
* Get cad_high_alert field
* Units: rpm
*
* @return cad_high_alert
*/
public Integer getCadHighAlert() {
return getFieldIntegerValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_CAD_HIGH_ALERT);
}
/**
* Set cad_high_alert field
* Units: rpm
*
* @param cadHighAlert
*/
public void setCadHighAlert(Integer cadHighAlert) {
setFieldValue(3, 0, cadHighAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_CAD_HIGH_ALERT);
}
/**
* Get cad_low_alert field
* Units: rpm
*
* @return cad_low_alert
*/
public Integer getCadLowAlert() {
return getFieldIntegerValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_CAD_LOW_ALERT);
}
/**
* Set cad_low_alert field
* Units: rpm
*
* @param cadLowAlert
*/
public void setCadLowAlert(Integer cadLowAlert) {
setFieldValue(3, 0, cadLowAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_CAD_LOW_ALERT);
}
/**
* Get power_high_alert field
* Units: watts
*
* @return power_high_alert
*/
public Integer getPowerHighAlert() {
return getFieldIntegerValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_POWER_HIGH_ALERT);
}
/**
* Set power_high_alert field
* Units: watts
*
* @param powerHighAlert
*/
public void setPowerHighAlert(Integer powerHighAlert) {
setFieldValue(3, 0, powerHighAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_POWER_HIGH_ALERT);
}
/**
* Get power_low_alert field
* Units: watts
*
* @return power_low_alert
*/
public Integer getPowerLowAlert() {
return getFieldIntegerValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_POWER_LOW_ALERT);
}
/**
* Set power_low_alert field
* Units: watts
*
* @param powerLowAlert
*/
public void setPowerLowAlert(Integer powerLowAlert) {
setFieldValue(3, 0, powerLowAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_POWER_LOW_ALERT);
}
/**
* Get time_duration_alert field
* Units: s
*
* @return time_duration_alert
*/
public Float getTimeDurationAlert() {
return getFieldFloatValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_TIME_DURATION_ALERT);
}
/**
* Set time_duration_alert field
* Units: s
*
* @param timeDurationAlert
*/
public void setTimeDurationAlert(Float timeDurationAlert) {
setFieldValue(3, 0, timeDurationAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_TIME_DURATION_ALERT);
}
/**
* Get distance_duration_alert field
* Units: m
*
* @return distance_duration_alert
*/
public Float getDistanceDurationAlert() {
return getFieldFloatValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_DISTANCE_DURATION_ALERT);
}
/**
* Set distance_duration_alert field
* Units: m
*
* @param distanceDurationAlert
*/
public void setDistanceDurationAlert(Float distanceDurationAlert) {
setFieldValue(3, 0, distanceDurationAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_DISTANCE_DURATION_ALERT);
}
/**
* Get calorie_duration_alert field
* Units: calories
*
* @return calorie_duration_alert
*/
public Long getCalorieDurationAlert() {
return getFieldLongValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_CALORIE_DURATION_ALERT);
}
/**
* Set calorie_duration_alert field
* Units: calories
*
* @param calorieDurationAlert
*/
public void setCalorieDurationAlert(Long calorieDurationAlert) {
setFieldValue(3, 0, calorieDurationAlert, Profile.SubFields.EVENT_MESG_DATA_FIELD_CALORIE_DURATION_ALERT);
}
/**
* Get fitness_equipment_state field
*
* @return fitness_equipment_state
*/
public FitnessEquipmentState getFitnessEquipmentState() {
Short value = getFieldShortValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_FITNESS_EQUIPMENT_STATE);
if (value == null)
return null;
return FitnessEquipmentState.getByValue(value);
}
/**
* Set fitness_equipment_state field
*
* @param fitnessEquipmentState
*/
public void setFitnessEquipmentState(FitnessEquipmentState fitnessEquipmentState) {
setFieldValue(3, 0, fitnessEquipmentState.value, Profile.SubFields.EVENT_MESG_DATA_FIELD_FITNESS_EQUIPMENT_STATE);
}
/**
* Get sport_point field
*
* @return sport_point
*/
public Long getSportPoint() {
return getFieldLongValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_SPORT_POINT);
}
/**
* Set sport_point field
*
* @param sportPoint
*/
public void setSportPoint(Long sportPoint) {
setFieldValue(3, 0, sportPoint, Profile.SubFields.EVENT_MESG_DATA_FIELD_SPORT_POINT);
}
/**
* Get gear_change_data field
*
* @return gear_change_data
*/
public Long getGearChangeData() {
return getFieldLongValue(3, 0, Profile.SubFields.EVENT_MESG_DATA_FIELD_GEAR_CHANGE_DATA);
}
/**
* Set gear_change_data field
*
* @param gearChangeData
*/
public void setGearChangeData(Long gearChangeData) {
setFieldValue(3, 0, gearChangeData, Profile.SubFields.EVENT_MESG_DATA_FIELD_GEAR_CHANGE_DATA);
}
/**
* Get event_group field
*
* @return event_group
*/
public Short getEventGroup() {
return getFieldShortValue(4, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Set event_group field
*
* @param eventGroup
*/
public void setEventGroup(Short eventGroup) {
setFieldValue(4, 0, eventGroup, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get score field
* Comment: Do not populate directly. Autogenerated by decoder for sport_point subfield components
*
* @return score
*/
public Integer getScore() {
return getFieldIntegerValue(7, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Set score field
* Comment: Do not populate directly. Autogenerated by decoder for sport_point subfield components
*
* @param score
*/
public void setScore(Integer score) {
setFieldValue(7, 0, score, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get opponent_score field
* Comment: Do not populate directly. Autogenerated by decoder for sport_point subfield components
*
* @return opponent_score
*/
public Integer getOpponentScore() {
return getFieldIntegerValue(8, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Set opponent_score field
* Comment: Do not populate directly. Autogenerated by decoder for sport_point subfield components
*
* @param opponentScore
*/
public void setOpponentScore(Integer opponentScore) {
setFieldValue(8, 0, opponentScore, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get front_gear_num field
* Comment: Do not populate directly. Autogenerated by decoder for gear_change subfield components. Front gear number. 1 is innermost.
*
* @return front_gear_num
*/
public Short getFrontGearNum() {
return getFieldShortValue(9, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Set front_gear_num field
* Comment: Do not populate directly. Autogenerated by decoder for gear_change subfield components. Front gear number. 1 is innermost.
*
* @param frontGearNum
*/
public void setFrontGearNum(Short frontGearNum) {
setFieldValue(9, 0, frontGearNum, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get front_gear field
* Comment: Do not populate directly. Autogenerated by decoder for gear_change subfield components. Number of front teeth.
*
* @return front_gear
*/
public Short getFrontGear() {
return getFieldShortValue(10, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Set front_gear field
* Comment: Do not populate directly. Autogenerated by decoder for gear_change subfield components. Number of front teeth.
*
* @param frontGear
*/
public void setFrontGear(Short frontGear) {
setFieldValue(10, 0, frontGear, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get rear_gear_num field
* Comment: Do not populate directly. Autogenerated by decoder for gear_change subfield components. Rear gear number. 1 is innermost.
*
* @return rear_gear_num
*/
public Short getRearGearNum() {
return getFieldShortValue(11, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Set rear_gear_num field
* Comment: Do not populate directly. Autogenerated by decoder for gear_change subfield components. Rear gear number. 1 is innermost.
*
* @param rearGearNum
*/
public void setRearGearNum(Short rearGearNum) {
setFieldValue(11, 0, rearGearNum, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Get rear_gear field
* Comment: Do not populate directly. Autogenerated by decoder for gear_change subfield components. Number of rear teeth.
*
* @return rear_gear
*/
public Short getRearGear() {
return getFieldShortValue(12, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
/**
* Set rear_gear field
* Comment: Do not populate directly. Autogenerated by decoder for gear_change subfield components. Number of rear teeth.
*
* @param rearGear
*/
public void setRearGear(Short rearGear) {
setFieldValue(12, 0, rearGear, Fit.SUBFIELD_INDEX_MAIN_FIELD);
}
}
| saschaiseli/opentrainingcenter_e4 | com.garmin.fit/src/com/garmin/fit/EventMesg.java | Java | lgpl-3.0 | 23,543 |
#ifndef KINECTPLUGIN_H
#define KINECTPLUGIN_H
#include <QObject>
#include <fugio/core/uuid.h>
#include <fugio/global_interface.h>
#include <fugio/plugin_interface.h>
class KinectPlugin : public QObject, public fugio::PluginInterface
{
Q_OBJECT
Q_INTERFACES( fugio::PluginInterface )
Q_PLUGIN_METADATA( IID "com.bigfug.fugio.kinect.plugin" )
public:
explicit KinectPlugin( void );
virtual ~KinectPlugin( void );
//-------------------------------------------------------------------------
// fugio::PluginInterface
virtual InitResult initialise( fugio::GlobalInterface *pApp, bool pLastChance );
virtual void deinitialise( void );
//-------------------------------------------------------------------------
private:
fugio::GlobalInterface *mApp;
fugio::ClassEntryList mNodeEntries;
fugio::ClassEntryList mPinEntries;
};
#endif // KINECTPLUGIN_H
| bigfug/Fugio | plugins/Kinect/kinectplugin.h | C | lgpl-3.0 | 870 |
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_building_player_player_garage_tatooine_style_01 = object_building_player_shared_player_garage_tatooine_style_01:new {
lotSize = 0,
baseMaintenanceRate = 0,
allowedZones = {"dantooine", "lok", "tatooine"},
gameObjectType = 4102,
planetMapCategory = "garage",
cityRankRequired = 2,
abilityRequired = "place_garage",
uniqueStructure = true,
cityMaintenanceBase = 20000,
zoneComponent = "StructureZoneComponent",
length = 5,
width = 5,
childObjects = {
{templateFile = "object/tangible/terminal/terminal_player_structure_nosnap_mini.iff", x = 2.90, z = 1, y = 2, ox = 0, oy = 0, oz = 0, ow = 1, cellid = -1, containmentType = -1}
}
}
ObjectTemplates:addTemplate(object_building_player_player_garage_tatooine_style_01, "object/building/player/player_garage_tatooine_style_01.iff")
| kidaa/Awakening-Core3 | bin/scripts/object/building/player/player_garage_tatooine_style_01.lua | Lua | lgpl-3.0 | 2,801 |
/*
* MoXie (SysTem128@GMail.Com) 2009-2-1 15:59:59
*
* Copyright © 2008-2009 Zoeey.Org
* Code license: GNU Lesser General Public License Version 3
* http://www.gnu.org/licenses/lgpl-3.0.txt
*/
package org.zoeey.validator.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 声明注释为验证器
* @author MoXie(SysTem128@GMail.Com)
*/
@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Vali {
}
| BGCX261/zoeey-hg-to-git | src/main/java/org/zoeey/validator/annotations/Vali.java | Java | lgpl-3.0 | 589 |
/// <reference name="MicrosoftAjax.debug.js" />
/// <reference path="../ExtenderBase/BaseScripts.js" />
/// <reference path="../Common/Common.js" />
(function() {
var scriptName = "ExtendedCascadingDropDown";
function execute() {
Type.registerNamespace('Sys.Extended.UI');
Sys.Extended.UI.CascadingDropDownSelectionChangedEventArgs = function(oldValue, newValue) {
/// <summary>
/// Event arguments used when the selectionChanged event is raised
/// </summary>
/// <param name="oldValue" type="String" mayBeNull="true">
/// Previous selection
/// </param>
/// <param name="newValue" type="String" mayBeNull="true">
/// New selection
/// </param>
Sys.Extended.UI.CascadingDropDownSelectionChangedEventArgs.initializeBase(this);
this._oldValue = oldValue;
this._newValue = newValue;
}
Sys.Extended.UI.CascadingDropDownSelectionChangedEventArgs.prototype = {
get_oldValue : function() {
/// <value type="String" mayBeNull="true">
/// Previous selection
/// </value>
return this._oldValue;
},
get_newValue : function() {
/// <value type="String" mayBeNull="true">
/// New selection
/// </value>
return this._newValue;
}
}
Sys.Extended.UI.CascadingDropDownSelectionChangedEventArgs.registerClass('Sys.Extended.UI.CascadingDropDownSelectionChangedEventArgs', Sys.EventArgs);
Sys.Extended.UI.CascadingDropDownBehavior = function(e) {
/// <summary>
/// The CascadingDropDownBehavior is used to populate drop downs with values from a web service
/// </summary>
/// <param name="e" type="Sys.UI.DomElement" domElement="true">
/// The DOM element the behavior is associated with
/// </param>
Sys.Extended.UI.CascadingDropDownBehavior.initializeBase(this, [e]);
// Properties
this._parentControlID = null;
this._category = null;
this._promptText = null;
this._loadingText = null;
this._promptValue = null;
this._emptyValue = null;
this._emptyText = null;
// Path to the web service, defaulting to a page method
this._servicePath = location.pathname;
// Name of the web method
this._serviceMethod = null;
// User/page specific context provided to the web method
this._contextKey = null;
// Whether or not the the user/page specific context should be used
this._useContextKey = false;
// Variables
this._parentElement = null;
this._changeHandler = null;
this._parentChangeHandler = null;
this._lastParentValues = null;
this._selectedValue = null;
}
Sys.Extended.UI.CascadingDropDownBehavior.prototype = {
initialize : function() {
/// <summary>
/// Initialize the behavior
/// </summary>
/// <returns />
Sys.Extended.UI.CascadingDropDownBehavior.callBaseMethod(this, 'initialize');
$common.prepareHiddenElementForATDeviceUpdate();
var e = this.get_element();
// Clear any items that may have been put there for server side convenience
this._clearItems();
e.CascadingDropDownCategory = this._category;
// Attach change handler to self
this._changeHandler = Function.createDelegate(this, this._onChange);
$addHandler(e, "change",this._changeHandler);
if (this._parentControlID) {
// Set properties on element so that children controls (if any) can have easy access
this._parentElement = $get(this._parentControlID);
// Attach change handler to parent
if (!this._parentElement) {
Sys.Debug.fail(String.format(Sys.Extended.UI.Resources.CascadingDropDown_NoParentElement, this._parentControlID));
}
if (this._parentElement) {
e.CascadingDropDownParentControlID = this._parentControlID;
this._parentChangeHandler = Function.createDelegate(this, this._onParentChange);
$addHandler(this._parentElement, "change", this._parentChangeHandler);
if (!this._parentElement.childDropDown) {
this._parentElement.childDropDown = new Array();
}
this._parentElement.childDropDown.push(this);
}
}
// Simulate parent change to populate self, even if no parent exists.
this._onParentChange(null, true);
},
dispose : function() {
/// <summary>
/// Dispose the behavior
/// </summary>
/// <returns />
var e = this.get_element();
// Detach change handler for self
if (this._changeHandler) {
$removeHandler(e, "change", this._changeHandler);
this._changeHandler = null;
}
// Detach change handler for parent
if (this._parentChangeHandler) {
if (this._parentElement) {
$removeHandler(this._parentElement, "change", this._parentChangeHandler);
}
this._parentChangeHandler = null;
}
Sys.Extended.UI.CascadingDropDownBehavior.callBaseMethod(this, 'dispose');
},
_clearItems : function() {
/// <summary>
/// Clear the items from the drop down
/// </summary>
/// <returns />
var e = this.get_element();
while (0 < e.options.length) {
e.remove(0);
}
},
_isPopulated : function() {
/// <summary>
/// Determine whether the drop down has any items
/// </summary>
/// <returns type="Boolean">
/// Whether the drop down has any items
/// </returns>
var items = this.get_element().options.length;
if (this._promptText) {
return items > 1;
} else {
return items > 0;
}
},
_setOptions : function(list, inInit, gettingList) {
/// <summary>
/// Set the contents of the DropDownList to the specified list
/// </summary>
/// <param name="list" mayBeNull="true" elementType="Object">
/// Array of options (where each option has name and value properties)
/// </param>
/// <param name="inInit" type="Boolean" optional="true">
/// Whether this is being called from the initialize method
/// </param>
/// <param name="gettingList" type="Boolean" optional="true">
/// Whether we are fetching the list of options from the web service
/// </param>
/// <returns />
if (!this.get_isInitialized()) {
return;
}
var e = this.get_element();
// Remove existing contents
this._clearItems();
// Populate prompt text (if available)
var headerText;
var headerValue = "";
if (gettingList && this._loadingText) {
headerText = this._loadingText;
if ( this._selectedValue) {
headerValue = this._selectedValue;
}
} else if (!gettingList && list && (0 == list.length) && (null != this._emptyText)) {
headerText = this._emptyText;
if (this._emptyValue) {
headerValue = this._emptyValue;
}
} else if (this._promptText) {
headerText = this._promptText;
if (this._promptValue) {
headerValue = this._promptValue;
}
}
if (headerText) {
var optionElement = new Option(headerText, headerValue);
e.options[e.options.length] = optionElement;
}
// Add each item to the DropDownList, selecting the previously selected item
var selectedValueOption = null;
var defaultIndex = -1;
if (list) {
for (i = 0 ; i < list.length ; i++) {
var listItemName = list[i].name;
var listItemValue = list[i].value;
if (list[i].isDefaultValue) {
defaultIndex = i;
if (this._promptText) {
// bump the index if there's a prompt item in the list.
//
defaultIndex++;
}
}
var optionElement = new Option(listItemName, listItemValue);
if (listItemValue == this._selectedValue) {
selectedValueOption = optionElement;
}
e.options[e.options.length] = optionElement;
}
if (selectedValueOption) {
selectedValueOption.selected = true;
}
}
// if we didn't match the selected value, and we found a default
// item, select that one.
//
if (selectedValueOption) {
// Call set_SelectedValue to store the text as well
this.set_SelectedValue(e.options[e.selectedIndex].value, e.options[e.selectedIndex].text);
} else if (!selectedValueOption && defaultIndex != -1) {
e.options[defaultIndex].selected = true;
this.set_SelectedValue(e.options[defaultIndex].value, e.options[defaultIndex].text);
} else if (!inInit && !selectedValueOption && !gettingList && !this._promptText && (e.options.length > 0)) {
// If no prompt text or default item, select the first item
this.set_SelectedValue(e.options[0].value, e.options[0].text);
} else if (!inInit && !selectedValueOption && !gettingList) {
this.set_SelectedValue('', '');
}
if (e.childDropDown && !gettingList) {
for(i = 0; i < e.childDropDown.length; i++) {
e.childDropDown[i]._onParentChange();
}
}
else {
if (list && (Sys.Browser.agent !== Sys.Browser.Safari) && (Sys.Browser.agent !== Sys.Browser.Opera)) {
// Fire the onchange event for the control to notify any listeners of the change
if (document.createEvent) {
var onchangeEvent = document.createEvent('HTMLEvents');
onchangeEvent.initEvent('change', true, false);
this.get_element().dispatchEvent(onchangeEvent);
} else if( document.createEventObject ) {
this.get_element().fireEvent('onchange');
}
}
}
// Disable the control if loading/prompt text is present and an empty list was populated
if (this._loadingText || this._promptText || this._emptyText) {
e.disabled = !list || (0 == list.length);
}
this.raisePopulated(Sys.EventArgs.Empty);
},
_onChange : function() {
/// <summary>
/// Handler for the drop down's change event
/// </summary>
/// <returns />
if (!this._isPopulated()) {
return;
}
var e = this.get_element();
// Record the selected value in the client state
if ((-1 != e.selectedIndex) && !(this._promptText && (0 == e.selectedIndex))) {
this.set_SelectedValue(e.options[e.selectedIndex].value, e.options[e.selectedIndex].text);
} else {
this.set_SelectedValue('', '');
}
},
_onParentChange : function(evt, inInit) {
/// <summary>
/// Handler for the parent drop down's change event
/// </summary>
/// <param name="evt" type="Object">
/// Set by the browser when called as an event handler (unused here)
/// </param>
/// <param name="inInit" type="Boolean">
/// Whether this is being called from the initialize method
/// </param>
/// <returns />
var e = this.get_element();
// Create the known category/value pairs string for sending to the helper web service
// Follow parent pointers so that the complete state can be sent
// Format: 'name1:value1;name2:value2;...'
var knownCategoryValues = '';
var parentControlID = this._parentControlID;
while (parentControlID) {
var parentElement = $get(parentControlID);
if (parentElement && (-1 != parentElement.selectedIndex)){
var selectedValue = parentElement.options[parentElement.selectedIndex].value;
if (selectedValue && selectedValue != "") {
knownCategoryValues = parentElement.CascadingDropDownCategory + ':' + selectedValue + ';' + knownCategoryValues;
parentControlID = parentElement.CascadingDropDownParentControlID;
continue;
}
}
break;
}
if (knownCategoryValues != '' && this._lastParentValues == knownCategoryValues) {
return;
}
this._lastParentValues = knownCategoryValues;
// we have a parent but it doesn't have a valid value
//
if (knownCategoryValues == '' && this._parentControlID) {
this._setOptions(null, inInit);
return;
}
// Show the loading text (if any)
this._setOptions(null, inInit, true);
if (this._servicePath && this._serviceMethod) {
// Raise the populating event and optionally cancel the web service invocation
var eventArgs = new Sys.CancelEventArgs();
this.raisePopulating(eventArgs);
if (eventArgs.get_cancel()) {
return;
}
// Create the service parameters and optionally add the context parameter
// (thereby determining which method signature we're expecting...)
var params = { knownCategoryValues:knownCategoryValues, category:this._category };
if (this._useContextKey) {
params.contextKey = this._contextKey;
}
// Call the helper web service
Sys.Net.WebServiceProxy.invoke(this._servicePath, this._serviceMethod, false, params,
Function.createDelegate(this, this._onMethodComplete), Function.createDelegate(this, this._onMethodError));
$common.updateFormToRefreshATDeviceBuffer();
}
},
_onMethodComplete : function(result, userContext, methodName) {
// Success, update the DropDownList
this._setOptions(result);
},
_onMethodError : function(webServiceError, userContext, methodName) {
// Indicate failure
if (webServiceError.get_timedOut()) {
this._setOptions( [ this._makeNameValueObject(Sys.Extended.UI.Resources.CascadingDropDown_MethodTimeout) ] );
} else {
this._setOptions( [ this._makeNameValueObject(String.format(Sys.Extended.UI.Resources.CascadingDropDown_MethodError, webServiceError.get_statusCode())) ] );
}
},
_makeNameValueObject : function(message) {
/// <summary>
/// Create an object with name and value properties set to the provided message
/// </summary>
/// <param name="message" type="String">
/// Message
/// </param>
/// <returns type="Object">
/// Object with name and value properties set to the message
/// </returns>
return { 'name': message, 'value': message };
},
get_ParentControlID : function() {
/// <value type="String">
/// ID of the parent drop down in a hierarchy of drop downs
/// </value>
return this._parentControlID;
},
set_ParentControlID : function(value) {
if (this._parentControlID != value) {
this._parentControlID = value;
this.raisePropertyChanged('ParentControlID');
}
},
get_Category : function() {
/// <value type="String">
/// Category of this drop down
/// </value>
return this._category;
},
set_Category : function(value) {
if (this._category != value) {
this._category = value;
this.raisePropertyChanged('Category');
}
},
get_PromptText : function() {
/// <value type="String">
/// Prompt text displayed as the first entry in the drop down
/// </value>
return this._promptText;
},
set_PromptText : function(value) {
if (this._promptText != value) {
this._promptText = value;
this.raisePropertyChanged('PromptText');
}
},
get_PromptValue : function() {
/// <value type="String">
/// Value for the option displayed by a DropDownList showing the PromptText
/// </value>
return this._promptValue;
},
set_PromptValue : function(value) {
if (this._promptValue != value) {
this._promptValue = value;
this.raisePropertyChanged('PromptValue');
}
},
get_EmptyText : function() {
/// <value type="String">
/// Text for the option displayed when the list is empty
/// </value>
return this._emptyText;
},
set_EmptyText : function(value) {
if (this._emptyText != value) {
this._emptyText = value;
this.raisePropertyChanged('EmptyText');
}
},
get_EmptyValue : function() {
/// <value type="String">
/// Value for the option displayed when the list is empty
/// </value>
return this._emptyValue;
},
set_EmptyValue : function(value) {
if (this._emptyValue != value) {
this._emptyValue = value;
this.raisePropertyChanged('EmptyValue');
}
},
get_LoadingText : function() {
/// <value type="String">
/// Loading text to to be displayed when getting the drop down's values from the web service
/// </value>
return this._loadingText;
},
set_LoadingText : function(value) {
if (this._loadingText != value) {
this._loadingText = value;
this.raisePropertyChanged('LoadingText');
}
},
get_SelectedValue : function() {
/// <value type="String">
/// Selected value of the drop down
/// </value>
return this._selectedValue;
},
set_SelectedValue : function(value, text) {
if (this._selectedValue != value) {
if (!text) {
// Initial population by server; look for "value:::text" pair
var i = value.indexOf(':::');
if (-1 != i) {
text = value.slice(i + 3);
value = value.slice(0, i);
}
}
var oldValue = this._selectedValue;
this._selectedValue = value;
this.raisePropertyChanged('SelectedValue');
this.raiseSelectionChanged(new Sys.Extended.UI.CascadingDropDownSelectionChangedEventArgs(oldValue, value));
}
Sys.Extended.UI.CascadingDropDownBehavior.callBaseMethod(this, 'set_ClientState', [ this._selectedValue+':::'+text ]);
},
get_ServicePath : function() {
/// <value type="String" mayBeNull="true">
/// Path to the web service
/// </value>
return this._servicePath;
},
set_ServicePath : function(value) {
if (this._servicePath != value) {
this._servicePath = value;
this.raisePropertyChanged('ServicePath');
}
},
get_ServiceMethod : function() {
/// <value type="String">
/// Name of the method to invoke on the web service
/// </value>
return this._serviceMethod;
},
set_ServiceMethod : function(value) {
if (this._serviceMethod != value) {
this._serviceMethod = value;
this.raisePropertyChanged('ServiceMethod');
}
},
get_contextKey : function() {
/// <value type="String" mayBeNull="true">
/// User/page specific context provided to an optional overload of the
/// web method described by ServiceMethod/ServicePath. If the context
/// key is used, it should have the same signature with an additional
/// parameter named contextKey of type string.
/// </value>
return this._contextKey;
},
set_contextKey : function(value) {
if (this._contextKey != value) {
this._contextKey = value;
this.set_useContextKey(true);
this.raisePropertyChanged('contextKey');
}
},
get_useContextKey : function() {
/// <value type="Boolean">
/// Whether or not the ContextKey property should be used. This will be
/// automatically enabled if the ContextKey property is ever set
/// (on either the client or the server). If the context key is used,
/// it should have the same signature with an additional parameter
/// named contextKey of type string.
/// </value>
return this._useContextKey;
},
set_useContextKey : function(value) {
if (this._useContextKey != value) {
this._useContextKey = value;
this.raisePropertyChanged('useContextKey');
}
},
add_selectionChanged : function(handler) {
/// <summary>
/// Add an event handler for the selectionChanged event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().addHandler('selectionChanged', handler);
},
remove_selectionChanged : function(handler) {
/// <summary>
/// Remove an event handler from the selectionChanged event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().removeHandler('selectionChanged', handler);
},
raiseSelectionChanged : function(eventArgs) {
/// <summary>
/// Raise the selectionChanged event
/// </summary>
/// <param name="eventArgs" type="Sys.Extended.UI.CascadingDropDownSelectionChangedEventArgs" mayBeNull="false">
/// Event arguments for the selectionChanged event
/// </param>
/// <returns />
var handler = this.get_events().getHandler('selectionChanged');
if (handler) {
handler(this, eventArgs);
}
},
add_populating : function(handler) {
/// <summary>
/// Add an event handler for the populating event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().addHandler('populating', handler);
},
remove_populating : function(handler) {
/// <summary>
/// Remove an event handler from the populating event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().removeHandler('populating', handler);
},
raisePopulating : function(eventArgs) {
/// <summary>
/// Raise the populating event
/// </summary>
/// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false">
/// Event arguments for the populating event
/// </param>
/// <returns />
/// <remarks>
/// The populating event can be used to provide custom data to
/// CascadingDropDown instead of using a web service. Just cancel the
/// event (using the CancelEventArgs) and pass your own data to the
/// _setOptions method.
/// </remarks>
var handler = this.get_events().getHandler('populating');
if (handler) {
handler(this, eventArgs);
}
},
add_populated : function(handler) {
/// <summary>
/// Add an event handler for the populated event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().addHandler('populated', handler);
},
remove_populated : function(handler) {
/// <summary>
/// Remove an event handler from the populated event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().removeHandler('populated', handler);
},
raisePopulated : function(eventArgs) {
/// <summary>
/// Raise the populated event
/// </summary>
/// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false">
/// Event arguments for the populated event
/// </param>
/// <returns />
var handler = this.get_events().getHandler('populated');
if (handler) {
handler(this, eventArgs);
}
}
}
Sys.Extended.UI.CascadingDropDownBehavior.registerClass('Sys.Extended.UI.CascadingDropDownBehavior', Sys.Extended.UI.BehaviorBase);
Sys.registerComponent(Sys.Extended.UI.CascadingDropDownBehavior, { name: "cascadingDropDown" });
// getDescriptor : function() {
// var td = Sys.Extended.UI.CascadingDropDownBehavior.callBaseMethod(this, 'getDescriptor');
// // Add custom properties
// td.addProperty('ParentControlID', String);
// td.addProperty('Category', String);
// td.addProperty('PromptText', String);
// td.addProperty('LoadingText', String);
// td.addProperty('ServicePath', String);
// td.addProperty('ServiceMethod', String);
// td.addProperty('SelectedValue', String);
// return td;
// },
} // execute
if (window.Sys && Sys.loader) {
Sys.loader.registerScript(scriptName, ["ExtendedBase", "ExtendedCommon", "WebServices"], execute);
}
else {
execute();
}
})();
| consumentor/Server | trunk/tools/AspNetAjaxLibraryBeta0911/Scripts/extended/CascadingDropDown/CascadingDropDownBehavior.debug.js | JavaScript | lgpl-3.0 | 26,967 |
// Copyright (c) 2012-2015, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Bytecoin.
//
// Bytecoin 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.
//
// Bytecoin 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 Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <mutex>
#include <condition_variable>
template <typename T>
class ObservableValueBase {
public:
ObservableValueBase(std::mutex& mtx, std::condition_variable& cv, const T defaultValue = T()) :
m_mutex(mtx), m_cv(cv), m_value(defaultValue), m_updated(false) {
}
void set(T value) {
std::lock_guard<std::mutex> lk(m_mutex);
m_value = value;
m_updated = true;
m_cv.notify_all();
}
void increment() {
std::lock_guard<std::mutex> lk(m_mutex);
++m_value;
m_updated = true;
m_cv.notify_all();
}
T get() {
std::lock_guard<std::mutex> lk(m_mutex);
return m_value;
}
bool waitFor(std::chrono::milliseconds ms, T& value) {
std::unique_lock<std::mutex> lk(m_mutex);
if (m_cv.wait_for(lk, ms, [this] { return m_updated; })) {
value = m_value;
m_updated = false;
return true;
}
return false;
}
T wait() {
std::unique_lock<std::mutex> lk(m_mutex);
m_cv.wait(lk, [this] { return m_updated; });
m_updated = false;
return m_value;
}
private:
std::mutex& m_mutex;
std::condition_variable& m_cv;
T m_value;
bool m_updated;
};
| papaLazzarou/dashcoin | tests/IntegrationTestLib/ObservableValue.h | C | lgpl-3.0 | 1,940 |
# -*- coding: utf-8 -*-
"""
Stores metadata about images which are built to encorporate changes to subuser images which are required in order to implement various permissions.
"""
#external imports
import os
import json
#internal imports
from subuserlib.classes.userOwnedObject import UserOwnedObject
from subuserlib.classes.fileBackedObject import FileBackedObject
class RuntimeCache(dict,UserOwnedObject,FileBackedObject):
def __init__(self,user,subuser):
self.__subuser = subuser
UserOwnedObject.__init__(self,user)
self.load()
def getPathToCurrentImagesRuntimeCacheDir(self):
return os.path.join(self.getUser().getConfig()["runtime-cache"],self.getSubuser().getImageId())
def getRuntimeCacheFilePath(self):
return os.path.join(self.getPathToCurrentImagesRuntimeCacheDir(),self.getSubuser().getPermissions().getHash()+".json")
def getSubuser(self):
return self.__subuser
def save(self):
try:
os.makedirs(self.getPathToCurrentImagesRuntimeCacheDir())
except OSError:
pass
with open(self.getRuntimeCacheFilePath(),mode='w') as runtimeCacheFileHandle:
json.dump(self,runtimeCacheFileHandle,indent=1,separators=(',',': '))
def reload(self):
self.save()
self.load()
def load(self):
if not self.getSubuser().getImageId():
raise NoRuntimeCacheForSubusersWhichDontHaveExistantImagesException("No runnable image for subuser found. Use\n\n $ subuser repair\n\nTo repair your instalation.")
runtimeCacheFilePath = self.getRuntimeCacheFilePath()
if os.path.exists(runtimeCacheFilePath):
with open(runtimeCacheFilePath,mode="r") as runtimeCacheFileHandle:
runtimeCacheInfo = json.load(runtimeCacheFileHandle)
self.update(runtimeCacheInfo)
class NoRuntimeCacheForSubusersWhichDontHaveExistantImagesException(Exception):
pass
| folti/subuser | logic/subuserlib/classes/subuserSubmodules/run/runtimeCache.py | Python | lgpl-3.0 | 1,842 |
<?php
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/
namespace Google\AdsApi\Common;
/**
* Holds and helps retrieve configuration data loaded from an *.ini file.
*/
class Configuration
{
private $config;
/**
* Creates a new configuration from the specified associative array of
* settings loaded from an *.ini file.
*
* @param array $iniFileContents an associative array of settings
*/
public function __construct(array $iniFileContents)
{
$this->config = $iniFileContents;
}
/**
* Gets the value for the specified setting name.
*
* @param string $name the setting name
* @param string $section optional, the name of the section containing the
* setting
* @return string|null the value of the setting, or null if it doesn't exist
*/
public function getConfiguration($name, $section = null)
{
$configValue = null;
if ($section === null) {
if (array_key_exists($name, $this->config)) {
$configValue = $this->config[$name];
}
} else {
if (array_key_exists($section, $this->config)) {
$sectionSettings = $this->config[$section];
if (array_key_exists($name, $sectionSettings)) {
$configValue = $sectionSettings[$name];
}
}
}
return $configValue;
}
}
| advanced-online-marketing/AOM | vendor/googleads/googleads-php-lib/src/Google/AdsApi/Common/Configuration.php | PHP | lgpl-3.0 | 2,004 |
package net.gtn.dimensionalpocket.oc.common.utils;
public class MathHelper {
public static int wrapInt(int value, int max) {
return wrapInt(value, 0, max);
}
public static int wrapInt(int value, int min, int max) {
return value < min ? max : value > max ? min : value;
}
public static float expandAwayFrom(float value, float expansion) {
return expandAwayFrom(value, 0, expansion);
}
public static float expandAwayFrom(float value, float awayFrom, float expansion) {
return value < awayFrom ? value - expansion : value > awayFrom ? value + expansion : value;
}
public static boolean withinValues(float value, float lowerBound, float upperBound) {
return lowerBound < value && value < upperBound;
}
public static boolean withinRange(double value, double target, double tolerance) {
return (target - tolerance) <= value && value <= (target + tolerance);
}
public static boolean withinRange(double value, double tolerance) {
return withinRange(value, 0.0D, tolerance);
}
public static boolean withinRange(float value, float target, float tolerance) {
return value >= (target - tolerance) && value <= (target + tolerance);
}
public static boolean withinRange(int value, int target, int tolerance) {
return value >= (target - tolerance) && value <= (target + tolerance);
}
public static double clipDouble(double value, double max) {
return clipDouble(value, 0, max);
}
public static double clipDouble(double value, double min, double max) {
return value > max ? max : value < min ? min : value;
}
public static int clipInt(int value, int max) {
return clipInt(value, 0, max);
}
public static int clipInt(int value, int min, int max) {
return value > max ? max : value < min ? min : value;
}
public static double interpolate(double a, double b, double d) {
return a + (b - a) * d;
}
public static float interpolate(float a, float b, float d) {
return a + (b - a) * d;
}
public static enum RoundingMethod {
FLOOR, CEILING, ROUND
}
}
| NPException42/Dimensional-Pockets | java/net/gtn/dimensionalpocket/oc/common/utils/MathHelper.java | Java | lgpl-3.0 | 2,200 |
<?php
/**
* Gekosale, Open Source E-Commerce Solution
* http://www.gekosale.pl
*
* Copyright (c) 2008-2013 WellCommerce sp. z o.o.. Zabronione jest usuwanie informacji o licencji i autorach.
*
* 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.
*
*
* $Revision: 619 $
* $Author: gekosale $
* $Date: 2011-12-19 22:09:00 +0100 (Pn, 19 gru 2011) $
* $Id: order.php 619 2011-12-19 21:09:00Z gekosale $
*/
namespace Gekosale;
class OrderModel extends Component\Model
{
public function __construct ($registry, $modelFile)
{
parent::__construct($registry, $modelFile);
$this->layer = $this->registry->loader->getCurrentLayer();
}
public function saveOrder ($Data)
{
$Data['clientaddress']['phone'] = $Data['contactData']['phone'];
$Data['clientaddress']['phone2'] = $Data['contactData']['phone2'];
$Data['clientaddress']['email'] = $Data['contactData']['email'];
$Data['deliveryAddress']['phone'] = $Data['contactData']['phone'];
$Data['deliveryAddress']['phone2'] = $Data['contactData']['phone2'];
$Data['deliveryAddress']['email'] = $Data['contactData']['email'];
Db::getInstance()->beginTransaction();
try{
$clientId = $Data['clientid'];
if ($clientId == NULL || $clientId == 0){
$clientId = Session::getActiveClientid();
}
$orderId = $this->addOrder($Data, $clientId);
$this->addOrderClientData($Data['clientaddress'], $clientId, $orderId);
$this->addOrderClientDeliveryData($Data['deliveryAddress'], $orderId);
$this->addOrderProduct($Data['cart'], $orderId);
App::getModel('order')->updateSessionString($orderId);
$this->syncStock();
Event::dispatch($this, 'frontend.order.saveOrder', Array(
'id' => $orderId,
'data' => $Data
));
}
catch (Exception $e){
throw new FrontendException($e->getMessage());
}
Db::getInstance()->commit();
return $orderId;
}
public function updateSessionString ($id)
{
$sql = 'UPDATE `order` SET sessionid = :crc WHERE idorder = :id';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('crc', session_id() . '-' . $id);
$stmt->bindValue('id', $id);
$stmt->execute();
}
protected function addOrder ($Data, $clientId = 0, $orginalOrderId = NULL)
{
$selectedOption = Session::getActiveDispatchmethodOption();
$globalPrice = 0;
$globalNetto = 0;
$price = 0;
$sql = 'INSERT INTO `order` (
price,
dispatchmethodprice,
globalprice,
dispatchmethodname,
paymentmethodname,
orderstatusid,
dispatchmethodid,
paymentmethodid,
clientid,
globalpricenetto,
viewid,
pricebeforepromotion,
currencyid,
currencysymbol,
currencyrate,
rulescartid,
sessionid,
customeropinion
)
VALUES (
:price,
:dispatchmethodprice,
:globalprice,
:dispatchmethodname,
:paymentmethodname,
(SELECT idorderstatus FROM orderstatus WHERE `default` = 1),
:dispatchmethodid,
:paymentmethodid,
:clientid,
:globalpricenetto,
:viewid,
:pricebeforepromotion,
:currencyid,
:currencysymbol,
:currencyrate,
:rulescartid,
:sessionid,
:customeropinion
)';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('dispatchmethodprice', $Data['dispatchmethod']['dispatchmethodcost']);
$stmt->bindValue('dispatchmethodname', $Data['dispatchmethod']['dispatchmethodname']);
$stmt->bindValue('dispatchmethodid', $Data['dispatchmethod']['dispatchmethodid']);
$stmt->bindValue('paymentmethodname', $Data['payment']['paymentmethodname']);
$stmt->bindValue('paymentmethodid', $Data['payment']['idpaymentmethod']);
$stmt->bindValue('clientid', $clientId);
$stmt->bindValue('sessionid', session_id());
$stmt->bindValue('customeropinion', $Data['customeropinion']);
$shopCurrency = Session::getActiveShopCurrencyId();
$clientCurrency = Session::getActiveCurrencyId();
if ($shopCurrency !== $clientCurrency){
$stmt->bindValue('currencyid', $clientCurrency);
$stmt->bindValue('currencysymbol', Session::getActiveCurrencySymbol());
$stmt->bindValue('currencyrate', Session::getActiveCurrencyRate());
}
else{
$stmt->bindValue('currencyid', $shopCurrency);
$stmt->bindValue('currencysymbol', $this->layer['currencysymbol']);
$stmt->bindValue('currencyrate', Session::getActiveCurrencyRate());
}
if (isset($Data['priceWithDispatchMethodPromo']) && $Data['priceWithDispatchMethodPromo'] > 0){
$stmt->bindValue('pricebeforepromotion', $Data['priceWithDispatchMethod']);
if ($globalPrice == 0){
$globalPrice = $Data['priceWithDispatchMethodPromo'];
$globalNetto = $Data['priceWithDispatchMethodNettoPromo'];
$price = $Data['globalPricePromo'];
}
}
else{
$stmt->bindValue('pricebeforepromotion', 0);
}
if ($globalPrice == 0 || $globalNetto == 0){
$globalPrice = $Data['priceWithDispatchMethod'];
$globalNetto = $Data['globalPriceWithoutVat'];
$price = $Data['globalPrice'];
}
if (isset($Data['rulescartid']) && ! empty($Data['rulescartid'])){
$stmt->bindValue('rulescartid', $Data['rulescartid']);
}
else{
$stmt->bindValue('rulescartid', NULL);
}
$stmt->bindValue('globalprice', $globalPrice);
$stmt->bindValue('globalpricenetto', $globalNetto);
$stmt->bindValue('price', $price);
$stmt->bindValue('viewid', Helper::getViewId());
try{
$stmt->execute();
}
catch (Exception $e){
throw new Exception($e->getMessage());
}
return Db::getInstance()->lastInsertId();
}
protected function addOrderClientData ($Data, $clientId = 0, $orderId)
{
$sql = 'INSERT INTO orderclientdata SET
firstname = AES_ENCRYPT(:firstname, :encryptionKey),
surname = AES_ENCRYPT(:surname, :encryptionKey),
street = AES_ENCRYPT(:street, :encryptionKey),
streetno = AES_ENCRYPT(:streetno, :encryptionKey),
placeno = AES_ENCRYPT(:placeno, :encryptionKey),
postcode = AES_ENCRYPT(:postcode, :encryptionKey),
place = AES_ENCRYPT(:place, :encryptionKey),
phone = AES_ENCRYPT(:phone, :encryptionKey),
phone2 = AES_ENCRYPT(:phone2, :encryptionKey),
email = AES_ENCRYPT(:email, :encryptionKey),
companyname = AES_ENCRYPT(:companyname, :encryptionKey),
nip = AES_ENCRYPT(:nip, :encryptionKey),
orderid = :orderid,
clientid = :clientid,
countryid = :country
';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('firstname', $Data['firstname']);
$stmt->bindValue('surname', $Data['surname']);
$stmt->bindValue('street', $Data['street']);
$stmt->bindValue('streetno', $Data['streetno']);
$stmt->bindValue('placeno', $Data['placeno']);
$stmt->bindValue('postcode', $Data['postcode']);
$stmt->bindValue('place', $Data['placename']);
$stmt->bindValue('phone', $Data['phone']);
$stmt->bindValue('phone2', $Data['phone2']);
$stmt->bindValue('email', $Data['email']);
$stmt->bindValue('companyname', $Data['companyname']);
$stmt->bindValue('nip', $Data['nip']);
$stmt->bindValue('country', $Data['countryid']);
$stmt->bindValue('orderid', $orderId);
$stmt->bindValue('clientid', $clientId);
$stmt->bindValue('viewid', Helper::getViewId());
$stmt->bindValue('encryptionKey', Session::getActiveEncryptionKeyValue());
try{
$stmt->execute();
}
catch (Exception $e){
throw new Exception($e->getMessage());
}
}
protected function addOrderClientDeliveryData ($Data, $orderId)
{
$sql = 'INSERT INTO orderclientdeliverydata SET
firstname = AES_ENCRYPT(:firstname, :encryptionKey),
surname = AES_ENCRYPT(:surname, :encryptionKey),
street = AES_ENCRYPT(:street, :encryptionKey),
streetno = AES_ENCRYPT(:streetno, :encryptionKey),
placeno = AES_ENCRYPT(:placeno, :encryptionKey),
postcode = AES_ENCRYPT(:postcode, :encryptionKey),
place = AES_ENCRYPT(:place, :encryptionKey),
phone = AES_ENCRYPT(:phone, :encryptionKey),
phone2 = AES_ENCRYPT(:phone2, :encryptionKey),
companyname = AES_ENCRYPT(:companyname, :encryptionKey),
nip = AES_ENCRYPT(:nip, :encryptionKey),
email = AES_ENCRYPT(:email, :encryptionKey),
orderid = :orderid,
countryid = :country';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('firstname', $Data['firstname']);
$stmt->bindValue('surname', $Data['surname']);
$stmt->bindValue('street', $Data['street']);
$stmt->bindValue('streetno', $Data['streetno']);
$stmt->bindValue('placeno', $Data['placeno']);
$stmt->bindValue('postcode', $Data['postcode']);
$stmt->bindValue('place', $Data['placename']);
$stmt->bindValue('phone', $Data['phone']);
$stmt->bindValue('phone2', $Data['phone2']);
$stmt->bindValue('email', $Data['email']);
$stmt->bindValue('companyname', $Data['companyname']);
$stmt->bindValue('nip', NULL);
$stmt->bindValue('orderid', $orderId);
$stmt->bindValue('country', $Data['countryid']);
$stmt->bindValue('encryptionKey', Session::getActiveEncryptionKeyValue());
try{
$stmt->execute();
}
catch (Exception $e){
throw new Exception($e->getMessage());
}
}
public function getOrderBillingData ($idorder)
{
$sql = 'SELECT
AES_DECRYPT(OCD.firstname, :encryptionkey) AS firstname,
AES_DECRYPT(OCD.surname, :encryptionkey) AS surname,
AES_DECRYPT(OCD.companyname, :encryptionkey) AS companyname,
AES_DECRYPT(OCD.nip, :encryptionkey) AS nip,
AES_DECRYPT(OCD.street, :encryptionkey) AS street,
AES_DECRYPT(OCD.streetno, :encryptionkey) AS streetno,
AES_DECRYPT(OCD.placeno, :encryptionkey) AS placeno,
AES_DECRYPT(OCD.place, :encryptionkey) AS placename,
AES_DECRYPT(OCD.postcode, :encryptionkey) AS postcode,
AES_DECRYPT(OCD.email, :encryptionkey) AS email,
AES_DECRYPT(OCD.phone, :encryptionkey) AS phone,
AES_DECRYPT(OCD.phone2, :encryptionkey) AS phone2
FROM orderclientdata OCD
WHERE OCD.orderid = :idorder';
$Data = Array();
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('idorder', $idorder);
$stmt->bindValue('encryptionkey', Session::getActiveEncryptionKeyValue());
$stmt->execute();
$rs = $stmt->fetch();
if ($rs){
$Data = Array(
'firstname' => $rs['firstname'],
'surname' => $rs['surname'],
'companyname' => $rs['companyname'],
'nip' => $rs['nip'],
'street' => $rs['street'],
'streetno' => $rs['streetno'],
'placeno' => $rs['placeno'],
'phone' => $rs['phone'],
'phone2' => $rs['phone2'],
'email' => $rs['email'],
'placename' => $rs['placename'],
'postcode' => $rs['postcode']
);
}
return $Data;
}
public function getOrderShippingData ($idorder)
{
$sql = 'SELECT
AES_DECRYPT(OCD.firstname, :encryptionkey) AS firstname,
AES_DECRYPT(OCD.surname, :encryptionkey) AS surname,
AES_DECRYPT(OCD.companyname, :encryptionkey) AS companyname,
AES_DECRYPT(OCD.nip, :encryptionkey) AS nip,
AES_DECRYPT(OCD.street, :encryptionkey) AS street,
AES_DECRYPT(OCD.streetno, :encryptionkey) AS streetno,
AES_DECRYPT(OCD.placeno, :encryptionkey) AS placeno,
AES_DECRYPT(OCD.place, :encryptionkey) AS placename,
AES_DECRYPT(OCD.postcode, :encryptionkey) AS postcode,
AES_DECRYPT(OCD.email, :encryptionkey) AS email,
AES_DECRYPT(OCD.phone, :encryptionkey) AS phone,
AES_DECRYPT(OCD.phone2, :encryptionkey) AS phone2
FROM orderclientdeliverydata OCD
WHERE OCD.orderid = :idorder';
$Data = Array();
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('idorder', $idorder);
$stmt->bindValue('encryptionkey', Session::getActiveEncryptionKeyValue());
$stmt->execute();
$rs = $stmt->fetch();
if ($rs){
$Data = Array(
'firstname' => $rs['firstname'],
'surname' => $rs['surname'],
'companyname' => $rs['companyname'],
'nip' => $rs['nip'],
'street' => $rs['street'],
'streetno' => $rs['streetno'],
'placeno' => $rs['placeno'],
'phone' => $rs['phone'],
'phone2' => $rs['phone2'],
'email' => $rs['email'],
'placename' => $rs['placename'],
'postcode' => $rs['postcode']
);
}
return $Data;
}
protected function addOrderProduct ($Data, $orderId)
{
foreach ($Data as $idproduct => $product){
if (isset($product['standard'])){
$sql = 'INSERT INTO orderproduct(name, price, qty, qtyprice, orderid, productid, vat, pricenetto, photoid, ean)
VALUES (:name, :price, :qty, :qtyprice, :orderid, :productid, :vat, :pricenetto, :photoid, :ean)';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('name', $product['name']);
$stmt->bindValue('price', $product['newprice']);
$stmt->bindValue('qty', $product['qty']);
$stmt->bindValue('qtyprice', $product['qtyprice']);
$stmt->bindValue('orderid', $orderId);
$stmt->bindValue('productid', $product['idproduct']);
$stmt->bindValue('vat', $product['vat']);
$stmt->bindValue('pricenetto', $product['pricewithoutvat']);
$stmt->bindValue('photoid', $product['mainphotoid']);
$stmt->bindValue('ean', $product['ean']);
try{
$stmt->execute();
if ($product['trackstock'] == 1){
$this->decreaseProductStock($product['idproduct'], $product['qty']);
}
}
catch (Exception $e){
throw new Exception($e->getMessage());
}
}
if (isset($product['attributes'])){
foreach ($product['attributes'] as $idattribute => $attribute){
$sql = 'INSERT INTO orderproduct(name, price, qty, qtyprice, orderid, productid, productattributesetid, vat, pricenetto, photoid, ean)
VALUES (:name, :price, :qty, :qtyprice, :orderid, :productid, :productattributesetid, :vat, :pricenetto, :photoid, :ean)';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('name', $attribute['name']);
$stmt->bindValue('price', $attribute['newprice']);
$stmt->bindValue('qty', $attribute['qty']);
$stmt->bindValue('qtyprice', $attribute['qtyprice']);
$stmt->bindValue('orderid', $orderId);
$stmt->bindValue('productid', $attribute['idproduct']);
$stmt->bindValue('productattributesetid', $attribute['attr']);
$stmt->bindValue('vat', $attribute['vat']);
$stmt->bindValue('pricenetto', $attribute['pricewithoutvat']);
$stmt->bindValue('photoid', $attribute['mainphotoid']);
$stmt->bindValue('ean', $attribute['ean']);
try{
$stmt->execute();
$this->addOrderProductAttribute($attribute['features'], Db::getInstance()->lastInsertId());
if ($attribute['trackstock'] == 1){
$this->decreaseProductAttributeStock($attribute['idproduct'], $attribute['attr'], $attribute['qty']);
}
}
catch (Exception $e){
throw new Exception($e->getMessage());
}
}
}
}
}
public function syncStock ()
{
$sql = 'UPDATE product SET stock = (SELECT IF(SUM(productattributeset.stock) IS NOT NULL, SUM(productattributeset.stock), product.stock) FROM productattributeset WHERE productattributeset.productid = product.idproduct)';
$stmt = Db::getInstance()->prepare($sql);
$stmt->execute();
$sql = 'UPDATE product SET enable = IF(stock > disableatstock, 1, 0) WHERE disableatstockenabled = 1';
$stmt = Db::getInstance()->prepare($sql);
$stmt->execute();
}
protected function addOrderProductAttribute ($Data, $orderProductId)
{
foreach ($Data as $featureid => $feature){
$sql = 'INSERT INTO orderproductattribute (name, `group`, attributeproductvalueid, orderproductid)
VALUES (:name, :group, :attributeproductvalueid, :orderproductid)';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('name', $feature['attributename']);
$stmt->bindValue('group', $feature['group']);
$stmt->bindValue('attributeproductvalueid', $feature['feature']);
$stmt->bindValue('orderproductid', $orderProductId);
try{
$stmt->execute();
}
catch (Exception $e){
throw new Exception($e->getMessage());
}
}
}
protected function decreaseProductAttributeStock ($productid, $idproductattribute, $qty)
{
$sql = 'UPDATE productattributeset SET stock = stock-:qty
WHERE productid = :productid
AND idproductattributeset = :idproductattribute';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('qty', $qty);
$stmt->bindValue('productid', $productid);
$stmt->bindValue('idproductattribute', $idproductattribute);
try{
$stmt->execute();
}
catch (Exception $e){
throw new Exception($e->getMessage());
}
}
protected function decreaseProductStock ($productid, $qty)
{
$sql = 'UPDATE product SET stock = stock-:qty
WHERE idproduct = :idproduct';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('qty', $qty);
$stmt->bindValue('idproduct', $productid);
try{
$stmt->execute();
}
catch (Exception $e){
throw new Exception($e->getMessage());
}
}
public function getDate ()
{
$orderid = Session::getActiveorderid();
$signs = Array(
':',
'-',
' '
);
$sql = "SELECT adddate FROM `order`
WHERE idorder = :orderid";
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('orderid', $orderid);
$stmt->execute();
$rs = $stmt->fetch();
$Data = '';
if ($rs){
$Data = $rs['adddate'];
$Data = str_replace($signs, '', $Data);
}
return $Data;
}
public function generateOrderLink ($idorder)
{
$date = $this->getDate();
$activelink = sha1($date . $idorder);
return $activelink;
}
public function changeOrderLink ($orderid, $orderlink)
{
$sql = "UPDATE `order` SET activelink = :activelink
WHERE idorder = :orderid";
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('activelink', $orderlink);
$stmt->bindValue('orderid', $orderid);
$stmt->execute();
}
public function getOrderById ($id)
{
$sql = "SELECT
O.clientid,
O.customeropinion,
O.adddate as order_date,
O.idorder as order_id,
OS.idorderstatus as current_status_id,
OST.name as current_status,
O.dispatchmethodprice as delivererprice,
O.dispatchmethodname as deliverername,
O.dispatchmethodid,
O.paymentmethodid,
O.paymentmethodname as paymentname,
PM.controller AS paymentmethodcontroller,
O.price as vat_value,
O.globalpricenetto as totalnetto,
O.globalprice as total,
O.orderstatusid,
V.name as view,
O.viewid,
O.currencyid,
O.currencysymbol,
O.currencyrate,
O.rulescartid,
O.pricebeforepromotion
FROM `order` O
LEFT JOIN view V ON O.viewid = V.idview
LEFT JOIN orderstatus OS ON OS.idorderstatus=O.orderstatusid
LEFT JOIN orderstatustranslation OST ON OS.idorderstatus = OST.orderstatusid AND OST.languageid = :languageid
LEFT JOIN paymentmethod PM ON PM.idpaymentmethod = O.paymentmethodid
WHERE O.idorder = :id";
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->bindValue('languageid', Helper::getLanguageId());
$stmt->execute();
$rs = $stmt->fetch();
$Data = Array();
if ($rs){
$Data = Array(
'clientid' => $rs['clientid'],
'customeropinion' => $rs['customeropinion'],
'order_id' => $rs['order_id'],
'viewid' => $rs['viewid'],
'view' => $rs['view'],
'orderstatusid' => $rs['orderstatusid'],
'order_date' => $rs['order_date'],
'current_status' => $rs['current_status'],
'current_status_id' => $rs['current_status_id'],
'clients_ip_address' => '123.456.123.456',
'vat_value' => $rs['vat_value'],
'totalnetto' => $rs['totalnetto'],
'total' => $rs['total'],
'currencyid' => $rs['currencyid'],
'currencysymbol' => $rs['currencysymbol'],
'currencyrate' => $rs['currencyrate'],
'pricebeforepromotion' => $rs['pricebeforepromotion'],
'rulescartid' => $rs['rulescartid'],
'client' => $this->getClientData($id),
'billing_address' => $this->getBillingAddress($id),
'delivery_address' => $this->getDeliveryAddress($id),
'products' => $this->getProducts($id)
);
$dispatchmethodVat = $this->getDispatchmethodForOrder($rs['dispatchmethodid']);
$delivererpricenetto = $rs['delivererprice'] / (1 + ($dispatchmethodVat / 100));
$Data['delivery_method'] = Array(
'delivererprice' => $rs['delivererprice'],
'deliverername' => $rs['deliverername'],
'dispatchmethodid' => $rs['dispatchmethodid'],
'delivererpricenetto' => $delivererpricenetto,
'deliverervat' => sprintf('%01.2f', $dispatchmethodVat),
'deliverervatvalue' => $rs['delivererprice'] - $delivererpricenetto
);
$Data['payment_method'] = Array(
'paymentname' => $rs['paymentname'],
'paymentmethodcontroller' => $rs['paymentmethodcontroller'],
'paymentmethodid' => $rs['paymentmethodid']
);
}
return $Data;
}
public function getProducts ($id)
{
$sql = "SELECT
OP.idorderproduct,
OP.productid as id,
OP.productattributesetid AS variant,
OP.name,
OP.pricenetto as net_price,
OP.qty as quantity,
(OP.pricenetto*OP.qty) as net_subtotal,
OP.vat,
ROUND((OP.pricenetto * OP.qty) * OP.vat/100 , 2) as vat_value,
ROUND(((OP.pricenetto*OP.qty)*OP.vat/100 )+(OP.pricenetto*OP.qty), 2) as subtotal
FROM orderproduct OP
WHERE OP.orderid=:id";
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->execute();
$Data = Array();
while ($rs = $stmt->fetch()){
$Data[] = Array(
'id' => $rs['id'],
'name' => $rs['name'],
'net_price' => $rs['net_price'],
'quantity' => $rs['quantity'],
'net_subtotal' => $rs['net_subtotal'],
'vat' => $rs['vat'],
'vat_value' => $rs['vat_value'],
'subtotal' => $rs['subtotal'],
'attributes' => $this->getOrderProductAttributes($rs['id'], $rs['variant'])
);
}
return $Data;
}
public function getOrderProductAttributes ($productId, $variantId)
{
if ($variantId != NULL){
$sql = '
SELECT
A.idproductattributeset AS id,
A.`value`,
A.stock AS qty,
A.symbol,
A.weight,
A.suffixtypeid AS prefix_id,
GROUP_CONCAT(SUBSTRING(CONCAT(\' \', CONCAT(AP.name,\': \',C.name)), 1) SEPARATOR \'<br />\') AS name
FROM
productattributeset A
LEFT JOIN productattributevalueset B ON A.idproductattributeset = B.productattributesetid
LEFT JOIN attributeproductvalue C ON B.attributeproductvalueid = C.idattributeproductvalue
LEFT JOIN attributeproduct AP ON C.attributeproductid = AP.idattributeproduct
LEFT JOIN product D ON A.productid = D.idproduct
LEFT JOIN suffixtype E ON A.suffixtypeid = E.idsuffixtype
LEFT JOIN vat V ON V.idvat = D.vatid
WHERE
productid = :productid AND
A.idproductattributeset = :variantid
';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('productid', $productId);
$stmt->bindValue('variantid', $variantId);
$stmt->execute();
$Data = $stmt->fetchAll();
return (isset($Data[0]) ? $Data[0] : Array());
}
else{
return Array();
}
}
public function getClientData ($id)
{
$sql = "SELECT
CGT.name as clientgroup,
O.clientid as ids,
AES_DECRYPT(OCD.firstname, :encryptionKey) as firstname,
AES_DECRYPT(OCD.surname, :encryptionKey) as surname,
AES_DECRYPT(CD.email, :encryptionKey) as email
FROM orderclientdata OCD
LEFT JOIN `order` O ON O.idorder = OCD.orderid
LEFT JOIN clientdata CD ON CD.clientid=O.clientid
LEFT JOIN clientgrouptranslation CGT ON CGT.clientgroupid = CD.clientgroupid AND languageid=:languageid
WHERE OCD.orderid=:id";
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('languageid', Helper::getLanguageId());
$stmt->bindValue('id', $id);
$stmt->bindValue('encryptionKey', Session::getActiveEncryptionKeyValue());
$stmt->execute();
$rs = $stmt->fetch();
$Data = Array();
if ($rs){
$Data = Array(
'ids' => $rs['ids'],
'firstname' => $rs['firstname'],
'surname' => $rs['surname'],
'email' => $rs['email'],
'clientgroup' => $rs['clientgroup']
);
}
else{
throw new CoreException(_('ERR_CLIENT_DATA_NO_EXIST'));
}
return $Data;
}
public function getDeliveryAddress ($id)
{
$sql = "SELECT
AES_DECRYPT(OCDD.firstname, :encryptionKey) firstname,
AES_DECRYPT(OCDD.surname, :encryptionKey) surname,
AES_DECRYPT(OCDD.place, :encryptionKey) city,
AES_DECRYPT(OCDD.postcode, :encryptionKey) postcode,
AES_DECRYPT(OCDD.phone, :encryptionKey) phone,
AES_DECRYPT(OCDD.phone2, :encryptionKey) phone2,
AES_DECRYPT(OCDD.street, :encryptionKey) street,
AES_DECRYPT(OCDD.streetno, :encryptionKey) streetno,
AES_DECRYPT(OCDD.placeno, :encryptionKey) placeno,
AES_DECRYPT(OCDD.email, :encryptionKey) email,
AES_DECRYPT(OCDD.nip, :encryptionKey) nip,
AES_DECRYPT(OCDD.companyname, :encryptionKey) companyname
FROM orderclientdeliverydata OCDD
WHERE orderid=:id";
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->bindValue('encryptionKey', Session::getActiveEncryptionKeyValue());
$stmt->execute();
$rs = $stmt->fetch();
$Data = Array();
if ($rs){
$Data = Array(
'firstname' => $rs['firstname'],
'surname' => $rs['surname'],
'city' => $rs['city'],
'postcode' => $rs['postcode'],
'phone' => $rs['phone'],
'phone2' => $rs['phone2'],
'street' => $rs['street'],
'streetno' => $rs['streetno'],
'placeno' => $rs['placeno'],
'country' => 'Poland',
'companyname' => $rs['companyname'],
'email' => $rs['email'],
'nip' => $rs['nip']
);
}
else{
throw new CoreException(_('ERR_DELIVERY_ADDRESS_NO_EXIST'));
}
return $Data;
}
public function getBillingAddress ($id)
{
$sql = "SELECT
AES_DECRYPT(OCD.firstname, :encryptionKey) AS firstname,
AES_DECRYPT(OCD.surname, :encryptionKey) AS surname,
AES_DECRYPT(OCD.place, :encryptionKey) AS city,
AES_DECRYPT(OCD.postcode, :encryptionKey) AS postcode,
AES_DECRYPT(OCD.phone, :encryptionKey) AS phone,
AES_DECRYPT(OCD.phone2, :encryptionKey) AS phone2,
AES_DECRYPT(OCD.street, :encryptionKey) AS street,
AES_DECRYPT(OCD.streetno, :encryptionKey) AS streetno,
AES_DECRYPT(OCD.placeno, :encryptionKey) AS placeno,
AES_DECRYPT(OCD.email, :encryptionKey) AS email,
AES_DECRYPT(OCD.nip, :encryptionKey) AS nip,
AES_DECRYPT(OCD.companyname, :encryptionKey) AS companyname
FROM orderclientdata OCD
WHERE orderid=:id";
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->bindValue('encryptionKey', Session::getActiveEncryptionKeyValue());
$stmt->execute();
$rs = $stmt->fetch();
$Data = Array();
if ($rs){
$Data = Array(
'firstname' => $rs['firstname'],
'surname' => $rs['surname'],
'city' => $rs['city'],
'postcode' => $rs['postcode'],
'phone' => $rs['phone'],
'phone2' => $rs['phone2'],
'street' => $rs['street'],
'streetno' => $rs['streetno'],
'placeno' => $rs['placeno'],
'country' => 'Poland',
'companyname' => $rs['companyname'],
'email' => $rs['email'],
'nip' => $rs['nip']
);
}
else{
throw new CoreException(_('ERR_BILLING_ADDRESS_NO_EXIST'));
}
return $Data;
}
public function getVATAllForRangeEditor ()
{
$sql = 'SELECT V.idvat AS id, V.value, VT.name
FROM vat V
LEFT JOIN vattranslation VT ON VT.vatid = V.idvat AND VT.languageid = :languageid';
$Data = Array();
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('languageid', Helper::getLanguageId());
$stmt->execute();
while ($rs = $stmt->fetch()){
$Data[$rs['id']] = $rs['value'];
}
return $Data;
}
public function getDispatchmethodForOrder ($id)
{
$sql = 'SELECT type FROM dispatchmethod WHERE iddispatchmethod = :id';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->execute();
$rs = $stmt->fetch();
$Data = Array();
if ($rs){
$type = $rs['type'];
}
if ($type == 1){
$method = $this->getDispatchmethodPrice($id);
}
else{
$method = $this->getDispatchmethodWeight($id);
}
if (isset($method['use_vat']) && $method['use_vat'] == 1 && $method['vat'] > 0){
$vatData = $this->getVATAllForRangeEditor();
$vatValue = $vatData[$method['vat']];
}
else{
$vatValue = 0;
}
return $vatValue;
}
public function getDispatchmethodPrice ($id)
{
$sql = 'SELECT iddispatchmethodprice as id, dispatchmethodcost, `from`, `to`, vat
FROM dispatchmethodprice
WHERE dispatchmethodid=:id';
$Data = Array();
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->execute();
$Data = Array();
while ($rs = $stmt->fetch()){
$Data['ranges'][] = Array(
'min' => $rs['from'],
'max' => $rs['to'],
'price' => $rs['dispatchmethodcost']
);
if ($rs['vat'] > 0){
$Data['vat'] = $rs['vat'];
$Data['use_vat'] = 1;
}
}
return $Data;
}
public function getDispatchmethodWeight ($id)
{
$sql = 'SELECT cost, `from`, `to`,vat
FROM dispatchmethodweight
WHERE dispatchmethodid=:id';
$Data = Array();
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->execute();
$Data = Array();
while ($rs = $stmt->fetch()){
$Data['ranges'][] = Array(
'min' => $rs['from'],
'max' => $rs['to'],
'price' => $rs['cost']
);
if ($rs['vat'] > 0){
$Data['vat'] = $rs['vat'];
$Data['use_vat'] = 1;
}
}
return $Data;
}
public function getOrderProductListByClient ($idorder)
{
$sql = 'SELECT
O.idorder,
OP.name as productname,
OP.qty,
OP.productid,
OP.qtyprice,
OP.price,
OP.pricenetto,
OP.vat,
OP.productid,
OP.idorderproduct,
PT.seo
FROM `order` O
LEFT JOIN orderclientdata OCD ON OCD.orderid=O.idorder
LEFT JOIN orderproduct OP ON OP.orderid=O.idorder
LEFT JOIN producttranslation PT ON OP.productid = PT.productid AND PT.languageid = :languageid
WHERE O.clientid= :clientid and idorder= :idorder
ORDER BY productname';
$Data = Array();
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('idorder', $idorder);
$stmt->bindValue('clientid', Session::getActiveClientid());
$stmt->bindValue('languageid', Helper::getLanguageId());
$stmt->execute();
while ($rs = $stmt->fetch()){
$Data[] = Array(
'idproduct' => $this->isProductAvailable($rs['productid']),
'seo' => $rs['seo'],
'qty' => $rs['qty'],
'productid' => $rs['productid'],
'qtyprice' => $rs['qtyprice'],
'price' => $rs['price'],
'pricenetto' => $rs['pricenetto'],
'vat' => $rs['vat'],
'productname' => $rs['productname'],
'idorderproduct' => $rs['idorderproduct'],
'attributes' => $this->getProductAttributes($rs['idorderproduct'])
);
}
return $Data;
}
public function isProductAvailable ($productid)
{
$sql = 'SELECT
idproduct
FROM product
WHERE idproduct = :productid';
$Data = Array();
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('productid', $productid);
$stmt->execute();
$rs = $stmt->fetch();
if ($rs){
$available = $rs['idproduct'];
}
else{
$available = 0;
}
return $available;
}
public function getProductAttributes ($productid)
{
$sql = 'SELECT
OP.idorderproduct as attrId,
OPA.group AS attributegroup,
OPA.name as attributename
FROM orderproduct OP
LEFT JOIN orderproductattribute OPA ON OPA.orderproductid = OP.idorderproduct
WHERE orderproductid= :productid';
$Data = Array();
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('productid', $productid);
$stmt->execute();
while ($rs = $stmt->fetch()){
$Data[] = Array(
'attributegroup' => $rs['attributegroup'],
'attributename' => $rs['attributename']
);
}
return $Data;
}
public function getOrderInvoices ($id)
{
$sql = "SELECT
idinvoice,
symbol,
invoicedate,
comment,
salesperson,
paymentduedate,
totalpayed
FROM invoice
WHERE orderid=:id";
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->execute();
return $stmt->fetchAll();
}
public function getOrderListByClient ()
{
$sql = 'SELECT
OST.name as orderstatusname,
O.idorder,
O.adddate as orderdate,
O.dispatchmethodname,
O.paymentmethodname,
O.dispatchmethodprice,
O.globalprice,
O.price,
O.globalpricenetto,
O.currencysymbol,
OSG.colour
FROM `order` O
LEFT JOIN orderstatus OS ON OS.idorderstatus = O.orderstatusid
LEFT JOIN orderstatustranslation OST ON OST.orderstatusid = OS.idorderstatus AND OST.languageid = :languageid
LEFT JOIN orderstatusorderstatusgroups OSOSG ON O.orderstatusid = OSOSG.orderstatusid
LEFT JOIN orderstatusgroups OSG ON OSG.idorderstatusgroups = OSOSG.orderstatusgroupsid
WHERE O.clientid= :clientid ORDER BY O.adddate DESC';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('clientid', Session::getActiveClientid());
$stmt->bindValue('languageid', Helper::getLanguageId());
$stmt->execute();
$Data = Array();
while ($rs = $stmt->fetch()){
$Data[] = Array(
'idorder' => $rs['idorder'],
'orderdate' => $rs['orderdate'],
'orderstatusname' => $rs['orderstatusname'],
'dispatchmethodname' => $rs['dispatchmethodname'],
'paymentmethodname' => $rs['paymentmethodname'],
'globalprice' => $rs['globalprice'],
'currencysymbol' => $rs['currencysymbol'],
'colour' => $rs['colour']
);
}
return $Data;
}
public function getOrderByClient ($idorder)
{
$sql = 'SELECT
OST.name as orderstatusname,
O.idorder,
O.adddate as orderdate,
O.dispatchmethodname,
O.paymentmethodname,
O.dispatchmethodprice,
O.globalprice,
O.price,
O.globalpricenetto,
O.currencysymbol
FROM `order` O
LEFT JOIN orderstatus OS ON OS.idorderstatus=O.orderstatusid
LEFT JOIN orderstatustranslation OST ON OST.orderstatusid = OS.idorderstatus AND OST.languageid = :languageid
WHERE O.clientid= :clientid AND idorder= :idorder';
$Data = Array();
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('idorder', $idorder);
$stmt->bindValue('clientid', Session::getActiveClientid());
$stmt->bindValue('languageid', Helper::getLanguageId());
$stmt->execute();
$rs = $stmt->fetch();
if ($rs){
$invoicedata = explode('-', $rs['orderdate']);
$invoicedata[2] = substr($invoicedata[2], 0, 2);
$dateinvoice = $invoicedata[0] . $invoicedata[1] . $invoicedata[2];
$Data = Array(
'idorder' => $rs['idorder'],
'globalprice' => $rs['globalprice'],
'price' => $rs['price'],
'globalpricenetto' => $rs['globalpricenetto'],
'orderstatusname' => $rs['orderstatusname'],
'orderdate' => $rs['orderdate'],
'currencysymbol' => $rs['currencysymbol'],
'dispatchmethodname' => $rs['dispatchmethodname'],
'paymentmethodname' => $rs['paymentmethodname'],
'dispatchmethodprice' => $rs['dispatchmethodprice'],
'dateinvoice' => $dateinvoice,
'billingaddress' => $this->getOrderBillingData($rs['idorder']),
'shippingaddress' => $this->getOrderShippingData($rs['idorder']),
'invoices' => $this->getOrderInvoices($rs['idorder']),
);
}
return $Data;
}
public function getOrderStatusByEmailAndId ($email, $id)
{
$sql = 'SELECT
OST.name as orderstatusname,
O.idorder
FROM `order` O
LEFT JOIN orderstatus OS ON OS.idorderstatus = O.orderstatusid
LEFT JOIN orderstatustranslation OST ON OST.orderstatusid = OS.idorderstatus AND OST.languageid = :languageid
LEFT JOIN orderclientdata OCD ON OCD.orderid = O.idorder
WHERE AES_DECRYPT(OCD.email, :encryptionKey) = :email AND O.idorder = :id';
$stmt = Db::getInstance()->prepare($sql);
$stmt->bindValue('email', $email);
$stmt->bindValue('id', $id);
$stmt->bindValue('encryptionKey', Session::getActiveEncryptionKeyValue());
$stmt->bindValue('languageid', Helper::getLanguageId());
$stmt->execute();
$rs = $stmt->fetch();
if ($rs){
return $rs['orderstatusname'];
}
return NULL;
}
}
| jmarceli/Gekosale2 | plugin/Gekosale/Frontend/order/model/order.php | PHP | lgpl-3.0 | 36,316 |
"""
This configuration file loads environment's specific config settings for the application.
It takes precedence over the config located in the boilerplate package.
"""
import os
if os.environ['HTTP_HOST'] == "appengine.beecoss.com":
# Load Boilerplate config only in http://appengine.beecoss.com
# this code is here just for testing purposes
from config.boilerplate import config
elif "SERVER_SOFTWARE" in os.environ:
if os.environ['SERVER_SOFTWARE'].startswith('Dev'):
from config.localhost import config
elif os.environ['SERVER_SOFTWARE'].startswith('Google'):
from config.production import config
else:
raise ValueError("Environment undetected")
else:
from config.testing import config | shupelneker/gae_new_structure | config/__init__.py | Python | lgpl-3.0 | 745 |
---
layout: default
title: Floats / Large screens
category: _utilities
---
<div class="p-card u-float-left--large">Float left on large screens</div>
<div class="p-card u-float-right--large">Float right on large screens</div> | anthonydillon/vanilla-framework | examples/utilities/floats/large-screens.html | HTML | lgpl-3.0 | 225 |
// <copyright file="SalesOrderPaymentStates.cs" company="Allors bvba">
// Copyright (c) Allors bvba. All rights reserved.
// Licensed under the LGPL license. See LICENSE file in the project root for full license information.
// </copyright>
namespace Allors.Domain
{
using System;
public partial class SalesOrderPaymentStates
{
internal static readonly Guid NotPaidId = new Guid("8F5E0C7D-893F-4C7F-8297-3B4BD6319D02");
internal static readonly Guid PaidId = new Guid("0C84C6F6-3204-4f7f-9BFA-FA4CBA643177");
internal static readonly Guid PartiallyPaidId = new Guid("F9E8E105-F84E-4550-A725-25CE6E96614E");
private UniquelyIdentifiableSticky<SalesOrderPaymentState> cache;
public SalesOrderPaymentState NotPaid => this.Cache[NotPaidId];
public SalesOrderPaymentState PartiallyPaid => this.Cache[PartiallyPaidId];
public SalesOrderPaymentState Paid => this.Cache[PaidId];
private UniquelyIdentifiableSticky<SalesOrderPaymentState> Cache => this.cache ??= new UniquelyIdentifiableSticky<SalesOrderPaymentState>(this.Session);
protected override void BaseSetup(Setup setup)
{
var merge = this.Cache.Merger().Action();
merge(NotPaidId, v => v.Name = "Not Paid");
merge(PartiallyPaidId, v => v.Name = "Partially Paid");
merge(PaidId, v => v.Name = "Paid");
}
}
}
| Allors/allors2 | Base/Database/Domain/Base/Order/SalesOrderPaymentStates.cs | C# | lgpl-3.0 | 1,419 |
package com.vistatec.ocelot.rules;
import com.vistatec.ocelot.its.model.LanguageQualityIssue;
public class RulesTestHelpers {
public static LanguageQualityIssue lqi(String type, int severity) {
LanguageQualityIssue lqi = new LanguageQualityIssue();
lqi.setType(type);
lqi.setSeverity(severity);
return lqi;
}
public static LanguageQualityIssue lqi(String type, int severity, String comment) {
LanguageQualityIssue lqi = new LanguageQualityIssue();
lqi.setType(type);
lqi.setSeverity(severity);
lqi.setComment(comment);
return lqi;
}
}
| vistatec/ocelot | src/test/java/com/vistatec/ocelot/rules/RulesTestHelpers.java | Java | lgpl-3.0 | 626 |
package com.jediterm.terminal.ui;
import com.google.common.base.Ascii;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.jediterm.terminal.*;
import com.jediterm.terminal.TextStyle.Option;
import com.jediterm.terminal.emulator.ColorPalette;
import com.jediterm.terminal.emulator.charset.CharacterSets;
import com.jediterm.terminal.emulator.mouse.MouseMode;
import com.jediterm.terminal.emulator.mouse.TerminalMouseListener;
import com.jediterm.terminal.model.*;
import com.jediterm.terminal.ui.settings.SettingsProvider;
import com.jediterm.terminal.util.Pair;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.font.TextHitInfo;
import java.awt.im.InputMethodRequests;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.AttributedCharacterIterator;
import java.text.CharacterIterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class TerminalPanel extends JComponent implements TerminalDisplay, ClipboardOwner, TerminalActionProvider {
private static final Logger LOG = Logger.getLogger(TerminalPanel.class);
private static final long serialVersionUID = -1048763516632093014L;
public static final double SCROLL_SPEED = 0.05;
/*font related*/
private Font myNormalFont;
private Font myItalicFont;
private Font myBoldFont;
private Font myBoldItalicFont;
private int myDescent = 0;
protected Dimension myCharSize = new Dimension();
private boolean myMonospaced;
protected Dimension myTermSize = new Dimension(80, 24);
private TerminalStarter myTerminalStarter = null;
private MouseMode myMouseMode = MouseMode.MOUSE_REPORTING_NONE;
private Point mySelectionStartPoint = null;
private TerminalSelection mySelection = null;
private Clipboard myClipboard;
private TerminalPanelListener myTerminalPanelListener;
private SettingsProvider mySettingsProvider;
final private TerminalTextBuffer myTerminalTextBuffer;
final private StyleState myStyleState;
/*scroll and cursor*/
final private TerminalCursor myCursor = new TerminalCursor();
private final BoundedRangeModel myBoundedRangeModel = new DefaultBoundedRangeModel(0, 80, 0, 80);
private boolean myScrollingEnabled = true;
protected int myClientScrollOrigin;
protected KeyListener myKeyListener;
private String myWindowTitle = "Terminal";
private TerminalActionProvider myNextActionProvider;
private String myInputMethodUncommitedChars;
private Timer myRepaintTimer;
private AtomicBoolean needScrollUpdate = new AtomicBoolean(true);
private AtomicBoolean needRepaint = new AtomicBoolean(true);
private int myMaxFPS = 50;
private int myBlinkingPeriod = 500;
private TerminalCoordinates myCoordsAccessor;
private String myCurrentPath; //TODO: handle current path if availabe
public TerminalPanel(@NotNull SettingsProvider settingsProvider, @NotNull TerminalTextBuffer terminalTextBuffer, @NotNull StyleState styleState) {
mySettingsProvider = settingsProvider;
myTerminalTextBuffer = terminalTextBuffer;
myStyleState = styleState;
myTermSize.width = terminalTextBuffer.getWidth();
myTermSize.height = terminalTextBuffer.getHeight();
myMaxFPS = mySettingsProvider.maxRefreshRate();
updateScrolling();
enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK);
enableInputMethods(true);
terminalTextBuffer.addModelListener(new TerminalModelListener() {
@Override
public void modelChanged() {
repaint();
}
});
}
@Override
public void repaint() {
needRepaint.set(true);
}
private void doRepaint() {
super.repaint();
}
@Deprecated
protected void reinitFontAndResize() {
initFont();
sizeTerminalFromComponent();
}
protected void initFont() {
myNormalFont = createFont();
myBoldFont = myNormalFont.deriveFont(Font.BOLD);
myItalicFont = myNormalFont.deriveFont(Font.ITALIC);
myBoldItalicFont = myBoldFont.deriveFont(Font.ITALIC);
establishFontMetrics();
}
public void init() {
initFont();
setUpClipboard();
setPreferredSize(new Dimension(getPixelWidth(), getPixelHeight()));
setFocusable(true);
enableInputMethods(true);
setDoubleBuffered(true);
setFocusTraversalKeysEnabled(false);
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(final MouseEvent e) {
if (!isLocalMouseAction(e)) {
return;
}
final Point charCoords = panelToCharCoords(e.getPoint());
if (mySelection == null) {
// prevent unlikely case where drag started outside terminal panel
if (mySelectionStartPoint == null) {
mySelectionStartPoint = charCoords;
}
mySelection = new TerminalSelection(new Point(mySelectionStartPoint));
}
repaint();
mySelection.updateEnd(charCoords);
if (mySettingsProvider.copyOnSelect()) {
handleCopy(false);
}
if (e.getPoint().y < 0) {
moveScrollBar((int) ((e.getPoint().y) * SCROLL_SPEED));
}
if (e.getPoint().y > getPixelHeight()) {
moveScrollBar((int) ((e.getPoint().y - getPixelHeight()) * SCROLL_SPEED));
}
}
});
addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (isLocalMouseAction(e)) {
int notches = e.getWheelRotation();
moveScrollBar(notches);
}
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
if (e.getClickCount() == 1) {
mySelectionStartPoint = panelToCharCoords(e.getPoint());
mySelection = null;
repaint();
}
}
}
@Override
public void mouseReleased(final MouseEvent e) {
requestFocusInWindow();
repaint();
}
@Override
public void mouseClicked(final MouseEvent e) {
requestFocusInWindow();
if (e.getButton() == MouseEvent.BUTTON1 && isLocalMouseAction(e)) {
int count = e.getClickCount();
if (count == 1) {
// do nothing
} else if (count == 2) {
// select word
final Point charCoords = panelToCharCoords(e.getPoint());
Point start = SelectionUtil.getPreviousSeparator(charCoords, myTerminalTextBuffer);
Point stop = SelectionUtil.getNextSeparator(charCoords, myTerminalTextBuffer);
mySelection = new TerminalSelection(start);
mySelection.updateEnd(stop);
if (mySettingsProvider.copyOnSelect()) {
handleCopy(false);
}
} else if (count == 3) {
// select line
final Point charCoords = panelToCharCoords(e.getPoint());
int startLine = charCoords.y;
while (startLine > -getScrollBuffer().getLineCount()
&& myTerminalTextBuffer.getLine(startLine - 1).isWrapped()) {
startLine--;
}
int endLine = charCoords.y;
while (endLine < myTerminalTextBuffer.getHeight()
&& myTerminalTextBuffer.getLine(endLine).isWrapped()) {
endLine++;
}
mySelection = new TerminalSelection(new Point(0, startLine));
mySelection.updateEnd(new Point(myTermSize.width, endLine));
if (mySettingsProvider.copyOnSelect()) {
handleCopy(false);
}
}
} else if (e.getButton() == MouseEvent.BUTTON2 && mySettingsProvider.pasteOnMiddleMouseClick() && isLocalMouseAction(e)) {
handlePaste();
} else if (e.getButton() == MouseEvent.BUTTON3) {
JPopupMenu popup = createPopupMenu();
popup.show(e.getComponent(), e.getX(), e.getY());
}
repaint();
}
});
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
sizeTerminalFromComponent();
}
});
addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
myCursor.cursorChanged();
}
@Override
public void focusLost(FocusEvent e) {
myCursor.cursorChanged();
}
});
myBoundedRangeModel.addChangeListener(new ChangeListener() {
public void stateChanged(final ChangeEvent e) {
myClientScrollOrigin = myBoundedRangeModel.getValue();
repaint();
}
});
createRepaintTimer();
}
private void createRepaintTimer() {
if (myRepaintTimer != null) {
myRepaintTimer.stop();
}
myRepaintTimer = new Timer(1000 / myMaxFPS, new WeakRedrawTimer(this));
myRepaintTimer.start();
}
public boolean isLocalMouseAction(MouseEvent e) {
return mySettingsProvider.forceActionOnMouseReporting() || (isMouseReporting() == e.isShiftDown());
}
public boolean isRemoteMouseAction(MouseEvent e) {
return isMouseReporting() && !e.isShiftDown();
}
protected boolean isRetina() {
return UIUtil.isRetina();
}
public void setBlinkingPeriod(int blinkingPeriod) {
myBlinkingPeriod = blinkingPeriod;
}
public void setCoordAccessor(TerminalCoordinates coordAccessor) {
myCoordsAccessor = coordAccessor;
}
static class WeakRedrawTimer implements ActionListener {
private WeakReference<TerminalPanel> ref;
public WeakRedrawTimer(TerminalPanel terminalPanel) {
this.ref = new WeakReference<TerminalPanel>(terminalPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
TerminalPanel terminalPanel = ref.get();
if (terminalPanel != null) {
terminalPanel.myCursor.changeStateIfNeeded();
if (terminalPanel.needScrollUpdate.getAndSet(false)) {
terminalPanel.updateScrolling();
}
if (terminalPanel.needRepaint.getAndSet(false)) {
try {
terminalPanel.doRepaint();
} catch (Exception ex) {
LOG.error("Error while terminal panel redraw", ex);
}
}
} else { // terminalPanel was garbage collected
Timer timer = (Timer) e.getSource();
timer.removeActionListener(this);
timer.stop();
}
}
}
@Override
public void terminalMouseModeSet(MouseMode mode) {
myMouseMode = mode;
}
private boolean isMouseReporting() {
return myMouseMode != MouseMode.MOUSE_REPORTING_NONE;
}
private void scrollToBottom() {
myBoundedRangeModel.setValue(myTermSize.height);
}
private void moveScrollBar(int k) {
myBoundedRangeModel.setValue(myBoundedRangeModel.getValue() + k);
}
protected Font createFont() {
return mySettingsProvider.getTerminalFont();
}
protected Point panelToCharCoords(final Point p) {
int x = Math.min(p.x / myCharSize.width, getColumnCount() - 1);
x = Math.max(0, x);
int y = Math.min(p.y / myCharSize.height, getRowCount() - 1) + myClientScrollOrigin;
return new Point(x, y);
}
protected Point charToPanelCoords(final Point p) {
return new Point(p.x * myCharSize.width, (p.y - myClientScrollOrigin) * myCharSize.height);
}
void setUpClipboard() {
myClipboard = Toolkit.getDefaultToolkit().getSystemSelection();
if (myClipboard == null) {
myClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
}
protected void copySelection(final Point selectionStart, final Point selectionEnd) {
if (selectionStart == null || selectionEnd == null) {
return;
}
final String selectionText = SelectionUtil
.getSelectionText(selectionStart, selectionEnd, myTerminalTextBuffer);
if (selectionText.length() != 0) {
try {
setCopyContents(new StringSelection(selectionText));
} catch (final IllegalStateException e) {
LOG.error("Could not set clipboard:", e);
}
}
}
protected void setCopyContents(StringSelection selection) {
myClipboard.setContents(selection, this);
}
protected void pasteSelection() {
final String selection = getClipboardString();
if (selection == null) {
return;
}
try {
myTerminalStarter.sendString(selection);
} catch (RuntimeException e) {
LOG.info(e);
}
}
private String getClipboardString() {
try {
return getClipboardContent();
} catch (final Exception e) {
LOG.info(e);
}
return null;
}
protected String getClipboardContent() throws IOException, UnsupportedFlavorException {
try {
return (String) myClipboard.getData(DataFlavor.stringFlavor);
} catch (Exception e) {
LOG.info(e);
return null;
}
}
/* Do not care
*/
public void lostOwnership(final Clipboard clipboard, final Transferable contents) {
}
protected void drawImage(Graphics2D gfx, BufferedImage image, int x, int y, ImageObserver observer) {
gfx.drawImage(image, x, y,
image.getWidth(), image.getHeight(), observer);
}
protected BufferedImage createBufferedImage(int width, int height) {
return new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
}
private void sizeTerminalFromComponent() {
if (myTerminalStarter != null) {
final int newWidth = getWidth() / myCharSize.width;
final int newHeight = getHeight() / myCharSize.height;
if (newHeight > 0 && newWidth > 0) {
final Dimension newSize = new Dimension(newWidth, newHeight);
myTerminalStarter.postResize(newSize, RequestOrigin.User);
}
}
}
public void setTerminalStarter(final TerminalStarter terminalStarter) {
myTerminalStarter = terminalStarter;
sizeTerminalFromComponent();
}
public void setKeyListener(final KeyListener keyListener) {
this.myKeyListener = keyListener;
}
public Dimension requestResize(final Dimension newSize,
final RequestOrigin origin,
int cursorY,
JediTerminal.ResizeHandler resizeHandler) {
if (!newSize.equals(myTermSize)) {
myTerminalTextBuffer.lock();
try {
myTerminalTextBuffer.resize(newSize, origin, cursorY, resizeHandler, mySelection);
myTermSize = (Dimension) newSize.clone();
final Dimension pixelDimension = new Dimension(getPixelWidth(), getPixelHeight());
setPreferredSize(pixelDimension);
if (myTerminalPanelListener != null) {
myTerminalPanelListener.onPanelResize(pixelDimension, origin);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
} finally {
myTerminalTextBuffer.unlock();
}
}
return new Dimension(getPixelWidth(), getPixelHeight());
}
public void setTerminalPanelListener(final TerminalPanelListener resizeDelegate) {
myTerminalPanelListener = resizeDelegate;
}
private void establishFontMetrics() {
final BufferedImage img = createBufferedImage(1, 1);
final Graphics2D graphics = img.createGraphics();
graphics.setFont(myNormalFont);
final float lineSpace = mySettingsProvider.getLineSpace();
final FontMetrics fo = graphics.getFontMetrics();
myDescent = fo.getDescent();
myCharSize.width = fo.charWidth('W');
myCharSize.height = fo.getHeight() + (int) (lineSpace * 2);
myDescent += lineSpace;
myMonospaced = isMonospaced(fo);
if (!myMonospaced) {
LOG.info("WARNING: Font " + myNormalFont.getName() + " is non-monospaced");
}
img.flush();
graphics.dispose();
}
private static boolean isMonospaced(FontMetrics fontMetrics) {
boolean isMonospaced = true;
int charWidth = -1;
for (int codePoint = 0; codePoint < 128; codePoint++) {
if (Character.isValidCodePoint(codePoint)) {
char character = (char) codePoint;
if (isWordCharacter(character)) {
int w = fontMetrics.charWidth(character);
if (charWidth != -1) {
if (w != charWidth) {
isMonospaced = false;
break;
}
} else {
charWidth = w;
}
}
}
}
return isMonospaced;
}
private static boolean isWordCharacter(char character) {
return Character.isLetterOrDigit(character);
}
protected void setupAntialiasing(Graphics graphics) {
if (graphics instanceof Graphics2D) {
Graphics2D myGfx = (Graphics2D) graphics;
final Object mode = mySettingsProvider.useAntialiasing() ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
: RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
final RenderingHints hints = new RenderingHints(
RenderingHints.KEY_TEXT_ANTIALIASING, mode);
myGfx.setRenderingHints(hints);
}
}
@Override
public Color getBackground() {
return getPalette().getColor(myStyleState.getBackground());
}
@Override
public Color getForeground() {
return getPalette().getColor(myStyleState.getForeground());
}
@Override
public void paintComponent(final Graphics g) {
final Graphics2D gfx = (Graphics2D) g;
setupAntialiasing(gfx);
gfx.setColor(getBackground());
gfx.fillRect(0, 0, getWidth(), getHeight());
myTerminalTextBuffer.processHistoryAndScreenLines(myClientScrollOrigin, new StyledTextConsumer() {
final int columnCount = getColumnCount();
@Override
public void consume(int x, int y, @NotNull TextStyle style, @NotNull CharBuffer characters, int startRow) {
int row = y - startRow;
drawCharacters(x, row, style, characters, gfx);
if (mySelection != null) {
Pair<Integer, Integer> interval = mySelection.intersect(x, row + myClientScrollOrigin, characters.length());
if (interval != null) {
TextStyle selectionStyle = getSelectionStyle(style);
drawCharacters(interval.first, row, selectionStyle, characters.subBuffer(interval.first - x, interval.second), gfx);
}
}
}
@Override
public void consumeNul(int x, int y, int nulIndex, TextStyle style, CharBuffer characters, int startRow) {
int row = y - startRow;
if (mySelection != null) {
// compute intersection with all NUL areas, non-breaking
Pair<Integer, Integer> interval = mySelection.intersect(nulIndex, row + myClientScrollOrigin, columnCount - nulIndex);
if (interval != null) {
TextStyle selectionStyle = getSelectionStyle(style);
drawCharacters(x, row, selectionStyle, characters, gfx);
return;
}
}
drawCharacters(x, row, style, characters, gfx);
}
@Override
public void consumeQueue(int x, int y, int nulIndex, int startRow) {
if (x < columnCount) {
consumeNul(x, y, nulIndex, TextStyle.EMPTY, new CharBuffer(CharUtils.EMPTY_CHAR, columnCount - x), startRow);
}
}
});
int cursorY = myCursor.getCoordY();
if (myClientScrollOrigin + getRowCount() > cursorY) {
int cursorX = myCursor.getCoordX();
Pair<Character, TextStyle> sc = myTerminalTextBuffer.getStyledCharAt(cursorX, cursorY);
TextStyle normalStyle = sc.second != null ? sc.second : myStyleState.getCurrent();
TextStyle selectionStyle = getSelectionStyle(normalStyle);
boolean inSelection = inSelection(cursorX, cursorY);
myCursor.drawCursor(sc.first, gfx, inSelection ? selectionStyle : normalStyle);
}
drawInputMethodUncommitedChars(gfx);
drawMargins(gfx, getWidth(), getHeight());
}
private TextStyle getSelectionStyle(TextStyle style) {
TextStyle selectionStyle = style.clone();
if (mySettingsProvider.useInverseSelectionColor()) {
selectionStyle = getInversedStyle(style);
} else {
TextStyle mySelectionStyle = mySettingsProvider.getSelectionColor();
selectionStyle.setBackground(mySelectionStyle.getBackground());
selectionStyle.setForeground(mySelectionStyle.getForeground());
}
return selectionStyle;
}
private void drawInputMethodUncommitedChars(Graphics2D gfx) {
if (myInputMethodUncommitedChars != null && myInputMethodUncommitedChars.length() > 0) {
int x = myCursor.getCoordX() * myCharSize.width;
int y = (myCursor.getCoordY()) * myCharSize.height - 2;
int len = (myInputMethodUncommitedChars.length()) * myCharSize.width;
gfx.setColor(getBackground());
gfx.fillRect(x, (myCursor.getCoordY() - 1) * myCharSize.height, len, myCharSize.height);
gfx.setColor(getForeground());
gfx.setFont(myNormalFont);
gfx.drawString(myInputMethodUncommitedChars, x, y);
Stroke saved = gfx.getStroke();
BasicStroke dotted = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{0, 2, 0, 2}, 0);
gfx.setStroke(dotted);
gfx.drawLine(x, y, x + len, y);
gfx.setStroke(saved);
}
}
private boolean inSelection(int x, int y) {
return mySelection != null && mySelection.contains(new Point(x, y));
}
@Override
public void processKeyEvent(final KeyEvent e) {
handleKeyEvent(e);
e.consume();
}
public void handleKeyEvent(KeyEvent e) {
final int id = e.getID();
if (id == KeyEvent.KEY_PRESSED) {
myKeyListener.keyPressed(e);
} else if (id == KeyEvent.KEY_RELEASED) {
/* keyReleased(e); */
} else if (id == KeyEvent.KEY_TYPED) {
myKeyListener.keyTyped(e);
}
}
public int getPixelWidth() {
return myCharSize.width * myTermSize.width;
}
public int getPixelHeight() {
return myCharSize.height * myTermSize.height;
}
public int getColumnCount() {
return myTermSize.width;
}
public int getRowCount() {
return myTermSize.height;
}
public String getWindowTitle() {
return myWindowTitle;
}
public void addTerminalMouseListener(final TerminalMouseListener listener) {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) {
Point p = panelToCharCoords(e.getPoint());
listener.mousePressed(p.x, p.y, e);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) {
Point p = panelToCharCoords(e.getPoint());
listener.mouseReleased(p.x, p.y, e);
}
}
});
addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) {
mySelection = null;
Point p = panelToCharCoords(e.getPoint());
listener.mouseWheelMoved(p.x, p.y, e);
}
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) {
Point p = panelToCharCoords(e.getPoint());
listener.mouseMoved(p.x, p.y, e);
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) {
Point p = panelToCharCoords(e.getPoint());
listener.mouseDragged(p.x, p.y, e);
}
}
});
}
public void initKeyHandler() {
setKeyListener(new TerminalKeyHandler());
}
public enum TerminalCursorState {
SHOWING, HIDDEN, NO_FOCUS;
}
public class TerminalCursor {
// cursor state
private boolean myCursorIsShown; // blinking state
protected Point myCursorCoordinates = new Point();
// terminal modes
private boolean myShouldDrawCursor = true;
private boolean myBlinking = true;
private long myLastCursorChange;
private boolean myCursorHasChanged;
public void setX(int x) {
myCursorCoordinates.x = x;
cursorChanged();
}
public void setY(int y) {
myCursorCoordinates.y = y;
cursorChanged();
}
public int getCoordX() {
return myCursorCoordinates.x;
}
public int getCoordY() {
return myCursorCoordinates.y - 1 - myClientScrollOrigin;
}
public void setShouldDrawCursor(boolean shouldDrawCursor) {
myShouldDrawCursor = shouldDrawCursor;
}
public void setBlinking(boolean blinking) {
myBlinking = blinking;
}
public boolean isBlinking() {
return myBlinking && (getBlinkingPeriod() > 0);
}
public void cursorChanged() {
myCursorHasChanged = true;
myLastCursorChange = System.currentTimeMillis();
repaint();
}
private boolean cursorShouldChangeBlinkState(long currentTime) {
return currentTime - myLastCursorChange > getBlinkingPeriod();
}
public void changeStateIfNeeded() {
if (!isFocusOwner()) {
return;
}
long currentTime = System.currentTimeMillis();
if (cursorShouldChangeBlinkState(currentTime)) {
myCursorIsShown = !myCursorIsShown;
myLastCursorChange = currentTime;
myCursorHasChanged = false;
repaint();
}
}
private TerminalCursorState computeBlinkingState() {
if (!isBlinking() || myCursorHasChanged || myCursorIsShown) {
return TerminalCursorState.SHOWING;
}
return TerminalCursorState.HIDDEN;
}
private TerminalCursorState computeCursorState() {
if (!myShouldDrawCursor) {
return TerminalCursorState.HIDDEN;
}
if (!isFocusOwner()) {
return TerminalCursorState.NO_FOCUS;
}
return computeBlinkingState();
}
public void drawCursor(char c, Graphics2D gfx, TextStyle style) {
TerminalCursorState state = computeCursorState();
// hidden: do nothing
if (state == TerminalCursorState.HIDDEN) {
return;
} else {
final int x = getCoordX();
final int y = getCoordY();
if (y >= 0 && y < myTermSize.height) {
if (state == TerminalCursorState.SHOWING) {
TextStyle styleToDraw = getInversedStyle(style);
drawCharacters(x, y, styleToDraw, new CharBuffer(c, 1), gfx);
} else if (state == TerminalCursorState.NO_FOCUS) {
int xCoord = x * myCharSize.width;
int yCoord = y * myCharSize.height;
gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun())));
gfx.drawRect(xCoord, yCoord, myCharSize.width - 1, myCharSize.height - 1);
}
}
}
}
}
private int getBlinkingPeriod() {
if (myBlinkingPeriod != mySettingsProvider.caretBlinkingMs()) {
setBlinkingPeriod(mySettingsProvider.caretBlinkingMs());
}
return myBlinkingPeriod;
}
protected void drawImage(Graphics2D g, BufferedImage image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) {
g.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
}
private TextStyle getInversedStyle(TextStyle style) {
TextStyle selectionStyle;
selectionStyle = style.clone();
selectionStyle.setOption(Option.INVERSE, !selectionStyle.hasOption(Option.INVERSE));
if (selectionStyle.getForeground() == null) {
selectionStyle.setForeground(myStyleState.getForeground());
}
if (selectionStyle.getBackground() == null) {
selectionStyle.setBackground(myStyleState.getBackground());
}
return selectionStyle;
}
private void drawCharacters(int x, int y, TextStyle style, CharBuffer buf, Graphics2D gfx) {
int xCoord = x * myCharSize.width;
int yCoord = y * myCharSize.height;
if (xCoord < 0 || xCoord > getWidth() || yCoord < 0 || yCoord > getHeight()) {
return;
}
gfx.setColor(getPalette().getColor(myStyleState.getBackground(style.getBackgroundForRun())));
int textLength = CharUtils.getTextLength(buf.getBuf(), buf.getStart(), buf.length());
gfx.fillRect(xCoord,
yCoord,
Math.min(textLength * myCharSize.width, getWidth() - xCoord),
Math.min(myCharSize.height, getHeight() - yCoord));
if (buf.isNul()) {
return; // nothing more to do
}
drawChars(x, y, buf, style, gfx);
gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun())));
int baseLine = (y + 1) * myCharSize.height - myDescent;
if (style.hasOption(TextStyle.Option.UNDERLINED)) {
gfx.drawLine(xCoord, baseLine + 1, (x + textLength) * myCharSize.width, baseLine + 1);
}
}
/**
* Draw every char in separate terminal cell to guaranty equal width for different lines.
* Nevertheless to improve kerning we draw word characters as one block for monospaced fonts.
*/
private void drawChars(int x, int y, CharBuffer buf, TextStyle style, Graphics2D gfx) {
int newBlockLen = 1;
int offset = 0;
int drawCharsOffset = 0;
// workaround to fix Swing bad rendering of bold special chars on Linux
// TODO required for italic?
CharBuffer renderingBuffer;
if (mySettingsProvider.DECCompatibilityMode() && style.hasOption(TextStyle.Option.BOLD)) {
renderingBuffer = CharUtils.heavyDecCompatibleBuffer(buf);
} else {
renderingBuffer = buf;
}
while (offset + newBlockLen <= buf.length()) {
Font font = getFontToDisplay(buf.charAt(offset + newBlockLen - 1), style);
// while (myMonospaced && (offset + newBlockLen < buf.getLength()) && isWordCharacter(buf.charAt(offset + newBlockLen - 1))
// && (font == getFontToDisplay(buf.charAt(offset + newBlockLen - 1), style))) {
// newBlockLen++;
// }
gfx.setFont(font);
int descent = gfx.getFontMetrics(font).getDescent();
int baseLine = (y + 1) * myCharSize.height - descent;
int xCoord = (x + drawCharsOffset) * myCharSize.width;
int textLength = CharUtils.getTextLength(buf.getBuf(), buf.getStart() + offset, newBlockLen);
int yCoord = y * myCharSize.height;
gfx.setClip(xCoord,
yCoord,
Math.min(textLength * myCharSize.width, getWidth() - xCoord),
Math.min(myCharSize.height, getHeight() - yCoord));
gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun())));
gfx.drawChars(renderingBuffer.getBuf(), buf.getStart() + offset, newBlockLen, xCoord, baseLine);
drawCharsOffset += textLength;
offset += newBlockLen;
newBlockLen = 1;
}
gfx.setClip(null);
}
protected Font getFontToDisplay(char c, TextStyle style) {
boolean bold = style.hasOption(TextStyle.Option.BOLD);
boolean italic = style.hasOption(TextStyle.Option.ITALIC);
// workaround to fix Swing bad rendering of bold special chars on Linux
if (bold && mySettingsProvider.DECCompatibilityMode() && CharacterSets.isDecBoxChar(c)) {
return myNormalFont;
}
return bold ? (italic ? myBoldItalicFont : myBoldFont)
: (italic ? myItalicFont : myNormalFont);
}
private ColorPalette getPalette() {
return mySettingsProvider.getTerminalColorPalette();
}
private void drawMargins(Graphics2D gfx, int width, int height) {
gfx.setColor(getBackground());
gfx.fillRect(0, height, getWidth(), getHeight() - height);
gfx.fillRect(width, 0, getWidth() - width, getHeight());
}
public void scrollArea(final int scrollRegionTop, final int scrollRegionSize, int dy) {
if (dy < 0) {
needScrollUpdate.set(true);
}
mySelection = null;
}
private void updateScrolling() {
if (myScrollingEnabled) {
myBoundedRangeModel
.setRangeProperties(0, myTermSize.height, -myTerminalTextBuffer.getHistoryBuffer().getLineCount(), myTermSize.height, false);
} else {
myBoundedRangeModel.setRangeProperties(0, myTermSize.height, 0, myTermSize.height, false);
}
}
public void setCursor(final int x, final int y) {
myCursor.setX(x);
myCursor.setY(y);
}
public void beep() {
if (mySettingsProvider.audibleBell()) {
Toolkit.getDefaultToolkit().beep();
}
}
public BoundedRangeModel getBoundedRangeModel() {
return myBoundedRangeModel;
}
public TerminalTextBuffer getTerminalTextBuffer() {
return myTerminalTextBuffer;
}
public TerminalSelection getSelection() {
return mySelection;
}
public LinesBuffer getScrollBuffer() {
return myTerminalTextBuffer.getHistoryBuffer();
}
@Override
public void setCursorVisible(boolean shouldDrawCursor) {
myCursor.setShouldDrawCursor(shouldDrawCursor);
}
protected JPopupMenu createPopupMenu() {
JPopupMenu popup = new JPopupMenu();
TerminalAction.addToMenu(popup, this);
return popup;
}
public void setScrollingEnabled(boolean scrollingEnabled) {
myScrollingEnabled = scrollingEnabled;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
@Override
public void setBlinkingCursor(boolean enabled) {
myCursor.setBlinking(enabled);
}
public TerminalCursor getTerminalCursor() {
return myCursor;
}
public TerminalOutputStream getTerminalOutputStream() {
return myTerminalStarter;
}
@Override
public void setWindowTitle(String name) {
myWindowTitle = name;
if (myTerminalPanelListener != null) {
myTerminalPanelListener.onTitleChanged(myWindowTitle);
}
}
@Override
public void setCurrentPath(String path) {
myCurrentPath = path;
}
@Override
public List<TerminalAction> getActions() {
return Lists.newArrayList(
new TerminalAction("Copy", mySettingsProvider.getCopyKeyStrokes(), new Predicate<KeyEvent>() {
@Override
public boolean apply(KeyEvent input) {
return handleCopy(true);
}
}).withMnemonicKey(KeyEvent.VK_C).withEnabledSupplier(new Supplier<Boolean>() {
@Override
public Boolean get() {
return mySelection != null;
}
}),
new TerminalAction("Paste", mySettingsProvider.getPasteKeyStrokes(), new Predicate<KeyEvent>() {
@Override
public boolean apply(KeyEvent input) {
handlePaste();
return true;
}
}).withMnemonicKey(KeyEvent.VK_P).withEnabledSupplier(new Supplier<Boolean>() {
@Override
public Boolean get() {
return getClipboardString() != null;
}
}),
new TerminalAction("Clear Buffer", mySettingsProvider.getClearBufferKeyStrokes(), new Predicate<KeyEvent>() {
@Override
public boolean apply(KeyEvent input) {
clearBuffer();
return true;
}
}).withMnemonicKey(KeyEvent.VK_K).withEnabledSupplier(new Supplier<Boolean>() {
@Override
public Boolean get() {
return !myTerminalTextBuffer.isUsingAlternateBuffer();
}
}).separatorBefore(true)
);
}
private void clearBuffer() {
if (!myTerminalTextBuffer.isUsingAlternateBuffer()) {
myTerminalTextBuffer.clearHistory();
if (myCoordsAccessor != null && myCoordsAccessor.getY()>0) {
TerminalLine line = myTerminalTextBuffer.getLine(myCoordsAccessor.getY() - 1);
myTerminalTextBuffer.clearAll();
myCoordsAccessor.setY(0);
myCursor.setY(1);
myTerminalTextBuffer.addLine(line);
}
updateScrolling();
myClientScrollOrigin = myBoundedRangeModel.getValue();
}
}
@Override
public TerminalActionProvider getNextProvider() {
return myNextActionProvider;
}
@Override
public void setNextProvider(TerminalActionProvider provider) {
myNextActionProvider = provider;
}
private void processTerminalKeyPressed(KeyEvent e) {
try {
final int keycode = e.getKeyCode();
final char keychar = e.getKeyChar();
// numLock does not change the code sent by keypad VK_DELETE
// although it send the char '.'
if (keycode == KeyEvent.VK_DELETE && keychar == '.') {
myTerminalStarter.sendBytes(new byte[]{'.'});
return;
}
// CTRL + Space is not handled in KeyEvent; handle it manually
else if (keychar == ' ' && (e.getModifiers() & KeyEvent.CTRL_MASK) != 0) {
myTerminalStarter.sendBytes(new byte[]{Ascii.NUL});
return;
}
final byte[] code = myTerminalStarter.getCode(keycode);
if (code != null) {
myTerminalStarter.sendBytes(code);
if (mySettingsProvider.scrollToBottomOnTyping() && isCodeThatScrolls(keycode)) {
scrollToBottom();
}
} else if ((keychar & 0xff00) == 0) {
final byte[] obuffer = new byte[1];
obuffer[0] = (byte) keychar;
myTerminalStarter.sendBytes(obuffer);
if (mySettingsProvider.scrollToBottomOnTyping()) {
scrollToBottom();
}
}
} catch (final Exception ex) {
LOG.error("Error sending key to emulator", ex);
}
}
private static boolean isCodeThatScrolls(int keycode) {
return keycode == KeyEvent.VK_UP
|| keycode == KeyEvent.VK_DOWN
|| keycode == KeyEvent.VK_LEFT
|| keycode == KeyEvent.VK_RIGHT
|| keycode == KeyEvent.VK_BACK_SPACE
|| keycode == KeyEvent.VK_DELETE;
}
private void processTerminalKeyTyped(KeyEvent e) {
final char keychar = e.getKeyChar();
if ((keychar & 0xff00) != 0) {
final char[] foo = new char[1];
foo[0] = keychar;
try {
myTerminalStarter.sendString(new String(foo));
if (mySettingsProvider.scrollToBottomOnTyping()) {
scrollToBottom();
}
} catch (final RuntimeException ex) {
LOG.error("Error sending key to emulator", ex);
}
}
}
public class TerminalKeyHandler implements KeyListener {
public TerminalKeyHandler() {
}
public void keyPressed(final KeyEvent e) {
if (!TerminalAction.processEvent(TerminalPanel.this, e)) {
processTerminalKeyPressed(e);
}
}
public void keyTyped(final KeyEvent e) {
processTerminalKeyTyped(e);
}
//Ignore releases
public void keyReleased(KeyEvent e) {
}
}
private void handlePaste() {
pasteSelection();
}
// "unselect" is needed to handle Ctrl+C copy shortcut collision with ^C signal shortcut
private boolean handleCopy(boolean unselect) {
if (mySelection != null) {
Pair<Point, Point> points = mySelection.pointsForRun(myTermSize.width);
copySelection(points.first, points.second);
if (unselect) {
mySelection = null;
repaint();
}
return true;
}
return false;
}
/**
* InputMethod implementation
* For details read http://docs.oracle.com/javase/7/docs/technotes/guides/imf/api-tutorial.html
*/
@Override
protected void processInputMethodEvent(InputMethodEvent e) {
int commitCount = e.getCommittedCharacterCount();
if (commitCount > 0) {
myInputMethodUncommitedChars = null;
AttributedCharacterIterator text = e.getText();
if (text != null) {
//noinspection ForLoopThatDoesntUseLoopVariable
for (char c = text.first(); commitCount > 0; c = text.next(), commitCount--) {
if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
int id = (c & 0xff00) == 0 ? KeyEvent.KEY_PRESSED : KeyEvent.KEY_TYPED;
handleKeyEvent(new KeyEvent(this, id, e.getWhen(), 0, 0, c));
}
}
}
} else {
myInputMethodUncommitedChars = uncommitedChars(e.getText());
}
}
private static String uncommitedChars(AttributedCharacterIterator text) {
StringBuilder sb = new StringBuilder();
for (char c = text.first(); c != CharacterIterator.DONE; c = text.next()) {
if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
sb.append(c);
}
}
return sb.toString();
}
@Override
public InputMethodRequests getInputMethodRequests() {
return new MyInputMethodRequests();
}
private class MyInputMethodRequests implements InputMethodRequests {
@Override
public Rectangle getTextLocation(TextHitInfo offset) {
Rectangle r = new Rectangle(myCursor.getCoordX() * myCharSize.width, (myCursor.getCoordY() + 1) * myCharSize.height,
0, 0);
Point p = TerminalPanel.this.getLocationOnScreen();
r.translate(p.x, p.y);
return r;
}
@Nullable
@Override
public TextHitInfo getLocationOffset(int x, int y) {
return null;
}
@Override
public int getInsertPositionOffset() {
return 0;
}
@Override
public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Override
public int getCommittedTextLength() {
return 0;
}
@Nullable
@Override
public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Nullable
@Override
public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
}
}
| patsimm/jediterm | src-terminal/com/jediterm/terminal/ui/TerminalPanel.java | Java | lgpl-3.0 | 42,325 |
/* The LibVMI Library is an introspection library that simplifies access to
* memory in a target virtual machine or in a file containing a dump of
* a system's physical memory. LibVMI is based on the XenAccess Library.
*
* Copyright 2011 Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government
* retains certain rights in this software.
*
* Author: Bryan D. Payne (bdpayne@acm.org)
* Author: Tamas K Lengyel (tamas.lengyel@zentific.com)
*
* This file is part of LibVMI.
*
* LibVMI 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.
*
* LibVMI 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 LibVMI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KVM_H
#define KVM_H
status_t kvm_init(
vmi_instance_t vmi,
uint32_t init_flags,
void *init_data);
status_t kvm_init_vmi(
vmi_instance_t vmi,
uint32_t init_flags,
void *init_data);
void kvm_destroy(
vmi_instance_t vmi);
uint64_t kvm_get_id_from_name(
vmi_instance_t vmi,
const char *name);
status_t kvm_get_name_from_id(
vmi_instance_t vmi,
uint64_t domainid,
char **name);
uint64_t kvm_get_id(
vmi_instance_t vmi);
void kvm_set_id(
vmi_instance_t vmi,
uint64_t domainid);
status_t kvm_check_id(
vmi_instance_t vmi,
uint64_t domainid);
status_t kvm_get_name(
vmi_instance_t vmi,
char **name);
void kvm_set_name(
vmi_instance_t vmi,
const char *name);
status_t kvm_get_memsize(
vmi_instance_t vmi,
uint64_t *allocate_ram_size,
addr_t *maximum_physical_address);
status_t kvm_get_vcpureg(
vmi_instance_t vmi,
uint64_t *value,
reg_t reg,
unsigned long vcpu);
addr_t kvm_pfn_to_mfn(
vmi_instance_t vmi,
addr_t pfn);
void *kvm_read_page(
vmi_instance_t vmi,
addr_t page);
status_t kvm_write(
vmi_instance_t vmi,
addr_t paddr,
void *buf,
uint32_t length);
int kvm_is_pv(
vmi_instance_t vmi);
status_t kvm_test(
uint64_t domainid,
const char *name,
uint64_t init_flags,
void* init_data);
status_t kvm_pause_vm(
vmi_instance_t vmi);
status_t kvm_resume_vm(
vmi_instance_t vmi);
status_t kvm_create_shm_snapshot(
vmi_instance_t vmi);
status_t kvm_destroy_shm_snapshot(
vmi_instance_t vmi);
size_t kvm_get_dgpma(
vmi_instance_t vmi,
addr_t paddr,
void** medial_addr_ptr,
size_t count);
size_t kvm_get_dgvma(
vmi_instance_t vmi,
addr_t vaddr,
pid_t pid,
void** medial_addr_ptr,
size_t count);
static inline status_t
driver_kvm_setup(vmi_instance_t vmi)
{
driver_interface_t driver = { 0 };
driver.initialized = true;
driver.init_ptr = &kvm_init;
driver.init_vmi_ptr = &kvm_init_vmi;
driver.destroy_ptr = &kvm_destroy;
driver.get_id_from_name_ptr = &kvm_get_id_from_name;
driver.get_name_from_id_ptr = &kvm_get_name_from_id;
driver.get_id_ptr = &kvm_get_id;
driver.set_id_ptr = &kvm_set_id;
driver.check_id_ptr = &kvm_check_id;
driver.get_name_ptr = &kvm_get_name;
driver.set_name_ptr = &kvm_set_name;
driver.get_memsize_ptr = &kvm_get_memsize;
driver.get_vcpureg_ptr = &kvm_get_vcpureg;
driver.read_page_ptr = &kvm_read_page;
driver.write_ptr = &kvm_write;
driver.is_pv_ptr = &kvm_is_pv;
driver.pause_vm_ptr = &kvm_pause_vm;
driver.resume_vm_ptr = &kvm_resume_vm;
#ifdef ENABLE_SHM_SNAPSHOT
driver.create_shm_snapshot_ptr = &kvm_create_shm_snapshot;
driver.destroy_shm_snapshot_ptr = &kvm_destroy_shm_snapshot;
driver.get_dgpma_ptr = &kvm_get_dgpma;
driver.get_dgvma_ptr = &kvm_get_dgvma;
#endif
vmi->driver = driver;
return VMI_SUCCESS;
}
#endif /* KVM_H */
| bentau/libvmi | libvmi/driver/kvm/kvm.h | C | lgpl-3.0 | 4,171 |
/* GIMP - The GNU Image Manipulation Program
* Copyright (C) 1995 Spencer Kimball and Peter Mattis
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <gegl.h>
#include <gtk/gtk.h>
#include "libgimpwidgets/gimpwidgets.h"
#include "actions-types.h"
#include "core/gimpcontext.h"
#include "core/gimpdata.h"
#include "widgets/gimpactiongroup.h"
#include "widgets/gimphelp-ids.h"
#include "actions.h"
#include "data-commands.h"
#include "dynamics-actions.h"
#include "gimp-intl.h"
static const GimpActionEntry dynamics_actions[] =
{
{ "dynamics-popup", GIMP_STOCK_DYNAMICS,
NC_("dynamics-action", "Paint Dynamics Menu"), NULL, NULL, NULL,
GIMP_HELP_DYNAMICS_DIALOG },
{ "dynamics-new", "document-new",
NC_("dynamics-action", "_New Dynamics"), NULL,
NC_("dynamics-action", "Create a new dynamics"),
G_CALLBACK (data_new_cmd_callback),
GIMP_HELP_DYNAMICS_NEW },
{ "dynamics-duplicate", GIMP_STOCK_DUPLICATE,
NC_("dynamics-action", "D_uplicate Dynamics"), NULL,
NC_("dynamics-action", "Duplicate this dynamics"),
G_CALLBACK (data_duplicate_cmd_callback),
GIMP_HELP_DYNAMICS_DUPLICATE },
{ "dynamics-copy-location", "edit-copy",
NC_("dynamics-action", "Copy Dynamics _Location"), NULL,
NC_("dynamics-action", "Copy dynamics file location to clipboard"),
G_CALLBACK (data_copy_location_cmd_callback),
GIMP_HELP_DYNAMICS_COPY_LOCATION },
{ "dynamics-show-in-file-manager", "gtk-directory",
NC_("dynamics-action", "Show in _File Manager"), NULL,
NC_("dynamics-action", "Show dynamics file location in the file manager"),
G_CALLBACK (data_show_in_file_manager_cmd_callback),
GIMP_HELP_DYNAMICS_SHOW_IN_FILE_MANAGER },
{ "dynamics-delete", "edit-delete",
NC_("dynamics-action", "_Delete Dynamics"), NULL,
NC_("dynamics-action", "Delete this dynamics"),
G_CALLBACK (data_delete_cmd_callback),
GIMP_HELP_DYNAMICS_DELETE },
{ "dynamics-refresh", "view-refresh",
NC_("dynamics-action", "_Refresh Dynamics"), NULL,
NC_("dynamics-action", "Refresh dynamics"),
G_CALLBACK (data_refresh_cmd_callback),
GIMP_HELP_DYNAMICS_REFRESH }
};
static const GimpStringActionEntry dynamics_edit_actions[] =
{
{ "dynamics-edit", "gtk-edit",
NC_("dynamics-action", "_Edit Dynamics..."), NULL,
NC_("dynamics-action", "Edit dynamics"),
"gimp-dynamics-editor",
GIMP_HELP_DYNAMICS_EDIT }
};
void
dynamics_actions_setup (GimpActionGroup *group)
{
gimp_action_group_add_actions (group, "dynamics-action",
dynamics_actions,
G_N_ELEMENTS (dynamics_actions));
gimp_action_group_add_string_actions (group, "dynamics-action",
dynamics_edit_actions,
G_N_ELEMENTS (dynamics_edit_actions),
G_CALLBACK (data_edit_cmd_callback));
}
void
dynamics_actions_update (GimpActionGroup *group,
gpointer user_data)
{
GimpContext *context = action_data_get_context (user_data);
GimpDynamics *dynamics = NULL;
GimpData *data = NULL;
GFile *file = NULL;
if (context)
{
dynamics = gimp_context_get_dynamics (context);
if (dynamics)
{
data = GIMP_DATA (dynamics);
file = gimp_data_get_file (data);
}
}
#define SET_SENSITIVE(action,condition) \
gimp_action_group_set_action_sensitive (group, action, (condition) != 0)
SET_SENSITIVE ("dynamics-edit", dynamics);
SET_SENSITIVE ("dynamics-duplicate", dynamics && GIMP_DATA_GET_CLASS (data)->duplicate);
SET_SENSITIVE ("dynamics-copy-location", file);
SET_SENSITIVE ("dynamics-show-in-file-manager", file);
SET_SENSITIVE ("dynamics-delete", dynamics && gimp_data_is_deletable (data));
#undef SET_SENSITIVE
}
| relsi/DaVinci | app/actions/dynamics-actions.c | C | lgpl-3.0 | 4,558 |
#! /usr/bin/env python3
"""The Tab Nanny despises ambiguous indentation. She knows no mercy.
tabnanny -- Detection of ambiguous indentation
For the time being this module is intended to be called as a script.
However it is possible to import it into an IDE and use the function
check() described below.
Warning: The API provided by this module is likely to change in future
releases; such changes may not be backward compatible.
"""
# Released to the public domain, by Tim Peters, 15 April 1998.
# XXX Note: this is now a standard library module.
# XXX The API needs to undergo changes however; the current code is too
# XXX script-like. This will be addressed later.
__version__ = "6"
import os
import sys
import getopt
import tokenize
if not hasattr(tokenize, 'NL'):
raise ValueError("tokenize.NL doesn't exist -- tokenize module too old")
__all__ = ["check", "NannyNag", "process_tokens"]
verbose = 0
filename_only = 0
def errprint(*args):
sep = ""
for arg in args:
sys.stderr.write(sep + str(arg))
sep = " "
sys.stderr.write("\n")
def main():
global verbose, filename_only
try:
opts, args = getopt.getopt(sys.argv[1:], "qv")
except getopt.error as msg:
errprint(msg)
return
for o, a in opts:
if o == '-q':
filename_only = filename_only + 1
if o == '-v':
verbose = verbose + 1
if not args:
errprint("Usage:", sys.argv[0], "[-v] file_or_directory ...")
return
for arg in args:
check(arg)
class NannyNag(Exception):
"""
Raised by tokeneater() if detecting an ambiguous indent.
Captured and handled in check().
"""
def __init__(self, lineno, msg, line):
self.lineno, self.msg, self.line = lineno, msg, line
def get_lineno(self):
return self.lineno
def get_msg(self):
return self.msg
def get_line(self):
return self.line
def check(file):
"""check(file_or_dir)
If file_or_dir is a directory and not a symbolic link, then recursively
descend the directory tree named by file_or_dir, checking all .py files
along the way. If file_or_dir is an ordinary Python source file, it is
checked for whitespace related problems. The diagnostic messages are
written to standard output using the print statement.
"""
if os.path.isdir(file) and not os.path.islink(file):
if verbose:
print("%r: listing directory" % (file,))
names = os.listdir(file)
for name in names:
fullname = os.path.join(file, name)
if (os.path.isdir(fullname) and
not os.path.islink(fullname) or
os.path.normcase(name[-3:]) == ".py"):
check(fullname)
return
try:
f = tokenize.open(file)
except OSError as msg:
errprint("%r: I/O Error: %s" % (file, msg))
return
if verbose > 1:
print("checking %r ..." % file)
try:
process_tokens(tokenize.generate_tokens(f.readline))
except tokenize.TokenError as msg:
errprint("%r: Token Error: %s" % (file, msg))
return
except IndentationError as msg:
errprint("%r: Indentation Error: %s" % (file, msg))
return
except NannyNag as nag:
badline = nag.get_lineno()
line = nag.get_line()
if verbose:
print("%r: *** Line %d: trouble in tab city! ***" % (file, badline))
print("offending line: %r" % (line,))
print(nag.get_msg())
else:
if ' ' in file: file = '"' + file + '"'
if filename_only: print(file)
else: print(file, badline, repr(line))
return
finally:
f.close()
if verbose:
print("%r: Clean bill of health." % (file,))
class Whitespace:
# the characters used for space and tab
S, T = ' \t'
# members:
# raw
# the original string
# n
# the number of leading whitespace characters in raw
# nt
# the number of tabs in raw[:n]
# norm
# the normal form as a pair (count, trailing), where:
# count
# a tuple such that raw[:n] contains count[i]
# instances of S * i + T
# trailing
# the number of trailing spaces in raw[:n]
# It's A Theorem that m.indent_level(t) ==
# n.indent_level(t) for all t >= 1 iff m.norm == n.norm.
# is_simple
# true iff raw[:n] is of the form (T*)(S*)
def __init__(self, ws):
self.raw = ws
S, T = Whitespace.S, Whitespace.T
count = []
b = n = nt = 0
for ch in self.raw:
if ch == S:
n = n + 1
b = b + 1
elif ch == T:
n = n + 1
nt = nt + 1
if b >= len(count):
count = count + [0] * (b - len(count) + 1)
count[b] = count[b] + 1
b = 0
else:
break
self.n = n
self.nt = nt
self.norm = tuple(count), b
self.is_simple = len(count) <= 1
# return length of longest contiguous run of spaces (whether or not
# preceding a tab)
def longest_run_of_spaces(self):
count, trailing = self.norm
return max(len(count)-1, trailing)
def indent_level(self, tabsize):
# count, il = self.norm
# for i in range(len(count)):
# if count[i]:
# il = il + (i//tabsize + 1)*tabsize * count[i]
# return il
# quicker:
# il = trailing + sum (i//ts + 1)*ts*count[i] =
# trailing + ts * sum (i//ts + 1)*count[i] =
# trailing + ts * sum i//ts*count[i] + count[i] =
# trailing + ts * [(sum i//ts*count[i]) + (sum count[i])] =
# trailing + ts * [(sum i//ts*count[i]) + num_tabs]
# and note that i//ts*count[i] is 0 when i < ts
count, trailing = self.norm
il = 0
for i in range(tabsize, len(count)):
il = il + i//tabsize * count[i]
return trailing + tabsize * (il + self.nt)
# return true iff self.indent_level(t) == other.indent_level(t)
# for all t >= 1
def equal(self, other):
return self.norm == other.norm
# return a list of tuples (ts, i1, i2) such that
# i1 == self.indent_level(ts) != other.indent_level(ts) == i2.
# Intended to be used after not self.equal(other) is known, in which
# case it will return at least one witnessing tab size.
def not_equal_witness(self, other):
n = max(self.longest_run_of_spaces(),
other.longest_run_of_spaces()) + 1
a = []
for ts in range(1, n+1):
if self.indent_level(ts) != other.indent_level(ts):
a.append( (ts,
self.indent_level(ts),
other.indent_level(ts)) )
return a
# Return True iff self.indent_level(t) < other.indent_level(t)
# for all t >= 1.
# The algorithm is due to Vincent Broman.
# Easy to prove it's correct.
# XXXpost that.
# Trivial to prove n is sharp (consider T vs ST).
# Unknown whether there's a faster general way. I suspected so at
# first, but no longer.
# For the special (but common!) case where M and N are both of the
# form (T*)(S*), M.less(N) iff M.len() < N.len() and
# M.num_tabs() <= N.num_tabs(). Proof is easy but kinda long-winded.
# XXXwrite that up.
# Note that M is of the form (T*)(S*) iff len(M.norm[0]) <= 1.
def less(self, other):
if self.n >= other.n:
return False
if self.is_simple and other.is_simple:
return self.nt <= other.nt
n = max(self.longest_run_of_spaces(),
other.longest_run_of_spaces()) + 1
# the self.n >= other.n test already did it for ts=1
for ts in range(2, n+1):
if self.indent_level(ts) >= other.indent_level(ts):
return False
return True
# return a list of tuples (ts, i1, i2) such that
# i1 == self.indent_level(ts) >= other.indent_level(ts) == i2.
# Intended to be used after not self.less(other) is known, in which
# case it will return at least one witnessing tab size.
def not_less_witness(self, other):
n = max(self.longest_run_of_spaces(),
other.longest_run_of_spaces()) + 1
a = []
for ts in range(1, n+1):
if self.indent_level(ts) >= other.indent_level(ts):
a.append( (ts,
self.indent_level(ts),
other.indent_level(ts)) )
return a
def format_witnesses(w):
firsts = (str(tup[0]) for tup in w)
prefix = "at tab size"
if len(w) > 1:
prefix = prefix + "s"
return prefix + " " + ', '.join(firsts)
def process_tokens(tokens):
INDENT = tokenize.INDENT
DEDENT = tokenize.DEDENT
NEWLINE = tokenize.NEWLINE
JUNK = tokenize.COMMENT, tokenize.NL
indents = [Whitespace("")]
check_equal = 0
for (type, token, start, end, line) in tokens:
if type == NEWLINE:
# a program statement, or ENDMARKER, will eventually follow,
# after some (possibly empty) run of tokens of the form
# (NL | COMMENT)* (INDENT | DEDENT+)?
# If an INDENT appears, setting check_equal is wrong, and will
# be undone when we see the INDENT.
check_equal = 1
elif type == INDENT:
check_equal = 0
thisguy = Whitespace(token)
if not indents[-1].less(thisguy):
witness = indents[-1].not_less_witness(thisguy)
msg = "indent not greater e.g. " + format_witnesses(witness)
raise NannyNag(start[0], msg, line)
indents.append(thisguy)
elif type == DEDENT:
# there's nothing we need to check here! what's important is
# that when the run of DEDENTs ends, the indentation of the
# program statement (or ENDMARKER) that triggered the run is
# equal to what's left at the top of the indents stack
# Ouch! This assert triggers if the last line of the source
# is indented *and* lacks a newline -- then DEDENTs pop out
# of thin air.
# assert check_equal # else no earlier NEWLINE, or an earlier INDENT
check_equal = 1
del indents[-1]
elif check_equal and type not in JUNK:
# this is the first "real token" following a NEWLINE, so it
# must be the first token of the next program statement, or an
# ENDMARKER; the "line" argument exposes the leading whitespace
# for this statement; in the case of ENDMARKER, line is an empty
# string, so will properly match the empty string with which the
# "indents" stack was seeded
check_equal = 0
thisguy = Whitespace(line)
if not indents[-1].equal(thisguy):
witness = indents[-1].not_equal_witness(thisguy)
msg = "indent not equal e.g. " + format_witnesses(witness)
raise NannyNag(start[0], msg, line)
if __name__ == '__main__':
main()
| Orav/kbengine | kbe/src/lib/python/Lib/tabnanny.py | Python | lgpl-3.0 | 11,731 |
/*
* $Id: Chunks.java 3373 2008-05-12 16:21:24Z xlv $
*
* This code is part of the 'iText Tutorial'.
* You can find the complete tutorial at the following address:
* http://itextdocs.lowagie.com/tutorial/
*
* This code 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.
*
* itext-questions@lists.sourceforge.net
*/
package com.lowagie.examples.objects;
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
/**
* Demonstrates some Chunk functionality.
*
* @author blowagie
*/
public class Chunks {
/**
* Demonstrates some Chunk functionality.
*
* @param args no arguments needed here
*/
public static void main(String[] args) {
System.out.println("the Chunk object");
// step 1: creation of a document-object
Document document = new Document();
try {
// step 2:
// we create a writer that listens to the document
PdfWriter.getInstance(document,
new FileOutputStream("Chunks.pdf"));
// step 3: we open the document
document.open();
// step 4:
Chunk fox = new Chunk("quick brown fox");
float superscript = 8.0f;
fox.setTextRise(superscript);
fox.setBackground(new Color(0xFF, 0xDE, 0xAD));
Chunk jumps = new Chunk(" jumps over ");
Chunk dog = new Chunk("the lazy dog");
float subscript = -8.0f;
dog.setTextRise(subscript);
dog.setUnderline(new Color(0xFF, 0x00, 0x00), 3.0f, 0.0f, -5.0f + subscript, 0.0f, PdfContentByte.LINE_CAP_ROUND);
document.add(fox);
document.add(jumps);
document.add(dog);
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
// step 5: we close the document
document.close();
}
} | yogthos/itext | www/examples/com/lowagie/examples/objects/Chunks.java | Java | lgpl-3.0 | 2,050 |
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: android/libcore/luni/src/main/java/javax/xml/xpath/XPathFactory.java
//
#ifndef _JavaxXmlXpathXPathFactory_H_
#define _JavaxXmlXpathXPathFactory_H_
@class JavaLangClassLoader;
@protocol JavaxXmlXpathXPath;
@protocol JavaxXmlXpathXPathFunctionResolver;
@protocol JavaxXmlXpathXPathVariableResolver;
#include "J2ObjC_header.h"
@interface JavaxXmlXpathXPathFactory : NSObject {
}
- (instancetype)init;
+ (JavaxXmlXpathXPathFactory *)newInstance OBJC_METHOD_FAMILY_NONE;
+ (JavaxXmlXpathXPathFactory *)newInstanceWithNSString:(NSString *)uri OBJC_METHOD_FAMILY_NONE;
+ (JavaxXmlXpathXPathFactory *)newInstanceWithNSString:(NSString *)uri
withNSString:(NSString *)factoryClassName
withJavaLangClassLoader:(JavaLangClassLoader *)classLoader OBJC_METHOD_FAMILY_NONE;
- (jboolean)isObjectModelSupportedWithNSString:(NSString *)objectModel;
- (void)setFeatureWithNSString:(NSString *)name
withBoolean:(jboolean)value;
- (jboolean)getFeatureWithNSString:(NSString *)name;
- (void)setXPathVariableResolverWithJavaxXmlXpathXPathVariableResolver:(id<JavaxXmlXpathXPathVariableResolver>)resolver;
- (void)setXPathFunctionResolverWithJavaxXmlXpathXPathFunctionResolver:(id<JavaxXmlXpathXPathFunctionResolver>)resolver;
- (id<JavaxXmlXpathXPath>)newXPath OBJC_METHOD_FAMILY_NONE;
@end
J2OBJC_EMPTY_STATIC_INIT(JavaxXmlXpathXPathFactory)
CF_EXTERN_C_BEGIN
FOUNDATION_EXPORT JavaxXmlXpathXPathFactory *JavaxXmlXpathXPathFactory_newInstance();
FOUNDATION_EXPORT JavaxXmlXpathXPathFactory *JavaxXmlXpathXPathFactory_newInstanceWithNSString_(NSString *uri);
FOUNDATION_EXPORT JavaxXmlXpathXPathFactory *JavaxXmlXpathXPathFactory_newInstanceWithNSString_withNSString_withJavaLangClassLoader_(NSString *uri, NSString *factoryClassName, JavaLangClassLoader *classLoader);
FOUNDATION_EXPORT NSString *JavaxXmlXpathXPathFactory_DEFAULT_PROPERTY_NAME_;
J2OBJC_STATIC_FIELD_GETTER(JavaxXmlXpathXPathFactory, DEFAULT_PROPERTY_NAME_, NSString *)
FOUNDATION_EXPORT NSString *JavaxXmlXpathXPathFactory_DEFAULT_OBJECT_MODEL_URI_;
J2OBJC_STATIC_FIELD_GETTER(JavaxXmlXpathXPathFactory, DEFAULT_OBJECT_MODEL_URI_, NSString *)
CF_EXTERN_C_END
J2OBJC_TYPE_LITERAL_HEADER(JavaxXmlXpathXPathFactory)
#endif // _JavaxXmlXpathXPathFactory_H_
| OpenSoftwareSolutions/PDFReporter | pdfreporter-xcode/j2objc/include/javax/xml/xpath/XPathFactory.h | C | lgpl-3.0 | 2,385 |
var searchData=
[
['_7eanalysis',['~Analysis',['../df/d86/classmknix_1_1_analysis.html#a4813618a04dd0c3098a58b60792f2e34',1,'mknix::Analysis']]],
['_7eanalysisdynamic',['~AnalysisDynamic',['../d4/d8c/classmknix_1_1_analysis_dynamic.html#a85fd7662ea3228c608c6761ffc4e46d4',1,'mknix::AnalysisDynamic']]],
['_7eanalysisstatic',['~AnalysisStatic',['../db/d8f/classmknix_1_1_analysis_static.html#a67877fe7b967f91b1b8c92cf4afe1658',1,'mknix::AnalysisStatic']]],
['_7eanalysisthermaldynamic',['~AnalysisThermalDynamic',['../d5/dd9/classmknix_1_1_analysis_thermal_dynamic.html#ad0dbaa6affc6e4a285d310e209fe2b73',1,'mknix::AnalysisThermalDynamic']]],
['_7eanalysisthermalstatic',['~AnalysisThermalStatic',['../d4/d3e/classmknix_1_1_analysis_thermal_static.html#a0164991e5c2829051b9e886cb07e3af7',1,'mknix::AnalysisThermalStatic']]],
['_7ebody',['~Body',['../dd/de3/classmknix_1_1_body.html#ad58a0a50a821e1adaa5abd1320e5a837',1,'mknix::Body']]],
['_7ecell',['~Cell',['../db/dd4/classmknix_1_1_cell.html#ab4efc3f7c10212304dd776e7b58bb57b',1,'mknix::Cell']]],
['_7ecellrect',['~CellRect',['../dd/d89/classmknix_1_1_cell_rect.html#a966a8afa0dee4990f8231cb7e32d33ee',1,'mknix::CellRect']]],
['_7ecelltetrahedron',['~CellTetrahedron',['../d9/d39/classmknix_1_1_cell_tetrahedron.html#a4ae5db633022a1714da463f4c32ffa03',1,'mknix::CellTetrahedron']]],
['_7ecelltriang',['~CellTriang',['../de/db4/classmknix_1_1_cell_triang.html#af0a12b3f4f6106291f3252716c4be025',1,'mknix::CellTriang']]],
['_7ecompbar',['~CompBar',['../d1/d90/classmknix_1_1_comp_bar.html#aad258dca0df1e017f189fc743baaf150',1,'mknix::CompBar']]],
['_7econstraint',['~Constraint',['../da/dd3/classmknix_1_1_constraint.html#a84cbe5af8074dc229f583d119bbde3e1',1,'mknix::Constraint']]],
['_7econstraintclearance',['~ConstraintClearance',['../d2/d2c/classmknix_1_1_constraint_clearance.html#a1db613ec74403b647fbeb68c91510c50',1,'mknix::ConstraintClearance']]],
['_7econstraintcontact',['~ConstraintContact',['../d8/d6a/classmknix_1_1_constraint_contact.html#a2570dc3ad5c593871f1d5dd4e6302f07',1,'mknix::ConstraintContact']]],
['_7econstraintdistance',['~ConstraintDistance',['../d7/de2/classmknix_1_1_constraint_distance.html#aa39735f682295e2c7b839fddb9eba545',1,'mknix::ConstraintDistance']]],
['_7econstraintfixedaxis',['~ConstraintFixedAxis',['../d7/dcd/classmknix_1_1_constraint_fixed_axis.html#a51f651cd9693210d991b6b16b28a94c9',1,'mknix::ConstraintFixedAxis']]],
['_7econstraintfixedcoordinates',['~ConstraintFixedCoordinates',['../de/dda/classmknix_1_1_constraint_fixed_coordinates.html#ab8fcae0a6b615cbc81d1db67887c1a54',1,'mknix::ConstraintFixedCoordinates']]],
['_7econtact',['~Contact',['../df/dde/classmknix_1_1_contact.html#a409ca0c936dcc34ce4ca1b25780b7635',1,'mknix::Contact']]],
['_7eelemtetrahedron',['~ElemTetrahedron',['../dd/d4d/classmknix_1_1_elem_tetrahedron.html#a2f836d024ff3adf00b94a3371505cff4',1,'mknix::ElemTetrahedron']]],
['_7eelemtriangle',['~ElemTriangle',['../d8/d3f/classmknix_1_1_elem_triangle.html#a7a29ea213e5eb2567702ab1cd01468c4',1,'mknix::ElemTriangle']]],
['_7eflexbody',['~FlexBody',['../dd/d8d/classmknix_1_1_flex_body.html#ad5d295b774afc3b265b629a859ea22d1',1,'mknix::FlexBody']]],
['_7eflexglobalgalerkin',['~FlexGlobalGalerkin',['../d6/d4a/classmknix_1_1_flex_global_galerkin.html#af036ee6bdc4450fd457e0d95b22ace7c',1,'mknix::FlexGlobalGalerkin']]],
['_7eforce',['~Force',['../d5/d3b/classmknix_1_1_force.html#a517004e90c90d84150b3570b74fdcce8',1,'mknix::Force']]],
['_7egausspoint',['~GaussPoint',['../d2/da4/classmknix_1_1_gauss_point.html#a84a09a5e3fa0bf13b6c1d710a838f883',1,'mknix::GaussPoint']]],
['_7eload',['~Load',['../db/d1c/classmknix_1_1_load.html#a79f63ce975fa0c0ad2d9cd8269908b8f',1,'mknix::Load']]],
['_7ematerial',['~Material',['../d6/d4a/classmknix_1_1_material.html#ab0c23c9dfb7119afa0f20e912d4af6e6',1,'mknix::Material']]],
['_7enode',['~Node',['../d3/d25/classmknix_1_1_node.html#adb415bbf3cd9031c1b45f3b2d36282e2',1,'mknix::Node']]],
['_7epoint',['~Point',['../d3/d19/classmknix_1_1_point.html#ad20e0663241df1986b8250a0ab7f2358',1,'mknix::Point']]],
['_7ereader',['~Reader',['../d0/d66/classmknix_1_1_reader.html#a5aa850c593a547a1215a9425e45da74b',1,'mknix::Reader']]],
['_7ereaderconstraints',['~ReaderConstraints',['../d2/dad/classmknix_1_1_reader_constraints.html#ae2c0d3f6e3c0d8fdfd99d4902fa8cd0f',1,'mknix::ReaderConstraints']]],
['_7ereaderflex',['~ReaderFlex',['../d7/d17/classmknix_1_1_reader_flex.html#a41c26a0eff85dc4093f38ec7cbf44bfe',1,'mknix::ReaderFlex']]],
['_7ereaderrigid',['~ReaderRigid',['../df/de5/classmknix_1_1_reader_rigid.html#ad220ff7f0dd151dd86142e6c3b7c4c80',1,'mknix::ReaderRigid']]],
['_7erigidbar',['~RigidBar',['../d6/dd9/classmknix_1_1_rigid_bar.html#aa349d4406824acbd0b29d25d9a2f2da4',1,'mknix::RigidBar::~RigidBar()'],['../d6/dd9/classmknix_1_1_rigid_bar.html#aa349d4406824acbd0b29d25d9a2f2da4',1,'mknix::RigidBar::~RigidBar()']]],
['_7erigidbody',['~RigidBody',['../d0/d13/classmknix_1_1_rigid_body.html#a61c219dee02f49659bc34528c2d0af49',1,'mknix::RigidBody']]],
['_7erigidbody2d',['~RigidBody2D',['../d6/d6d/classmknix_1_1_rigid_body2_d.html#a38d39e70ab2af08776a426fec5dc8f36',1,'mknix::RigidBody2D']]],
['_7erigidbody3d',['~RigidBody3D',['../dd/d2a/classmknix_1_1_rigid_body3_d.html#a34e8faafa4f7be677eca2b1400f85863',1,'mknix::RigidBody3D']]],
['_7erigidbodymasspoint',['~RigidBodyMassPoint',['../d8/de9/classmknix_1_1_rigid_body_mass_point.html#a005fcbbf85deb13c32e87c9a3ef51844',1,'mknix::RigidBodyMassPoint']]],
['_7eshapefunction',['~ShapeFunction',['../dd/d8d/classmknix_1_1_shape_function.html#ac5762f37f460aa48b8d2a53a1f422220',1,'mknix::ShapeFunction']]],
['_7eshapefunctionlinear',['~ShapeFunctionLinear',['../d8/d0e/classmknix_1_1_shape_function_linear.html#a8922b26c916d8befb3f568f91b6cd388',1,'mknix::ShapeFunctionLinear']]],
['_7eshapefunctionmls',['~ShapeFunctionMLS',['../db/d02/classmknix_1_1_shape_function_m_l_s.html#a023ccf7cbc4ad50738271c4807c5f32a',1,'mknix::ShapeFunctionMLS']]],
['_7eshapefunctionrbf',['~ShapeFunctionRBF',['../db/d4a/classmknix_1_1_shape_function_r_b_f.html#a7a46908b3fbbbd7ffc312698e15b3d8f',1,'mknix::ShapeFunctionRBF']]],
['_7eshapefunctionrigidbar',['~ShapeFunctionRigidBar',['../df/d82/classmknix_1_1_shape_function_rigid_bar.html#ac95778202de9d1afca7c0198f0693365',1,'mknix::ShapeFunctionRigidBar']]],
['_7eshapefunctiontetrahedron',['~ShapeFunctionTetrahedron',['../d8/dbd/classmknix_1_1_shape_function_tetrahedron.html#acd13333d97502dc1ab76178452beef76',1,'mknix::ShapeFunctionTetrahedron']]],
['_7eshapefunctiontriangle',['~ShapeFunctionTriangle',['../d4/d8b/classmknix_1_1_shape_function_triangle.html#ae940dedb08ab37bbbcd253cd202f12c2',1,'mknix::ShapeFunctionTriangle']]],
['_7eshapefunctiontrianglesigned',['~ShapeFunctionTriangleSigned',['../d0/dbb/classmknix_1_1_shape_function_triangle_signed.html#acf9337e7665af9d12d72240c19880cb0',1,'mknix::ShapeFunctionTriangleSigned']]],
['_7esimulation',['~Simulation',['../db/d0b/classmknix_1_1_simulation.html#a8ab58ea5b4557c72b2a8f00cb8ef3e75',1,'mknix::Simulation']]],
['_7esystem',['~System',['../df/dd9/classmknix_1_1_system.html#a2edabe7efbc4e1c07efe75e635f3469d',1,'mknix::System']]],
['_7ethermalbody',['~ThermalBody',['../d2/d2b/classmknix_1_1_thermal_body.html#a5d4980cc538507f1f10111de9eca4018',1,'mknix::ThermalBody']]],
['_7ethermalload',['~ThermalLoad',['../df/d32/classmknix_1_1_thermal_load.html#a6932bfdd9473e55e2182bce35ad0a1bf',1,'mknix::ThermalLoad']]]
];
| daniel-iglesias/mknix | doc/html/search/functions_7e.js | JavaScript | lgpl-3.0 | 7,520 |
class DeviceDetector
class VersionExtractor < MetadataExtractor
private
def metadata_string
String(regex_meta[:version])
end
end
end
| local-ch/device_detector | lib/device_detector/version_extractor.rb | Ruby | lgpl-3.0 | 159 |
import $ from 'jquery';
import _ from 'underscore';
import Marionette from 'backbone.marionette';
import CreateProfileView from './create-profile-view';
import RestoreProfileView from './restore-profile-view';
import RestoreBuiltInProfilesView from './restore-built-in-profiles-view';
import Template from './templates/quality-profiles-actions.hbs';
export default Marionette.ItemView.extend({
template: Template,
events: {
'click #quality-profiles-create': 'onCreateClick',
'click #quality-profiles-restore': 'onRestoreClick',
'click #quality-profiles-restore-built-in': 'onRestoreBuiltInClick',
'click .js-filter-by-language': 'onLanguageClick'
},
onCreateClick: function (e) {
e.preventDefault();
this.create();
},
onRestoreClick: function (e) {
e.preventDefault();
this.restore();
},
onRestoreBuiltInClick: function (e) {
e.preventDefault();
this.restoreBuiltIn();
},
onLanguageClick: function (e) {
e.preventDefault();
var language = $(e.currentTarget).data('language');
this.filterByLanguage(language);
},
create: function () {
var that = this;
this.requestImporters().done(function () {
new CreateProfileView({
collection: that.collection,
languages: that.languages,
importers: that.importers
}).render();
});
},
restore: function () {
new RestoreProfileView({
collection: this.collection
}).render();
},
restoreBuiltIn: function () {
new RestoreBuiltInProfilesView({
collection: this.collection,
languages: this.languages
}).render();
},
requestLanguages: function () {
var that = this,
url = baseUrl + '/api/languages/list';
return $.get(url).done(function (r) {
that.languages = r.languages;
});
},
requestImporters: function () {
var that = this,
url = baseUrl + '/api/qualityprofiles/importers';
return $.get(url).done(function (r) {
that.importers = r.importers;
});
},
filterByLanguage: function (language) {
this.selectedLanguage = _.findWhere(this.languages, { key: language });
this.render();
this.collection.trigger('filter', language);
},
serializeData: function () {
return _.extend(Marionette.ItemView.prototype.serializeData.apply(this, arguments), {
canWrite: this.options.canWrite,
languages: this.languages,
selectedLanguage: this.selectedLanguage
});
}
});
| abbeyj/sonarqube | server/sonar-web/src/main/js/apps/quality-profiles/actions-view.js | JavaScript | lgpl-3.0 | 2,473 |
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Copyright (c) 2012-2017 The plumed team
(see the PEOPLE file at the root of the distribution for a list of names)
See http://www.plumed.org for more information.
This file is part of plumed, version 2.
plumed is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
plumed is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with plumed. If not, see <http://www.gnu.org/licenses/>.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
#ifndef __PLUMED_multicolvar_ActionVolume_h
#define __PLUMED_multicolvar_ActionVolume_h
#include "tools/HistogramBead.h"
#include "VolumeGradientBase.h"
namespace PLMD {
namespace multicolvar {
/**
\ingroup INHERIT
This is the abstract base class to use for implementing a new way of definining a particular region of the simulation
box. You can use this to calculate the number of atoms inside that part or the average value of a quantity like the
coordination number inside that part of the cell.
*/
class ActionVolume : public VolumeGradientBase {
private:
/// Number of quantities in use in this colvar
unsigned nquantities;
/// The value of sigma
double sigma;
/// Are we interested in the area outside the colvar
bool not_in;
/// The kernel type for this histogram
std::string kerneltype;
protected:
double getSigma() const ;
std::string getKernelType() const ;
public:
static void registerKeywords( Keywords& keys );
explicit ActionVolume(const ActionOptions&);
/// Get the number of quantities that are calculated each time
virtual unsigned getNumberOfQuantities() const ;
/// Calculate whats in the volume
void calculateAllVolumes( const unsigned& curr, MultiValue& outvals ) const ;
/// This calculates whether or not a particular is inside the box of interest
/// this is used for neighbour list with volumes
bool inVolumeOfInterest( const unsigned& curr ) const ;
virtual double calculateNumberInside( const Vector& cpos, Vector& derivatives, Tensor& vir, std::vector<Vector>& refders ) const=0;
unsigned getCentralAtomElementIndex();
};
inline
unsigned ActionVolume::getNumberOfQuantities() const {
return nquantities;
}
inline
double ActionVolume::getSigma() const {
return sigma;
}
inline
std::string ActionVolume::getKernelType() const {
return kerneltype;
}
inline
unsigned ActionVolume::getCentralAtomElementIndex() {
return 1;
}
}
}
#endif
| JFDama/plumed2 | src/multicolvar/ActionVolume.h | C | lgpl-3.0 | 2,918 |
/********************************************************************************
* Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH *
* *
* This software is distributed under the terms of the *
* GNU Lesser General Public Licence version 3 (LGPL) version 3, *
* copied verbatim in the file "LICENSE" *
********************************************************************************/
#include "BaseSourcePolicy.h"
#include "FairMQLogger.h"
#include "FairRunAna.h"
#include "FairFileSource.h"
//#include "FairLmdSource.h"
//#include "FairMbsSource.h"
//#include "FairMbsStreamSource.h"
//#include "FairMixedSource.h"
//#include "FairRemoteSource.h"
#include <type_traits>
#include <functional>
template<typename T, typename U>
using enable_if_match = typename std::enable_if<std::is_same<T,U>::value,int>::type;
template<typename FairSourceType, typename DataType>
class FairSourceMQInterface : public BaseSourcePolicy< FairSourceMQInterface<FairSourceType, DataType> >
{
typedef DataType* DataType_ptr;
typedef FairSourceMQInterface<FairSourceType,DataType> this_type;
public:
FairSourceMQInterface() :
BaseSourcePolicy<FairSourceMQInterface<FairSourceType, DataType>>(),
fSource(nullptr),
fData(nullptr),
fIndex(0),
fMaxIndex(-1),
fSourceName(),
fBranchName(),
fRunAna(nullptr)
{
}
virtual ~FairSourceMQInterface()
{
if(fData)
delete fData;
fData=nullptr;
if(fSource)
delete fSource;
fSource=nullptr;
if(fRunAna)
delete fRunAna;
fRunAna=nullptr;
}
//______________________________________________________________________________
int64_t GetNumberOfEvent()
{
return fMaxIndex;
}
void SetFileProperties(const std::string &filename, const std::string &branchname)
{
fSourceName = filename;
fBranchName = branchname;
}
//______________________________________________________________________________
// FairFileSource
template <typename T = FairSourceType, enable_if_match<T, FairFileSource> = 0>
void InitSource()
{
fRunAna = new FairRunAna();
fSource = new FairSourceType(fSourceName.c_str());
fSource->Init();
fSource->ActivateObject((TObject**)&fData,fBranchName.c_str());
fMaxIndex = fSource->CheckMaxEventNo();
}
template <typename T = FairSourceType, enable_if_match<T, FairFileSource> = 0>
void SetIndex(int64_t eventIdx)
{
fIndex=eventIdx;
}
template <typename T = FairSourceType, enable_if_match<T, FairFileSource> = 0>
DataType_ptr GetOutData()
{
fSource->ReadEvent(fIndex);
return fData;
}
protected:
FairSourceType* fSource;
DataType_ptr fData;
int64_t fIndex;
int64_t fMaxIndex;
std::string fClassName;
std::string fBranchName;
std::string fSourceName;
FairRunAna* fRunAna;
}; | Barthelemy/FairRoot | base/MQ/policies/Sampler/FairSourceMQInterface.h | C | lgpl-3.0 | 2,936 |
"""Interactive context using the GLUT API (provides navigation support)"""
from OpenGLContext import interactivecontext, glutcontext, context
from OpenGLContext.move import viewplatformmixin
from OpenGL.GLUT import *
class GLUTInteractiveContext (
viewplatformmixin.ViewPlatformMixin,
interactivecontext.InteractiveContext,
glutcontext.GLUTContext,
):
'''GLUT context providing camera, mouse and keyboard interaction '''
if __name__ == "__main__":
from drawcube import drawCube
from OpenGL.GL import glTranslated
class TestRenderer(GLUTInteractiveContext):
def Render( self, mode = None):
GLUTInteractiveContext.Render (self, mode)
glTranslated ( 2,0,-4)
drawCube()
# initialize GLUT windowing system
TestRenderer.ContextMainLoop( ) | stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGLContext/glutinteractivecontext.py | Python | lgpl-3.0 | 828 |
using System;
namespace NetMQ.Core
{
/// <summary>
/// This enum-type serves to identity a particular socket-option.
/// </summary>
internal enum ZmqSocketOption
{
/// <summary>
/// The I/O-thread affinity.
/// 0 means no affinity, meaning that work shall be distributed fairly among all I/O threads.
/// For non-zero values, the lowest bit corresponds to thread 1, second lowest bit to thread 2, and so on.
/// </summary>
/// <remarks>
/// The I/O-thread <c>Affinity</c> is a 64-bit value used to specify which threads from the I/O thread-pool
/// associated with the socket's context shall handle newly-created connections.
/// 0 means no affinity, meaning that work shall be distributed fairly among all I/O threads.
/// For non-zero values, the lowest bit corresponds to thread 1, second lowest bit to thread 2, and so on.
/// </remarks>
Affinity = 4,
/// <summary>
/// The unique identity of the socket, from a message-queueing router's perspective.
/// </summary>
/// <remarks>
/// This is at most 255 bytes long.
/// </remarks>
Identity = 5,
/// <summary>
/// Setting this option subscribes a socket to messages that have the given topic. This is valid only for Subscriber and XSubscriber sockets.
/// </summary>
/// <remarks>
/// You subscribe a socket to a given topic when you want that socket to receive messages of that topic.
/// A topic is simply a specific prefix (in the form of a byte-array or the equivalent text).
/// This is valid only for Subscriber and XSubscriber sockets.
/// </remarks>
Subscribe = 6,
/// <summary>
/// Set this option to un-subscribe a socket from a given topic. Only for Subscriber and XSubscriber sockets.
/// </summary>
/// <remarks>
/// You un-subscribe a socket from the given topic when you no longer want that socket to receive
/// messages of that topic. A topic is simply a specific prefix (in the form of a byte-array or the equivalent text).
/// This is valid only for Subscriber and XSubscriber sockets.
/// </remarks>
Unsubscribe = 7,
/// <summary>
/// The maximum send or receive data rate for multicast transports on the specified socket.
/// </summary>
Rate = 8,
/// <summary>
/// The recovery-interval, in milliseconds, for multicast transports using the specified socket.
/// Default is 10,000 ms (10 seconds).
/// </summary>
/// <remarks>
/// This option determines the maximum time that a receiver can be absent from a multicast group
/// before unrecoverable data loss will occur. Default is 10,000 ms (10 seconds).
/// </remarks>
RecoveryIvl = 9,
/// <summary>
/// The size of the transmit buffer for the specified socket.
/// </summary>
SendBuffer = 11,
/// <summary>
/// The size of the receive buffer for the specified socket.
/// </summary>
ReceiveBuffer = 12,
/// <summary>
/// This indicates more messages are to be received.
/// </summary>
ReceiveMore = 13,
/// <summary>
/// The file descriptor associated with the specified socket.
/// </summary>
Handle = 14,
/// <summary>
/// The event state for the specified socket.
/// This is a combination of:
/// PollIn - at least one message may be received without blocking
/// PollOut - at least one messsage may be sent without blocking
/// </summary>
Events = 15,
Type = 16,
/// <summary>
/// This option specifies the linger period for the specified socket,
/// which determines how long pending messages which have yet to be sent to a peer
/// shall linger in memory after a socket is closed.
/// </summary>
Linger = 17,
/// <summary>
/// The initial reconnection interval for the specified socket.
/// -1 means no reconnection.
/// </summary>
/// <remarks>
/// This is the period to wait between attempts to reconnect disconnected peers
/// when using connection-oriented transports.
/// A value of -1 means no reconnection.
/// </remarks>
ReconnectIvl = 18,
/// <summary>
/// This is the maximum length of the queue of outstanding peer connections
/// for the specified socket. This only applies to connection-oriented transports.
/// Default is 100.
/// </summary>
Backlog = 19,
/// <summary>
/// The maximum reconnection interval for the specified socket.
/// The default value of zero means no exponential backoff is performed.
/// </summary>
/// <remarks>
/// This option value denotes the maximum reconnection interval for a socket.
/// It is used when a connection drops and NetMQ attempts to reconnect.
/// On each attempt to reconnect, the previous interval is doubled
/// until this maximum period is reached.
/// The default value of zero means no exponential backoff is performed.
/// </remarks>
ReconnectIvlMax = 21,
/// <summary>
/// The upper limit to the size for inbound messages.
/// -1 (the default value) means no limit.
/// </summary>
/// <remarks>
/// If a peer sends a message larger than this it is disconnected.
/// </remarks>
MaxMessageSize = 22,
/// <summary>
/// The high-water mark for message transmission, which is the number of messages that are allowed to queue up
/// before mitigative action is taken. The default value is 1000.
/// </summary>
SendHighWatermark = 23,
/// <summary>
/// The high-water mark for message reception, which is the number of messages that are allowed to queue up
/// before mitigative action is taken. The default value is 1000.
/// </summary>
ReceiveHighWatermark = 24,
/// <summary>
/// The time-to-live (maximum number of hops) that outbound multicast packets
/// are allowed to propagate.
/// The default value of 1 means that the multicast packets don't leave the local network.
/// </summary>
MulticastHops = 25,
/// <summary>
/// Specifies the amount of time after which a synchronous send call will time out.
/// A value of 0 means Send will return immediately, with a EAGAIN error if the message cannot be sent.
/// -1 means to block until the message is sent.
/// </summary>
SendTimeout = 28,
/// <summary>
/// This indicates the underlying native socket type.
/// </summary>
/// <remarks>
/// An IPv4 socket will only use IPv4, while an IPv6 socket lets applications
/// connect to and accept connections from both IPv4 and IPv6 hosts.
/// </remarks>
IPv4Only = 31,
/// <summary>
/// The last endpoint bound for TCP and IPC transports.
/// The returned value will be a string in the form of a ZMQ DSN.
/// </summary>
/// <remarks>
/// If the TCP host is ANY, indicated by a *, then the returned address
/// will be 0.0.0.0 (for IPv4).
/// </remarks>
LastEndpoint = 32,
/// <summary>
/// Sets the RouterSocket behavior when an unroutable message is encountered.
/// A value of 0 is the default and discards the message silently when it cannot be routed.
/// A value of 1 returns an EHOSTUNREACH error code if the message cannot be routed.
/// </summary>
RouterMandatory = 33,
/// <summary>
/// Whether to use TCP keep-alive on this socket.
/// 0 = no, 1 = yes,
/// -1 (the default value) means to skip any overrides and leave it to the OS default.
/// </summary>
TcpKeepalive = 34,
/// <summary>
/// The keep-alive time - the duration between two keepalive transmissions in idle condition.
/// </summary>
/// <remarks>
/// The TCP keepalive period is required by socket implementers to be configurable and by default is
/// set to no less than 2 hours.
/// In 0MQ, -1 (the default value) means to just leave it to the OS default.
/// </remarks>
TcpKeepaliveIdle = 36,
/// <summary>
/// The TCP keep-alive interval - the duration between two keepalive transmission if no response was received to a previous keepalive probe.
/// </summary>
/// <remarks>
/// By default a keepalive packet is sent every 2 hours or 7,200,000 milliseconds
/// if no other data have been carried over the TCP connection.
/// If there is no response to a keepalive, it is repeated once every KeepAliveInterval seconds.
/// The default is one second.
/// </remarks>
TcpKeepaliveIntvl = 37,
/// <summary>
/// The list of accept-filters, which denote the addresses that a socket may accept.
/// Setting this to null clears the filter.
/// </summary>
/// <remarks>
/// This applies to IPv4 addresses only.
/// </remarks>
DelayAttachOnConnect = 39,
/// <summary>
/// This applies only to XPub sockets.
/// If true, send all subscription messages upstream, not just unique ones.
/// The default is false.
/// </summary>
XpubVerbose = 40,
/// <summary>
/// If true, router socket accepts non-zmq tcp connections
/// </summary>
RouterRawSocket = 41,
XPublisherManual = 42,
/// <summary>
/// This is an XPublisher-socket welcome-message.
/// </summary>
XPublisherWelcomeMessage = 43,
DisableTimeWait = 44,
/// <summary>
/// This applies only to XPub sockets.
/// If true, enable broadcast option on XPublishers
/// </summary>
XPublisherBroadcast = 45,
/// <summary>
/// The low-water mark for message transmission. This is the number of messages that should be processed
/// before transmission is unblocked (in case it was blocked by reaching high-watermark). The default value is
/// calculated using relevant high-watermark (HWM): HWM > 2048 ? HWM - 1024 : (HWM + 1) / 2
/// </summary>
SendLowWatermark = 46,
/// <summary>
/// The low-water mark for message reception. This is the number of messages that should be processed
/// before reception is unblocked (in case it was blocked by reaching high-watermark). The default value is
/// calculated using relevant high-watermark (HWM): HWM > 2048 ? HWM - 1024 : (HWM + 1) / 2
/// </summary>
ReceiveLowWatermark = 47,
/// <summary>
/// When enabled new router connections with same identity take over old ones
/// </summary>
RouterHandover = 48,
/// <summary>
/// Specifies the byte-order: big-endian, vs little-endian.
/// </summary>
Endian = 1000,
/// <summary>
/// Specifies the max datagram size for PGM.
/// </summary>
PgmMaxTransportServiceDataUnitLength = 1001
}
} | MikkelPorse/netmq | src/NetMQ/Core/ZmqSocketOption.cs | C# | lgpl-3.0 | 11,703 |
/**
******************************************************************************
* @file stm32f429i_discovery_gyroscope.h
* @author MCD Application Team
* @version V2.1.0
* @date 19-June-2014
* @brief This file contains definitions for stm32f429i_discovery_gyroscope.c
* firmware driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
*
* 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.
* 3. Neither the name of STMicroelectronics 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 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.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F429I_DISCOVERY_GYROSCOPE_H
#define __STM32F429I_DISCOVERY_GYROSCOPE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f429i_discovery.h"
/* Include Gyroscope component driver */
#include "..\Components\l3gd20\l3gd20.h"
/** @addtogroup BSP
* @{
*/
/** @addtogroup STM32F429I_DISCOVERY
* @{
*/
/** @addtogroup STM32F429I_DISCOVERY_GYROSCOPE
* @{
*/
/** @defgroup STM32F429I_DISCOVERY_GYROSCOPE_Exported_Types
* @{
*/
typedef enum
{
GYRO_OK = 0,
GYRO_ERROR = 1,
GYRO_TIMEOUT = 2
}GYRO_StatusTypeDef;
/**
* @}
*/
/** @defgroup STM32F429I_DISCOVERY_GYROSCOPE_Exported_Constants
* @{
*/
/**
* @}
*/
/** @defgroup STM32F429I_DISCOVERY_GYROSCOPE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32F429I_DISCOVERY_GYROSCOPE_Exported_Functions
* @{
*/
/* Gyroscope Functions */
uint8_t BSP_GYRO_Init(void);
void BSP_GYRO_Reset(void);
uint8_t BSP_GYRO_ReadID(void);
void BSP_GYRO_ITConfig(GYRO_InterruptConfigTypeDef *pIntConfigStruct);
void BSP_GYRO_EnableIT(uint8_t IntPin);
void BSP_GYRO_DisableIT(uint8_t IntPin);
void BSP_GYRO_GetXYZ(float* pfData);
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32F429I_DISCOVERY_GYROSCOPE_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| ludopo/STM32F429I | STM32Cube_FW_F4_V1.3.0_lite/Drivers/BSP/STM32F429I-Discovery/stm32f429i_discovery_gyroscope.h | C | lgpl-3.0 | 3,801 |
/* MOD_V2.0
* Copyright (c) 2012 OpenDA Association
* All rights reserved.
*
* This file is part of OpenDA.
*
* OpenDA 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.
*
* OpenDA 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 OpenDA. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openda.costa;
import org.openda.interfaces.ITime;
/**
* Costa implementation for Time interface
*/
public class CtaTime extends CtaObject implements ITime {
/**
* Constructor for Time.
*/
public CtaTime() {
ctaHandle = this.create();
}
public CtaTime(ITime time) {
ctaHandle = this.create();
if(time.isStamp()){
this.setMJD(time.getMJD());
}else{
this.setSpanMJD(time.getBeginTime().getMJD(), time.getEndTime().getMJD(), time.getStepMJD());
}
}
protected native int create();
public boolean isStamp() {
return (this.getEndMJD() == this.getBeginMJD());
}
public boolean isSpan() {
return !isStamp();
}
public ITime getBeginTime() {
CtaTime time_ret = new CtaTime();
double step=this.getStepMJD();
double start=this.getBeginMJD();
time_ret.setSpanMJD(start, start, step);
return time_ret;
}
public ITime getEndTime() {
CtaTime time_ret = new CtaTime();
double step=this.getStepMJD();
double end=this.getEndMJD();
time_ret.setSpanMJD(end, end, step);
return time_ret;
}
public native double getMJD();
public native void setMJD(double mjd);
public native double getBeginMJD();
public native double getEndMJD();
public native double getStepMJD();
public native double getBeginUserTime();
public native double getEndUserTime();
public native double getUserStep();
public native void setSpanMJD(double startTime, double endTime, double timeStep);
public native void setUserSpan(double startTime, double endTime, double timeStep);
public native long getStepCount();
public boolean inSpan(ITime toCheck) {
boolean result = false;
if (toCheck.isStamp()) {
result = false; //Nothing can exist in empty interval
} else {
if (toCheck.isSpan()) {
result = (this.after(toCheck))
& (this.beforeEquals(toCheck));
}
}
return result;
}
public boolean after(ITime toCheck) {
return this.getBeginMJD() > toCheck.getEndTime().getMJD();
}
public boolean beforeEquals(ITime toCheck) {
return (!(this.getEndMJD() > toCheck.getBeginTime().getMJD()));
}
@SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException"})
public native ITime clone();
/**
* Compares two times ; is needed for sorting in java.util
*
* @param toCheck other time
* @return int with 1,0 or -1 for this>other, this==other and this<other
*/
public int compareTo(ITime toCheck) {
int result = 0;
if (toCheck.after(this)) {
result = -1;
} else if (this.after(toCheck)) {
result = 1;
}
return result;
}
public String toString() {
return "t" + this.getBeginMJD() + "-t" + this.getEndMJD();
}
}
| wkramer/openda | core/src/main/java/org/openda/costa/CtaTime.java | Java | lgpl-3.0 | 3,771 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2) on Sat Sep 25 12:34:52 EDT 2004 -->
<TITLE>
HttpRequestStream (Catalina Internal API Documentation)
</TITLE>
<META NAME="keywords" CONTENT="org.apache.catalina.connector.http.HttpRequestStream class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="HttpRequestStream (Catalina Internal API Documentation)";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/catalina/connector/http/HttpConnector.html" title="class in org.apache.catalina.connector.http"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/apache/catalina/connector/http/HttpResponseStream.html" title="class in org.apache.catalina.connector.http"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="HttpRequestStream.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.apache.catalina.connector.http</FONT>
<BR>
Class HttpRequestStream</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by">java.io.InputStream
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by">javax.servlet.ServletInputStream
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by"><A HREF="../../../../../org/apache/catalina/connector/RequestStream.html" title="class in org.apache.catalina.connector">org.apache.catalina.connector.RequestStream</A>
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by"><B>org.apache.catalina.connector.http.HttpRequestStream</B>
</PRE>
<HR>
<P>
<DL>
<DT>public class <B>HttpRequestStream</B><DT>extends <A HREF="../../../../../org/apache/catalina/connector/RequestStream.html" title="class in org.apache.catalina.connector">RequestStream</A></DL>
<P>
<DL>
<DT><B>Author:</B></DT>
<DD><a href="mailto:remm@apache.org">Remy Maucherat</a></DD>
</DL>
<HR>
<P>
<!-- ======== NESTED CLASS SUMMARY ======== -->
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Field Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#chunk">chunk</A></B></CODE>
<BR>
<B>Deprecated.</B> Use chunking ?</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected byte[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#chunkBuffer">chunkBuffer</A></B></CODE>
<BR>
<B>Deprecated.</B> Chunk buffer.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#chunkLength">chunkLength</A></B></CODE>
<BR>
<B>Deprecated.</B> Chunk length.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#chunkPos">chunkPos</A></B></CODE>
<BR>
<B>Deprecated.</B> Chunk buffer position.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#endChunk">endChunk</A></B></CODE>
<BR>
<B>Deprecated.</B> True if the final chunk was found.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#http11">http11</A></B></CODE>
<BR>
<B>Deprecated.</B> HTTP/1.1 flag.</TD>
</TR>
</TABLE>
<A NAME="fields_inherited_from_class_org.apache.catalina.connector.RequestStream"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Fields inherited from class org.apache.catalina.connector.<A HREF="../../../../../org/apache/catalina/connector/RequestStream.html" title="class in org.apache.catalina.connector">RequestStream</A></B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../../org/apache/catalina/connector/RequestStream.html#closed">closed</A>, <A HREF="../../../../../org/apache/catalina/connector/RequestStream.html#count">count</A>, <A HREF="../../../../../org/apache/catalina/connector/RequestStream.html#length">length</A>, <A HREF="../../../../../org/apache/catalina/connector/RequestStream.html#sm">sm</A>, <A HREF="../../../../../org/apache/catalina/connector/RequestStream.html#stream">stream</A></CODE></TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#HttpRequestStream(org.apache.catalina.connector.http.HttpRequestImpl, org.apache.catalina.connector.http.HttpResponseImpl)">HttpRequestStream</A></B>(org.apache.catalina.connector.http.HttpRequestImpl request,
org.apache.catalina.connector.http.HttpResponseImpl response)</CODE>
<BR>
<B>Deprecated.</B> Construct a servlet input stream associated with the specified Request.</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Method Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#close()">close</A></B>()</CODE>
<BR>
<B>Deprecated.</B> Close this input stream.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#read()">read</A></B>()</CODE>
<BR>
<B>Deprecated.</B> Read and return a single byte from this input stream, or -1 if end of
file has been encountered.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/catalina/connector/http/HttpRequestStream.html#read(byte[], int, int)">read</A></B>(byte[] b,
int off,
int len)</CODE>
<BR>
<B>Deprecated.</B> Read up to <code>len</code> bytes of data from the input stream
into an array of bytes.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_org.apache.catalina.connector.RequestStream"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class org.apache.catalina.connector.<A HREF="../../../../../org/apache/catalina/connector/RequestStream.html" title="class in org.apache.catalina.connector">RequestStream</A></B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../../org/apache/catalina/connector/RequestStream.html#read(byte[])">read</A></CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_javax.servlet.ServletInputStream"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class javax.servlet.ServletInputStream</B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>readLine</CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.io.InputStream"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class java.io.InputStream</B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>available, mark, markSupported, reset, skip</CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class java.lang.Object</B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Field Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="chunk"><!-- --></A><H3>
chunk</H3>
<PRE>
protected boolean <B>chunk</B></PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Use chunking ?
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="endChunk"><!-- --></A><H3>
endChunk</H3>
<PRE>
protected boolean <B>endChunk</B></PRE>
<DL>
<DD><B>Deprecated.</B> <DD>True if the final chunk was found.
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="chunkBuffer"><!-- --></A><H3>
chunkBuffer</H3>
<PRE>
protected byte[] <B>chunkBuffer</B></PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Chunk buffer.
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="chunkLength"><!-- --></A><H3>
chunkLength</H3>
<PRE>
protected int <B>chunkLength</B></PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Chunk length.
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="chunkPos"><!-- --></A><H3>
chunkPos</H3>
<PRE>
protected int <B>chunkPos</B></PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Chunk buffer position.
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="http11"><!-- --></A><H3>
http11</H3>
<PRE>
protected boolean <B>http11</B></PRE>
<DL>
<DD><B>Deprecated.</B> <DD>HTTP/1.1 flag.
<P>
<DL>
</DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="HttpRequestStream(org.apache.catalina.connector.http.HttpRequestImpl, org.apache.catalina.connector.http.HttpResponseImpl)"><!-- --></A><H3>
HttpRequestStream</H3>
<PRE>
public <B>HttpRequestStream</B>(org.apache.catalina.connector.http.HttpRequestImpl request,
org.apache.catalina.connector.http.HttpResponseImpl response)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Construct a servlet input stream associated with the specified Request.
<P>
<DT><B>Parameters:</B><DD><CODE>request</CODE> - The associated request<DD><CODE>response</CODE> - The associated response</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Method Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="close()"><!-- --></A><H3>
close</H3>
<PRE>
public void <B>close</B>()
throws java.io.IOException</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Close this input stream. No physical level I-O is performed, but
any further attempt to read from this stream will throw an IOException.
If a content length has been set but not all of the bytes have yet been
consumed, the remaining bytes will be swallowed.
<P>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="../../../../../org/apache/catalina/connector/RequestStream.html#close()">close</A></CODE> in class <CODE><A HREF="../../../../../org/apache/catalina/connector/RequestStream.html" title="class in org.apache.catalina.connector">RequestStream</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="read()"><!-- --></A><H3>
read</H3>
<PRE>
public int <B>read</B>()
throws java.io.IOException</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Read and return a single byte from this input stream, or -1 if end of
file has been encountered.
<P>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="../../../../../org/apache/catalina/connector/RequestStream.html#read()">read</A></CODE> in class <CODE><A HREF="../../../../../org/apache/catalina/connector/RequestStream.html" title="class in org.apache.catalina.connector">RequestStream</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE> - if an input/output error occurs</DL>
</DD>
</DL>
<HR>
<A NAME="read(byte[], int, int)"><!-- --></A><H3>
read</H3>
<PRE>
public int <B>read</B>(byte[] b,
int off,
int len)
throws java.io.IOException</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Read up to <code>len</code> bytes of data from the input stream
into an array of bytes. An attempt is made to read as many as
<code>len</code> bytes, but a smaller number may be read,
possibly zero. The number of bytes actually read is returned as
an integer. This method blocks until input data is available,
end of file is detected, or an exception is thrown.
<P>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="../../../../../org/apache/catalina/connector/RequestStream.html#read(byte[], int, int)">read</A></CODE> in class <CODE><A HREF="../../../../../org/apache/catalina/connector/RequestStream.html" title="class in org.apache.catalina.connector">RequestStream</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>b</CODE> - The buffer into which the data is read<DD><CODE>off</CODE> - The start offset into array <code>b</code> at which
the data is written<DD><CODE>len</CODE> - The maximum number of bytes to read
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE> - if an input/output error occurs</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/catalina/connector/http/HttpConnector.html" title="class in org.apache.catalina.connector.http"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/apache/catalina/connector/http/HttpResponseStream.html" title="class in org.apache.catalina.connector.http"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="HttpRequestStream.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2000-2002 Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| simeshev/parabuild-ci | 3rdparty/tomcat4131/webapps/tomcat-docs/catalina/docs/api/org/apache/catalina/connector/http/HttpRequestStream.html | HTML | lgpl-3.0 | 21,431 |
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2016 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarth/IntersectionPicker>
#include <osgEarth/PrimitiveIntersector>
#include <osgEarth/Registry>
#define LC "[Picker] "
using namespace osgEarth;
IntersectionPicker::IntersectionPicker( osgViewer::View* view, osg::Node* root, unsigned travMask, float buffer, Limit limit ) :
_view ( view ),
_root ( root ),
_travMask( travMask ),
_buffer ( buffer ),
_limit ( limit )
{
if ( root )
_path = root->getParentalNodePaths()[0];
}
void
IntersectionPicker::setLimit(const IntersectionPicker::Limit& value)
{
_limit = value;
}
void
IntersectionPicker::setTraversalMask(unsigned value)
{
_travMask = value;
}
void
IntersectionPicker::setBuffer(float value)
{
_buffer = value;
}
bool
IntersectionPicker::pick( float x, float y, Hits& results ) const
{
float local_x, local_y = 0.0;
const osg::Camera* camera = _view->getCameraContainingPosition(x, y, local_x, local_y);
if ( !camera )
camera = _view->getCamera();
osg::ref_ptr<osgEarth::PrimitiveIntersector> picker;
double buffer_x = _buffer, buffer_y = _buffer;
if ( camera->getViewport() )
{
double aspectRatio = camera->getViewport()->width()/camera->getViewport()->height();
buffer_x *= aspectRatio;
buffer_y /= aspectRatio;
}
osg::Matrix windowMatrix;
if ( _root.valid() )
{
osg::Matrix modelMatrix;
if (camera->getViewport())
{
windowMatrix = camera->getViewport()->computeWindowMatrix();
modelMatrix.preMult( windowMatrix );
}
modelMatrix.preMult( camera->getProjectionMatrix() );
modelMatrix.preMult( camera->getViewMatrix() );
osg::NodePath prunedNodePath( _path.begin(), _path.end()-1 );
modelMatrix.preMult( osg::computeWorldToLocal(prunedNodePath) );
osg::Matrix modelInverse;
modelInverse.invert(modelMatrix);
osg::Vec3d startLocal(local_x, local_y, 0.0);
osg::Vec3d startModel = startLocal * modelInverse;
osg::Vec3d endLocal(local_x, local_y, 1.0);
osg::Vec3d endModel = endLocal * modelInverse;
osg::Vec3d bufferLocal(local_x + buffer_x, local_y + buffer_y, 0.0);
osg::Vec3d bufferModel = bufferLocal * modelInverse;
double buffer = osg::maximum((bufferModel - startModel).length(), 5.0); //TODO: Setting a minimum of 4.0 may need revisited
OE_DEBUG
<< "local_x:" << local_x << ", local_y:" << local_y
<< ", buffer_x:" << buffer_x << ", buffer_y:" << buffer_y
<< ", bm.x:" << bufferModel.x() << ", bm.y:" << bufferModel.y()
<< ", bm.z:" << bufferModel.z()
<< ", BUFFER: " << buffer
<< std::endl;
picker = new osgEarth::PrimitiveIntersector(osgUtil::Intersector::MODEL, startModel, endModel, buffer);
}
else
{
picker = new osgEarth::PrimitiveIntersector(camera->getViewport() ? osgUtil::Intersector::WINDOW : osgUtil::Intersector::PROJECTION, local_x, local_y, _buffer);
}
picker->setIntersectionLimit( (osgUtil::Intersector::IntersectionLimit)_limit );
osgUtil::IntersectionVisitor iv(picker.get());
//picker->setIntersectionLimit( osgUtil::Intersector::LIMIT_ONE_PER_DRAWABLE );
// in MODEL mode, we need to window and proj matrixes in order to support some of the
// features in osgEarth (like Annotation::GeoPositionNode).
if ( _root.valid() )
{
iv.pushWindowMatrix( new osg::RefMatrix(windowMatrix) );
iv.pushProjectionMatrix( new osg::RefMatrix(camera->getProjectionMatrix()) );
iv.pushViewMatrix( new osg::RefMatrix(camera->getViewMatrix()) );
}
iv.setTraversalMask( _travMask );
if ( _root.valid() )
_path.back()->accept(iv);
else
const_cast<osg::Camera*>(camera)->accept(iv);
if (picker->containsIntersections())
{
results = picker->getIntersections();
return true;
}
else
{
results.clear();
return false;
}
}
bool
IntersectionPicker::getObjectIDs(const Hits& results, std::set<ObjectID>& out_objectIDs) const
{
ObjectIndex* index = Registry::objectIndex();
for(Hits::const_iterator hit = results.begin(); hit != results.end(); ++hit)
{
bool found = false;
// check for the uniform.
const osg::NodePath& path = hit->nodePath;
for(osg::NodePath::const_reverse_iterator n = path.rbegin(); n != path.rend(); ++n )
{
osg::Node* node = *n;
if ( node && node->getStateSet() )
{
osg::Uniform* u = node->getStateSet()->getUniform( index->getObjectIDUniformName() );
if ( u )
{
ObjectID oid;
if ( u->get(oid) )
{
out_objectIDs.insert( oid );
found = true;
}
}
}
}
if ( !found )
{
// check the geometry.
const osg::Geometry* geom = hit->drawable ? hit->drawable->asGeometry() : 0L;
if ( geom )
{
const ObjectIDArray* ids = dynamic_cast<const ObjectIDArray*>( geom->getVertexAttribArray(index->getObjectIDAttribLocation()) );
if ( ids )
{
for(unsigned i=0; i < hit->indexList.size(); ++i)
{
unsigned index = hit->indexList[i];
if ( index < ids->size() )
{
ObjectID oid = (*ids)[index];
out_objectIDs.insert( oid );
}
}
}
}
}
}
return !out_objectIDs.empty();
}
| ldelgass/osgearth | src/osgEarth/IntersectionPicker.cpp | C++ | lgpl-3.0 | 6,655 |
thisdir = class/System.Reactive.Runtime.Remoting
SUBDIRS =
include ../../build/rules.make
LIBRARY = System.Reactive.Runtime.Remoting.dll
LIB_MCS_FLAGS = \
@more_build_args \
-r:System.dll \
-r:System.Core.dll \
-r:System.Reactive.Interfaces.dll \
-r:System.Reactive.Core.dll \
-r:System.Reactive.Linq.dll
ifeq (2.1, $(FRAMEWORK_VERSION))
LIB_MCS_FLAGS += -d:NO_TASK_DELAY
endif
NET_4_5 := $(filter 4.5, $(FRAMEWORK_VERSION))
ifdef NET_4_5
LIB_MCS_FLAGS += -d:HAS_EDI -d:PREFERASYNC -d:PREFER_ASYNC -d:HAS_AWAIT
endif
TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
EXTRA_DISTFILES = more_build_args
VALID_PROFILE := $(filter net_4_0 net_4_5, $(PROFILE))
ifndef VALID_PROFILE
LIBRARY_NAME = dummy-System.System.Reactive.Runtime.Remoting.dll
NO_SIGN_ASSEMBLY = yes
endif
INSTALL_PROFILE := $(filter net_4_5, $(PROFILE))
ifndef INSTALL_PROFILE
NO_INSTALL = yes
endif
NO_TEST = yes
include ../../build/library.make
| edwinspire/VSharp | class/System.Reactive.Runtime.Remoting/Makefile | Makefile | lgpl-3.0 | 933 |
/*
* Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
*
* Produced at the Lawrence Livermore National Laboratory. Written by:
* Barry Rountree <rountree@llnl.gov>,
* Scott Walker <walker91@llnl.gov>, and
* Kathleen Shoga <shoga1@llnl.gov>.
*
* LLNL-CODE-645430
*
* All rights reserved.
*
* This file is part of libmsr. For details, see https://github.com/LLNL/libmsr.git.
*
* Please also read libmsr/LICENSE for our notice and the LGPL.
*
* libmsr is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License (as published by the Free
* Software Foundation) version 2.1 dated February 1999.
*
* libmsr is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the terms and conditions of the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with libmsr; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#include <inttypes.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include "cpuid.h"
#include "memhdlr.h"
#include "msr_core.h"
#include "msr_rapl.h"
#include "msr_thermal.h"
#include "msr_counters.h"
#include "msr_clocks.h"
#include "msr_misc.h"
#include "msr_turbo.h"
#include "csr_core.h"
#include "csr_imc.h"
#include "libmsr_error.h"
#ifdef MPI
#include <mpi.h>
#endif
struct rapl_limit l1, l2, l3;
void get_limits()
{
int i;
static uint64_t sockets = 0;
if (!sockets)
{
core_config(NULL, NULL, &sockets, NULL);
}
for (i = 0; i < sockets; i++)
{
if (i != 0)
{
fprintf(stdout, "\n");
}
fprintf(stdout, "Socket %d:\n", i);
if (get_pkg_rapl_limit(i, &l1, &l2) == 0)
{
fprintf(stdout, "Pkg Domain Power Lim 1 (lower lim)\n");
dump_rapl_limit(&l1, stdout);
fprintf(stdout, "\n");
fprintf(stdout, "Pkg Domain Power Lim 2 (upper lim)\n");
dump_rapl_limit(&l2, stdout);
}
if (get_dram_rapl_limit(i, &l3) == 0)
{
fprintf(stdout, "\nDRAM Domain\n");
dump_rapl_limit(&l3, stdout);
}
}
}
// TODO: test other parts of clocks
void clocks_test(double *freq)
{
fprintf(stdout, "\n--- Read IA32_APERF, IA32_MPERF, and IA32_TIME_STAMP_COUNTER ---\n");
dump_clocks_data_readable(stdout);
fprintf(stdout, "\n--- Reading IA32_PERF_STATUS ---\n");
dump_p_state(stdout);
fprintf(stdout, "\n");
fprintf(stdout, "--- Set New CPU Frequencies ---\n");
fprintf(stdout, "- Setting socket 0 to %.1fGHz\n", freq[0]);
unsigned long long speedstep = (freq[0]*10)*256;
printf(" WRITING dec=%llu hex=0x%llx\n", speedstep, speedstep);
set_p_state(0, (uint64_t)speedstep);
fprintf(stdout, "- Setting socket 1 to %.1fGHz\n", freq[1]);
speedstep = (freq[1]*10)*256;
printf(" WRITING dec=%llu hex=0x%llx\n", speedstep, speedstep);
set_p_state(1, (uint64_t)speedstep);
fprintf(stdout, "\n--- Confirm New Settings ---\n");
dump_p_state(stdout);
}
void set_to_defaults()
{
int socket = 0;
int numsockets = num_sockets();
struct rapl_power_info raplinfo;
struct rapl_limit socketlim, socketlim2, dramlim;
for (socket = 0; socket < numsockets; socket++)
{
if (socket != 0)
{
fprintf(stdout, "\n");
}
fprintf(stdout, "Socket %d:\n", socket);
get_rapl_power_info(socket, &raplinfo);
socketlim.bits = 0;
socketlim.watts = raplinfo.pkg_therm_power;
socketlim.seconds = 1;
socketlim2.bits = 0;
socketlim2.watts = raplinfo.pkg_therm_power * 1.2;
socketlim2.seconds = 3;
dramlim.bits = 0;
dramlim.watts = raplinfo.dram_max_power;
dramlim.seconds = 1;
fprintf(stdout, "Pkg Domain Power Lim 1 (lower lim)\n");
dump_rapl_limit(&socketlim, stdout);
fprintf(stdout, "\n");
fprintf(stdout, "Pkg Domain Power Lim 2 (upper lim)\n");
dump_rapl_limit(&socketlim2, stdout);
fprintf(stdout, "\nDRAM Domain\n");
dump_rapl_limit(&dramlim, stdout);
set_pkg_rapl_limit(socket, &socketlim, &socketlim2);
set_dram_rapl_limit(socket, &dramlim);
}
}
// TODO: check if test for oversized bitfield is in place, change that warning
// to an error
int main(int argc, char **argv)
{
struct rapl_data *rd = NULL;
uint64_t *rapl_flags = NULL;
uint64_t cores = 0;
uint64_t threads = 0;
uint64_t sockets = 0;
int ri_stat = 0;
double *new_p_states_ghz;
if (!sockets)
{
core_config(&cores, &threads, &sockets, NULL);
}
new_p_states_ghz = malloc(sockets * sizeof(double));
if (argc == 1)
{
/* Default p-states to write. */
new_p_states_ghz[0] = 1.8;
new_p_states_ghz[1] = 1.2;
}
else if (argc-1 > sockets)
{
fprintf(stderr, "ERROR: Too many p-states (in GHz) specified.\n");
return -1;
}
else if (argc-1 == sockets)
{
new_p_states_ghz[0] = atof(argv[1]);
new_p_states_ghz[1] = atof(argv[2]);
}
else
{
fprintf(stderr, "ERROR: Not enough p-states (in GHz) specified.\n");
return -1;
}
if (init_msr())
{
libmsr_error_handler("Unable to initialize libmsr", LIBMSR_ERROR_MSR_INIT, getenv("HOSTNAME"), __FILE__, __LINE__);
return -1;
}
fprintf(stdout, "\n===== MSR Init Done =====\n");
ri_stat = rapl_init(&rd, &rapl_flags);
if (ri_stat < 0)
{
libmsr_error_handler("Unable to initialize rapl", LIBMSR_ERROR_RAPL_INIT, getenv("HOSTNAME"), __FILE__, __LINE__);
return -1;
}
fprintf(stdout, "\n===== RAPL Init Done =====\n");
fprintf(stdout, "\n===== Get Initial RAPL Power Limits =====\n");
get_limits();
fprintf(stdout, "\n===== POWER INFO =====\n");
dump_rapl_power_info(stdout);
fprintf(stdout, "\n===== Clocks Test =====\n");
clocks_test(new_p_states_ghz);
fprintf(stdout, "\n===== Setting Defaults =====\n");
set_to_defaults();
finalize_msr();
fprintf(stdout, "===== MSR Finalized =====\n");
fprintf(stdout, "\n===== Test Finished Successfully =====\n");
return 0;
}
| scalability-llnl/libmsr | test/pstate_test.c | C | lgpl-3.0 | 6,553 |
/* Jakopter
* Copyright © 2015 ALF@INRIA
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#ifndef JAKOPTER_NETWORK_H
#define JAKOPTER_NETWORK_H
#include "com_channel.h"
#include "com_master.h"
#include "utils.h"
#define CHANNEL_INPUT_SIZE 16384
#define CHANNEL_OUTPUT_SIZE 1024
#define ORDER_SIZE 256
#define ADDR_SIZE 256
#define DEFAULT_CLIENT_IN "http://127.0.0.1"
#define DEFAULT_CLIENT_OUT "http://127.0.0.1/index.php"
/* 10 ms in ns */
#define TIMEOUT_NETWORK 4000000
/** \brief Start the thread that listen on server_in and send data on server_out
* \param server_in a HTTP address where Curl GET his data
* \param server_out a HTTP address where Curl POST his data
* \return 0 OK, -1 otherwise
*/
int jakopter_init_network(const char* server_in, const char* server_out);
/** \brief Stop curl */
int jakopter_stop_network();
#endif | thibhul/Jakopter | include/network.h | C | lgpl-3.0 | 1,481 |
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.client.modloader;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import net.minecraft.client.Minecraft;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.src.BaseMod;
import net.minecraft.client.*;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.multiplayer.NetClientHandler;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import com.google.common.base.Equivalence;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.modloader.BaseModProxy;
import cpw.mods.fml.common.modloader.IModLoaderSidedHelper;
import cpw.mods.fml.common.modloader.ModLoaderHelper;
import cpw.mods.fml.common.modloader.ModLoaderModContainer;
import cpw.mods.fml.common.network.EntitySpawnPacket;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
public class ModLoaderClientHelper implements IModLoaderSidedHelper
{
public static int obtainBlockModelIdFor(BaseMod mod, boolean inventoryRenderer)
{
int renderId=RenderingRegistry.getNextAvailableRenderId();
ModLoaderBlockRendererHandler bri=new ModLoaderBlockRendererHandler(renderId, inventoryRenderer, mod);
RenderingRegistry.registerBlockHandler(bri);
return renderId;
}
public static void handleFinishLoadingFor(ModLoaderModContainer mc, Minecraft game)
{
FMLLog.log(mc.getModId(), Level.FINE, "Handling post startup activities for ModLoader mod %s", mc.getModId());
BaseMod mod = (BaseMod) mc.getMod();
Map<Class<? extends Entity>, Render> renderers = Maps.newHashMap(RenderManager.instance.entityRenderMap);
try
{
FMLLog.log(mc.getModId(), Level.FINEST, "Requesting renderers from basemod %s", mc.getModId());
mod.addRenderer(renderers);
FMLLog.log(mc.getModId(), Level.FINEST, "Received %d renderers from basemod %s", renderers.size(), mc.getModId());
}
catch (Exception e)
{
FMLLog.log(mc.getModId(), Level.SEVERE, e, "A severe problem was detected with the mod %s during the addRenderer call. Continuing, but expect odd results", mc.getModId());
}
MapDifference<Class<? extends Entity>, Render> difference = Maps.difference(RenderManager.instance.entityRenderMap, renderers, Equivalence.identity());
for ( Entry<Class<? extends Entity>, Render> e : difference.entriesOnlyOnLeft().entrySet())
{
FMLLog.log(mc.getModId(), Level.WARNING, "The mod %s attempted to remove an entity renderer %s from the entity map. This will be ignored.", mc.getModId(), e.getKey().getName());
}
for (Entry<Class<? extends Entity>, Render> e : difference.entriesOnlyOnRight().entrySet())
{
FMLLog.log(mc.getModId(), Level.FINEST, "Registering ModLoader entity renderer %s as instance of %s", e.getKey().getName(), e.getValue().getClass().getName());
RenderingRegistry.registerEntityRenderingHandler(e.getKey(), e.getValue());
}
for (Entry<Class<? extends Entity>, ValueDifference<Render>> e : difference.entriesDiffering().entrySet())
{
FMLLog.log(mc.getModId(), Level.FINEST, "Registering ModLoader entity rendering override for %s as instance of %s", e.getKey().getName(), e.getValue().rightValue().getClass().getName());
RenderingRegistry.registerEntityRenderingHandler(e.getKey(), e.getValue().rightValue());
}
try
{
mod.registerAnimation(game);
}
catch (Exception e)
{
FMLLog.log(mc.getModId(), Level.SEVERE, e, "A severe problem was detected with the mod %s during the registerAnimation call. Continuing, but expect odd results", mc.getModId());
}
}
public ModLoaderClientHelper(Minecraft client)
{
this.client = client;
ModLoaderHelper.sidedHelper = this;
keyBindingContainers = Multimaps.newMultimap(Maps.<ModLoaderModContainer, Collection<ModLoaderKeyBindingHandler>>newHashMap(), new Supplier<Collection<ModLoaderKeyBindingHandler>>()
{
@Override
public Collection<ModLoaderKeyBindingHandler> get()
{
return Collections.singleton(new ModLoaderKeyBindingHandler());
}
});
}
private Minecraft client;
private static Multimap<ModLoaderModContainer, ModLoaderKeyBindingHandler> keyBindingContainers;
@Override
public void finishModLoading(ModLoaderModContainer mc)
{
handleFinishLoadingFor(mc, client);
}
public static void registerKeyBinding(BaseModProxy mod, KeyBinding keyHandler, boolean allowRepeat)
{
ModLoaderModContainer mlmc = (ModLoaderModContainer) Loader.instance().activeModContainer();
ModLoaderKeyBindingHandler handler = Iterables.getOnlyElement(keyBindingContainers.get(mlmc));
handler.setModContainer(mlmc);
handler.addKeyBinding(keyHandler, allowRepeat);
KeyBindingRegistry.registerKeyBinding(handler);
}
@Override
public Object getClientGui(BaseModProxy mod, EntityPlayer player, int ID, int x, int y, int z)
{
return ((net.minecraft.src.BaseMod)mod).getContainerGUI((EntityClientPlayerMP) player, ID, x, y, z);
}
@Override
public Entity spawnEntity(BaseModProxy mod, EntitySpawnPacket input, EntityRegistration er)
{
return ((net.minecraft.src.BaseMod)mod).spawnEntity(er.getModEntityId(), client.theWorld, input.scaledX, input.scaledY, input.scaledZ);
}
@Override
public void sendClientPacket(BaseModProxy mod, Packet250CustomPayload packet)
{
((net.minecraft.src.BaseMod)mod).clientCustomPayload(client.thePlayer.sendQueue, packet);
}
private Map<INetworkManager,NetHandler> managerLookups = new MapMaker().weakKeys().weakValues().makeMap();
@Override
public void clientConnectionOpened(NetHandler netClientHandler, INetworkManager manager, BaseModProxy mod)
{
managerLookups.put(manager, netClientHandler);
((BaseMod)mod).clientConnect((NetClientHandler)netClientHandler);
}
@Override
public boolean clientConnectionClosed(INetworkManager manager, BaseModProxy mod)
{
if (managerLookups.containsKey(manager))
{
((BaseMod)mod).clientDisconnect((NetClientHandler) managerLookups.get(manager));
return true;
}
return false;
}
}
| HATB0T/RuneCraftery | forge/mcp/src/minecraft/cpw/mods/fml/client/modloader/ModLoaderClientHelper.java | Java | lgpl-3.0 | 7,879 |
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCBone.h"
#include "CCArmature.h"
#include "utils/CCUtilMath.h"
#include "utils/CCArmatureDataManager.h"
#include "utils/CCTransformHelp.h"
#include "display/CCDisplayManager.h"
NS_CC_EXT_BEGIN
CCBone *CCBone::create()
{
CCBone *pBone = new CCBone();
if (pBone && pBone->init())
{
pBone->autorelease();
return pBone;
}
CC_SAFE_DELETE(pBone);
return NULL;
}
CCBone *CCBone::create(const char *name)
{
CCBone *pBone = new CCBone();
if (pBone && pBone->init(name))
{
pBone->autorelease();
return pBone;
}
CC_SAFE_DELETE(pBone);
return NULL;
}
CCBone::CCBone()
{
m_pTweenData = NULL;
m_pParentBone = NULL;
m_pArmature = NULL;
m_pChildArmature = NULL;
m_pBoneData = NULL;
m_pTween = NULL;
m_pTween = NULL;
m_pChildren = NULL;
m_pDisplayManager = NULL;
m_bIgnoreMovementBoneData = false;
m_tWorldTransform = CCAffineTransformMake(1, 0, 0, 1, 0, 0);
m_bBoneTransformDirty = true;
m_tWorldInfo = NULL;
m_pArmatureParentBone = NULL;
m_fDataVersion = 0;
m_sBlendFunc.src = CC_BLEND_SRC;
m_sBlendFunc.dst = CC_BLEND_DST;
m_bBlendDirty = false;
}
CCBone::~CCBone(void)
{
CC_SAFE_DELETE(m_pTweenData);
CC_SAFE_DELETE(m_pChildren);
CC_SAFE_DELETE(m_pTween);
CC_SAFE_DELETE(m_pDisplayManager);
CC_SAFE_DELETE(m_tWorldInfo);
CC_SAFE_RELEASE_NULL(m_pBoneData);
CC_SAFE_RELEASE(m_pChildArmature);
}
bool CCBone::init()
{
return CCBone::init(NULL);
}
bool CCBone::init(const char *name)
{
bool bRet = false;
do
{
if(NULL != name)
{
m_strName = name;
}
CC_SAFE_DELETE(m_pTweenData);
m_pTweenData = new CCFrameData();
CC_SAFE_DELETE(m_pTween);
m_pTween = new CCTween();
m_pTween->init(this);
CC_SAFE_DELETE(m_pDisplayManager);
m_pDisplayManager = new CCDisplayManager();
m_pDisplayManager->init(this);
CC_SAFE_DELETE(m_tWorldInfo);
m_tWorldInfo = new CCBaseData();
CC_SAFE_DELETE(m_pBoneData);
m_pBoneData = new CCBoneData();
bRet = true;
}
while (0);
return bRet;
}
void CCBone::setBoneData(CCBoneData *boneData)
{
CCAssert(NULL != boneData, "_boneData must not be NULL");
if (m_pBoneData != boneData)
{
CC_SAFE_RETAIN(boneData);
CC_SAFE_RELEASE(m_pBoneData);
m_pBoneData = boneData;
}
m_strName = m_pBoneData->name;
m_nZOrder = m_pBoneData->zOrder;
m_pDisplayManager->initDisplayList(boneData);
}
CCBoneData *CCBone::getBoneData()
{
return m_pBoneData;
}
void CCBone::setArmature(CCArmature *armature)
{
m_pArmature = armature;
if (m_pArmature)
{
m_pTween->setAnimation(m_pArmature->getAnimation());
m_fDataVersion = m_pArmature->getArmatureData()->dataVersion;
m_pArmatureParentBone = m_pArmature->getParentBone();
}
else
{
m_pArmatureParentBone = NULL;
}
}
CCArmature *CCBone::getArmature()
{
return m_pArmature;
}
void CCBone::update(float delta)
{
if (m_pParentBone)
m_bBoneTransformDirty = m_bBoneTransformDirty || m_pParentBone->isTransformDirty();
if (m_pArmatureParentBone && !m_bBoneTransformDirty)
{
m_bBoneTransformDirty = m_pArmatureParentBone->isTransformDirty();
}
if (m_bBoneTransformDirty)
{
if (m_fDataVersion >= VERSION_COMBINED)
{
CCTransformHelp::nodeConcat(*m_pTweenData, *m_pBoneData);
m_pTweenData->scaleX -= 1;
m_pTweenData->scaleY -= 1;
}
m_tWorldInfo->x = m_pTweenData->x + m_obPosition.x;
m_tWorldInfo->y = m_pTweenData->y + m_obPosition.y;
m_tWorldInfo->scaleX = m_pTweenData->scaleX * m_fScaleX;
m_tWorldInfo->scaleY = m_pTweenData->scaleY * m_fScaleY;
m_tWorldInfo->skewX = m_pTweenData->skewX + m_fSkewX + m_fRotationX;
m_tWorldInfo->skewY = m_pTweenData->skewY + m_fSkewY - m_fRotationY;
if(m_pParentBone)
{
applyParentTransform(m_pParentBone);
}
else
{
if (m_pArmatureParentBone)
{
applyParentTransform(m_pArmatureParentBone);
}
}
CCTransformHelp::nodeToMatrix(*m_tWorldInfo, m_tWorldTransform);
if (m_pArmatureParentBone)
{
m_tWorldTransform = CCAffineTransformConcat(m_tWorldTransform, m_pArmature->nodeToParentTransform());
}
}
CCDisplayFactory::updateDisplay(this, delta, m_bBoneTransformDirty || m_pArmature->getArmatureTransformDirty());
CCObject *object = NULL;
CCARRAY_FOREACH(m_pChildren, object)
{
CCBone *childBone = (CCBone *)object;
childBone->update(delta);
}
m_bBoneTransformDirty = false;
}
void CCBone::applyParentTransform(CCBone *parent)
{
float x = m_tWorldInfo->x;
float y = m_tWorldInfo->y;
m_tWorldInfo->x = x * parent->m_tWorldTransform.a + y * parent->m_tWorldTransform.c + parent->m_tWorldInfo->x;
m_tWorldInfo->y = x * parent->m_tWorldTransform.b + y * parent->m_tWorldTransform.d + parent->m_tWorldInfo->y;
m_tWorldInfo->scaleX = m_tWorldInfo->scaleX * parent->m_tWorldInfo->scaleX;
m_tWorldInfo->scaleY = m_tWorldInfo->scaleY * parent->m_tWorldInfo->scaleY;
m_tWorldInfo->skewX = m_tWorldInfo->skewX + parent->m_tWorldInfo->skewX;
m_tWorldInfo->skewY = m_tWorldInfo->skewY + parent->m_tWorldInfo->skewY;
}
void CCBone::updateDisplayedColor(const ccColor3B &parentColor)
{
_realColor = ccc3(255, 255, 255);
CCNodeRGBA::updateDisplayedColor(parentColor);
updateColor();
}
void CCBone::updateDisplayedOpacity(GLubyte parentOpacity)
{
_realOpacity = 255;
CCNodeRGBA::updateDisplayedOpacity(parentOpacity);
updateColor();
}
void CCBone::setColor(const ccColor3B &color)
{
CCNodeRGBA::setColor(color);
updateColor();
}
void CCBone::setOpacity(GLubyte opacity)
{
CCNodeRGBA::setOpacity(opacity);
updateColor();
}
void CCBone::updateColor()
{
CCNode *display = m_pDisplayManager->getDisplayRenderNode();
CCRGBAProtocol *protocol = dynamic_cast<CCRGBAProtocol *>(display);
if(protocol != NULL)
{
protocol->setColor(ccc3(_displayedColor.r * m_pTweenData->r / 255, _displayedColor.g * m_pTweenData->g / 255, _displayedColor.b * m_pTweenData->b / 255));
protocol->setOpacity(_displayedOpacity * m_pTweenData->a / 255);
}
}
void CCBone::updateZOrder()
{
if (m_fDataVersion >= VERSION_COMBINED)
{
int zorder = m_pTweenData->zOrder + m_pBoneData->zOrder;
setZOrder(zorder);
}
else
{
setZOrder(m_pTweenData->zOrder);
}
}
void CCBone::addChildBone(CCBone *child)
{
CCAssert( NULL != child, "Argument must be non-nil");
CCAssert( NULL == child->m_pParentBone, "child already added. It can't be added again");
if(!m_pChildren)
{
m_pChildren = CCArray::createWithCapacity(4);
m_pChildren->retain();
}
if (m_pChildren->indexOfObject(child) == UINT_MAX)
{
m_pChildren->addObject(child);
child->setParentBone(this);
}
}
void CCBone::removeChildBone(CCBone *bone, bool recursion)
{
if ( m_pChildren->indexOfObject(bone) != UINT_MAX )
{
if(recursion)
{
CCArray *_ccbones = bone->m_pChildren;
CCObject *_object = NULL;
CCARRAY_FOREACH(_ccbones, _object)
{
CCBone *_ccBone = (CCBone *)_object;
bone->removeChildBone(_ccBone, recursion);
}
}
bone->setParentBone(NULL);
bone->getDisplayManager()->setCurrentDecorativeDisplay(NULL);
m_pChildren->removeObject(bone);
}
}
void CCBone::removeFromParent(bool recursion)
{
if (NULL != m_pParentBone)
{
m_pParentBone->removeChildBone(this, recursion);
}
}
void CCBone::setParentBone(CCBone *parent)
{
m_pParentBone = parent;
}
CCBone *CCBone::getParentBone()
{
return m_pParentBone;
}
void CCBone::setChildArmature(CCArmature *armature)
{
if (m_pChildArmature != armature)
{
if (armature == NULL && m_pChildArmature)
{
m_pChildArmature->setParentBone(NULL);
}
CC_SAFE_RETAIN(armature);
CC_SAFE_RELEASE(m_pChildArmature);
m_pChildArmature = armature;
}
}
CCArmature *CCBone::getChildArmature()
{
return m_pChildArmature;
}
CCTween *CCBone::getTween()
{
return m_pTween;
}
void CCBone::setBlendFunc(const ccBlendFunc& blendFunc)
{
if (m_sBlendFunc.src != blendFunc.src && m_sBlendFunc.dst != blendFunc.dst)
{
m_sBlendFunc = blendFunc;
m_bBlendDirty = true;
}
}
void CCBone::setZOrder(int zOrder)
{
if (m_nZOrder != zOrder)
CCNode::setZOrder(zOrder);
}
CCAffineTransform CCBone::nodeToArmatureTransform()
{
return m_tWorldTransform;
}
CCAffineTransform CCBone::nodeToWorldTransform()
{
return CCAffineTransformConcat(m_tWorldTransform, m_pArmature->nodeToWorldTransform());
}
CCNode *CCBone::getDisplayRenderNode()
{
return m_pDisplayManager->getDisplayRenderNode();
}
DisplayType CCBone::getDisplayRenderNodeType()
{
return m_pDisplayManager->getDisplayRenderNodeType();
}
void CCBone::addDisplay(CCDisplayData *displayData, int index)
{
m_pDisplayManager->addDisplay(displayData, index);
}
void CCBone::addDisplay(CCNode *display, int index)
{
m_pDisplayManager->addDisplay(display, index);
}
void CCBone::removeDisplay(int index)
{
m_pDisplayManager->removeDisplay(index);
}
void CCBone::changeDisplayByIndex(int index, bool force)
{
changeDisplayWithIndex(index, force);
}
void CCBone::changeDisplayByName(const char *name, bool force)
{
changeDisplayWithName(name, force);
}
void CCBone::changeDisplayWithIndex(int index, bool force)
{
m_pDisplayManager->changeDisplayWithIndex(index, force);
}
void CCBone::changeDisplayWithName(const char *name, bool force)
{
m_pDisplayManager->changeDisplayWithName(name, force);
}
CCArray *CCBone::getColliderBodyList()
{
if (CCDecorativeDisplay *decoDisplay = m_pDisplayManager->getCurrentDecorativeDisplay())
{
if (CCColliderDetector *detector = decoDisplay->getColliderDetector())
{
return detector->getColliderBodyList();
}
}
return NULL;
}
#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT
void CCBone::setColliderFilter(CCColliderFilter *filter)
{
CCArray *array = m_pDisplayManager->getDecorativeDisplayList();
CCObject *object = NULL;
CCARRAY_FOREACH(array, object)
{
CCDecorativeDisplay *decoDisplay = static_cast<CCDecorativeDisplay *>(object);
if (CCColliderDetector *detector = decoDisplay->getColliderDetector())
{
detector->setColliderFilter(filter);
}
}
}
CCColliderFilter *CCBone::getColliderFilter()
{
if (CCDecorativeDisplay *decoDisplay = m_pDisplayManager->getCurrentDecorativeDisplay())
{
if (CCColliderDetector *detector = decoDisplay->getColliderDetector())
{
return detector->getColliderFilter();
}
}
return NULL;
}
#endif
NS_CC_EXT_END
| gameview/WareCocos2dx | extensions/CocoStudio/Armature/CCBone.cpp | C++ | lgpl-3.0 | 12,553 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2) on Sat Sep 25 12:34:50 EDT 2004 -->
<TITLE>
org.apache.catalina.users (Catalina Internal API Documentation)
</TITLE>
<META NAME="keywords" CONTENT="org.apache.catalina.users package">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="org.apache.catalina.users (Catalina Internal API Documentation)";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/apache/catalina/startup/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../org/apache/catalina/util/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package org.apache.catalina.users
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Class Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/catalina/users/AbstractGroup.html" title="class in org.apache.catalina.users">AbstractGroup</A></B></TD>
<TD>Convenience base class for <A HREF="../../../../org/apache/catalina/Group.html" title="interface in org.apache.catalina"><CODE>Group</CODE></A> implementations.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/catalina/users/AbstractRole.html" title="class in org.apache.catalina.users">AbstractRole</A></B></TD>
<TD>Convenience base class for <A HREF="../../../../org/apache/catalina/Role.html" title="interface in org.apache.catalina"><CODE>Role</CODE></A> implementations.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/catalina/users/AbstractUser.html" title="class in org.apache.catalina.users">AbstractUser</A></B></TD>
<TD>Convenience base class for <A HREF="../../../../org/apache/catalina/User.html" title="interface in org.apache.catalina"><CODE>User</CODE></A> implementations.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/catalina/users/Constants.html" title="class in org.apache.catalina.users">Constants</A></B></TD>
<TD>Manifest constants for this Java package.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/catalina/users/MemoryGroup.html" title="class in org.apache.catalina.users">MemoryGroup</A></B></TD>
<TD>Concrete implementation of <A HREF="../../../../org/apache/catalina/Group.html" title="interface in org.apache.catalina"><CODE>Group</CODE></A> for the
<A HREF="../../../../org/apache/catalina/users/MemoryUserDatabase.html" title="class in org.apache.catalina.users"><CODE>MemoryUserDatabase</CODE></A> implementation of <A HREF="../../../../org/apache/catalina/UserDatabase.html" title="interface in org.apache.catalina"><CODE>UserDatabase</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/catalina/users/MemoryRole.html" title="class in org.apache.catalina.users">MemoryRole</A></B></TD>
<TD>Concrete implementation of <A HREF="../../../../org/apache/catalina/Role.html" title="interface in org.apache.catalina"><CODE>Role</CODE></A> for the
<A HREF="../../../../org/apache/catalina/users/MemoryUserDatabase.html" title="class in org.apache.catalina.users"><CODE>MemoryUserDatabase</CODE></A> implementation of <A HREF="../../../../org/apache/catalina/UserDatabase.html" title="interface in org.apache.catalina"><CODE>UserDatabase</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/catalina/users/MemoryUser.html" title="class in org.apache.catalina.users">MemoryUser</A></B></TD>
<TD>Concrete implementation of <A HREF="../../../../org/apache/catalina/User.html" title="interface in org.apache.catalina"><CODE>User</CODE></A> for the
<A HREF="../../../../org/apache/catalina/users/MemoryUserDatabase.html" title="class in org.apache.catalina.users"><CODE>MemoryUserDatabase</CODE></A> implementation of <A HREF="../../../../org/apache/catalina/UserDatabase.html" title="interface in org.apache.catalina"><CODE>UserDatabase</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/catalina/users/MemoryUserDatabase.html" title="class in org.apache.catalina.users">MemoryUserDatabase</A></B></TD>
<TD>Concrete implementation of <A HREF="../../../../org/apache/catalina/UserDatabase.html" title="interface in org.apache.catalina"><CODE>UserDatabase</CODE></A> that loads all
defined users, groups, and roles into an in-memory data structure,
and uses a specified XML file for its persistent storage.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/catalina/users/MemoryUserDatabaseFactory.html" title="class in org.apache.catalina.users">MemoryUserDatabaseFactory</A></B></TD>
<TD>JNDI object creation factory for <code>MemoryUserDatabase</code>
instances.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/apache/catalina/startup/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../org/apache/catalina/util/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2000-2002 Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| simeshev/parabuild-ci | 3rdparty/tomcat4131/webapps/tomcat-docs/catalina/docs/api/org/apache/catalina/users/package-summary.html | HTML | lgpl-3.0 | 9,897 |
/****************************************************************************
**
** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt3D 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 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.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QT3DCORE_JOB_COMMON_P_H
#define QT3DCORE_JOB_COMMON_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <Qt3DCore/private/qaspectjob_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DCore {
namespace JobTypes {
enum JobType {
LoadBuffer = 4096,
CalcBoundingVolume,
};
} // JobTypes
} // Qt3DCore
QT_END_NAMESPACE
#endif // QT3DCORE_JOB_COMMON_P_H
| qtproject/qt3d | src/core/jobs/job_common_p.h | C | lgpl-3.0 | 2,519 |
package fi.cs.ubicomp.database.traces;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class TracesCollector {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
public static String TABLENAME = "loadtraces";
public TracesCollector(){
}
public void saveTrace(double timestamp, String device, int accgroup, double rtt, double energy, double responsetime){
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager
.getConnection("jdbc:mysql://localhost/qoe?"
+ "user=huberuser&password=huber");
String sql = "INSERT INTO " + TABLENAME + "(timestamp, device, acceleration, rtt, energy, responsetime) " +
"VALUES ("+ timestamp + "," + "\"" + device + "\"" + "," + accgroup + "," + rtt + "," + energy + "," + responsetime + ");";
preparedStatement = connect.
prepareStatement(sql);
preparedStatement.executeUpdate();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
close();
}
}
private void close() {
try {
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
}
| mobile-cloud-computing/ScalingMobileCodeOffloading | Framework-JVM/Manager/CodeOffload/src/main/java/fi/cs/ubicomp/database/traces/TracesCollector.java | Java | lgpl-3.0 | 1,634 |
/*
* Copyright (C) 2009 Christian Hujer
*
* 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 net.sf.japi.progs.jeduca.jtest.gui;
import java.awt.GridBagConstraints;
import static java.awt.GridBagConstraints.HORIZONTAL;
import static java.awt.GridBagConstraints.NORTHWEST;
import static java.awt.GridBagConstraints.REMAINDER;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import static javax.swing.BorderFactory.createTitledBorder;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import net.sf.japi.progs.jeduca.jtest.Settings;
import net.sf.japi.swing.prefs.AbstractPrefs;
/** Settings module.
* @author <a href="mailto:cher@riedquat.de">Christian Hujer</a>
* @since 0.1
*/
public class FirstSettingsModule extends AbstractPrefs {
/** Serial Version. */
@SuppressWarnings({"AnalyzingVariableNaming"})
private static final long serialVersionUID = 1L;
/** The Settings. */
private transient Settings settings;
/** ShowSolutionsOn.
* @serial include
*/
private final JRadioButton showSolutionsOn;
/** ShowSolutionsOff.
* @serial include
*/
private final JRadioButton showSolutionsOff;
/** Create a FirstSettingsModule.
* @param settings Settings to modify
*/
public FirstSettingsModule(final Settings settings) {
setLayout(new GridBagLayout());
final JPanel showSolutionPanel = new JPanel(new GridLayout(2, 1));
//setBorder(createCompoundBorder(createTitledBorder("Dummy Lösungen anzeigen"), createEtchedBorder()));
showSolutionPanel.setBorder(createTitledBorder("Dummy Lösungen anzeigen"));
final ButtonGroup solutions = new ButtonGroup();
showSolutionsOn = new JRadioButton("Dummy Auflösung nach jeder Frage anzeigen");
showSolutionsOff = new JRadioButton("Auflösung für alle Fragen erst am Ende des Tests anzeigen");
showSolutionPanel.add(showSolutionsOn);
showSolutionPanel.add(showSolutionsOff);
solutions.add(showSolutionsOn);
solutions.add(showSolutionsOff);
final GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = REMAINDER;
gbc.fill = HORIZONTAL;
gbc.anchor = NORTHWEST;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(showSolutionPanel, gbc);
setSettings(settings);
setHelpURL(getClass().getClassLoader().getResource("help/FirstSettingsModule.html"));
setListLabelText("Dummy Auflösung");
setLabelText("Dummy Einstellungen zum Anzeigen der Auflösungen");
}
/** Returns the Settings.
* @return the Settings.
*/
public Settings getSettings() {
return settings;
}
/** Set the Settings Object to be attached.
* Automatically sets the state of all GUI components to the current settings of the Settings object.
* @param settings Settings object to be attached
*/
public void setSettings(final Settings settings) {
this.settings = settings;
restore();
}
/** ??? */ // TODO:2009-02-22:christianhujer:Provide in supertype and use {@inheritDoc} ?
public void restore() {
showSolutionsOn.setSelected(settings.isShowQuestionSolution());
showSolutionsOff.setSelected(!settings.isShowQuestionSolution());
}
/** {@inheritDoc} */
public String getSettingsId() {
return "displaySolution";
}
/** {@inheritDoc} */
public void apply() {
settings.setShowQuestionSolution(showSolutionsOn.isSelected());
}
/** {@inheritDoc} */
public void defaults() {
// TODO:2009-02-22:christianhujer:Implement.
restore();
}
public boolean isChanged() {
// TODO:2009-02-22:christianhujer:Implement.
return false;
}
public void revert() {
// TODO:2009-02-22:christianhujer:Implement.
}
} // class FirstSettingsModule
| christianhujer/japi | historic2/src/prj/net/sf/japi/progs/jeduca/jtest/gui/FirstSettingsModule.java | Java | lgpl-3.0 | 4,554 |
/*
* Copyright 2006 - 2013
* Stefan Balev <stefan.balev@graphstream-project.org>
* Julien Baudry <julien.baudry@graphstream-project.org>
* Antoine Dutot <antoine.dutot@graphstream-project.org>
* Yoann Pigné <yoann.pigne@graphstream-project.org>
* Guilhelm Savin <guilhelm.savin@graphstream-project.org>
*
* This file is part of GraphStream <http://graphstream-project.org>.
*
* GraphStream is a library whose purpose is to handle static or dynamic
* graph, create them from scratch, file or any source and display them.
*
* This program is free software distributed under the terms of two licenses, the
* CeCILL-C license that fits European law, and the GNU Lesser General Public
* License. You can use, modify and/ or redistribute the software under the terms
* of the CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
* URL <http://www.cecill.info> or under the terms of the GNU LGPL 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/>.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-C and LGPL licenses and that you accept their terms.
*/
package org.graphstream.graph.implementations;
/**
* Default implementation of graph. This is just a synonym of {@link SingleGraph}. It is here for clarity only.
*
*/
public class DefaultGraph extends SingleGraph {
/**
* Creates an empty graph.
*
* @param id
* Unique identifier of the graph.
* @param strictChecking
* If true any non-fatal error throws an exception.
* @param autoCreate
* If true (and strict checking is false), nodes are
* automatically created when referenced when creating a edge,
* even if not yet inserted in the graph.
* @param initialNodeCapacity
* Initial capacity of the node storage data structures. Use this
* if you know the approximate maximum number of nodes of the
* graph. The graph can grow beyond this limit, but storage
* reallocation is expensive operation.
* @param initialEdgeCapacity
* Initial capacity of the edge storage data structures. Use this
* if you know the approximate maximum number of edges of the
* graph. The graph can grow beyond this limit, but storage
* reallocation is expensive operation.
*/
public DefaultGraph(String id, boolean strictChecking, boolean autoCreate,
int initialNodeCapacity, int initialEdgeCapacity) {
super(id, strictChecking, autoCreate, initialNodeCapacity,
initialEdgeCapacity);
}
/**
* Creates an empty graph with default edge and node capacity.
*
* @param id
* Unique identifier of the graph.
* @param strictChecking
* If true any non-fatal error throws an exception.
* @param autoCreate
* If true (and strict checking is false), nodes are
* automatically created when referenced when creating a edge,
* even if not yet inserted in the graph.
*/
public DefaultGraph(String id, boolean strictChecking, boolean autoCreate) {
super(id, strictChecking, autoCreate);
}
/**
* Creates an empty graph with strict checking and without auto-creation.
*
* @param id
* Unique identifier of the graph.
*/
public DefaultGraph(String id) {
super(id);
}
}
| margaritis/gs-core | src/org/graphstream/graph/implementations/DefaultGraph.java | Java | lgpl-3.0 | 3,896 |
/* radare - LGPL - Copyright 2010-2017 - pancake, oddcoder */
#include <r_anal.h>
#include <r_util.h>
#include <r_cons.h>
#include <r_list.h>
#define DB a->sdb_fcns
struct VarType {
char kind;
char *type;
int size;
char *name;
};
#define SDB_VARTYPE_FMT "czdz"
#define EXISTS(x, ...) snprintf (key, sizeof (key) - 1, x, ## __VA_ARGS__), sdb_exists (DB, key)
#define SETKEY(x, ...) snprintf (key, sizeof (key) - 1, x, ## __VA_ARGS__);
#define SETKEY2(x, ...) snprintf (key2, sizeof (key) - 1, x, ## __VA_ARGS__);
#define SETVAL(x, ...) snprintf (val, sizeof (val) - 1, x, ## __VA_ARGS__);
R_API bool r_anal_var_display(RAnal *anal, int delta, char kind, const char *type) {
char *fmt = r_anal_type_format (anal, type);
RRegItem *i;
if (!fmt) {
eprintf ("type:%s doesn't exist\n", type);
return false;
}
bool usePxr = !strcmp (type, "int"); // hacky but useful
switch (kind) {
case R_ANAL_VAR_KIND_REG:
i = r_reg_index_get (anal->reg, delta);
if (i) {
if (usePxr) {
anal->cb_printf ("pxr $w @r:%s\n", i->name);
} else {
anal->cb_printf ("pf r (%s)\n", i->name);
}
} else {
eprintf ("register not found\n");
}
break;
case R_ANAL_VAR_KIND_BPV:
if (delta > 0) {
if (usePxr) {
anal->cb_printf ("pxr $w @%s+0x%x\n", anal->reg->name[R_REG_NAME_BP], delta);
} else {
anal->cb_printf ("pf %s @%s+0x%x\n", fmt, anal->reg->name[R_REG_NAME_BP], delta);
}
} else {
if (usePxr) {
anal->cb_printf ("pxr $w @%s+0x%x\n", anal->reg->name[R_REG_NAME_BP], -delta);
} else {
anal->cb_printf ("pf %s @%s-0x%x\n", fmt, anal->reg->name[R_REG_NAME_BP], -delta);
}
}
break;
case R_ANAL_VAR_KIND_SPV:
if (usePxr) {
anal->cb_printf ("pxr $w @%s+0x%x\n", anal->reg->name[R_REG_NAME_SP], delta);
} else {
anal->cb_printf ("pf %s @ %s+0x%x\n", fmt, anal->reg->name[R_REG_NAME_SP], delta);
}
break;
}
free (fmt);
return true;
}
R_API bool r_anal_var_add(RAnal *a, ut64 addr, int scope, int delta, char kind, const char *type, int size, const char *name) {
if (!a) {
return false;
}
if (!kind) {
kind = R_ANAL_VAR_KIND_BPV;
}
if (!type) {
type = "int";
}
switch (kind) {
case R_ANAL_VAR_KIND_BPV: // base pointer var/args
case R_ANAL_VAR_KIND_SPV: // stack pointer var/args
case R_ANAL_VAR_KIND_REG: // registers args
break;
default:
eprintf ("Invalid var kind '%c'\n", kind);
return false;
}
const char *var_def = sdb_fmt (0, "%c,%s,%d,%s", kind, type, size, name);
if (scope > 0) {
const char *sign = "";
if (delta < 0) {
delta = -delta;
sign = "_";
}
/* local variable */
const char *fcn_key = sdb_fmt (1, "fcn.0x%"PFMT64x ".%c", addr, kind);
const char *var_key = sdb_fmt (2, "var.0x%"PFMT64x ".%c.%d.%s%d", addr, kind, scope, sign, delta);
const char *name_key = sdb_fmt (3, "var.0x%"PFMT64x ".%d.%s", addr, scope, name);
const char *shortvar = sdb_fmt (4, "%d.%s%d", scope, sign, delta);
sdb_array_add (DB, fcn_key, shortvar, 0);
sdb_set (DB, var_key, var_def, 0);
if (*sign) {
delta = -delta;
}
const char *name_val = sdb_fmt (5, "%c,%d", kind, delta);
sdb_set (DB, name_key, name_val, 0);
} else {
/* global variable */
const char *var_global = sdb_fmt (1, "var.0x%"PFMT64x, addr);
const char *var_def = sdb_fmt (2, "%c.%s,%d,%s", kind, type, size, name);
sdb_array_add (DB, var_global, var_def, 0);
}
// ls_sort (DB->ht->list, mystrcmp);
return true;
}
R_API int r_anal_var_retype(RAnal *a, ut64 addr, int scope, int delta, char kind, const char *type, int size, const char *name) {
if (!a) {
return false;
}
if (kind < 1) {
kind = R_ANAL_VAR_KIND_BPV;
}
if (!type) {
type = "int";
}
RAnalFunction *fcn = r_anal_get_fcn_in (a, addr, 0);
if (!fcn) {
eprintf ("Cant find function here\n");
return false;
}
if (size == -1) {
RList *list = r_anal_var_list (a, fcn, kind);
RListIter *iter;
RAnalVar *var;
r_list_foreach (list, iter, var) {
if (delta == -1 && !strcmp (var->name, name)) {
delta = var->delta;
size = var->size;
break;
}
}
r_list_free (list);
}
switch (kind) {
case R_ANAL_VAR_KIND_REG:
case R_ANAL_VAR_KIND_BPV:
case R_ANAL_VAR_KIND_SPV:
break;
default:
eprintf ("Invalid var kind '%c'\n", kind);
return false;
}
const char *var_def = sdb_fmt (0, "%c,%s,%d,%s", kind, type, size, name);
if (scope > 0) {
char *sign = delta> 0? "": "_";
/* local variable */
const char *fcn_key = sdb_fmt (1, "fcn.0x%"PFMT64x ".%c", fcn->addr, kind);
const char *var_key = sdb_fmt (2, "var.0x%"PFMT64x ".%c.%d.%s%d", fcn->addr, kind, scope, sign, R_ABS(delta));
const char *name_key = sdb_fmt (3, "var.0x%"PFMT64x ".%d.%s", fcn->addr, scope, name);
const char *shortvar = sdb_fmt (4, "%d.%s%d", scope, sign, R_ABS(delta));
const char *name_val = sdb_fmt (5, "%c,%d", kind, delta);
sdb_array_add (DB, fcn_key, shortvar, 0);
sdb_set (DB, var_key, var_def, 0);
sdb_set (DB, name_key, name_val, 0);
Sdb *TDB = a->sdb_types;
const char *type_kind = sdb_const_get (TDB, type, 0);
if (type_kind && r_str_startswith (type_kind, "struct")) {
char *field;
int field_n;
char *type_key = r_str_newf ("%s.%s", type_kind, type);
for (field_n = 0; (field = sdb_array_get (TDB, type_key, field_n, NULL)); field_n++) {
char *field_key = r_str_newf ("%s.%s", type_key, field);
char *field_type = sdb_array_get (TDB, field_key, 0, NULL);
ut64 field_offset = sdb_array_get_num (TDB, field_key, 1, NULL);
if (field_offset != 0) { // delete variables which are overlayed by structure
r_anal_var_delete (a, addr, kind, scope, delta + field_offset);
}
free (field_type);
free (field_key);
free (field);
}
free (type_key);
}
} else {
/* global variable */
const char *var_global = sdb_fmt (1, "var.0x%"PFMT64x, fcn->addr);
sdb_array_add (DB, var_global, var_def, 0);
}
return true;
}
R_API int r_anal_var_delete_all(RAnal *a, ut64 addr, const char kind) {
RAnalFunction *fcn = r_anal_get_fcn_in (a, addr, 0);
if (fcn) {
RAnalVar *v;
RListIter *iter;
RList *list = r_anal_var_list (a, fcn, kind);
r_list_foreach (list, iter, v) {
// r_anal_var_delete (a, addr, kind, v->scope, v->delta);
r_anal_var_delete (a, addr, kind, 1, v->delta);
}
// XXX: i dont think we want to alocate and free by hand. r_anal_var_delete should be the list->free already
r_list_free (list);
}
return 0;
}
R_API int r_anal_var_delete(RAnal *a, ut64 addr, const char kind, int scope, int delta) {
RAnalVar *av = r_anal_var_get (a, addr, kind, scope, delta);
if (!av) {
return false;
}
if (scope > 0) {
char *sign = "";
if (delta < 0) {
delta = -delta;
sign = "_";
}
char *fcn_key = sdb_fmt (1, "fcn.0x%"PFMT64x ".%c", addr, kind);
char *var_key = sdb_fmt (2, "var.0x%"PFMT64x ".%c.%d.%s%d", addr, kind, scope, sign, delta);
char *name_key = sdb_fmt (3, "var.0x%"PFMT64x ".%d.%s", addr, scope, av->name);
char *shortvar = sdb_fmt (4, "%d.%s%d", scope, sign, delta);
sdb_array_remove (DB, fcn_key, shortvar, 0);
sdb_unset (DB, var_key, 0);
sdb_unset (DB, name_key, 0);
if (*sign) {
delta = -delta;
}
} else {
char *var_global = sdb_fmt (1, "var.0x%"PFMT64x, addr);
char *var_def = sdb_fmt (2, "%c.%s,%d,%s", kind, av->type, av->size, av->name);
sdb_array_remove (DB, var_global, var_def, 0);
}
r_anal_var_free (av);
r_anal_var_access_clear (a, addr, scope, delta);
return true;
}
R_API bool r_anal_var_delete_byname(RAnal *a, RAnalFunction *fcn, int kind, const char *name) {
char *varlist;
if (!a || !fcn) {
return false;
}
varlist = sdb_get (DB, sdb_fmt (0, "fcn.0x%"PFMT64x ".%c",
fcn->addr, kind), 0);
if (varlist) {
char *next, *ptr = varlist;
if (varlist && *varlist) {
do {
char *word = sdb_anext (ptr, &next);
char *sign = strstr (word, "_");
const char *vardef = sdb_const_get (DB, sdb_fmt (1,
"var.0x%"PFMT64x ".%c.%s",
fcn->addr, kind, word), 0);
if (sign) {
*sign = '-';
}
int delta = strlen (word) < 3? -1: atoi (word + 2);
if (vardef) {
const char *p = strchr (vardef, ',');
if (p) {
p = strchr (p + 1, ',');
if (p) {
p = strchr (p + 1, ',');
if (p) {
int mykind = vardef[0];
if (!strcmp (p + 1, name)) {
return r_anal_var_delete (a, fcn->addr,
mykind, 1, delta);
}
}
}
}
} else {
eprintf ("Inconsistent Sdb storage, Cannot find '%s'\n", word);
}
ptr = next;
} while (next);
}
}
free (varlist);
return false;
}
R_API RAnalVar *r_anal_var_get_byname(RAnal *a, RAnalFunction *fcn, const char *name) {
if (!fcn || !a || !name) {
// eprintf ("No something\n");
return NULL;
}
char *name_key = sdb_fmt (-1, "var.0x%"PFMT64x ".%d.%s", fcn->addr, 1, name);
const char *name_value = sdb_const_get (DB, name_key, 0);
if (!name_value) {
// eprintf ("Cant find key for %s\n", name_key);
return NULL;
}
const char *comma = strchr (name_value, ',');
if (comma) {
int delta = r_num_math (NULL, comma + 1);
// eprintf ("Silently failing (%s)\n", name_value);
return r_anal_var_get (a, fcn->addr, *name_value, 1, delta);
}
return NULL;
}
R_API RAnalVar *r_anal_var_get(RAnal *a, ut64 addr, char kind, int scope, int delta) {
RAnalVar *av;
struct VarType vt = {
0
};
char *sign = "";
RAnalFunction *fcn = r_anal_get_fcn_in (a, addr, 0);
if (!fcn) {
return NULL;
}
if (delta < 0) {
delta = -delta;
sign = "_";
}
const char *varkey = sdb_fmt (-1, "var.0x%"PFMT64x ".%c.%d.%s%d",
fcn->addr, kind, scope, sign, delta);
const char *vardef = sdb_const_get (DB, varkey, 0);
if (!vardef) {
return NULL;
}
if (*sign) {
delta = -delta;
}
sdb_fmt_init (&vt, SDB_VARTYPE_FMT);
sdb_fmt_tobin (vardef, SDB_VARTYPE_FMT, &vt);
av = R_NEW0 (RAnalVar);
if (!av) {
sdb_fmt_free (&vt, SDB_VARTYPE_FMT);
return NULL;
}
av->addr = fcn->addr;
av->scope = scope;
av->delta = delta;
av->name = vt.name? strdup (vt.name): strdup ("unkown_var");
av->size = vt.size;
av->type = vt.type? strdup (vt.type): strdup ("unkown_type");
av->kind = kind;
sdb_fmt_free (&vt, SDB_VARTYPE_FMT);
// TODO:
// get name from sdb
// get size from sdb
// get type from sdb
return av;
}
R_API void r_anal_var_free(RAnalVar *av) {
if (av) {
free (av->name);
free (av->type);
R_FREE (av);
}
}
/* (columns) elements in the array value */
#define R_ANAL_VAR_SDB_KIND 0 /* char */
#define R_ANAL_VAR_SDB_TYPE 1 /* string */
#define R_ANAL_VAR_SDB_SIZE 2 /* number */
#define R_ANAL_VAR_SDB_NAME 3 /* string */
#define IS_NUMBER(x) ((x) >= '0' && (x) <= '9')
R_API bool r_anal_var_check_name(const char *name) {
return !IS_NUMBER (*name) && strcspn (name, "., =/");
}
// afvn local_48 counter
R_API int r_anal_var_rename(RAnal *a, ut64 var_addr, int scope, char kind, const char *old_name, const char *new_name) {
char key[128], *stored_name;
int delta;
if (!r_anal_var_check_name (new_name)) {
// eprintf ("Invalid name\n");
return 0;
}
RAnalFunction *fcn = r_anal_get_fcn_in (a, var_addr, 0);
RAnalVar *v1 = r_anal_var_get_byname (a, fcn, new_name);
if (v1) {
r_anal_var_free (v1);
eprintf ("variable or arg with name `%s` already exist\n", new_name);
return false;
}
// XXX: This is hardcoded because ->kind seems to be 0
scope = 1;
// XXX. this is pretty weak, because oldname may not exist too and error returned.
if (scope > 0) { // local
const char *sign = "";
SETKEY ("var.0x%"PFMT64x ".%d.%s", var_addr, scope, old_name);
char *name_val = sdb_get (DB, key, 0);
char *comma = strchr (name_val, ',');
if (comma) {
delta = r_num_math (NULL, comma + 1);
sdb_unset (DB, key, 0);
SETKEY ("var.0x%"PFMT64x ".%d.%s", var_addr, scope, new_name);
sdb_set (DB, key, name_val, 0);
free (name_val);
if (delta < 0) {
delta = -delta;
sign = "_";
}
SETKEY ("var.0x%"PFMT64x ".%c.%d.%s%d", var_addr, kind, scope, sign, delta);
sdb_array_set (DB, key, R_ANAL_VAR_SDB_NAME, new_name, 0);
}
} else { // global
SETKEY ("var.0x%"PFMT64x, var_addr);
stored_name = sdb_array_get (DB, key, R_ANAL_VAR_SDB_NAME, 0);
if (!stored_name) {
eprintf ("Cannot find key in storage.\n");
return 0;
}
if (!old_name) {
old_name = stored_name;
} else if (strcmp (stored_name, old_name)) {
eprintf ("Old name missmatch %s vs %s.\n", stored_name, old_name);
return 0;
}
sdb_unset (DB, key, 0);
SETKEY ("var.0x%"PFMT64x, var_addr);
sdb_array_set (DB, key, R_ANAL_VAR_SDB_NAME, new_name, 0);
}
// var.sdb_hash(old_name)=var_addr.scope.delta
return 1;
}
// avr
R_API int r_anal_var_access(RAnal *a, ut64 var_addr, char kind, int scope, int delta, int xs_type, ut64 xs_addr) {
const char *var_global;
const char *xs_type_str = xs_type? "writes": "reads";
// TODO: kind is not used
if (scope > 0) { // local
const char *var_local = sdb_fmt (0, "var.0x%"PFMT64x ".%d.%d.%s",
var_addr, scope, delta, xs_type_str);
const char *inst_key = sdb_fmt (1, "inst.0x%"PFMT64x ".vars", xs_addr);
const char *var_def = sdb_fmt (2, "0x%"PFMT64x ",%c,0x%x,0x%x", var_addr,
kind, scope, delta);
sdb_set (DB, inst_key, var_def, 0);
return sdb_array_add_num (DB, var_local, xs_addr, 0);
}
// global
sdb_add (DB, sdb_fmt (0, "var.0x%"PFMT64x, var_addr), "a,", 0);
var_global = sdb_fmt (0, "var.0x%"PFMT64x ".%s", var_addr, xs_type_str);
return sdb_array_add_num (DB, var_global, xs_addr, 0);
}
R_API void r_anal_var_access_clear(RAnal *a, ut64 var_addr, int scope, int delta) {
char key[128], key2[128];
if (scope > 0) { // local arg or var
SETKEY ("var.0x%"PFMT64x ".%d.%d.%s", var_addr, scope, delta, "writes");
SETKEY2 ("var.0x%"PFMT64x ".%d.%d.%s", var_addr, scope, delta, "reads");
} else { // global
SETKEY ("var.0x%"PFMT64x ".%s", var_addr, "writes");
SETKEY2 ("var.0x%"PFMT64x ".%s", var_addr, "reads");
}
sdb_unset (DB, key, 0);
sdb_unset (DB, key2, 0);
}
R_API int r_anal_fcn_var_del_bydelta(RAnal *a, ut64 fna, const char kind, int scope, ut32 delta) {
int idx;
char key[128], val[128], *v;
SETKEY ("fcn.0x%08"PFMT64x ".%c", fna, kind);
v = sdb_itoa (delta, val, 10);
idx = sdb_array_indexof (DB, key, v, 0);
if (idx != -1) {
sdb_array_delete (DB, key, idx, 0);
SETKEY ("fcn.0x%08"PFMT64x ".%c.%d", fna, kind, delta);
sdb_unset (DB, key, 0);
}
return false;
}
R_API int r_anal_var_count(RAnal *a, RAnalFunction *fcn, int kind, int type) {
// type { local: 0, arg: 1 };
RList *list = r_anal_var_list (a, fcn, kind);
RAnalVar *var;
RListIter *iter;
int count[2] = {
0
};
r_list_foreach (list, iter, var) {
if (kind == R_ANAL_VAR_KIND_REG) {
count[1]++;
continue;
}
count[(kind == R_ANAL_VAR_KIND_BPV && var->delta > 0) || (kind == R_ANAL_VAR_KIND_SPV && var->delta > fcn->maxstack)]++;
}
r_list_free (list);
return count[type];
}
static void var_add_structure_fields_to_list(RAnal *a, RAnalVar *av, const char *base_name, int delta, RList *list) {
/* ATTENTION: av->name might be freed and reassigned */
Sdb *TDB = a->sdb_types;
const char *type_kind = sdb_const_get (TDB, av->type, 0);
if (type_kind && r_str_startswith (type_kind, "struct")) {
char *field_name, *new_name;
int field_n;
char *type_key = r_str_newf ("%s.%s", type_kind, av->type);
for (field_n = 0; (field_name = sdb_array_get (TDB, type_key, field_n, NULL)); field_n++) {
char *field_key = r_str_newf ("%s.%s", type_key, field_name);
char *field_type = sdb_array_get (TDB, field_key, 0, NULL);
ut64 field_offset = sdb_array_get_num (TDB, field_key, 1, NULL);
int field_count = sdb_array_get_num (TDB, field_key, 2, NULL);
int field_size = r_anal_type_get_size (a, field_type) * (field_count? field_count: 1);
new_name = r_str_newf ( "%s.%s", base_name, field_name);
if (field_offset == 0) {
free (av->name);
av->name = new_name;
} else {
RAnalVar *fav = R_NEW0 (RAnalVar);
if (!fav) {
free (field_key);
free (new_name);
continue;
}
fav->delta = delta + field_offset;
fav->kind = av->kind;
fav->name = new_name;
fav->size = field_size;
fav->type = strdup (field_type);
r_list_append (list, fav);
}
free (field_type);
free (field_key);
free (field_name);
}
free (type_key);
}
}
static RList *var_generate_list(RAnal *a, RAnalFunction *fcn, int kind, bool dynamicVars) {
if (!a || !fcn) {
return NULL;
}
RList *list = r_list_newf ((RListFree) r_anal_var_free);
if (kind < 1) {
kind = R_ANAL_VAR_KIND_BPV; // by default show vars
}
char *varlist = sdb_get (DB, sdb_fmt (0, "fcn.0x%"PFMT64x ".%c", fcn->addr, kind), 0);
if (varlist && *varlist) {
char *next, *ptr = varlist;
do {
char *word = sdb_anext (ptr, &next);
if (r_str_nlen (word, 3) < 3) {
return NULL;
}
const char *vardef = sdb_const_get (DB, sdb_fmt (1,
"var.0x%"PFMT64x ".%c.%s",
fcn->addr, kind, word), 0);
if (word[2] == '_') {
word[2] = '-';
}
int delta = atoi (word + 2);
if (vardef) {
struct VarType vt = { 0 };
sdb_fmt_init (&vt, SDB_VARTYPE_FMT);
sdb_fmt_tobin (vardef, SDB_VARTYPE_FMT, &vt);
RAnalVar *av = R_NEW0 (RAnalVar);
if (!av) {
free (varlist);
r_list_free (list);
return NULL;
}
if (!vt.name || !vt.type) {
// This should be properly fixed
eprintf ("Warning null var in fcn.0x%"PFMT64x ".%c.%s\n",
fcn->addr, kind, word);
free (av);
continue;
}
av->delta = delta;
av->kind = kind;
av->name = strdup (vt.name);
av->size = vt.size;
av->type = strdup (vt.type);
r_list_append (list, av);
if (dynamicVars) { // make dynamic variables like structure fields
var_add_structure_fields_to_list (a, av, vt.name, delta, list);
}
sdb_fmt_free (&vt, SDB_VARTYPE_FMT);
} else {
eprintf ("Cannot find var definition for '%s'\n", word);
}
ptr = next;
} while (next);
}
free (varlist);
return list;
}
R_API RList *r_anal_var_all_list(RAnal *anal, RAnalFunction *fcn) {
// r_anal_var_list if there are not vars with that kind returns a list with
// zero element.. which is an unnecessary loss of cpu time
RList *list = r_anal_var_list (anal, fcn, R_ANAL_VAR_KIND_ARG);
if (!list) {
return NULL;
}
r_list_join (list, r_anal_var_list (anal, fcn, R_ANAL_VAR_KIND_REG));
r_list_join (list, r_anal_var_list (anal, fcn, R_ANAL_VAR_KIND_BPV));
r_list_join (list, r_anal_var_list (anal, fcn, R_ANAL_VAR_KIND_SPV));
return list;
}
R_API RList *r_anal_var_list(RAnal *a, RAnalFunction *fcn, int kind) {
return var_generate_list (a, fcn, kind, false);
}
R_API RList *r_anal_var_list_dynamic(RAnal *a, RAnalFunction *fcn, int kind) {
return var_generate_list (a, fcn, kind, true);
}
static int var_comparator(const RAnalVar *a, const RAnalVar *b){
// avoid NULL dereference
return (a && b)? a->delta > b->delta: false;
}
R_API void r_anal_var_list_show(RAnal *anal, RAnalFunction *fcn, int kind, int mode) {
RList *list = r_anal_var_list (anal, fcn, kind);
r_list_sort (list, (RListComparator) var_comparator);
RAnalVar *var;
RListIter *iter;
if (mode == 'j') {
anal->cb_printf ("[");
}
r_list_foreach (list, iter, var) {
if (var->kind != kind) {
continue;
}
switch (mode) {
case '*':
// we cant express all type info here :(
if (kind == R_ANAL_VAR_KIND_REG) { // registers
RRegItem *i = r_reg_index_get (anal->reg, var->delta);
if (!i) {
eprintf ("Register not found");
break;
}
anal->cb_printf ("afv%c %s %s %s @ 0x%"PFMT64x "\n",
kind, i->name, var->name, var->type, fcn->addr);
} else {
anal->cb_printf ("afv%c %d %s %s @ 0x%"PFMT64x "\n",
kind, var->delta, var->name, var->type,
fcn->addr);
}
break;
case 'j':
switch (var->kind) {
case R_ANAL_VAR_KIND_BPV:
if (var->delta > 0) {
anal->cb_printf ("{\"name\":\"%s\","
"\"kind\":\"arg\",\"type\":\"%s\",\"ref\":"
"{\"base\":\"%s\", \"offset\":%"PFMT64d "}}",
var->name, var->type, anal->reg->name[R_REG_NAME_BP],
var->delta);
} else {
anal->cb_printf ("{\"name\":\"%s\","
"\"kind\":\"var\",\"type\":\"%s\",\"ref\":"
"{\"base\":\"%s\", \"offset\":-%"PFMT64d "}}",
var->name, var->type, anal->reg->name[R_REG_NAME_BP],
-var->delta);
}
break;
case R_ANAL_VAR_KIND_REG: {
RRegItem *i = r_reg_index_get (anal->reg, var->delta);
if (!i) {
eprintf ("Register not found");
break;
}
anal->cb_printf ("{\"name\":\"%s\","
"\"kind\":\"reg\",\"type\":\"%s\",\"ref\":\"%s\"}",
var->name, var->type, i->name, anal->reg->name[var->delta]);
}
break;
case R_ANAL_VAR_KIND_SPV:
if (var->delta < fcn->maxstack) {
anal->cb_printf ("{\"name\":\"%s\","
"\"kind\":\"arg\",\"type\":\"%s\",\"ref\":"
"{\"base\":\"%s\", \"offset\":%"PFMT64d "}}",
var->name, var->type, anal->reg->name[R_REG_NAME_SP],
var->delta);
} else {
anal->cb_printf ("{\"name\":\"%s\","
"\"kind\":\"var\",\"type\":\"%s\",\"ref\":"
"{\"base\":\"%s\", \"offset\":-%"PFMT64d "}}",
var->name, var->type, anal->reg->name[R_REG_NAME_SP],
var->delta);
}
break;
}
if (iter->n) {
anal->cb_printf (",");
}
break;
default:
switch (kind) {
case R_ANAL_VAR_KIND_BPV:
if (var->delta > 0) {
anal->cb_printf ("arg %s %s @ %s+0x%x\n",
var->type, var->name,
anal->reg->name[R_REG_NAME_BP],
var->delta);
} else {
anal->cb_printf ("var %s %s @ %s-0x%x\n",
var->type, var->name,
anal->reg->name[R_REG_NAME_BP],
-var->delta);
}
break;
case R_ANAL_VAR_KIND_REG: {
RRegItem *i = r_reg_index_get (anal->reg, var->delta);
if (!i) {
eprintf ("Register not found");
break;
}
anal->cb_printf ("reg %s %s @ %s\n",
var->type, var->name, i->name);
}
break;
case R_ANAL_VAR_KIND_SPV:
if (var->delta < fcn->maxstack) {
anal->cb_printf ("var %s %s @ %s+0x%x\n",
var->type, var->name,
anal->reg->name[R_REG_NAME_SP],
var->delta);
} else {
anal->cb_printf ("arg %s %s @ %s+0x%x\n",
var->type, var->name,
anal->reg->name[R_REG_NAME_SP],
var->delta);
}
break;
}
}
}
if (mode == 'j') {
anal->cb_printf ("]\n");
}
r_list_free (list);
}
| Svenito/radare2 | libr/anal/var.c | C | lgpl-3.0 | 22,317 |
/*!
*
*
* \brief Very basic math abstraction layer.
*
* \par
* This file serves as a minimal abstraction layer.
* Inclusion of this file makes some frequently used
* functions, constants, and header file inclusions
* OS-, compiler-, and version-independent.
*
*
*
*
* \author -
* \date -
*
*
* \par Copyright 1995-2017 Shark Development Team
*
* <BR><HR>
* This file is part of Shark.
* <http://shark-ml.org/>
*
* Shark 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.
*
* Shark 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 Shark. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef SHARK_CORE_MATH_H
#define SHARK_CORE_MATH_H
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/sign.hpp>
#include <boost/utility/enable_if.hpp>
#include <limits>
#include <cmath>
#include <type_traits>
#include <shark/Core/Exception.h>
namespace shark {
// define doxygen group for shark global functions, var, etc. (should only appear once in all shark files)
/**
* \defgroup shark_globals shark_globals
*
* \brief Several mathematical, linear-algebra, or other functions within Shark are not part of any particular class. They are collected here in the doxygen group "shark_globals"
*
* @{
*
*/
/**
* \brief Constant for sqrt( 2 * pi ).
*/
static const double SQRT_2_PI = boost::math::constants::root_two_pi<double>();
// static const double SQRT_PI = boost::math::constants::root_pi<double>();
/// Maximum allowed input value for exp.
template<class T>
T maxExpInput(){
return boost::math::constants::ln_two<T>()*std::numeric_limits<T>::max_exponent;
}
/// Minimum value for exp(x) allowed so that it is not 0.
template<class T>
T minExpInput(){
return boost::math::constants::ln_two<T>()*std::numeric_limits<T>::min_exponent;
}
/// Calculates x^2.
template <class T>
inline typename boost::enable_if<std::is_arithmetic<T>, T>::type sqr( const T & x) {
return x * x;
}
/// Calculates x^3.
template <class T> inline T cube( const T & x) {
return x * x * x;
}
///\brief Logistic function/logistic function.
///
///Calculates the sigmoid function 1/(1+exp(-x)). The type must be arithmetic. For example
///float,double,long double, int,... but no custom Type.
template<class T>
typename boost::enable_if<std::is_arithmetic<T>, T>::type sigmoid(T x){
if(x < minExpInput<T>()) {
return 1;
}
if(x > maxExpInput<T>()) {
return 0;
}
return 1. / (1.+ std::exp(-x));
}
///\brief Thresholded exp function, over- and underflow safe.
///
///Replaces the value of exp(x) for numerical reasons by the a threshold value if it gets too large.
///Use it only, if there is no other way to get the function stable!
///
///@param x the exponent
template<class T>
T safeExp(T x ){
if(x > maxExpInput<T>()){
//std::cout<<"warning, x too high"<<std::endl;
return 0.9 * std::numeric_limits<long double>::max();
}
//Allow Koenig Lookup
using std::exp;
return exp(x);
}
///\brief Thresholded log function, over- and underflow safe.
///
///Replaces the value of log(x) for numerical reasons by the a threshold value if it gets too low.
///Use it only, if there is no other way to get the function stable!
///@param x the exponent
template<class T>
T safeLog(T x)
{
if(x> -std::numeric_limits<T>::epsilon() && x < std::numeric_limits<T>::epsilon()){
//std::cout<<"warning, x too low"<<std::endl;
return boost::math::sign(x)*std::numeric_limits<T>::min_exponent;
}
//Allow Koenig Lookup
using std::log;
return log(x);
};
///\brief Numerically stable version of the function log(1+exp(x)).
///
///Numerically stable version of the function log(1+exp(x)).
///This function is the integral of the famous sigmoid function.
///The type must be arithmetic. For example
///float,double,long double, int,... but no custom Type.
template<class T>
typename boost::enable_if<std::is_arithmetic<T>, T>::type softPlus(T x){
if(x > maxExpInput<T>()){
return x;
}
if(x < minExpInput<T>()){
return 0;
}
return std::log(1+std::exp(x));
}
///\brief Numerically stable version of the function log(1+exp(x)). calculated with float precision to save some time
///
///Numerically stable version of the function log(1+exp(x)).
///This function is the integral of the famous sigmoid function.
inline double softPlus(double x){
if(x > 15){
return x;
}
if(x < -17){
return 0;
}
return std::log(1.0f+std::exp(float(x)));
}
///brief lets x have the same sign as y.
///
///This is the famous well known copysign function from fortran.
template<class T>
T copySign(T x, T y){
using std::abs;
if(y > 0){
return abs(x);
}
return -abs(x);
}
}
/** @}*/
#endif
| Shark-ML/Shark | include/shark/Core/Math.h | C | lgpl-3.0 | 5,265 |
#ifndef FILE_POSITION_H
#define FILE_POSITION_H
#include <cstddef>
#include "finite_state_machine.h"
class FilePosition {
private:
std::size_t line, column;
bool carriage_return;
public:
FilePosition() : line(1), column(1), carriage_return(false) {}
void on_state_change(Direction direction, char symbol);
void increment_column() { this->column++; }
void increment_column(size_t column_count) { this->column += column_count; }
void increment_line();
std::size_t get_line() const { return this->line; }
std::size_t get_column() const { return this->column; }
};
#endif /* FILE_POSITION_H */
| Vvardenfell/lexer | include/file_position.h | C | lgpl-3.0 | 605 |
#ifndef AV_PYTHON_GUA_PBS_MATERIAL_FACTORY_HPP
#define AV_PYTHON_GUA_PBS_MATERIAL_FACTORY_HPP
void init_PBSMaterialFactory();
#endif //AV_PYTHON_GUA_PBS_MATERIAL_FACTORY_HPP
| jakobharlan/avango | avango-gua/python/avango/gua/renderer/PBSMaterialFactory.hpp | C++ | lgpl-3.0 | 176 |
/********************
* HTML CSS
*/
.chartWrap {
margin: 0;
padding: 0;
overflow: hidden;
}
/********************
Box shadow and border radius styling
*/
.nvtooltip.with-3d-shadow, .with-3d-shadow .nvtooltip {
-moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
-webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
box-shadow: 0 5px 10px rgba(0,0,0,.2);
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
}
/********************
* TOOLTIP CSS
*/
.nvtooltip {
position: absolute;
background-color: rgba(255,255,255,1.0);
padding: 1px;
border: 1px solid rgba(0,0,0,.2);
z-index: 10000;
font-family: Arial;
font-size: 13px;
text-align: left;
pointer-events: none;
white-space: nowrap;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/*Give tooltips that old fade in transition by
putting a "with-transitions" class on the container div.
*/
.nvtooltip.with-transitions, .with-transitions .nvtooltip {
transition: opacity 250ms linear;
-moz-transition: opacity 250ms linear;
-webkit-transition: opacity 250ms linear;
transition-delay: 250ms;
-moz-transition-delay: 250ms;
-webkit-transition-delay: 250ms;
}
.nvtooltip.x-nvtooltip,
.nvtooltip.y-nvtooltip {
padding: 8px;
}
.nvtooltip h3 {
margin: 0;
padding: 4px 14px;
line-height: 18px;
font-weight: normal;
background-color: rgba(247,247,247,0.75);
text-align: center;
border-bottom: 1px solid #ebebeb;
-webkit-border-radius: 5px 5px 0 0;
-moz-border-radius: 5px 5px 0 0;
border-radius: 5px 5px 0 0;
}
.nvtooltip p {
margin: 0;
padding: 5px 14px;
text-align: center;
}
.nvtooltip span {
display: inline-block;
margin: 2px 0;
}
.nvtooltip table {
margin: 6px;
border-spacing:0;
}
.nvtooltip table td {
padding: 2px 9px 2px 0;
vertical-align: middle;
}
.nvtooltip table td.key {
font-weight:normal;
}
.nvtooltip table td.value {
text-align: right;
font-weight: bold;
}
.nvtooltip table tr.highlight td {
padding: 1px 9px 1px 0;
border-bottom-style: solid;
border-bottom-width: 1px;
border-top-style: solid;
border-top-width: 1px;
}
.nvtooltip table td.legend-color-guide div {
width: 8px;
height: 8px;
vertical-align: middle;
}
.nvtooltip .footer {
padding: 3px;
text-align: center;
}
.nvtooltip-pending-removal {
position: absolute;
pointer-events: none;
}
/********************
* SVG CSS
*/
svg {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
/* Trying to get SVG to act like a greedy block in all browsers */
display: block;
/* width:100%;
height:100%; */
}
svg text {
font: normal 12px Arial;
}
svg .title {
font: bold 14px Arial;
}
.nvd3 .nv-background {
fill: white;
fill-opacity: 0;
/*
pointer-events: none;
*/
}
.nvd3.nv-noData {
font-size: 18px;
font-weight: bold;
}
/**********
* Brush
*/
.nv-brush .extent {
fill-opacity: .125;
shape-rendering: crispEdges;
}
/**********
* Legend
*/
.nvd3 .nv-legend .nv-series {
cursor: pointer;
}
.nvd3 .nv-legend .disabled circle {
fill-opacity: 0;
}
/**********
* Axes
*/
.nvd3 .nv-axis {
pointer-events:none;
}
.nvd3 .nv-axis path {
fill: none;
stroke: #000;
stroke-opacity: .75;
shape-rendering: crispEdges;
}
.nvd3 .nv-axis path.domain {
stroke-opacity: .75;
}
.nvd3 .nv-axis.nv-x path.domain {
stroke-opacity: 0;
}
.nvd3 .nv-axis line {
fill: none;
stroke: #e5e5e5;
shape-rendering: crispEdges;
}
.nvd3 .nv-axis .zero line,
/*this selector may not be necessary*/ .nvd3 .nv-axis line.zero {
stroke-opacity: .75;
}
.nvd3 .nv-axis .nv-axisMaxMin text {
font-weight: bold;
}
.nvd3 .x .nv-axis .nv-axisMaxMin text,
.nvd3 .x2 .nv-axis .nv-axisMaxMin text,
.nvd3 .x3 .nv-axis .nv-axisMaxMin text {
text-anchor: middle
}
/**********
* Brush
*/
.nv-brush .resize path {
fill: #eee;
stroke: #666;
}
/**********
* Bars
*/
.nvd3 .nv-bars .negative rect {
zfill: brown;
}
.nvd3 .nv-bars rect {
zfill: steelblue;
fill-opacity: .75;
transition: fill-opacity 250ms linear;
-moz-transition: fill-opacity 250ms linear;
-webkit-transition: fill-opacity 250ms linear;
}
.nvd3 .nv-bars rect.hover {
fill-opacity: 1;
}
.nvd3 .nv-bars .hover rect {
fill: lightblue;
}
.nvd3 .nv-bars text {
fill: rgba(0,0,0,0);
}
.nvd3 .nv-bars .hover text {
fill: rgba(0,0,0,1);
}
/**********
* Bars
*/
.nvd3 .nv-multibar .nv-groups rect,
.nvd3 .nv-multibarHorizontal .nv-groups rect,
.nvd3 .nv-discretebar .nv-groups rect {
stroke-opacity: 0;
transition: fill-opacity 250ms linear;
-moz-transition: fill-opacity 250ms linear;
-webkit-transition: fill-opacity 250ms linear;
}
.nvd3 .nv-multibar .nv-groups rect:hover,
.nvd3 .nv-multibarHorizontal .nv-groups rect:hover,
.nvd3 .nv-discretebar .nv-groups rect:hover {
fill-opacity: 1;
}
.nvd3 .nv-discretebar .nv-groups text,
.nvd3 .nv-multibarHorizontal .nv-groups text {
font-weight: bold;
fill: rgba(0,0,0,1);
stroke: rgba(0,0,0,0);
}
/***********
* Pie Chart
*/
.nvd3.nv-pie path {
stroke-opacity: 0;
transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear;
-moz-transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear;
-webkit-transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear;
}
.nvd3.nv-pie .nv-slice text {
stroke: #000;
stroke-width: 0;
}
.nvd3.nv-pie path {
stroke: #fff;
stroke-width: 1px;
stroke-opacity: 1;
}
.nvd3.nv-pie .hover path {
fill-opacity: .7;
}
.nvd3.nv-pie .nv-label {
pointer-events: none;
}
.nvd3.nv-pie .nv-label rect {
fill-opacity: 0;
stroke-opacity: 0;
}
/**********
* Lines
*/
.nvd3 .nv-groups path.nv-line {
fill: none;
stroke-width: 1.5px;
/*
stroke-linecap: round;
shape-rendering: geometricPrecision;
transition: stroke-width 250ms linear;
-moz-transition: stroke-width 250ms linear;
-webkit-transition: stroke-width 250ms linear;
transition-delay: 250ms
-moz-transition-delay: 250ms;
-webkit-transition-delay: 250ms;
*/
}
.nvd3 .nv-groups path.nv-line.nv-thin-line {
stroke-width: 1px;
}
.nvd3 .nv-groups path.nv-area {
stroke: none;
/*
stroke-linecap: round;
shape-rendering: geometricPrecision;
stroke-width: 2.5px;
transition: stroke-width 250ms linear;
-moz-transition: stroke-width 250ms linear;
-webkit-transition: stroke-width 250ms linear;
transition-delay: 250ms
-moz-transition-delay: 250ms;
-webkit-transition-delay: 250ms;
*/
}
.nvd3 .nv-line.hover path {
stroke-width: 6px;
}
/*
.nvd3.scatter .groups .point {
fill-opacity: 0.1;
stroke-opacity: 0.1;
}
*/
.nvd3.nv-line .nvd3.nv-scatter .nv-groups .nv-point {
fill-opacity: 0;
stroke-opacity: 0;
}
.nvd3.nv-scatter.nv-single-point .nv-groups .nv-point {
fill-opacity: .5 !important;
stroke-opacity: .5 !important;
}
.with-transitions .nvd3 .nv-groups .nv-point {
transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
-moz-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
-webkit-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
}
.nvd3.nv-scatter .nv-groups .nv-point.hover,
.nvd3 .nv-groups .nv-point.hover {
stroke-width: 7px;
fill-opacity: .95 !important;
stroke-opacity: .95 !important;
}
.nvd3 .nv-point-paths path {
stroke: #aaa;
stroke-opacity: 0;
fill: #eee;
fill-opacity: 0;
}
.nvd3 .nv-indexLine {
cursor: ew-resize;
}
/**********
* Distribution
*/
.nvd3 .nv-distribution {
pointer-events: none;
}
/**********
* Scatter
*/
/* **Attempting to remove this for useVoronoi(false), need to see if it's required anywhere
.nvd3 .nv-groups .nv-point {
pointer-events: none;
}
*/
.nvd3 .nv-groups .nv-point.hover {
stroke-width: 20px;
stroke-opacity: .5;
}
.nvd3 .nv-scatter .nv-point.hover {
fill-opacity: 1;
}
/*
.nv-group.hover .nv-point {
fill-opacity: 1;
}
*/
/**********
* Stacked Area
*/
.nvd3.nv-stackedarea path.nv-area {
fill-opacity: .7;
/*
stroke-opacity: .65;
fill-opacity: 1;
*/
stroke-opacity: 0;
transition: fill-opacity 250ms linear, stroke-opacity 250ms linear;
-moz-transition: fill-opacity 250ms linear, stroke-opacity 250ms linear;
-webkit-transition: fill-opacity 250ms linear, stroke-opacity 250ms linear;
/*
transition-delay: 500ms;
-moz-transition-delay: 500ms;
-webkit-transition-delay: 500ms;
*/
}
.nvd3.nv-stackedarea path.nv-area.hover {
fill-opacity: .9;
/*
stroke-opacity: .85;
*/
}
/*
.d3stackedarea .groups path {
stroke-opacity: 0;
}
*/
.nvd3.nv-stackedarea .nv-groups .nv-point {
stroke-opacity: 0;
fill-opacity: 0;
}
/*
.nvd3.nv-stackedarea .nv-groups .nv-point.hover {
stroke-width: 20px;
stroke-opacity: .75;
fill-opacity: 1;
}*/
/**********
* Line Plus Bar
*/
.nvd3.nv-linePlusBar .nv-bar rect {
fill-opacity: .75;
}
.nvd3.nv-linePlusBar .nv-bar rect:hover {
fill-opacity: 1;
}
/**********
* Bullet
*/
.nvd3.nv-bullet { font: 10px sans-serif; }
.nvd3.nv-bullet .nv-measure { fill-opacity: .8; }
.nvd3.nv-bullet .nv-measure:hover { fill-opacity: 1; }
.nvd3.nv-bullet .nv-marker { stroke: #000; stroke-width: 2px; }
.nvd3.nv-bullet .nv-markerTriangle { stroke: #000; fill: #fff; stroke-width: 1.5px; }
.nvd3.nv-bullet .nv-tick line { stroke: #666; stroke-width: .5px; }
.nvd3.nv-bullet .nv-range.nv-s0 { fill: #eee; }
.nvd3.nv-bullet .nv-range.nv-s1 { fill: #ddd; }
.nvd3.nv-bullet .nv-range.nv-s2 { fill: #ccc; }
.nvd3.nv-bullet .nv-title { font-size: 14px; font-weight: bold; }
.nvd3.nv-bullet .nv-subtitle { fill: #999; }
.nvd3.nv-bullet .nv-range {
fill: #bababa;
fill-opacity: .4;
}
.nvd3.nv-bullet .nv-range:hover {
fill-opacity: .7;
}
/**********
* Sparkline
*/
.nvd3.nv-sparkline path {
fill: none;
}
.nvd3.nv-sparklineplus g.nv-hoverValue {
pointer-events: none;
}
.nvd3.nv-sparklineplus .nv-hoverValue line {
stroke: #333;
stroke-width: 1.5px;
}
.nvd3.nv-sparklineplus,
.nvd3.nv-sparklineplus g {
pointer-events: all;
}
.nvd3 .nv-hoverArea {
fill-opacity: 0;
stroke-opacity: 0;
}
.nvd3.nv-sparklineplus .nv-xValue,
.nvd3.nv-sparklineplus .nv-yValue {
/*
stroke: #666;
*/
stroke-width: 0;
font-size: .9em;
font-weight: normal;
}
.nvd3.nv-sparklineplus .nv-yValue {
stroke: #f66;
}
.nvd3.nv-sparklineplus .nv-maxValue {
stroke: #2ca02c;
fill: #2ca02c;
}
.nvd3.nv-sparklineplus .nv-minValue {
stroke: #d62728;
fill: #d62728;
}
.nvd3.nv-sparklineplus .nv-currentValue {
/*
stroke: #444;
fill: #000;
*/
font-weight: bold;
font-size: 1.1em;
}
/**********
* historical stock
*/
.nvd3.nv-ohlcBar .nv-ticks .nv-tick {
stroke-width: 2px;
}
.nvd3.nv-ohlcBar .nv-ticks .nv-tick.hover {
stroke-width: 4px;
}
.nvd3.nv-ohlcBar .nv-ticks .nv-tick.positive {
stroke: #2ca02c;
}
.nvd3.nv-ohlcBar .nv-ticks .nv-tick.negative {
stroke: #d62728;
}
.nvd3.nv-historicalStockChart .nv-axis .nv-axislabel {
font-weight: bold;
}
.nvd3.nv-historicalStockChart .nv-dragTarget {
fill-opacity: 0;
stroke: none;
cursor: move;
}
.nvd3 .nv-brush .extent {
/*
cursor: ew-resize !important;
*/
fill-opacity: 0 !important;
}
.nvd3 .nv-brushBackground rect {
stroke: #000;
stroke-width: .4;
fill: #fff;
fill-opacity: .7;
}
/**********
* Indented Tree
*/
/**
* TODO: the following 3 selectors are based on classes used in the example. I should either make them standard and leave them here, or move to a CSS file not included in the library
*/
.nvd3.nv-indentedtree .name {
margin-left: 5px;
}
.nvd3.nv-indentedtree .clickable {
color: #08C;
cursor: pointer;
}
.nvd3.nv-indentedtree span.clickable:hover {
color: #005580;
text-decoration: underline;
}
.nvd3.nv-indentedtree .nv-childrenCount {
display: inline-block;
margin-left: 5px;
}
.nvd3.nv-indentedtree .nv-treeicon {
cursor: pointer;
/*
cursor: n-resize;
*/
}
.nvd3.nv-indentedtree .nv-treeicon.nv-folded {
cursor: pointer;
/*
cursor: s-resize;
*/
}
/**********
* Parallel Coordinates
*/
.nvd3 .background path {
fill: none;
stroke: #ccc;
stroke-opacity: .4;
shape-rendering: crispEdges;
}
.nvd3 .foreground path {
fill: none;
stroke: steelblue;
stroke-opacity: .7;
}
.nvd3 .brush .extent {
fill-opacity: .3;
stroke: #fff;
shape-rendering: crispEdges;
}
.nvd3 .axis line, .axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.nvd3 .axis text {
text-shadow: 0 1px 0 #fff;
}
/****
Interactive Layer
*/
.nvd3 .nv-interactiveGuideLine {
pointer-events:none;
}
.nvd3 line.nv-guideline {
stroke: #ccc;
} | zengzhaozheng/ankush | ankush/src/main/webapp/resources/libcss3.0/nv.d3.css | CSS | lgpl-3.0 | 12,841 |
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define max(x,y) ( x>y?x:y )
#define min(x,y) ( x<y?x:y )
void Roe_HLL_solver(double *V_mk, double *F, double gamma, double P_L, double RHO_L, double U_L, double V_L, double P_R, double RHO_R, double U_R, double V_R, double *lambda_max, double delta)
{
// double const Q_user = 2.0;
double C_L, C_R;
C_L = sqrt(gamma*P_L/RHO_L);
C_R = sqrt(gamma*P_R/RHO_R);
double z = 0.5 * (gamma-1.0) / gamma;
/*
double Q, P_pvrs, P_max, P_min, RHO_bar, C_bar;
P_min = min(P_L,P_R);
P_max = max(P_L,P_R);
Q = P_max/P_min;
RHO_bar = 0.5*(RHO_L+RHO_R);
C_bar = 0.5*(C_L+C_R);
P_pvrs = 0.5*(P_L+P_R)+0.5*(U_L-U_R)*RHO_bar*C_bar;
double A_L,A_R,B_L,B_R;
A_L = 2.0/(gamma+1.0)/RHO_L;
A_R = 2.0/(gamma+1.0)/RHO_R;
B_L = (gamma-1)/(gamma+1)*P_L;
B_R = (gamma-1)/(gamma+1)*P_R;
double P_star, U_star, U_star_L, U_star_R, RHO_star_L, RHO_star_R, C_star_L, C_star_R, P_0, g_L_0, g_R_0, lambda_L_1, lambda_R_1, lambda_L_3, lambda_R_3;
if(Q<Q_user&&P_min<P_pvrs&&P_pvrs<P_max) //PVRS
{
P_star = max(0,P_pvrs);
U_star = 0.5*(U_L+U_R)+0.5*(P_L-P_R)/(RHO_bar*C_bar);
RHO_star_L = RHO_L + (U_L-U_star)*RHO_bar/C_bar;
RHO_star_R = RHO_R + (U_star - U_R)*RHO_bar/C_bar;
C_star_L = sqrt(gamma*P_star/RHO_star_L);
C_star_R = sqrt(gamma*P_star/RHO_star_R);
U_star_L = U_star;
U_star_R = U_star;
}
else if(P_pvrs<P_min) //TRRS
{
P_star = pow((C_L + C_R - (gamma-1.0)/2.0*(U_R - U_L))/(C_L/pow(P_L,z) + C_R/pow(P_R,z)), 1.0/z);
C_star_L = C_L * pow(P_star/P_L, z);
U_star_L = U_L + 2.0/(gamma - 1.0)*(C_L - C_star_L);
C_star_R = C_R * pow(P_star/P_R, z);
U_star_R = U_R + 2.0/(gamma - 1.0)*(C_star_R - C_R);
}
else //TSRS
{
P_0 = max(0,P_pvrs);
g_L_0 = sqrt(A_L/(P_0+B_L));
g_R_0 = sqrt(A_R/(P_0+B_R));
P_star = (g_L_0*P_L+g_R_0*P_R-(U_R-U_L))/(g_L_0+g_R_0);
U_star = 0.5*(U_R+U_L)+0.5*((P_star-P_R)*g_R_0-(P_star-P_L)*g_L_0);
RHO_star_L = RHO_L*(P_star/P_L+(gamma-1.0)/(gamma+1.0))/((gamma-1.0)*P_star/(gamma+1.0)/P_L+1.0);
RHO_star_R = RHO_R*(P_star/P_R+(gamma-1.0)/(gamma+1.0))/((gamma-1.0)*P_star/(gamma+1.0)/P_R+1.0);
C_star_L = sqrt(gamma*P_star/RHO_star_L);
C_star_R = sqrt(gamma*P_star/RHO_star_R);
U_star_L = U_star;
U_star_R = U_star;
}
lambda_L_1 = U_L - C_L;
lambda_R_1 = U_star_L - C_star_L;
lambda_L_3 = U_star_R + C_star_R;
lambda_R_3 = U_R + C_R;
*/
double H_L, H_R;
H_L = gamma/(gamma-1.0)*P_L/RHO_L + 0.5*(U_L*U_L);
H_R = gamma/(gamma-1.0)*P_R/RHO_R + 0.5*(U_R*U_R);
double E_L, E_R;
E_L = 1.0/(gamma-1.0)*P_L/RHO_L + 0.5*(U_L*U_L);
E_R = 1.0/(gamma-1.0)*P_R/RHO_R + 0.5*(U_R*U_R);
double U[3];
U[0] = RHO_L;
U[1] = RHO_L*U_L;
U[2] = RHO_L*E_L;
double RHO_S, U_S, H_S, C_S;
RHO_S = sqrt(RHO_L*RHO_R);
U_S = (U_L*sqrt(RHO_L)+U_R*sqrt(RHO_R)) / (sqrt(RHO_L)+sqrt(RHO_R));
H_S = (H_L*sqrt(RHO_L)+H_R*sqrt(RHO_R)) / (sqrt(RHO_L)+sqrt(RHO_R));
C_S = sqrt((gamma-1.0)*(H_S-0.5*U_S*U_S));
double R[3][3];
double lambda[3], W[3];
R[0][0] = 1.0;
R[0][1] = 1.0;
R[0][2] = 1.0;
R[1][0] = U_S - C_S;
R[1][1] = U_S;
R[1][2] = U_S + C_S;
R[2][0] = H_S - U_S*C_S;
R[2][1] = 0.5*(U_S*U_S);
R[2][2] = H_S + U_S*C_S;
int i, j;
W[0] = 0.5*((P_R-P_L)-RHO_S*C_S*(U_R-U_L))/(C_S*C_S);
W[1] = (RHO_R-RHO_L)-(P_R-P_L)/(C_S*C_S);
W[2] = 0.5*((P_R-P_L)+RHO_S*C_S*(U_R-U_L))/(C_S*C_S);
lambda[0] = U_S - C_S;
lambda[1] = U_S;
lambda[2] = U_S + C_S;
*lambda_max = fabs(U_S) + C_S;
/*
if(lambda_L_1<0&&lambda_R_1>0)
{
for(i = 0; i < 3; i++)
{
U[i] += (lambda_R_1-(U_S-C_S))/(lambda_R_1-lambda_L_1)*W[0]*R[i][0];
}
}
else if(lambda_L_3<0&&lambda_R_3>0)
{
U[0] = RHO_R;
U[1] = RHO_R*U_R;
U[2] = RHO_R*E_R;
for(i = 0; i < 3; i++)
{
U[i] += -((U_S+C_S)-lambda_L_3)/(lambda_R_3-lambda_L_3)*W[2]*R[i][2];
}
}
else
{
*/ for(j = 0; j < 3; j++)
{
if(lambda[j]<=0)
{
for(i = 0; i < 3 ; i++)
{
U[i] += W[j]*R[i][j];
}
}
}
// }
F[0] = U[0];
F[1] = U[1]/U[0];
F[2] = (U[2]/U[0] - 0.5*F[1]*F[1])*(gamma-1.0)*F[0];
double S_L, S_R;
S_L=min(U_S-C_S,U_L-C_L);
S_R=max(U_S+C_S,U_R+C_R);
S_L=min(0,S_L);
S_R=max(0,S_R);
*V_mk=(RHO_R*(S_R-U_R)*V_R-RHO_L*(S_L-U_L)*V_L)/(RHO_R*(S_R-U_R)-RHO_L*(S_L-U_L));
}
| ximlel/Multiphase_Flow_Program | src/Riemann_solver/Roe_HLL_solver.c | C | lgpl-3.0 | 4,359 |
//
// CacheDependencyCas.cs
// - CAS unit tests for System.Web.Caching.CacheDependency
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Web;
using System.Web.Caching;
namespace MonoCasTests.System.Web.Caching {
[TestFixture]
[Category ("CAS")]
public class CacheDependencyCas : AspNetHostingMinimal {
private string tempFile;
[TestFixtureSetUp]
public void FixtureSetUp ()
{
// that requires both FileIOPermission and EnvironmentPermission
// so we do it before setting the stack with PermitOnly and Deny
tempFile = Path.GetTempFileName ();
}
// note: CacheDependency still requires some file access
[FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
#if ONLY_1_1
[SecurityPermission (SecurityAction.Assert, UnmanagedCode = true)]
#endif
private object FileIOPermissionCreateControl (SecurityAction action, AspNetHostingPermissionLevel level)
{
return CreateControlStringCtor (action, level);
}
public override object CreateControl (SecurityAction action, AspNetHostingPermissionLevel level)
{
if ((level != AspNetHostingPermissionLevel.None) && (action == SecurityAction.PermitOnly)) {
try {
return FileIOPermissionCreateControl (action, level);
}
catch (TargetInvocationException tie) {
#if ONLY_1_1
// hide this error (occurs with ms 1.x)
if ((tie.InnerException is NullReferenceException) &&
(level == AspNetHostingPermissionLevel.Unrestricted)) {
return String.Empty;
}
#endif
throw tie;
}
}
else
return CreateControlStringCtor (action, level);
}
private object CreateControlStringCtor (SecurityAction action, AspNetHostingPermissionLevel level)
{
// not public empty (default) ctor - at least not before 2.0
ConstructorInfo ci = this.Type.GetConstructor (new Type[1] { typeof (string) });
Assert.IsNotNull (ci, ".ctor(string)");
return ci.Invoke (new object[1] { tempFile });
}
public override Type Type {
get { return typeof (CacheDependency); }
}
}
}
| edwinspire/VSharp | class/System.Web/Test/System.Web.Caching/CacheDependencyCas.cs | C# | lgpl-3.0 | 3,300 |
//
// Authors:
// David Straw
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2011 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using NUnit.Framework;
using WebServiceMoonlightTest.ServiceReference1;
namespace MonoTests.System.ServiceModel.Dispatcher
{
[TestFixture]
public class Bug652331Test
{
[Test]
public void Bug652331_2 () // test in one of the comment
{
// Init service
ServiceHost serviceHost = new ServiceHost (typeof (Service1), new Uri ("http://localhost:37564/Service1"));
serviceHost.AddServiceEndpoint (typeof (IService1), new BasicHttpBinding (), string.Empty);
// Enable metadata exchange (WSDL publishing)
var mexBehavior = new ServiceMetadataBehavior ();
mexBehavior.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add (mexBehavior);
serviceHost.AddServiceEndpoint (typeof (IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding (), "mex");
serviceHost.Open ();
try {
// client
var binding = new BasicHttpBinding ();
var remoteAddress = new EndpointAddress ("http://localhost:37564/Service1");
var client = new Service1Client (binding, remoteAddress);
var wait = new ManualResetEvent (false);
client.GetDataCompleted += delegate (object o, GetDataCompletedEventArgs e) {
if (e.Error != null)
throw e.Error;
Assert.AreEqual ("A", ((DataType1) e.Result).Id, "#1");
wait.Set ();
};
client.GetDataAsync ();
if (!wait.WaitOne (TimeSpan.FromSeconds (10)))
Assert.Fail ("timeout");
} finally {
serviceHost.Close ();
}
}
public class Service1 : IService1
{
public object GetData ()
{
return new DataType1 { Id = "A" };
}
Func<object> d;
public IAsyncResult BeginGetData (AsyncCallback callback, object state)
{
if (d == null)
d = new Func<object> (GetData);
return d.BeginInvoke (callback, state);
}
public object EndGetData (IAsyncResult result)
{
return d.EndInvoke (result);
}
}
}
}
// below are part of autogenerated code in comment #1 on bug #652331.
namespace WebServiceMoonlightTest.ServiceReference1 {
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="DataType1", Namespace="http://mynamespace")]
public partial class DataType1 : object, System.ComponentModel.INotifyPropertyChanged {
private string IdField;
[System.Runtime.Serialization.DataMemberAttribute()]
public string Id {
get {
return this.IdField;
}
set {
if ((object.ReferenceEquals(this.IdField, value) != true)) {
this.IdField = value;
this.RaisePropertyChanged("Id");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://mynamespace", ConfigurationName="ServiceReference1.IService1")]
[ServiceKnownType (typeof (DataType1))]
public interface IService1 {
[System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://mynamespace/IService1/GetData", ReplyAction="http://mynamespace/IService1/GetDataResponse")]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(WebServiceMoonlightTest.ServiceReference1.DataType1))]
System.IAsyncResult BeginGetData(System.AsyncCallback callback, object asyncState);
object EndGetData(System.IAsyncResult result);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IService1Channel : WebServiceMoonlightTest.ServiceReference1.IService1, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class GetDataCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
public GetDataCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
public object Result {
get {
base.RaiseExceptionIfNecessary();
return ((object)(this.results[0]));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class Service1Client : System.ServiceModel.ClientBase<WebServiceMoonlightTest.ServiceReference1.IService1>, WebServiceMoonlightTest.ServiceReference1.IService1 {
private BeginOperationDelegate onBeginGetDataDelegate;
private EndOperationDelegate onEndGetDataDelegate;
private System.Threading.SendOrPostCallback onGetDataCompletedDelegate;
private BeginOperationDelegate onBeginOpenDelegate;
private EndOperationDelegate onEndOpenDelegate;
private System.Threading.SendOrPostCallback onOpenCompletedDelegate;
private BeginOperationDelegate onBeginCloseDelegate;
private EndOperationDelegate onEndCloseDelegate;
private System.Threading.SendOrPostCallback onCloseCompletedDelegate;
public Service1Client() {
}
public Service1Client(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public Service1Client(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public Service1Client(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public Service1Client(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
/*
public System.Net.CookieContainer CookieContainer {
get {
System.ServiceModel.Channels.IHttpCookieContainerManager httpCookieContainerManager = this.InnerChannel.GetProperty<System.ServiceModel.Channels.IHttpCookieContainerManager>();
if ((httpCookieContainerManager != null)) {
return httpCookieContainerManager.CookieContainer;
}
else {
return null;
}
}
set {
System.ServiceModel.Channels.IHttpCookieContainerManager httpCookieContainerManager = this.InnerChannel.GetProperty<System.ServiceModel.Channels.IHttpCookieContainerManager>();
if ((httpCookieContainerManager != null)) {
httpCookieContainerManager.CookieContainer = value;
}
else {
throw new System.InvalidOperationException("Unable to set the CookieContainer. Please make sure the binding contains an HttpC" +
"ookieContainerBindingElement.");
}
}
}
*/
public event System.EventHandler<GetDataCompletedEventArgs> GetDataCompleted;
public event System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs> OpenCompleted;
public event System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs> CloseCompleted;
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.IAsyncResult WebServiceMoonlightTest.ServiceReference1.IService1.BeginGetData(System.AsyncCallback callback, object asyncState) {
return base.Channel.BeginGetData(callback, asyncState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
object WebServiceMoonlightTest.ServiceReference1.IService1.EndGetData(System.IAsyncResult result) {
return base.Channel.EndGetData(result);
}
private System.IAsyncResult OnBeginGetData(object[] inValues, System.AsyncCallback callback, object asyncState) {
return ((WebServiceMoonlightTest.ServiceReference1.IService1)(this)).BeginGetData(callback, asyncState);
}
private object[] OnEndGetData(System.IAsyncResult result) {
object retVal = ((WebServiceMoonlightTest.ServiceReference1.IService1)(this)).EndGetData(result);
return new object[] {
retVal};
}
private void OnGetDataCompleted(object state) {
if ((this.GetDataCompleted != null)) {
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.GetDataCompleted(this, new GetDataCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
}
}
public void GetDataAsync() {
this.GetDataAsync(null);
}
public void GetDataAsync(object userState) {
if ((this.onBeginGetDataDelegate == null)) {
this.onBeginGetDataDelegate = new BeginOperationDelegate(this.OnBeginGetData);
}
if ((this.onEndGetDataDelegate == null)) {
this.onEndGetDataDelegate = new EndOperationDelegate(this.OnEndGetData);
}
if ((this.onGetDataCompletedDelegate == null)) {
this.onGetDataCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnGetDataCompleted);
}
base.InvokeAsync(this.onBeginGetDataDelegate, null, this.onEndGetDataDelegate, this.onGetDataCompletedDelegate, userState);
}
private System.IAsyncResult OnBeginOpen(object[] inValues, System.AsyncCallback callback, object asyncState) {
return ((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(callback, asyncState);
}
private object[] OnEndOpen(System.IAsyncResult result) {
((System.ServiceModel.ICommunicationObject)(this)).EndOpen(result);
return null;
}
private void OnOpenCompleted(object state) {
if ((this.OpenCompleted != null)) {
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.OpenCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
}
}
public void OpenAsync() {
this.OpenAsync(null);
}
public void OpenAsync(object userState) {
if ((this.onBeginOpenDelegate == null)) {
this.onBeginOpenDelegate = new BeginOperationDelegate(this.OnBeginOpen);
}
if ((this.onEndOpenDelegate == null)) {
this.onEndOpenDelegate = new EndOperationDelegate(this.OnEndOpen);
}
if ((this.onOpenCompletedDelegate == null)) {
this.onOpenCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnOpenCompleted);
}
base.InvokeAsync(this.onBeginOpenDelegate, null, this.onEndOpenDelegate, this.onOpenCompletedDelegate, userState);
}
private System.IAsyncResult OnBeginClose(object[] inValues, System.AsyncCallback callback, object asyncState) {
return ((System.ServiceModel.ICommunicationObject)(this)).BeginClose(callback, asyncState);
}
private object[] OnEndClose(System.IAsyncResult result) {
((System.ServiceModel.ICommunicationObject)(this)).EndClose(result);
return null;
}
private void OnCloseCompleted(object state) {
if ((this.CloseCompleted != null)) {
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.CloseCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
}
}
public void CloseAsync() {
this.CloseAsync(null);
}
public void CloseAsync(object userState) {
if ((this.onBeginCloseDelegate == null)) {
this.onBeginCloseDelegate = new BeginOperationDelegate(this.OnBeginClose);
}
if ((this.onEndCloseDelegate == null)) {
this.onEndCloseDelegate = new EndOperationDelegate(this.OnEndClose);
}
if ((this.onCloseCompletedDelegate == null)) {
this.onCloseCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnCloseCompleted);
}
base.InvokeAsync(this.onBeginCloseDelegate, null, this.onEndCloseDelegate, this.onCloseCompletedDelegate, userState);
}
/*
protected override WebServiceMoonlightTest.ServiceReference1.IService1 CreateChannel() {
return new Service1ClientChannel(this);
}
private class Service1ClientChannel : ChannelBase<WebServiceMoonlightTest.ServiceReference1.IService1>, WebServiceMoonlightTest.ServiceReference1.IService1 {
public Service1ClientChannel(System.ServiceModel.ClientBase<WebServiceMoonlightTest.ServiceReference1.IService1> client) :
base(client) {
}
public System.IAsyncResult BeginGetData(System.AsyncCallback callback, object asyncState) {
object[] _args = new object[0];
System.IAsyncResult _result = base.BeginInvoke("GetData", _args, callback, asyncState);
return _result;
}
public object EndGetData(System.IAsyncResult result) {
object[] _args = new object[0];
object _result = ((object)(base.EndInvoke("GetData", _args, result)));
return _result;
}
}
*/
}
}
| edwinspire/VSharp | class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/Bug652331Test.cs | C# | lgpl-3.0 | 16,194 |
import numpy as np
try:
import scipy.optimize as opt
except ImportError:
pass
from ase.optimize.optimize import Optimizer
class Converged(Exception):
pass
class OptimizerConvergenceError(Exception):
pass
class SciPyOptimizer(Optimizer):
"""General interface for SciPy optimizers
Only the call to the optimizer is still needed
"""
def __init__(self, atoms, logfile='-', trajectory=None,
callback_always=False, alpha=70.0, master=None):
"""Initialize object
Parameters:
atoms: Atoms object
The Atoms object to relax.
trajectory: string
Pickle file used to store trajectory of atomic movement.
logfile: file object or str
If *logfile* is a string, a file with that name will be opened.
Use '-' for stdout.
callback_always: book
Should the callback be run after each force call (also in the
linesearch)
alpha: float
Initial guess for the Hessian (curvature of energy surface). A
conservative value of 70.0 is the default, but number of needed
steps to converge might be less if a lower value is used. However,
a lower value also means risk of instability.
master: boolean
Defaults to None, which causes only rank 0 to save files. If
set to true, this rank will save files.
"""
restart = None
Optimizer.__init__(self, atoms, restart, logfile, trajectory, master)
self.force_calls = 0
self.callback_always = callback_always
self.H0 = alpha
def x0(self):
"""Return x0 in a way SciPy can use
This class is mostly usable for subclasses wanting to redefine the
parameters (and the objective function)"""
return self.atoms.get_positions().reshape(-1)
def f(self, x):
"""Objective function for use of the optimizers"""
self.atoms.set_positions(x.reshape(-1, 3))
# Scale the problem as SciPy uses I as initial Hessian.
return self.atoms.get_potential_energy() / self.H0
def fprime(self, x):
"""Gradient of the objective function for use of the optimizers"""
self.atoms.set_positions(x.reshape(-1, 3))
self.force_calls += 1
if self.callback_always:
self.callback(x)
# Remember that forces are minus the gradient!
# Scale the problem as SciPy uses I as initial Hessian.
return - self.atoms.get_forces().reshape(-1) / self.H0
def callback(self, x):
"""Callback function to be run after each iteration by SciPy
This should also be called once before optimization starts, as SciPy
optimizers only calls it after each iteration, while ase optimizers
call something similar before as well.
"""
f = self.atoms.get_forces()
self.log(f)
self.call_observers()
if self.converged(f):
raise Converged
self.nsteps += 1
def run(self, fmax=0.05, steps=100000000):
self.fmax = fmax
# As SciPy does not log the zeroth iteration, we do that manually
self.callback(None)
try:
# Scale the problem as SciPy uses I as initial Hessian.
self.call_fmin(fmax / self.H0, steps)
except Converged:
pass
def dump(self, data):
pass
def load(self):
pass
def call_fmin(self, fmax, steps):
raise NotImplementedError
class SciPyFminCG(SciPyOptimizer):
"""Non-linear (Polak-Ribiere) conjugate gradient algorithm"""
def call_fmin(self, fmax, steps):
output = opt.fmin_cg(self.f,
self.x0(),
fprime=self.fprime,
#args=(),
gtol=fmax * 0.1, #Should never be reached
norm=np.inf,
#epsilon=
maxiter=steps,
full_output=1,
disp=0,
#retall=0,
callback=self.callback
)
warnflag = output[-1]
if warnflag == 2:
raise OptimizerConvergenceError('Warning: Desired error not necessarily achieved ' \
'due to precision loss')
class SciPyFminBFGS(SciPyOptimizer):
"""Quasi-Newton method (Broydon-Fletcher-Goldfarb-Shanno)"""
def call_fmin(self, fmax, steps):
output = opt.fmin_bfgs(self.f,
self.x0(),
fprime=self.fprime,
#args=(),
gtol=fmax * 0.1, #Should never be reached
norm=np.inf,
#epsilon=1.4901161193847656e-08,
maxiter=steps,
full_output=1,
disp=0,
#retall=0,
callback=self.callback
)
warnflag = output[-1]
if warnflag == 2:
raise OptimizerConvergenceError('Warning: Desired error not necessarily achieved' \
'due to precision loss')
class SciPyGradientlessOptimizer(Optimizer):
"""General interface for gradient less SciPy optimizers
Only the call to the optimizer is still needed
Note: If you redefine x0() and f(), you don't even need an atoms object.
Redefining these also allows you to specify an arbitrary objective
function.
XXX: This is still a work in progress
"""
def __init__(self, atoms, logfile='-', trajectory=None,
callback_always=False, master=None):
"""Initialize object
Parameters:
atoms: Atoms object
The Atoms object to relax.
trajectory: string
Pickle file used to store trajectory of atomic movement.
logfile: file object or str
If *logfile* is a string, a file with that name will be opened.
Use '-' for stdout.
callback_always: book
Should the callback be run after each force call (also in the
linesearch)
alpha: float
Initial guess for the Hessian (curvature of energy surface). A
conservative value of 70.0 is the default, but number of needed
steps to converge might be less if a lower value is used. However,
a lower value also means risk of instability.
master: boolean
Defaults to None, which causes only rank 0 to save files. If
set to true, this rank will save files.
"""
restart = None
Optimizer.__init__(self, atoms, restart, logfile, trajectory, master)
self.function_calls = 0
self.callback_always = callback_always
def x0(self):
"""Return x0 in a way SciPy can use
This class is mostly usable for subclasses wanting to redefine the
parameters (and the objective function)"""
return self.atoms.get_positions().reshape(-1)
def f(self, x):
"""Objective function for use of the optimizers"""
self.atoms.set_positions(x.reshape(-1, 3))
self.function_calls += 1
# Scale the problem as SciPy uses I as initial Hessian.
return self.atoms.get_potential_energy()
def callback(self, x):
"""Callback function to be run after each iteration by SciPy
This should also be called once before optimization starts, as SciPy
optimizers only calls it after each iteration, while ase optimizers
call something similar before as well.
"""
# We can't assume that forces are available!
#f = self.atoms.get_forces()
#self.log(f)
self.call_observers()
#if self.converged(f):
# raise Converged
self.nsteps += 1
def run(self, ftol=0.01, xtol=0.01, steps=100000000):
self.xtol = xtol
self.ftol = ftol
# As SciPy does not log the zeroth iteration, we do that manually
self.callback(None)
try:
# Scale the problem as SciPy uses I as initial Hessian.
self.call_fmin(xtol, ftol, steps)
except Converged:
pass
def dump(self, data):
pass
def load(self):
pass
def call_fmin(self, fmax, steps):
raise NotImplementedError
class SciPyFmin(SciPyGradientlessOptimizer):
"""Nelder-Mead Simplex algorithm
Uses only function calls.
XXX: This is still a work in progress
"""
def call_fmin(self, xtol, ftol, steps):
output = opt.fmin(self.f,
self.x0(),
#args=(),
xtol=xtol,
ftol=ftol,
maxiter=steps,
#maxfun=None,
#full_output=1,
disp=0,
#retall=0,
callback=self.callback
)
class SciPyFminPowell(SciPyGradientlessOptimizer):
"""Powell's (modified) level set method
Uses only function calls.
XXX: This is still a work in progress
"""
def __init__(self, *args, **kwargs):
"""Parameters:
direc: float
How much to change x to initially. Defaults to 0.04.
"""
direc = kwargs.pop('direc', None)
SciPyGradientlessOptimizer.__init__(self, *args, **kwargs)
if direc is None:
self.direc = np.eye(len(self.x0()), dtype=float) * 0.04
else:
self.direc = np.eye(len(self.x0()), dtype=float) * direc
def call_fmin(self, xtol, ftol, steps):
output = opt.fmin_powell(self.f,
self.x0(),
#args=(),
xtol=xtol,
ftol=ftol,
maxiter=steps,
#maxfun=None,
#full_output=1,
disp=0,
#retall=0,
callback=self.callback,
direc=self.direc
)
| suttond/MODOI | ase/optimize/sciopt.py | Python | lgpl-3.0 | 10,601 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.harium.keel.core.interpolation;
/**
* Interpolation routines.
* @author Diego Catalano
*/
public final class Interpolation {
/**
* Don't let anyone instantiate this class.
*/
private Interpolation() {
}
/**
* Bicubic kernel.
* <p>
* <para>The function implements bicubic kernel W(x) as described on
* http://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm
* (coefficient <b>a</b> is set to <b>-0.5</b>).</para>
*
* @param x X value.
* @return Bicubic cooefficient.
*/
public static double BiCubicKernel(double x) {
if (x < 0) {
x = -x;
}
double biCoef = 0;
if (x <= 1) {
biCoef = (1.5 * x - 2.5) * x * x + 1;
} else if (x < 2) {
biCoef = ((-0.5 * x + 2.5) * x - 4) * x + 2;
}
return biCoef;
}
} | yuripourre/keel | src/main/java/com/harium/keel/core/interpolation/Interpolation.java | Java | lgpl-3.0 | 1,057 |
#include <bits/stdc++.h>
using namespace std;
long long st[400005],lazy[400005];
long long query(int idx,int l,int r,int a,int b){
if (r<a||l>b) return 0;
if (lazy[idx]){
st[idx] = lazy[idx];
if (r!=l){
lazy[idx*2] = lazy[idx];
lazy[idx*2+1] = lazy[idx];
}
lazy[idx] = 0;
}
if (l>=a&&r<=b){
return st[idx];
}
long long q1,q2;
q1 = query(idx*2,l,(l+r)/2,a,b);
q2 = query(idx*2+1,(l+r)/2+1,r,a,b);
return max(q1,q2);
}
void update(int idx,int l,int r,int a,int b,int val){
if (lazy[idx]){
st[idx] = lazy[idx];
if (r!=l){
lazy[idx*2] = lazy[idx];
lazy[idx*2+1] = lazy[idx];
}
lazy[idx] = 0;
}
if (r<a||l>b) return;
if (l>=a&&r<=b){
st[idx] = val;
if (r!=l){
lazy[idx*2] = val;
lazy[idx*2+1] = val;
}
return;
}
update(idx*2,l,(l+r)/2,a,b,val);
update(idx*2+1,(l+r)/2+1,r,a,b,val);
st[idx] = max(st[idx*2] , st[idx*2+1]);
}
int main(){
return 0;
}
| SaBuZa/SaBuZa-Competitive-Code | Segment_Tree/MaxLazySegmentTree.cpp | C++ | unlicense | 1,093 |
# [Ben Forbes Griffith](https://github.com/Epicurean306)

| category | value |
|-----------|-------|
| _:house:_ | Toledo, OH |
| _:dog: or :cat:_ | :dog2: :smirk_cat: :dragon: |
## Faves! :v:
| category | value |
|----------|--------|
| _sport_ | :sailboat: |
| _team_ | apathetic :godmode: |
| _drink_ | :beer: :wine_glass: :coffee: :tea: |
| _food_ | :sushi: :meat_on_bone: |
| _movie_ | Dai-bosatsu tôge |
## Esoteric :crystal_ball:
| category | value |
|----------|-------|
| _zodiac_ | classical:taurus:, sidereal:aries: |
| _spirit animal_ | :dragon_face: |
| _celeb birthday_ | Robert Oppenheimer :bomb: |
| JessyRiordan/student-roster | 2015-05/FEE/Epicurean306.md | Markdown | unlicense | 716 |
const router = require('koa-router')();
router.get('/', (ctx) => {
return ctx.render('contact')
})
module.exports = router;
| colealbon/bubblemachine | routes/contact.js | JavaScript | unlicense | 130 |
/**
* event handler to be fired if the content of input element have changed.
*/
function eventHandler() {
// write your own event handler here.
document.getElementById('info').innerHTML = 'input content changed to ' +
document.getElementById('input').value;
}
/**
* Variable which keeps track of the content of input element
* @type {string}
*/
INPUT_CONTENT = '';
/**
* Check input element periodically.
*/
polling = function() {
if (INPUT_CONTENT != document.getElementById('input').value)
eventHandler();
// update INPUT_CONTENT
INPUT_CONTENT = document.getElementById('input').value;
// polling interval: 500ms.
// you can change the polling interval to fit your need.
setTimeout(polling, 500);
};
| yegle/userpages | content/code/javascript-oninput-event-alternative/polling.js | JavaScript | unlicense | 738 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.