code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
|---|---|---|---|---|---|
'use strict';
/**
* pratice Node.js project
*
* @author Mingyi Zheng <badb0y520@gmail.com>
*/
import {expect} from 'chai';
import {request} from '../test';
describe('user', function () {
it('signup', async function () {
try {
const ret = await request.post('/api/signup', {
name: 'test1',
password: '123456789',
});
throw new Error('should throws missing parameter "email" error');
} catch (err) {
expect(err.message).to.equal('email: missing parameter "email"');
}
{
const ret = await request.post('/api/signup', {
name: 'test1',
password: '123456789',
email: 'test1@example.com',
});
console.log(ret);
expect(ret.user.name).to.equal('test1');
expect(ret.user.email).to.equal('test1@example.com');
}
{
const ret = await request.post('/api/login', {
name: 'test1',
password: '123456789',
});
console.log(ret);
expect(ret.token).to.be.a('string');
}
});
});
|
akin520/pratice-node-project
|
src/test/test_user.js
|
JavaScript
|
gpl-3.0
| 1,036
|
# nnmware(c)2012-2020
from __future__ import unicode_literals
from django import forms
from django.contrib.admin.widgets import AdminTimeWidget
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.utils.timezone import now
from django.utils.translation import gettext as _, get_language
from nnmware.apps.booking.models import Hotel, Room, Booking, Discount, DISCOUNT_SPECIAL
from nnmware.apps.booking.models import RequestAddHotel, DISCOUNT_NOREFUND, DISCOUNT_CREDITCARD, \
DISCOUNT_EARLY, DISCOUNT_LATER, DISCOUNT_PERIOD, DISCOUNT_PACKAGE, DISCOUNT_NORMAL, DISCOUNT_HOLIDAY, \
DISCOUNT_LAST_MINUTE
from nnmware.apps.money.models import Bill
from nnmware.core.fields import ReCaptchaField
from nnmware.core.forms import UserFromRequestForm
class LocaleNamedForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(LocaleNamedForm, self).__init__(*args, **kwargs)
if get_language() == 'ru':
name = self.instance.name
description = self.instance.description
else:
name = self.instance.name_en
description = self.instance.description_en
self.fields['name'] = forms.CharField(widget=forms.TextInput(attrs={'size': '25'}), initial=name)
self.fields['description'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'wide',
'rows': '5'}),
initial=description)
def save(self, commit=True):
if get_language() == 'ru':
self.instance.name = self.cleaned_data['name']
self.instance.description = self.cleaned_data['description']
else:
self.instance.name_en = self.cleaned_data['name']
self.instance.description_en = self.cleaned_data['description']
return super(LocaleNamedForm, self).save(commit=commit)
class CabinetInfoForm(UserFromRequestForm, LocaleNamedForm):
time_on = forms.CharField(widget=AdminTimeWidget(), required=False)
time_off = forms.CharField(widget=AdminTimeWidget(), required=False)
class Meta:
model = Hotel
fields = ('option', 'time_on', 'time_off')
def __init__(self, *args, **kwargs):
super(CabinetInfoForm, self).__init__(*args, **kwargs)
if get_language() == 'ru':
schema_transit = self.instance.schema_transit
paid_services = self.instance.paid_services
else:
schema_transit = self.instance.schema_transit_en
paid_services = self.instance.paid_services_en
self.fields['schema_transit'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'wide',
'rows': '5'}),
initial=schema_transit)
self.fields['paid_services'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'wide',
'rows': '5'}),
initial=paid_services)
if not self._user.is_superuser:
self.fields['name'].widget.attrs['readonly'] = True
def clean_name(self):
if self._user.is_superuser:
return self.cleaned_data['name']
if get_language() == 'ru':
return self.instance.name
else:
return self.instance.name_en
def save(self, commit=True):
if get_language() == 'ru':
self.instance.schema_transit = self.cleaned_data['schema_transit']
self.instance.paid_services = self.cleaned_data['paid_services']
else:
self.instance.schema_transit_en = self.cleaned_data['schema_transit']
self.instance.paid_services_en = self.cleaned_data['paid_services']
return super(CabinetInfoForm, self).save(commit=commit)
class CabinetRoomForm(LocaleNamedForm):
class Meta:
model = Room
fields = ('option', 'typefood', 'surface_area')
widgets = {
'typefood': forms.RadioSelect(),
}
class CabinetEditBillForm(forms.ModelForm):
class Meta:
model = Bill
fields = ('date_billed', 'status', 'description_small', 'invoice_number', 'amount')
class RequestAddHotelForm(forms.ModelForm):
city = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
address = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
name = forms.CharField(widget=forms.TextInput(attrs={'size': '35'}))
email = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
phone = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
fax = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
contact_email = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
website = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
rooms_count = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
class Meta:
model = RequestAddHotel
fields = ('city', 'address', 'name', 'email', 'phone', 'fax', 'contact_email',
'website', 'rooms_count', 'starcount')
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(RequestAddHotelForm, self).__init__(*args, **kwargs)
if not user.is_authenticated:
self.fields['recaptcha'] = ReCaptchaField(error_messages={'required': _('This field is required'),
'invalid': _('Answer is wrong')})
class UserCabinetInfoForm(UserFromRequestForm):
class Meta:
model = get_user_model()
fields = ('first_name', 'last_name', 'subscribe')
class BookingAddForm(UserFromRequestForm):
room_id = forms.CharField(max_length=30, required=False)
settlement = forms.CharField(max_length=30, required=False)
hid_method = forms.CharField(max_length=30, required=False)
class Meta:
model = Booking
fields = (
'from_date', 'to_date', 'first_name', 'middle_name', 'last_name', 'phone', 'email', 'guests', 'comment')
def clean_hid_method(self):
m = self.cleaned_data.get('hid_method')
if m:
raise forms.ValidationError(_("Spam."))
return None
def clean_phone(self):
phone = self.cleaned_data.get('phone')
if not phone:
raise forms.ValidationError(_("Phone is required"))
return phone
def clean_email(self):
email = self.cleaned_data.get('email')
if not email:
raise forms.ValidationError(_("Email is required"))
try:
validate_email(email)
except ValidationError as verr:
raise forms.ValidationError(_("Email is wrong"))
return email
def clean(self):
cleaned_data = super(BookingAddForm, self).clean()
if not self._user.is_authenticated:
email = cleaned_data.get('email')
if get_user_model().objects.filter(email=email).exists():
raise forms.ValidationError(_("Email already registered, please sign-in."))
return cleaned_data
class AddDiscountForm(LocaleNamedForm):
# TODO - Not used now(future)
class Meta:
model = Discount
fields = ('name', 'choice', 'time_on', 'time_off', 'days', 'at_price_days', 'percentage', 'apply_norefund',
'apply_creditcard', 'apply_package', 'apply_period')
def __init__(self, *args, **kwargs):
super(AddDiscountForm, self).__init__(*args, **kwargs)
self.fields['name'].required = False
def clean_choice(self):
choice = self.cleaned_data.get('choice')
if choice == 0:
raise forms.ValidationError(_("Discount not set"))
return choice
def clean_name(self):
name = self.cleaned_data.get('name')
if len(name.strip()) is 0:
name = _("New discount from ") + now().strftime("%d.%m.%Y")
return name
def clean(self):
cleaned_data = super(AddDiscountForm, self).clean()
choice = cleaned_data.get("choice")
need_del = []
if choice == DISCOUNT_NOREFUND or choice == DISCOUNT_CREDITCARD:
need_del = ['time_on', 'time_off', 'days', 'at_price_days', 'apply_norefund', 'apply_creditcard',
'apply_package', 'apply_period']
elif choice == DISCOUNT_EARLY:
need_del = ['time_on', 'time_off', 'at_price_days', 'apply_creditcard']
elif choice == DISCOUNT_LATER:
need_del = ['time_off', 'at_price_days']
elif choice == DISCOUNT_PERIOD:
need_del = ['time_on', 'time_off', 'at_price_days', 'apply_package', 'apply_period']
elif choice == DISCOUNT_PACKAGE:
need_del = ['time_on', 'time_off', 'apply_norefund', 'apply_creditcard']
elif choice == DISCOUNT_HOLIDAY or choice == DISCOUNT_SPECIAL or choice == DISCOUNT_NORMAL:
need_del = ['time_on', 'time_off', 'days', 'at_price_days', 'apply_package', 'apply_period']
elif choice == DISCOUNT_LAST_MINUTE:
need_del = ['days', 'at_price_days', 'apply_norefund', 'apply_creditcard', 'apply_package', 'apply_period']
for i in need_del:
del cleaned_data[i]
|
nnmware/nnmware
|
apps/booking/forms.py
|
Python
|
gpl-3.0
| 9,755
|
/*
* Copyright (C) 2014 Hector Espert Pardo
*
* 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 utilidades;
import java.util.Random;
/**
*
* @author Hector Espert
*
*/
public class Aleatorios {
/**
* Genera un numero aleatorio entre dos numeros.
* @param min
* @param max
* @return int
*/
public static int entre(int min, int max) {
//Ordenar
if (min > max) {
int aux = min;
min = max;
max = aux;
}
Random aleatorio = new Random();
int numale;
do {
numale = aleatorio.nextInt(max);
if (aleatorio.nextBoolean()) {
numale = -numale;
}
} while (numale < min);
return numale;
}
/**
* Genera un numero aleatorio entre dos numeros.
* @param min
* @param max
* @return double
*/
public static double entre(double min, double max) {
//Ordenar
if (min > max) {
double aux = min;
min = max;
max = aux;
}
Random aleatorio = new Random();
int numale;
do {
numale = aleatorio.nextInt();
if (aleatorio.nextBoolean()) {
numale = -numale;
}
} while (numale < min && numale > max);
return numale;
}
/**
* Devuelve una matrix de enteros aleatorios.
* num es el tamaño de la matriz
* @param num
* @return
*/
public static int[] toMatriz(int num) {
int[] numeros = new int[num];
Random aleatorio = new Random();
for (int i = 0; i < numeros.length; i++) {
int numero = aleatorio.nextInt();
numeros[i] = numero;
}
return numeros;
}
/**
* Devuelve una matrix de enteros aleatorios de 0 a un valor.
* num es el tamaño de la matriz
* max es el valor maximo de los aleatorios.
* @param num
* @param max
* @return
*/
public static int[] toMatriz(int num, int max) {
int[] numeros = new int[num];
Random aleatorio = new Random();
for (int i = 0; i < numeros.length; i++) {
int numero = aleatorio.nextInt(max);
numeros[i] = numero;
}
return numeros;
}
/**
* Devuelve una matrix de enteros aleatorios entre dos valores.
* @param num
* @param min
* @param max
* @return
*/
public static int[] toMatrizEntre (int num, int min, int max) {
int[] numeros = new int[num];
//Ordenar
if (min > max) {
int aux = min;
min = max;
max = aux;
}
for (int i = 0; i < numeros.length; i++) {
numeros[i] = entre(min, max);
}
return numeros;
}
/**
* Devuelve una matriz multiplie con numeros aleatorios.
* @param num
* @return
*/
public static int[][] toMatrizMulti(int num) {
int[][] numeros = new int[num][num];
Random aleatorio = new Random();
for (int[] matriz : numeros) {
for (int i = 0; i < matriz.length; i++) {
matriz[i] = aleatorio.nextInt();
}
}
return numeros;
}
/**
* Devuelve una matriz
* @param num
* @param max
* @return
*/
public static int[][] toMatrizMulti(int num, int max) {
int[][] numeros = new int[num][num];
Random aleatorio = new Random();
for (int[] matriz : numeros) {
for (int i = 0; i < matriz.length; i++) {
matriz[i] = aleatorio.nextInt(max);
}
}
return numeros;
}
/**
*
* @param num
* @param min
* @param max
* @return
*/
public static int[][] toMatrizMultiEntre (int num, int min, int max) {
int[][] numeros = new int[num][num];
//Ordenar
if (min > max) {
int aux = min;
min = max;
max = aux;
}
for (int[] matriz : numeros) {
for (int i = 0; i < matriz.length; i++) {
matriz[i] = entre(min, max);
}
}
return numeros;
}
/**
* Devuelve un boolean aleatorio.
* @return
*/
public static boolean getBoolean() {
Random aleatorio = new Random();
return aleatorio.nextBoolean();
}
/**
* Devuelve un int aleatorio.
* @return
*/
public static int getInt() {
Random aleatorio = new Random();
return aleatorio.nextInt();
}
}
|
cheste1/LibDAM
|
LibDAM/src/utilidades/Aleatorios.java
|
Java
|
gpl-3.0
| 6,150
|
// Copyright (C) 2009--2011, 2013, 2014 Jed Brown and Ed Bueler and Constantine Khroulev and David Maxwell
//
// This file is part of PISM.
//
// PISM 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.
//
// PISM 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 PISM; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
// The following are macros (instead of inline functions) so that error handling
// is less cluttered. They should be replaced with empty macros when in
// optimized mode.
#ifndef _FETOOLS_H_
#define _FETOOLS_H_
#include <petscmat.h>
#include "iceModelVec.hh" // to get PISMVector2
//! \file
//! \brief Classes for implementing the Finite Element Method on an IceGrid.
/*! \file
We assume that the reader has a basic understanding of the finite element method.
The following is a reminder of the method that also
gives the background for the how to implement it on an IceGrid with the tools in this
module.
The IceGrid domain \f$\Omega\f$ is decomposed into a grid of rectangular physical elements indexed by indices (i,j):
\verbatim
(0,1) (1,1)
---------
| | |
---------
| | |
---------
(0,0) (1,0)
\endverbatim
The index of an element corresponds with the index of its lower-left vertex in the grid.
The reference element is the square \f$[-1,1]\times[-1,1]\f$. For each physical element \f$E_{ij}\f$, there is an
map \f$F_{ij}\f$ from the reference element \f$R\f$ to \f$E_{ij}\f$.
In this implementation, the rectangles in the domain are all congruent, and the maps F_{ij} are all the same up
to a translation.
On the reference element, vertices are ordered as follows:
\verbatim
3 o---------o 2
| |
| |
| |
0 o---------o 1
\endverbatim
For each vertex \f$k\f$ there is an element basis function \f$\phi_k\f$ that is bilinear, equals 1 at
vertex \f$k\f$, and equals 0 at the remaining vertices.
For each node \f$(i',j')\f$ in the physical domain there is a basis function that equals 1 at
vertex \f$(i',j')\f$, equals zero at all other vertices, and that on element \f$(i,j)\f$
can be written as \f$\phi_k\circ F_{i,j}^{-1}\f$ for some index \f$k\f$.
A (scalar) finite element function \f$f\f$ on the domain is then a linear combination
\f[
f_h = \sum_{i,j} c_{ij}\psi_{ij}.
\f]
Let \f$G(w,\psi)\f$ denote the weak form of the PDE under consideration. For
example, for the scalar Poisson equation \f$-\Delta w = f\f$,
\f[
G(w,\psi) = \int_\Omega \nabla w \cdot \nabla \psi -f\psi\;dx.
\f]
In the continuous problem we seek to
find a trial function \f$w\f$ such that \f$G(w,\psi)=0\f$ for all suitable test
functions \f$\psi\f$. In the discrete problem, we seek a finite element function \f$w_h\f$
such that \f$G(w_h,\psi_{ij})=0\f$ for all suitable indices \f$(i,j)\f$.
For realistice problems, the integral given by \f$G\f$ cannot be evaluated exactly,
but is approximated with some \f$G_h\f$ that arises from numerical quadrature quadrature rule:
integration on an element \f$E\f$ is approximated with
\f[
\int_E f dx \approx \sum_{q} f(x_q) w_q
\f]
for certain points \f$x_q\f$ and weights \f$j_q\f$ (specific details are found in FEQuadrature).
The unknown \f$w_h\f$ is represented by an IceVec, \f$w_h=\sum_{ij} c_{ij} \psi_{ij}\f$ where
\f$c_{ij}\f$ are the coefficients of the vector. The solution of the finite element problem
requires the following computations:
-# Evaluation of the residuals \f$r_{ij} = G_h(w_h,\psi_{ij})\f$
-# Evaluation of the Jacobian matrix
\f[
J_{(ij)\;(kl)}=\frac{d}{dc_{kl}} G_h(w_h,\psi_{ij}).
\f]
Computations of these 'integrals' are done by adding up the contributions
from each element (an FEElementMap helps with iterating over the elements).
For a fixed element, there is a locally defined trial
function \f$\hat w_h\f$ (with 4 degrees of freedom in the scalar case) and
4 local test functions \f$\hat\psi_k\f$, one for each vertex.
The contribution to the integrals proceeds as follows (for concreteness
in the case of computing the residual):
- Extract from the global degrees of freedom \f$c\f$ defining \f$w_h\f$
the local degrees of freedom \f$d\f$ defining \f$\hat w_h\f$. (FEDOFMap)
- Evaluate the local trial function \f$w_h\f$ (values and derivatives as needed)
at the quadrature points \f$x_q\f$ (FEQuadrature)
- Evaluate the local test functions (again values and derivatives)
at the quadrature points. (FEQuadrature)
- Obtain the quadrature weights $j_q$ for the element (FEQuadrature)
- Compute the values of the integrand \f$g(\hat w_h,\psi_k)\f$
at each quadrature point (call these \f$g_{qk}\f$) and
form the weighted sums \f$y_k=\sum_{q} j_q g_{qk}\f$.
- Each sum \f$y_k\f$ is the contribution of the current element to
a residual entry \f$r_{ij}\f$, where local degree of freedom \f$k\f$
corresponds with global degree of freedom \f$(i,j)\f$. The
local contibutions now need to be added to the global residual vector (FEDOFMap).
Computation of the Jacobian is similar, except that there are now
multiple integrals per element (one for each local degree of freedom of
\f$\hat w_h\f$).
All of the above is a simplified description of what happens in practice.
The complications below treated by the following classes, and discussed
in their documentation:
- Ghost elements (as well as periodic boundary conditions): FEElementMap
- Dirichlet data: FEDOFMap
- Vector valued functions: (FEDOFMap, FEQuadrature)
The classes in this module are not intended
to be a fancy finite element package.
Their purpose is to clarify the steps that occur in the computation of
residuals and Jacobians in SSAFEM, and to isolate and consolodate
the hard steps so that they are not scattered about the code.
*/
//! Struct for gathering the value and derivative of a function at a point.
/*! Germ in meant in the mathematical sense, sort of. */
struct FEFunctionGerm
{
double val, //!< Function value.
dx, //!< Function deriviative with respect to x.
dy; //!< Function derivative with respect to y.
};
//! Struct for gathering the value and derivative of a vector valued function at a point.
/*! Germ in meant in the mathematical sense, sort of. */
struct FEVector2Germ
{
PISMVector2 val, //!< Function value.
dx, //!< Function deriviative with respect to x.
dy; //!< Function derivative with respect to y.
};
//! Computation of Q1 shape function values.
/*! The Q1 shape functions are bilinear functions. On a rectangular
element, there are four (FEShapeQ1::Nk) basis functions, each equal
to 1 at one vertex and equal to zero at the remainder.
The FEShapeQ1 class consolodates the computation of the values and
derivatives of these basis functions. */
class FEShapeQ1 {
public:
virtual ~FEShapeQ1() {}
//! Compute values and derivatives of the shape function supported at node 0
static void shape0(double x, double y, FEFunctionGerm *value)
{
value->val = (1-x)*(1-y)/4.;
value->dx = -(1-y)/4.;
value->dy = -(1-x)/4;
}
//! Compute values and derivatives of the shape function supported at node 1
static void shape1(double x, double y, FEFunctionGerm *value)
{
value->val = (1+x)*(1-y)/4.;
value->dx = (1-y)/4.;
value->dy = -(1+x)/4;
}
//! Compute values and derivatives of the shape function supported at node 2
static void shape2(double x, double y, FEFunctionGerm *value)
{
value->val = (1+x)*(1+y)/4.;
value->dx = (1+y)/4.;
value->dy = (1+x)/4;
}
//! Compute values and derivatives of the shape function supported at node 3
static void shape3(double x, double y, FEFunctionGerm *value)
{
value->val = (1-x)*(1+y)/4.;
value->dx = -(1+y)/4.;
value->dy = (1-x)/4;
}
//! The number of basis shape functions.
static const int Nk = 4;
//! A table of function pointers, one for each shape function.
typedef void (*ShapeFunctionSpec)(double,double,FEFunctionGerm*);
static const ShapeFunctionSpec shapeFunction[Nk];
//! Evaluate shape function \a k at (\a x,\a y) with values returned in \a germ.
virtual void eval(int k, double x, double y,FEFunctionGerm*germ){
shapeFunction[k](x,y,germ);
}
};
//! The mapping from global to local degrees of freedom.
/*! Computations of residual and Jacobian entries in the finite element method are
done by iterating of the elements and adding the various contributions from each element.
To do this, degrees of freedom from the global vector of unknowns must be remapped to
element-local degrees of freedom for the purposes of local computation,
(and the results added back again to the global residual and Jacobian arrays).
An FEDOFMap mediates the transfer between element-local and global degrees of freedom.
In this very concrete implementation, the global degrees of freedom are either
scalars (double's) or vectors (PISMVector2's), one per node in the IceGrid,
and the local degrees of freedom on the element are FEDOFMap::Nk (%i.e. four) scalars or vectors, one
for each vertex of the element.
The FEDOFMap is also (perhaps awkwardly) overloaded to also mediate transfering locally
computed contributions to residual and Jacobian matricies to their global
counterparts.
See also: \link FETools.hh FiniteElement/IceGrid background material\endlink.
*/
class FEDOFMap
{
public:
FEDOFMap()
{
m_i = m_j = 0;
PetscMemzero(m_row, Nk*sizeof(MatStencil));
PetscMemzero(m_col, Nk*sizeof(MatStencil));
};
virtual ~FEDOFMap() {};
virtual void extractLocalDOFs(int i, int j, double const*const*xg, double *x) const;
virtual void extractLocalDOFs(int i, int j, PISMVector2 const*const*xg, PISMVector2 *x) const;
virtual void extractLocalDOFs(double const*const*xg, double *x) const;
virtual void extractLocalDOFs(PISMVector2 const*const*xg, PISMVector2 *x) const;
virtual void reset(int i, int j, const IceGrid &g);
virtual void markRowInvalid(int k);
virtual void markColInvalid(int k);
void localToGlobal(int k, int *i, int *j);
virtual void addLocalResidualBlock(const PISMVector2 *y, PISMVector2 **yg);
virtual void addLocalResidualBlock(const double *y, double **yg);
virtual PetscErrorCode addLocalJacobianBlock(const double *K, Mat J);
virtual PetscErrorCode setJacobianDiag(int i, int j, const double *K, Mat J);
static const int Nk = 4; //<! The number of test functions defined on an element.
protected:
static const int kDofInvalid = PETSC_MIN_INT / 8; //!< Constant for marking invalid row/columns.
static const int kIOffset[Nk];
static const int kJOffset[Nk];
//! Indices of the current element (for updating residual/Jacobian).
int m_i, m_j;
//! Stencils for updating entries of the Jacobian matrix.
MatStencil m_row[Nk], m_col[Nk];
};
//! Manages iterating over element indices.
/*! When computing residuals and Jacobians, there is a loop over all the elements
in the IceGrid, and computations are done on each element. The IceGrid
has an underlying Petsc DA, and our processor does not own all of the nodes in the grid.
Therefore we should not perform computation on all of the elements. In general,
an element will have ghost (o) and real (*) vertices:
\verbatim
o---*---*---*---o
| | | | |
o---*---*---*---o
| | | | |
o---o---o---o---o
\endverbatim
The strategy is to do computations on this processor on every element that has
a vertex that is owned by this processor. But we only update entries in the
global residual and Jacobian matrices if the corresponding row corresponds to a
vertex that we own. In the worst case, where each vertex of an element is owned by
a different processor, the computations for that element will be repeated four times,
once for each processor.
This same strategy also correctly deals with periodic boundary conditions. The way Petsc deals
with periodic boundaries can be thought of as using a kind of ghost. So the rule still works:
compute on all elements containg a real vertex, but only update rows corresponding to that real vertex.
The calculation of what elements to index over needs to account for ghosts and the
presence or absense of periodic boundary conditions in the IceGrid. The FEElementMap performs
that computation for you (see FEElementMap::xs and friends).
See also: \link FETools.hh FiniteElement/IceGrid background material\endlink.
*/
class FEElementMap
{
public:
FEElementMap(const IceGrid &g);
/*!\brief The total number of elements to be iterated over. Useful for creating per-element storage.*/
int element_count()
{
return xm*ym;
}
/*!\brief Convert an element index (\a i,\a j) into a flattened (1-d) array index, with the first
element (\a i, \a j) to be iterated over corresponding to flattened index 0. */
int flatten(int i, int j)
{
return (i-xs)*ym+(j-ys);
}
int xs, //!< x-coordinate of the first element to loop over.
xm, //!< total number of elements to loop over in the x-direction.
ys, //!< y-coordinate of the first element to loop over.
ym, //!< total number of elements to loop over in the y-direction.
lxs, //!< x-index of the first local element.
lxm, //!< total number local elements in x direction.
lys, //!< y-index of the first local element.
lym; //!< total number local elements in y direction.
};
//! Numerical integration of finite element functions.
/*! The core of the finite element method is the computation of integrals over elements.
For nonlinear problems, or problems with non-constant coefficients (%i.e. any real problem)
the integration has to be done approximately:
\f[
\int_E f(x)\; dx \approx \sum_q f(x_q) w_q
\f]
for certain quadrature points \f$x_q\f$ and weights \f$w_q\f$. An FEQuadrature is used
to evaluate finite element functions at quadrature points, and to compute weights \f$w_q\f$
for a given element.
In this concrete implementation, the reference element \f$R\f$ is the square
\f$[-1,1]\times[-1,1]\f$. On a given element, nodes (o) and quadrature points (*)
are ordered as follows:
\verbatim
3 o------------------o 2
| 3 2 |
| * * |
| |
| |
| * * |
| 0 1 |
0 o------------------o 1
\endverbatim
So there are four quad points per element, which occur at \f$x,y=\pm 1/\sqrt{3}\f$. This corresponds to the tensor product
of Gaussian integration on an interval that is exact for cubic functions on the interval.
Integration on a physical element can be thought of as being done by change of variables. The quadrature weights need
to be modified, and the FEQuadrature takes care of this for you. Because all elements in an IceGrid are congruent, the
quadrature weights are the same for each element, and are computed upon initialization with an IceGrid.
See also: \link FETools.hh FiniteElement/IceGrid background material\endlink.
*/
class FEQuadrature
{
public:
static const int Nq = 4; //!< Number of quadrature points.
static const int Nk = 4; //!< Number of test functions on the element.
FEQuadrature();
void init(const IceGrid &g,double L=1.); // FIXME Allow a length scale to be specified.
const FEFunctionGerm (*testFunctionValues())[Nq];
const FEFunctionGerm *testFunctionValues(int q);
const FEFunctionGerm *testFunctionValues(int q,int k);
void computeTrialFunctionValues( const double *x, double *vals);
void computeTrialFunctionValues( const double *x, double *vals, double *dx, double *dy);
void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, double const*const*xg, double *vals);
void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, double const*const*xg,
double *vals, double *dx, double *dy);
void computeTrialFunctionValues( const PISMVector2 *x, PISMVector2 *vals);
void computeTrialFunctionValues( const PISMVector2 *x, PISMVector2 *vals, double (*Dv)[3]);
void computeTrialFunctionValues( const PISMVector2 *x, PISMVector2 *vals, PISMVector2 *dx, PISMVector2 *dy);
void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, PISMVector2 const*const*xg,
PISMVector2 *vals);
void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, PISMVector2 const*const*xg,
PISMVector2 *vals, double (*Dv)[3]);
void getWeightedJacobian(double *jxw);
//! The coordinates of the quadrature points on the reference element.
static const double quadPoints[Nq][2];
//! The weights for quadrature on the reference element.
static const double quadWeights[Nq];
protected:
//! The Jacobian determinant of the map from the reference element to the physical element.
double m_jacobianDet;
//! Shape function values (for each of \a Nq quadrature points, and each of \a Nk shape function )
FEFunctionGerm m_germs[Nq][Nk];
double m_tmpScalar[Nk];
PISMVector2 m_tmpVector[Nk];
};
class DirichletData {
public:
DirichletData();
~DirichletData();
PetscErrorCode init( IceModelVec2Int *indices, IceModelVec2V *values, double weight);
PetscErrorCode init( IceModelVec2Int *indices, IceModelVec2S *values, double weight);
PetscErrorCode init( IceModelVec2Int *indices);
void constrain( FEDOFMap &dofmap );
void update( FEDOFMap &dofmap, PISMVector2* x_e );
void update( FEDOFMap &dofmap, double* x_e );
void updateHomogeneous( FEDOFMap &dofmap, PISMVector2* x_e );
void updateHomogeneous( FEDOFMap &dofmap, double* x_e );
void fixResidual( PISMVector2 **x, PISMVector2 **r);
void fixResidual( double **x, double **r);
void fixResidualHomogeneous( PISMVector2 **r);
void fixResidualHomogeneous( double **r);
PetscErrorCode fixJacobian2V( Mat J);
PetscErrorCode fixJacobian2S( Mat J);
operator bool() {
return m_indices != NULL;
}
PetscErrorCode finish();
protected:
double m_indices_e[FEQuadrature::Nk];
IceModelVec2Int *m_indices;
IceModelVec *m_values;
double **m_pIndices;
void **m_pValues;
double m_weight;
};
#endif/* _FETOOLS_H_*/
|
talbrecht/pism_pik06
|
src/base/stressbalance/ssa/FETools.hh
|
C++
|
gpl-3.0
| 18,810
|
/*
* Copyright (c) 2010-2014 Clark & Parsia, LLC. <http://www.clarkparsia.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.complexible.stardog.plan.aggregates;
import java.io.File;
import com.complexible.common.protocols.server.Server;
import com.complexible.common.rdf.query.resultio.TextTableQueryResultWriter;
import com.complexible.stardog.Stardog;
import com.complexible.stardog.api.Connection;
import com.complexible.stardog.api.ConnectionConfiguration;
import com.complexible.stardog.api.admin.AdminConnection;
import com.complexible.stardog.api.admin.AdminConnectionConfiguration;
import com.complexible.stardog.protocols.snarl.SNARLProtocolConstants;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.resultio.QueryResultIO;
/**
* <p></p>
*
* @author Albert Meroño-Peñuela
* @since 1.0
* @version 1.0
*/
public class TestRAggregates {
private static Server SERVER = null;
private static final String DB = "testRAggregates";
@BeforeClass
public static void beforeClass() throws Exception {
SERVER = Stardog.buildServer()
.bind(SNARLProtocolConstants.EMBEDDED_ADDRESS)
.start();
final AdminConnection aConn = AdminConnectionConfiguration.toEmbeddedServer()
.credentials("admin", "admin")
.connect();
try {
if (aConn.list().contains(DB)) {
aConn.drop(DB);
}
aConn.memory(DB).create(new File("/Users/Albert/src/linked-edit-rules/data/people.ttl"));
}
finally {
aConn.close();
}
}
@AfterClass
public static void afterClass() {
if (SERVER != null) {
SERVER.stop();
}
}
@Test
public void TestMean() throws Exception {
final Connection aConn = ConnectionConfiguration.to(DB)
.credentials("admin", "admin")
.connect();
try {
final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
"PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
"PREFIX agg: <urn:aggregate> " +
"SELECT (agg:stardog:mean(?o) AS ?c) " +
"WHERE { ?s leri:height ?o } ";
System.out.println("Executing query: " + aQuery);
final TupleQueryResult aResult = aConn.select(aQuery).execute();
try {
System.out.println("Query result:");
while (aResult.hasNext()) {
System.out.println(aResult.next().getValue("c").stringValue());
}
}
finally {
aResult.close();
}
}
finally {
aConn.close();
}
}
// @Test
// public void TestMedian() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:median(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestMaxAggregate() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:max(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestMinAggregate() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:min(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestSd() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:sd(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestVar() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:var(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestAbs() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:abs(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestSqrt() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:sqrt(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestCeiling() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:ceiling(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestFloor() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:floor(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestTrunc() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:trunc(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestLog() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:log(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestLog10() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:log10(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestExp() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:exp(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestRound() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:round(stardog:sin(?o), 4) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestSignif() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:signif(stardog:sin(?o), 4) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestCos() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:cos(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestSin() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:sin(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestTan() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:tan(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestCov() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX sdmx-dimension: <http://purl.org/linked-data/sdmx/2009/dimension#> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT (stardog:cov(?height, ?age) AS ?c) " +
// "WHERE { ?s leri:height ?height ; sdmx-dimension:age ?age } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
@Test
public void TestPredict() throws Exception {
final Connection aConn = ConnectionConfiguration.to(DB)
.credentials("admin", "admin")
.connect();
try {
final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
"PREFIX sdmx-dimension: <http://purl.org/linked-data/sdmx/2009/dimension#> " +
"PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
"SELECT (stardog:predict(?age) AS ?page) " +
"WHERE { ?s leri:height ?height . } ";
System.out.println("Executing query: " + aQuery);
final TupleQueryResult aResult = aConn.select(aQuery).execute();
//QueryResultIO.write(aResult, TextTableQueryResultWriter.FORMAT, System.out);
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// try {
// System.out.println(aResult.next().getValue("page").stringValue());
// } catch (NullPointerException e) {
// System.out.println("NA");
// }
// }
// } catch (NullPointerException e) {
// System.err.println(e.getMessage());
// }
// finally {
// aResult.close();
// }
}
finally {
aConn.close();
}
}
}
|
albertmeronyo/stardog-r
|
aggregates/test/src/com/complexible/stardog/plan/aggregates/TestRAggregates.java
|
Java
|
gpl-3.0
| 22,803
|
---
layout: documentation-summary
title: "Gadget"
date: 2014-10-01 10:52:00
category: documentation/core-api/gadget
parent-order: 7
order: 0
---
#### [core.gadget.get]({{site.absoluteurl}}documentation/core-api/gadget/core.gadget.get)
Returns the complete Gadget object by **id**.
***
#### [core.gadget.list]({{site.absoluteurl}}documentation/core-api/gadget/core.gadget.list)
Lists all Gadgets for the given Company as well as all Gadgets shared with the given Company.
***
|
Rise-Vision/risevision-documentation
|
_posts/documentation/core-api/gadget/2014-10-01-gadget.md
|
Markdown
|
gpl-3.0
| 484
|
/*
* HelpCommand.java
*
* Copyright (C) 2002-2013 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.executequery.gui.console.commands;
import org.executequery.gui.console.Console;
import org.underworldlabs.util.SystemProperties;
/* ----------------------------------------------------------
* CVS NOTE: Changes to the CVS repository prior to the
* release of version 3.0.0beta1 has meant a
* resetting of CVS revision numbers.
* ----------------------------------------------------------
*/
/**
* This command displays command help.
* @author Romain Guy
*/
/**
* @author Takis Diakoumis
* @version $Revision: 160 $
* @date $Date: 2013-02-08 17:15:04 +0400 (Пт, 08 фев 2013) $
*/
public class HelpCommand extends Command {
private static final String COMMAND_NAME = "help";
public String getCommandName() {
return COMMAND_NAME;
}
public String getCommandSummary() {
return SystemProperties.getProperty("console", "console.help.command.help");
}
public boolean handleCommand(Console console, String command) {
if (command.equals(COMMAND_NAME)) {
console.help();
return true;
}
return false;
}
}
|
Black-millenium/rdb-executequery
|
java/src/org/executequery/gui/console/commands/HelpCommand.java
|
Java
|
gpl-3.0
| 1,823
|
/*
* Copyright 2010 kk-electronic a/s.
*
* This file is part of KKPortal.
*
* KKPortal 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.
*
* KKPortal 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 KKPortal. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kk_electronic.kkportal.core.rpc.jsonformat;
@SuppressWarnings("serial")
public class UnableToDeserialize extends Exception {
public UnableToDeserialize(String string) {
super(string);
}
}
|
kk-electronic/KKPortal
|
src/com/kk_electronic/kkportal/core/rpc/jsonformat/UnableToDeserialize.java
|
Java
|
gpl-3.0
| 950
|
/**
* Copyright 2015 Poznań Supercomputing and Networking Center
*
* Licensed under the GNU General Public License, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pl.psnc.synat.wrdz.ms.stats;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import pl.psnc.synat.wrdz.ms.entity.stats.DataFileFormatStat;
import pl.psnc.synat.wrdz.zmd.dto.format.DataFileFormatDto;
import pl.psnc.synat.wrdz.zmd.format.DataFileFormatBrowser;
/**
* Bean that handles data file format statistics.
*/
@SuppressWarnings("serial")
public abstract class DataFileFormatBean implements Serializable {
/** Data file format statistics. */
private List<DataFileFormatStat> stats;
/** Data file format information. */
private Map<String, DataFileFormatDto> formats;
/** Data file format browser. */
@EJB(name = "DataFileFormatBrowser")
private transient DataFileFormatBrowser formatBrowser;
/** When the statistics were computed. */
private Date computedOn;
/**
* Refreshes the currently cached statistics.
*/
public void refresh() {
stats = fetchStatistics();
computedOn = !stats.isEmpty() ? stats.get(0).getComputedOn() : null;
formats = new HashMap<String, DataFileFormatDto>();
for (DataFileFormatDto format : formatBrowser.getFormats()) {
formats.put(format.getPuid(), format);
}
}
/**
* Returns the currently cached statistics, refreshing them if necessary.
*
* @return statistics
*/
public List<DataFileFormatStat> getStatistics() {
if (stats == null) {
refresh();
}
return stats;
}
public Date getComputedOn() {
return computedOn;
}
/**
* Returns the map with format puids and their data.
*
* @return a <format puid, format data> map
*/
public Map<String, DataFileFormatDto> getFormats() {
if (formats == null) {
refresh();
}
return formats;
}
/**
* Fetches the statistics from database.
*
* @return the statistics
*/
protected abstract List<DataFileFormatStat> fetchStatistics();
}
|
psnc-dl/darceo
|
wrdz/wrdz-ms/web/src/main/java/pl/psnc/synat/wrdz/ms/stats/DataFileFormatBean.java
|
Java
|
gpl-3.0
| 2,754
|
<?php
/*
Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Legacy mode enabler
class F3
{
public static $fw;
/**
* Forward function calls to framework
*
* @return mixed
* @param $func callback
* @param $args array
**/
public static function __callstatic($func, array $args)
{
if (!self::$fw) {
self::$fw=Base::instance();
}
return call_user_func_array([self::$fw,$func], $args);
}
}
|
vijinho/fatfree-core-psr2
|
f3.php
|
PHP
|
gpl-3.0
| 1,213
|
#include "pointconversor.h"
#include "invalidconversorinput.h"
// TODO: implement human notation WIHTOUT double float (or any float).
// With float, there are some 64 bits numbers which cannot be represented
// because double float only really has 52 bits for mantissa.
PointConversor::PointConversor():
bits(0),
exponent(0),
sign(false),
normality(PointConversor::NORMAL)
{
}
// Raw input functions
PointConversor& PointConversor::inputHalfFloatRaw(uint16_t number)
{
return this->inputGenericFloatRaw(number, 10, 5);
}
PointConversor& PointConversor::inputSingleFloatRaw(float number)
{
union { float number; uint32_t bits; } bitCast { number };
return this->inputGenericFloatRaw(bitCast.bits, 23, 8);
}
PointConversor& PointConversor::inputDoubleFloatRaw(double number)
{
union { double number; uint64_t bits; } bitCast { number };
return this->inputGenericFloatRaw(bitCast.bits, 52, 11);
}
PointConversor& PointConversor::inputFixed8Raw(uint8_t number, int16_t pointPos, Signedness signedness)
{
return this->inputGenericFixedRaw(number, 8, pointPos, signedness);
}
PointConversor& PointConversor::inputFixed16Raw(uint16_t number, int16_t pointPos, Signedness signedness)
{
return this->inputGenericFixedRaw(number, 16, pointPos, signedness);
}
PointConversor& PointConversor::inputFixed32Raw(uint32_t number, int16_t pointPos, Signedness signedness)
{
return this->inputGenericFixedRaw(number, 32, pointPos, signedness);
}
PointConversor& PointConversor::inputFixed64Raw(uint64_t number, int16_t pointPos, Signedness signedness)
{
return this->inputGenericFixedRaw(number, 64, pointPos, signedness);
}
// String input functions
PointConversor& PointConversor::inputHalfFloat(QString const& number)
{
return this->inputGenericFloat(number, 10, 5);
}
PointConversor& PointConversor::inputSingleFloat(QString const& number)
{
return this->inputGenericFloat(number, 23, 8);
}
PointConversor& PointConversor::inputDoubleFloat(QString const& number)
{
return this->inputGenericFloat(number, 52, 11);
}
PointConversor& PointConversor::inputFixed8(QString const& number, Signedness signedness)
{
return this->inputGenericFixed(number, 8, signedness);
}
PointConversor& PointConversor::inputFixed16(QString const& number, Signedness signedness)
{
return this->inputGenericFixed(number, 16, signedness);
}
PointConversor& PointConversor::inputFixed32(QString const& number, Signedness signedness)
{
return this->inputGenericFixed(number, 32, signedness);
}
PointConversor& PointConversor::inputFixed64(QString const& number, Signedness signedness)
{
return this->inputGenericFixed(number, 64, signedness);
}
PointConversor& PointConversor::inputHumanNotation(QString const& number)
{
// For now, we are decoding human notation via double float. This means we
// are losing some precision, since double has only 52 bits of significant
// digits, and our class stores 64 bits of significant digits, but that's
// perhaps acceptable.
bool ok = true;
double asDoubleFloat = number.toDouble(&ok);
if (!ok) {
throw InvalidConversorInput("Número não está na notação humana adequada");
}
return this->inputDoubleFloatRaw(asDoubleFloat);
}
// Raw output functions
uint16_t PointConversor::outputHalfFloatRaw() const
{
return this->outputGenericFloatRaw(10, 5);
}
float PointConversor::outputSingleFloatRaw() const
{
uint32_t number = this->outputGenericFloatRaw(23, 8);
union { uint32_t bits; float number; } bitCast { number };
return bitCast.number;
}
double PointConversor::outputDoubleFloatRaw() const
{
uint64_t number = this->outputGenericFloatRaw(52, 11);
union { uint64_t bits; double number; } bitCast { number };
return bitCast.number;
}
uint8_t PointConversor::outputFixed8Raw(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixedRaw(8, pointPos, signedness);
}
uint16_t PointConversor::outputFixed16Raw(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixedRaw(16, pointPos, signedness);
}
uint32_t PointConversor::outputFixed32Raw(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixedRaw(32, pointPos, signedness);
}
uint64_t PointConversor::outputFixed64Raw(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixedRaw(64, pointPos, signedness);
}
QString PointConversor::outputHalfFloat() const
{
return this->outputGenericFloat(10, 5);
}
QString PointConversor::outputSingleFloat() const
{
return this->outputGenericFloat(23, 8);
}
QString PointConversor::outputDoubleFloat() const
{
return this->outputGenericFloat(52, 11);
}
// String output function
QString PointConversor::outputFixed8(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixed(8, pointPos, signedness);
}
QString PointConversor::outputFixed16(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixed(16, pointPos, signedness);
}
QString PointConversor::outputFixed32(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixed(32, pointPos, signedness);
}
QString PointConversor::outputFixed64(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixed(64, pointPos, signedness);
}
QString PointConversor::outputHumanNotation() const
{
double asDoubleFloat = this->outputDoubleFloatRaw();
QString rendered = QString::number(asDoubleFloat, 'f', 50);
if (rendered.contains('.')) {
int trailingPos = rendered.length() - 1;
while (trailingPos > 2 && rendered[trailingPos] == '0') {
trailingPos--;
}
rendered.truncate(trailingPos + 1);
}
return rendered;
}
// Generic input functions
PointConversor& PointConversor::inputGenericFloatRaw(uint64_t number, uint16_t mantissaSize, uint16_t exponentSize)
{
uint64_t mantissaMask = 0;
int16_t exponentMask = 0;
uint64_t finalBit = 0;
validateFloatSpec(mantissaSize, exponentSize);
// Initialize here because mantissa size or exponent size might be invalid.
mantissaMask = ((uint64_t) 1 << mantissaSize) - 1;
exponentMask = ((uint64_t) 1 << exponentSize) - 1;
finalBit = ((uint64_t) 1 << mantissaSize);
// Sign is the last bit.
this->sign = number >> (exponentSize + mantissaSize);
// We store the mantissa bits (lower bits) as the significant bits.
this->bits = number & mantissaMask;
// Exponent is between the mantissa and the sign.
this->exponent = (number >> mantissaSize) & exponentMask;
if (this->exponent != exponentMask) {
// Exponent being `< maximum` exponent means it is normal.
if (this->exponent == 0) {
// But if the exponent is zero, it is actually subnormal.
this->exponent++;
} else {
// Otherwise, `0 < exponent < max` means it is really normal.
//
// There is an extra high bit, because a normal number is in this
// format:
//
// 1.xxxxxxx... * 2**e
//
// And this "1" is not stored, only the xxxxxx...
//
// So, we need to introduce it.
this->bits |= finalBit;
}
this->normality = PointConversor::NORMAL;
// The exponent uses an encoding which we need to translate to C++'s signed numbers.
this->exponent -= mantissaSize + (exponentMask >> 1);
} else if (this->bits == 0) {
// exponent == MAX and bits are zeroed, therefore, Infinity.
this->normality = PointConversor::INFINITY_NAN;
} else {
// exponent == MAX and bits not zeroed, therefore, regular NAN.
this->normality = PointConversor::NOT_A_NUMBER;
}
return *this;
}
PointConversor& PointConversor::inputGenericFixedRaw(uint64_t number, int16_t width, int16_t pointPos, Signedness signedness)
{
uint64_t signMask = 0;
uint64_t extendMask = 0;
validateFixedSpec(width, pointPos, signedness);
// Initialize here because width might be invalid.
//
// Last bit.
signMask = (uint64_t) 1 << (width - 1);
// Cut off extension mask, 0000....011111...1111
extendMask = ~((uint64_t) 0) >> (MAX_WIDTH - width);
// Fixed point is always normal.
this->normality = PointConversor::NORMAL;
switch (signedness) {
case UNSIGNED:
this->sign = false;
break;
case TWOS_COMPL:
this->sign = (number & signMask) != 0;
break;
}
// Bits b with point p means the number is b * 2**(-p)
this->exponent = -pointPos;
this->bits = number;
if (this->sign) {
// Complementing negativeness.
this->bits = (~this->bits + 1) & extendMask;
}
return *this;
}
PointConversor& PointConversor::inputGenericFloat(QString const &number, uint16_t mantissaSize, uint16_t exponentSize)
{
uint64_t numBits = 0;
bool hasChars = false;
int count = 0;
for (QChar numChar : number) {
if (numChar == '0' || numChar == '1') {
numBits <<= 1;
// By now we know it is zero or one.
numBits |= numChar.digitValue();
if (numBits != 0) {
// Only start to count when bits not zero because leading zeros are ignored.
count++;
}
if (count > mantissaSize + exponentSize + 1) {
// Note that count ignores leading zeros.
throw InvalidConversorInput("Entrada é muito grande");
}
hasChars = true;
} else if (numChar != ' ') {
// Space is ignored, but other chars are an error!
throw InvalidConversorInput("Entrada precisa conter apenas 0 ou 1");
}
}
if (!hasChars) {
throw InvalidConversorInput("Entrada não pode ser vazia");
}
return this->inputGenericFloatRaw(numBits, mantissaSize, exponentSize);
}
PointConversor& PointConversor::inputGenericFixed(QString const &number, int16_t width, Signedness signedness)
{
uint64_t numBits = 0;
bool hasChars = false;
bool pointFound = false;
int16_t pointPos = 0;
int count = 0;
for (QChar numChar : number) {
if (numChar == '0' || numChar == '1') {
numBits <<= 1;
// By now we know it is zero or one.
numBits |= numChar.digitValue();
if (numBits != 0 || pointFound) {
// Only start to count when bits not zero because leading zeros are ignored.
//
// However, once a point has been found, we cannot ignore anymore.
count++;
}
if (count > width && numChar != '0') {
// Note that count ignores leading zeros (before point!).
throw InvalidConversorInput("Entrada é muito grande");
}
hasChars = true;
} else if (numChar == '.') {
if (pointFound) {
throw InvalidConversorInput("Entrada pode conter apenas um ponto");
}
pointFound = true;
// Saves point position, because count still has to be incremented for overflow checks,
// and for knowing the total width.
pointPos = count;
} else if (numChar != ' ') {
// Space is ignored, but other chars are an error!
throw InvalidConversorInput("Entrada precisa conter apenas 0 ou 1 (ou ponto)");
}
}
if (!hasChars) {
throw InvalidConversorInput("Entrada não pode ser vazia");
}
if (!pointFound) {
throw InvalidConversorInput("O número em ponto fixo deve conter um ponto.");
}
if (pointPos > width || count - pointPos > width) {
throw InvalidConversorInput("O ponto não pode estar fora dos limites.");
}
// Actual point position is reversed because humans usually write numbers in big-endian:
// complement it with the found width to reverse it back..
return this->inputGenericFixedRaw(numBits, width, count - pointPos, signedness);
}
// Generic output functions
uint64_t PointConversor::outputGenericFloatRaw(uint16_t mantissaSize, uint16_t exponentSize) const
{
int16_t numExponent = 0;
uint64_t numBits = 0;
uint64_t number = 0;
uint64_t mantissaMask = 0;
int16_t exponentMask = 0;
uint64_t finalBit = 0;
bool subnormal = false;
uint64_t roundRight = 0;
// Initialize here because mantissa size or exponent size might be invalid.
validateFloatSpec(mantissaSize, exponentSize);
mantissaMask = ((uint64_t) 1 << mantissaSize) - 1;
exponentMask = ((uint64_t) 1 << exponentSize) - 1;
finalBit = (uint64_t) 1 << mantissaSize;
switch (this->normality) {
case PointConversor::NORMAL:
// Converts the C++'s signed integer representation of the exponent into float's one.
numExponent = this->exponent + (exponentMask >> 1) + mantissaSize;
numBits = this->bits;
// Try to normalize the number if too small. Remember "really" normal floats have an implicit bit,
// and that the significant bits they store are `xxxxx...` in the number `1.xxxxx... * 2**e`.
// This makes that 1 be in the correct position.
while (numBits < finalBit && numBits != 0) {
numBits <<= 1;
// Remember making an equivalent exponent.
numExponent -= 1;
}
// Same as the loop above, but in this case the number is too big.
while (numBits >= (finalBit << 1)) {
// If the last eliminated bit was 1, we might round the number later.
roundRight = numBits & 1;
numBits >>= 1;
// Remember making an equivalent exponent.
numExponent += 1;
}
if (numExponent <= 0) {
// In case the exponent is below zero, this will be subnormal...
while (numExponent < 0) {
numBits >>= 1;
numExponent += 1;
}
roundRight = numBits & 1;
// Subnormal numbers have an extra step on the exponent, so we must
// get rid off an extra bit to compensate.
numBits >>= 1;
}
// If it does not have final bit, it is subnormal. Important for below.
subnormal = (numBits & finalBit) == 0;
// Getting rid of that implicit "1".
numBits &= ~finalBit;
// Potentially rounding in the right.
numBits += roundRight;
// Tries to fit the exponent. Might fail and end up with infinity below.
while (numExponent > exponentMask && numBits < (finalBit >> 1)) {
numBits <<= 1;
numExponent -= 1;
}
if (subnormal && numBits == 0) {
// No final bit => subnormal.
numExponent = 0;
} else if (numExponent >= exponentMask) {
// Exponent too big? Then infinity.
numExponent = exponentMask;
numBits = 0;
}
break;
case PointConversor::INFINITY_NAN:
numExponent = exponentMask;
numBits = 0;
break;
case PointConversor::NOT_A_NUMBER:
numExponent = exponentMask;
// Could be any non-zero value.
numBits = 1;
break;
}
number = numBits & mantissaMask;
number |= (uint64_t) (numExponent & exponentMask) << mantissaSize;
number |= (uint64_t) this->sign << (mantissaSize + exponentSize);
return number;
}
uint64_t PointConversor::outputGenericFixedRaw(int16_t width, int16_t pointPos, Signedness signedness) const
{
uint64_t number = this->bits;
int16_t numExponent = this->exponent;
uint64_t finalBit = 0;
uint64_t mantissaMask = 0;
uint64_t digitsMask = 0;
uint64_t roundLeft = 0;
uint64_t roundRight = 0;
validateFixedSpec(width, pointPos, signedness);
// Initialize here because width might be invalid.
//
// 0000...01111..111111
digitsMask = ~((uint64_t) 0) >> (MAX_WIDTH - width);
// Gets final significant bit (except for sign).
switch (signedness) {
case UNSIGNED:
finalBit = (uint64_t) 1 << (width - 1);
break;
case TWOS_COMPL:
finalBit = (uint64_t) 1 << (width - 2);
break;
}
// Significant bits mask.
mantissaMask = (finalBit << 1) - 1;
switch (this->normality) {
case NORMAL:
// We need to normalize the exponent to the point position.
while (numExponent > -pointPos) {
// We might need to round the number in the left.
if (number >= finalBit) {
roundLeft = finalBit;
}
numExponent -= 1;
number <<= 1;
}
// If the exponent was not too big, it could be too small.
while (numExponent < -pointPos) {
// In this case, we might need to round by the right.
roundRight = (number & 1) != 0;
numExponent += 1;
number >>= 1;
}
if (number > mantissaMask) {
roundLeft = finalBit;
}
// Potential rounding at left position (most significant).
number |= roundLeft;
// Truncating the number.
number &= mantissaMask;
if (digitsMask != number) {
// But that's ok because we will round right (less significant) it here if required.
number += roundRight;
}
if (this->sign) {
switch (signedness) {
case UNSIGNED:
throw InvalidConversorInput("Formato de saída é sem sinal, mas entrada é negativa.");
case TWOS_COMPL:
// Complementing via 2's complement.
number = (~number + 1) & digitsMask;
break;
}
}
break;
case INFINITY_NAN:
// If infinity, let's just assign it to the greatest value (in magnitude).
number = mantissaMask;
if (this->sign) {
switch (signedness) {
case UNSIGNED:
throw InvalidConversorInput("Formato de saída é sem sinal, mas entrada é negativa.");
case TWOS_COMPL:
// Negative "infinity".
number = ((~number + 1) & digitsMask) - 1;
break;
}
}
break;
case NOT_A_NUMBER:
// NAN is invalid for fixed points. No way to represent?
throw InvalidConversorInput("Entrada é um NAN (Not A Number)");
}
return number;
}
QString PointConversor::outputGenericFloat(uint16_t mantissaSize, uint16_t exponentSize) const
{
uint64_t number = this->outputGenericFloatRaw(mantissaSize, exponentSize);
QString output;
// Simple dummy binary conversion loop :P
for (uint64_t i = mantissaSize + exponentSize + 1; i > 0; i--) {
uint64_t mask = (uint64_t) 1 << (i - 1);
output.append(number & mask ? '1' : '0');
}
return output;
}
QString PointConversor::outputGenericFixed(int16_t width, int16_t pointPos, Signedness signedness) const
{
uint64_t number = this->outputGenericFixedRaw(width, pointPos, signedness);
QString output;
// Before the point.
for (int i = width - 1; i >= pointPos; i--) {
if (i >= 0) {
// Regular bit conversion.
uint64_t mask = (uint64_t) 1 << (uint64_t) i;
output.append(number & mask ? '1' : '0');
} else {
// Append a trailing zero.
output.append('0');
}
}
// Point required because fixed-point format.
output.append('.');
// After the point.
for (int i = pointPos - 1; i >= 0; i--) {
if (i < width) {
// Regular bit conversion.
uint64_t mask = (uint64_t) 1 << (uint64_t) i;
output.append(number & mask ? '1' : '0');
} else {
// Append a trailing zero.
output.append('0');
}
}
return output;
}
// Validation functions
void PointConversor::validateFloatSpec(uint16_t mantissaSize, uint16_t exponentSize) const
{
if (mantissaSize < MIN_MANTISSA_SIZE) {
throw InvalidConversorInput(QString("Tamanho da mantissa não pode ser menor que ") + QString::number(MIN_MANTISSA_SIZE));
}
if (exponentSize < MIN_EXPONENT_SIZE) {
throw InvalidConversorInput(QString("Tamanho do expoente não pode ser menor que ") + QString::number(MIN_EXPONENT_SIZE));
}
if (mantissaSize + exponentSize > MAX_WIDTH - 1) {
throw InvalidConversorInput(
QString("É necessário um bit de sinal, mantissa e expoente juntos devem ser menor que ")
+ QString::number(MAX_WIDTH - 1));
}
}
void PointConversor::validateFixedSpec(int16_t width, int16_t pointPos, Signedness signedness) const
{
if (width < MIN_FIXED_WIDTH) {
throw InvalidConversorInput(QString("Largura não pode ser menor que ") + QString::number(MIN_FIXED_WIDTH));
}
if (width > MAX_WIDTH) {
throw InvalidConversorInput(QString("Largura não pode ser maior que ") + QString::number(MAX_WIDTH));
}
if (pointPos > width || pointPos < 0) {
throw InvalidConversorInput("Ponto fora da quantidade de bits disponíveis.");
}
if (pointPos > width || pointPos < 0) {
throw InvalidConversorInput("Ponto fora da quantidade de bits disponíveis.");
}
}
|
petcomputacaoufrgs/hidracpp
|
src/core/pointconversor.cpp
|
C++
|
gpl-3.0
| 21,532
|
import java.util.ArrayList;
/**
* Write a description of class StrengthPotion here.
*
* @author Jarom Kraus
* @version 2.23.16
*/
@SuppressWarnings("unchecked")
public class StrengthPotion extends Potion{
private ArrayList stats;
public StrengthPotion(String Name){
super(Name);
}
public void drinkStrengthPotion(){
System.out.println("You drink the strength potion and your strength is increased.");
}public ArrayList getStats(){
stats = new ArrayList();
stats.addAll(super.getStats());
return stats;
}
}
|
jaromkraus/RPG
|
RPG/StrengthPotion.java
|
Java
|
gpl-3.0
| 577
|
obj-y += ls.o test.o stat.o cat.o echo.o uptime.o wc.o \
grep.o cp.o rm.o mv.o touch.o mkdir.o history.o \
ps.o pwd.o df.o du.o snake.o ln.o
srec-y += ls.srec test.srec stat.srec cat.srec echo.srec \
uptime.srec wc.srec grep.srec cp.srec rm.srec mv.srec \
touch.srec mkdir.srec history.srec ps.srec pwd.srec \
df.srec du.srec snake.srec ln.srec
ls.srec = ls.o
test.srec = test.o
stat.srec = stat.o
cat.srec = cat.o
echo.srec = echo.o
uptime.srec = uptime.o
wc.srec = wc.o
grep.srec = grep.o
cp.srec = cp.o
rm.srec = rm.o
mv.srec = mv.o
touch.srec = touch.o
mkdir.srec = mkdir.o
history.srec = history.o
ps.srec = ps.o
pwd.srec = pwd.o
df.srec = df.o
du.srec = du.o
snake.srec = snake.o
ln.srec = ln.o
|
halfer53/winix
|
user/commands/Makefile
|
Makefile
|
gpl-3.0
| 710
|
package centralapp.views;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import centralapp.controlers.CentralApp;
/**
* The main window containing all the sub-views
*/
@SuppressWarnings("serial")
public class MainView extends JFrame {
private JTabbedPane tabbedPane;
/**
* Constructor of MainView
*
* @param controler The controlers associated to this view
*/
public MainView(CentralApp controler) {
//GTK theme
/*try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
} catch (Exception e) { }*/
//Ensure to exit the program and not only the window
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 600);
tabbedPane = new JTabbedPane();
getContentPane().add(tabbedPane);
//Just to test
//openCheckInOutTab();
//Set up events
addWindowListener(controler.new ExitEvent());
}
/**
* Add the panel in parameter as a tab of the main window
*
* @param name The tab's name
* @param tab The panel to add
*/
public void addTab(String name, JPanel tab){
tabbedPane.addTab(name, tab);
CentralApp.nbTab++;
}
/**
* Close a tab
*
* @param tabNb The tab id
*/
public void closeTab(int tabNb) {
tabbedPane.remove(tabNb);
}
}
|
Edroxis/DI3_Projet4_Pointeuse
|
src/centralapp/views/MainView.java
|
Java
|
gpl-3.0
| 1,273
|
from __future__ import print_function, division
INLINE_LABEL_STYLE = {
'display': 'inline-block',
}
GRAPH_GLOBAL_CONFIG = {
'displaylogo': False,
'modeBarButtonsToRemove': ['sendDataToCloud'],
}
AXIS_OPTIONS = ({
'label': 'linear',
'value': 'linear',
}, {
'label': 'log',
'value': 'log',
})
ERRORBAR_OPTIONS = ({
'label': 'True',
'value': True,
}, {
'label': 'False',
'value': False,
})
LINE_STYLE = {
'width': 1.0,
}
XLABEL = {
'linear': r'Scattering Vector, $q$ $(\text{\AA}^{-1})$',
'log': r'Scattering Vector, $q$ $(\text{\AA}^{-1}) (log scale)$',
'guinier': r'$q^2$ $(\text{\AA}^{-2})$',
'kratky': r'Scattering Vector, $q$ $(\text{\AA}^{-1})$',
'porod': r'$q^4$ $(\text{\AA}^{-4})$',
'pdf': r'pair distance ($\text{\AA}$)',
}
YLABEL = {
'linear': 'Intensity (arb. units.)',
'log': r'$\log(I)$',
'guinier': r'$\ln(I(q))$',
'kratky': r'$I(q) \cdot q^2$',
'porod': r'$I(q) \cdot q^4$',
'relative_diff': 'Relative Ratio (%)',
'absolute_diff': 'Absolute Difference (arb. units.)',
'error': 'Error',
'error_relative_diff': 'Error Relative Ratio (%)',
'pdf': 'P(r)',
}
TITLE = {
'sasprofile': 'Subtracted Profiles',
'guinier': 'Guinier Profiles',
'kratky': 'Kratky Profiles',
'porod': 'Porod Profiles',
'relative_diff': 'Relative Difference Profiles',
'absolute_diff': 'Absolute Difference Profiles',
'error': 'Error Profile',
'error_relative_diff': 'Error Relative Difference Profile',
'pdf': 'Pair-wise Distribution',
'fitting': 'P(r) Distribution Fitting',
}
|
lqhuang/SAXS-tools
|
dashboard/layouts/style.py
|
Python
|
gpl-3.0
| 1,620
|
/*
* Copyright (C) 2020 <mark@makr.zone>
* inspired and based on work
* Copyright (C) 2011 Jason von Nieda <jason@vonnieda.org>
*
* This file is part of OpenPnP.
*
* OpenPnP 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.
*
* OpenPnP 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 OpenPnP. If not, see
* <http://www.gnu.org/licenses/>.
*
* For more information about OpenPnP visit http://openpnp.org
*/
package org.openpnp.machine.reference.axis.wizards;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import org.openpnp.gui.components.ComponentDecorators;
import org.openpnp.gui.support.AbstractConfigurationWizard;
import org.openpnp.spi.Axis;
import org.openpnp.spi.base.AbstractAxis;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.RowSpec;
@SuppressWarnings("serial")
public abstract class AbstractAxisConfigurationWizard extends AbstractConfigurationWizard {
protected final AbstractAxis axis;
protected JPanel panelProperties;
protected JLabel lblName;
protected JTextField name;
protected JLabel lblType;
protected JComboBox type;
public AbstractAxisConfigurationWizard(AbstractAxis axis) {
super();
this.axis = axis;
panelProperties = new JPanel();
panelProperties.setBorder(new TitledBorder(null, "Properties", TitledBorder.LEADING, TitledBorder.TOP, null, null));
contentPanel.add(panelProperties);
panelProperties.setLayout(new FormLayout(new ColumnSpec[] {
FormSpecs.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(70dlu;default)"),
FormSpecs.RELATED_GAP_COLSPEC,
FormSpecs.DEFAULT_COLSPEC,},
new RowSpec[] {
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,}));
lblType = new JLabel("Type");
panelProperties.add(lblType, "2, 2, right, default");
type = new JComboBox(Axis.Type.values());
panelProperties.add(type, "4, 2, fill, default");
lblName = new JLabel("Name");
panelProperties.add(lblName, "2, 4, right, default");
name = new JTextField();
panelProperties.add(name, "4, 4, fill, default");
name.setColumns(20);
}
protected AbstractAxis getAxis() {
return axis;
}
@Override
public void createBindings() {
addWrappedBinding(axis, "type", type, "selectedItem");
addWrappedBinding(axis, "name", name, "text");
ComponentDecorators.decorateWithAutoSelect(name);
}
}
|
openpnp/openpnp
|
src/main/java/org/openpnp/machine/reference/axis/wizards/AbstractAxisConfigurationWizard.java
|
Java
|
gpl-3.0
| 3,328
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#ifdef __cplusplus
extern "C" { /* C-declarations for C++ */
#endif
extern void lv_draw_pause_message(const PauseMessage msg);
#ifdef __cplusplus
} /* C-declarations for C++ */
#endif
|
1stsetup/Marlin
|
Marlin/src/lcd/extui/lib/mks_ui/draw_pause_message.h
|
C
|
gpl-3.0
| 1,066
|
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<!-- ===========================================================================================
Instituto Municipal de Planeación y Competitividad de Torreón.
Al usar, estudiar y copiar está aceptando los términos de uso de la información y del sitio web:
http://www.trcimplan.gob.mx/terminos/terminos-informacion.html
http://www.trcimplan.gob.mx/terminos/terminos-sitio.html
El software que lo construye está bajo la licencia GPL versión 3. © 2014, 2015, 2016.
Una copia está contenida en el archivo LICENCE al bajar desde GitHub.
Plataforma de Conocimiento https://github.com/guivaloz/PlataformaDeConocimiento
Agradecemos y compartimos las tecnologías abiertas y gratuitas sobre las que se basa:
Morris.js https://morrisjs.github.io/morris.js/
PHP http://php.net
StartBootStrap http://startbootstrap.com
Twitter Bootstrap http://getbootstrap.com
Descargue, aprenda y colabore con este Software Libre:
GitHub IMPLAN Torreón https://github.com/TRCIMPLAN/trcimplan.github.io
=========================================================================================== -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Incluido en el subíndice 'Sociedad Preparada, Incluyente y Sana'. Mide el número de mujeres en la PEA como proporción del total de mujeres en edad de trabajar. De acuerdo con la ENOE, la edad para trabajar empieza a partir de los 14 años.">
<meta name="author" content="Dirección de Investigación Estratégica">
<meta name="keywords" content="IMPLAN, Matamoros, Índice de Competitividad Urbana, Género">
<title>Mujeres en la Fuerza Laboral en Matamoros - IMPLAN Torreón</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-XdYbMnZ/QjLh6iI4ogqCTaIjrFk87ip+ekIjefZch0Y+PvJ8CDYtEs1ipDmPorQ+" crossorigin="anonymous">
<link href="../imagenes/favicon.png" rel="shortcut icon" type="image/x-icon">
<link href="../rss.xml" rel="alternate" type="application/rss+xml" title="IMPLAN Torreón">
<link href="../css/morris.css" rel="stylesheet">
<link href="../css/plugins/metisMenu/metisMenu.min.css" rel="stylesheet">
<link href="../css/sb-admin-2.css" rel="stylesheet">
<link href="../css/plataforma-de-conocimiento.css" rel="stylesheet">
<link href="../css/trcimplan.css" rel="stylesheet">
<link href="http://fonts.googleapis.com/css?family=Questrial|Roboto+Condensed:400,700" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html"><img class="navbar-brand-img" src="../imagenes/implan-barra-logo-chico-gris.png" alt="IMPLAN Torreón"></a>
</div>
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li class="sidebar-search">
<form method="get" id="searchbox_015475140351266618625:04hulmghdys" action="http://www.trcimplan.gob.mx/buscador-resultados.html">
<input type="hidden" value="015475140351266618625:04hulmghdys" name="cx">
<input type="hidden" value="FORID:11" name="cof">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Buscar..." value="" name="s" id="s">
<span class="input-group-btn">
<button class="btn btn-default" type="submit" id="searchsubmit"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</li>
<li><a href="../blog/index.html"><span class="navegacion-icono"><i class="fa fa-lightbulb-o"></i></span> Análisis Publicados</a></li>
<li class="active">
<a href="#"><span class="navegacion-icono"><i class="fa fa-area-chart"></i></span> Indicadores<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="../smi/introduccion.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Introducción al S.M.I.</a></li>
<li><a href="../indicadores-categorias/index.html"><span class="navegacion-icono"><i class="fa fa-th-list"></i></span> Indicadores por Categoría</a></li>
<li><a href="../smi/por-region.html"><span class="navegacion-icono"><i class="fa fa-table"></i></span> Indicadores por Región</a></li>
<li><a href="../smi-georreferenciados/index.html"><span class="navegacion-icono"><i class="fa fa-map-marker"></i></span> Georreferenciados</a></li>
<li><a href="../smi/datos-abiertos.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Datos Abiertos</a></li>
</ul>
</li>
<li>
<a href="#"><span class="navegacion-icono"><i class="fa fa-puzzle-piece"></i></span> IBC Torreón<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="../#"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Introducción</a></li>
<li><a href="../ibc-torreon/index.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Listado de Colonias</a></li>
<li><a href="../#"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Mapa de Colonias</a></li>
<li><a href="../#"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Datos Abiertos</a></li>
</ul>
</li>
<li>
<a href="#"><span class="navegacion-icono"><i class="fa fa-map-marker"></i></span> Información Geográfica<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="../sig/introduccion.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Introducción al S.I.G.</a></li>
<li><a href="../sig-planes/index.html"><span class="navegacion-icono"><i class="fa fa-server"></i></span> Planes</a></li>
<li><a href="../sig-mapas-torreon/index.html"><span class="navegacion-icono"><i class="fa fa-map-marker"></i></span> S.I.G. de Torreón</a></li>
<li><a href="../sig-mapas-torreon/zonificacion-secundaria.html"><span class="navegacion-icono"><i class="fa fa-map-marker"></i></span> Zonificación Secundaria</a></li>
</ul>
</li>
<li>
<a href="#"><span class="navegacion-icono"><i class="fa fa-sun-o"></i></span> Plan Estratégico Metropolitano<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="../plan-estrategico-metropolitano/introduccion.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Qué es el P.E.M.</a></li>
<li><a href="../plan-estrategico-metropolitano/metodologia.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Metodología</a></li>
<li><a href="../plan-estrategico-metropolitano/descripcion-del-proceso.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Descripción del Proceso</a></li>
</ul>
</li>
<li>
<a href="#"><span class="navegacion-icono"><i class="fa fa-check-square"></i></span> Banco de Proyectos<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="../proyectos/proyectos-por-ejes.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Proyectos por Ejes</a></li>
<li><a href="../proyectos/cartera-pem.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Cartera P.E.M.</a></li>
<li><a href="../proyectos/planes-y-programas.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Planes y Programas</a></li>
</ul>
</li>
<li><a href="../investigaciones/index.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Investigaciones</a></li>
<li>
<a href="#"><span class="navegacion-icono"><i class="fa fa-building-o"></i></span> Institucional<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="../institucional/vision-mision.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Visión / Misión</a></li>
<li><a href="../institucional/mensaje-director.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Mensaje del Director</a></li>
<li><a href="../autores/index.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Quienes Somos</a></li>
<li><a href="../institucional/estructura-organica.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Estructura Orgánica</a></li>
<li><a href="../institucional/modelo-operativo-universal.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Modelo Operativo Univ.</a></li>
<li><a href="../institucional/reglamentos.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Reglamentos</a></li>
<li><a href="../institucional/informacion-financiera.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Información Financiera</a></li>
<li><a href="http://www.icai.org.mx:8282/ipo/dependencia.php?dep=178" target="_blank"><span class="navegacion-icono"><i class="fa fa-external-link"></i></span> Transparencia</a></li>
</ul>
</li>
<li><a href="../consejo-directivo/integrantes.html"><span class="navegacion-icono"><i class="fa fa-users"></i></span> Consejo Directivo</a></li>
<li><a href="../sala-prensa/index.html"><span class="navegacion-icono"><i class="fa fa-comments"></i></span> Sala de Prensa</a></li>
<li><a href="../preguntas-frecuentes/preguntas-frecuentes.html"><span class="navegacion-icono"><i class="fa fa-question"></i></span> Preguntas Frecuentes</a></li>
<li>
<a href="#"><span class="navegacion-icono"><i class="fa fa-files-o"></i></span> Términos de Uso<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="../terminos/terminos-informacion.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> De la información</a></li>
<li><a href="../terminos/terminos-sitio.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Del sitio web</a></li>
<li><a href="../terminos/privacidad.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Aviso de Privacidad</a></li>
</ul>
</li>
<li>
<a href="#"><span class="navegacion-icono"><i class="fa fa-phone"></i></span> Contacto<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="../contacto/contacto.html"><span class="navegacion-icono"><i class="fa fa-phone"></i></span> Medios de contacto</a></li>
<li><a href="../#"><span class="navegacion-icono"><i class="fa fa-external-link"></i></span> Comentarios y Sugerencias</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div id="page-wrapper">
<div class="cuerpo">
<article><div itemscope itemtype="http://schema.org/Article">
<div class="encabezado" style="background-color:#CA198A;">
<h1 itemprop="name">Mujeres en la Fuerza Laboral en Matamoros</h1>
<div class="encabezado-descripcion" itemprop="description">Incluido en el subíndice "Sociedad Preparada, Incluyente y Sana". Mide el número de mujeres en la PEA como proporción del total de mujeres en edad de trabajar. De acuerdo con la ENOE, la edad para trabajar empieza a partir de los 14 años.</div>
<div class="encabezado-autor-fecha">
Por <span itemprop="author">Dirección de Investigación Estratégica</span>
- <meta itemprop="datePublished" content="2015-07-14T15:45">14/07/2015 15:45
</div>
</div>
<meta itemprop="image" alt="Mujeres en la Fuerza Laboral en Matamoros" src="../smi/introduccion/imagen.jpg">
<div itemprop="articleBody">
<ul class="nav nav-tabs lenguetas" id="smi-indicador">
<li><a href="#smi-indicador-datos" data-toggle="tab">Datos</a></li>
<li><a href="#smi-indicador-grafica" data-toggle="tab">Gráfica</a></li>
<li><a href="#smi-indicador-otras_regiones" data-toggle="tab">Otras regiones</a></li>
</ul>
<div class="tab-content lengueta-contenido">
<div class="tab-pane" id="smi-indicador-datos">
<h3>Información recopilada</h3>
<table class="table table-hover table-bordered matriz">
<thead>
<tr>
<th>Fecha</th>
<th>Dato</th>
<th>Fuente</th>
<th>Notas</th>
</tr>
</thead>
<tbody>
<tr>
<td>31/12/2008</td>
<td>36.05 %</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2009</td>
<td>42.32 %</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2010</td>
<td>32.13 %</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2011</td>
<td>37.30 %</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>31/12/2012</td>
<td>36.66 %</td>
<td>IMCO</td>
<td></td>
</tr>
</tbody>
</table>
<p><b>Unidad:</b> Mujeres en la PEA como porcentaje del total de mujeres en edad laboral.</p>
<h3>Observaciones</h3>
<p>Fuente: INEGI (ENOE).</p>
</div>
<div class="tab-pane" id="smi-indicador-grafica">
<h3>Gráfica de Mujeres en la Fuerza Laboral en Matamoros</h3>
<div id="graficaDatos" class="grafica"></div>
</div>
<div class="tab-pane" id="smi-indicador-otras_regiones">
<h3>Gráfica con los últimos datos de Mujeres en la Fuerza Laboral</h3>
<div id="graficaOtrasRegiones" class="grafica"></div>
<h3>Últimos datos de Mujeres en la Fuerza Laboral</h3>
<table class="table table-hover table-bordered matriz">
<thead>
<tr>
<th>Región</th>
<th>Fecha</th>
<th>Dato</th>
<th>Fuente</th>
<th>Notas</th>
</tr>
</thead>
<tbody>
<tr>
<td>Torreón</td>
<td>2012-12-31</td>
<td>43.61 %</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>Gómez Palacio</td>
<td>2012-12-31</td>
<td>42.52 %</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>Lerdo</td>
<td>2012-12-31</td>
<td>39.57 %</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>Matamoros</td>
<td>2012-12-31</td>
<td>36.66 %</td>
<td>IMCO</td>
<td></td>
</tr>
<tr>
<td>La Laguna</td>
<td>2012-12-31</td>
<td>42.29 %</td>
<td>IMCO</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<article><div itemprop="contentLocation" itemscope itemtype="http://schema.org/Place"">
<article><div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress"">
<div class="direccion">
<span itemprop="addressLocality">Matamoros</span>, <span itemprop="addressRegion">Coahuila de Zaragoza</span>. <meta itemprop="addressCountry" content="MX">México.
</div>
</div></article>
</div></article>
</div></article>
<div class="contenido-social">
<h5>Compartir en Redes Sociales</h5>
<a href="https://twitter.com/share" class="twitter-share-button" data-via="trcimplan" data-lang="es">Twittear</a>
<iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.trcimplan.gob.mx%2Findicadores-matamoros%2Fsociedad-mujeres-en-la-fuerza-laboral.html&width=300&layout=button_count&action=like&show_faces=true&share=false&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:300px; height:21px;" allowTransparency="true"></iframe>
</div>
</div>
<div class="mapa-inferior">
<div class="row">
<div class="col-md-8">
<a href="../index.html"><img class="img-responsive mapa-inferior-logo" src="../imagenes/implan-transparente-gris.png" alt="IMPLAN Torreón"></a>
</div>
<div class="col-md-4">
<div class="pull-right redes-sociales">
<a class="fa fa-twitter-square" href="http://www.twitter.com/trcimplan" target="_blank"></a>
<a class="fa fa-facebook-square" href="https://facebook.com/trcimplan" target="_blank"></a>
<a class="fa fa-google-plus-square" href="https://plus.google.com/106220426241750550649" target="_blank"></a>
<a class="fa fa-github-square" href="https://github.com/TRCIMPLAN" target="_blank"></a>
<a class="fa fa-rss-square" href="../rss.xml"></a>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="../js/raphael-min.js"></script>
<script src="../js/morris.min.js"></script>
<script src="../js/plugins/metisMenu/metisMenu.min.js"></script>
<script src="../js/sb-admin-2.js"></script>
<script>
// LENGUETA smi-indicador-grafica
$('#smi-indicador a[href="#smi-indicador-grafica"]').on('shown.bs.tab', function(e){
// Gráfica
if (typeof vargraficaDatos === 'undefined') {
vargraficaDatos = Morris.Line({
element: 'graficaDatos',
data: [{ fecha: '2008-12-31', dato: 36.0500 },{ fecha: '2009-12-31', dato: 42.3200 },{ fecha: '2010-12-31', dato: 32.1300 },{ fecha: '2011-12-31', dato: 37.3000 },{ fecha: '2012-12-31', dato: 36.6600 }],
xkey: 'fecha',
ykeys: ['dato'],
labels: ['Dato'],
lineColors: ['#FF5B02'],
xLabelFormat: function(d) { return d.getDate()+'/'+(d.getMonth()+1)+'/'+d.getFullYear(); },
dateFormat: function(ts) { var d = new Date(ts); return d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear(); }
});
}
});
// LENGUETA smi-indicador-otras_regiones
$('#smi-indicador a[href="#smi-indicador-otras_regiones"]').on('shown.bs.tab', function(e){
// Gráfica
if (typeof vargraficaOtrasRegiones === 'undefined') {
vargraficaOtrasRegiones = Morris.Bar({
element: 'graficaOtrasRegiones',
data: [{ region: 'Torreón', dato: 43.6100 },{ region: 'Gómez Palacio', dato: 42.5200 },{ region: 'Lerdo', dato: 39.5700 },{ region: 'Matamoros', dato: 36.6600 },{ region: 'La Laguna', dato: 42.2900 }],
xkey: 'region',
ykeys: ['dato'],
labels: ['Dato'],
barColors: ['#FF5B02']
});
}
});
// TWITTER BOOTSTRAP TABS, ESTABLECER QUE LA LENGÜETA ACTIVA ES smi-indicador-datos
$(document).ready(function(){
$('#smi-indicador a[href="#smi-indicador-datos"]').tab('show')
});
</script>
<script>
// Twitter
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
</script>
<script>
// Google Analytics
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-58290501-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
|
TRCIMPLAN/beta
|
indicadores-matamoros/sociedad-mujeres-en-la-fuerza-laboral.html
|
HTML
|
gpl-3.0
| 21,559
|
package com.github.alexaegis.plane.poligons;
import com.github.alexaegis.plane.Point;
public abstract class RegularPolygon implements Polygon {
protected RegularPolygons type = null;
protected Point center = new Point(0, 0);
protected double edgeLength = 0; // length of the edges
protected double radius = 0; // the radius of the circumscribed circle
protected double apothem = 0; // the radius of the inscribed circle
protected double perimeter = 0;
RegularPolygon() {
}
@Override
public double getArea() {
return 0.5d * apothem * perimeter;
}
@Override
public double getPerimeter() {
return perimeter;
}
@Override
public Point getCenter() {
return new Point(center);
}
@Override
public double diffInPerimArea() {
return Math.abs(getArea() - getPerimeter());
}
@Override
public void show() {
System.out.println(toString());
}
@Override
public String toString() {
return "Regular Polygon{" +
"type = " + type.getName() +
", vertices = " + Integer.toString(type.getVertices() - 1) +
", center = " + center.toString() +
", edgeLength = " + edgeLength +
", radius = " + radius +
", apothem = " + apothem +
", area = " + getArea() +
", perimeter = " + perimeter +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RegularPolygon that = (RegularPolygon) o;
if (Double.compare(that.edgeLength, edgeLength) != 0) return false;
if (Double.compare(that.radius, radius) != 0) return false;
if (Double.compare(that.apothem, apothem) != 0) return false;
if (Double.compare(that.perimeter, perimeter) != 0) return false;
if (type != that.type) return false;
if (center != null ? !center.equals(that.center) : that.center != null) return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = type != null ? type.hashCode() : 0;
result = 31 * result + (center != null ? center.hashCode() : 0);
temp = Double.doubleToLongBits(edgeLength);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(radius);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(apothem);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(perimeter);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
|
AlexAegis/elte-progtech-1
|
submission1/src/main/java/com/github/alexaegis/plane/poligons/RegularPolygon.java
|
Java
|
gpl-3.0
| 2,838
|
/*******************************************************************************
* HellFirePvP / Astral Sorcery 2017
*
* This project is licensed under GNU GENERAL PUBLIC LICENSE Version 3.
* The source code is available on github: https://github.com/HellFirePvP/AstralSorcery
* For further details, see the License file there.
******************************************************************************/
package hellfirepvp.astralsorcery.common.base;
import hellfirepvp.astralsorcery.common.constellation.effect.GenListEntries;
import hellfirepvp.astralsorcery.common.util.BlockStateCheck;
import hellfirepvp.astralsorcery.common.util.ItemUtils;
import hellfirepvp.astralsorcery.common.util.MiscUtils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* This class is part of the Astral Sorcery Mod
* The complete source code for this mod can be found on github.
* Class: WorldMeltables
* Created by HellFirePvP
* Date: 31.10.2016 / 22:49
*/
public enum WorldMeltables implements MeltInteraction {
COBBLE( new BlockStateCheck.Block(Blocks.COBBLESTONE), Blocks.FLOWING_LAVA.getDefaultState(), 180),
STONE( new BlockStateCheck.Block(Blocks.STONE), Blocks.FLOWING_LAVA.getDefaultState(), 100),
OBSIDIAN( new BlockStateCheck.Block(Blocks.OBSIDIAN), Blocks.FLOWING_LAVA.getDefaultState(), 75),
NETHERRACK( new BlockStateCheck.Block(Blocks.NETHERRACK), Blocks.FLOWING_LAVA.getDefaultState(), 40),
NETHERBRICK(new BlockStateCheck.Block(Blocks.NETHER_BRICK), Blocks.FLOWING_LAVA.getDefaultState(), 60),
MAGMA( new BlockStateCheck.Block(Blocks.MAGMA), Blocks.FLOWING_LAVA.getDefaultState(), 1),
ICE( new BlockStateCheck.Block(Blocks.ICE), Blocks.FLOWING_WATER.getDefaultState(), 1),
FROSTED_ICE(new BlockStateCheck.Block(Blocks.FROSTED_ICE), Blocks.FLOWING_WATER.getDefaultState(), 1),
PACKED_ICE( new BlockStateCheck.Block(Blocks.PACKED_ICE), Blocks.FLOWING_WATER.getDefaultState(), 2);
private final BlockStateCheck meltableCheck;
private final IBlockState meltResult;
private final int meltDuration;
private WorldMeltables(BlockStateCheck meltableCheck, IBlockState meltResult, int meltDuration) {
this.meltableCheck = meltableCheck;
this.meltResult = meltResult;
this.meltDuration = meltDuration;
}
@Override
public boolean isMeltable(World world, BlockPos pos, IBlockState worldState) {
return meltableCheck.isStateValid(world, pos, worldState);
}
@Override
@Nullable
public IBlockState getMeltResultState() {
return meltResult;
}
@Override
@Nonnull
public ItemStack getMeltResultStack() {
return ItemStack.EMPTY;
}
@Override
public int getMeltTickDuration() {
return meltDuration;
}
@Nullable
public static MeltInteraction getMeltable(World world, BlockPos pos) {
IBlockState state = world.getBlockState(pos);
for (WorldMeltables melt : values()) {
if(melt.isMeltable(world, pos, state))
return melt;
}
ItemStack stack = ItemUtils.createBlockStack(state);
if(!stack.isEmpty()) {
ItemStack out = FurnaceRecipes.instance().getSmeltingResult(stack);
if(!out.isEmpty()) {
return new FurnaceRecipeInteraction(state, out);
}
}
return null;
}
public static class ActiveMeltableEntry extends GenListEntries.CounterListEntry {
public ActiveMeltableEntry(BlockPos pos) {
super(pos);
}
public boolean isValid(World world, boolean forceLoad) {
if(!forceLoad && !MiscUtils.isChunkLoaded(world, new ChunkPos(getPos()))) return true;
return getMeltable(world) != null;
}
public MeltInteraction getMeltable(World world) {
return WorldMeltables.getMeltable(world, getPos());
}
}
public static class FurnaceRecipeInteraction implements MeltInteraction {
private final ItemStack out;
private final BlockStateCheck.Meta matchInState;
public FurnaceRecipeInteraction(IBlockState inState, ItemStack outStack) {
this.matchInState = new BlockStateCheck.Meta(inState.getBlock(), inState.getBlock().getMetaFromState(inState));
this.out = outStack;
}
@Override
public boolean isMeltable(World world, BlockPos pos, IBlockState state) {
return matchInState.isStateValid(world, pos, state);
}
@Nullable
@Override
public IBlockState getMeltResultState() {
return ItemUtils.createBlockState(out);
}
@Nonnull
@Override
public ItemStack getMeltResultStack() {
return out;
}
}
}
|
Saereth/AstralSorcery
|
src/main/java/hellfirepvp/astralsorcery/common/base/WorldMeltables.java
|
Java
|
gpl-3.0
| 5,184
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="generator" content="ApiGen 2.8.0">
<title>No package</title>
<script type="text/javascript" src="resources/combined.js?3770084987"></script>
<script type="text/javascript" src="elementlist.js?163924357"></script>
<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360">
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Packages</h3>
<ul>
<li><a href="package-app.html">app<span></span></a>
<ul>
<li><a href="package-app.Config.html">Config<span></span></a>
<ul>
<li><a href="package-app.Config.Schema.html">Schema</a>
</li>
</ul></li>
<li><a href="package-app.Console.html">Console<span></span></a>
<ul>
<li><a href="package-app.Console.Command.html">Command</a>
</li>
</ul></li>
<li><a href="package-app.Controller.html">Controller</a>
</li>
<li><a href="package-app.Model.html">Model</a>
</li>
<li><a href="package-app.View.html">View<span></span></a>
<ul>
<li><a href="package-app.View.Helper.html">Helper</a>
</li>
</ul></li></ul></li>
<li class="active"><a href="package-None.html">None</a>
</li>
</ul>
</div>
<hr>
<div id="elements">
<h3>Classes</h3>
<ul>
<li><a href="class-AllDebugKitTest.html">AllDebugKitTest</a></li>
<li><a href="class-AllDebugKitViewTest.html">AllDebugKitViewTest</a></li>
<li><a href="class-AllDebugKitWithoutViewTest.html">AllDebugKitWithoutViewTest</a></li>
<li><a href="class-AllTestsTest.html">AllTestsTest</a></li>
<li><a href="class-BenchmarkShell.html">BenchmarkShell</a></li>
<li><a href="class-DebugKitAppController.html">DebugKitAppController</a></li>
<li><a href="class-DebugKitAppModel.html">DebugKitAppModel</a></li>
<li><a href="class-DebugKitDebugger.html">DebugKitDebugger</a></li>
<li><a href="class-DebugKitDebuggerTest.html">DebugKitDebuggerTest</a></li>
<li><a href="class-DebugKitGroupTestCase.html">DebugKitGroupTestCase</a></li>
<li><a href="class-DebugKitLog.html">DebugKitLog</a></li>
<li><a href="class-DebugKitTestController.html">DebugKitTestController</a></li>
<li><a href="class-DebugMemory.html">DebugMemory</a></li>
<li><a href="class-DebugMemoryTest.html">DebugMemoryTest</a></li>
<li><a href="class-DebugPanel.html">DebugPanel</a></li>
<li><a href="class-DebugTimer.html">DebugTimer</a></li>
<li><a href="class-DebugTimerHelper.html">DebugTimerHelper</a></li>
<li><a href="class-DebugTimerTest.html">DebugTimerTest</a></li>
<li><a href="class-DocFixture.html">DocFixture</a></li>
<li><a href="class-DocsControllerTest.html">DocsControllerTest</a></li>
<li><a href="class-DocStatusesControllerTest.html">DocStatusesControllerTest</a></li>
<li><a href="class-DocStatusFixture.html">DocStatusFixture</a></li>
<li><a href="class-DocStatusTest.html">DocStatusTest</a></li>
<li><a href="class-DocSubtypeFixture.html">DocSubtypeFixture</a></li>
<li><a href="class-DocSubtypesControllerTest.html">DocSubtypesControllerTest</a></li>
<li><a href="class-DocSubtypeTest.html">DocSubtypeTest</a></li>
<li><a href="class-DocTest.html">DocTest</a></li>
<li><a href="class-DocTypeFixture.html">DocTypeFixture</a></li>
<li><a href="class-DocTypesControllerTest.html">DocTypesControllerTest</a></li>
<li><a href="class-DocTypeTest.html">DocTypeTest</a></li>
<li><a href="class-EnvironmentPanel.html">EnvironmentPanel</a></li>
<li><a href="class-FacilitiesControllerTest.html">FacilitiesControllerTest</a></li>
<li><a href="class-FacilityFixture.html">FacilityFixture</a></li>
<li><a href="class-FacilityTest.html">FacilityTest</a></li>
<li><a href="class-FireCake.html">FireCake</a></li>
<li><a href="class-FireCakeTestCase.html">FireCakeTestCase</a></li>
<li><a href="class-FirePhpToolbarHelper.html">FirePhpToolbarHelper</a></li>
<li><a href="class-FirePhpToolbarHelperTestCase.html">FirePhpToolbarHelperTestCase</a></li>
<li><a href="class-HistoryPanel.html">HistoryPanel</a></li>
<li><a href="class-HtmlToolbarHelper.html">HtmlToolbarHelper</a></li>
<li><a href="class-HtmlToolbarHelperTestCase.html">HtmlToolbarHelperTestCase</a></li>
<li><a href="class-IncludePanel.html">IncludePanel</a></li>
<li><a href="class-LogPanel.html">LogPanel</a></li>
<li><a href="class-LogPanelTest.html">LogPanelTest</a></li>
<li><a href="class-MockBackendHelper.html">MockBackendHelper</a></li>
<li><a href="class-NotificationFixture.html">NotificationFixture</a></li>
<li><a href="class-NotificationsControllerTest.html">NotificationsControllerTest</a></li>
<li><a href="class-NotificationTest.html">NotificationTest</a></li>
<li><a href="class-PluginTestPanel.html">PluginTestPanel</a></li>
<li><a href="class-RequestPanel.html">RequestPanel</a></li>
<li><a href="class-ResponseFixture.html">ResponseFixture</a></li>
<li><a href="class-ResponsesControllerTest.html">ResponsesControllerTest</a></li>
<li><a href="class-ResponseTest.html">ResponseTest</a></li>
<li><a href="class-Revision.html" class="invalid">Revision</a></li>
<li><a href="class-RevisionFixture.html">RevisionFixture</a></li>
<li><a href="class-RevisionsControllerTest.html">RevisionsControllerTest</a></li>
<li><a href="class-RevisionTest.html">RevisionTest</a></li>
<li><a href="class-RoleFixture.html">RoleFixture</a></li>
<li><a href="class-RolesControllerTest.html">RolesControllerTest</a></li>
<li><a href="class-RoleTest.html">RoleTest</a></li>
<li><a href="class-RouteListEntriesControllerTest.html">RouteListEntriesControllerTest</a></li>
<li><a href="class-RouteListEntryFixture.html">RouteListEntryFixture</a></li>
<li><a href="class-RouteListEntryTest.html">RouteListEntryTest</a></li>
<li><a href="class-RouteListFixture.html">RouteListFixture</a></li>
<li><a href="class-RouteListsController.html">RouteListsController</a></li>
<li><a href="class-RouteListsControllerTest.html">RouteListsControllerTest</a></li>
<li><a href="class-RouteListTest.html">RouteListTest</a></li>
<li><a href="class-SessionPanel.html">SessionPanel</a></li>
<li><a href="class-SimpleGraphHelper.html">SimpleGraphHelper</a></li>
<li><a href="class-SqlLogPanel.html">SqlLogPanel</a></li>
<li><a href="class-SqlLogPanelTest.html">SqlLogPanelTest</a></li>
<li><a href="class-Test.html">Test</a></li>
<li><a href="class-TestFireCake.html">TestFireCake</a></li>
<li><a href="class-TestFixture.html">TestFixture</a></li>
<li><a href="class-TestPanel.html">TestPanel</a></li>
<li><a href="class-TestsControllerTest.html">TestsControllerTest</a></li>
<li><a href="class-TestTest.html">TestTest</a></li>
<li><a href="class-TestToolbarComponent.html">TestToolbarComponent</a></li>
<li><a href="class-TidyHelper.html">TidyHelper</a></li>
<li><a href="class-TimedBehavior.html">TimedBehavior</a></li>
<li><a href="class-TimedBehaviorTestCase.html">TimedBehaviorTestCase</a></li>
<li><a href="class-TimerPanel.html">TimerPanel</a></li>
<li><a href="class-ToolbarAccess.html">ToolbarAccess</a></li>
<li><a href="class-ToolbarAccessController.html">ToolbarAccessController</a></li>
<li><a href="class-ToolbarAccessTestCase.html">ToolbarAccessTestCase</a></li>
<li><a href="class-ToolbarComponent.html">ToolbarComponent</a></li>
<li><a href="class-ToolbarComponentTestCase.html">ToolbarComponentTestCase</a></li>
<li><a href="class-ToolbarHelper.html">ToolbarHelper</a></li>
<li><a href="class-ToolbarHelperTestCase.html">ToolbarHelperTestCase</a></li>
<li><a href="class-UserFixture.html">UserFixture</a></li>
<li><a href="class-UsersControllerTest.html">UsersControllerTest</a></li>
<li><a href="class-UserTest.html">UserTest</a></li>
<li><a href="class-VariablesPanel.html">VariablesPanel</a></li>
<li><a href="class-WhitespaceShell.html">WhitespaceShell</a></li>
</ul>
<h3>Functions</h3>
<ul>
<li><a href="function-firecake.html">firecake</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="">
<input type="hidden" name="ie" value="UTF-8">
<input type="text" name="q" class="text">
<input type="submit" value="Search">
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li class="active">
<span>Package</span> </li>
<li>
<span>Class</span> </li>
</ul>
<ul>
<li>
<a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a>
</li>
</ul>
<ul>
</ul>
</div>
<div id="content" class="package">
<h1>No package</h1>
<table class="summary" id="classes">
<caption>Classes summary</caption>
<tr>
<td class="name"><a href="class-AllDebugKitTest.html">AllDebugKitTest</a></td>
<td>DebugKitViewTestSuite class</td>
</tr>
<tr>
<td class="name"><a href="class-AllDebugKitViewTest.html">AllDebugKitViewTest</a></td>
<td>DebugKitViewTestSuite class</td>
</tr>
<tr>
<td class="name"><a href="class-AllDebugKitWithoutViewTest.html">AllDebugKitWithoutViewTest</a></td>
<td>DebugKitViewTestSuite class</td>
</tr>
<tr>
<td class="name"><a href="class-AllTestsTest.html">AllTestsTest</a></td>
<td>AllTestsTest class</td>
</tr>
<tr>
<td class="name"><a href="class-BenchmarkShell.html">BenchmarkShell</a></td>
<td>Benchmark Shell Class</td>
</tr>
<tr>
<td class="name"><a href="class-DebugKitAppController.html">DebugKitAppController</a></td>
<td>Class DebugKitAppController</td>
</tr>
<tr>
<td class="name"><a href="class-DebugKitAppModel.html">DebugKitAppModel</a></td>
<td>Class DebugKitAppModel</td>
</tr>
<tr>
<td class="name"><a href="class-DebugKitDebugger.html">DebugKitDebugger</a></td>
<td>DebugKit Temporary Debugger Class</td>
</tr>
<tr>
<td class="name"><a href="class-DebugKitDebuggerTest.html">DebugKitDebuggerTest</a></td>
<td>Test case for the DebugKitDebugger</td>
</tr>
<tr>
<td class="name"><a href="class-DebugKitGroupTestCase.html">DebugKitGroupTestCase</a></td>
<td>Class DebugKitGroupTestCase</td>
</tr>
<tr>
<td class="name"><a href="class-DebugKitLog.html">DebugKitLog</a></td>
<td>A CakeLog listener which saves having to munge files or other configured
loggers.</td>
</tr>
<tr>
<td class="name"><a href="class-DebugKitTestController.html">DebugKitTestController</a></td>
<td>Class DebugKitTestController</td>
</tr>
<tr>
<td class="name"><a href="class-DebugMemory.html">DebugMemory</a></td>
<td>Contains methods for Profiling memory usage.</td>
</tr>
<tr>
<td class="name"><a href="class-DebugMemoryTest.html">DebugMemoryTest</a></td>
<td>Class DebugMemoryTest</td>
</tr>
<tr>
<td class="name"><a href="class-DebugPanel.html">DebugPanel</a></td>
<td>Base class for debug panels.</td>
</tr>
<tr>
<td class="name"><a href="class-DebugTimer.html">DebugTimer</a></td>
<td>Contains methods for Profiling and creating timers.</td>
</tr>
<tr>
<td class="name"><a href="class-DebugTimerHelper.html">DebugTimerHelper</a></td>
<td>Class DebugTimerHelper</td>
</tr>
<tr>
<td class="name"><a href="class-DebugTimerTest.html">DebugTimerTest</a></td>
<td>Class DebugTimerTest</td>
</tr>
<tr>
<td class="name"><a href="class-DocFixture.html">DocFixture</a></td>
<td>DocFixture</td>
</tr>
<tr>
<td class="name"><a href="class-DocsControllerTest.html">DocsControllerTest</a></td>
<td>DocsController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-DocStatusesControllerTest.html">DocStatusesControllerTest</a></td>
<td>DocStatusesController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-DocStatusFixture.html">DocStatusFixture</a></td>
<td>DocStatusFixture</td>
</tr>
<tr>
<td class="name"><a href="class-DocStatusTest.html">DocStatusTest</a></td>
<td>DocStatus Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-DocSubtypeFixture.html">DocSubtypeFixture</a></td>
<td>DocSubtypeFixture</td>
</tr>
<tr>
<td class="name"><a href="class-DocSubtypesControllerTest.html">DocSubtypesControllerTest</a></td>
<td>DocSubtypesController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-DocSubtypeTest.html">DocSubtypeTest</a></td>
<td>DocSubtype Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-DocTest.html">DocTest</a></td>
<td>Doc Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-DocTypeFixture.html">DocTypeFixture</a></td>
<td>DocTypeFixture</td>
</tr>
<tr>
<td class="name"><a href="class-DocTypesControllerTest.html">DocTypesControllerTest</a></td>
<td>DocTypesController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-DocTypeTest.html">DocTypeTest</a></td>
<td>DocType Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-EnvironmentPanel.html">EnvironmentPanel</a></td>
<td>Provides information about your PHP and CakePHP environment to assist with
debugging.</td>
</tr>
<tr>
<td class="name"><a href="class-FacilitiesControllerTest.html">FacilitiesControllerTest</a></td>
<td>FacilitiesController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-FacilityFixture.html">FacilityFixture</a></td>
<td>FacilityFixture</td>
</tr>
<tr>
<td class="name"><a href="class-FacilityTest.html">FacilityTest</a></td>
<td>Facility Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-FireCake.html">FireCake</a></td>
<td>FirePHP Class for CakePHP</td>
</tr>
<tr>
<td class="name"><a href="class-FireCakeTestCase.html">FireCakeTestCase</a></td>
<td>Test Case For FireCake</td>
</tr>
<tr>
<td class="name"><a href="class-FirePhpToolbarHelper.html">FirePhpToolbarHelper</a></td>
<td>FirePHP Toolbar Helper</td>
</tr>
<tr>
<td class="name"><a href="class-FirePhpToolbarHelperTestCase.html">FirePhpToolbarHelperTestCase</a></td>
<td>Class FirePhpToolbarHelperTestCase</td>
</tr>
<tr>
<td class="name"><a href="class-HistoryPanel.html">HistoryPanel</a></td>
<td>Provides debug information on previous requests.</td>
</tr>
<tr>
<td class="name"><a href="class-HtmlToolbarHelper.html">HtmlToolbarHelper</a></td>
<td>Html Toolbar Helper</td>
</tr>
<tr>
<td class="name"><a href="class-HtmlToolbarHelperTestCase.html">HtmlToolbarHelperTestCase</a></td>
<td>Class HtmlToolbarHelperTestCase</td>
</tr>
<tr>
<td class="name"><a href="class-IncludePanel.html">IncludePanel</a></td>
<td>Provides a list of included files for the current request</td>
</tr>
<tr>
<td class="name"><a href="class-LogPanel.html">LogPanel</a></td>
<td>Log Panel - Reads log entries made this request.</td>
</tr>
<tr>
<td class="name"><a href="class-LogPanelTest.html">LogPanelTest</a></td>
<td>Class LogPanelTest</td>
</tr>
<tr>
<td class="name"><a href="class-MockBackendHelper.html">MockBackendHelper</a></td>
<td>Class MockBackendHelper</td>
</tr>
<tr>
<td class="name"><a href="class-NotificationFixture.html">NotificationFixture</a></td>
<td>NotificationFixture</td>
</tr>
<tr>
<td class="name"><a href="class-NotificationsControllerTest.html">NotificationsControllerTest</a></td>
<td>NotificationsController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-NotificationTest.html">NotificationTest</a></td>
<td>Notification Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-PluginTestPanel.html">PluginTestPanel</a></td>
<td>Class PluginTestPanel</td>
</tr>
<tr>
<td class="name"><a href="class-RequestPanel.html">RequestPanel</a></td>
<td>Provides debug information on the Current request params.</td>
</tr>
<tr>
<td class="name"><a href="class-ResponseFixture.html">ResponseFixture</a></td>
<td>ResponseFixture</td>
</tr>
<tr>
<td class="name"><a href="class-ResponsesControllerTest.html">ResponsesControllerTest</a></td>
<td>ResponsesController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-ResponseTest.html">ResponseTest</a></td>
<td>Response Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-Revision.html" class="invalid">Revision</a></td>
<td></td>
</tr>
<tr>
<td class="name"><a href="class-RevisionFixture.html">RevisionFixture</a></td>
<td>RevisionFixture</td>
</tr>
<tr>
<td class="name"><a href="class-RevisionsControllerTest.html">RevisionsControllerTest</a></td>
<td>RevisionsController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-RevisionTest.html">RevisionTest</a></td>
<td>Revision Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-RoleFixture.html">RoleFixture</a></td>
<td>RoleFixture</td>
</tr>
<tr>
<td class="name"><a href="class-RolesControllerTest.html">RolesControllerTest</a></td>
<td>RolesController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-RoleTest.html">RoleTest</a></td>
<td>Role Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-RouteListEntriesControllerTest.html">RouteListEntriesControllerTest</a></td>
<td>RouteListEntriesController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-RouteListEntryFixture.html">RouteListEntryFixture</a></td>
<td>RouteListEntryFixture</td>
</tr>
<tr>
<td class="name"><a href="class-RouteListEntryTest.html">RouteListEntryTest</a></td>
<td>RouteListEntry Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-RouteListFixture.html">RouteListFixture</a></td>
<td>RouteListFixture</td>
</tr>
<tr>
<td class="name"><a href="class-RouteListsController.html">RouteListsController</a></td>
<td>RouteLists Controller</td>
</tr>
<tr>
<td class="name"><a href="class-RouteListsControllerTest.html">RouteListsControllerTest</a></td>
<td>RouteListsController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-RouteListTest.html">RouteListTest</a></td>
<td>RouteList Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-SessionPanel.html">SessionPanel</a></td>
<td>Provides debug information on the Session contents.</td>
</tr>
<tr>
<td class="name"><a href="class-SimpleGraphHelper.html">SimpleGraphHelper</a></td>
<td>Class SimpleGraphHelper</td>
</tr>
<tr>
<td class="name"><a href="class-SqlLogPanel.html">SqlLogPanel</a></td>
<td>Provides debug information on the SQL logs and provides links to an ajax explain
interface.</td>
</tr>
<tr>
<td class="name"><a href="class-SqlLogPanelTest.html">SqlLogPanelTest</a></td>
<td>Class SqlLogPanelTest</td>
</tr>
<tr>
<td class="name"><a href="class-Test.html">Test</a></td>
<td>Test Model</td>
</tr>
<tr>
<td class="name"><a href="class-TestFireCake.html">TestFireCake</a></td>
<td>TestFireCake class allows for testing of FireCake</td>
</tr>
<tr>
<td class="name"><a href="class-TestFixture.html">TestFixture</a></td>
<td>TestFixture</td>
</tr>
<tr>
<td class="name"><a href="class-TestPanel.html">TestPanel</a></td>
<td>Class TestPanel</td>
</tr>
<tr>
<td class="name"><a href="class-TestsControllerTest.html">TestsControllerTest</a></td>
<td>TestsController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-TestTest.html">TestTest</a></td>
<td>Test Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-TestToolbarComponent.html">TestToolbarComponent</a></td>
<td>Class TestToolbarComponent</td>
</tr>
<tr>
<td class="name"><a href="class-TidyHelper.html">TidyHelper</a></td>
<td>TidyHelper class</td>
</tr>
<tr>
<td class="name"><a href="class-TimedBehavior.html">TimedBehavior</a></td>
<td>Class TimedBehavior</td>
</tr>
<tr>
<td class="name"><a href="class-TimedBehaviorTestCase.html">TimedBehaviorTestCase</a></td>
<td>Class TimedBehaviorTestCase</td>
</tr>
<tr>
<td class="name"><a href="class-TimerPanel.html">TimerPanel</a></td>
<td>Provides debug information on all timers used in a request.</td>
</tr>
<tr>
<td class="name"><a href="class-ToolbarAccess.html">ToolbarAccess</a></td>
<td>Class ToolbarAccess</td>
</tr>
<tr>
<td class="name"><a href="class-ToolbarAccessController.html">ToolbarAccessController</a></td>
<td>DebugKit ToolbarAccess Controller</td>
</tr>
<tr>
<td class="name"><a href="class-ToolbarAccessTestCase.html">ToolbarAccessTestCase</a></td>
<td>Test case for ToolbarAccess model</td>
</tr>
<tr>
<td class="name"><a href="class-ToolbarComponent.html">ToolbarComponent</a></td>
<td>Class ToolbarComponent</td>
</tr>
<tr>
<td class="name"><a href="class-ToolbarComponentTestCase.html">ToolbarComponentTestCase</a></td>
<td>ToolbarComponentTestCase Test case</td>
</tr>
<tr>
<td class="name"><a href="class-ToolbarHelper.html">ToolbarHelper</a></td>
<td>Provides Base methods for content specific debug toolbar helpers. Acts as a
facade for other toolbars helpers as well.</td>
</tr>
<tr>
<td class="name"><a href="class-ToolbarHelperTestCase.html">ToolbarHelperTestCase</a></td>
<td>Class ToolbarHelperTestCase</td>
</tr>
<tr>
<td class="name"><a href="class-UserFixture.html">UserFixture</a></td>
<td>UserFixture</td>
</tr>
<tr>
<td class="name"><a href="class-UsersControllerTest.html">UsersControllerTest</a></td>
<td>UsersController Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-UserTest.html">UserTest</a></td>
<td>User Test Case</td>
</tr>
<tr>
<td class="name"><a href="class-VariablesPanel.html">VariablesPanel</a></td>
<td>Provides debug information on the View variables.</td>
</tr>
<tr>
<td class="name"><a href="class-WhitespaceShell.html">WhitespaceShell</a></td>
<td>Whitespace shell. Helps find and trim whitespace from files.</td>
</tr>
</table>
<table class="summary" id="functions">
<caption>Functions summary</caption>
<tr>
<td class="name"><a href="function-firecake.html">firecake</a></td>
<td>Procedural version of FireCake::log()</td>
</tr>
</table>
</div>
<div id="footer">
API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a>
</div>
</div>
</div>
</body>
</html>
|
jones139/hdms
|
doc/api/package-None.html
|
HTML
|
gpl-3.0
| 21,944
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.3 on 2016-07-01 17:09
from __future__ import unicode_literals
from django.db import migrations
import django_fsm
class Migration(migrations.Migration):
dependencies = [
('invoice', '0002_billordering'),
]
operations = [
migrations.AlterField(
model_name='bill',
name='status',
field=django_fsm.FSMIntegerField(choices=[(0, 'building'), (1, 'valid'), (2, 'cancel'), (3, 'archive')], db_index=True, default=0, verbose_name='status'),
),
]
|
Diacamma2/financial
|
diacamma/invoice/migrations/0003_bill_status.py
|
Python
|
gpl-3.0
| 568
|
program checkfiles
integer, parameter :: n = 10340
integer, parameter :: p = 4
integer a(p,n)
integer b(p,n)
real*8 da(p,n)
real*8 db(p,n)
read(200,*) a
read(201,*) da
open(unit=1,file='adtInts.dat',form='formatted')
read(1,*) b
close(1)
open(unit=1,file='adtReals.dat',form='formatted')
read(1,*) db
close(1)
isum=0
dsum=0
do i=1,n
do j=1,p
isum=isum+abs(a(j,i)-b(j,i)-1)
dsum=dsum+abs(da(j,i)-db(j,i))
enddo
enddo
write(6,*) isum
write(6,*) dsum
end
|
JacobCrabill/FlurryPP
|
lib/tioga/driver/checkfiles.f90
|
FORTRAN
|
gpl-3.0
| 488
|
/* News.c generated by valac 0.20.1, the Vala compiler
* generated from News.vala, do not modify */
#include <glib.h>
#include <glib-object.h>
#include <clutter/clutter.h>
#include <gio/gio.h>
#include <libsoup/soup.h>
#include <stdlib.h>
#include <string.h>
#include <glib/gi18n-lib.h>
#include <float.h>
#include <math.h>
#define TYPE_SERVICE (service_get_type ())
#define SERVICE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), TYPE_SERVICE, Service))
#define SERVICE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), TYPE_SERVICE, ServiceClass))
#define IS_SERVICE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), TYPE_SERVICE))
#define IS_SERVICE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), TYPE_SERVICE))
#define SERVICE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), TYPE_SERVICE, ServiceClass))
typedef struct _Service Service;
typedef struct _ServiceClass ServiceClass;
typedef struct _ServicePrivate ServicePrivate;
#define TYPE_NEWS (news_get_type ())
#define NEWS(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), TYPE_NEWS, News))
#define NEWS_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), TYPE_NEWS, NewsClass))
#define IS_NEWS(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), TYPE_NEWS))
#define IS_NEWS_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), TYPE_NEWS))
#define NEWS_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), TYPE_NEWS, NewsClass))
typedef struct _News News;
typedef struct _NewsClass NewsClass;
typedef struct _NewsPrivate NewsPrivate;
#define TYPE_SHADOWED_LABEL (shadowed_label_get_type ())
#define SHADOWED_LABEL(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), TYPE_SHADOWED_LABEL, ShadowedLabel))
#define SHADOWED_LABEL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), TYPE_SHADOWED_LABEL, ShadowedLabelClass))
#define IS_SHADOWED_LABEL(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), TYPE_SHADOWED_LABEL))
#define IS_SHADOWED_LABEL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), TYPE_SHADOWED_LABEL))
#define SHADOWED_LABEL_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), TYPE_SHADOWED_LABEL, ShadowedLabelClass))
typedef struct _ShadowedLabel ShadowedLabel;
typedef struct _ShadowedLabelClass ShadowedLabelClass;
#define NEWS_TYPE_NEWS (news_news_get_type ())
typedef struct _NewsNews NewsNews;
#define _g_object_unref0(var) ((var == NULL) ? NULL : (var = (g_object_unref (var), NULL)))
#define _g_error_free0(var) ((var == NULL) ? NULL : (var = (g_error_free (var), NULL)))
#define __g_list_free__g_free0_0(var) ((var == NULL) ? NULL : (var = (_g_list_free__g_free0_ (var), NULL)))
#define _g_free0(var) (var = (g_free (var), NULL))
struct _Service {
ClutterActor parent_instance;
ServicePrivate * priv;
};
struct _ServiceClass {
ClutterActorClass parent_class;
void (*create) (Service* self);
gboolean (*update) (Service* self);
};
struct _News {
Service parent_instance;
NewsPrivate * priv;
};
struct _NewsClass {
ServiceClass parent_class;
};
struct _NewsNews {
gchar* title;
gchar* url;
};
struct _NewsPrivate {
GSettings* settings;
SoupSession* session;
SoupMessage* message;
ShadowedLabel* label_list;
ShadowedLabel* reload;
NewsNews* news;
gint news_length1;
gint _news_size_;
};
static gpointer news_parent_class = NULL;
GType service_get_type (void) G_GNUC_CONST;
GType news_get_type (void) G_GNUC_CONST;
GType shadowed_label_get_type (void) G_GNUC_CONST;
static GType news_news_get_type (void) G_GNUC_CONST G_GNUC_UNUSED;
static NewsNews* news_news_dup (const NewsNews* self);
static void news_news_free (NewsNews* self);
static void news_news_copy (const NewsNews* self, NewsNews* dest);
static void news_news_destroy (NewsNews* self);
#define NEWS_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), TYPE_NEWS, NewsPrivate))
enum {
NEWS_DUMMY_PROPERTY
};
static void _vala_NewsNews_array_free (NewsNews* array, gint array_length);
News* news_new (void);
News* news_construct (GType object_type);
Service* service_construct (GType object_type, const gchar* _id);
ShadowedLabel* service_get_reload_label (Service* self, const gchar* service_name);
ShadowedLabel* shadowed_label_new (const gchar* _label);
ShadowedLabel* shadowed_label_construct (GType object_type, const gchar* _label);
static gboolean __lambda14_ (News* self, ClutterButtonEvent* e);
static void _g_free0_ (gpointer var);
static void _g_list_free__g_free0_ (GList* self);
static gboolean ___lambda14__clutter_actor_button_release_event (ClutterActor* _sender, ClutterButtonEvent* event, gpointer self);
static void __lambda15_ (News* self, const gchar* key);
gboolean service_update (Service* self);
static void ___lambda15__g_settings_changed (GSettings* _sender, const gchar* key, gpointer self);
gboolean service_load (Service* self);
static gboolean _service_update_gsource_func (gpointer self);
#define textcolor "black"
static void news_real_create (Service* base);
static gboolean news_real_update (Service* base);
void shadowed_label_set_label (ShadowedLabel* self, const gchar* value);
static void __lambda16_ (News* self, SoupSession* session, SoupMessage* m);
gchar* service_ellipsize (const gchar* s, gint max_length);
static void ___lambda16__soup_session_callback (SoupSession* session, SoupMessage* msg, gpointer self);
static void news_finalize (GObject* obj);
static void _vala_NewsNews_array_free (NewsNews* array, gint array_length) {
if (array != NULL) {
int i;
for (i = 0; i < array_length; i = i + 1) {
news_news_destroy (&array[i]);
}
}
g_free (array);
}
static void _g_free0_ (gpointer var) {
var = (g_free (var), NULL);
}
static void _g_list_free__g_free0_ (GList* self) {
g_list_foreach (self, (GFunc) _g_free0_, NULL);
g_list_free (self);
}
static gboolean __lambda14_ (News* self, ClutterButtonEvent* e) {
gboolean result = FALSE;
gfloat root_x = 0.0F;
gfloat root_y = 0.0F;
ShadowedLabel* _tmp0_;
gfloat _tmp1_ = 0.0F;
gfloat _tmp2_ = 0.0F;
NewsNews* _tmp3_;
gint _tmp3__length1;
ClutterButtonEvent _tmp4_;
gfloat _tmp5_;
ShadowedLabel* _tmp6_;
gfloat _tmp7_;
gfloat _tmp8_;
gint _tmp9_ = 0;
NewsNews _tmp10_;
const gchar* _tmp11_;
gchar* _tmp12_;
gchar* url;
GList* uris;
gchar* _tmp13_;
GError * _inner_error_ = NULL;
g_return_val_if_fail (e != NULL, FALSE);
_tmp0_ = self->priv->label_list;
clutter_actor_get_transformed_position ((ClutterActor*) _tmp0_, &_tmp1_, &_tmp2_);
root_x = _tmp1_;
root_y = _tmp2_;
_tmp3_ = self->priv->news;
_tmp3__length1 = self->priv->news_length1;
_tmp4_ = *e;
_tmp5_ = _tmp4_.y;
_tmp6_ = self->priv->label_list;
_tmp7_ = clutter_actor_get_height ((ClutterActor*) _tmp6_);
_tmp8_ = _tmp7_;
_tmp9_ = MIN ((gint) ((_tmp5_ - root_y) / ((_tmp8_ - 20) / 10.0f)), 9);
_tmp10_ = _tmp3_[_tmp9_];
_tmp11_ = _tmp10_.url;
_tmp12_ = g_strdup (_tmp11_);
url = _tmp12_;
uris = NULL;
_tmp13_ = g_strdup (url);
uris = g_list_append (uris, _tmp13_);
{
GAppInfo* _tmp14_ = NULL;
GAppInfo* _tmp15_;
_tmp14_ = g_app_info_get_default_for_uri_scheme ("http");
_tmp15_ = _tmp14_;
g_app_info_launch_uris (_tmp15_, uris, NULL, &_inner_error_);
_g_object_unref0 (_tmp15_);
if (_inner_error_ != NULL) {
goto __catch2_g_error;
}
}
goto __finally2;
__catch2_g_error:
{
GError* e = NULL;
GError* _tmp16_;
const gchar* _tmp17_;
e = _inner_error_;
_inner_error_ = NULL;
_tmp16_ = e;
_tmp17_ = _tmp16_->message;
g_warning ("News.vala:32: %s", _tmp17_);
_g_error_free0 (e);
}
__finally2:
if (_inner_error_ != NULL) {
__g_list_free__g_free0_0 (uris);
_g_free0 (url);
g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
g_clear_error (&_inner_error_);
return FALSE;
}
result = TRUE;
__g_list_free__g_free0_0 (uris);
_g_free0 (url);
return result;
}
static gboolean ___lambda14__clutter_actor_button_release_event (ClutterActor* _sender, ClutterButtonEvent* event, gpointer self) {
gboolean result;
result = __lambda14_ (self, event);
return result;
}
static void __lambda15_ (News* self, const gchar* key) {
const gchar* _tmp0_;
g_return_if_fail (key != NULL);
_tmp0_ = key;
if (g_strcmp0 (_tmp0_, "update-interval") != 0) {
service_update ((Service*) self);
}
}
static void ___lambda15__g_settings_changed (GSettings* _sender, const gchar* key, gpointer self) {
__lambda15_ (self, key);
}
static gboolean _service_update_gsource_func (gpointer self) {
gboolean result;
result = service_update (self);
return result;
}
News* news_construct (GType object_type) {
News * self = NULL;
const gchar* _tmp0_ = NULL;
ShadowedLabel* _tmp1_ = NULL;
ShadowedLabel* _tmp2_;
ShadowedLabel* _tmp3_;
ShadowedLabel* _tmp4_;
ShadowedLabel* _tmp5_;
ShadowedLabel* _tmp6_;
GSettings* _tmp7_;
GSettings* _tmp8_;
SoupSessionAsync* _tmp9_;
GSettings* _tmp10_;
gint _tmp11_ = 0;
const gchar* _tmp12_ = NULL;
gchar* _tmp13_ = NULL;
gchar* _tmp14_;
gchar* _tmp15_;
gchar* _tmp16_;
ShadowedLabel* _tmp17_;
ShadowedLabel* _tmp18_;
ShadowedLabel* label;
ShadowedLabel* _tmp19_;
gfloat _tmp20_;
gfloat _tmp21_;
ShadowedLabel* _tmp22_;
ShadowedLabel* _tmp23_;
ShadowedLabel* _tmp24_;
gfloat _tmp25_;
gfloat _tmp26_;
ShadowedLabel* _tmp27_;
ShadowedLabel* _tmp28_;
gfloat _tmp29_;
gfloat _tmp30_;
ShadowedLabel* _tmp31_;
ShadowedLabel* _tmp32_;
self = (News*) service_construct (object_type, "news");
_tmp0_ = _ ("news");
_tmp1_ = service_get_reload_label ((Service*) self, _tmp0_);
_g_object_unref0 (self->priv->reload);
self->priv->reload = _tmp1_;
_tmp2_ = self->priv->reload;
clutter_actor_hide ((ClutterActor*) _tmp2_);
_tmp3_ = shadowed_label_new ("");
g_object_ref_sink (_tmp3_);
_g_object_unref0 (self->priv->label_list);
self->priv->label_list = _tmp3_;
_tmp4_ = self->priv->label_list;
clutter_actor_hide ((ClutterActor*) _tmp4_);
_tmp5_ = self->priv->label_list;
clutter_actor_set_reactive ((ClutterActor*) _tmp5_, TRUE);
_tmp6_ = self->priv->label_list;
g_signal_connect_object ((ClutterActor*) _tmp6_, "button-release-event", (GCallback) ___lambda14__clutter_actor_button_release_event, self, 0);
_tmp7_ = g_settings_new ("org.pantheon.gazette.news");
_g_object_unref0 (self->priv->settings);
self->priv->settings = _tmp7_;
_tmp8_ = self->priv->settings;
g_signal_connect_object (_tmp8_, "changed", (GCallback) ___lambda15__g_settings_changed, self, 0);
_tmp9_ = (SoupSessionAsync*) soup_session_async_new ();
_g_object_unref0 (self->priv->session);
self->priv->session = (SoupSession*) _tmp9_;
service_load ((Service*) self);
_tmp10_ = self->priv->settings;
_tmp11_ = g_settings_get_int (_tmp10_, "update-interval");
g_timeout_add_full (G_PRIORITY_DEFAULT, (guint) _tmp11_, _service_update_gsource_func, g_object_ref ((Service*) self), g_object_unref);
_tmp12_ = _ ("News");
_tmp13_ = g_strdup_printf ("' font='20' face='Raleway'>%s</span>", _tmp12_);
_tmp14_ = _tmp13_;
_tmp15_ = g_strconcat ("<span color='" textcolor, _tmp14_, NULL);
_tmp16_ = _tmp15_;
_tmp17_ = shadowed_label_new (_tmp16_);
g_object_ref_sink (_tmp17_);
_tmp18_ = _tmp17_;
_g_free0 (_tmp16_);
_g_free0 (_tmp14_);
label = _tmp18_;
_tmp19_ = self->priv->label_list;
_tmp20_ = clutter_actor_get_height ((ClutterActor*) label);
_tmp21_ = _tmp20_;
clutter_actor_set_y ((ClutterActor*) _tmp19_, _tmp21_ + 12);
_tmp22_ = self->priv->label_list;
clutter_actor_set_x ((ClutterActor*) _tmp22_, (gfloat) 12);
_tmp23_ = self->priv->reload;
_tmp24_ = self->priv->label_list;
_tmp25_ = clutter_actor_get_y ((ClutterActor*) _tmp24_);
_tmp26_ = _tmp25_;
clutter_actor_set_y ((ClutterActor*) _tmp23_, _tmp26_);
_tmp27_ = self->priv->reload;
_tmp28_ = self->priv->label_list;
_tmp29_ = clutter_actor_get_x ((ClutterActor*) _tmp28_);
_tmp30_ = _tmp29_;
clutter_actor_set_x ((ClutterActor*) _tmp27_, _tmp30_);
clutter_actor_add_child ((ClutterActor*) self, (ClutterActor*) label);
_tmp31_ = self->priv->reload;
clutter_actor_add_child ((ClutterActor*) self, (ClutterActor*) _tmp31_);
_tmp32_ = self->priv->label_list;
clutter_actor_add_child ((ClutterActor*) self, (ClutterActor*) _tmp32_);
_g_object_unref0 (label);
return self;
}
News* news_new (void) {
return news_construct (TYPE_NEWS);
}
static void news_real_create (Service* base) {
News * self;
self = (News*) base;
}
static gpointer _g_object_ref0 (gpointer self) {
return self ? g_object_ref (self) : NULL;
}
static gint string_index_of (const gchar* self, const gchar* needle, gint start_index) {
gint result = 0;
gint _tmp0_;
const gchar* _tmp1_;
gchar* _tmp2_ = NULL;
gchar* _result_;
gchar* _tmp3_;
g_return_val_if_fail (self != NULL, 0);
g_return_val_if_fail (needle != NULL, 0);
_tmp0_ = start_index;
_tmp1_ = needle;
_tmp2_ = strstr (((gchar*) self) + _tmp0_, (gchar*) _tmp1_);
_result_ = _tmp2_;
_tmp3_ = _result_;
if (_tmp3_ != NULL) {
gchar* _tmp4_;
_tmp4_ = _result_;
result = (gint) (_tmp4_ - ((gchar*) self));
return result;
} else {
result = -1;
return result;
}
}
static glong string_strnlen (gchar* str, glong maxlen) {
glong result = 0L;
gchar* _tmp0_;
glong _tmp1_;
gchar* _tmp2_ = NULL;
gchar* end;
gchar* _tmp3_;
_tmp0_ = str;
_tmp1_ = maxlen;
_tmp2_ = memchr (_tmp0_, 0, (gsize) _tmp1_);
end = _tmp2_;
_tmp3_ = end;
if (_tmp3_ == NULL) {
glong _tmp4_;
_tmp4_ = maxlen;
result = _tmp4_;
return result;
} else {
gchar* _tmp5_;
gchar* _tmp6_;
_tmp5_ = end;
_tmp6_ = str;
result = (glong) (_tmp5_ - _tmp6_);
return result;
}
}
static gchar* string_substring (const gchar* self, glong offset, glong len) {
gchar* result = NULL;
glong string_length = 0L;
gboolean _tmp0_ = FALSE;
glong _tmp1_;
gboolean _tmp3_;
glong _tmp9_;
glong _tmp15_;
glong _tmp18_;
glong _tmp19_;
glong _tmp20_;
glong _tmp21_;
glong _tmp22_;
gchar* _tmp23_ = NULL;
g_return_val_if_fail (self != NULL, NULL);
_tmp1_ = offset;
if (_tmp1_ >= ((glong) 0)) {
glong _tmp2_;
_tmp2_ = len;
_tmp0_ = _tmp2_ >= ((glong) 0);
} else {
_tmp0_ = FALSE;
}
_tmp3_ = _tmp0_;
if (_tmp3_) {
glong _tmp4_;
glong _tmp5_;
glong _tmp6_ = 0L;
_tmp4_ = offset;
_tmp5_ = len;
_tmp6_ = string_strnlen ((gchar*) self, _tmp4_ + _tmp5_);
string_length = _tmp6_;
} else {
gint _tmp7_;
gint _tmp8_;
_tmp7_ = strlen (self);
_tmp8_ = _tmp7_;
string_length = (glong) _tmp8_;
}
_tmp9_ = offset;
if (_tmp9_ < ((glong) 0)) {
glong _tmp10_;
glong _tmp11_;
glong _tmp12_;
_tmp10_ = string_length;
_tmp11_ = offset;
offset = _tmp10_ + _tmp11_;
_tmp12_ = offset;
g_return_val_if_fail (_tmp12_ >= ((glong) 0), NULL);
} else {
glong _tmp13_;
glong _tmp14_;
_tmp13_ = offset;
_tmp14_ = string_length;
g_return_val_if_fail (_tmp13_ <= _tmp14_, NULL);
}
_tmp15_ = len;
if (_tmp15_ < ((glong) 0)) {
glong _tmp16_;
glong _tmp17_;
_tmp16_ = string_length;
_tmp17_ = offset;
len = _tmp16_ - _tmp17_;
}
_tmp18_ = offset;
_tmp19_ = len;
_tmp20_ = string_length;
g_return_val_if_fail ((_tmp18_ + _tmp19_) <= _tmp20_, NULL);
_tmp21_ = offset;
_tmp22_ = len;
_tmp23_ = g_strndup (((gchar*) self) + _tmp21_, (gsize) _tmp22_);
result = _tmp23_;
return result;
}
static void __lambda16_ (News* self, SoupSession* session, SoupMessage* m) {
SoupMessage* _tmp0_;
SoupMessageBody* _tmp1_;
guint8* _tmp2_;
gint _tmp2__length1;
gchar* _tmp3_;
gchar* output;
const gchar* _tmp4_;
const gchar* _tmp7_;
gint _tmp8_ = 0;
gint offset;
NewsNews* _tmp9_ = NULL;
gchar* _tmp42_;
gchar* list;
ShadowedLabel* _tmp56_;
const gchar* _tmp57_;
gchar* _tmp58_;
gchar* _tmp59_;
ShadowedLabel* _tmp60_;
g_return_if_fail (session != NULL);
g_return_if_fail (m != NULL);
_tmp0_ = m;
_tmp1_ = _tmp0_->response_body;
_tmp2_ = _tmp1_->data;
_tmp2__length1 = (gint) _tmp1_->length;
_tmp3_ = g_strdup ((const gchar*) _tmp2_);
output = _tmp3_;
_tmp4_ = output;
if (_tmp4_ == NULL) {
ShadowedLabel* _tmp5_;
ShadowedLabel* _tmp6_;
_tmp5_ = self->priv->label_list;
clutter_actor_hide ((ClutterActor*) _tmp5_);
_tmp6_ = self->priv->reload;
clutter_actor_show ((ClutterActor*) _tmp6_);
_g_free0 (output);
return;
}
_tmp7_ = output;
_tmp8_ = string_index_of (_tmp7_, "<item>", 0);
offset = _tmp8_;
_tmp9_ = g_new0 (NewsNews, 10);
self->priv->news = (_vala_NewsNews_array_free (self->priv->news, self->priv->news_length1), NULL);
self->priv->news = _tmp9_;
self->priv->news_length1 = 10;
self->priv->_news_size_ = self->priv->news_length1;
{
gint i;
i = 0;
{
gboolean _tmp10_;
_tmp10_ = TRUE;
while (TRUE) {
gboolean _tmp11_;
gint _tmp13_;
const gchar* _tmp14_;
gint _tmp15_;
gint _tmp16_ = 0;
const gchar* _tmp17_;
gint _tmp18_;
const gchar* _tmp19_;
gint _tmp20_;
gint _tmp21_ = 0;
gint _tmp22_;
gchar* _tmp23_ = NULL;
gchar* title;
const gchar* _tmp24_;
gint _tmp25_;
gint _tmp26_ = 0;
const gchar* _tmp27_;
gint _tmp28_;
const gchar* _tmp29_;
gint _tmp30_;
gint _tmp31_ = 0;
gint _tmp32_;
gchar* _tmp33_ = NULL;
gchar* url;
NewsNews* _tmp34_;
gint _tmp34__length1;
gint _tmp35_;
const gchar* _tmp36_;
gchar* _tmp37_ = NULL;
const gchar* _tmp38_;
gchar* _tmp39_;
NewsNews _tmp40_ = {0};
NewsNews _tmp41_;
_tmp11_ = _tmp10_;
if (!_tmp11_) {
gint _tmp12_;
_tmp12_ = i;
i = _tmp12_ + 1;
}
_tmp10_ = FALSE;
_tmp13_ = i;
if (!(_tmp13_ < 10)) {
break;
}
_tmp14_ = output;
_tmp15_ = offset;
_tmp16_ = string_index_of (_tmp14_, "<title>", _tmp15_);
offset = _tmp16_ + 7;
_tmp17_ = output;
_tmp18_ = offset;
_tmp19_ = output;
_tmp20_ = offset;
_tmp21_ = string_index_of (_tmp19_, "</title>", _tmp20_);
_tmp22_ = offset;
_tmp23_ = string_substring (_tmp17_, (glong) _tmp18_, (glong) (_tmp21_ - _tmp22_));
title = _tmp23_;
_tmp24_ = output;
_tmp25_ = offset;
_tmp26_ = string_index_of (_tmp24_, "<link>", _tmp25_);
offset = _tmp26_ + 6;
_tmp27_ = output;
_tmp28_ = offset;
_tmp29_ = output;
_tmp30_ = offset;
_tmp31_ = string_index_of (_tmp29_, "</link>", _tmp30_);
_tmp32_ = offset;
_tmp33_ = string_substring (_tmp27_, (glong) _tmp28_, (glong) (_tmp31_ - _tmp32_));
url = _tmp33_;
_tmp34_ = self->priv->news;
_tmp34__length1 = self->priv->news_length1;
_tmp35_ = i;
_tmp36_ = title;
_tmp37_ = service_ellipsize (_tmp36_, 40);
_tmp38_ = url;
_tmp39_ = g_strdup (_tmp38_);
_g_free0 (_tmp40_.title);
_tmp40_.title = _tmp37_;
_g_free0 (_tmp40_.url);
_tmp40_.url = _tmp39_;
news_news_destroy (&_tmp34_[_tmp35_]);
_tmp34_[_tmp35_] = _tmp40_;
_tmp41_ = _tmp34_[_tmp35_];
_g_free0 (url);
_g_free0 (title);
}
}
}
_tmp42_ = g_strdup ("<span color='" textcolor "' font='12' face='Open Sans'>");
list = _tmp42_;
{
gint i;
i = 0;
{
gboolean _tmp43_;
_tmp43_ = TRUE;
while (TRUE) {
gboolean _tmp44_;
gint _tmp46_;
NewsNews* _tmp47_;
gint _tmp47__length1;
const gchar* _tmp48_;
NewsNews* _tmp49_;
gint _tmp49__length1;
gint _tmp50_;
NewsNews _tmp51_;
const gchar* _tmp52_;
gchar* _tmp53_;
gchar* _tmp54_;
gchar* _tmp55_;
_tmp44_ = _tmp43_;
if (!_tmp44_) {
gint _tmp45_;
_tmp45_ = i;
i = _tmp45_ + 1;
}
_tmp43_ = FALSE;
_tmp46_ = i;
_tmp47_ = self->priv->news;
_tmp47__length1 = self->priv->news_length1;
if (!(_tmp46_ < _tmp47__length1)) {
break;
}
_tmp48_ = list;
_tmp49_ = self->priv->news;
_tmp49__length1 = self->priv->news_length1;
_tmp50_ = i;
_tmp51_ = _tmp49_[_tmp50_];
_tmp52_ = _tmp51_.title;
_tmp53_ = g_strconcat (_tmp52_, "\n", NULL);
_tmp54_ = _tmp53_;
_tmp55_ = g_strconcat (_tmp48_, _tmp54_, NULL);
_g_free0 (list);
list = _tmp55_;
_g_free0 (_tmp54_);
}
}
}
_tmp56_ = self->priv->label_list;
_tmp57_ = list;
_tmp58_ = g_strconcat (_tmp57_, "</span>", NULL);
_tmp59_ = _tmp58_;
shadowed_label_set_label (_tmp56_, _tmp59_);
_g_free0 (_tmp59_);
_tmp60_ = self->priv->label_list;
clutter_actor_set_reactive ((ClutterActor*) _tmp60_, TRUE);
_g_free0 (list);
_g_free0 (output);
}
static void ___lambda16__soup_session_callback (SoupSession* session, SoupMessage* msg, gpointer self) {
__lambda16_ (self, session, msg);
}
static gboolean news_real_update (Service* base) {
News * self;
gboolean result = FALSE;
ShadowedLabel* _tmp0_;
ShadowedLabel* _tmp1_;
ShadowedLabel* _tmp2_;
ShadowedLabel* _tmp3_;
const gchar* _tmp4_ = NULL;
gchar* _tmp5_;
gchar* _tmp6_;
gchar* _tmp7_;
gchar* _tmp8_;
GSettings* _tmp9_;
gchar* _tmp10_ = NULL;
gchar* soup_url;
SoupMessage* _tmp11_;
SoupSession* _tmp12_;
SoupMessage* _tmp13_;
SoupMessage* _tmp14_;
self = (News*) base;
g_debug ("News.vala:56: Updating News");
_tmp0_ = self->priv->reload;
clutter_actor_hide ((ClutterActor*) _tmp0_);
_tmp1_ = self->priv->label_list;
clutter_actor_set_reactive ((ClutterActor*) _tmp1_, FALSE);
_tmp2_ = self->priv->label_list;
clutter_actor_show ((ClutterActor*) _tmp2_);
_tmp3_ = self->priv->label_list;
_tmp4_ = _ ("Loading news,\nplease wait.");
_tmp5_ = g_strconcat ("<span color='" textcolor "' face='Open Sans Light' font='16'>", _tmp4_, NULL);
_tmp6_ = _tmp5_;
_tmp7_ = g_strconcat (_tmp6_, "</span>", NULL);
_tmp8_ = _tmp7_;
shadowed_label_set_label (_tmp3_, _tmp8_);
_g_free0 (_tmp8_);
_g_free0 (_tmp6_);
_tmp9_ = self->priv->settings;
_tmp10_ = g_settings_get_string (_tmp9_, "rss-url");
soup_url = _tmp10_;
_tmp11_ = soup_message_new ("GET", soup_url);
_g_object_unref0 (self->priv->message);
self->priv->message = _tmp11_;
_tmp12_ = self->priv->session;
_tmp13_ = self->priv->message;
_tmp14_ = _g_object_ref0 (_tmp13_);
soup_session_queue_message (_tmp12_, _tmp14_, ___lambda16__soup_session_callback, self);
result = TRUE;
_g_free0 (soup_url);
return result;
}
static void news_news_copy (const NewsNews* self, NewsNews* dest) {
const gchar* _tmp0_;
gchar* _tmp1_;
const gchar* _tmp2_;
gchar* _tmp3_;
_tmp0_ = (*self).title;
_tmp1_ = g_strdup (_tmp0_);
_g_free0 ((*dest).title);
(*dest).title = _tmp1_;
_tmp2_ = (*self).url;
_tmp3_ = g_strdup (_tmp2_);
_g_free0 ((*dest).url);
(*dest).url = _tmp3_;
}
static void news_news_destroy (NewsNews* self) {
_g_free0 ((*self).title);
_g_free0 ((*self).url);
}
static NewsNews* news_news_dup (const NewsNews* self) {
NewsNews* dup;
dup = g_new0 (NewsNews, 1);
news_news_copy (self, dup);
return dup;
}
static void news_news_free (NewsNews* self) {
news_news_destroy (self);
g_free (self);
}
static GType news_news_get_type (void) {
static volatile gsize news_news_type_id__volatile = 0;
if (g_once_init_enter (&news_news_type_id__volatile)) {
GType news_news_type_id;
news_news_type_id = g_boxed_type_register_static ("NewsNews", (GBoxedCopyFunc) news_news_dup, (GBoxedFreeFunc) news_news_free);
g_once_init_leave (&news_news_type_id__volatile, news_news_type_id);
}
return news_news_type_id__volatile;
}
static void news_class_init (NewsClass * klass) {
news_parent_class = g_type_class_peek_parent (klass);
g_type_class_add_private (klass, sizeof (NewsPrivate));
SERVICE_CLASS (klass)->create = news_real_create;
SERVICE_CLASS (klass)->update = news_real_update;
G_OBJECT_CLASS (klass)->finalize = news_finalize;
}
static void news_instance_init (News * self) {
self->priv = NEWS_GET_PRIVATE (self);
}
static void news_finalize (GObject* obj) {
News * self;
self = G_TYPE_CHECK_INSTANCE_CAST (obj, TYPE_NEWS, News);
_g_object_unref0 (self->priv->settings);
_g_object_unref0 (self->priv->session);
_g_object_unref0 (self->priv->message);
_g_object_unref0 (self->priv->label_list);
_g_object_unref0 (self->priv->reload);
self->priv->news = (_vala_NewsNews_array_free (self->priv->news, self->priv->news_length1), NULL);
G_OBJECT_CLASS (news_parent_class)->finalize (obj);
}
GType news_get_type (void) {
static volatile gsize news_type_id__volatile = 0;
if (g_once_init_enter (&news_type_id__volatile)) {
static const GTypeInfo g_define_type_info = { sizeof (NewsClass), (GBaseInitFunc) NULL, (GBaseFinalizeFunc) NULL, (GClassInitFunc) news_class_init, (GClassFinalizeFunc) NULL, NULL, sizeof (News), 0, (GInstanceInitFunc) news_instance_init, NULL };
GType news_type_id;
news_type_id = g_type_register_static (TYPE_SERVICE, "News", &g_define_type_info, 0);
g_once_init_leave (&news_type_id__volatile, news_type_id);
}
return news_type_id__volatile;
}
|
red-green/gazette
|
src/Services/News.c
|
C
|
gpl-3.0
| 24,486
|
package com.taobao.api.domain;
import java.util.List;
import com.taobao.api.TaobaoObject;
import com.taobao.api.internal.mapping.ApiField;
import com.taobao.api.internal.mapping.ApiListField;
/**
* 评价信息
*
* @author auto create
* @since 1.0, null
*/
public class RateInfo extends TaobaoObject {
private static final long serialVersionUID = 7494752753378247845L;
/**
* 评价信息
*/
@ApiListField("rate_list")
@ApiField("rate_item")
private List<RateItem> rateList;
public List<RateItem> getRateList() {
return this.rateList;
}
public void setRateList(List<RateItem> rateList) {
this.rateList = rateList;
}
}
|
kuiwang/my-dev
|
src/main/java/com/taobao/api/domain/RateInfo.java
|
Java
|
gpl-3.0
| 692
|
from setuptools import setup, find_packages
DESCRIPTION = "Implementation of Huff et. al. (2011) Estimation of Recent Shared Ancestry "
LONG_DESCRIPTION = "`ersa` estimates the combined number of generations between pairs of " \
"individuals using a " \
"`Germline <http://www1.cs.columbia.edu/~gusev/germline/>`_ " \
"matchfile as input. It is an implementation of " \
"`Huff et. al. (2011) Maximum-Likelihood estimation of recent shared ancenstry (ERSA) <http://genome.cshlp.org/content/21/5/768.full>`_ " \
"and `Li et. al. (2014) Relationship Estimation from Whole-Genome Sequence Data <http://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1004144>`_ ."
NAME = "ersa"
AUTHOR = "Richard Munoz, Jie Yuan, Yaniv Erlich"
AUTHOR_EMAIL = "rmunoz@columbia.edu, jyuan@columbia.edu, yaniv@cs.columbia.edu"
MAINTAINER = "Richard Munoz"
MAINTAINER_EMAIL = "rmunoz@columbia.edu"
DOWNLOAD_URL = 'http://github.com/rmunoz12/ersa'
LICENSE = 'GNU General Public License v3 (GPLv3)'
VERSION = '1.1.2'
setup(name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
url=DOWNLOAD_URL,
download_url=DOWNLOAD_URL,
license=LICENSE,
packages=find_packages(),
test_suite='tests',
entry_points = {
"console_scripts": ['ersa = ersa.ersa:main']
},
install_requires=['sqlalchemy', 'inflect', 'pytest', 'scipy'],
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3 :: Only',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Sociology :: Genealogy']
)
|
rmunoz12/ersa
|
setup.py
|
Python
|
gpl-3.0
| 2,290
|
/*
* Created: 31.03.2012
*
* Copyright (C) 2012 Victor Antonovich (v.antonovich@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package su.comp.bk.arch;
import android.content.res.Resources;
import android.os.Bundle;
import org.apache.commons.lang.ArrayUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import su.comp.bk.R;
import su.comp.bk.arch.cpu.Cpu;
import su.comp.bk.arch.io.Device;
import su.comp.bk.arch.io.KeyboardController;
import su.comp.bk.arch.io.PeripheralPort;
import su.comp.bk.arch.io.Sel1RegisterSystemBits;
import su.comp.bk.arch.io.SystemTimer;
import su.comp.bk.arch.io.Timer;
import su.comp.bk.arch.io.VideoController;
import su.comp.bk.arch.io.VideoControllerManager;
import su.comp.bk.arch.io.audio.AudioOutput;
import su.comp.bk.arch.io.audio.Ay8910;
import su.comp.bk.arch.io.audio.Covox;
import su.comp.bk.arch.io.audio.Speaker;
import su.comp.bk.arch.io.disk.FloppyController;
import su.comp.bk.arch.io.disk.IdeController;
import su.comp.bk.arch.io.disk.SmkIdeController;
import su.comp.bk.arch.io.memory.Bk11MemoryManager;
import su.comp.bk.arch.io.memory.SmkMemoryManager;
import su.comp.bk.arch.memory.BankedMemory;
import su.comp.bk.arch.memory.Memory;
import su.comp.bk.arch.memory.RandomAccessMemory;
import su.comp.bk.arch.memory.RandomAccessMemory.Type;
import su.comp.bk.arch.memory.ReadOnlyMemory;
import su.comp.bk.arch.memory.SegmentedMemory;
import su.comp.bk.arch.memory.SelectableMemory;
import su.comp.bk.util.FileUtils;
import timber.log.Timber;
/**
* BK001x computer implementation.
*/
public class Computer implements Runnable {
// State save/restore: Computer system uptime (in nanoseconds)
private static final String STATE_SYSTEM_UPTIME = Computer.class.getName() + "#sys_uptime";
// State save/restore: Computer RAM data
private static final String STATE_RAM_DATA = Computer.class.getName() + "#ram_data";
/** Bus error constant */
public final static int BUS_ERROR = -1;
// Computer configuration
private Configuration configuration;
// Memory table mapped by 4KB blocks
private final List<?>[] memoryTable = new List[16];
// List of created RandomAccessMemory instances
private final List<RandomAccessMemory> randomAccessMemoryList = new ArrayList<>();
// CPU implementation reference
private final Cpu cpu;
// Video controller reference
private VideoController videoController;
// Keyboard controller reference
private KeyboardController keyboardController;
// Peripheral port reference
private PeripheralPort peripheralPort;
// Audio outputs list
private List<AudioOutput> audioOutputs = new ArrayList<>();
// Floppy controller reference (<code>null</code> if no floppy controller attached)
private FloppyController floppyController;
/** BK0011 first banked memory block address */
public static final int BK0011_BANKED_MEMORY_0_ADDRESS = 040000;
/** BK0011 second banked memory block address */
public static final int BK0011_BANKED_MEMORY_1_ADDRESS = 0100000;
/** I/O registers space min start address */
public final static int IO_REGISTERS_MIN_ADDRESS = 0177000;
// I/O devices list
private final List<Device> deviceList = new ArrayList<>();
// I/O registers space addresses mapped to devices
private final List<?>[] deviceTable = new List[2048];
private boolean isRunning = false;
private boolean isPaused = true;
private Thread clockThread;
/** Amount of nanoseconds in one microsecond */
public static final long NANOSECS_IN_USEC = 1000L;
/** Amount of nanoseconds in one millisecond */
public static final long NANOSECS_IN_MSEC = 1000000L;
/** BK0010 clock frequency (in kHz) */
public final static int CLOCK_FREQUENCY_BK0010 = 3000;
/** BK0011 clock frequency (in kHz) */
public final static int CLOCK_FREQUENCY_BK0011 = 4000;
// Computer clock frequency (in kHz)
private int clockFrequency;
/** Uptime sync threshold (in nanoseconds) */
private static final long UPTIME_SYNC_THRESHOLD = (10L * NANOSECS_IN_MSEC);
// Last computer system uptime update timestamp (unix timestamp, in nanoseconds)
private long systemUptimeUpdateTimestamp;
// Computer system uptime since start (in nanoseconds)
private long systemUptime;
/** Uptime sync check interval (in nanoseconds) */
private static final long UPTIME_SYNC_CHECK_INTERVAL = (1L * NANOSECS_IN_MSEC);
// Computer system uptime sync check interval (in CPU ticks)
private long systemUptimeSyncCheckIntervalTicks;
// Last computer system uptime sync check timestamp (in CPU ticks)
private long systemUptimeSyncCheckTimestampTicks;
private final List<UptimeListener> uptimeListeners = new ArrayList<>();
// IDE controller reference (<code>null</code> if no IDE controller present)
private IdeController ideController;
/**
* Computer uptime updates listener.
*/
public interface UptimeListener {
void uptimeUpdated(long uptime);
}
public enum Configuration {
/** BK0010 - monitor only */
BK_0010_MONITOR,
/** BK0010 - monitor and Basic */
BK_0010_BASIC,
/** BK0010 - monitor, Focal and tests */
BK_0010_MSTD,
/** BK0010 with connected floppy drive controller (КНГМД) */
BK_0010_KNGMD(true),
/** BK0011M - MSTD block attached */
BK_0011M_MSTD(false, true),
/** BK0011M with connected floppy drive controller (КНГМД) */
BK_0011M_KNGMD(true, true),
/** BK0011M with connected SMK512 controller */
BK_0011M_SMK512(true, true);
private final boolean isFloppyControllerPresent;
private final boolean isMemoryManagerPresent;
Configuration() {
this(false, false);
}
Configuration(boolean isFloppyControllerPresent) {
this(isFloppyControllerPresent, false);
}
Configuration(boolean isFloppyControllerPresent, boolean isMemoryManagerPresent) {
this.isFloppyControllerPresent = isFloppyControllerPresent;
this.isMemoryManagerPresent = isMemoryManagerPresent;
}
/**
* Check is {@link FloppyController} present in this configuration.
* @return <code>true</code> if floppy controller present, <code>false</code> otherwise
*/
public boolean isFloppyControllerPresent() {
return isFloppyControllerPresent;
}
/**
* Check is BK-0011 {@link Bk11MemoryManager} present in configuration.
* @return <code>true</code> if memory manager present, <code>false</code> otherwise
*/
public boolean isMemoryManagerPresent() {
return isMemoryManagerPresent;
}
}
public static class MemoryRange {
private final int startAddress;
private final Memory memory;
private final int endAddress;
public MemoryRange(int startAddress, Memory memory) {
this.startAddress = startAddress;
this.memory = memory;
this.endAddress = startAddress + (memory.getSize() << 1) - 1;
}
public int getStartAddress() {
return startAddress;
}
public Memory getMemory() {
return memory;
}
public boolean isRelatedAddress(int address) {
return (address >= startAddress) && (address <= endAddress);
}
}
public Computer() {
this.cpu = new Cpu(this);
}
/**
* Configure this computer.
* @param resources Android resources object reference
* @param config computer configuration as {@link Configuration} value
* @throws Exception in case of error while configuring
*/
public void configure(Resources resources, Configuration config) throws Exception {
setConfiguration(config);
// Apply shared configuration
addDevice(new Sel1RegisterSystemBits(!config.isMemoryManagerPresent() ? 0100000 : 0140000));
keyboardController = new KeyboardController(this);
addDevice(keyboardController);
peripheralPort = new PeripheralPort();
addDevice(peripheralPort);
addDevice(new Timer());
// Apply computer specific configuration
if (!config.isMemoryManagerPresent()) {
// BK-0010 configurations
setClockFrequency(CLOCK_FREQUENCY_BK0010);
// Set RAM configuration
RandomAccessMemory workMemory = createRandomAccessMemory("WorkMemory",
020000, Type.K565RU6);
addMemory(0, workMemory);
RandomAccessMemory videoMemory = createRandomAccessMemory("VideoMemory",
020000, Type.K565RU6);
addMemory(040000, videoMemory);
// Add video controller
videoController = new VideoController(videoMemory);
addDevice(videoController);
// Set ROM configuration
addReadOnlyMemory(resources, 0100000, R.raw.monit10, "Monitor10");
switch (config) {
case BK_0010_BASIC:
addReadOnlyMemory(resources, 0120000, R.raw.basic10_1, "Basic10:1");
addReadOnlyMemory(resources, 0140000, R.raw.basic10_2, "Basic10:2");
addReadOnlyMemory(resources, 0160000, R.raw.basic10_3, "Basic10:3");
break;
case BK_0010_MSTD:
addReadOnlyMemory(resources, 0120000, R.raw.focal, "Focal");
addReadOnlyMemory(resources, 0160000, R.raw.tests, "MSTD10");
break;
case BK_0010_KNGMD:
addMemory(0120000, createRandomAccessMemory("ExtMemory", 020000, Type.K537RU10));
addReadOnlyMemory(resources, 0160000, R.raw.disk_327, "FloppyBios");
floppyController = new FloppyController(this);
addDevice(floppyController);
break;
default:
break;
}
} else {
// BK-0011 configurations
setClockFrequency(CLOCK_FREQUENCY_BK0011);
// Set RAM configuration
BankedMemory firstBankedMemory = new BankedMemory("BankedMemory0",
020000, Bk11MemoryManager.NUM_RAM_BANKS);
BankedMemory secondBankedMemory = new BankedMemory("BankedMemory1",
020000,
Bk11MemoryManager.NUM_RAM_BANKS + Bk11MemoryManager.NUM_ROM_BANKS);
for (int memoryBankIndex = 0; memoryBankIndex < Bk11MemoryManager.NUM_RAM_BANKS;
memoryBankIndex++) {
Memory memoryBank = createRandomAccessMemory("MemoryBank" + memoryBankIndex,
020000, Type.K565RU5);
firstBankedMemory.setBank(memoryBankIndex, memoryBank);
secondBankedMemory.setBank(memoryBankIndex, memoryBank);
}
addMemory(0, firstBankedMemory.getBank(6)); // Fixed RAM page at address 0
addMemory(BK0011_BANKED_MEMORY_0_ADDRESS, firstBankedMemory); // First banked memory window at address 040000
SelectableMemory selectableSecondBankedMemory = new SelectableMemory(
secondBankedMemory.getId(), secondBankedMemory, true);
addMemory(BK0011_BANKED_MEMORY_1_ADDRESS, selectableSecondBankedMemory); // Second banked memory window at address 0100000
// Set ROM configuration
secondBankedMemory.setBank(Bk11MemoryManager.NUM_RAM_BANKS, new ReadOnlyMemory(
"Basic11M:0", loadReadOnlyMemoryData(resources, R.raw.basic11m_0)));
secondBankedMemory.setBank(Bk11MemoryManager.NUM_RAM_BANKS + 1,
new ReadOnlyMemory("Basic11M:1/ExtBOS11M", loadReadOnlyMemoryData(resources,
R.raw.basic11m_1, R.raw.ext11m)));
ReadOnlyMemory bosRom = new ReadOnlyMemory("BOS11M",
loadReadOnlyMemoryData(resources, R.raw.bos11m));
SelectableMemory selectableBosRom = new SelectableMemory(bosRom.getId(), bosRom, true);
addMemory( 0140000, selectableBosRom);
switch (config) {
case BK_0011M_MSTD:
addReadOnlyMemory(resources, 0160000, R.raw.mstd11m, "MSTD11M");
break;
case BK_0011M_KNGMD:
addReadOnlyMemory(resources, 0160000, R.raw.disk_327, "FloppyBios");
floppyController = new FloppyController(this);
addDevice(floppyController);
break;
case BK_0011M_SMK512:
ReadOnlyMemory smkBiosRom = new ReadOnlyMemory("SmkBiosRom",
loadReadOnlyMemoryData(resources, R.raw.disk_smk512_v205));
SelectableMemory selectableSmkBiosRom0 = new SelectableMemory(
smkBiosRom.getId() + ":0", smkBiosRom, false);
SelectableMemory selectableSmkBiosRom1 = new SelectableMemory(
smkBiosRom.getId() + ":1", smkBiosRom, false);
addMemory(SmkMemoryManager.BIOS_ROM_0_START_ADDRESS, selectableSmkBiosRom0);
addMemory(SmkMemoryManager.BIOS_ROM_1_START_ADDRESS, selectableSmkBiosRom1);
RandomAccessMemory smkRam = createRandomAccessMemory("SmkRam",
SmkMemoryManager.MEMORY_TOTAL_SIZE, Type.K565RU5);
List<SegmentedMemory> smkRamSegments = new ArrayList<>(
SmkMemoryManager.NUM_MEMORY_SEGMENTS);
for (int i = 0; i < SmkMemoryManager.NUM_MEMORY_SEGMENTS; i++) {
SegmentedMemory smkRamSegment = new SegmentedMemory("SmkRamSegment" + i,
smkRam, SmkMemoryManager.MEMORY_SEGMENT_SIZE);
smkRamSegments.add(smkRamSegment);
addMemory(SmkMemoryManager.MEMORY_START_ADDRESS +
i * SmkMemoryManager.MEMORY_SEGMENT_SIZE * 2, smkRamSegment);
}
SmkMemoryManager smkMemoryManager = new SmkMemoryManager(smkRamSegments,
selectableSmkBiosRom0, selectableSmkBiosRom1);
smkMemoryManager.setSelectableBk11BosRom(selectableBosRom);
smkMemoryManager.setSelectableBk11SecondBankedMemory(selectableSecondBankedMemory);
addDevice(smkMemoryManager);
floppyController = new FloppyController(this);
addDevice(floppyController);
SmkIdeController smkIdeController = new SmkIdeController(this);
ideController = smkIdeController;
addDevice(smkIdeController);
break;
default:
break;
}
// Configure BK0011M memory manager
addDevice(new Bk11MemoryManager(firstBankedMemory, secondBankedMemory));
// Add video controller with palette/screen manager
BankedMemory videoMemory = new BankedMemory("VideoPagesMemory", 020000, 2);
videoMemory.setBank(0, firstBankedMemory.getBank(1));
videoMemory.setBank(1, firstBankedMemory.getBank(7));
videoController = new VideoController(videoMemory);
addDevice(videoController);
addDevice(new VideoControllerManager(videoController, videoMemory));
// Add system timer
SystemTimer systemTimer = new SystemTimer(this);
addDevice(systemTimer);
videoController.addFrameSyncListener(systemTimer);
}
// Notify video controller about computer time updates
addUptimeListener(videoController);
// Add audio outputs
addAudioOutput(new Speaker(this, config.isMemoryManagerPresent()));
addAudioOutput(new Covox(this));
addAudioOutput(new Ay8910(this));
}
/**
* Set computer configuration.
* @param config computer configuration as {@link Configuration} value
*/
public void setConfiguration(Configuration config) {
this.configuration = config;
}
/**
* Get computer configuration.
* @return computer configuration as {@link Configuration} value
*/
public Configuration getConfiguration() {
return this.configuration;
}
/**
* Create new {@link RandomAccessMemory} and add it to the RAM list for further saving/restoring.
* @param memoryId RAM identifier
* @param memorySize RAM size (in words)
* @param memoryType RAM type
* @return created {@link RandomAccessMemory} reference
*/
private RandomAccessMemory createRandomAccessMemory(String memoryId, int memorySize,
Type memoryType) {
RandomAccessMemory memory = new RandomAccessMemory(memoryId, memorySize, memoryType);
addToRandomAccessMemoryList(memory);
return memory;
}
private void addToRandomAccessMemoryList(RandomAccessMemory memory) {
randomAccessMemoryList.add(memory);
}
private List<RandomAccessMemory> getRandomAccessMemoryList() {
return randomAccessMemoryList;
}
/**
* Save computer state.
* @param outState {@link Bundle} to save state
*/
public void saveState(Bundle outState) {
// Save computer configuration
outState.putString(Configuration.class.getName(), getConfiguration().name());
// Save computer system uptime
outState.putLong(STATE_SYSTEM_UPTIME, getSystemUptime());
// Save RAM data
saveRandomAccessMemoryData(outState);
// Save CPU state
getCpu().saveState(outState);
// Save device states
for (Device device : deviceList) {
device.saveState(outState);
}
}
private void saveRandomAccessMemoryData(Bundle outState) {
List<RandomAccessMemory> randomAccessMemoryList = getRandomAccessMemoryList();
// Calculate total RAM data size (in bytes)
int totalDataSize = 0;
for (RandomAccessMemory memory: randomAccessMemoryList) {
totalDataSize += memory.getSize() * 2;
}
// Pack all RAM data into a single buffer
ByteBuffer dataBuf = ByteBuffer.allocate(totalDataSize);
ShortBuffer shortDataBuf = dataBuf.asShortBuffer();
for (RandomAccessMemory memory: randomAccessMemoryList) {
shortDataBuf.put(memory.getData(), 0, memory.getSize());
}
dataBuf.flip();
// Compress RAM data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
try (DeflaterOutputStream dos = new DeflaterOutputStream(baos, deflater)) {
dos.write(dataBuf.array());
} catch (IOException e) {
throw new IllegalStateException("Can't compress RAM data", e);
}
byte[] compressedData = baos.toByteArray();
outState.putByteArray(STATE_RAM_DATA, compressedData);
Timber.d("Saved RAM data: original %dKB, compressed %dKB",
totalDataSize / 1024, compressedData.length / 1024);
}
/**
* Restore computer state.
* @param inState {@link Bundle} to restore state
* @throws Exception in case of error while state restoring
*/
public void restoreState(Bundle inState) throws Exception {
// Restore computer system uptime
setSystemUptime(inState.getLong(STATE_SYSTEM_UPTIME));
// Initialize CPU and devices
cpu.initDevices(true);
// Restore RAM data
restoreRandomAccessMemoryData(inState);
// Restore CPU state
getCpu().restoreState(inState);
// Restore device states
for (Device device : deviceList) {
device.restoreState(inState);
}
}
private void restoreRandomAccessMemoryData(Bundle inState) {
byte[] compressedData = inState.getByteArray(STATE_RAM_DATA);
if (compressedData == null || compressedData.length == 0) {
throw new IllegalArgumentException("No RAM data to restore");
}
List<RandomAccessMemory> randomAccessMemoryList = getRandomAccessMemoryList();
// Calculate RAM memory data size (in bytes)
int totalDataSize = 0;
for (RandomAccessMemory memory: randomAccessMemoryList) {
totalDataSize += memory.getSize() * 2;
}
// Decompress RAM data
ByteArrayOutputStream baos = new ByteArrayOutputStream(totalDataSize);
ByteArrayInputStream bais = new ByteArrayInputStream(compressedData);
try (InflaterInputStream iis = new InflaterInputStream(bais)) {
FileUtils.writeFully(iis, baos);
} catch (IOException e) {
throw new IllegalArgumentException("Can't decompress RAM data", e);
}
// Check decompressed data
byte[] data = baos.toByteArray();
if (data.length != totalDataSize) {
throw new IllegalArgumentException(String.format("Invalid decompressed RAM " +
"data length: expected %d, got %d", totalDataSize, data.length));
}
// Restore RAM data
ByteBuffer dataBuf = ByteBuffer.wrap(data);
ShortBuffer shortDataBuf = dataBuf.asShortBuffer();
for (RandomAccessMemory memory: randomAccessMemoryList) {
short[] memoryData = new short[memory.getSize()];
shortDataBuf.get(memoryData);
memory.putData(memoryData);
}
}
public static Configuration getStoredConfiguration(Bundle inState) {
return (inState != null) ? Configuration.valueOf(inState.getString(
Configuration.class.getName())) : null;
}
/**
* Get clock frequency (in kHz)
* @return clock frequency
*/
public int getClockFrequency() {
return clockFrequency;
}
/**
* Set clock frequency (in kHz)
* @param clockFrequency clock frequency to set
*/
public void setClockFrequency(int clockFrequency) {
this.clockFrequency = clockFrequency;
systemUptimeSyncCheckIntervalTicks = nanosToCpuTime(UPTIME_SYNC_CHECK_INTERVAL);
}
private void addReadOnlyMemory(Resources resources, int address, int romDataResId, String romId)
throws IOException {
byte[] romData = loadReadOnlyMemoryData(resources, romDataResId);
addMemory(address, new ReadOnlyMemory(romId, romData));
}
/**
* Load ROM data from raw resources.
* @param resources {@link Resources} reference
* @param romDataResIds ROM raw resource IDs
* @return loaded ROM data
* @throws IOException in case of ROM data loading error
*/
private byte[] loadReadOnlyMemoryData(Resources resources, int... romDataResIds)
throws IOException {
byte[] romData = null;
for (int romDataResId : romDataResIds) {
romData = ArrayUtils.addAll(romData, loadRawResourceData(resources, romDataResId));
}
return romData;
}
/**
* Load data of raw resource.
* @param resources {@link Resources} reference
* @param resourceId raw resource ID
* @return read raw resource data
* @throws IOException in case of loading error
*/
private byte[] loadRawResourceData(Resources resources, int resourceId) throws IOException {
InputStream resourceDataStream = resources.openRawResource(resourceId);
byte[] resourceData = new byte[resourceDataStream.available()];
resourceDataStream.read(resourceData);
return resourceData;
}
/**
* Get {@link Cpu} reference.
* @return this <code>Computer</code> CPU object reference
*/
public Cpu getCpu() {
return cpu;
}
/**
* Get {@link VideoController} reference.
* @return video controller reference
*/
public VideoController getVideoController() {
return videoController;
}
/**
* Get {@link KeyboardController} reference.
* @return keyboard controller reference
*/
public KeyboardController getKeyboardController() {
return keyboardController;
}
/**
* Get {@link PeripheralPort} reference.
* @return peripheral port reference
*/
public PeripheralPort getPeripheralPort() {
return peripheralPort;
}
/**
* Get {@link FloppyController} reference.
* @return floppy controller reference or <code>null</code> if floppy controller is not present
*/
public FloppyController getFloppyController() {
return floppyController;
}
/**
* Get {@link IdeController} reference.
* @return IDE controller reference or <code>null</code> if IDE controller is not present
*/
public IdeController getIdeController() {
return ideController;
}
/**
* Get list of available {@link AudioOutput}s.
* @return audio outputs list
*/
public List<AudioOutput> getAudioOutputs() {
return audioOutputs;
}
/**
* Add {@link AudioOutput} device.
* @param audioOutput audio output device to add
*/
public void addAudioOutput(AudioOutput audioOutput) {
audioOutputs.add(audioOutput);
addDevice(audioOutput);
}
/**
* Set computer system uptime (in nanoseconds).
* @param systemUptime computer system uptime to set (in nanoseconds)
*/
public void setSystemUptime(long systemUptime) {
this.systemUptime = systemUptime;
}
/**
* Get computer system uptime (in nanoseconds).
* @return computer system uptime (in nanoseconds)
*/
public long getSystemUptime() {
return systemUptime;
}
/**
* Get computer time (in nanoseconds).
* @return current computer uptime
*/
public long getUptime() {
return cpuTimeToNanos(cpu.getTime());
}
/**
* Get computer time (in CPU ticks).
* @return current computer uptime
*/
public long getUptimeTicks() {
return cpu.getTime();
}
/**
* Add computer uptime updates listener.
* @param uptimeListener {@link UptimeListener} object reference to add
*/
public void addUptimeListener(UptimeListener uptimeListener) {
uptimeListeners.add(uptimeListener);
}
private void notifyUptimeListeners() {
long uptime = getUptime();
for (int i = 0; i < uptimeListeners.size(); i++) {
UptimeListener uptimeListener = uptimeListeners.get(i);
uptimeListener.uptimeUpdated(uptime);
}
}
/**
* Add memory (RAM/ROM) to address space.
* @param address address to add memory
* @param memory {@link Memory} to add
*/
public void addMemory(int address, Memory memory) {
int memoryStartBlock = address >> 12;
int memoryBlocksCount = memory.getSize() >> 11; // ((size << 1) >> 12)
if ((memory.getSize() & 03777) != 0) {
memoryBlocksCount++;
}
MemoryRange memoryRange = new MemoryRange(address, memory);
for (int i = 0; i < memoryBlocksCount; i++) {
int memoryBlockIdx = memoryStartBlock + i;
@SuppressWarnings("unchecked")
List<MemoryRange> memoryRanges = (List<MemoryRange>) memoryTable[memoryBlockIdx];
if (memoryRanges == null) {
memoryRanges = new ArrayList<>(1);
memoryTable[memoryBlockIdx] = memoryRanges;
}
memoryRanges.add(0, memoryRange);
}
}
/**
* Add I/O device to address space.
* @param device {@link Device} to add
*/
public void addDevice(Device device) {
deviceList.add(device);
int[] deviceAddresses = device.getAddresses();
for (int deviceAddress : deviceAddresses) {
int deviceTableIndex = (deviceAddress - IO_REGISTERS_MIN_ADDRESS) >> 1;
@SuppressWarnings("unchecked")
List<Device> addressDevices = (List<Device>) deviceTable[deviceTableIndex];
if (addressDevices == null) {
addressDevices = new ArrayList<>(1);
deviceTable[deviceTableIndex] = addressDevices;
}
addressDevices.add(device);
}
}
/**
* Check is given address is mapped to ROM area.
* @param address address to check
* @return <code>true</code> if given address is mapped to ROM area,
* <code>false</code> otherwise
*/
public boolean isReadOnlyMemoryAddress(int address) {
if (address >= 0) {
List<MemoryRange> memoryRanges = getMemoryRanges(address);
if (memoryRanges == null || memoryRanges.isEmpty()) {
return false;
}
for (MemoryRange memoryRange : memoryRanges) {
if (memoryRange != null && memoryRange.isRelatedAddress(address)
&& memoryRange.getMemory() instanceof ReadOnlyMemory) {
return true;
}
}
}
return false;
}
@SuppressWarnings("unchecked")
public List<MemoryRange> getMemoryRanges(int address) {
return (List<MemoryRange>) memoryTable[address >> 12];
}
@SuppressWarnings("unchecked")
private List<Device> getDevices(int address) {
return (List<Device>) deviceTable[(address - IO_REGISTERS_MIN_ADDRESS) >> 1];
}
/**
* Initialize bus devices state (on power-on cycle or RESET opcode).
* @param isHardwareReset true if bus initialization is initiated by hardware reset,
* false if it is initiated by RESET command
*/
public void initDevices(boolean isHardwareReset) {
for (Device device: deviceList) {
device.init(getCpu().getTime(), isHardwareReset);
}
}
/**
* Reset computer state.
*/
public void reset() {
pause();
synchronized (this) {
Timber.d("resetting computer");
getCpu().reset();
}
resume();
}
/**
* Read byte or word from memory or I/O device mapped to given address.
* @param isByteMode <code>true</code> to read byte, <code>false</code> to read word
* @param address address or memory location to read
* @return read memory or I/O device data or <code>BUS_ERROR</code> in case if given memory
* location is not mapped
*/
public int readMemory(boolean isByteMode, int address) {
int readValue = BUS_ERROR;
int wordAddress = address & 0177776;
// Check for memories at given address
List<MemoryRange> memoryRanges = getMemoryRanges(address);
if (memoryRanges != null) {
for (int i = 0, memoryRangesSize = memoryRanges.size(); i < memoryRangesSize; i++) {
MemoryRange memoryRange = memoryRanges.get(i);
if (memoryRange.isRelatedAddress(address)) {
int memoryReadValue = memoryRange.getMemory().read(
wordAddress - memoryRange.getStartAddress());
if (memoryReadValue != BUS_ERROR) {
readValue = memoryReadValue;
break;
}
}
}
}
// Check for I/O registers
if (address >= IO_REGISTERS_MIN_ADDRESS) {
List<Device> subdevices = getDevices(address);
if (subdevices != null) {
long cpuClock = getCpu().getTime();
for (int i = 0, subdevicesSize = subdevices.size(); i < subdevicesSize; i++) {
Device subdevice = subdevices.get(i);
// Read and combine subdevice state values in word mode
int subdeviceReadValue = subdevice.read(cpuClock, wordAddress);
if (subdeviceReadValue != BUS_ERROR) {
readValue = (readValue == BUS_ERROR)
? subdeviceReadValue
: readValue | subdeviceReadValue;
}
}
}
}
if (readValue != BUS_ERROR) {
if (isByteMode && (address & 1) != 0) {
// Extract high byte if byte mode read from odd address
readValue >>= 8;
}
readValue &= (isByteMode ? 0377 : 0177777);
}
return readValue;
}
/**
* Write byte or word to memory or I/O device mapped to given address.
* @param isByteMode <code>true</code> to write byte, <code>false</code> to write word
* @param address address or memory location to write
* @param value value (byte/word) to write to given address
* @return <code>true</code> if data successfully written or <code>false</code>
* in case if given memory location is not mapped
*/
public boolean writeMemory(boolean isByteMode, int address, int value) {
boolean isWritten = false;
if (isByteMode && (address & 1) != 0) {
value <<= 8;
}
// Check for memories at given address
List<MemoryRange> memoryRanges = getMemoryRanges(address);
if (memoryRanges != null) {
for (int i = 0, memoryRangesSize = memoryRanges.size(); i < memoryRangesSize; i++) {
MemoryRange memoryRange = memoryRanges.get(i);
if (memoryRange.isRelatedAddress(address)) {
if (memoryRange.getMemory().write(isByteMode,
address - memoryRange.getStartAddress(), value)) {
isWritten = true;
}
}
}
}
// Check for I/O registers
if (address >= IO_REGISTERS_MIN_ADDRESS) {
List<Device> devices = getDevices(address);
if (devices != null) {
long cpuClock = getCpu().getTime();
for (int i = 0, devicesSize = devices.size(); i < devicesSize; i++) {
Device device = devices.get(i);
if (device.write(cpuClock, isByteMode, address, value)) {
isWritten = true;
}
}
}
}
return isWritten;
}
/**
* Start computer.
*/
public synchronized void start() {
if (!isRunning) {
Timber.d("starting computer");
clockThread = new Thread(this, "ComputerClockThread");
isRunning = true;
clockThread.start();
// Waiting for emulation thread start
try {
this.wait();
} catch (InterruptedException e) {
// Do nothing
}
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.start();
}
} else {
throw new IllegalStateException("Computer is already running!");
}
}
/**
* Stop computer.
*/
public void stop() {
if (isRunning) {
Timber.d("stopping computer");
isRunning = false;
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.stop();
}
synchronized (this) {
this.notifyAll();
}
while (clockThread.isAlive()) {
try {
clockThread.join();
} catch (InterruptedException e) {
// Do nothing
}
}
} else {
throw new IllegalStateException("Computer is already stopped!");
}
}
public boolean isPaused() {
return isPaused;
}
/**
* Pause computer.
*/
public void pause() {
if (!isPaused) {
Timber.d("pausing computer");
isPaused = true;
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.pause();
}
}
}
/**
* Resume computer.
*/
public void resume() {
if (isPaused) {
Timber.d("resuming computer");
systemUptimeUpdateTimestamp = System.nanoTime();
systemUptimeSyncCheckTimestampTicks = getUptimeTicks();
isPaused = false;
synchronized (this) {
this.notifyAll();
}
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.resume();
}
}
}
/**
* Release computer resources.
*/
public void release() {
Timber.d("releasing computer");
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.release();
}
if (floppyController != null) {
floppyController.unmountDiskImages();
}
if (ideController != null) {
ideController.detachDrives();
}
}
/**
* Get effective emulation clock frequency.
* @return effective emulation clock frequency (in kHz)
*/
public float getEffectiveClockFrequency() {
return (float) getCpu().getTime() * NANOSECS_IN_MSEC / getSystemUptime();
}
/**
* Get CPU time (converted from clock ticks to nanoseconds).
* @param cpuTime CPU time (in clock ticks) to convert
* @return CPU time in nanoseconds
*/
public long cpuTimeToNanos(long cpuTime) {
return cpuTime * NANOSECS_IN_MSEC / clockFrequency;
}
/**
* Get number of CPU clock ticks for given time in nanoseconds.
* @param nanosecs time (in nanoseconds) to convert to CPU ticks
* @return CPU ticks for given time
*/
public long nanosToCpuTime(long nanosecs) {
return nanosecs * clockFrequency / NANOSECS_IN_MSEC;
}
/**
* Check computer uptime is in sync with system time.
*/
private void checkUptimeSync() {
long uptimeTicks = getUptimeTicks();
if (uptimeTicks - systemUptimeSyncCheckTimestampTicks < systemUptimeSyncCheckIntervalTicks) {
return;
}
long systemTime = System.nanoTime();
systemUptime += systemTime - systemUptimeUpdateTimestamp;
systemUptimeUpdateTimestamp = systemTime;
systemUptimeSyncCheckTimestampTicks = uptimeTicks;
long uptimesDifference = getUptime() - systemUptime;
if (uptimesDifference >= UPTIME_SYNC_THRESHOLD) {
long uptimesDifferenceMillis = uptimesDifference / NANOSECS_IN_MSEC;
int uptimesDifferenceNanos = (int) (uptimesDifference % NANOSECS_IN_MSEC);
try {
this.wait(uptimesDifferenceMillis, uptimesDifferenceNanos);
} catch (InterruptedException e) {
// Do nothing
}
}
}
@Override
public void run() {
synchronized (this) {
Timber.d("computer started");
this.notifyAll();
while (isRunning) {
if (isPaused) {
Timber.d("computer paused");
while (isRunning && isPaused) {
try {
this.wait(100);
} catch (InterruptedException e) {
// Do nothing
}
}
Timber.d("computer resumed");
} else {
cpu.executeNextOperation();
notifyUptimeListeners();
checkUptimeSync();
}
}
}
Timber.d("computer stopped");
}
}
|
3cky/bkemu-android
|
app/src/main/java/su/comp/bk/arch/Computer.java
|
Java
|
gpl-3.0
| 40,937
|
//
// 1029Ca.cpp
// Problems
//
// Created by NicolasCardozo on 4/24/21.
// Copyright © 2021 NicolasCardozo. All rights reserved.
//
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
multiset<int> l, r;
pair<int, int> intervals[300010];
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> intervals[i].first >> intervals[i].second;
l.insert(intervals[i].first);
r.insert(intervals[i].second);
}
int best = 0;
for (int i = 0; i < n; ++i) {
l.erase(l.find(intervals[i].first));
r.erase(r.find(intervals[i].second));
best = max(best, *r.begin() - *l.rbegin());
l.insert(intervals[i].first);
r.insert(intervals[i].second);
}
cout << best << endl;
return 0;
}
|
mua-uniandes/weekly-problems
|
codeforces/1029/1029Ca.cpp
|
C++
|
gpl-3.0
| 800
|
/* Global layout adjustments */
html {
background: url(../../assets/img/grey_wash_wall.png);
background-attachment: fixed;
background-color: #626262;
}
body {
background-color: transparent;
font-family: Georgia;
font-size: 15px;
}
body div.container {
margin-top: 3em;
max-width: 70%;
background-color: #fefefe;
box-shadow: 0 0 15px rgba(0, 0, 0, .3);
padding-left: 5em;
padding-right: 5em;
padding-bottom: 2em;
}
/* Page header */
.page-header {
border-bottom: 1px solid #ccc;
}
/* Navbar */
ul.nav {
position: fixed;
margin-left: -8.1em;
margin-top: 4.5em;
background-color: #6495ed;
z-index: 9999999999;
}
ul.nav a {
color: black;
}
/* Headings */
/* bold the title */
.page-header h1 {
font-weight: bold;
margin-top: 2.5em;
font-size: 2em;
}
h1 {
margin-top: 1em;
font-size: 1.8em;
}
h2 {
margin-top: 1em;
font-size: 1.5em;
width: 100%;
}
h3 {
font-size: 1.2em;
}
p {
text-align: justify
}
a.navbar-brand {
font-weight: 100;
}
a.navbar-brand strong {
font-weight: 500;
}
/* Lists */
div.container ul {
margin-bottom: 1em;
}
div.paper-authors {
float: left;
font-size: 13px;
width: 80%;
}
div.paper-resource {
float: right;
font-size: 13px;
width: 20%;
text-align: right;
}
div.paper {
width: 100%;
float: center;
}
div.paper-break hr {
margin-top: 5em;
}
/* Latex */
/* make math font more similar in size to surrounding text */
.katex { font-size: 17px !important; }
/* Quotes */
blockquote {
font-family: Georgia;
font-style: italic;
font-size: 15px;
}
blockquote em {
font-style: normal
}
/* Code boxes */
.container code, .container pre.highlight, .container .wpedit .CodeMirror {
font-family: Inconsolata, monospace;
}
/* inline code */
code.highlighter-rouge {
color: black;
border: 1px solid #ddd;
}
pre.highlight, .container .wpedit .CodeMirror {
border: 1px solid #bbb;
border-radius: 4px;
white-space: pre-wrap;
background: none;
font-size: 14px;
line-height: 20px;
}
pre.highlight code {
color: #aaa;
}
pre.highlight {
margin-bottom: 45px;
padding: 4px;
}
.container .wpedit .CodeMirror {
padding: 0;
margin-bottom: 0.5em;
}
.container .wpedit button {
font-family: Inconsolata;
margin: 0 0.2em 0.5em 0;
padding: 0.3em;
border: none;
background-color: #e8e8e8;
}
.container .wpedit .drawerButton {
background-color: transparent;
font-size: 10px;
}
.container .wpedit .result pre {
background-color: transparent
}
.container .graphComponent .settings {
background-color: transparent
}
.container .wpedit .clearButton {
padding: 10px;
border: none;
background-color: transparent;
color: #ccc;
margin-right: 0 !important;
z-index: 9999;
}
/* Tables */
table {
border: 1px solid gray;
margin: 0.5em 0;
}
tr, td, th {
border: 1px solid gray;
}
td, th {
padding: 0.2em 0.4em
}
/* footnotes */
.container .bigfoot-footnote__button {
border: 1px solid gray;
margin-bottom: 0.4em;
margin-left: 0.5em;
background-color: #da7ea6
}
|
sebdumancic/RelationalDeepLearning
|
assets/css/default.css
|
CSS
|
gpl-3.0
| 3,203
|
/*
* SMInfo.h
*
* Copyright 2019 Avérous Julien-Pierre
*
* This file is part of SMFoundation.
*
* SMFoundation 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.
*
* SMFoundation 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 SMFoundation. If not, see <http://www.gnu.org/licenses/>.
*
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/*
** Defines
*/
#pragma mark - Defines
// Descriptor.
#define SMInfoNameKey @"name"
#define SMInfoTextKey @"text"
#define SMInfoDynTextKey @"dyn_text"
#define SMInfoLocalizableKey @"localizable"
/*
** Types
*/
#pragma mark - Types
typedef NS_ENUM(unsigned int, SMInfoKind) {
SMInfoInfo,
SMInfoWarning,
SMInfoError,
};
typedef NSDictionary * _Nullable (^SMInfoDescriptorBuilder)(SMInfoKind kind, int code);
typedef NSString * _Nullable (^SMInfoLocalizer)(NSString *token);
/*
** Forward
*/
#pragma mark - Forward
@class SMInfo;
/*
** SMInfo
*/
#pragma mark - SMInfo
@interface SMInfo : NSObject
// -- Properties --
@property (assign, nonatomic, readonly) SMInfoKind kind;
@property (strong, nonatomic, readonly) NSString *domain;
@property (assign, nonatomic, readonly) int code;
@property (strong, nonatomic, readonly) id context;
@property (strong, nonatomic, readonly) NSDate *timestamp;
@property (strong, nonatomic, readonly) SMInfo *subInfo;
// -- Instance --
+ (SMInfo *)infoOfKind:(SMInfoKind)kind domain:(NSString *)domain code:(int)code;
+ (SMInfo *)infoOfKind:(SMInfoKind)kind domain:(NSString *)domain code:(int)code context:(nullable id)context;
+ (SMInfo *)infoOfKind:(SMInfoKind)kind domain:(NSString *)domain code:(int)code info:(nullable SMInfo *)info;
+ (SMInfo *)infoOfKind:(SMInfoKind)kind domain:(NSString *)domain code:(int)code context:(nullable id)context info:(nullable SMInfo *)info;
// -- Descriptors --
+ (void)registerDomainsDescriptors:(NSDictionary *)descriptors localizer:(nullable SMInfoLocalizer)localizer;
// -- Rendering --
@property (nonatomic, readonly, copy) NSString * _Nonnull renderComplete;
@property (nonatomic, readonly, copy) NSString * _Nullable renderMessage;
@end
NS_ASSUME_NONNULL_END
|
javerous/framework-foundation
|
SMFoundation/SMInfo.h
|
C
|
gpl-3.0
| 2,606
|
package net.ddns.templex.commands;
import io.github.trulyfree.va.command.commands.TabbableCommand;
import io.github.trulyfree.va.daemon.Daemon;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.TabCompleteEvent;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TPAHereCommand extends TabbableCommand {
private final BaseComponent[] NO_ACTIVE_REQUESTS = new ComponentBuilder("You didn't have any active requests!").color(ChatColor.RED).create();
private final BaseComponent[] ALREADY_ACTIVE_REQUEST = new ComponentBuilder("You already have an active request!").color(ChatColor.RED).create();
private final BaseComponent[] TIMEOUT = new ComponentBuilder("Request timed out.").color(ChatColor.RED).create();
/**
* The set of currently active requests. This map is threadsafe.
*/
private final Map<ProxiedPlayer, ProxiedPlayer> requests;
/**
* The scheduler which manages request timeouts. Requests will timeout after 10 seconds.
*/
private final ScheduledExecutorService requestManager;
public TPAHereCommand() {
super("tpahere", "nonop");
this.requests = new ConcurrentHashMap<>();
requestManager = Executors.newSingleThreadScheduledExecutor();
}
@Override
public void execute(final CommandSender commandSender, String[] strings) {
if (!(commandSender instanceof ProxiedPlayer)) {
return;
}
ProxyServer proxy = ProxyServer.getInstance();
final ProxiedPlayer executor = (ProxiedPlayer) commandSender;
if (strings.length == 0) {
ProxiedPlayer target = null;
for (Map.Entry<ProxiedPlayer, ProxiedPlayer> entry : requests.entrySet()) {
if (entry.getValue().equals(executor)) {
target = entry.getKey();
break;
}
}
if (target == null) {
commandSender.sendMessage(NO_ACTIVE_REQUESTS);
} else {
requests.remove(target);
Daemon instance = Daemon.getInstanceNow();
if (instance == null) {
CommandUtil.daemonNotFound(commandSender);
return;
}
instance.submitCommands(Collections.singletonList(String.format("/tp %s %s", executor.getName(), target.getName())));
}
return;
}
if (requests.containsKey(executor)) {
commandSender.sendMessage(ALREADY_ACTIVE_REQUEST);
} else {
final ProxiedPlayer requested = proxy.getPlayer(strings[0]);
if (requested == null) {
commandSender.sendMessage(new ComponentBuilder(String.format("Didn't recognize the name %s.", strings[0])).color(ChatColor.RED).create());
} else {
commandSender.sendMessage(new ComponentBuilder(String.format("Request sent to %s", strings[0])).color(ChatColor.GREEN).create());
requested.sendMessage(new ComponentBuilder(String.format("%s requested that you TP to them! Type /tpahere to accept.", commandSender.getName())).color(ChatColor.GOLD).create());
requests.put(executor, requested);
requestManager.schedule(new Runnable() {
@Override
public void run() {
if (requests.remove(executor) != null) {
commandSender.sendMessage(TIMEOUT);
requested.sendMessage(new ComponentBuilder(String.format("Request from %s timed out.", commandSender.getName())).color(ChatColor.RED).create());
}
}
}, 10, TimeUnit.SECONDS);
}
}
}
@Override
public void handleTabCompleteEvent(TabCompleteEvent event) {
CommandUtil.pushAutocompletePlayers(event);
}
}
|
TemplexMC/TemplexAdditions
|
src/main/java/net/ddns/templex/commands/TPAHereCommand.java
|
Java
|
gpl-3.0
| 4,347
|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-6 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose 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.
#
# Rose 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 Rose. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
import os
import time
import webbrowser
import pygtk
pygtk.require('2.0')
import gtk
import rose.config
import rose.config_editor.util
import rose.gtk.dialog
class NavPanelHandler(object):
"""Handles the navigation panel menu."""
def __init__(self, data, util, reporter, mainwindow,
undo_stack, redo_stack, add_config_func,
group_ops_inst, section_ops_inst, variable_ops_inst,
kill_page_func, reload_ns_tree_func, transform_default_func,
graph_ns_func):
self.data = data
self.util = util
self.reporter = reporter
self.mainwindow = mainwindow
self.undo_stack = undo_stack
self.redo_stack = redo_stack
self.group_ops = group_ops_inst
self.sect_ops = section_ops_inst
self.var_ops = variable_ops_inst
self._add_config = add_config_func
self.kill_page_func = kill_page_func
self.reload_ns_tree_func = reload_ns_tree_func
self._transform_default_func = transform_default_func
self._graph_ns_func = graph_ns_func
def add_dialog(self, base_ns):
"""Handle an add section dialog and request."""
if base_ns is not None and '/' in base_ns:
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
config_data = self.data.config[config_name]
if config_name == base_ns:
help_str = ''
else:
sections = self.data.helper.get_sections_from_namespace(
base_ns)
if sections == []:
help_str = subsp.replace('/', ':')
else:
help_str = sections[0]
help_str = help_str.split(':', 1)[0]
for config_section in (config_data.sections.now.keys() +
config_data.sections.latent.keys()):
if config_section.startswith(help_str + ":"):
help_str = help_str + ":"
else:
help_str = None
config_name = None
choices_help = self.data.helper.get_missing_sections(config_name)
config_names = [
n for n in self.data.config if not self.ask_is_preview(n)]
config_names.sort(lambda x, y: (y == config_name) - (x == config_name))
config_name, section = self.mainwindow.launch_add_dialog(
config_names, choices_help, help_str)
if config_name in self.data.config and section is not None:
self.sect_ops.add_section(config_name, section, page_launch=True)
def ask_is_preview(self, base_ns):
namespace = "/" + base_ns.lstrip("/")
try:
config_name = self.util.split_full_ns(self.data, namespace)[0]
config_data = self.data.config[config_name]
return config_data.is_preview
except KeyError:
print config_name
return False
def copy_request(self, base_ns, new_section=None, skip_update=False):
"""Handle a copy request for a section and its options."""
namespace = "/" + base_ns.lstrip("/")
sections = self.data.helper.get_sections_from_namespace(namespace)
if len(sections) != 1:
return False
section = sections.pop()
config_name = self.util.split_full_ns(self.data, namespace)[0]
config_data = self.data.config[config_name]
return self.group_ops.copy_section(config_name, section,
skip_update=skip_update)
def create_request(self):
"""Handle a create configuration request."""
if not any([v.config_type == rose.TOP_CONFIG_NAME
for v in self.data.config.values()]):
text = rose.config_editor.WARNING_APP_CONFIG_CREATE
title = rose.config_editor.WARNING_APP_CONFIG_CREATE_TITLE
rose.gtk.dialog.run_dialog(rose.gtk.dialog.DIALOG_TYPE_ERROR,
text, title)
return False
# Need an application configuration to be created.
root = os.path.join(self.data.top_level_directory,
rose.SUB_CONFIGS_DIR)
name, meta = self.mainwindow.launch_new_config_dialog(root)
if name is None:
return False
config_name = "/" + name
self._add_config(config_name, meta)
def ignore_request(self, base_ns, is_ignored):
"""Handle an ignore or enable section request."""
config_names = self.data.config.keys()
if base_ns is not None and '/' in base_ns:
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
prefer_name_sections = {
config_name:
self.data.helper.get_sections_from_namespace(base_ns)}
else:
prefer_name_sections = {}
config_sect_dict = {}
sorter = rose.config.sort_settings
for config_name in config_names:
config_data = self.data.config[config_name]
config_sect_dict[config_name] = []
sect_and_data = list(config_data.sections.now.items())
for v_sect in config_data.vars.now:
sect_data = config_data.sections.now[v_sect]
sect_and_data.append((v_sect, sect_data))
for section, sect_data in sect_and_data:
if section not in config_sect_dict[config_name]:
if sect_data.ignored_reason:
if is_ignored:
continue
if not is_ignored:
co = sect_data.metadata.get(rose.META_PROP_COMPULSORY)
if (not sect_data.ignored_reason or
co == rose.META_PROP_VALUE_TRUE):
continue
config_sect_dict[config_name].append(section)
config_sect_dict[config_name].sort(rose.config.sort_settings)
if config_name in prefer_name_sections:
prefer_name_sections[config_name].sort(
rose.config.sort_settings)
config_name, section = self.mainwindow.launch_ignore_dialog(
config_sect_dict, prefer_name_sections, is_ignored)
if config_name in self.data.config and section is not None:
self.sect_ops.ignore_section(config_name, section, is_ignored)
def edit_request(self, base_ns):
"""Handle a request for editing section comments."""
if base_ns is None:
return False
base_ns = "/" + base_ns.lstrip("/")
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
config_data = self.data.config[config_name]
sections = self.data.helper.get_sections_from_namespace(base_ns)
for section in list(sections):
if section not in config_data.sections.now:
sections.remove(section)
if not sections:
return False
if len(sections) > 1:
section = rose.gtk.dialog.run_choices_dialog(
rose.config_editor.DIALOG_LABEL_CHOOSE_SECTION_EDIT,
sections,
rose.config_editor.DIALOG_TITLE_CHOOSE_SECTION)
else:
section = sections[0]
if section is None:
return False
title = rose.config_editor.DIALOG_TITLE_EDIT_COMMENTS.format(section)
text = "\n".join(config_data.sections.now[section].comments)
finish = lambda t: self.sect_ops.set_section_comments(
config_name, section, t.splitlines())
rose.gtk.dialog.run_edit_dialog(text, finish_hook=finish, title=title)
def fix_request(self, base_ns):
"""Handle a request to auto-fix a configuration."""
if base_ns is None:
return False
base_ns = "/" + base_ns.lstrip("/")
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
self._transform_default_func(only_this_config=config_name)
def get_ns_metadata_and_comments(self, namespace):
"""Return metadata dict and comments list."""
namespace = "/" + namespace.lstrip("/")
metadata = {}
comments = ""
if namespace is None:
return metadata, comments
metadata = self.data.namespace_meta_lookup.get(namespace, {})
comments = self.data.helper.get_ns_comment_string(namespace)
return metadata, comments
def info_request(self, namespace):
"""Handle a request for namespace info."""
if namespace is None:
return False
config_name, subsp = self.util.split_full_ns(self.data, namespace)
config_data = self.data.config[config_name]
sections = self.data.helper.get_sections_from_namespace(namespace)
search_function = lambda i: self.search_request(namespace, i)
for section in sections:
sect_data = config_data.sections.now.get(section)
if sect_data is not None:
rose.config_editor.util.launch_node_info_dialog(
sect_data, "", search_function)
def graph_request(self, namespace):
"""Handle a graph request for namespace info."""
self._graph_ns_func(namespace)
def remove_request(self, base_ns):
"""Handle a delete section request."""
config_names = self.data.config.keys()
if base_ns is not None and '/' in base_ns:
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
prefer_name_sections = {
config_name:
self.data.helper.get_sections_from_namespace(base_ns)}
else:
prefer_name_sections = {}
config_sect_dict = {}
sorter = rose.config.sort_settings
for config_name in config_names:
config_data = self.data.config[config_name]
config_sect_dict[config_name] = config_data.sections.now.keys()
config_sect_dict[config_name].sort(rose.config.sort_settings)
if config_name in prefer_name_sections:
prefer_name_sections[config_name].sort(
rose.config.sort_settings)
config_name, section = self.mainwindow.launch_remove_dialog(
config_sect_dict, prefer_name_sections)
if config_name in self.data.config and section is not None:
start_stack_index = len(self.undo_stack)
group = (
rose.config_editor.STACK_GROUP_DELETE + "-" + str(time.time()))
config_data = self.data.config[config_name]
sect_data = config_data.sections.now[section]
ns = sect_data.metadata["full_ns"]
variable_sorter = lambda v, w: rose.config.sort_settings(
v.metadata['id'], w.metadata['id'])
variables = list(config_data.vars.now.get(section, []))
variables.sort(variable_sorter)
variables.reverse()
for variable in variables:
self.var_ops.remove_var(variable)
self.sect_ops.remove_section(config_name, section)
for stack_item in self.undo_stack[start_stack_index:]:
stack_item.group = group
def search_request(self, namespace, setting_id):
"""Handle a search for an id (hyperlink)."""
config_name, subsp = self.util.split_full_ns(self.data, namespace)
self.var_ops.search_for_var(config_name, setting_id)
def popup_panel_menu(self, base_ns, event):
"""Popup a page menu on the navigation panel."""
if base_ns is None:
namespace = None
else:
namespace = "/" + base_ns.lstrip("/")
ui_config_string = """<ui> <popup name='Popup'>"""
actions = [('New', gtk.STOCK_NEW,
rose.config_editor.TREE_PANEL_NEW_CONFIG),
('Add', gtk.STOCK_ADD,
rose.config_editor.TREE_PANEL_ADD_GENERIC),
('Add section', gtk.STOCK_ADD,
rose.config_editor.TREE_PANEL_ADD_SECTION),
('Autofix', gtk.STOCK_CONVERT,
rose.config_editor.TREE_PANEL_AUTOFIX_CONFIG),
('Clone', gtk.STOCK_COPY,
rose.config_editor.TREE_PANEL_CLONE_SECTION),
('Edit', gtk.STOCK_EDIT,
rose.config_editor.TREE_PANEL_EDIT_SECTION),
('Enable', gtk.STOCK_YES,
rose.config_editor.TREE_PANEL_ENABLE_GENERIC),
('Enable section', gtk.STOCK_YES,
rose.config_editor.TREE_PANEL_ENABLE_SECTION),
('Graph', gtk.STOCK_SORT_ASCENDING,
rose.config_editor.TREE_PANEL_GRAPH_SECTION),
('Ignore', gtk.STOCK_NO,
rose.config_editor.TREE_PANEL_IGNORE_GENERIC),
('Ignore section', gtk.STOCK_NO,
rose.config_editor.TREE_PANEL_IGNORE_SECTION),
('Info', gtk.STOCK_INFO,
rose.config_editor.TREE_PANEL_INFO_SECTION),
('Help', gtk.STOCK_HELP,
rose.config_editor.TREE_PANEL_HELP_SECTION),
('URL', gtk.STOCK_HOME,
rose.config_editor.TREE_PANEL_URL_SECTION),
('Remove', gtk.STOCK_DELETE,
rose.config_editor.TREE_PANEL_REMOVE_GENERIC),
('Remove section', gtk.STOCK_DELETE,
rose.config_editor.TREE_PANEL_REMOVE_SECTION)]
url = None
help = None
is_empty = (not self.data.config)
if namespace is not None:
config_name = self.util.split_full_ns(self.data, namespace)[0]
if self.data.config[config_name].is_preview:
return False
cloneable = self.is_ns_duplicate(namespace)
is_top = (namespace in self.data.config.keys())
is_fixable = bool(self.get_ns_errors(namespace))
has_content = self.data.helper.is_ns_content(namespace)
is_unsaved = self.data.helper.get_config_has_unsaved_changes(
config_name)
ignored_sections = self.data.helper.get_ignored_sections(namespace)
enabled_sections = self.data.helper.get_ignored_sections(
namespace, get_enabled=True)
is_latent = self.data.helper.get_ns_latent_status(namespace)
latent_sections = self.data.helper.get_latent_sections(namespace)
metadata, comments = self.get_ns_metadata_and_comments(namespace)
if is_latent:
for i, section in enumerate(latent_sections):
action_name = "Add {0}".format(i)
ui_config_string += '<menuitem action="{0}"/>'.format(
action_name)
actions.append(
(action_name, gtk.STOCK_ADD,
rose.config_editor.TREE_PANEL_ADD_SECTION.format(
section.replace("_", "__")))
)
ui_config_string += '<separator name="addlatentsep"/>'
ui_config_string += '<menuitem action="Add"/>'
if cloneable:
ui_config_string += '<separator name="clonesep"/>'
ui_config_string += '<menuitem action="Clone"/>'
ui_config_string += '<separator name="ignoresep"/>'
ui_config_string += '<menuitem action="Enable"/>'
ui_config_string += '<menuitem action="Ignore"/>'
ui_config_string += '<separator name="infosep"/>'
if has_content:
ui_config_string += '<menuitem action="Info"/>'
ui_config_string += '<menuitem action="Edit"/>'
ui_config_string += '<separator name="graphsep"/>'
ui_config_string += '<menuitem action="Graph"/>'
url = metadata.get(rose.META_PROP_URL)
help = metadata.get(rose.META_PROP_HELP)
if url is not None or help is not None:
ui_config_string += '<separator name="helpsep"/>'
if url is not None:
ui_config_string += '<menuitem action="URL"/>'
if help is not None:
ui_config_string += '<menuitem action="Help"/>'
if not is_empty:
ui_config_string += """<separator name="removesep"/>"""
ui_config_string += """<menuitem action="Remove"/>"""
if is_fixable:
ui_config_string += """<separator name="sepauto"/>
<menuitem action="Autofix"/>"""
else:
ui_config_string += '<menuitem action="Add"/>'
ui_config_string += '<separator name="ignoresep"/>'
ui_config_string += '<menuitem action="Enable"/>'
ui_config_string += '<menuitem action="Ignore"/>'
if namespace is None or (is_top or is_empty):
ui_config_string += """<separator name="newconfigsep"/>
<menuitem action="New"/>"""
ui_config_string += """</popup> </ui>"""
uimanager = gtk.UIManager()
actiongroup = gtk.ActionGroup('Popup')
actiongroup.add_actions(actions)
uimanager.insert_action_group(actiongroup, pos=0)
uimanager.add_ui_from_string(ui_config_string)
if namespace is None or (is_top or is_empty):
new_item = uimanager.get_widget('/Popup/New')
new_item.connect("activate", lambda b: self.create_request())
new_item.set_sensitive(not is_empty)
add_item = uimanager.get_widget('/Popup/Add')
add_item.connect("activate", lambda b: self.add_dialog(namespace))
add_item.set_sensitive(not is_empty)
enable_item = uimanager.get_widget('/Popup/Enable')
enable_item.connect(
"activate", lambda b: self.ignore_request(namespace, False))
enable_item.set_sensitive(not is_empty)
ignore_item = uimanager.get_widget('/Popup/Ignore')
ignore_item.connect(
"activate", lambda b: self.ignore_request(namespace, True))
ignore_item.set_sensitive(not is_empty)
if namespace is not None:
if is_latent:
for i, section in enumerate(latent_sections):
action_name = "Add {0}".format(i)
add_item = uimanager.get_widget("/Popup/" + action_name)
add_item._section = section
add_item.connect(
"activate",
lambda b: self.sect_ops.add_section(
config_name, b._section))
if cloneable:
clone_item = uimanager.get_widget('/Popup/Clone')
clone_item.connect("activate",
lambda b: self.copy_request(namespace))
if has_content:
edit_item = uimanager.get_widget('/Popup/Edit')
edit_item.connect("activate",
lambda b: self.edit_request(namespace))
info_item = uimanager.get_widget('/Popup/Info')
info_item.connect("activate",
lambda b: self.info_request(namespace))
graph_item = uimanager.get_widget("/Popup/Graph")
graph_item.connect("activate",
lambda b: self.graph_request(namespace))
if is_unsaved:
graph_item.set_sensitive(False)
if help is not None:
help_item = uimanager.get_widget('/Popup/Help')
help_title = namespace.split('/')[1:]
help_title = rose.config_editor.DIALOG_HELP_TITLE.format(
help_title)
search_function = lambda i: self.search_request(namespace, i)
help_item.connect(
"activate",
lambda b: rose.gtk.dialog.run_hyperlink_dialog(
gtk.STOCK_DIALOG_INFO, help, help_title,
search_function))
if url is not None:
url_item = uimanager.get_widget('/Popup/URL')
url_item.connect(
"activate", lambda b: webbrowser.open(url))
if is_fixable:
autofix_item = uimanager.get_widget('/Popup/Autofix')
autofix_item.connect("activate",
lambda b: self.fix_request(namespace))
remove_section_item = uimanager.get_widget('/Popup/Remove')
remove_section_item.connect(
"activate", lambda b: self.remove_request(namespace))
menu = uimanager.get_widget('/Popup')
menu.popup(None, None, None, event.button, event.time)
return False
def is_ns_duplicate(self, namespace):
"""Lookup whether a page can be cloned, via the metadata."""
sections = self.data.helper.get_sections_from_namespace(namespace)
if len(sections) != 1:
return False
section = sections.pop()
config_name = self.util.split_full_ns(self.data, namespace)[0]
sect_data = self.data.config[config_name].sections.now.get(section)
if sect_data is None:
return False
return (sect_data.metadata.get(rose.META_PROP_DUPLICATE) ==
rose.META_PROP_VALUE_TRUE)
def get_ns_errors(self, namespace):
"""Count the number of errors in a namespace."""
config_name = self.util.split_full_ns(self.data, namespace)[0]
config_data = self.data.config[config_name]
sections = self.data.helper.get_sections_from_namespace(namespace)
errors = 0
for section in sections:
errors += len(config_data.sections.get_sect(section).error)
real_data, latent_data = self.data.helper.get_data_for_namespace(
namespace)
errors += sum([len(v.error) for v in real_data + latent_data])
return errors
def get_ns_ignored(self, base_ns):
"""Lookup the ignored status of a namespace's data."""
namespace = "/" + base_ns.lstrip("/")
return self.data.helper.get_ns_ignored_status(namespace)
def get_can_show_page(self, latent_status, ignored_status, has_error):
"""Lookup whether to display a page based on the data status."""
if has_error or (not ignored_status and not latent_status):
# Always show this.
return True
show_ignored = self.data.page_ns_show_modes[
rose.config_editor.SHOW_MODE_IGNORED]
show_user_ignored = self.data.page_ns_show_modes[
rose.config_editor.SHOW_MODE_USER_IGNORED]
show_latent = self.data.page_ns_show_modes[
rose.config_editor.SHOW_MODE_LATENT]
if latent_status:
if not show_latent:
# Latent page, no latent pages allowed.
return False
# Latent page, latent pages allowed (but may be ignored...).
if ignored_status:
if ignored_status == rose.config.ConfigNode.STATE_USER_IGNORED:
if show_ignored or show_user_ignored:
# This is an allowed user-ignored page.
return True
# This is a user-ignored page that isn't allowed.
return False
# This is a trigger-ignored page that may be allowed.
return show_ignored
# This is a latent page that isn't ignored, latent pages allowed.
return True
|
kaday/rose
|
lib/python/rose/config_editor/nav_panel_menu.py
|
Python
|
gpl-3.0
| 24,642
|
package com.ebrightmoon.doraemonkit.ui.dialog;
/**
* Created by wanglikun on 2019/4/12
*/
public interface DialogListener {
boolean onPositive();
boolean onNegative();
void onCancel();
}
|
jinsedeyuzhou/NewsClient
|
doraemonkit/src/main/java/com/ebrightmoon/doraemonkit/ui/dialog/DialogListener.java
|
Java
|
gpl-3.0
| 203
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-11-30 03:32
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('administrador', '0011_auto_20171129_2215'),
]
operations = [
migrations.AlterField(
model_name='respuesta',
name='fecha',
field=models.DateTimeField(blank=True, default=datetime.datetime(2017, 11, 29, 22, 32, 35, 304385), null=True),
),
]
|
adbetin/organico-cooperativas
|
administrador/migrations/0012_auto_20171129_2232.py
|
Python
|
gpl-3.0
| 548
|
<?xml version="1.0" encoding="utf-8"?>
<!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" xml:lang="en" lang="en">
<head>
<title>attribute.rb</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../../../css/github.css" type="text/css" media="screen" />
<script src="../../../../../../../../../../../../../../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.2.6</span><br />
<h1>
attribute.rb
</h1>
<ul class="files">
<li>
../../.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.6/lib/active_support/core_ext/class/attribute.rb
</li>
<li>Last modified: 2017-05-02 14:15:01 -0600</li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<!-- File only: requires -->
<div class="sectiontitle">Required Files</div>
<ul>
<li>active_support/core_ext/kernel/singleton_class</li>
<li>active_support/core_ext/module/remove_method</li>
<li>active_support/core_ext/array/extract_options</li>
</ul>
<!-- Namespace -->
<div class="sectiontitle">Namespace</div>
<ul>
<li>
<span class="type">CLASS</span>
<a href="../../../../../../../../../../../../../../../../classes/Class.html">Class</a>
</li>
</ul>
<!-- Methods -->
</div>
</div>
</body>
</html>
|
Dpasi314/DevConnect
|
project/doc/api/files/__/__/_rbenv/versions/2_4_0/lib/ruby/gems/2_4_0/gems/activesupport-4_2_6/lib/active_support/core_ext/class/attribute_rb.html
|
HTML
|
gpl-3.0
| 2,509
|
\chapter{Модуль работы с портами ввода-вывода общего назначения (PORT)}\label{port:0}
Данный модуль состоит из следующих классов:
\begin{itemize}
\item \textbf{pin} (раздел~\ref{class:pin});
\item \textbf{global\_port} (раздел~\ref{class:global:port});
\end{itemize}
\section{Класс pin}\label{class:pin}
\subsection{Общие сведения о классе}
Объект данного класса позволяет работать с конкретным выводом порта.
\subsection{Методы класса pin}
\begin{itemize}
\item \textbf{constexpr pin ( const pin\_config\_t* const pin\_cfg\_array, uint8\_t size = 1 );}\\Конструктор класса принимает указатель на структуру/массив структур конфигурации режима(-ов) работы вывода.\\\textbf{Замечание 1: } в случае, если метод \textbf{reinit} объекта будет использован в коде пользователя или драйверах высокого уровня, структура/массив структур, на которую(-ый) ссылается указатель, полностью попадает во flash. В связи с тем, что метод \textbf{reinit} будет использовать структуру/элемент массива.
\\\textbf{Замечание 2: }важно понимать, что все структуры конфигурации вывода (в случае, если передаётся указатель на массив структур) должны относится к одному физическому выводу (изменяя лишь режим его работы).
\\\textbf{Замечание 3: }В случае, если в качестве параметра выступая единичная структура, а не массив структур, второй параметр указывать н нужно.
\item \textbf{void set ( void ) const;}\\Устанавливает 1 на выводе, если вывод сконфигурирован как выход;
\item \textbf{void reset ( void ) const;}\\Устанавливает 0 на выводе, если вывод сконфигурирован как выход;
\item \textbf{void set ( uint8\_t state ) const;}\\Устанавливает заданное состояние на выводе (1 или 0), если вывод сконфигурирован как выход;
\item \textbf{void set ( bool state ) const;}\\Устанавливает заданное состояние на выводе (true == 1 или false == 0), если вывод сконфигурирован как выход;
\item \textbf{void set ( int state ) const;}\\Устанавливает заданное состояние на выводе (1 или 0), если вывод сконфигурирован как выход;
\item \textbf{void invert ( void ) const;}\\Логическое \textbf{НЕ} состояния на выходе вывода, если вывод сконфигурирован как выход;
\item \textbf{int read ( void ) const;}\\Возвращает логическое состояние на входе вывода, если вывод сконфигурирован как вход;
\item \textbf{EC\_ANSWER\_PIN\_REINIT reinit (uint8\_t number\_config) const;}\\Переинициализирует вывод в ходе выполнения программы в выбранную конфигурацию.\\\textbf{Замечание: }первичная инициализация вывода по нулевой (0) структуре производится объектом \textit{global\_port}. Что избавляет от надобности начальной инициализации вывода. Данный метод следует вызывать, если требуется изменить конфигурацию вывода на иную в ходе выполнения программы (при условии, что он не был заблокирован объектом \textit{global\_port}).\\\textbf{Возвращаемое значение:}
\begin{itemize}
\item \textbf{OK} - вывод был успешно переинициализирован;
\item \textbf{LOCKED} - конфигурация вывода была заблокирована;
\item \textbf{CFG\_NUMBER\_ERROR} - вы попытались инициализировать вывод несуществующей конфигурацией;
\end{itemize}
\end{itemize}
\section{Класс global\_port}\label{class:global:port}
\subsection{Общие сведения о классе}
Объект данного класса позволяет работать со всеми имеющимися в контроллере портами ввода-вывода. В проекте должен быть один экземпляр (объект) данного класса. Объект предоставляет следующие возможности:
\begin{itemize}
\item переинициализация конкретных или всех портов (при условии, что те не были заблокированы);
\item блокировка конкретных или всех портов;
\item получение данных о текущем состоянии блокировки;
\end{itemize}
\subsection{Методы класса global\_port}
\begin{itemize}
\item \textbf{constexpr global\_port ( const pin\_config\_t* const pin\_cfg\_array, const uint32\_t pin\_count );
}\\Конструктор класса принимает указатель на структуру/массив структур конфигурации режима(-ов) работы вывода(-ов). Сами структуры во flash загружены не будут (при условии, что они не были повторно использованы ещё и объектом класса \textit{pin}).\\На основе этих структур создаётся внутренняя структура \textit{gb\_msk\_struct}, содержащая в себе массив масок портов, физически разведённых в корпусе контроллера. Важно заметит следующее:
\begin{itemize}
\item размер массива зависит только от количества физически разведённых портов в корпусе контроллера и не зависит от количества переданных структур конфигурации выводов;
\item на каждый физический вывод контроллера должна приходиться только одна структура конфигурации;
\item в случае, если по ошибке будет передано несколько структур инициализации, ссылающиеся на один вывод, в итоговом массиве масок будет последняя конфигурация из массива структур;
\item для тех выводов, для которых не было передано структуры инициализации, будет выбрана конфигурация по-умолчанию;
\end{itemize}
\item \textbf{E\_ANSWER\_GP reinit\_all\_ports ( void ) const;}\\Метод инициализирует в реальном времени все порты ввода-вывода контроллера, основываясь на переданной(-ом) во время формирования объекта \textit{pin\_config} структуре/массиве структур (используется созданная конструктором структура с массивом масок портов).\\\textbf{Возвращаемое значение:}
\begin{itemize}
\item \textbf{SUCCESS} - переинициализация прошла успешно;
\item \textbf{LOOK} - порт заблокирован, переинициализация некоторых (или всех) выводов какого-то (или всех) порта(-ов) невозможна.\\\textbf{Заметка: } Может быть, что выводы одного или нескольких портов не были переинициализированы. В случае обнаружения блокировки порта производится попытка переинициализации (на случай, если требуется переинициализировать те выводы, которые заблокированы не были). Данное поведение можно изменить, раскомментировав define \textit{NO\_REINIT\_PORT\_AFTER\_LOOKING} в файле \textit{stm32\_f20x\_f21x\_conf.h}. В этом случае, если порт был заблокирован ранее - попытки переинициализировать его не производится и метод переходит к следующему порту.\\Если хоть один порт из имеющихся был ранее заблокирован, то будет возвращено именно \textbf{LOOK}, даже если другие были успешно проинициализированы.
\end{itemize}
\item \textbf{E\_ANSWER\_GP reinit\_port ( EC\_PORT\_NAME port ) const;}\\Метод переинициализирует конкретный порт, основываясь на переданной(-ом) во время формирования объекта \textit{pin\_config} структуре/массиве структур (используются созданная конструктором структура с массивам масок портов).\\\textbf{Возвращаемое значение:}
\begin{itemize}
\item \textbf{SUCCESS} - переинициализация прошла успешно;
\item \textbf{LOOK} - порт заблокирован, переинициализация некоторых (или всех) выводов порта невозможна.\\\textbf{Заметка: } В случае обнаружения блокировки порта производится попытка переинициализации (на случай, если требуется переинициализировать те выводы, которые заблокированы не были). Данное поведение можно изменить, раскомментировав define \textit{NO\_REINIT\_PORT\_AFTER\_LOOKING} в файле \textit{stm32\_f20x\_f21x\_conf.h}. В этом случае, если порт был заблокирован ранее - попытки переинициализировать его не производится и работа мететода на этом заканчивается (будет возвращен \textbf{LOOK}).
\end{itemize}
\item \textbf{E\_PORT\_LOCKED\_KEY get\_state\_locked\_key\_port ( EC\_PORT\_NAME port ) const;}\\Метод возвращает состояние ключа блокировки порта.\\\textbf{Возвращаемое значение:}
\begin{itemize}
\item \textbf{SET} - порт уже заблокирован;
\item \textbf{RESET} - порт не был заблокирован.
\end{itemize}
\item \textbf{E\_ANSWER\_PORT\_SET\_LOCK set\_locked\_key\_port ( EC\_PORT\_NAME port ) const;}\\Метод блокирует конфигурацию выводов порта, подлежащих блокировке.\\\textbf{Возвращаемое значение:}
\begin{itemize}
\item \textbf{OK} - конфигурации выводов, в структурах конфигурации которых значилось, что их можно блокировать, были успешно заблокированы (порт успешно заблокирован);
\item \textbf{ALREADY} - порт был ранее заблокирован;
\item \textbf{ERROR} - после попытки блокировки порта, порт не был заблокирован (вероятнее всего, на порт не был подан сигнал тактирования);
\end{itemize}
\item \textbf{E\_ANSWER\_PORT\_SET\_LOCK set\_locked\_keys\_all\_port ( void ) const; }\\Метод блокирует конфигурацию выводов, подлежащих блокировке, во всех портах.\\\textbf{Возвращаемое значение:}
\begin{itemize}
\item \textbf{OK} - все порты были успешно заблокированы;
\item \textbf{ALREADY} - один из портов был ранее заблокирован;
\item \textbf{ERROR} - после попытки блокировки порта, один из портов (или все) не был заблокирован (вероятнее всего, на один (или все) из порт не был подан сигнал тактирования);
\end{itemize}
\end{itemize}
\subsection{Замечания к классу global\_port}
\begin{itemize}
\item В случае, если некоторые (или все) выводы порта/портов были заблокированы, попытка переинициализации выводов методами \textit{reinit\_all\_ports} и \textit{reinit\_port} все равно производится.\\Это нужно на случай, когда требуется переинициализировать некоторые (1 и более) выводов не трогая другие. Данное поведение можно сменить в stm32\_f20x\_f21x\_conf.h, раскомментировав define \textbf{NO\_\-REINIT\_\-PORT\_\-AFTER\_\-LOOKING}.
\end{itemize}
|
Vadimatorik/stm32f2_api
|
doc/part/module/chapter/port.tex
|
TeX
|
gpl-3.0
| 14,471
|
/**
* @file Surface Component
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
import { ComponentRegistry } from "../globals.js";
import { defaults } from "../utils.js";
import Component from "./component.js";
/**
* Component wrapping a Surface object
* @class
* @extends Component
* @param {Stage} stage - stage object the component belongs to
* @param {Surface} surface - surface object to wrap
* @param {ComponentParameters} params - component parameters
*/
function SurfaceComponent( stage, surface, params ){
var p = params || {};
p.name = defaults( p.name, surface.name );
Component.call( this, stage, p );
this.surface = surface;
}
SurfaceComponent.prototype = Object.assign( Object.create(
Component.prototype ), {
constructor: SurfaceComponent,
/**
* Component type
* @alias SurfaceComponent#type
* @constant
* @type {String}
* @default
*/
type: "surface",
/**
* Add a new surface representation to the component
* @alias SurfaceComponent#addRepresentation
* @param {String} type - the name of the representation, one of:
* surface, dot.
* @param {SurfaceRepresentationParameters} params - representation parameters
* @return {RepresentationComponent} the created representation wrapped into
* a representation component object
*/
addRepresentation: function( type, params ){
return Component.prototype.addRepresentation.call(
this, type, this.surface, params
);
},
dispose: function(){
this.surface.dispose();
Component.prototype.dispose.call( this );
},
centerView: function( zoom ){
var center = this.surface.center;
if( zoom ){
zoom = this.surface.boundingBox.size().length();
}
this.viewer.centerView( zoom, center );
},
} );
ComponentRegistry.add( "surface", SurfaceComponent );
export default SurfaceComponent;
|
deepchem/deepchem-gui
|
gui/static/ngl/src/component/surface-component.js
|
JavaScript
|
gpl-3.0
| 2,061
|
from django.db import models
from wagtail.core.models import Page
from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel
from wagtail.core.fields import StreamField
from wagtail.core import blocks
from wagtail.images.blocks import ImageChooserBlock
from test.anotherapp.models import HomePage
class AnotherTest(Page):
"""
This model is entirely NOT translated.
This could be normal for some kind of page that's individual to every
language.
"""
field_that_is_not_translated = models.CharField(max_length=255, null=True, blank=True)
content_panels = [
FieldPanel("field_that_is_not_translated"),
StreamFieldPanel("body"),
]
body = StreamField(
[
("heading", blocks.CharBlock(classname="full title")),
("paragraph", blocks.RichTextBlock()),
("image", ImageChooserBlock()),
],
verbose_name="body",
blank=True,
help_text="The main contents of the page",
)
def get_context(self, request):
context = super().get_context(request)
context['test'] = self.get_children().live()
return context
class Test(Page):
"""
This model is translated
"""
field_that_is_translated = models.CharField(max_length=255, null=True, blank=True)
field_that_is_not_translated = models.CharField(max_length=255, null=True, blank=True)
class InheritsFromHomePageTranslated(HomePage):
"""
This model is translated but inherits from a non-translated parent.
This could be normal for some kind of page that's individual to every
language.
"""
field_that_is_translated = models.CharField(max_length=255, null=True, blank=True)
field_that_is_not_translated = models.CharField(max_length=255, null=True, blank=True)
class InheritsFromPageTranslated(Page):
"""
This model is translated but inherits from a non-translated parent.
This could be normal for some kind of page that's individual to every
language.
"""
field_that_is_translated = models.CharField(max_length=255, null=True, blank=True)
field_that_is_not_translated = models.CharField(max_length=255, null=True, blank=True)
|
benjaoming/django-modeltranslation-wagtail
|
test/transapp/models.py
|
Python
|
gpl-3.0
| 2,238
|
# daisy-extract
# Copyright (C) 2016 James Scholes
# This program is free software, licensed under the terms of the GNU General Public License (version 3 or later).
# See the file LICENSE for more details.
from collections import namedtuple
import argparse
import glob
import logging
import os
import platform
import shutil
import sys
from bs4 import BeautifulSoup
from natsort import natsorted
__version__ = '0.1'
is_windows = 'windows' in platform.system().lower()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
log_stream = logging.StreamHandler(sys.stdout)
log_stream.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
logger.addHandler(log_stream)
HTML_PARSER = 'html.parser'
NCC_FILENAME = 'NCC.HTML'
MASTER_SMIL_FILENAME = 'MASTER.SMIL'
SMIL_GLOB = '*.[sS][mM][iI][lL]'
BookMetadata = namedtuple('BookMetadata', ('authors', 'title'))
class InvalidDAISYBookError(Exception):
pass
class ExtractMetadataError(Exception):
pass
def main():
logger.info('daisy-extract version {0}'.format(__version__))
cli_args = parse_command_line()
if cli_args.debug:
logger.setLevel(logging.DEBUG)
encoding = getattr(cli_args, 'encoding', 'utf-8')
input_directory = os.path.abspath(cli_args.input_directory)
output_directory = os.path.abspath(cli_args.output_directory)
if not os.path.exists(input_directory) or not os.path.isdir(input_directory):
exit_with_error('{0} does not exist or is not a directory'.format(input_directory))
try:
metadata = create_metadata_object_from_ncc(find_ncc_path(input_directory), encoding=encoding)
except InvalidDAISYBookError as e:
exit_with_error('The contents of {0} don\'t seem to be a valid DAISY 2.02 book: {1}'.format(input_directory, str(e)))
except ExtractMetadataError as e:
exit_with_error(str(e))
output_directory = os.path.join(output_directory, make_safe_filename(metadata.authors), make_safe_filename(metadata.title))
logger.info('Extracting content of book: {0} by {1} from {2} to {3}'.format(metadata.title, metadata.authors, input_directory, output_directory))
source_audio_files = []
destination_audio_files = []
for doc in find_smil_documents(input_directory):
parsed_doc = parse_smil_document(doc, encoding=encoding)
try:
section_title = find_document_title(parsed_doc)
logger.debug('Found SMIL document: {0}'.format(section_title))
except ExtractMetadataError as e:
exit_with_error('Could not retrieve metadata from SMIL document ({0}): {1}'.format(file, str(e)))
section_audio_files = get_audio_filenames_from_smil(parsed_doc)
logger.debug('SMIL document spans {0} audio file(s)'.format(len(section_audio_files)))
for audio_file in section_audio_files:
source_audio_files.append((section_title, os.path.join(input_directory, audio_file)))
logger.info('Copying {0} audio files'.format(len(source_audio_files)))
try:
os.makedirs(output_directory)
logger.debug('Created directory: {0}'.format(output_directory))
except (FileExistsError, PermissionError):
pass
track_number = 1
for section_name, file_path in source_audio_files:
destination_filename = '{0:02d} - {1}.{2}'.format(track_number, make_safe_filename(section_name), os.path.splitext(file_path)[-1][1:].lower())
destination_path = os.path.join(output_directory, destination_filename)
logger.debug('Copying file: {0} to: {1}'.format(file_path, destination_path))
if is_windows:
destination_path = add_path_prefix(destination_path)
shutil.copyfile(file_path, destination_path)
destination_audio_files.append(os.path.split(destination_path)[-1])
track_number += 1
logger.info('Creating M3U playlist')
playlist_filename = '{0}.m3u'.format(make_safe_filename(metadata.title))
playlist_path = os.path.join(output_directory, playlist_filename)
logger.debug('M3U playlist path: {0}'.format(playlist_path))
if is_windows:
playlist_path = add_path_prefix(playlist_path)
with open(playlist_path, 'w', newline=None) as f:
f.write('\n'.join(destination_audio_files))
logger.info('Done!')
def parse_command_line():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input-directory', nargs='?', required=True)
parser.add_argument('-o', '--output-directory', nargs='?', required=True)
parser.add_argument('-e', '--encoding', nargs='?', required=False)
parser.add_argument('-d', '--debug', dest='debug', action='store_true', default=False, help='Enable debug logging')
args = parser.parse_args()
return args
def exit_with_error(message):
logger.error(message)
sys.exit(1)
def find_ncc_path(directory):
filenames = (NCC_FILENAME, NCC_FILENAME.lower())
for filename in filenames:
path = os.path.join(directory, filename)
if os.path.exists(path) and os.path.isfile(path):
logger.debug('Found NCC file: {0}'.format(path))
return path
raise InvalidDAISYBookError('Could not find NCC file')
def find_smil_documents(directory):
documents = list(filter(lambda smil: not smil.upper().endswith(MASTER_SMIL_FILENAME), glob.iglob(os.path.join(directory, SMIL_GLOB))))
if documents:
logger.debug('Found {0} SMIL documents in directory'.format(len(documents)))
return natsorted(documents)
else:
raise InvalidDAISYBookError('No SMIL documents found')
def create_metadata_object_from_ncc(ncc_path, encoding='utf-8'):
with open(ncc_path, 'r', encoding=encoding) as f:
ncc = BeautifulSoup(f, HTML_PARSER)
title_tag = ncc.find('meta', attrs={'name': 'dc:title'})
if title_tag is None:
raise ExtractMetadataError('The title of the DAISY book could not be found')
title = title_tag.attrs.get('content')
if not title:
raise ExtractMetadataError('The title of the DAISY book is blank')
creator_tags = ncc.find_all('meta', attrs={'name': 'dc:creator'})
if not creator_tags:
raise ExtractMetadataError('No authors are listed in the DAISY book')
authors = ', '.join([tag.attrs.get('content') for tag in creator_tags])
return BookMetadata(authors, title)
def parse_smil_document(path, encoding='utf-8'):
logger.debug('Parsing SMIL document: {0}'.format(os.path.split(path)[-1]))
with open(path, 'r', encoding=encoding) as f:
return BeautifulSoup(f, HTML_PARSER)
def find_document_title(doc):
title_tag = doc.find('meta', attrs={'name': 'title'})
if title_tag is None:
raise ExtractMetadataError('Unable to extract title from SMIL document')
title = title_tag.attrs.get('content')
if not title:
raise ExtractMetadataError('SMIL document has no title')
return title
def get_audio_filenames_from_smil(smil):
audio_files = [audio.attrs.get('src') for audio in smil.find_all('audio')]
unique_audio_files = []
for file in audio_files:
if file not in unique_audio_files:
unique_audio_files.append(file)
return tuple(unique_audio_files)
def add_path_prefix(path):
return '\\\\?\\{0}'.format(path)
def make_safe_filename(filename):
# strip out any disallowed chars and replace with underscores
disallowed_ascii = [chr(i) for i in range(0, 32)]
disallowed_chars = '<>:"/\\|?*^{0}'.format(''.join(disallowed_ascii))
translator = dict((ord(char), '_') for char in disallowed_chars)
safe_filename = filename.replace(': ', ' - ').translate(translator).rstrip('. ')
return safe_filename
if __name__ == '__main__':
main()
|
jscholes/daisy-extract
|
extract.py
|
Python
|
gpl-3.0
| 7,728
|
# alienspace51-tool
Ferramenta de auxilio a testes de penetração em sistemas operacionais web , desktops e dispositivos mobiles...
|
Mundo-Unix/alienspace51-tool
|
README.md
|
Markdown
|
gpl-3.0
| 133
|
package com.abada.trazability.datamatrix.decode;
/*
* #%L
* Contramed
* %%
* Copyright (C) 2013 Abada Servicios Desarrollo (investigacion@abadasoft.com)
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import com.abada.trazability.datamatrix.code.Codificar;
import com.abada.trazability.datamatrix.dato.DatosCodeDecode;
import com.abada.trazability.datamatrix.dato.DatosExponentePeso;
import com.abada.trazability.datamatrix.dato.DatosExponenteVolumen;
import com.abada.trazability.datamatrix.dato.ObjectPeso;
import com.abada.trazability.datamatrix.dato.ObjectVolumen;
import com.abada.trazability.datamatrix.exceptions.ExceptionCodeDecode;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*Decodificar una cadena en formato GS1
* @author maria
*/
public class DecodeImpl implements Decode {
private static final Log logger=LogFactory.getLog(DecodeImpl.class);
/**
* Metodo para codificar en forma legible por el humano un string que representa
* un formato GS1.
* @param ent
* @return map
*/
public Map<DatosCodeDecode, Object> decode(String ent) {
logger.debug("Entrada: "+ ent);
CompruebaDecode cd = new CompruebaDecode();
String sinparen = cd.quitaParentesis(ent);
String a;
if (sinparen.startsWith(Codificar.START_TAG)) {
a = sinparen.substring(3, sinparen.length());
} else {
a = sinparen;
}
Map<DatosCodeDecode, Object> cadenadeco = new HashMap<DatosCodeDecode, Object>();
/**
* Comprobamos que el tamaño del String de entrada es correcto, sino algun
* campo no estara bien codificado
* El tamaño correcto se corresponde con :
* GTIN n2+n14
* BATCH n2+X..20
* Expirate Date n2+n6 en formato YYMMDD
* Serial Number n2+X..20
* Wigeht n4+n6
* Dimension n4+n6
* En total tendremos 86 caracteres, teniendo en cuenta que se va a expresar el GTIN con 13 caracteres
*/
if (a.length() > 86) {
//new ExceptionCodeDecode("Cadena a decodificar incorrecta");
String cad = "The size of the chain is superior to the allowed one";
//FIXME falta lanzar la excepcion new ExceptionCodeDecode(cad);
} else {
String falta = "";
while (a.length() != 0) {
try {
if (a.substring(0, 1).equals(".")) {
return cadenadeco;
}
DatosCodeDecode dato = cd.recogecaso(a);
switch (dato) {
case EAN13:
//GTIN
falta = a.substring(16, a.length());
cadenadeco.put(dato.EAN13, a.substring(2, 16));
a = falta;
break;
case BATCH:
//BATCH
//La longitud Es variable a como maximo 20 caracteres
int maximalong = cd.comprobarLongitud(a.substring(2, a.length()), 20);
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == ('<') || (a.charAt(i) == '.')) {
if (a.charAt(i) == ('<')) {
falta = a.substring(maximalong + 2, a.length());
cadenadeco.put(dato.BATCH, a.substring(2, maximalong - 2));
break;
} else {
falta = a.substring(maximalong, a.length());
cadenadeco.put(dato.BATCH, a.substring(2, maximalong));
break;
}
}
}
a = falta;
break;
case EXPIRATEDATE:
//EXPIRATEDATE
falta = a.substring(8, a.length());
String fecha = a.substring(2, 8);
Calendar cal = cd.fechaCalendar(fecha);
cadenadeco.put(dato.EXPIRATEDATE, cal);
a = falta;
break;
case SERIALNUMBER:
//SerialNumber
//La longitud Es variable a como maximo 20 caracteres
int maxlong = cd.comprobarLongitud(a.substring(2, a.length()), 20);
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == ('<') || (a.charAt(i) == '.')) {
if (a.charAt(i) == ('<')) {
falta = a.substring(maxlong + 2, a.length());
cadenadeco.put(dato.SERIALNUMBER, a.substring(2, maxlong - 2));
break;
} else {
falta = a.substring(maxlong, a.length());
cadenadeco.put(dato.SERIALNUMBER, a.substring(2, maxlong));
break;
}
}
}
a = falta;
break;
case WEIGHT:
//Net weight, kilograms (Variable Measure Trade Item)
//Longitud fija de 6 caracteres, por eso al comprobar la cantidad de decimales
//que puede representar sera como maximo 5
ObjectPeso op = new ObjectPeso();
falta = falta = a.substring(10, a.length());
DatosExponentePeso caso = cd.recogeExpoPeso(a);
op.setExpo(caso);
String expop = cd.escribeExpoPeso(a, caso);
Double peso = Double.parseDouble(expop);
op.setValor(peso);
cadenadeco.put(dato.WEIGHT, op);
a = falta;
break;
case DIMENSION:
ObjectVolumen ov = new ObjectVolumen();
falta = falta = a.substring(10, a.length());
DatosExponenteVolumen volum = cd.recogeExpoVolumen(a);
ov.setExpo(volum);
String expov = cd.escribeExpoVolumen(a, volum);
Double volumen = Double.parseDouble(expov);
ov.setValor(volumen);
cadenadeco.put(dato.DIMENSION, ov);
a = falta;
break;
default:
break;
}
} catch (ExceptionCodeDecode ex) {
logger.error(ex);
}
}
}
return cadenadeco;
}
}
|
abada-investigacion/contramed
|
trazability/trazability-datamatrix-utils/src/main/java/com/abada/trazability/datamatrix/decode/DecodeImpl.java
|
Java
|
gpl-3.0
| 8,180
|
/*
* Copyright (C) 2015 Cybernetica
*
* Research/Commercial License Usage
* Licensees holding a valid Research License or Commercial License
* for the Software may use this file according to the written
* agreement between you and Cybernetica.
*
* 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-3.0.html.
*
* For further information, please contact us at sharemind@cyber.ee.
*/
#ifndef MOD_SHARED3P_EMU_SYSCALLS_META_H
#define MOD_SHARED3P_EMU_SYSCALLS_META_H
#include <sharemind/module-apis/api_0x1.h>
#include <sharemind/VmVector.h>
#include "Common.h"
#include "../Shared3pPDPI.h"
/**
* Meta-syscalls for many common cases.
*/
namespace sharemind {
/**
* SysCall: binary_vec<T1, T2, T3, Protocol>
* Args:
* 0) uint64[0] pd index
* 1) p[0] LHS handle
* 2) p[0] RHS handle
* 2) p[0] output handle
* Precondition:
* LHS handle is a vector of type T1.
* RHS handle is a vector of type T2.
* Output handle is a vector of type T3.
*/
template <typename T1, typename T2, typename T3, typename Protocol>
NAMED_SYSCALL(binary_vec, name, args, num_args, refs, crefs, returnValue, c)
{
VMHandles handles;
if (!SyscallArgs<4>::check(num_args, refs, crefs, returnValue) ||
!handles.get(c, args))
{
return SHAREMIND_MODULE_API_0x1_INVALID_CALL;
}
try {
Shared3pPDPI * const pdpi = static_cast<Shared3pPDPI*>(handles.pdpiHandle);
void * const lhsHandle = args[1u].p[0u];
void * const rhsHandle = args[2u].p[0u];
void * const resultHandle = args[3u].p[0u];
if (!pdpi->isValidHandle<T1>(lhsHandle) ||
!pdpi->isValidHandle<T2>(rhsHandle) ||
!pdpi->isValidHandle<T3>(resultHandle))
{
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
}
const ShareVec<T1> & param1 = *static_cast<ShareVec<T1>*>(lhsHandle);
const ShareVec<T2> & param2 = *static_cast<ShareVec<T2>*>(rhsHandle);
ShareVec<T3> & result = *static_cast<ShareVec<T3>*>(resultHandle);
Protocol protocol(*pdpi);
if (!protocol.invoke(param1, param2, result))
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
PROFILE_SYSCALL(c, pdpi->modelEvaluator(), name,
param1.size());
return SHAREMIND_MODULE_API_0x1_OK;
} catch (...) {
return catchModuleApiErrors();
}
}
/**
* SysCall: binary_public_vec<T1, T2, T3, Protocol>
* Args:
* 0) uint64[0] pd index
* 1) p[0] LHS handle
* 2) p[0] output handle
* Precondition:
* LHS handle is a vector of type T1.
* RHS handle is a vector of type T2.
* Output handle is a vector of type T3.
*/
template <typename T1, typename T2, typename T3, typename Protocol>
NAMED_SYSCALL(binary_public_vec, name, args, num_args, refs, crefs, returnValue, c)
{
VMHandles handles;
if (!SyscallArgs<3, false, 0u, 1u>::check(num_args, refs, crefs, returnValue) ||
!handles.get(c, args))
{
return SHAREMIND_MODULE_API_0x1_INVALID_CALL;
}
try {
Shared3pPDPI * const pdpi = static_cast<Shared3pPDPI*>(handles.pdpiHandle);
void * const lhsHandle = args[1u].p[0u];
void * const resultHandle = args[2u].p[0u];
if (!pdpi->isValidHandle<T1>(lhsHandle) ||
!pdpi->isValidHandle<T3>(resultHandle))
{
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
}
const ShareVec<T1> & param1 = *static_cast<ShareVec<T1>*>(lhsHandle);
const ImmutableVmVec<T2> param2(crefs[0u]);
ShareVec<T3> & result = *static_cast<ShareVec<T3>*>(resultHandle);
Protocol protocol(*pdpi);
if (!protocol.invoke(param1, param2, result))
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
PROFILE_SYSCALL(c, pdpi->modelEvaluator(), name,
param1.size());
return SHAREMIND_MODULE_API_0x1_OK;
} catch (...) {
return catchModuleApiErrors();
}
}
/**
* SysCall: binary_arith_vec<T, Protocol>
* Args:
* 0) uint64[0] pd index
* 1) p[0] vector handle (lhs)
* 2) p[0] vector handle (rhs)
* 3) p[0] output handle
* Precondition:
* All handles are valid vectors of type T.
*/
template <typename T, typename Protocol>
NAMED_SYSCALL(binary_arith_vec, name, args, num_args, refs, crefs, returnValue, c)
{
return binary_vec<T, T, T, Protocol>(name, args, num_args, refs, crefs, returnValue, c);
}
/**
* SysCall: binary_arith_public_vec<T, Protocol>
* Args:
* 0) uint64[0] pd index
* 1) p[0] vector handle (lhs)
* 2) p[0] vector handle (rhs)
* 3) p[0] output handle
* Precondition:
* All handles are valid vectors of type T.
*/
template <typename T, typename Protocol>
NAMED_SYSCALL(binary_arith_public_vec, name, args, num_args, refs, crefs, returnValue, c)
{
return binary_public_vec<T, T, T, Protocol>(name, args, num_args, refs, crefs, returnValue, c);
}
/**
* SysCall: unary_vec<T, L, Protocol>
* Args:
* 0) uint64[0] pd index
* 1) p[0] input handle
* 2) p[0] output handle
* Precondition:
* Input handle is a vector of type T.
* Output handle is a vector of type L.
*/
template <typename T, typename L, typename Protocol>
NAMED_SYSCALL(unary_vec, name, args, num_args, refs, crefs, returnValue, c)
{
VMHandles handles;
if (!SyscallArgs<3>::check(num_args, refs, crefs, returnValue) ||
!handles.get(c, args))
{
return SHAREMIND_MODULE_API_0x1_INVALID_CALL;
}
try {
Shared3pPDPI * const pdpi = static_cast<Shared3pPDPI *>(handles.pdpiHandle);
void * const paramHandle = args[1u].p[0u];
void * const resultHandle = args[2u].p[0u];
if (!pdpi->isValidHandle<T>(paramHandle) ||
!pdpi->isValidHandle<L>(resultHandle))
{
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
}
const ShareVec<T>& param = *static_cast<ShareVec<T>*>(paramHandle);
ShareVec<L>& result = *static_cast<ShareVec<L>*>(resultHandle);
Protocol protocol(*pdpi);
if (!protocol.invoke(param, result))
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
PROFILE_SYSCALL(c, pdpi->modelEvaluator(), name,
param.size());
return SHAREMIND_MODULE_API_0x1_OK;
} catch (...) {
return catchModuleApiErrors();
}
}
/**
* SysCall: unary_arith_vec<T, Protocol>
* Args:
* 0) uint64[0] pd index
* 1) p[0] input handle
* 2) p[0] output handle
* Precondition:
* Both handles are valid vectors of type T.
*/
template <typename T, typename Protocol>
NAMED_SYSCALL(unary_arith_vec, name, args, num_args, refs, crefs, returnValue, c)
{
return unary_vec<T, T, Protocol>(name, args, num_args, refs, crefs, returnValue, c);
}
/**
* SysCall: nullary_vec<T, Protocol>
* Args:
* 0) uint64[0] pd index
* 1) p[0] output handle
* Precondition:
* Output handle is valid vectors of type T.
*/
template <typename T, typename Protocol>
NAMED_SYSCALL(nullary_vec, name, args, num_args, refs, crefs, returnValue, c)
{
VMHandles handles;
if (!SyscallArgs<2>::check(num_args, refs, crefs, returnValue) ||
!handles.get(c, args))
{
return SHAREMIND_MODULE_API_0x1_INVALID_CALL;
}
try {
Shared3pPDPI * const pdpi = static_cast<Shared3pPDPI*>(handles.pdpiHandle);
void * const resultHandle = args[1u].p[0u];
if (!pdpi->isValidHandle<T>(resultHandle)) {
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
}
ShareVec<T> & result = *static_cast<ShareVec<T>*>(resultHandle);
if (!Protocol(*pdpi).invoke(result))
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
PROFILE_SYSCALL(c, pdpi->modelEvaluator(), name,
result.size());
return SHAREMIND_MODULE_API_0x1_OK;
} catch (...) {
return catchModuleApiErrors();
}
}
/**
* SysCall: ternary_vec<T1, T2, T3, T4, Protocol>
* Args:
* 0) uint64[0] pd index
* 1) p[0] first parameter handle
* 2) p[1] second parameter handle
* 3) p[1] third parameter handle
* 4) p[3] output handle
* Precondition:
* first parameter handle is a vector of type T1.
* second paremeter handle is a vector of type T2.
* third paremeter handle is a vector of type T3.
* Output handle is a vector of type T4.
*/
template <typename T1, typename T2, typename T3, typename T4, typename Protocol>
NAMED_SYSCALL(ternary_vec, name, args, num_args, refs, crefs, returnValue, c)
{
VMHandles handles;
if (!SyscallArgs<5>::check(num_args, refs, crefs, returnValue) ||
!handles.get(c, args))
{
return SHAREMIND_MODULE_API_0x1_INVALID_CALL;
}
try {
Shared3pPDPI * const pdpi = static_cast<Shared3pPDPI*>(handles.pdpiHandle);
void * const param1Handle = args[1u].p[0u];
void * const param2Handle = args[2u].p[0u];
void * const param3Handle = args[3u].p[0u];
void * const resultHandle = args[4u].p[0u];
if (!pdpi->isValidHandle<T1>(param1Handle) ||
!pdpi->isValidHandle<T2>(param2Handle) ||
!pdpi->isValidHandle<T3>(param3Handle) ||
!pdpi->isValidHandle<T4>(resultHandle))
{
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
}
const ShareVec<T1> & param1 = *static_cast<ShareVec<T1>*>(param1Handle);
const ShareVec<T2> & param2 = *static_cast<ShareVec<T2>*>(param2Handle);
const ShareVec<T3> & param3 = *static_cast<ShareVec<T3>*>(param3Handle);
ShareVec<T4> & result = *static_cast<ShareVec<T4>*>(resultHandle);
Protocol protocol(*pdpi);
if (!protocol.invoke(param1, param2, param3, result))
return SHAREMIND_MODULE_API_0x1_GENERAL_ERROR;
PROFILE_SYSCALL(c, pdpi->modelEvaluator(), name,
param1.size());
return SHAREMIND_MODULE_API_0x1_OK;
} catch (...) {
return catchModuleApiErrors();
}
}
} /* namespace sharemind */
#endif /* MOD_SHARED3P_EMU_SYSCALLS_META_H */
|
sharemind-sdk/mod_shared3p_emu
|
src/Syscalls/Meta.h
|
C
|
gpl-3.0
| 10,851
|
# frozen_string_literal: true
class RenameTableCardExpenses < ActiveRecord::Migration[4.2]
def change
# noinspection RailsParamDefResolve
rename_table :card_expenses, :trip_expenses
end
end
|
lssjbrolli/ctcadmin
|
db/migrate/20140809104441_rename_table_card_expenses.rb
|
Ruby
|
gpl-3.0
| 203
|
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.core;
import net.minecraftforge.common.util.ForgeDirection;
import appeng.api.IAppEngApi;
import appeng.api.definitions.Blocks;
import appeng.api.definitions.Items;
import appeng.api.definitions.Materials;
import appeng.api.definitions.Parts;
import appeng.api.exceptions.FailedConnection;
import appeng.api.features.IRegistryContainer;
import appeng.api.networking.IGridBlock;
import appeng.api.networking.IGridConnection;
import appeng.api.networking.IGridNode;
import appeng.api.storage.IStorageHelper;
import appeng.core.api.ApiPart;
import appeng.core.api.ApiStorage;
import appeng.core.features.registries.RegistryContainer;
import appeng.me.GridConnection;
import appeng.me.GridNode;
import appeng.util.Platform;
public final class Api implements IAppEngApi
{
public static final Api INSTANCE = new Api();
private final ApiPart partHelper;
// private MovableTileRegistry MovableRegistry = new MovableTileRegistry();
private final IRegistryContainer registryContainer;
private final IStorageHelper storageHelper;
private final Materials materials;
private final Items items;
private final Blocks blocks;
private final Parts parts;
private final ApiDefinitions definitions;
private Api()
{
this.parts = new Parts();
this.blocks = new Blocks();
this.items = new Items();
this.materials = new Materials();
this.storageHelper = new ApiStorage();
this.registryContainer = new RegistryContainer();
this.partHelper = new ApiPart();
this.definitions = new ApiDefinitions( this.partHelper );
}
@Override
public IRegistryContainer registries()
{
return this.registryContainer;
}
@Override
public IStorageHelper storage()
{
return this.storageHelper;
}
@Override
public ApiPart partHelper()
{
return this.partHelper;
}
@Override
public Items items()
{
return this.items;
}
@Override
public Materials materials()
{
return this.materials;
}
@Override
public Blocks blocks()
{
return this.blocks;
}
@Override
public Parts parts()
{
return this.parts;
}
@Override
public ApiDefinitions definitions()
{
return this.definitions;
}
@Override
public IGridNode createGridNode( final IGridBlock blk )
{
if( Platform.isClient() )
{
throw new IllegalStateException( "Grid features for " + blk + " are server side only." );
}
return new GridNode( blk );
}
@Override
public IGridConnection createGridConnection( final IGridNode a, final IGridNode b ) throws FailedConnection
{
return new GridConnection( a, b, ForgeDirection.UNKNOWN );
}
}
|
itachi1706/Applied-Energistics-2
|
src/main/java/appeng/core/Api.java
|
Java
|
gpl-3.0
| 3,373
|
/*
ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio
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.
*/
/**
* @file templates/halconf.h
* @brief HAL configuration header.
* @details HAL configuration file, this file allows to enable or disable the
* various device drivers from your application. You may also use
* this file in order to override the device drivers default settings.
*
* @addtogroup HAL_CONF
* @{
*/
#ifndef _HALCONF_H_
#define _HALCONF_H_
#include "mcuconf.h"
/**
* @brief Enables the PAL subsystem.
*/
#if !defined(HAL_USE_PAL) || defined(__DOXYGEN__)
#define HAL_USE_PAL TRUE
#endif
/**
* @brief Enables the ADC subsystem.
*/
#if !defined(HAL_USE_ADC) || defined(__DOXYGEN__)
#define HAL_USE_ADC FALSE
#endif
/**
* @brief Enables the CAN subsystem.
*/
#if !defined(HAL_USE_CAN) || defined(__DOXYGEN__)
#define HAL_USE_CAN FALSE
#endif
/**
* @brief Enables the DAC subsystem.
*/
#if !defined(HAL_USE_DAC) || defined(__DOXYGEN__)
#define HAL_USE_DAC FALSE
#endif
/**
* @brief Enables the EXT subsystem.
*/
#if !defined(HAL_USE_EXT) || defined(__DOXYGEN__)
#define HAL_USE_EXT FALSE
#endif
/**
* @brief Enables the GPT subsystem.
*/
#if !defined(HAL_USE_GPT) || defined(__DOXYGEN__)
#define HAL_USE_GPT FALSE
#endif
/**
* @brief Enables the I2C subsystem.
*/
#if !defined(HAL_USE_I2C) || defined(__DOXYGEN__)
#define HAL_USE_I2C FALSE
#endif
/**
* @brief Enables the I2S subsystem.
*/
#if !defined(HAL_USE_I2S) || defined(__DOXYGEN__)
#define HAL_USE_I2S FALSE
#endif
/**
* @brief Enables the ICU subsystem.
*/
#if !defined(HAL_USE_ICU) || defined(__DOXYGEN__)
#define HAL_USE_ICU FALSE
#endif
/**
* @brief Enables the MAC subsystem.
*/
#if !defined(HAL_USE_MAC) || defined(__DOXYGEN__)
#define HAL_USE_MAC FALSE
#endif
/**
* @brief Enables the MMC_SPI subsystem.
*/
#if !defined(HAL_USE_MMC_SPI) || defined(__DOXYGEN__)
#define HAL_USE_MMC_SPI FALSE
#endif
/**
* @brief Enables the PWM subsystem.
*/
#if !defined(HAL_USE_PWM) || defined(__DOXYGEN__)
#define HAL_USE_PWM FALSE
#endif
/**
* @brief Enables the RTC subsystem.
*/
#if !defined(HAL_USE_RTC) || defined(__DOXYGEN__)
#define HAL_USE_RTC FALSE
#endif
/**
* @brief Enables the SDC subsystem.
*/
#if !defined(HAL_USE_SDC) || defined(__DOXYGEN__)
#define HAL_USE_SDC TRUE
#endif
/**
* @brief Enables the SERIAL subsystem.
*/
#if !defined(HAL_USE_SERIAL) || defined(__DOXYGEN__)
#define HAL_USE_SERIAL TRUE
#endif
/**
* @brief Enables the SERIAL over USB subsystem.
*/
#if !defined(HAL_USE_SERIAL_USB) || defined(__DOXYGEN__)
#define HAL_USE_SERIAL_USB FALSE
#endif
/**
* @brief Enables the SPI subsystem.
*/
#if !defined(HAL_USE_SPI) || defined(__DOXYGEN__)
#define HAL_USE_SPI FALSE
#endif
/**
* @brief Enables the UART subsystem.
*/
#if !defined(HAL_USE_UART) || defined(__DOXYGEN__)
#define HAL_USE_UART FALSE
#endif
/**
* @brief Enables the USB subsystem.
*/
#if !defined(HAL_USE_USB) || defined(__DOXYGEN__)
#define HAL_USE_USB FALSE
#endif
/**
* @brief Enables the WDG subsystem.
*/
#if !defined(HAL_USE_WDG) || defined(__DOXYGEN__)
#define HAL_USE_WDG FALSE
#endif
/*===========================================================================*/
/* ADC driver related settings. */
/*===========================================================================*/
/**
* @brief Enables synchronous APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(ADC_USE_WAIT) || defined(__DOXYGEN__)
#define ADC_USE_WAIT TRUE
#endif
/**
* @brief Enables the @p adcAcquireBus() and @p adcReleaseBus() APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(ADC_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define ADC_USE_MUTUAL_EXCLUSION TRUE
#endif
/*===========================================================================*/
/* CAN driver related settings. */
/*===========================================================================*/
/**
* @brief Sleep mode related APIs inclusion switch.
*/
#if !defined(CAN_USE_SLEEP_MODE) || defined(__DOXYGEN__)
#define CAN_USE_SLEEP_MODE TRUE
#endif
/*===========================================================================*/
/* I2C driver related settings. */
/*===========================================================================*/
/**
* @brief Enables the mutual exclusion APIs on the I2C bus.
*/
#if !defined(I2C_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define I2C_USE_MUTUAL_EXCLUSION TRUE
#endif
/*===========================================================================*/
/* MAC driver related settings. */
/*===========================================================================*/
/**
* @brief Enables an event sources for incoming packets.
*/
#if !defined(MAC_USE_ZERO_COPY) || defined(__DOXYGEN__)
#define MAC_USE_ZERO_COPY FALSE
#endif
/**
* @brief Enables an event sources for incoming packets.
*/
#if !defined(MAC_USE_EVENTS) || defined(__DOXYGEN__)
#define MAC_USE_EVENTS TRUE
#endif
/*===========================================================================*/
/* MMC_SPI driver related settings. */
/*===========================================================================*/
/**
* @brief Delays insertions.
* @details If enabled this options inserts delays into the MMC waiting
* routines releasing some extra CPU time for the threads with
* lower priority, this may slow down the driver a bit however.
* This option is recommended also if the SPI driver does not
* use a DMA channel and heavily loads the CPU.
*/
#if !defined(MMC_NICE_WAITING) || defined(__DOXYGEN__)
#define MMC_NICE_WAITING TRUE
#endif
/*===========================================================================*/
/* SDC driver related settings. */
/*===========================================================================*/
/**
* @brief Number of initialization attempts before rejecting the card.
* @note Attempts are performed at 10mS intervals.
*/
#if !defined(SDC_INIT_RETRY) || defined(__DOXYGEN__)
#define SDC_INIT_RETRY 100
#endif
/**
* @brief Include support for MMC cards.
* @note MMC support is not yet implemented so this option must be kept
* at @p FALSE.
*/
#if !defined(SDC_MMC_SUPPORT) || defined(__DOXYGEN__)
#define SDC_MMC_SUPPORT FALSE
#endif
/**
* @brief Delays insertions.
* @details If enabled this options inserts delays into the MMC waiting
* routines releasing some extra CPU time for the threads with
* lower priority, this may slow down the driver a bit however.
*/
#if !defined(SDC_NICE_WAITING) || defined(__DOXYGEN__)
#define SDC_NICE_WAITING TRUE
#endif
/**
* @brief Write timeout in milliseconds.
*/
#if !defined(SDC_WRITE_TIMEOUT_MS) || defined(__DOXYGEN__)
#define SDC_WRITE_TIMEOUT_MS 250
#endif
/**
* @brief Write timeout in milliseconds.
*/
#if !defined(SDC_READ_TIMEOUT_MS) || defined(__DOXYGEN__)
#define SDC_READ_TIMEOUT_MS 5
#endif
/*===========================================================================*/
/* SERIAL driver related settings. */
/*===========================================================================*/
/**
* @brief Default bit rate.
* @details Configuration parameter, this is the baud rate selected for the
* default configuration.
*/
#if !defined(SERIAL_DEFAULT_BITRATE) || defined(__DOXYGEN__)
#define SERIAL_DEFAULT_BITRATE 38400
#endif
/**
* @brief Serial buffers size.
* @details Configuration parameter, you can change the depth of the queue
* buffers depending on the requirements of your application.
* @note The default is 64 bytes for both the transmission and receive
* buffers.
*/
#if !defined(SERIAL_BUFFERS_SIZE) || defined(__DOXYGEN__)
#define SERIAL_BUFFERS_SIZE 16
#endif
/*===========================================================================*/
/* SERIAL_USB driver related setting. */
/*===========================================================================*/
/**
* @brief Serial over USB buffers size.
* @details Configuration parameter, the buffer size must be a multiple of
* the USB data endpoint maximum packet size.
* @note The default is 64 bytes for both the transmission and receive
* buffers.
*/
#if !defined(SERIAL_USB_BUFFERS_SIZE) || defined(__DOXYGEN__)
#define SERIAL_USB_BUFFERS_SIZE 256
#endif
/*===========================================================================*/
/* SPI driver related settings. */
/*===========================================================================*/
/**
* @brief Enables synchronous APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(SPI_USE_WAIT) || defined(__DOXYGEN__)
#define SPI_USE_WAIT TRUE
#endif
/**
* @brief Enables the @p spiAcquireBus() and @p spiReleaseBus() APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(SPI_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define SPI_USE_MUTUAL_EXCLUSION TRUE
#endif
/*===========================================================================*/
/* UART driver related settings. */
/*===========================================================================*/
/**
* @brief Enables synchronous APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(UART_USE_WAIT) || defined(__DOXYGEN__)
#define UART_USE_WAIT FALSE
#endif
/**
* @brief Enables the @p uartAcquireBus() and @p uartReleaseBus() APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(UART_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define UART_USE_MUTUAL_EXCLUSION FALSE
#endif
#endif /* _HALCONF_H_ */
/** @} */
|
bunnie/chibios-kl02
|
testhal/STM32/STM32F4xx/SDC/halconf.h
|
C
|
gpl-3.0
| 11,642
|
/*
Copyright (C) 2011 Jason von Nieda <jason@vonnieda.org>
This file is part of OpenPnP.
OpenPnP 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.
OpenPnP 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 OpenPnP. If not, see <http://www.gnu.org/licenses/>.
For more information about OpenPnP visit http://openpnp.org
*/
package org.openpnp.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.FocusTraversalPolicy;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Hashtable;
import java.util.Locale;
import java.util.concurrent.Callable;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import org.openpnp.ConfigurationListener;
import org.openpnp.gui.components.CameraPanel;
import org.openpnp.gui.support.Icons;
import org.openpnp.gui.support.MessageBoxes;
import org.openpnp.gui.support.NozzleItem;
import org.openpnp.model.Configuration;
import org.openpnp.model.LengthUnit;
import org.openpnp.model.Location;
import org.openpnp.spi.Camera;
import org.openpnp.spi.Head;
import org.openpnp.spi.Machine;
import org.openpnp.spi.MachineListener;
import org.openpnp.spi.Nozzle;
import org.openpnp.spi.PasteDispenser;
import org.openpnp.util.MovableUtils;
import com.google.common.util.concurrent.FutureCallback;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.RowSpec;
public class MachineControlsPanel extends JPanel {
private final JFrame frame;
private final CameraPanel cameraPanel;
private final Configuration configuration;
private Nozzle selectedNozzle;
private JTextField textFieldX;
private JTextField textFieldY;
private JTextField textFieldC;
private JTextField textFieldZ;
private JButton btnStartStop;
private JSlider sliderIncrements;
private JComboBox comboBoxNozzles;
private Color startColor = Color.green;
private Color stopColor = new Color(178, 34, 34);
private Color droNormalColor = new Color(0xBDFFBE);
private Color droEditingColor = new Color(0xF0F0A1);
private Color droWarningColor = new Color(0xFF5C5C);
private Color droSavedColor = new Color(0x90cce0);
private JogControlsPanel jogControlsPanel;
private JDialog jogControlsWindow;
private volatile double savedX = Double.NaN, savedY = Double.NaN, savedZ = Double.NaN, savedC = Double.NaN;
/**
* Create the panel.
*/
public MachineControlsPanel(Configuration configuration, JFrame frame, CameraPanel cameraPanel) {
this.frame = frame;
this.cameraPanel = cameraPanel;
this.configuration = configuration;
jogControlsPanel = new JogControlsPanel(configuration, this, frame);
createUi();
configuration.addListener(configurationListener);
jogControlsWindow = new JDialog(frame, "Jog Controls");
jogControlsWindow.setResizable(false);
jogControlsWindow.getContentPane().setLayout(new BorderLayout());
jogControlsWindow.getContentPane().add(jogControlsPanel);
}
/**
* @deprecated See {@link Machine#submit(Runnable)}
* @param runnable
*/
public void submitMachineTask(Runnable runnable) {
if (!Configuration.get().getMachine().isEnabled()) {
MessageBoxes.errorBox(getTopLevelAncestor(), "Machine Error", "Machine is not started.");
return;
}
Configuration.get().getMachine().submit(runnable);
}
public void setSelectedNozzle(Nozzle nozzle) {
selectedNozzle = nozzle;
comboBoxNozzles.setSelectedItem(selectedNozzle);
updateDros();
}
public Nozzle getSelectedNozzle() {
return selectedNozzle;
}
public PasteDispenser getSelectedPasteDispenser() {
try {
// TODO: We don't actually have a way to select a dispenser yet, so
// until we do we just return the first one.
return Configuration.get().getMachine().getHeads().get(0).getPasteDispensers().get(0);
}
catch (Exception e) {
return null;
}
}
public JogControlsPanel getJogControlsPanel() {
return jogControlsPanel;
}
private void setUnits(LengthUnit units) {
if (units == LengthUnit.Millimeters) {
Hashtable<Integer, JLabel> incrementsLabels = new Hashtable<Integer, JLabel>();
incrementsLabels.put(1, new JLabel("0.01"));
incrementsLabels.put(2, new JLabel("0.1"));
incrementsLabels.put(3, new JLabel("1.0"));
incrementsLabels.put(4, new JLabel("10"));
incrementsLabels.put(5, new JLabel("100"));
sliderIncrements.setLabelTable(incrementsLabels);
}
else if (units == LengthUnit.Inches) {
Hashtable<Integer, JLabel> incrementsLabels = new Hashtable<Integer, JLabel>();
incrementsLabels.put(1, new JLabel("0.001"));
incrementsLabels.put(2, new JLabel("0.01"));
incrementsLabels.put(3, new JLabel("0.1"));
incrementsLabels.put(4, new JLabel("1.0"));
incrementsLabels.put(5, new JLabel("10.0"));
sliderIncrements.setLabelTable(incrementsLabels);
}
else {
throw new Error("setUnits() not implemented for " + units);
}
updateDros();
}
public double getJogIncrement() {
if (configuration.getSystemUnits() == LengthUnit.Millimeters) {
return 0.01 * Math.pow(10, sliderIncrements.getValue() - 1);
}
else if (configuration.getSystemUnits() == LengthUnit.Inches) {
return 0.001 * Math.pow(10, sliderIncrements.getValue() - 1);
}
else {
throw new Error("getJogIncrement() not implemented for " + configuration.getSystemUnits());
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
homeAction.setEnabled(enabled);
goToZeroAction.setEnabled(enabled);
jogControlsPanel.setEnabled(enabled);
targetCameraAction.setEnabled(enabled);
targetToolAction.setEnabled(enabled);
}
public Location getCurrentLocation() {
if (selectedNozzle == null) {
return null;
}
Location l = selectedNozzle.getLocation();
l = l.convertToUnits(configuration.getSystemUnits());
return l;
}
public void updateDros() {
Location l = getCurrentLocation();
if (l == null) {
return;
}
double x, y, z, c;
x = l.getX();
y = l.getY();
z = l.getZ();
c = l.getRotation();
double savedX = this.savedX;
if (!Double.isNaN(savedX)) {
x -= savedX;
}
double savedY = this.savedY;
if (!Double.isNaN(savedY)) {
y -= savedY;
}
double savedZ = this.savedZ;
if (!Double.isNaN(savedZ)) {
z -= savedZ;
}
double savedC = this.savedC;
if (!Double.isNaN(savedC)) {
c -= savedC;
}
textFieldX.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), x));
textFieldY.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), y));
textFieldZ.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), z));
textFieldC.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), c));
}
private void createUi() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
ButtonGroup buttonGroup = new ButtonGroup();
JPanel panel = new JPanel();
add(panel);
panel.setLayout(new FormLayout(new ColumnSpec[] {
FormSpecs.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),},
new RowSpec[] {
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,}));
comboBoxNozzles = new JComboBox();
comboBoxNozzles.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setSelectedNozzle(((NozzleItem) comboBoxNozzles.getSelectedItem()).getNozzle());
}
});
panel.add(comboBoxNozzles, "2, 2, fill, default");
JPanel panelDrosParent = new JPanel();
add(panelDrosParent);
panelDrosParent.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JPanel panelDros = new JPanel();
panelDrosParent.add(panelDros);
panelDros.setLayout(new BoxLayout(panelDros, BoxLayout.Y_AXIS));
JPanel panelDrosFirstLine = new JPanel();
panelDros.add(panelDrosFirstLine);
panelDrosFirstLine.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblX = new JLabel("X");
lblX.setFont(new Font("Lucida Grande", Font.BOLD, 24));
panelDrosFirstLine.add(lblX);
textFieldX = new JTextField();
textFieldX.setEditable(false);
textFieldX.setFocusTraversalKeysEnabled(false);
textFieldX.setSelectionColor(droEditingColor);
textFieldX.setDisabledTextColor(Color.BLACK);
textFieldX.setBackground(droNormalColor);
textFieldX.setFont(new Font("Lucida Grande", Font.BOLD, 24));
textFieldX.setText("0000.0000");
textFieldX.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
savedX = Double.NaN;
}
saveXAction.actionPerformed(null);
}
});
panelDrosFirstLine.add(textFieldX);
textFieldX.setColumns(6);
Component horizontalStrut = Box.createHorizontalStrut(15);
panelDrosFirstLine.add(horizontalStrut);
JLabel lblY = new JLabel("Y");
lblY.setFont(new Font("Lucida Grande", Font.BOLD, 24));
panelDrosFirstLine.add(lblY);
textFieldY = new JTextField();
textFieldY.setEditable(false);
textFieldY.setFocusTraversalKeysEnabled(false);
textFieldY.setSelectionColor(droEditingColor);
textFieldY.setDisabledTextColor(Color.BLACK);
textFieldY.setBackground(droNormalColor);
textFieldY.setFont(new Font("Lucida Grande", Font.BOLD, 24));
textFieldY.setText("0000.0000");
textFieldY.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
savedY = Double.NaN;
}
saveYAction.actionPerformed(null);
}
});
panelDrosFirstLine.add(textFieldY);
textFieldY.setColumns(6);
JButton btnTargetTool = new JButton(targetToolAction);
panelDrosFirstLine.add(btnTargetTool);
btnTargetTool.setToolTipText("Position the tool at the camera's current location.");
JPanel panelDrosSecondLine = new JPanel();
panelDros.add(panelDrosSecondLine);
panelDrosSecondLine.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblC = new JLabel("C");
lblC.setFont(new Font("Lucida Grande", Font.BOLD, 24));
panelDrosSecondLine.add(lblC);
textFieldC = new JTextField();
textFieldC.setEditable(false);
textFieldC.setFocusTraversalKeysEnabled(false);
textFieldC.setSelectionColor(droEditingColor);
textFieldC.setDisabledTextColor(Color.BLACK);
textFieldC.setBackground(droNormalColor);
textFieldC.setText("0000.0000");
textFieldC.setFont(new Font("Lucida Grande", Font.BOLD, 24));
textFieldC.setColumns(6);
textFieldC.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
savedC = Double.NaN;
}
saveCAction.actionPerformed(null);
}
});
panelDrosSecondLine.add(textFieldC);
Component horizontalStrut_1 = Box.createHorizontalStrut(15);
panelDrosSecondLine.add(horizontalStrut_1);
JLabel lblZ = new JLabel("Z");
lblZ.setFont(new Font("Lucida Grande", Font.BOLD, 24));
panelDrosSecondLine.add(lblZ);
textFieldZ = new JTextField();
textFieldZ.setEditable(false);
textFieldZ.setFocusTraversalKeysEnabled(false);
textFieldZ.setSelectionColor(droEditingColor);
textFieldZ.setDisabledTextColor(Color.BLACK);
textFieldZ.setBackground(droNormalColor);
textFieldZ.setText("0000.0000");
textFieldZ.setFont(new Font("Lucida Grande", Font.BOLD, 24));
textFieldZ.setColumns(6);
textFieldZ.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
savedZ = Double.NaN;
}
saveZAction.actionPerformed(null);
}
});
panelDrosSecondLine.add(textFieldZ);
JButton btnTargetCamera = new JButton(targetCameraAction);
panelDrosSecondLine.add(btnTargetCamera);
btnTargetCamera.setToolTipText("Position the camera at the tool's current location.");
JPanel panelIncrements = new JPanel();
add(panelIncrements);
sliderIncrements = new JSlider();
panelIncrements.add(sliderIncrements);
sliderIncrements.setMajorTickSpacing(1);
sliderIncrements.setValue(1);
sliderIncrements.setSnapToTicks(true);
sliderIncrements.setPaintLabels(true);
sliderIncrements.setPaintTicks(true);
sliderIncrements.setMinimum(1);
sliderIncrements.setMaximum(5);
JPanel panelStartStop = new JPanel();
add(panelStartStop);
panelStartStop.setLayout(new BorderLayout(0, 0));
btnStartStop = new JButton(startMachineAction);
btnStartStop.setFocusable(true);
btnStartStop.setForeground(startColor);
panelStartStop.add(btnStartStop);
btnStartStop.setFont(new Font("Lucida Grande", Font.BOLD, 48));
btnStartStop.setPreferredSize(new Dimension(160, 70));
setFocusTraversalPolicy(focusPolicy);
setFocusTraversalPolicyProvider(true);
}
private FocusTraversalPolicy focusPolicy = new FocusTraversalPolicy() {
@Override
public Component getComponentAfter(Container aContainer,
Component aComponent) {
return sliderIncrements;
}
@Override
public Component getComponentBefore(Container aContainer,
Component aComponent) {
return sliderIncrements;
}
@Override
public Component getDefaultComponent(Container aContainer) {
return sliderIncrements;
}
@Override
public Component getFirstComponent(Container aContainer) {
return sliderIncrements;
}
@Override
public Component getInitialComponent(Window window) {
return sliderIncrements;
}
@Override
public Component getLastComponent(Container aContainer) {
return sliderIncrements;
}
};
@SuppressWarnings("serial")
private Action stopMachineAction = new AbstractAction("STOP") {
@Override
public void actionPerformed(ActionEvent arg0) {
setEnabled(false);
Configuration.get().getMachine().submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
Configuration.get().getMachine().setEnabled(false);
return null;
}
}, new FutureCallback<Void>() {
@Override
public void onSuccess(Void result) {
setEnabled(true);
}
@Override
public void onFailure(Throwable t) {
MessageBoxes.errorBox(MachineControlsPanel.this, "Stop Failed", t.getMessage());
setEnabled(true);
}
}, true);
}
};
@SuppressWarnings("serial")
private Action startMachineAction = new AbstractAction("START") {
@Override
public void actionPerformed(ActionEvent arg0) {
setEnabled(false);
Configuration.get().getMachine().submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
Configuration.get().getMachine().setEnabled(true);
return null;
}
}, new FutureCallback<Void>() {
@Override
public void onSuccess(Void result) {
setEnabled(true);
}
@Override
public void onFailure(Throwable t) {
MessageBoxes.errorBox(MachineControlsPanel.this, "Start Failed", t.getMessage());
setEnabled(true);
}
}, true);
}
};
@SuppressWarnings("serial")
public Action goToZeroAction = new AbstractAction("Go To Zero") {
@Override
public void actionPerformed(ActionEvent arg0) {
submitMachineTask(new Runnable() {
public void run() {
try {
selectedNozzle.moveToSafeZ(1.0);
// Move to 0, 0, 0, 0.
selectedNozzle.moveTo(new Location(LengthUnit.Millimeters, 0, 0, 0, 0), 1.0);
}
catch (Exception e) {
e.printStackTrace();
MessageBoxes.errorBox(frame, "Go To Zero Failed", e);
}
}
});
}
};
@SuppressWarnings("serial")
public Action homeAction = new AbstractAction("Home") {
@Override
public void actionPerformed(ActionEvent arg0) {
submitMachineTask(new Runnable() {
public void run() {
try {
selectedNozzle.getHead().home();
}
catch (Exception e) {
e.printStackTrace();
MessageBoxes.errorBox(frame, "Homing Failed", e);
}
}
});
}
};
public Action showHideJogControlsWindowAction = new AbstractAction("Show Jog Controls") {
@Override
public void actionPerformed(ActionEvent arg0) {
if (jogControlsWindow.isVisible()) {
// Hide
jogControlsWindow.setVisible(false);
putValue(AbstractAction.NAME, "Show Jog Controls");
}
else {
// Show
jogControlsWindow.setVisible(true);
jogControlsWindow.pack();
int x = (int) getLocationOnScreen().getX();
int y = (int) getLocationOnScreen().getY();
x += (getSize().getWidth() / 2) - (jogControlsWindow.getSize().getWidth() / 2);
y += getSize().getHeight();
jogControlsWindow.setLocation(x, y);
putValue(AbstractAction.NAME, "Hide Jog Controls");
}
}
};
@SuppressWarnings("serial")
public Action raiseIncrementAction = new AbstractAction("Raise Jog Increment") {
@Override
public void actionPerformed(ActionEvent arg0) {
sliderIncrements.setValue(Math.min(sliderIncrements.getMaximum(), sliderIncrements.getValue() + 1));
}
};
@SuppressWarnings("serial")
public Action lowerIncrementAction = new AbstractAction("Lower Jog Increment") {
@Override
public void actionPerformed(ActionEvent arg0) {
sliderIncrements.setValue(Math.max(sliderIncrements.getMinimum(), sliderIncrements.getValue() - 1));
}
};
@SuppressWarnings("serial")
public Action targetToolAction = new AbstractAction(null, Icons.centerTool) {
@Override
public void actionPerformed(ActionEvent arg0) {
final Location location = cameraPanel.getSelectedCameraLocation();
final Nozzle nozzle = getSelectedNozzle();
submitMachineTask(new Runnable() {
public void run() {
try {
MovableUtils.moveToLocationAtSafeZ(nozzle, location, 1.0);
}
catch (Exception e) {
MessageBoxes.errorBox(frame, "Move Failed", e);
}
}
});
}
};
@SuppressWarnings("serial")
public Action targetCameraAction = new AbstractAction(null, Icons.centerCamera) {
@Override
public void actionPerformed(ActionEvent arg0) {
final Camera camera = cameraPanel.getSelectedCamera();
if (camera == null) {
return;
}
final Location location = getSelectedNozzle().getLocation();
submitMachineTask(new Runnable() {
public void run() {
try {
MovableUtils.moveToLocationAtSafeZ(camera, location, 1.0);
}
catch (Exception e) {
MessageBoxes.errorBox(frame, "Move Failed", e);
}
}
});
}
};
@SuppressWarnings("serial")
public Action saveXAction = new AbstractAction(null) {
@Override
public void actionPerformed(ActionEvent arg0) {
if (Double.isNaN(savedX)) {
textFieldX.setBackground(droSavedColor);
savedX = getCurrentLocation().getX();
}
else {
textFieldX.setBackground(droNormalColor);
savedX = Double.NaN;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
};
@SuppressWarnings("serial")
public Action saveYAction = new AbstractAction(null) {
@Override
public void actionPerformed(ActionEvent arg0) {
if (Double.isNaN(savedY)) {
textFieldY.setBackground(droSavedColor);
savedY = getCurrentLocation().getY();
}
else {
textFieldY.setBackground(droNormalColor);
savedY = Double.NaN;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
};
@SuppressWarnings("serial")
public Action saveZAction = new AbstractAction(null) {
@Override
public void actionPerformed(ActionEvent arg0) {
if (Double.isNaN(savedZ)) {
textFieldZ.setBackground(droSavedColor);
savedZ = getCurrentLocation().getZ();
}
else {
textFieldZ.setBackground(droNormalColor);
savedZ = Double.NaN;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
};
@SuppressWarnings("serial")
public Action saveCAction = new AbstractAction(null) {
@Override
public void actionPerformed(ActionEvent arg0) {
if (Double.isNaN(savedC)) {
textFieldC.setBackground(droSavedColor);
savedC = getCurrentLocation().getRotation();
}
else {
textFieldC.setBackground(droNormalColor);
savedC = Double.NaN;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
};
private MachineListener machineListener = new MachineListener.Adapter() {
@Override
public void machineHeadActivity(Machine machine, Head head) {
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
@Override
public void machineEnabled(Machine machine) {
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
setEnabled(true);
}
@Override
public void machineEnableFailed(Machine machine, String reason) {
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
}
@Override
public void machineDisabled(Machine machine, String reason) {
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
setEnabled(false);
}
@Override
public void machineDisableFailed(Machine machine, String reason) {
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
}
};
private ConfigurationListener configurationListener = new ConfigurationListener.Adapter() {
@Override
public void configurationComplete(Configuration configuration) {
Machine machine = configuration.getMachine();
if (machine != null) {
machine.removeListener(machineListener);
}
for (Head head : machine.getHeads()) {
for (Nozzle nozzle : head.getNozzles()) {
comboBoxNozzles.addItem(new NozzleItem(nozzle));
}
}
setSelectedNozzle(((NozzleItem) comboBoxNozzles.getItemAt(0)).getNozzle());
setUnits(configuration.getSystemUnits());
machine.addListener(machineListener);
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
setEnabled(machine.isEnabled());
}
};
}
|
TinWhiskers/openpnp
|
src/main/java/org/openpnp/gui/MachineControlsPanel.java
|
Java
|
gpl-3.0
| 25,064
|
/*
* This file is part of CarAlarm an Arduino project for a car alarm system.
*
* Copyright (c) 2016 Francisco Zamora-Martinez (pakozm@gmail.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.
*/
#ifndef ACC_UTILS_H
#define ACC_UTILS_H
#include "SensorUtils.h"
class AccelerometerUtils {
public:
/// domain [-300,300] which is -3G to 3G
static long convertToG(int value, long MV=SensorUtils::Vcc) {
return ((SensorUtils::convertToMv(value,MV) - ZEROG) * MUL) / SCALE;
}
private:
static const long ZEROG = 1650;
static const long MUL = 100;
static const long SCALE = 1650;
};
#endif // ACC_UTILS_H
|
pakozm/CarAlarm
|
libraries/SensorsTransformations/AccelerometerUtils.h
|
C
|
gpl-3.0
| 1,652
|
(function() {
'use strict';
angular
.module('weatheropendataApp')
.config(stateConfig);
stateConfig.$inject = ['$stateProvider'];
function stateConfig($stateProvider) {
$stateProvider.state('register', {
parent: 'account',
url: '/register',
data: {
authorities: [],
pageTitle: 'register.title'
},
views: {
'content@': {
templateUrl: 'app/account/register/register.html',
controller: 'RegisterController',
controllerAs: 'vm'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('register');
return $translate.refresh();
}]
}
});
}
})();
|
hackathinho/open-clean-energy
|
backend-weather/src/main/webapp/app/account/register/register.state.js
|
JavaScript
|
gpl-3.0
| 993
|
/*
* MindmapsDB - A Distributed Semantic Database
* Copyright (C) 2016 Mindmaps Research Ltd
*
* MindmapsDB 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.
*
* MindmapsDB 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 MindmapsDB. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package io.mindmaps.graql;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import io.mindmaps.MindmapsTransaction;
import io.mindmaps.core.model.Concept;
import io.mindmaps.graql.internal.parser.GraqlLexer;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.Token;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* An autocomplete result suggesting keywords, types and variables that the user may wish to type
*/
public class Autocomplete {
private final ImmutableSet<String> candidates;
private final int cursorPosition;
/**
* @param transaction the transaction to find types in
* @param query the query to autocomplete
* @param cursorPosition the cursor position in the query
* @return an autocomplete object containing potential candidates and cursor position to autocomplete from
*/
public static Autocomplete create(MindmapsTransaction transaction, String query, int cursorPosition) {
return new Autocomplete(transaction, query, cursorPosition);
}
/**
* @return all candidate autocomplete words
*/
public Set<String> getCandidates() {
return candidates;
}
/**
* @return the cursor position that autocompletions should start from
*/
public int getCursorPosition() {
return cursorPosition;
}
/**
* @param transaction the transaction to find types in
* @param query the query to autocomplete
* @param cursorPosition the cursor position in the query
*/
private Autocomplete(MindmapsTransaction transaction, String query, int cursorPosition) {
Optional<? extends Token> optToken = getCursorToken(query, cursorPosition);
candidates = ImmutableSet.copyOf(findCandidates(transaction, query, optToken));
this.cursorPosition = findCursorPosition(cursorPosition, optToken);
}
/**
* @param transaction the transaction to find types in
* @param query a graql query
* @param optToken the token the cursor is on in the query
* @return a set of potential autocomplete words
*/
private static Set<String> findCandidates(MindmapsTransaction transaction, String query, Optional<? extends Token> optToken) {
Set<String> allCandidates = Stream.of(getKeywords(), getTypes(transaction), getVariables(query))
.flatMap(Function.identity()).collect(Collectors.toSet());
return optToken.map(
token -> {
Set<String> candidates = allCandidates.stream()
.filter(candidate -> candidate.startsWith(token.getText()))
.collect(Collectors.toSet());
if (candidates.size() == 1 && candidates.iterator().next().equals(token.getText())) {
return Sets.newHashSet(" ");
} else {
return candidates;
}
}
).orElse(allCandidates);
}
/**
* @param cursorPosition the current cursor position
* @param optToken the token the cursor is on in the query
* @return the new cursor position to start autocompleting from
*/
private int findCursorPosition(int cursorPosition, Optional<? extends Token> optToken) {
return optToken
.filter(token -> !candidates.contains(" "))
.map(Token::getStartIndex)
.orElse(cursorPosition);
}
/**
* @return all Graql keywords
*/
private static Stream<String> getKeywords() {
HashSet<String> keywords = new HashSet<>();
for (int i = 1; GraqlLexer.VOCABULARY.getLiteralName(i) != null; i ++) {
String name = GraqlLexer.VOCABULARY.getLiteralName(i);
keywords.add(name.replaceAll("'", ""));
}
return keywords.stream();
}
/**
* @param transaction the transaction to find types in
* @return all type IDs in the ontology
*/
private static Stream<String> getTypes(MindmapsTransaction transaction) {
return transaction.getMetaType().instances().stream().map(Concept::getId);
}
/**
* @param query a graql query
* @return all variable names occurring in the query
*/
private static Stream<String> getVariables(String query) {
List<? extends Token> allTokens = getTokens(query);
if (allTokens.size() > 0) allTokens.remove(allTokens.size() - 1);
return allTokens.stream()
.filter(t -> t.getType() == GraqlLexer.VARIABLE)
.map(Token::getText);
}
/**
* @param query a graql query
* @param cursorPosition the cursor position in the query
* @return the token at the cursor position in the given graql query
*/
private static Optional<? extends Token> getCursorToken(String query, int cursorPosition) {
if (query == null) return Optional.empty();
return getTokens(query).stream()
.filter(t -> t.getStartIndex() <= cursorPosition && t.getStopIndex() >= cursorPosition - 1)
.findFirst();
}
/**
* @param query a graql query
* @return a list of tokens from running the lexer on the query
*/
private static List<? extends Token> getTokens(String query) {
ANTLRInputStream input = new ANTLRInputStream(query);
GraqlLexer lexer = new GraqlLexer(input);
// Ignore syntax errors
lexer.removeErrorListeners();
lexer.addErrorListener(new BaseErrorListener());
return lexer.getAllTokens();
}
}
|
duckofyork/mindmapsdb
|
mindmaps-graql/src/main/java/io/mindmaps/graql/Autocomplete.java
|
Java
|
gpl-3.0
| 6,589
|
# 18_shutdown_hpsmh.sh
if (( PREVIEW )) ; then
Log "Stopping HP System Mgmt Homepage processes [not done in preview]"
else
LogPrint "Stopping HP System Mgmt Homepage processes"
[[ -x /sbin/init.d/hpsmh ]] && /sbin/init.d/hpsmh stop >&2
# as SMH caused update-ux to hang we do a 2th check
netstat -a | grep -q 2301
if (( $? == 0 )) ; then
LogPrint "smh is still running - force a kill of smh"
KillProc smh
fi
fi
|
gdha/upgrade-ux
|
opt/upgrade-ux/scripts/preinstall/hp/18_shutdown_hpsmh.sh
|
Shell
|
gpl-3.0
| 449
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Camel : GamePiece {
public override List<GridCell>GetMovementCells(GameGrid grid, GridCell cell)
{
return grid.GetLeapCells(cell, 3, 1);
}
public override List<GridCell>GetAttackCells(GameGrid grid, GridCell cell)
{
return GetMovementCells(grid, cell);
}
}
|
matthewvroman/single-player-chess
|
Assets/Scripts/GamePieces/Camel.cs
|
C#
|
gpl-3.0
| 365
|
package org.betonquest.betonquest.objectives;
import lombok.CustomLog;
import org.betonquest.betonquest.BetonQuest;
import org.betonquest.betonquest.Instruction;
import org.betonquest.betonquest.api.Condition;
import org.betonquest.betonquest.api.Objective;
import org.betonquest.betonquest.api.QuestEvent;
import org.betonquest.betonquest.conditions.ChestItemCondition;
import org.betonquest.betonquest.events.ChestTakeEvent;
import org.betonquest.betonquest.exceptions.InstructionParseException;
import org.betonquest.betonquest.exceptions.ObjectNotFoundException;
import org.betonquest.betonquest.exceptions.QuestRuntimeException;
import org.betonquest.betonquest.id.NoID;
import org.betonquest.betonquest.utils.PlayerConverter;
import org.betonquest.betonquest.utils.location.CompoundLocation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.InventoryHolder;
/**
* Requires the player to put items in the chest. Items can optionally NOT
* disappear once the chest is closed.
*/
@SuppressWarnings("PMD.CommentRequired")
@CustomLog
public class ChestPutObjective extends Objective implements Listener {
private final Condition chestItemCondition;
private final QuestEvent chestTakeEvent;
private final CompoundLocation loc;
public ChestPutObjective(final Instruction instruction) throws InstructionParseException {
super(instruction);
template = ObjectiveData.class;
// extract location
loc = instruction.getLocation();
final String location = instruction.current();
final String items = instruction.next();
try {
chestItemCondition = new ChestItemCondition(new Instruction(instruction.getPackage(), new NoID(instruction.getPackage()), "chestitem " + location + " " + items));
} catch (InstructionParseException | ObjectNotFoundException e) {
throw new InstructionParseException("Could not create inner chest item condition: " + e.getMessage(), e);
}
if (instruction.hasArgument("items-stay")) {
chestTakeEvent = null;
} else {
try {
chestTakeEvent = new ChestTakeEvent(new Instruction(instruction.getPackage(), new NoID(instruction.getPackage()), "chesttake " + location + " " + items));
} catch (final ObjectNotFoundException e) {
throw new InstructionParseException("Could not create inner chest take event: " + e.getMessage(), e);
}
}
}
@SuppressWarnings("PMD.CyclomaticComplexity")
@EventHandler(ignoreCancelled = true)
public void onChestClose(final InventoryCloseEvent event) {
if (!(event.getPlayer() instanceof Player)) {
return;
}
final String playerID = PlayerConverter.getID((Player) event.getPlayer());
if (!containsPlayer(playerID)) {
return;
}
try {
final Location targetChestLocation = loc.getLocation(playerID);
final Block block = targetChestLocation.getBlock();
if (!(block.getState() instanceof InventoryHolder)) {
final World world = targetChestLocation.getWorld();
LOG.warn(instruction.getPackage(),
String.format("Error in '%s' chestput objective: Block at location x:%d y:%d z:%d in world '%s' isn't a chest!",
instruction.getID().getFullID(),
targetChestLocation.getBlockX(),
targetChestLocation.getBlockY(),
targetChestLocation.getBlockZ(),
world == null ? "null" : world.getName()));
return;
}
final InventoryHolder chest = (InventoryHolder) block.getState();
if (!chest.equals(event.getInventory().getHolder())) {
return;
}
if (chestItemCondition.handle(playerID) && checkConditions(playerID)) {
completeObjective(playerID);
if (chestTakeEvent != null) {
chestTakeEvent.handle(playerID);
}
}
} catch (final QuestRuntimeException e) {
LOG.warn(instruction.getPackage(), "Error while handling '" + instruction.getID() + "' objective: " + e.getMessage(), e);
}
}
@Override
public void start() {
Bukkit.getPluginManager().registerEvents(this, BetonQuest.getInstance());
}
@Override
public void stop() {
HandlerList.unregisterAll(this);
}
@Override
public String getDefaultDataInstruction() {
return "";
}
@Override
public String getProperty(final String name, final String playerID) {
return "";
}
}
|
Co0sh/BetonQuest
|
src/main/java/org/betonquest/betonquest/objectives/ChestPutObjective.java
|
Java
|
gpl-3.0
| 5,067
|
/************************************************************************
* Virtual Whiteboard System Based on Image Processing
* Main file
*
* Author: Alankar Kotwal <alankarkotwal13@gmail.com>
************************************************************************/
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <sstream>
#include <string>
#include "path.hpp"
using namespace cv;
int main() {
std::stringstream configPath;
configPath<<REPO_ROOT<<"/config/config.xml";
boost::property_tree::ptree config;
boost::property_tree::read_xml(configPath.str(), config);
VideoCapture cap(config.get<int>("whiteboard.capture.captureNo"));
Mat frame;
cap >> frame;
Mat draw = Mat::zeros(frame.rows, frame.cols, CV_8UC3);
namedWindow("Drawing", WINDOW_AUTOSIZE);
Moments mom;
Point cen, oldCen;
int xC, yC;
bool first=1;
char key;
while(1) {
boost::property_tree::read_xml(configPath.str(), config);
cap >> frame;
Mat channels[3];
split(frame, channels);
Mat red = channels[2]; // OpenCV follows BGR
threshold(red, red, config.get<int>("whiteboard.imgproc.threshold"), config.get<int>("whiteboard.imgproc.maxVal"), THRESH_BINARY);
mom = moments(red, true);
xC = mom.m10 / mom.m00;
yC = mom.m01 / mom.m00;
Scalar color(config.get<int>("whiteboard.rendering.b"), config.get<int>("whiteboard.rendering.g"), config.get<int>("whiteboard.rendering.r"));
if(mom.m00 > config.get<int>("whiteboard.imgproc.minPixelNo")) {
oldCen.x = cen.x;
oldCen.y = cen.y;
cen.x = xC;
cen.y = yC;
if(config.get<string>("whiteboard.rendering.mode") == "circles") {
circle(draw, cen, config.get<int>("whiteboard.rendering.lineWidth"), color, 0, 8, 0);
}
else if(config.get<string>("whiteboard.rendering.mode") == "lines" && first == 0) {
line(draw, oldCen, cen, color, config.get<int>("whiteboard.rendering.lineWidth"), 8, 0);
}
first = 0;
}
else {
first = 1;
}
imshow("Drawing", draw);
key = waitKey(1);
if(key == 'r') {
draw = Mat::zeros(frame.rows, frame.cols, CV_8UC3);
}
}
return 0;
}
|
alankarkotwal/lvp-whiteboard
|
code/opencv/Whiteboard.cpp
|
C++
|
gpl-3.0
| 2,252
|
/**
* File ./src/main/java/de/lemo/dms/db/mapping/CourseAssignmentMining.java
* Lemo-Data-Management-Server for learning analytics.
* Copyright (C) 2013
* Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
/**
* File ./main/java/de/lemo/dms/db/mapping/CourseAssignmentMining.java
* Date 2013-01-24
* Project Lemo Learning Analytics
*/
package de.lemo.dms.db.mapping;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import de.lemo.dms.db.mapping.abstractions.ICourseLORelation;
import de.lemo.dms.db.mapping.abstractions.ICourseRatedObjectAssociation;
import de.lemo.dms.db.mapping.abstractions.ILearningObject;
import de.lemo.dms.db.mapping.abstractions.IMappingClass;
import de.lemo.dms.db.mapping.abstractions.IRatedObject;
/**
* This class represents the relationship between the courses and assignments.
* @author Sebastian Schwarzrock
*/
@Entity
@Table(name = "course_assignment")
public class CourseAssignmentMining implements ICourseLORelation, IMappingClass, ICourseRatedObjectAssociation {
private long id;
private CourseMining course;
private AssignmentMining assignment;
private Long platform;
@Override
public boolean equals(final IMappingClass o)
{
if (!(o instanceof CourseAssignmentMining)) {
return false;
}
if ((o.getId() == this.getId()) && (o instanceof CourseAssignmentMining)) {
return true;
}
return false;
}
@Override
public int hashCode() {
return (int) id;
}
/**
* standard getter for the attribut course
*
* @return a course in which the quiz is used
*/
@Override
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="course_id")
public CourseMining getCourse() {
return this.course;
}
/**
* standard setter for the attribut course
*
* @param course
* a course in which the quiz is used
*/
public void setCourse(final CourseMining course) {
this.course = course;
}
/**
* parameterized setter for the attribut course
*
* @param course
* the id of a course in which the quiz is used
* @param courseMining
* a list of new added courses, which is searched for the course with the id submitted in the course
* parameter
* @param oldCourseMining
* a list of course in the miningdatabase, which is searched for the course with the id submitted in the
* course parameter
*/
public void setCourse(final long course, final Map<Long, CourseMining> courseMining,
final Map<Long, CourseMining> oldCourseMining) {
if (courseMining.get(course) != null)
{
this.course = courseMining.get(course);
courseMining.get(course).addCourseAssignment(this);
}
if ((this.course == null) && (oldCourseMining.get(course) != null))
{
this.course = oldCourseMining.get(course);
oldCourseMining.get(course).addCourseAssignment(this);
}
}
/**
* standard getter for the attribut assignment
*
* @return the quiz which is used in the course
*/
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="assignment_id")
public AssignmentMining getAssignment() {
return this.assignment;
}
/**
* standard setter for the attribut assignment
*
* @param assignment
* the assignment which is used in the course
*/
public void setAssignment(final AssignmentMining assignment) {
this.assignment = assignment;
}
/**
* parameterized setter for the attribut assignment
*
* @param id
* the id of the quiz in which the action takes place
* @param assignmentMining
* a list of new added quiz, which is searched for the quiz with the qid and qtype submitted in the other
* parameters
* @param oldAssignmentMining
* a list of quiz in the miningdatabase, which is searched for the quiz with the qid and qtype submitted
* in the other parameters
*/
public void setAssignment(final long assignment, final Map<Long, AssignmentMining> assignmentMining,
final Map<Long, AssignmentMining> oldAssignmentMining) {
if (assignmentMining.get(assignment) != null)
{
this.assignment = assignmentMining.get(assignment);
assignmentMining.get(assignment).addCourseAssignment(this);
}
if ((this.assignment == null) && (oldAssignmentMining.get(assignment) != null))
{
this.assignment = oldAssignmentMining.get(assignment);
oldAssignmentMining.get(assignment).addCourseAssignment(this);
}
}
/**
* standard setter for the attribut id
*
* @param id
* the identifier for the assoziation between course and assignment
*/
public void setId(final long id) {
this.id = id;
}
/**
* standard getter for the attribut id
*
* @return the identifier for the assoziation between course and assignment
*/
@Override
@Id
public long getId() {
return this.id;
}
@Column(name="platform")
public Long getPlatform() {
return this.platform;
}
public void setPlatform(final Long platform) {
this.platform = platform;
}
@Override
@Transient
public IRatedObject getRatedObject() {
return this.assignment;
}
@Override
@Transient
public Long getPrefix() {
return this.assignment.getPrefix();
}
@Override
@Transient
public ILearningObject getLearningObject() {
return this.getAssignment();
}
}
|
LemoProject/lemo2
|
src/main/java/de/lemo/dms/db/mapping/CourseAssignmentMining.java
|
Java
|
gpl-3.0
| 6,152
|
/*******************************************************************************************************************************************************
* Copyright ¨Ï 2016 <WIZnet Co.,Ltd.>
* 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.
*********************************************************************************************************************************************************/
/**
******************************************************************************
* @file RNG/Random_number_generation/main.c
* @author IOP Team
* @version V1.0.0
* @date 26-AUG-2015
* @brief Main program body
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, WIZnet SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2015 WIZnet Co.,Ltd.</center></h2>
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
#include "W7500x_gpio.h"
#include "W7500x_rng.h"
#include "W7500x_uart.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint32_t rng_data;
/* Private function prototypes -----------------------------------------------*/
void UART_Configuration(void);
/* Private functions ---------------------------------------------------------*/
/**
* @brief Main program
* @param None
* @retval None
*/
int main()
{
/*System clock configuration*/
SystemInit();
/* UART configuration */
UART_Configuration();
printf("*****W7500 RNG TEST*****\r\n");
// Read Power up random value
rng_data = RNG_ReadRandomNumber();
printf("Initial random number = %d\r\n", rng_data);
// RNG Initialize : Change RNG mode to manual RUN
RNG_Init ();
// RNG RUN & STOP
RNG_Run(ENABLE);
__NOP();
__NOP();
RNG_Run(DISABLE);
// Read Manual RUN RNG Data
rng_data = RNG_ReadRandomNumber();
printf("manual run & stop random number = %d\r\n", rng_data);
// Change Seed value & polynimials
RNG_SetSeedvalue(0x30002001);
RNG_SetPolynomial(0x90001011);
// RNG RUN & STOP again
RNG_Run(ENABLE);
__NOP();
__NOP();
RNG_Run(DISABLE);
// Read 2nd Manual RUN RNG data
rng_data = RNG_ReadRandomNumber();
printf("updated polynomial & seed value\r\n");
printf("manual run & stop random number = %d\r\n", rng_data);
printf("\r\n");
}
void UART_Configuration(void)
{
UART_InitTypeDef UART_InitStructure;
/* UART Configuration for UART1*/
UART_StructInit(&UART_InitStructure);
UART_Init(UART1,&UART_InitStructure);
/* UART Configuration for UART2*/
S_UART_Init(115200);
}
|
arm8686/W7500P-Tau
|
W7500P-Tau-FW/Projects/Peripheral_Examples/RNG/Random_number_generation/main.c
|
C
|
gpl-3.0
| 4,378
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html
"""
class Countries_Tajikistan():
'''Class that manages this specific menu context.'''
def open(self, plugin, menu):
menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels",
"Events", "Live", "Movies", "Sports", "TVShows"],
countries=["Tajikistan"]))
|
xbmcmegapack/plugin.video.megapack.dev
|
resources/lib/menus/home_countries_tajikistan.py
|
Python
|
gpl-3.0
| 1,117
|
@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"c:\Ruby21-x64\bin\ruby.exe" "c:/repos/refridged/.gem/2.1/ruby/2.1.0/bin/scss" %1 %2 %3 %4 %5 %6 %7 %8 %9
GOTO :EOF
:WinNT
@"c:\Ruby21-x64\bin\ruby.exe" "%~dpn0" %*
|
trisys3/refridged
|
.gem/2.1/ruby/2.1.0/bin/scss.bat
|
Batchfile
|
gpl-3.0
| 211
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Migration_modifica_coluna_hologated_null extends CI_Migration {
public function up() {
$this->dbforge->modify_column('selection_process_user_subscription', [
'homologated' => ['type' => 'tinyint(1)', 'null' => TRUE, 'default' => NULL]
]);
}
public function down() {
$this->dbforge->modify_column('selection_process_user_subscription', [
'homologated' => ['type' => 'tinyint(1)', 'null' => FALSE, 'default' => FALSE]
]);
}
}
|
Sistema-Integrado-Gestao-Academica/SiGA
|
application/migrations/162_modifica_coluna_hologated_null.php
|
PHP
|
gpl-3.0
| 581
|
/**
* initSession
*
* @module :: Policy
* @description :: make sure all session related values are properly setup
*
*/
module.exports = function(req, res, next) {
// make sure the appdev session obj is created.
req.session.appdev = req.session.appdev || ADCore.session.default();
// if this is a socket request, then initialize the socket info:
if (req.isSocket) {
ADCore.socket.init(req);
}
// ok, our session is properly setup.
next();
};
|
appdevdesigns/appdev-core
|
api/policies/initSession.js
|
JavaScript
|
gpl-3.0
| 500
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.media.cts;
import android.app.Presentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.SurfaceTexture;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaCodec;
import android.media.MediaCodec.BufferInfo;
import android.media.MediaCodecInfo;
import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCodecInfo.CodecProfileLevel;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Parcel;
import android.test.AndroidTestCase;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Size;
import android.view.Display;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.media.cts.R;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Tests to check if MediaCodec encoding works with composition of multiple virtual displays
* The test also tries to destroy and create virtual displays repeatedly to
* detect any issues. The test itself does not check the output as it is already done in other
* tests.
*/
public class EncodeVirtualDisplayWithCompositionTest extends AndroidTestCase {
private static final String TAG = "EncodeVirtualDisplayWithCompositionTest";
private static final boolean DBG = true;
private static final String MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC;
private static final long DEFAULT_WAIT_TIMEOUT_MS = 3000;
private static final long DEFAULT_WAIT_TIMEOUT_US = 3000000;
private static final int COLOR_RED = makeColor(100, 0, 0);
private static final int COLOR_BLUE = makeColor(0, 100, 0);
private static final int COLOR_GREEN = makeColor(0, 0, 100);
private static final int COLOR_GREY = makeColor(100, 100, 100);
private static final int BITRATE_1080p = 20000000;
private static final int BITRATE_720p = 14000000;
private static final int BITRATE_800x480 = 14000000;
private static final int BITRATE_DEFAULT = 10000000;
private static final int IFRAME_INTERVAL = 10;
private static final int MAX_NUM_WINDOWS = 3;
private static Handler sHandlerForRunOnMain = new Handler(Looper.getMainLooper());
private Surface mEncodingSurface;
private OutputSurface mDecodingSurface;
private volatile boolean mCodecConfigReceived = false;
private volatile boolean mCodecBufferReceived = false;
private EncodingHelper mEncodingHelper;
private MediaCodec mDecoder;
private final ByteBuffer mPixelBuf = ByteBuffer.allocateDirect(4);
private volatile boolean mIsQuitting = false;
private Throwable mTestException;
private VirtualDisplayPresentation mLocalPresentation;
private RemoteVirtualDisplayPresentation mRemotePresentation;
private ByteBuffer[] mDecoderInputBuffers;
/** event listener for test without verifying output */
private EncoderEventListener mEncoderEventListener = new EncoderEventListener() {
@Override
public void onCodecConfig(ByteBuffer data, MediaCodec.BufferInfo info) {
mCodecConfigReceived = true;
}
@Override
public void onBufferReady(ByteBuffer data, MediaCodec.BufferInfo info) {
mCodecBufferReceived = true;
}
@Override
public void onError(String errorMessage) {
fail(errorMessage);
}
};
/* TEST_COLORS static initialization; need ARGB for ColorDrawable */
private static int makeColor(int red, int green, int blue) {
return 0xff << 24 | (red & 0xff) << 16 | (green & 0xff) << 8 | (blue & 0xff);
}
public void testVirtualDisplayRecycles() throws Exception {
doTestVirtualDisplayRecycles(3);
}
public void testRendering800x480Locally() throws Throwable {
Log.i(TAG, "testRendering800x480Locally");
if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
runTestRenderingInSeparateThread(800, 480, false, false);
} else {
Log.i(TAG, "SKIPPING testRendering800x480Locally(): codec not supported");
}
}
public void testRenderingMaxResolutionLocally() throws Throwable {
Log.i(TAG, "testRenderingMaxResolutionLocally");
Size maxRes = checkMaxConcurrentEncodingDecodingResolution();
if (maxRes == null) {
Log.i(TAG, "SKIPPING testRenderingMaxResolutionLocally(): codec not supported");
} else {
Log.w(TAG, "Trying resolution " + maxRes);
runTestRenderingInSeparateThread(maxRes.getWidth(), maxRes.getHeight(), false, false);
}
}
public void testRendering800x480Remotely() throws Throwable {
Log.i(TAG, "testRendering800x480Remotely");
if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
runTestRenderingInSeparateThread(800, 480, true, false);
} else {
Log.i(TAG, "SKIPPING testRendering800x480Remotely(): codec not supported");
}
}
public void testRenderingMaxResolutionRemotely() throws Throwable {
Log.i(TAG, "testRenderingMaxResolutionRemotely");
Size maxRes = checkMaxConcurrentEncodingDecodingResolution();
if (maxRes == null) {
Log.i(TAG, "SKIPPING testRenderingMaxResolutionRemotely(): codec not supported");
} else {
Log.w(TAG, "Trying resolution " + maxRes);
runTestRenderingInSeparateThread(maxRes.getWidth(), maxRes.getHeight(), true, false);
}
}
public void testRendering800x480RemotelyWith3Windows() throws Throwable {
Log.i(TAG, "testRendering800x480RemotelyWith3Windows");
if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
runTestRenderingInSeparateThread(800, 480, true, true);
} else {
Log.i(TAG, "SKIPPING testRendering800x480RemotelyWith3Windows(): codec not supported");
}
}
public void testRendering800x480LocallyWith3Windows() throws Throwable {
Log.i(TAG, "testRendering800x480LocallyWith3Windows");
if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
runTestRenderingInSeparateThread(800, 480, false, true);
} else {
Log.i(TAG, "SKIPPING testRendering800x480LocallyWith3Windows(): codec not supported");
}
}
/**
* Run rendering test in a separate thread. This is necessary as {@link OutputSurface} requires
* constructing it in a non-test thread.
* @param w
* @param h
* @throws Exception
*/
private void runTestRenderingInSeparateThread(final int w, final int h,
final boolean runRemotely, final boolean multipleWindows) throws Throwable {
mTestException = null;
Thread renderingThread = new Thread(new Runnable() {
public void run() {
try {
doTestRenderingOutput(w, h, runRemotely, multipleWindows);
} catch (Throwable t) {
t.printStackTrace();
mTestException = t;
}
}
});
renderingThread.start();
renderingThread.join(60000);
assertTrue(!renderingThread.isAlive());
if (mTestException != null) {
throw mTestException;
}
}
private void doTestRenderingOutput(int w, int h, boolean runRemotely, boolean multipleWindows)
throws Throwable {
if (DBG) {
Log.i(TAG, "doTestRenderingOutput for w:" + w + " h:" + h);
}
try {
mIsQuitting = false;
mDecoder = MediaCodec.createDecoderByType(MIME_TYPE);
MediaFormat decoderFormat = MediaFormat.createVideoFormat(MIME_TYPE, w, h);
mDecodingSurface = new OutputSurface(w, h);
mDecoder.configure(decoderFormat, mDecodingSurface.getSurface(), null, 0);
mDecoder.start();
mDecoderInputBuffers = mDecoder.getInputBuffers();
mEncodingHelper = new EncodingHelper();
mEncodingSurface = mEncodingHelper.startEncoding(w, h,
new EncoderEventListener() {
@Override
public void onCodecConfig(ByteBuffer data, BufferInfo info) {
if (DBG) {
Log.i(TAG, "onCodecConfig l:" + info.size);
}
handleEncodedData(data, info);
}
@Override
public void onBufferReady(ByteBuffer data, BufferInfo info) {
if (DBG) {
Log.i(TAG, "onBufferReady l:" + info.size);
}
handleEncodedData(data, info);
}
@Override
public void onError(String errorMessage) {
fail(errorMessage);
}
private void handleEncodedData(ByteBuffer data, BufferInfo info) {
if (mIsQuitting) {
if (DBG) {
Log.i(TAG, "ignore data as test is quitting");
}
return;
}
int inputBufferIndex = mDecoder.dequeueInputBuffer(DEFAULT_WAIT_TIMEOUT_US);
if (inputBufferIndex < 0) {
if (DBG) {
Log.i(TAG, "dequeueInputBuffer returned:" + inputBufferIndex);
}
return;
}
assertTrue(inputBufferIndex >= 0);
ByteBuffer inputBuffer = mDecoderInputBuffers[inputBufferIndex];
inputBuffer.clear();
inputBuffer.put(data);
mDecoder.queueInputBuffer(inputBufferIndex, 0, info.size,
info.presentationTimeUs, info.flags);
}
});
GlCompositor compositor = new GlCompositor();
if (DBG) {
Log.i(TAG, "start composition");
}
compositor.startComposition(mEncodingSurface, w, h, multipleWindows ? 3 : 1);
if (DBG) {
Log.i(TAG, "create display");
}
Renderer renderer = null;
if (runRemotely) {
mRemotePresentation = new RemoteVirtualDisplayPresentation(getContext(),
compositor.getWindowSurface(multipleWindows? 1 : 0), w, h);
mRemotePresentation.connect();
mRemotePresentation.start();
renderer = mRemotePresentation;
} else {
mLocalPresentation = new VirtualDisplayPresentation(getContext(),
compositor.getWindowSurface(multipleWindows? 1 : 0), w, h);
mLocalPresentation.createVirtualDisplay();
mLocalPresentation.createPresentation();
renderer = mLocalPresentation;
}
if (DBG) {
Log.i(TAG, "start rendering and check");
}
renderColorAndCheckResult(renderer, w, h, COLOR_RED);
renderColorAndCheckResult(renderer, w, h, COLOR_BLUE);
renderColorAndCheckResult(renderer, w, h, COLOR_GREEN);
renderColorAndCheckResult(renderer, w, h, COLOR_GREY);
mIsQuitting = true;
if (runRemotely) {
mRemotePresentation.disconnect();
} else {
mLocalPresentation.dismissPresentation();
mLocalPresentation.destroyVirtualDisplay();
}
compositor.stopComposition();
} finally {
if (mEncodingHelper != null) {
mEncodingHelper.stopEncoding();
mEncodingHelper = null;
}
if (mDecoder != null) {
mDecoder.stop();
mDecoder.release();
mDecoder = null;
}
if (mDecodingSurface != null) {
mDecodingSurface.release();
mDecodingSurface = null;
}
}
}
private static final int NUM_MAX_RETRY = 120;
private static final int IMAGE_WAIT_TIMEOUT_MS = 1000;
private void renderColorAndCheckResult(Renderer renderer, int w, int h,
int color) throws Exception {
BufferInfo info = new BufferInfo();
for (int i = 0; i < NUM_MAX_RETRY; i++) {
renderer.doRendering(color);
int bufferIndex = mDecoder.dequeueOutputBuffer(info, DEFAULT_WAIT_TIMEOUT_US);
if (DBG) {
Log.i(TAG, "decoder dequeueOutputBuffer returned " + bufferIndex);
}
if (bufferIndex < 0) {
continue;
}
mDecoder.releaseOutputBuffer(bufferIndex, true);
if (mDecodingSurface.checkForNewImage(IMAGE_WAIT_TIMEOUT_MS)) {
mDecodingSurface.drawImage();
if (checkSurfaceFrameColor(w, h, color)) {
Log.i(TAG, "color " + Integer.toHexString(color) + " matched");
return;
}
} else if(DBG) {
Log.i(TAG, "no rendering yet");
}
}
fail("Color did not match");
}
private boolean checkSurfaceFrameColor(int w, int h, int color) {
// Read a pixel from the center of the surface. Might want to read from multiple points
// and average them together.
int x = w / 2;
int y = h / 2;
GLES20.glReadPixels(x, y, 1, 1, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, mPixelBuf);
int r = mPixelBuf.get(0) & 0xff;
int g = mPixelBuf.get(1) & 0xff;
int b = mPixelBuf.get(2) & 0xff;
int redExpected = (color >> 16) & 0xff;
int greenExpected = (color >> 8) & 0xff;
int blueExpected = color & 0xff;
if (approxEquals(redExpected, r) && approxEquals(greenExpected, g)
&& approxEquals(blueExpected, b)) {
return true;
}
Log.i(TAG, "expected 0x" + Integer.toHexString(color) + " got 0x"
+ Integer.toHexString(makeColor(r, g, b)));
return false;
}
/**
* Determines if two color values are approximately equal.
*/
private static boolean approxEquals(int expected, int actual) {
final int MAX_DELTA = 4;
return Math.abs(expected - actual) <= MAX_DELTA;
}
private static final int NUM_CODEC_CREATION = 5;
private static final int NUM_DISPLAY_CREATION = 10;
private static final int NUM_RENDERING = 10;
private void doTestVirtualDisplayRecycles(int numDisplays) throws Exception {
Size maxSize = getMaxSupportedEncoderSize();
if (maxSize == null) {
Log.i(TAG, "no codec found, skipping");
return;
}
VirtualDisplayPresentation[] virtualDisplays = new VirtualDisplayPresentation[numDisplays];
for (int i = 0; i < NUM_CODEC_CREATION; i++) {
mCodecConfigReceived = false;
mCodecBufferReceived = false;
if (DBG) {
Log.i(TAG, "start encoding");
}
EncodingHelper encodingHelper = new EncodingHelper();
mEncodingSurface = encodingHelper.startEncoding(maxSize.getWidth(), maxSize.getHeight(),
mEncoderEventListener);
GlCompositor compositor = new GlCompositor();
if (DBG) {
Log.i(TAG, "start composition");
}
compositor.startComposition(mEncodingSurface, maxSize.getWidth(), maxSize.getHeight(),
numDisplays);
for (int j = 0; j < NUM_DISPLAY_CREATION; j++) {
if (DBG) {
Log.i(TAG, "create display");
}
for (int k = 0; k < numDisplays; k++) {
virtualDisplays[k] =
new VirtualDisplayPresentation(getContext(),
compositor.getWindowSurface(k),
maxSize.getWidth()/numDisplays, maxSize.getHeight());
virtualDisplays[k].createVirtualDisplay();
virtualDisplays[k].createPresentation();
}
if (DBG) {
Log.i(TAG, "start rendering");
}
for (int k = 0; k < NUM_RENDERING; k++) {
for (int l = 0; l < numDisplays; l++) {
virtualDisplays[l].doRendering(COLOR_RED);
}
// do not care how many frames are actually rendered.
Thread.sleep(1);
}
for (int k = 0; k < numDisplays; k++) {
virtualDisplays[k].dismissPresentation();
virtualDisplays[k].destroyVirtualDisplay();
}
compositor.recreateWindows();
}
if (DBG) {
Log.i(TAG, "stop composition");
}
compositor.stopComposition();
if (DBG) {
Log.i(TAG, "stop encoding");
}
encodingHelper.stopEncoding();
assertTrue(mCodecConfigReceived);
assertTrue(mCodecBufferReceived);
}
}
interface EncoderEventListener {
public void onCodecConfig(ByteBuffer data, MediaCodec.BufferInfo info);
public void onBufferReady(ByteBuffer data, MediaCodec.BufferInfo info);
public void onError(String errorMessage);
}
private class EncodingHelper {
private MediaCodec mEncoder;
private volatile boolean mStopEncoding = false;
private EncoderEventListener mEventListener;
private int mW;
private int mH;
private Thread mEncodingThread;
private Surface mEncodingSurface;
private Semaphore mInitCompleted = new Semaphore(0);
Surface startEncoding(int w, int h, EncoderEventListener eventListener) {
mStopEncoding = false;
mW = w;
mH = h;
mEventListener = eventListener;
mEncodingThread = new Thread(new Runnable() {
@Override
public void run() {
try {
doEncoding();
} catch (Exception e) {
e.printStackTrace();
mEventListener.onError(e.toString());
}
}
});
mEncodingThread.start();
try {
if (DBG) {
Log.i(TAG, "wait for encoder init");
}
mInitCompleted.acquire();
if (DBG) {
Log.i(TAG, "wait for encoder done");
}
} catch (InterruptedException e) {
fail("should not happen");
}
return mEncodingSurface;
}
void stopEncoding() {
try {
mStopEncoding = true;
mEncodingThread.join();
} catch(InterruptedException e) {
// just ignore
} finally {
mEncodingThread = null;
}
}
private void doEncoding() throws Exception {
final int TIMEOUT_USEC_NORMAL = 1000000;
MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mW, mH);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
int bitRate = BITRATE_DEFAULT;
if (mW == 1920 && mH == 1080) {
bitRate = BITRATE_1080p;
} else if (mW == 1280 && mH == 720) {
bitRate = BITRATE_720p;
} else if (mW == 800 && mH == 480) {
bitRate = BITRATE_800x480;
}
format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
format.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
String codecName = null;
if ((codecName = mcl.findEncoderForFormat(format)) == null) {
throw new RuntimeException("encoder "+ MIME_TYPE + " not support : " + format.toString());
}
mEncoder = MediaCodec.createByCodecName(codecName);
mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mEncodingSurface = mEncoder.createInputSurface();
mEncoder.start();
mInitCompleted.release();
if (DBG) {
Log.i(TAG, "starting encoder");
}
try {
ByteBuffer[] encoderOutputBuffers = mEncoder.getOutputBuffers();
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
while (!mStopEncoding) {
int index = mEncoder.dequeueOutputBuffer(info, TIMEOUT_USEC_NORMAL);
if (DBG) {
Log.i(TAG, "encoder dequeOutputBuffer returned " + index);
}
if (index >= 0) {
if ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
Log.i(TAG, "codec config data");
ByteBuffer encodedData = encoderOutputBuffers[index];
encodedData.position(info.offset);
encodedData.limit(info.offset + info.size);
mEventListener.onCodecConfig(encodedData, info);
mEncoder.releaseOutputBuffer(index, false);
} else if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
Log.i(TAG, "EOS, stopping encoding");
break;
} else {
ByteBuffer encodedData = encoderOutputBuffers[index];
encodedData.position(info.offset);
encodedData.limit(info.offset + info.size);
mEventListener.onBufferReady(encodedData, info);
mEncoder.releaseOutputBuffer(index, false);
}
} else if (index == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED){
Log.i(TAG, "output buffer changed");
encoderOutputBuffers = mEncoder.getOutputBuffers();
}
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
mEncoder.stop();
mEncoder.release();
mEncoder = null;
mEncodingSurface.release();
mEncodingSurface = null;
}
}
}
/**
* Handles composition of multiple SurfaceTexture into a single Surface
*/
private class GlCompositor implements SurfaceTexture.OnFrameAvailableListener {
private Surface mSurface;
private int mWidth;
private int mHeight;
private volatile int mNumWindows;
private GlWindow mTopWindow;
private Thread mCompositionThread;
private Semaphore mStartCompletionSemaphore;
private Semaphore mRecreationCompletionSemaphore;
private Looper mLooper;
private Handler mHandler;
private InputSurface mEglHelper;
private int mGlProgramId = 0;
private int mGluMVPMatrixHandle;
private int mGluSTMatrixHandle;
private int mGlaPositionHandle;
private int mGlaTextureHandle;
private float[] mMVPMatrix = new float[16];
private TopWindowVirtualDisplayPresentation mTopPresentation;
private static final String VERTEX_SHADER =
"uniform mat4 uMVPMatrix;\n" +
"uniform mat4 uSTMatrix;\n" +
"attribute vec4 aPosition;\n" +
"attribute vec4 aTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"void main() {\n" +
" gl_Position = uMVPMatrix * aPosition;\n" +
" vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
"}\n";
private static final String FRAGMENT_SHADER =
"#extension GL_OES_EGL_image_external : require\n" +
"precision mediump float;\n" +
"varying vec2 vTextureCoord;\n" +
"uniform samplerExternalOES sTexture;\n" +
"void main() {\n" +
" gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
"}\n";
void startComposition(Surface surface, int w, int h, int numWindows) throws Exception {
mSurface = surface;
mWidth = w;
mHeight = h;
mNumWindows = numWindows;
mCompositionThread = new Thread(new CompositionRunnable());
mStartCompletionSemaphore = new Semaphore(0);
mCompositionThread.start();
waitForStartCompletion();
}
void stopComposition() {
try {
if (mLooper != null) {
mLooper.quit();
mCompositionThread.join();
}
} catch (InterruptedException e) {
// don't care
}
mCompositionThread = null;
mSurface = null;
mStartCompletionSemaphore = null;
}
Surface getWindowSurface(int windowIndex) {
return mTopPresentation.getSurface(windowIndex);
}
void recreateWindows() throws Exception {
mRecreationCompletionSemaphore = new Semaphore(0);
Message msg = mHandler.obtainMessage(CompositionHandler.DO_RECREATE_WINDOWS);
mHandler.sendMessage(msg);
if(!mRecreationCompletionSemaphore.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS,
TimeUnit.MILLISECONDS)) {
fail("recreation timeout");
}
mTopPresentation.waitForSurfaceReady(DEFAULT_WAIT_TIMEOUT_MS);
}
@Override
public void onFrameAvailable(SurfaceTexture surface) {
if (DBG) {
Log.i(TAG, "onFrameAvailable " + surface);
}
GlWindow w = mTopWindow;
if (w != null) {
w.markTextureUpdated();
requestUpdate();
} else {
Log.w(TAG, "top window gone");
}
}
private void requestUpdate() {
Thread compositionThread = mCompositionThread;
if (compositionThread == null || !compositionThread.isAlive()) {
return;
}
Message msg = mHandler.obtainMessage(CompositionHandler.DO_RENDERING);
mHandler.sendMessage(msg);
}
private int loadShader(int shaderType, String source) throws GlException {
int shader = GLES20.glCreateShader(shaderType);
checkGlError("glCreateShader type=" + shaderType);
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
int[] compiled = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
Log.e(TAG, "Could not compile shader " + shaderType + ":");
Log.e(TAG, " " + GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
return shader;
}
private int createProgram(String vertexSource, String fragmentSource) throws GlException {
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0) {
return 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0) {
return 0;
}
int program = GLES20.glCreateProgram();
checkGlError("glCreateProgram");
if (program == 0) {
Log.e(TAG, "Could not create program");
}
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e(TAG, "Could not link program: ");
Log.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
return program;
}
private void initGl() throws GlException {
mEglHelper = new InputSurface(mSurface);
mEglHelper.makeCurrent();
mGlProgramId = createProgram(VERTEX_SHADER, FRAGMENT_SHADER);
mGlaPositionHandle = GLES20.glGetAttribLocation(mGlProgramId, "aPosition");
checkGlError("glGetAttribLocation aPosition");
if (mGlaPositionHandle == -1) {
throw new RuntimeException("Could not get attrib location for aPosition");
}
mGlaTextureHandle = GLES20.glGetAttribLocation(mGlProgramId, "aTextureCoord");
checkGlError("glGetAttribLocation aTextureCoord");
if (mGlaTextureHandle == -1) {
throw new RuntimeException("Could not get attrib location for aTextureCoord");
}
mGluMVPMatrixHandle = GLES20.glGetUniformLocation(mGlProgramId, "uMVPMatrix");
checkGlError("glGetUniformLocation uMVPMatrix");
if (mGluMVPMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uMVPMatrix");
}
mGluSTMatrixHandle = GLES20.glGetUniformLocation(mGlProgramId, "uSTMatrix");
checkGlError("glGetUniformLocation uSTMatrix");
if (mGluSTMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uSTMatrix");
}
Matrix.setIdentityM(mMVPMatrix, 0);
Log.i(TAG, "initGl w:" + mWidth + " h:" + mHeight);
GLES20.glViewport(0, 0, mWidth, mHeight);
float[] vMatrix = new float[16];
float[] projMatrix = new float[16];
// max window is from (0,0) to (mWidth - 1, mHeight - 1)
float wMid = mWidth / 2f;
float hMid = mHeight / 2f;
// look from positive z to hide windows in lower z
Matrix.setLookAtM(vMatrix, 0, wMid, hMid, 5f, wMid, hMid, 0f, 0f, 1.0f, 0.0f);
Matrix.orthoM(projMatrix, 0, -wMid, wMid, -hMid, hMid, 1, 10);
Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, vMatrix, 0);
createWindows();
}
private void createWindows() throws GlException {
mTopWindow = new GlWindow(this, 0, 0, mWidth, mHeight);
mTopWindow.init();
mTopPresentation = new TopWindowVirtualDisplayPresentation(mContext,
mTopWindow.getSurface(), mWidth, mHeight, mNumWindows);
mTopPresentation.createVirtualDisplay();
mTopPresentation.createPresentation();
((TopWindowPresentation) mTopPresentation.getPresentation()).populateWindows();
}
private void cleanupGl() {
if (mTopPresentation != null) {
mTopPresentation.dismissPresentation();
mTopPresentation.destroyVirtualDisplay();
mTopPresentation = null;
}
if (mTopWindow != null) {
mTopWindow.cleanup();
mTopWindow = null;
}
if (mEglHelper != null) {
mEglHelper.release();
mEglHelper = null;
}
}
private void doGlRendering() throws GlException {
if (DBG) {
Log.i(TAG, "doGlRendering");
}
mTopWindow.updateTexImageIfNecessary();
GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glUseProgram(mGlProgramId);
GLES20.glUniformMatrix4fv(mGluMVPMatrixHandle, 1, false, mMVPMatrix, 0);
mTopWindow.onDraw(mGluSTMatrixHandle, mGlaPositionHandle, mGlaTextureHandle);
checkGlError("window draw");
if (DBG) {
final IntBuffer pixels = IntBuffer.allocate(1);
GLES20.glReadPixels(mWidth / 2, mHeight / 2, 1, 1,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, pixels);
Log.i(TAG, "glReadPixels returned 0x" + Integer.toHexString(pixels.get(0)));
}
mEglHelper.swapBuffers();
}
private void doRecreateWindows() throws GlException {
mTopPresentation.dismissPresentation();
mTopPresentation.destroyVirtualDisplay();
mTopWindow.cleanup();
createWindows();
mRecreationCompletionSemaphore.release();
}
private void waitForStartCompletion() throws Exception {
if (!mStartCompletionSemaphore.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS,
TimeUnit.MILLISECONDS)) {
fail("start timeout");
}
mStartCompletionSemaphore = null;
mTopPresentation.waitForSurfaceReady(DEFAULT_WAIT_TIMEOUT_MS);
}
private class CompositionRunnable implements Runnable {
@Override
public void run() {
try {
Looper.prepare();
mLooper = Looper.myLooper();
mHandler = new CompositionHandler();
initGl();
// init done
mStartCompletionSemaphore.release();
Looper.loop();
} catch (GlException e) {
e.printStackTrace();
fail("got gl exception");
} finally {
cleanupGl();
mHandler = null;
mLooper = null;
}
}
}
private class CompositionHandler extends Handler {
private static final int DO_RENDERING = 1;
private static final int DO_RECREATE_WINDOWS = 2;
@Override
public void handleMessage(Message msg) {
try {
switch(msg.what) {
case DO_RENDERING: {
doGlRendering();
} break;
case DO_RECREATE_WINDOWS: {
doRecreateWindows();
} break;
}
} catch (GlException e) {
//ignore as this can happen during tearing down
}
}
}
private class GlWindow {
private static final int FLOAT_SIZE_BYTES = 4;
private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
private int mBlX;
private int mBlY;
private int mWidth;
private int mHeight;
private int mTextureId = 0; // 0 is invalid
private volatile SurfaceTexture mSurfaceTexture;
private volatile Surface mSurface;
private FloatBuffer mVerticesData;
private float[] mSTMatrix = new float[16];
private AtomicInteger mNumTextureUpdated = new AtomicInteger(0);
private GlCompositor mCompositor;
/**
* @param blX X coordinate of bottom-left point of window
* @param blY Y coordinate of bottom-left point of window
* @param w window width
* @param h window height
*/
public GlWindow(GlCompositor compositor, int blX, int blY, int w, int h) {
mCompositor = compositor;
mBlX = blX;
mBlY = blY;
mWidth = w;
mHeight = h;
int trX = blX + w;
int trY = blY + h;
float[] vertices = new float[] {
// x, y, z, u, v
mBlX, mBlY, 0, 0, 0,
trX, mBlY, 0, 1, 0,
mBlX, trY, 0, 0, 1,
trX, trY, 0, 1, 1
};
Log.i(TAG, "create window " + this + " blX:" + mBlX + " blY:" + mBlY + " trX:" +
trX + " trY:" + trY);
mVerticesData = ByteBuffer.allocateDirect(
vertices.length * FLOAT_SIZE_BYTES)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVerticesData.put(vertices).position(0);
}
/**
* initialize the window for composition. counter-part is cleanup()
* @throws GlException
*/
public void init() throws GlException {
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
mTextureId = textures[0];
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId);
checkGlError("glBindTexture mTextureID");
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S,
GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T,
GLES20.GL_CLAMP_TO_EDGE);
checkGlError("glTexParameter");
mSurfaceTexture = new SurfaceTexture(mTextureId);
mSurfaceTexture.setDefaultBufferSize(mWidth, mHeight);
mSurface = new Surface(mSurfaceTexture);
mSurfaceTexture.setOnFrameAvailableListener(mCompositor);
}
public void cleanup() {
mNumTextureUpdated.set(0);
if (mTextureId != 0) {
int[] textures = new int[] {
mTextureId
};
GLES20.glDeleteTextures(1, textures, 0);
}
GLES20.glFinish();
if (mSurface != null) {
mSurface.release();
mSurface = null;
}
if (mSurfaceTexture != null) {
mSurfaceTexture.release();
mSurfaceTexture = null;
}
}
/**
* make texture as updated so that it can be updated in the next rendering.
*/
public void markTextureUpdated() {
mNumTextureUpdated.incrementAndGet();
}
/**
* update texture for rendering if it is updated.
*/
public void updateTexImageIfNecessary() {
int numTextureUpdated = mNumTextureUpdated.getAndDecrement();
if (numTextureUpdated > 0) {
if (DBG) {
Log.i(TAG, "updateTexImageIfNecessary " + this);
}
mSurfaceTexture.updateTexImage();
mSurfaceTexture.getTransformMatrix(mSTMatrix);
}
if (numTextureUpdated < 0) {
fail("should not happen");
}
}
/**
* draw the window. It will not be drawn at all if the window is not visible.
* @param uSTMatrixHandle shader handler for the STMatrix for texture coordinates
* mapping
* @param aPositionHandle shader handle for vertex position.
* @param aTextureHandle shader handle for texture
*/
public void onDraw(int uSTMatrixHandle, int aPositionHandle, int aTextureHandle) {
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId);
mVerticesData.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
GLES20.glVertexAttribPointer(aPositionHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mVerticesData);
GLES20.glEnableVertexAttribArray(aPositionHandle);
mVerticesData.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
GLES20.glVertexAttribPointer(aTextureHandle, 2, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mVerticesData);
GLES20.glEnableVertexAttribArray(aTextureHandle);
GLES20.glUniformMatrix4fv(uSTMatrixHandle, 1, false, mSTMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
}
public SurfaceTexture getSurfaceTexture() {
return mSurfaceTexture;
}
public Surface getSurface() {
return mSurface;
}
}
}
static void checkGlError(String op) throws GlException {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
Log.e(TAG, op + ": glError " + error);
throw new GlException(op + ": glError " + error);
}
}
public static class GlException extends Exception {
public GlException(String msg) {
super(msg);
}
}
private interface Renderer {
void doRendering(final int color) throws Exception;
}
private static class VirtualDisplayPresentation implements Renderer {
protected final Context mContext;
protected final Surface mSurface;
protected final int mWidth;
protected final int mHeight;
protected VirtualDisplay mVirtualDisplay;
protected TestPresentationBase mPresentation;
private final DisplayManager mDisplayManager;
VirtualDisplayPresentation(Context context, Surface surface, int w, int h) {
mContext = context;
mSurface = surface;
mWidth = w;
mHeight = h;
mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
}
void createVirtualDisplay() {
runOnMainSync(new Runnable() {
@Override
public void run() {
mVirtualDisplay = mDisplayManager.createVirtualDisplay(
TAG, mWidth, mHeight, 200, mSurface,
DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY |
DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION);
}
});
}
void destroyVirtualDisplay() {
runOnMainSync(new Runnable() {
@Override
public void run() {
mVirtualDisplay.release();
}
});
}
void createPresentation() {
runOnMainSync(new Runnable() {
@Override
public void run() {
mPresentation = doCreatePresentation();
mPresentation.show();
}
});
}
protected TestPresentationBase doCreatePresentation() {
return new TestPresentation(mContext, mVirtualDisplay.getDisplay());
}
TestPresentationBase getPresentation() {
return mPresentation;
}
void dismissPresentation() {
runOnMainSync(new Runnable() {
@Override
public void run() {
mPresentation.dismiss();
}
});
}
@Override
public void doRendering(final int color) throws Exception {
runOnMainSync(new Runnable() {
@Override
public void run() {
mPresentation.doRendering(color);
}
});
}
}
private static class TestPresentationBase extends Presentation {
public TestPresentationBase(Context outerContext, Display display) {
// This theme is required to prevent an extra view from obscuring the presentation
super(outerContext, display,
android.R.style.Theme_Holo_Light_NoActionBar_TranslucentDecor);
getWindow().setType(WindowManager.LayoutParams.TYPE_PRIVATE_PRESENTATION);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
}
public void doRendering(int color) {
// to be implemented by child
}
}
private static class TestPresentation extends TestPresentationBase {
private ImageView mImageView;
public TestPresentation(Context outerContext, Display display) {
super(outerContext, display);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageView = new ImageView(getContext());
mImageView.setImageDrawable(new ColorDrawable(COLOR_RED));
mImageView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
setContentView(mImageView);
}
public void doRendering(int color) {
if (DBG) {
Log.i(TAG, "doRendering " + Integer.toHexString(color));
}
mImageView.setImageDrawable(new ColorDrawable(color));
}
}
private static class TopWindowPresentation extends TestPresentationBase {
private FrameLayout[] mWindowsLayout = new FrameLayout[MAX_NUM_WINDOWS];
private CompositionTextureView[] mWindows = new CompositionTextureView[MAX_NUM_WINDOWS];
private final int mNumWindows;
private final Semaphore mWindowWaitSemaphore = new Semaphore(0);
public TopWindowPresentation(int numWindows, Context outerContext, Display display) {
super(outerContext, display);
mNumWindows = numWindows;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DBG) {
Log.i(TAG, "TopWindowPresentation onCreate, numWindows " + mNumWindows);
}
setContentView(R.layout.composition_layout);
mWindowsLayout[0] = (FrameLayout) findViewById(R.id.window0);
mWindowsLayout[1] = (FrameLayout) findViewById(R.id.window1);
mWindowsLayout[2] = (FrameLayout) findViewById(R.id.window2);
}
public void populateWindows() {
runOnMain(new Runnable() {
public void run() {
for (int i = 0; i < mNumWindows; i++) {
mWindows[i] = new CompositionTextureView(getContext());
mWindows[i].setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mWindowsLayout[i].setVisibility(View.VISIBLE);
mWindowsLayout[i].addView(mWindows[i]);
mWindows[i].startListening();
}
mWindowWaitSemaphore.release();
}
});
}
public void waitForSurfaceReady(long timeoutMs) throws Exception {
mWindowWaitSemaphore.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
for (int i = 0; i < mNumWindows; i++) {
if(!mWindows[i].waitForSurfaceReady(timeoutMs)) {
fail("surface wait timeout");
}
}
}
public Surface getSurface(int windowIndex) {
Surface surface = mWindows[windowIndex].getSurface();
assertNotNull(surface);
return surface;
}
}
private static class TopWindowVirtualDisplayPresentation extends VirtualDisplayPresentation {
private final int mNumWindows;
TopWindowVirtualDisplayPresentation(Context context, Surface surface, int w, int h,
int numWindows) {
super(context, surface, w, h);
assertNotNull(surface);
mNumWindows = numWindows;
}
void waitForSurfaceReady(long timeoutMs) throws Exception {
((TopWindowPresentation) mPresentation).waitForSurfaceReady(timeoutMs);
}
Surface getSurface(int windowIndex) {
return ((TopWindowPresentation) mPresentation).getSurface(windowIndex);
}
protected TestPresentationBase doCreatePresentation() {
return new TopWindowPresentation(mNumWindows, mContext, mVirtualDisplay.getDisplay());
}
}
private static class RemoteVirtualDisplayPresentation implements Renderer {
/** argument: Surface, int w, int h, return none */
private static final int BINDER_CMD_START = IBinder.FIRST_CALL_TRANSACTION;
/** argument: int color, return none */
private static final int BINDER_CMD_RENDER = IBinder.FIRST_CALL_TRANSACTION + 1;
private final Context mContext;
private final Surface mSurface;
private final int mWidth;
private final int mHeight;
private IBinder mService;
private final Semaphore mConnectionWait = new Semaphore(0);
private final ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mService = arg1;
mConnectionWait.release();
}
public void onServiceDisconnected(ComponentName arg0) {
//ignore
}
};
RemoteVirtualDisplayPresentation(Context context, Surface surface, int w, int h) {
mContext = context;
mSurface = surface;
mWidth = w;
mHeight = h;
}
void connect() throws Exception {
Intent intent = new Intent();
intent.setClassName("android.media.cts",
"android.media.cts.RemoteVirtualDisplayService");
mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
if (!mConnectionWait.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
fail("cannot bind to service");
}
}
void disconnect() {
mContext.unbindService(mConnection);
}
void start() throws Exception {
Parcel parcel = Parcel.obtain();
mSurface.writeToParcel(parcel, 0);
parcel.writeInt(mWidth);
parcel.writeInt(mHeight);
mService.transact(BINDER_CMD_START, parcel, null, 0);
}
@Override
public void doRendering(int color) throws Exception {
Parcel parcel = Parcel.obtain();
parcel.writeInt(color);
mService.transact(BINDER_CMD_RENDER, parcel, null, 0);
}
}
private static Size getMaxSupportedEncoderSize() {
final Size[] standardSizes = new Size[] {
new Size(1920, 1080),
new Size(1280, 720),
new Size(720, 480),
new Size(352, 576)
};
MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
for (Size sz : standardSizes) {
MediaFormat format = MediaFormat.createVideoFormat(
MIME_TYPE, sz.getWidth(), sz.getHeight());
format.setInteger(MediaFormat.KEY_FRAME_RATE, 15); // require at least 15fps
if (mcl.findEncoderForFormat(format) != null) {
return sz;
}
}
return null;
}
/**
* Check maximum concurrent encoding / decoding resolution allowed.
* Some H/Ws cannot support maximum resolution reported in encoder if decoder is running
* at the same time.
* Check is done for 4 different levels: 1080p, 720p, 800x480, 480p
* (The last one is required by CDD.)
*/
private Size checkMaxConcurrentEncodingDecodingResolution() {
if (isConcurrentEncodingDecodingSupported(1920, 1080, BITRATE_1080p)) {
return new Size(1920, 1080);
} else if (isConcurrentEncodingDecodingSupported(1280, 720, BITRATE_720p)) {
return new Size(1280, 720);
} else if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
return new Size(800, 480);
} else if (isConcurrentEncodingDecodingSupported(720, 480, BITRATE_DEFAULT)) {
return new Size(720, 480);
}
Log.i(TAG, "SKIPPING test: concurrent encoding and decoding is not supported");
return null;
}
private boolean isConcurrentEncodingDecodingSupported(int w, int h, int bitRate) {
MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
MediaFormat testFormat = MediaFormat.createVideoFormat(MIME_TYPE, w, h);
testFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
testFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
if (mcl.findDecoderForFormat(testFormat) == null
|| mcl.findEncoderForFormat(testFormat) == null) {
return false;
}
MediaCodec decoder = null;
OutputSurface decodingSurface = null;
MediaCodec encoder = null;
Surface encodingSurface = null;
try {
decoder = MediaCodec.createDecoderByType(MIME_TYPE);
MediaFormat decoderFormat = MediaFormat.createVideoFormat(MIME_TYPE, w, h);
decodingSurface = new OutputSurface(w, h);
decodingSurface.makeCurrent();
decoder.configure(decoderFormat, decodingSurface.getSurface(), null, 0);
decoder.start();
MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, w, h);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
format.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
encoder = MediaCodec.createEncoderByType(MIME_TYPE);;
encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
encodingSurface = encoder.createInputSurface();
encoder.start();
encoder.stop();
decoder.stop();
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "This H/W does not support w:" + w + " h:" + h);
return false;
} finally {
if (encodingSurface != null) {
encodingSurface.release();
}
if (encoder != null) {
encoder.release();
}
if (decoder != null) {
decoder.release();
}
if (decodingSurface != null) {
decodingSurface.release();
}
}
return true;
}
private static void runOnMain(Runnable runner) {
sHandlerForRunOnMain.post(runner);
}
private static void runOnMainSync(Runnable runner) {
SyncRunnable sr = new SyncRunnable(runner);
sHandlerForRunOnMain.post(sr);
sr.waitForComplete();
}
private static final class SyncRunnable implements Runnable {
private final Runnable mTarget;
private boolean mComplete;
public SyncRunnable(Runnable target) {
mTarget = target;
}
public void run() {
mTarget.run();
synchronized (this) {
mComplete = true;
notifyAll();
}
}
public void waitForComplete() {
synchronized (this) {
while (!mComplete) {
try {
wait();
} catch (InterruptedException e) {
//ignore
}
}
}
}
}
}
|
wiki2014/Learning-Summary
|
alps/cts/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java
|
Java
|
gpl-3.0
| 59,181
|
-- MySQL dump 10.13 Distrib 5.5.43, for debian-linux-gnu (x86_64)
--
-- Host: localhost Database: dspdb
-- ------------------------------------------------------
-- Server version 5.5.43-0ubuntu0.14.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `char_look`
--
DROP TABLE IF EXISTS `char_look`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `char_look` (
`charid` int(10) unsigned NOT NULL,
`face` tinyint(2) unsigned NOT NULL DEFAULT '0',
`race` tinyint(2) unsigned NOT NULL DEFAULT '0',
`size` tinyint(1) unsigned NOT NULL DEFAULT '0',
`head` smallint(4) unsigned NOT NULL DEFAULT '0',
`body` smallint(4) unsigned NOT NULL DEFAULT '8',
`hands` smallint(4) unsigned NOT NULL DEFAULT '8',
`legs` smallint(4) unsigned NOT NULL DEFAULT '8',
`feet` smallint(4) unsigned NOT NULL DEFAULT '8',
`main` smallint(4) unsigned NOT NULL DEFAULT '0',
`sub` smallint(4) unsigned NOT NULL DEFAULT '0',
`ranged` smallint(4) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`charid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AVG_ROW_LENGTH=24;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `char_look`
--
LOCK TABLES `char_look` WRITE;
/*!40000 ALTER TABLE `char_look` DISABLE KEYS */;
INSERT INTO `char_look` VALUES (21833,11,5,0,240,57,142,142,142,105,35,0),(21836,6,5,0,241,241,241,241,241,513,313,0),(21832,11,3,2,6,28,6,28,28,256,41,0),(21837,0,4,0,0,8,8,8,8,164,0,0),(21835,15,3,2,299,299,299,299,299,503,4599,0),(21838,4,8,2,30,30,30,30,30,308,0,0),(21839,2,5,2,125,37,117,17,6,314,314,0),(21840,15,3,2,17,17,17,17,17,131,4227,0),(21841,4,2,0,72,72,73,143,31,420,0,0),(21842,5,7,2,0,0,1,15,15,197,0,0),(21843,0,1,0,0,8,8,8,8,21,0,0),(21844,14,3,2,0,8,8,8,8,21,0,0),(21845,6,5,0,60,34,9,172,4,309,309,57),(21846,7,7,1,0,34,0,172,162,180,262,52),(21847,11,8,2,28,28,28,28,28,266,44,0),(21848,14,7,1,20,6,6,6,16,165,36,0),(21849,2,1,1,239,239,239,239,239,514,0,0),(21850,6,1,1,0,8,8,8,8,159,0,0);
/*!40000 ALTER TABLE `char_look` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-06-21 20:34:50
|
AdamGagorik/superdarkstar
|
backup/backup_2015_06_21/char_look.sql
|
SQL
|
gpl-3.0
| 3,145
|
#include "MapState.hpp"
namespace states {
MapState::MapState(engine::Engine& engine)
: GameState(engine), renderer(engine, world), saveFileHandler(engine), pauseState(engine, world, renderer) {
suspended = false;
};
void MapState::init() {
world::PerspectiveState initialPerspective;
initialPerspective.fovy = 45.f;
initialPerspective.aspect = engine.getWindowHandler().getViewportRatio();
initialPerspective.zNear = 0.1f;
initialPerspective.zFar = 10000.f;
data::CameraState initialCamera;
initialCamera.lookAt = glm::vec3();
initialCamera.distance = 80;
initialCamera.rotationAroundX = M_PI / 4.f;
initialCamera.rotationAroundY = 0;
world.getCamera().init(initialPerspective, initialCamera);
world.init();
city.name = "Warsaw";
city.people = 57950;
city.money = 445684;
world.getMap().setCurrentCity(&city);
createNewWorld();
geometry.init(engine, world);
init_brushes();
tree_shape = std::make_shared<geometry::Circle>(0.20f);
if (!renderer.init()) {
engine.stop();
return;
}
setCurrentAction(MapStateAction::PLACE_BUILDING);
this->pole_a = std::make_shared<data::PowerLinePole>(glm::vec2(5, 5));
this->pole_b = std::make_shared<data::PowerLinePole>(glm::vec2(5, 10));
this->pole_c = std::make_shared<data::PowerLinePole>(glm::vec2(5, 15));
world.getMap().add_power_pole(pole_a);
world.getMap().add_power_pole(pole_b);
world.getMap().add_power_pole(pole_c);
world.getMap().add_power_cable(std::make_shared<data::PowerLineCable>(*pole_a, *pole_b));
world.getMap().add_power_cable(std::make_shared<data::PowerLineCable>(*pole_b, *pole_c));
world.getTimer().start();
};
void MapState::init_brushes() noexcept {
tree_brush =
std::make_unique<input::Brush>(data::Position<float>(), TREE_BRUSH_RADIUS_NORMAL, TREE_BRUSH_BORDER_WIDTH);
tree_brush->set_base_colors(glm::vec4(1, 1, 1, 0.05f), glm::vec4(1, 1, 1, 0.4f));
tree_brush->set_active_colors(glm::vec4(1, 1, 0, 0.1f), glm::vec4(1, 1, 0, 0.4f));
}
void MapState::cleanup() {
renderer.cleanup();
world.cleanup();
}
void MapState::update(std::chrono::milliseconds delta) {
if (rmbPressed) {
handleMapDragging(delta);
}
if (rotatingClockwise) {
handleRotatingAroundY(delta, true);
}
if (rotatingCounterClockwise) {
handleRotatingAroundY(delta, false);
}
if (rotatingUpwards) {
handleRotatingAroundX(delta, true);
}
if (rotatingDownwards) {
handleRotatingAroundX(delta, false);
}
glm::ivec2 selectionEnd;
if (geometry.hitField(engine.getWindowHandler().getMousePositionNormalized(), selectionEnd)) {
if (!selection->isSelecting()) {
selection->from(selectionEnd);
}
selection->to(selectionEnd);
}
if (selection->isSelecting() && MapStateAction::PLACE_BUILDING == currentAction) {
glm::vec2 selection_size = selection->getTo() - selection->getFrom() + glm::ivec2(1, 1);
auto to_add_shape = std::make_shared<geometry::AABB>(glm::vec2(), selection_size);
auto colliders = collides_with(data::CollisionLayer::BUILDINGS);
geometry::Collidable to_add(data::CollisionLayer::BUILDINGS, colliders, to_add_shape, selection->getFrom());
if (!world.get_collision_space().if_collides(to_add)) {
selection->markValid();
} else {
selection->markInvalid();
}
}
if (MapStateAction::PLACE_ROAD == currentAction && selection->isSelecting()) {
data::Position from(selection->getFrom());
data::Position to(selection->getTo());
// FIXME(kantoniak): What if chunk in the middle is not active in the scene? Is it allowed.
bool chunk_exists = world.getMap().chunkExists(from.getChunk()) && world.getMap().chunkExists(to.getChunk());
if (!chunk_exists) {
selection->markInvalid();
} else {
geometry::Collidable::ptr candidate = selection_to_AABB(*selection, data::CollisionLayer::ROADS);
if (!world.get_collision_space().if_collides(*candidate)) {
selection->markValid();
} else {
selection->markInvalid();
}
}
}
if (currentAction == MapStateAction::PLACE_TREES) {
glm::vec3 hitpoint;
if (geometry.hitGround(engine.getWindowHandler().getMousePositionNormalized(), hitpoint)) {
tree_brush->set_center(glm::vec2(hitpoint.x, hitpoint.z));
if (tree_brush->get_radius() > TREE_BRUSH_RADIUS_SINGLE && tree_brush->is_active()) {
if (glm::distance(saved_tree_brush_hitpoint, tree_brush->get_center().getGlobal()) > 2.f) {
saved_tree_brush_hitpoint = tree_brush->get_center().getGlobal();
insert_trees_from_brush();
}
}
}
}
if (MapStateAction::PLACE_POWER_LINES == currentAction) {
this->current_tool->update();
}
// TODO(kantoniak): Remove temporary poles
float angle = (world.getTimer().get_turn_number() / 12.f) * M_PI * 2.f;
glm::vec2 pos_delta(cos(angle), sin(angle));
pole_a->set_translation(glm::vec2(5, 5) + pos_delta * 2.f);
pole_c->set_translation(glm::vec2(5, 15) + -pos_delta * 2.f);
float mid_angle = (fmod(world.getTimer().get_turn_number(), 24.f) / 24.f) * M_PI * 2.f;
pole_b->set_rotation(mid_angle);
pole_a->set_rotation(2 * M_PI - mid_angle);
world.update(delta);
};
void MapState::render() {
renderer.prepareFrame();
if (current_tool) {
this->current_tool->pre_render(renderer);
}
renderer.renderWorld(*selection, current_brush, current_tool);
#ifdef _DEBUG
renderer.renderWorldDebug();
renderer.renderDebug();
#endif
renderer.flushWorld();
engine.getDebugInfo().onRenderWorldEnd();
engine.getUI().startFrame();
renderer.renderUI();
#ifdef _DEBUG
renderer.renderDebugUI();
#endif
engine.getUI().endFrame();
renderer.sendFrame();
};
void MapState::onKey(int key, int, int action, int mods) {
// TODO(kantoniak): Refactor MapState::onKey by the end of march. If it's April you can start laughing now :)
if (key == GLFW_KEY_MINUS && action != GLFW_RELEASE) {
world.getCamera().zoom(-5);
}
if (key == GLFW_KEY_EQUAL && action != GLFW_RELEASE) {
world.getCamera().zoom(5);
}
// Rotation around Y
if (key == GLFW_KEY_Q && action == GLFW_PRESS) {
rotatingClockwise = true;
} else if (key == GLFW_KEY_Q && action == GLFW_RELEASE) {
rotatingClockwise = false;
}
if (key == GLFW_KEY_E && action == GLFW_PRESS) {
rotatingCounterClockwise = true;
} else if (key == GLFW_KEY_E && action == GLFW_RELEASE) {
rotatingCounterClockwise = false;
}
// Rotation around X
if (key == GLFW_KEY_HOME && action == GLFW_PRESS) {
rotatingUpwards = true;
} else if (key == GLFW_KEY_HOME && action == GLFW_RELEASE) {
rotatingUpwards = false;
}
if (key == GLFW_KEY_END && action == GLFW_PRESS) {
rotatingDownwards = true;
} else if (key == GLFW_KEY_END && action == GLFW_RELEASE) {
rotatingDownwards = false;
}
if (key == GLFW_KEY_N && action == GLFW_PRESS) {
engine.getSettings().rendering.renderNormals = !engine.getSettings().rendering.renderNormals;
engine.getLogger().debug(std::string("Normals view: %s"),
(engine.getSettings().rendering.renderNormals ? "on" : "off"));
}
if (key == GLFW_KEY_M && action == GLFW_PRESS) {
engine.getLogger().debug("Road nodes debug: %s",
(engine.getSettings().rendering.renderRoadNodesAsMarkers ? "on" : "off"));
engine.getSettings().rendering.renderRoadNodesAsMarkers = !engine.getSettings().rendering.renderRoadNodesAsMarkers;
renderer.markTileDataForUpdate();
}
if (key == GLFW_KEY_G && action == GLFW_PRESS) {
engine.getSettings().world.showGrid = !engine.getSettings().world.showGrid;
}
if (mods == GLFW_MOD_CONTROL) {
if (GLFW_KEY_1 <= key && key <= GLFW_KEY_9 && action == GLFW_PRESS) {
newBuildingHeight = key - GLFW_KEY_1 + 1;
}
} else {
if (GLFW_KEY_1 <= key && key <= GLFW_KEY_1 + world.getTimer().getMaxSpeed() - 1 && action == GLFW_PRESS) {
world.getTimer().setSpeed(key - GLFW_KEY_1 + 1);
world.getTimer().start();
}
}
if (key == GLFW_KEY_GRAVE_ACCENT && action == GLFW_PRESS) {
world.getTimer().pause();
}
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
switchToPauseState();
}
if (key == GLFW_KEY_Z && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_BUILDING);
}
if (key == GLFW_KEY_X && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_ZONE);
}
if (key == GLFW_KEY_C && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_ROAD);
}
if (key == GLFW_KEY_V && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_TREES);
}
if (key == GLFW_KEY_B && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::BULDOZE);
}
if (key == GLFW_KEY_N && action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) {
this->createNewWorld();
}
if (key == GLFW_KEY_S && action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) {
saveFileHandler.createSave(world);
}
if (key == GLFW_KEY_L && action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) {
world.get_collision_space().clear();
world.getMap().cleanup();
saveFileHandler.loadSave(world);
renderer.markTileDataForUpdate();
renderer.markBuildingDataForUpdate();
}
// Power lines
if (key == GLFW_KEY_P && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_POWER_LINES);
}
if (currentAction == MapStateAction::PLACE_TREES) {
switch (action) {
case GLFW_PRESS: {
if (key == GLFW_KEY_LEFT_ALT) {
tree_brush->set_radius(TREE_BRUSH_RADIUS_SINGLE);
renderer.mark_brush_dirty();
}
if (key == GLFW_KEY_LEFT_CONTROL) {
tree_brush->set_radius(TREE_BRUSH_RADIUS_SMALL);
renderer.mark_brush_dirty();
}
if (key == GLFW_KEY_LEFT_SHIFT) {
tree_brush->set_radius(TREE_BRUSH_RADIUS_BIG);
renderer.mark_brush_dirty();
}
break;
}
case GLFW_RELEASE: {
if (key != GLFW_KEY_LEFT_ALT && key != GLFW_KEY_LEFT_SHIFT && key != GLFW_KEY_LEFT_CONTROL) {
break;
}
if (tree_brush->get_radius() != TREE_BRUSH_RADIUS_NORMAL) {
tree_brush->set_radius(TREE_BRUSH_RADIUS_NORMAL);
renderer.mark_brush_dirty();
}
break;
}
}
}
}
void MapState::onMouseButton(int button, int action, int mods) {
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
selection->start(selection->getFrom());
} else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {
selection->stop();
if (MapStateAction::PLACE_BUILDING == currentAction) {
glm::ivec2 size = selection->getTo() - selection->getFrom() + glm::ivec2(1, 1);
auto to_add = std::make_shared<data::Building>();
to_add->width = size.x;
to_add->length = size.y;
to_add->level = newBuildingHeight;
to_add->x = selection->getFrom().x;
to_add->y = selection->getFrom().y;
auto to_add_shape = std::make_shared<geometry::AABB>(glm::vec2(), glm::vec2(size.x, size.y));
auto colliders = collides_with(data::CollisionLayer::BUILDINGS);
to_add->body = std::make_shared<geometry::Collidable>(data::CollisionLayer::BUILDINGS, colliders, to_add_shape,
selection->getFrom());
if (!world.get_collision_space().if_collides(*to_add->body)) {
// Delete colliding trees
auto collidables = world.get_collision_space().find_colliding_with(*to_add->body);
delete_collidables(collidables);
// Insert building
to_add->body->set_user_data(to_add.get());
world.get_collision_space().insert(to_add->body);
world.getMap().add_building(to_add);
renderer.markBuildingDataForUpdate();
}
}
if (MapStateAction::PLACE_ROAD == currentAction && selection->isValid()) {
geometry::Collidable::ptr candidate = selection_to_AABB(*selection, data::CollisionLayer::ROADS);
if (!world.get_collision_space().if_collides(*candidate)) {
// Delete colliding trees
auto collidables = world.get_collision_space().find_colliding_with(*candidate);
delete_collidables(collidables);
// Create and insert roads
auto* s = static_cast<input::LineSelection*>(selection.get());
const std::vector<input::LineSelection> selections = s->divideByChunk();
std::vector<data::Road> roads;
for (auto& selection : selections) {
geometry::Collidable::ptr road_body = selection_to_AABB(selection, data::CollisionLayer::ROADS);
world.get_collision_space().insert(road_body);
roads.emplace_back(selection.getSelected(), road_body);
}
world.getMap().addRoads(roads);
renderer.markTileDataForUpdate();
}
}
if (MapStateAction::BULDOZE == currentAction) {
// FIXME(kantoniak): Remove roads on buildozer
geometry::Collidable::ptr selection_phantom = selection_to_AABB(*selection, data::CollisionLayer::NONE);
geometry::Collidable::layer_key to_delete = data::CollisionLayer::BUILDINGS | data::CollisionLayer::TREES;
auto collidables = world.get_collision_space().collisions_with(*selection_phantom, to_delete);
delete_collidables(collidables);
renderer.markBuildingDataForUpdate();
}
}
if (button == GLFW_MOUSE_BUTTON_RIGHT) {
if (action == GLFW_PRESS) {
rmbPressed = true;
dragStart = engine.getWindowHandler().getMousePosition();
} else {
rmbPressed = false;
}
}
if (current_brush && button == GLFW_MOUSE_BUTTON_LEFT) {
if (action == GLFW_PRESS) {
current_brush->set_active(true);
glm::vec3 hitpoint;
if (geometry.hitGround(engine.getWindowHandler().getMousePositionNormalized(), hitpoint)) {
saved_tree_brush_hitpoint = glm::vec2(hitpoint.x, hitpoint.z);
if (current_brush->get_radius() == TREE_BRUSH_RADIUS_SINGLE) {
insert_trees_around(saved_tree_brush_hitpoint, {glm::vec2()});
} else {
insert_trees_from_brush();
}
}
} else if (action == GLFW_RELEASE) {
current_brush->set_active(false);
}
renderer.mark_brush_dirty();
}
if (current_tool) {
current_tool->on_mouse_button(button, action, mods);
}
}
void MapState::onScroll(double, double yoffset) {
world.getCamera().zoom(yoffset * 5);
}
void MapState::onWindowFocusChange(int focused) {
if (!focused) {
switchToPauseState();
}
}
void MapState::onWindowResize(int width, int height) {
world.getCamera().updateAspect(width / (float)height);
}
geometry::Collidable::ptr MapState::selection_to_AABB(const input::Selection& selection,
data::CollisionLayer layer) const noexcept {
glm::vec2 selection_size = selection.getTo() - selection.getFrom() + glm::ivec2(1, 1);
auto to_add_shape = std::make_shared<geometry::AABB>(glm::vec2(), selection_size);
geometry::Collidable::layer_key colliders = collides_with(static_cast<data::CollisionLayer>(layer));
return std::make_shared<geometry::Collidable>(layer, colliders, to_add_shape, selection.getFrom());
}
void MapState::delete_collidables(const std::vector<geometry::Collidable::ptr>& collidables) noexcept {
// TODO(kantoniak): Allow for reuse with different tools
for (auto& collidable : collidables) {
if (collidable->get_user_data() != nullptr) {
switch (collidable->get_layer_key()) {
case data::CollisionLayer::BUILDINGS: {
const data::Building& building = *static_cast<data::Building*>(collidable->get_user_data());
world.getMap().remove_building(building);
break;
}
case data::CollisionLayer::TREES: {
const data::Tree& tree = *static_cast<data::Tree*>(collidable->get_user_data());
world.getMap().remove_tree(tree);
break;
}
}
}
world.get_collision_space().remove(*collidable);
}
}
data::Tree::ptr MapState::create_random_tree(const data::Position<float>& position,
geometry::Collidable::ptr tree_body) noexcept {
const auto type = static_cast<data::Tree::Type>(rand() % data::Tree::TREE_TYPE_COUNT);
const float age = 100.f * static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
const float rotation = 2.f * M_PI * static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
return std::make_shared<data::Tree>(type, position, rotation, age, tree_body);
}
void MapState::insert_trees_from_brush() noexcept {
static const float tree_density = 2.5f;
const float brush_radius = current_brush->get_radius();
size_t point_count = tree_density * brush_radius * brush_radius;
std::vector<glm::vec2> points = geometry.distribute_in_circle(point_count, brush_radius, 3.f);
insert_trees_around(saved_tree_brush_hitpoint, points);
}
void MapState::insert_trees_around(const glm::vec2& center, const std::vector<glm::vec2>& points) noexcept {
for (auto& point : points) {
const glm::vec2 tree_center(center + point);
// Skip trees outside chunks
// FIXME(kantoniak): This should handle when there are multiple chunks on the board
if (tree_center.x < 0 || data::Chunk::SIDE_LENGTH < tree_center.x || tree_center.y < 0 ||
data::Chunk::SIDE_LENGTH < tree_center.y) {
continue;
}
auto colliders = collides_with(data::CollisionLayer::TREES);
auto collidable_ptr =
std::make_shared<geometry::Collidable>(data::CollisionLayer::TREES, colliders, tree_shape, tree_center);
if (!world.get_collision_space().if_collides(*collidable_ptr)) {
auto tree_ptr = create_random_tree(tree_center, collidable_ptr);
collidable_ptr->set_user_data(tree_ptr.get());
world.get_collision_space().insert(collidable_ptr);
world.getMap().add_tree(tree_ptr);
}
}
}
void MapState::createNewWorld() {
world.getMap().cleanup();
const glm::ivec2 mapSize = glm::ivec2(1, 1);
for (int x = 0; x < mapSize.x; x++) {
for (int y = 0; y < mapSize.y; y++) {
world.getMap().createChunk(glm::ivec2(x, y));
}
}
}
void MapState::createRandomWorld() {
/*const glm::ivec2 mapSize = glm::ivec2(2, 2);
for (int x = 0; x < mapSize.x; x++) {
for (int y = 0; y < mapSize.y; y++) {
world.getMap().createChunk(glm::ivec2(x, y));
}
}
for (int x = 0; x < mapSize.x; x++) {
for (int y = 0; y < mapSize.y; y++) {
auto chunkPos = glm::ivec2(x, y);
int lotX = 0;
for (int i = 2; i < 11; i++) {
data::Lot lot;
lot.position.setLocal(glm::ivec2(lotX + 2, 2), chunkPos);
lot.size = glm::ivec2(i, 6);
switch (i % 4) {
case 0:
lot.direction = data::Direction::N;
break;
case 1:
lot.direction = data::Direction::S;
break;
case 2:
lot.direction = data::Direction::W;
break;
case 3:
lot.direction = data::Direction::E;
break;
}
world.getMap().addLot(lot);
lotX += 1 + i;
}
}
}
// TEST road division
renderer.markTileDataForUpdate();
constexpr unsigned int minBuildingSide = 2;
constexpr unsigned int maxBuildingSideDifference = 3;
constexpr unsigned int minBuildingHeight = 1;
constexpr unsigned int maxBuildingHeightDifference = 6;
constexpr unsigned int maxCollisionTries = 20;
const unsigned int buildingCount =
(mapSize.x * mapSize.y) * (data::Chunk::SIDE_LENGTH * data::Chunk::SIDE_LENGTH / 4) * 0.02f;
for (unsigned int i = 0; i < buildingCount; i++) {
data::buildings::Building test;
for (unsigned int i = 0; i < maxCollisionTries; i++) {
test.width = rand() % maxBuildingSideDifference + minBuildingSide;
test.length = rand() % maxBuildingSideDifference + minBuildingSide;
test.level = rand() % maxBuildingHeightDifference + minBuildingHeight;
test.x = rand() % (data::Chunk::SIDE_LENGTH * mapSize.x - test.width + 1);
test.y = rand() % (data::Chunk::SIDE_LENGTH * mapSize.y - test.length + 1);
if (!geometry.checkCollisions(test)) {
world.getMap().addBuilding(test);
break;
}
}
}*/
}
void MapState::setCurrentAction(MapStateAction action) {
currentAction = action;
renderer.setLeftMenuActiveIcon(currentAction - MapStateAction::PLACE_BUILDING);
// Reset brush, selection and tool
engine.getSettings().rendering.renderSelection = false;
current_brush = nullptr;
renderer.mark_brush_dirty();
this->current_tool.reset();
switch (action) {
case MapStateAction::PLACE_BUILDING:
engine.getSettings().rendering.renderSelection = true;
selection = std::make_unique<input::Selection>();
selection->setColors(glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 0, 0, 0.4f));
break;
case MapStateAction::PLACE_ZONE:
break;
case MapStateAction::PLACE_POWER_LINES: {
auto tool_ptr = std::make_shared<input::PowerLineTool>(engine.getWindowHandler(), world,
renderer.get_model_manager(), geometry, current_brush);
this->current_tool = tool_ptr;
this->current_brush = tool_ptr->get_brush_ptr();
break;
}
case MapStateAction::PLACE_ROAD:
engine.getSettings().rendering.renderSelection = true;
selection = std::make_unique<input::LineSelection>(1);
selection->setColors(glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 0, 0, 0.4f));
break;
case MapStateAction::PLACE_TREES:
current_brush = tree_brush;
tree_brush->set_center(glm::vec2(10, 10));
renderer.mark_brush_dirty();
break;
case MapStateAction::BULDOZE:
engine.getSettings().rendering.renderSelection = true;
selection = std::make_unique<input::Selection>();
selection->setColors(glm::vec4(1, 0.f, 0.f, 0.2f), glm::vec4(1, 0.f, 0.f, 0.6f), glm::vec4(1, 0, 0, 1.f));
break;
}
}
void MapState::handleMapDragging(std::chrono::milliseconds delta) {
const glm::vec2 mousePosition = engine.getWindowHandler().getMousePosition();
const glm::vec2 dragDelta = mousePosition - dragStart;
float dragSpeed = 0.2f * delta.count() / 1000.f;
world.getCamera().move(dragSpeed * glm::vec3(dragDelta.x, 0.f, dragDelta.y));
}
void MapState::handleRotatingAroundY(std::chrono::milliseconds delta, bool clockwise) {
float rotationDelta = M_PI * delta.count() / 1000.f;
float modifier = (clockwise ? 1.f : -1.f);
world.getCamera().rotateAroundY(rotationDelta * modifier);
}
void MapState::handleRotatingAroundX(std::chrono::milliseconds delta, bool upwards) {
float rotationDelta = M_PI * delta.count() / 1000.f;
float modifier = (upwards ? 1.f : -1.f);
world.getCamera().rotateAroundX(rotationDelta * modifier);
}
void MapState::switchToPauseState() {
engine.pushState(pauseState);
}
}
|
kantoniak/konstruisto
|
src/states/MapState.cpp
|
C++
|
gpl-3.0
| 22,882
|
from core.testcases import APIModelViewSetTestCase, ModelViewSetTestCase, get_permissions_from_compact
from authentication.models import User, UserType
class UserViewSetTestCase(APIModelViewSetTestCase):
model = User
permissions = get_permissions_from_compact({
'list': '...a', # Only admin can list
'retrieve': '.u.a', # Only user and admin can retrieve
# 'update': '.u.a', # TODO Only user and admin can update ??
})
def create_object(self, user: User=None) -> User:
return self.users['user']
class UserTypeViewSetTestCase(ModelViewSetTestCase):
model = UserType
permissions = get_permissions_from_compact({
'list': 'puoa', # Everyone can list
'retrieve': 'puoa', # Everyone can retrieve
'create': '...a', # Only admin can create
'update': '...a', # Only admin can update
'delete': '...a', # Only admin can delete
})
# TODO Test user retrieval from API
|
simde-utc/woolly-api
|
authentication/tests.py
|
Python
|
gpl-3.0
| 999
|
Monster = ring.create([AbstractIcon], {
constructor: function()
{
this.sprite = objPhaser.add.sprite(0, 0, Constants.ASSET_MONSTER);
this.sprite.animations.add("fly");
this.sprite.animations.play("fly", 3, true);
this.type = Constants.ASSET_MONSTER;
this.anim = 0;
this.sinchange = 0;
},
update: function(gamespeed)
{
this.$super(gamespeed);
/*this.anim++;
if (this.anim % Constants.MONSTER_LEVITATE_SPEED == 0)
{
this.sinchange++;
this.sprite.y += Math.round(Math.sin(this.sinchange) * Constants.MONSTER_LEVITATE_ACCELERATION);
}*/
},
toString: function()
{
return "Monster";
}
});
|
gfrymer/GGJ2015-BSAS-Duality
|
src/entities/Monster.js
|
JavaScript
|
gpl-3.0
| 629
|
#ifndef HTTPSERVER_H
#define HTTPSERVER_H
class ServerStarter;
namespace Ilwis {
namespace HTTP {
class HTTPServer : public OperationImplementation
{
public:
HTTPServer();
HTTPServer(quint64 metaid, const Ilwis::OperationExpression &expr);
~HTTPServer() ;
static quint64 createMetadata();
static Ilwis::OperationImplementation *create(quint64 metaid,const Ilwis::OperationExpression& expr);
OperationImplementation::State prepare(ExecutionContext *ctx, const SymbolTable& symTable);
bool execute(ExecutionContext *ctx, SymbolTable& symTable);
NEW_OPERATION(HTTPServer);
private:
static std::unique_ptr<ServerStarter>_server;
quint16 _port;
};
}
}
#endif // HTTPSERVER_H
|
52North/IlwisCore
|
httpserver/httpserver.h
|
C
|
gpl-3.0
| 715
|
function direction(dir, neg) {
if (dir == 'x') {
return function (num) {
num = num == null ? 1 : num;
return new Tile(this.x + (neg ? -num : num), this.y);
};
}
return function (num) {
num = num == null ? 1 : num;
return new Tile(this.x, this.y + (neg ? -num : num));
};
}
var Tile = new Class({
initialize: function (x, y, layer) {
this.width = GetTileWidth();
this.height = GetTileHeight();
if (arguments.length > 1) {
this.layer = [layer, GetPersonLayer(Arq.config.player)].pick();
this.id = GetTile(x, y, this.layer);
this.x = x;
this.y = y;
this.pixelX = this.width * x;
this.pixelY = this.height * y;
}
else
this.id = x;
this.name = GetTileName(this.id);
},
north: direction('y', true),
south: direction('y'),
east: direction('x'),
west: direction('x', true),
place: function (person) {
SetPersonX(person, this.pixelX + this.width / 2);
SetPersonY(person, this.pixelY + this.height / 2);
return this;
},
set: function (tile) {
if (typeof tile == 'string')
tile = Tile.name(tile);
SetTile(this.x, this.y, this.layer, typeof tile == 'number' ? tile : tile.id);
return this;
}
});
function creator(create) {
return function (x, y, layer) {
if (arguments.length == 1) {
var coords = x;
x = coords.x;
y = coords.y;
}
return create(x, y, layer);
};
}
Tile.id = function (id) new Tile(id);
Tile.name = function (name) {
var n = GetNumTiles();
while (n--) {
if (GetTileName(n) == name)
return Tile.id(n);
}
};
Tile.tile = creator(function (x, y, layer) new Tile(x, y, layer));
Tile.pixels = creator(function (x, y, layer) new Tile(Math.floor(x / GetTileWidth()), Math.floor(y / GetTileHeight()), layer));
Tile.under = function (person) Tile.pixels(GetPersonX(person), GetPersonY(person), GetPersonLayer(person));
Tile.current = function () Tile.under(Arq.config.player);
exports.Tile = Tile;
|
alpha123/Arq
|
tile.js
|
JavaScript
|
gpl-3.0
| 2,213
|
<?php
namespace ModulusContent\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ItensMenu
*
* @ORM\Table(name="itens_menu")
* @ORM\Entity(repositoryClass="ModulusContent\Repository\ItensMenu")
*/
class ItensMenu
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="label", type="string", length=100, nullable=false)
*/
private $label;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=100, nullable=false)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="url", type="string", length=255, nullable=true)
*/
private $url;
/**
* @var integer
*
* @ORM\Column(name="ordem", type="integer", nullable=false)
*/
private $ordem;
/**
* @var \Menu
*
* @ORM\ManyToOne(targetEntity="Menu")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
* })
*/
private $menu;
/**
* @var \ItensMenu
*
* @ORM\ManyToOne(targetEntity="ItensMenu")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="parent_item_menu_id", referencedColumnName="id")
* })
*/
private $parentItemMenu;
/**
* @var \SiteContent
*
* @ORM\ManyToOne(targetEntity="SiteContent")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="site_content_id", referencedColumnName="id")
* })
*/
private $siteContent;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set label
*
* @param string $label
* @return ItensMenu
*/
public function setLabel($label)
{
$this->label = $label;
return $this;
}
/**
* Get label
*
* @return string
*/
public function getLabel()
{
return $this->label;
}
/**
* Set title
*
* @param string $title
* @return ItensMenu
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set url
*
* @param string $url
* @return ItensMenu
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set ordem
*
* @param integer $ordem
* @return ItensMenu
*/
public function setOrdem($ordem)
{
$this->ordem = $ordem;
return $this;
}
/**
* Get ordem
*
* @return integer
*/
public function getOrdem()
{
return $this->ordem;
}
/**
* Set menu
*
* @param \Menu $menu
* @return ItensMenu
*/
public function setMenu(Menu $menu = null)
{
$this->menu = $menu;
return $this;
}
/**
* Get menu
*
* @return \Menu
*/
public function getMenu()
{
return $this->menu;
}
/**
* Set parentItemMenu
*
* @param \ItensMenu $parentItemMenu
* @return ItensMenu
*/
public function setParentItemMenu(ItensMenu $parentItemMenu = null)
{
$this->parentItemMenu = $parentItemMenu;
return $this;
}
/**
* Get parentItemMenu
*
* @return \ItensMenu
*/
public function getParentItemMenu()
{
return $this->parentItemMenu;
}
/**
* Set siteContent
*
* @param \SiteContent $siteContent
* @return ItensMenu
*/
public function setSiteContent(SiteContent $siteContent = null)
{
$this->siteContent = $siteContent;
return $this;
}
/**
* Get siteContent
*
* @return \SiteContent
*/
public function getSiteContent()
{
return $this->siteContent;
}
}
|
ZF2-Modulus/ModulusContent
|
src/ModulusContent/Entity/ItensMenu.php
|
PHP
|
gpl-3.0
| 4,282
|
// TinyXML2Demo.cpp : ¶¨Òå¿ØÖÆÌ¨Ó¦ÓóÌÐòµÄÈë¿Úµã¡£
//
#include "stdafx.h"
#include "tinyxml2.h"
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include <time.h>
using namespace std;
using namespace tinyxml2;
const char* NODE_XML = "Node.xml";
const char* NODE_ACG_H = "../AcgDemo/NodeAcg.h";
template<class TData>
string DebugData(const TData& data)
{
ostringstream oss;
oss << data;
return oss.str();
}
template<class TData>
string DebugData(const vector<TData>& dataVec)
{
ostringstream oss;
for each (const TData& data in dataVec)
{
oss << data << " ";
}
return oss.str();
}
template<class TData1, class TData2>
string DebugData(const map<TData1, TData2>& dataMap)
{
ostringstream oss;
for each (pair<TData1, TData2> data in dataMap)
{
oss << "[" << DebugData(data.first) << " " << DebugData(data.second) << "]";
}
return oss.str();
}
void DebugElement(FILE* fp, const char* pszSpace, const char* pszPrefix, const char* pszName, const char* pszType, bool bPrintName)
{
if (bPrintName)
fprintf(fp, "%soss << \"%s:\"", pszSpace, pszName);
else
fprintf(fp, "%soss", pszSpace);
if (!strncmp(pszType, "Ms", 2))
{
fprintf(fp, " << DebugClass(%s%s);\n", pszPrefix, pszName);
}
else if (!strncmp(pszType, "vector", 6))
{
fprintf(fp, " << \"[ \";\n");
char pszVecType[64] = { 0 };
const char* pszLT = strchr(pszType, '<');
const char* pszGT = strrchr(pszType, '>');
strncpy_s(pszVecType, 64, pszLT + 1, pszGT - pszLT - 1);
fprintf(fp, "%sfor_each(%s%s.begin(), %s%s.end(), [&oss](const %s& data)->void\n", pszSpace, pszPrefix, pszName, pszPrefix, pszName, pszVecType);
fprintf(fp, "%s{\n", pszSpace);
char pszNewSpace[1024] = { 0 };
strncpy_s(pszNewSpace, 1024, pszSpace, strlen(pszSpace));
strcat_s(pszNewSpace, 1024, " ");
DebugElement(fp, pszNewSpace, "", "data", pszVecType, false);
fprintf(fp, "%s});\n", pszSpace);
fprintf(fp, "%soss << \"] \";\n", pszSpace);
}
else if (!strncmp(pszType, "map", 3))
{
fprintf(fp, " << \"{ \";\n");
char keyType[64] = { 0 };
char valType[64] = { 0 };
char pairType[64] = { 0 };
const char* pszLT = strchr(pszType, '<');
const char* pszComma = strchr(pszType, ',');
const char* pszGT = strrchr(pszType, '>');
strncpy_s(keyType, 64, pszLT + 1, pszComma - pszLT - 1);
strncpy_s(valType, 64, pszComma + 1, pszGT - pszComma - 1);
strncpy_s(pairType, 64, pszLT + 1, pszGT - pszLT - 1);
fprintf(fp, "%sfor_each(%s%s.begin(), %s%s.end(), [&oss](const pair<%s>& data)->void\n", pszSpace, pszPrefix, pszName, pszPrefix, pszName, pairType);
fprintf(fp, "%s{\n", pszSpace);
char pszNewSpace[1024] = { 0 };
strncpy_s(pszNewSpace, 1024, pszSpace, strlen(pszSpace));
strcat_s(pszNewSpace, 1024, " ");
fprintf(fp, "%soss << \"[ \";\n", pszNewSpace);
DebugElement(fp, pszNewSpace, "", "data.first", keyType, false);
DebugElement(fp, pszNewSpace, "", "data.second", valType, false);
fprintf(fp, "%soss << \"]\";\n", pszNewSpace);
fprintf(fp, "%s});\n", pszSpace);
fprintf(fp, "%soss << \" } \";\n", pszSpace);
}
else
{
fprintf(fp, " << %s%s << \" \";\n", pszPrefix, pszName);
}
}
//string DebugClass(MsUserInfoLite& mb)
//{
// ostringstream oss;
//
// oss << DebugData(mb.roleId) << " " << DebugData(mb.roleName);
//
// return oss.str();
//}
void AutoGenClass()
{
FILE* fp;
fopen_s(&fp, NODE_ACG_H, "w");
if (!fp)
{
printf("error open file %s\n", NODE_ACG_H);
return;
}
XMLDocument *pDoc = new XMLDocument();
XMLError errorId = pDoc->LoadFile(NODE_XML);
if (errorId != XML_SUCCESS)
{
fclose(fp);
printf("error load xml: %d %s\n", errorId, NODE_XML);
return;
}
XMLElement* pRoot = pDoc->RootElement();
XMLElement* pCppText = pRoot->FirstChildElement("CppText");
fprintf(fp, "%s\n", pCppText->GetText());
XMLElement* pMessage = pRoot->FirstChildElement("Message");
while (pMessage)
{
const char* pszName = pMessage->Attribute("name");
const char* pszBase = pMessage->Attribute("base");
fprintf(fp, "class Ms%s", pszName);
if (pszBase)
fprintf(fp, " : public Ms%s", pszBase);
fprintf(fp, "\n");
fprintf(fp, "{\n");
fprintf(fp, "public:\n");
fprintf(fp, " Ms%s(){}\n", pszName);
fprintf(fp, "\npublic:\n");
XMLElement* pVar = pMessage->FirstChildElement("Var");
while (pVar)
{
const char* pszName = pVar->Attribute("name");
const char* pszType = pVar->Attribute("type");
fprintf(fp, " %s %s;\n", pszType, pszName);
pVar = pVar->NextSiblingElement();
}
fprintf(fp, "};\n\n\n");
pMessage = pMessage->NextSiblingElement();
}
fclose(fp);
}
void AutoGenDebugClass()
{
FILE* fp;
fopen_s(&fp, NODE_ACG_H, "a");
if (!fp)
{
printf("error open file: %s\n", NODE_ACG_H);
return;
}
XMLDocument *pDoc = new XMLDocument();
XMLError errorId = pDoc->LoadFile(NODE_XML);
if (errorId != XML_SUCCESS)
{
fclose(fp);
printf("error load xml: %d %s\n", errorId, NODE_XML);
return;
}
XMLElement* pRoot = pDoc->RootElement();
XMLElement* pMessage = pRoot->FirstChildElement("Message");
while (pMessage)
{
const char* pszName = pMessage->Attribute("name");
const char* pszBase = pMessage->Attribute("base");
fprintf(fp, "string DebugClass(const class Ms%s& mb)\n", pszName);
fprintf(fp, "{\n");
char pszSpace[1024] = " ";
fprintf(fp, "%sostringstream oss;\n", pszSpace);
fprintf(fp, "%soss << \"{ \";\n", pszSpace);
if (pszBase)
{
fprintf(fp, "%soss << \"Ms%s: \" << DebugClass(static_cast<const Ms%s&>(mb));\n", pszSpace, pszBase, pszBase);
}
XMLElement* pVar = pMessage->FirstChildElement("Var");
while (pVar)
{
const char* pszName = pVar->Attribute("name");
const char* pszType = pVar->Attribute("type");
DebugElement(fp, pszSpace, "mb.", pszName, pszType, true);
pVar = pVar->NextSiblingElement();
}
fprintf(fp, "%soss << \"} \";\n", pszSpace);
fprintf(fp, "%sreturn oss.str();\n", pszSpace);
fprintf(fp, "}\n");
pMessage = pMessage->NextSiblingElement();
}
fclose(fp);
}
int main()
{
//printf("/\\");
//printf("\n");
if ((void)0, 0)
{
printf("i am void 0\n");
}
else
{
printf("i am not void 0\n");
}
AutoGenClass();
AutoGenDebugClass();
//FILE* fp;
//fopen_s(&fp, "../AcgDemo/NodeAcg.h", "a");
//XMLDocument *pDoc = new XMLDocument();
//XMLError errorId = pDoc->LoadFile(NODE_XML);
//if (errorId != XML_SUCCESS)
//{
// fclose(fp);
// printf("error load xml: %d %s\n", errorId, NODE_XML);
// system("pause");
// return 0;
//}
//XMLElement* pRoot = pDoc->RootElement();
//XMLElement* pMessage = pRoot->FirstChildElement("Message");
//while (pMessage)
//{
// const char* pszName = pMessage->Attribute("name");
// const char* pszBase = pMessage->Attribute("base");
// fprintf(fp, "string DebugClass(class Ms%s& mb)\n", pszName);
// fprintf(fp, "{\n");
// fprintf(fp, " ostringstream oss;\n");
// XMLElement* pVar = pMessage->FirstChildElement("Var");
// while (pVar)
// {
// const char* pszName = pVar->Attribute("name");
// const char* pszType = pVar->Attribute("type");
// DebugElement(fp, "mb.", pszName, pszType);
// //if( !strncmp(pszType, "Ms", 2) )
// // printf(" oss << DebugClass(mb.%s);\n", pszName);
// //else if( !strncmp(pszType, "vector", 6))
// //else
// // printf(" oss << DebugData(mb.%s);\n", pszName);
// pVar = pVar->NextSiblingElement();
// }
// fprintf(fp, " return oss.str();\n");
// fprintf(fp, "}\n");
//
// pMessage = pMessage->NextSiblingElement();
//}
//while (pMessage)
//{
// const char* pszName = pMessage->Attribute("name");
// const char* pszBase = pMessage->Attribute("base");
// XMLElement* pVar = pMessage->FirstChildElement("Var");
// while (pVar)
// {
// printf("var name:%s type:%s\n", pVar->Attribute("name"), pVar->Attribute("type"));
// pVar = pVar->NextSiblingElement();
// }
// pMessage = pMessage->NextSiblingElement();
//}
//int nNum = 1;
//printf("debug 1: %s\n", DebugData(nNum).c_str());
//vector<int> numVec;
//numVec.push_back(1);
//numVec.push_back(1);
//numVec.push_back(3);
//printf("debug vector: %s\n", DebugData(numVec).c_str());
//map<int, int> numMap;
//numMap[1] = 1;
//numMap[2] = 2;
//numMap[3] = 3;
//printf("debug map: %s\n", DebugData(numMap).c_str());
//fclose(fp);
system("pause");
return 0;
}
|
windpenguin/TinyXML2Demo
|
TinyXML2Demo/TinyXML2Demo.cpp
|
C++
|
gpl-3.0
| 8,301
|
google-site-verification: google96c17f49c1d12b36.html
|
paperhive/paperhive-launch
|
src/google96c17f49c1d12b36.html
|
HTML
|
gpl-3.0
| 53
|
class Deputy < User
has_many :users, :through => :substitutions, :dependent => :restrict, :inverse_of => :deputies
end
|
informatom/qm
|
app/models/deputy.rb
|
Ruby
|
gpl-3.0
| 121
|
/*
Copyright (C) 2016 Julien Le Fur
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/>.
*/
var CST = require('../../constants.js');
var fs = require('fs');
var util = require('util');
function execute(args,options,input,ctx,callback){
if(ctx[CST.OBJ.TEMPLATE]==undefined){
return callback(new Error(util.format(CST.MSG_ERR.TEMPLATE_NOT_EXIST,args[CST.OBJ.TEMPLATE])));
}
var template=`./${config.get('simusPath')}/${args[CST.OBJ.SERVICE]}/${args[CST.OBJ.API]}/${args[CST.OBJ.TEMPLATE]}`;
fs.unlink(template, (err)=>{
if(err)
return callback(new Error(util.format(CST.MSG_ERR.TEMPLATE_DELETE,args[CST.OBJ.TEMPLATE])));
else{
return callback(null,args,options,input,ctx);
}
});
}
module.exports = execute
|
Ju-Li-An/gs_engine
|
lib/dataAccess/fs/template/delete.js
|
JavaScript
|
gpl-3.0
| 1,386
|
<?php
/*
* TreeChecker: Error recognition for genealogical trees
*
* Copyright (C) 2014 Digital Humanities Lab, Faculty of Humanities, Universiteit Utrecht
* Corry Gellatly <corry.gellatly@gmail.com>
* Martijn van der Klis <M.H.vanderKlis@uu.nl>
*
* Class that defines an event details object
*
* Derived from webtrees: Web based Family History software
* Copyright (C) 2014 webtrees development team.
*
* 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/>.
*/
if (!defined('WT_WEBTREES')) {
header('HTTP/1.0 403 Forbidden');
exit;
}
class WT_Fact {
private $fact_id = null; // Unique identifier for this fact
private $parent = null; // The GEDCOM record from which this fact is taken.
private $gedcom = null; // The raw GEDCOM data for this fact
private $tag = null; // The GEDCOM tag for this record
private $is_old = false; // Is this a pending record?
private $is_new = false; // Is this a pending record?
private $date = null; // The WT_Date object for the "2 DATE ..." attribute
private $place = null; // The WT_Place object for the "2 PLAC ..." attribute
private $lati = null; // The WT_Lati object for the "2 LATI ..." attribute
private $long = null; // The WT_Long object for the "2 LONG ..." attribute
// Temporary(!) variables that are used by other scripts
public $temp = null; // Timeline controller
public $sortOrder = 0; // sort_facts()
// Create an event objects from a gedcom fragment.
// We need the parent object (to check privacy) and a (pseudo) fact ID to
// identify the fact within the record.
public function __construct($gedcom, WT_GedcomRecord $parent, $fact_id) {
if (preg_match('/^1 ('.WT_REGEX_TAG.')/', $gedcom, $match)) {
$this->gedcom = $gedcom;
$this->parent = $parent;
$this->fact_id = $fact_id;
$this->tag = $match[1];
} else {
// TODO need to rewrite code that passes dummy data to this function
//throw new Exception('Invalid GEDCOM data passed to WT_Fact::_construct('.$gedcom.')');
}
}
// Get the value of level 1 data in the fact
// Allow for multi-line values
public function getValue() {
if (preg_match('/^1 (?:' . $this->tag . ') ?(.*(?:(?:\n2 CONT ?.*)*))/', $this->gedcom, $match)) {
return preg_replace("/\n2 CONT ?/", "\n", $match[1]);
} else {
return null;
}
}
// Get the record to which this fact links
public function getTarget() {
$xref = trim($this->getValue(), '@');
switch ($this->tag) {
case 'FAMC':
case 'FAMS':
return WT_Family::getInstance($xref, $this->getParent()->getGedcomId());
case 'HUSB':
case 'WIFE':
case 'CHIL':
return WT_Individual::getInstance($xref, $this->getParent()->getGedcomId());
case 'SOUR':
return WT_Source::getInstance($xref, $this->getParent()->getGedcomId());
case 'OBJE':
return WT_Media::getInstance($xref, $this->getParent()->getGedcomId());
case 'REPO':
return WT_Repository::getInstance($xref, $this->getParent()->getGedcomId());
case 'NOTE':
return WT_Note::getInstance($xref, $this->getParent()->getGedcomId());
default:
return WT_GedcomRecord::getInstance($xref, $this->getParent()->getGedcomId());
}
}
// Get the value of level 2 data in the fact
public function getAttribute($tag) {
if (preg_match('/\n2 (?:' . $tag . ') ?(.*(?:(?:\n3 CONT ?.*)*)*)/', $this->gedcom, $match)) {
return preg_replace("/\n3 CONT ?/", "\n", $match[1]);
} else {
return null;
}
}
// Do the privacy rules allow us to display this fact to the current user
public function canShow($access_level=WT_USER_ACCESS_LEVEL) {
// TODO - use the privacy settings for $this->gedcom_id, not the default gedcom.
global $person_facts, $global_facts;
// // Does this record have an explicit RESN?
// if (strpos($this->gedcom, "\n2 RESN confidential")) {
// return WT_PRIV_NONE >= $access_level;
// }
// if (strpos($this->gedcom, "\n2 RESN privacy")) {
// return WT_PRIV_USER >= $access_level;
// }
// if (strpos($this->gedcom, "\n2 RESN none")) {
// return true;
// }
//
// // Does this record have a default RESN?
// $xref = $this->parent->getXref();
// if (isset($person_facts[$xref][$this->tag])) {
// return $person_facts[$xref][$this->tag] >= $access_level;
// }
// if (isset($global_facts[$this->tag])) {
// return $global_facts[$this->tag] >= $access_level;
// }
// No restrictions - it must be public
return true;
}
// Check whether this fact is protected against edit
public function canEdit() {
// Managers can edit anything
// Members cannot edit RESN, CHAN and locked records
return
$this->parent->canEdit() && !$this->isOld() && (
WT_USER_GEDCOM_ADMIN ||
WT_USER_CAN_EDIT && strpos($this->gedcom, "\n2 RESN locked")===false && $this->getTag()!='RESN' && $this->getTag()!='CHAN'
);
}
// The place where the event occured.
public function getPlace() {
if ($this->place === null) {
$this->place = new WT_Place($this->getAttribute('PLAC'), $this->getParent()->getGedcomId());
}
return $this->place;
}
// The latitude where the event occured.
public function getLati() {
if ($this->lati === null) {
$this->lati = new WT_Place($this->getAttribute('LATI'), $this->getParent()->getGedcomId());
}
return $this->lati;
}
// The longitude where the event occured.
public function getLong() {
if ($this->long === null) {
$this->long = new WT_Place($this->getAttribute('LONG'), $this->getParent()->getGedcomId());
}
return $this->long;
}
// We can call this function many times, especially when sorting,
// so keep a copy of the date.
public function getDate() {
if ($this->date === null) {
$this->date = new WT_Date($this->getAttribute('DATE'));
}
return $this->date;
}
// The raw GEDCOM data for this fact
public function getGedcom() {
return $this->gedcom;
}
// Unique identifier for the fact
public function getFactId() {
return $this->fact_id;
}
// What sort of fact is this?
public function getTag() {
return $this->tag;
}
// Used to convert a real fact (e.g. BIRT) into a close-relative’s fact (e.g. _BIRT_CHIL)
public function setTag($tag) {
$this->tag = $tag;
}
// The Person/Family record where this WT_Fact came from
public function getParent() {
return $this->parent;
}
public function getLabel() {
switch($this->tag) {
case 'EVEN':
case 'FACT':
if ($this->getAttribute('TYPE')) {
// Custom FACT/EVEN - with a TYPE
return WT_I18N::translate(WT_Filter::escapeHtml($this->getAttribute('TYPE')));
}
// no break - drop into next case
default:
return WT_Gedcom_Tag::getLabel($this->tag, $this->parent);
}
}
// Is this a pending edit?
public function setIsOld() {
$this->is_old = true;
$this->is_new = false;
}
public function isOld() {
return $this->is_old;
}
public function setIsNew() {
$this->is_new = true;
$this->is_old = false;
}
public function isNew() {
return $this->is_new;
}
// Source citations linked to this fact
public function getCitations() {
preg_match_all('/\n(2 SOUR @(' . WT_REGEX_XREF . ')@(?:\n[3-9] .*)*)/', $this->getGedcom(), $matches, PREG_SET_ORDER);
$citations = array();
foreach ($matches as $match) {
$source = WT_Source::getInstance($match[2], $this->getParent()->getGedcomId());
if ($source->canShow()) {
$citations[] = $match[1];
}
}
return $citations;
}
// Notes (inline and objects) linked to this fact
public function getNotes() {
$notes = array();
preg_match_all('/\n2 NOTE ?(.*(?:\n3.*)*)/', $this->getGedcom(), $matches);
foreach ($matches[1] as $match) {
$note = preg_replace("/\n3 CONT ?/", "\n", $match);
if (preg_match('/@(' . WT_REGEX_XREF . ')@/', $note, $nmatch)) {
$note = WT_Note::getInstance($nmatch[1], $this->getParent()->getGedcomId());
if ($note && $note->canShow()) {
// A note object
$notes[] = $note;
}
} else {
// An inline note
$notes[] = $note;
}
}
return $notes;
}
// Media objects linked to this fact
public function getMedia() {
$media = array();
preg_match_all('/\n2 OBJE @(' . WT_REGEX_XREF . ')@/', $this->getGedcom(), $matches);
foreach ($matches[1] as $match) {
$obje = WT_Media::getInstance($match, $this->getParent()->getGedcomId());
if ($obje->canShow()) {
$media[] = $obje;
}
}
return $media;
}
// A one-line summary of the fact - for charts, etc.
public function summary() {
global $SHOW_PARENTS_AGE;
$attributes = array();
$target = $this->getTarget();
if ($target) {
$attributes[] = $target->getFullName();
} else {
$value = $this->getValue();
if ($value && $value!='Y') {
$attributes[] = '<span dir="auto">' . WT_Filter::escapeHtml($value) . '</span>';
}
$date = $this->getDate();
if ($this->getTag() == 'BIRT' && $SHOW_PARENTS_AGE && $this->getParent() instanceof WT_Individual) {
$attributes[] = $date->display() . format_parents_age($this->getParent(), $date);
} else {
$attributes[] = $date->display();
}
$place = $this->getPlace()->getShortName();
if ($place) {
$attributes[] = $place;
}
}
$html = WT_Gedcom_Tag::getLabelValue($this->getTag(), implode(' — ', $attributes), $this->getParent());
if ($this->isNew()) {
return '<div class="new">' . $html . '</div>';
} elseif ($this->isOld()) {
return '<div class="old">' . $html . '</div>';
} else {
return $html;
}
}
// Display an icon for this fact.
// Icons are held in a theme subfolder. Not all themes provide icons.
public function Icon() {
$icon = 'images/facts/' . $this->getTag() . '.png';
$dir = substr(WT_CSS_URL, strlen(WT_STATIC_URL));
if (file_exists($dir . $icon)) {
return '<img src="' . WT_CSS_URL . $icon . '" title="' . WT_Gedcom_Tag::getLabel($this->getTag()) . '">';
} elseif (file_exists($dir . 'images/facts/NULL.png')) {
// Spacer image - for alignment - until we move to a sprite.
return '<img src="' . WT_CSS_URL . 'images/facts/NULL.png">';
} else {
return '';
}
}
/**
* Static Helper functions to sort events
*
* @param WT_Fact $a Fact one
* @param WT_Fact $b Fact two
*
* @return integer
*/
public static function CompareDate(WT_Fact $a, WT_Fact $b)
{
if ($a->getDate()->isOK() && $b->getDate()->isOK()) {
// If both events have dates, compare by date
$ret = WT_Date::Compare($a->getDate(), $b->getDate());
if ($ret == 0) {
// If dates are the same, compare by fact type
$ret = self::CompareType($a, $b);
// If the fact type is also the same, retain the initial order
if ($ret == 0) {
$ret = $a->sortOrder - $b->sortOrder;
}
}
return $ret;
} else {
// One or both events have no date - retain the initial order
return $a->sortOrder - $b->sortOrder;
}
}
/**
* Static method to compare two events by their type.
*
* @param WT_Fact $a Fact one
* @param WT_Fact $b Fact two
*
* @return integer
*/
public static function CompareType(WT_Fact $a, WT_Fact $b) {
global $factsort;
if (empty($factsort)) {
$factsort = array_flip(
array(
'BIRT',
'_HNM',
'ALIA', '_AKA', '_AKAN',
'ADOP', '_ADPF', '_ADPF',
'_BRTM',
'CHR', 'BAPM',
'FCOM',
'CONF',
'BARM', 'BASM',
'EDUC',
'GRAD',
'_DEG',
'EMIG', 'IMMI',
'NATU',
'_MILI', '_MILT',
'ENGA',
'MARB', 'MARC', 'MARL', '_MARI', '_MBON',
'MARR', 'MARR_CIVIL', 'MARR_RELIGIOUS', 'MARR_PARTNERS', 'MARR_UNKNOWN', '_COML',
'_STAT',
'_SEPR',
'DIVF',
'MARS',
'_BIRT_CHIL',
'DIV', 'ANUL',
'_BIRT_', '_MARR_', '_DEAT_','_BURI_', // other events of close relatives
'CENS',
'OCCU',
'RESI',
'PROP',
'CHRA',
'RETI',
'FACT', 'EVEN',
'_NMR', '_NMAR', 'NMR',
'NCHI',
'WILL',
'_HOL',
'_????_',
'DEAT',
'_FNRL', 'CREM', 'BURI', '_INTE',
'_YART',
'_NLIV',
'PROB',
'TITL',
'COMM',
'NATI',
'CITN',
'CAST',
'RELI',
'SSN', 'IDNO',
'TEMP',
'SLGC', 'BAPL', 'CONL', 'ENDL', 'SLGS',
'ADDR', 'PHON', 'EMAIL', '_EMAIL', 'EMAL', 'FAX', 'WWW', 'URL', '_URL',
'FILE', // For media objects
'AFN', 'REFN', '_PRMN', 'REF', 'RIN', '_UID',
'OBJE', 'NOTE', 'SOUR',
'CHAN', '_TODO',
)
);
}
// Facts from same families stay grouped together
// Keep MARR and DIV from the same families from mixing with events from other FAMs
// Use the original order in which the facts were added
if (($a->parent instanceof WT_Family)
&& ($b->parent instanceof WT_Family)
&& ($a->parent !== $b->parent)
) {
return $a->sortOrder - $b->sortOrder;
}
$atag = $a->getTag();
$btag = $b->getTag();
// Events not in the above list get mapped onto one that is.
if (!array_key_exists($atag, $factsort)) {
if (preg_match('/^(_(BIRT|MARR|DEAT|BURI)_)/', $atag, $match)) {
$atag = $match[1];
} else {
$atag = "_????_";
}
}
if (!array_key_exists($btag, $factsort)) {
if (preg_match('/^(_(BIRT|MARR|DEAT|BURI)_)/', $btag, $match)) {
$btag = $match[1];
} else {
$btag = "_????_";
}
}
// - Don't let dated after DEAT/BURI facts sort non-dated facts before DEAT/BURI
// - Treat dated after BURI facts as BURI instead
if (($a->getAttribute('DATE') != null)
&& ($factsort[$atag] > $factsort['BURI'])
&& ($factsort[$atag] < $factsort['CHAN'])
) {
$atag = 'BURI';
}
if (($b->getAttribute('DATE') != null)
&& ($factsort[$btag] > $factsort['BURI'])
&& ($factsort[$btag] < $factsort['CHAN'])
) {
$btag = 'BURI';
}
$ret = $factsort[$atag] - $factsort[$btag];
// If facts are the same then put dated facts before non-dated facts
if ($ret == 0) {
if (($a->getAttribute('DATE') != null)
&& ($b->getAttribute('DATE') == null)
) {
return -1;
}
if (($b->getAttribute('DATE') != null)
&& ($a->getAttribute('DATE')==null)
) {
return 1;
}
// If no sorting preference, then keep original ordering
$ret = $a->sortOrder - $b->sortOrder;
}
return $ret;
}
// Allow native PHP functions such as array_unique() to work with objects
public function __toString() {
return $this->fact_id . '@' . $this->parent->getXref();
}
}
|
cgeltly/treechecker
|
app/models/webtrees/Fact.php
|
PHP
|
gpl-3.0
| 14,911
|
import Palabra from '../../models/palabras'
import { GROUP_ID } from '../../config'
/**
* Obtiene el ranking de palabras más usadas.
* @param {*} msg
*/
const ranking = async msg => {
if(msg.chat.id !== GROUP_ID) return;
try {
let palabras = await Palabra.find({}).sort('-amount').exec();
if (palabras.length >= 3) {
await msg.reply.text(
`${palabras[0].palabra} (${palabras[0].amount} veces), ` +
`${palabras[1].palabra} (${palabras[1].amount} veces), ` +
`${palabras[2].palabra} (${palabras[2].amount} veces)`
);
} else if (palabras.length === 2) {
await msg.reply.text(
`${palabras[0].palabra} (${palabras[0].amount} veces), ` +
`${palabras[1].palabra} (${palabras[1].amount} veces)`
);
} else if (palabras.length === 1) {
await msg.reply.text(
`${palabras[0].palabra} (${palabras[0].amount} veces)`
);
} else {
await msg.reply.text('Hablen más por favor');
}
return 0;
} catch (err) {
console.error(err.message || err);
return;
}
};
export default bot => bot.on(['/ranking'], ranking)
|
jesusgn90/etsiit-moderator
|
lib/lib/estadisticas/estadisticas.js
|
JavaScript
|
gpl-3.0
| 1,257
|
package de.randi2.core.unit.model.randomization;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import de.randi2.model.TreatmentArm;
import de.randi2.model.Trial;
import de.randi2.model.randomization.UrnDesignConfig;
import de.randi2.randomization.RandomizationAlgorithm;
import de.randi2.testUtility.utility.AbstractDomainTest;
public class UrnDesignConfigTest extends AbstractDomainTest<UrnDesignConfig> {
UrnDesignConfig conf;
public UrnDesignConfigTest(){
super(UrnDesignConfig.class);
}
@Test
public void testTrial_null(){
conf = new UrnDesignConfig();
conf.setTrial(null);
assertNull(conf.getTrial());
}
@Test
public void testTrial_withEmptyRandomizationConfig(){
conf = new UrnDesignConfig();
Trial trial = new Trial();
assertNull(trial.getRandomizationConfiguration());
conf.setTrial(trial);
assertEquals(trial, conf.getTrial());
assertEquals(conf, trial.getRandomizationConfiguration());
}
@Test
public void testTrial_withRandomizationConfig(){
conf = new UrnDesignConfig();
Trial trial = new Trial();
trial.setRandomizationConfiguration(new UrnDesignConfig());
assertNotNull(trial.getRandomizationConfiguration());
conf.setTrial(trial);
assertEquals(trial, conf.getTrial());
assertFalse(conf.equals(trial.getRandomizationConfiguration()));
}
@Test
public void testGetAlgortihm_withSeed(){
conf = new UrnDesignConfig(1234);
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertNotNull(algorithm);
assertEquals(1234, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
}
@Test
public void testGetAlgortihm_withoutSeed(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertNotNull(algorithm);
assertEquals(Long.MIN_VALUE, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgorithm_withSeed(){
conf = new UrnDesignConfig(1234);
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(1234, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithm();
assertEquals(1234, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgortihm_withoutSeed(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(Long.MIN_VALUE, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithm();
assertEquals(Long.MIN_VALUE, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgorithmWithNextSeed(){
conf = new UrnDesignConfig(1234);
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(1234, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithmWithNextSeed();
assertEquals(1234+10000, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgorithmWithNextSeed_withoutSeed(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(Long.MIN_VALUE, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithmWithNextSeed();
assertEquals(Long.MIN_VALUE, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgorithmNewSeed(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(Long.MIN_VALUE, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithm(123);
assertEquals(123, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testCountReplacedBalls(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
conf.setCountReplacedBalls(10);
assertEquals(10, conf.getCountReplacedBalls());
}
@Test
public void testInitializeCountBalls(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
conf.setInitializeCountBalls(10);
assertEquals(10, conf.getInitializeCountBalls());
}
@Test
public void testTempData(){
conf = new UrnDesignConfig();
conf.setTempData(null);
assertNotNull(conf.getTempData());
}
@Test
public void testTrialHasOnlyTwoArms(){
conf = new UrnDesignConfig();
Trial trial = new Trial();
Set<TreatmentArm> arms = new HashSet<TreatmentArm>();
TreatmentArm arm1 = new TreatmentArm();
arm1.setName("arm1");
arms.add(arm1);
trial.setTreatmentArms(arms);
conf.setTrial(trial);
assertInvalid(conf);
TreatmentArm arm2 = new TreatmentArm();
arm2.setName("arm2");
arms.add(arm2);
trial.setTreatmentArms(arms);
conf.setTrial(trial);
assertValid(conf);
}
}
|
randi2/randi2
|
src/test/java/de/randi2/core/unit/model/randomization/UrnDesignConfigTest.java
|
Java
|
gpl-3.0
| 5,309
|
# amino-acid-backend
Java backend for the amino-acid viewer application.
|
rmbernardi/amino-acid-backend
|
README.md
|
Markdown
|
gpl-3.0
| 73
|
# from mainsite.models import Web_Region
context = {'title': 'my static title',
'description': 'my static description',
'data': 'my static data',
}
def get_context(request):
# region_list = Web_Region.objects.values_list('region_name', flat=True)
context.update({'data': 'my dynamic data'})
return context
|
sstacha/uweb-vagrant
|
files/docroot/files/test.data.py
|
Python
|
gpl-3.0
| 364
|
var Octopi = function(words) {
this.uid = 0;
this.tree = {$$: []};
this.table = {};
words = (words || []);
for (var i = 0; i < words.length; i++)
this.add(words[i]);
};
/**
* Take serialized Octopi data as string and initialize the Octopi object
* @param json String The serialized Octopi trie
*/
Octopi.load = function(json){
var oct = new Octopi();
var o = JSON.parse(json);
oct.uid = o.uid;
oct.tree = o.tree;
oct.table = o.table;
return oct;
}
Octopi.prototype = {
constructor: Octopi,
/**
* Add a new element to the trie
* @param key String prefix to look up
* @param data Object returned by trie
*/
add: function(key, data) {
var id = ++this.uid;
var sub = this.tree;
this.table[id] = data || key;
sub.$$.push(id);
for (var i = 0; i < key.length; i++) {
var c = key[i];
sub = sub[c] || (sub[c] = {$$:[]});
sub.$$.push(id);
}
},
/**
* Return the list of elements in the trie for a given query
* @param key String The prefix to lookup
*/
get: function(key) {
var sub = this.tree;
var tbl = this.table;
for (var i = 0; i < key.length; i++)
if (!(sub = sub[key[i]]))
return [];
return sub.$$.map(function(id) {
return tbl[id];
});
},
/**
* Serialize the Octopi trie as string
*
* @return String
*/
serialize: function(){
var o = { uid: this.uid,
tree: this.tree,
table: this.table
}
return JSON.stringify(o);
}
};
//Search core code
var trie_data = AUTOCOMPLETE_PLUGIN_REPLACE;
var Autocomplete = function() {
this.oct = new Octopi();
};
Autocomplete.prototype = {
load_data: function(data) {
for (var i = 0; data[i]; i++) {
var info = {
'w': data[i][0],
'd': data[i][1],
's': data[i][2]
}
this.oct.add(data[i][0], info)
}
},
get: function(str) {
// Fixme: cleanup malicious input
var candidates = this.oct.get(str);
return candidates.sort(function(a,b){
return (a.s < b.s) ? 1: -1;
}
);
}
};
// Export needed functions/data to the global context
window.Autocomplete = Autocomplete;
window.trie_data = trie_data;
|
ebursztein/SiteFab
|
plugins/site/rendering/autocomplete/autocomplete.js
|
JavaScript
|
gpl-3.0
| 2,263
|
<?php
namespace at\eisisoft\partywithme\api;
/**
* Created by PhpStorm.
* User: Florian
* Date: 05.03.2016
* Time: 09:11
*/
use at\eisisoft\partywithme as pwm;
use function at\eisisoft\partywithme\api\fetchEvents;
use function at\eisisoft\partywithme\api\toJSON;
require_once "../hidden/partials/jsonHeader.php";
$fbLogin = isFbLogin();
$sql = file_get_contents(resolveFileRelativeToHidden("resources/sql/api/allevents.sql"));
if (fetchEvents($fbLogin)) {
try {
$connection = pwm\MySQLHelper::getConnection();
$pstmt = $connection->prepare($sql);
$pstmt->bindValue(":userId", $fbLogin[FB_USER_ID_KEY], \PDO::PARAM_STR);
toJSON($pstmt);;
} catch (\PDOException $e) {
echo "[]";
}
}
?>
|
reisi007/Party-With-Me
|
api/listEvents.php
|
PHP
|
gpl-3.0
| 743
|
/*
* Copyright 2016 Marcelo Garlet Millani
This file is part of itsalamp.
itsalamp 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.
itsalamp 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 itsalamp. If not, see <http://www.gnu.org/licenses/>.
*/
#include <gtk/gtk.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <glib.h>
#include "image.h"
void colorMultiply(GdkPixbuf *source, GdkPixbuf *target, guchar color[])
{
int width, height, rowstride, channels;
guchar *tPixels, *sPixels;
channels = gdk_pixbuf_get_n_channels (target);
g_assert (gdk_pixbuf_get_colorspace (target) == GDK_COLORSPACE_RGB);
g_assert (gdk_pixbuf_get_bits_per_sample (target) == 8);
g_assert (channels == 4 || channels == 3);
width = gdk_pixbuf_get_width (target);
height = gdk_pixbuf_get_height (target);
rowstride = gdk_pixbuf_get_rowstride (target);
tPixels = gdk_pixbuf_get_pixels (target);
sPixels = gdk_pixbuf_get_pixels (source);
int x,y;
for(y=0 ; y < height * rowstride ; y+=rowstride)
{
for(x=0 ; x < width * channels ; x += channels)
{
int c;
for(c = 0 ; c < 3 ; c++)
{
tPixels[c + x + y] = (sPixels[c + x + y] * color[c])/255;
}
}
}
}
void colorSet(GdkPixbuf *target, guchar color[])
{
int width, height, rowstride, channels;
guchar *tPixels;
channels = gdk_pixbuf_get_n_channels (target);
g_assert (gdk_pixbuf_get_colorspace (target) == GDK_COLORSPACE_RGB);
g_assert (gdk_pixbuf_get_bits_per_sample (target) == 8);
g_assert (channels == 4 || channels == 3);
width = gdk_pixbuf_get_width (target);
height = gdk_pixbuf_get_height (target);
rowstride = gdk_pixbuf_get_rowstride (target);
tPixels = gdk_pixbuf_get_pixels (target);
int x,y;
for(y=0 ; y < height * rowstride ; y+=rowstride)
{
for(x=0 ; x < width * channels ; x += channels)
{
int c;
for(c = 0 ; c < channels ; c++)
{
tPixels[c + x + y] = color[c];
}
}
}
}
|
mgmillani/itsalamp
|
src/image.c
|
C
|
gpl-3.0
| 2,336
|
/* Copyright 2015, 2016 Parity Technologies (UK) Ltd.
/* This file is part of Parity.
/*
/* Parity 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.
/*
/* Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
*/
.signerIcon {
width: 24px;
height: 24px;
margin-bottom: 5px;
}
.view {
}
.view+.view {
padding-top: 1.5em;
}
.header {
}
.labelicon {
display: inline-block;
margin-right: 0.75em;
}
.label {
display: inline-block;
vertical-align: top;
line-height: 24px;
color: white !important;
}
.info {
color: #aaa;
padding-left: 4.75em;
}
|
jesuscript/parity
|
js/src/views/Settings/Views/views.css
|
CSS
|
gpl-3.0
| 1,076
|
/********************************************************************
Copyright (c) 2013-2015 - Mogara
This file is part of Cardirector.
This game engine 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.0
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 LICENSE file for more details.
Mogara
*********************************************************************/
#ifndef CSERVER_H
#define CSERVER_H
#include "cglobal.h"
#include <QObject>
#include <QHostAddress>
class CAbstractPacketParser;
class CAbstractUser;
class CRoom;
class CServerAgent;
class CServerRobot;
class CServerUser;
class CTcpServer;
class CTcpSocket;
class CServerPrivate;
class MCD_EXPORT CServer : public QObject
{
Q_OBJECT
public:
CServer(QObject *parent = 0);
~CServer();
bool listen(const QHostAddress &address = QHostAddress::Any, ushort port = 0);
QHostAddress address() const;
ushort port() const;
void setAcceptMultipleClientsBehindOneIp(bool enabled);
bool acceptMultipleClientsBehindOneIp() const;
void createRobot(CRoom *room);
void killRobot(uint id);
CServerUser *findUser(uint id) const;
QHash<uint, CServerUser *> users() const;
CServerRobot *findRobot(uint id) const;
QHash<uint, CServerRobot *> robots() const;
QList<CServerAgent *> agents() const;
void createRoom(CServerUser *owner, const QString &name, uint capacity);
CRoom *findRoom(uint id) const;
QHash<uint, CRoom *> rooms() const;
CRoom *lobby() const;
void updateRoomList(CServerUser *user);
void setPacketParser(CAbstractPacketParser *parser);
CAbstractPacketParser *packetParser() const;
void broadcastNotification(int command, const QVariant &data = QVariant(), CServerUser *except = NULL);
signals:
void roomCreated(CRoom *room);
void userAdded(CServerUser *user);
void robotAdded(CServerRobot *robot);
protected:
void handleNewConnection(CTcpSocket *client);
void onRoomAbandoned();
void onUserDisconnected();
void onUserStateChanged();
private:
C_DISABLE_COPY(CServer)
C_DECLARE_PRIVATE(CServer)
CServerPrivate *p_ptr;
};
#endif
|
LGCaerwyn/Cardirector
|
src/server/cserver.h
|
C
|
gpl-3.0
| 2,503
|
(function() {
var billerModule = angular.module('billerModule');
billerModule.filter('offset', function() {
return function(input, start) {
start = parseInt(start, 10);
return input != null ? input.slice(start) : [];
};
});
billerModule.directive('billRecalculationInfo', function() {
return {
restrict : 'AE',
templateUrl : 'html/bills/bill-recalculation-info.html',
controller : ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http) {
$scope.init = function() {
$scope.itemsPerPage = 10;
$scope.pageCurrentBills = 0;
$scope.pageNonExistingBills = 0;
};
$scope.setCurrentBillsPage = function(value) {
$scope.pageCurrentBills = value;
};
$scope.setNonExistingBillsPage = function(value) {
$scope.pageNonExistingBills = value;
};
$scope.init();
}],
require : '^ngModel',
replace : 'true',
scope : {
entity : '=ngModel'
}
};
});
billerModule.controller('BillRecalculationCtrl', [ '$scope', '$rootScope', '$routeParams', '$http', 'dialogs', function($scope, $rootScope, $routeParams, $http, dialogs) {
$scope.init = function() {
$scope.modes = [
{ id: 'byStore', label:'Por establecimiento' },
{ id: 'byCompany', label:'Por operador' },
{ id: 'allBills', label:'Todos' }
];
$scope.months = [
{ id: '1', label: "Enero"}, { id: '2', label: "Febrero"}, { id: '3', label: "Marzo"}, { id: '4', label: "Abril"},
{ id: '5', label: "Mayo"}, { id: '6', label: "Junio"}, { id: '7', label: "Julio"}, { id: '8', label: "Agosto"},
{ id: '9', label: "Septiembre"}, { id: '10', label: "Octubre"}, { id: '11', label: "Noviembre"}, { id: '12', label: "Diciembre"},
];
$scope.options = { mode: $scope.modes[0]};
};
$scope.prepareBill = function() {
$http.get('rest/recalculation/prepare/bill', {
params: {
y: $scope.options.year,
m: $scope.options.month != null ? $scope.options.month.id : null,
s: $scope.options.store != null && $scope.options.mode.id == 'byStore' ? $scope.options.store.id : null,
c: $scope.options.company != null && $scope.options.mode.id == 'byCompany' ? $scope.options.company.id : null
}
}).success(function(data) {
$scope.message = data;
$scope.prepareResult = data.payload;
});
};
$scope.cancelBillRecalculation = function() {
$scope.prepareResult = null;
};
$scope.executeBillRecalculation = function() {
var dlg = dialogs.confirm('Confirmacion','Desea recalcular la factura? Los ajustes manuales se perderan');
dlg.result.then(function(btn){
$scope.message = {code: 200, info: ['billRecalculation.inProgress']};
$scope.isLoading = true;
$scope.prepareResult.recalculateLiquidation = $scope.recalculateLiquidation;
$http.post('rest/recalculation/execute/bill', $scope.prepareResult
).success(function(data) {
$scope.message = data;
$scope.results = data.payload;
$scope.isLoading = false;
});
});
};
$scope.init();
}]);
})();
|
labcabrera/biller
|
biller-web/src/main/webapp/js/controllers/bill-recalculation-ctrl.js
|
JavaScript
|
gpl-3.0
| 3,019
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.12.22 at 06:47:20 AM EET
//
package bias.extension.DashBoard.xmlb;
import jakarta.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the bias.extension.DashBoard.xmlb package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: bias.extension.DashBoard.xmlb
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Frames }
*
*/
public Frames createFrames() {
return new Frames();
}
/**
* Create an instance of {@link Frame }
*
*/
public Frame createFrame() {
return new Frame();
}
}
|
kion/Bias
|
src/bias/extension/DashBoard/xmlb/ObjectFactory.java
|
Java
|
gpl-3.0
| 1,528
|
/*
* FinTP - Financial Transactions Processing Application
* Copyright (C) 2013 Business Information Systems (Allevo) S.R.L.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* or contact Allevo at : 031281 Bucuresti, 23C Calea Vitan, Romania,
* phone +40212554577, office@allevo.ro <mailto:office@allevo.ro>, www.allevo.ro.
*/
#ifndef LOGMANAGER_H
#define LOGMANAGER_H
#include <exception>
#include <string>
#include <iostream>
#include <vector>
#include "pthread.h"
#include <xercesc/dom/DOM.hpp>
//#include "AppSettings.h"
#include "Collections.h"
#include "WorkItemPool.h"
#include "AbstractLogPublisher.h"
#include "AppExceptions.h"
using namespace std;
XERCES_CPP_NAMESPACE_USE
namespace FinTP
{
//EXPIMP_TEMPLATE template class ExportedLogObject std::vector< AbstractLogPublisher* >;
class ExportedLogObject LogManager
{
public :
typedef WorkItemPool< AppException > EventsPool;
~LogManager();// Terminate XML4C2 and delete m_AppException
// methods
static void Publish( const AppException& except );
static void Publish( const string& message, const EventType::EventTypeEnum eventType = EventType::Error );
static void Publish( const char* message, const EventType::EventTypeEnum eventType = EventType::Error );
static void Publish( const std::exception& innerException, const EventType::EventTypeEnum eventType = EventType::Error, const string& message="" );
// initialize m_PropSettings
static void Initialize( const NameValueCollection& applicationSettings, bool threaded = false );
static bool isInitialized();
static void setCorrelationId( const string& value );
static void setSessionId( const string& value );
static void Terminate();
static pthread_t getPublisherThreadId();
static void Register( AbstractLogPublisher* logPublisher, bool isDefault );
private :
static void CreateKeys();
static void DeleteCorrelIds( void* data );
LogManager();// Initialize the XML4C2 system
bool m_Initialized;
bool m_Threaded;
// the one and only instance
static LogManager Instance;
static pthread_once_t KeysCreate;
static pthread_key_t CorrelationKey;
static pthread_mutex_t InstanceMutex;
pthread_t m_PublishThreadId;
void setThreaded( const bool threaded );
static void* PublisherThread( void *param );
string m_SessionId;
// default publisher and all other publishers
AbstractLogPublisher* m_DefaultPublisher;
vector< AbstractLogPublisher* > m_Publishers;
void setDefaultPublisher( AbstractLogPublisher* defaultPublisher );
void ClearPublishers();
// either inserts the event to the pool or publishers the event ( regarding m_Threaded attribute )
void InternalPublish( const AppException& except ) throw();
void InternalPublishProc( const AppException& except );
static EventsPool m_EventsPool;
};
}
#endif // LOGMANAGER_H
|
FinTP/fintp_log
|
src/LogManager.h
|
C
|
gpl-3.0
| 3,482
|
<?php
/**
* TrcIMPLAN Sitio Web - Retrospectiva y estado actual del empleo en Torreón y la Zona Metropolitana de La Laguna
*
* Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package TrcIMPLANSitioWeb
*/
namespace Blog;
/**
* Clase RestrospectivaEstadoActualEmpleo
*/
class RestrospectivaEstadoActualEmpleo extends \Base\PublicacionSchemaBlogPosting {
/**
* Constructor
*/
public function __construct() {
// Ejecutar constructor en el padre
parent::__construct();
// Título, autor y fecha
$this->nombre = 'Retrospectiva y estado actual del empleo en Torreón y la ZML';
$this->autor = 'Lic. Rodrigo González Morales';
$this->fecha = '2014-09-26T08:05';
// El nombre del archivo a crear
$this->archivo = 'retrospectiva-estado-actual-empleo';
// La descripción y claves dan información a los buscadores y redes sociales
$this->descripcion = 'El empleo es uno de los principales indicadores, que muestra el desempeño económico de una ciudad, región o país. Desde hace 9 años Torreón y la Zona Metropolitana de la Laguna se habían separado a la alza de la media nacional.';
$this->claves = 'IMPLAN, Torreon, Empleo';
// Ruta al archivo HTML con el contenido
$this->contenido_archivo_html = 'lib/Blog/RestrospectivaEstadoActualEmpleo.html';
// Para el Organizador
$this->categorias = array('Empleo');
$this->fuentes = array();
$this->regiones = array();
} // constructor
} // Clase RestrospectivaEstadoActualEmpleo
?>
|
TRCIMPLAN/trcimplan.github.io
|
lib/Blog/RestrospectivaEstadoActualEmpleo.php
|
PHP
|
gpl-3.0
| 2,450
|
package org.betonquest.betonquest.conditions;
import org.betonquest.betonquest.Instruction;
import org.betonquest.betonquest.api.Condition;
import org.betonquest.betonquest.exceptions.InstructionParseException;
import org.betonquest.betonquest.utils.PlayerConverter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import java.util.Locale;
@SuppressWarnings("PMD.CommentRequired")
public class RideCondition extends Condition {
private EntityType vehicle;
private boolean any;
public RideCondition(final Instruction instruction) throws InstructionParseException {
super(instruction, true);
final String name = instruction.next();
if ("any".equalsIgnoreCase(name)) {
any = true;
} else {
try {
vehicle = EntityType.valueOf(name.toUpperCase(Locale.ROOT));
} catch (final IllegalArgumentException e) {
throw new InstructionParseException("Entity type " + name + " does not exist.", e);
}
}
}
@Override
protected Boolean execute(final String playerID) {
final Entity entity = PlayerConverter.getPlayer(playerID).getVehicle();
return entity != null && (any || entity.getType() == vehicle);
}
}
|
Co0sh/BetonQuest
|
src/main/java/org/betonquest/betonquest/conditions/RideCondition.java
|
Java
|
gpl-3.0
| 1,282
|
//
// StateUtils.cs
//
// Author:
// Willem Van Onsem <vanonsem.willem@gmail.com>
//
// Copyright (c) 2014 Willem Van Onsem
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using NUtils.Collections;
namespace NUtils.Automata {
/// <summary>
/// Utility functions for <see cref="T:IState`2"/> instances.
/// </summary>
public static class StateUtils {
#region Blankets
/// <summary>
/// Calculate the blanket of the given <see cref="T:IState`2"/> for the given <paramref name="blankettag"/>.
/// </summary>
/// <returns>The blanket.</returns>
/// <param name="state">Current.</param>
/// <param name="blankettag">Blankettag.</param>
/// <typeparam name="TStateTag">The 1st type parameter.</typeparam>
/// <typeparam name="TEdgeTag">The 2nd type parameter.</typeparam>
/// <remarks>
/// <para>A blanket is the set of states that can be reached by applying zero, one or more times the given tag onto the given state.</para>
/// <para>Each state is included in its own blanket.</para>
/// <para>The algorithm avoids loops by storing the already visited states.</para>
/// <para>The order of the blanken is unique depth-first.</para>
/// </remarks>
public static IEnumerable<IState<TStateTag,TEdgeTag>> GetBlanket<TStateTag,TEdgeTag> (this IState<TStateTag,TEdgeTag> state, TEdgeTag blankettag) {
yield return state;
IState<TStateTag,TEdgeTag> current;
Queue<IState<TStateTag,TEdgeTag>> todo = new Queue<IState<TStateTag, TEdgeTag>> ();
HashSet<IState<TStateTag,TEdgeTag>> seen = new HashSet<IState<TStateTag, TEdgeTag>> ();
seen.Add (state);
todo.Enqueue (state);
while (todo.Count > 0x00) {
current = todo.Dequeue ();
foreach (IState<TStateTag,TEdgeTag> target in current.TaggedEdges(blankettag).SelectMany ((x => x.ResultingStates))) {
if (seen.Add (target)) {
yield return target;
todo.Enqueue (target);
}
}
}
}
#endregion
}
}
|
KommuSoft/NUtils
|
NUtils/Automata/StateUtils.cs
|
C#
|
gpl-3.0
| 2,615
|
#!/usr/bin/python
"""
DES-CHAN: A Framework for Channel Assignment Algorithms for Testbeds
This module provides a class to represent network graphs and conflict graphs.
Authors: Matthias Philipp <mphilipp@inf.fu-berlin.de>,
Felix Juraschek <fjuraschek@gmail.com>
Copyright 2008-2013, Freie Universitaet Berlin (FUB). All rights reserved.
These sources were developed at the Freie Universitaet Berlin,
Computer Systems and Telematics / Distributed, embedded Systems (DES) group
(http://cst.mi.fu-berlin.de, http://www.des-testbed.net)
-------------------------------------------------------------------------------
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/ .
--------------------------------------------------------------------------------
For further information and questions please use the web site
http://www.des-testbed.net
"""
import re
import sys
class Graph:
def __init__(self, vertices=[]):
# initialize internal data structures
self.values = dict()
self.distances = dict()
# set vertex names and distances
for vertex in vertices:
self.add_vertex(vertex)
def add_vertex(self, new_vertex):
"""Adds the given vertex to the graph.
"""
# do nothing if vertex already exists
if new_vertex in self.get_vertices():
return
# otherwise set up data structures for new vertex
self.values[new_vertex] = dict()
self.distances[new_vertex] = dict()
for old_vertex in self.get_vertices():
self.set_edge_value((old_vertex, new_vertex), None, False)
self.set_distance(old_vertex, new_vertex, sys.maxint)
# distance to itself is 0
self.set_distance(new_vertex, new_vertex, 0)
def remove_vertex(self, vertex):
"""Removes the given vertex from the graph.
"""
del self.values[vertex]
del self.distances[vertex]
for v in self.get_vertices():
del self.values[v][vertex]
del self.distances[v][vertex]
def get_vertices(self):
"""Returns a list that contains all vertices of the graph.
"""
return set(self.values.keys())
def set_edge_value(self, edge, value, update=True):
"""Sets the value of the given edge. The edge is represented by a tuple
of two vertices.
"""
v1, v2 = edge
self.values[v1][v2] = value
# we implement an undirected graph
self.values[v2][v1] = value
# update distance information
# None, "", False, and 0 correspond to no edge
if value:
self.set_distance(v1, v2, 1)
# other shortest paths may have changed
if update:
self.update_distances()
def set_distance(self, v1, v2, d):
"""Sets the distance between the two vertices.
"""
self.distances[v1][v2] = d
# we implement an undirected graph
self.distances[v2][v1] = d
def get_edge_value(self, edge):
"""Returns the value of the given edge. The edge is represented by a tuple
of two vertices.
"""
v1, v2 = edge
return self.values[v1][v2]
def get_distance(self, v1, v2):
"""Returns the distance between v1 and v2.
"""
return self.distances[v1][v2]
def get_edges(self, get_all=False):
"""Returns a dictionary that contains all edges as keys and the
corresponding edge values as values. Only edges that have a value are
returned. By default the graph is assumed to be undirected. If the
optional parameter get_all is True, all vertices are returned.
"""
edges = dict()
remaining_vertices = self.get_vertices()
for v1 in self.get_vertices():
for v2 in remaining_vertices:
value = self.get_edge_value((v1, v2))
# None, "", False, and 0 correspond to no edge
if value:
edges[(v1, v2)] = value
# graph is assumed to be undirected, therefore discard
# duplicate edges if not explicitly requested
if not get_all:
remaining_vertices.remove(v1)
return edges
def merge(self, graph):
"""Merges the current graph with the specified graph. The new graph
contains the union of both vertex sets and the corresponding edge
values.
"""
# add missing vertices
for vertex in graph.get_vertices() - self.get_vertices():
self.add_vertex(vertex)
# set edge values
for edge, edge_value in graph.get_edges().items():
self.set_edge_value(edge, edge_value, False)
self.update_distances()
def get_adjacency_matrix(self):
"""Returns the graph's adjacency matrix as a formatted string.
"""
vertices = self.values.keys()
maxlen = 4
# get maximum length of vertex names for proper layout
for vertex in vertices:
if len(str(vertex)) > maxlen:
maxlen = len(str(vertex))
# print column heads
matrix = "".rjust(maxlen) + " |"
for vertex in vertices:
matrix += " " + str(vertex).rjust(maxlen) + " |"
# print without trailing |
matrix = matrix[:-1] + "\n"
# generate row separator
matrix += "-" * maxlen + "-+"
for i in range(len(vertices)):
matrix += "-" + "-" * maxlen + "-+"
# print without trailing +
matrix = matrix[:-1] + "\n"
# print rows
for v1 in vertices:
matrix += str(v1).ljust(maxlen) + " |"
for v2 in vertices:
matrix += " " + self._get_edge_value_as_text((v1, v2)).rjust(maxlen) + " |"
# print without trailing |
matrix = matrix[:-1] + "\n"
return matrix
def get_graphviz(self, label=""):
"""Returns a string representation of the graph in the dot language from
the graphviz project.
"""
left_vertices = set(self.values.keys())
graph = "Graph G {\n"
if label != "":
graph += "\tgraph [label = \"%s\", labelloc=t]\n" % label
for v1 in self.values.keys():
for v2 in left_vertices:
if self.get_edge_value((v1, v2)):
graph += "\t\"" + str(v1) + "\" -- \"" + str(v2) + "\" "
graph += "[label = \"" + str(self.get_edge_value((v1, v2))) + "\"]\n"
# undirected graph, therefore discard double connections
left_vertices.remove(v1)
graph += "}\n"
return graph
def write_to_file(self, file_name, use_graphviz=False):
"""Writes a textual representation of the graph to the specified file.
If the optional parameter use_graphviz is True, the graph is represented
in the dot language from the graphviz project.
"""
file = open(file_name, 'w')
if use_graphviz:
file.write(self.get_graphviz())
else:
file.write(self.get_adjacency_matrix())
file.close()
def read_from_dotfile(self, file_name):
"""Reads the graph from a graphviz dot file.
"""
file = open(file_name, 'r')
# clear current data
self.__init__()
# match following lines
# "t9-035" -- "t9-146" [label = "1"]
edge_re = re.compile('\s*"(.+)" -- "(.+)" \[label = "(.+)"\]')
for line in file:
edge_ma = edge_re.match(line)
if edge_ma:
v1 = edge_ma.group(1)
v2 = edge_ma.group(2)
value = edge_ma.group(3)
self.add_vertex(v1)
self.add_vertex(v2)
self.set_edge_value((v1, v2), value, False)
file.close()
self.update_distances()
def read_from_file(self, file_name):
"""Reads the graph from a file containing an adjacency matrix as
generated by get_adjacency_matrix() or write_to_file(). The dot format
is not supported.
"""
file = open(file_name, 'r')
# line counter
i = 0;
vertices = list()
for line in file:
i += 1
# first line contains the vertex names
if i == 1:
# first element is empty, therefore discard it
for vertex in line.split("|")[1:]:
vertices.append(vertex.strip())
# clear current data and set new vertices
self.__init__(vertices)
if i > 2:
row = line.split("|")
# first element is the vertex name
v1 = row[0].strip()
# remaining elements are edge values
row = row[1:]
for v2 in vertices:
value = row[vertices.index(v2)].strip()
if value == '':
value = None
self.set_edge_value((v1, v2), value, False)
file.close()
self.update_distances()
def update_distances(self):
"""Updates the distance matrix with the number of hops between all
vertex pairs.
"""
# Floyd Warshall algorithm
# calculate all shortest paths
for k in self.get_vertices():
remaining_vertices = self.get_vertices()
for v1 in self.get_vertices():
for v2 in remaining_vertices:
d = min(self.get_distance(v1, v2),
self.get_distance(v1, k) + self.get_distance(k, v2))
self.set_distance(v1, v2, d)
remaining_vertices.remove(v1)
def get_neighbors(self, vertex):
"""Returns a set that contains all direct neighbors of the given vertex.
"""
neighbors = set()
for v1, v2 in self.get_edges().keys():
if v1 == vertex:
neighbors.add(v2)
elif v2 == vertex:
neighbors.add(v1)
return neighbors
def copy(self):
"""Returns a new Graph object that contains the same vertices and edges.
"""
remaining_vertices = self.get_vertices()
g = Graph(list(remaining_vertices))
for v1 in self.get_vertices():
for v2 in remaining_vertices:
g.set_edge_value((v1, v2), self.get_edge_value((v1, v2)))
g.set_distance(v1, v2, self.get_distance(v1, v2))
remaining_vertices.remove(v1)
return g
def copy_fast(self):
"""Returns a new Graph object that contains the same vertices and edges.
"""
remaining_vertices = self.get_vertices()
g = Graph(list(remaining_vertices))
e = self.get_edges()
for (v1, v2), chans in self.get_edges().iteritems():
g.set_edge_value((v1,v2), self.get_edge_value((v1, v2)), update=False)
g.set_distance(v1, v2, self.get_distance(v1, v2))
return g
def _get_edge_value_as_text(self, edge):
"""Returns a textual representation of the value of the given edge. The
edge is represented by a tuple of two vertices.
"""
v1, v2 = edge
if not self.values[v1][v2]:
return ""
else:
return str(self.values[v1][v2])
class ConflictGraphVertex:
def __init__(self, conflict_graph, nw_graph_edge):
self.conflict_graph = conflict_graph
self.nw_graph_edge = nw_graph_edge
self.channels = None
def __str__(self):
return "%s_%s" % (self.nw_graph_edge)
def get_channel(self):
"""Returns the channel of the link in the network graph that corresponds
to this vertex.
"""
return int(self.conflict_graph.network_graph.get_edge_value(self.nw_graph_edge))
def set_channel(self, channel):
"""Sets the channel in the network graph and computes the resulting
conflict graph.
"""
# update network graph
self.conflict_graph.network_graph.set_edge_value(self.nw_graph_edge,
str(channel))
# update conflict graph
# NOTE the change: We do not have to recalculate ALL edges, just the onces
# adjacent to the changed one are enough! gives us O(n) instead of O(n*n)
self.conflict_graph.update_edge(self)
# self.conflict_graph.update_edges()
def get_nw_graph_neighbor(self, node_name):
"""Returns the neigbor in the network graph corresponding to the link.
"""
if node_name not in self.nw_graph_edge:
return None
if self.nw_graph_edge[0] == node_name:
return self.nw_graph_edge[1]
else:
return self.nw_graph_edge[0]
class ConflictGraph(Graph):
def __init__(self, network_graph, interference_model):
# store the original network graph for later reference
self.network_graph = network_graph
self.interference_model = interference_model
vertices = set()
# each edge in the network graph corresponds to a vertex in the conflict
# graph
for edge in network_graph.get_edges().keys():
vertices.add(ConflictGraphVertex(self, edge))
# call constructor of the super-class with new vertex set
Graph.__init__(self, vertices)
# set edges according to interference model
self.update_edges()
def update_edges(self):
"""Updates all edges of the ConflictGraph regarding the current channel
assignment and the applied interference model.
"""
remaining_vertices = self.get_vertices()
for v1 in self.get_vertices():
for v2 in remaining_vertices:
# get edge value according to the interference model
value = self.interference_model.get_interference(self.network_graph,
v1.nw_graph_edge,
v2.nw_graph_edge)
self.set_edge_value((v1, v2), value, False)
# graph is undirected
remaining_vertices.remove(v1)
def update_edge(self, cg_vertex):
"""Updates all edges that are adjacent to the supplied cg_vertex.
"""
remaining_vertices = self.get_vertices()
for v2 in self.get_vertices():
# get edge value according to the interference model
value = self.interference_model.get_interference(self.network_graph,
cg_vertex.nw_graph_edge,
v2.nw_graph_edge)
self.set_edge_value((cg_vertex, v2), value, False)
def get_vertices_for_node(self, node_name):
"""Returns a set containing all vertices that correspond to links that
are incident to the given node.
"""
vertices = set()
for vertex in self.get_vertices():
if vertex.nw_graph_edge[0] == node_name or \
vertex.nw_graph_edge[1] == node_name:
vertices.add(vertex)
return vertices
def get_vertex(self, node1, node2):
"""Returns the vertex that corresponds to the link between the two given
node names, or None, if such vertex does not exist.
"""
for vertex in self.get_vertices():
if (vertex.nw_graph_edge[0] == node1 and \
vertex.nw_graph_edge[1] == node2) or \
(vertex.nw_graph_edge[0] == node2 and \
vertex.nw_graph_edge[1] == node1):
return vertex
return None
def get_interference_sum(self):
"""Returns the overall interference which is calculated by summing up
all edge values.
"""
sum = 0
for value in self.get_edges().values():
sum += value
return sum
def get_vertex_names(self):
vertex_names = set()
for vertex in self.get_vertices():
vertex_names.add(str(vertex))
return vertex_names
def update(self, network_graph):
old_edges = self.network_graph.get_edges()
new_edges = network_graph.get_edges()
# do nothing if graphs are equal
if new_edges == old_edges:
return
old_edges_keys = set(old_edges.keys())
new_edges_keys = set(new_edges.keys())
# assign new network graph
self.network_graph = network_graph
# update conflict graph
for new_edge in new_edges_keys - old_edges_keys:
# create a new conflict graph vertex for each new network graph edge
self.add_vertex(ConflictGraphVertex(self, new_edge))
for obsolete_edge in old_edges_keys - new_edges_keys:
# remove conflict graph vertices for obsolete edges
self.remove_vertex(self.get_vertex(obsolete_edge[0],
obsolete_edge[1]))
self.update_edges()
# this only runs if the module was *not* imported
if __name__ == '__main__':
g = Graph(["a", "b", "c", "d", "e"])
g.set_edge_value(("a", "b"), 40)
g.set_edge_value(("b", "c"), 40)
g.set_edge_value(("c", "d"), 40)
g.set_edge_value(("d", "e"), 40)
print g.get_adjacency_matrix()
|
des-testbed/des_chan
|
graph.py
|
Python
|
gpl-3.0
| 18,151
|
# DirectionalNK
NK Models [1] are used in simulating biological systems. This project simulates the evolutionary behavior of a viral system using an NK model where the system is given environmental shocks of varying degrees.
The repository contains a self-contained project that can be imported into Eclipse (Juno). The main program is Simulation.java. Inputs can be given as described in resources/input.txt.
[1] S. Kauffman and S. Levin, Towards a General Theory of Adaptive Walks on Rugged Landscapes, J. Theor. Biol (1987) 128, 11-45
|
ssinghal53/DirectionalNK
|
README.md
|
Markdown
|
gpl-3.0
| 541
|
/*
* File: DataFileTypes.h
* Author: 123
*
* Created on 1 Март 2014 г., 18:58
*/
#ifndef DATAFILETYPES_H
#define DATAFILETYPES_H
#define ntype int
//#define ntype int //(void *)int="Указатель на область памяти )"
#ifdef WIN32
#define TRUE_SLASH L"\\"
#else
#define TRUE_SLASH L"/"
#endif
#define STATE_NOT_READY 0
#define STATE_READY 1
#define STATE_EXCITED 2
#define _PREFIX_LINKLIST 0xA000FF01
typedef struct _linclist_card {
long listnext, listprev; //Позиция в файле предидущей и последующей структуры LICX
} LICL;
typedef struct _linklist_blk {
LICL inlist, outlist;
} LAR; //Указатели на списки связи
typedef struct _linc_cardX {
LAR around; //Указатели на списки связи
// LICL inlst, outlst; //Указатели на списки связи
long OSneurofrom, OSneuroto; //Указатели на прицепленность к нейронам
ntype weight; //Накопительный вес связи
int activated; //Количество использований связи до активации нейрона
void *memorypoint;
} LICX;
#define _PREFIX_NEURON 0xA000FF02
typedef struct _neuron_card {
long neuronnext, neuronprev;
ntype val, retval;
short type;
char state, chance;
short incount, outcount;
long LListin, LListout;
long OSlayer;
void *memorypoint;
} NC;
#define _PREFIX_LAYER 0xA000FF03
typedef struct _lay_around {
long downcard, upcard;
long nextcard, prevcard;
} LA;
typedef struct _logic_card {
LA around;
long neurofirst;
int neurocount, neurocount_activ;
char state, type, chance;
void *memorypoint;
} LC;
typedef struct _thread_neuro_block {
long LayerOS;
long NeuroOS;
char shance;
} NBT;
//Протестить приведение из char type to int type и наоборот
typedef struct _freedoom_case_base_block {
int itemscount, type;
long entrypoint;
} FCBB;
void *_MallocZeroBytes(unsigned int size);
#ifdef __linux__
#define __stdcall
int _wCrossUnlink(const wchar_t* filename);
FILE *_wCrossFopen(const wchar_t* filename, const wchar_t* mode);
int _wCrossAccess(const wchar_t* filename, int mode); //Аналог int access() только для пухлых символик
#else
//Венда, домохозяюшка и классная наложница ;)
#endif
#endif /* DATAFILETYPES_H */
|
DemonSinusa/SiemanC
|
LibsCore/nnl/DataFileTypes.h
|
C
|
gpl-3.0
| 2,528
|
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
dist: {
options: {
style: 'compressed'
},
files: {
'assets/css/global.css': 'src/sass/global.scss'
}
}
},
concat: {
options: {
separator: ';'
},
dist: {
src: ['src/js/**.js'],
dest: 'assets/js/global.js'
}
},
uglify: {
my_target: {
files: {
'assets/js/global.min.js': ['assets/js/global.js']
}
}
},
autoprefixer: {
options: {
map: true,
browsers: ['Last 8 versions', 'IE > 7', '> 1%']
},
css: {
src: 'assets/css/*.css'
}
},
watch: {
sass: {
files: ['src/sass/**/*.scss'],
tasks: ['sass', 'autoprefixer']
},
js: {
files: ['src/js/**/*.js'],
tasks: ['concat', 'uglify']
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['sass', 'autoprefixer', 'concat', 'uglify']);
};
|
Treenity/bbpress-wp-support
|
gruntfile.js
|
JavaScript
|
gpl-3.0
| 1,604
|
/*
Copyright (c) 2011 Mathieu Laurendeau <mat.lau@laposte.net>
License: GPLv3
*/
#ifndef GIMXUPDATER_H_
#define GIMXUPDATER_H_
#include <string>
class Updater {
public:
Updater();
virtual ~Updater();
int checkVersion(std::string versionUrl, std::string version);
enum UpdaterStatus {
UpdaterStatusOk = 0,
UpdaterStatusConnectionPending = 1,
UpdaterStatusDownloadInProgress = 2,
UpdaterStatusInstallPending = 3,
UpdaterStatusCancelled = -1,
UpdaterStatusInitFailed = -2,
UpdaterStatusDownloadFailed = -3,
UpdaterStatusInstallFailed = -4,
};
typedef int (*ProgressCallback)(void *clientp, Updater::UpdaterStatus status, double progress, double total);
UpdaterStatus update(std::string url, ProgressCallback callback, void *clientp, bool wait);
int progress(Updater::UpdaterStatus, double dlnow, double dltotal);
static std::string getProgress(double progress, double total);
private:
ProgressCallback clientCallback;
void * clientData;
};
#endif /* GIMXUPDATER_H_ */
|
matlo/GIMX
|
shared/gimxupdater/Updater.h
|
C
|
gpl-3.0
| 1,082
|
package it.kytech.skywars;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Vector;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import it.kytech.skywars.MessageManager.PrefixType;
import it.kytech.skywars.commands.AddWall;
import it.kytech.skywars.commands.CreateArena;
import it.kytech.skywars.commands.DelArena;
import it.kytech.skywars.commands.Disable;
import it.kytech.skywars.commands.Enable;
import it.kytech.skywars.commands.ForceStart;
import it.kytech.skywars.commands.Join;
import it.kytech.skywars.commands.Leave;
import it.kytech.skywars.commands.LeaveQueue;
import it.kytech.skywars.commands.ListArenas;
import it.kytech.skywars.commands.ListPlayers;
import it.kytech.skywars.commands.Reload;
import it.kytech.skywars.commands.ResetSpawns;
import it.kytech.skywars.commands.SetLobbySpawn;
import it.kytech.skywars.commands.SetLobbyWall;
import it.kytech.skywars.commands.SetSpawn;
import it.kytech.skywars.commands.Spectate;
import it.kytech.skywars.commands.SubCommand;
import it.kytech.skywars.commands.Teleport;
import it.kytech.skywars.commands.Vote;
public class CommandHandler implements CommandExecutor {
private Plugin plugin;
private HashMap < String, SubCommand > commands;
private HashMap < String, Integer > helpinfo;
private MessageManager msgmgr = MessageManager.getInstance();
public CommandHandler(Plugin plugin) {
this.plugin = plugin;
commands = new HashMap < String, SubCommand > ();
helpinfo = new HashMap < String, Integer > ();
loadCommands();
loadHelpInfo();
}
private void loadCommands() {
commands.put("createarena", new CreateArena());
commands.put("join", new Join());
commands.put("addwall", new AddWall());
commands.put("setspawn", new SetSpawn());
commands.put("getcount", new ListArenas());
commands.put("disable", new Disable());
commands.put("start", new ForceStart());
commands.put("enable", new Enable());
commands.put("vote", new Vote());
commands.put("leave", new Leave());
commands.put("setlobbyspawn", new SetLobbySpawn());
commands.put("setlobbywall", new SetLobbyWall());
commands.put("resetspawns", new ResetSpawns());
commands.put("delarena", new DelArena());
commands.put("spectate", new Spectate());
commands.put("lq", new LeaveQueue());
commands.put("leavequeue", new LeaveQueue());
commands.put("list", new ListPlayers());
commands.put("tp", new Teleport());
commands.put("reload", new Reload());
commands.put("reload", new Reload());
}
private void loadHelpInfo() {
//you can do this by iterating thru the hashmap from a certian index btw instead of using a new hashmap,
//plus, instead of doing three differnet ifs, just iterate thru and check if the value == the page
helpinfo.put("createarena", 3);
helpinfo.put("join", 1);
helpinfo.put("addwall", 3);
helpinfo.put("setspawn", 3);
helpinfo.put("getcount", 3);
helpinfo.put("disable", 2);
helpinfo.put("start", 2);
helpinfo.put("enable", 2);
helpinfo.put("vote", 1);
helpinfo.put("leave", 1);
helpinfo.put("setlobbyspawn", 3);
helpinfo.put("resetspawns", 3);
helpinfo.put("delarena", 3);
helpinfo.put("flag", 3);
helpinfo.put("spectate", 1);
helpinfo.put("lq", 1);
helpinfo.put("leavequeue", 1);
helpinfo.put("list", 1);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd1, String commandLabel, String[] args) {
PluginDescriptionFile pdfFile = plugin.getDescription();
if (!(sender instanceof Player)) {
msgmgr.logMessage(PrefixType.WARNING, "Only in-game players can use SurvivalGames commands! ");
return true;
}
Player player = (Player) sender;
if (SkyWars.config_todate == false) {
msgmgr.sendMessage(PrefixType.WARNING, "The config file is out of date. Please tell an administrator to reset the config.", player);
return true;
}
if (SkyWars.dbcon == false) {
msgmgr.sendMessage(PrefixType.WARNING, "Could not connect to server. Plugin disabled.", player);
return true;
}
if (cmd1.getName().equalsIgnoreCase("skywar")) {
if (args == null || args.length < 1) {
msgmgr.sendMessage(PrefixType.INFO, "Version " + pdfFile.getVersion() + " by Double0negative", player);
msgmgr.sendMessage(PrefixType.INFO, "Type /sw help <player | staff | admin> for command information", player);
return true;
}
if (args[0].equalsIgnoreCase("help")) {
if (args.length == 1) {
help(player, 1);
}
else {
if (args[1].toLowerCase().startsWith("player")) {
help(player, 1);
return true;
}
if (args[1].toLowerCase().startsWith("staff")) {
help(player, 2);
return true;
}
if (args[1].toLowerCase().startsWith("admin")) {
help(player, 3);
return true;
}
else {
msgmgr.sendMessage(PrefixType.WARNING, args[1] + " is not a valid page! Valid pages are Player, Staff, and Admin.", player);
}
}
return true;
}
String sub = args[0];
Vector < String > l = new Vector < String > ();
l.addAll(Arrays.asList(args));
l.remove(0);
args = (String[]) l.toArray(new String[0]);
if (!commands.containsKey(sub)) {
msgmgr.sendMessage(PrefixType.WARNING, "Command doesn't exist.", player);
msgmgr.sendMessage(PrefixType.INFO, "Type /sw help for command information", player);
return true;
}
try {
commands.get(sub).onCommand(player, args);
} catch (Exception e) {
e.printStackTrace();
msgmgr.sendFMessage(PrefixType.ERROR, "error.command", player, "command-["+sub+"] "+Arrays.toString(args));
msgmgr.sendMessage(PrefixType.INFO, "Type /sw help for command information", player);
}
return true;
}
return false;
}
public void help (Player p, int page) {
if (page == 1) {
p.sendMessage(ChatColor.BLUE + "------------ " + msgmgr.pre + ChatColor.DARK_AQUA + " Player Commands" + ChatColor.BLUE + " ------------");
}
if (page == 2) {
p.sendMessage(ChatColor.BLUE + "------------ " + msgmgr.pre + ChatColor.DARK_AQUA + " Staff Commands" + ChatColor.BLUE + " ------------");
}
if (page == 3) {
p.sendMessage(ChatColor.BLUE + "------------ " + msgmgr.pre + ChatColor.DARK_AQUA + " Admin Commands" + ChatColor.BLUE + " ------------");
}
for (String command : commands.keySet()) {
try{
if (helpinfo.get(command) == page) {
msgmgr.sendMessage(PrefixType.INFO, commands.get(command).help(p), p);
}
}catch(Exception e){}
}
/*for (SubCommand v : commands.values()) {
if (v.permission() != null) {
if (p.hasPermission(v.permission())) {
msgmgr.sendMessage(PrefixType.INFO1, v.help(p), p);
} else {
msgmgr.sendMessage(PrefixType.WARNING, v.help(p), p);
}
} else {
msgmgr.sendMessage(PrefixType.INFO, v.help(p), p);
}
}*/
}
}
|
hitech95/SkyWars
|
src/main/java/it/kytech/skywars/CommandHandler.java
|
Java
|
gpl-3.0
| 7,097
|
package com.cole.somecraft.proxy;
public interface IProxy
{
}
|
ClarmonkGaming/SomeCraftReboot
|
src/main/java/com/cole/somecraft/proxy/IProxy.java
|
Java
|
gpl-3.0
| 63
|
/*
* //******************************************************************
* //
* // Copyright 2016 Samsung Electronics 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.
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
package org.iotivity.cloud.ciserver.resources;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.iotivity.cloud.base.device.CoapDevice;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.device.IRequestChannel;
import org.iotivity.cloud.base.device.IResponseEventHandler;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.base.exception.ServerException.NotFoundException;
import org.iotivity.cloud.base.exception.ServerException.PreconditionFailedException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.coap.CoapResponse;
import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.ciserver.Constants;
import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapDevicePool;
import org.iotivity.cloud.util.Cbor;
/**
*
* This class provides a set of APIs to send requests about message to another
* device
*
*/
public class DiResource extends Resource {
private CoapDevicePool mDevicePool = null;
public DiResource(CoapDevicePool devicePool) {
super(Arrays.asList(Constants.REQ_DEVICE_ID));
mDevicePool = devicePool;
addQueryHandler(
Arrays.asList(Constants.RS_INTERFACE + "="
+ Constants.LINK_INTERFACE),
this::onLinkInterfaceRequestReceived);
}
private IRequestChannel getTargetDeviceChannel(IRequest request)
throws ServerException {
List<String> uriPathSegment = request.getUriPathSegments();
if (uriPathSegment.size() < 2) {
throw new PreconditionFailedException();
}
String deviceId = uriPathSegment.get(1);
CoapDevice targetDevice = (CoapDevice) mDevicePool
.queryDevice(deviceId);
if (targetDevice == null) {
throw new NotFoundException();
}
// Do request and receive response
return targetDevice.getRequestChannel();
}
private String extractTargetUriPath(IRequest request) {
List<String> uriPathSegment = request.getUriPathSegments();
// Remove prefix path
uriPathSegment.remove(0);
uriPathSegment.remove(0);
StringBuilder uriPath = new StringBuilder();
for (String path : uriPathSegment) {
uriPath.append("/" + path);
}
return uriPath.toString();
}
private IResponse convertReponseUri(IResponse response, String di) {
String convertedUri = new String();
CoapResponse coapResponse = (CoapResponse) response;
if (coapResponse.getUriPath().isEmpty() == false) {
convertedUri = "/di/" + di + "/" + coapResponse.getUriPath();
}
return MessageBuilder.modifyResponse(response, convertedUri, null,
null);
}
/**
*
* This class provides a set of APIs to handling message contains link
* interface.
*
*/
class LinkInterfaceHandler implements IResponseEventHandler {
private Cbor<List<HashMap<String, Object>>> mCbor = new Cbor<>();
private String mTargetDI = null;
private Device mSrcDevice = null;
public LinkInterfaceHandler(String targetDI, Device srcDevice) {
mTargetDI = targetDI;
mSrcDevice = srcDevice;
}
private void convertHref(List<HashMap<String, Object>> linkPayload) {
for (HashMap<String, Object> link : linkPayload) {
link.put("href", "/di/" + mTargetDI + link.get("href"));
}
}
@Override
public void onResponseReceived(IResponse response) {
List<HashMap<String, Object>> linkPayload = null;
if (response.getStatus() == ResponseStatus.CONTENT) {
linkPayload = mCbor.parsePayloadFromCbor(response.getPayload(),
ArrayList.class);
if (linkPayload == null) {
throw new BadRequestException("payload is null");
}
convertHref(linkPayload);
}
mSrcDevice.sendResponse(MessageBuilder.modifyResponse(
convertReponseUri(response, mTargetDI),
ContentFormat.APPLICATION_CBOR, linkPayload != null
? mCbor.encodingPayloadToCbor(linkPayload) : null));
}
}
/**
* API for handling optional method for handling packet contains link
* interface.
*
* @param srcDevice
* device information contains response channel
* @param request
* received request to relay
*/
public void onLinkInterfaceRequestReceived(Device srcDevice,
IRequest request) throws ServerException {
IRequestChannel requestChannel = getTargetDeviceChannel(request);
if (requestChannel == null) {
throw new NotFoundException();
}
String deviceId = request.getUriPathSegments().get(1);
requestChannel.sendRequest(
MessageBuilder.modifyRequest(request,
extractTargetUriPath(request), null, null, null),
new LinkInterfaceHandler(deviceId, srcDevice));
}
class DefaultResponseHandler implements IResponseEventHandler {
private String mTargetDI = null;
private Device mSrcDevice = null;
public DefaultResponseHandler(String targetDI, Device srcDevice) {
mTargetDI = targetDI;
mSrcDevice = srcDevice;
}
@Override
public void onResponseReceived(IResponse response) {
mSrcDevice.sendResponse(convertReponseUri(response, mTargetDI));
}
}
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
// Find proper request channel using di in URI path field.
IRequestChannel requestChannel = getTargetDeviceChannel(request);
if (requestChannel == null) {
throw new NotFoundException();
}
String deviceId = request.getUriPathSegments().get(1);
requestChannel.sendRequest(
MessageBuilder.modifyRequest(request,
extractTargetUriPath(request), null, null, null),
new DefaultResponseHandler(deviceId, srcDevice));
}
}
|
kadasaikumar/iotivity-1.2.1
|
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/DiResource.java
|
Java
|
gpl-3.0
| 7,727
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Repeat event collection tests.
*
* @package core_calendar
* @copyright 2017 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/calendar/lib.php');
use core_calendar\local\event\entities\event;
use core_calendar\local\event\entities\repeat_event_collection;
use core_calendar\local\event\proxies\coursecat_proxy;
use core_calendar\local\event\proxies\std_proxy;
use core_calendar\local\event\value_objects\event_description;
use core_calendar\local\event\value_objects\event_times;
use core_calendar\local\event\factories\event_factory_interface;
/**
* Repeat event collection tests.
*
* @copyright 2017 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class core_calendar_repeat_event_collection_testcase extends advanced_testcase {
/**
* Test that creating a repeat collection for a parent that doesn't
* exist throws an exception.
*/
public function test_no_parent_collection() {
$this->resetAfterTest(true);
$parentid = 123122131;
$factory = new core_calendar_repeat_event_collection_event_test_factory();
$this->expectException('\core_calendar\local\event\exceptions\no_repeat_parent_exception');
$collection = new repeat_event_collection($parentid, null, $factory);
}
/**
* Test that an empty collection is valid.
*/
public function test_empty_collection() {
$this->resetAfterTest(true);
$this->setAdminUser();
$event = $this->create_event([
// This causes the code to set the repeat id on this record
// but not create any repeat event records.
'repeat' => 1,
'repeats' => 0
]);
$parentid = $event->id;
$factory = new core_calendar_repeat_event_collection_event_test_factory();
// Event collection with no repeats.
$collection = new repeat_event_collection($parentid, null, $factory);
$this->assertEquals($parentid, $collection->get_id());
$this->assertEquals(0, $collection->get_num());
$this->assertNull($collection->getIterator()->next());
}
/**
* Test that a collection with values behaves correctly.
*/
public function test_values_collection() {
$this->resetAfterTest(true);
$this->setAdminUser();
$factory = new core_calendar_repeat_event_collection_event_test_factory();
$event = $this->create_event([
// This causes the code to set the repeat id on this record
// but not create any repeat event records.
'repeat' => 1,
'repeats' => 0
]);
$parentid = $event->id;
$repeats = [];
for ($i = 1; $i < 4; $i++) {
$record = $this->create_event([
'name' => sprintf('repeat %d', $i),
'repeatid' => $parentid
]);
// Index by name so that we don't have to rely on sorting
// when doing the comparison later.
$repeats[$record->name] = $record;
}
// Event collection with no repeats.
$collection = new repeat_event_collection($parentid, null, $factory);
$this->assertEquals($parentid, $collection->get_id());
$this->assertEquals(count($repeats), $collection->get_num());
foreach ($collection as $index => $event) {
$name = $event->get_name();
$this->assertEquals($repeats[$name]->name, $name);
}
}
/**
* Helper function to create calendar events using the old code.
*
* @param array $properties A list of calendar event properties to set
* @return calendar_event
*/
protected function create_event($properties = []) {
$record = new \stdClass();
$record->name = 'event name';
$record->eventtype = 'global';
$record->repeat = 0;
$record->repeats = 0;
$record->timestart = time();
$record->timeduration = 0;
$record->timesort = 0;
$record->type = 1;
$record->courseid = 0;
$record->categoryid = 0;
foreach ($properties as $name => $value) {
$record->$name = $value;
}
$event = new calendar_event($record);
return $event->create($record, false);
}
}
/**
* Test event factory.
*
* @copyright 2017 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class core_calendar_repeat_event_collection_event_test_factory implements event_factory_interface {
public function create_instance(\stdClass $dbrow) {
$identity = function($id) {
return $id;
};
return new event(
$dbrow->id,
$dbrow->name,
new event_description($dbrow->description, $dbrow->format),
new coursecat_proxy($dbrow->categoryid),
new std_proxy($dbrow->courseid, $identity),
new std_proxy($dbrow->groupid, $identity),
new std_proxy($dbrow->userid, $identity),
new repeat_event_collection($dbrow->id, null, $this),
new std_proxy($dbrow->instance, $identity),
$dbrow->type,
new event_times(
(new \DateTimeImmutable())->setTimestamp($dbrow->timestart),
(new \DateTimeImmutable())->setTimestamp($dbrow->timestart + $dbrow->timeduration),
(new \DateTimeImmutable())->setTimestamp($dbrow->timesort ? $dbrow->timesort : $dbrow->timestart),
(new \DateTimeImmutable())->setTimestamp($dbrow->timemodified)
),
!empty($dbrow->visible),
new std_proxy($dbrow->subscriptionid, $identity)
);
}
}
|
eSrem/moodle
|
calendar/tests/repeat_event_collection_test.php
|
PHP
|
gpl-3.0
| 6,590
|
# Docker-REDHAWK Ubuntu Edition
This repository builds a series of Docker images and scripts for standing up an installation of REDHAWK SDR as well as several example devices and a web server. If you're familiar with [Docker-REDHAWK](http://github.com/GeonTech/docker-redhawk), this document will seem very familiar except for this:
> **IMPORTANT NOTE:** This version's Components will not be binary compatible with a CentOS 7 or RPM -based installation. You cannot deploy Components from one installation type onto the GPP of another. That said, nothing should limit you from having an Ubuntu -borne Node join a CentOS 7 Domain or vice versa.
For the USRP image (geontech/redhawk-ubuntu-usrp), the UHD driver is recompiled to a newer version and the USRP_UHD Device is compiled from source against that newer driver. The result is access to the latest Ettus Research USRPs from the container.
> **DOCKER:** You must be using at least Docker 17. This was tested using Docker-CE.
## Installing
Run `make` to pull the prebuild images and link the helper scripts. Depending on your internet connection, this may take several minutes.
## Building
To build all images, simply type `make build`. At the command line, you can also specify the variables: `REST_PYTHON` and `REST_PYTHON_BRANCH`, which specifically apply to the `geontech/redhawk-ubuntu-webserver`.
You will end up with the following images that are meant't to be run individually.
* `geontech/redhawk-ubuntu-base`: This is the repository installation, omni services (non-running), and an `/etc/omniORB.cfg` update script.
* `geontech/redhawk-ubuntu-runtime`: The typical "REDHAWK Runtime" group install. It is the basis for the `domain` and various device launchers.
The remaining images are derived and come with helper scripts for deploying your system:
* `geontech/redhawk-ubuntu-omniserver`: Inherits from `geontech/redhawk-ubuntu-base`, it has OmniORB and OmniEvents services wrapped in a single image, intended to be run as a singleton in the network. If you have an Omni server running elsewhere, you do not need this.
* `geontech/redhawk-ubuntu-development`: Configured to expose a workspace volume and run the IDE.
* `geontech/redhawk-ubuntu-domain`: Configured to run as a Domain.
* `geontech/redhawk-ubuntu-gpp`: Configured to run as a GPP -bearing Node.
* `geontech/redhawk-ubuntu-rtl2832u`: Configured to run as an RTL2832U -bearing Node.
* `geontech/redhawk-ubuntu-usrp`: Configured to run as an USRP_UHD -bearing Node.
* `geontech/redhawk-ubuntu-bu353s4`: Configured to run as a BU353S4 -bearing Node.
* `geontech/redhawk-ubuntu-webserver`: Instantiates a rest-python web server.
The following scripts will also be linked into the main directory. Each script supports `-h` and `--help` to learn the usage of the script, and running the script with no arguments provides a status update.
* `login`: Starts a bash shell for the named container (basically a `docker exec` wrapper).
* `show-log`: Displays a log from a named container.
* `omniserver`: Manages an instance of the OmniORB services (locally to the Docker host, optional).
* `domain`: Manages REDHAWK Domain instances.
* `gpp`: Starts or stops a GPP for the named domain and external OmniServer IP address.
* `rtl2832u`: Manages [RTL2832U](http://github.com/redhawksdr/RTL2832U) Nodes (USB-attached devices).
* `usrp`: Manages [USRP_UHD](http://github.com/redhawksdr/USRP_UHD) Nodes (USB- or network-attached devices).
* `bu353s4`: Manages [BU353S4](http://github.com/geontech/BU353S4) Nodes (USB serial).
* `volume-manager`: Creates or deletes Docker volumes labeled for use as an SDRROOT or a development (IDE) Workspace.
* `rhide`: Runs an instance of the REDHAWK IDE with named SDRROOT and workspace (Docker volume or host file system).
* `webserver`: Manages an instance of a REST-Python server.
## Usage
The main elements one needs for a REDHAWK system are the naming and event services (OmniORB and OmniEvents), a Domain, and a GPP. If the scripts are not in the main directory, use `make scripts` to generate the links. Each scripts supports the `-h` and `--help` that cover usage. Below is a simplified example.
./omniserver
./domain start REDHAWK_DEV1
At this point you will have a functioning REDHAWK Domain at a host-exposed OmniORB server. Its container name will be `REDHAWK_DEV`. Other non-Docker REDHAWK instances can now join this Domain as well as long as your host system's firewall settings expose ports 2809 and 11169.
./gpp start GPP1 -d REDHAWK_DEV1
A GPP container launches the node GPP1 on the REDHAWK_DEV1 Domain. Its container name will be `GPP1-REDHAWK_DEV1`. You can now launch waveforms.
If you would like to log into the Domain container, use `login`:
./login REDHAWK_DEV1 redhawk
You will enter a bash shell as the `redhawk` user.
> **Note:** Not all images have this user defined. For example, the only user in the `geontech/redhawk-ubuntu-omniserver` image is `root`, the default.
> **Note:** For containers where the name is derived from the Node and Domain names (e.g., GPP), you have to specify the full container name (in this example, `GPP1-REDHAWK_DEV1`).
## Persistent SDRROOT
Use `volume-manager` to create an SDRROOT volume that can be mounted to the Domain and IDE.
./volume-manager create sdrroot MY_REDHAWK
./domain start MY_DOMAIN --sdrroot MY_REDHAWK
The result will be a Domain with a persistent SDRROOT.
## Running the IDE
The `geontech/redhawk-ubuntu-development` image provides the development libraries necessary to develop components and devices. Use the `rhide` script to map your SDRROOT volume and workspace (absolute path or volume name):
./rhide --sdrroot MY_REDHAWK --workspace /home/me/workspace
## REST-Python Web Server
The following section contains information about the `geontech/redhawk-ubuntu-webserver` REST-Python server image.
### Running
Running the REST-Python server via the script is simple:
./webserver start
The host-side port to map can be set using either `-p` or `--port`.
Additionally, if an alternate version of REST-Python should be mounted, use `--rest-python` to specify the local absolute file path. Alternatively, one can build the image with a different version already installed (see [this](#customizing-the-image)).
### Customizing the Image
Building the REST-Python `geontech/redhawk-ubuntu-webserver` image has a two options:
* `REST_PYTHON`: URL to a git server where the REST-Python source is located (default is [Geon's](http://github.com/geontech/rest-python)).
* `REST_PYTHON_BRANCH`: Branch name of the preferred REST-Python source tree (default is master).
Specifying no options (`make geontech/redhawk-ubuntu-webserver`) bakes in the default REST-Python server and branch. The above options can be specified by passing the variables at make time:
make geontech/redhawk-ubuntu-webserver REST_PYTHON=http://my_other_target/repo
## Device Node Controllers
The following devices have their own images, launching scripts, etc. to facilitate rapid development and integration with hardware. The included devices are the REDHAWK SDR community's GPP, USRP_UHD and RTL2832U as well as Geon's [BU353S4](http://github.com/geontech/BU353S4).
In each case, similar to running `./domain` with no arguments, each of these device launchers will also print a status message for all running instances of their respecive images.
### GPP
The `geontech/redhawk-ubuntu-gpp` image provides a Node running a GPP Device for your system. The `gpp` script provides only a few options for naming the device, setting the Domain name, etc. See the `--help` for usage. Starting with the default domain:
./gpp start MyGPP
### USRP_UHD
The `geontech/redhawk-ubuntu-usrp` image compiles the 3.10 version of UHD and then compiles the USRP_UHD from source. The resulting device is capable of working with many of the latest Ettus Research USRPs like the USB-attached B205mini. The associated `usrp` script allows you to configure the Device in its Node when starting an instance of it.
For the B205mini, it identifies as the `b200` type. With it connected to a powered USB 3.0 port:
./usrp start MyB205 --usrptype b200
This will start a container attached to REDHAWK_DEV (the default Domain). The container will be mapped to the host's `/dev/usb` bus as a volume so that UHD can locate the device and update it before the node is started.
> **Note:** Because the container startup is going through that lengthy process, startup may take several seconds.
Other USRP types can be as well. See the script's `--help` for a list of options.
#### Special notes for USB USRPs
USB-attached USRPs like the B205mini may need firmware loaded the first time the device is plugged into the computer (or virtual machine). Otherwise, when you `show-log` the container, you will see CORBA Transient errors when the device fails to initialize quickly enough. You can stop and restart the container andd the problem will be resolved, or you can run a container first to initialize the device:
docker run --rm -it \
-v /dev/bus/usb:/dev/bus/usb \
--privileged \
geontech/redhawk-usrp \
bash -lc "uhd_find_devices && uhd_usrp_probe"
The result is a one-off container that will configure the firmware and FPGA image.
### RTL2832U
The `geontech/redhawk-ubuntu-rtl2832u` image provides the RTL2832U Device. The associated launcher script is `rtl2832u`:
./rtl2832u start MyRTL
This will start a container with the RTL2832U device configured with its defaults.
> **IMPORTANT:** You may need to blacklist the RTL's kernel driver(s) on your host system before starting this container.
#### Black-listing
Methods for temporarily unloading the kernel drivers varies with host operating system distribution. For example, Ubuntu 16.04 is by way of `modprobe`:
modprobe -r dvb_usb_rtl28xxu rtl2832
To make the change permanent, one creates a configuration (`.conf`) file in `/etc/modprobe.d` with these contents:
blacklist dvb_usb_rtl28xxu
blacklist rtl2832
blacklist rtl2830
### BU353S4
The `geontech/redhawk-ubuntu-bu353s4` image provides Geon's BU353S4 FEI 2.0 -compliant USB-attached serial GPS receiver. Like the Device, it has only one option: the path to the serial device in `/dev`. The default is `/dev/ttyUSB0`. Starting an instance on the default REDHAWK_DEV Domain is:
./bu353s4 start MyGPS
You can then attach to the GPS port and pull coordinates, time, etc.
|
Geontech/docker-redhawk-ubuntu
|
README.md
|
Markdown
|
gpl-3.0
| 10,591
|
/*
Copyright 2015 Rudolf Fiala
This file is part of Alpheus AFP Parser.
Alpheus AFP Parser 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.
Alpheus AFP Parser 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 Alpheus AFP Parser. If not, see <http://www.gnu.org/licenses/>
*/
package com.mgz.afp.modca;
import com.mgz.afp.base.IRepeatingGroup;
import com.mgz.afp.base.RepeatingGroupWithTriplets;
import com.mgz.afp.base.StructuredFieldBaseRepeatingGroups;
import com.mgz.afp.exceptions.AFPParserException;
import com.mgz.afp.parser.AFPParserConfiguration;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* MO:DCA, page 293.<br> <br> The Map Page Overlay structured field maps local identifiers to page
* overlay names.
*/
public class MPO_MapPageOverlay extends StructuredFieldBaseRepeatingGroups {
@Override
public void decodeAFP(byte[] sfData, int offset, int length, AFPParserConfiguration config) throws AFPParserException {
int actualLength = getActualLength(sfData, offset, length);
int pos = 0;
while (pos < actualLength) {
MPO_RepeatinGroup rg = new MPO_RepeatinGroup();
rg.decodeAFP(sfData, offset + pos, actualLength - pos, config);
addRepeatingGroup(rg);
pos += rg.getRepeatingGroupLength();
}
}
@Override
public void writeAFP(OutputStream os, AFPParserConfiguration config) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (IRepeatingGroup rg : repeatingGroups) rg.writeAFP(baos, config);
writeFullStructuredField(os, baos.toByteArray());
}
public static class MPO_RepeatinGroup extends RepeatingGroupWithTriplets {
}
}
|
quike/alpheusafpparser
|
src/main/java/com/mgz/afp/modca/MPO_MapPageOverlay.java
|
Java
|
gpl-3.0
| 2,124
|
/*
* U-Boot - main board file
*
* Copyright (c) 2005-2008 Analog Devices Inc.
*
* (C) Copyright 2000-2004
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <config.h>
#include <command.h>
#include <asm/blackfin.h>
#include <net.h>
#include <asm/mach-common/bits/bootrom.h>
#include <netdev.h>
DECLARE_GLOBAL_DATA_PTR;
int checkboard(void)
{
printf("Board: ADI BF537 stamp board\n");
printf(" Support: http://blackfin.uclinux.org/\n");
return 0;
}
#ifdef CONFIG_BFIN_MAC
static void board_init_enetaddr(uchar *mac_addr)
{
#ifdef CONFIG_MTD_NOR_FLASH
/* we cram the MAC in the last flash sector */
uchar *board_mac_addr = (uchar *)0x203F0000;
if (is_valid_ethaddr(board_mac_addr)) {
memcpy(mac_addr, board_mac_addr, 6);
eth_setenv_enetaddr("ethaddr", mac_addr);
}
#endif
}
int board_eth_init(bd_t *bis)
{
return bfin_EMAC_initialize(bis);
}
#endif
/* miscellaneous platform dependent initialisations */
int misc_init_r(void)
{
#ifdef CONFIG_BFIN_MAC
uchar enetaddr[6];
if (!eth_getenv_enetaddr("ethaddr", enetaddr))
board_init_enetaddr(enetaddr);
#endif
#ifdef CONFIG_MTD_NOR_FLASH
/* we use the last sector for the MAC address / POST LDR */
extern flash_info_t flash_info[];
flash_protect(FLAG_PROTECT_SET, 0x203F0000, 0x203FFFFF, &flash_info[0]);
#endif
#ifdef CONFIG_BFIN_IDE
cf_ide_init();
#endif
return 0;
}
|
dasuimao/U-BOOT-Tiny4412
|
board/bf537-stamp/bf537-stamp.c
|
C
|
gpl-3.0
| 1,432
|
//
//
// Generated by StarUML(tm) C++ Add-In
//
// @ Project : Untitled
// @ File Name : StaticData.cpp
// @ Date : 2017/9/29
// @ Author : ouo
//
//
#include "StaticData.h"
StaticData StaticData::sharedStaticData() {
}
viod StaticData::purge() {
}
int StaticData::intValueFormKey(std::string key) {
}
char StaticData::stringValueFromKey(std::string key) {
}
float StaticData::floatValueFromKey(std::string key) {
}
bool StaticData::booleanFromKey(std::string key) {
}
cocos2d::CCPoint StaticData::pointFromKey(std::string key) {
}
cocos2d::CCRect StaticData::rectFromKey(std::string key) {
}
cocos2d::CCSize StaticData::sizeFromKey(std::string key) {
}
bool StaticData::init() {
}
StaticData::~StaticData() {
}
StaticData::StaticData() {
}
|
ouopoi/StaticData
|
StaticData/StaticData.cpp
|
C++
|
gpl-3.0
| 835
|