repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
moisesjbc/gcs | web/js/utilities.js | 2184 | /***
* Copyright 2012, 2014
* Garoe Dorta Perez
* Moises J. Bonilla Caraballo (Neodivert)
*
* This file is part of GCS.
*
* GCS 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.
*
* GCS 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 GCS. If not, see <http://www.gnu.org/licenses/>.
***/
/*
SendPOSTRequest: Send POST parameters 'parameters' to url 'url'. Also set
the function 'responseFunction' as the response's handle.
*/
var request_url = 'controller.php';
function SendPOSTRequest( url, parameters, responseFunction, async ){
// Create a new HTML request.
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set the response function.
xmlhttp.onreadystatechange = responseFunction;
// Prepaer the request and send it.
if( async == null ){ async == true; }
xmlhttp.open("POST",url,async);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send( parameters );
}
/*
RemoveElement: Get the DOM element whose id is 'id' and remove it from
document.
*/
function RemoveElement( id ){
var element = document.getElementById( id );
element.parentNode.removeChild( element );
}
/*
CreateDiv: Create a div element with id 'id' and content 'html'. When
created, append it as a child of 'parent' DOM element.
*/
function CreateDiv( parent, id, html ){
var newDiv = document.createElement('div');
newDiv.setAttribute('id', id);
if (html) {
newDiv.innerHTML = html;
}
parent.appendChild( newDiv );
}
| gpl-3.0 |
nickbattle/vdmj | vdmj/src/main/java/com/fujitsu/vdmj/po/definitions/POThreadDefinition.java | 2304 | /*******************************************************************************
*
* Copyright (c) 2016 Fujitsu Services Ltd.
*
* Author: Nick Battle
*
* This file is part of VDMJ.
*
* VDMJ 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.
*
* VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>.
* SPDX-License-Identifier: GPL-3.0-or-later
*
******************************************************************************/
package com.fujitsu.vdmj.po.definitions;
import com.fujitsu.vdmj.po.definitions.visitors.PODefinitionVisitor;
import com.fujitsu.vdmj.po.statements.POStatement;
import com.fujitsu.vdmj.tc.lex.TCNameToken;
import com.fujitsu.vdmj.tc.types.TCType;
import com.fujitsu.vdmj.tc.types.TCUnknownType;
public class POThreadDefinition extends PODefinition
{
private static final long serialVersionUID = 1L;
public final POStatement statement;
public final TCNameToken operationName;
public POThreadDefinition(POStatement statement)
{
super(statement.location, null);
this.statement = statement;
this.operationName = TCNameToken.getThreadName(statement.location);
}
@Override
public TCType getType()
{
return new TCUnknownType(location);
}
@Override
public String toString()
{
return "thread " + statement.toString();
}
@Override
public boolean equals(Object other)
{
if (other instanceof POThreadDefinition)
{
POThreadDefinition tho = (POThreadDefinition)other;
return tho.operationName.equals(operationName);
}
return false;
}
@Override
public int hashCode()
{
return operationName.hashCode();
}
@Override
public <R, S> R apply(PODefinitionVisitor<R, S> visitor, S arg)
{
return visitor.caseThreadDefinition(this, arg);
}
}
| gpl-3.0 |
SamuelDoud/complex-homotopy | NavigationBar.py | 464 | import tkinter
import matplotlib
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
class NavigationBar(NavigationToolbar2TkAgg):
"""This class removes the buttons not usable in the program"""
def __init__(self, canvas, window):
self.toolitems = [tool for tool in NavigationToolbar2TkAgg.toolitems if tool[0] in ('Pan', 'Save')]
self.toolitems.reverse()
NavigationToolbar2TkAgg.__init__(self, canvas, window)
| gpl-3.0 |
Urco13/PracticasClase | ArrayBidimensional/src/arraybidimensional/ArrayBidimensional.java | 2146 | /*
Crear Matriz de 3x4
Almacenar numeros
metodo mostrar tabla,
mostrar los datos de la fila 3,
mostrar suma de cada fila,
mostrar suma columna 3,
Donde esta el numero?
Recorrer por columnas y mostrar
*/
package arraybidimensional;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
*
* @author dam115
*/
public class ArrayBidimensional {
/**
* @param args the command line arguments
*/
static BufferedReader leerFlujo = new BufferedReader(new InputStreamReader(System.in));
public static final int FILAS = 3;
public static final int COLUMNAS = 4;
//comienzo main
public static void main(String[] args) {
int miMatriz[][];
miMatriz=guardarNumerosArray();
}//fin main
//Metodo mostrar tabla
public static void mostrarTabla(int matriz[][]){
for (int i = 0; i <matriz.length; i++) {
for (int j = 0; j <matriz[i].length; j++) {
System.out.println("Fila "+i+" numero "+matriz[i][j]);
}
}
}//fin metodo
//Metodo guardar numero array
public static int[][] guardarNumerosArray(){
int matriz[][] = new int[FILAS][COLUMNAS];
for (int i = 0; i<matriz.length; i++) {
for (int j = 0; j <matriz[i].length; j++) {
matriz[i][j]=leerStringI("Dime un numero");
}
}
}//fin metodo
//METODO LEER
public static int leerStringI(String texto){
int numero=0;
System.out.println(texto);
try {
numero = Integer.parseInt(leerFlujo.readLine());
} catch (NumberFormatException ex) {
System.out.println("Dime un numero entero no decimal");
} catch (Exception ex) {
System.out.println("Erro");
}
return numero;
// int tabla[][]=new int[FILA][COLUM];
// System.out.println("numero filas "+tabla.length);
// System.out.println("elementos fila 0 ==> "+tabla[0].length);
}//fin metodo
}//fin class
| gpl-3.0 |
RalphBariz/RalphsDotNet | Service.Data.NHibernate/RalphsDotNet.Service.Data.NHibernate/MonoSqliteDriver.cs | 941 | namespace RalphsDotNet.Service.Data
{
public class MonoSqliteDriver : NHibernate.Driver.ReflectionBasedDriver
{
public MonoSqliteDriver ()
: base(
"Mono.Data.Sqlite",
"Mono.Data.Sqlite",
"Mono.Data.Sqlite.SqliteConnection",
"Mono.Data.Sqlite.SqliteCommand")
{
}
public override bool UseNamedPrefixInParameter {
get {
return true;
}
}
public override bool UseNamedPrefixInSql {
get {
return true;
}
}
public override string NamedPrefix {
get {
return "@";
}
}
public override bool SupportsMultipleOpenReaders {
get {
return false;
}
}
}
} | gpl-3.0 |
veronecrm/veronecrm | src/core/System/Http/Session/FlashBag.php | 1939 | <?php
/**
* Verone CRM | http://www.veronecrm.com
*
* @copyright Copyright (C) 2015 - 2016 Adam Banaszkiewicz
* @license GNU General Public License version 3; see license.txt
*/
namespace System\Http\Session;
use System\ParameterBag;
class FlashBag
{
protected $flashes = ['new' => [], 'current' => []];
public function initialize(array &$flashes)
{
$this->flashes = &$flashes;
$this->flashes['current'] = isset($this->flashes['new']) ? $this->flashes['new'] : [];
$this->flashes['new'] = [];
}
public function all()
{
$return = $this->flashes['current'];
$this->flashes = ['new' => [], 'current' => []];
return $return;
}
public function set($type, $messages)
{
$this->flashes['new'][$type] = (array) $messages;
return $this;
}
public function setAll(array $messages)
{
$this->flashes['new'] = $messages;
return $this;
}
public function get($type, array $default = array())
{
$return = $default;
if(! $this->has($type))
{
return $return;
}
if(isset($this->flashes['current'][$type]))
{
$return = $this->flashes['current'][$type];
unset($this->flashes['current'][$type]);
}
return $return;
}
public function add($key, $value)
{
$this->flashes['new'][$key][] = $value;
return $this;
}
public function has($type)
{
return isset($this->flashes['current'][$type]) && $this->flashes['current'][$type];
}
public function count($type)
{
return count($this->flashes['current'][$type]);
}
public function remove($key)
{
unset($this->flashes['current'][$type]);
return $this;
}
public function keys()
{
return array_keys($this->flashes['current']);
}
}
| gpl-3.0 |
delalond/STEPS | STEPS-2.0.0/cpp/tetexact/tri.hpp | 9710 | ////////////////////////////////////////////////////////////////////////////////
// STEPS - STochastic Engine for Pathway Simulation
// Copyright (C) 2007-2013ÊOkinawa Institute of Science and Technology, Japan.
// Copyright (C) 2003-2006ÊUniversity of Antwerp, Belgium.
//
// See the file AUTHORS for details.
//
// This file is part of STEPS.
//
// STEPSÊ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.
//
// STEPSÊ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/>.
//
////////////////////////////////////////////////////////////////////////////////
/*
* Last Changed Rev: $Rev: 489 $
* Last Changed Date: $Date: 2013-04-19 19:37:42 +0900 (Fri, 19 Apr 2013) $
* Last Changed By: $Author: iain $
*/
#ifndef STEPS_TETEXACT_TRI_HPP
#define STEPS_TETEXACT_TRI_HPP 1
// STL headers.
#include <cassert>
#include <vector>
// STEPS headers.
#include "../common.h"
#include "../solver/patchdef.hpp"
#include "kproc.hpp"
#include "../solver/types.hpp"
////////////////////////////////////////////////////////////////////////////////
START_NAMESPACE(steps)
START_NAMESPACE(tetexact)
////////////////////////////////////////////////////////////////////////////////
NAMESPACE_ALIAS(steps::tetexact, stex);
////////////////////////////////////////////////////////////////////////////////
// Forward declarations
class Tet;
class WmVol;
class Tri;
class SReac;
class SDiff;
class Tetexact;
class VDepTrans;
class VDepSReac;
class GHKcurr;
////////////////////////////////////////////////////////////////////////////////
// Auxiliary declarations.
typedef Tri * TriP;
typedef std::vector<TriP> TriPVec;
typedef TriPVec::iterator TriPVecI;
typedef TriPVec::const_iterator TriPVecCI;
////////////////////////////////////////////////////////////////////////////////
class Tri
{
public:
////////////////////////////////////////////////////////////////////////
// OBJECT CONSTRUCTION & DESTRUCTION
////////////////////////////////////////////////////////////////////////
Tri(uint idx, steps::solver::Patchdef * patchdef, double area,
double l0, double l1, double l2, double d0, double d1, double d2,
int tetinner, int tetouter, int tri0, int tri1, int tri2);
~Tri(void);
////////////////////////////////////////////////////////////////////////
// CHECKPOINTING
////////////////////////////////////////////////////////////////////////
/// checkpoint data
void checkpoint(std::fstream & cp_file);
/// restore data
void restore(std::fstream & cp_file);
////////////////////////////////////////////////////////////////////////
// SETUP
////////////////////////////////////////////////////////////////////////
/// Set pointer to the 'inside' neighbouring tetrahedron.
///
void setInnerTet(stex::WmVol * t);
/// Set pointer to the 'outside' neighbouring tetrahedron.
///
void setOuterTet(stex::WmVol * t);
/// Set pointer to the next neighbouring triangle.
void setNextTri(uint i, stex::Tri * t);
/// Create the kinetic processes -- to be called when all tetrahedrons
/// and triangles have been fully declared and connected.
///
void setupKProcs(stex::Tetexact * tex, bool efield = false);
/// Set all pool flags and molecular populations to zero.
void reset(void);
////////////////////////////////////////////////////////////////////////
// DATA ACCESS: GENERAL
////////////////////////////////////////////////////////////////////////
inline steps::solver::Patchdef * patchdef(void) const
{ return pPatchdef; }
inline uint idx(void) const
{ return pIdx; }
////////////////////////////////////////////////////////////////////////
// DATA ACCESS: SHAPE & CONNECTIVITY
////////////////////////////////////////////////////////////////////////
inline double area(void) const
{ return pArea; }
inline stex::WmVol * iTet(void) const
{ return pInnerTet; }
inline stex::WmVol * oTet(void) const
{ return pOuterTet; }
inline stex::Tri * nextTri(uint i) const
{
assert (i < 3);
return pNextTri[i];
}
inline int tri(uint t)
{ return pTris[t]; }
/// Get the length of a boundary bar.
///
inline double length(uint i) const
{ return pLengths[i]; }
/// Get the distance to the centroid of the next neighbouring
/// triangle.
///
inline double dist(uint i) const
{ return pDist[i]; }
inline int tet(uint t) const
{ return pTets[t]; }
////////////////////////////////////////////////////////////////////////
// DATA ACCESS: EFIELD
////////////////////////////////////////////////////////////////////////
// Local index of GHK current given
void incECharge(uint lidx, int charge);
// Should be called at the beginning of every EField time-step
void resetECharge(void);
// reset the Ohmic current opening time integral info, also should be
// called just before commencing or just after completing an EField dt
void resetOCintegrals(void);
double computeI(double v, double dt, double simtime);
double getOhmicI(double v, double dt) const;
double getOhmicI(uint lidx, double v,double dt) const;
double getGHKI( double dt) const;
double getGHKI(uint lidx, double dt) const;
////////////////////////////////////////////////////////////////////////
// MAIN FUNCTIONALITY
////////////////////////////////////////////////////////////////////////
inline uint * pools(void) const
{ return pPoolCount; }
void setCount(uint lidx, uint count);
void incCount(uint lidx, int inc);
static const uint CLAMPED = 1;
inline bool clamped(uint lidx) const
{ return pPoolFlags[lidx] & CLAMPED; }
void setClamped(uint lidx, bool clamp);
// Set a channel state relating to an ohmic current change.
// 0th argument is oc local index, 1st argument is the local index
// of the related channel state
void setOCchange(uint oclidx, uint slidx, double dt, double simtime);
////////////////////////////////////////////////////////////////////////
inline std::vector<stex::KProc *>::const_iterator kprocBegin(void) const
{ return pKProcs.begin(); }
inline std::vector<stex::KProc *>::const_iterator kprocEnd(void) const
{ return pKProcs.end(); }
inline uint countKProcs(void) const
{ return pKProcs.size(); }
stex::SReac * sreac(uint lidx) const;
stex::SDiff * sdiff(uint lidx) const;
stex::VDepTrans * vdeptrans(uint lidx) const;
stex::VDepSReac * vdepsreac(uint lidx) const;
stex::GHKcurr * ghkcurr(uint lidx) const;
////////////////////////////////////////////////////////////////////////
private:
////////////////////////////////////////////////////////////////////////
uint pIdx;
steps::solver::Patchdef * pPatchdef;
/// Pointers to neighbouring tetrahedra.
stex::WmVol * pInnerTet;
stex::WmVol * pOuterTet;
// Indices of two neighbouring tets; -1 if surface triangle (if
// triangle's patch is on the surface of the mesh, quite often the case)
int pTets[2];
// Indices of neighbouring triangles.
int pTris[3];
/// POinters to neighbouring triangles
stex::Tri * pNextTri[3];
double pArea;
// Neighbour information- needed for surface diffusion
double pLengths[3];
double pDist[3];
/// Numbers of molecules -- stored as machine word integers.
uint * pPoolCount;
/// Flags on these pools -- stored as machine word flags.
uint * pPoolFlags;
/// The kinetic processes.
std::vector<stex::KProc *> pKProcs;
/// For the EFIELD calculation. An integer storing the amount of
/// elementary charge from inner tet to outer tet (positive if
/// net flux is positive, negative if net flux is negative) for
/// one EField time-step.
// NOTE: Now arrays so as to separate into different GHK currs,
// for data access
int * pECharge;
// to store the latest ECharge, so that the info is available to solver
int * pECharge_last;
// Store the Ohmic currents' channel's opening information by OC local indices
// and the time since the related channel state changed it's number
// The pOCchan_timeintg stores number of channel open * opening time
// so at the end of the step this number/Efield dt will give the
// mean number of channels open
double * pOCchan_timeintg;
double * pOCtime_upd;
////////////////////////////////////////////////////////////////////////
};
////////////////////////////////////////////////////////////////////////////////
END_NAMESPACE(tetexact)
END_NAMESPACE(steps)
////////////////////////////////////////////////////////////////////////////////
#endif
// STEPS_TETEXACT_TRI_HPP
// END
| gpl-3.0 |
famzim13/CS585 | src/engine/containers/node.cpp | 30 | // node.cpp
#include "node.h"
| gpl-3.0 |
Grumbel/scatterbackup | scatterbackup/fileinfo.py | 6866 | # ScatterBackup - A chaotic backup solution
# Copyright (C) 2015 Ingo Ruhnke <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
import os
import stat
import time
from collections import OrderedDict
from scatterbackup.blobinfo import BlobInfo
class FileInfo:
def __init__(self, path):
self.rowid = None
self.kind = None
self.path = path
self.dev = None # FIXME: this is not stable across reboots
self.ino = None
self.mode = None
self.nlink = None
self.uid = None
self.gid = None
self.rdev = None
self.size = None
self.blksize = None
self.blocks = None
self.atime = None
self.ctime = None
self.mtime = None
self.time = None
self.birth = None
self.death = None
self.blob = None
self.target = None
self.directory_id = None
def __eq__(self, other):
if type(other) is type(self):
return (
self.kind == other.kind and
self.path == other.path and
# dev does not stay permanent across reboots
# self.dev == other.dev and
self.ino == other.ino and
self.mode == other.mode and
self.nlink == other.nlink and
self.uid == other.uid and
self.gid == other.gid and
self.rdev == other.rdev and
self.size == other.size and
self.blksize == other.blksize and
self.blocks == other.blocks and
# atime creates to much bloat in db if each change is recorded
# self.atime == other.atime and
self.ctime == other.ctime and
self.mtime == other.mtime and
# creation time of the FileInfo is not relevant
# self.time == other.time and
self.blob == other.blob and
self.target == other.target)
else:
return False
def to_js_dict(self):
# use OrderedDict to create pretty and deterministic output
js = OrderedDict()
def assign(name, value):
if value is not None:
js[name] = value
assign('type', self.kind)
assign('path', self.path)
assign('dev', self.dev)
assign('ino', self.ino)
assign('mode', self.mode)
assign('nlink', self.nlink)
assign('uid', self.uid)
assign('gid', self.gid)
assign('rdev', self.rdev)
assign('size', self.size)
assign('blksize', self.blksize)
assign('blocks', self.blocks)
assign('atime', self.atime)
assign('ctime', self.ctime)
assign('mtime', self.mtime)
if self.blob is not None:
js['blob'] = OrderedDict([('size', self.size)])
if self.blob.sha1 is not None:
js['blob']['sha1'] = self.blob.sha1
if self.blob.md5 is not None:
js['blob']['md5'] = self.blob.md5
if self.blob.crc32 is not None:
js['blob']['crc32'] = self.blob.crc32
assign('target', self.target)
assign('time', self.time)
return js
def json(self):
js = self.to_js_dict()
return json.dumps(js)
def calc_checksums(self):
statinfo = os.lstat(self.path)
if stat.S_ISREG(statinfo.st_mode):
self.blob = BlobInfo.from_file(self.path)
@staticmethod
def from_file(path, checksums=True, relative=False):
abspath = path if relative else os.path.abspath(path)
result = FileInfo(abspath)
statinfo = os.lstat(path)
m = statinfo.st_mode
if stat.S_ISREG(m):
result.kind = "file"
elif stat.S_ISDIR(m):
result.kind = "directory"
elif stat.S_ISCHR(m):
result.kind = "chardev"
elif stat.S_ISBLK(m):
result.kind = "blockdev"
elif stat.S_ISFIFO(m):
result.kind = "fifo"
elif stat.S_ISLNK(m):
result.kind = "link"
elif stat.S_ISSOCK(m):
result.kind = "socket"
else:
result.kind = "unknown"
result.dev = statinfo.st_dev
result.ino = statinfo.st_ino
result.mode = statinfo.st_mode
result.nlink = statinfo.st_nlink
result.uid = statinfo.st_uid
result.gid = statinfo.st_gid
result.rdev = statinfo.st_rdev
result.size = statinfo.st_size
result.blksize = statinfo.st_blksize
result.blocks = statinfo.st_blocks
result.atime = statinfo.st_atime_ns
result.ctime = statinfo.st_ctime_ns
result.mtime = statinfo.st_mtime_ns
result.time = int(round(time.time() * 1000000000))
if stat.S_ISREG(statinfo.st_mode) and checksums:
result.blob = BlobInfo.from_file(abspath)
elif stat.S_ISLNK(statinfo.st_mode):
result.target = os.readlink(abspath)
return result
@staticmethod
def from_json(text):
js = json.loads(text)
path = js.get('path')
result = FileInfo(path)
result.kind = js.get('type')
result.dev = js.get('dev')
result.ino = js.get('ino')
result.mode = js.get('mode')
result.nlink = js.get('nlink')
result.uid = js.get('uid')
result.gid = js.get('gid')
result.rdev = js.get('rdev')
result.size = js.get('size')
result.blksize = js.get('blksize')
result.blocks = js.get('blocks')
result.atime = js.get('atime')
result.ctime = js.get('ctime')
result.mtime = js.get('mtime')
result.time = js.get('time')
blob = js.get('blob')
if blob is not None:
result.blob = BlobInfo(blob.get('size'),
md5=blob.get('md5'),
sha1=blob.get('sha1'),
crc32=blob.get('crc32'))
result.target = js.get('target')
return result
def __repr__(self):
return "FileInfo({!r})".format(self.path)
# EOF #
| gpl-3.0 |
XMGmen/zentao | search/view/buildform.html.php | 16230 | <?php
/**
* The buildform view of search module of ZenTaoPMS.
*
* @copyright Copyright 2009-2015 青岛易软天创网络科技有限公司(QingDao Nature Easy Soft Network Technology Co,LTD, www.cnezsoft.com)
* @license ZPL (http://zpl.pub/page/zplv11.html)
* @author Chunsheng Wang <[email protected]>
* @package search
* @version $Id: buildform.html.php 4129 2013-01-18 01:58:14Z wwccss $
* @link http://www.zentao.net
*/
?>
<?php
$jsRoot = $this->app->getWebRoot() . "js/";
include '../../common/view/datepicker.html.php';
?>
<style>
#bysearchTab {transition: all .3s cubic-bezier(.175, .885, .32, 1);}
#bysearchTab.active {background: #fff; padding: 2px 10px 3px; padding-bottom: 2px\0; border: 1px solid #ddd; border-bottom: none}
#bysearchTab.active:hover {background: #ddd}
#bysearchTab.active > a:after {font-size: 14px; font-family: ZenIcon; content: ' \e6e2'; color: #808080}
#featurebar .nav {z-index: 999; position: relative;}
#querybox form{padding-right: 40px;}
#querybox .form-control {padding: 2px; padding: 6px 2px\0;}
@-moz-document url-prefix() {#querybox .form-control {padding: 6px 2px;}}
#querybox .table {border: none}
#querybox .table-form td {border: none}
#querybox .btn {padding: 5px 8px;}
#querybox .table-form td td {padding: 2px;}
#querybox .table .table {margin: 0;}
.outer #querybox .table tr > th:first-child, .outer #querybox .table tr > td:first-child,
.outer #querybox .table tr > th:last-child, .outer #querybox .table tr > td:last-child,
.outer #querybox .table tbody > tr:last-child td {padding: 2px}
#querybox a:hover {text-decoration: none;}
#selectPeriod {padding: 4px; height: 197px; min-width: 120px}
#selectPeriod > .dropdown-header {background: #f1f1f1; display: block; text-align: center; padding: 4px 0; line-height: 20px; margin-bottom: 5px; font-size: 14px; border-radius: 2px; color: #333; font-size: 12px}
#selectPeriod li > a {padding: 4px 15px; border-radius: 2px}
#moreOrLite {position: absolute; right: 0; top: 0; bottom: 0}
#searchlite, #searchmore {/*color: #4d90fe; changed by xufangye*/width: 50px; padding: 0 5px; line-height: 70px; text-align: center;}
#searchlite {line-height: 127px}
#searchform.showmore #searchmore, #searchform #searchlite {display: none;}
#searchform.showmore #searchlite, #searchform #searchmore {display: inline-block;}
#searchmore > i, #searchlite > i {font-size: 28px;}
#searchmore:hover, #searchlite:hover {color: #145CCD; background: #e5e5e5}
.bootbox-prompt .modal-dialog {width: 500px; margin-top: 10%;}
#groupAndOr {display: inline-block;}
.outer > #querybox {margin: -20px -20px 20px; border-top: none; border-bottom: 1px solid #ddd}
</style>
<script language='Javascript'>
var dtOptions =
{
language: '<?php echo $this->app->getClientLang();?>',
weekStart: 1,
todayBtn: 1,
autoclose: 1,
todayHighlight: 1,
startView: 2,
minView: 2,
forceParse: 0,
format: 'yyyy-mm-dd'
};
$(function()
{
$('.date').each(function()
{
time = $(this).val();
if(!isNaN(time) && time != ''){
var Y = time.substring(0, 4);
var m = time.substring(4, 6);
var d = time.substring(6, 8);
time = Y + '-' + m + '-' + d;
$('.date').val(time);
}
});
setDateField('.date');
});
var <?php echo $module . 'params'?> = <?php echo empty($fieldParams) ? '{}' : json_encode($fieldParams);?>;
var groupItems = <?php echo $config->search->groupItems;?>;
var setQueryTitle = '<?php echo $lang->search->setQueryTitle;?>';
var module = '<?php echo $module;?>';
var actionURL = '<?php echo $actionURL;?>';
/**
* Set date field
*
* @param string $query
* @return void
*/
function setDateField(query, fieldNO)
{
var $period = $('#selectPeriod');
if(!$period.length)
{
$period = $("<ul id='selectPeriod' class='dropdown-menu'><li class='dropdown-header'><?php echo $lang->datepicker->dpText->TEXT_OR . ' ' . $lang->datepicker->dpText->TEXT_DATE;?></li><li><a href='#lastWeek'><?php echo $lang->datepicker->dpText->TEXT_PREV_WEEK;?></a></li><li><a href='#thisWeek'><?php echo $lang->datepicker->dpText->TEXT_THIS_WEEK;?></a></li><li><a href='#yesterday'><?php echo $lang->datepicker->dpText->TEXT_YESTERDAY;?></a></li><li><a href='#today'><?php echo $lang->datepicker->dpText->TEXT_TODAY;?></a></li><li><a href='#lastMonth'><?php echo $lang->datepicker->dpText->TEXT_PREV_MONTH;?></a></li><li><a href='#thisMonth'><?php echo $lang->datepicker->dpText->TEXT_THIS_MONTH;?></a></li></ul>").appendTo('body');
$period.find('li > a').click(function(event)
{
var target = $(query).parents('form').find('#' + $period.data('target'));
if(target.length)
{
target.val($(this).attr('href').replace('#', '$'));
$(query).parents('form').find('#operator' + $period.data('fieldNO')).val('between');
$period.hide();
}
event.stopPropagation();
return false;
});
}
$(query).datetimepicker('remove').datetimepicker(dtOptions).on('show', function(e)
{
var $e = $(e.target);
var ePos = $e.offset();
$period.css({'left': ePos.left + 175, 'top': ePos.top + 29, 'min-height': $('.datetimepicker').outerHeight()}).show().data('target', $e.attr('id')).data('fieldNO', fieldNO).find('li.active').removeClass('active');
$period.find("li > a[href='" + $e.val().replace('$', '#') + "']").closest('li').addClass('active');
}).on('changeDate', function()
{
var opt = $(query).parents('form').find('#operator' + $period.data('fieldNO'));
if(opt.val() == 'between') opt.val('<=');
$period.hide();
}).on('hide', function(){setTimeout(function(){$period.hide();}, 200);});
}
/**
* When the value of the fields select changed, set the operator and value of the new field.
*
* @param string $obj
* @param int $fieldNO
* @access public
* @return void
*/
function setField(obj, fieldNO, moduleparams)
{
var params = moduleparams;
var fieldName = $(obj).val();
$(obj).parents('form').find('#operator' + fieldNO).val(params[fieldName]['operator']); // Set the operator according the param setting.
$(obj).parents('form').find('#valueBox' + fieldNO).html($(obj).parents('form').find('#box' + fieldName).children().clone());
$(obj).parents('form').find('#valueBox' + fieldNO).children().attr({name : 'value' + fieldNO, id : 'value' + fieldNO});
if(typeof(params[fieldName]['class']) != undefined && params[fieldName]['class'] == 'date')
{
setDateField($(obj).parents('form').find("#value" + fieldNO), fieldNO);
$(obj).parents('form').find("#value" + fieldNO).addClass('date'); // Shortcut the width of the datepicker to make sure align with others.
var groupItems = <?php echo $config->search->groupItems?>;
var maxNO = 2 * groupItems;
var nextNO = fieldNO > groupItems ? fieldNO - groupItems + 1 : fieldNO + groupItems;
var nextValue = $(obj).parents('form').find('#value' + nextNO).val();
if(nextNO <= maxNO && fieldNO < maxNO && (nextValue == '' || nextValue == 0))
{
$(obj).parents('form').find('#field' + nextNO).val($(obj).parents('form').find('#field' + fieldNO).val());
$(obj).parents('form').find('#operator' + nextNO).val('<=');
$(obj).parents('form').find('#valueBox' + nextNO).html($(obj).parents('form').find('#box' + fieldName).children().clone());
$(obj).parents('form').find('#valueBox' + nextNO).children().attr({name : 'value' + nextNO, id : 'value' + nextNO});
setDateField($(obj).parents('form').find("#value" + nextNO), nextNO);
$(obj).parents('form').find("#value" + nextNO).addClass('date');
}
}
}
/**
* Reset forms.
*
* @access public
* @return void
*/
function resetForm(obj)
{
for(i = 1; i <= groupItems * 2; i ++)
{
$(obj).parents('form').find('#value' + i).val('');
}
}
/**
* Show more fields.
*
* @access public
* @return void
*/
function showmore(obj)
{
for(i = 1; i <= groupItems * 2; i ++)
{
if(i != 1 && i != groupItems + 1 )
{
$(obj).parents('form').find('#searchbox' + i).removeClass('hidden');
}
}
$(obj).parents('form').find('#formType').val('more');
$(obj).parents('form').addClass('showmore');
}
/**
* Show lite search form.
*
* @access public
* @return void
*/
function showlite(obj)
{
for(i = 1; i <= groupItems * 2; i ++)
{
if(i != 1 && i != groupItems + 1)
{
$(obj).parents('form').find('#value' + i).val('');
$(obj).parents('form').find('#searchbox' + i).addClass('hidden');
}
}
$(obj).parents('form').removeClass('showmore');
$(obj).parents('form').find('#formType').val('lite');
}
/**
* Save the query.
*
* @access public
* @return void
*/
function saveQuery()
{
bootbox.prompt(setQueryTitle, function(r)
{
if(!r) return;
saveQueryLink = createLink('search', 'saveQuery');
$.post(saveQueryLink, {title: r, module: module}, function(data)
{
if(data == 'success') location.reload();
});
});
}
/**
* Execute a query.
*
* @param int $queryID
* @access public
* @return void
*/
function executeQuery(queryID)
{
if(!queryID) return;
location.href = actionURL.replace('myQueryID', queryID);
}
/**
* Delete a query.
*
* @access public
* @return void
*/
function deleteQuery()
{
queryID = $('#queryID').val();
if(!queryID) return;
hiddenwin.location.href = createLink('search', 'deleteQuery', 'queryID=' + queryID);
}
</script>
<form method='post' action='<?php echo $this->createLink('search', 'buildQuery');?>' target='hiddenwin' id='searchform' class='form-condensed'>
<div class='hidden'>
<?php
/* Print every field as an html object, select or input. Thus when setFiled is called, copy it's html to build the search form. */
foreach($fieldParams as $fieldName => $param)
{
echo "<span id='box$fieldName'>";
if($param['control'] == 'select') echo html::select($fieldName, $param['values'], '', "class='form-control searchSelect'");
if($param['control'] == 'input') echo html::input($fieldName, '', "class='form-control searchInput'");
echo '</span>';
}
?>
</div>
<table class='table table-condensed table-form' id='<?php echo "{$module}-search";?>' style='max-width: 1200px; margin: 0 auto'>
<tr>
<td class='w-400px'>
<table class='table active-disabled'>
<?php
$formSessionName = $module . 'Form';
$formSession = $this->session->$formSessionName;
$fieldNO = 1;
for($i = 1; $i <= $groupItems; $i ++)
{
$spanClass = $i == 1 ? '' : 'hidden';
echo "<tr id='searchbox$fieldNO' class='$spanClass'>";
/* Get params of current field. */
$currentField = $formSession["field$fieldNO"];
$param = $fieldParams[$currentField];
/* Print and or. */
echo "<td class='text-right w-60px'>";
if($i == 1) echo "<span id='searchgroup1'><strong>{$lang->search->group1}</strong></span>" . html::hidden("andOr$fieldNO", 'AND');
if($i > 1) echo html::select("andOr$fieldNO", $lang->search->andor, $formSession["andOr$fieldNO"], "class='form-control'");
echo '</td>';
/* Print field. */
echo "<td class='w-90px'>" . html::select("field$fieldNO", $searchFields, $formSession["field$fieldNO"], "onchange='setField(this, $fieldNO, {$module}params)' class='form-control'") . '</td>';
/* Print operator. */
echo "<td class='w-70px'>" . html::select("operator$fieldNO", $lang->search->operators, $formSession["operator$fieldNO"], "class='form-control'") . '</td>';
/* Print value. */
echo "<td id='valueBox$fieldNO'>";
if($param['control'] == 'select') echo html::select("value$fieldNO", $param['values'], $formSession["value$fieldNO"], "class='form-control searchSelect'");
if($param['control'] == 'input')
{
$fieldName = $formSession["field$fieldNO"];
$extraClass = isset($param['class']) ? $param['class'] : '';
echo html::input("value$fieldNO", $formSession["value$fieldNO"], "class='form-control $extraClass searchInput'");
}
echo '</td>';
$fieldNO ++;
echo '</tr>';
}
?>
</table>
</td>
<td class='text-center nobr'><?php echo html::select('groupAndOr', $lang->search->andor, $formSession['groupAndOr'], "class='form-control w-60px'")?></td>
<td class='w-400px'>
<table class='table active-disabled'>
<?php
for($i = 1; $i <= $groupItems; $i ++)
{
$spanClass = $i == 1 ? '' : 'hidden';
echo "<tr id='searchbox$fieldNO' class='$spanClass'>";
/* Get params of current field. */
$currentField = $formSession["field$fieldNO"];
$param = $fieldParams[$currentField];
/* Print and or. */
echo "<td class='text-right w-60px'>";
if($i == 1) echo "<span id='searchgroup2'><strong>{$lang->search->group2}</strong></span>" . html::hidden("andOr$fieldNO", 'AND');
if($i > 1) echo html::select("andOr$fieldNO", $lang->search->andor, $formSession["andOr$fieldNO"], "class='form-control'");
echo '</td>';
/* Print field. */
echo "<td class='w-90px'>" . html::select("field$fieldNO", $searchFields, $formSession["field$fieldNO"], "onchange='setField(this, $fieldNO, {$module}params)' class='form-control'") . '</td>';
/* Print operator. */
echo "<td class='w-70px'>" . html::select("operator$fieldNO", $lang->search->operators, $formSession["operator$fieldNO"], "class='form-control'") . '</td>';
/* Print value. */
echo "<td id='valueBox$fieldNO'>";
if($param['control'] == 'select') echo html::select("value$fieldNO", $param['values'], $formSession["value$fieldNO"], "class='form-control searchSelect'");
if($param['control'] == 'input')
{
$fieldName = $formSession["field$fieldNO"];
$extraClass = isset($param['class']) ? $param['class'] : '';
echo html::input("value$fieldNO", $formSession["value$fieldNO"], "class='form-control $extraClass searchInput'");
}
echo '</td>';
$fieldNO ++;
echo '</tr>';
}
?>
</table>
</td>
<td class='<?php echo $style == 'simple' ? 'w-60px' : 'w-150px'?>'>
<?php
echo html::hidden('module', $module);
echo html::hidden('actionURL', $actionURL);
echo html::hidden('groupItems', $groupItems);
echo "<div class='btn-group'>";
echo html::submitButton($lang->search->common, '', 'btn-primary');
if($style != 'simple')
{
echo html::commonButton($lang->search->reset, 'onclick=resetForm(this) class=btn');
echo html::commonButton($lang->save, 'onclick=saveQuery() class=btn');
}
echo '</div>';
?>
</td>
<?php if($style != 'simple'):?>
<td class='w-120px'>
<div class='input-group'>
<?php
echo html::select('queryID', $queries, $queryID, 'onchange=executeQuery(this.value) class=form-control');
if(common::hasPriv('search', 'deleteQuery')) echo "<span class='input-group-btn'>" . html::a('javascript:deleteQuery()', '<i class="icon-remove"></i>', '', 'class=btn') . '</span>';
?>
</div>
</td>
<?php endif;?>
</tr>
</table>
<div id='moreOrLite'>
<a id="searchmore" href="javascript:;" onclick="showmore(this)"><i class="icon-double-angle-down icon-2x"></i></a>
<a id="searchlite" href="javascript:;" onclick="showlite(this)"><i class="icon-double-angle-up icon-2x"></i></a>
<?php echo html::hidden('formType', 'lite');?>
</div>
</form>
<script language='Javascript'>
<?php if(isset($formSession['formType'])) echo "show{$formSession['formType']}('#{$module}-search')";?>
</script>
| gpl-3.0 |
h4ck3rm1k3/ansible | v2/ansible/executor/module_common.py | 7421 | # (c) 2013-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# from python and deps
from cStringIO import StringIO
import inspect
import json
import os
import shlex
# from Ansible
from ansible import __version__
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.parsing.utils.jsonify import jsonify
REPLACER = "#<<INCLUDE_ANSIBLE_MODULE_COMMON>>"
REPLACER_ARGS = "\"<<INCLUDE_ANSIBLE_MODULE_ARGS>>\""
REPLACER_COMPLEX = "\"<<INCLUDE_ANSIBLE_MODULE_COMPLEX_ARGS>>\""
REPLACER_WINDOWS = "# POWERSHELL_COMMON"
REPLACER_VERSION = "\"<<ANSIBLE_VERSION>>\""
class ModuleReplacer(object):
"""
The Replacer is used to insert chunks of code into modules before
transfer. Rather than doing classical python imports, this allows for more
efficient transfer in a no-bootstrapping scenario by not moving extra files
over the wire, and also takes care of embedding arguments in the transferred
modules.
This version is done in such a way that local imports can still be
used in the module code, so IDEs don't have to be aware of what is going on.
Example:
from ansible.module_utils.basic import *
... will result in the insertion basic.py into the module
from the module_utils/ directory in the source tree.
All modules are required to import at least basic, though there will also
be other snippets.
# POWERSHELL_COMMON
Also results in the inclusion of the common code in powershell.ps1
"""
# ******************************************************************************
def __init__(self, strip_comments=False):
# FIXME: these members need to be prefixed with '_' and the rest of the file fixed
this_file = inspect.getfile(inspect.currentframe())
# we've moved the module_common relative to the snippets, so fix the path
self.snippet_path = os.path.join(os.path.dirname(this_file), '..', 'module_utils')
self.strip_comments = strip_comments
# ******************************************************************************
def slurp(self, path):
if not os.path.exists(path):
raise AnsibleError("imported module support code does not exist at %s" % path)
fd = open(path)
data = fd.read()
fd.close()
return data
def _find_snippet_imports(self, module_data, module_path):
"""
Given the source of the module, convert it to a Jinja2 template to insert
module code and return whether it's a new or old style module.
"""
module_style = 'old'
if REPLACER in module_data:
module_style = 'new'
elif 'from ansible.module_utils.' in module_data:
module_style = 'new'
elif 'WANT_JSON' in module_data:
module_style = 'non_native_want_json'
output = StringIO()
lines = module_data.split('\n')
snippet_names = []
for line in lines:
if REPLACER in line:
output.write(self.slurp(os.path.join(self.snippet_path, "basic.py")))
snippet_names.append('basic')
if REPLACER_WINDOWS in line:
ps_data = self.slurp(os.path.join(self.snippet_path, "powershell.ps1"))
output.write(ps_data)
snippet_names.append('powershell')
elif line.startswith('from ansible.module_utils.'):
tokens=line.split(".")
import_error = False
if len(tokens) != 3:
import_error = True
if " import *" not in line:
import_error = True
if import_error:
raise AnsibleError("error importing module in %s, expecting format like 'from ansible.module_utils.basic import *'" % module_path)
snippet_name = tokens[2].split()[0]
snippet_names.append(snippet_name)
output.write(self.slurp(os.path.join(self.snippet_path, snippet_name + ".py")))
else:
if self.strip_comments and line.startswith("#") or line == '':
pass
output.write(line)
output.write("\n")
if not module_path.endswith(".ps1"):
# Unixy modules
if len(snippet_names) > 0 and not 'basic' in snippet_names:
raise AnsibleError("missing required import in %s: from ansible.module_utils.basic import *" % module_path)
else:
# Windows modules
if len(snippet_names) > 0 and not 'powershell' in snippet_names:
raise AnsibleError("missing required import in %s: # POWERSHELL_COMMON" % module_path)
return (output.getvalue(), module_style)
# ******************************************************************************
def modify_module(self, module_path, module_args):
with open(module_path) as f:
# read in the module source
module_data = f.read()
(module_data, module_style) = self._find_snippet_imports(module_data, module_path)
#module_args_json = jsonify(module_args)
module_args_json = json.dumps(module_args)
encoded_args = repr(module_args_json.encode('utf-8'))
# these strings should be part of the 'basic' snippet which is required to be included
module_data = module_data.replace(REPLACER_VERSION, repr(__version__))
module_data = module_data.replace(REPLACER_COMPLEX, encoded_args)
# FIXME: we're not passing around an inject dictionary anymore, so
# this needs to be fixed with whatever method we use for vars
# like this moving forward
#if module_style == 'new':
# facility = C.DEFAULT_SYSLOG_FACILITY
# if 'ansible_syslog_facility' in inject:
# facility = inject['ansible_syslog_facility']
# module_data = module_data.replace('syslog.LOG_USER', "syslog.%s" % facility)
lines = module_data.split("\n")
shebang = None
if lines[0].startswith("#!"):
shebang = lines[0].strip()
args = shlex.split(str(shebang[2:]))
interpreter = args[0]
interpreter_config = 'ansible_%s_interpreter' % os.path.basename(interpreter)
# FIXME: more inject stuff here...
#if interpreter_config in inject:
# lines[0] = shebang = "#!%s %s" % (inject[interpreter_config], " ".join(args[1:]))
# module_data = "\n".join(lines)
return (module_data, module_style, shebang)
| gpl-3.0 |
VictorPisciotti/Asistente-Lucy | Speech Lucy/Bluetooth-Demo/Bluetooth-Demo/Window1.xaml.cs | 5079 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using InTheHand.Net;
using System.Threading;
namespace Bluetooth_Demo
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
BackgroundWorker bg;
BackgroundWorker bg_send;
public Window1()
{
InitializeComponent();
bg = new BackgroundWorker();
bg_send = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
bg_send.DoWork += new DoWorkEventHandler(bg_send_DoWork);
bg_send.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_send_RunWorkerCompleted);
}
void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
device_list.ItemsSource = (List<Device>)e.Result;
pb.Visibility = Visibility.Hidden;
btn_find.IsEnabled = true;
}
void bg_DoWork(object sender, DoWorkEventArgs e)
{
List<Device> devices = new List<Device>();
InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient();
InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices();
for (int i = 0; i < array.Length; i++)
{
Device device = new Device(array[i]);
devices.Add(device);
}
e.Result = devices;
}
private void btn_find_Click(object sender, RoutedEventArgs e)
{
if (!bg.IsBusy)
{
btn_find.IsEnabled = false;
pb.Visibility = Visibility.Visible;
bg.RunWorkerAsync();
}
}
private void device_list_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (device_list.SelectedItem != null)
{
Device device = (Device)device_list.SelectedItem;
txt_authenticated.Text = device.Authenticated.ToString();
txt_connected.Text = device.Connected.ToString();
txt_devicename.Text = device.DeviceName;
txt_lastseen.Text = device.LastSeen.ToString();
txt_lastused.Text = device.LastUsed.ToString();
txt_nap.Text = device.Nap.ToString();
txt_remembered.Text = device.Remembered.ToString();
txt_sap.Text = device.Sap.ToString();
}
}
public string FilePath { get; set; }
private void btn_browse_Click(object sender, RoutedEventArgs e)//Solo sirve para habilitar el boton de enviar en este caso
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "File To Send";
dlg.DefaultExt = "*.*";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
FilePath = dlg.FileName;
btn_send.IsEnabled = true;
lbRuta.Content = FilePath;
}
else
btn_send.IsEnabled = false;
}
void bg_send_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)//Respuesta del cliente
{
if (e.Result != null)
{
ObexStatusCode status = (ObexStatusCode)e.Result;
MessageBox.Show("Estado del envio de archivos - " + status.ToString(), "Enviando archivos", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
void bg_send_DoWork(object sender, DoWorkEventArgs e)//Envio de datos desde el servidor
{
string texto = "Hola mundo";
Device device = (Device)e.Argument;
//Sirve para enviar string o bytes
ObexStatusCode envio = SendModule.SendFile(device.DeviceInfo, texto);
e.Result = envio;
//Sirve para enviar archivos
//ObexStatusCode response_status = SendModule.SendFile(device.DeviceInfo, FilePath);
//e.Result = response_status;
}
private void btn_send_Click(object sender, RoutedEventArgs e)
{
if (!bg_send.IsBusy && device_list.SelectedItem != null && !string.IsNullOrEmpty(FilePath))
{
Device device = (Device)device_list.SelectedItem;
bg_send.RunWorkerAsync(device);
}
}
}
}
| gpl-3.0 |
openqt/algorithms | projecteuler/pe482-the-incenter-of-a-triangle.py | 370 | #!/usr/bin/env python
# coding=utf-8
"""482. The incenter of a triangle
https://projecteuler.net/problem=482
ABC is an integer sided triangle with incenter I and perimeter p.
The segments IA, IB and IC have integral length as well.
Let L = p + |IA| + |IB| + |IC|.
Let S(P) = ∑L for all such triangles where p ≤ P. For example, S(103) = 3619.
Find S(107).
"""
| gpl-3.0 |
OgarioProject/Ogar2-Server | src/main/java/com/ogarproject/ogar/server/util/thread/RunnableImpl.java | 1349 | /**
* This file is part of Ogar.
*
* Ogar 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.
*
* Ogar 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 Ogar. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ogarproject.ogar.server.util.thread;
import org.apache.log4j.Logger;
/**
* @author VISTALL
* @date 19:13/04.04.2011
*/
public abstract class RunnableImpl implements Runnable
{
private static final Logger _log = Logger.getLogger(RunnableImpl.class);
protected abstract void runImpl() throws Exception;
@Override
public final void run()
{
try
{
runImpl();
}
catch(Exception e)
{
_log.error("Exception: RunnableImpl.run():", e);
e.printStackTrace();
}
}
} | gpl-3.0 |
kidsfm/cms | schedule/migrations/0005_auto_20170314_1035.py | 1492 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-14 14:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedule', '0004_auto_20170309_1040'),
]
operations = [
migrations.CreateModel(
name='Slot',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start_time', models.TimeField()),
('end_time', models.TimeField()),
('start_date', models.DateField()),
('end_date', models.DateField()),
('day', models.ManyToManyField(to='schedule.Day')),
],
),
migrations.RemoveField(
model_name='program',
name='end_date',
),
migrations.RemoveField(
model_name='program',
name='end_time',
),
migrations.RemoveField(
model_name='program',
name='frequency',
),
migrations.RemoveField(
model_name='program',
name='start_date',
),
migrations.RemoveField(
model_name='program',
name='start_time',
),
migrations.AddField(
model_name='program',
name='time_slots',
field=models.ManyToManyField(to='schedule.Slot'),
),
]
| gpl-3.0 |
aci2n/isms | Common/src/isms/models/ThresholdType.java | 232 | package isms.models;
public enum ThresholdType {
WARNING(10),
DANGER(20),
CRITICAL(30);
private int priority;
ThresholdType(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
}
| gpl-3.0 |
Chase22/Disgaea-Multiverse | Disgaea-Multiverse/src/main/java/org/disgea/data/character/Resistances.java | 2164 | package org.disgea.data.character;
public class Resistances {
private int sword;
private int spear;
private int axe;
private int fist;
private int staff;
private int gun;
private int bow;
private int monstera;
private int monsterb;
private int heat;
private int cold;
private int wind;
private int earth;
private int lightning;
private int lux;
private int r_void;
public int getSword() {
return sword;
}
public void setSword(int sword) {
this.sword = sword;
}
public int getSpear() {
return spear;
}
public void setSpear(int spear) {
this.spear = spear;
}
public int getAxe() {
return axe;
}
public void setAxe(int axe) {
this.axe = axe;
}
public int getFist() {
return fist;
}
public void setFist(int fist) {
this.fist = fist;
}
public int getStaff() {
return staff;
}
public void setStaff(int staff) {
this.staff = staff;
}
public int getGun() {
return gun;
}
public void setGun(int gun) {
this.gun = gun;
}
public int getBow() {
return bow;
}
public void setBow(int bow) {
this.bow = bow;
}
public int getMonstera() {
return monstera;
}
public void setMonstera(int monstera) {
this.monstera = monstera;
}
public int getMonsterb() {
return monsterb;
}
public void setMonsterb(int monsterb) {
this.monsterb = monsterb;
}
public int getHeat() {
return heat;
}
public void setHeat(int heat) {
this.heat = heat;
}
public int getCold() {
return cold;
}
public void setCold(int cold) {
this.cold = cold;
}
public int getWind() {
return wind;
}
public void setWind(int wind) {
this.wind = wind;
}
public int getEarth() {
return earth;
}
public void setEarth(int earth) {
this.earth = earth;
}
public int getLightning() {
return lightning;
}
public void setLightning(int lightning) {
this.lightning = lightning;
}
public int getLux() {
return lux;
}
public void setLux(int lux) {
this.lux = lux;
}
public int getR_void() {
return r_void;
}
public void setR_void(int r_void) {
this.r_void = r_void;
}
}
| gpl-3.0 |
OPM/ResInsight | ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogPlotCollection.cpp | 10863 | /////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2015- Statoil ASA
// Copyright (C) 2015- Ceetron Solutions AS
//
// ResInsight 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.
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RimWellLogPlotCollection.h"
#include "RiaGuiApplication.h"
#include "RiuPlotMainWindow.h"
#include "RigEclipseWellLogExtractor.h"
#include "RigGeoMechCaseData.h"
#include "RigGeoMechWellLogExtractor.h"
#include "RimEclipseCase.h"
#include "RimGeoMechCase.h"
#include "RimProject.h"
#include "RimWellLogPlot.h"
#include "RimWellPath.h"
#include "RimWellPathCollection.h"
#include "cafPdmFieldScriptingCapability.h"
#include "cafPdmObjectScriptingCapability.h"
#include "cvfAssert.h"
CAF_PDM_SOURCE_INIT( RimWellLogPlotCollection, "WellLogPlotCollection" );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimWellLogPlotCollection::RimWellLogPlotCollection()
{
CAF_PDM_InitScriptableObject( "Well Log Plots", ":/WellLogPlots16x16.png" );
CAF_PDM_InitScriptableFieldNoDefault( &m_wellLogPlots, "WellLogPlots", "" );
m_wellLogPlots.uiCapability()->setUiTreeHidden( true );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimWellLogPlotCollection::~RimWellLogPlotCollection()
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigEclipseWellLogExtractor* RimWellLogPlotCollection::findOrCreateSimWellExtractor( const QString& simWellName,
const QString& caseUserDescription,
const RigWellPath* wellPathGeometry,
const RigEclipseCaseData* eclCaseData )
{
if ( !( wellPathGeometry && eclCaseData ) ) return nullptr;
for ( size_t exIdx = 0; exIdx < m_extractors.size(); ++exIdx )
{
if ( m_extractors[exIdx]->caseData() == eclCaseData && m_extractors[exIdx]->wellPathGeometry() == wellPathGeometry )
{
return m_extractors[exIdx].p();
}
}
std::string errorIdName = ( simWellName + " " + caseUserDescription ).toStdString();
cvf::ref<RigEclipseWellLogExtractor> extractor =
new RigEclipseWellLogExtractor( eclCaseData, wellPathGeometry, errorIdName );
m_extractors.push_back( extractor.p() );
return extractor.p();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigEclipseWellLogExtractor* RimWellLogPlotCollection::findOrCreateExtractor( RimWellPath* wellPath, RimEclipseCase* eclCase )
{
if ( !( wellPath && eclCase ) ) return nullptr;
RigEclipseCaseData* eclCaseData = eclCase->eclipseCaseData();
auto wellPathGeometry = wellPath->wellPathGeometry();
if ( !( eclCaseData && wellPathGeometry ) ) return nullptr;
for ( size_t exIdx = 0; exIdx < m_extractors.size(); ++exIdx )
{
if ( m_extractors[exIdx]->caseData() == eclCaseData && m_extractors[exIdx]->wellPathGeometry() == wellPathGeometry )
{
return m_extractors[exIdx].p();
}
}
std::string errorIdName = ( wellPath->name() + " " + eclCase->caseUserDescription() ).toStdString();
cvf::ref<RigEclipseWellLogExtractor> extractor =
new RigEclipseWellLogExtractor( eclCaseData, wellPathGeometry, errorIdName );
m_extractors.push_back( extractor.p() );
return extractor.p();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigGeoMechWellLogExtractor* RimWellLogPlotCollection::findOrCreateExtractor( RimWellPath* wellPath,
RimGeoMechCase* geoMechCase )
{
if ( !( wellPath && geoMechCase ) ) return nullptr;
RigGeoMechCaseData* caseData = geoMechCase->geoMechData();
auto wellPathGeometry = wellPath->wellPathGeometry();
if ( !( caseData && wellPathGeometry ) ) return nullptr;
for ( size_t exIdx = 0; exIdx < m_geomExtractors.size(); ++exIdx )
{
if ( m_geomExtractors[exIdx]->caseData() == caseData &&
m_geomExtractors[exIdx]->wellPathGeometry() == wellPathGeometry )
{
return m_geomExtractors[exIdx].p();
}
}
std::string errorIdName = ( wellPath->name() + " " + geoMechCase->caseUserDescription() ).toStdString();
cvf::ref<RigGeoMechWellLogExtractor> extractor =
new RigGeoMechWellLogExtractor( caseData, wellPathGeometry, errorIdName );
m_geomExtractors.push_back( extractor.p() );
return extractor.p();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<RimWellLogPlot*> RimWellLogPlotCollection::wellLogPlots() const
{
return m_wellLogPlots.childObjects();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellLogPlotCollection::addWellLogPlot( gsl::not_null<RimWellLogPlot*> wellLogPlot )
{
m_wellLogPlots.push_back( wellLogPlot );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellLogPlotCollection::deleteAllPlots()
{
m_wellLogPlots.deleteAllChildObjects();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellLogPlotCollection::removePlot( gsl::not_null<RimWellLogPlot*> plot )
{
m_wellLogPlots.removeChildObject( plot );
updateAllRequiredEditors();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellLogPlotCollection::loadDataAndUpdateAllPlots()
{
for ( const auto& w : m_wellLogPlots() )
{
w->loadDataAndUpdate();
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellLogPlotCollection::deleteAllExtractors()
{
m_extractors.clear();
m_geomExtractors.clear();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellLogPlotCollection::removeExtractors( const RigWellPath* wellPathGeometry )
{
for ( int eIdx = (int)m_extractors.size() - 1; eIdx >= 0; eIdx-- )
{
if ( m_extractors[eIdx]->wellPathGeometry() == wellPathGeometry )
{
m_extractors.eraseAt( eIdx );
}
}
for ( int eIdx = (int)m_geomExtractors.size() - 1; eIdx >= 0; eIdx-- )
{
if ( m_geomExtractors[eIdx]->wellPathGeometry() == wellPathGeometry )
{
m_geomExtractors.eraseAt( eIdx );
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellLogPlotCollection::removeExtractors( const RigEclipseCaseData* caseData )
{
for ( int eIdx = (int)m_extractors.size() - 1; eIdx >= 0; eIdx-- )
{
if ( m_extractors[eIdx]->caseData() == caseData )
{
m_extractors.eraseAt( eIdx );
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellLogPlotCollection::removeExtractors( const RigGeoMechCaseData* caseData )
{
for ( int eIdx = (int)m_geomExtractors.size() - 1; eIdx >= 0; eIdx-- )
{
if ( m_geomExtractors[eIdx]->caseData() == caseData )
{
m_geomExtractors.eraseAt( eIdx );
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellLogPlotCollection::onChildDeleted( caf::PdmChildArrayFieldHandle* childArray,
std::vector<caf::PdmObjectHandle*>& referringObjects )
{
// Make sure the plot collection disappears with the last plot
if ( m_wellLogPlots().empty() )
{
RimProject* project = RimProject::current();
if ( project )
{
project->updateConnectedEditors();
}
}
RiuPlotMainWindow* mainPlotWindow = RiaGuiApplication::instance()->mainPlotWindow();
mainPlotWindow->updateWellLogPlotToolBar();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
size_t RimWellLogPlotCollection::plotCount() const
{
return m_wellLogPlots.size();
}
| gpl-3.0 |
KabOOm356/Reporter | src/main/java/net/KabOOm356/Locale/Entry/LocalePhrases/UnclaimPhrases.java | 1600 | package net.KabOOm356.Locale.Entry.LocalePhrases;
import net.KabOOm356.Locale.Entry.LocalePhrase;
/**
* Class containing static {@link LocalePhrase}s that are used by
* {@link net.KabOOm356.Command.Commands.UnclaimCommand}.
*/
public abstract class UnclaimPhrases {
/**
* The report at index %i is already claimed by %c, whose priority clearance is equal to or above yours!
*/
public static final LocalePhrase reportAlreadyClaimed = new LocalePhrase(
"reportAlreadyClaimed",
"The report at index %i is already claimed by %c, whose priority clearance is equal to or above yours!");
/**
* The report at index %i is not claimed yet!
*/
public static final LocalePhrase reportIsNotClaimed = new LocalePhrase(
"reportIsNotClaimed",
"The report at index %i is not claimed yet!");
/**
* You have successfully unclaimed the report at index %i!
*/
public static final LocalePhrase reportUnclaimSuccess = new LocalePhrase(
"reportUnclaimSuccess",
"You have successfully unclaimed the report at index %i!");
/**
* /report unclaim Index/last
*/
public static final LocalePhrase unclaimHelp = new LocalePhrase(
"unclaimHelp",
"/report unclaim <Index/last>");
/**
* Opposite of claiming a report, states you would like to step down from being in charge of dealing with this report.
*/
public static final LocalePhrase unclaimHelpDetails = new LocalePhrase(
"unclaimHelpDetails",
"Opposite of claiming a report, states you would like to step down from being in charge of dealing with this report.");
}
| gpl-3.0 |
rtezli/Blitzableiter | Swf/H236VideoPacket.cs | 6112 | using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Recurity.Blitzableiter.SWF
{
/// <summary>
/// The video packet is the top-level structural element in a Sorenson H.263 video packet.
/// </summary>
public class H236VideoPacket : AbstractSwfElement, IVideoPacket
{
private UInt32 _pictureStartCode;
private byte _version;
private byte _temporalReference;
private byte _pictureSize;
private UInt16 _customWidth;
private UInt16 _customHeight;
private byte _pictureType;
private bool _deblockingFlag;
private byte _quantizer;
private bool _extraInformationFlag;
private List<byte> _extraInformation;
private MacroBlock _macroBlock;
private object _pictureStuffing;
/// <summary>
/// The video packet is the top-level structural element in a Sorenson H.263 video packet.
/// </summary>
/// <param name="InitialVersion">The version of the SWF file using this object.</param>
public H236VideoPacket(byte InitialVersion): base(InitialVersion)
{
}
/// <summary>
/// The length of this tag including the header.
/// </summary>
public ulong Length
{
get
{
return 0;
}
}
/// <summary>
/// Verifies this object and its components for documentation compliance.
/// </summary>
/// <returns>True if the object is documentation compliant.</returns>
public bool Verify()
{
return true;
}
/// <summary>
/// Parses this object out of a stream
/// </summary>
public void Parse(Stream input)
{
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
BitStream bits = new BitStream(input);
this._pictureStartCode = bits.GetBits(17);
this._version = (byte)bits.GetBits(5);
this._temporalReference = (byte)bits.GetBits(8);
this._pictureSize = (byte)bits.GetBits(3);
if (this._pictureSize.Equals(0))
{
this._customWidth = (UInt16)bits.GetBits(8);
this._customHeight = (UInt16)bits.GetBits(8);
}
else if (this._pictureSize.Equals(1))
{
this._customWidth = (UInt16)bits.GetBits(16);
this._customHeight = (UInt16)bits.GetBits(16);
}
else
{
SwfFormatException e = new SwfFormatException("Not supported picture size.");
log.Error(e.Message);
throw e;
}
this._pictureType = (byte)bits.GetBits(2);
this._deblockingFlag = Convert.ToBoolean(bits.GetBits(1));
this._quantizer = (byte)bits.GetBits(5);
this._extraInformationFlag = Convert.ToBoolean(bits.GetBits(1));
bits.Reset();
BinaryReader br = new BinaryReader(input);
byte tempByte = 0;
if (this._extraInformationFlag)
{
this._extraInformation = new List<byte>();
while (0 != (tempByte = br.ReadByte()))
{
this._extraInformation.Add(tempByte);
}
}
this._extraInformation.Add(0);
this._macroBlock = new MacroBlock(this._SwfVersion);
this._macroBlock.Parse(input);
//this._pictureStuffing.Parse(input);
}
/// <summary>
/// Writes this object back to a stream
/// </summary>
/// <param name="output">The stream to write to.</param>
public void Write(Stream output)
{
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
BitStream bits = new BitStream(output);
bits.WriteBits(17, (Int32)this._pictureStartCode);
bits.WriteBits(5, (Int32)this._version);
bits.WriteBits(8, (Int32)this._temporalReference);
bits.WriteBits(3, (Int32)this._pictureSize);
if (this._pictureSize.Equals(0))
{
bits.WriteBits(8, (Int32)this._customWidth);
bits.WriteBits(8, (Int32)this._customHeight);
}
else if (this._pictureSize.Equals(1))
{
bits.WriteBits(16, (Int32)this._customWidth);
bits.WriteBits(16, (Int32)this._customHeight);
}
else
{
SwfFormatException e = new SwfFormatException("Not supported picture size.");
log.Error(e.Message);
throw e;
}
bits.WriteBits(2, (Int32)this._pictureType);
bits.WriteBits(1, Convert.ToInt32(this._deblockingFlag));
bits.WriteBits(5, (Int32)this._quantizer);
bits.WriteBits(1, Convert.ToInt32(this._extraInformationFlag));
bits.WriteFlush();
if (this._extraInformationFlag)
{
for (int i = 0; i < this._extraInformation.Count; i++)
{
output.WriteByte(this._extraInformation[i]);
}
}
this._macroBlock.Write(output);
// this._pictureStuffing.Write(output);
}
/// <summary>
/// Converts the value of this instance to a System.String.
/// </summary>
/// <returns>A string whose value is the same as this instance.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(base.ToString());
return sb.ToString();
}
}
}
| gpl-3.0 |
arksu/origin | client/src/com/a2client/g3d/ModelData.java | 7237 | package com.a2client.g3d;
import com.a2client.Config;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* данные для визуализации 3д модели
* Created by arksu on 13.03.17.
*/
public class ModelData
{
private static final Logger _log = LoggerFactory.getLogger(ModelData.class.getName());
private static Gson _gson = new Gson();
/**
* дескриптор модели
*/
private ModelDesc _desc;
/**
* меши по группам
*/
private Map<String, List<Mesh>> _meshGroups = new HashMap<>();
private Map<String, Material> _meshMaterials = new HashMap<>();
/**
* если в этой модели вообще не прудсмотрено групп - храним массив мешей в явном виде
*/
private List<Mesh> _defaultGroup;
private Material _defaultMaterial;
/**
* сколько всего полигонов
*/
private int _totalTriCount;
/**
* имя которое указали при загрузке
*/
private final String _name;
private SkeletonData _skeletonData;
private final Map<String, AnimationData> _animations = new HashMap<>();
public ModelData(String name)
{
_log.debug("loading model: " + name);
_name = name;
File file = Gdx.files.internal(Config.MODELS_DIR + name + ".json").file();
try
{
_desc = _gson.fromJson(new FileReader(file), ModelDesc.class);
}
catch (FileNotFoundException e)
{
_log.debug("desc for model: <" + name + "> not found");
_desc = new ModelDesc();
}
try
{
MyInputStream in = MyInputStream.fromFile(name + ".mdl");
// flag skeleton
if (in.readByte() > 0)
{
loadSkeleton(in);
// flag anims
if (in.readByte() > 0)
{
int animationsCount = in.readWord();
while (animationsCount > 0)
{
loadAnimation(in);
animationsCount--;
}
}
}
// mesh exists anyway
loadMesh(in);
}
catch (Exception e)
{
_log.error("failed load model " + name, e);
}
}
private void loadSkeleton(MyInputStream in) throws IOException
{
_skeletonData = SkeletonLoader.load(in);
}
private void loadAnimation(MyInputStream in) throws IOException
{
AnimationData data = AnimationLoader.load(in, _skeletonData);
_log.debug("loaded anim: " + data.getName() + " frames: " + data.getFramesCount() + " fps: " + data.getFps());
_animations.put(data.getName(), data);
}
/**
* загрузить меш из потока
*/
private void loadMesh(MyInputStream in) throws IOException
{
_totalTriCount = 0;
int meshCount = in.readInt();
List<Mesh> tmpList = new LinkedList<>();
// грузим сначала все меши из файла
Map<String, Mesh> map = new HashMap<>();
while (meshCount > 0)
{
String name = in.readAnsiString().toLowerCase();
Mesh mesh = MeshLoader.load(in);
_totalTriCount += mesh.getNumIndices() / 3;
// для моделей используем батчинг. поэтому бинд буферов будет только там
mesh.setAutoBind(false);
tmpList.add(mesh);
map.put(name, mesh);
meshCount--;
}
_log.debug("total tri count: " + _totalTriCount + " in " + tmpList.size() + " mesh");
// если группы для этой модели есть. надо их сформировать
if (_desc.meshgroups != null)
{
for (Map.Entry<String, ModelDesc.MeshGroup> entry : _desc.meshgroups.entrySet())
{
String groupName = entry.getKey();
ModelDesc.Material descMaterial = entry.getValue().material;
if (descMaterial == null)
{
throw new RuntimeException("no material in group: " + groupName);
}
Material material = new Material(descMaterial);
List<Mesh> tmpData = new LinkedList<>();
// выдираем поименно все меши
for (String name : entry.getValue().names)
{
Mesh mesh = map.get(name);
if (mesh != null)
{
tmpData.add(mesh);
}
}
_meshGroups.put(groupName, tmpData);
_meshMaterials.put(groupName, material);
}
}
else
{
// групп в этой модели нет
_defaultGroup = new LinkedList<>();
ModelDesc.Material descMaterial = _desc.material;
if (descMaterial == null)
{
ModelDesc.Material desc = new ModelDesc.Material();
String fname = _name + ".png";
if (!MyInputStream.fileExists(fname))
{
fname = null;
}
desc.diffuse = fname;
_defaultMaterial = new Material(desc);
}
else
{
_defaultMaterial = new Material(descMaterial);
}
for (Mesh mesh : tmpList)
{
_defaultGroup.add(mesh);
}
}
}
/**
* есть только один меш?
*/
public boolean isOneMesh()
{
return _defaultGroup != null && _defaultGroup.size() == 1;
}
/**
* рендер без указания группы. выводим ВСЕ возможное (все группы)
*/
public void render(ModelBatch modelBatch, int primitiveType)
{
if (_defaultGroup != null)
{
if (!modelBatch.isShadowMode() || _defaultMaterial.isCastShadows())
{
modelBatch.bindMaterial(_defaultMaterial);
for (Mesh mesh : _defaultGroup)
{
// биндим меш через батчер, там проверим текущий меш и только тогда будет бинд если реально нужно
modelBatch.bindMesh(mesh);
mesh.render(modelBatch.getShader(), primitiveType);
}
}
}
else
{
for (Map.Entry<String, List<Mesh>> entry : _meshGroups.entrySet())
{
Material material = _meshMaterials.get(entry.getKey());
if (!modelBatch.isShadowMode() || material.isCastShadows())
{
modelBatch.bindMaterial(material);
for (Mesh mesh : entry.getValue())
{
// биндим меш через батчер, там проверим текущий меш и только тогда будет бинд если реально нужно
modelBatch.bindMesh(mesh);
mesh.render(modelBatch.getShader(), primitiveType);
}
}
}
}
}
/**
* обсчитать bound box
*/
public void extendBoundingBox(BoundingBox boundingBox, Matrix4 worldTransform)
{
if (_defaultGroup != null)
{
for (Mesh mesh : _defaultGroup)
{
mesh.extendBoundingBox(boundingBox, 0, mesh.getNumIndices(), worldTransform);
}
}
else
{
for (Map.Entry<String, List<Mesh>> entry : _meshGroups.entrySet())
{
for (Mesh mesh : entry.getValue())
{
mesh.extendBoundingBox(boundingBox, 0, mesh.getNumIndices(), worldTransform);
}
}
}
}
public SkeletonData getSkeletonData()
{
return _skeletonData;
}
public AnimationData getAnimation(String name)
{
return _animations.get(name);
}
public Map<String, AnimationData> getAnimations()
{
return _animations;
}
}
| gpl-3.0 |
bojuelu/unity-toolbox | Assets/Scripts/UI/Tools/TextSharperer.cs | 907 | using UnityEngine;
using UnityEngine.UI;
namespace UnityToolbox
{
/// <summary>
/// Sharp the fucking UGUI Text
/// Refrence: http://answers.unity3d.com/questions/1226551/ui-text-is-blurred-unity-535f.html
/// Use the way "Lame hack 1"
/// Author: U_Ku_Shu (http://answers.unity3d.com/users/490552/u-ku-shu.html)
/// </summary>
[ExecuteInEditMode]
public class TextSharperer : MonoBehaviour
{
private const int scaleValue = 10;
private Text thisText;
void Start()
{
thisText = gameObject.GetComponent<Text>();
thisText.fontSize = thisText.fontSize * scaleValue;
thisText.transform.localScale = thisText.transform.localScale / scaleValue;
thisText.horizontalOverflow = HorizontalWrapMode.Overflow;
thisText.verticalOverflow = VerticalWrapMode.Overflow;
}
}
}
| gpl-3.0 |
Kneesnap/Kineticraft | src/net/kineticraft/lostcity/data/reflect/behavior/MapStore.java | 1231 | package net.kineticraft.lostcity.data.reflect.behavior;
import net.kineticraft.lostcity.data.JsonData;
import net.kineticraft.lostcity.data.Jsonable;
import net.kineticraft.lostcity.data.maps.SaveableMap;
import net.kineticraft.lostcity.guis.data.GUIMapEditor;
import net.kineticraft.lostcity.item.display.GUIItem;
import org.bukkit.Material;
import java.lang.reflect.Field;
import java.util.function.Consumer;
/**
* Handles dictionary saving / loading
* Created by Kneesnap on 7/4/2017.
*/
public class MapStore extends DataStore<SaveableMap> {
public MapStore() {
super(SaveableMap.class, "setElement");
}
@Override
protected Class<Jsonable> getSaveArgument() {
return Jsonable.class;
}
@SuppressWarnings("unchecked")
@Override
public SaveableMap getField(JsonData data, String key, Field field) {
return data.getMap(key, (Class<? extends SaveableMap>) field.getType(), getArgs(field));
}
@Override
public void editItem(GUIItem item, Object value, Consumer<Object> setter) {
item.setIcon(Material.CHEST).addLoreAction("Left", "Edit Values");
item.leftClick(ce -> new GUIMapEditor<>(ce.getPlayer(), (SaveableMap<?, ?>) value));
}
}
| gpl-3.0 |
Belxjander/Kirito | SnowStorm/indra/linux_crash_logger/linux_crash_logger.cpp | 1787 | /**
* @file linux_crash_logger.cpp
* @brief Linux crash logger implementation
*
* $LicenseInfo:firstyear=2003&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llcrashloggerlinux.h"
#include "llsdutil.h"
int main(int argc, char **argv)
{
LL_INFOS() << "Starting crash reporter." << LL_ENDL;
LLCrashLoggerLinux app;
app.parseCommandOptions(argc, argv);
LLSD options = LLApp::instance()->getOptionData(
LLApp::PRIORITY_COMMAND_LINE);
//LLApp::PRIORITY_RUNTIME_OVERRIDE);
if (!(options.has("pid") && options.has("dumpdir")))
{
llwarns << "Insufficient parameters to crash report." << llendl;
}
if (! app.init())
{
LL_WARNS() << "Unable to initialize application." << LL_ENDL;
return 1;
}
app.mainLoop();
app.cleanup();
LL_INFOS() << "Crash reporter finished normally." << LL_ENDL;
return 0;
}
| gpl-3.0 |
mahalaxmi123/moodleanalytics | corplms/reportbuilder/report_forms.php | 71585 | <?php
/*
* This file is part of Corplms LMS
*
* Copyright (C) 2010 onwards Corplms Learning Solutions LTD
*
* 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/>.
*
* @author Simon Coggins <[email protected]>
* @package corplms
* @subpackage reportbuilder
*/
/**
* Moodle Formslib templates for report builder settings forms
*/
require_once "$CFG->dirroot/lib/formslib.php";
include_once($CFG->dirroot . '/corplms/reportbuilder/classes/rb_base_content.php');
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
/**
* Formslib template for the new report form
*/
class report_builder_new_form extends moodleform {
function definition() {
$mform =& $this->_form;
$mform->addElement('header', 'general', get_string('newreport', 'corplms_reportbuilder'));
$sources = reportbuilder::get_source_list();
if (count($sources) > 0) {
$mform->addElement('text', 'fullname', get_string('reportname', 'corplms_reportbuilder'), 'maxlength="255"');
$mform->setType('fullname', PARAM_TEXT);
$mform->addRule('fullname', null, 'required');
$mform->addHelpButton('fullname', 'reportbuilderfullname', 'corplms_reportbuilder');
$pick = array(0 => get_string('selectsource', 'corplms_reportbuilder'));
$select = array_merge($pick, $sources);
$mform->addElement('select', 'source', get_string('source', 'corplms_reportbuilder'), $select);
// invalid if not set
$mform->addRule('source', get_string('error:mustselectsource', 'corplms_reportbuilder'), 'regex', '/[^0]+/');
$mform->addHelpButton('source', 'reportbuildersource', 'corplms_reportbuilder');
$mform->addElement('advcheckbox', 'hidden', get_string('hidden', 'corplms_reportbuilder'), '', null, array(0, 1));
$mform->addHelpButton('hidden', 'reportbuilderhidden', 'corplms_reportbuilder');
$this->add_action_buttons(true, get_string('createreport', 'corplms_reportbuilder'));
} else {
$mform->addElement('html', get_string('error:nosources', 'corplms_reportbuilder'));
}
}
}
/**
* Formslib tempalte for the edit report form
*/
class report_builder_edit_form extends moodleform {
function definition() {
global $TEXTAREA_OPTIONS;
$mform = $this->_form;
$report = $this->_customdata['report'];
$record = $this->_customdata['record'];
$mform->addElement('header', 'general', get_string('reportsettings', 'corplms_reportbuilder'));
$mform->addElement('text', 'fullname', get_string('reporttitle', 'corplms_reportbuilder'), array('size' => '30'));
$mform->setType('fullname', PARAM_TEXT);
$mform->addRule('fullname', null, 'required');
$mform->addHelpButton('fullname', 'reportbuilderfullname', 'corplms_reportbuilder');
$mform->addElement('editor', 'description_editor', get_string('description'), null, $TEXTAREA_OPTIONS);
$mform->setType('description_editor', PARAM_CLEANHTML);
$mform->addHelpButton('description_editor', 'reportbuilderdescription', 'corplms_reportbuilder');
$mform->addElement('static', 'reportsource', get_string('source', 'corplms_reportbuilder'), $report->src->sourcetitle);
$mform->addHelpButton('reportsource', 'reportbuildersource', 'corplms_reportbuilder');
$mform->addElement('advcheckbox', 'hidden', get_string('hidden', 'corplms_reportbuilder'), '', null, array(0, 1));
$mform->setType('hidden', PARAM_INT);
$mform->addHelpButton('hidden', 'reportbuilderhidden', 'corplms_reportbuilder');
$mform->addElement('text', 'recordsperpage', get_string('recordsperpage', 'corplms_reportbuilder'), array('size' => '6', 'maxlength' => 4));
$mform->setType('recordsperpage', PARAM_INT);
$mform->addRule('recordsperpage', null, 'numeric');
$mform->addHelpButton('recordsperpage', 'reportbuilderrecordsperpage', 'corplms_reportbuilder');
$reporttype = ($report->embeddedurl === null) ? get_string('usergenerated', 'corplms_reportbuilder') :
get_string('embedded', 'corplms_reportbuilder');
$mform->addElement('static', 'reporttype', get_string('reporttype', 'corplms_reportbuilder'), $reporttype);
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
$this->add_action_buttons();
// Set the data.
$this->set_data($record);
}
}
/**
* Formslib template for edit filters form
*/
class report_builder_edit_filters_form extends moodleform {
function definition() {
global $OUTPUT;
// Common.
$mform =& $this->_form;
$report = $this->_customdata['report'];
$id = $this->_customdata['id'];
$allstandardfilters = $this->_customdata['allstandardfilters'];
$unusedstandardfilters = $this->_customdata['unusedstandardfilters'];
$allsidebarfilters = $this->_customdata['allsidebarfilters'];
$unusedsidebarfilters = $this->_customdata['unusedsidebarfilters'];
$allsearchcolumns = $this->_customdata['allsearchcolumns'];
$unusedsearchcolumns = $this->_customdata['unusedsearchcolumns'];
$filters = array();
$strmovedown = get_string('movedown', 'corplms_reportbuilder');
$strmoveup = get_string('moveup', 'corplms_reportbuilder');
$strdelete = get_string('delete', 'corplms_reportbuilder');
$spacer = $OUTPUT->spacer(array('width' => 11, 'height' => 11));
$renderer =& $mform->defaultRenderer();
$selectelementtemplate = $OUTPUT->container($OUTPUT->container('{element}', 'fselectgroups'), 'fitem');
$checkelementtemplate = $OUTPUT->container($OUTPUT->container('{element}', 'fcheckbox'), 'fitem');
$textelementtemplate = $OUTPUT->container($OUTPUT->container('{element}', 'ftext'), 'fitem');
// Standard and sidebar filters.
$mform->addElement('header', 'standardfilter', get_string('standardfilter', 'corplms_reportbuilder'));
$mform->addHelpButton('standardfilter', 'standardfilter', 'corplms_reportbuilder');
$mform->setExpanded('standardfilter');
if (isset($report->filteroptions) && is_array($report->filteroptions) && count($report->filteroptions) > 0) {
$filters = $report->filters;
$standardfiltercount = 0;
$sidebarfiltercount = 0;
foreach ($filters as $filter) {
if ($filter->region == rb_filter_type::RB_FILTER_REGION_STANDARD) {
$standardfiltercount++;
} else if ($filter->region == rb_filter_type::RB_FILTER_REGION_SIDEBAR) {
$sidebarfiltercount++;
}
}
// Standard filter options.
$mform->addElement('html', $OUTPUT->container(get_string('standardfilterdesc', 'corplms_reportbuilder')) .
html_writer::empty_tag('br'));
$mform->addElement('html', $OUTPUT->container_start('reportbuilderform') . html_writer::start_tag('table') .
html_writer::start_tag('tr') . html_writer::tag('th', get_string('searchfield', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('customisename', 'corplms_reportbuilder'), array('colspan' => 2)) .
html_writer::tag('th', get_string('advanced', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('options', 'corplms_reportbuilder')) . html_writer::end_tag('tr'));
if (isset($report->filters) && is_array($report->filters) && count($report->filters) > 0) {
$i = 1;
foreach ($filters as $index => $filter) {
if ($filter->region != rb_filter_type::RB_FILTER_REGION_STANDARD) {
continue;
}
$row = array();
$filterid = $filter->filterid;
$type = $filter->type;
$value = $filter->value;
$field = "{$type}-{$value}";
$advanced = $filter->advanced;
$mform->addElement('html', html_writer::start_tag('tr', array('fid' => $filterid)) .
html_writer::start_tag('td'));
$mform->addElement('selectgroups', "filter{$filterid}", '', $allstandardfilters,
array('class' => 'filter_selector'));
$mform->setDefault("filter{$filterid}", $field);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', "customname{$filterid}", '', '',
array('class' => 'filter_custom_name_checkbox', 'group' => 0), array(0, 1));
$mform->setDefault("customname{$filterid}", $filter->customname);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('text', "filtername{$filterid}", '', 'class="filter_name_text"');
$mform->setType("filtername{$filterid}", PARAM_TEXT);
$mform->setDefault("filtername{$filterid}", (empty($filter->filtername) ? $filter->label : $filter->filtername));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', "advanced{$filterid}", '', '', array('class' => 'filter_advanced_checkbox'));
$mform->setDefault("advanced{$filterid}", $filter->advanced);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$deleteurl = new moodle_url('/corplms/reportbuilder/filters.php',
array('d' => '1', 'id' => $id, 'fid' => $filterid));
$mform->addElement('html', html_writer::link(
$deleteurl,
$OUTPUT->pix_icon('t/delete', $strdelete, null, array('iconsmall')),
array('title' => $strdelete, 'class' => 'deletefilterbtn action-icon')
));
if ($i != 1) {
$moveupurl = new moodle_url('/corplms/reportbuilder/filters.php',
array('m' => 'up', 'id' => $id, 'fid' => $filterid));
$mform->addElement('html', html_writer::link(
$moveupurl,
$OUTPUT->pix_icon('t/up', $strmoveup, null, array('class' => 'iconsmall')),
array('title' => $strmoveup, 'class' => 'movefilterupbtn action-icon')
));
} else {
$mform->addElement('html', $spacer);
}
if ($i != $standardfiltercount) {
$movedownurl = new moodle_url('/corplms/reportbuilder/filters.php',
array('m' => 'down', 'id' => $id, 'fid' => $filterid));
$mform->addElement('html', html_writer::link(
$movedownurl,
$OUTPUT->pix_icon('t/down', $strmovedown, null, array('class' => 'iconsmall')),
array('title' => $strmovedown, 'class' => 'movefilterdownbtn action-icon')
));
} else {
$mform->addElement('html', $spacer);
}
$mform->addElement('html', html_writer::end_tag('td') . html_writer::end_tag('tr'));
$i++;
}
} else {
$mform->addElement('html', html_writer::tag('p', get_string('nofiltersyet', 'corplms_reportbuilder')));
}
$mform->addElement('html', html_writer::start_tag('tr') . html_writer::start_tag('td'));
$mform->addElement('selectgroups', 'newstandardfilter', '', $unusedstandardfilters,
array('class' => 'new_standard_filter_selector filter_selector'));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', 'newstandardcustomname', '', '',
array('id' => 'id_newstandardcustomname', 'class' => 'filter_custom_name_checkbox', 'group' => 0),
array(0, 1));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->setDefault('newstandardcustomname', 0);
$mform->addElement('text', 'newstandardfiltername', '', 'class="filter_name_text"');
$mform->setType('newstandardfiltername', PARAM_TEXT);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', 'newstandardadvanced', '', '', array('class' => 'filter_advanced_checkbox'));
$mform->disabledIf('newstandardadvanced', 'newstandardfilter', 'eq', 0);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::end_tag('tr'));
$mform->addElement('html', html_writer::end_tag('table') . $OUTPUT->container_end());
// Sidebar filter options.
$mform->addElement('header', 'sidebarfilter', get_string('sidebarfilter', 'corplms_reportbuilder'));
$mform->addHelpButton('sidebarfilter', 'sidebarfilter', 'corplms_reportbuilder');
$mform->setExpanded('sidebarfilter');
$mform->addElement('html', $OUTPUT->container(get_string('sidebarfilterdesc', 'corplms_reportbuilder')) .
html_writer::empty_tag('br'));
$mform->addElement('selectgroups', "all_sidebar_filters", '', $allsidebarfilters);
$mform->addElement('html', $OUTPUT->container_start('reportbuilderform') . html_writer::start_tag('table') .
html_writer::start_tag('tr') . html_writer::tag('th', get_string('searchfield', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('customisename', 'corplms_reportbuilder'), array('colspan' => 2)) .
html_writer::tag('th', get_string('advanced', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('options', 'corplms_reportbuilder')) . html_writer::end_tag('tr'));
if (isset($report->filters) && is_array($report->filters) && count($report->filters) > 0) {
$i = 1;
foreach ($filters as $index => $filter) {
if ($filter->region != rb_filter_type::RB_FILTER_REGION_SIDEBAR) {
continue;
}
$row = array();
$filterid = $filter->filterid;
$type = $filter->type;
$value = $filter->value;
$field = "{$type}-{$value}";
$advanced = $filter->advanced;
$mform->addElement('html', html_writer::start_tag('tr', array('fid' => $filterid)) .
html_writer::start_tag('td'));
$mform->addElement('selectgroups', "filter{$filterid}", '', $allsidebarfilters,
array('class' => 'filter_selector'));
$mform->setDefault("filter{$filterid}", $field);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', "customname{$filterid}", '', '',
array('class' => 'filter_custom_name_checkbox', 'group' => 0), array(0, 1));
$mform->setDefault("customname{$filterid}", $filter->customname);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('text', "filtername{$filterid}", '', 'class="filter_name_text"');
$mform->setType("filtername{$filterid}", PARAM_TEXT);
$mform->setDefault("filtername{$filterid}", (empty($filter->filtername) ?
$filter->label : $filter->filtername));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', "advanced{$filterid}", '', '',
array('class' => 'filter_advanced_checkbox'));
$mform->setDefault("advanced{$filterid}", $filter->advanced);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$deleteurl = new moodle_url('/corplms/reportbuilder/filters.php',
array('d' => '1', 'id' => $id, 'fid' => $filterid));
$mform->addElement('html', html_writer::link($deleteurl, $OUTPUT->pix_icon('/t/delete', $strdelete),
array('title' => $strdelete, 'class' => 'deletefilterbtn action-icon')));
if ($i != 1) {
$moveupurl = new moodle_url('/corplms/reportbuilder/filters.php',
array('m' => 'up', 'id' => $id, 'fid' => $filterid));
$mform->addElement('html', html_writer::link($moveupurl, $OUTPUT->pix_icon('/t/up', $strmoveup),
array('title' => $strmoveup, 'class' => 'movefilterupbtn action-icon')));
} else {
$mform->addElement('html', $spacer);
}
if ($i != $sidebarfiltercount) {
$movedownurl = new moodle_url('/corplms/reportbuilder/filters.php',
array('m' => 'down', 'id' => $id, 'fid' => $filterid));
$mform->addElement('html', html_writer::link($movedownurl, $OUTPUT->pix_icon('/t/down', $strmovedown),
array('title' => $strmovedown, 'class' => 'movefilterdownbtn action-icon')));
} else {
$mform->addElement('html', $spacer);
}
$mform->addElement('html', html_writer::end_tag('td') . html_writer::end_tag('tr'));
$i++;
}
} else {
$mform->addElement('html', html_writer::tag('p', get_string('nofiltersyet', 'corplms_reportbuilder')));
}
$mform->addElement('html', html_writer::start_tag('tr') . html_writer::start_tag('td'));
$mform->addElement('selectgroups', 'newsidebarfilter', '', $unusedsidebarfilters,
array('class' => 'new_sidebar_filter_selector filter_selector'));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', 'newsidebarcustomname', '', '',
array('id' => 'id_newsidebarcustomname', 'class' => 'filter_custom_name_checkbox', 'group' => 0), array(0, 1));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->setDefault('newsidebarcustomname', 0);
$mform->addElement('text', 'newsidebarfiltername', '', 'class="filter_name_text"');
$mform->setType('newsidebarfiltername', PARAM_TEXT);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', 'newsidebaradvanced', '', '', array('class' => 'filter_advanced_checkbox'));
$mform->disabledIf('newsidebaradvanced', 'newsidebarfilter', 'eq', 0);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::end_tag('tr'));
$mform->addElement('html', html_writer::end_tag('table') . $OUTPUT->container_end());
// Standard and sidebar filters.
// Remove the labels from the form elements.
$renderer->setElementTemplate($selectelementtemplate, 'newstandardfilter');
$renderer->setElementTemplate($selectelementtemplate, 'newsidebarfilter');
$renderer->setElementTemplate($checkelementtemplate, 'newstandardadvanced');
$renderer->setElementTemplate($checkelementtemplate, 'newsidebaradvanced');
$renderer->setElementTemplate($textelementtemplate, 'newstandardfiltername');
$renderer->setElementTemplate($textelementtemplate, 'newsidebarfiltername');
$renderer->setElementTemplate($checkelementtemplate, 'newstandardcustomname');
$renderer->setElementTemplate($checkelementtemplate, 'newsidebarcustomname');
foreach ($filters as $index => $filter) {
$filterid = $filter->filterid;
$renderer->setElementTemplate($selectelementtemplate, 'filter' . $filterid);
$renderer->setElementTemplate($checkelementtemplate, 'advanced' . $filterid);
$renderer->setElementTemplate($textelementtemplate, 'filtername' . $filterid);
$renderer->setElementTemplate($checkelementtemplate, 'customname' . $filterid);
}
} else {
// No filters available.
$mform->addElement('html', get_string('nofilteraskdeveloper', 'corplms_reportbuilder', $report->source));
}
// Toolbar search options.
$mform->addElement('header', 'toolbarsearch', get_string('toolbarsearch', 'corplms_reportbuilder'));
$mform->addHelpButton('toolbarsearch', 'toolbarsearch', 'corplms_reportbuilder');
$mform->setExpanded('toolbarsearch');
$mform->addElement('advcheckbox', 'toolbarsearchdisabled', get_string('toolbarsearchdisabled', 'corplms_reportbuilder'));
$mform->setDefault('toolbarsearchdisabled', !$report->toolbarsearch);
$mform->addHelpButton('toolbarsearchdisabled', 'toolbarsearchdisabled', 'corplms_reportbuilder');
if (count($allsearchcolumns) > 0) {
$searchcolumns = $report->searchcolumns;
$mform->addElement('html', $OUTPUT->container(get_string('toolbarsearchdesc', 'corplms_reportbuilder')) .
html_writer::empty_tag('br'));
$mform->addElement('html', $OUTPUT->container_start('reportbuilderform') . html_writer::start_tag('table') .
html_writer::start_tag('tr') . html_writer::tag('th', get_string('searchfield', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('options', 'corplms_reportbuilder')) . html_writer::end_tag('tr'));
if (isset($report->searchcolumns) && is_array($report->searchcolumns) && count($report->searchcolumns) > 0) {
foreach ($searchcolumns as $index => $searchcolumn) {
$row = array();
$searchcolumnid = $searchcolumn->id;
$type = $searchcolumn->type;
$value = $searchcolumn->value;
$field = "{$type}-{$value}";
$mform->addElement('html', html_writer::start_tag('tr', array('searchcolumnid' => $searchcolumnid)) .
html_writer::start_tag('td'));
$mform->addElement('selectgroups', "searchcolumn{$searchcolumnid}", '', $allsearchcolumns,
array('class' => 'search_column_selector'));
$mform->setDefault("searchcolumn{$searchcolumnid}", $field);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$deleteurl = new moodle_url('/corplms/reportbuilder/filters.php',
array('d' => '1', 'id' => $id, 'searchcolumnid' => $searchcolumnid));
$mform->addElement('html', html_writer::link($deleteurl, $OUTPUT->pix_icon('/t/delete', $strdelete),
array('title' => $strdelete, 'class' => 'deletesearchcolumnbtn')));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::end_tag('tr'));
}
} else {
$mform->addElement('html', html_writer::tag('p', get_string('nosearchcolumnsyet', 'corplms_reportbuilder')));
}
$mform->addElement('html', html_writer::start_tag('tr') . html_writer::start_tag('td'));
$mform->addElement('selectgroups', 'newsearchcolumn', '', $unusedsearchcolumns,
array('class' => 'new_search_column_selector search_column_selector'));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::end_tag('tr'));
$mform->addElement('html', html_writer::end_tag('table') . $OUTPUT->container_end());
$renderer->setElementTemplate($selectelementtemplate, 'newsearchcolumn');
foreach ($searchcolumns as $index => $searchcolumn) {
$searchcolumnid = $searchcolumn->id;
$renderer->setElementTemplate($selectelementtemplate, 'searchcolumn' . $searchcolumnid);
}
} else {
// No search columns available.
$mform->addElement('html', get_string('nosearchcolumnsaskdeveloper', 'corplms_reportbuilder', $report->source));
}
// Common.
$mform->addElement('hidden', 'id', $id);
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'source', $report->source);
$mform->setType('source', PARAM_TEXT);
$this->add_action_buttons();
}
/**
* Carries out validation of submitted form values
*
* @param array $data array of ("fieldname"=>value) of submitted data
* @param array $files array of uploaded files "element_name"=>tmp_file_path
* @return array of "element_name"=>"error_description" if there are errors,
* or an empty array if everything is OK (true allowed for backwards compatibility too).
*/
function validation($data, $files) {
$err = array();
$err += validate_unique_filters($data);
return $err;
}
}
/**
* Formslib template for edit columns form
*/
class report_builder_edit_columns_form extends moodleform {
/** @var reportbuilder */
protected $report;
/** @var array */
protected $allowedadvanced;
/** @var array */
protected $grouped;
function definition() {
global $CFG, $OUTPUT, $DB;
$mform =& $this->_form;
$this->report = $this->_customdata['report'];
$report = $this->report;
$this->allowedadvanced = $this->_customdata['allowedadvanced'];
$this->grouped = $this->_customdata['grouped'];
$advoptions = $this->_customdata['advoptions'];
$id = $report->_id;
$strmovedown = get_string('movedown', 'corplms_reportbuilder');
$strmoveup = get_string('moveup', 'corplms_reportbuilder');
$strdelete = get_string('delete', 'corplms_reportbuilder');
$strhide = get_string('hide');
$strshow = get_string('show');
$spacer = $OUTPUT->spacer(array('width' => 11, 'height' => 11));
$mform->addElement('header', 'reportcolumns', get_string('reportcolumns', 'corplms_reportbuilder'));
$mform->addHelpButton('reportcolumns', 'reportbuildercolumns', 'corplms_reportbuilder');
if (isset($report->columnoptions) && is_array($report->columnoptions) && count($report->columnoptions) > 0) {
$mform->addElement('html', $OUTPUT->container(get_string('help:columnsdesc', 'corplms_reportbuilder')) .
html_writer::empty_tag('br'));
$mform->addElement('html', $OUTPUT->container_start('reportbuilderform') . html_writer::start_tag('table') .
html_writer::start_tag('tr') . html_writer::tag('th', get_string('column', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('advancedcolumnheading', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('customiseheading', 'corplms_reportbuilder'), array('colspan' => 2)) .
html_writer::tag('th', get_string('options', 'corplms_reportbuilder') . html_writer::end_tag('tr')));
$columnsselect = $report->get_columns_select();
$columnoptions = array();
$rawcolumns = $DB->get_records('report_builder_columns', array('reportid' => $id), 'sortorder ASC, id ASC');
$badcolumns = array();
$goodcolumns = array();
foreach ($rawcolumns as $rawcolumn) {
$key = $rawcolumn->type . '-' . $rawcolumn->value;
if (!isset($report->columnoptions[$key]) or !empty($report->columnoptions[$key]->required)) {
$badcolumns[] = array(
'id' => $rawcolumn->id,
'type' => $rawcolumn->type,
'value' => $rawcolumn->value,
'heading' => $rawcolumn->heading
);
unset($rawcolumns[$rawcolumn->id]);
continue;
}
$goodcolumns[$rawcolumn->id] = $rawcolumn;
}
if ($goodcolumns) {
$colcount = count($goodcolumns);
$i = 1;
foreach ($goodcolumns as $cid => $column) {
$columnoptions["{$column->type}_{$column->value}"] = $column->heading;
if (!isset($column->required) || !$column->required) {
$field = "{$column->type}-{$column->value}";
$mform->addElement('html', html_writer::start_tag('tr', array('colid' => $cid)) .
html_writer::start_tag('td'));
$mform->addElement('selectgroups', "column{$cid}", '', $columnsselect, array('class' => 'column_selector'));
$mform->setDefault("column{$cid}", $field);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$advanced = '';
if ($column->transform) {
$advanced = 'transform_' . $column->transform;
} else if ($column->aggregate) {
$advanced = 'aggregate_' . $column->aggregate;
}
$mform->addElement('selectgroups', 'advanced'.$cid, '', $advoptions, array('class' => 'advanced_selector'));
$mform->setDefault("advanced{$cid}", $advanced);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', "customheading{$cid}", '', '', array('class' => 'column_custom_heading_checkbox', 'group' => 0), array(0, 1));
$mform->setDefault("customheading{$cid}", $column->customheading);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('text', "heading{$cid}", '', 'class="column_heading_text"');
$mform->setType("heading{$cid}", PARAM_TEXT);
$mform->setDefault("heading{$cid}", $column->heading);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
// show/hide link
if ($column->hidden == 0) {
$hideurl = new moodle_url('/corplms/reportbuilder/columns.php',
array('h' => '1', 'id' => $id, 'cid' => $cid));
$mform->addElement('html', html_writer::link(
$hideurl,
$OUTPUT->pix_icon('/t/hide', $strhide, null, array('class' => 'iconsmall')),
array('class' => 'hidecolbtn action-icon', 'title' => $strhide)
));
} else {
$showurl = new moodle_url('/corplms/reportbuilder/columns.php',
array('h' => '0', 'id' => $id, 'cid' => $cid));
$mform->addElement('html', html_writer::link(
$showurl,
$OUTPUT->pix_icon('/t/show', $strshow, null, array('class' => 'iconsmall')),
array('class' => 'showcolbtn action-icon', 'title' => $strshow)
));
}
// delete link
$delurl = new moodle_url('/corplms/reportbuilder/columns.php',
array('d' => '1', 'id' => $id, 'cid' => $cid));
$mform->addElement('html', html_writer::link(
$delurl,
$OUTPUT->pix_icon('/t/delete', $strdelete, null, array('class' => 'iconsmall')),
array('class' => 'deletecolbtn action-icon', 'title' => $strdelete)
));
// move up link
if ($i != 1) {
$moveupurl = new moodle_url('/corplms/reportbuilder/columns.php',
array('m' => 'up', 'id' => $id, 'cid' => $cid));
$mform->addElement('html', html_writer::link(
$moveupurl,
$OUTPUT->pix_icon('/t/up', $strmoveup, null, array('class' => 'iconsmall')),
array('class' => 'movecolupbtn action-icon', 'title' => $strmoveup)
));
} else {
$mform->addElement('html', $spacer);
}
// move down link
if ($i != $colcount) {
$movedownurl = new moodle_url('/corplms/reportbuilder/columns.php',
array('m' => 'down', 'id' => $id, 'cid' => $cid));
$mform->addElement('html', html_writer::link(
$movedownurl,
$OUTPUT->pix_icon('/t/down', $strmovedown, null, array('class' => 'iconsmall')),
array('class' => 'movecoldownbtn action-icon', 'title' => $strmovedown)
));
} else {
$mform->addElement('html', $spacer);
}
$mform->addElement('html', html_writer::end_tag('td') . html_writer::end_tag('tr'));
$i++;
}
}
} else {
$mform->addElement('html', html_writer::tag('p', get_string('nocolumnsyet', 'corplms_reportbuilder')));
}
$mform->addElement('html', html_writer::start_tag('tr') . html_writer::start_tag('td'));
$newcolumnsselect = array_merge(
array(
get_string('new') => array(0 => get_string('addanothercolumn', 'corplms_reportbuilder'))
),
$columnsselect);
// Remove already-added cols from the new col selector
$cleanednewcolselect = $newcolumnsselect;
foreach ($newcolumnsselect as $okey => $optgroup) {
foreach ($optgroup as $typeval => $heading) {
$typevalarr = explode('-', $typeval);
foreach ($goodcolumns as $curcol) {
if ($curcol->type == $typevalarr[0] && $curcol->value == $typevalarr[1]) {
unset($cleanednewcolselect[$okey][$typeval]);
}
}
}
}
$newcolumnsselect = $cleanednewcolselect;
unset($cleanednewcolselect);
$mform->addElement('selectgroups', 'newcolumns', '', $newcolumnsselect,
array('class' => 'column_selector new_column_selector'));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('selectgroups', 'newadvanced', '', $advoptions,
array('class' => 'advanced_selector new_advanced_selector'));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('advcheckbox', "newcustomheading", '', '', array('id' => 'id_newcustomheading',
'class' => 'column_custom_heading_checkbox', 'group' => 0), array(0, 1));
$mform->setDefault("newcustomheading", 0);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('text', 'newheading', '', 'class="column_heading_text"');
$mform->setType('newheading', PARAM_TEXT);
// Do manually as disabledIf doesn't play nicely with using JS to update heading values.
// $mform->disabledIf('newheading', 'newcolumns', 'eq', 0);
$mform->addElement('html', html_writer::end_tag('td') . html_writer::start_tag('td'));
$mform->addElement('html', html_writer::end_tag('td') . html_writer::end_tag('tr'));
$mform->addElement('html', html_writer::end_tag('table') . $OUTPUT->container_end());
// If the report is referencing columns that don't exist in the
// source, display them here so the user has the option to delete them.
if ($badcolumns) {
$mform->addElement('header', 'badcols', get_string('badcolumns', 'corplms_reportbuilder'));
$mform->addElement('html', html_writer::tag('p', get_string('badcolumnsdesc', 'corplms_reportbuilder')));
$mform->addElement('html',
$OUTPUT->container_start('reportbuilderform') . html_writer::start_tag('table') . html_writer::start_tag('tr') .
html_writer::tag('th', get_string('type', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('value', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('heading', 'corplms_reportbuilder')) .
html_writer::tag('th', get_string('options', 'corplms_reportbuilder')) . html_writer::end_tag('tr'));
foreach ($badcolumns as $bad) {
$deleteurl = new moodle_url('/corplms/reportbuilder/columns.php',
array('d' => '1', 'id' => $id, 'cid' => $bad['id']));
$mform->addElement('html', html_writer::start_tag('tr', array('colid' => $bad['id'])) .
html_writer::tag('td', $bad['type']) .
html_writer::tag('td', $bad['value']) .
html_writer::tag('td', $bad['heading']) .
html_writer::start_tag('td') .
html_writer::link($deleteurl, $OUTPUT->pix_icon('/t/delete', $strdelete),
array('title' => $strdelete, 'class' => 'deletecolbtn')) .
html_writer::end_tag('td') . html_writer::end_tag('tr'));
}
$mform->addElement('html', html_writer::end_tag('table') . $OUTPUT->container_end());
}
$mform->addElement('header', 'sorting', get_string('sorting', 'corplms_reportbuilder'));
$mform->addHelpButton('sorting', 'reportbuildersorting', 'corplms_reportbuilder');
$pick = array('' => get_string('noneselected', 'corplms_reportbuilder'));
$select = array_merge($pick, $columnoptions);
$mform->addElement('select', 'defaultsortcolumn', get_string('defaultsortcolumn', 'corplms_reportbuilder'), $select);
$mform->setDefault('defaultsortcolumn', $report->defaultsortcolumn);
$radiogroup = array();
$radiogroup[] =& $mform->createElement('radio', 'defaultsortorder', '', get_string('ascending', 'corplms_reportbuilder'), SORT_ASC);
$radiogroup[] =& $mform->createElement('radio', 'defaultsortorder', '', get_string('descending', 'corplms_reportbuilder'), SORT_DESC);
$mform->addGroup($radiogroup, 'radiogroup', get_string('defaultsortorder', 'corplms_reportbuilder'), html_writer::empty_tag('br'), false);
$mform->setDefault('defaultsortorder', $report->defaultsortorder);
} else {
$mform->addElement('html', get_string('error:nocolumns', 'corplms_reportbuilder', $report->source));
}
$mform->addElement('hidden', 'id', $id);
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'source', $report->source);
$mform->setType('source', PARAM_TEXT);
$this->add_action_buttons();
// Remove the labels from the form elements.
$renderer = $mform->defaultRenderer();
// Do not mess with $OUTPUT here, we need to get decent quickforms template
// which also includes error placeholder here.
$select_elementtemplate = '<div class="fitem"><div class="fselectgroups<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div>';
$check_elementtemplate ='<div class="fitem"><div class="fcheckbox<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div>';
$text_elementtemplate = '<div class="fitem"><div class="ftext<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div>';
$renderer->setElementTemplate($select_elementtemplate, 'newcolumns');
$renderer->setElementTemplate($select_elementtemplate, 'newadvanced');
$renderer->setElementTemplate($check_elementtemplate, 'newcustomheading');
$renderer->setElementTemplate($text_elementtemplate, 'newheading');
foreach ($goodcolumns as $cid => $unused) {
$renderer->setElementTemplate($select_elementtemplate, 'column' . $cid);
$renderer->setElementTemplate($select_elementtemplate, 'advanced' . $cid);
$renderer->setElementTemplate($check_elementtemplate, 'customheading' . $cid);
$renderer->setElementTemplate($text_elementtemplate, 'heading' . $cid);
}
}
/**
* Carries out validation of submitted form values
*
* @param array $data array of ("fieldname"=>value) of submitted data
* @param array $files array of uploaded files "element_name"=>tmp_file_path
* @return array of "element_name"=>"error_description" if there are errors,
* or an empty array if everything is OK (true allowed for backwards compatibility too).
*/
public function validation($data, $files) {
$errors = array();
// NOTE: do NOT move the validation to some obscure functions, this needs to be kept in sync with the form!
$usedcols = array();
foreach ($data as $key => $value) {
// Validate unique columns including the new column if set.
if (preg_match('/^column\d+/', $key) or ($key === 'newcolumns' and $value)) {
if (isset($usedcols[$value])) {
$errors[$key] = get_string('norepeatcols', 'corplms_reportbuilder');
} else {
$usedcols[$value] = true;
}
continue;
}
// Validate the heading is not empty if custom heading used.
if (preg_match('/^heading(\d+)/', $key, $matches)) {
$cid = $matches[1];
if ($data['customheading'.$cid]) {
if (trim($value) == '') {
$errors[$key] = get_string('noemptycols', 'corplms_reportbuilder');
}
}
continue;
}
// Validate the advanced type is compatible with column.
if (preg_match('/^advanced(\d+)/', $key, $matches)) {
if ($value) {
$cid = $matches[1];
$column = $data['column'.$cid];
if (!in_array($column, $this->grouped)) { // Grouped columns do not have advanced option.
if (!in_array($value, $this->allowedadvanced[$column], true)) {
// This is non-js fallback only, no need to localise this.
$errors[$key] = get_string('error');
}
}
}
continue;
}
}
return $errors;
}
}
/**
* Formslib template for graph form
*/
class report_builder_edit_graph_form extends moodleform {
public function definition() {
global $CFG, $OUTPUT;
$mform = $this->_form;
/* @var reportbuilder $report */
$report = $this->_customdata['report'];
$graph = $this->_customdata['graph'];
// Graph types.
$types = array(
'' => get_string('none'),
'column' => get_string('graphtypecolumn', 'corplms_reportbuilder'),
'line' => get_string('graphtypeline', 'corplms_reportbuilder'),
'bar' => get_string('graphtypebar', 'corplms_reportbuilder'),
'pie' => get_string('graphtypepie', 'corplms_reportbuilder'),
'scatter' => get_string('graphtypescatter', 'corplms_reportbuilder'),
'area' => get_string('graphtypearea', 'corplms_reportbuilder'),
);
$mform->addElement('select', 'type', get_string('graphtype', 'corplms_reportbuilder'), $types);
$optionoptions = array(
'C' => get_string('graphorientationcolumn', 'corplms_reportbuilder'),
'R' => get_string('graphorientationrow', 'corplms_reportbuilder'),
);
$mform->addElement('select', 'orientation', get_string('graphorientation', 'corplms_reportbuilder'), $optionoptions);
$mform->addHelpButton('orientation', 'graphorientation', 'corplms_reportbuilder');
$mform->addElement('header', 'serieshdr', 'Data');
$catoptions = array('none' => get_string('graphnocategory', 'corplms_reportbuilder'));
$legendoptions = array();
foreach ($report->columns as $key => $column) {
if (!$column->display_column(true)) {
continue;
}
$catoptions[$key] = $report->format_column_heading($column, true);
$legendoptions[$key] = $catoptions[$key];
}
$mform->addElement('select', 'category', get_string('graphcategory', 'corplms_reportbuilder'), $catoptions);
$mform->disabledIf('category', 'type', 'eq', '');
$mform->disabledIf('category', 'orientation', 'noteq', 'C');
$mform->addElement('select', 'legend', get_string('graphlegend', 'corplms_reportbuilder'), $legendoptions);
$mform->disabledIf('legend', 'type', 'eq', '');
$mform->disabledIf('legend', 'orientation', 'noteq', 'R');
$series = array();
foreach ($catoptions as $key => $colheading) {
if ($key === 'none') {
continue;
}
$series[$key] = $colheading;
}
$mform->addElement('select', 'series', get_string('graphseries', 'corplms_reportbuilder'), $series, array('multiple' => true));
$mform->disabledIf('series', 'type', 'eq', '');
$mform->addElement('advcheckbox', 'stacked', get_string('graphstacked', 'corplms_reportbuilder'));
$mform->disabledIf('stacked', 'type', 'eq', '');
$mform->disabledIf('stacked', 'type', 'eq', 'pie');
$mform->disabledIf('stacked', 'type', 'eq', 'scatter');
$mform->addElement('header', 'advancedhdr', 'Advanced options');
$mform->addElement('text', 'maxrecords', get_string('graphmaxrecords', 'corplms_reportbuilder'));
$mform->setType('maxrecords', PARAM_INT);
$mform->disabledIf('maxrecords', 'type', 'eq', '');
$mform->addElement('textarea', 'settings', get_string('graphsettings', 'corplms_reportbuilder'), array('rows' => 10));
$mform->addHelpButton('settings', 'graphsettings', 'corplms_reportbuilder');
$mform->setType('settings', PARAM_RAW);
$mform->disabledIf('settings', 'type', 'eq', '');
// No need for param 'id' here.
$mform->addElement('hidden', 'reportid');
$mform->setType('reportid', PARAM_INT);
$this->add_action_buttons();
$this->set_data($graph);
}
function validation($data, $files) {
$errors = parent::validation($data, $files);
if ($data['type']) {
if ($data['orientation'] == 'C') {
if (!empty($data['series'])) {
$key = array_search($data['category'], $data['series']);
if ($key !== false) {
unset($data['series'][$key]);
}
}
} else {
if (!empty($data['series'])) {
$key = array_search($data['legend'], $data['series']);
if ($key !== false) {
unset($data['series'][$key]);
}
}
}
if (empty($data['series'])) {
$errors['series'] = get_string('required');
}
}
if (trim($data['settings'])) {
// Unfortunately it is not easy to get meaningful errors from this parser.
$test = @parse_ini_string($data['settings'], false);
if ($test === false) {
$errors['settings'] = get_string('error');
}
}
return $errors;
}
}
/**
* Formslib template for content restrictions form
*/
class report_builder_edit_content_form extends moodleform {
function definition() {
global $DB;
$mform =& $this->_form;
$report = $this->_customdata['report'];
$id = $this->_customdata['id'];
// get array of content options
$contentoptions = isset($report->contentoptions) ?
$report->contentoptions : array();
$mform->addElement('header', 'contentheader', get_string('contentcontrols', 'corplms_reportbuilder'));
if (count($contentoptions)) {
if ($report->embeddedurl !== null) {
$mform->addElement('html', html_writer::tag('p', get_string('embeddedcontentnotes', 'corplms_reportbuilder')));
}
$radiogroup = array();
$radiogroup[] =& $mform->createElement('radio', 'contentenabled', '', get_string('nocontentrestriction', 'corplms_reportbuilder'), 0);
$radiogroup[] =& $mform->createElement('radio', 'contentenabled', '', get_string('withcontentrestrictionany', 'corplms_reportbuilder'), 1);
$radiogroup[] =& $mform->createElement('radio', 'contentenabled', '', get_string('withcontentrestrictionall', 'corplms_reportbuilder'), 2);
$mform->addGroup($radiogroup, 'radiogroup', get_string('restrictcontent', 'corplms_reportbuilder'), html_writer::empty_tag('br'), false);
$mform->addHelpButton('radiogroup', 'reportbuildercontentmode', 'corplms_reportbuilder');
$mform->setDefault('contentenabled', $DB->get_field('report_builder', 'contentmode', array('id' => $id)));
// display any content restriction form sections that are enabled for
// this source
foreach ($contentoptions as $option) {
$classname = 'rb_' . $option->classname.'_content';
if (class_exists($classname)) {
$obj = new $classname();
$obj->form_template($mform, $id, $option->title);
}
}
$mform->addElement('hidden', 'id', $id);
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'source', $report->source);
$mform->setType('source', PARAM_TEXT);
$this->add_action_buttons();
} else {
// there are no content restrictions for this source. Inform the user
$mform->addElement('html',
get_string('error:nocontentrestrictions',
'corplms_reportbuilder', $report->source));
}
}
}
/**
* Formslib template for access restrictions form
*/
class report_builder_edit_access_form extends moodleform {
function definition() {
global $DB;
$mform =& $this->_form;
$report = $this->_customdata['report'];
$id = $this->_customdata['id'];
$mform->addElement('header', 'access', get_string('accesscontrols', 'corplms_reportbuilder'));
if ($report->embeddedurl !== null) {
$mform->addElement('html', html_writer::tag('p', get_string('embeddedaccessnotes', 'corplms_reportbuilder')));
}
$radiogroup = array();
$radiogroup[] =& $mform->createElement('radio', 'accessenabled', '', get_string('norestriction', 'corplms_reportbuilder'), 0);
$radiogroup[] =& $mform->createElement('radio', 'accessenabled', '', get_string('withrestriction', 'corplms_reportbuilder'), 1);
$mform->addGroup($radiogroup, 'radiogroup', get_string('restrictaccess', 'corplms_reportbuilder'), html_writer::empty_tag('br'), false);
$mform->setDefault('accessenabled', $DB->get_field('report_builder', 'accessmode', array('id' => $id)));
$mform->addHelpButton('radiogroup', 'reportbuilderaccessmode', 'corplms_reportbuilder');
// loop round classes, only considering classes that extend rb_base_access
foreach (get_declared_classes() as $class) {
if (is_subclass_of($class, 'rb_base_access')) {
$obj = new $class();
// add any form elements for this access option
$obj->form_template($mform, $id);
}
}
$mform->addElement('hidden', 'id', $id);
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'source', $report->source);
$mform->setType('source', PARAM_TEXT);
$this->add_action_buttons();
}
}
/**
* Formslib tempalte for the edit report form
*/
class report_builder_edit_performance_form extends moodleform {
function definition() {
global $output, $CFG;
$mform =& $this->_form;
$report = $this->_customdata['report'];
$id = $this->_customdata['id'];
$schedule = $this->_customdata['schedule'];
$mform->addElement('header', 'general', get_string('initialdisplay_heading', 'corplms_reportbuilder'));
$initial_display_attributes = sizeof($report->filters) < 1 ? array('disabled' => 'disabled', 'group' => null) : null;
$initial_display_sidenote = is_null($initial_display_attributes) ? '' : get_string('initialdisplay_disabled', 'corplms_reportbuilder');
$mform->addElement('advcheckbox', 'initialdisplay', get_string('initialdisplay', 'corplms_reportbuilder'),
$initial_display_sidenote, $initial_display_attributes, array(RB_INITIAL_DISPLAY_SHOW, RB_INITIAL_DISPLAY_HIDE));
$mform->setType('initialdisplay', PARAM_INT);
$mform->setDefault('initialdisplay', RB_INITIAL_DISPLAY_SHOW);
$mform->addHelpButton('initialdisplay', 'initialdisplay', 'corplms_reportbuilder');
$mform->addElement('header', 'general', get_string('reportbuildercache_heading', 'corplms_reportbuilder'));
if (!empty($CFG->enablereportcaching)) {
//only show report cache settings if it is enabled
$caching_attributes = $report->src->cacheable ? null : array('disabled' => 'disabled', 'group' => null);
$caching_sidenote = is_null($caching_attributes) ? '' :
get_string('reportbuildercache_disabled', 'corplms_reportbuilder');
$mform->addElement('advcheckbox', 'cache', get_string('cache', 'corplms_reportbuilder'),
$caching_sidenote, $caching_attributes, array(0, 1));
$mform->setType('cache', PARAM_INT);
$mform->addHelpButton('cache', 'reportbuildercache', 'corplms_reportbuilder');
$mform->addElement('scheduler', 'schedulegroup', get_string('reportbuildercachescheduler', 'corplms_reportbuilder'));
$mform->disabledIf('schedulegroup', 'cache');
$mform->addHelpButton('schedulegroup', 'reportbuildercachescheduler', 'corplms_reportbuilder');
$mform->addElement('static', 'servertime', get_string('reportbuildercacheservertime', 'corplms_reportbuilder'),
date_format_string(time(), get_string('strftimedaydatetime', 'langconfig')));
$mform->addHelpButton('servertime', 'reportbuildercacheservertime', 'corplms_reportbuilder');
$usertz = corplms_get_clean_timezone();
$cachetime = isset($report->cacheschedule->lastreport) ? $report->cacheschedule->lastreport : 0;
$cachedstr = get_string('lastcached','corplms_reportbuilder', userdate($cachetime, '', $usertz));
$notcachedstr = get_string('notcached','corplms_reportbuilder');
$lastcached = ($cachetime > 0) ? $cachedstr : $notcachedstr;
if ($report->cache) {
$mform->addElement('static', 'cachenowselector', get_string('reportbuilderinitcache', 'corplms_reportbuilder'),
html_writer::tag('span', $lastcached. ' ') .
$output->cachenow_button($id)
);
} else {
$mform->addElement('advcheckbox', 'generatenow', get_string('cachenow', 'corplms_reportbuilder'), '', null, array(0, 1));
$mform->setType('generatenow', PARAM_INT);
$mform->addHelpButton('generatenow', 'cachenow', 'corplms_reportbuilder');
$mform->disabledIf('generatenow', 'cache');
}
} else {
//report caching is not enabled, inform user and link to settings page.
$mform->addElement('hidden', 'cache', 0);
$mform->setType('cache', PARAM_INT);
$enablelink = new moodle_url("/".$CFG->admin."/settings.php", array('section' => 'optionalsubsystems'));
$mform->addElement('static', 'reportcachingdisabled', '', get_string('reportcachingdisabled', 'corplms_reportbuilder', $enablelink->out()));
}
$mform->addElement('hidden', 'id', $id);
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'source', $report->source);
$mform->setType('source', PARAM_TEXT);
// set the defaults
$this->set_data($report);
$this->set_data($schedule);
$this->add_action_buttons();
}
}
/**
* Method to check a shortname is unique in database
*
* @param array $data Array of data from the form
*
* @return array Array of errors to display on failure
*/
function validate_shortname($data) {
global $DB;
$errors = array();
$foundreports = $DB->get_records('report_builder', array('shortname' => $data['shortname']));
if (count($foundreports)) {
if (!empty($data['id'])) {
unset($foundreports[$data['id']]);
}
if (!empty($foundreports)) {
$errors['shortname'] = get_string('shortnametaken', 'corplms_reportbuilder');
}
}
return $errors;
}
/**
* Method to check each filter is only included once
*
* @param array $data Array of data from the form
*
* @return array Array of errors to display on failure
*/
function validate_unique_filters($data) {
global $DB;
$errors = array();
$id = $data['id'];
$used_filters = array();
$currentfilters = $DB->get_records('report_builder_filters', array('reportid' => $id));
foreach ($currentfilters as $filt) {
$field = "filter{$filt->id}";
if (isset($data[$field])) {
if (array_key_exists($data[$field], $used_filters)) {
$errors[$field] = get_string('norepeatfilters', 'corplms_reportbuilder');
} else {
$used_filters[$data[$field]] = 1;
}
}
}
// also check new filter if set
if (isset($data['newfilter'])) {
if (array_key_exists($data['newfilter'], $used_filters)) {
$errors['newfilter'] = get_string('norepeatfilters', 'corplms_reportbuilder');
}
}
return $errors;
}
/**
* Formslib template for saved searches form
*/
class report_builder_save_form extends moodleform {
function definition() {
$mform = $this->_form;
$report = $this->_customdata['report'];
$data = $this->_customdata['data'];
$filterparams = $report->get_restriction_descriptions('filter');
$params = implode(html_writer::empty_tag('br'), $filterparams);
if ($data->sid) {
$mform->addElement('header', 'savesearch', get_string('editingsavedsearch', 'corplms_reportbuilder'));
} else {
$mform->addElement('header', 'savesearch', get_string('createasavedsearch', 'corplms_reportbuilder'));
}
$mform->addElement('static', 'description', '', get_string('savedsearchdesc', 'corplms_reportbuilder'));
$mform->addElement('static', 'params', get_string('currentsearchparams', 'corplms_reportbuilder'), $params);
$mform->addElement('text', 'name', get_string('searchname', 'corplms_reportbuilder'));
$mform->setType('name', PARAM_TEXT);
$mform->addRule('name', get_string('missingsearchname', 'corplms_reportbuilder'), 'required', null, 'server');
$mform->addElement('advcheckbox', 'ispublic', get_string('publicallyavailable', 'corplms_reportbuilder'), '', null, array(0, 1));
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'sid');
$mform->setType('sid', PARAM_INT);
$mform->addElement('hidden', 'action');
$mform->setType('action', PARAM_ALPHANUMEXT);
$this->add_action_buttons();
$this->set_data($data);
}
}
class report_builder_standard_search_form extends moodleform {
function definition() {
$mform =& $this->_form;
$fields = $this->_customdata['fields'];
$mform->disable_form_change_checker();
if ($fields && is_array($fields) && count($fields) > 0) {
$mform->addElement('header', 'newfilterstandard', get_string('searchby', 'corplms_reportbuilder'));
foreach ($fields as $ft) {
$ft->setupForm($mform);
}
$submitgroup = array();
$submitgroup[] =& $mform->createElement('html', ' ', html_writer::empty_tag('br'));
$submitgroup[] =& $mform->createElement('submit', 'addfilter',
get_string('search', 'corplms_reportbuilder'));
$submitgroup[] =& $mform->createElement('submit', 'clearstandardfilters',
get_string('clearform', 'corplms_reportbuilder'));
$mform->addGroup($submitgroup, 'submitgroupstandard', ' ', ' ');
}
}
function definition_after_data() {
$mform =& $this->_form;
$fields = $this->_customdata['fields'];
if ($fields && is_array($fields) && count($fields) > 0) {
foreach ($fields as $ft) {
if (method_exists($ft, 'definition_after_data')) {
$ft->definition_after_data($mform);
}
}
}
}
}
class report_builder_sidebar_search_form extends moodleform {
public function definition() {
$mform =& $this->_form;
$report = $this->_customdata['report'];
$id = $report->_id;
$fields = $this->_customdata['fields'];
$mform->updateAttributes(array('id' => 'sidebarfilter'.$id));
$mform->disable_form_change_checker();
if ($fields && is_array($fields) && count($fields) > 0) {
$mform->_attributes['class'] = 'span3 mform rb-sidebar desktop-first-column';
$mform->addElement('header', 'newfiltersidebar', get_string('filterby', 'corplms_reportbuilder'));
foreach ($fields as $ft) {
$ft->setupForm($mform);
}
$submitgroup = array();
$submitgroup[] =& $mform->createElement('html', ' ', html_writer::empty_tag('br'));
$submitgroup[] =& $mform->createElement('submit', 'addfilter',
get_string('search', 'corplms_reportbuilder'));
$submitgroup[] =& $mform->createElement('submit', 'clearsidebarfilters',
get_string('clearform', 'corplms_reportbuilder'));
$mform->addGroup($submitgroup, 'submitgroupsidebar', ' ', ' ');
}
$mform->addElement('hidden', 'id', $id);
$mform->setType('id', PARAM_INT);
}
public function definition_after_data() {
$mform =& $this->_form;
$report = $this->_customdata['report'];
$fields = $this->_customdata['fields'];
$report->add_filter_counts($mform);
if ($fields && is_array($fields) && count($fields) > 0) {
foreach ($fields as $ft) {
if (method_exists($ft, 'definition_after_data')) {
$ft->definition_after_data($mform);
}
}
}
}
}
class report_builder_toolbar_search_form extends moodleform {
public function definition() {
$mform =& $this->_form;
$mform->addElement('text', 'toolbarsearchtext',
get_string('searchby', 'corplms_reportbuilder'));
$mform->setType('toolbarsearchtext', PARAM_TEXT);
$mform->addElement('submit', 'toolbarsearchbutton',
get_string('search', 'corplms_reportbuilder'));
$mform->addElement('submit', 'cleartoolbarsearchtext',
get_string('clearform', 'corplms_reportbuilder'));
}
public function definition_after_data() {
$mform =& $this->_form;
$toolbarsearchtext = $this->_customdata['toolbarsearchtext'];
$mform->setDefault('toolbarsearchtext', $toolbarsearchtext);
}
}
class report_builder_course_expand_form extends moodleform {
public function definition() {
global $PAGE, $CFG;
$mform =& $this->_form;
$summary = $this->_customdata['summary'];
$status = $this->_customdata['status'];
$inlineenrolmentelements = isset($this->_customdata['inlineenrolmentelements'])
? $this->_customdata['inlineenrolmentelements'] : '';
$enroltype = isset($this->_customdata['enroltype']) ? $this->_customdata['enroltype'] : '';
$progress = isset($this->_customdata['progress']) ? $this->_customdata['progress'] : '';
$enddate = isset($this->_customdata['enddate']) ? $this->_customdata['enddate'] : '';
$grade = isset($this->_customdata['grade']) ? $this->_customdata['grade'] : '';
$courseid = $this->_customdata['courseid'];
$action = $this->_customdata['action'];
$url = $this->_customdata['url'];
if ($summary != '') {
$mform->addElement('static', 'summary', get_string('coursesummary'), $summary);
}
if ($status != '') {
$mform->addElement('static', 'status', get_string('status'), $status);
}
if ($enroltype != '') {
$mform->addElement('static', 'enroltype', get_string('courseenroltype', 'corplms_reportbuilder'), $enroltype);
}
if ($progress != '') {
$mform->addElement('static', 'progress', get_string('courseprogress', 'corplms_reportbuilder'), $progress);
}
if ($enddate != '') {
$mform->addElement('static', 'enddate', get_string('courseenddate', 'corplms_reportbuilder'), $enddate);
}
if ($grade != '') {
$mform->addElement('static', 'grade', get_string('grade'), $grade);
}
$mform->addElement('hidden', 'courseid', $courseid);
if (count($inlineenrolmentelements) > 0) {
// If we haven't enrolled there may be notifications with errors in so display them now.
$corplmsrenderer = $PAGE->get_renderer('corplms_core', null);
$notifications = $corplmsrenderer->print_corplms_notifications();
$mform->addElement('static', 'notifications', $notifications);
}
foreach ($inlineenrolmentelements as $inlineenrolmentelement) {
$mform->addElement($inlineenrolmentelement);
if ($inlineenrolmentelement->_type == 'header') { // Headers are collapsed by default and we want them open.
$mform->setExpanded($inlineenrolmentelement->getName());
}
}
if ($url != '') {
$mform->addElement('static', 'enrol', '', html_writer::link($url, $action,
array('class' => 'link-as-button')));
}
}
}
class report_builder_program_expand_form extends moodleform {
public function definition() {
$mform =& $this->_form;
$prog = $this->_customdata;
if ($prog['summary']) {
$mform->addElement('static', 'summary', get_string('summary', 'corplms_program'), $prog['summary']);
}
if ($prog['certifid']) {
$type = 'certification';
if ($prog['assigned']) {
$mform->addElement('static', 'status', get_string('status'), get_string('youareassigned', 'corplms_certification'));
}
} else {
$type = 'program';
if ($prog['assigned']) {
$mform->addElement('static', 'status', get_string('status'), get_string('youareassigned', 'corplms_program'));
}
}
$url = new moodle_url('/corplms/program/view.php', array('id' => $prog['id']));
$mform->addElement('static', 'view', '', html_writer::link($url, get_string('view' . $type, 'corplms_' . $type),
array('class' => 'link-as-button')));
}
}
| gpl-3.0 |
projectcuracao/projectcuracao | testSelectSolar.py | 803 |
"""
testSelectSolar.py
JCS 01/14/2014 Version 1.0
This program selects Solar
"""
# shelves:
# datacollect - sensor data collection - disabled to RAM
# graphprep - building system graphs
# housekeeping - fan check , general health and wellfare
# alarmchecks - checks for system health alarms
# actions - specific actions scheduled (i.e. camera picture)
from datetime import datetime, timedelta
import sys
import time
from apscheduler.scheduler import Scheduler
from apscheduler.jobstores.shelve_store import ShelveJobStore
sys.path.append('./datacollect')
sys.path.append('./graphprep')
sys.path.append('./hardware')
sys.path.append('./housekeeping')
sys.path.append('./alarmchecks')
sys.path.append('./actions')
import selectSolar
print( "result=",selectSolar.selectSolar("test", 1) )
| gpl-3.0 |
scurest/Player | src/decoder_wildmidi.cpp | 6526 | /*
* This file is part of EasyRPG Player.
*
* EasyRPG Player 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.
*
* EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
*/
#include "system.h"
#ifdef HAVE_WILDMIDI
// Headers
#include <cassert>
#include <stdlib.h>
#include <wildmidi_lib.h>
#include "audio_decoder.h"
#include "output.h"
#include "filefinder.h"
#include "utils.h"
#include "decoder_wildmidi.h"
#if defined(GEKKO) || defined(_3DS)
# define WILDMIDI_FREQ 22050
#else
# define WILDMIDI_FREQ 44100
#endif
/* possible options include: WM_MO_REVERB|WM_MO_ENHANCED_RESAMPLING
* however, they cause high cpu usage, so not using them for now.
*/
#define WILDMIDI_OPTS 0
static bool init = false;
static void WildMidiDecoder_deinit(void) {
WildMidi_Shutdown();
}
WildMidiDecoder::WildMidiDecoder(const std::string file_name) {
music_type = "midi";
filename = file_name;
std::string config_file = "";
bool found = false;
// only initialize once
if (init)
return;
/* find the configuration file in different paths on different platforms
* FIXME: move this logic into some configuration class
*/
#ifdef GEKKO
// preferred under /data
config_file = "usb:/data/wildmidi/wildmidi.cfg";
found = FileFinder::Exists(config_file);
if (!found) {
config_file = "sd:/data/wildmidi/wildmidi.cfg";
found = FileFinder::Exists(config_file);
}
// app directory
if (!found) {
config_file = "wildmidi.cfg";
found = FileFinder::Exists(config_file);
}
// same, but legacy from SDL_mixer's timidity
if (!found) {
config_file = "usb:/data/timidity/timidity.cfg";
found = FileFinder::Exists(config_file);
}
if (!found) {
config_file = "sd:/data/timidity/timidity.cfg";
found = FileFinder::Exists(config_file);
}
if (!found) {
config_file = "timidity.cfg";
found = FileFinder::Exists(config_file);
}
#elif _3DS
// Only wildmidi paths, no timidity because there was never timidity used on 3DS
// Shipped in a romfs (for CIA files)
config_file = "romfs:/wildmidi.cfg";
found = FileFinder::Exists(config_file);
// preferred SD card directory
if (!found) {
config_file = "sdmc:/3ds/easyrpg-player/wildmidi.cfg";
found = FileFinder::Exists(config_file);
}
// Current directory
if (!found) {
config_file = "wildmidi.cfg";
found = FileFinder::Exists(config_file);
}
#else
// Prefer wildmidi in current directory
config_file = "wildmidi.cfg";
found = FileFinder::Exists(config_file);
// Use Timidity strategy used in SDL mixer
// Environment variable
const char *env = getenv("TIMIDITY_CFG");
if (env) {
config_file = env;
found = FileFinder::Exists(config_file);
}
if (!found) {
config_file = "timidity.cfg";
found = FileFinder::Exists(config_file);
}
# ifdef _WIN32
// Probably not too useful
if (!found) {
config_file = "C:\\TIMIDITY\\timidity.cfg";
found = FileFinder::Exists(config_file);
}
// TODO: We need some installer which creates registry keys for wildmidi
# else
if (!found) {
config_file = "/etc/timidity.cfg";
found = FileFinder::Exists(config_file);
}
if (!found) {
// Folders used in timidity code
const std::vector<std::string> folders = {
"/etc/timidity",
"/usr/share/timidity",
"/usr/local/share/timidity",
"/usr/local/lib/timidity"
};
for (const std::string& s : folders) {
config_file = s + "/timidity.cfg";
found = FileFinder::Exists(config_file);
if (found) {
break;
}
// Some distributions have it in timidity++
config_file = s + "++/timidity.cfg";
found = FileFinder::Exists(config_file);
if (found) {
break;
}
}
}
# endif
#endif
// bail, if nothing found
if (!found) {
error_message = "WildMidi: Could not find configuration file.";
return;
}
Output::Debug("WildMidi: Using %s as configuration file...", config_file.c_str());
init = (WildMidi_Init(config_file.c_str(), WILDMIDI_FREQ, WILDMIDI_OPTS) == 0);
if (!init) {
error_message = "Could not initialize libWildMidi";
return;
}
// setup deinitialization
atexit(WildMidiDecoder_deinit);
}
WildMidiDecoder::~WildMidiDecoder() {
if (handle)
WildMidi_Close(handle);
}
bool WildMidiDecoder::WasInited() const {
return init;
}
bool WildMidiDecoder::Open(FILE* file) {
if (!init)
return false;
// this should not happen
if (handle) {
WildMidi_Close(handle);
Output::Debug("WildMidi: Previous handle was not closed.");
}
handle = WildMidi_Open(filename.c_str());
if (!handle) {
error_message = "WildMidi: Error reading file";
return false;
}
fclose(file);
return true;
}
bool WildMidiDecoder::Seek(size_t offset, Origin origin) {
if (offset == 0 && origin == Origin::Begin) {
if (handle) {
unsigned long int pos = 0;
WildMidi_FastSeek(handle, &pos);
}
return true;
}
return false;
}
bool WildMidiDecoder::IsFinished() const {
if (!handle)
return false;
struct _WM_Info* midi_info = WildMidi_GetInfo(handle);
return midi_info->current_sample >= midi_info->approx_total_samples;
}
void WildMidiDecoder::GetFormat(int& freq, AudioDecoder::Format& format, int& channels) const {
freq = WILDMIDI_FREQ;
format = Format::S16;
channels = 2;
}
bool WildMidiDecoder::SetFormat(int freq, AudioDecoder::Format format, int channels) {
if (freq != WILDMIDI_FREQ || channels != 2 || format != Format::S16)
return false;
return true;
}
int WildMidiDecoder::FillBuffer(uint8_t* buffer, int length) {
if (!handle)
return -1;
/* Old wildmidi (< 0.4.0) did output only in little endian and had a different API,
* this inverts the buffer. The used version macro exists since 0.4.0.
*/
#ifndef LIBWILDMIDI_VERSION
int res = WildMidi_GetOutput(handle, reinterpret_cast<char*>(buffer), length);
if (Utils::IsBigEndian() && res > 0) {
uint16_t* buffer_16 = reinterpret_cast<uint16_t*>(buffer);
for (int i = 0; i < res / 2; ++i) {
Utils::SwapByteOrder(buffer_16[i]);
}
}
#else
int res = WildMidi_GetOutput(handle, reinterpret_cast<int8_t*>(buffer), length);
#endif
return res;
}
#endif
| gpl-3.0 |
PavelSilukou/AlienRP | AlienRP/Elements/TrackTimeline.xaml.cs | 2772 | /*
* ***** BEGIN GPL LICENSE BLOCK*****
* Copyright © 2017 Pavel Silukou
* This file is part of AlienRP.
* AlienRP 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.
* AlienRP 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 AlienRP. If not, see<http://www.gnu.org/licenses/>.
* ***** END GPL LICENSE BLOCK*****
*/
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
namespace AlienRP.Elements
{
public partial class TrackTimeline : UserControl
{
DispatcherTimer trackTimelineTimer;
private double trackTimeTicks = 0;
private double finishTrackTimeTicks = 0;
public TimerCompletedEvent TimerCompleted;
public TrackTimeline()
{
InitializeComponent();
trackTimelineTimer = new System.Windows.Threading.DispatcherTimer();
trackTimelineTimer.Tick += TrackTimeTick;
trackTimelineTimer.Interval = new TimeSpan(0, 0, 1);
}
private void TrackTimeTick(object sender, EventArgs e)
{
if (trackTimeTicks < finishTrackTimeTicks)
{
trackTime.Text = GetFormattedTime();
trackTimeTicks += 1;
}
else
{
TimerCompleted();
trackTimelineTimer.Stop();
}
}
private string TimeSpanToString(double time)
{
TimeSpan timeSpan = TimeSpan.FromSeconds(time);
int minutes = timeSpan.Minutes + timeSpan.Hours * 60;
return minutes.ToString() + ":" + timeSpan.ToString("ss");
}
private string GetFormattedTime()
{
return TimeSpanToString(trackTimeTicks) + " / " + TimeSpanToString(finishTrackTimeTicks);
}
public void Start(double startTime, double finishTime)
{
this.trackTimeTicks = startTime;
this.finishTrackTimeTicks = finishTime;
this.trackTimelineTimer.Start();
trackTime.Text = GetFormattedTime();
this.Visibility = Visibility.Visible;
}
public void Stop()
{
this.Visibility = Visibility.Collapsed;
this.trackTimelineTimer.Stop();
}
}
public delegate void TimerCompletedEvent();
}
| gpl-3.0 |
jhjguxin/PyCDC | Karrigell-2.3.5/webapps/demo/consoleOutput.py | 37 | import k_utils
k_utils.trace('essai') | gpl-3.0 |
webSPELL/webSPELL | languages/no/registered_users.php | 2134 | <?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2011 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'contact'=>'Kontakt',
'country'=>'C',
'homepage'=>'Hjemmeside',
'last_login'=>'Last login',
'nickname'=>'Nickname',
'no_users'=>'ingen registrerte brukere',
'now_on'=>'nå pålogget',
'registered_users'=>'registered users',
'registration'=>'Registrert siden',
'sort'=>'Sorter:'
);
?> | gpl-3.0 |
baoping/Red-Bull-Media-Player | RedBullPlayer/PlayerShell/UI/Region.cpp | 1171 | /*
* Red Bull Media Player
* Copyright (C) 2011, Red Bull
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Region.h"
// QT Includes
using namespace RedBullPlayer::PlayerShell;
RedBullPlayer::PlayerShell::Region::Region( QObject * parent, QString name, QWidget* widget ) : QObject( parent ) {
Q_ASSERT( parent != 0 );
Q_ASSERT( widget != 0 );
Q_ASSERT( ! name.isNull() );
Q_ASSERT( ! name.isEmpty() );
_widget = widget;
_name = name;
}
RedBullPlayer::PlayerShell::Region::~Region() {}
| gpl-3.0 |
albertz/diplom-thesis-math | src/utils.py | 21773 | # -*- coding: utf-8 -*-
# Hermitian modular forms, https://github.com/albertz/diplom-thesis-math
# Copyright (c) 2013, Albert Zeyer, www.az2000.de
# This code is under the GPL v3 or later, see License.txt in the root directory of this project.
from threading import currentThread
import time, os
from sage.matrix.matrix2 import Matrix
from sage.rings.integer import Integer
from sage.structure.sage_object import SageObject
from sage.modules.free_module_element import vector
from sage.structure.sequence import Sequence_generic, Sequence
from sage.symbolic.ring import SymbolicRing
from sage.symbolic.expression import Expression
# For debugging. It's a drop-in replacement for sys.excepthook.
import better_exchook
# our own verbose function because I just want our msgs, not other stuff
def verbose(msg):
print msg
MyDir = os.path.dirname(__file__) or os.getcwd()
MyDir = os.path.abspath(MyDir)
# It seems that Sage load/save uses the standard pickle module.
# The standard pickle cannot save the Sage Expression objects for some reason.
# We extend the standard pickler.
import pickle, types, marshal, sys
CellType = type((lambda x: lambda: x)(0).func_closure[0])
def makeCell(value): return (lambda: value).func_closure[0]
def getModuleDict(modname): return __import__(modname).__dict__
class Pickler(pickle.Pickler):
def __init__(self, *args, **kwargs):
if not "protocol" in kwargs:
kwargs["protocol"] = pickle.HIGHEST_PROTOCOL
pickle.Pickler.__init__(self, *args, **kwargs)
dispatch = pickle.Pickler.dispatch.copy()
def save_func(self, obj):
try:
self.save_global(obj)
return
except pickle.PicklingError:
pass
assert type(obj) is types.FunctionType
self.save(types.FunctionType)
self.save((
obj.func_code,
obj.func_globals,
obj.func_name,
obj.func_defaults,
obj.func_closure,
))
self.write(pickle.REDUCE)
self.memoize(obj)
dispatch[types.FunctionType] = save_func
def save_code(self, obj):
assert type(obj) is types.CodeType
self.save(marshal.loads)
self.save((marshal.dumps(obj),))
self.write(pickle.REDUCE)
self.memoize(obj)
dispatch[types.CodeType] = save_code
def save_cell(self, obj):
assert type(obj) is CellType
self.save(makeCell)
self.save((obj.cell_contents,))
self.write(pickle.REDUCE)
self.memoize(obj)
dispatch[CellType] = save_cell
# We also search for module dicts and reference them.
def intellisave_dict(self, obj):
if len(obj) <= 5: # fastpath
self.save_dict(obj)
return
for modname, mod in sys.modules.iteritems():
if not mod: continue
if modname == "__main__": continue
moddict = mod.__dict__
if obj is moddict:
self.save(getModuleDict)
self.save((modname,))
self.write(pickle.REDUCE)
self.memoize(obj)
return
self.save_dict(obj)
dispatch[types.DictionaryType] = intellisave_dict
# Some types in the types modules are not correctly referenced,
# such as types.FunctionType. This is fixed here.
def fixedsave_type(self, obj):
try:
self.save_global(obj)
return
except pickle.PicklingError:
pass
for modname in ["types"]:
moddict = sys.modules[modname].__dict__
for modobjname,modobj in moddict.iteritems():
if modobj is obj:
self.write(pickle.GLOBAL + modname + '\n' + modobjname + '\n')
self.memoize(obj)
return
self.save_global(obj)
dispatch[types.TypeType] = fixedsave_type
# Wrap _batch_setitems (e.g. for dicts) so that our representations stays fixed
# (the order of dict.keys() can be different at each run).
orig_batch_setitems = pickle.Pickler._batch_setitems
def _batch_setitems(self, items):
items = sorted(items)
self.orig_batch_setitems(iter(items))
# Wrap save_reduce so that we can catch a few cases (e.g. set)
# to fix up the representation so that it stays fixed (as for dicts).
orig_save_reduce = pickle.Pickler.save_reduce
def save_reduce(self, func, args, state=None, listitems=None, dictitems=None, obj=None):
if func is set:
assert len(args) == 1
args = (sorted(args[0]),)
self.orig_save_reduce(func=func, args=args, state=state, listitems=listitems, dictitems=dictitems, obj=obj)
# avoid pickling instances of ourself. this mostly doesn't make sense and leads to trouble.
# however, also doesn't break. it mostly makes sense to just ignore.
def __getstate__(self): return None
def __setstate__(self, state): pass
# The extended Pickler above writes pickle-data such that the standard unpickler
# should be able to unpickle it.
# However, Sage has problems to generate some objects, so we catch those and automatically
# create equivalent structures.
class Unpickler(pickle.Unpickler):
dispatch = dict(pickle.Unpickler.dispatch)
def create(self, cls, args):
if cls is Sequence_generic:
return Sequence(list(*args))
return cls.__new__(cls, *args)
def wrapped_load_newobj(self):
args = self.stack.pop()
cls = self.stack[-1]
obj = self.create(cls, args)
self.stack[-1] = obj
dispatch[pickle.NEWOBJ] = wrapped_load_newobj
# We dont use these:
#from sage.misc.db import save, load
# But these:
def save(obj, filename):
from StringIO import StringIO
s = StringIO()
pickler = Pickler(s)
pickler.dump(obj)
try:
f = open(filename, "w")
f.write(s.getvalue())
except BaseException:
# try again
f = open(filename, "w")
f.write(s.getvalue())
# but reraise
raise
def load(filename):
f = open(filename)
unpickler = Unpickler(f)
obj = unpickler.load()
return obj
CacheEnabled = True
if not int(os.environ.get("CACHE", 1)):
print "Cache disabled"
CacheEnabled = False
class PersistentCache:
def __init__(self, name):
self.name = name
def _key_repr(self, key):
from StringIO import StringIO
key_sstr = StringIO()
Pickler(key_sstr).dump(key)
key_str = key_sstr.getvalue()
import hashlib
m = hashlib.md5()
m.update(key_str)
return m.hexdigest()
def _filename_for_key(self, key):
return MyDir + "/cache/" + self.name + "_" + self._key_repr(key) + ".sobj"
def _filename_pattern(self):
return MyDir + "/cache/" + self.name + "_*.sobj"
def __getitem__(self, key):
if not CacheEnabled: raise KeyError
try:
cache_key, value = load(self._filename_for_key(key))
except IOError:
raise KeyError, "cache file not found"
except Exception as exc:
better_exchook.better_exchook(*sys.exc_info())
if isinstance(exc, KeyError): raise Exception # no KeyError exception fall-through
raise
else:
if cache_key == key: return value
raise KeyError, "key repr collidation"
def __setitem__(self, key, value):
if not CacheEnabled: return
try:
save((key, value), self._filename_for_key(key))
except Exception:
print self.name, key
raise
def __contains__(self, key):
try: self.__getitem__(key)
except KeyError: return False
else: return True
def items(self):
if not CacheEnabled: return
from glob import glob
for fn in glob(self._filename_pattern()):
try:
key, value = load(fn)
except Exception:
print "Exception on loading cache file %s" % fn
better_exchook.better_exchook(*sys.exc_info())
raise
yield key, value
def keys(self):
if not CacheEnabled: return
for key,value in self.items():
yield key
def __iter__(self):
return self.keys()
def pickle_dumps(obj):
from StringIO import StringIO
s = StringIO()
pickler = Pickler(s)
pickler.dump(obj)
return s.getvalue()
def pickle_loads(s):
from StringIO import StringIO
ss = StringIO(s)
unpickler = Unpickler(ss)
return unpickler.load()
def persistent_cache(name, index=None, timeLimit=2, ignoreNone=True):
def decorator(func):
from functools import wraps
import algo_cython as C
import inspect
funcargs = tuple(inspect.getargspec(func).args)
funcargdefaults = tuple(inspect.getargspec(func).defaults or [])
assert len(funcargdefaults) <= len(funcargs)
NotSpecifiedFlag = object()
cache = PersistentCache(name=name)
@wraps(func)
def cached_function(*args, **kwargs):
kwargs = kwargs.copy()
if len(args) > len(funcargs): raise TypeError, "too many args"
for i,arg in enumerate(args):
key = funcargs[i]
if key in kwargs: raise TypeError, "%r specified in both args and kwargs" % arg
kwargs[key] = arg
args = list(funcargdefaults) + [NotSpecifiedFlag] * (len(funcargs) - len(funcargdefaults))
for key,value in kwargs.items():
if key not in funcargs:
raise TypeError, "kwarg %r is unknown" % key
i = funcargs.index(key)
args[i] = value
for key,value in zip(funcargs,args):
if value is NotSpecifiedFlag:
raise TypeError, "arg %r is not specified" % key
cacheidx = ()
if index is not None:
cacheidx = index(*args)
else:
for arg in args:
if isinstance(arg, C.Calc):
cacheidx += (arg.params, arg.curlS,)
else:
cacheidx += (arg,)
if cacheidx in cache:
return cache[cacheidx]
t = time.time()
res = func(*args)
if res is None and ignoreNone:
return None
if timeLimit is None or time.time() - t > timeLimit:
print "calculation of %r took %f secs" % (func, time.time() - t)
cache[cacheidx] = res
return res
return cached_function
return decorator
# This was needed to convert some cache files which were created with an earlier version
# of this code. This probably can be deleted at some later point. (2013-06-12)
def convert_old_cache(name):
old_cache_fn = MyDir + "/" + name + ".cache.sobj"
assert os.path.exists(old_cache_fn)
d = load(old_cache_fn)
assert isinstance(d, dict)
new_cache = PersistentCache(name=name)
for key,value in d.items():
new_cache[key] = value
# The following code is partly from [MusicPlayer](https://github.com/albertz/music-player/)
# but all written by me, thus I transfer this part to GPL here.
def attrChain(base, *attribs, **kwargs):
default = kwargs.get("default", None)
obj = base
for attr in attribs:
if obj is None: return default
obj = getattr(obj, attr, None)
if obj is None: return default
return obj
# This is needed in some cases to avoid pickling problems with bounded funcs.
def funcCall(attrChainArgs, args=()):
f = attrChain(*attrChainArgs)
return f(*args)
class ExecingProcess:
def __init__(self, target, args, name):
self.target = target
self.args = args
self.name = name
self.daemon = True
self.pid = None
self.isChild = False
def start(self):
assert self.pid is None
def pipeOpen():
readend,writeend = os.pipe()
readend = os.fdopen(readend, "r")
writeend = os.fdopen(writeend, "w")
return readend,writeend
self.pipe_c2p = pipeOpen()
self.pipe_p2c = pipeOpen()
pid = os.fork()
if pid == 0: # child
self.isChild = True
self.pipe_c2p[0].close()
self.pipe_p2c[1].close()
if "/local/bin/" in sys.executable: #'/Applications/sage-5.9/local/bin/python'
SageBin = os.path.normpath(os.path.dirname(sys.executable) + "/../../sage")
assert os.path.exists(SageBin), "%r" % ([SageBin, sys.executable, sys.argv, sys.exec_prefix])
else:
assert False, "%r" % ([sys.executable, sys.argv, sys.exec_prefix])
args = [
SageBin,
"run.py",
"--forkExecProc",
str(self.pipe_c2p[1].fileno()),
str(self.pipe_p2c[0].fileno())]
print "parent pid: %r, pid: %r, args: %r" % (os.getppid(), os.getpid(), args)
os.execv(args[0], args)
else: # parent
self.pipe_c2p[1].close()
self.pipe_p2c[0].close()
self.pid = pid
self.writeend = self.pipe_p2c[1]
self.readend = self.pipe_c2p[0]
self.pickler = Pickler(self.writeend)
self.pickler.dump(self.name)
self.pickler.dump(self.target)
self.pickler.dump(self.args)
self.writeend.flush()
self.unpickler = Unpickler(self.readend)
def isFinished(self):
assert not self.isChild
pid, status = os.waitpid(self.pid, os.WNOHANG)
if pid != 0: assert pid == self.pid
return pid != 0
def __del__(self):
if not self.isChild and self.pid:
import signal
os.kill(self.pid, signal.SIGINT)
os.waitpid(self.pid, 0)
@staticmethod
def checkExec():
if "--forkExecProc" in sys.argv:
argidx = sys.argv.index("--forkExecProc")
writeFileNo = int(sys.argv[argidx + 1])
readFileNo = int(sys.argv[argidx + 2])
readend = os.fdopen(readFileNo, "r")
writeend = os.fdopen(writeFileNo, "w")
unpickler = Unpickler(readend)
name = unpickler.load()
print "ExecingProcess child %s (pid %i)" % (name, os.getpid())
try:
target = unpickler.load()
args = unpickler.load()
except EOFError:
print "Error: unpickle incomplete"
raise SystemExit
pickler = Pickler(writeend)
target(*(args + (readend, unpickler, writeend, pickler)))
print "ExecingProcess child %s (pid %i) finished" % (name, os.getpid())
raise SystemExit
class ExecingProcess_ConnectionWrapper(object):
def __init__(self, readend, unpickler, writeend, pickler):
self.readend = readend
self.unpickler = unpickler
self.writeend = writeend
self.pickler = pickler
def send(self, value):
self.pickler.dump(value)
self.writeend.flush()
def recv(self):
return self.unpickler.load()
def poll(self, timeout=None):
import select
rlist, wlist, xlist = select.select([self.readend.fileno()], [], [], timeout)
return bool(rlist)
def close(self):
self.readend.close()
self.writeend.close()
class AsyncTask:
def __init__(self, func, name=None):
self.name = name or repr(func)
self.func = func
self.parent_pid = os.getpid()
# We exec() instead of just fork() because of problems with non-fork-safe libs in Sage.
# See: http://ask.sagemath.org/question/2627/sigill-in-forked-process
self.proc = ExecingProcess(
target = self._asyncCall,
args = (self,),
name = self.name + " worker process")
self.proc.daemon = True
self.proc.start()
self.child_pid = self.proc.pid
assert self.child_pid
self.conn = ExecingProcess_ConnectionWrapper(
readend=self.proc.readend,
unpickler=self.proc.unpickler,
writeend=self.proc.writeend,
pickler=self.proc.pickler)
@staticmethod
def _asyncCall(self, readend, unpickler, writeend, pickler):
assert self.isChild
self.conn = ExecingProcess_ConnectionWrapper(
readend=readend,
unpickler=unpickler,
writeend=writeend,
pickler=pickler)
try:
self.func(self)
except KeyboardInterrupt:
print "Exception in AsyncTask", self.name, ": KeyboardInterrupt"
except Exception:
print "Exception in AsyncTask", self.name
sys.excepthook(*sys.exc_info())
finally:
self.conn.close()
def put(self, value):
self.conn.send(value)
def get(self):
thread = currentThread()
try:
thread.waitQueue = self
res = self.conn.recv()
except EOFError: # this happens when the child died
raise ForwardedKeyboardInterrupt()
except Exception:
raise
finally:
thread.waitQueue = None
return res
def poll(self, **kwargs):
return self.conn.poll(**kwargs)
@property
def isParent(self):
return self.parent_pid == os.getpid()
@property
def isChild(self):
if self.isParent: return False
# No check. The Sage wrapper binary itself forks again, so this is wrong.
#assert self.parent_pid == os.getppid(), "%i, %i, %i" % (self.parent_pid, os.getppid(), os.getpid())
return True
# This might be called from the module code.
# See OnRequestQueue which implements the same interface.
def setCancel(self):
self.conn.close()
if self.isParent and self.child_pid:
import signal
os.kill(self.child_pid, signal.SIGINT)
self.child_pid = None
class ForwardedKeyboardInterrupt(Exception): pass
def asyncCall(func, name=None):
def doCall(queue):
res = None
try:
res = func()
queue.put((None,res))
except KeyboardInterrupt as exc:
print "Exception in asyncCall", name, ": KeyboardInterrupt"
queue.put((ForwardedKeyboardInterrupt(exc),None))
except BaseException as exc:
print "Exception in asyncCall", name
sys.excepthook(*sys.exc_info())
queue.put((exc,None))
task = AsyncTask(func=doCall, name=name)
# If there is an unhandled exception in doCall or the process got killed/segfaulted or so,
# this will raise an EOFError here.
# However, normally, we should catch all exceptions and just reraise them here.
exc,res = task.get()
if exc is not None:
raise exc
return res
# END of the part of MusicPlayer code.
class Parallelization_Worker:
"""
See documentation of the `Parallelization` class.
"""
def __init__(self, _id):
self.id = _id
self.joblist = []
self._init_task()
def _init_task(self):
self.task = AsyncTask(func=self._work, name="Parallel worker")
def _handle_job(self, queue, func, name):
try:
try:
res = func()
except KeyboardInterrupt as exc:
print "Exception in asyncCall", name, ": KeyboardInterrupt"
queue.put((self.id, func, ForwardedKeyboardInterrupt(exc), None))
except BaseException as exc:
print "Exception in asyncCall", name, "<pid %i>" % os.getpid(), ": %r" % exc
sys.excepthook(*sys.exc_info())
queue.put((self.id, func, exc, None))
else:
queue.put((self.id, func, None, res))
except IOError as exc:
# This is probably a broken pipe or so.
print "parallel worker <pid %i> IOError: %r" % (os.getpid(), exc)
raise SystemExit
def _work(self, queue):
while True:
func, name = queue.get()
self._handle_job(queue=queue, func=func, name=name)
def put_job(self, func, name):
job = (func, name)
self.joblist += [job]
self.task.put(job)
def is_ready(self):
return len(self.joblist) == 0
def get_result(self, block=False, timeout=None):
if not block or timeout is not None:
poll_kwargs = {}
if timeout is not None: poll_kwargs["timeout"] = timeout
if not self.task.poll(**poll_kwargs):
from Queue import Empty
raise Empty
selfid, func, exc, res = self.task.get()
assert selfid == self.id
assert len(self.joblist) > 0
self.joblist.pop(0)
return func, exc, res
def fixup_broken_proc(self):
# We expect that the proc has terminated. If it hasn't,
# this function shouldn't be called and this is a bug.
assert self.task.proc.isFinished()
self._init_task() # reinit new proc
# push all incompleted jobs
for job in self.joblist:
self.task.put(job)
class Parallelization:
"""
This class is the base class to parallize some calculation. It creates multiple
worker processes via the `Parallelization_Worker` class. These are own independent
processes and we do the communication via serialization (via pickling) on pipes.
You queue any number of tasks which will be executed on any worker. You can get
any available results via `get_next_result()` which is blocking or `get_all_ready_results()`.
Queueing the tasks works by setting the `task_iter` attribute to any iterator.
That iterator must yield tasks, which are callable objects.
The managing/parent process can call `maybe_queue_tasks()` to start the calculation
of new tasks, if we are idling. This is also called automatically in `get_next_result()`.
You can also call `exec_task()` manually to queue a task.
"""
def __init__(self, task_limit=4):
import multiprocessing
self.task_count = 0
self.task_limit = task_limit
self.task_iter = None
self.task_queue = multiprocessing.Queue()
self.workers = [Parallelization_Worker(i) for i in range(self.task_limit)]
def get_next_result(self):
from Queue import Empty
while True:
self.maybe_queue_tasks()
for w in self.workers:
if w.is_ready(): continue
try:
restuple = self._stable_proc_communicate(
w, lambda: w.get_result(timeout=0.1))
except Empty: pass
else:
self.task_count -= 1
self.maybe_queue_tasks()
return restuple
def _stable_proc_communicate(self, worker, action):
while True:
try:
return action()
except IOError as e: # broken pipe or so
# Expect that the proc has been terminated.
# (If this is wrong, this need some more checking code what happened
# so that we can recover accordingly.)
print "%r proc exception: %r" % (action, e)
print "Reinit proc ..."
worker.fixup_broken_proc()
print "And retry."
def get_all_ready_results(self):
results = []
from Queue import Empty
for w in self.workers:
while True:
# Try to get all results and break if there aren't anymore.
if w.is_ready(): break
try:
restuple = self._stable_proc_communicate(
w, lambda: w.get_result(timeout=0))
except Empty:
break
else:
self.task_count -= 1
results += [restuple]
return results
def maybe_queue_tasks(self):
count = 0
while self.task_count < self.task_limit:
next_task = next(self.task_iter)
self.exec_task(func=next_task)
count += 1
return count
def exec_task(self, func, name=None):
_, w = min([(len(w.joblist), w) for w in self.workers])
if name is None: name=repr(func)
self.task_count += 1
self._stable_proc_communicate(
w, lambda: w.put_job(func=func, name=name))
def get_pending_tasks(self):
joblist = []
for w in self.workers:
joblist += w.joblist # list of (func,name)
return joblist
def reloadC():
"""
This is just for testing to reload the C (Cython) module
after it was recompiled.
Note that this code is very unsafe! It will likely crash
when you have other references on the C module.
This is only for debugging and development!
"""
import algo
C = algo.C
import ctypes
try:
libdl = ctypes.CDLL("libdl.so")
except Exception:
# MacOSX:
libdl = ctypes.CDLL("libdl.dylib")
libdl.dlclose.argtypes = [ctypes.c_void_p]
so = ctypes.PyDLL(C.__file__)
assert(libdl.dlclose(so._handle) == 0)
reload(C)
# Hack for reload handling
def reimportMeIntoAlgoModule():
import sys
if "algo" in sys.modules:
mod = sys.modules["algo"]
for attr in globals().keys():
if attr.startswith("__"): continue
if hasattr(mod, attr):
setattr(mod, attr, globals()[attr])
reimportMeIntoAlgoModule()
| gpl-3.0 |
danielelinaro/dynclamp | python/lcg/seal_test_gui.py | 28383 | #! /usr/bin/env python
import sys
import os
import lcg
import numpy as np
import subprocess as sub
import getopt
from PyQt4 import QtGui,QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import time
from scipy.io import savemat
import socket
from time import sleep
import atexit
plt.rc('font',**{'size':10})
plt.rc('axes',linewidth=0.8)
plt.rc('ytick',direction='out')
plt.rc('xtick',direction='out')
from scipy import optimize
description = '''
Measures the pipete or membrane resistance in
voltage clamp or current clamp mode.
Note: this script does not take over the amplifier
so you have to assure that you are in the correct mode
when using it.
Using this wrongly is a nice way to get cells fried...
Turn of the "Resistance test" or other amplifier features
when using this.
Options:
-a: Amplitude of the pulses (5mV)
-d: Duration of the pulses (5ms)
-I: Input channel
-O: Output channel
-n,--number-of-traces-overlap: Number of traces to display and compute the mean
--CC: Current clamp mode.
--reset: runs lcg-zero before quitting
--kernel Computes the kernel for AEC
--remote-blind-patch clamp (server:port,axes)
--patch-opts [hunt depth, max depth, step size, hunt step size]
Tip: You can use the + and - keys to increase/decrease the holding potential by
10mV (VC) or 25 pA (CC).
'''
def smooth(x,beta):
''' hanning window smoothing'''
# extending the data at beginning and at the end
# to apply the window at the borders
s = np.r_[x[beta-1:0:-1],x,x[-1:-beta:-1]]
w = np.hanning(beta)
y = np.convolve(w/w.sum(),s,mode='valid')
return y[5:len(y)-5]
exp1 = lambda p,x: p[0]*(np.exp(-x/p[1])) + p[2]
exp2 = lambda p,x: p[0]*(np.exp(-x/p[1])) + p[2]*(np.exp(-x/p[3])) + p[4]
errfunc = lambda p, x, y: exp2(p, x) - y
env = lambda x:os.environ[x]
class Window(QtGui.QDialog):
def parse_options(self,opts):
defaults = {'ai':env('AI_CHANNEL_VC'),
'ao':env('AO_CHANNEL_VC'),
'amp':10,
'duration':15,
'nTracesOverlap':5,
'holding':0,
'mode':'VC',
'kernel':False,
'reset':False,
'remoteManipulator':None,
'patchOptions':[300., 1000., 10., 2.]}
options = defaults.copy()
for o,a in opts:
if o == '-I':
options['ai'] = int(a)
elif o == '-O':
options['ao'] = int(a)
elif o == '-d':
options['duration'] = float(a)
elif o == '-a':
options['amp'] = float(a)
elif o in ['-n','--number-of-traces-overlap']:
options['nTracesOverlap'] = int(a)
elif o == '-H':
options['holding'] = float(a)
elif o == '--kernel':
options['kernel'] = True
elif o == '--reset':
options['reset'] = True
elif o == '--CC':
options['ai'] = int(env('AI_CHANNEL_CC'))
options['ao'] = int(env('AO_CHANNEL_CC'))
options['amp'] = -100.
options['duration'] = 40.
print('CC mode!')
options['mode'] = 'CC'
elif o == '--remote-blind-patch':
options['remoteManipulator'] = a
elif o == '--patch-opts':
# [hunt depth, max depth, step size, hunt-step size]
options['patchOptions'] = [float(ii) for ii in a.split(',')]
print options['patchOptions']
if options['mode'] == 'VC':
options['kernel'] = False
return options
def __init__(self,parent = None,opts=[]):
self.opts = self.parse_options(opts)
QtGui.QDialog.__init__(self,parent)
self.fig = plt.figure()
self.b_reset = QtGui.QPushButton('Reset')
self.b_reset.clicked.connect(self.reset)
self.b_zoom = QtGui.QCheckBox('Auto Zoom')
self.b_zoom.clicked.connect(self.autoZoom)
self.b_zoom.setChecked(True)
self.b_save = QtGui.QPushButton('Save')
self.b_save.clicked.connect(self.save)
self.b_fit = QtGui.QCheckBox('Fit decay')
self.b_fit.clicked.connect(self.tryFit)
self.b_fit.setChecked(False)
self.b_running = QtGui.QCheckBox('Running')
self.b_running.setChecked(True)
if self.opts['kernel']:
self.b_kernel = QtGui.QPushButton('AEC')
self.b_kernel.clicked.connect(self.runKernel)
self.layout = QtGui.QGridLayout()
self.init_canvas()
layout = QtGui.QHBoxLayout()
layout.addWidget(self.b_reset)
layout.addWidget(self.b_zoom)
layout.addWidget(self.b_fit)
layout.addWidget(self.b_running)
layout.addWidget(self.b_save)
if self.opts['kernel']:
layout.addWidget(self.b_kernel)
self.layout.addItem(layout,2,0,1,2)
if not self.opts['remoteManipulator'] is None:
self.init_remote_blind_patch()
self.layout.addItem(self.rBlindPatch['layout'],1,2,1,1)
print('Selected remote blind patch clamping mode.')
self.setLayout(self.layout)
self.init_lcg()
self.reset()
# Init timers
self.timer = QtCore.QTimer()
self.plot_timer = QtCore.QTimer()
QtCore.QObject.connect(self.timer,QtCore.SIGNAL('timeout()'),self.run_pulse)
QtCore.QObject.connect(self.plot_timer,QtCore.SIGNAL('timeout()'),self.plot)
self.timer.start(self.duration*1.2)
self.plot_timer.start(self.duration*3)
def init_lcg(self):
self.cwd = os.getcwd()
os.chdir('/tmp')
self.filename = '/tmp/seal_test.h5'
self.cfg_file = '/tmp/seal_test.xml'
self.duration = self.opts['duration']
duration = self.duration*1e-3
self.stim_file = '/tmp/seal_test.stim'
self.amplitude = self.opts['amp'] #mV
self.sampling_rate = env('SAMPLING_RATE')
holding = self.opts['holding']
channels = [{'type':'input',
'channel':self.opts['ai'],
'factor':float(os.environ['AI_CONVERSION_FACTOR_'+self.opts['mode']]),
'units':os.environ['AI_UNITS_'+self.opts['mode']]}]
channels.append({'type':'output',
'channel':self.opts['ao'],
'factor':float(os.environ['AO_CONVERSION_FACTOR_'+self.opts['mode']]),
'units':os.environ['AO_UNITS_'+self.opts['mode']],
'resetOutput':False,
'stimfile':self.stim_file})
# print('Conversion factors are {0}{2} and {1}{3}.'.format(
# channels[0]['factor'],
# channels[1]['factor'],
# channels[0]['units'],
# channels[1]['units']))
sys.argv = ['lcg-stimgen','-o',self.stim_file,
'dc', '-d',str(duration/4.0),'--',str(holding),
'dc', '-d',str(duration),'--',str(self.amplitude+holding),
'dc', '-d',str(duration/2.0),'--',str(holding)]
lcg.stimgen.main()
lcg.writeIOConfigurationFile(self.cfg_file,self.sampling_rate,
duration*(7/4.0),channels,
realtime=True,
output_filename=self.filename)
atexit.register(self.on_exit)
def on_exit(self):
if self.opts['reset']:
sub.call('lcg-zero')
def keyPressEvent(self, event):
step = 10
holdStr = '{0} mV'
if self.opts['mode'] == 'CC':
step = 25
holdStr = '{0} pA'
if event.key() == 43:
self.opts['holding'] += step
elif event.key() == 45:
self.opts['holding'] -= step
self.init_lcg()
self.holdingText.set_text(holdStr.format(self.opts['holding']))
event.accept()
def runKernel(self):
# Pause
self.b_kernel.setEnabled(False)
self.b_running.setChecked(False)
sleep(0.5)
xterm = 'xterm -fg white -bc -bg black -e '
sub.call('cd {3} ; pwd ; {0} "lcg-kernel -d 1 -I {1} -O {2}"'.format(
xterm, self.opts['ai'],self.opts['ao'],'/tmp'),shell=True)
self.AEC = np.loadtxt('kernel.dat')
self.b_kernel.setEnabled(True)
self.b_running.setChecked(True)
def tryFit(self):
I = np.mean(np.vstack(self.I).T[:,-8:],axis=1)
idxpost = np.where((self.time<(self.duration)))[0][-1]
if self.opts['amp']>0:
idxpre = np.argmax(I)
else:
idxpre = np.argmin(I)
#V = np.vstack(self.V).T[:,-8:],axis=1)
p0 = [10,0.4,0,0.001,0]
p2,success = optimize.leastsq(errfunc, p0[:], args=(
(self.time[idxpre:idxpost]-self.time[idxpre]),
I[idxpre:idxpost]))
maxtau = np.max(np.array(p2)[[1,3]])
self.exp_param = p2
self.fit_line.set_xdata(self.time[idxpre:idxpost])
self.fit_line.set_ydata(exp2(p2,
self.time[idxpre:idxpost]-self.time[idxpre]))
# print('Fit time constants are: {0:.2f} and {1:.2f}ms.'.format(p2[1],p2[3]))
# print('Fit time constants are: {0}ms.'.format(p2[1]))
self.tautext.set_text('{0:.2f}ms'.format(maxtau))
def autoZoom(self):
self.ax[0].set_ylim(self.Iaxis_limits)
self.ax[0].set_xlim([self.time[0],self.time[-1]])
def reset(self):
self.time = []
self.V = []
self.I = []
self.meanI = []
self.resistance = []
self.resistance_time = []
self.exp_param = None
self.count = 0
self.autoscale = True
self.fit_line.set_xdata([])
self.fit_line.set_ydata([])
self.fit_deduct.set_xdata([])
self.fit_deduct.set_ydata([])
sys.stdout.write('Starting...')
sys.stdout.flush()
def closeEvent(self,event):
sys.stdout.write('\n Stopping timers...\n')
self.timer.stop()
self.plot_timer.stop()
sys.stdout.flush()
for f in [self.filename, self.cfg_file, self.stim_file]:
os.unlink(f)
def init_canvas(self):
self.canvas = FigureCanvas(self.fig)
self.toolbar = NavigationToolbar(self.canvas,self)
self.layout.addWidget(self.toolbar,0,0,1,2)
self.layout.addWidget(self.canvas,1,0,1,2)
# initialise axes and lines
self.ax = []
self.ax.append(self.fig.add_axes([0.11,0.4,0.84,0.58],
axisbg='none',
xlabel='time (ms)',
ylabel='Current (pA)'))
if self.opts['mode'] == 'CC':
self.ax[0].set_ylabel('Voltage (mV)')
if not self.opts['remoteManipulator']:
self.ax.append(self.fig.add_axes([0.11,0.1,0.84,0.2],
axisbg='none',
xlabel='time (minutes)',
ylabel='Resistance (Mohm)'))
else:
self.ax.append(self.fig.add_axes([0.11,0.1,0.75,0.2],
axisbg='none',
xlabel='time (minutes)',
ylabel='Resistance (Mohm)'))
for ax in self.ax:
ax.spines['bottom'].set_color('black')
ax.spines['top'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
self.raw_data_plot = []
self.postI_line, = self.ax[0].plot([],[],'--',c='b',lw=1)
self.preI_line, = self.ax[0].plot([],[],'--',c='b',lw=1)
for ii in range(21):
tmp, = self.ax[0].plot([],[],color = 'k',lw=0.5)
self.raw_data_plot.append(tmp)
self.fit_deduct, = self.ax[0].plot([],[],'-',c='c',lw=1.5)
self.mean_I_plot, = self.ax[0].plot([],[],c='r',lw=1)
self.resistance_plot, = self.ax[1].plot([],[],color = 'r',lw=1)
self.autoscale = True
self.Iaxis_limits = [-1500,1500]
self.fit_line, = self.ax[0].plot([],[],'-',c='g',lw=1.5)
self.Rtext = self.ax[0].annotate(
"", xy=(0.99, 1),
xycoords='axes fraction',
ha='right',va='top',color='r',fontsize=14)
self.tautext = self.ax[0].annotate(
"", xy=(0.99, 0.90),
xycoords='axes fraction',
ha='right',va='top',color='g',fontsize=13)
self.holdingText = self.ax[0].annotate(
"", xy=(0.1, 0.1),
xycoords='axes fraction',
ha='left',va='bottom',color='g',fontsize=12, fontweight='bold')
def save(self):
foldername = QtGui.QFileDialog.getExistingDirectory(
self,
'Select a folder to save',
self.cwd)
fname = time.strftime('%Y%m%d%H%M%S')
filename = '{0}/sealtest_{1}.mat'.format(foldername,fname)
print('\n Saving to folder {0}\n'.format(filename))
self.tryFit()
try:
savemat('{0}'.format(filename),
{'timeR':self.resistance_time,
'R':self.resistance,
'V':np.vstack(self.V).T,
'I':np.vstack(self.I).T,
'expParam':self.exp_param},
do_compression=True,
oned_as='row')
except:
print('\nFile save failed.\n')
def run_pulse(self):
if self.b_running.isChecked():
duration = self.duration
sub.call('lcg-experiment -c {0} -V 4 --disable-replay'.format(self.cfg_file),shell=True)
try:
ent,info = lcg.loadH5Trace(self.filename)
except:
print('File {0} not found.\n',)
return
Idone = False
Vdone = False
for e in ent:
if e['units'] in 'pA' and not Idone:
if not Idone:
self.I.append(e['data'])
Idone = True
else:
self.I[-1] = self.I[-1] + e['data']
break
for e in ent:
if e['units'] in 'mV':
if not Vdone:
self.V.append(e['data'])
self.time = np.linspace(0,info['tend']*1.0e3,
len(self.V[-1]))
Vdone = True
else:
self.V[-1] = self.V[-1] + e['data']
break
if len(self.I) > 20:
del(self.I[0])
del(self.V[0])
self.count += 1
allI = np.vstack(self.I).T
allV = np.vstack(self.V).T
idxpre = np.where(self.time<(-0.1+duration/4))[0]
idxpost = np.where((self.time>(-1+(duration*5)/4)) &
(self.time<(-0.1+(duration*5)/4)))[0]
if len(self.I) > 11:
self.meanI = np.mean(allI[:,-8:],axis=1)
self.meanV = np.mean(allV[:,-8:],axis=1)
else:
self.meanI = self.I[-1]
self.meanV = self.V[-1]
self.Vpre = np.mean(self.meanV[idxpre])
self.Vpost = np.mean(self.meanV[idxpost])
self.Ipre = np.mean(self.meanI[idxpre])
self.Ipost = np.mean(self.meanI[idxpost])
self.resistance_time.append(info['startTimeSec'])
# print([(self.Vpost-self.Vpre),((self.Ipost-self.Ipre))])
self.resistance.append(1e3*((self.Vpost-
self.Vpre)/(self.Ipost-
self.Ipre)))
if self.opts['mode'] == 'VC':
self.Iaxis_limits = [np.min(allI),np.max(allI)]
else:
self.Iaxis_limits = [np.min(allV),np.max(allV)]
def plot(self):
sys.stdout.flush()
if len(self.I) > self.opts['nTracesOverlap']:
self.postI_line.set_xdata(np.array([self.time[0],self.time[-1]]))
self.preI_line.set_xdata(np.array([self.time[0],self.time[-1]]))
self.mean_I_plot.set_xdata(self.time)
if self.opts['mode'] == 'CC':
self.postI_line.set_ydata(self.Vpost*np.array([1,1]))
self.preI_line.set_ydata(self.Vpre*np.array([1,1]))
self.mean_I_plot.set_ydata(self.meanV)
for ii in range(1,self.opts['nTracesOverlap']+1):
if not len(self.raw_data_plot[-ii].get_xdata()):
self.raw_data_plot[ii].set_xdata(self.time)
self.raw_data_plot[ii].set_ydata(self.V[-ii])
else:
self.postI_line.set_ydata(self.Ipost*np.array([1,1]))
self.preI_line.set_ydata(self.Ipre*np.array([1,1]))
self.mean_I_plot.set_ydata(self.meanI)
for ii in range(1,self.opts['nTracesOverlap']+1):
if not len(self.raw_data_plot[ii].get_xdata()):
self.raw_data_plot[ii].set_xdata(self.time)
self.raw_data_plot[ii].set_ydata(self.I[-ii])
self.Rtext.set_text('{0:.1f}MOhm'.format(np.mean(self.resistance[-10:])))
self.resistance_plot.set_xdata(np.array(self.resistance_time - self.resistance_time[0])/60.0)
self.resistance_plot.set_ydata(np.array(self.resistance))
self.ax[1].set_xlim([-1,0]+np.max(self.resistance_plot.get_xdata())+0.1)
self.ax[1].set_ylim([0,np.max(np.array(self.resistance[-30:]))+10])
if self.b_zoom.isChecked():
self.autoZoom()
self.autoscale = False
if not self.exp_param is None:
maxtau = np.max(np.array(self.exp_param)[[1,3]])
I = np.mean(np.vstack(self.I).T[:,-self.opts['nTracesOverlap']:],axis=1)
idxpost = np.where((self.time<(self.duration)))[0][-1]
if self.opts['amp']>0:
idxpre = np.argmax(I)
else:
idxpre = np.argmin(I)
self.fit_deduct.set_xdata(self.time[idxpre:idxpost])
self.fit_deduct.set_ydata(
exp1([-(self.Ipost-self.Ipre),
maxtau,self.Ipre + (self.Ipost-self.Ipre)],
self.time[idxpre:idxpost]-self.time[idxpre]))
self.canvas.draw()
### REMOTE BLIND PATCH ####
def rBlindPatch_retract(self):
print('Retracting Pipette')
self.rBlindPatch['mode'] = 'retract'
pass
def rBlindPatch_resetResistance(self):
print('Resetting pipette resistance')
self.rBlindPatch['pipetteResistance'] = np.mean(np.array(self.resistance)[-10:])
pass
def rBlindPatch_zeroPosition(self):
print('Zero-ing pipette position')
try:
self.rBlindPatch['socket'].sendall('zero')
except:
print('Zero command failed.')
self.rBlindPatch['absPos'] = []
self.rBlindPatch['position'] = []
self.rBlindPatch['time'] = []
self.ax[2].set_ylim([0,self.rBlindPatch['maxDepth']])
def rBlindPatch_advance(self):
print('Advancing pipette!')
self.rBlindPatch['mode'] = 'advance'
def rBlindPatch_stop(self):
print('Stopping!!')
self.rBlindPatch['mode'] = 'stop'
def rBlindPatch_evolve(self):
# ask position
self.rBlindPatch['socket'].sendall('position')
pos = self.rBlindPatch['socket'].recv(1024).split(',')
self.rBlindPatch['absPos'].append([float(p[2:]) for p in pos])
self.rBlindPatch['position'].append(np.sign(self.rBlindPatch['absPos'][-1][2])*np.sqrt(
np.sum([p**2 for p in self.rBlindPatch['absPos'][-1]])))
self.rBlindPatch['time'].append(time.time())
self.rBlindPatch['positionPlot'].set_xdata(
(np.array(self.rBlindPatch['time']) - self.resistance_time[0])/60.0)
self.rBlindPatch['positionPlot'].set_ydata(np.array(self.rBlindPatch['position']))
self.ax[2].set_xlim([-1,0]+np.max(self.rBlindPatch['positionPlot'].get_xdata())+0.1)
# self.ax[2].set_ylim([0,np.max(np.array(self.rBlindPatch['position']))+50])
self.rBlindPatch['patchResistancePlot'].set_xdata(np.array(self.ax[1].get_xlim()))
self.rBlindPatch['patchResistancePlot'].set_ydata(np.array([1,1])*self.rBlindPatch['pipetteResistance'])
if self.rBlindPatch['mode'] == 'hunt':
self.rBlindPatch['modeText'].set_color('orange')
# in hunting mode, advance small step
self.rBlindPatch['socket'].sendall('move {0}={1}'.format(
self.rBlindPatch['axes'],self.rBlindPatch['huntStep']))
if np.mean(np.array(self.resistance)[-5:]) > self.rBlindPatch['pipetteResistance']*1.4:
print('Cell found??!?')
self.rBlindPatch['mode'] = 'stop'
self.rBlindPatch['modeText'].set_color('green')
elif self.rBlindPatch['mode'] == 'advance':
self.rBlindPatch['modeText'].set_color('yellow')
# in mode advance make a large step until targetDepth
self.rBlindPatch['socket'].sendall('move {0}={1}'.format(
self.rBlindPatch['axes'],self.rBlindPatch['step']))
if ((self.rBlindPatch['position'][-1] +
self.rBlindPatch['step']) > self.rBlindPatch['targetDepth']):
self.rBlindPatch['mode'] = 'hunt'
elif self.rBlindPatch['mode'] == 'retract':
self.rBlindPatch['modeText'].set_color('blue')
# in mode retract, go in the oposite direction
if (self.rBlindPatch['position'][-1] < -50):
self.rBlindPatch['mode'] = 'stop'
if ((self.rBlindPatch['position'][-1] +
self.rBlindPatch['step']) < self.rBlindPatch['targetDepth']):
self.rBlindPatch['socket'].sendall('move {0}={1}'.format(
self.rBlindPatch['axes'],-self.rBlindPatch['step']*1.5))
else:
self.rBlindPatch['socket'].sendall('move {0}={1}'.format(
self.rBlindPatch['axes'],-self.rBlindPatch['huntStep']*2.))
if (not self.rBlindPatch['mode'] == 'retract') and (
(self.rBlindPatch['position'][-1] + self.rBlindPatch['step'])
>= self.rBlindPatch['maxDepth']):
self.rBlindPatch['mode'] = 'stop'
self.rBlindPatch['modeText'].set_text(self.rBlindPatch['mode'])
self.rBlindPatch['pText'].set_text(self.rBlindPatch['position'][-1])
#print [self.rBlindPatch['mode'], self.rBlindPatch['position'][-1]]
def init_remote_blind_patch(self):
address = self.opts['remoteManipulator'].split(':')
self.rBlindPatch = {}
self.rBlindPatch['absPos'] = []
self.rBlindPatch['position'] = []
self.rBlindPatch['time'] = []
self.rBlindPatch['mode'] = 'stop'
self.rBlindPatch['pipetteResistance'] = np.nan
# [hunt depth, max depth, step size, hunt-step size]
self.rBlindPatch['axes'] = address[2]
self.rBlindPatch['step'] = self.opts['patchOptions'][2]
self.rBlindPatch['huntStep'] = self.opts['patchOptions'][3]
self.rBlindPatch['targetDepth'] = self.opts['patchOptions'][0]
self.rBlindPatch['maxDepth'] = self.opts['patchOptions'][1]
print self.rBlindPatch['maxDepth'],self.rBlindPatch['targetDepth']
self.rBlindPatch['buttons'] = {}
self.rBlindPatch['buttons']['zeroPosition'] = QtGui.QPushButton('Zero Position')
self.rBlindPatch['buttons']['zeroPosition'].clicked.connect(
self.rBlindPatch_zeroPosition)
self.rBlindPatch['buttons']['resetResistance'] = QtGui.QPushButton(
'Reset Pipette Resistance')
self.rBlindPatch['buttons']['resetResistance'].clicked.connect(
self.rBlindPatch_resetResistance)
self.rBlindPatch['buttons']['retract'] = QtGui.QPushButton('Retract')
self.rBlindPatch['buttons']['retract'].clicked.connect(
self.rBlindPatch_retract)
self.rBlindPatch['buttons']['advance'] = QtGui.QPushButton('Start')
self.rBlindPatch['buttons']['advance'].clicked.connect(
self.rBlindPatch_advance)
self.rBlindPatch['buttons']['stop'] = QtGui.QPushButton('Stop!')
self.rBlindPatch['buttons']['stop'].clicked.connect(
self.rBlindPatch_stop)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.rBlindPatch['buttons']['zeroPosition'])
layout.addWidget(self.rBlindPatch['buttons']['resetResistance'])
layout.addWidget(self.rBlindPatch['buttons']['retract'])
layout.addWidget(self.rBlindPatch['buttons']['advance'])
layout.addWidget(self.rBlindPatch['buttons']['stop'])
self.rBlindPatch['layout'] = layout
self.rBlindPatch['timerObj'] = QtCore.QTimer()
QtCore.QObject.connect(self.rBlindPatch['timerObj'],
QtCore.SIGNAL('timeout()'),
self.rBlindPatch_evolve)
self.rBlindPatch['socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.rBlindPatch['socket'].connect((address[0],int(address[1])))
print('Connected to remote manipulator (maybe...)')
except:
print('Could not connect to: %s'%(self.opts['remoteManipulator']))
sys.exit(1)
self.ax.append(self.ax[1].twinx())
ax = self.ax[-1]
ax.spines['right'].set_visible(True)
ax.get_yaxis().tick_right()
ax.set_ylabel('Position',)
self.rBlindPatch['positionPlot'], = ax.plot([],[],color = 'b',lw=1)
ax.set_ylim([0,self.rBlindPatch['maxDepth']])
self.rBlindPatch['patchResistancePlot'], = self.ax[1].plot([],[],
linestyle='--',color = 'g',lw=1)
self.rBlindPatch['modeText'] = self.ax[1].annotate("",
xy=(0.1, 0.1),
xycoords='axes fraction',
ha='left',va='bottom',
color='k',fontsize=12)
self.rBlindPatch['pText'] = self.ax[1].annotate("",
xy=(0.99, 1),
xycoords='axes fraction',
ha='right',va='top',
color=[.1,.1,.9],fontsize=12)
self.rBlindPatch['timerObj'].start(1000) # Starts with 1 second period
############################
def main():
try:
opts,args = getopt.getopt(sys.argv[1:], 'H:I:O:a:d:n:',
['kernel',
'CC',
'number-of-traces-overlap='
'remote-blind-patch=',
'reset',
'patch-opts='])
except getopt.GetoptError, err:
print(err)
print(description)
sys.exit(1)
app = QtGui.QApplication(sys.argv)
widget = Window(opts=opts)
widget.resize(750,500)
widget.setWindowTitle("LCG Seal Test")
widget.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
| gpl-3.0 |
Expugn/S-argo | src/main/java/io/github/spugn/Sargo/CharacterScout/SAOGameFifthAnniversaryStepUp.java | 6941 | package io.github.spugn.Sargo.CharacterScout;
import discord4j.core.object.entity.Message;
import io.github.spugn.Sargo.Objects.Banner;
import io.github.spugn.Sargo.Objects.Character;
import java.util.List;
/**
* SAO GAME 5TH ANNIVERSARY CHARACTER SCOUT
* <p>
* View {@link StepUp}'s JavaDoc for more information
* about Step Up scouts in general.<br>
*
* Same deal as StepUpv2, but with some changes to what
* happens in each step. This scout type is used for
* the banners that include characters with voted skills.
* </p>
* <p>
* STEP CHANGES:<br>
* Step 1)<br>
* - Multi Scout price is 55 Memory Diamonds.<br>
* Step 3)<br>
* - Platinum rarity character rates increase by 1.5x.<br>
* Step 5)<br>
* - One platinum rarity character is guaranteed.<br>
* Step 6)<br>
* - Platinum rarity character rates increase by 2.0x<br>
* - Step 6 repeats.
* </p>
*
* @author S'pugn
* @version 1.0
* @since v2.0
* @see StepUp
* @see CharacterScout
*/
public class SAOGameFifthAnniversaryStepUp extends CharacterScout
{
public SAOGameFifthAnniversaryStepUp(Message message, int bannerID, String choice, String discordID)
{
super(message, bannerID, choice, discordID);
run();
}
@Override
protected void initBannerInfo()
{
USER.addBannerInfo(SELECTED_BANNER.getBannerName(), 1);
bannerTypeData = 1;
}
@Override
protected void modifyScoutData()
{
if (CHOICE.equalsIgnoreCase("m") ||
CHOICE.equalsIgnoreCase("mi"))
{
// REMOVE 1.5% FROM PLATINUM (IT'S ORIGINAL VALUE)
COPPER = COPPER + (PLATINUM - (PLATINUM / 1.5));
PLATINUM = PLATINUM / 1.5;
switch (bannerTypeData)
{
case 1:
multiScoutPrice = 55;
break;
case 3:
COPPER = COPPER - ((PLATINUM * 1.5) - PLATINUM);
PLATINUM = PLATINUM * 1.5;
break;
case 5:
guaranteeOnePlatinum = true;
break;
case 6:
COPPER = COPPER - ((PLATINUM * 2.0) - PLATINUM);
PLATINUM = PLATINUM * 2.0;
default:
break;
}
}
}
@Override
protected void updateBannerData()
{
int currentStep = USER.getBannerData(SELECTED_BANNER.getBannerName());
currentStep++;
if (currentStep > 6)
{
USER.changeValue(SELECTED_BANNER.getBannerName(), 6);
}
else
{
USER.changeValue(SELECTED_BANNER.getBannerName(), currentStep);
}
}
@Override
protected Character randGoldCharacter()
{
/* GET A RANDOM GOLD VARIANT CHARACTER, IF THERE IS A PLATINUM
VARIANT OF THAT CHARACTER IN THE BANNER THEN GET A NEW CHARACTER. */
Character c = null;
boolean charInBanner = true;
int randIndex;
Banner randBanner;
List<Character> randCharacters;
boolean sameName;
boolean samePrefix;
while(charInBanner)
{
randIndex = GOLD_BANNERS_V2.get(RNG.nextInt(GOLD_BANNERS_V2.size()));
randBanner = BANNERS.get(randIndex - 1);
randCharacters = randBanner.getCharacters();
c = randCharacters.get(RNG.nextInt(randCharacters.size()));
for (Character bc : SELECTED_BANNER.getCharacters())
{
sameName = c.getName().equalsIgnoreCase(bc.getName());
samePrefix = c.getPrefix().equalsIgnoreCase(bc.getPrefix());
if (!(sameName && samePrefix))
{
charInBanner = false;
}
else
{
charInBanner = true;
break;
}
}
}
return c;
}
@Override
protected Character randPlatinumCharacter()
{
/* THIS SCOUT TYPE DOES NOT USE THIS FUNCTIONALITY */
return null;
}
@Override
protected void setupScoutMenu()
{
if (!SIMPLE_MESSAGE)
{
switch (CHOICE.toLowerCase())
{
case "s":
case "si":
sMenu = sMenu.andThen(s -> s.setTitle("Single Pull"));
break;
case "m":
case "mi":
sMenu = sMenu.andThen(s -> s.setTitle("[SAO Game 5th Anniversary Step Up] - Step " + bannerTypeData));
break;
default:
sMenu = sMenu.andThen(s -> s.setTitle("[SAO Game 5th Anniversary Step Up] - Unknown"));
break;
}
}
else
{
switch (CHOICE.toLowerCase())
{
case "s":
case "si":
simpleMessage += "**Single Pull**" + "\n";
break;
case "m":
case "mi":
simpleMessage += "**[SAO Game 5th Anniversary Step Up] - Step " + bannerTypeData + "**" + "\n";
break;
default:
simpleMessage += "**[SAO Game 5th Anniversary Step Up] - Unknown**" + "\n";
break;
}
}
}
@Override
protected void run()
{
switch (CHOICE.toLowerCase())
{
case "s":
case "si":
if (userMemoryDiamonds < singleScoutPrice)
{
print_NotEnoughMemoryDiamonds_Single_Message();
return;
}
if (CHOICE.equalsIgnoreCase("si") && !IMAGE_DISABLED)
{
generateImage = true;
}
userMemoryDiamonds -= singleScoutPrice;
USER.setMemoryDiamonds(userMemoryDiamonds);
doSinglePull();
break;
case "m":
case "mi":
if (userMemoryDiamonds < multiScoutPrice)
{
print_NotEnoughMemoryDiamonds_Multi_Message();
return;
}
if (CHOICE.equalsIgnoreCase("mi") && !IMAGE_DISABLED)
{
generateImage = true;
}
userMemoryDiamonds -= multiScoutPrice;
USER.setMemoryDiamonds(userMemoryDiamonds);
doMultiPull();
updateBannerData();
break;
default:
print_UnknownScoutType_sm_Message();
return;
}
if (stopScout)
return;
displayAndSave();
}
}
| gpl-3.0 |
jjdmol/LOFAR | MAC/Deployment/data/Coordinates/load_rotation_matrices.py | 2341 | #!/usr/bin/env python
#coding: iso-8859-15
import re,sys,pgdb,pg
import numpy as np
from math import *
from database import *
# get info from database.py
dbName=getDBname()
dbHost=getDBhost()
db1 = pgdb.connect(user="postgres", host=dbHost, database=dbName)
cursor = db1.cursor()
# calling stored procedures only works from the pg module for some reason.
db2 = pg.connect(user="postgres", host=dbHost, dbname=dbName)
#
# getRotationLines
#
def getRotationLines(filename):
"""
Returns a list containing all lines with rotations
"""
f = open(filename,'r')
lines = f.readlines()
f.close()
return [ line.strip().split(',') for line in lines[3:]]
##
def getRotationMatrix(line):
#print line
station = str(line[0]).upper().strip()
anttype = str(line[1]).upper().strip()
# make db matrix [3][3]
matrix = "ARRAY[[%f,%f,%f],[%f,%f,%f],[%f,%f,%f]]" %\
(float(line[2]),float(line[3]),float(line[4]), \
float(line[5]),float(line[6]),float(line[7]), \
float(line[8]),float(line[9]),float(line[10]))
return(station,anttype,matrix)
#
# MAIN
#
if __name__ == '__main__':
# check syntax of invocation
# Expected syntax: load_measurement stationname objecttypes datafile
#
if (len(sys.argv) != 2):
print "Syntax: %s datafile" % sys.argv[0]
sys.exit(1)
filename = str(sys.argv[1])
#filename = 'rotation-matrices/rotation_matrices.dat'
lines = getRotationLines(filename)
for line in lines:
(stationname,anttype,matrix) = getRotationMatrix(line)
if stationname == 'CS001': print stationname,' ',anttype,' ',matrix[0]
# check stationname
cursor.execute("select name from station")
stations = cursor.fetchall()
station = []
station.append(stationname)
if station not in stations:
print "station %s is not a legal stationame" % stationname
sys.exit(1)
try:
db2.query("select * from add_rotation_matrix('%s','%s',%s)" %(stationname, anttype, matrix))
print stationname,' ',anttype,' ',matrix
except:
print 'ERR, station=%s has no types defined' %(stationname)
print ' Done'
db1.close()
db2.close()
sys.exit(0)
| gpl-3.0 |
QIUMENGYUAN/GeomCrisis | Assets/Scripts/CheckLine.cs | 630 | using UnityEngine;
using System.Collections;
public class CheckLine : MonoBehaviour {
public GameObject NextCheckPoint;
Vector3 StartPosition ;
bool Into = true;
void Start()
{
}
void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Player" && Into)
{
StartPosition = new Vector3(PointCheck.PointPosition + 10f, -0.25f, -0.1f);
if (PlayerPrefs.GetInt("CheckPoint", 0) <8)
Instantiate(NextCheckPoint, StartPosition, Quaternion.identity);
Into = false;
Destroy(gameObject);
}
}
}
| gpl-3.0 |
rogersmendonca/joia | joia-hadoop/src/main/java/br/com/auditoria/joia/mapreduce/all/JoiaReduceAll.java | 945 | package br.com.auditoria.joia.mapreduce.all;
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
/**
* Reduce que acumula as reducoes de JobReduceCount e JobReduceNotOk.
*
* @author Rogers Reiche de Mendonca
*
*/
public class JoiaReduceAll extends Reducer<Text, Text, Text, Text>
{
private Text result;
public JoiaReduceAll()
{
result = new Text();
}
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException
{
int sum = 0;
StringBuilder strBuilder = new StringBuilder();
for (Text value : values)
{
if (value.toString().matches("^[0-9]*$"))
{
sum += Integer.parseInt(value.toString());
}
else
{
strBuilder.append(value.toString()).append(" ");
}
}
result.set(strBuilder.length() > 0 ? strBuilder.toString().trim()
: String.valueOf(sum));
context.write(key, result);
}
} | gpl-3.0 |
pinkra/neisse | src/agent/model/DataCollector.py | 374 |
class DataCollector:
"""
A DataCollector collects all data related to a specific group
(e.g. system data, network data, ...).
It denotes an abstract class that define the interface of a DataCollector.
More specific data collectors implements this interface.
"""
def load(self):
pass
def retrieveData(self):
return self.data | gpl-3.0 |
ZephyrRaine/LD39 | Assets/Scripts/ShapeColorLibrary.cs | 212 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShapeColorLibrary : ScriptableObject {
public List<Color> _colorShapes;
// Use this for initialization
}
| gpl-3.0 |
jbarascut/blog | pelicanconf.py | 1230 | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Gnupyx'
SITENAME = u'Gnupyx'
SITEURL = 'http://gnupyx.ninja'
PATH = 'content'
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'fr'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = True
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
('Python.org', 'http://python.org/'),
('Jinja2', 'http://jinja.pocoo.org/'),
('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
# Custom
USE_CUSTOM_MENU = True
CUSTOM_MENUITEMS = (('Blog', ''),
#('CV', 'pages/cv.html'),
('Contact', 'pages/contact.html'))
CONTACT_EMAIL = "[email protected]"
CONTACTS = (('linkedin', 'https://www.linkedin.com/pub/j%C3%A9r%C3%A9my-barascut/22/107/446'),
('github', 'https://github.com/jbarascut'),)
| gpl-3.0 |
yokuba/data-protest | src/App.js | 1644 | import React, { Component } from 'react';
import { auth, database } from './firebase';
import CurrentUser from './CurrentUser';
import SignIn from './SignIn';
import Newsers from './Newsers';
import pick from 'lodash/pick' ;
import map from 'lodash/map';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.usersRef = null;
this.userRef = null;
this.state = {
user: null,
users: {}
};
}
componentWillMount() {
auth.onAuthStateChanged((user) => {
this.setState({ user });
this.usersRef = database.ref('users');
if (user) {
this.userRef = this.usersRef.child(user.uid);
this.userRef.once('value').then((snapshot) => {
if (snapshot.val()) return;
const userInfo = pick(user, ['displayName', 'photoURL', 'email']);
this.userRef.set(userInfo);
});
}
this.usersRef.on('value', (snapshot) => {
this.setState({ users: snapshot.val() });
});
});
}
render() {
const { user, users } = this.state;
return (
<div className="App">
<header className="App--header">
<h1>Article Grab Bag</h1>
</header>
{ user
? <div>
<section className="Newsers">
{
map(users, (profile, uid) => (
<Newsers key={uid} {...profile} uid={uid} user={user} />
))
}
</section>
<CurrentUser user={user} />
</div>
: <SignIn />
}
</div>
);
}
}
export default App; | gpl-3.0 |
kalliope-project/kalliope | Tests/test_order_analyser.py | 30914 | import unittest
from Tests.utils.utils import get_test_path
from kalliope.core.Models import Brain
from kalliope.core.Models import Neuron
from kalliope.core.Models import Synapse
from kalliope.core.Models.MatchedSynapse import MatchedSynapse
from kalliope.core.Models.Signal import Signal
from kalliope.core.OrderAnalyser import OrderAnalyser
class TestOrderAnalyser(unittest.TestCase):
"""Test case for the OrderAnalyser Class"""
def setUp(self):
self.correction_file_to_test = get_test_path("files/test-stt-correction.yml")
def test_get_matching_synapse(self):
# Init
neuron1 = Neuron(name='neurone1', parameters={'var1': 'val1'})
neuron2 = Neuron(name='neurone2', parameters={'var2': 'val2'})
neuron3 = Neuron(name='neurone3', parameters={'var3': 'val3'})
neuron4 = Neuron(name='neurone4', parameters={'var4': 'val4'})
signal1 = Signal(name="order", parameters="this is the sentence")
signal2 = Signal(name="order", parameters="this is the second sentence")
signal3 = Signal(name="order", parameters="that is part of the third sentence")
signal4 = Signal(name="order", parameters={"matching-type": "strict",
"text": "that is part of the fourth sentence"})
signal5 = Signal(name="order", parameters={"matching-type": "ordered-strict",
"text": "sentence 5 with specific order"})
signal6 = Signal(name="order", parameters={"matching-type": "normal",
"text": "matching type normal"})
signal7 = Signal(name="order", parameters={"matching-type": "non-existing",
"text": "matching type non existing"})
signal8 = Signal(name="order", parameters={"matching-type": "non-existing",
"non-existing-parameter": "will not match order"})
signal9 = Signal(name="order", parameters="order that should be triggered because synapse is disabled")
signal10 = Signal(name="order", parameters="i say this")
signal11 = Signal(name="order", parameters="and then that")
signal12 = Signal(name="order", parameters={"matching-type": "strict",
"text": "just 1 test",
"stt-correction": [
{"input": "one", "output": "1"}
]})
signal13 = Signal(name="order", parameters={"matching-type": "not-contain",
"text": "testing the not contain",
"excluded-words": ["that", "in"]})
synapse1 = Synapse(name="Synapse1", neurons=[neuron1, neuron2], signals=[signal1])
synapse2 = Synapse(name="Synapse2", neurons=[neuron3, neuron4], signals=[signal2])
synapse3 = Synapse(name="Synapse3", neurons=[neuron2, neuron4], signals=[signal3])
synapse4 = Synapse(name="Synapse4", neurons=[neuron2, neuron4], signals=[signal4])
synapse5 = Synapse(name="Synapse5", neurons=[neuron1, neuron2], signals=[signal5])
synapse6 = Synapse(name="Synapse6", neurons=[neuron1, neuron2], signals=[signal6])
synapse7 = Synapse(name="Synapse7", neurons=[neuron1, neuron2], signals=[signal7])
synapse8 = Synapse(name="Synapse8", neurons=[neuron1, neuron2], signals=[signal8])
synapse9 = Synapse(name="Synapse9", enabled=False, neurons=[neuron1, neuron2], signals=[signal9])
synapse10 = Synapse(name="Synapse10", neurons=[neuron1], signals=[signal10, signal11])
synapse11 = Synapse(name="Synapse11", neurons=[neuron1], signals=[signal12])
synapse12 = Synapse(name="Synapse13", neurons=[neuron1], signals=[signal13])
all_synapse_list = [synapse1,
synapse2,
synapse3,
synapse4,
synapse5,
synapse6,
synapse7,
synapse8,
synapse9,
synapse10,
synapse11,
synapse12]
br = Brain(synapses=all_synapse_list)
# TEST1: should return synapse1
spoken_order = "this is the sentence"
# Create the matched synapse
expected_matched_synapse_1 = MatchedSynapse(matched_synapse=synapse1,
matched_order=spoken_order,
user_order=spoken_order)
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertEqual(len(matched_synapses), 1)
self.assertTrue(expected_matched_synapse_1 in matched_synapses)
# with defined normal matching type
spoken_order = "matching type normal"
expected_matched_synapse_5 = MatchedSynapse(matched_synapse=synapse6,
matched_order=spoken_order,
user_order=spoken_order)
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertEqual(len(matched_synapses), 1)
self.assertTrue(expected_matched_synapse_5 in matched_synapses)
# TEST2: should return synapse1 and 2
spoken_order = "this is the second sentence"
expected_matched_synapse_2 = MatchedSynapse(matched_synapse=synapse1,
matched_order=spoken_order,
user_order=spoken_order)
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertEqual(len(matched_synapses), 2)
self.assertTrue(expected_matched_synapse_1, expected_matched_synapse_2 in matched_synapses)
# TEST3: should empty
spoken_order = "not a valid order"
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertFalse(matched_synapses)
# TEST4: with matching type strict
spoken_order = "that is part of the fourth sentence"
expected_matched_synapse_3 = MatchedSynapse(matched_synapse=synapse4,
matched_order=spoken_order,
user_order=spoken_order)
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertTrue(expected_matched_synapse_3 in matched_synapses)
spoken_order = "that is part of the fourth sentence with more word"
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertFalse(matched_synapses)
# TEST5: with matching type ordered strict
spoken_order = "sentence 5 with specific order"
expected_matched_synapse_4 = MatchedSynapse(matched_synapse=synapse5,
matched_order=spoken_order,
user_order=spoken_order)
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertEqual(len(matched_synapses), 1)
self.assertTrue(expected_matched_synapse_4 in matched_synapses)
spoken_order = "order specific with 5 sentence"
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertFalse(matched_synapses)
# TEST6: non supported type of matching. should fallback to normal
spoken_order = "matching type non existing"
expected_matched_synapse_5 = MatchedSynapse(matched_synapse=synapse7,
matched_order=spoken_order,
user_order=spoken_order)
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertTrue(expected_matched_synapse_5 in matched_synapses)
# TEST7: should not match the disabled synapse
spoken_order = "order that should be triggered because synapse is disabled"
# we expect an empty list
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertTrue(len(matched_synapses) == 0)
# TEST8: a spoken order that match multiple time the same synapse should return the synapse only once
spoken_order = "i say this and then that"
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertTrue("Synapse10" in matched_synapse.synapse.name for matched_synapse in matched_synapses)
self.assertTrue(len(matched_synapses) == 1)
# TEST9: with STT correction
spoken_order = "just one test"
expected_order_with_correction = "just 1 test"
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertTrue("Synapse11" in matched_synapse.synapse.name for matched_synapse in matched_synapses)
self.assertEqual(expected_order_with_correction, next(matched_synapse.matched_order for matched_synapse in
matched_synapses))
self.assertTrue(len(matched_synapses) == 1)
# TEST10: with `not-contain`
spoken_order = "testing the not contain"
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertTrue("Synapse12" in matched_synapse.synapse.name for matched_synapse in matched_synapses)
self.assertEqual(spoken_order,
next(matched_synapse.matched_order for matched_synapse in matched_synapses))
self.assertTrue(len(matched_synapses) == 1)
# test excluded word after the matching sentence
spoken_order = "testing the not contain in "
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertFalse(matched_synapses)
self.assertTrue(len(matched_synapses) == 0)
# test excluded word before the matching sequence
spoken_order = "in testing the not contain"
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertFalse(matched_synapses)
self.assertTrue(len(matched_synapses) == 0)
# test excluded word in the middle of the matching sequence
spoken_order = "testing the in not contain"
matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
self.assertFalse(matched_synapses)
self.assertTrue(len(matched_synapses) == 0)
def test_get_split_order_without_bracket(self):
# Success
order_to_test = "this is the order"
expected_result = ["this", "is", "the", "order"]
self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
"No brackets Fails to return the expected list")
order_to_test = "this is the {{ order }}"
expected_result = ["this", "is", "the"]
self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
"With spaced brackets Fails to return the expected list")
order_to_test = "this is the {{order }}" # left bracket without space
expected_result = ["this", "is", "the"]
self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
"Left brackets Fails to return the expected list")
order_to_test = "this is the {{ order}}" # right bracket without space
expected_result = ["this", "is", "the"]
self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
"Right brackets Fails to return the expected list")
order_to_test = "this is the {{order}}" # bracket without space
expected_result = ["this", "is", "the"]
self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
"No space brackets Fails to return the expected list")
def test_is_normal_matching(self):
# same order
test_order = "expected order in the signal"
test_signal = "expected order in the signal"
self.assertTrue(OrderAnalyser.is_normal_matching(user_order=test_order,
signal_order=test_signal))
# not the same order
test_order = "this is an order"
test_signal = "expected order in the signal"
self.assertFalse(OrderAnalyser.is_normal_matching(user_order=test_order,
signal_order=test_signal))
# same order with more word in the user order
test_order = "expected order in the signal with more word"
test_signal = "expected order in the signal"
self.assertTrue(OrderAnalyser.is_normal_matching(user_order=test_order,
signal_order=test_signal))
# same order with bracket
test_order = "expected order in the signal"
test_signal = "expected order in the signal {{ variable }}"
self.assertTrue(OrderAnalyser.is_normal_matching(user_order=test_order,
signal_order=test_signal))
# same order with bracket
test_order = "expected order in the signal variable_to_catch"
test_signal = "expected order in the signal {{ variable }}"
self.assertTrue(OrderAnalyser.is_normal_matching(user_order=test_order,
signal_order=test_signal))
# same order with bracket and words after brackets
test_order = "expected order in the signal variable_to_catch other word"
test_signal = "expected order in the signal {{ variable }} other word"
self.assertTrue(OrderAnalyser.is_normal_matching(user_order=test_order,
signal_order=test_signal))
def test_is_not_contain_matching(self):
# Test the normal matching use case with no excluded words matching in the order
test_order = "expected order in the signal"
test_signal = "expected order in the signal"
excluded_words = "test"
self.assertTrue(OrderAnalyser.is_not_contain_matching(user_order=test_order,
signal_order=test_signal,
not_containing_words=excluded_words))
# test with one excluded word matching in the order.
test_order = "expected order in the signal"
test_signal = "expected"
excluded_words = ["order"]
self.assertFalse(OrderAnalyser.is_not_contain_matching(user_order=test_order,
signal_order=test_signal,
not_containing_words=excluded_words))
# test with multiple excluded word and only one matching in the order.
test_order = "expected order in the signal"
test_signal = "expected"
excluded_words = ["blabla", "order", "bloblo"]
self.assertFalse(OrderAnalyser.is_not_contain_matching(user_order=test_order,
signal_order=test_signal,
not_containing_words=excluded_words))
# test with multiple excluded word and multiple are matching in the order.
test_order = "expected order in the signal"
test_signal = "expected"
excluded_words = ["in", "order", "in"]
self.assertFalse(OrderAnalyser.is_not_contain_matching(user_order=test_order,
signal_order=test_signal,
not_containing_words=excluded_words))
# test with multiple excluded word and only none is matching the order
test_order = "expected order in the signal"
test_signal = "expected order in"
excluded_words = ["blublu", "blabla", "bloblo"]
self.assertTrue(OrderAnalyser.is_not_contain_matching(user_order=test_order,
signal_order=test_signal,
not_containing_words=excluded_words))
# test with multiple excluded word and brackets.
test_order = "expected order the signal"
test_signal = "expected order {{ in }}"
excluded_words = ["blublu", "blabla", "in"]
self.assertTrue(OrderAnalyser.is_not_contain_matching(user_order=test_order,
signal_order=test_signal,
not_containing_words=excluded_words))
def test_is_strict_matching(self):
# same order with same amount of word
test_order = "expected order in the signal"
test_signal = "expected order in the signal"
self.assertTrue(OrderAnalyser.is_strict_matching(user_order=test_order,
signal_order=test_signal))
# same order but not the same amount of word
test_order = "expected order in the signal with more word"
test_signal = "expected order in the signal"
self.assertFalse(OrderAnalyser.is_strict_matching(user_order=test_order,
signal_order=test_signal))
# same order with same amount of word and brackets
test_order = "expected order in the signal variable_to_catch"
test_signal = "expected order in the signal {{ variable }}"
self.assertTrue(OrderAnalyser.is_strict_matching(user_order=test_order,
signal_order=test_signal))
# same order with same amount of word and brackets with words after last brackets
test_order = "expected order in the signal variable_to_catch other word"
test_signal = "expected order in the signal {{ variable }} other word"
self.assertTrue(OrderAnalyser.is_strict_matching(user_order=test_order,
signal_order=test_signal))
# same order with same amount of word and brackets with words after last brackets but more words
test_order = "expected order in the signal variable_to_catch other word and more word"
test_signal = "expected order in the signal {{ variable }} other word"
self.assertFalse(OrderAnalyser.is_strict_matching(user_order=test_order,
signal_order=test_signal))
def test_ordered_strict_matching(self):
# same order with same amount of word with same order
test_order = "expected order in the signal"
test_signal = "expected order in the signal"
self.assertTrue(OrderAnalyser.is_ordered_strict_matching(user_order=test_order,
signal_order=test_signal))
# same order with same amount of word without same order
test_order = "signal the in order expected"
test_signal = "expected order in the signal"
self.assertFalse(OrderAnalyser.is_ordered_strict_matching(user_order=test_order,
signal_order=test_signal))
# same order with same amount of word and brackets in the same order
test_order = "expected order in the signal variable_to_catch"
test_signal = "expected order in the signal {{ variable }}"
self.assertTrue(OrderAnalyser.is_ordered_strict_matching(user_order=test_order,
signal_order=test_signal))
# same order with same amount of word and brackets in the same order with words after bracket
test_order = "expected order in the signal variable_to_catch with word"
test_signal = "expected order in the signal {{ variable }} with word"
self.assertTrue(OrderAnalyser.is_ordered_strict_matching(user_order=test_order,
signal_order=test_signal))
# not same order with same amount of word and brackets
test_order = "signal the in order expected"
test_signal = "expected order in the signal {{ variable }}"
self.assertFalse(OrderAnalyser.is_ordered_strict_matching(user_order=test_order,
signal_order=test_signal))
# not same order with same amount of word and brackets with words after bracket
test_order = "word expected order in the signal variable_to_catch with"
test_signal = "expected order in the signal {{ variable }} with word"
self.assertFalse(OrderAnalyser.is_ordered_strict_matching(user_order=test_order,
signal_order=test_signal))
def test_is_order_matching_signal(self):
# Note: This is a private method, most of the test use cases are covered by `test_get_matching_synapse`
# all lowercase
test_order = "expected order in the signal"
signal1 = Signal(name="order", parameters="expected order in the signal")
test_signal = signal1
self.assertTrue(OrderAnalyser.is_order_matching_signal(user_order=test_order,
signal=test_signal))
# with uppercase
test_order = "Expected Order In The Signal"
test_signal = signal1
self.assertTrue(OrderAnalyser.is_order_matching_signal(user_order=test_order,
signal=test_signal))
def test_override_order_with_correction(self):
# test with provided correction
order = "this is my test"
stt_correction = [{
"input": "test",
"output": "order"
}]
expected_output = "this is my order"
new_order = OrderAnalyser.override_order_with_correction(order=order, stt_correction=stt_correction)
self.assertEqual(new_order, expected_output)
# missing key input
order = "this is my test"
stt_correction = [{
"wrong_key": "test",
"output": "order"
}]
expected_output = "this is my test"
new_order = OrderAnalyser.override_order_with_correction(order=order, stt_correction=stt_correction)
self.assertEqual(new_order, expected_output)
def test_override_stt_correction_list(self):
# test override
list_stt_to_override = [
{"input": "value1", "output": "value2"}
]
overriding_list = [
{"input": "value1", "output": "overridden"}
]
expected_list = [
{"input": "value1", "output": "overridden"}
]
self.assertListEqual(expected_list, OrderAnalyser.override_stt_correction_list(list_stt_to_override,
overriding_list))
# stt correction added from the overriding_list
list_stt_to_override = [
{"input": "value1", "output": "value2"}
]
overriding_list = [
{"input": "value2", "output": "overridden"}
]
expected_list = [
{"input": "value1", "output": "value2"},
{"input": "value2", "output": "overridden"}
]
self.assertListEqual(expected_list, OrderAnalyser.override_stt_correction_list(list_stt_to_override,
overriding_list))
def test_order_correction(self):
# test with only stt-correction
testing_order = "thus is my test"
signal_parameter = {
"stt-correction": [
{"input": "thus",
"output": "this"}
]
}
testing_signals = Signal(name="test",
parameters=signal_parameter)
expected_fixed_order = "this is my test"
self.assertEqual(OrderAnalyser.order_correction(order=testing_order, signal=testing_signals),
expected_fixed_order)
# test with both stt-correction and stt-correction-file
testing_order = "thus is my test"
signal_parameter = {
"stt-correction": [
{"input": "thus",
"output": "this"}
],
"stt-correction-file": self.correction_file_to_test
}
testing_signals = Signal(name="test",
parameters=signal_parameter)
expected_fixed_order = "this is my order"
self.assertEqual(OrderAnalyser.order_correction(order=testing_order, signal=testing_signals),
expected_fixed_order)
# test with stt-correction that override stt-correction-file
testing_order = "thus is my test"
signal_parameter = {
"stt-correction": [
{"input": "test",
"output": "overridden"}
],
"stt-correction-file": self.correction_file_to_test
}
testing_signals = Signal(name="test",
parameters=signal_parameter)
expected_fixed_order = "thus is my overridden"
self.assertEqual(OrderAnalyser.order_correction(order=testing_order, signal=testing_signals),
expected_fixed_order)
# test with stt-correction that override multiple words.
testing_order = "thus is my test"
signal_parameter = {
"stt-correction": [
{"input": "is my test",
"output": "is overridden"}
]
}
testing_signals = Signal(name="test",
parameters=signal_parameter)
expected_fixed_order = "thus is overridden"
self.assertEqual(OrderAnalyser.order_correction(order=testing_order, signal=testing_signals),
expected_fixed_order)
# test stt-correction that override one word with multiple words.
testing_order = "thus is my test"
signal_parameter = {
"stt-correction": [
{"input": "test",
"output": "is overridden"}
]
}
testing_signals = Signal(name="test",
parameters=signal_parameter)
expected_fixed_order = "thus is my is overridden"
self.assertEqual(OrderAnalyser.order_correction(order=testing_order, signal=testing_signals),
expected_fixed_order)
# test stt-correction that multiple words override files one word.
testing_order = "thus is my test"
signal_parameter = {
"stt-correction": [
{"input": "test",
"output": "the overridden"}
],
"stt-correction-file": self.correction_file_to_test
}
testing_signals = Signal(name="test",
parameters=signal_parameter)
expected_fixed_order = "thus is my the overridden"
self.assertEqual(OrderAnalyser.order_correction(order=testing_order, signal=testing_signals),
expected_fixed_order)
# test stt-correction with multiple inputs words in file.
testing_order = "hello the test"
signal_parameter = {
"stt-correction-file": self.correction_file_to_test
}
testing_signals = Signal(name="test",
parameters=signal_parameter)
expected_fixed_order = "i am order"
self.assertEqual(OrderAnalyser.order_correction(order=testing_order, signal=testing_signals),
expected_fixed_order)
def test_get_signal_order(self):
signal1 = Signal(name="order", parameters="expected order in the signal")
signal2 = Signal(name="order", parameters={"matching-type": "strict",
"text": "that is the sentence"})
signal3 = Signal(name="order", parameters={"matching-type": "strict",
"fake-value": "that is the sentence"})
# Signal order is a str
expected_signal_order = "expected order in the signal"
self.assertEqual(expected_signal_order, OrderAnalyser.get_signal_order(signal=signal1))
# Signal order is a dict
expected_signal_order = "that is the sentence"
self.assertEqual(expected_signal_order, OrderAnalyser.get_signal_order(signal=signal2))
# signal order is a dict and `text` element is missing
expected_signal_order = "" # not found !
self.assertEqual(expected_signal_order, OrderAnalyser.get_signal_order(signal=signal3))
def test_get_not_containing_words(self):
signal1 = Signal(name="order", parameters={"matching-type": "not-contain", "excluded-words": ["that", "is"]})
# get the correct list of excluded words
expected_list_excluded_words = ["that", "is"]
self.assertEqual(expected_list_excluded_words, OrderAnalyser.get_not_containing_words(signal=signal1))
# assert it returns None when a str is provided and not a list
signal1 = Signal(name="order", parameters={"matching-type": "not-contain", "excluded_words": "that"})
self.assertIsNone(OrderAnalyser.get_not_containing_words(signal=signal1))
# assert it returns None when `excluded_words` is not provided
signal1 = Signal(name="order", parameters={"matching-type": "not-contain"})
self.assertIsNone(OrderAnalyser.get_not_containing_words(signal=signal1))
if __name__ == '__main__':
unittest.main()
| gpl-3.0 |
gladly-team/goodblock | src/js/contentscript-goodblock.js | 1461 | // console.log('Goodblock content script.');
/******************************************************************************/
/******************************************************************************/
var baseElemId = 'goodblock-iframe-base';
var createGbScript = function() {
var script = document.createElement('script');
script.id = baseElemId;
script.src = process.env.GOODBLOCK_SCRIPT_SRC;
script.async = 'async';
document.body.appendChild(script);
return script;
}
// Create the Goodblock script if it does not exist.
// Return the script element.
var createGbScriptIdempotent = function() {
var baseElem = document.querySelector('#' + baseElemId);
if (!baseElem) {
baseElem = createGbScript();
}
}
// When this content script executes, there are two possibilities:
// (1) This is the first time the content script has run in the
// current page, like when the user navigates to a new web
// page or when the user installs the extension for the first
// time.
// (2) This is the second or greater time the content script has
// has run in the current page. This can happen when the extension
// updates, when the user manually reloads the extension, or if
// the user uninstalls and reinstalls without reloading a web page.
createGbScriptIdempotent();
/******************************************************************************/
/******************************************************************************/
| gpl-3.0 |
masterucm1617/botzzaroni | BotzzaroniDev/GATE_Developer_8.4/src/test/gate/corpora/TestDocument.java | 12627 | /*
* TestDocument.java
*
* Copyright (c) 1995-2012, The University of Sheffield. See the file
* COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
*
* This file is part of GATE (see http://gate.ac.uk/), and is free
* software, licenced under the GNU Library General Public License,
* Version 2, June 1991 (in the distribution as file licence.html,
* and also available at http://gate.ac.uk/gate/licence.html).
*
* Hamish Cunningham, 21/Jan/00
*
* $Id: TestDocument.java 17656 2014-03-14 08:55:23Z markagreenwood $
*/
package gate.corpora;
import java.io.*;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.*;
import junit.framework.*;
import gate.*;
import gate.util.BomStrippingInputStreamReader;
import gate.util.Err;
import gate.util.SimpleFeatureMapImpl;
/** Tests for the Document classes
*/
public class TestDocument extends TestCase
{
/** Construction */
public TestDocument(String name) { super(name); setUp();}
/** Base of the test server URL */
protected static String testServer = null;
/** Name of test document 1 */
protected String testDocument1;
/** Fixture set up */
@Override
public void setUp() {
//try{
// Gate.init();
//testServer = Gate.getUrl().toExternalForm();
testServer = getTestServerName();
//} catch (GateException e){
// e.printStackTrace(Err.getPrintWriter());
//}
testDocument1 = "tests/html/test2.htm";
} // setUp
/** Get the name of the test server */
public static String getTestServerName() {
if(testServer != null)
return testServer;
else {
try {
URL url =
Gate.getClassLoader().getResource("gate/resources/gate.ac.uk/");
testServer = url.toExternalForm();
}
catch(Exception e) {
}
return testServer;
}
}
/** Test ordering */
public void testCompareTo() throws Exception{
Document doc1 = null;
Document doc2 = null;
Document doc3 = null;
doc1 = Factory.newDocument(new URL(testServer + "tests/def"));
doc2 = Factory.newDocument(new URL(testServer + "tests/defg"));
doc3 = Factory.newDocument(new URL(testServer + "tests/abc"));
assertTrue(doc1.compareTo(doc2) < 0);
assertTrue(doc1.compareTo(doc1) == 0);
assertTrue(doc1.compareTo(doc3) > 0);
} // testCompareTo()
/** Test loading of the original document content */
public void testOriginalContentPreserving() throws Exception {
Document doc = null;
FeatureMap params;
String encoding = "UTF-8";
String origContent;
// test the default value of preserve content flag
params = Factory.newFeatureMap();
params.put(Document.DOCUMENT_URL_PARAMETER_NAME, new URL(testServer + testDocument1));
params.put(Document.DOCUMENT_ENCODING_PARAMETER_NAME, encoding);
doc =
(Document) Factory.createResource("gate.corpora.DocumentImpl", params);
origContent = (String) doc.getFeatures().get(
GateConstants.ORIGINAL_DOCUMENT_CONTENT_FEATURE_NAME);
assertNull(
"The original content should not be preserved without demand.",
origContent);
params = Factory.newFeatureMap();
params.put(Document.DOCUMENT_URL_PARAMETER_NAME,
new URL(testServer + testDocument1));
params.put(Document.DOCUMENT_ENCODING_PARAMETER_NAME, encoding);
params.put(Document.DOCUMENT_PRESERVE_CONTENT_PARAMETER_NAME, new Boolean(true));
doc =
(Document) Factory.createResource("gate.corpora.DocumentImpl", params);
origContent = (String) doc.getFeatures().get(
GateConstants.ORIGINAL_DOCUMENT_CONTENT_FEATURE_NAME);
assertNotNull("The original content is not preserved on demand.",
origContent);
assertTrue("The original content size is zerro.", origContent.length()>0);
} // testOriginalContentPreserving()
/** A comprehensive test */
public void testLotsOfThings() {
// check that the test URL is available
URL u = null;
try{
u = new URL(testServer + testDocument1);
} catch (Exception e){
e.printStackTrace(Err.getPrintWriter());
}
// get some text out of the test URL
BufferedReader uReader = null;
try {
uReader = new BomStrippingInputStreamReader(u.openStream());
assertEquals(uReader.readLine(), "<HTML>");
} catch(UnknownHostException e) { // no network connection
return;
} catch(IOException e) {
fail(e.toString());
}
/*
Document doc = new TextualDocument(testServer + testDocument1);
AnnotationGraph ag = new AnnotationGraphImpl();
Tokeniser t = ... doc.getContent()
tokenise doc using java stream tokeniser
add several thousand token annotation
select a subset
*/
} // testLotsOfThings
public void testDocRender() throws Exception
{
Document doc = Factory.newDocument("Hi Mom");
doc.getAnnotations().add(new Long(0), new Long(2),
"Foo", new SimpleFeatureMapImpl());
String content = doc.toXml(doc.getAnnotations(), false);
// Will fail, content is "<Foo>Hi Mom</Foo>"
assertEquals("<Foo>Hi</Foo> Mom", content);
}
/** The reason this is method begins with verify and not with test is that it
* gets called by various other test methods. It is somehow a utility test
* method. It should be called on all gate documents having annotation sets.
*/
public static void verifyNodeIdConsistency(gate.Document doc)throws Exception{
if (doc == null) return;
Map<Long,Integer> offests2NodeId = new HashMap<Long,Integer>();
// Test the default annotation set
AnnotationSet annotSet = doc.getAnnotations();
verifyNodeIdConsistency(annotSet,offests2NodeId, doc);
// Test all named annotation sets
if (doc.getNamedAnnotationSets() != null){
Iterator<AnnotationSet> namedAnnotSetsIter =
doc.getNamedAnnotationSets().values().iterator();
while(namedAnnotSetsIter.hasNext()){
verifyNodeIdConsistency(namedAnnotSetsIter.next(),offests2NodeId,doc);
}// End while
}// End if
// Test suceeded. The map is not needed anymore.
offests2NodeId = null;
}// verifyNodeIdConsistency();
/** This metod runs the test over an annotation Set. It is called from her
* older sister. Se above.
* @param annotSet is the annotation set being tested.
* @param offests2NodeId is the Map used to test the consistency.
* @param doc is used in composing the assert error messsage.
*/
public static void verifyNodeIdConsistency(gate.AnnotationSet annotSet,
Map<Long,Integer> offests2NodeId,
gate.Document doc)
throws Exception{
if (annotSet == null || offests2NodeId == null) return;
Iterator<Annotation> iter = annotSet.iterator();
while(iter.hasNext()){
Annotation annot = iter.next();
String annotSetName = (annotSet.getName() == null)? "Default":
annotSet.getName();
// check the Start node
if (offests2NodeId.containsKey(annot.getStartNode().getOffset())){
assertEquals("Found two different node IDs for the same offset( "+
annot.getStartNode().getOffset()+ " ).\n" +
"START NODE is buggy for annotation(" + annot +
") from annotation set " + annotSetName + " of GATE document :" +
doc.getSourceUrl(),
annot.getStartNode().getId(),
offests2NodeId.get(annot.getStartNode().getOffset()));
}// End if
// Check the End node
if (offests2NodeId.containsKey(annot.getEndNode().getOffset())){
assertEquals("Found two different node IDs for the same offset("+
annot.getEndNode().getOffset()+ ").\n" +
"END NODE is buggy for annotation(" + annot+ ") from annotation"+
" set " + annotSetName +" of GATE document :" + doc.getSourceUrl(),
annot.getEndNode().getId(),
offests2NodeId.get(annot.getEndNode().getOffset()));
}// End if
offests2NodeId.put(annot.getStartNode().getOffset(),
annot.getStartNode().getId());
offests2NodeId.put(annot.getEndNode().getOffset(),
annot.getEndNode().getId());
}// End while
}//verifyNodeIdConsistency();
/**
* Test to verify behaviour of the mimeType init parameter.
*/
public void testExplicitMimeType() throws Exception {
// override the user config to make sure we DON'T add extra space on
// unpackMarkup when parsing XML, whatever is set in the user config file.
Object savedAddSpaceValue = Gate.getUserConfig().get(
GateConstants.DOCUMENT_ADD_SPACE_ON_UNPACK_FEATURE_NAME);
Gate.getUserConfig().put(
GateConstants.DOCUMENT_ADD_SPACE_ON_UNPACK_FEATURE_NAME, "false");
try {
String testXmlString = "<p>This is a <strong>TEST</strong>.</p>";
String xmlParsedContent = "This is a TEST.";
String htmlParsedContent = "This is a TEST.\n";
// if we create a Document from this string WITHOUT setting a mime type,
// it should be treated as plain text and not parsed.
FeatureMap docParams = Factory.newFeatureMap();
docParams.put(Document.DOCUMENT_STRING_CONTENT_PARAMETER_NAME,
testXmlString);
docParams.put(Document.DOCUMENT_MARKUP_AWARE_PARAMETER_NAME,
Boolean.TRUE);
Document noMimeTypeDoc = (Document)Factory.createResource(
DocumentImpl.class.getName(), docParams);
assertEquals("Document created with no explicit mime type should have "
+ "unparsed XML as content.", testXmlString,
noMimeTypeDoc.getContent().toString());
assertEquals("Document created with no explicit mime type should not "
+ "have any Original markups annotations.", 0,
noMimeTypeDoc.getAnnotations(
GateConstants.ORIGINAL_MARKUPS_ANNOT_SET_NAME).size());
Factory.deleteResource(noMimeTypeDoc);
noMimeTypeDoc = null;
// if we create the same document with an explicit mime type of text/xml,
// it should be parsed properly, and have two original markups
// annotations.
docParams.put(Document.DOCUMENT_MIME_TYPE_PARAMETER_NAME, "text/xml");
Document xmlDoc = (Document)Factory.createResource(
DocumentImpl.class.getName(), docParams);
assertEquals("Document created with explicit mime type should have been "
+ "parsed as XML.", xmlParsedContent,
xmlDoc.getContent().toString());
assertEquals("Document created with explicit mime type has wrong number "
+ "of Original markups annotations.", 2,
xmlDoc.getAnnotations(
GateConstants.ORIGINAL_MARKUPS_ANNOT_SET_NAME).size());
Factory.deleteResource(xmlDoc);
xmlDoc = null;
// if we create the same document with an explicit mime type of text/html,
// it should be parsed properly and have *4* original markups
// annotations, as the HTML parser creates enclosing <html> and <body>
// elements and a zero-length <head> annotation.
docParams.put(Document.DOCUMENT_MIME_TYPE_PARAMETER_NAME, "text/html");
Document htmlDoc = (Document)Factory.createResource(
DocumentImpl.class.getName(), docParams);
assertEquals("Document created with explicit mime type should have been "
+ "parsed as HTML.", htmlParsedContent,
htmlDoc.getContent().toString());
assertEquals("Document created with explicit mime type has wrong number "
+ "of Original markups annotations.", 5,
htmlDoc.getAnnotations(
GateConstants.ORIGINAL_MARKUPS_ANNOT_SET_NAME).size());
Factory.deleteResource(htmlDoc);
htmlDoc = null;
}
finally {
// restore the saved value for ADD_SPACE_ON_MARKUP_UNPACK
if(savedAddSpaceValue == null) {
Gate.getUserConfig().remove(
GateConstants.DOCUMENT_ADD_SPACE_ON_UNPACK_FEATURE_NAME);
}
else {
Gate.getUserConfig().put(
GateConstants.DOCUMENT_ADD_SPACE_ON_UNPACK_FEATURE_NAME,
savedAddSpaceValue);
}
}
}
/** Test suite routine for the test runner */
public static Test suite() {
return new TestSuite(TestDocument.class);
} // suite
} // class TestDocument
| gpl-3.0 |
OpenSHAPA/openshapa | src/main/java/org/openshapa/util/WindowsFileAssociations.java | 2250 | /**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openshapa.util;
import java.io.File;
import ca.beq.util.win32.registry.*;
/**
* Set up file associations in the Windows Registry. User must have admin
* access.
* http://www.jrsoftware.org/isfaq.php
*/
public class WindowsFileAssociations {
public static void setup() throws Win32Exception {
RegistryKey hkcr = new RegistryKey(RootKey.HKEY_CLASSES_ROOT);
RegistryKey extension = hkcr.createSubkey(".opf");
extension.setValue(new RegistryValue("", ValueType.REG_SZ,
"OpenSHAPA Project File"));
if (!hkcr.hasSubkey("OpenSHAPA")) {
RegistryKey program = hkcr.createSubkey("OpenSHAPA");
program.setValue(new RegistryValue("", ValueType.REG_SZ,
"OpenSHAPA"));
}
File programFile = cwd(); // This will return the .exe in production
String command = programFile.getAbsolutePath() + " \"%1\"";
RegistryKey programCmd = null;
if (hkcr.hasSubkey("OpenSHAPA\\shell\\open\\command")) {
programCmd = new RegistryKey("OpenSHAPA\\shell\\open\\command");
} else {
programCmd = hkcr.createSubkey("OpenSHAPA\\shell\\open\\command");
}
// Update the key value so that the new version of OpenSHAPA is used.
programCmd.deleteValue("");
programCmd.setValue(new RegistryValue("", ValueType.REG_SZ, command));
}
private static File cwd() {
return new File(WindowsFileAssociations.class.getProtectionDomain()
.getCodeSource().getLocation().getFile());
}
}
| gpl-3.0 |
jhodapp/snapd | overlord/overlord_test.go | 13317 | // -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package overlord_test
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"syscall"
"testing"
"time"
. "gopkg.in/check.v1"
"gopkg.in/tomb.v2"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/overlord"
"github.com/snapcore/snapd/overlord/patch"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/testutil"
)
func TestOverlord(t *testing.T) { TestingT(t) }
type overlordSuite struct{}
var _ = Suite(&overlordSuite{})
func (ovs *overlordSuite) SetUpTest(c *C) {
tmpdir := c.MkDir()
dirs.SetRootDir(tmpdir)
dirs.SnapStateFile = filepath.Join(tmpdir, "test.json")
}
func (ovs *overlordSuite) TearDownTest(c *C) {
dirs.SetRootDir("/")
}
func (ovs *overlordSuite) TestNew(c *C) {
restore := patch.Mock(42, nil)
defer restore()
o, err := overlord.New()
c.Assert(err, IsNil)
c.Check(o, NotNil)
c.Check(o.SnapManager(), NotNil)
c.Check(o.AssertManager(), NotNil)
c.Check(o.InterfaceManager(), NotNil)
c.Check(o.DeviceManager(), NotNil)
s := o.State()
c.Check(s, NotNil)
c.Check(o.Engine().State(), Equals, s)
s.Lock()
defer s.Unlock()
var patchLevel int
s.Get("patch-level", &patchLevel)
c.Check(patchLevel, Equals, 42)
// store is setup
sto := snapstate.Store(s)
c.Check(sto, FitsTypeOf, &store.Store{})
}
func (ovs *overlordSuite) TestNewWithGoodState(c *C) {
fakeState := []byte(fmt.Sprintf(`{"data":{"patch-level":%d,"some":"data"},"changes":null,"tasks":null,"last-change-id":0,"last-task-id":0,"last-lane-id":0}`, patch.Level))
err := ioutil.WriteFile(dirs.SnapStateFile, fakeState, 0600)
c.Assert(err, IsNil)
o, err := overlord.New()
c.Assert(err, IsNil)
state := o.State()
c.Assert(err, IsNil)
state.Lock()
defer state.Unlock()
d, err := state.MarshalJSON()
c.Assert(err, IsNil)
var got, expected map[string]interface{}
err = json.Unmarshal(d, &got)
c.Assert(err, IsNil)
err = json.Unmarshal(fakeState, &expected)
c.Assert(err, IsNil)
c.Check(got, DeepEquals, expected)
}
func (ovs *overlordSuite) TestNewWithInvalidState(c *C) {
fakeState := []byte(``)
err := ioutil.WriteFile(dirs.SnapStateFile, fakeState, 0600)
c.Assert(err, IsNil)
_, err = overlord.New()
c.Assert(err, ErrorMatches, "EOF")
}
func (ovs *overlordSuite) TestNewWithPatches(c *C) {
p := func(s *state.State) error {
s.Set("patched", true)
return nil
}
patch.Mock(1, map[int]func(*state.State) error{1: p})
fakeState := []byte(fmt.Sprintf(`{"data":{"patch-level":0}}`))
err := ioutil.WriteFile(dirs.SnapStateFile, fakeState, 0600)
c.Assert(err, IsNil)
o, err := overlord.New()
c.Assert(err, IsNil)
state := o.State()
c.Assert(err, IsNil)
state.Lock()
defer state.Unlock()
var level int
err = state.Get("patch-level", &level)
c.Assert(err, IsNil)
c.Check(level, Equals, 1)
var b bool
err = state.Get("patched", &b)
c.Assert(err, IsNil)
c.Check(b, Equals, true)
}
type witnessManager struct {
state *state.State
expectedEnsure int
ensureCalled chan struct{}
ensureCallback func(s *state.State) error
}
func (wm *witnessManager) Ensure() error {
if wm.expectedEnsure--; wm.expectedEnsure == 0 {
close(wm.ensureCalled)
return nil
}
if wm.ensureCallback != nil {
return wm.ensureCallback(wm.state)
}
return nil
}
func (wm *witnessManager) Stop() {
}
func (wm *witnessManager) Wait() {
}
func (ovs *overlordSuite) TestTrivialRunAndStop(c *C) {
o, err := overlord.New()
c.Assert(err, IsNil)
o.Loop()
err = o.Stop()
c.Assert(err, IsNil)
}
func (ovs *overlordSuite) TestEnsureLoopRunAndStop(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Millisecond)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
witness := &witnessManager{
state: o.State(),
expectedEnsure: 3,
ensureCalled: make(chan struct{}),
}
o.Engine().AddManager(witness)
o.Loop()
defer o.Stop()
t0 := time.Now()
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
c.Check(time.Since(t0) >= 10*time.Millisecond, Equals, true)
err = o.Stop()
c.Assert(err, IsNil)
}
func (ovs *overlordSuite) TestEnsureLoopMediatedEnsureBeforeImmediate(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Minute)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
ensure := func(s *state.State) error {
s.EnsureBefore(0)
return nil
}
witness := &witnessManager{
state: o.State(),
expectedEnsure: 2,
ensureCalled: make(chan struct{}),
ensureCallback: ensure,
}
se := o.Engine()
se.AddManager(witness)
o.Loop()
defer o.Stop()
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
}
func (ovs *overlordSuite) TestEnsureLoopMediatedEnsureBefore(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Minute)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
ensure := func(s *state.State) error {
s.EnsureBefore(10 * time.Millisecond)
return nil
}
witness := &witnessManager{
state: o.State(),
expectedEnsure: 2,
ensureCalled: make(chan struct{}),
ensureCallback: ensure,
}
se := o.Engine()
se.AddManager(witness)
o.Loop()
defer o.Stop()
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
}
func (ovs *overlordSuite) TestEnsureBeforeSleepy(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Minute)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
ensure := func(s *state.State) error {
overlord.MockEnsureNext(o, time.Now().Add(-10*time.Hour))
s.EnsureBefore(0)
return nil
}
witness := &witnessManager{
state: o.State(),
expectedEnsure: 2,
ensureCalled: make(chan struct{}),
ensureCallback: ensure,
}
se := o.Engine()
se.AddManager(witness)
o.Loop()
defer o.Stop()
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
}
func (ovs *overlordSuite) TestEnsureLoopMediatedEnsureBeforeOutsideEnsure(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Minute)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
ch := make(chan struct{})
ensure := func(s *state.State) error {
close(ch)
return nil
}
witness := &witnessManager{
state: o.State(),
expectedEnsure: 2,
ensureCalled: make(chan struct{}),
ensureCallback: ensure,
}
se := o.Engine()
se.AddManager(witness)
o.Loop()
defer o.Stop()
select {
case <-ch:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
se.State().EnsureBefore(0)
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
}
func (ovs *overlordSuite) TestEnsureLoopPrune(c *C) {
restoreIntv := overlord.MockPruneInterval(20*time.Millisecond, 100*time.Millisecond, 100*time.Millisecond)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
st := o.State()
st.Lock()
t1 := st.NewTask("foo", "...")
chg1 := st.NewChange("abort", "...")
chg1.AddTask(t1)
chg2 := st.NewChange("prune", "...")
chg2.SetStatus(state.DoneStatus)
st.Unlock()
o.Loop()
time.Sleep(150 * time.Millisecond)
err = o.Stop()
c.Assert(err, IsNil)
st.Lock()
defer st.Unlock()
c.Assert(st.Change(chg1.ID()), Equals, chg1)
c.Assert(st.Change(chg2.ID()), IsNil)
c.Assert(t1.Status(), Equals, state.HoldStatus)
}
func (ovs *overlordSuite) TestEnsureLoopPruneRunsMultipleTimes(c *C) {
restoreIntv := overlord.MockPruneInterval(10*time.Millisecond, 100*time.Millisecond, 1*time.Hour)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
// create two changes, one that can be pruned now, one in progress
st := o.State()
st.Lock()
t1 := st.NewTask("foo", "...")
chg1 := st.NewChange("pruneNow", "...")
chg1.AddTask(t1)
t1.SetStatus(state.DoneStatus)
t2 := st.NewTask("foo", "...")
chg2 := st.NewChange("pruneNext", "...")
chg2.AddTask(t2)
t2.SetStatus(state.DoStatus)
c.Check(st.Changes(), HasLen, 2)
st.Unlock()
// start the loop that runs the prune ticker
o.Loop()
// ensure the first change is pruned
time.Sleep(150 * time.Millisecond)
st.Lock()
c.Check(st.Changes(), HasLen, 1)
st.Unlock()
// ensure the second is also purged after it is ready
st.Lock()
chg2.SetStatus(state.DoneStatus)
st.Unlock()
time.Sleep(150 * time.Millisecond)
st.Lock()
c.Check(st.Changes(), HasLen, 0)
st.Unlock()
// cleanup loop ticker
err = o.Stop()
c.Assert(err, IsNil)
}
func (ovs *overlordSuite) TestCheckpoint(c *C) {
oldUmask := syscall.Umask(0)
defer syscall.Umask(oldUmask)
o, err := overlord.New()
c.Assert(err, IsNil)
s := o.State()
s.Lock()
s.Set("mark", 1)
s.Unlock()
st, err := os.Stat(dirs.SnapStateFile)
c.Assert(err, IsNil)
c.Assert(st.Mode(), Equals, os.FileMode(0600))
content, err := ioutil.ReadFile(dirs.SnapStateFile)
c.Assert(err, IsNil)
c.Check(string(content), testutil.Contains, `"mark":1`)
}
type runnerManager struct {
runner *state.TaskRunner
ensureCallback func()
}
func newRunnerManager(s *state.State) *runnerManager {
rm := &runnerManager{
runner: state.NewTaskRunner(s),
}
rm.runner.AddHandler("runMgr1", func(t *state.Task, _ *tomb.Tomb) error {
s := t.State()
s.Lock()
defer s.Unlock()
s.Set("runMgr1Mark", 1)
return nil
}, nil)
rm.runner.AddHandler("runMgr2", func(t *state.Task, _ *tomb.Tomb) error {
s := t.State()
s.Lock()
defer s.Unlock()
s.Set("runMgr2Mark", 1)
return nil
}, nil)
rm.runner.AddHandler("runMgrEnsureBefore", func(t *state.Task, _ *tomb.Tomb) error {
s := t.State()
s.Lock()
defer s.Unlock()
s.EnsureBefore(20 * time.Millisecond)
return nil
}, nil)
return rm
}
func (rm *runnerManager) Ensure() error {
if rm.ensureCallback != nil {
rm.ensureCallback()
}
rm.runner.Ensure()
return nil
}
func (rm *runnerManager) Stop() {
rm.runner.Stop()
}
func (rm *runnerManager) Wait() {
rm.runner.Wait()
}
func (ovs *overlordSuite) TestTrivialSettle(c *C) {
restoreIntv := overlord.MockEnsureInterval(1 * time.Minute)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
se := o.Engine()
s := se.State()
rm1 := newRunnerManager(s)
se.AddManager(rm1)
defer o.Engine().Stop()
s.Lock()
defer s.Unlock()
chg := s.NewChange("chg", "...")
t1 := s.NewTask("runMgr1", "1...")
chg.AddTask(t1)
s.Unlock()
o.Settle()
s.Lock()
c.Check(t1.Status(), Equals, state.DoneStatus)
var v int
err = s.Get("runMgr1Mark", &v)
c.Check(err, IsNil)
}
func (ovs *overlordSuite) TestSettleChain(c *C) {
restoreIntv := overlord.MockEnsureInterval(1 * time.Minute)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
se := o.Engine()
s := se.State()
rm1 := newRunnerManager(s)
se.AddManager(rm1)
defer o.Engine().Stop()
s.Lock()
defer s.Unlock()
chg := s.NewChange("chg", "...")
t1 := s.NewTask("runMgr1", "1...")
t2 := s.NewTask("runMgr2", "2...")
t2.WaitFor(t1)
chg.AddAll(state.NewTaskSet(t1, t2))
s.Unlock()
o.Settle()
s.Lock()
c.Check(t1.Status(), Equals, state.DoneStatus)
c.Check(t2.Status(), Equals, state.DoneStatus)
var v int
err = s.Get("runMgr1Mark", &v)
c.Check(err, IsNil)
err = s.Get("runMgr2Mark", &v)
c.Check(err, IsNil)
}
func (ovs *overlordSuite) TestSettleExplicitEnsureBefore(c *C) {
restoreIntv := overlord.MockEnsureInterval(1 * time.Minute)
defer restoreIntv()
o, err := overlord.New()
c.Assert(err, IsNil)
se := o.Engine()
s := se.State()
rm1 := newRunnerManager(s)
rm1.ensureCallback = func() {
s.Lock()
defer s.Unlock()
v := 0
s.Get("ensureCount", &v)
s.Set("ensureCount", v+1)
}
se.AddManager(rm1)
defer o.Engine().Stop()
s.Lock()
defer s.Unlock()
chg := s.NewChange("chg", "...")
t := s.NewTask("runMgrEnsureBefore", "...")
chg.AddTask(t)
s.Unlock()
o.Settle()
s.Lock()
c.Check(t.Status(), Equals, state.DoneStatus)
var v int
err = s.Get("ensureCount", &v)
c.Check(err, IsNil)
c.Check(v, Equals, 2)
}
func (ovs *overlordSuite) TestRequestRestartNoHandler(c *C) {
o, err := overlord.New()
c.Assert(err, IsNil)
o.State().RequestRestart(state.RestartDaemon)
}
func (ovs *overlordSuite) TestRequestRestartHandler(c *C) {
o, err := overlord.New()
c.Assert(err, IsNil)
restartRequested := false
o.SetRestartHandler(func(t state.RestartType) {
restartRequested = true
})
o.State().RequestRestart(state.RestartDaemon)
c.Check(restartRequested, Equals, true)
}
| gpl-3.0 |
ellis/2009QuVault | quvault/server-lift/src/main/scala/net/ellisw/quvault/lift/QuRendererInstructions.scala | 3462 | package net.ellisw.quvault.lift
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.LinkedHashSet
import scala.xml._
class QuRendererInstructions {
def render(xmlQuestions: Node): NodeSeq = {
val xmlInstructionList = xmlQuestions \\ "instructions"
val xmlEntryModeList = xmlQuestions \\ "entryMode"
println("xmlInstructionList: " + xmlInstructionList)
val xhtml = new ArrayBuffer[Node]
println("xmlInstructionList.size: " + xmlInstructionList.size)
if (xmlInstructionList.size > 0) {
val setKeywords = new LinkedHashSet[String]
for (xml <- xmlInstructionList) {
val asKeywords = (xml \ "@keywords").text.split(",").map(_.trim)
println("asKeywords: " + asKeywords)
setKeywords ++= asKeywords
}
println("setKeywords: " + setKeywords)
for (sKeyword <- setKeywords) {
sKeyword match {
case "ee" => xhtml += render_instruction_ee
}
}
}
if (xmlEntryModeList.size > 0) {
val setKeywords = new LinkedHashSet[String]
for (xml <- xmlEntryModeList) {
setKeywords += (xml \ "@mode").text.trim
}
val xhtmlRows = new ArrayBuffer[Node]
for (sKeyword <- setKeywords) {
sKeyword match {
case "mathlib" => xhtmlRows += (<a href="/help_mathlib.html" target="help">Matlab-Style</a>)
}
}
xhtml += (
<div style="margin-bottom: 1em">
<b>Answer Modes:</b>
Some question require that you type your answer in a special format. Click the following link(s) for more information:<br/>
{xhtmlRows}
</div>
)
}
if (xhtml.size > 0)
(<div>{xhtml}<hr/></div>)
else
xhtml
}
private def render_instruction_ee: Node = {
(
<div style="margin-bottom: 1em">
<p><b>Electronics Instructions</b></p>
<p>
Below is a description of the naming convention used for electrical ciruits.
The "Example" column shows how the variable will be displayed in descriptive text.
The "Code" column shows how to name the variable when typing your answers.
Variables names are <i>case-sensitive</i>.
</p>
<table class="vartable">
<tr><th>Symbol</th><th>Example</th><th>Code</th><th>Description</th></tr>
<tr>
<td>Lower-case <span class="variable">i</span> denotes the current through an element</td>
<td><span class="variable">i<sub>R1</sub></span></td><td class="vartable-code">iR1</td>
<td>Current through <i>R1</i></td></tr>
<tr>
<td>Lower-case <span class="variable">p</span> denotes the power dissipated by an element</td>
<td><span class="variable">p<sub>R1</sub></span></td>
<td class="vartable-code">pR1</td><td>Power dissipated by <i>R1</i></td></tr>
<tr>
<td>Lower-case <span class="variable">v</span> denotes the voltage drop between two nodes</td>
<td><span class="variable">v<sub>a</sub></span></td><td class="vartable-code">va</td>
<td>Voltage drop from <i>a</i> to <i>ground</i></td></tr>
<tr>
<td></td>
<td><span class="variable">v<sub>ab</sub></span></td>
<td class="vartable-code">vab</td><td>Voltage drop from <i>a</i> to <i>b</i></td></tr>
<tr>
<td>Capital <span class="variable">Z</span> denotes combined impedance</td>
<td><span class="variable">Z<sub>R1,R2</sub></span></td><td class="vartable-code">ZR1R2</td>
<td>Combined impedance of <i>R1</i> and <i>R2</i></td></tr>
</table>
</div>
)
}
}
| gpl-3.0 |
LilyPad/GoLilyPad | packet/minecraft/nbt/limits.go | 381 | package nbt
import (
"fmt"
)
const (
ListLimit = 2097152
ByteArrayLimit = 16777216
Int32ArrayLimit = ByteArrayLimit
Int64ArrayLimit = ByteArrayLimit
DepthLimit = 512
)
type ErrorLimit struct {
Subject string
Length int
Limit int
}
func (this ErrorLimit) Error() string {
return fmt.Sprintf("Limit: %s %d > %d", this.Subject, this.Length, this.Limit)
}
| gpl-3.0 |
divyanshgaba/Competitive-Coding | Posterized/main.cpp | 1192 | /************************************
* AUTHOR: Divyansh Gaba *
* INSTITUTION: ASET, BIJWASAN *
************************************/
#include<bits/stdc++.h>
#define fast ios_base::sync_with_stdio(0); cin.tie(0);
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define REP(i,a,b) for (int i = a; i <= b; i++)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
int main()
{
fast;
int n,k;
cin>>n>>k;
vector<int> v(256,-1);
vector<bool> use(256,false);
int a[n],b[n];
for(int i = 0;i<n;i++)
cin>>a[i];
for(int i = 0;i<n;i++)
{
if(v[a[i]]!=-1)
{
b[i]=v[a[i]];
for(int j = a[i];j>=v[a[i]];j--)
use[j]=true;
continue;
}
int j;
for(j = max(0,a[i]-k+1);j<a[i];j++)
{
if(!use[j])
{
break;
}
}
b[i]=j;
for(int x = j;x<=a[i];x++)
use[x]=true;
for(int x = j;x<min(256,j+k);x++)
{
v[x]=j;
}
}
for(int i =0;i<n;i++)
cout<<b[i]<<" ";
cout<<endl;
return 0;
}
| gpl-3.0 |
MazZzinatus/storm | src/storm/storage/jani/Property.cpp | 2003 | #include "Property.h"
namespace storm {
namespace jani {
std::ostream& operator<<(std::ostream& os, FilterExpression const& fe) {
return os << "Obtain " << toString(fe.getFilterType()) << " of the '" << fe.getStatesFormula() << "'-states with values described by '" << *fe.getFormula() << "'";
}
Property::Property(std::string const& name, std::shared_ptr<storm::logic::Formula const> const& formula, std::string const& comment)
: name(name), comment(comment), filterExpression(FilterExpression(formula)) {
// Intentionally left empty.
}
Property::Property(std::string const& name, FilterExpression const& fe, std::string const& comment)
: name(name), comment(comment), filterExpression(fe) {
// Intentionally left empty.
}
std::string const& Property::getName() const {
return this->name;
}
std::string const& Property::getComment() const {
return this->comment;
}
Property Property::substitute(std::map<storm::expressions::Variable, storm::expressions::Expression> const& substitution) const {
return Property(name, filterExpression.substitute(substitution), comment);
}
Property Property::substituteLabels(std::map<std::string, std::string> const& substitution) const {
return Property(name, filterExpression.substituteLabels(substitution), comment);
}
FilterExpression const& Property::getFilter() const {
return this->filterExpression;
}
std::shared_ptr<storm::logic::Formula const> Property::getRawFormula() const {
return this->filterExpression.getFormula();
}
std::ostream& operator<<(std::ostream& os, Property const& p) {
return os << "(" << p.getName() << ") : " << p.getFilter();
}
}
}
| gpl-3.0 |
frederikweber/DataAcquisition | src/domain/Generator.java | 2139 | /*
* DataAcquisition
* Copyright (C) 2011 Frederik Weber
*
* 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 domain;
import java.util.ArrayList;
import org.apache.log4j.Logger;
public class Generator {
private Generator() {
}
/**
* Gibt eine Liste mit Sinuswerten zurück.
*
* @return Eine Liste mit Sinuswerten
*/
public static ArrayList<Data> getSinusValues() {
ArrayList<Data> dataList = new ArrayList<Data>();
for (double i = 0; i < 2 * Math.PI; i += 0.1) {
dataList.add(new Data(i, Math.sin(i)));
}
Logger.getLogger(Generator.class).trace("Sinus Daten zurückgegeben");
return dataList;
}
/**
* Gibt eine Liste mit Zufallswerten zurück.
*
* @return Eine Liste mit Zufallswerten
*/
public static ArrayList<Data> getRandomValues() {
ArrayList<Data> dataList = new ArrayList<Data>();
for (int i = 0; i < 111; i++) {
double negativ1 = Math.random();
double negativ2 = Math.random();
double zufall1 = Math.random();
double zufall2 = Math.random();
if (negativ1 < 0.5) {
zufall1 -= 1;
}
if (negativ2 < 0.5) {
zufall2 -= 1;
}
zufall1 *= 10;
zufall2 *= 10;
dataList.add(new Data(zufall1, zufall2));
}
Logger.getLogger(Generator.class).trace("Random Daten zurückgegeben");
return dataList;
}
}
| gpl-3.0 |
tanlanxing/demo | php/extra/Trie.php | 3905 | <?php
/**
* Class Trie
* 前缀树搜索
*
* $trie = Trie::getInstance();
* var_dump($trie->search('abcd'));
* $trie->remove('abcd');
* var_dump($trie->search('abcd'));
* $trie->insert('abcd');
* var_dump($trie->search('abcd'));
*
* $time = microtime(true);
* for ($i = 0; $i < 10000; $i++) {
* var_dump($trie->search('abc'));
* }
* echo microtime(true) - $time;
*/
class Trie
{
public static $instance;
public static $tree;
private function __construct()
{
$this->init();
}
/**
* @return self
*/
public static function getInstance()
{
if (static::$instance instanceof self) {
return static::$instance;
}
static::$instance = new self();
return static::$instance;
}
private function init()
{
$arr = [
'abcd',
'abef',
'achf',
'baccc',
'baeff',
'edffds'
];
foreach ($arr as $str) {
$this->insert($str);
// print_r(static::$tree);
}
/*
$file = new SplFileObject('keywords');
$i = 0;
while (!$file->eof()) {
$line = $file->fgets();
echo $line;
$this->insert(static::$tree, $line);
$i++;
if ($i > 10) {
break;
}
}*/
}
/**
* @param array $tree
* @param string $str
* @return null
*/
public function insert($str, &$tree = null)
{
if ($str == '') {
return null;
}
if (!is_array($tree)) {
$tree = &static::$tree;
}
$length = mb_strlen($str, 'utf-8');
if (1 == $length) {
$tree[$str] = 1;
return null;
}
$char = mb_substr($str, 0, 1, 'utf-8');
if (isset($tree[$char]) && 1 == $tree[$char]) {
return null;
} else {
$childStr = mb_substr($str, 1, $length - 1, 'utf-8');
if (!isset($tree[$char])) {
$tree[$char] = [];
}
$this->insert($childStr, $tree[$char]);
}
}
/**
* @param string $str
* @param array|null $tree
* @return bool
*/
public function remove($str, &$tree = null)
{
if ($str == '') {
return false;
}
if (!is_array($tree)) {
$tree = &static::$tree;
}
$length = mb_strlen($str, 'utf-8');
if (1 == $length) {
if(isset($tree[$str]) && 1 == $tree[$str]) {
unset($tree[$str]);
return true;
}
return false;
}
$char = mb_substr($str, 0, 1, 'utf-8');
if (!isset($tree[$char]) || 1 == $tree[$char]) {
return false;
}
$childStr = mb_substr($str, 1, $length - 1, 'utf-8');
if ($this->remove($childStr, $tree[$char]) && count($tree[$char]) == 0) {
unset($tree[$char]);
return true;
}
return false;
}
/**
* @param string $search
* @param array|null $tree
* @return bool
*/
public function search($search, &$tree = null)
{
if ($search == '') {
return false;
}
if (!is_array($tree)) {
$tree = &static::$tree;
}
$length = mb_strlen($search, 'utf-8');
if (1 == $length) {
return $tree[$search] == 1;
}
$char = mb_substr($search, 0, 1, 'utf-8');
if (isset($tree[$char]) && 1 == $tree[$char]) {
return true;
} else {
if (!isset($tree[$char])) {
return false;
}
$childStr = mb_substr($search, 1, $length - 1, 'utf-8');
return $this->search($childStr, $tree[$char]);
}
}
}
| gpl-3.0 |
stephengold/gold-tiles | src/cells.cpp | 3206 | // File: cells.cpp
// Location: src
// Purpose: implement Cells class
// Author: Stephen Gold [email protected]
// (c) Copyright 2012 Stephen Gold
// Distributed under the terms of the GNU General Public License
/*
This file is part of the Gold Tile Game.
The Gold Tile Game is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
The Gold Tile Game is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with the Gold Tile Game. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cells.hpp"
#include "direction.hpp"
// lifecycle
Cells::Cells(void) {
}
// The implicitly defined copy constructor is fine.
// The implicitly defined destructor is fine.
Cells::Cells(Cell const& rCell) {
Add(rCell);
}
// operators
#if 0
Cells::operator String(void) const {
String result("{");
ConstIterator i_cell;
for (i_cell = begin(); i_cell != end(); i_cell++) {
if (i_cell != begin()) {
result += ", ";
}
result += String(*i_cell);
}
result += "}";
return result;
}
#endif
// The implicitly defined assignment method is fine.
// misc methods
void Cells::Add(Cell const& rCell) {
ASSERT(!Contains(rCell));
insert(rCell);
ASSERT(Contains(rCell));
}
void Cells::AddCells(Cells const& rCells) {
ConstIterator i_cell;
for (i_cell = rCells.begin(); i_cell != rCells.end(); i_cell++) {
Cell const cell = *i_cell;
Add(cell);
}
}
SizeType Cells::Count(void) const {
SizeType const result = SizeType(size());
return result;
}
Cell Cells::First(void) const {
ASSERT(!IsEmpty());
ConstIterator const i_cell = begin();
ASSERT(i_cell != end());
Cell const result = *i_cell;
return result;
}
void Cells::MakeEmpty(void) {
clear();
ASSERT(IsEmpty());
}
// inquiry methods
bool Cells::Contains(Cell const& rCell) const {
ConstIterator const i_cell = find(rCell);
bool const result = (i_cell != end());
return result;
}
bool Cells::ContainsAll(Cells const& rCells) const {
bool result = true;
for (ConstIterator i_cell = rCells.begin(); i_cell != rCells.end(); i_cell++) {
Cell const cell = *i_cell;
if (!Contains(cell)) {
result = false;
break;
}
}
return result;
}
bool Cells::IsAnyStart(void) const {
bool result = false;
for (ConstIterator i_cell = begin(); i_cell != end(); i_cell++) {
if (i_cell->IsStart()) {
result = true;
break;
}
}
return result;
}
bool Cells::IsEmpty(void) const {
bool const result = (size() == 0);
return result;
}
| gpl-3.0 |
nadavkav/moodle | mod/label/lang/en/label.php | 2976 | <?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/>.
/**
* Strings for component 'label', language 'en', branch 'MOODLE_20_STABLE'
*
* @package mod_label
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['configdndmedia'] = 'Offer to create a label when media files are dragged & dropped onto a course';
$string['configdndresizeheight'] = 'When a label is created from a dragged & dropped image, resize it if it is higher than this many pixels (0 for no resize)';
$string['configdndresizewidth'] = 'When a label is created from a dragged & dropped image, resize it if it is wider than this many pixels (0 for no resize)';
$string['dndmedia'] = 'Media drag and drop';
$string['dndresizeheight'] = 'Resize drag and drop height';
$string['dndresizewidth'] = 'Resize drag and drop width';
$string['dnduploadlabel'] = 'Add media to course page';
$string['dnduploadlabeltext'] = 'Add a label to the course page';
$string['indicator:cognitivedepth'] = 'Label cognitive';
$string['indicator:cognitivedepth_help'] = 'This indicator is based on the cognitive depth reached by the student in a Label resource.';
$string['indicator:socialbreadth'] = 'Label social';
$string['indicator:socialbreadth_help'] = 'This indicator is based on the social breadth reached by the student in a Label resource.';
$string['label:addinstance'] = 'Add a new label';
$string['label:view'] = 'View label';
$string['labeltext'] = 'Label text';
$string['modulename'] = 'Label';
$string['modulename_help'] = 'The label module enables text and multimedia to be inserted into the course page in between links to other resources and activities. Labels are very versatile and can help to improve the appearance of a course if used thoughtfully.
Labels may be used
* To split up a long list of activities with a subheading or an image
* To display an embedded sound file or video directly on the course page
* To add a short description to a course section';
$string['modulename_link'] = 'mod/label/view';
$string['modulenameplural'] = 'Labels';
$string['privacy:metadata'] = 'The mod_label plugin does not store any personal data.';
$string['pluginadministration'] = 'Label administration';
$string['pluginname'] = 'Label';
$string['search:activity'] = 'Label';
| gpl-3.0 |
qharley/BotQueue | models/bot.php | 12322 | <?
/*
This file is part of BotQueue.
BotQueue 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.
BotQueue 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 BotQueue. If not, see <http://www.gnu.org/licenses/>.
*/
class Bot extends Model
{
public function __construct($id = null)
{
parent::__construct($id, "bots");
}
public function getName()
{
return $this->get('name');
}
public function getUser()
{
return new User($this->get('user_id'));
}
public function getAPIData()
{
$r = array();
$r['id'] = $this->id;
$r['queue_id'] = $this->get('queue_id'); //todo: implement bot_to_queues and make this better.
$r['identifier'] = $this->get('identifier');
$r['name'] = $this->getName();
$r['manufacturer'] = $this->get('manufacturer');
$r['model'] = $this->get('model');
$r['status'] = $this->get('status');
$r['last_seen'] = $this->get('last_seen');
$r['error_text'] = $this->get('error_text');
$webcam = $this->getWebcamImage();
if ($webcam->isHydrated())
$r['webcam'] = $webcam->getAPIData();
$job = $this->getCurrentJob();
if ($job->isHydrated())
$r['job'] = $job->getAPIData();
else
$r['job'] = array();
//pull in and harmonize our config.
$r['driver_config'] = $this->getDriverConfig();
return $r;
}
public function getDriverConfig()
{
//load up our config
$config = json::decode($this->get('driver_config'));
if (!is_object($config))
$config = new stdClass;
$config->name = $this->getName();
//default our slicing value
if (!isset($config->can_slice))
$config->can_slice = True;
return $config;
}
public function getStatusHTML()
{
return Controller::byName('bot')->renderView('statusbutton', array('bot' => $this));
}
public function getStatusHTMLClass()
{
$s2c = array(
'idle' => 'success',
'working' => 'info',
'slicing' => 'info',
'waiting' => 'warning',
'error' => 'danger',
'offline' => 'inverse',
);
return $s2c[$this->get('status')];
}
public function getUrl()
{
return "/bot:" . $this->id;
}
public function getApp()
{
return new OAuthToken($this->get('oauth_token_id'));
}
public function getCurrentJob()
{
return new Job($this->get('job_id'));
}
public function getWebCamImage()
{
return new S3File($this->get('webcam_image_id'));
}
public function getJobs($status = null, $sortField = 'user_sort', $sortOrder = 'ASC')
{
if ($status !== null)
$statusSql = " AND status = '" . db()->escape($status) . "'";
$sql = "
SELECT id
FROM jobs
WHERE bot_id = " . db()->escape($this->id) ."
{$statusSql}
ORDER BY {$sortField} {$sortOrder}
";
return new Collection($sql, array('Job' => 'id'));
}
public function getErrorLog()
{
$sql = "
SELECT id
FROM error_log
WHERE bot_id = '". db()->escape($this->id) ."'
ORDER BY error_date DESC
";
return new Collection($sql, array('ErrorLog' => 'id'));
}
public function isMine()
{
return (User::$me->id == $this->get('user_id'));
}
public function canGrab($job)
{
//if we're already the owner, we can grab the job.
//this is because sometimes the grab request times out and the bot doesn't know it hasn't grabbed the job.
if ($job->get('status') == 'taken' && $job->get('bot_id') == $this->id)
return true;
//todo: fix me once we have the bot_to_queues table
if ($this->get('user_id') != $job->getQueue()->get('user_id'))
return false;
if ($job->get('status') != 'available')
return false;
if ($this->get('status') != 'idle')
return false;
if ($this->get('job_id'))
return false;
return true;
}
public function grabJob($job, $can_slice = true)
{
$job->set('status', 'taken');
$job->set('bot_id', $this->id);
$job->set('taken_time', date('Y-m-d H:i:s'));
$job->save();
usleep(1000 + mt_rand(100,500));
$job = new Job($job->id);
if ($job->get('bot_id') != $this->id)
throw new Exception("Unable to lock job #{$job->id}");
//do we need to slice this job?
if (!$job->getFile()->isHydrated())
{
//pull in our config and make sure its legit.
$config = $this->getSliceConfig();
if (!$config->isHydrated())
{
$job->set('status', 'available');
$job->set('bot_id', 0);
$job->set('taken_time', 0);
$job->save();
throw new Exception("This bot does not have a slice engine + configuration set.");
}
//is there an existing slice job w/ this exact file and config?
$sj = SliceJob::byConfigAndSource($config->id, $job->get('source_file_id'));
if ($sj->isHydrated())
{
//update our job status.
$job->set('slice_job_id', $sj->id);
$job->set('slice_complete_time', $job->get('taken_time'));
$job->set('file_id', $sj->get('output_id'));
$job->save();
}
else
{
//nope, create our slice job for processing.
$sj->set('user_id', User::$me->id);
$sj->set('job_id', $job->id);
$sj->set('input_id', $job->get('source_file_id'));
$sj->set('slice_config_id', $config->id);
$sj->set('slice_config_snapshot', $config->getSnapshot());
$sj->set('add_date', date("Y-m-d H:i:s"));
$sj->set('status', 'available');
$sj->save();
//update our job status.
$job->set('status', 'slicing');
$job->set('slice_job_id', $sj->id);
$job->save();
}
}
$log = new JobClockEntry();
$log->set('job_id', $job->id);
$log->set('user_id', User::$me->id);
$log->set('bot_id', $this->id);
$log->set('queue_id', $job->get('queue_id'));
$log->set('start_date', date("Y-m-d H:i:s"));
$log->set('status', 'working');
$log->save();
$this->set('job_id', $job->id);
$this->set('status', 'working');
$this->set('last_seen', date("Y-m-d H:i:s"));
$this->save();
return $job;
}
public function canDrop($job)
{
if ($job->get('bot_id') == $this->id && $this->get('job_id') == $job->id)
return true;
//if nobody has the job, we can safely drop it. sometimes the web requests will time out and a bot will get stuck trying to drop a job.
else if ($job->get('bot_id' == 0) && $job->get('bot_id') == 0)
return true;
else
return false;
}
public function dropJob($job)
{
//if its a sliced job, clear it for a potentially different bot.
if ($job->getSliceJob()->isHydrated())
{
$job->set('slice_job_id', 0);
$job->set('file_id', 0);
}
//clear out our data for the next bot.
$job->set('status', 'available');
$job->set('bot_id', 0);
$job->set('taken_time', 0);
$job->set('downloaded_time', 0);
$job->set('finished_time', 0);
$job->set('verified_time', 0);
$job->set('progress', 0);
$job->set('temperature_data', '');
$job->save();
$log = $job->getLatestTimeLog();
$log->set('end_date', date("Y-m-d H:i:s"));
$log->set('status', 'dropped');
$log->save();
$this->set('job_id', 0);
$this->set('status', 'idle');
$this->set('temperature_data', '');
$this->set('last_seen', date("Y-m-d H:i:s"));
$this->save();
}
public function pause()
{
$this->set('status', 'paused');
$this->save();
}
public function unpause()
{
$this->set('status', 'working');
$this->save();
}
public function canComplete($job)
{
if ($job->get('bot_id') == $this->id && $job->get('status') == 'taken')
return true;
//sometimes the web requests will time out and a bot will get stuck trying to complete a job.
else if ($job->get('bot_id') == $this->id && $job->get('status') == 'qa')
return true;
else
return false;
}
public function completeJob($job)
{
$job->set('status', 'qa');
$job->set('progress', 100);
$job->set('finished_time', date('Y-m-d H:i:s'));
$job->save();
$log = $job->getLatestTimeLog();
$log->set('end_date', date("Y-m-d H:i:s"));
$log->set('status', 'complete');
$log->save();
//copy our webcam image so that we stop overwriting the last image of the job.
$webcam = $this->getWebcamImage();
if ($webcam->isHydrated())
{
$copy = $webcam->copy();
$this->set('webcam_image_id', $copy->id);
}
$this->set('status', 'waiting');
$this->set('last_seen', date("Y-m-d H:i:s"));
$this->save();
}
public function getQueue()
{
return new Queue($this->get('queue_id'));
}
public function getStats()
{
$sql = "
SELECT status, count(status) as cnt
FROM jobs
WHERE bot_id = ". db()->escape($this->id) ."
GROUP BY status
";
$data = array();
$stats = db()->getArray($sql);
if (!empty($stats))
{
//load up our stats
foreach ($stats AS $row)
{
$data[$row['status']] = $row['cnt'];
$data['total'] += $row['cnt'];
}
//calculate percentages
foreach ($stats AS $row)
$data[$row['status'] . '_pct'] = ($row['cnt'] / $data['total']) * 100;
}
//pull in our time based stats.
$sql = "
SELECT sum(unix_timestamp(verified_time) - unix_timestamp(finished_time)) as wait, sum(unix_timestamp(finished_time) - unix_timestamp(taken_time)) as runtime, sum(unix_timestamp(verified_time) - unix_timestamp(taken_time)) as total
FROM jobs
WHERE status = 'complete'
AND bot_id = ". db()->escape($this->id);
$stats = db()->getArray($sql);
$data['total_waittime'] = (int)$stats[0]['wait'];
$data['total_time'] = (int)$stats[0]['total'];
//pull in our runtime stats
$sql = "SELECT sum(unix_timestamp(end_date) - unix_timestamp(start_date)) FROM job_clock WHERE status != 'working' AND bot_id = " . db()->escape($this->id);
$data['total_runtime'] = (int)db()->getValue($sql);
if ($data['total'])
{
$data['avg_waittime'] = $stats[0]['wait'] / $data['total'];
$data['avg_runtime'] = $stats[0]['runtime'] / $data['total'];
$data['avg_time'] = $stats[0]['total'] / $data['total'];
}
else
{
$data['avg_waittime'] = 0;
$data['avg_runtime'] = 0;
$data['avg_time'] = 0;
}
return $data;
}
public function delete()
{
//delete our jobs.
$jobs = $this->getJobs()->getAll();
foreach ($jobs AS $row)
{
$row['Job']->delete();
}
parent::delete();
}
public function getSliceEngine()
{
return new SliceEngine($this->get('slice_engine_id'));
}
public function getSliceConfig()
{
return new SliceConfig($this->get('slice_config_id'));
}
public function getLastSeenHTML()
{
$now = time();
$last = strtotime($this->get('last_seen'));
$elapsed = $now - $last;
if ($last < 0)
return "never";
$months = floor($elapsed / (60*60*24*30));
$elapsed = $elapsed - $months * 60 * 60 * 30;
$days = floor($elapsed / (60*60*24));
$elapsed = $elapsed - $days * 60 * 60 * 24;
$hours = floor($elapsed / (60*60));
$elapsed = $elapsed - $hours * 60 * 60;
$minutes = floor($elapsed / (60));
if ($minutes > 1)
$elapsed = $elapsed - $minutes * 60;
if ($months)
return "{$months} months";
if ($days > 1)
return "{$days} days ago";
if ($days)
return "{$days} day ago";
if ($hours > 1)
return "{$hours} hours ago";
if ($hours)
return "{$hours}:{$minutes}:{$elapsed} ago";
if ($minutes > 1)
return "{$minutes} mins ago";
return "{$elapsed}s ago";
}
}
?> | gpl-3.0 |
danielbchapman/production-management | ProductionWebService/src/main/java/com/danielbchapman/production/web/production/beans/AccountBean.java | 1671 | package com.danielbchapman.production.web.production.beans;
import java.io.Serializable;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import lombok.Getter;
import lombok.Setter;
import com.danielbchapman.jboss.login.LoginBeanRemote;
import com.danielbchapman.jboss.login.User;
import com.danielbchapman.production.Utility;
import com.danielbchapman.production.web.schedule.beans.LoginBean;
@ViewScoped
public class AccountBean implements Serializable
{
private LoginBeanRemote loginDao;
private static final long serialVersionUID = 1L;
@Getter
@Setter
private String oldPass;
@Getter
@Setter
private String password;
@Getter
@Setter
private String passwordConfirm;
@Getter
@Setter
private String errorMessage;
@Getter
@Setter
private boolean success;
public void changePass(ActionEvent evt)
{
User user = getLoginDao().validateLogin(Utility.getBean(LoginBean.class).getUserPrinciple(), oldPass);
success = false;
if(user == null)
{
errorMessage = "Inavlid password";
return;
}
if(Utility.compareTo(password, passwordConfirm) != 0)
{
errorMessage = "Passwords do not match";
return;
}
getLoginDao().changePassword(user.getUser(), password);
password = null;
oldPass = null;
passwordConfirm = null;
errorMessage = "";
success = true;
Utility.raiseInfo("Success", "Your password was successfully changed");
}
private LoginBeanRemote getLoginDao()
{
if(loginDao == null)
loginDao = Utility.getObjectFromContext(LoginBeanRemote.class, Utility.Namespace.PRODUCTION);
return loginDao;
}
}
| gpl-3.0 |
harlequin-tech/MarlinHQ | watchdog.cpp | 1958 | #ifdef USE_WATCHDOG
#include "Marlin.h"
#include "watchdog.h"
//===========================================================================
//=============================private variables ============================
//===========================================================================
static volatile uint8_t timeout_seconds=0;
void(* ctrlaltdelete) (void) = 0; //does not work on my atmega2560
//===========================================================================
//=============================functinos ============================
//===========================================================================
/// intialise watch dog with a 1 sec interrupt time
void wd_init()
{
WDTCSR |= (1<<WDCE )|(1<<WDE ); //allow changes
WDTCSR = (1<<WDCE )|(1<<WDE )|(1<<WDP3 )|(1<<WDP0); // Reset after 8 sec.
// WDTCSR = (1<<WDIF)|(1<<WDIE)| (1<<WDCE )|(1<<WDE )| (1<<WDP3) | (1<<WDP0);
}
/// reset watchdog. MUST be called every 1s after init or avr will reset.
void wd_reset()
{
wdt_reset();
}
//===========================================================================
//=============================ISR ============================
//===========================================================================
//Watchdog timer interrupt, called if main program blocks >1sec
ISR(WDT_vect)
{
if(timeout_seconds++ >= WATCHDOG_TIMEOUT)
{
#ifdef RESET_MANUAL
LCD_MESSAGEPGM("Please Reset!");
LCD_STATUS;
SERIAL_ERROR_START;
SERIAL_ERRORLNPGM("Something is wrong, please turn off the printer.");
#else
LCD_MESSAGEPGM("Timeout, resetting!");
LCD_STATUS;
#endif
//disable watchdog, it will survife reboot.
WDTCSR |= (1<<WDCE) | (1<<WDE);
WDTCSR = 0;
#ifdef RESET_MANUAL
kill(__LINE__); //kill blocks
while(1); //wait for user or serial reset
#else
ctrlaltdelete();
#endif
}
}
#endif /* USE_WATCHDOG */
| gpl-3.0 |
hitherejoe/Vineyard | app/src/main/java/com/hitherejoe/vineyard/ui/activity/LauncherActivity.java | 592 | package com.hitherejoe.vineyard.ui.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.hitherejoe.vineyard.util.AccountUtils;
public class LauncherActivity extends Activity {
public LauncherActivity() { }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Class intentClass = AccountUtils.isUserAuthenticated(this) ?
MainActivity.class : ConnectActivity.class;
startActivity(new Intent(this, intentClass));
finish();
}
} | gpl-3.0 |
jwdonze/CloudFormationCs | CloudFormationCsTests/Resources/RDS/DBInstanceTests.cs | 283 | using System;
using NUnit.Framework;
using CFN = CloudFormationCs;
using RDS = CloudFormationCs.Resources.RDS;
namespace CloudFormationCsTests.Resources.RDSTests
{
//[TestFixture()]
//public class DBInstanceTests
//{
// [Test()]
// public void TemplateOk()
// {
// }
//}
}
| gpl-3.0 |
ojschumann/clip | tools/zipiterator.cpp | 1054 | /**********************************************************************
Copyright (C) 2008-2011 Olaf J. Schumann
This file is part of the Cologne Laue Indexation Program.
For more information, see <http://clip4.sf.net>
Clip 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.
Clip 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 write to the Free Software Foundation, Inc., 51 Franklin Street,
Fifth Floor, Boston, MA 02110-1301, USA.
**********************************************************************/
#include "zipiterator.h"
| gpl-3.0 |
savetheinternet/bbsoop | content/themes/default/views/admin/_user_search.php | 64 | <h3><a href="javascript:void(0);" onclick="">Search…</a></h3>
| gpl-3.0 |
XTRO123/mybb_lang_ru | inc/languages/russian/admin/tools_mailerrors.lang.php | 2501 | <?php
/**
* MyBB Copyright 2014 MyBB Group, All Rights Reserved
*
* Website: http://www.mybb.com
* License: http://www.mybb.com/about/license
*
*/
// --------------------------------------------------------------------------------
// MyBB Language Pack File.
// This file has been generated by MyBB - buildin language pack editor.
// ================================================================================
// Friendly name of the language : Russian
// Author of the language pack : RUNetCMS Group
// Language pack translators website : http://runetcms.ru/
// Compatible version of MyBB : 1807
// Last edited in MyBB Editor by : XTRO
// Last edited date : Thu, 09 Jun 2016 13:23:03 +0000
// --------------------------------------------------------------------------------
$l['system_email_log'] = 'Системный журнал Email ';
$l['system_email_log_desc'] = 'Любые письма, которые были отправлены из MyBB и вернувшие сообщение об ошибке при отправке, регистрируются в MyBB и показаны ниже. Этот раздел особенно полезен для выявления проблем конфигурации SMTP или для идентификации поддержки почты на сервере.';
$l['prune_system_email_log'] = 'Очистить системный журнал Email ';
$l['filter_system_email_log'] = 'Фильтр системного журнала Email ';
$l['close_window'] = 'Закрыть окно';
$l['user_email_log_viewer'] = 'Просмотр лога Email пользователей';
$l['smtp_code'] = 'SMTP код:';
$l['smtp_server_response'] = 'SMTP ответ сервера:';
$l['to'] = 'Кому';
$l['from'] = 'От';
$l['subject'] = 'Тема';
$l['date'] = 'Дата';
$l['email'] = 'Email';
$l['date_sent'] = 'Дата отправки';
$l['error_message'] = 'Ошибка сообщения';
$l['fine'] = 'Найти';
$l['no_logs'] = 'Нет записей в журнале с выбранными критериями.';
$l['subject_contains'] = 'Тема содержит';
$l['error_message_contains'] = 'Ошибка сообщения содержит';
$l['to_address_contains'] = 'Адрес Кому содержит';
$l['from_address_contains'] = 'Адрес От содержит';
$l['find_emails_to_addr'] = 'Найти все сообщения, отправленные на этот адрес';
| gpl-3.0 |
thebracket/bgame | world_defs/items_mechanical.lua | 1010 | -- This file defines mechanical items.
-----------------------------------------------------------------------------------------------------------------
-- Mechanisms are an abstract item used for traps, door/bridge controls and similar.
items["mechanism"] = {
name = "Simple Mechanism",
description = "A collection of gears and connectors",
itemtype = {"component"},
glyph = glyphs['mechanism_simple'],
glyph_ascii = glyphs['sigma'],
foreground = colors['green'],
background = colors['black'],
stockpile = stockpiles['furniture'].id,
vox = voxelId("mechanism")
};
-- Circuits are the basis of a lot of electronic items.
items["circuit"] = {
name = "Simple Circuit",
description = "A simple cooper/silicon circuit",
itemtype = {"component"},
glyph = glyphs['circuit_simple'],
glyph_ascii = glyphs['sigma'],
foreground = colors['yellow'],
background = colors['black'],
stockpile = stockpiles['furniture'].id,
vox = voxelId("circuit")
};
| gpl-3.0 |
nataniel/e4u-framework | src/E4u/Model/Repository.php | 2081 | <?php
namespace E4u\Model;
use Doctrine\ORM\EntityRepository,
Doctrine\ORM\QueryBuilder,
Doctrine\ORM\Query\Expr;
class Repository extends EntityRepository
{
const PATTERN_PHRASE_ID = '/^(ID:|#)([\d ,]+)$/i';
const PATTERN_FIELD_ID = '/^\w+\.id$/i';
/**
*
* @param mixed $x
* @param mixed $y
* @param QueryBuilder $qb
* @return Expr\Orx
*/
public function notEqOrNull($x, $y, $qb)
{
$ex = $qb->expr();
return $ex->orX(
$ex->neq($x, $y),
$ex->isNull($x)
);
}
/**
* @param string $phrase
* @return string
*/
protected function preparePhrase($phrase)
{
$phrase = '%'.trim($phrase).'%';
$phrase = str_replace('-', '%', $phrase);
$phrase = str_replace(' ', '%', $phrase);
$phrase = str_replace('*', '%', $phrase);
$phrase = preg_replace('/%+/', '%', $phrase);
return $phrase;
}
/**
* @param array $fields
* @return string|null
*/
private function _getIDField($fields)
{
foreach ($fields as $field) {
if (preg_match(self::PATTERN_FIELD_ID, $field)) {
return $field;
}
}
return null;
}
/**
* @param string $phrase
* @param array $fields
* @param QueryBuilder $qb
* @return Expr\Orx|Expr\Comparison
*/
protected function wherePhrase($phrase, $fields, $qb)
{
$ex = $qb->expr();
$phrase = trim($phrase);
// if the search phrase is something like #123456 or ID:123456
// and we have id in field list, we narrow the search to id-only
if (preg_match(self::PATTERN_PHRASE_ID, $phrase, $regs)
&& ($alias = $this->_getIDField($fields))) {
return $ex->in($alias, $regs[2]);
}
$phrase = $ex->literal($this->preparePhrase($phrase));
$orX = $ex->orX();
foreach ($fields as $field) {
$orX->add($ex->like($field, $phrase));
}
return $orX;
}
} | gpl-3.0 |
darktorres/ERP-STACCATO | src/estoque.cpp | 18515 | #include "estoque.h"
#include "ui_estoque.h"
#include "acbrlib.h"
#include "application.h"
#include "doubledelegate.h"
#include "estoqueproxymodel.h"
#include "sql.h"
#include "user.h"
#include <QDebug>
#include <QScrollBar>
#include <QSqlError>
#include <QSqlRecord>
Estoque::Estoque(const QVariant &idEstoque_, QWidget *parent) : QDialog(parent), idEstoque(idEstoque_.toString()), ui(new Ui::Estoque) {
ui->setupUi(this);
setWindowFlags(Qt::Window);
setupTables();
preencherRestante();
limitarAlturaTabela();
if (not User::isAdministrativo()) { ui->pushButtonExibirNfe->hide(); }
if (idEstoque.isEmpty()) { throw RuntimeException("Estoque não encontrado!", this); }
setConnections();
}
Estoque::~Estoque() { delete ui; }
void Estoque::setConnections() {
const auto connectionType = static_cast<Qt::ConnectionType>(Qt::AutoConnection | Qt::UniqueConnection);
connect(ui->pushButtonExibirNfe, &QPushButton::clicked, this, &Estoque::on_pushButtonExibirNfe_clicked, connectionType);
}
void Estoque::setupTables() {
modelEstoque.setQuery(Sql::view_estoque(idEstoque));
modelEstoque.select();
modelEstoque.setHeaderData("idEstoque", "Estoque");
modelEstoque.setHeaderData("recebidoPor", "Recebido Por");
modelEstoque.setHeaderData("status", "Status");
modelEstoque.setHeaderData("fornecedor", "Fornecedor");
modelEstoque.setHeaderData("descricao", "Produto");
modelEstoque.setHeaderData("observacao", "Obs.");
modelEstoque.setHeaderData("lote", "Lote");
modelEstoque.setHeaderData("local", "Local");
modelEstoque.setHeaderData("label", "Bloco");
modelEstoque.setHeaderData("quant", "Quant.");
modelEstoque.setHeaderData("un", "Un.");
modelEstoque.setHeaderData("caixas", "Caixas");
modelEstoque.setHeaderData("codComercial", "Cód. Com.");
modelEstoque.proxyModel = new EstoqueProxyModel(&modelEstoque, this);
ui->tableEstoque->setModel(&modelEstoque);
ui->tableEstoque->setItemDelegateForColumn("quant", new DoubleDelegate(4, this));
ui->tableEstoque->hideColumn("idNFe");
ui->tableEstoque->hideColumn("idProduto");
ui->tableEstoque->hideColumn("idBloco");
ui->tableEstoque->hideColumn("quantUpd");
ui->tableEstoque->hideColumn("restante");
ui->tableEstoque->hideColumn("codBarras");
ui->tableEstoque->hideColumn("ncm");
ui->tableEstoque->hideColumn("cfop");
ui->tableEstoque->hideColumn("valorUnid");
ui->tableEstoque->hideColumn("quantCaixa");
ui->tableEstoque->hideColumn("codBarrasTrib");
ui->tableEstoque->hideColumn("unTrib");
ui->tableEstoque->hideColumn("quantTrib");
ui->tableEstoque->hideColumn("valorUnidTrib");
ui->tableEstoque->hideColumn("desconto");
ui->tableEstoque->hideColumn("compoeTotal");
ui->tableEstoque->hideColumn("numeroPedido");
ui->tableEstoque->hideColumn("itemPedido");
ui->tableEstoque->hideColumn("tipoICMS");
ui->tableEstoque->hideColumn("orig");
ui->tableEstoque->hideColumn("cstICMS");
ui->tableEstoque->hideColumn("modBC");
ui->tableEstoque->hideColumn("vBC");
ui->tableEstoque->hideColumn("pICMS");
ui->tableEstoque->hideColumn("vICMS");
ui->tableEstoque->hideColumn("modBCST");
ui->tableEstoque->hideColumn("pMVAST");
ui->tableEstoque->hideColumn("vBCST");
ui->tableEstoque->hideColumn("pICMSST");
ui->tableEstoque->hideColumn("vICMSST");
ui->tableEstoque->hideColumn("cEnq");
ui->tableEstoque->hideColumn("cstIPI");
ui->tableEstoque->hideColumn("cstPIS");
ui->tableEstoque->hideColumn("vBCPIS");
ui->tableEstoque->hideColumn("pPIS");
ui->tableEstoque->hideColumn("vPIS");
ui->tableEstoque->hideColumn("cstCOFINS");
ui->tableEstoque->hideColumn("vBCCOFINS");
ui->tableEstoque->hideColumn("pCOFINS");
ui->tableEstoque->hideColumn("vCOFINS");
//--------------------------------------------------------------------
modelViewConsumo.setTable("view_estoque_consumo");
modelViewConsumo.setFilter("idEstoque = " + idEstoque);
modelViewConsumo.select();
modelViewConsumo.setHeaderData("statusProduto", "Status Pedido");
modelViewConsumo.setHeaderData("status", "Status Consumo");
modelViewConsumo.setHeaderData("bloco", "Bloco");
modelViewConsumo.setHeaderData("fornecedor", "Fornecedor");
modelViewConsumo.setHeaderData("descricao", "Produto");
modelViewConsumo.setHeaderData("quant", "Quant.");
modelViewConsumo.setHeaderData("un", "Un.");
modelViewConsumo.setHeaderData("caixas", "Caixas");
modelViewConsumo.setHeaderData("codComercial", "Cód. Com.");
modelViewConsumo.setHeaderData("dataRealEnt", "Entrega");
modelViewConsumo.setHeaderData("created", "Criado");
modelViewConsumo.proxyModel = new EstoqueProxyModel(&modelViewConsumo, this);
ui->tableConsumo->setModel(&modelViewConsumo);
ui->tableConsumo->setItemDelegateForColumn("quant", new DoubleDelegate(4, this));
ui->tableConsumo->showColumn("created");
ui->tableConsumo->hideColumn("idEstoque");
ui->tableConsumo->hideColumn("quantUpd");
}
void Estoque::preencherRestante() {
const double quantRestante = modelEstoque.data(0, "restante").toDouble();
const QString un = modelEstoque.data(0, "un").toString();
ui->doubleSpinBoxQuantRestante->setValue(quantRestante);
ui->doubleSpinBoxQuantRestante->setSuffix(" " + un);
//--------------------------------------
const double quantCaixa = modelEstoque.data(0, "quantCaixa").toDouble();
const double caixasRestante = quantRestante / quantCaixa;
ui->doubleSpinBoxCaixasRestante->setValue(caixasRestante);
ui->doubleSpinBoxCaixasRestante->setSuffix(" cx.");
}
void Estoque::limitarAlturaTabela() {
int rowTotalHeight = ui->tableEstoque->verticalHeader()->sectionSize(0) * 2; // add extra height
int count = ui->tableEstoque->verticalHeader()->count();
for (int i = 0; i < count; ++i) {
if (not ui->tableEstoque->verticalHeader()->isSectionHidden(i)) { rowTotalHeight += ui->tableEstoque->verticalHeader()->sectionSize(i); }
}
ui->tableEstoque->setMaximumHeight(rowTotalHeight);
}
void Estoque::on_pushButtonExibirNfe_clicked() { exibirNota(); }
void Estoque::exibirNota() {
SqlQuery query;
query.prepare("SELECT xml FROM nfe WHERE idNFe = :idNFe");
query.bindValue(":idNFe", modelEstoque.data(0, "idNFe"));
if (not query.exec()) { throw RuntimeException("Erro buscando NFe: " + query.lastError().text(), this); }
if (not query.first()) { return qApp->enqueueWarning("Não encontrou NFe associada!", this); }
ACBrLib::gerarDanfe(query.value("xml"), true);
}
void Estoque::criarConsumo(const int idVendaProduto2, const double quant) {
// TODO: verificar se as divisões de linha batem com a outra função criarConsumo
if (modelEstoque.rowCount() == 0) { throw RuntimeException("Não setou idEstoque!"); }
// TODO: o valor restante no spinbox não é atualizado, se essa função for chamada mais de uma vez pode ocasionar em um consumo maior que o estoque
if (quant > ui->doubleSpinBoxQuantRestante->value()) { throw RuntimeException("Quantidade insuficiente do estoque " + idEstoque + "!"); }
// -------------------------------------------------------------------------
dividirCompra(idVendaProduto2, quant);
// -------------------------------------------------------------------------
SqlTableModel modelConsumo;
modelConsumo.setTable("estoque_has_consumo");
const int rowEstoque = 0;
const int rowConsumo = modelConsumo.insertRowAtEnd();
const double quantCaixa = modelEstoque.data(rowEstoque, "quantCaixa").toDouble();
const double caixas = quant / quantCaixa;
const double quantEstoque = modelEstoque.data(rowEstoque, "quant").toDouble();
const double proporcao = quant / quantEstoque;
modelConsumo.setData(rowConsumo, "idEstoque", modelEstoque.data(rowEstoque, "idEstoque"));
modelConsumo.setData(rowConsumo, "idVendaProduto2", idVendaProduto2);
modelConsumo.setData(rowConsumo, "status", "CONSUMO");
modelConsumo.setData(rowConsumo, "idBloco", modelEstoque.data(rowEstoque, "idBloco"));
modelConsumo.setData(rowConsumo, "idProduto", modelEstoque.data(rowEstoque, "idProduto"));
modelConsumo.setData(rowConsumo, "fornecedor", modelEstoque.data(rowEstoque, "fornecedor"));
modelConsumo.setData(rowConsumo, "descricao", modelEstoque.data(rowEstoque, "descricao"));
modelConsumo.setData(rowConsumo, "quant", quant * -1);
modelConsumo.setData(rowConsumo, "quantUpd", static_cast<int>(FieldColors::DarkGreen));
modelConsumo.setData(rowConsumo, "un", modelEstoque.data(rowEstoque, "un"));
modelConsumo.setData(rowConsumo, "caixas", caixas);
modelConsumo.setData(rowConsumo, "codBarras", modelEstoque.data(rowEstoque, "codBarras"));
modelConsumo.setData(rowConsumo, "codComercial", modelEstoque.data(rowEstoque, "codComercial"));
modelConsumo.setData(rowConsumo, "ncm", modelEstoque.data(rowEstoque, "ncm"));
modelConsumo.setData(rowConsumo, "cfop", modelEstoque.data(rowEstoque, "cfop"));
modelConsumo.setData(rowConsumo, "valorUnid", modelEstoque.data(rowEstoque, "valorUnid"));
const double valorUnid = modelConsumo.data(rowConsumo, "valorUnid").toDouble();
modelConsumo.setData(rowConsumo, "valor", quant * valorUnid);
modelConsumo.setData(rowConsumo, "codBarrasTrib", modelEstoque.data(rowEstoque, "codBarrasTrib"));
modelConsumo.setData(rowConsumo, "unTrib", modelEstoque.data(rowEstoque, "unTrib"));
modelConsumo.setData(rowConsumo, "quantTrib", modelEstoque.data(rowEstoque, "quantTrib").toDouble() * proporcao);
modelConsumo.setData(rowConsumo, "valorUnidTrib", modelEstoque.data(rowEstoque, "valorUnidTrib"));
modelConsumo.setData(rowConsumo, "desconto", modelEstoque.data(rowEstoque, "desconto").toDouble() * proporcao);
modelConsumo.setData(rowConsumo, "compoeTotal", modelEstoque.data(rowEstoque, "compoeTotal"));
modelConsumo.setData(rowConsumo, "numeroPedido", modelEstoque.data(rowEstoque, "numeroPedido"));
modelConsumo.setData(rowConsumo, "itemPedido", modelEstoque.data(rowEstoque, "itemPedido"));
modelConsumo.setData(rowConsumo, "tipoICMS", modelEstoque.data(rowEstoque, "tipoICMS"));
modelConsumo.setData(rowConsumo, "orig", modelEstoque.data(rowEstoque, "orig"));
modelConsumo.setData(rowConsumo, "cstICMS", modelEstoque.data(rowEstoque, "cstICMS"));
modelConsumo.setData(rowConsumo, "modBC", modelEstoque.data(rowEstoque, "modBC"));
modelConsumo.setData(rowConsumo, "vBC", modelEstoque.data(rowEstoque, "vBC").toDouble() * proporcao);
modelConsumo.setData(rowConsumo, "pICMS", modelEstoque.data(rowEstoque, "pICMS"));
modelConsumo.setData(rowConsumo, "vICMS", modelEstoque.data(rowEstoque, "vICMS").toDouble() * proporcao);
modelConsumo.setData(rowConsumo, "modBCST", modelEstoque.data(rowEstoque, "modBCST"));
modelConsumo.setData(rowConsumo, "pMVAST", modelEstoque.data(rowEstoque, "pMVAST"));
modelConsumo.setData(rowConsumo, "vBCST", modelEstoque.data(rowEstoque, "vBCST").toDouble() * proporcao);
modelConsumo.setData(rowConsumo, "pICMSST", modelEstoque.data(rowEstoque, "pICMSST"));
modelConsumo.setData(rowConsumo, "vICMSST", modelEstoque.data(rowEstoque, "vICMSST").toDouble() * proporcao);
modelConsumo.setData(rowConsumo, "cEnq", modelEstoque.data(rowEstoque, "cEnq"));
modelConsumo.setData(rowConsumo, "cstIPI", modelEstoque.data(rowEstoque, "cstIPI"));
modelConsumo.setData(rowConsumo, "cstPIS", modelEstoque.data(rowEstoque, "cstPIS"));
modelConsumo.setData(rowConsumo, "vBCPIS", modelEstoque.data(rowEstoque, "vBCPIS").toDouble() * proporcao);
modelConsumo.setData(rowConsumo, "pPIS", modelEstoque.data(rowEstoque, "pPIS"));
modelConsumo.setData(rowConsumo, "vPIS", modelEstoque.data(rowEstoque, "vPIS").toDouble() * proporcao);
modelConsumo.setData(rowConsumo, "cstCOFINS", modelEstoque.data(rowEstoque, "cstCOFINS"));
modelConsumo.setData(rowConsumo, "vBCCOFINS", modelEstoque.data(rowEstoque, "vBCCOFINS").toDouble() * proporcao);
modelConsumo.setData(rowConsumo, "pCOFINS", modelEstoque.data(rowEstoque, "pCOFINS"));
modelConsumo.setData(rowConsumo, "vCOFINS", modelEstoque.data(rowEstoque, "vCOFINS").toDouble() * proporcao);
modelConsumo.submitAll();
// -------------------------------------------------------------------------
// copy lote to venda_has_produto
const QString lote = modelEstoque.data(rowEstoque, "lote").toString();
if (not lote.isEmpty() and lote != "N/D") {
SqlQuery queryProduto;
queryProduto.prepare("UPDATE venda_has_produto2 SET lote = :lote WHERE idVendaProduto2 = :idVendaProduto2");
queryProduto.bindValue(":lote", modelEstoque.data(rowEstoque, "lote"));
queryProduto.bindValue(":idVendaProduto2", idVendaProduto2);
if (not queryProduto.exec()) { throw RuntimeException("Erro salvando lote: " + queryProduto.lastError().text()); }
}
}
void Estoque::dividirCompra(const int idVendaProduto2, const double quant) {
// se quant a consumir for igual a quant da compra apenas alterar idVenda/produto
// senao fazer a quebra
SqlTableModel modelCompra;
modelCompra.setTable("pedido_fornecedor_has_produto2");
const QString subQuery = "SELECT idPedido2 FROM estoque_has_compra WHERE idEstoque = " + idEstoque;
modelCompra.setFilter("(idPedido2 IN (" + subQuery + ") OR idRelacionado IN (" + subQuery + ")) AND idVenda IS NULL AND idVendaProduto2 IS NULL AND quant >= " + QString::number(quant));
modelCompra.select();
if (modelCompra.rowCount() == 0) { return; }
//--------------------------------------------------------------------
SqlQuery query;
query.prepare("SELECT idVenda FROM venda_has_produto2 WHERE idVendaProduto2 = :idVendaProduto2");
query.bindValue(":idVendaProduto2", idVendaProduto2);
if (not query.exec()) { throw RuntimeException("Erro buscando idVenda: " + query.lastError().text()); }
if (not query.first()) { throw RuntimeException("Dados não encontrados para id: " + QString::number(idVendaProduto2)); }
const int row = 0;
const double quantCompra = modelCompra.data(row, "quant").toDouble();
if (quant > quantCompra) { throw RuntimeException("Erro quant > quantCompra"); }
if (qFuzzyCompare(quant, quantCompra)) {
modelCompra.setData(row, "idVenda", query.value("idVenda"));
modelCompra.setData(row, "idVendaProduto2", idVendaProduto2);
}
const bool dividir = (quant < quantCompra);
if (dividir) {
// NOTE: *quebralinha pedido_fornecedor2
const double caixas = modelCompra.data(row, "caixas").toDouble();
const double prcUnitario = modelCompra.data(row, "prcUnitario").toDouble();
const double quantOriginal = modelCompra.data(row, "quant").toDouble();
const double proporcaoNovo = quant / quantOriginal;
const double proporcaoAntigo = (quantOriginal - quant) / quantOriginal;
modelCompra.setData(row, "quant", quantOriginal - quant);
modelCompra.setData(row, "caixas", caixas * proporcaoAntigo);
modelCompra.setData(row, "preco", prcUnitario * (quantOriginal - quant));
// -------------------------------------------------------------------------
const int newRow = modelCompra.insertRowAtEnd();
for (int column = 0, columnCount = modelCompra.columnCount(); column < columnCount; ++column) {
if (column == modelCompra.fieldIndex("idPedido2")) { continue; }
if (column == modelCompra.fieldIndex("created")) { continue; }
if (column == modelCompra.fieldIndex("lastUpdated")) { continue; }
const QVariant value = modelCompra.data(row, column);
if (value.isNull()) { continue; }
modelCompra.setData(newRow, column, value);
}
// -------------------------------------------------------------------------
modelCompra.setData(newRow, "idRelacionado", modelCompra.data(row, "idPedido2"));
modelCompra.setData(newRow, "idVenda", query.value("idVenda"));
modelCompra.setData(newRow, "idVendaProduto2", idVendaProduto2);
modelCompra.setData(newRow, "quant", quant);
modelCompra.setData(newRow, "caixas", caixas * proporcaoNovo);
modelCompra.setData(newRow, "preco", prcUnitario * quant);
}
modelCompra.submitAll();
}
void Estoque::desfazerConsumo(const int idVendaProduto2) {
// there is one implementation in InputDialogConfirmacao
// TODO: juntar as lógicas
// TODO: se houver agendamento de estoque remover
// NOTE: estoque_has_consumo may have the same idVendaProduto2 in more than one row (only until the field is made UNIQUE)
SqlQuery queryDelete;
if (not queryDelete.exec("DELETE FROM estoque_has_consumo WHERE idVendaProduto2 = " + QString::number(idVendaProduto2))) {
throw RuntimeException("Erro removendo consumo estoque: " + queryDelete.lastError().text());
}
// TODO: juntar linhas sem consumo do mesmo tipo? (usar idRelacionado)
SqlQuery queryCompra;
if (not queryCompra.exec("UPDATE pedido_fornecedor_has_produto2 SET idVenda = NULL, idVendaProduto2 = NULL WHERE idVendaProduto2 = " + QString::number(idVendaProduto2) +
" AND status NOT IN ('CANCELADO', 'DEVOLVIDO')")) {
throw RuntimeException("Erro atualizando pedido compra: " + queryCompra.lastError().text());
}
SqlQuery queryVenda;
if (not queryVenda.exec(" UPDATE venda_has_produto2 SET "
" status = CASE "
" WHEN reposicaoEntrega THEN 'REPO. ENTREGA' "
" WHEN reposicaoReceb THEN 'REPO. RECEB.' "
" ELSE 'PENDENTE' END, "
" idCompra = NULL, "
" lote = NULL, "
" dataPrevCompra = NULL, "
" dataRealCompra = NULL, "
" dataPrevConf = NULL, "
" dataRealConf = NULL, "
" dataPrevFat = NULL, "
" dataRealFat = NULL, "
" dataPrevColeta = NULL, "
" dataRealColeta = NULL, "
" dataPrevReceb = NULL, "
" dataRealReceb = NULL, "
" dataPrevEnt = NULL, "
" dataRealEnt = NULL "
" WHERE "
" `idVendaProduto2` = " +
QString::number(idVendaProduto2) + " AND status NOT IN ('CANCELADO', 'DEVOLVIDO', 'QUEBRADO')")) {
throw RuntimeException("Erro atualizando pedido venda: " + queryVenda.lastError().text());
}
}
// TODO: 1colocar o botao de desvincular consumo nesta tela
// TODO: no view_widget_estoque deixar apenas o status do consumo
| gpl-3.0 |
MaharaProject/mahara | htdocs/group/view.php | 5906 | <?php
/**
* The group 'About' page.
*
* @package mahara
* @subpackage core
* @author Catalyst IT Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
* @copyright For copyright information on Mahara, please see the README file distributed with this software.
*
*/
define('INTERNAL', 1);
define('PUBLIC', 1);
define('MENUITEM', 'engage/index');
define('MENUITEM_SUBPAGE', 'info');
require(dirname(dirname(__FILE__)) . '/init.php');
require_once('group.php');
require_once('searchlib.php');
require_once(get_config('docroot') . 'interaction/lib.php');
require_once(get_config('libroot') . 'view.php');
safe_require('artefact', 'file');
if ($urlid = param_alphanumext('homepage', null)) {
define('GROUPURLID', $urlid);
$group = group_current_group();
}
else {
define('GROUP', param_integer('id'));
$group = group_current_group();
}
if (!is_logged_in() && !$group->public) {
throw new AccessDeniedException();
}
if ($usetemplate = param_integer('usetemplate', null)) {
// If a form has been submitted, build it now and pieforms will
// call the submit function straight away
pieform(create_view_form(null, null, $usetemplate, param_integer('copycollection', null)));
}
define('TITLE', $group->name);
define('SUBSECTIONHEADING', get_string('about'));
$group->role = group_user_access($group->id);
// logged in user can do stuff
if ($USER->is_logged_in()) {
if ($group->role) {
if ($group->role == 'admin') {
$group->membershiptype = 'admin';
$group->requests = count_records('group_member_request', 'group', $group->id);
}
else {
$group->membershiptype = 'member';
}
$group->canleave = group_user_can_leave($group->id);
}
else if ($invite = get_record('group_member_invite', 'group', $group->id, 'member', $USER->get('id'))) {
$group->membershiptype = 'invite';
$group->invite = group_get_accept_form('invite', $group->id);
}
// When 'isolatedinstitutions' is set, people cannot join public groups by themselves
else if ($group->jointype == 'open' && !is_isolated()) {
$group->groupjoin = group_get_join_form('joingroup', $group->id);
}
else if ($group->request
and $request = get_record('group_member_request', 'group', $group->id, 'member', $USER->get('id'))) {
$group->membershiptype = 'request';
}
}
// Check to see if we can invite anyone
if ($group->invitefriends) {
$results = get_group_user_search_results($group->id, '', 0, 1, 'notinvited', null, $USER->get('id'), 'adminfirst',
(((int) $group->hidemembers === GROUP_HIDE_TUTORS || (int) $group->hidemembersfrommembers === GROUP_HIDE_TUTORS) ? true : false)
);
if (empty($results['count'])) {
$group->invitefriends = 0;
}
}
$editwindow = group_format_editwindow($group);
$view = group_get_homepage_view($group->id);
if ($newlayout = $view->uses_new_layout()) {
$layoutjs = array('js/lodash/lodash.js', 'js/gridstack/gridstack.js', 'js/gridlayout.js');
$blocks = $view->get_blocks();
$blocks = json_encode($blocks);
$blocksjs = <<<EOF
$(function () {
var options = {
verticalMargin: 5,
cellHeight: 10,
disableDrag : true,
disableResize: true,
};
var grid = $('.grid-stack');
grid.gridstack(options);
grid = $('.grid-stack').data('gridstack');
// should add the blocks one by one
var blocks = {$blocks};
loadGrid(grid, blocks);
});
EOF;
}
else {
$viewcontent = $view->build_rows(); // Build content before initialising smarty in case pieform elements define headers.
$layoutjs= array();
$blocksjs = "$(function () {jQuery(document).trigger('blocksloaded');});";
}
$headers = array();
if ($group->public) {
$feedlink = get_config('wwwroot') . 'interaction/forum/atom.php?type=g&id=' . $group->id;
$headers[] = '<link rel="alternate" type="application/atom+xml" href="' . $feedlink . '">';
}
$javascript = array('paginator');
$javascript = array_merge($javascript, $layoutjs);
$blocktype_js = $view->get_all_blocktype_javascript();
$javascript = array_merge($javascript, $blocktype_js['jsfiles']);
$inlinejs = <<<JS
jQuery(function($) {
JS;
$inlinejs .= join("\n", $blocktype_js['initjs']) . "\n";
$inlinejs .= <<<JS
// Disable the modal_links for images etc... when page loads
$('a[class*=modal_link], a[class*=inner-link]').addClass('no-modal');
$('a[class*=modal_link], a[class*=inner-link]').css('cursor', 'default');
});
JS;
$headers = array_merge($headers, $view->get_all_blocktype_css());
// Set up skin, if the page has one
$viewskin = $view->get('skin');
$owner = $view->get('owner');
$issiteview = $view->get('institution') == 'mahara';
if ($viewskin && get_config('skins') && can_use_skins($owner, false, $issiteview) && (!isset($THEME->skins) || $THEME->skins !== false)) {
$skin = array('skinid' => $viewskin, 'viewid' => $view->get('id'));
}
else {
$skin = false;
}
$smarty = smarty(
$javascript,
$headers,
array(),
array(
'stylesheets' => array('style/views.css'),
'skin' => $skin,
)
);
$smarty->assign('INLINEJAVASCRIPT', $blocksjs . $inlinejs);
$smarty->assign('viewid', $view->get('id'));
$smarty->assign('newlayout', $newlayout);
if (!$newlayout) {
$smarty->assign('viewcontent', $viewcontent);
}
$smarty->assign('group', $group);
$smarty->assign('editwindow', $editwindow);
$smarty->assign('cancopy', group_can_create_groups());
$smarty->assign('SUBPAGETOP', 'group/groupuseractions.tpl');
$smarty->assign('headingclass', 'page-header');
$smarty->assign('lastupdatedstr', $view->lastchanged_message());
$smarty->assign('visitstring', $view->visit_message());
$smarty->display('group/view.tpl');
| gpl-3.0 |
TallerUnityFICH/GeometryDash | Assets/Assets/Scripts/Modules/LoadScene.cs | 348 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadScene : MonoBehaviour {
public void Load (int sceneIndex) {
if (sceneIndex == 0)
GameManager.simulate = true;
SceneManager.LoadScene (sceneIndex);
}
public void Quit() {
Application.Quit ();
}
}
| gpl-3.0 |
nieklinnenbank/FreeNOS | lib/libarch/intel/IntelMP.cpp | 3465 | /*
* Copyright (C) 2015 Niek Linnenbank
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <FreeNOS/System.h>
#include <Log.h>
#include "IntelConstant.h"
#include "IntelMP.h"
#include "IntelBoot.h"
IntelMP::IntelMP(IntelAPIC & apic)
: CoreManager()
, m_apic(apic)
{
}
IntelMP::Result IntelMP::initialize()
{
SystemInformation info;
m_bios.map(MPAreaAddr, MPAreaSize);
m_lastMemory.map(info.memorySize - MegaByte(1), MegaByte(1));
m_apic.getIO().map(IntelAPIC::IOBase, PAGESIZE);
return Success;
}
IntelMP::MPConfig * IntelMP::scanMemory(Address addr)
{
MPFloat *mpf;
// Look for the Multiprocessor configuration
for (uint i = 0; i < MPAreaSize - sizeof(Address); i += sizeof(Address))
{
mpf = (MPFloat *)(addr + i);
if (mpf->signature == MPFloatSignature)
return (MPConfig *) (mpf->configAddr - MPAreaAddr + addr);
}
return ZERO;
}
IntelMP::Result IntelMP::discover()
{
MPConfig *mpc = 0;
MPEntry *entry;
// Clear previous discoveries
m_cores.clear();
// Try to find MPTable in the BIOS memory.
mpc = scanMemory(m_bios.getBase());
// Retry in the last 1MB of physical memory if not found.
if (!mpc)
{
mpc = scanMemory(m_lastMemory.getBase());
if (!mpc)
{
ERROR("MP header not found");
return NotFound;
}
}
// Found config
DEBUG("MP header found at " << (void *) mpc);
DEBUG("Local APIC at " << (void *) mpc->apicAddr);
entry = (MPEntry *)(mpc + 1);
// Search for multiprocessor entries
for (uint i = 0; i < mpc->count; i++)
entry = parseEntry(entry);
return Success;
}
IntelMP::Result IntelMP::boot(CoreInfo *info)
{
DEBUG("booting core" << info->coreId << " at " <<
(void *) info->memory.phys << " with kernel: " << info->kernelCommand);
// Copy 16-bit realmode startup code
VMCopy(SELF, API::Write, (Address) bootEntry16, MPEntryAddr, PAGESIZE);
// Copy the CoreInfo structure
VMCopy(SELF, API::Write, (Address) info, MPInfoAddr, sizeof(*info));
// Send inter-processor-interrupt to wakeup the processor
if (m_apic.sendStartupIPI(info->coreId, MPEntryAddr) != IntController::Success)
{
ERROR("failed to send startup IPI via APIC");
return IOError;
}
// Wait until the core raises the 'booted' flag in CoreInfo
while (1)
{
CoreInfo check;
VMCopy(SELF, API::Read, (Address) &check, MPInfoAddr, sizeof(check));
if (check.booted)
break;
}
return Success;
}
IntelMP::MPEntry * IntelMP::parseEntry(IntelMP::MPEntry *entry)
{
if (entry->type == MPEntryProc)
{
m_cores.append(entry->apicId);
return entry + 1;
}
else
return (MPEntry *) (((Address)(entry)) + 8);
}
| gpl-3.0 |
InfinityDeer/Unity-Project | Unity Project/Assets/FirstPersonView/Scripts/Renderer/FPV_Renderer_DisableOnly.cs | 1445 | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace FirstPersonView
{
/// <summary>
/// FPV Renderer for Disable Only objects.
/// This class will disable the renderer on OnPreCull.
/// It will re-enable it on OnPostRender.
/// </summary>
public class FPV_Renderer_DisableOnly : FPV_Renderer_Base
{
/// <summary>
/// Enable first Person Viewer
/// </summary>
public override void EnableFirstPersonViewer()
{
_render.enabled = false;
}
/// <summary>
/// Disable first Person Viewer.
/// </summary>
public override void DisableFirstPersonViewer()
{
_render.enabled = true;
}
/// <summary>
/// After this object is rendered by a camera, it will first check if it is a first person object.
/// If not, and if the current camera rendering is the world camera, it will tell the parent object that an object was affected
/// to the First Person View, and then it will enable the First Person View to prepare for the First Person Camera.
/// </summary>
void OnRenderObject()
{
if (_isFirstPersonObject) return;
if (isWorldCameraRendering)
{
_parent.SetChanged();
EnableFirstPersonViewer();
}
}
}
}
| gpl-3.0 |
StapleButter/SM64DSe | SM64DSFormats/SWAR.cs | 9925 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
namespace SM64DSe.SM64DSFormats
{
class SwavStream : WaveStream, ISampleProvider
{
public static int[] INDEX_TABLE = { -1, -1, -1, -1, 2, 4, 6, 8 };
public static int[] ADPCM_TABLE =
{
0x0007,0x0008,0x0009,0x000A,0x000B,0x000C,0x000D,0x000E,0x0010,0x0011,0x0013,0x0015,
0x0017,0x0019,0x001C,0x001F,0x0022,0x0025,0x0029,0x002D,0x0032,0x0037,0x003C,0x0042,
0x0049,0x0050,0x0058,0x0061,0x006B,0x0076,0x0082,0x008F,0x009D,0x00AD,0x00BE,0x00D1,
0x00E6,0x00FD,0x0117,0x0133,0x0151,0x0173,0x0198,0x01C1,0x01EE,0x0220,0x0256,0x0292,
0x02D4,0x031C,0x036C,0x03C3,0x0424,0x048E,0x0502,0x0583,0x0610,0x06AB,0x0756,0x0812,
0x08E0,0x09C3,0x0ABD,0x0BD0,0x0CFF,0x0E4C,0x0FBA,0x114C,0x1307,0x14EE,0x1706,0x1954,
0x1BDC,0x1EA5,0x21B6,0x2515,0x28CA,0x2CDF,0x315B,0x364B,0x3BB9,0x41B2,0x4844,0x4F7E,
0x5771,0x602F,0x69CE,0x7462,0x7FFF
};
private WaveFormat m_WaveFormat;
public SWAR.Wave m_Wave;
public ISampleProvider m_Resampled { get; private set; }
private int m_Position;
public override long Position
{
get
{
return m_Position;
}
set
{
m_Position = (int)value;
if (value == 0)
Reset();
}
}
public override long Length
{
get
{
return m_Wave.m_WaveType == SWAR.WaveType.ADPCM
? m_Wave.m_TheWave.m_Data.Length * 4 - 16
: m_Wave.m_TheWave.m_Data.Length;
}
}
//for IMA ADPCM
private int m_CurrPcm16Val;
private int m_CurrIndex;
private int m_LoopStartPcm16Val;
private int m_LoopStartIndex;
public SwavStream(SWAR.Wave wave)
{
m_Wave = wave;
m_WaveFormat = new WaveFormat(wave.m_SampleRate,
wave.m_WaveType == SWAR.WaveType.PCM8 ? 8 : 16, 1);
m_Position = 0;
if(m_Wave.m_WaveType == SWAR.WaveType.ADPCM)
{
m_CurrPcm16Val = (short)m_Wave.m_TheWave.Read16(0);
m_CurrIndex = m_Wave.m_TheWave.Read16(2);
m_Position = 4;
if(m_Wave.m_Loop)
{
byte[] buffer = new byte[4 * (m_Wave.m_LoopStart - 4)];
Read(buffer, 0, (int)(4 * (m_Wave.m_LoopStart - 4)));
m_LoopStartPcm16Val = m_CurrPcm16Val;
m_LoopStartIndex = m_CurrIndex;
//restore the starting state
m_CurrPcm16Val = (short)m_Wave.m_TheWave.Read16(0);
m_CurrIndex = m_Wave.m_TheWave.Read16(2);
m_Position = 4;
}
}
m_Resampled = new WdlResamplingSampleProvider(this, 44100);
}
public void Reset()
{
m_Position = m_Wave.m_WaveType == SWAR.WaveType.ADPCM ? 4 : 0;
if (m_Wave.m_WaveType == SWAR.WaveType.ADPCM)
{
m_CurrPcm16Val = (short)m_Wave.m_TheWave.Read16(0);
m_CurrIndex = m_Wave.m_TheWave.Read16(2);
}
}
public override WaveFormat WaveFormat { get { return m_WaveFormat; } }
public override int Read(byte[] buffer, int offset, int count)
{
if (m_Wave.m_WaveType != SWAR.WaveType.PCM8)
count = count / 2 * 2;
int currCount;
int totalCount = 0;
do
{
currCount = count;
switch (m_Wave.m_WaveType)
{
case SWAR.WaveType.PCM8:
case SWAR.WaveType.PCM16:
currCount = Math.Min(currCount, m_Wave.m_TheWave.m_Data.Length - m_Position);
Array.Copy(m_Wave.m_TheWave.m_Data, m_Position, buffer, offset, currCount);
m_Position += currCount;
break;
case SWAR.WaveType.ADPCM:
currCount = Math.Min(currCount, (m_Wave.m_TheWave.m_Data.Length - m_Position) * 4);
int byteData = 0;
for (int i = 0; i < currCount / 2; ++i)
{
if (i % 2 == 0)
byteData = m_Wave.m_TheWave.Read8((uint)m_Position);
int nybble = byteData >> 4 * (i % 2) & 0xf;
int diff = ADPCM_TABLE[m_CurrIndex] / 8;
if ((nybble & 1) != 0) diff += ADPCM_TABLE[m_CurrIndex] / 4;
if ((nybble & 2) != 0) diff += ADPCM_TABLE[m_CurrIndex] / 2;
if ((nybble & 4) != 0) diff += ADPCM_TABLE[m_CurrIndex] / 1;
if ((nybble & 8) == 0) m_CurrPcm16Val = Math.Min(m_CurrPcm16Val + diff, 0x7fff);
else m_CurrPcm16Val = Math.Max(m_CurrPcm16Val - diff, -0x7fff);
m_CurrIndex = Math.Min(Math.Max(m_CurrIndex + INDEX_TABLE[nybble & 7], 0), 88);
buffer[offset + 2 * i ] = (byte)(m_CurrPcm16Val >> 0);
buffer[offset + 2 * i + 1] = (byte)(m_CurrPcm16Val >> 8);
if (i % 2 == 1)
++m_Position;
}
break;
}
if(m_Wave.m_Loop && count > currCount)
{
m_Position = (int)m_Wave.m_LoopStart;
m_CurrPcm16Val = m_LoopStartPcm16Val;
m_CurrIndex = m_LoopStartIndex;
}
count -= currCount;
totalCount += currCount;
offset += currCount;
} while (m_Wave.m_Loop && count > 0);
return totalCount;
}
//the offset is into the buffer.
public int Read(float[] buffer, int offset, int count)
{
if (m_Wave.m_WaveType == SWAR.WaveType.ADPCM)
count = count / 2 * 2;
int byteCount = count * (m_Wave.m_WaveType == SWAR.WaveType.PCM8 ? 1 : 2);
INitroROMBlock byteBuffer = new INitroROMBlock(new byte[byteCount]);
byteCount = Read(byteBuffer.m_Data, 0, byteCount);
count = byteCount / (m_Wave.m_WaveType == SWAR.WaveType.PCM8 ? 1 : 2);
if (m_Wave.m_WaveType == SWAR.WaveType.PCM8)
for (int i = 0; i < count; ++i)
buffer[offset + i] = (sbyte)byteBuffer.m_Data[i] / 128.0f;
else
for (int i = 0; i < count; ++i)
buffer[offset + i] = (short)byteBuffer.Read16((uint)(2 * i)) / 32768.0f;
return count;
}
}
//http://mark-dot-net.blogspot.co.uk/2014/02/fire-and-forget-audio-playback-with.html
class AudioPlaybackEngine
{
private readonly IWavePlayer m_OutputDevice;
public AudioPlaybackEngine()
{
m_OutputDevice = new WaveOutEvent();
}
public void PlaySound(SwavStream input)
{
m_OutputDevice.Stop();
input.Reset();
m_OutputDevice.Init(input.m_Resampled);
m_OutputDevice.Play();
}
public void PlaySound(SWAR.Wave wave)
{
PlaySound(wave.m_TheTrueWave);
}
public void StopSound()
{
m_OutputDevice.Stop();
}
public void Dispose()
{
m_OutputDevice.Dispose();
}
public static readonly AudioPlaybackEngine Instance = new AudioPlaybackEngine();
}
class SWAR : SDAT.Record
{
public enum WaveType
{
PCM8 = 0,
PCM16,
ADPCM
}
public class Wave
{
public WaveType m_WaveType;
public bool m_Loop;
public int m_SampleRate;
public int m_Time; //sampleRate * time = 16756991
public uint m_LoopStart; //measured by byte
public uint m_LoopLength; //measured by byte
public INitroROMBlock m_TheWave;
public SwavStream m_TheTrueWave;
public void Play()
{
AudioPlaybackEngine.Instance.PlaySound(m_TheTrueWave);
}
}
public string m_Name { get; private set; }
public Wave[] m_Waves { get; private set; }
public SWAR(string name, INitroROMBlock swar)
{
m_Name = name;
m_Waves = new Wave[swar.Read32(0x38)];
for(uint i = 0; i < m_Waves.Length; ++i)
{
uint offset = swar.Read32(0x3c + 4 * i);
Wave wave = new Wave();
wave.m_WaveType = (WaveType)swar.Read8(offset + 0);
wave.m_Loop = swar.Read8(offset + 1) != 0;
wave.m_SampleRate = swar.Read16(offset + 2);
wave.m_Time = swar.Read16(offset + 4);
wave.m_LoopStart = swar.Read16(offset + 6) * 4u;
wave.m_LoopLength = swar.Read32(offset + 8) * 4u;
wave.m_TheWave = new INitroROMBlock(swar.ReadBlock(
offset + 12, wave.m_LoopStart + wave.m_LoopLength));
wave.m_TheTrueWave = new SwavStream(wave);
m_Waves[i] = wave;
/*sample.Play();
System.Threading.Thread.Sleep(2000);*/
}
}
}
}
| gpl-3.0 |
zilgrg/opencart | upload/admin/controller/blog/setting.php | 18585 | <?php
class ControllerBlogSetting extends Controller {
private $error = array();
public function index() {
$this->load->model('blog/setting');
$this->load->model('setting/setting');
$this->data = $this->load->language('blog/blog');
$this->data = $this->load->language('blog/setting');
$this->document->setTitle($this->language->get('heading_title'));
$this->document->addStyle('view/stylesheet/blog.css');
$this->data['link_author'] = sprintf($this->data['text_link'], $this->data['dev_url'], $this->data['dev_name'], $this->data['dev_name']);
$this->data['link_copyright'] = sprintf($this->data['dev_copyright'], $this->data['heading_title'], '2011 - ' . date('Y'), $this->data['link_author']);
$this->data['oc_footer'] = sprintf($this->language->get('oc_footer'), VERSION);
$this->load->model('blog/article');
$isAuthor = $this->model_blog_article->getAuthorByUser($this->user->getId());
if (!$isAuthor) {
$this->session->data['warning'] = $this->language->get('error_notauthor');
$this->redirect($this->url->link('blog/blog', 'token=' . $this->session->data['token'], 'SSL'));
}
$this->load->model('blog/author');
$blogPermission = $this->model_blog_author->getPermissionByUser($this->user->getId());
if (is_array(unserialize($blogPermission))) { foreach (unserialize($blogPermission) as $permission) { $this->data['haspermission_'. $permission] = 1; }; }
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('blog/blog', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => ' <span class="separator">»</span> '
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('head_setting'),
'href' => $this->url->link('blog/setting', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => ' <span class="separator">»</span> '
);
if (isset($this->session->data['success'])) {
$this->data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$this->data['success'] = '';
}
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateSetting()) {
if (isset($this->request->post['articleAdmin'])) {
//===
$post_data = $this->request->post;
$blogHomeDescription = (isset($this->request->post['blogHomeDescription'])) ? $this->request->post['blogHomeDescription'] : array();
$blogExclude = (isset($this->request->post['blogExclude'])) ? $this->request->post['blogExclude'] : array();
$blogHomeTemplate = (isset($this->request->post['blogHomeTemplate'])) ? $this->request->post['blogHomeTemplate'] : array();
$blogCatTemplate = (isset($this->request->post['blogHomeTemplate'])) ? $this->request->post['blogCatTemplate'] : array();
$blogArtTemplate = (isset($this->request->post['blogHomeTemplate'])) ? $this->request->post['blogArtTemplate'] : array();
$virDirExclude = (isset($this->request->post['virDirExclude'])) ? $this->request->post['virDirExclude'] : array();
$commentDisableCat = (isset($this->request->post['commentDisableCat'])) ? $this->request->post['commentDisableCat'] : array();
$commentApproveGroup = (isset($this->request->post['commentApproveGroup'])) ? $this->request->post['commentApproveGroup'] : array();
$commentAdminBadgeGroup = (isset($this->request->post['commentAdminBadgeGroup'])) ? $this->request->post['commentAdminBadgeGroup'] : array();
$commentBadgeGroup = (isset($this->request->post['commentBadgeGroup'])) ? $this->request->post['commentBadgeGroup'] : array();
$adminBlogColors = (isset($this->request->post['adminBlogColors'])) ? $this->request->post['adminBlogColors'] : array();
$commentBadgeColor = (isset($this->request->post['commentBadgeColor'])) ? $this->request->post['commentBadgeColor'] : array();
$post_data['blogHomeDescription'] = serialize($blogHomeDescription);
$post_data['blogExclude'] = serialize($blogExclude);
$post_data['blogHomeTemplate'] = serialize($blogHomeTemplate);
$post_data['blogCatTemplate'] = serialize($blogCatTemplate);
$post_data['blogArtTemplate'] = serialize($blogArtTemplate);
$post_data['virDirExclude'] = serialize($virDirExclude);
$post_data['commentDisableCat'] = serialize($commentDisableCat);
$post_data['commentApproveGroup'] = serialize($commentApproveGroup);
$post_data['commentAdminBadgeGroup'] = serialize($commentAdminBadgeGroup);
$post_data['commentBadgeGroup'] = serialize($commentBadgeGroup);
$post_data['adminBlogColors'] = serialize($adminBlogColors);
$post_data['commentBadgeColor'] = serialize($commentBadgeColor);
$this->model_blog_setting->updateSetting($post_data);
//=== Save some data at OpenCart setting
$blogSettingConfig = array(
'blogSetting_virDir' => $this->request->post['virDir'],
'blogSetting_virDirName' => $this->request->post['virDirName'],
'blogSetting_virDirExclude' => $virDirExclude,
'blogSetting_relProductArticle' => $this->request->post['relProductArticle']
);
$this->model_setting_setting->editSetting('blogSetting', $blogSettingConfig);
//===
$this->session->data['success'] = $this->language->get('text_success_setting');
$this->redirect($this->url->link('blog/setting', 'token=' . $this->session->data['token'], 'SSL'));
}
}
//== Menu
$this->data['menu_home_href'] = $this->url->link('blog/blog', 'token=' . $this->session->data['token'], 'SSL');
$this->data['menu_article_href'] = $this->url->link('blog/article', 'token=' . $this->session->data['token'], 'SSL');
$this->data['menu_category_href'] = $this->url->link('blog/category', 'token=' . $this->session->data['token'], 'SSL');
$this->data['menu_comment_href'] = $this->url->link('blog/comment', 'token=' . $this->session->data['token'], 'SSL');
$this->data['menu_author_href'] = $this->url->link('blog/author', 'token=' . $this->session->data['token'], 'SSL');
$this->data['menu_setting_href'] = $this->url->link('blog/setting', 'token=' . $this->session->data['token'], 'SSL');
$this->data['menu_about_href'] = $this->url->link('blog/about', 'token=' . $this->session->data['token'], 'SSL');
$this->data['token'] = $this->session->data['token'];
$this->data['action'] = $this->url->link('blog/setting', 'token=' . $this->session->data['token'], 'SSL');
// Fallback compatibility and transition for Blog home multi-language. Removed when BM reach v.1.4.2
$this->data['blogNameValue'] = '';
$this->data['blogTitleValue'] = '';
$this->data['blogKeywordValue'] = '';
$this->data['blogDescriptionValue'] = '';
//== General Data
$this->load->model('setting/store');
$this->data['stores'] = $this->model_setting_store->getStores();
$blogSettings = $this->model_blog_setting->getSettings();
foreach ($blogSettings as $key => $value) { $this->data[$key . 'Value'] = $value; };
//== Blog Home Description
$this->load->model('localisation/language');
$this->data['languages'] = $this->model_localisation_language->getLanguages();
if (isset($this->request->post['blogHomeDescription'])) {
$this->data['blogHomeDescriptionValues'] = $this->request->post['blogHomeDescription'];
} elseif (isset($this->data['blogHomeDescriptionValue'])) {
$this->data['blogHomeDescriptionValues'] = unserialize($this->data['blogHomeDescriptionValue']);
} else {
$this->data['blogHomeDescriptionValues'] = array();
}
//== Blog Home: Exclude Category
$this->load->model('blog/category');
$this->data['categories'] = $this->model_blog_category->getCategories(0);
if (isset($this->request->post['blogExclude'])) {
$this->data['blogExcludeValues'] = $this->request->post['blogExclude'];
} elseif ($this->data['blogExcludeValue']) {
$this->data['blogExcludeValues'] = unserialize($this->data['blogExcludeValue']);
} else {
$this->data['blogExcludeValues'] = array();
}
//== Blog Home: Specific Template
$this->specificTemplate('Home', 'category_');
if (isset($this->request->post['blogHomeTemplate'])) {
$this->data['blogHomeTemplateValues'] = $this->request->post['blogHomeTemplate'];
} elseif (isset($this->data['blogHomeTemplateValue'])) {
$this->data['blogHomeTemplateValues'] = unserialize($this->data['blogHomeTemplateValue']);
} else {
$this->data['blogHomeTemplateValues'] = array();
}
//== Categories: Default Template
$this->specificTemplate('Cat', 'category_');
if (isset($this->request->post['blogCatTemplate'])) {
$this->data['blogCatTemplateValues'] = $this->request->post['blogCatTemplate'];
} elseif (isset($this->data['blogCatTemplateValue'])) {
$this->data['blogCatTemplateValues'] = unserialize($this->data['blogCatTemplateValue']);
} else {
$this->data['blogCatTemplateValues'] = array();
}
//== Articles: Default Template
$this->specificTemplate('Art', 'article_');
if (isset($this->request->post['blogArtTemplate'])) {
$this->data['blogArtTemplateValues'] = $this->request->post['blogArtTemplate'];
} elseif (isset($this->data['blogArtTemplateValue'])) {
$this->data['blogArtTemplateValues'] = unserialize($this->data['blogArtTemplateValue']);
} else {
$this->data['blogArtTemplateValues'] = array();
}
//== Categories: Virtual Directory Exclude
if (isset($this->request->post['virDirExclude'])) {
$this->data['virDirExcludeValues'] = $this->request->post['virDirExclude'];
} elseif ($this->data['virDirExcludeValue']) {
$this->data['virDirExcludeValues'] = unserialize($this->data['virDirExcludeValue']);
} else {
$this->data['virDirExcludeValues'] = array();
}
//== Comments: Disable Category
if (isset($this->request->post['commentDisableCat'])) {
$this->data['commentDisableCatValues'] = $this->request->post['commentDisableCat'];
} elseif ($this->data['commentDisableCatValue']) {
$this->data['commentDisableCatValues'] = unserialize($this->data['commentDisableCatValue']);
} else {
$this->data['commentDisableCatValues'] = array();
}
//== Comments: Customer Group Auto Approve
$this->load->model('sale/customer_group');
$this->data['customer_groups'] = $this->model_sale_customer_group->getCustomerGroups();
if (isset($this->request->post['commentApproveGroup'])) {
$this->data['commentApproveGroupValues'] = $this->request->post['commentApproveGroup'];
} elseif ($this->data['commentApproveGroupValue']) {
$this->data['commentApproveGroupValues'] = unserialize($this->data['commentApproveGroupValue']);
} else {
$this->data['commentApproveGroupValues'] = array();
}
$this->load->model('user/user_group');
$this->data['user_groups'] = $this->model_user_user_group->getUserGroups();
//== Comments: Admin Group Badge
if (isset($this->request->post['commentAdminBadgeGroup'])) {
$this->data['commentBadgeGroupValues'] = $this->request->post['commentAdminBadgeGroup'];
} elseif ($this->data['commentAdminBadgeGroupValue']) {
$this->data['commentAdminBadgeGroupValues'] = unserialize($this->data['commentAdminBadgeGroupValue']);
} else {
$this->data['commentAdminBadgeGroupValues'] = array();
}
//== Comments: Admin Group Badge Color
if (isset($this->request->post['adminBlogColors'])) {
$this->data['adminBlogColorsValues'] = $this->request->post['adminBlogColors'];
} elseif (isset($this->data['adminBlogColorsValue'])) {
$this->data['adminBlogColorsValues'] = unserialize($this->data['adminBlogColorsValue']);
} else {
$this->data['adminBlogColorsValues'] = array();
}
//== Comments: Customer Group Badge
if (isset($this->request->post['commentBadgeGroup'])) {
$this->data['commentBadgeGroupValues'] = $this->request->post['commentBadgeGroup'];
} elseif ($this->data['commentBadgeGroupValue']) {
$this->data['commentBadgeGroupValues'] = unserialize($this->data['commentBadgeGroupValue']);
} else {
$this->data['commentBadgeGroupValues'] = array();
}
//== Comments: Customer Group Badge Color
if (isset($this->request->post['commentBadgeColor'])) {
$this->data['commentBadgeColorValues'] = $this->request->post['commentBadgeColor'];
} elseif (isset($this->data['commentBadgeColorValue'])) {
$this->data['commentBadgeColorValues'] = unserialize($this->data['commentBadgeColorValue']);
} else {
$this->data['commentBadgeColorValues'] = array();
}
//== Error Handler
$errorSettings = array('warning', 'tabAdmin', 'articleAdmin', 'tabCategory', 'articleCat', 'articleDesc', 'articleFeature', 'tabArticle', 'relProduct', 'relProductWH', 'tabComment', 'commentMinMax', 'tabSearch', 'searchLimit', 'searchGrid');
foreach ($errorSettings as $errorSetting) {
if (isset($this->error[$errorSetting])) {
$this->data['error_'.$errorSetting] = $this->error[$errorSetting];
} else {
$this->data['error_'.$errorSetting] = '';
}
}
if (isset($this->error['warning'])) {
$this->data['warning'] = $this->error['warning'];
} else {
$this->data['warning'] = '';
}
$help_meta = $this->language->get('help_meta'); // @todo language file
$help_page = '11469110';
$this->data['online_help_url'] = $this->url->link('blog/help', 'meta=' . $help_meta . '&page=' . $help_page . '&token=' . $this->session->data['token'], 'SSL');
$this->template = 'blog/setting.tpl';
$this->children = array(
'common/header',
'common/footer',
);
$this->response->setOutput($this->render());
}
private function specificTemplate($identifier = 'Blog', $tempPrefix = 'blog_') {
$this->data['templates' . $identifier] = array();
$storeTemplates = $this->model_blog_category->getStoresTemplate();
foreach ($storeTemplates as $storeTemplate) {
$templateData = '';
$templateFiles = glob(DIR_CATALOG . 'view/theme/' . $storeTemplate['value'] . '/template/blog/' . $tempPrefix . '*.tpl');
if ($templateFiles) {
foreach ($templateFiles as $templateFile) {
$template = basename($templateFile, '.tpl');
$template1 = str_replace($tempPrefix, '', $template);
$template2 = str_replace('_', ' ', $template1);
$templateData[] = array(
'value' => $template1,
'name' => ucwords($template2)
);
}
$this->data['templates' . $identifier][$storeTemplate['store_id']] = $templateData;
}
}
}
private function validateSetting() {
if (!$this->user->hasPermission('modify', 'blog/setting')) {
$this->error['warning'] = $this->language->get('error_permission');
}
if (isset($this->request->post['articleCat'])) {
if (!$this->request->post['articleCat'] || $this->request->post['articleCat'] <= 0) {
$this->error['articleCat'] = $this->language->get('error_limit');
}
if (!$this->request->post['articleDesc'] || $this->request->post['articleDesc'] <= 0) {
$this->error['articleDesc'] = $this->language->get('error_limit');
}
if (!$this->request->post['articleFeatWidth'] || $this->request->post['articleFeatWidth'] <= 0 || !$this->request->post['articleFeatHeight'] || $this->request->post['articleFeatHeight'] <= 0) {
$this->error['articleFeature'] = $this->language->get('error_size');
}
if ((isset($this->error['articleCat']) || isset($this->error['articleDesc']) || isset($this->error['articleFeatWidth'])) && !isset($this->error['warning'])) {
$this->error['tabCategory'] = $this->language->get('error_tab');
}
}
if (isset($this->request->post['relProduct'])) {
if (!$this->request->post['relProduct'] || $this->request->post['relProduct'] <= 0) {
$this->error['relProduct'] = $this->language->get('error_limit');
}
if (!$this->request->post['relProductWidth'] || $this->request->post['relProductWidth'] <= 0 || !$this->request->post['relProductHeight'] || $this->request->post['relProductHeight'] <= 0) {
$this->error['relProductWH'] = $this->language->get('error_size');
}
if ((isset($this->error['relProduct']) || isset($this->error['relProductWH']) || isset($this->error['commentMinMax'])) && !isset($this->error['warning'])) {
$this->error['tabArticle'] = $this->language->get('error_tab');
}
}
if (isset($this->request->post['commentMin']) || isset($this->request->post['commentMax'])) {
if (!$this->request->post['commentMin'] || $this->request->post['commentMin'] <= 0 || !$this->request->post['commentMax'] || $this->request->post['commentMax'] <= 0) {
$this->error['commentMinMax'] = $this->language->get('error_limit');
}
if (isset($this->error['commentMinMax']) && !isset($this->error['warning'])) {
$this->error['tabComment'] = $this->language->get('error_tab');
}
}
if (isset($this->request->post['searchLimit'])) {
if (!$this->request->post['searchLimit'] || $this->request->post['searchLimit'] <= 0) {
$this->error['searchLimit'] = $this->language->get('error_limit');
}
if (!$this->request->post['searchGrid'] || $this->request->post['searchGrid'] <= 0) {
$this->error['searchGrid'] = $this->language->get('error_limit');
}
if ((isset($this->error['searchLimit']) || isset($this->error['searchGrid'])) && !isset($this->error['warning'])) {
$this->error['tabSearch'] = $this->language->get('error_tab');
}
}
if (isset($this->request->post['articleAdmin'])) {
if (!$this->request->post['articleAdmin'] || $this->request->post['articleAdmin'] <= 0) {
$this->error['articleAdmin'] = $this->language->get('error_limit');
}
if (isset($this->error['articleAdmin']) && !isset($this->error['warning'])) {
$this->error['tabAdmin'] = $this->language->get('error_tab');
}
}
if (!$this->error) {
return true;
} else {
return false;
}
}
}
?> | gpl-3.0 |
pasanzaza/Dragonbound | src/server/GameServerDB/Chat/ChatManager.cs | 2929 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using System.Web;
namespace GameServerDB.Chat
{
public class ChatManager
{
public static string Msj(string _msjx, UserManager.UserClass _user)
{
string msj_f = HttpUtility.HtmlEncode(_msjx.Replace("\\\"", "\""));
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.None;
writer.WriteStartArray();
writer.WriteValue((int)ServerOpcode.chat);
writer.WriteValue(_msjx);
writer.WriteValue(_user.Name);
writer.WriteValue(0); //type
writer.WriteEndArray();
}
return sb.ToString();
}
public static void Notice(UserManager.UserClass _user)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.None;
writer.WriteStartArray();
writer.WriteValue((int)ServerOpcode.room_state);
writer.WriteStartArray();
writer.WriteStartArray();
writer.WriteValue("GameServerDB");
writer.WriteValue("");
writer.WriteValue(9);
writer.WriteEndArray();
writer.WriteStartArray();
writer.WriteValue("Bienvenido!");
writer.WriteValue("");
writer.WriteValue(9);
writer.WriteEndArray();
writer.WriteEndArray();
writer.WriteEndArray();
}
_user.sep.Send(sb.ToString());
}
public static void UpdateBoddy(Serverb _serv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.None;
writer.WriteStartArray();
writer.WriteValue((int)ServerOpcode.channel_players);
writer.WriteStartArray();
foreach (UserManager.UserClass _user in Program.Users)
{
writer.WriteValue(_user.user_id);
writer.WriteValue(_user.Name);
writer.WriteValue(_user.rank);
writer.WriteValue(_user.unk0);
}
writer.WriteEndArray();
writer.WriteEndArray();
}
_serv.Broadcast(sb.ToString());
}
}
}
| gpl-3.0 |
libretees/libreshop | libreshop/api/views.py | 5461 | import hashlib
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.mail import EmailMessage
from django.db import transaction
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework import status
from rest_framework.permissions import AllowAny, IsAuthenticated, IsAdminUser
from rest_framework import exceptions
from customers.forms import RegistrationToken
from addresses.models import Address
from orders.models import Order, Purchase
from fulfillment.models import Carrier, Shipment
from .serializers import (
UserSerializer, GroupSerializer, RegistrationTokenSerializer,
ShipmentSerializer, OrderSerializer, PurchaseSerializer
)
User = get_user_model()
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
def get_queryset(self):
if self.request.user.is_staff:
return User.objects.all()
else:
return User.objects.filter(id=self.request.user.id)
def get_permissions(self):
permissions = None
if self.request.method in ['GET', 'PUT', 'PATCH', 'HEAD']:
permissions = (IsAuthenticated(),)
if self.request.method in ['POST', 'OPTIONS']:
# allow non-authenticated users to create via POST
# and allow API capabilities to be described via OPTIONS
permissions = (AllowAny(),)
return permissions
def create(self, request, *args, **kwargs):
data = request.data
self._validate_captcha(request, *args, **kwargs)
# Get an email address, if one was specified.
user_email_address = data.get('email', None)
with transaction.atomic():
user = User.objects.create_user(
username=data['username'],
password=data['password'],
email=user_email_address
)
user.save()
if user_email_address:
email = EmailMessage(
subject='Welcome to LibreShop!',
body='Test',
from_email=settings.DEFAULT_FROM_EMAIL,
to=[user_email_address],
bcc=[],
connection=None,
attachments=None,
headers=None,
cc=None,
reply_to=None
)
email.send()
serializer = UserSerializer(user, context={'request': request})
headers = self.get_success_headers(serializer.data)
return Response(
serializer.data, status=status.HTTP_201_CREATED, headers=headers
)
def _validate_captcha(self, request, *args, **kwargs):
data = request.data
token = data.get('token', None)
if not token:
error = {'token': ['A registration token is required.'], 'description': ['This field may not be blank.']}
raise exceptions.ValidationError(error)
captcha = data.get('captcha', None)
if not captcha:
error = {'captcha': ['A CAPTCHA response is required.'], 'description': ['This field may not be blank.']}
raise exceptions.ValidationError(error)
token_hash = hashlib.sha256(captcha.encode()).hexdigest()
if token != token_hash:
error = {'captcha': ['CAPTCHA is invalid'], 'description': ['The supplied CAPTCHA response is invalid.']}
raise exceptions.ValidationError(error)
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
class RegistrationTokenView(APIView):
"""
API endpoint to obtain a user registration token.
"""
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
"""
Return a list of all users.
"""
registration_token = RegistrationToken()
serializer = RegistrationTokenSerializer(registration_token)
return Response(serializer.data)
class OrderViewSet(viewsets.ReadOnlyModelViewSet):
"""
API endpoint that allows Orders to be viewed.
"""
queryset = Order.objects.all()
serializer_class = OrderSerializer
permission_classes = (IsAdminUser,)
lookup_field = 'token'
def retrieve(self, request, token=None):
queryset = Order.objects.all()
order = get_object_or_404(queryset, token=token)
serializer = OrderSerializer(order, context={'request': request})
return Response(serializer.data)
class PurchaseViewSet(viewsets.ModelViewSet):
queryset = Purchase.objects.all()
serializer_class = PurchaseSerializer
permission_classes = (IsAdminUser,)
class ShipmentViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows Shipments to be viewed or edited.
"""
queryset = Shipment.objects.all()
serializer_class = ShipmentSerializer
permission_classes = (IsAdminUser,)
lookup_field = 'token'
def retrieve(self, request, token=None):
queryset = Shipment.objects.all()
shipment = get_object_or_404(queryset, token=token)
serializer = ShipmentSerializer(shipment, context={'request': request})
return Response(serializer.data)
| gpl-3.0 |
blackdesert/DesertProject | WorldServer/Scripts/AdminCommands/ScrKick.cs | 1882 | using System.Linq;
using Commons.Enums;
using WorldServer.Emu;
using WorldServer.Emu.Networking;
using WorldServer.Emu.Networking.Handling.Frames.Send;
/*
Author:Sagara, InCube
*/
namespace WorldServer.Scripts.AdminCommands
{
public class ScrKick : ICommandScript
{
public void Process(ClientConnection connection, string[] message)
{
Core.Act(s =>
{
var playersList = s.CharacterProcessor.OnlineList;
if (message.Length > 1)
{
foreach (var selectedName in message)
{
var result = playersList.FirstOrDefault(
p => p.DatabaseCharacterData.CharacterName == selectedName);
if (result == null)
new SMSG_Chat($"[Admin processor] cannot found {selectedName} player", connection.ActivePlayer.GameSessionId,
connection.ActivePlayer.DatabaseCharacterData.CharacterName, ChatType.Notice)
.Send(connection);
else
result.Connection.CloseConnection();
}
}
if (message.Length == 1)
{
var select =
playersList.FirstOrDefault(p => p.DatabaseCharacterData.CharacterName == message[0]);
if (select != null)
select.Connection.CloseConnection();
else
new SMSG_Chat($"[Admin processor] cannot found {message[0]} player",
connection.ActivePlayer.GameSessionId, connection.ActivePlayer.DatabaseCharacterData.CharacterName, ChatType.Notice).Send(connection);
}
});
}
}
} | gpl-3.0 |
Bramas/CakePHP2-Upload | Controller/UploadController.php | 1460 | <?php
App::uses('AppController', 'Controller');
class UploadController extends AppController {
public $components = array('Upload.PluploadHandler');
public function admin_uploadHandler()
{
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : $_FILES['file']["name"];
$this->PluploadHandler->no_cache_headers();
$this->PluploadHandler->cors_headers();
$chunk = isset($_REQUEST['chunk']) ? intval($_REQUEST['chunk']) : 0;
$chunks = isset($_REQUEST['chunks']) ? intval($_REQUEST['chunks']) : 0;
$tmpName = uniqid('file_');
if($chunks)
{
if($chunk)
{
$tmpName = $this->Session->read('Upload.tmp_names.'.$name);
if(empty($tmpName))
{
die(json_encode(array(
'OK' => 0,
'error' => array(
'message' => 'Temp name does not exist in the Session'
)
)));
}
}
else
{
$this->Session->write('Upload.tmp_names.'.$name, $tmpName);
}
}
if (!$this->PluploadHandler->handle(array(
'target_dir' => TMP,
'file_name' => $tmpName,
'allow_extensions' => array('jpg','jpeg','png','dmg','bmp','zip','pdf','gif','exe')
))) {
die(json_encode(array(
'OK' => 0,
'error' => array(
'code' => $this->PluploadHandler->get_error_code(),
'message' => $this->PluploadHandler->get_error_message()
)
)));
} else {
die(json_encode(array('OK' => 1, "name" => $name , "tmp_name" => TMP.$tmpName)));
}
}
} | gpl-3.0 |
hgonzalezgaviria/diheke | config/app.php | 8769 | <?php
return [
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'America/Bogota',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'es',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'es',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => env('APP_LOG', 'single'),
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Application Service Providers...
*/
reservas\Providers\AppServiceProvider::class,
reservas\Providers\AuthServiceProvider::class,
reservas\Providers\EventServiceProvider::class,
reservas\Providers\RouteServiceProvider::class,
MaddHatter\LaravelFullcalendar\ServiceProvider::class,
Barryvdh\DomPDF\ServiceProvider::class,
//Add by DiegoCortes
Styde\Html\HtmlServiceProvider::class,
Maatwebsite\Excel\ExcelServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'Entrust' => Zizaco\Entrust\EntrustFacade::class,
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
'Calendar' => MaddHatter\LaravelFullcalendar\Facades\Calendar::class,
'PDF' => Barryvdh\DomPDF\Facade::class,
],
];
| gpl-3.0 |
processmining/synthetic-log-generator | DeclareDesigner/src/nl/tue/declare/appl/design/model/gui/ActivityDataTableModel.java | 920 | package nl.tue.declare.appl.design.model.gui;
import nl.tue.declare.appl.util.swing.*;
import nl.tue.declare.domain.model.*;
public class ActivityDataTableModel
extends TTableModel {
/**
*
*/
private static final long serialVersionUID = 6799371841545528012L;
public ActivityDataTableModel() {
super(0, new Object[] {"data element", "type", "input - output"});
}
/**
*
* @param data ActivityData
*/
public void addRow(ActivityDataDefinition data) {
addRow(new Object[] {data, data.getDataElement().getType(),
data.getType().name()});
}
/**
*
* @param data ActivityData
*/
public void updateRow(ActivityDataDefinition data) {
int row = this.getIndexOf(data);
this.setValueAt(data, row, 0);
this.setValueAt(data.getDataElement().getName(), row, 1);
this.setValueAt(data.getType().name(), row, 2);
}
}
| gpl-3.0 |
proarc/proarc | proarc-webapp/src/main/java/cz/cas/lib/proarc/webapp/server/rest/AnnotatedStringRecord.java | 1851 | /*
* Copyright (C) 2013 Jan Pokorsky
*
* 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 cz.cas.lib.proarc.webapp.server.rest;
import cz.cas.lib.proarc.common.fedora.StringEditor.StringRecord;
import cz.cas.lib.proarc.webapp.shared.rest.DigitalObjectResourceApi;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Helper class to annotate {@link StringRecord} properties.
*
* @see JacksonProvider
*
* @author Jan Pokorsky
*/
@XmlRootElement(name = DigitalObjectResourceApi.STRINGRECORD_ELEMENT)
@XmlAccessorType(XmlAccessType.NONE)
public abstract class AnnotatedStringRecord extends StringRecord {
@XmlElement(name = DigitalObjectResourceApi.BATCHID_PARAM)
@Override
public abstract Integer getBatchId();
@XmlElement(name = DigitalObjectResourceApi.STRINGRECORD_CONTENT)
@Override
public abstract String getContent();
@XmlElement(name = DigitalObjectResourceApi.DIGITALOBJECT_PID)
@Override
public abstract String getPid();
@XmlElement(name = DigitalObjectResourceApi.TIMESTAMP_PARAM)
@Override
public abstract long getTimestamp();
}
| gpl-3.0 |
Abnaxos/NeoBeans | src/test/java/ch/raffael/neobeans/impl/TestBeanPropertyMapping.java | 4883 | package ch.raffael.neobeans.impl;
import java.net.URL;
import org.testng.annotations.*;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.NotFoundException;
import org.neo4j.graphdb.Transaction;
import static org.testng.Assert.*;
/**
* @author <a href="mailto:[email protected]">Raffael Herzog</a>
*/
public class TestBeanPropertyMapping extends Neo4jTest {
@Test
public void testSimple() throws Exception {
BeanPropertyMapping mapping = new BeanPropertyMapping(beanStore.database(), "name", null, null,
TestBean.class.getMethod("getName"),
TestBean.class.getMethod("setName", String.class));
TestBean bean = new TestBean();
bean.setName("Raffael");
Node node;
Transaction tx = beanStore.beginTx();
try {
node = beanStore.database().createNode();
mapping.beanToEntity(node, bean);
tx.success();
}
finally {
tx.finish();
}
tx = beginTx();
try {
assertEquals(node.getProperty("name"), "Raffael", "Value in DB");
node.setProperty("name", "Raffi");
tx.success();
}
finally {
tx.finish();
}
tx = beginTx();
try {
mapping.entityToBean(node, bean);
assertEquals(bean.getName(), "Raffi", "Bean value");
bean.setName(null);
mapping.beanToEntity(node, bean);
tx.success();
}
finally {
tx.finish();
}
tx = beginTx();
try {
try {
node.getProperty("name");
fail("NotFoundException expected");
}
catch ( NotFoundException e ) {
// expected
}
tx.success();
}
finally {
tx.finish();
}
}
@Test
public void testConverter() throws Exception {
BeanPropertyMapping mapping = new BeanPropertyMapping(beanStore.database(), "homepage",
new UrlConverter(), null,
TestBean.class.getMethod("getHomepage"),
TestBean.class.getMethod("setHomepage", URL.class));
TestBean bean = new TestBean();
Transaction tx = beginTx();
Node node;
try {
bean.setHomepage(new URL("http://github.com/"));
node = beanStore.database().createNode();
mapping.beanToEntity(node, bean);
tx.success();
}
finally {
tx.finish();
}
tx = beginTx();
try {
assertEquals(node.getProperty("homepage"), "http://github.com/", "URL in DB");
node.setProperty("homepage", "http://github.com/test");
tx.success();
}
finally {
tx.finish();
}
tx = beginTx();
try {
mapping.entityToBean(node, bean);
assertEquals(bean.getHomepage(), new URL("http://github.com/test"), "Bean value");
bean.setHomepage(null);
mapping.beanToEntity(node, bean);
tx.success();
}
finally {
tx.finish();
}
tx = beginTx();
try {
try {
node.getProperty("homepage");
fail("Expected not found exception");
}
catch ( NotFoundException e ) {
// expected
}
tx.success();
}
finally {
tx.finish();
}
}
@Test
public void testSetFromNullToNull() throws Exception {
BeanPropertyMapping mapping = new BeanPropertyMapping(beanStore.database(), "name", null, null,
TestBean.class.getMethod("getName"),
TestBean.class.getMethod("setName", String.class));
TestBean bean = new TestBean();
assertNull(bean.getName());
Transaction tx = beginTx();
Node node;
try {
node = beanStore.database().createNode();
mapping.beanToEntity(node, bean);
tx.success();
}
finally {
tx.finish();
}
tx = beginTx();
try {
try {
node.getProperty("name");
fail("Expected not found exception");
}
catch ( NotFoundException e ) {
// expected
}
tx.success();
}
finally {
tx.finish();
}
}
}
| gpl-3.0 |
astralien3000/aversive-- | tests/sasiae/sync/server.cpp | 1302 | #include <QProcess>
#include <iostream>
#include "../../my_assert.hpp"
#include "../util.hpp"
int main(int argc, char** argv) {
(void) argc;
(void) argv;
QProcess client;
client.start("./client.elf", QStringList());
myAssert(client.waitForStarted(), "Line " S__LINE__ ": The client could not be initialized properly.");
client.write("T 1 10\n");
char buffer2[80];
for(int i = 0; i < 10; i++) {
sprintf(buffer2, "D TESTER value is %d", i);
myAssert(checkMsg(client, buffer2), "Line " S__LINE__ ": Unexpected message.");
}
myAssert(checkMsg(client, "T"), "Line " S__LINE__ ": The client thread did not send \"T\" as expected.");
client.write("T 2 100\n");
for(int i = 10; i < 110; i++) {
sprintf(buffer2, "D TESTER value is %d", i);
myAssert(checkMsg(client, buffer2), "Line " S__LINE__ ": Unexpected message.");
}
myAssert(checkMsg(client, "T"), "Line " S__LINE__ ": The client thread did not send \"T\" as expected.");
client.write("S\n");
myAssert(checkMsg(client, "S"), "Line " S__LINE__ ": The client thread did not send \"S\" as expected.");
client.closeWriteChannel();
myAssert(client.waitForFinished(), "Line " S__LINE__ ": The client did not close properly.");
std::cout << "OK" << std::endl;
return 0;
}
| gpl-3.0 |
jo-soft/jadfr | jadfr/api/feeds/tests/unittests/test_serializers.py | 2049 | from api.feeds.serializers import RecursiveField, ProxyModelSerializer
from django.db.models import Model, ForeignKey, CharField
from django.test import TestCase
from rest_framework.serializers import Serializer, ModelSerializer
from django.utils.six import BytesIO
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
__author__ = 'j_schn14'
class TestProxyModelSerializer(TestCase):
def setUp(self):
class M1(Model):
field = CharField()
class M2(Model):
field = CharField()
proxy = ForeignKey(M1)
class CSerializerM1(ModelSerializer):
class Meta:
model = M1
fields = 'field',
class CSerializerM2(ProxyModelSerializer):
class Meta:
model = M2
fields = tuple()
proxy_fields = 'field',
proxy = 'proxy'
self.M1 = M1
self.M2 = M2
self.SerializerM1 = CSerializerM1
self.SerializerM2 = CSerializerM2
def test_proxyed_val(self):
# do some setup stuff.
fld1 = 'field1'
fld2 = 'field2'
m1 = self.M1(field=fld1)
m2 = self.M2(field=fld2, proxy=m1)
# first try: serialize m2 which has to have field2 as value of field2 after serialisation
data_serializer = self.SerializerM2(m2)
json = JSONRenderer().render(data_serializer.data)
stream = BytesIO(json)
data = JSONParser().parse(stream)
for field_name, value in data.iteritems():
assert getattr(m2, field_name) == value
# second try: serialize m2prime which has the proxyed value field1.
m2prime = self.M2(field='', proxy=m1)
data_serializer = self.SerializerM2(m2prime)
json = JSONRenderer().render(data_serializer.data)
stream = BytesIO(json)
data = JSONParser().parse(stream)
for field_name, value in data.iteritems():
assert getattr(m1, field_name) == value
| gpl-3.0 |
svn2github/rlgo | unittest/RlTestMain.cpp | 524 | #define BOOST_TEST_DYN_LINK // Must be defined before including unit_test.hpp
#include <boost/test/unit_test.hpp>
#include <iostream>
#include "SgSystem.h"
#include "GoBoard.h"
#include "GoInit.h"
#include "SgInit.h"
#include "RlSetup.h"
bool init_unit_test()
{
SgInit();
GoInit();
GoBoard bd(9);
RlSetup* setup = new RlSetup(bd);
setup->SetDebugLevel(RlSetup::VERBOSE);
return true;
}
int main(int argc, char* argv[])
{
return boost::unit_test::unit_test_main(&init_unit_test, argc, argv);
}
| gpl-3.0 |
softwareanimal/TextSecure-WinterBreak2015 | src/org/thoughtcrime/securesms/database/MmsSmsColumns.java | 10838 | package org.thoughtcrime.securesms.database;
public interface MmsSmsColumns {
public static final String ID = "_id";
public static final String NORMALIZED_DATE_SENT = "date_sent";
public static final String NORMALIZED_DATE_RECEIVED = "date_received";
public static final String THREAD_ID = "thread_id";
public static final String READ = "read";
public static final String BODY = "body";
public static final String ADDRESS = "address";
public static final String ADDRESS_DEVICE_ID = "address_device_id";
public static final String RECEIPT_COUNT = "delivery_receipt_count";
public static class Types {
protected static final long TOTAL_MASK = 0xFFFFFFFF;
// Base Types
protected static final long BASE_TYPE_MASK = 0x1F;
protected static final long BASE_INBOX_TYPE = 20;
protected static final long BASE_OUTBOX_TYPE = 21;
protected static final long BASE_SENDING_TYPE = 22;
protected static final long BASE_SENT_TYPE = 23;
protected static final long BASE_SENT_FAILED_TYPE = 24;
protected static final long BASE_PENDING_SECURE_SMS_FALLBACK = 25;
protected static final long BASE_PENDING_INSECURE_SMS_FALLBACK = 26;
public static final long BASE_DRAFT_TYPE = 27;
protected static final long[] OUTGOING_MESSAGE_TYPES = {BASE_OUTBOX_TYPE, BASE_SENT_TYPE,
BASE_SENDING_TYPE, BASE_SENT_FAILED_TYPE,
BASE_PENDING_SECURE_SMS_FALLBACK,
BASE_PENDING_INSECURE_SMS_FALLBACK};
// Message attributes
protected static final long MESSAGE_ATTRIBUTE_MASK = 0xE0;
protected static final long MESSAGE_FORCE_SMS_BIT = 0x40;
// Key Exchange Information
protected static final long KEY_EXCHANGE_BIT = 0x8000;
protected static final long KEY_EXCHANGE_STALE_BIT = 0x4000;
protected static final long KEY_EXCHANGE_PROCESSED_BIT = 0x2000;
protected static final long KEY_EXCHANGE_CORRUPTED_BIT = 0x1000;
protected static final long KEY_EXCHANGE_INVALID_VERSION_BIT = 0x800;
protected static final long KEY_EXCHANGE_BUNDLE_BIT = 0x400;
protected static final long KEY_EXCHANGE_IDENTITY_UPDATE_BIT = 0x200;
// Secure Message Information
protected static final long SECURE_MESSAGE_BIT = 0x800000;
protected static final long END_SESSION_BIT = 0x400000;
protected static final long PUSH_MESSAGE_BIT = 0x200000;
// Group Message Information
protected static final long GROUP_UPDATE_BIT = 0x10000;
protected static final long GROUP_QUIT_BIT = 0x20000;
// Encrypted Storage Information
protected static final long ENCRYPTION_MASK = 0xFF000000;
protected static final long ENCRYPTION_SYMMETRIC_BIT = 0x80000000;
protected static final long ENCRYPTION_ASYMMETRIC_BIT = 0x40000000;
protected static final long ENCRYPTION_REMOTE_BIT = 0x20000000;
protected static final long ENCRYPTION_REMOTE_FAILED_BIT = 0x10000000;
protected static final long ENCRYPTION_REMOTE_NO_SESSION_BIT = 0x08000000;
protected static final long ENCRYPTION_REMOTE_DUPLICATE_BIT = 0x04000000;
protected static final long ENCRYPTION_REMOTE_LEGACY_BIT = 0x02000000;
public static boolean isDraftMessageType(long type) {
return (type & BASE_TYPE_MASK) == BASE_DRAFT_TYPE;
}
public static boolean isFailedMessageType(long type) {
return (type & BASE_TYPE_MASK) == BASE_SENT_FAILED_TYPE;
}
public static boolean isOutgoingMessageType(long type) {
for (long outgoingType : OUTGOING_MESSAGE_TYPES) {
if ((type & BASE_TYPE_MASK) == outgoingType)
return true;
}
return false;
}
public static boolean isForcedSms(long type) {
return (type & MESSAGE_FORCE_SMS_BIT) != 0;
}
public static boolean isPendingMessageType(long type) {
return
(type & BASE_TYPE_MASK) == BASE_OUTBOX_TYPE ||
(type & BASE_TYPE_MASK) == BASE_SENDING_TYPE;
}
public static boolean isPendingSmsFallbackType(long type) {
return (type & BASE_TYPE_MASK) == BASE_PENDING_INSECURE_SMS_FALLBACK ||
(type & BASE_TYPE_MASK) == BASE_PENDING_SECURE_SMS_FALLBACK;
}
public static boolean isPendingSecureSmsFallbackType(long type) {
return (type & BASE_TYPE_MASK) == BASE_PENDING_SECURE_SMS_FALLBACK;
}
public static boolean isPendingInsecureSmsFallbackType(long type) {
return (type & BASE_TYPE_MASK) == BASE_PENDING_INSECURE_SMS_FALLBACK;
}
public static boolean isInboxType(long type) {
return (type & BASE_TYPE_MASK) == BASE_INBOX_TYPE;
}
public static boolean isSecureType(long type) {
return (type & SECURE_MESSAGE_BIT) != 0;
}
public static boolean isPushType(long type) {
return (type & PUSH_MESSAGE_BIT) != 0;
}
public static boolean isEndSessionType(long type) {
return (type & END_SESSION_BIT) != 0;
}
public static boolean isKeyExchangeType(long type) {
return (type & KEY_EXCHANGE_BIT) != 0;
}
public static boolean isStaleKeyExchange(long type) {
return (type & KEY_EXCHANGE_STALE_BIT) != 0;
}
public static boolean isProcessedKeyExchange(long type) {
return (type & KEY_EXCHANGE_PROCESSED_BIT) != 0;
}
public static boolean isCorruptedKeyExchange(long type) {
return (type & KEY_EXCHANGE_CORRUPTED_BIT) != 0;
}
public static boolean isInvalidVersionKeyExchange(long type) {
return (type & KEY_EXCHANGE_INVALID_VERSION_BIT) != 0;
}
public static boolean isBundleKeyExchange(long type) {
return (type & KEY_EXCHANGE_BUNDLE_BIT) != 0;
}
public static boolean isIdentityUpdate(long type) {
return (type & KEY_EXCHANGE_IDENTITY_UPDATE_BIT) != 0;
}
public static boolean isGroupUpdate(long type) {
return (type & GROUP_UPDATE_BIT) != 0;
}
public static boolean isGroupQuit(long type) {
return (type & GROUP_QUIT_BIT) != 0;
}
public static boolean isSymmetricEncryption(long type) {
return (type & ENCRYPTION_SYMMETRIC_BIT) != 0;
}
public static boolean isAsymmetricEncryption(long type) {
return (type & ENCRYPTION_ASYMMETRIC_BIT) != 0;
}
public static boolean isFailedDecryptType(long type) {
return (type & ENCRYPTION_REMOTE_FAILED_BIT) != 0;
}
public static boolean isDuplicateMessageType(long type) {
return (type & ENCRYPTION_REMOTE_DUPLICATE_BIT) != 0;
}
public static boolean isDecryptInProgressType(long type) {
return
(type & ENCRYPTION_REMOTE_BIT) != 0 ||
(type & ENCRYPTION_ASYMMETRIC_BIT) != 0;
}
public static boolean isNoRemoteSessionType(long type) {
return (type & ENCRYPTION_REMOTE_NO_SESSION_BIT) != 0;
}
public static boolean isLegacyType(long type) {
return (type & ENCRYPTION_REMOTE_LEGACY_BIT) != 0;
}
public static long translateFromSystemBaseType(long theirType) {
// public static final int NONE_TYPE = 0;
// public static final int INBOX_TYPE = 1;
// public static final int SENT_TYPE = 2;
// public static final int SENT_PENDING = 4;
// public static final int FAILED_TYPE = 5;
switch ((int)theirType) {
case 1: return BASE_INBOX_TYPE;
case 2: return BASE_SENT_TYPE;
case 3: return BASE_DRAFT_TYPE;
case 4: return BASE_OUTBOX_TYPE;
case 5: return BASE_SENT_FAILED_TYPE;
case 6: return BASE_OUTBOX_TYPE;
}
return BASE_INBOX_TYPE;
}
public static int translateToSystemBaseType(long type) {
if (isInboxType(type)) return 1;
else if (isOutgoingMessageType(type)) return 2;
else if (isFailedMessageType(type)) return 5;
return 1;
}
//
//
//
// public static final int NONE_TYPE = 0;
// public static final int INBOX_TYPE = 1;
// public static final int SENT_TYPE = 2;
// public static final int SENT_PENDING = 4;
// public static final int FAILED_TYPE = 5;
//
// public static final int OUTBOX_TYPE = 43; // Messages are stored local encrypted and need delivery.
//
//
// public static final int ENCRYPTING_TYPE = 42; // Messages are stored local encrypted and need async encryption and delivery.
// public static final int SECURE_SENT_TYPE = 44; // Messages were sent with async encryption.
// public static final int SECURE_RECEIVED_TYPE = 45; // Messages were received with async decryption.
// public static final int FAILED_DECRYPT_TYPE = 46; // Messages were received with async encryption and failed to decrypt.
// public static final int DECRYPTING_TYPE = 47; // Messages are in the process of being asymmetricaly decrypted.
// public static final int NO_SESSION_TYPE = 48; // Messages were received with async encryption but there is no session yet.
//
// public static final int OUTGOING_KEY_EXCHANGE_TYPE = 49;
// public static final int INCOMING_KEY_EXCHANGE_TYPE = 50;
// public static final int STALE_KEY_EXCHANGE_TYPE = 51;
// public static final int PROCESSED_KEY_EXCHANGE_TYPE = 52;
//
// public static final int[] OUTGOING_MESSAGE_TYPES = {SENT_TYPE, SENT_PENDING, ENCRYPTING_TYPE,
// OUTBOX_TYPE, SECURE_SENT_TYPE,
// FAILED_TYPE, OUTGOING_KEY_EXCHANGE_TYPE};
//
// public static boolean isFailedMessageType(long type) {
// return type == FAILED_TYPE;
// }
//
// public static boolean isOutgoingMessageType(long type) {
// for (int outgoingType : OUTGOING_MESSAGE_TYPES) {
// if (type == outgoingType)
// return true;
// }
//
// return false;
// }
//
// public static boolean isPendingMessageType(long type) {
// return type == SENT_PENDING || type == ENCRYPTING_TYPE || type == OUTBOX_TYPE;
// }
//
// public static boolean isSecureType(long type) {
// return
// type == SECURE_SENT_TYPE || type == ENCRYPTING_TYPE ||
// type == SECURE_RECEIVED_TYPE || type == DECRYPTING_TYPE;
// }
//
// public static boolean isKeyExchangeType(long type) {
// return type == OUTGOING_KEY_EXCHANGE_TYPE || type == INCOMING_KEY_EXCHANGE_TYPE;
// }
}
}
| gpl-3.0 |
e-biz/arpi-gl | android/arpigl/src/main/java/mobi/designmyapp/arpigl/event/TileEvent.java | 906 | /*
* Copyright (C) 2015 eBusiness Information
* 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 mobi.designmyapp.arpigl.event;
import mobi.designmyapp.arpigl.model.Tile;
public class TileEvent {
public final Tile tile;
public TileEvent(Tile tile) {
this.tile = tile;
}
}
| gpl-3.0 |
m3ccanico/ti | threat_intelligence/threat_crowd.py | 6796 | import time
import os
import json
import requests
import logging
import threat_intelligence
from helper import Helper
class ThreatCrowd(threat_intelligence.ThreatIntelligence):
def __init__(self, arguments):
self.ts_file = os.path.join('.cache', 'threatcrowd')
# check if caching file exists
if os.path.isfile(self.ts_file):
# read file
file = open(self.ts_file, 'r')
self.ts = file.read().strip()
file.close
# check ts
try:
self.ts = float(self.ts)
except ValueError:
self.ts = time.time()
else:
# create cache dir if it does not exists yet
if not os.path.isdir('.cache'):
os.makedirs('.cache')
# creat ts file with current timestamp
self.ts = time.time()
file = open(self.ts_file, 'w')
file.write(self.ts)
file.close
#self.vt = threat_crowd.ThreatCrowd(configuration['key'])
#self.key = configuration['key']
def header(self, additional=''):
if additional:
print "-\nThreatCrowd (%s)" % additional
else:
print "-\nThreatCrowd"
def ip(self, ip):
self.check_timeout()
url = 'https://www.threatcrowd.org/searchApi/v2/ip/report/'
parameters = {'ip': ip}
response = requests.get(url, params=parameters)
response_dict = json.loads(response.text)
#Helper.prettyprint(response_dict)
if int(response_dict['response_code']) == 1:
self.header(response_dict['permalink'])
if 'resolutions' in response_dict:
print "\t%i domains resolve to this ip" % len(response_dict['resolutions'])
if 'hashes' in response_dict:
print "\t%i malicious files referring to this IP address" % len(response_dict['hashes'])
if 'references' in response_dict:
print "\t%i references for this IP address" % len(response_dict['references'])
else:
logging.error("unknown response code: >%s<" % response_dict['response_code'])
self.update_ts()
def domain(self, domain):
self.check_timeout()
url = 'https://www.threatcrowd.org/searchApi/v2/domain/report/'
parameters = {'domain': domain}
response = requests.get(url, params=parameters)
response_dict = json.loads(response.text)
#Helper.prettyprint(response_dict)
if int(response_dict['response_code']) == 1:
self.header(response_dict['permalink'])
#print "\tCategories: %s" % ', '.join(response_dict['categories'])
ips = (resolution['ip_address'] for resolution in response_dict['resolutions'])
print "\tResolved IPs: %s" % ', '.join(ips)
if 'hashes' in response_dict:
print "\t%i hashes linked to this domain" % len(response_dict['hashes'])
if 'emails' in response_dict:
print "\t%i emails linked to this domain" % len(response_dict['emails'])
if 'subdomains' in response_dict:
print "\t%i subdomains linked this domain" % len(response_dict['subdomains'])
if 'references' in response_dict:
print "\t%i references for this domain" % len(response_dict['references'])
elif int(response_dict['response_code']) == 0:
print "\t%s" % response_dict['verbose_msg']
else:
logging.error("unknown response code: %s" % response_dict['response_code'])
self.update_ts()
def hash(self, hash):
self.check_timeout()
url = 'https://www.threatcrowd.org/searchApi/v2/file/report/'
parameters = {'resource': hash}
response = requests.get(url, params=parameters)
response_dict = json.loads(response.text)
#Helper.prettyprint(response_dict)
if int(response_dict['response_code']) == 1:
self.header(response_dict['permalink'])
if 'md5' in response_dict:
print "\tMD5: %s" % response_dict['md5']
if 'sha1' in response_dict:
print "\tSHA1: %s" % response_dict['sha1']
if 'scans' in response_dict:
print "\tConsidered malicious by %s scanners" % len(response_dict['scans'])
if 'ips' in response_dict:
print "\t%i IPs linked this hash" % len(response_dict['ips'])
if 'domains' in response_dict:
print "\t%i domains linked this hash" % len(response_dict['domains'])
if 'references' in response_dict:
print "\t%i references for this hash" % len(response_dict['references'])
elif int(response_dict['response_code']) == 0:
print "\tunknown hash"
else:
logging.error("unknown response code: %s" % response_dict['response_code'])
self.update_ts()
def email(self, email):
self.check_timeout()
url = 'https://www.threatcrowd.org/searchApi/v2/email/report/'
parameters = {'email': email}
response = requests.get(url, params=parameters)
response_dict = json.loads(response.text)
#Helper.prettyprint(response_dict)
if int(response_dict['response_code']) == 1:
self.header(response_dict['permalink'])
#if 'ips' in response_dict: print "\t%i IPs linked this hash" % len(response_dict['ips'])
if 'domains' in response_dict:
print "\t%i domains linked this email" % len(response_dict['domains'])
if 'references' in response_dict:
print "\t%i references for this email" % len(response_dict['references'])
elif int(response_dict['response_code']) == 0:
print "\tunknown email"
else:
logging.error("unknown response code: %s" % response_dict['response_code'])
self.update_ts()
def update_ts(self):
# create cache dir if it does not exists yet
if not os.path.isdir('.cache'):
os.makedirs('.cache')
# creat ts file with current timestamp
self.ts = time.time()
file = open(self.ts_file, 'w')
file.write(str(self.ts))
file.close
#print "updated ts"
def check_timeout(self):
delta = time.time() - self.ts
if delta < 10:
#print "sleep:", str(15-delta)
logging.debug('wait %d seconds for timeout' % (10-delta))
time.sleep(10-delta)
| gpl-3.0 |
kaanburaksener/octoBubbles | src/com/kaanburaksener/octoUML/src/controller/SelectController.java | 8403 | package com.kaanburaksener.octoUML.src.controller;
import com.kaanburaksener.octoUML.src.controller.AbstractDiagramController.Mode;
import com.kaanburaksener.octoUML.src.controller.AbstractDiagramController.ToolEnum;
import com.kaanburaksener.octoUML.src.model.Sketch;
import com.kaanburaksener.octoUML.src.model.edges.MessageEdge;
import com.kaanburaksener.octoUML.src.view.edges.AbstractEdgeView;
import com.kaanburaksener.octoUML.src.view.edges.MessageEdgeView;
import com.kaanburaksener.octoUML.src.view.nodes.AbstractNodeView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
/**
* Used by MainController for handling when a user tries to select elements in the graph.
*/
//TODO Refactor code from MainController here.
public class SelectController {
//For drag-selecting nodes
double selectStartX, selectStartY;
Rectangle selectRectangle;
private Pane aDrawPane;
private AbstractDiagramController diagramController;
public SelectController(Pane pDrawPane, AbstractDiagramController diagramController){
aDrawPane = pDrawPane;
this.diagramController = diagramController;
//init selectRectangle
selectRectangle = new Rectangle();
selectRectangle.setFill(null);
selectRectangle.setStroke(Color.BLACK);
selectRectangle.getStrokeDashArray().addAll(4.0,5.0,4.0,5.0);
}
public void onMousePressed(MouseEvent event){
if (diagramController.getTool() == AbstractDiagramController.ToolEnum.EDGE)
{
for(AbstractEdgeView edgeView : diagramController.allEdgeViews){
if (!(edgeView instanceof MessageEdgeView) && (distanceToLine(edgeView.getStartLine(), event.getX(), event.getY()) < 15 ||
distanceToLine(edgeView.getMiddleLine(), event.getX(), event.getY()) < 15 ||
distanceToLine(edgeView.getStartLine(), event.getX(), event.getY()) < 15)){
diagramController.selectedEdges.add(edgeView);
if(event.getClickCount() > 1){
diagramController.edgeController.showEdgeEditDialog(edgeView.getRefEdge());
diagramController.setTool(ToolEnum.SELECT);
diagramController.setButtonClicked(diagramController.selectBtn);
}
} else if((edgeView instanceof MessageEdgeView) && distanceToLine(edgeView.getStartLine(), event.getX(), event.getY()) < 15){
diagramController.selectedEdges.add(edgeView);
if(event.getClickCount() > 1){
diagramController.edgeController.showMessageEditDialog((MessageEdge)edgeView.getRefEdge());
diagramController.setTool(ToolEnum.SELECT);
diagramController.setButtonClicked(diagramController.selectBtn);
}
}
}
}
else if (diagramController.getTool() == ToolEnum.SELECT)
{
for(AbstractEdgeView edgeView : diagramController.allEdgeViews){
if (!(edgeView instanceof MessageEdgeView) && (distanceToLine(edgeView.getStartLine(), event.getX(), event.getY()) < 15 ||
distanceToLine(edgeView.getMiddleLine(), event.getX(), event.getY()) < 15 ||
distanceToLine(edgeView.getStartLine(), event.getX(), event.getY()) < 15)){
if(!diagramController.selectedEdges.contains(edgeView)){
diagramController.selectedEdges.add(edgeView);
}
if(event.getClickCount() > 1){
diagramController.edgeController.showEdgeEditDialog(edgeView.getRefEdge());
diagramController.setTool(ToolEnum.SELECT);
diagramController.setButtonClicked(diagramController.selectBtn);
}
} else if((edgeView instanceof MessageEdgeView) && distanceToLine(edgeView.getStartLine(), event.getX(), event.getY()) < 15){
if(!diagramController.selectedEdges.contains(edgeView)){
diagramController.selectedEdges.add(edgeView);
}
if(event.getClickCount() > 1){
diagramController.edgeController.showMessageEditDialog((MessageEdge)edgeView.getRefEdge());
diagramController.setTool(ToolEnum.SELECT);
diagramController.setButtonClicked(diagramController.selectBtn);
} else {
diagramController.setTool(ToolEnum.SELECT);
diagramController.setButtonClicked(diagramController.selectBtn);
diagramController.edgeController.onMousePressDragEdge(event);
}
diagramController.drawSelected();
}
}
if(diagramController.mode != Mode.DRAGGING_EDGE){
diagramController.setMode(Mode.SELECTING);
//TODO This should not be needed, should be in nodeView.initActions().
for(AbstractNodeView nodeView : diagramController.allNodeViews){
if (nodeView.getBoundsInParent().contains(event.getX(), event.getY()))
{
diagramController.selectedNodes.add(nodeView);
}
}
selectStartX = event.getX();
selectStartY = event.getY();
selectRectangle.setX(event.getX());
selectRectangle.setY(event.getY());
if (!aDrawPane.getChildren().contains(selectRectangle)) {
aDrawPane.getChildren().add(selectRectangle);
}
}
}
}
void onMouseDragged(MouseEvent event){
selectRectangle.setX(Math.min(selectStartX, event.getX()));
selectRectangle.setY(Math.min(selectStartY, event.getY()));
selectRectangle.setWidth(Math.abs(selectStartX - event.getX()));
selectRectangle.setHeight(Math.abs(selectStartY - event.getY()));
selectRectangle.setHeight(Math.max(event.getY() - selectStartY, selectStartY - event.getY()));
}
void onMouseReleased(){
for(AbstractNodeView nodeView : diagramController.allNodeViews) {
if (selectRectangle.getBoundsInParent().contains(nodeView.getBoundsInParent()))
{
diagramController.selected = true;
diagramController.selectedNodes.add(nodeView);
}
}
for (Sketch sketch : diagramController.getGraphModel().getAllSketches()) {
if (selectRectangle.getBoundsInParent().intersects(sketch.getPath().getBoundsInParent())) {
diagramController.selected = true;
diagramController.selectedSketches.add(sketch);
}
}
//If no nodes were contained, remove all selections
if (!diagramController.selected) {
diagramController.selectedNodes.clear();
diagramController.selectedEdges.clear();
diagramController.selectedSketches.clear();
}
diagramController.drawSelected();
selectRectangle.setWidth(0);
selectRectangle.setHeight(0);
aDrawPane.getChildren().remove(selectRectangle);
diagramController.selected = false;
diagramController.setMode(Mode.NO_MODE);
}
//Code copied, sorry!
//Used to determine if a click on canvas is in within range of an edge
private double distanceToLine(Line l, double pointX, double pointY){
double y1 = l.getStartY();
double y2 = l.getEndY();
double x1 = l.getStartX();
double x2 = l.getEndX();
double px = x2-x1;
double py = y2-y1;
double something = px*px + py*py;
double u = ((pointX - x1) * px + (pointY - y1) * py) / something;
if (u > 1){
u = 1;
}
else if (u < 0){
u = 0;
}
double x = x1 + u * px;
double y = y1 + u * py;
double dx = x - pointX;
double dy = y - pointY;
double dist = Math.sqrt(dx*dx + dy*dy);
return dist;
}
}
| gpl-3.0 |
turlir/Ursmu | src/ru/ursmu/application/Activity/GendalfDialog.java | 1044 | package ru.ursmu.application.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import ru.ursmu.application.R;
public class GendalfDialog extends DialogFragment {
private UrsmuBuilding t;
public GendalfDialog(UrsmuBuilding s) {
t = s;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = inflater.inflate(R.layout.gendalf_dialog, null);
AudienceInfoView control = ((AudienceInfoView) view.findViewById(R.id.audience_control));
control.setAudienceText(t);
builder.setView(view);
builder.setPositiveButton(android.R.string.ok, null);
builder.setTitle("Аудитория " + t.getOriginal());
return builder.create();
}
}
| gpl-3.0 |
danielbonetto/twig_MVC | lang/nl/lesson.php | 40706 | <?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/>.
/**
* Strings for component 'lesson', language 'nl', branch 'MOODLE_22_STABLE'
*
* @package lesson
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['accesscontrol'] = 'Toegangscontrole';
$string['actionaftercorrectanswer'] = 'Actie na juist antwoord';
$string['actionaftercorrectanswer_help'] = 'Na een juist antwoord op een vraag zijn er 3 opties voor de volgende pagina:
* Normaal - Volgt het lesverloop
* Toon een ongeziene pagina - Toont een willekeurige pagina die nog niet eerder werd getoond, één enkele keer
* Toon een onbeantwoorde pagina - Toont een willekeurige pagina die nog niet eerder werd beantwoord, hoewel misschien eerder getoond';
$string['actions'] = 'Acties';
$string['activitylink'] = 'Link naar een activiteit';
$string['activitylink_help'] = 'In dit rolmenu zitten alle activiteiten van deze cursus. Als er één van geselecteerd wordt, dan zal er aan het eind van de les een link verschijnen naar die activiteit.';
$string['activitylinkname'] = 'Ga naar {$a}';
$string['addabranchtable'] = 'Voeg een pagina toe';
$string['addanendofbranch'] = 'Voeg het einde van een tak toe';
$string['addanewpage'] = 'Voeg een nieuwe pagina toe';
$string['addaquestionpage'] = 'Voeg een vragenpagina toe';
$string['addaquestionpagehere'] = 'Voeg hier een vragenpagina toe';
$string['addbranchtable'] = 'Voeg een inhoudspagina toe';
$string['addcluster'] = 'Voeg een cluster toe';
$string['addedabranchtable'] = 'Inhoudspagina toegevoegd';
$string['addedanendofbranch'] = 'Einde van een tak toegevoegd';
$string['addedaquestionpage'] = 'Vragenpagina toegevoegd';
$string['addedcluster'] = 'Cluster toegevoegd';
$string['addedendofcluster'] = 'Einde van een cluster toegevoegd';
$string['addendofcluster'] = 'Voeg het einde van een cluster toe';
$string['addpage'] = 'Pagina toevoegen';
$string['anchortitle'] = 'Begin van de hoofdinhoud';
$string['and'] = 'EN';
$string['answer'] = 'Antwoord';
$string['answeredcorrectly'] = 'juist geantwoord.';
$string['answersfornumerical'] = 'Antwoorden voor numerieke vragen moeten koppels zijn van de minimum- en de maximumwaarde';
$string['arrangebuttonshorizontally'] = 'Inhoudsknoppen horizontaal schikken?';
$string['attempt'] = 'Poging: {$a}';
$string['attempts'] = 'Pogingen';
$string['attemptsdeleted'] = 'Verwijderde pogingen';
$string['attemptsremaining'] = 'Je kan nog {$a} poging(en) doen';
$string['available'] = 'Beschikbaar vanaf';
$string['averagescore'] = 'Gemiddelde score';
$string['averagetime'] = 'Gemiddelde tijd';
$string['branch'] = 'Inhoud';
$string['branchtable'] = 'Inhoud';
$string['cancel'] = 'Annuleer';
$string['cannotfindanswer'] = 'Fout: kon antwoord niet vinden';
$string['cannotfindattempt'] = 'Fout: kon poging niet vinden';
$string['cannotfindessay'] = 'Fout: kon open vraag niet vinden';
$string['cannotfindfirstgrade'] = 'Fout: kon cijfers niet vinden';
$string['cannotfindfirstpage'] = 'Kon eerste pagina niet vinden';
$string['cannotfindgrade'] = 'Fout: kon cijfers niet vinden';
$string['cannotfindnewestgrade'] = 'Fout: kon nieuwste cijfer niet vinden';
$string['cannotfindnextpage'] = 'Les backup: volgende pagina niet gevonden';
$string['cannotfindpagerecord'] = 'Pagina-record aan het einde van de vertakking niet gevonden';
$string['cannotfindpages'] = 'Kon lespagina\'s niet vinden';
$string['cannotfindpagetitle'] = 'Bevesting verwijderen: paginatitel niet gevonden';
$string['cannotfindpreattempt'] = 'Record van vorige poging niet gevondden!';
$string['cannotfindrecords'] = 'Fout: kon records van les niet vinden';
$string['cannotfindtimer'] = 'Fout: kon records van lestimer niet vinden';
$string['cannotfinduser'] = 'Fout: kon geen gebruikers vinden';
$string['canretake'] = '{$a} mag de les opnieuw doen';
$string['casesensitive'] = 'Regular expressions gebruiken';
$string['casesensitive_help'] = 'Enkele vraagtypes hebben een optie die ingeschakeld kan worden door deze checkbox aan te vinken. De vraagtypes en de bedoeling van de opties worden hier in detail overlopen.
1.**Meerkeuzevragen** Er is een variant op de meerkeuzevragen die
**"Meerkeuzevraag met meerdere antwoorden"** genoemd wordt. Als de vraagoptie aangevinkt is, dan wordt de leerling verwacht alle juiste opties te selecteren uit de aangeboden set antwoorden. In de vraag kun je al dan niet aangeven \*hoeveel\* antwoorden uit de set juist zijn. Bijvoorbeeld: "Welke van de volgende personen waren Amerikaanse presidenten?" tegenover "Kies de twee Amerikaanse presidenten uit de onderstaande lijst.". Het aantal juiste antwoorden kan van **één** tot een willekeurig aantal zijn. (Meerkeuzevragen met de mogelijkheid om meerdere antwoorden te kiezen en waar maar één antwoord juist is, dat kan ook: het geeft de leerling de mogelijkheid meerdere antwoorden aan te duiden, terwijl een gewone meerkeuzevraag die mogelijkheid niet geeft.)
2.**Kort antwoord** Standaard is hoofdlettergevoeligheid uitgeschakeld. Als de vraagoptie is aangevinkt, dan wordt er bij de verbetering met hoofdletters rekening gehouden.
De andere vraagtypes gebruiken de vraagopties niet.';
$string['checkbranchtable'] = 'Controleer inhoudspagina';
$string['checkedthisone'] = 'Deze is gecontroleerd';
$string['checknavigation'] = 'Controleer de navigatie';
$string['checkquestion'] = 'Controleer de vraag';
$string['classstats'] = 'Statistieken van de klas';
$string['clicktodownload'] = 'Klik op de link om het bestand te downloaden';
$string['clicktopost'] = 'Klik hier om je cijfer op de scorelijst te zetten';
$string['cluster'] = 'Cluster';
$string['clusterjump'] = 'Ongeziene vraag binnen een cluster';
$string['clustertitle'] = 'Cluster';
$string['collapsed'] = 'Samengeplooid';
$string['comments'] = 'Jouw commentaar';
$string['completed'] = 'Voltooid';
$string['completederror'] = 'Werk de les af';
$string['completethefollowingconditions'] = 'Je moet volgende voorwaarde(n) voltooien in les <b>{$a}</b> voor je verder kan gaan.';
$string['conditionsfordependency'] = 'Voorwaarde(n) voor deeltaak';
$string['configactionaftercorrectanswer'] = 'De standaardactie na een juist antwoord';
$string['configmaxanswers'] = 'Standaard maximum aantal antwoorden per pagina';
$string['configmaxhighscores'] = 'Te tonen aantal hoogste scores';
$string['configmediaclose'] = 'Toont een sluit-knop als deel van de popup waarin het gelinkte mediabestand getoond wordt';
$string['configmediaheight'] = 'Instelling voor de hoogte van de popup voor het gelinkte mediabestand';
$string['configmediawidth'] = 'Instelling voor de breedte van de popup voor het gelinkte mediabestand';
$string['configslideshowbgcolor'] = 'Achtergrondkleur voor de diashow als die is ingeschakeld';
$string['configslideshowheight'] = 'Instelling voor de hoogte van de diashow als die is ingeschakeld';
$string['configslideshowwidth'] = 'Instelling voor de breedte van de diashow als die is ingeschakeld';
$string['confirmdelete'] = 'Verwijder pagina';
$string['confirmdeletionofthispage'] = 'Bevestig het verwijderen van deze pagina';
$string['congratulations'] = 'Proficiat - je hebt het einde van de les bereikt';
$string['continue'] = 'Ga verder';
$string['continuetoanswer'] = 'Ga verder met het wijzigen van de antwoorden';
$string['continuetonextpage'] = 'Ga naar volgende pagina';
$string['correctanswerjump'] = 'Sprong bij juist antwoord';
$string['correctanswerscore'] = 'Cijfer bij juist antwoord';
$string['correctresponse'] = 'Juist antwoord';
$string['credit'] = 'Krediet';
$string['customscoring'] = 'Aangepaste cijfers';
$string['customscoring_help'] = 'Hiermee kun je een numerieke puntenwaarde geven voor elk antwoord. Antwoorden kunnen een negatief of een positief cijfer krijgen. Geïmporteerde vragen zullen automatisch 1 punt voor een juist en 0 punten voor een fout antwoord krijgen. Je kunt dit wijzigen na het importeren.';
$string['deadline'] = 'Deadline';
$string['defaultessayresponse'] = 'Je antwoord op deze open vraag zal door de leraar beoordeeld worden.';
$string['deleteallattempts'] = 'Verwijder alle pogingen';
$string['deletedefaults'] = 'Standaard les {$a} verwijderd';
$string['deletedpage'] = 'Pagina verwijderd';
$string['deleting'] = 'Verwijderen';
$string['deletingpage'] = 'Bezig met pagina {$a} verwijderen';
$string['dependencyon'] = 'Deeltaak van';
$string['dependencyon_help'] = 'Met deze instelling kun je de toegang tot deze les afhankelijk maken van de score van een student voor een andere les in dezelfde cursus. Elke combinatie van gespendeerde tijd, voltooid, of "cijfer hoger dan" kunnen worden gebruikt.';
$string['description'] = 'Beschrijving';
$string['detailedstats'] = 'Gedetailleerde statistieken';
$string['didnotanswerquestion'] = 'Deze vraag niet beantwoord';
$string['didnotreceivecredit'] = 'Geen cijfers gekregen';
$string['displaydefaultfeedback'] = 'Toon standaard feedback';
$string['displaydefaultfeedback_help'] = '**Toon standaardfeedback**
Als deze instelling op **ja** gezet wordt, dan zal bij het ontbreken van feedback, de standaardfeedback "Juist antwoord" en "Fout antwoord" gebruikt worden.
Als deze instelling op **Nee** gezet wordt, dan zal er bij het ontbreken van feedback niets getoond worden. De gebruiker wordt dan automatisch naar de volgende pagina van de les gebracht worden.';
$string['displayhighscores'] = 'Toon hoogste cijfers';
$string['displayinleftmenu'] = 'Toon in linkermenu?';
$string['displayleftif'] = 'Toon linkermenu enkel als cijfer het groter is dan';
$string['displayleftif_help'] = 'Deze instelling bepaalt of een leerling een bepaald cijfer moet halen voor die het linker menu kan zien. Dit verplicht een leerling om door de hele les te gaan tijdens de eerste poging, dan kan die na het behalen van het vereiste cijfer, het linker menu gebruiken om na te kijken.';
$string['displayleftmenu'] = 'Toon linkermenu';
$string['displayleftmenu_help'] = 'Indien ingeschakeld, wordt een lijst van pagina\'s getoond.';
$string['displayofgrade'] = 'Tonen van het cijfer (voor de leerling)';
$string['displayreview'] = 'Geef de optie om een vraag opnieuw te proberen';
$string['displayreview_help'] = 'Indien ingeschakeld, zal bij een fout antwoord de student de optie krijgen om ofwel de vraag vrijblijvend opnieuw te proberen (zonder cijfer), ofwel verder te gaan met de les.';
$string['displayscorewithessays'] = 'Je hebt {$a->score} punten op {$a->tempmaxgrade} behaald voor de automatisch beoordeelde vragen.<br />Je {$a->essayquestions} open vragen zullen beoordeeld worden op een later moment<br />en toegevoegd worden bij je totaalcijfer.<br /><br />Je resultaat op dit ogenblik, zonder de open vragen is {$a->score} op {$a->grade}.';
$string['displayscorewithoutessays'] = 'Je cijfer is {$a->score} (op {$a->grade}).';
$string['edit'] = 'Bewerk';
$string['editingquestionpage'] = 'Bewerken {$a} vragenpagina';
$string['editlessonsettings'] = 'Bewerk de instellingen van deze les';
$string['editpage'] = 'Bewerk pagina inhoud';
$string['editpagecontent'] = 'Bewerk de inhoud van deze pagina';
$string['email'] = 'E-mail';
$string['emailallgradedessays'] = 'E-mail ALLE beoordeelde werken';
$string['emailgradedessays'] = 'E-mail de werken met een cijfer';
$string['emailsuccess'] = 'E-mails goed verzonden';
$string['emptypassword'] = 'Wachtwoord kan niet leeg zijn';
$string['endofbranch'] = 'Einde vertakking';
$string['endofcluster'] = 'Einde cluster';
$string['endofclustertitle'] = 'Einde van de cluster';
$string['endoflesson'] = 'Einde van de les';
$string['enteredthis'] = 'dit ingegeven.';
$string['entername'] = 'Geef een schuilnaam voor de lijst met hoogste scores';
$string['enterpassword'] = 'Geef het wachtwoord:';
$string['eolstudentoutoftime'] = 'Opgelet: je tijd voor deze les is helemaal op. Wanneer je laatste antwoord verstuurd is nadat de tijd op was, dan telt dat niet meer mee.';
$string['eolstudentoutoftimenoanswers'] = 'Je hebt geen enkele vraag beantwoord. Je hebt een 0 voor deze les';
$string['essay'] = 'Open vraag';
$string['essayemailmessage'] = '<p>Open vraag: <blockquote>{$a->question}</blockquote></p><p>Je antwoord: <blockquote><em>{$a->response}</em></blockquote></p><p>{$a->teacher}\'s comments:<blockquote><em>{$a->comment}</em></blockquote></p><p>Je hebt {$a->earned} punten gekregen op {$a->outof} voor deze open vraag.</p><p>Je cijfer voor deze les is gewijzigd naar {$a->newgrade}%.</p>';
$string['essayemailmessage2'] = '<p>Open vraag prompt:
<blockquote>{$a->question}</blockquote></p><p>Jouw antwoord:<blockquote><em>{$a->response}</em></blockquote></p><p>Commentaar van de beoordeler:<blockquote><em>{$a->comment}</em></blockquote></p><p>Je hebt {$a->earned} op {$a->outof} gekregen voor deze open vraag.</p><p>Je cijfer voor deze les is gewijzigd naar {$a->newgrade}%.</p>';
$string['essayemailsubject'] = 'Jouw cijfer voor {$a} vraag';
$string['essays'] = 'Open vragen';
$string['essayscore'] = 'Cijfer voor de open vragen';
$string['fileformat'] = 'Bestandsformaat';
$string['finish'] = 'Einde';
$string['firstanswershould'] = 'Het eerste antwoord moet naar de "juist"-pagina verwijzen';
$string['firstwrong'] = 'Jammer genoeg verdien je dit punt niet, omdat je antwoord fout was. Wil je alleen maar voor de pret van het leren nog eens gokken (maar zonder er punten mee te verdienen)?';
$string['flowcontrol'] = 'Controle van het verloop';
$string['full'] = 'Volledig';
$string['general'] = 'Algemeen';
$string['gotoendoflesson'] = 'Ga naar het einde van de les';
$string['grade'] = 'Cijfer';
$string['gradebetterthan'] = 'Cijfer beter dan (%)';
$string['gradebetterthanerror'] = 'Verdien een cijfer beter dan {$a} procent';
$string['gradeessay'] = 'Beoordeel open vragen';
$string['gradeis'] = 'Cijfer is {$a}';
$string['gradeoptions'] = 'Beoordelingsopties';
$string['handlingofretakes'] = 'Behandeling van nieuwe pogingen';
$string['handlingofretakes_help'] = 'Als leerlingen een les opnieuw mogen proberen, dan kan de leraar met deze instelling bepalen of voor het cijfer voor deze les het **gemiddelde** cijfer van alle pogingen gebruikt wordt of het **beste** cijfer van alle pogingen.
Deze instelling mag altijd veranderd worden.';
$string['havenotgradedyet'] = 'Nog geen cijfer gegeven';
$string['here'] = 'hier';
$string['highscore'] = 'Hoogste score';
$string['highscores'] = 'Hoogste scores';
$string['hightime'] = 'Langste duur';
$string['importcount'] = '{$a} vragen importeren';
$string['importppt'] = 'Importeer Powerpoint';
$string['importppt_help'] = 'HOE TE GEBRUIKEN
Alle PowerPointdia\'s worden geïmporteerd als vertakkingstabellen met Vorige en Volgende knoppen.
1.Open je PowerPoint presentatie.
2.Bewaar ze als Webpagina (geen speciale opties)
3.Het resultaat van stap 3 zou een htm bestand en een map met alle dia\'s, geconverteerd naar webpagina\'s.
ZET DE MAP ALEEN IN EEN ZIP-BESTAND.
4.Ga naar je Moodle-site en voeg een nieuwe les toe.
5.Na het bewaren van de instellingen van de les, zou je vier opties moeten zien onder "Wat wil je eerst doen?" Klik op "Importeer PowerPoint"
6.Gebruik de "Bladeren..."-knop om je zip-bestand uit stap 3 te zoeken. Klik dan op "Upload dit bestand"
7.Als alles werkte zoals het hoort, zou je volgende scherm alleen een ga verder-knop moeten tonen.
Als er afbeeldingen in je Powerpoint presentatie waren, dan zouden die bewaard moeten zij als cursusbestanden in moddata/XY waar X de naam van je les is en Y een getal is (gewoonlijk 0). Er worden tijdens het importeerproces nog meer bestanden gemaakt in de map temp/lesson. Deze bestanden worden tot nu toe nog niet verwijderd door importppt.php.
';
$string['importquestions'] = 'Importeer vragen';
$string['importquestions_help'] = 'Met deze functie kun je vragen importeren uit tekstbestanden op je eigen computer door ze te uploaden via een
formulier.
Een aantal bestandsformaten worden ondersteund:
**GIFT**
GIFT is het meest uitgebreide importformaat beschikbaar voor het importeren van Moodle-vragen vanuit een
tekstbestand. Het is ontworpen als gemakkelijke importeermethode voor Moodle-vragen vanuit tekstbestanden. Het ondersteunt
meerkeuzevragen, waar/onwaar, kort antwoord, koppelvragen en numerieke vragen, evenals het invoeren van een \_\_\_|\_\_\_|\_\_\_|\_ voor
het gatentekstformaat. Verschillende vragentypes kunnen gemixt worden in één tekstbestand en de opmaak ondersteunt ook
commentaar, vraagnamen, feedback en procentuele weging van cijfers. Hieronder enkele voorbeelden:
Wie is er begraven in de tombe van Grant?{~Grant ~Jefferson =niemand}
Grant is {~begraven =bijgezet ~levend} in Grants tombe.
Grant is begraven in Grants tombe.{FALSE}
Wie is begraven in Grants tombe?{=niemand =helemaal niemand}
Wanneer werd Ulysses S. Grant geboren?{#1822:1}
[Meer info over "GIFT"](help.php?file=formatgift.html&module=quiz)
**Aiken**
De Aiken bestandsopmaak is een heel eenvoudige manier om meerkeuzevragen te creëren door gebruik te maken van een
duidelijk, voor mensen leesbare opmaak. Hieronder een voorbeeld van de opmaak:
Wat is het doel van eerste hulp?
A. Levens redden, verdere kwetsuren voorkomen, goede gezondheid bewaren
B. Medicijnen toedienen aan een gekwetste of gewonde persoon
C. Verdere kwetsuren voorkomen
D. Slachtoffers die hulp zoeken helpen
ANSWER: A
[Meer info over "Aiken"](help.php?file=formataiken.html&module=quiz)
**Gatentekst**
Elk antwoord wordt gescheiden door een tilde (~). Het juiste antwoord wordt voorafgegaan door een gelijkheidsteken (=).
Tussen de vragen moet je één vrije regel laten.
Enkele voorbeelden:
Meerkeuzevragen
Zodra we als kind onze lichaamsdelen beginnen te verkennen, bestuderen we
{=anatomie ~wetenschappen ~reflexen ~experimenten} en in feite blijven we studenten voor de rest van onsleven.
[Meer info over "Gatentekst"](help.php?file=formatmissingword.html&module=quiz)
**AON**
Dit is hetzelfde als het \'Gatentekst\'-formaat, behalve dat alle \'korte antwoord\' vragen per vier geconverteerd worden in koppelvragen
Het formaat is genoemd naar een organisatie die de ontwikkeling van testen gesponsord heeft.
1 m is gelijk aan ...
{
=100 cm;
~1 cm;
~10 cm;
~1000 cm;
}
**Blackboard**
Met deze module kun je vragen importeren die in het exportformaat van Blackboard gemaakt zijn. Het steunt
op XML-functies die door PHP gecompileerd worden.
[Meer info over "Blackboard"-formaat](help.php?file=formatblackboard.html&module=quiz)
**WebCT**
Deze module kan vragen importeren vanuit het tekstgebaseerde vragenformaat van WebCT.
[Meer informatie over het "WebCT"-formaat](help.php?file=formatwebct.html&module=quiz)
**Course Test Manager**
Deze module kan vragen importeren die bewaard zijn in een Course Test Manager toetsenbank.
Het steunt op verschillende manieren om de testbank, die in een Microsoft Access databank zit, te koppelen.
De manier hangt ervan af of je Moodle-installatie op een Microsoft of op een Linux webserver loopt.
Op Windows laat het je gewoon je access databank uploaden zoals je gelijk welk ander gegevensbestand zou importeren.
Op Linux moet je eerst een windowsmachine installeren op hetzelfde netwerk als de Course Test
Manager databank en een stukje software installeren, nl de ODBC Socket Server, die XML gebruikt om data door te zenden
naar Moodle op de Linux server.
Lees best eerst de volledige documentatie voor je deze importfilter gebruikt.
[Meer info over het "CTM"-formaat](help.php?file=formatctm.html&module=quiz)
**Ingebedde antwoorden (Cloze)**
Met dit importformaat kun je slechts één soort vragen importeren: de ingebedde antwoorden (ook bekend als "cloze")
[Meer informatie over het "Cloze"-formaat](help.php?file=multianswer.html&module=quiz)
**Aangepast**
Als je je eigen opmaak hebt die geïmporteerd moet worden, dan kan je dit bouwen door mod/quiz/format/custom.php te bewerken.
De hoeveelheid nieuwe code die je moet maken is klein - juist genoeg om een stukje tekst om te zetten in een vraag.
[Meer info over het aangepast formaat](help.php?file=formatcustom.html&module=quiz)
Er zijn nog meer formaten in ontwikkeling, zoals WebCT, IMS, QTI en gelijk welk formaat dat uitgewerkt wordt door Moodle-gebruikers!';
$string['insertedpage'] = 'Pagina ingevoegd';
$string['invalidfile'] = 'Ingeldig bestand';
$string['invalidid'] = 'Geen cursusmodule ID of le ID is doorgegeven';
$string['invalidlessonid'] = 'Foute les ID';
$string['invalidpageid'] = 'Ongeldige pagina ID';
$string['jump'] = 'Spring';
$string['jumps'] = 'Verspringen';
$string['jumps_help'] = 'Elk antwoord (voor vragen) of beschrijving (voor inhoudelijke pagina\'s) heeft een bijhorende "ga naar"-link. De link kan relatief zijn, zoals \'deze pagina\', \'volgende pagina\' of absoluut, waarbij wordt verwezen naar een bepaalde, specifieke pagina in de les.';
$string['jumpsto'] = 'Verspringen naar <em>{$a}</em>';
$string['leftduringtimed'] = 'Je bent weggegaan tijdens een getimede les. <br />Klik op ga verder om de les te hervatten.';
$string['leftduringtimednoretake'] = 'Je bent weggegaan tijdens een getimede les. <br />Je mag niet verder werken.';
$string['lesson:edit'] = 'Bewerk een les';
$string['lesson:manage'] = 'Beheer een les';
$string['lessonattempted'] = 'Poging';
$string['lessonclosed'] = 'Deze les sluit op {$a}.';
$string['lessoncloses'] = 'Les sluit';
$string['lessoncloseson'] = 'Les sluit op {$a}';
$string['lessonformating'] = 'Opmaken van de les';
$string['lessonmenu'] = 'Lesmenu';
$string['lessonnotready'] = 'Deze les is nog niet klaar. Contacteer aub je {$a}';
$string['lessonnotready2'] = 'Deze les is niet klaar om te starten';
$string['lessonopen'] = 'Deze les zal openen op {$a}.';
$string['lessonopens'] = 'Les opent';
$string['lessonpagelinkingbroken'] = 'Eerste pagina niet gevonden. Waarschijnlijk is de link naar de lespagina gebroken. Contacteer een beheerder';
$string['lessonstats'] = 'Statistieken van de les';
$string['linkedmedia'] = 'Gelinkte media';
$string['loginfail'] = 'Login mislukt. Probeer nog eens...';
$string['lowscore'] = 'Laagste score';
$string['lowtime'] = 'kortste duur';
$string['manualgrading'] = 'Beoordeel open vragen';
$string['matchesanswer'] = 'Komt overeen met antwoord';
$string['matching'] = 'Koppelen';
$string['matchingpair'] = 'Gekoppeld paar {$a}';
$string['maxgrade'] = 'Maximum cijfer';
$string['maxgrade_help'] = 'Deze waarde bepaalt het maximumcijfer dat gegeven kan worden voor deze les. Het bereik is van 0 tot 100%. Deze waarde kan op elk moment gewijzigd worden. Elke wijziging heeft onmiddellijk effect op de overzichtstabel en op de cijfers die via verschillende lijsten aan de leerlingen getoond worden.';
$string['maxhighscores'] = 'Aantal getoonde hoogste cijfers';
$string['maximumnumberofanswersbranches'] = 'Maximumaantal antwoorden';
$string['maximumnumberofanswersbranches_help'] = 'Deze waarde bepaalt het maximum aantal antwoorden dat kan worden gebruikt in de les. Als de les enkel waar/onwaar-vragen gebruikt, dan kun je deze optie beter op 2 zetten.
De waarde kan op ieder moment worden gewijzigd; een nieuwe instelling heeft immers enkel effect op wat de leraar ziet, en niet op de data.';
$string['maximumnumberofattempts'] = 'Maximumaantal pogingen';
$string['maximumnumberofattempts_help'] = 'Deze waarde bepaalt het maximum aantal pogingen die een leerling krijgt om een vraag te beantwoorden. Indien het maximum wordt bereikt na telkens opnieuw een foutief antwoord, dan wordt de volgende pagina van de les getoond.';
$string['maximumnumberofattemptsreached'] = 'Maximum aantal pogingen bereikt - we gaan verder naar de volgende pagina.';
$string['maxtime'] = 'Tijdslimiet (minuten)';
$string['maxtimewarning'] = 'Je hebt {$a} minuten om de les af te werken.';
$string['mediaclose'] = 'Toon knop om te sluiten';
$string['mediafile'] = 'Mediabestand';
$string['mediafile_help'] = 'Hiermee zal een popup-venster gemaakt worden met een link naar een bestand (bijvoorbeeld een mp3-bestand) aan het begin van een les of op een webpagina. Er zal ook een link getoond worden op elke lespagina waarmee het popup-venster opnieuw kan geopend worden indien nodig.
Optioneel kan er een "Sluit venster" -knop gezet worden onderaan het popup-venster, de hoogte en breedte van het venster kan ook ingesteld worden.';
$string['mediafilepopup'] = 'Klik hier om te bekijken';
$string['mediaheight'] = 'Hoogte popup-venster:';
$string['mediawidth'] = 'Breedte popup-venster:';
$string['messageprovider:graded_essay'] = 'Melding beoordeling open vraag';
$string['minimumnumberofquestions'] = 'Minimumaantal vragen';
$string['minimumnumberofquestions_help'] = 'Deze instelling specifieert het minimum aantal vragen dat het mogelijk maakt om het cijfer voor de activiteit te berekenen. Indien de les een of meer inhoudspagina\'s bevat, dan moet de waarde worden ingesteld op nul.
Indien ingesteld op 20, bijvoorbeeld, dan voeg je best de volgende tekst toe in de openingspagina: "In deze les wordt van je verwacht dat je minstens 20 vragen beantwoordt. Je mag er meer beantwoorden als je wil, maar als je er minder maakt dan 20, dan zal je cijfer berekend worden alsof je er 20 gemaakt hebt."';
$string['missingname'] = 'Geef een schuilnaam';
$string['modattempts'] = 'Laat leerling nalezen';
$string['modattempts_help'] = 'Deze instelling zal leerlingen toelaten opnieuw door de les te navigeren en antwoorden te wijzigen.';
$string['modattemptsnoteacher'] = 'Nalezen werkt alleen voor leerlingen';
$string['modulename'] = 'Les';
$string['modulename_help'] = 'Een les biedt inhoud op een interessante en flexibele manier aan. Ze is opgebouwd uit een aantal pagina\'s. Elke pagina eindigt met een vraag en een aantal mogelijke antwoorden. Afhankelijk van de keuze van de leerling wordt hij naar de volgende pagina of opnieuw naar de vorige of naar nog een andere pagina gebracht. Navigatie door de les kan lineair of complex zijn, grotendeels afhankelijk van de structuur van het aangeboden materiaal.';
$string['modulenameplural'] = 'Lessen';
$string['move'] = 'Verplaats pagina';
$string['movedpage'] = 'Pagina verplaatst';
$string['movepagehere'] = 'Verplaats de pagina naar hier';
$string['moving'] = 'Bezig met pagina {$a} verplaatsen';
$string['multianswer'] = 'Meer antwoorden';
$string['multianswer_help'] = 'Enkele vraagtypes hebben een optie die ingeschakeld kan worden door deze checkbox aan te vinken. De vraagtypes en de bedoeling van de opties worden hier in detail overlopen.
1.**Meerkeuzevragen** Er is een variant op de meerkeuzevragen die
**"Meerkeuzevraag met meerdere antwoorden"** genoemd wordt. Als de vraagoptie aangevinkt is, dan wordt de leerling verwacht alle juiste opties te selecteren uit de aangeboden set antwoorden. In de vraag kun je al dan niet aangeven \*hoeveel\* antwoorden uit de set juist zijn. Bijvoorbeeld: "Welke van de volgende personen waren Amerikaanse presidenten?" tegenover "Kies de twee Amerikaanse presidenten uit de onderstaande lijst.". Het aantal juiste antwoorden kan van **één** tot een willekeurig aantal zijn. (Meerkeuzevragen met de mogelijkheid om meerdere antwoorden te kiezen en waar maar één antwoord juist is, dat kan ook: het geeft de leerling de mogelijkheid meerdere antwoorden aan te duiden, terwijl een gewone meerkeuzevraag die mogelijkheid niet geeft.)
2.**Kort antwoord** Standaard is hoofdlettergevoeligheid uitgeschakeld. Als de vraagoptie is aangevinkt, dan wordt er bij de verbetering met hoofdletters rekening gehouden.
De andere vraagtypes gebruiken de vraagopties niet.';
$string['multichoice'] = 'Meerkeuze';
$string['multipleanswer'] = 'Meer antwoorden';
$string['nameapproved'] = 'Naam goedgekeurd';
$string['namereject'] = 'Je naam werd geweigerd. Probeer een andere naam.';
$string['new'] = 'nieuw';
$string['nextpage'] = 'Volgende pagina';
$string['noanswer'] = 'Er is niet geantwoord';
$string['noattemptrecordsfound'] = 'Geen pogingen gevonden: geen cijfer gegeven.';
$string['nobranchtablefound'] = 'Geen inhoudspagina gevonden';
$string['nocommentyet'] = 'Nog geen commentaar';
$string['nocoursemods'] = 'Geen activiteiten gevonden';
$string['nocredit'] = 'Geen krediet';
$string['nodeadline'] = 'Geen deadline';
$string['noessayquestionsfound'] = 'Er zijn geen open vragen gevonden in deze les';
$string['nohighscores'] = 'Geen hoogste cijfer';
$string['nolessonattempts'] = 'Niemand heeft deze les gemaakt.';
$string['nooneansweredcorrectly'] = 'Niemand heeft juist geantwoord';
$string['nooneansweredthisquestion'] = 'Niemand heeft deze vraag beantwoord';
$string['noonecheckedthis'] = 'Niemand heeft dit gecontroleerd';
$string['nooneenteredthis'] = 'Niemand heeft dit ingegeven';
$string['noonehasanswered'] = 'Niemand heeft een open vraag beantwoord';
$string['noretake'] = 'Je mag deze les niet opnieuw maken';
$string['normal'] = 'Normaal - volg het lespad';
$string['notcompleted'] = 'Nog niet voltooid';
$string['notdefined'] = 'Niet gedefinieerd';
$string['nothighscore'] = 'Je hebt de top {$a} cijferlijst niet gehaald.';
$string['notitle'] = 'Geen titel';
$string['numberofcorrectanswers'] = 'Aantal juiste antwoorden: {$a}';
$string['numberofcorrectmatches'] = 'Aantal juiste koppelingen: {$a}';
$string['numberofpagestoshow'] = 'Aantal te tonen pagina\'s';
$string['numberofpagestoshow_help'] = 'Deze pagina wordt alleen maar gebruikt in lessen met Flash Cards. De standaardwaarde is nul, wat betekent dat alle pagina\'s/Flash Cards in de les getoond worden. Door deze parameter op een andere waarde dan nul te zetten, worden slechts dat aantal pagina\'s getoond. Als dat aantal pagina\'s/Flash Cards getoond is, krijgt de leerling te zien dat het einde van de les bereikt is en wordt zijn cijfer getoond.
Als deze parameter op een getal groter dan het aantal pagina\'s in de les is ingesteld, dan wordt het einde van de les bereikt als alle pagina\'s getoond zijn.';
$string['numberofpagesviewed'] = 'Aantal beantwoorde vragen: {$a}';
$string['numberofpagesviewednotice'] = 'Aantal beantwoorde vragen: {$a->nquestions}; (minimum aantal antwoorden: {$a->minquestions})';
$string['numerical'] = 'Numeriek';
$string['ongoing'] = 'Toon het huidige cijfer';
$string['ongoing_help'] = 'Met dit ingeschakeld zal elke pagina het cijfer dat de leerling tot nu toe behaald heeft op het tot nu toe te halen maximum weergeven. Bijvoorbeeld: een leerling heeft 4 vragen op 5 punten beantwoord en heeft er één fout. Het cijfer tot nu toe zou op het scherm tonen dat de leerling 15/20 punten verdient heeft.';
$string['ongoingcustom'] = 'Dit is een les op {$a->score} punten. Je hebt nu al {$a->score} punten verdiend van de {$a->currenthigh} punten die er tot nu toe te verdienen waren.';
$string['ongoingnormal'] = 'Je hebt {$a->correct} vragen van de {$a->viewed} juist beantwoord.';
$string['onpostperpage'] = 'Slechts één bericht per cijfer';
$string['options'] = 'Opties';
$string['or'] = 'OF';
$string['ordered'] = 'Gesorteerd';
$string['other'] = 'Andere';
$string['outof'] = 'Van {$a}';
$string['overview'] = 'Overzicht';
$string['overview_help'] = 'Een les is opgebouwd uit een aantal pagina\'s en optioneel een aantal inhoudspagina\'s. Een pagina bevat een zekere inhoud en eindigt gewoonlijk met een vraag.
Aan elk antwoord op de vraag is een sprong verbonden. De sprong kan relatief zijn, zoals deze pagina of volgende pagina, of absoluut verwijzen naar om het even welke pagina in de les. Een inhoudspagina is een pagina die een reeks links naar andere pagina\'s in de les bevat, zoals bijvoorbeeld een inhoudstafel.';
$string['page'] = 'Pagina: {$a}';
$string['page-mod-lesson-edit'] = 'Bewerk lespagina';
$string['page-mod-lesson-view'] = 'Bekijk of bekijk voorbeeld van lespagina';
$string['page-mod-lesson-x'] = 'Elke lespagina';
$string['pagecontents'] = 'Inhoud van de pagina';
$string['pages'] = 'Pagina\'s';
$string['pagetitle'] = 'Titel van de pagina';
$string['password'] = 'Wachtwoord';
$string['passwordprotectedlesson'] = '{$a} is met een wachtwoord beveiligd.';
$string['pleasecheckoneanswer'] = 'Kies één antwoord';
$string['pleasecheckoneormoreanswers'] = 'Duid één of meer antwoorden aan';
$string['pleaseenteryouranswerinthebox'] = 'Geef je antwoord in het vakje';
$string['pleasematchtheabovepairs'] = 'Koppel bovenstaande paren';
$string['pluginadministration'] = 'Beheer les';
$string['pluginname'] = 'Les';
$string['pointsearned'] = 'Verdiende punten';
$string['postprocesserror'] = 'Fout opgetreden tijdens de verwerking!';
$string['postsuccess'] = 'Posten gelukt';
$string['pptsuccessfullimport'] = 'Importeren van de geüploade PowerPoint presentatie gelukt';
$string['practice'] = 'Oefenles';
$string['practice_help'] = 'Een oefenles zal niet in het puntenboek verschijnen.';
$string['preprocesserror'] = 'Fout opgetreden tijdens de voorbereiding!';
$string['preview'] = 'Voorbeeld';
$string['previewlesson'] = 'Voorbeeld van {$a}';
$string['previouspage'] = 'Vorige pagina';
$string['processerror'] = 'Fout opgetreden tijdens de verwerking!';
$string['progressbar'] = 'Vorderingsbalk';
$string['progressbar_help'] = 'Indien ingeschakeld, krijg je een vorderingsbalk te zien onderaan de les pagina\'s. Deze vorderingsbalk toont bij nadering het percentage dat is voltooid.';
$string['progressbarteacherwarning'] = 'Vorderingsbalk niet tonen voor {$a}';
$string['progressbarteacherwarning2'] = 'Je zult de progressiebalk niet zien omdat je deze les kunt bewerken';
$string['progresscompleted'] = 'Je hebt {$a}% van de les beëindigd';
$string['qtype'] = 'Paginatype';
$string['question'] = 'Vraag';
$string['questionoption'] = 'Vraagoptie';
$string['questiontype'] = 'Vraagtype';
$string['randombranch'] = 'Willekeurige inhoudspagina';
$string['randompageinbranch'] = 'Willekeurige vraag binnen een inhoudspagina';
$string['rank'] = 'Rangschikking';
$string['rawgrade'] = 'Ruwe score';
$string['receivedcredit'] = 'Behaalde score';
$string['redisplaypage'] = 'Toon pagina opnieuw';
$string['report'] = 'Rapport';
$string['reports'] = 'Rapporten';
$string['response'] = 'Respons';
$string['retakesallowed'] = 'Opnieuw doen toegelaten';
$string['retakesallowed_help'] = 'Deze instelling bepaalt of de leerlingen de les meer dan eens kunnen doormaken of slechts één keer. De leraar kan beslissen of deze les materiaal bevat dat de leerlingen erg grondig moeten kennen. In dat geval moet het herhaald bekijken van de les toegelaten worden. Als het materaal eerder gebruikt wordt om te testen, dan kun je er beter voor kiezen de les maar één keer te laten doornemen.
Als de leerlingen de les mogen overdoen, dan wordt voor de **cijfers** in de cijfertabel hun **beste** poging gekozen. Nochtans worden voor de **vragen analyse** altijd de antwoorden van de eerste pogingen genomen. De volgende antwoorden worden genegeerd.
Merk op: de **Vraaganalyse** gebruikt altijd de antwoorden van de eerste poging van de les. De volgende pogingen worden genegeerd.
De standaardinstelling van deze optie is **Ja**, wat wil zeggen dat leerlingen de les opnieuw mogen doornemen. Waarschijnlijk moet deze optie slechts in uitzonderlijke gevallen op **Nee** gezet worden.';
$string['returnto'] = 'Keer terug naar {$a}';
$string['returntocourse'] = 'Keer terug naar de cursuspagina';
$string['review'] = 'Nalezen';
$string['reviewlesson'] = 'Les nalezen';
$string['reviewquestionback'] = 'Ja, ik wil nog eens proberen';
$string['reviewquestioncontinue'] = 'Nee, ik wil naar de volgende vraag gaan';
$string['sanitycheckfailed'] = 'Fouten gevonden: deze poging wordt verwijderd';
$string['savechanges'] = 'Bewaar wijzigingen';
$string['savechangesandeol'] = 'Bewaar alle wijzigingen en ga naar het einde van de les';
$string['savepage'] = 'Bewaar pagina';
$string['score'] = 'Cijfer';
$string['scores'] = 'Cijfers';
$string['secondpluswrong'] = 'Niet echt. Wil je nog eens proberen?';
$string['selectaqtype'] = 'Kies een vraagtype';
$string['shortanswer'] = 'Kort antwoord';
$string['showanunansweredpage'] = 'Toon een onbeantwoorde pagina';
$string['showanunseenpage'] = 'Toon een ongeziene pagina';
$string['singleanswer'] = 'Eén enkel antwoord';
$string['skip'] = 'Sla navigatie over';
$string['slideshow'] = 'Diavoorstelling';
$string['slideshow_help'] = 'Hiermee kun je de les als een diavoorstelling tonen, met een vaste breedte, hoogte en een aangepaste achtergrondkleur. Een op CSS gebaseerde rolbalk wordt getoond als de breedte of hoogte van de dia overschreden wordt door de inhoud van de pagina.
Standaard worden vragen niet getoond in een diavoorstelling, alleen vertakkingstabellen verschijnen. Knoppen met labels voor "Terug" en "Verder" worden links en rechts van de dia getoond als die optie gekozen is. Andere knoppen worden in het midden van de dia geplaatst.';
$string['slideshowbgcolor'] = 'Achtergrondkleur van de diavoorstelling';
$string['slideshowheight'] = 'Hoogte van de diavoorstelling';
$string['slideshowwidth'] = 'Breedte van de diavoorstelling';
$string['startlesson'] = 'Start de les';
$string['studentattemptlesson'] = 'Pogingnummer {$a->attempt} van {$a->lastname}, {$a->firstname}';
$string['studentname'] = '{$a} naam';
$string['studentoneminwarning'] = 'Waarschuwing: je hebt nog één minuut of minder om deze les af te werken.';
$string['studentresponse'] = 'Het antwoord van {$a}';
$string['submit'] = 'Insturen';
$string['submitname'] = 'Geef een naam';
$string['teacherjumpwarning'] = 'Er wordt een {$a->cluster} sprong of een {$a->unseen} sprong gebruikt in deze les. De sprong naar de volgende pagina zal in de plaats gebruikt worden. Meld je aan als leerling om deze sprongen te testen.';
$string['teacherongoingwarning'] = 'De score tijdens de les wordt alleen aan leerlingen getoond. Meld je aan als leerling om deze optie te testen';
$string['teachertimerwarning'] = 'De timer werkt enkel voor leerlingen. Test de timer door je als leerling aan te melden.';
$string['thatsthecorrectanswer'] = 'Dat is het juiste antwoord';
$string['thatsthewronganswer'] = 'Dat is het verkeerde antwoord';
$string['thefollowingpagesjumptothispage'] = 'Volgende pagina verwijst naar deze pagina';
$string['thispage'] = 'Deze pagina';
$string['timeremaining'] = 'Resterende tijd';
$string['timespenterror'] = 'Neem minstens {$a} minuten de tijd om de les te maken';
$string['timespentminutes'] = 'Gebruikte tijd (minuten)';
$string['timetaken'] = 'Gebruikte tijd';
$string['topscorestitle'] = 'Top {$a} hoogste cijfers';
$string['truefalse'] = 'Waar/niet waar';
$string['unabledtosavefile'] = 'Het bestand dat je uploadde kon niet bewaard worden';
$string['unknownqtypesnotimported'] = '{$a} vragen met niet ondersteunde vraagtypes werden niet geïmporteerd';
$string['unseenpageinbranch'] = 'Ongeziene vraag binnen een inhoudspagina';
$string['unsupportedqtype'] = 'Vraagtype ({$a}) niet ondersteund';
$string['updatedpage'] = 'Pagina geüpdatet';
$string['updatefailed'] = 'Update mislukt';
$string['usemaximum'] = 'Beste';
$string['usemean'] = 'Gemiddelde';
$string['usepassword'] = 'Les beschermd met wachtwoord';
$string['usepassword_help'] = 'Hiermee zullen leerlingen die het wachtwoord niet kunnen intypen de les niet kunnen beginnen.';
$string['viewgrades'] = 'Bekijk de cijfers';
$string['viewhighscores'] = 'Bekijk de lijst met de hoogste cijfers';
$string['viewreports'] = 'Bekijk {$a->attempts} voltooide pogingen van {$a->student}';
$string['viewreports2'] = 'Bekijk {$a} volledige pogingen';
$string['welldone'] = 'Goed gedaan!';
$string['whatdofirst'] = 'Wat wil je eerst doen?';
$string['wronganswerjump'] = 'Verkeerde antwoordsprong';
$string['wronganswerscore'] = 'Verkeerd antwoordcijfer';
$string['wrongresponse'] = 'Verkeerd antwoord';
$string['xattempts'] = '{$a} pogingen';
$string['youhaveseen'] = 'Je hebt al meer dan één pagina van deze les bekeken.<br />Wil je beginnen bij de laatste pagina die je vorige keer bekeken hebt?';
$string['youmadehighscore'] = 'Je hebt de top {$a} cijferlijst gehaald';
$string['youranswer'] = 'Jouw antwoord';
$string['yourcurrentgradeis'] = 'Je cijfer is nu {$a}';
$string['yourcurrentgradeisoutof'] = 'Je huidige cijfer is {$a->grade} op {$a->total}';
$string['youshouldview'] = 'Je moet een antwoord geven op minimum: {$a}';
| gpl-3.0 |
duthils/osmose-frontend | control.py | 9292 | #! /usr/bin/env python
#-*- coding: utf-8 -*-
###########################################################################
## ##
## Copyrights Etienne Chové <[email protected]> 2009 ##
## ##
## This program is free software: you can redistribute it and/or modify ##
## it under the terms of the GNU General Public License as published by ##
## the Free Software Foundation, either version 3 of the License, or ##
## (at your option) any later version. ##
## ##
## This program is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with this program. If not, see <http://www.gnu.org/licenses/>. ##
## ##
###########################################################################
from bottle import route, request, response, template, post
from tools import utils
import tools.update
import os
import sys
from collections import defaultdict
@route('/control/update')
def updates(db, lang):
db.execute("""
SELECT
source.id,
EXTRACT(EPOCH FROM ((now())-dynpoi_update_last.timestamp)) AS age,
source.country,
source.analyser
FROM
source
LEFT JOIN dynpoi_update_last ON
source.id = dynpoi_update_last.source
ORDER BY
dynpoi_update_last.timestamp DESC
""")
liste = []
for res in db.fetchall():
(source, age, country, analyser) = (res[0], res[1], res[2], res[3])
if age:
if age >= 0:
# TRANSLATORS: days / hours / minutes since last source update, abbreviated to d / h / m
txt = _("{day}d, {hour}h, {minute}m ago").format(day=int(age/86400), hour=int(age/3600)%24, minute=int(age/60)%60)
else:
txt = _("in {day}d, {hour}h, {minute}m").format(day=int(-age/86400), hour=int(-age/3600)%24, minute=int(-age/60)%60)
liste.append((country, analyser, age, txt, source))
else:
liste.append((country, analyser, 1e10, _("never generated"), source))
liste.sort(lambda x, y: -cmp(x[2], y[2]))
return template('control/updates', liste=liste)
@route('/control/update_matrix')
def updates(db, lang):
remote = request.params.get('remote')
country = request.params.get('country')
db.execute("""
SELECT DISTINCT ON (source.id)
source.id,
EXTRACT(EPOCH FROM ((now())-dynpoi_update_last.timestamp)) AS age,
country,
analyser
FROM
source
JOIN dynpoi_update_last ON
source.id = dynpoi_update_last.source """ + (
"""
JOIN dynpoi_update ON
dynpoi_update.source = dynpoi_update_last.source AND
dynpoi_update.timestamp = dynpoi_update_last.timestamp """ if remote else "") + """
WHERE
""" + ("""
RIGHT(MD5(remote_ip), 4) = %(remote)s AND """ if remote else "") + ("""
source.country LIKE %(country)s AND """ if country else "") + """
true
ORDER BY
source.id ASC,
dynpoi_update_last.timestamp DESC
""", {"remote": remote, "country": country and country.replace("*", "%")})
keys = defaultdict(int)
matrix = defaultdict(dict)
stats_analyser = {}
stats_country = {}
for res in db.fetchall():
(source, age, country, analyser) = (res[0], res[1], res[2], res[3])
keys[country] += 1
matrix[analyser][country] = (age/60/60/24, source)
for analyser in matrix:
min = max = None
sum = 0
for country in matrix[analyser]:
v = matrix[analyser][country][0]
min = v if not min or v < min else min
max = v if not max or v > max else max
sum += v
if not stats_country.has_key(country):
min_c = v
sum_c = v
max_c = v
n_c = 1
else:
(min_c, sum_c, max_c, n_c) = stats_country[country]
min_c = v if v < min_c else min_c
max_c = v if v > max_c else max_c
sum_c += v
n_c += 1
stats_country[country] = [min_c, sum_c, max_c, n_c]
stats_analyser[analyser] = [min, sum/len(matrix[analyser]), max]
avg_country = {}
for country in stats_country:
stats_country[country][1] = stats_country[country][1]/stats_country[country][3]
keys = sorted(keys.keys())
return template('control/updates_matrix', keys=keys, matrix=matrix, stats_analyser=stats_analyser, stats_country=stats_country)
@route('/control/update_summary')
def updates(db, lang):
db.execute("""
SELECT
RIGHT(MD5(remote_ip), 4) AS remote_ip,
country,
MAX(EXTRACT(EPOCH FROM ((now())-dynpoi_update_last.timestamp))) AS max_age,
MIN(EXTRACT(EPOCH FROM ((now())-dynpoi_update_last.timestamp))) AS min_age,
MAX(dynpoi_update.version) AS max_version,
MIN(dynpoi_update.version) AS min_version,
count(*) AS count
FROM
source
JOIN dynpoi_update_last ON
source.id = dynpoi_update_last.source
JOIN dynpoi_update ON
dynpoi_update.source = dynpoi_update_last.source AND
dynpoi_update.timestamp = dynpoi_update_last.timestamp
GROUP BY
remote_ip,
country
ORDER BY
remote_ip,
MIN(EXTRACT(EPOCH FROM ((now())-dynpoi_update_last.timestamp))) ASC
""")
summary = defaultdict(list)
max_versions = defaultdict(list)
min_versions = defaultdict(list)
for res in db.fetchall():
(remote, country, max_age, min_age, max_version, min_version, count) = res
summary[remote].append({'country': country, 'max_age': max_age/60/60/24, 'min_age': min_age/60/60/24, 'count': count})
max_versions[remote].append(max_version)
min_versions[remote].append(min_version)
for remote in max_versions.keys():
max_versions[remote] = max(max_versions[remote])
if max_versions[remote] and '-' in max_versions[remote]:
max_versions[remote] = '-'.join(max_versions[remote].split('-')[1:5])
min_versions[remote] = min(min_versions[remote])
if min_versions[remote] and '-' in min_versions[remote]:
min_versions[remote] = '-'.join(min_versions[remote].split('-')[1:5])
return template('control/updates_summary', summary=summary, max_versions=max_versions, min_versions=min_versions)
@route('/control/update/<source:int>')
def update(db, lang, source=None):
sql = "SELECT source,timestamp,remote_url,remote_ip,version FROM dynpoi_update WHERE source=%d ORDER BY timestamp DESC;" % source
db.execute(sql)
return template('control/update', liste=db.fetchall())
@route('/control/i18n')
def update():
return os.popen("cd po && make statistics | sed -n '1h;2,$H;${g;s/\\n/<br>/g;p}'").read()
@route('/control/lang')
def update(lang):
out = "Accept-Language: " + request.headers['Accept-Language'] + "\n"
if request.get_cookie('lang'):
out += "Cookie: " + request.get_cookie('lang') + "\n"
out += "Chosen languages: " + (",".join(lang)) + "\n"
response.content_type = "text/plain; charset=utf-8"
return out
@post('/control/send-update')
@post('/cgi-bin/update.py') # Backward compatibility
def send_update():
src = request.params.get('source', default=None)
code = request.params.get('code')
url = request.params.get('url', default=None)
upload = request.files.get('content', default=None)
response.content_type = "text/plain; charset=utf-8"
if not code or not (url or upload):
return "FAIL"
remote_ip = request.remote_addr
sources = utils.get_sources()
for s in sources:
if src and sources[s]["comment"] != src:
continue
if not code in sources[s]["password"]:
continue
try:
if url:
tools.update.update(sources[s], url, remote_ip=remote_ip)
elif upload:
(name, ext) = os.path.splitext(upload.filename)
if ext not in ('.bz2','.gz','.xml'):
return 'FAIL: File extension not allowed.'
save_filename = os.path.join(utils.dir_results, upload.filename)
upload.save(save_filename, overwrite=True)
tools.update.update(sources[s], save_filename, remote_ip=remote_ip)
os.unlink(save_filename)
except tools.update.OsmoseUpdateAlreadyDone:
pass
except:
import traceback
from cStringIO import StringIO
import smtplib
s = StringIO()
sys.stderr = s
traceback.print_exc()
sys.stderr = sys.__stderr__
traceback = s.getvalue()
return traceback.rstrip()
return "OK"
return "AUTH FAIL"
| gpl-3.0 |
detroit/detroit-rspec | lib/detroit-rspec.rb | 3915 | require 'detroit/tool'
module Detroit
# Create new RSpec tool with specified +options+.
def RSpec(options={})
RSpec.new(options)
end
# The RSpec tool is used to run project specifications
# written with RSpec. Specifications are expected to found
# in the standard `spec/` directory unless otherwise specified
# in the tools options.
#
# Options:
#
# specs File glob(s) of spec files. Defaults to ['spec/**/*_spec.rb', 'spec/**/spec_*.rb'].
# loadpath Paths to add $LOAD_PATH. Defaults to ['lib'].
# live Ignore loadpath, use installed libraries instead. Default is false.
# require Lib(s) to require before excuting specifications.
# warning Whether to show warnings or not. Default is false.
# format Format of RSpec output.
# extra Additional commandl ine options for spec command.
#
# NOTE: This tool currently shells out to the command line.
#
#--
# TODO: Use rspec options file?
#
# TODO: RCOV suppot?
# ruby [ruby_opts] -Ilib -S rcov [rcov_opts] bin/spec -- examples [spec_opts]
#++
class RSpec < Tool
# File glob(s) of spec files. Defaults to ['spec/**/*_spec.rb', 'spec/**/spec_*.rb'].
attr_accessor :specs
# A more generic alternative to #specs.
alias_accessor :include, :specs
# Paths to add $LOAD_PATH. Defaults to ['lib'].
attr_accessor :loadpath
# Ignore loadpath, use installed libraries instead. Default is false.
#attr_accessor :live
# Scripts to require before excuting specifications.
attr_accessor :requires
# Whether to show warnings or not. Default is false.
attr_accessor :warning
# Format of RSpec output.
attr_accessor :format
# Output file, STDOUT if nil.
attr_accessor :output
# Additional command line options for rspec.
attr_accessor :extra
# A S S E M B L Y M E T H O D S
#
def assemble?(station, options={})
case station
when :test then true
end
end
# Attach test method to test assembly.
#
# @todo Attach documentaton?
def assemble(station, options={})
case station
#when :document then document
when :test then run
end
end
# S E R V I C E M E T H O D S
# Run all specs.
#
# Returns +false+ if any tests failed, otherwise +true+.
def run
run_specs
end
#
alias_method :test, :run
# Run all specs with documentation output.
def document
run_specs('documentation')
end
private
#
def initialize_defaults
@loadpath = metadata.loadpath
@specs = ['spec/**/*_spec.rb', 'spec/**/spec_*.rb']
@requires = []
@warning = false
end
# Run rspecs.
def run_specs(format=nil)
format = format || self.format
specs = self.specs.to_list
loadpath = self.loadpath.to_list
requires = self.requires.to_list
files = multiglob(*specs)
if files.empty?
puts "No specifications."
else
# ruby [ruby_opts] -Ilib bin/spec examples [spec_opts]
argv = []
argv << "-w" if warning
argv << %[-I"#{loadpath.join(':')}"] unless loadpath.empty?
argv << %[-r"#{requires.join(':')}"] unless requires.empty?
argv << %[-f"#{format}"] if format
argv << %[-o"#{output}"] if output
argv << files
argv << extra_options
argv = argv.flatten
trace "rspec " + argv.join(' ')
success = ::RSpec::Core::Runner.run(argv)
end
end
# Extra options.
def extra_options
case extra
when String
extra.split(/\s+/)
when Array
extra
else
[]
end
end
#
def initialize_requires
require 'rspec/core'
end
public
def self.man_page
File.dirname(__FILE__)+'/../man/detroit-rspec.5'
end
end
end
| gpl-3.0 |
arielsiles/sisk1 | src/main/com/encens/khipus/model/finances/CompanyConfiguration.java | 44802 | package com.encens.khipus.model.finances;
import com.encens.khipus.model.CompanyListener;
import com.encens.khipus.model.CompanyNumberListener;
import com.encens.khipus.model.UpperCaseStringListener;
import com.encens.khipus.model.admin.Company;
import com.encens.khipus.model.contacts.Salutation;
import com.encens.khipus.model.customers.DocumentType;
import com.encens.khipus.model.employees.Charge;
import com.encens.khipus.model.employees.JobCategory;
import com.encens.khipus.util.Constants;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import javax.persistence.*;
import java.math.BigDecimal;
import static com.encens.khipus.model.usertype.StringBooleanUserType.*;
/**
* CompanyConfiguration
*
* @author
* @version 2.22
*/
@NamedQueries({
@NamedQuery(name = "CompanyConfiguration.findByCompany", query = "select c from CompanyConfiguration c")
})
@Entity
@EntityListeners({CompanyListener.class, CompanyNumberListener.class, UpperCaseStringListener.class})
@Filter(name = com.encens.khipus.util.Constants.COMPANY_FILTER_NAME)
@Table(name = "configuracion", schema = Constants.FINANCES_SCHEMA)
public class CompanyConfiguration {
@Id
@Column(name = "NO_CIA", nullable = false, updatable = false)
private String companyNumber;
@Column(name = "CTADIFTIPCAM", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String balanceExchangeRateAccountCode;
@ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTADIFTIPCAM", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount balanceExchangeRateAccount;
@Column(name = "CTAANTPROVME", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String advancePaymentForeignCurrencyAccountCode;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAANTPROVME", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount advancePaymentForeignCurrencyAccount;
@Column(name = "CTAANTPROVMN", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String advancePaymentNationalCurrencyAccountCode;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAANTPROVMN", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount advancePaymentNationalCurrencyAccount;
@ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, insertable = false, updatable = false),
@JoinColumn(name = "CTADEPTRAME", referencedColumnName = "CUENTA", nullable = false, insertable = false, updatable = false)
})
private CashAccount depositInTransitForeignCurrencyAccount;
@Column(name = "CTADEPTRAME", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String depositInTransitForeignCurrencyAccountCode;
@ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, insertable = false, updatable = false),
@JoinColumn(name = "CTADEPTRAMN", referencedColumnName = "CUENTA", nullable = false, insertable = false, updatable = false)
})
private CashAccount depositInTransitNationalCurrencyAccount;
@Column(name = "CTADEPTRAMN", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String depositInTransitNationalCurrencyAccountCode;
@Column(name = "CTAALMME", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String warehouseForeignCurrencyAccountCode;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAALMME", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount warehouseForeignCurrencyAccount;
@Column(name = "CTAALMMN", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String warehouseNationalCurrencyAccountCode;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAALMMN", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount warehouseNationalCurrencyAccount;
@Column(name = "CTATRANSALMME", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String warehouseForeignCurrencyTransientAccountCode;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTATRANSALMME", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount warehouseForeignCurrencyTransientAccount;
@Column(name = "CTATRANSALMMN", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String warehouseNationalCurrencyTransientAccountCode;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTATRANSALMMN", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount warehouseNationalCurrencyTransientAccount;
@Column(name = "CTATRANSALM1MN", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String warehouseNationalCurrencyTransientAccount1Code;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTATRANSALM1MN", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount warehouseNationalCurrencyTransientAccount1;
@Column(name = "CTATRANSALM2MN", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String warehouseNationalCurrencyTransientAccount2Code;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTATRANSALM2MN", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount warehouseNationalCurrencyTransientAccount2;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAAITB", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount adjustmentForInflationAccount;
@Column(name = "CTAAITB", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String adjustmentForInflationAccountCode;
/* account for iva fiscal credit (VAT=value-added tax) foreign currency*/
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAIVACREFIME", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount foreignCurrencyVATFiscalCreditAccount;
@Column(name = "CTAIVACREFIME", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String foreignCurrencyVATFiscalCreditAccountCode;
/* account for iva fiscal credit (VAT=value-added tax) national currency*/
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAIVACREFIMN", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount nationalCurrencyVATFiscalCreditAccount;
@Column(name = "CTAIVACREFIMN", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String nationalCurrencyVATFiscalCreditAccountCode;
/* account for iva fiscal credit (VAT=value-added tax) national currency*/
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAIVACREFITRMN", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount nationalCurrencyVATFiscalCreditTransientAccount;
@Column(name = "CTAIVACREFITRMN", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String nationalCurrencyVATFiscalCreditTransientAccountCode;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAPROVOBU", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount provisionByTangibleFixedAssetObsolescenceAccount;
@Column(name = "CTAPROVOBU", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String provisionByTangibleFixedAssetObsolescenceAccountCode;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "CTAAFET", referencedColumnName = "CUENTA", nullable = false, updatable = false, insertable = false)
})
private CashAccount fixedAssetInTransitAccount;
@Column(name = "CTAAFET", length = 20, nullable = false)
@Length(max = 20)
@NotNull
private String fixedAssetInTransitAccountCode;
@Column(name = "NO_USR_SIS", length = 4, nullable = false)
@Length(max = 4)
@NotNull
private String defaultSystemUserNumber;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "NO_USR_TESO", referencedColumnName = "NO_USR", nullable = false)
@NotNull
private FinanceUser defaultTreasuryUser;
@Column(name = "NO_USR_RPAGOS", length = 4, nullable = false)
@NotNull
private String defaultPurchaseOrderRemakePaymentUserNumber;
@Column(name = "ANIO_GEN_RPAGOS", length = 4, nullable = false)
@NotNull
private Integer defaultPurchaseOrderRemakeYear;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "NO_USR_CONTA", referencedColumnName = "NO_USR", nullable = false)
@NotNull
private FinanceUser defaultAccountancyUser;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "NO_USR_PRODUCCION", referencedColumnName = "NO_USR", nullable = false)
@NotNull
private FinanceUser defaultAccountancyUserProduction;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "NO_USR_PAGAR", referencedColumnName = "NO_USR", nullable = false)
@NotNull
private FinanceUser defaultPayableFinanceUser;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "PAGOCTABCOMN", referencedColumnName = "CTA_BCO", nullable = false, updatable = false, insertable = false)
})
private FinancesBankAccount nationalBankAccountForPayment;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, updatable = false, insertable = false),
@JoinColumn(name = "PAGOCTABCOME", referencedColumnName = "CTA_BCO", nullable = false, updatable = false, insertable = false)
})
private FinancesBankAccount foreignBankAccountForPayment;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDCARGODOC", nullable = false)
private Charge defaultProfessorsCharge;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDDEFTIPODOC", nullable = false)
private DocumentType defaultDocumentType;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDDEFSALMUJ", nullable = false)
private Salutation defaultSalutationForWoman;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDDEFSALHOM", nullable = false)
private Salutation defaultSalutationForMan;
@Column(name = "URLREDIREVALPROG", nullable = false)
private String scheduleEvaluationRedirectURL;
@Column(name = "URLREDIREVALPROGEST", nullable = false)
private String studentScheduleEvaluationRedirectURL;
@Column(name = "URLREDIREVALPROGDOC", nullable = false)
private String teacherScheduleEvaluationRedirectURL;
@Column(name = "URLREDIREVALPROGJC", nullable = false)
private String careerManagerScheduleEvaluationRedirectURL;
@Column(name = "URLREDIREVALPROGAE", nullable = false)
private String autoEvaluationScheduleEvaluationRedirectURL;
@Column(name = "OCCODIFACTIVA", nullable = false)
@Type(type = com.encens.khipus.model.usertype.IntegerBooleanUserType.NAME)
private boolean purchaseOrderCodificationEnabled;
@Column(name = "RETENCIONPRESTAMOANTI", nullable = false)
@Type(type = com.encens.khipus.model.usertype.IntegerBooleanUserType.NAME)
private boolean retentionForLoanAndAdvance;
@Column(name = "PRECIOUNITARIOLECHE",columnDefinition = "DECIMAL(5,2)",nullable = true)
private Double unitPriceMilk;
@Column(name = "IT",columnDefinition = "DECIMAL(3,2)",nullable = true)
private Double it;
@Column(name = "IUE",columnDefinition = "DECIMAL(3,2)",nullable = true)
private Double iue;
@Column(name = "AUTOMODIFCONTRATO", nullable = false)
@Type(type = com.encens.khipus.model.usertype.IntegerBooleanUserType.NAME)
private boolean contractModificationAuthorization;
@Column(name = "CODMODIFCONTRATO", nullable = false)
@Type(type = com.encens.khipus.model.usertype.IntegerBooleanUserType.NAME)
@NotNull
private boolean contractModificationCode;
@Column(name = "ACTIVOAUTDOC_TESO", nullable = false)
@Type(type = com.encens.khipus.model.usertype.StringBooleanUserType.NAME, parameters = {
@Parameter(name = TRUE_PARAMETER, value = TRUE_VALUE),
@Parameter(name = FALSE_PARAMETER, value = FALSE_VALUE)
})
private boolean treasuryDocumentsAuthorizationEnabled;
@Column(name = "ACTIVOAUTDOC_CXP", nullable = false)
@Type(type = com.encens.khipus.model.usertype.StringBooleanUserType.NAME, parameters = {
@Parameter(name = TRUE_PARAMETER, value = TRUE_VALUE),
@Parameter(name = FALSE_PARAMETER, value = FALSE_VALUE)
})
private boolean payablesDocumentsAuthorizationEnabled;
@Column(name = "AGUI_BASICO", nullable = false)
@Type(type = com.encens.khipus.model.usertype.IntegerBooleanUserType.NAME)
@NotNull
private boolean basicBasedChristmasPayroll;
@Column(name = "HRSDIALABORAL", precision = 10, scale = 2, nullable = false)
@NotNull
private BigDecimal hrsWorkingDay;
@Column(name = "TIPO_DOC_CAJA")
private String cashBoxDocumentTypeCode;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", nullable = false, insertable = false, updatable = false),
@JoinColumn(name = "TIPO_DOC_CAJA", referencedColumnName = "TIPO_DOC", nullable = false, insertable = false, updatable = false)
})
private PayableDocumentType cashBoxDocumentType;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDCATEGORIAPUESTODLH", referencedColumnName = "idcategoriapuesto", nullable = false)
private JobCategory jobCategoryDLH;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDCATEGORIAPUESTODTH", referencedColumnName = "idcategoriapuesto", nullable = false)
private JobCategory jobCategoryDTH;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDTIPOSUELDODLH", referencedColumnName = "idtiposueldo", nullable = false)
private KindOfSalary kindOfSalaryDLH;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDTIPOSUELDODTH", referencedColumnName = "idtiposueldo", nullable = false)
private KindOfSalary kindOfSalaryDTH;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
@JoinColumn(name = "NO_CIA", referencedColumnName = "NO_CIA", updatable = false, insertable = false),
@JoinColumn(name = "COD_CC", referencedColumnName = "COD_CC", updatable = false, insertable = false)
})
private CostCenter exchangeRateBalanceCostCenter;
@Column(name = "COD_CC", length = 8)
@Length(max = 8)
private String costCenterCode;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "IDCOMPANIA", unique = true, nullable = false, updatable = false, insertable = true)
private Company company;
@Version
@Column(name = "VERSION", nullable = false)
private long version;
public String getCompanyNumber() {
return companyNumber;
}
public void setCompanyNumber(String companyNumber) {
this.companyNumber = companyNumber;
}
public String getBalanceExchangeRateAccountCode() {
return balanceExchangeRateAccountCode;
}
public void setBalanceExchangeRateAccountCode(String balanceExchangeRateAccountCode) {
this.balanceExchangeRateAccountCode = balanceExchangeRateAccountCode;
}
public CashAccount getBalanceExchangeRateAccount() {
return balanceExchangeRateAccount;
}
public void setBalanceExchangeRateAccount(CashAccount balanceExchangeRateAccount) {
this.balanceExchangeRateAccount = balanceExchangeRateAccount;
setBalanceExchangeRateAccountCode(this.balanceExchangeRateAccount != null ? this.balanceExchangeRateAccount.getAccountCode() : null);
}
public String getAdvancePaymentForeignCurrencyAccountCode() {
return advancePaymentForeignCurrencyAccountCode;
}
public void setAdvancePaymentForeignCurrencyAccountCode(String advancePaymentForeignCurrencyAccountCode) {
this.advancePaymentForeignCurrencyAccountCode = advancePaymentForeignCurrencyAccountCode;
}
public CashAccount getAdvancePaymentForeignCurrencyAccount() {
return advancePaymentForeignCurrencyAccount;
}
public void setAdvancePaymentForeignCurrencyAccount(CashAccount advancePaymentForeignCurrencyAccount) {
this.advancePaymentForeignCurrencyAccount = advancePaymentForeignCurrencyAccount;
setAdvancePaymentForeignCurrencyAccountCode(advancePaymentForeignCurrencyAccount != null ? advancePaymentForeignCurrencyAccount.getAccountCode() : null);
}
public String getAdvancePaymentNationalCurrencyAccountCode() {
return advancePaymentNationalCurrencyAccountCode;
}
public void setAdvancePaymentNationalCurrencyAccountCode(String advancePaymentNationalCurrencyAccountCode) {
this.advancePaymentNationalCurrencyAccountCode = advancePaymentNationalCurrencyAccountCode;
}
public CashAccount getAdvancePaymentNationalCurrencyAccount() {
return advancePaymentNationalCurrencyAccount;
}
public void setAdvancePaymentNationalCurrencyAccount(CashAccount advancePaymentNationalCurrencyAccount) {
this.advancePaymentNationalCurrencyAccount = advancePaymentNationalCurrencyAccount;
setAdvancePaymentNationalCurrencyAccountCode(advancePaymentNationalCurrencyAccount != null ? advancePaymentNationalCurrencyAccount.getAccountCode() : null);
}
public String getWarehouseForeignCurrencyAccountCode() {
return warehouseForeignCurrencyAccountCode;
}
public void setWarehouseForeignCurrencyAccountCode(String warehouseForeignCurrencyAccountCode) {
this.warehouseForeignCurrencyAccountCode = warehouseForeignCurrencyAccountCode;
}
public CashAccount getWarehouseForeignCurrencyAccount() {
return warehouseForeignCurrencyAccount;
}
public void setWarehouseForeignCurrencyAccount(CashAccount warehouseForeignCurrencyAccount) {
this.warehouseForeignCurrencyAccount = warehouseForeignCurrencyAccount;
setWarehouseForeignCurrencyAccountCode(warehouseForeignCurrencyAccount != null ? warehouseForeignCurrencyAccount.getAccountCode() : null);
}
public String getWarehouseNationalCurrencyAccountCode() {
return warehouseNationalCurrencyAccountCode;
}
public void setWarehouseNationalCurrencyAccountCode(String warehouseNationalCurrencyAccountCode) {
this.warehouseNationalCurrencyAccountCode = warehouseNationalCurrencyAccountCode;
}
public CashAccount getWarehouseNationalCurrencyAccount() {
return warehouseNationalCurrencyAccount;
}
public void setWarehouseNationalCurrencyAccount(CashAccount warehouseNationalCurrencyAccount) {
this.warehouseNationalCurrencyAccount = warehouseNationalCurrencyAccount;
setWarehouseNationalCurrencyAccountCode(warehouseNationalCurrencyAccount != null ? warehouseNationalCurrencyAccount.getAccountCode() : null);
}
public String getWarehouseForeignCurrencyTransientAccountCode() {
return warehouseForeignCurrencyTransientAccountCode;
}
public void setWarehouseForeignCurrencyTransientAccountCode(String warehouseForeignCurrencyTransientAccountCode) {
this.warehouseForeignCurrencyTransientAccountCode = warehouseForeignCurrencyTransientAccountCode;
}
public CashAccount getWarehouseForeignCurrencyTransientAccount() {
return warehouseForeignCurrencyTransientAccount;
}
public void setWarehouseForeignCurrencyTransientAccount(CashAccount warehouseForeignCurrencyTransientAccount) {
this.warehouseForeignCurrencyTransientAccount = warehouseForeignCurrencyTransientAccount;
setWarehouseForeignCurrencyTransientAccountCode(warehouseForeignCurrencyTransientAccount != null ? warehouseForeignCurrencyTransientAccount.getAccountCode() : null);
}
public String getWarehouseNationalCurrencyTransientAccountCode() {
return warehouseNationalCurrencyTransientAccountCode;
}
public void setWarehouseNationalCurrencyTransientAccountCode(String warehouseNationalCurrencyTransientAccountCode) {
this.warehouseNationalCurrencyTransientAccountCode = warehouseNationalCurrencyTransientAccountCode;
}
public CashAccount getWarehouseNationalCurrencyTransientAccount() {
return warehouseNationalCurrencyTransientAccount;
}
public void setWarehouseNationalCurrencyTransientAccount(CashAccount warehouseNationalCurrencyTransientAccount) {
this.warehouseNationalCurrencyTransientAccount = warehouseNationalCurrencyTransientAccount;
setWarehouseNationalCurrencyTransientAccountCode(warehouseNationalCurrencyTransientAccount != null ? warehouseNationalCurrencyTransientAccount.getAccountCode() : null);
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public CashAccount getAdjustmentForInflationAccount() {
return adjustmentForInflationAccount;
}
public void setAdjustmentForInflationAccount(CashAccount adjustmentForInflationAccount) {
this.adjustmentForInflationAccount = adjustmentForInflationAccount;
setAdjustmentForInflationAccountCode(this.adjustmentForInflationAccount != null ?
this.adjustmentForInflationAccount.getAccountCode() : null);
}
public String getAdjustmentForInflationAccountCode() {
return adjustmentForInflationAccountCode;
}
public void setAdjustmentForInflationAccountCode(String adjustmentForInflationAccountCode) {
this.adjustmentForInflationAccountCode = adjustmentForInflationAccountCode;
}
public CashAccount getProvisionByTangibleFixedAssetObsolescenceAccount() {
return provisionByTangibleFixedAssetObsolescenceAccount;
}
public void setProvisionByTangibleFixedAssetObsolescenceAccount(CashAccount provisionByTangibleFixedAssetObsolescenceAccount) {
this.provisionByTangibleFixedAssetObsolescenceAccount = provisionByTangibleFixedAssetObsolescenceAccount;
setProvisionByTangibleFixedAssetObsolescenceAccountCode(this.provisionByTangibleFixedAssetObsolescenceAccount != null ?
this.provisionByTangibleFixedAssetObsolescenceAccount.getAccountCode() : null);
}
public String getProvisionByTangibleFixedAssetObsolescenceAccountCode() {
return provisionByTangibleFixedAssetObsolescenceAccountCode;
}
public void setProvisionByTangibleFixedAssetObsolescenceAccountCode(String provisionByTangibleFixedAssetObsolescenceAccountCode) {
this.provisionByTangibleFixedAssetObsolescenceAccountCode = provisionByTangibleFixedAssetObsolescenceAccountCode;
}
public String getDefaultSystemUserNumber() {
return defaultSystemUserNumber;
}
public void setDefaultSystemUserNumber(String defaultSystemUserNumber) {
this.defaultSystemUserNumber = defaultSystemUserNumber;
}
public FinanceUser getDefaultTreasuryUser() {
return defaultTreasuryUser;
}
public void setDefaultTreasuryUser(FinanceUser defaultTreasuryUser) {
this.defaultTreasuryUser = defaultTreasuryUser;
}
public String getDefaultPurchaseOrderRemakePaymentUserNumber() {
return defaultPurchaseOrderRemakePaymentUserNumber;
}
public void setDefaultPurchaseOrderRemakePaymentUserNumber(String defaultPurchaseOrderRemakePaymentUserNumber) {
this.defaultPurchaseOrderRemakePaymentUserNumber = defaultPurchaseOrderRemakePaymentUserNumber;
}
public Integer getDefaultPurchaseOrderRemakeYear() {
return defaultPurchaseOrderRemakeYear;
}
public void setDefaultPurchaseOrderRemakeYear(Integer defaultPurchaseOrderRemakeYear) {
this.defaultPurchaseOrderRemakeYear = defaultPurchaseOrderRemakeYear;
}
public FinanceUser getDefaultAccountancyUser() {
return defaultAccountancyUser;
}
public void setDefaultAccountancyUser(FinanceUser defaultAccountancyUser) {
this.defaultAccountancyUser = defaultAccountancyUser;
}
public FinanceUser getDefaultPayableFinanceUser() {
return defaultPayableFinanceUser;
}
public void setDefaultPayableFinanceUser(FinanceUser defaultPayableFinanceUser) {
this.defaultPayableFinanceUser = defaultPayableFinanceUser;
}
public FinancesBankAccount getNationalBankAccountForPayment() {
return nationalBankAccountForPayment;
}
public void setNationalBankAccountForPayment(FinancesBankAccount nationalBankAccountForPayment) {
this.nationalBankAccountForPayment = nationalBankAccountForPayment;
}
public FinancesBankAccount getForeignBankAccountForPayment() {
return foreignBankAccountForPayment;
}
public void setForeignBankAccountForPayment(FinancesBankAccount foreignBankAccountForPayment) {
this.foreignBankAccountForPayment = foreignBankAccountForPayment;
}
public Charge getDefaultProfessorsCharge() {
return defaultProfessorsCharge;
}
public void setDefaultProfessorsCharge(Charge defaultProfessorsCharge) {
this.defaultProfessorsCharge = defaultProfessorsCharge;
}
public CashAccount getForeignCurrencyVATFiscalCreditAccount() {
return foreignCurrencyVATFiscalCreditAccount;
}
public void setForeignCurrencyVATFiscalCreditAccount(CashAccount foreignCurrencyVATFiscalCreditAccount) {
this.foreignCurrencyVATFiscalCreditAccount = foreignCurrencyVATFiscalCreditAccount;
setForeignCurrencyVATFiscalCreditAccountCode(this.foreignCurrencyVATFiscalCreditAccount != null ?
this.foreignCurrencyVATFiscalCreditAccount.getAccountCode() : null);
}
public String getForeignCurrencyVATFiscalCreditAccountCode() {
return foreignCurrencyVATFiscalCreditAccountCode;
}
public void setForeignCurrencyVATFiscalCreditAccountCode(String foreignCurrencyVATFiscalCreditAccountCode) {
this.foreignCurrencyVATFiscalCreditAccountCode = foreignCurrencyVATFiscalCreditAccountCode;
}
public CashAccount getNationalCurrencyVATFiscalCreditAccount() {
return nationalCurrencyVATFiscalCreditAccount;
}
public void setNationalCurrencyVATFiscalCreditAccount(CashAccount nationalCurrencyVATFiscalCreditAccount) {
this.nationalCurrencyVATFiscalCreditAccount = nationalCurrencyVATFiscalCreditAccount;
setNationalCurrencyVATFiscalCreditAccountCode(this.nationalCurrencyVATFiscalCreditAccount != null ?
this.nationalCurrencyVATFiscalCreditAccount.getAccountCode() : null);
}
public String getNationalCurrencyVATFiscalCreditAccountCode() {
return nationalCurrencyVATFiscalCreditAccountCode;
}
public void setNationalCurrencyVATFiscalCreditAccountCode(String nationalCurrencyVATFiscalCreditAccountCode) {
this.nationalCurrencyVATFiscalCreditAccountCode = nationalCurrencyVATFiscalCreditAccountCode;
}
public CashAccount getNationalCurrencyVATFiscalCreditTransientAccount() {
return nationalCurrencyVATFiscalCreditTransientAccount;
}
public void setNationalCurrencyVATFiscalCreditTransientAccount(CashAccount nationalCurrencyVATFiscalCreditTransientAccount) {
this.nationalCurrencyVATFiscalCreditTransientAccount = nationalCurrencyVATFiscalCreditTransientAccount;
setNationalCurrencyVATFiscalCreditTransientAccountCode(this.nationalCurrencyVATFiscalCreditTransientAccount != null ?
this.nationalCurrencyVATFiscalCreditTransientAccount.getAccountCode() : null);
}
public String getNationalCurrencyVATFiscalCreditTransientAccountCode() {
return nationalCurrencyVATFiscalCreditTransientAccountCode;
}
public void setNationalCurrencyVATFiscalCreditTransientAccountCode(String nationalCurrencyVATFiscalCreditTransientAccountCode) {
this.nationalCurrencyVATFiscalCreditTransientAccountCode = nationalCurrencyVATFiscalCreditTransientAccountCode;
}
public CashAccount getFixedAssetInTransitAccount() {
return fixedAssetInTransitAccount;
}
public void setFixedAssetInTransitAccount(CashAccount fixedAssetInTransitAccount) {
this.fixedAssetInTransitAccount = fixedAssetInTransitAccount;
}
public String getFixedAssetInTransitAccountCode() {
return fixedAssetInTransitAccountCode;
}
public void setFixedAssetInTransitAccountCode(String fixedAssetInTransitAccountCode) {
this.fixedAssetInTransitAccountCode = fixedAssetInTransitAccountCode;
}
public DocumentType getDefaultDocumentType() {
return defaultDocumentType;
}
public void setDefaultDocumentType(DocumentType defaultDocumentType) {
this.defaultDocumentType = defaultDocumentType;
}
public Salutation getDefaultSalutationForWoman() {
return defaultSalutationForWoman;
}
public void setDefaultSalutationForWoman(Salutation defaultSalutationForWoman) {
this.defaultSalutationForWoman = defaultSalutationForWoman;
}
public Salutation getDefaultSalutationForMan() {
return defaultSalutationForMan;
}
public void setDefaultSalutationForMan(Salutation defaultSalutationForMan) {
this.defaultSalutationForMan = defaultSalutationForMan;
}
public String getScheduleEvaluationRedirectURL() {
return scheduleEvaluationRedirectURL;
}
public void setScheduleEvaluationRedirectURL(String scheduleEvaluationRedirectURL) {
this.scheduleEvaluationRedirectURL = scheduleEvaluationRedirectURL;
}
public String getStudentScheduleEvaluationRedirectURL() {
return studentScheduleEvaluationRedirectURL;
}
public void setStudentScheduleEvaluationRedirectURL(String studentScheduleEvaluationRedirectURL) {
this.studentScheduleEvaluationRedirectURL = studentScheduleEvaluationRedirectURL;
}
public String getTeacherScheduleEvaluationRedirectURL() {
return teacherScheduleEvaluationRedirectURL;
}
public void setTeacherScheduleEvaluationRedirectURL(String teacherScheduleEvaluationRedirectURL) {
this.teacherScheduleEvaluationRedirectURL = teacherScheduleEvaluationRedirectURL;
}
public String getCareerManagerScheduleEvaluationRedirectURL() {
return careerManagerScheduleEvaluationRedirectURL;
}
public void setCareerManagerScheduleEvaluationRedirectURL(String careerManagerScheduleEvaluationRedirectURL) {
this.careerManagerScheduleEvaluationRedirectURL = careerManagerScheduleEvaluationRedirectURL;
}
public String getAutoEvaluationScheduleEvaluationRedirectURL() {
return autoEvaluationScheduleEvaluationRedirectURL;
}
public void setAutoEvaluationScheduleEvaluationRedirectURL(String autoEvaluationScheduleEvaluationRedirectURL) {
this.autoEvaluationScheduleEvaluationRedirectURL = autoEvaluationScheduleEvaluationRedirectURL;
}
public boolean isPurchaseOrderCodificationEnabled() {
return purchaseOrderCodificationEnabled;
}
public void setPurchaseOrderCodificationEnabled(boolean purchaseOrderCodificationEnabled) {
this.purchaseOrderCodificationEnabled = purchaseOrderCodificationEnabled;
}
public boolean isRetentionForLoanAndAdvance() {
return retentionForLoanAndAdvance;
}
public void setRetentionForLoanAndAdvance(boolean retentionForLoanAndAdvance) {
this.retentionForLoanAndAdvance = retentionForLoanAndAdvance;
}
public boolean getTreasuryDocumentsAuthorizationEnabled() {
return treasuryDocumentsAuthorizationEnabled;
}
public void setTreasuryDocumentsAuthorizationEnabled(boolean treasuryDocumentsAuthorizationEnabled) {
this.treasuryDocumentsAuthorizationEnabled = treasuryDocumentsAuthorizationEnabled;
}
public boolean getPayablesDocumentsAuthorizationEnabled() {
return payablesDocumentsAuthorizationEnabled;
}
public void setPayablesDocumentsAuthorizationEnabled(boolean payablesDocumentsAuthorizationEnabled) {
this.payablesDocumentsAuthorizationEnabled = payablesDocumentsAuthorizationEnabled;
}
public boolean getContractModificationAuthorization() {
return contractModificationAuthorization;
}
public void setContractModificationAuthorization(boolean contractModificationAuthorization) {
this.contractModificationAuthorization = contractModificationAuthorization;
}
public boolean getContractModificationCode() {
return contractModificationCode;
}
public void setContractModificationCode(boolean contractModificationCode) {
this.contractModificationCode = contractModificationCode;
}
public boolean getBasicBasedChristmasPayroll() {
return basicBasedChristmasPayroll;
}
public void setBasicBasedChristmasPayroll(boolean basicBasedChristmasPayroll) {
this.basicBasedChristmasPayroll = basicBasedChristmasPayroll;
}
public BigDecimal getHrsWorkingDay() {
return hrsWorkingDay;
}
public void setHrsWorkingDay(BigDecimal hrsWorkingDay) {
this.hrsWorkingDay = hrsWorkingDay;
}
public String getCashBoxDocumentTypeCode() {
return cashBoxDocumentTypeCode;
}
public void setCashBoxDocumentTypeCode(String cashBoxDocumentTypeCode) {
this.cashBoxDocumentTypeCode = cashBoxDocumentTypeCode;
}
public PayableDocumentType getCashBoxDocumentType() {
return cashBoxDocumentType;
}
public void setCashBoxDocumentType(PayableDocumentType cashBoxDocumentType) {
this.cashBoxDocumentType = cashBoxDocumentType;
setCashBoxDocumentTypeCode(cashBoxDocumentType != null ? cashBoxDocumentType.getDocumentType() : null);
}
public JobCategory getJobCategoryDLH() {
return jobCategoryDLH;
}
public void setJobCategoryDLH(JobCategory jobCategoryDLH) {
this.jobCategoryDLH = jobCategoryDLH;
}
public JobCategory getJobCategoryDTH() {
return jobCategoryDTH;
}
public void setJobCategoryDTH(JobCategory jobCategoryDTH) {
this.jobCategoryDTH = jobCategoryDTH;
}
public KindOfSalary getKindOfSalaryDLH() {
return kindOfSalaryDLH;
}
public void setKindOfSalaryDLH(KindOfSalary kindOfSalaryDLH) {
this.kindOfSalaryDLH = kindOfSalaryDLH;
}
public KindOfSalary getKindOfSalaryDTH() {
return kindOfSalaryDTH;
}
public void setKindOfSalaryDTH(KindOfSalary kindOfSalaryDTH) {
this.kindOfSalaryDTH = kindOfSalaryDTH;
}
public CostCenter getExchangeRateBalanceCostCenter() {
return exchangeRateBalanceCostCenter;
}
public void setExchangeRateBalanceCostCenter(CostCenter exchangeRateBalanceCostCenter) {
this.exchangeRateBalanceCostCenter = exchangeRateBalanceCostCenter;
setCostCenterCode(exchangeRateBalanceCostCenter != null ? exchangeRateBalanceCostCenter.getCode() : null);
}
public String getCostCenterCode() {
return costCenterCode;
}
public void setCostCenterCode(String costCenterCode) {
this.costCenterCode = costCenterCode;
}
public CashAccount getDepositInTransitForeignCurrencyAccount() {
return depositInTransitForeignCurrencyAccount;
}
public void setDepositInTransitForeignCurrencyAccount(CashAccount depositInTransitForeignCurrencyAccount) {
this.depositInTransitForeignCurrencyAccount = depositInTransitForeignCurrencyAccount;
if (null != depositInTransitForeignCurrencyAccount) {
depositInTransitForeignCurrencyAccountCode = depositInTransitForeignCurrencyAccount.getAccountCode();
}
}
public CashAccount getDepositInTransitNationalCurrencyAccount() {
return depositInTransitNationalCurrencyAccount;
}
public void setDepositInTransitNationalCurrencyAccount(CashAccount depositInTransitNationalCurrencyAccount) {
this.depositInTransitNationalCurrencyAccount = depositInTransitNationalCurrencyAccount;
if (null != depositInTransitNationalCurrencyAccount) {
depositInTransitNationalCurrencyAccountCode = depositInTransitNationalCurrencyAccount.getAccountCode();
}
}
public String getDepositInTransitForeignCurrencyAccountCode() {
return depositInTransitForeignCurrencyAccountCode;
}
public void setDepositInTransitForeignCurrencyAccountCode(String depositInTransitForeignCurrencyAccountCode) {
this.depositInTransitForeignCurrencyAccountCode = depositInTransitForeignCurrencyAccountCode;
}
public String getDepositInTransitNationalCurrencyAccountCode() {
return depositInTransitNationalCurrencyAccountCode;
}
public void setDepositInTransitNationalCurrencyAccountCode(String depositInTransitNationalCurrencyAccountCode) {
this.depositInTransitNationalCurrencyAccountCode = depositInTransitNationalCurrencyAccountCode;
}
public String getWarehouseNationalCurrencyTransientAccount1Code() {
return warehouseNationalCurrencyTransientAccount1Code;
}
public void setWarehouseNationalCurrencyTransientAccount1Code(String warehouseNationalCurrencyTransientAccount1Code) {
this.warehouseNationalCurrencyTransientAccount1Code = warehouseNationalCurrencyTransientAccount1Code;
}
public CashAccount getWarehouseNationalCurrencyTransientAccount1() {
return warehouseNationalCurrencyTransientAccount1;
}
public void setWarehouseNationalCurrencyTransientAccount1(CashAccount warehouseNationalCurrencyTransientAccount1) {
this.warehouseNationalCurrencyTransientAccount1 = warehouseNationalCurrencyTransientAccount1;
}
@Override
public String toString() {
return "CompanyConfiguration{" +
"companyNumber='" + companyNumber + '\'' +
", balanceExchangeRateAccountCode='" + balanceExchangeRateAccountCode + '\'' +
", balanceExchangeRateAccount=" + balanceExchangeRateAccount +
", version=" + version +
'}';
}
public String getWarehouseNationalCurrencyTransientAccount2Code() {
return warehouseNationalCurrencyTransientAccount2Code;
}
public void setWarehouseNationalCurrencyTransientAccount2Code(String warehouseNationalCurrencyTransientAccount2Code) {
this.warehouseNationalCurrencyTransientAccount2Code = warehouseNationalCurrencyTransientAccount2Code;
}
public CashAccount getWarehouseNationalCurrencyTransientAccount2() {
return warehouseNationalCurrencyTransientAccount2;
}
public void setWarehouseNationalCurrencyTransientAccount2(CashAccount warehouseNationalCurrencyTransientAccount2) {
this.warehouseNationalCurrencyTransientAccount2 = warehouseNationalCurrencyTransientAccount2;
}
public FinanceUser getDefaultAccountancyUserProduction() {
return defaultAccountancyUserProduction;
}
public void setDefaultAccountancyUserProduction(FinanceUser defaultAccountancyUserProduction) {
this.defaultAccountancyUserProduction = defaultAccountancyUserProduction;
}
public double getUnitPriceMilk() {
return unitPriceMilk;
}
public void setUnitPriceMilk(double unitPriceMilk) {
this.unitPriceMilk = unitPriceMilk;
}
public double getIt() {
return it;
}
public void setIt(double it) {
this.it = it;
}
public double getIue() {
return iue;
}
public void setIue(double iue) {
this.iue = iue;
}
} | gpl-3.0 |
pacoqueen/cican | formularios/graficas/graph_test.py | 3985 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (C) 2008-2010 Francisco José Rodríguez Bogado #
# <[email protected]> #
# #
# 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/>. #
# #
###############################################################################
'''
Created on 18/05/2010
@author: bogado
Un par de pruebas con las gráficas de hamster-applet.
'''
import gtk
import charting
class BasicWindow:
"""
# PyUML: Do not remove this line! # XMI_ID:_XW0G0u5DEd-QvZvwvxUy6Q
"""
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(600, 500)
window.connect("delete_event", lambda *args: gtk.main_quit())
contenedor = gtk.VBox()
## Gráfica de barras horizontales
claves = ["uno", "dos", "tres", "¡catorce!"]
valores = [1, 2, 3, 14]
self.grafica1 = charting.add_grafica_barras_horizontales(contenedor,
claves,
valores)
## Gráfica de rangos horizontales
import random
valores = []
for clave in claves:
rango_clave = []
for i in xrange(random.randrange(1, 3)):
rango = [random.random(), random.random()]
rango.sort()
rango = tuple([v * 60 * 24 for v in rango])
rango_clave.append(rango)
valores.append(rango_clave)
self.grafica2 = charting.add_grafica_rangos(contenedor, claves, valores)
## Gráfica de barras verticales
montones = ["x", "y", "z"]
colores = dict([(stack, None) for stack in montones])
valores = [[random.randint(0, 10) for j in range(len(montones))]
for i in range(len(claves))]
self.grafica3 = charting.add_grafica_barras_verticales(contenedor,
claves, valores, montones, colores,
ver_botones_colores = True)
## Gráfica "simple"
data = iter([["Beatrix Kiddo", 1],
["Bill", 1],
["Budd", 1],
["Elle Driver", 0],
["Vernita Green", 0],
["O-Ren Ishii", 0]])
claves = []
valores = []
for c, v in data:
claves.append(c)
valores.append(v)
self.grafica4 = charting.add_grafica_simple(contenedor, claves,
valores)
##
window.add(contenedor)
window.show_all()
def main():
BasicWindow()
gtk.main()
if __name__ == "__main__":
main()
| gpl-3.0 |
fca1/openpnp | src/main/java/org/openpnp/gui/components/reticle/PackageReticle.java | 3250 | /*
* Copyright (C) 2011 Jason von Nieda <[email protected]>
*
* 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.components.reticle;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import org.openpnp.model.Footprint;
import org.openpnp.model.Length;
import org.openpnp.model.LengthUnit;
public class PackageReticle implements Reticle {
private Color color;
private org.openpnp.model.Package pkg;
public PackageReticle(org.openpnp.model.Package pkg) {
setPkg(pkg);
setColor(Color.red);
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public org.openpnp.model.Package getPkg() {
return pkg;
}
public void setPkg(org.openpnp.model.Package pkg) {
this.pkg = pkg;
}
@Override
public void draw(Graphics2D g2d, LengthUnit cameraUnitsPerPixelUnits,
double cameraUnitsPerPixelX, double cameraUnitsPerPixelY, double viewPortCenterX,
double viewPortCenterY, int viewPortWidth, int viewPortHeight, double rotation) {
g2d.setStroke(new BasicStroke(1f));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(color);
Footprint footprint = pkg.getFootprint();
if (footprint == null) {
return;
}
Shape shape = footprint.getShape();
if (shape == null) {
return;
}
// Determine the scaling factor to go from Outline units to
// Camera units.
Length l = new Length(1, footprint.getUnits());
l = l.convertToUnits(cameraUnitsPerPixelUnits);
double unitScale = l.getValue();
// Create a transform to scale the Shape by
AffineTransform tx = new AffineTransform();
tx.translate(viewPortCenterX, viewPortCenterY);
// AffineTransform rotates positive clockwise, so we invert the value.
tx.rotate(Math.toRadians(-rotation));
// First we scale by units to convert the units and then we scale
// by the camera X and Y units per pixels to get pixel locations.
tx.scale(unitScale, unitScale);
tx.scale(1.0 / cameraUnitsPerPixelX, 1.0 / cameraUnitsPerPixelY);
// Transform the Shape and draw it out.
shape = tx.createTransformedShape(shape);
g2d.fill(shape);
}
}
| gpl-3.0 |
CognutSecurity/webdemo | orm/Users.py | 518 | '''
Data Model for registered Users
Author: Huang Xiao
Group: Cognitive Security Technologies
Institute: Fraunhofer AISEC
Mail: [email protected]
Copyright@2017
'''
from peewee import CharField, DateTimeField, Model
class User(Model):
'''
Data Model for registered User
'''
username = CharField(null=False, unique=True)
password = CharField(null=False)
email = CharField(null=False)
join_date = DateTimeField(null=False)
class Meta:
order_by = ('join_date',)
| gpl-3.0 |
mbshopM/openconcerto | OpenConcerto/src/org/openconcerto/sql/navigator/RowsSQLListModel.java | 4160 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
/*
* Créé le 21 mai 2005
*/
package org.openconcerto.sql.navigator;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.IResultSetHandler;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTableEvent;
import org.openconcerto.sql.model.SQLTableModifiedListener;
import org.openconcerto.sql.model.Where;
import java.util.List;
import java.util.Set;
import org.apache.commons.dbutils.ResultSetHandler;
public class RowsSQLListModel extends SQLListModel<SQLRow> implements SQLTableModifiedListener {
private final SQLElement element;
private final ResultSetHandler handler;
public RowsSQLListModel(SQLElement element) {
super();
this.element = element;
this.handler = new SQLRowListRSH(this.getElement().getTable(), true);
this.getElement().getTable().addTableModifiedListener(this);
}
@Override
protected void reload(final boolean noCache) {
final Set<Number> ids = getIds();
final SQLField key = this.getElement().getParentForeignField();
final SQLSelect sel = new SQLSelect();
sel.addSelectStar(this.getElement().getTable());
sel.addOrderSilent(this.getElement().getTable().getName());
// si null pas de where, on montre tout
if (ids != null && key != null) {
sel.setWhere(new Where(key, ids));
}
final SQLDataSource source = this.getElement().getTable().getBase().getDataSource();
// cannot just use a SwingWorker, cause some methods (like SQLBrowser#selectPath())
// expect reload() to by synchronous.
@SuppressWarnings("unchecked")
final List<SQLRow> rows = (List<SQLRow>) source.execute(sel.asString(), new IResultSetHandler(this.handler) {
@Override
public boolean readCache() {
return !noCache;
}
@Override
public boolean writeCache() {
return true;
}
});
this.setAll(rows);
}
/**
* Search the row with the passed <code>id</code> and return its index.
*
* @param id an ID of a SQLRow.
* @return the index of the SQLRow or -1 if none is found.
*/
public int indexFromID(int id) {
for (int i = 0; i < this.getDisplayedItems().size(); i++) {
final SQLRow row = this.getDisplayedItems().get(i);
if (row != this.getALLValue() && row.getID() == id)
return i;
}
return -1;
}
protected String toString(SQLRow item) {
return this.getElement().getDescription(item);
}
public final SQLElement getElement() {
return this.element;
}
@Override
public void tableModified(SQLTableEvent evt) {
// TODO test if that concern us
this.reload();
}
public String toString() {
return this.getClass().getName() + " on " + this.getElement();
}
protected void die() {
this.getElement().getTable().removeTableModifiedListener(this);
}
@Override
protected void idsChanged() {
this.reload();
}
@Override
protected boolean hasALLValue() {
return true;
}
}
| gpl-3.0 |
TesfayKidane/mum-mpp | Lab05/src/mum/mpp/lab08/problem04/Weak.java | 1017 | package mum.mpp.lab08.problem04;
import java.util.ArrayList;
import java.util.List;
/** Java 7 way of counting number of names that start with 'N' */
public class Weak {
public static void main(final String[] args) {
Weak w = new Weak();
System.out.println(String.format("Friends with names that start"
+ " with 'N': "+ w.findStartsWithLetterToUpper(Folks.friends, 'N')));
System.out.println(String.format("Editors with names that start"
+ " with 'N': " + w.findStartsWithLetterToUpper(Folks.editors, 'N')));
System.out.println(String.format("Friends with names that start"
+ " with 'S': " + w.findStartsWithLetterToUpper(Folks.friends, 'S')));
}
public List<String> findStartsWithLetterToUpper(List<String> list, char c) {
List<String> startsWithLetter = new ArrayList<String>();
for(String name : list) {
if(name.startsWith(""+c)) {
startsWithLetter.add(name.toUpperCase());
}
}
return startsWithLetter;
}
}
| gpl-3.0 |
jhtan/cp | uva/12149/main.cpp | 371 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef set<int> si;
typedef map<string, int> msi;
int main() {
int n; scanf("%d", &n);
while(n) {
printf("%d\n", (n*(n+1)*(2*n+1))/6);
scanf("%d", &n);
}
return 0;
}
| gpl-3.0 |
sssfire/com.sun.examples | spring.basic/src/main/java/com/sun/example/activemq/topic/Publisher.java | 3877 | package com.sun.example.activemq.topic;
import java.util.Hashtable;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQMapMessage;
/**
* 1. 使用Topic方式
* (1)Publish - Subscribe 消息发布订阅机制
* (2)topic数据默认不会存储,是无状态的。
* (3)并不保证publisher发布的每条消息,subscriber都可以接收到。只有正在监听该topic地址的subscriber能够接收到消息。
* (4)一对多的消息发布接受策略,监听同一个topic地址的多个subscribe都可以接收到,并通知MQ服务器
*
*/
public class Publisher {
protected int MAX_DELTA_PERCENT = 1;
protected Map<String, Double> LAST_PRICES = new Hashtable<String, Double>();
protected static int count = 10;
protected static int total;
protected static String brokerURL = "tcp://localhost:61616";
protected static transient ConnectionFactory factory;
protected transient Connection connection;
protected transient Session session;
protected transient MessageProducer producer;
public Publisher() throws JMSException {
factory = new ActiveMQConnectionFactory(brokerURL);
connection = factory.createConnection();
try {
connection.start();
} catch (JMSException jmse) {
connection.close();
throw jmse;
}
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(null);
//(可选)设置是否持久化消息
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
public void close() throws JMSException {
if (connection != null) {
connection.close();
}
}
public static void main(String[] args) throws JMSException {
Publisher publisher = new Publisher();
while (total < 1000) {
for (int i = 0; i < count; i++) {
publisher.sendMessage(args);
}
total += count;
System.out.println("Published '" + count + "' of '" + total + "' price messages");
try {
Thread.sleep(1000);
} catch (InterruptedException x) {
}
}
publisher.close();
}
protected void sendMessage(String[] stocks) throws JMSException {
int idx = 0;
while (true) {
idx = (int) Math.round(stocks.length * Math.random());
if (idx < stocks.length) {
break;
}
}
String stock = stocks[idx];
Destination destination = session.createTopic("STOCKS." + stock);
Message message = createStockMessage(stock, session);
System.out.println(
"Sending: " + ((ActiveMQMapMessage) message).getContentMap() + " on destination: " + destination);
producer.send(destination, message);
}
protected Message createStockMessage(String stock, Session session) throws JMSException {
Double value = LAST_PRICES.get(stock);
if (value == null) {
value = new Double(Math.random() * 100);
}
// lets mutate the value by some percentage
double oldPrice = value.doubleValue();
value = new Double(mutatePrice(oldPrice));
LAST_PRICES.put(stock, value);
double price = value.doubleValue();
double offer = price * 1.001;
boolean up = (price > oldPrice);
MapMessage message = session.createMapMessage();
message.setString("stock", stock);
message.setDouble("price", price);
message.setDouble("offer", offer);
message.setBoolean("up", up);
return message;
}
protected double mutatePrice(double price) {
double percentChange = (2 * Math.random() * MAX_DELTA_PERCENT) - MAX_DELTA_PERCENT;
return price * (100 + percentChange) / 100;
}
}
| gpl-3.0 |
open-fidias/db-migration-app | docs/.vuepress/config.js | 599 | module.exports = {
base: '/db-migration-app/',
title: 'DB Migration App',
description: 'Desktop app to migrate databases',
themeConfig: {
repo: 'open-fidias/db-migration-app',
docsDir: 'docs',
editLinks: true,
editLinkText: 'Help us improve this page!',
search: true,
searchMaxSuggestions: 10,
lastUpdated: true,
nav: [
{ text: 'Guide', link: '/guide/' },
{ text: 'Building', link: '/building/' }
]
},
head: [
['link', { rel: 'icon', href: '/img/favicon.png' }],
]
}
| gpl-3.0 |
khan0407/FinalArcade | theme/splash/layout/report.php | 9251 | <?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/>.
/**
* General layout for the splash theme
*
* @package theme_splash
* @copyright 2012 Caroline Kennedy - Synergy Learning
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$hasheading = ($PAGE->heading);
$hasnavbar = (empty($PAGE->layout_options['nonavbar']) && $PAGE->has_navbar());
$hasfooter = (empty($PAGE->layout_options['nofooter']));
$hassidepre = $PAGE->blocks->region_has_content('side-pre', $OUTPUT);
$hassidepost = $PAGE->blocks->region_has_content('side-post', $OUTPUT);
$custommenu = $OUTPUT->custom_menu();
$hascustommenu = (empty($PAGE->layout_options['nocustommenu']) && !empty($custommenu));
splash_check_colourswitch();
splash_initialise_colourswitcher($PAGE);
<<<<<<< HEAD
=======
$courseheader = $coursecontentheader = $coursecontentfooter = $coursefooter = '';
if (empty($PAGE->layout_options['nocourseheaderfooter'])) {
$courseheader = $OUTPUT->course_header();
$coursecontentheader = $OUTPUT->course_content_header();
if (empty($PAGE->layout_options['nocoursefooter'])) {
$coursecontentfooter = $OUTPUT->course_content_footer();
$coursefooter = $OUTPUT->course_footer();
}
}
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
$bodyclasses = array();
$bodyclasses[] = 'splash-'.splash_get_colour();
if ($hassidepre && !$hassidepost) {
$bodyclasses[] = 'side-pre-only';
} else if ($hassidepost && !$hassidepre) {
$bodyclasses[] = 'side-post-only';
} else if (!$hassidepost && !$hassidepre) {
$bodyclasses[] = 'content-only';
}
$haslogo = (!empty($PAGE->theme->settings->logo));
$hasfootnote = (!empty($PAGE->theme->settings->footnote));
$hidetagline = (!empty($PAGE->theme->settings->hide_tagline) && $PAGE->theme->settings->hide_tagline == 1);
if (!empty($PAGE->theme->settings->tagline)) {
$tagline = $PAGE->theme->settings->tagline;
} else {
$tagline = get_string('defaulttagline', 'theme_splash');
}
echo $OUTPUT->doctype() ?>
<html <?php echo $OUTPUT->htmlattributes() ?>>
<head>
<title><?php echo $PAGE->title ?></title>
<link rel="shortcut icon" href="<?php echo $OUTPUT->pix_url('favicon', 'theme')?>" />
<meta name="description" content="<?php p(strip_tags(format_text($SITE->summary, FORMAT_HTML))) ?>" />
<?php echo $OUTPUT->standard_head_html() ?>
</head>
<body id="<?php p($PAGE->bodyid) ?>" class="<?php p($PAGE->bodyclasses.' '.join(' ', $bodyclasses)) ?>">
<?php echo $OUTPUT->standard_top_of_body_html() ?>
<div id="page">
<?php if ($hasheading || $hasnavbar) { ?>
<div id="page-header">
<div id="page-header-wrapper" class="wrapper clearfix">
<?php
if ($hasheading) { ?>
<div id="headermenu">
<?php
if (isloggedin()) {
echo html_writer::start_tag('div', array('id'=>'userdetails'));
echo html_writer::tag('h1', get_string('usergreeting', 'theme_splash', $USER->firstname));
echo html_writer::start_tag('p', array('class'=>'prolog'));
echo html_writer::link(new moodle_url('/user/profile.php', array('id'=>$USER->id)),
get_string('myprofile')).' | ';
echo html_writer::link(new moodle_url('/login/logout.php', array('sesskey'=>sesskey())),
get_string('logout'));
echo html_writer::end_tag('p');
echo html_writer::end_tag('div');
echo html_writer::tag('div', $OUTPUT->user_picture($USER, array('size'=>55)), array('class'=>'userimg'));
} else {
echo html_writer::start_tag('div', array('id'=>'userdetails_loggedout'));
$loginlink = html_writer::link(new moodle_url('/login/'), get_string('loginhere', 'theme_splash'));
echo html_writer::tag('h1', get_string('welcome', 'theme_splash', $loginlink));
echo html_writer::end_tag('div');
} ?>
<div class="clearer"></div>
<div id="colourswitcher">
<ul>
<li><img src="<?php echo $OUTPUT->pix_url('colour', 'theme'); ?>" alt="colour" /></li>
<li><a href="<?php echo new moodle_url($PAGE->url, array('splashcolour'=>'red')); ?>" class="styleswitch
colour-red"><img src="<?php echo $OUTPUT->pix_url('red-theme2', 'theme'); ?>" alt="red" /></a></li>
<li><a href="<?php echo new moodle_url($PAGE->url, array('splashcolour'=>'green')); ?>"
class="styleswitch colour-green"><img src="<?php echo $OUTPUT->pix_url('green-theme2', 'theme'); ?>"
alt="green" /></a></li>
<li><a href="<?php echo new moodle_url($PAGE->url, array('splashcolour'=>'blue')); ?>"
class="styleswitch colour-blue"><img src="<?php echo $OUTPUT->pix_url('blue-theme2', 'theme'); ?>"
alt="blue" /></a></li>
<li><a href="<?php echo new moodle_url($PAGE->url, array('splashcolour'=>'orange')); ?>"
class="styleswitch colour-orange"><img src="<?php echo $OUTPUT->pix_url('orange-theme2', 'theme');
?>"
alt="orange" /></a></li>
</ul>
</div>
<?php
if (!empty($PAGE->layout_options['langmenu'])) {
echo $OUTPUT->lang_menu();
}
echo $PAGE->headingmenu
?>
</div>
<div id="logobox">
<?php
if ($haslogo) {
echo html_writer::link(new moodle_url('/'), "<img src='".$PAGE->theme->settings->logo."' alt='logo' />");
} else {
echo html_writer::link(new moodle_url('/'), $PAGE->heading, array('class'=>'nologoimage'));
} ?>
<?php
if (!$hidetagline) { ?>
<h4><?php echo $tagline ?></h4>
<?php
} ?>
</div>
<div class="clearer"></div>
<?php
if ($haslogo) { ?>
<h4 class="headermain inside"> </h4>
<?php
} else { ?>
<h4 class="headermain inside"><?php echo $PAGE->heading ?></h4>
<?php
} ?>
<?php
} // End of if ($hasheading)?>
<!-- CUSTOMMENU -->
<div class="clearer"></div>
<?php
if ($hascustommenu) { ?>
<div id="moodlemenu">
<div id="custommenu"><?php echo $custommenu; ?></div>
</div>
<?php
} ?>
<!-- END CUSTOMMENU -->
<<<<<<< HEAD
=======
<?php if (!empty($courseheader)) { ?>
<div id="course-header"><?php echo $courseheader; ?></div>
<?php } ?>
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
<div class="navbar">
<div class="wrapper clearfix">
<div class="breadcrumb">
<?php
if ($hasnavbar) {
echo $OUTPUT->navbar();
} ?>
</div>
<div class="navbutton"> <?php echo $PAGE->button; ?></div>
</div>
</div>
</div>
</div>
<?php
} // if ($hasheading || $hasnavbar) ?>
<!-- END OF HEADER -->
<!-- START OF CONTENT -->
<div id="page-content" class="clearfix">
<div id="report-main-content">
<div class="region-content">
<<<<<<< HEAD
<?php echo $OUTPUT->main_content() ?>
=======
<?php echo $coursecontentheader; ?>
<?php echo $OUTPUT->main_content() ?>
<?php echo $coursecontentfooter; ?>
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
</div>
</div>
<?php if ($hassidepre) { ?>
<div id="report-region-wrap">
<div id="report-region-pre" class="block-region">
<div class="region-content">
<?php echo $OUTPUT->blocks_for_region('side-pre') ?>
</div>
</div>
</div>
<?php
} ?>
</div>
<!-- END OF CONTENT -->
<<<<<<< HEAD
=======
<?php if (!empty($coursefooter)) { ?>
<div id="course-footer"><?php echo $coursefooter; ?></div>
<?php } ?>
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
<div class="clearfix"></div>
<!-- END OF #Page -->
</div>
<!-- START OF FOOTER -->
<?php if ($hasfooter) { ?>
<div id="page-footer">
<div id="footer-wrapper">
<?php
if ($hasfootnote) { ?>
<div id="footnote"><?php echo $PAGE->theme->settings->footnote; ?></div>
<?php
} ?>
<p class="helplink"><?php echo page_doc_link(get_string('moodledocslink')) ?></p>
<?php
echo $OUTPUT->login_info();
echo $OUTPUT->home_link();
echo $OUTPUT->standard_footer_html();
?>
</div>
</div>
<?php
} ?>
<?php echo $OUTPUT->standard_end_of_body_html() ?>
</body>
</html>
| gpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.