repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
|---|---|---|---|---|
Intermesh/groupoffice-server
|
lib/IFW.php
|
613
|
<?php
use IFW\App;
/**
* Global IFW class with static functions to access the application instance.
*
* eg. IFW::app()->config() access the application configuration
*/
class IFW {
private static $app;
/**
* Register the application instance
*
* @param App $app
* @throws Exception
*/
public static function setApp(App $app) {
if(isset(self::$app)){
throw new Exception("You can only register one application");
}
self::$app = $app;
}
/**
* Get the application instance
*
* @return \IFW\Web\App|IFW\Cli\App
*/
public static function app() {
return self::$app;
}
}
|
agpl-3.0
|
Linaro/lava-server
|
lava_results_app/views/chart/forms.py
|
2583
|
# Copyright (C) 2015 Linaro Limited
#
# Author: Stevan Radakovic <stevan.radakovic@linaro.org>
#
# This file is part of Lava Server.
#
# Lava Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software Foundation
#
# Lava Server 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 Affero General Public License
# along with Lava Server. If not, see <http://www.gnu.org/licenses/>.
from django import forms
from lava_results_app.models import (
Chart,
ChartQuery,
ChartQueryUser,
TestCase,
)
class ChartForm(forms.ModelForm):
class Meta:
model = Chart
exclude = ('is_published', 'chart_group', 'group', 'queries')
widgets = {'owner': forms.HiddenInput}
def __init__(self, owner, *args, **kwargs):
super(ChartForm, self).__init__(*args, **kwargs)
def save(self, commit=True, **kwargs):
instance = super(ChartForm, self).save(commit=commit, **kwargs)
return instance
class ChartQueryForm(forms.ModelForm):
class Meta:
model = ChartQuery
exclude = ()
widgets = {'chart': forms.HiddenInput,
'query': forms.HiddenInput,
'relative_index': forms.HiddenInput}
def __init__(self, user, *args, **kwargs):
super(ChartQueryForm, self).__init__(*args, **kwargs)
def save(self, commit=True, **kwargs):
instance = super(ChartQueryForm, self).save(commit=commit, **kwargs)
return instance
def clean(self):
form_data = self.cleaned_data
try:
# Chart type validation.
if form_data["query"].content_type.model_class() == TestCase and \
form_data["chart_type"] == "pass/fail":
self.add_error(
"chart_type",
"Pass/fail is incorrect value for 'chart_type' with TestCase based queries.")
except KeyError:
# form_data will pick up the rest of validation errors.
pass
return form_data
class ChartQueryUserForm(forms.ModelForm):
class Meta:
model = ChartQueryUser
exclude = ['user', 'chart_query']
def __init__(self, user, *args, **kwargs):
super(ChartQueryUserForm, self).__init__(*args, **kwargs)
|
agpl-3.0
|
gamchantoi/AgroSHop-UTUAWARDS
|
var/cache/production_201510221322/templates/frontend_Responsive_id_ID_1/97/7c/fe/977cfeb9bb070320a1c6f58c27362cf6c3284590.snippet.facet-value-list.tpl.php
|
5114
|
<?php /* Smarty version Smarty-3.1.12, created on 2015-11-09 19:00:26
compiled from "/home/gam/themes/Frontend/Bare/frontend/listing/filter/facet-value-list.tpl" */ ?>
<?php /*%%SmartyHeaderCode:11956854235640df3a270b21-87257079%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'977cfeb9bb070320a1c6f58c27362cf6c3284590' =>
array (
0 => '/home/gam/themes/Frontend/Bare/frontend/listing/filter/facet-value-list.tpl',
1 => 1445520152,
2 => 'file',
),
),
'nocache_hash' => '11956854235640df3a270b21-87257079',
'function' =>
array (
),
'variables' =>
array (
'facet' => 0,
'option' => 0,
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.12',
'unifunc' => 'content_5640df3a37bfc8_73766854',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_5640df3a37bfc8_73766854')) {function content_5640df3a37bfc8_73766854($_smarty_tpl) {?>
<div class="filter-panel filter--property facet--<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFacetName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?>
"
data-filter-type="value-list"
data-field-name="<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?>
">
<div class="filter-panel--flyout">
<label class="filter-panel--title">
<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getLabel(), ENT_QUOTES, 'utf-8', true);?>
</label>
<span class="filter-panel--icon"></span>
<div class="filter-panel--content">
<ul class="filter-panel--option-list">
<?php $_smarty_tpl->tpl_vars['option'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['option']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['facet']->value->getValues(); if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['option']->key => $_smarty_tpl->tpl_vars['option']->value){
$_smarty_tpl->tpl_vars['option']->_loop = true;
?>
<li class="filter-panel--option">
<div class="option--container">
<span class="filter-panel--checkbox">
<input type="checkbox"
id="__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?>
__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?>
"
name="__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?>
__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?>
"
value="<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?>
"
<?php if ($_smarty_tpl->tpl_vars['option']->value->isActive()){?>checked="checked" <?php }?>/>
<span class="checkbox--state"> </span>
</span>
<label class="filter-panel--label"
for="__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?>
__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?>
">
<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getLabel(), ENT_QUOTES, 'utf-8', true);?>
</label>
</div>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
<?php }} ?>
|
agpl-3.0
|
AndranikMarkosyan/lms
|
app/controllers/provisional_grades_controller.rb
|
8598
|
#
# Copyright (C) 2011 - 2015 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# @API Moderated Grading
# @subtopic Provisional Grades
# @beta
#
# API for manipulating provisional grades
#
# Provisional grades are created by using the Submissions API endpoint "Grade or comment on a submission" with `provisional=true`.
# They can be viewed by using "List assignment submissions", "Get a single submission", or "List gradeable students" with `include[]=provisional_grades`.
# This API performs other operations on provisional grades for use with the Moderated Grading feature.
#
# @model ProvisionalGrade
# {
# "id": "ProvisionalGrade",
# "description": "",
# "properties": {
# "provisional_grade_id": {
# "description": "The identifier for the provisional grade",
# "example": 23,
# "type": "integer"
# },
# "score": {
# "description": "The numeric score",
# "example": 90,
# "type": "integer"
# },
# "grade": {
# "description": "The grade",
# "example": "A-",
# "type": "string"
# },
# "grade_matches_current_submission": {
# "description": "Whether the grade was applied to the most current submission (false if the student resubmitted after grading)",
# "example": true,
# "type": "boolean"
# },
# "graded_at": {
# "description": "When the grade was given",
# "example": "2015-11-01T00:03:21-06:00",
# "type": "datetime"
# },
# "final": {
# "description": "Whether this is the 'final' provisional grade created by the moderator",
# "example": false,
# "type": "boolean"
# },
# "speedgrader_url": {
# "description": "A link to view this provisional grade in SpeedGrader™",
# "example": "http://www.example.com/courses/123/gradebook/speed_grader?...",
# "type": "string"
# }
# }
# }
class ProvisionalGradesController < ApplicationController
before_filter :require_user
before_filter :load_assignment
include Api::V1::Submission
# @API Show provisional grade status for a student
#
# @argument student_id [Integer]
# The id of the student to show the status for
#
# @example_request
#
# curl 'https://<canvas>/api/v1/courses/1/assignments/2/provisional_status?student_id=1' \
# -X POST
#
# @example_response
#
# { "needs_provisional_grade": false }
#
def status
if authorized_action(@context, @current_user, [:manage_grades, :view_all_grades])
unless @context.feature_enabled?(:moderated_grading) && @assignment.moderated_grading?
return render :json => { :message => "Assignment does not use moderated grading" }, :status => :bad_request
end
if @assignment.grades_published?
return render :json => { :message => "Assignment grades have already been published" }, :status => :bad_request
end
# in theory we could apply visibility here, but for now we would rather be performant
# e.g. @assignment.students_with_visibility(@context.students_visible_to(@current_user)).find(params[:student_id])
student = @context.students.find(params[:student_id])
render :json => { :needs_provisional_grade => @assignment.student_needs_provisional_grade?(student) }
end
end
# @API Select provisional grade
#
# Choose which provisional grade the student should receive for a submission.
# The caller must have :moderate_grades rights.
#
# @example_response
# {
# "assignment_id": 867,
# "student_id": 5309,
# "selected_provisional_grade_id": 53669
# }
#
def select
if authorized_action(@context, @current_user, :moderate_grades)
pg = @assignment.provisional_grades.find(params[:provisional_grade_id])
selection = @assignment.moderated_grading_selections.where(student_id: pg.submission.user_id).first
return render :json => { :message => 'student not in moderation set' }, :status => :bad_request unless selection
selection.provisional_grade = pg
selection.save!
render :json => selection.as_json(:include_root => false, :only => %w(assignment_id student_id selected_provisional_grade_id))
end
end
# @API Copy provisional grade
#
# Given a provisional grade, copy the grade (and associated submission comments and rubric assessments)
# to a "final" mark which can be edited or commented upon by a moderator prior to publication of grades.
#
# Notes:
# * The student must be in the moderation set for the assignment.
# * The newly created grade will be selected.
# * The caller must have "Moderate Grades" rights in the course.
#
# @returns ProvisionalGrade
def copy_to_final_mark
if authorized_action @context, @current_user, :moderate_grades
pg = @assignment.provisional_grades.find(params[:provisional_grade_id])
return render :json => { :message => 'provisional grade is already final' }, :status => :bad_request if pg.final
selection = @assignment.moderated_grading_selections.where(student_id: pg.submission.user_id).first
return render :json => { :message => 'student not in moderation set' }, :status => :bad_request unless selection
final_mark = pg.copy_to_final_mark!(@current_user)
selection.provisional_grade = final_mark
selection.save!
render :json => provisional_grade_json(final_mark, pg.submission, @assignment, @current_user, %w(submission_comments rubric_assessment))
end
end
# @API Publish provisional grades for an assignment
#
# Publish the selected provisional grade for all submissions to an assignment.
# Use the "Select provisional grade" endpoint to choose which provisional grade to publish
# for a particular submission.
#
# Students not in the moderation set will have their one and only provisional grade published.
#
# WARNING: This is irreversible. This will overwrite existing grades in the gradebook.
#
# @example_request
#
# curl 'https://<canvas>/api/v1/courses/1/assignments/2/provisional_grades/publish' \
# -X POST
#
def publish
if authorized_action(@context, @current_user, :moderate_grades)
unless @context.feature_enabled?(:moderated_grading) && @assignment.moderated_grading?
return render :json => { :message => "Assignment does not use moderated grading" }, :status => :bad_request
end
if @assignment.grades_published?
return render :json => { :message => "Assignment grades have already been published" }, :status => :bad_request
end
submissions = @assignment.submissions.preload(:all_submission_comments,
{ :provisional_grades => :rubric_assessments })
selections = @assignment.moderated_grading_selections.index_by(&:student_id)
submissions.each do |submission|
if (selection = selections[submission.user_id])
# student in moderation: choose the selected provisional grade
selected_provisional_grade = submission.provisional_grades
.detect { |pg| pg.id == selection.selected_provisional_grade_id }
else
# student not in moderation: choose the first one with a grade (there should only be one)
selected_provisional_grade = submission.provisional_grades
.select { |pg| pg.graded_at.present? }
.sort_by { |pg| pg.created_at }
.first
end
if selected_provisional_grade
selected_provisional_grade.publish!
end
end
@assignment.update_attribute(:grades_published_at, Time.now.utc)
render :json => { :message => "OK" }
end
end
private
def load_assignment
@context = api_find(Course, params[:course_id])
@assignment = @context.assignments.active.find(params[:assignment_id])
end
end
|
agpl-3.0
|
culturagovbr/CEUs
|
www/includes/JsLibrary/css/tabelaTarefaNotIE.css
|
2104
|
body
{
}
#listaTarefas table.tabelaTarefas
{
width: 95%;
padding: 1px;
border-spacing: 1px;
border: 1px;
border-color: #DDDDAA;
border-style: solid;
background-color: #dcdcdc;
border-collapse:
}
#conteudoTarefas
{
width: 95%;
overflow: auto;
height: 450px;
border: 1px;
border-color: #DDDDAA;
border-style: solid;
}
#conteudoTarefas table.tabelaTarefas
{
width: 99.9%;
padding: 1px;
border-spacing: 1px;
border: 0px;
border-color: #DDDDAA;
border-style: solid;
background-color: #dcdcdc;
}
.tabelaTarefas th
{
font-size: 11px;
}
.tabelaTarefas td
{
text-align: center;
}
.tabelaTarefas div
{
}
.tarefasFilhas
{
display: none;
}
.MacroEtapa span
{
font-weight: bold;
}
.MacroEtapa span
{
font-weight: bold;
}
.tarefasFilhasAberto
{
}
.tarefasFilhasFechado
{
}
.MacroEtapa .tarefaMais
{
cursor: pointer;
}
.Etapa .tarefaMais img
{
visibility: hidden;
}
.Etapa .gantt img
{
visibility: hidden;
}
.tarefaMais span
{
width: 15px;
white-space: nowrap;
}
.OrigemEspecial .imagemPPA
{
visibility: visible;
}
.OrigemComum .imagemPPA
{
visibility: hidden;
}
.tarefaOrdem
{
width: 90px;
}
.tarefaTipo
{
width: 40px;
}
.tarefaNome
{
width: 30%;
}
td.tarefaNome
{
text-align: left;
}
.tarefaDescricao
{
width: 250px;
}
.tarefaSituacao
{
width: 80px;
}
.tarefaInicio , .tarefaTermino
{
width: 90px;
}
.tarefaAprovada
{
width: 75px;
}
.tarefaFechada
{
width: 75px;
}
.inputActiveFrozenField
{
width: 100%;
background-color: #EEEEEE;
}
.activeFrozenFieldEnabled
{
cursor: pointer;
color: #6F6FFF;
}
.activeFrozenFieldDisable
{
color: #A5A5A5;
cursor: wait;
}
.subAcao .activeFrozenFieldEnabled
{
cursor: pointer;
color: #2FDD1F;
}
input.activeFrozenFieldOver
{
/*
cursor: pointer;
text-decoration: underline;
*/
}
table.tabelaTarefas tr.Par
{
background-color: #FFFFFF;
border-style: solid;
border-width: 1px;
border-color: #090909;
}
table.tabelaTarefas tr.Impar
{
background-color: #F7F7F7;
border-style: solid;
border-width: 1px;
border-color: #090909;
}
.novaTarefa
{
/*
text-decoration: underline;
background-color: yellow;
*/
}
|
agpl-3.0
|
osgcc/ryzom
|
ryzom/client/src/interface_v3/reflect.cpp
|
4462
|
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "stdpch.h"
#include "reflect.h"
// Yoyo: Act like a singleton, else registerClass may crash.
CReflectSystem::TClassMap *CReflectSystem::_ClassMap= NULL;
// hack to register the root class at startup
static const struct CRootReflectableClassRegister
{
CRootReflectableClassRegister()
{
TReflectedProperties props;
CReflectSystem::registerClass("CReflectable", "", props);
}
} _RootReflectableClassRegisterInstance;
//===================================================================================
// release memory
void CReflectSystem::release()
{
delete _ClassMap;
_ClassMap = NULL;
}
//===================================================================================
void CReflectSystem::registerClass(const std::string &className, const std::string &parentName, const TReflectedProperties properties)
{
if(!_ClassMap) _ClassMap= new TClassMap;
TClassMap::const_iterator it = _ClassMap->find(className);
if (it != _ClassMap->end())
{
nlerror("CReflectSystem::registerClass : Class registered twice : %s!", className.c_str());
}
CClassInfo &ci = (*_ClassMap)[className];
ci.Properties = properties;
ci.ClassName = className;
for(uint k = 0; k < ci.Properties.size(); ++k)
{
ci.Properties[k].ParentClass = &ci;
}
if (parentName.empty())
{
ci.ParentClass = NULL;
}
else
{
it = _ClassMap->find(parentName);
if (it == _ClassMap->end())
{
nlerror("CReflectSystem::registerClass : Parent class %s not found", parentName.c_str());
}
ci.ParentClass = &(it->second);
}
}
//===================================================================================
const CReflectedProperty *CReflectSystem::getProperty(const std::string &className, const std::string &propertyName, bool dspWarning)
{
if(!_ClassMap) _ClassMap= new TClassMap;
TClassMap::const_iterator it = _ClassMap->find(className);
if (it == _ClassMap->end())
{
nlwarning("CReflectSystem::getProperty : Unkwown class : %s", className.c_str());
return NULL;
}
const CClassInfo *ci = &it->second;
while (ci)
{
// Linear search should suffice for now
for(uint k = 0; k < ci->Properties.size(); ++k)
{
if (ci->Properties[k].Name == propertyName)
{
return &(ci->Properties[k]);
}
}
// search in parent
ci = ci->ParentClass;
}
//\ TODO nico : possible optimization : instead of going up in the parents when
// searching for a property, it would be simpler to concatenate properties
// from parent class at registration.
// All that would be left at the end would be a hash_map of properties ...
if(dspWarning)
nlwarning("CReflectSystem::getProperty : %s is not a property of class : %s", propertyName.c_str(), className.c_str());
return NULL;
}
//===================================================================================
const CClassInfo *CReflectable::getClassInfo()
{
if (!CReflectSystem::getClassMap()) return NULL;
// TODO nico : a possible optimization would be to use the address of the static function
// 'getReflectedProperties' as a key into the CClassInfo map. This pointer uniquely identify
// classes that export properties
CReflectSystem::TClassMap::const_iterator it = CReflectSystem::getClassMap()->find(this->getReflectedClassName());
if (it == CReflectSystem::getClassMap()->end())
{
return NULL;
}
return &(it->second);
}
//===================================================================================
const CReflectedProperty *CReflectable::getReflectedProperty(const std::string &propertyName, bool dspWarning) const
{
return CReflectSystem::getProperty(this->getReflectedClassName(), propertyName, dspWarning);
}
|
agpl-3.0
|
nextcloud/deck
|
l10n/es_AR.js
|
1856
|
OC.L10N.register(
"deck",
{
"Deck" : "Deck",
"Personal" : "Personal",
"Finished" : "Terminado",
"To review" : "Para revisar",
"Action needed" : "Acción requerida",
"Later" : "Después",
"copy" : "copiar",
"Done" : "Hecho",
"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" : "El archivo subido sobrepasa el valor MAX_FILE_SIZE especificada en el formulario HTML",
"No file was uploaded" : "No se subió ningún archivo ",
"Missing a temporary folder" : "Falta un directorio temporal",
"Add board" : "Nuevo Tablero",
"Cancel" : "Cancelar",
"Hide archived cards" : "Ocultar tarjetas archivadas",
"Show archived cards" : "Mostrar tarjetas archivadas",
"Details" : "Detalles",
"Sharing" : "Compartiendo",
"Tags" : "Etiquetas",
"Undo" : "Deshacer",
"Can edit" : "Puede editar",
"Can share" : "Puede compartir",
"Delete" : "Eliminar",
"Edit" : "Editar",
"Members" : "Miembros",
"Attachments" : "Adjuntos",
"Comments" : "Comentarios",
"Modified" : "Modificado",
"Created" : "Creado",
"Due date" : "Fecha de vencimiento",
"Select Date" : "Seleccionar fecha",
"Today" : "Hoy",
"Tomorrow" : "Mañana",
"Save" : "Guardar",
"Reply" : "Responder",
"Update" : "Actualizar",
"Description" : "Descripción",
"Formatting help" : "Ayuda de formato",
"(group)" : "(grupo)",
"seconds ago" : "segundos",
"All boards" : "Todos los Tableros",
"Shared with you" : "Compartido con usted",
"Board details" : "Detalles del tablero",
"Edit board" : "Editar Tablero",
"Clone board" : "Clonar Tablero",
"Delete board" : "Eliminar Tablero",
"An error occurred" : "Ocurrió un error",
"This week" : "Esta semana"
},
"nplurals=2; plural=(n != 1);");
|
agpl-3.0
|
azyva/dragom-api
|
src/main/java/org/azyva/dragom/model/config/NodeConfigTransferObject.java
|
7040
|
/*
* Copyright 2015 - 2017 AZYVA INC. INC.
*
* This file is part of Dragom.
*
* Dragom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dragom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Dragom. If not, see <http://www.gnu.org/licenses/>.
*/
package org.azyva.dragom.model.config;
import java.util.List;
import org.azyva.dragom.model.plugin.NodePlugin;
/**
* Transfer object for a {@link MutableNodeConfig} basic configuration data.
* <p>
* MutableNodeConfig and its sub-interfaces return and take as argument this
* interface to allow getting and setting atomically data. See
* {@link MutableConfig}.
* <p>
* It so happens that the only configuration data that can be transfered from and
* to MutableNodeConfig's (and its sub-interfaces) are the same and are
* represented by this interface. If MutableNodeConfig and its sub-interfaces
* eventually contain other configuration data that are not common, the
* orientation will probably be to introduce new transfer objects instead
* implementing an interface hierarchy to factor out commonality.
* <p>
* Since this interface represents a transfer object, implementations are
* generally straightforward, and in most cases,
* SimpleNodeConfigTransferObject will be adequate. Specifically if an
* implementation of MutableNodeConfig needs to manage concurrency with optimistic
* locking, {@link OptimisticLockHandle} should be used instead of including some
* hidden field within the NodeConfigTransferObject implementation.
*
* @author David Raymond
*/
public interface NodeConfigTransferObject {
/**
* @return Name.
*/
String getName();
/**
* Sets the name.
*
* @param name See description.
*/
void setName(String name);
/**
* Returns a {@link PropertyDefConfig}.
* <p>
* If the PropertyDefConfig exists but is defined with the value field set to
* null, a PropertyDefConfig is returned (instead of returning null).
*
* @param name Name of the PropertyDefConfig.
* @return PropertyDefConfig. null if the PropertyDefConfig does not exist.
*/
PropertyDefConfig getPropertyDefConfig(String name);
/**
* Verifies if a {@link PropertyDefConfig} exists.
* <p>
* If the PropertyDefConfig exists but is defined with the value field set to
* null, true is returned.
* <p>
* Returns true if an only if {@link #getPropertyDefConfig} does not return null.
*
* @param name Name of the PropertyDefConfig.
* @return Indicates if the PropertyDefConfig exists.
*/
boolean isPropertyExists(String name);
/**
* Returns a List of all the {@link PropertyDefConfig}'s.
* <p>
* If no PropertyDefConfig is defined for the NodeConfig, an empty List is
* returned (as opposed to null).
* <p>
* The order of the PropertyDefConfig is generally expected to be as defined
* in the underlying storage for the configuration, hence the List return type.
* But no particular order is actually guaranteed.
*
* @return See description.
*/
public List<PropertyDefConfig> getListPropertyDefConfig();
/**
* Removes a {@link PropertyDefConfig}.
*
* @param name Name of the PropertyDefConfig.
*/
public void removePropertyDefConfig(String name);
/**
* Sets a {@link PropertyDefConfig}.
* <p>
* If one already exists with the same name, it is overwritten. Otherwise it is
* added.
* <p>
* Mostly any implementation of PropertyDefConfig can be used, although
* SimplePropertyDefConfig is generally the better choice.
*
* @param propertyDefConfig PropertyDefConfig.
* @return Indicates if a new PropertyDefConfig was added (as opposed to an
* existing one having been overwritten.
*/
public boolean setPropertyDefConfig(PropertyDefConfig propertyDefConfig);
/**
* Returns a {@link PluginDefConfig}.
* <p>
* If the PluginDefConfig exists but is defined with the pluginClass field set to
* null, a PluginDefConfig is returned (instead of returning null).
*
* @param classNodePlugin Class of the {@link NodePlugin} interface.
* @param pluginId Plugin ID to distinguish between multiple instances of the same
* plugin. Can be null to get a PluginDefConfig whose field pluginId is null.
* @return PluginDefConfig. null if the PluginDefConfig does not exist.
*/
public PluginDefConfig getPluginDefConfig(Class<? extends NodePlugin> classNodePlugin, String pluginId);
/**
* Verifies if a {@link PluginDefConfig} exists.
* <p>
* If the PluginDefConfig exists but is defined with the pluginClass field set to
* null, true is returned.
* <p>
* Returns true if an only if {@link #getPluginDefConfig} does not return null.
*
* @param classNodePlugin Class of the {@link NodePlugin} interface.
* @param pluginId Plugin ID to distinguish between multiple instances of the same
* plugin. Can be null to get a PluginDefConfig whose field pluginId is null.
* @return Indicates if the PluginDefConfig exists.
*/
public boolean isPluginDefConfigExists(Class<? extends NodePlugin> classNodePlugin, String pluginId);
/**
* Returns a List of all the {@link PluginDefConfig}'s.
* <p>
* If no PluginDefConfig is defined for the NodeConfig, an empty Set is returned
* (as opposed to null).
* <p>
* The order of the PluginDefConfig is generally expected to be as defined
* in the underlying storage for the configuration, hence the List return type.
* But no particular order is actually guaranteed.
*
* @return See description.
*/
public List<PluginDefConfig> getListPluginDefConfig();
/**
* Removes a {@link PropertyDefConfig}.
*
* @param classNodePlugin Class of the {@link NodePlugin} interface.
* @param pluginId Plugin ID to distinguish between multiple instances of the same
* plugin. Can be null to get a PluginDefConfig whose field pluginId is null.
*/
public void removePlugingDefConfig(Class<? extends NodePlugin> classNodePlugin, String pluginId);
/**
* Sets a {@link PluginDefConfig}.
* <p>
* If one already exists with the same {@link PluginKey}, it is overwritten.
* Otherwise it is added.
* <p>
* Mostly any implementation of PluginDefConfig can be used, although
* SimplePluginDefConfig is generally the better choice.
*
* @param pluginDefConfig PluginDefConfig.
* @return Indicates if a new PluginDefConfig was added (as opposed to an existing
* one having been overwritten.
*/
public boolean setPluginDefConfig(PluginDefConfig pluginDefConfig);
}
|
agpl-3.0
|
Ardinis/server
|
apps/updatenotification/lib/Notification/Notifier.php
|
5672
|
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\UpdateNotification\Notification;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserSession;
use OCP\L10N\IFactory;
use OCP\Notification\IManager;
use OCP\Notification\INotification;
use OCP\Notification\INotifier;
class Notifier implements INotifier {
/** @var IURLGenerator */
protected $url;
/** @var IConfig */
protected $config;
/** @var IManager */
protected $notificationManager;
/** @var IFactory */
protected $l10NFactory;
/** @var IUserSession */
protected $userSession;
/** @var IGroupManager */
protected $groupManager;
/** @var string[] */
protected $appVersions;
/**
* Notifier constructor.
*
* @param IURLGenerator $url
* @param IConfig $config
* @param IManager $notificationManager
* @param IFactory $l10NFactory
* @param IUserSession $userSession
* @param IGroupManager $groupManager
*/
public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) {
$this->url = $url;
$this->notificationManager = $notificationManager;
$this->config = $config;
$this->l10NFactory = $l10NFactory;
$this->userSession = $userSession;
$this->groupManager = $groupManager;
$this->appVersions = $this->getAppVersions();
}
/**
* @param INotification $notification
* @param string $languageCode The code of the language that should be used to prepare the notification
* @return INotification
* @throws \InvalidArgumentException When the notification was not prepared by a notifier
* @since 9.0.0
*/
public function prepare(INotification $notification, $languageCode) {
if ($notification->getApp() !== 'updatenotification') {
throw new \InvalidArgumentException();
}
$l = $this->l10NFactory->get('updatenotification', $languageCode);
if ($notification->getSubject() === 'connection_error') {
$errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0);
if ($errors === 0) {
$this->notificationManager->markProcessed($notification);
throw new \InvalidArgumentException();
}
$notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors]))
->setParsedMessage($l->t('Please check the nextcloud and server log files for errors.'));
} elseif ($notification->getObjectType() === 'core') {
$this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions());
$parameters = $notification->getSubjectParameters();
$notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']]));
if ($this->isAdmin()) {
$notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater');
}
} else {
$appInfo = $this->getAppInfo($notification->getObjectType());
$appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name'];
if (isset($this->appVersions[$notification->getObjectType()])) {
$this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]);
}
$notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()]))
->setRichSubject($l->t('Update for {app} to version %s is available.', $notification->getObjectId()), [
'app' => [
'type' => 'app',
'id' => $notification->getObjectType(),
'name' => $appName,
]
]);
if ($this->isAdmin()) {
$notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps') . '#app-' . $notification->getObjectType());
}
}
$notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg')));
return $notification;
}
/**
* Remove the notification and prevent rendering, when the update is installed
*
* @param INotification $notification
* @param string $installedVersion
* @throws \InvalidArgumentException When the update is already installed
*/
protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) {
if (version_compare($notification->getObjectId(), $installedVersion, '<=')) {
$this->notificationManager->markProcessed($notification);
throw new \InvalidArgumentException();
}
}
/**
* @return bool
*/
protected function isAdmin() {
$user = $this->userSession->getUser();
if ($user instanceof IUser) {
return $this->groupManager->isAdmin($user->getUID());
}
return false;
}
protected function getCoreVersions() {
return implode('.', \OCP\Util::getVersion());
}
protected function getAppVersions() {
return \OC_App::getAppVersions();
}
protected function getAppInfo($appId) {
return \OC_App::getAppInfo($appId);
}
}
|
agpl-3.0
|
ixdu/capsule
|
modules/timer.js
|
457
|
var error = require('parts/error');
exports.create = function(callback, millisec, cyclic){
if(typeof(setInterval) == 'undefined'
&&typeof(setTimeout) == 'undefined')
return new error('not supported', 'this platform is not supported timer functionality');
var id = cyclic ? setInterval(callback, millisec) : setTimeout(callback, millisec);
return {
destroy : function(){
cyclic ? clearInterval(id) : clearTimeout(id);
}
};
}
|
agpl-3.0
|
kobotoolbox/kpi
|
kpi/tests/api/v2/test_api_permissions.py
|
34731
|
# coding: utf-8
from django.contrib.auth.models import User, Permission
from django.urls import reverse
from django.utils import timezone
from rest_framework import status
from kpi.constants import (
ASSET_TYPE_COLLECTION,
PERM_CHANGE_ASSET,
PERM_MANAGE_ASSET,
PERM_VIEW_ASSET,
)
from kpi.models import Asset, ObjectPermission
from kpi.tests.kpi_test_case import KpiTestCase
from kpi.urls.router_api_v2 import URL_NAMESPACE as ROUTER_URL_NAMESPACE
from kpi.utils.object_permission import get_anonymous_user
class ApiAnonymousPermissionsTestCase(KpiTestCase):
URL_NAMESPACE = ROUTER_URL_NAMESPACE
def setUp(self):
self.anon = get_anonymous_user()
self.someuser = User.objects.get(username='someuser')
self.someuser_password = 'someuser'
# This was written when we allowed anons to create assets, but I'll
# leave it here just to make sure it has no effect
permission = Permission.objects.get(codename='add_asset')
self.anon.user_permissions.add(permission)
# Log in and create an asset that anon can access
self.client.login(username=self.someuser.username,
password=self.someuser_password)
self.anon_accessible = self.create_asset('Anonymous can access this!')
self.add_perm(self.anon_accessible, self.anon, 'view_')
# Log out and become anonymous again
self.client.logout()
response = self.client.get(reverse('currentuser-detail'))
self.assertFalse('username' in response.data)
def test_anon_list_assets(self):
# `view_` granted to anon means detail access, NOT list access
self.assert_object_in_object_list(self.anon_accessible, in_list=False)
def test_anon_asset_detail(self):
self.assert_detail_viewable(self.anon_accessible)
def test_cannot_create_asset(self):
url = reverse(self._get_endpoint('asset-list'))
data = {'name': 'my asset', 'content': ''}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN,
msg="anonymous user cannot create a asset")
class ApiPermissionsPublicAssetTestCase(KpiTestCase):
URL_NAMESPACE = ROUTER_URL_NAMESPACE
def setUp(self):
KpiTestCase.setUp(self)
self.anon = get_anonymous_user()
self.admin = User.objects.get(username='admin')
self.admin_password = 'pass'
self.someuser = User.objects.get(username='someuser')
self.someuser_password = 'someuser'
self.login(self.admin.username, self.admin_password)
self.admins_public_asset = self.create_asset('admins_public_asset')
self.add_perm(self.admins_public_asset, self.anon, 'view')
self.login(self.someuser.username, self.someuser_password)
self.someusers_public_asset = self.create_asset('someusers_public_asset')
self.add_perm(self.someusers_public_asset, self.anon, 'view')
def test_user_can_view_public_asset(self):
self.assert_detail_viewable(self.admins_public_asset, self.someuser, self.someuser_password)
def test_public_asset_not_in_list_user(self):
self.assert_object_in_object_list(self.admins_public_asset, self.someuser, self.someuser_password,
in_list=False)
def test_public_asset_not_in_list_admin(self):
self.assert_object_in_object_list(self.someusers_public_asset, self.admin, self.admin_password,
in_list=False)
def test_revoke_anon_from_asset_in_public_collection(self):
self.login(self.someuser.username, self.someuser_password)
public_collection = self.create_collection('public_collection')
child_asset = self.create_asset('child_asset_in_public_collection')
self.add_to_collection(child_asset, public_collection)
child_asset.refresh_from_db()
# Anon should have no access at this point
self.client.logout()
self.assert_viewable(child_asset, viewable=False)
# Grant anon access to the parent collection
self.login(self.someuser.username, self.someuser_password)
self.add_perm(public_collection, self.anon, 'view_')
# Verify anon can access the child asset
self.client.logout()
# Anon can only see a public asset by accessing the detail view
# directly; `assert_viewble()` will always fail because it expects the
# asset to be in the list view as well
self.assert_detail_viewable(child_asset)
# Revoke anon's access to the child asset
self.login(self.someuser.username, self.someuser_password)
self.remove_perm_v2_api(child_asset, self.anon, PERM_VIEW_ASSET)
# Make sure anon cannot access the child asset any longer
self.client.logout()
self.assert_viewable(child_asset, viewable=False)
class ApiPermissionsTestCase(KpiTestCase):
fixtures = ['test_data']
URL_NAMESPACE = ROUTER_URL_NAMESPACE
def setUp(self):
self.admin = User.objects.get(username='admin')
self.admin_password = 'pass'
self.someuser = User.objects.get(username='someuser')
self.someuser_password = 'someuser'
self.anotheruser = User.objects.get(username='anotheruser')
self.anotheruser_password = 'anotheruser'
self.assertTrue(self.client.login(username=self.admin.username,
password=self.admin_password))
self.admin_asset = self.create_asset('admin_asset')
self.admin_collection = self.create_collection('admin_collection')
self.child_collection = self.create_collection('child_collection')
self.add_to_collection(self.child_collection, self.admin_collection)
self.client.logout()
################# Asset tests #####################
def test_own_asset_in_asset_list(self):
self.assert_viewable(self.admin_asset, self.admin,
self.admin_password)
def test_viewable_asset_in_asset_list(self):
# Give "someuser" view permissions on an asset owned by "admin".
self.add_perm(self.admin_asset, self.someuser, 'view_')
# Test that "someuser" can now view the asset.
self.assert_viewable(self.admin_asset, self.someuser,
self.someuser_password)
def test_non_viewable_asset_not_in_asset_list(self):
# Wow, that's quite a function name...
# Ensure that "someuser" doesn't have permission to view the survey
# asset owned by "admin".
perm_name = self._get_perm_name('view_', self.admin_asset)
self.assertFalse(self.someuser.has_perm(perm_name, self.admin_asset))
# Verify they can't view the asset through the API.
self.assert_viewable(self.admin_asset, self.someuser,
self.someuser_password, viewable=False)
def test_inherited_viewable_assets_in_asset_list(self):
# Give "someuser" view permissions on a collection owned by "admin" and
# add an asset also owned by "admin" to that collection.
self.add_perm(self.admin_asset, self.someuser, 'view_')
self.add_to_collection(self.admin_asset, self.admin_collection,
self.admin, self.admin_password)
# Test that "someuser" can now view the asset.
self.assert_viewable(self.admin_asset, self.someuser,
self.someuser_password)
def test_viewable_asset_inheritance_conflict(self):
# Log in as "admin", create a new child collection, and add an asset to
# that collection.
self.add_to_collection(self.admin_asset, self.child_collection,
self.admin, self.admin_password)
# Give "someuser" view permission on 'child_collection'.
self.add_perm(self.child_collection, self.someuser, 'view_')
# Give "someuser" view permission on the parent collection.
self.add_perm(self.admin_collection, self.someuser, 'view_')
# Revoke the view permissions of "someuser" on the parent collection.
self.remove_perm(self.admin_collection, self.admin,
self.admin_password, self.someuser,
self.someuser_password, 'view_')
# Confirm that "someuser" can view the contents of 'child_collection'.
self.assert_viewable(self.admin_asset, self.someuser,
self.someuser_password)
def test_non_viewable_asset_inheritance_conflict(self):
# Log in as "admin", create a new child collection, and add an asset to
# that collection.
self.add_to_collection(self.admin_asset, self.child_collection,
self.admin, self.admin_password)
# Give "someuser" view permission on the parent collection.
self.add_perm(self.admin_collection, self.someuser, 'view_')
# Revoke the view permissions of "someuser" on the child collection.
self.remove_perm(self.child_collection, self.admin, self.admin_password,
self.someuser, self.someuser_password, 'view_')
# Confirm that "someuser" can't view the contents of 'child_collection'.
self.assert_viewable(self.admin_asset, self.someuser,
self.someuser_password, viewable=False)
def test_viewable_asset_not_deletable(self):
# Give "someuser" view permissions on an asset owned by "admin".
self.add_perm(self.admin_asset, self.someuser, 'view_')
# Confirm that "someuser" is not allowed to delete the asset.
delete_perm = self._get_perm_name('delete_', self.admin_asset)
self.assertFalse(self.someuser.has_perm(delete_perm, self.admin_asset))
# Test that "someuser" can't delete the asset.
self.client.login(username=self.someuser.username,
password=self.someuser_password)
url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.admin_asset.uid})
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_inherited_viewable_asset_not_deletable(self):
# Give "someuser" view permissions on a collection owned by "admin" and
# add an asset also owned by "admin" to that collection.
self.add_perm(self.admin_asset, self.someuser, 'view_')
self.add_to_collection(self.admin_asset, self.admin_collection,
self.admin, self.admin_password)
# Confirm that "someuser" is not allowed to delete the asset.
delete_perm = self._get_perm_name('delete_', self.admin_asset)
self.assertFalse(self.someuser.has_perm(delete_perm, self.admin_asset))
# Test that "someuser" can't delete the asset.
self.client.login(username=self.someuser.username,
password=self.someuser_password)
url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.admin_asset.uid})
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_shared_asset_remove_own_permissions_allowed(self):
"""
Ensuring that a non-owner who has been shared an asset is able to remove
themselves from that asset if they want.
"""
self.client.login(
username=self.someuser.username,
password=self.someuser_password,
)
new_asset = self.create_asset(
name='a new asset',
owner=self.someuser,
)
perm = new_asset.assign_perm(self.anotheruser, 'view_asset')
kwargs = {
'parent_lookup_asset': new_asset.uid,
'uid': perm.uid,
}
url = reverse(
'api_v2:asset-permission-assignment-detail', kwargs=kwargs
)
self.client.logout()
self.client.login(
username=self.anotheruser.username,
password=self.anotheruser_password,
)
assert self.anotheruser.has_perm(PERM_VIEW_ASSET, new_asset)
# `anotheruser` attempting to remove themselves from the asset
res = self.client.delete(url)
assert res.status_code == status.HTTP_204_NO_CONTENT
assert not self.anotheruser.has_perm(PERM_VIEW_ASSET, new_asset)
assert len(new_asset.get_perms(self.anotheruser)) == 0
def test_shared_asset_non_owner_remove_owners_permissions_not_allowed(self):
"""
Ensuring that a non-owner who has been shared an asset is not able to
remove permissions from the owner of that asset
"""
self.client.login(
username=self.someuser.username,
password=self.someuser_password,
)
new_asset = self.create_asset(
name='a new asset',
owner=self.someuser,
)
# Getting existing permission for the owner of the asset
perm = ObjectPermission.objects.filter(asset=new_asset).get(
user=self.someuser, permission__codename=PERM_VIEW_ASSET
)
new_asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET)
kwargs = {
'parent_lookup_asset': new_asset.uid,
'uid': perm.uid,
}
url = reverse(
'api_v2:asset-permission-assignment-detail', kwargs=kwargs
)
self.client.logout()
self.client.login(
username=self.anotheruser.username,
password=self.anotheruser_password,
)
assert self.someuser.has_perm(PERM_VIEW_ASSET, new_asset)
# `anotheruser` attempting to remove `someuser` from the asset
res = self.client.delete(url)
assert res.status_code == status.HTTP_403_FORBIDDEN
assert self.someuser.has_perm(PERM_VIEW_ASSET, new_asset)
def test_shared_asset_non_owner_remove_another_non_owners_permissions_not_allowed(self):
"""
Ensuring that a non-owner who has an asset shared with them cannot
remove permissions from another non-owner with that same asset shared
with them.
"""
yetanotheruser = User.objects.create(
username='yetanotheruser',
)
self.client.login(
username=self.someuser.username,
password=self.someuser_password,
)
new_asset = self.create_asset(
name='a new asset',
owner=self.someuser,
owner_password=self.someuser_password,
)
new_asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET)
perm = new_asset.assign_perm(yetanotheruser, PERM_VIEW_ASSET)
kwargs = {
'parent_lookup_asset': new_asset.uid,
'uid': perm.uid,
}
url = reverse(
'api_v2:asset-permission-assignment-detail', kwargs=kwargs
)
self.client.logout()
self.client.login(
username=self.anotheruser.username,
password=self.anotheruser_password,
)
assert yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset)
# `anotheruser` attempting to remove `yetanotheruser` from the asset
res = self.client.delete(url)
assert res.status_code == status.HTTP_404_NOT_FOUND
assert yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset)
def test_shared_asset_manage_asset_remove_another_non_owners_permissions_allowed(self):
"""
Ensure that a non-owner who has an asset shared with them and has
`manage_asset` permissions is able to remove permissions from another
non-owner with that same asset shared with them.
"""
yetanotheruser = User.objects.create(
username='yetanotheruser',
)
self.client.login(
username=self.someuser.username,
password=self.someuser_password,
)
new_asset = self.create_asset(
name='a new asset',
owner=self.someuser,
owner_password=self.someuser_password,
)
new_asset.assign_perm(self.anotheruser, PERM_MANAGE_ASSET)
perm = new_asset.assign_perm(yetanotheruser, PERM_VIEW_ASSET)
kwargs = {
'parent_lookup_asset': new_asset.uid,
'uid': perm.uid,
}
url = reverse(
'api_v2:asset-permission-assignment-detail', kwargs=kwargs
)
self.client.logout()
self.client.login(
username=self.anotheruser.username,
password=self.anotheruser_password,
)
assert yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset)
# `anotheruser` attempting to remove `yetanotheruser` from the asset
res = self.client.delete(url)
assert res.status_code == status.HTTP_204_NO_CONTENT
assert not yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset)
def test_copy_permissions_between_assets(self):
# Give "someuser" edit permissions on an asset owned by "admin"
self.add_perm(self.admin_asset, self.someuser, 'change_')
# Confirm that "someuser" has received the implied permissions
expected_perms = [PERM_CHANGE_ASSET, PERM_VIEW_ASSET]
self.assertListEqual(
sorted(self.admin_asset.get_perms(self.someuser)),
expected_perms
)
# Create another asset to receive the copied permissions
new_asset = self.create_asset(
name='destination asset', owner=self.admin,
owner_password=self.admin_password
)
# Add some extraneous permissions to the destination asset; these
# should be removed by the copy operation
self.add_perm(new_asset, self.anotheruser, 'view_')
self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, new_asset))
# Perform the permissions copy via the API endpoint
self.client.login(
username=self.admin.username, password=self.admin_password
)
if self.URL_NAMESPACE is None:
dest_asset_perm_url = reverse(
'asset-permissions', kwargs={'uid': new_asset.uid}
)
else:
dest_asset_perm_url = reverse(
'api_v2:asset-permission-assignment-clone',
kwargs={'parent_lookup_asset': new_asset.uid}
)
# TODO: check that `clone_from` can also be a URL.
# You know, Roy Fielding and all that.
self.client.patch(
dest_asset_perm_url, data={'clone_from': self.admin_asset.uid}
)
# Check the result; since the source and destination have the same
# owner, the permissions should be identical
self.assertDictEqual(
self.admin_asset.get_users_with_perms(attach_perms=True),
new_asset.get_users_with_perms(attach_perms=True)
)
def test_cannot_copy_permissions_between_non_owned_assets(self):
# Give "someuser" view permissions on an asset owned by "admin"
self.add_perm(self.admin_asset, self.someuser, 'view_')
self.assertTrue(self.someuser.has_perm(PERM_VIEW_ASSET, self.admin_asset))
# Create another asset to receive the copied permissions
new_asset = self.create_asset(
name='destination asset', owner=self.admin,
owner_password=self.admin_password
)
# Give "someuser" edit permissions on the new asset owned by "admin"
self.add_perm(new_asset, self.someuser, 'change_')
self.assertTrue(self.someuser.has_perm(PERM_CHANGE_ASSET, new_asset))
new_asset_perms_before_copy_attempt = new_asset.get_users_with_perms(
attach_perms=True
)
# Perform the permissions copy via the API endpoint
self.client.login(
username=self.someuser.username, password=self.someuser_password
)
if self.URL_NAMESPACE is None:
dest_asset_perm_url = reverse(
'asset-permissions', kwargs={'uid': new_asset.uid}
)
else:
dest_asset_perm_url = reverse(
'api_v2:asset-permission-assignment-clone',
kwargs={'parent_lookup_asset': new_asset.uid}
)
response = self.client.patch(
dest_asset_perm_url, data={'clone_from': self.admin_asset.uid}
)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Check the result; nothing should have changed
self.assertDictEqual(
new_asset_perms_before_copy_attempt,
new_asset.get_users_with_perms(attach_perms=True)
)
def test_user_cannot_copy_permissions_from_non_viewable_asset(self):
# Make sure "someuser" cannot view the asset owned by "admin"
self.assertFalse(
self.someuser.has_perm(PERM_VIEW_ASSET, self.admin_asset)
)
# Create another asset to receive the copied permissions
new_asset = self.create_asset(
name='destination asset', owner=self.admin,
owner_password=self.admin_password
)
# Take note of the destination asset's permissions to make sure they
# are *not* changed later
dest_asset_original_perms = new_asset.get_users_with_perms(
attach_perms=True
)
# Perform the permissions copy via the API endpoint
self.client.login(
username=self.someuser.username, password=self.someuser_password
)
if self.URL_NAMESPACE is None:
dest_asset_perm_url = reverse(
'asset-permissions', kwargs={'uid': new_asset.uid}
)
else:
dest_asset_perm_url = reverse(
'api_v2:asset-permission-assignment-clone',
kwargs={'parent_lookup_asset': new_asset.uid}
)
response = self.client.patch(
dest_asset_perm_url, data={'clone_from': self.admin_asset.uid}
)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
# Make sure no permissions were changed on the destination asset
self.assertDictEqual(
dest_asset_original_perms,
new_asset.get_users_with_perms(attach_perms=True)
)
def test_user_cannot_copy_permissions_to_non_editable_asset(self):
# Give "someuser" view permissions on an asset owned by "admin"
self.add_perm(self.admin_asset, self.someuser, 'view_')
self.assertTrue(self.someuser.has_perm(PERM_VIEW_ASSET, self.admin_asset))
# Create another asset to receive the copied permissions
new_asset = self.create_asset(
name='destination asset', owner=self.admin,
owner_password=self.admin_password
)
# Give "someuser" view permissions on the new asset owned by "admin"
self.add_perm(new_asset, self.someuser, 'view_')
self.assertTrue(self.someuser.has_perm(PERM_VIEW_ASSET, new_asset))
# Take note of the destination asset's permissions to make sure they
# are *not* changed later
dest_asset_original_perms = new_asset.get_users_with_perms(
attach_perms=True
)
# Perform the permissions copy via the API endpoint
self.client.login(
username=self.someuser.username, password=self.someuser_password
)
if self.URL_NAMESPACE is None:
dest_asset_perm_url = reverse(
'asset-permissions', kwargs={'uid': new_asset.uid}
)
else:
dest_asset_perm_url = reverse(
'api_v2:asset-permission-assignment-clone',
kwargs={'parent_lookup_asset': new_asset.uid}
)
response = self.client.patch(
dest_asset_perm_url, data={'clone_from': self.admin_asset.uid}
)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Make sure no permissions were changed on the destination asset
self.assertDictEqual(
dest_asset_original_perms,
new_asset.get_users_with_perms(attach_perms=True)
)
############# Collection tests ###############
def test_own_collection_in_collection_list(self):
self.assert_viewable(self.admin_collection, self.admin,
self.admin_password)
def test_viewable_collection_in_collection_list(self):
# Give "someuser" view permissions on a collection owned by "admin".
self.add_perm(self.admin_collection, self.someuser, 'view_')
# Test that "someuser" can now view the collection.
self.assert_viewable(self.admin_collection, self.someuser,
self.someuser_password)
def test_non_viewable_collection_not_in_collection_list(self):
# Wow, that's quite a function name...
# Ensure that "someuser" doesn't have permission to view the survey
# collection owned by "admin".
perm_name = self._get_perm_name('view_', self.admin_collection)
self.assertFalse(self.someuser.has_perm(perm_name, self.admin_collection))
# Verify they can't view the collection through the API.
self.assert_viewable(self.admin_collection, self.someuser,
self.someuser_password, viewable=False)
def test_inherited_viewable_collections_in_collection_list(self):
# Give "someuser" view permissions on the parent collection.
self.add_perm(self.admin_collection, self.someuser, 'view_')
# Test that "someuser" can now view the child collection.
self.assert_viewable(self.child_collection, self.someuser,
self.someuser_password)
def test_viewable_collection_inheritance_conflict(self):
grandchild_collection = self.create_collection('grandchild_collection',
self.admin, self.admin_password)
self.add_to_collection(grandchild_collection, self.child_collection,
self.admin, self.admin_password)
# Give "someuser" view permission on 'child_collection'.
self.add_perm(self.child_collection, self.someuser, 'view_')
# Give "someuser" view permission on the parent collection.
self.add_perm(self.admin_collection, self.someuser, 'view_')
# Revoke the view permissions of "someuser" on 'parent_collection'.
self.remove_perm(self.admin_collection, self.admin,
self.admin_password, self.someuser,
self.someuser_password, 'view_')
# Confirm that "someuser" can view 'grandchild_collection'.
self.assert_viewable(grandchild_collection, self.someuser,
self.someuser_password)
def test_non_viewable_collection_inheritance_conflict(self):
grandchild_collection = self.create_collection('grandchild_collection',
self.admin, self.admin_password)
self.add_to_collection(grandchild_collection, self.child_collection,
self.admin, self.admin_password)
# Give "someuser" view permission on the parent collection.
self.add_perm(self.admin_collection, self.someuser, 'view_')
# Revoke the view permissions of "someuser" on the child collection.
self.remove_perm(self.child_collection, self.admin,
self.admin_password, self.someuser,
self.someuser_password, 'view_')
# Confirm that "someuser" can't view 'grandchild_collection'.
self.assert_viewable(grandchild_collection, self.someuser,
self.someuser_password, viewable=False)
def test_viewable_collection_not_deletable(self):
# Give "someuser" view permissions on a collection owned by "admin".
self.add_perm(self.admin_collection, self.someuser, 'view_')
# Confirm that "someuser" is not allowed to delete the collection.
delete_perm = self._get_perm_name('delete_', self.admin_collection)
self.assertFalse(self.someuser.has_perm(delete_perm,
self.admin_collection))
# Test that "someuser" can't delete the collection.
self.client.login(username=self.someuser.username,
password=self.someuser_password)
url = reverse(self._get_endpoint('asset-detail'),
kwargs={'uid': self.admin_collection.uid})
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_inherited_viewable_collection_not_deletable(self):
# Give "someuser" view permissions on a collection owned by "admin".
self.add_perm(self.admin_collection, self.someuser, 'view_')
# Confirm that "someuser" is not allowed to delete the child collection.
delete_perm = self._get_perm_name('delete_', self.child_collection)
self.assertFalse(self.someuser.has_perm(delete_perm, self.child_collection))
# Test that "someuser" can't delete the child collection.
self.client.login(username=self.someuser.username,
password=self.someuser_password)
url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid':
self.child_collection.uid})
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
class ApiAssignedPermissionsTestCase(KpiTestCase):
"""
An obnoxiously large amount of code to test that the endpoint for listing
assigned permissions complies with the following rules:
* Superusers see it all (and there is *no* pagination)
* Anonymous users see nothing
* Regular users see everything that concerns them, namely all
their own permissions and all the owners' permissions for all objects
to which they have been assigned any permission
See also
kpi.utils.object_permission.get_user_permission_assignments_queryset
"""
# TODO: does this duplicate stuff in
# test_api_asset_permission_assignment.py / should it be moved there?
URL_NAMESPACE = ROUTER_URL_NAMESPACE
def setUp(self):
super().setUp()
self.anon = get_anonymous_user()
self.super = User.objects.get(username='admin')
self.super_password = 'pass'
self.someuser = User.objects.get(username='someuser')
self.someuser_password = 'someuser'
self.anotheruser = User.objects.get(username='anotheruser')
self.anotheruser_password = 'anotheruser'
self.collection = Asset.objects.create(
asset_type=ASSET_TYPE_COLLECTION, owner=self.someuser
)
self.asset = Asset.objects.create(owner=self.someuser)
def test_anon_only_sees_owner_and_anon_permissions(self):
self.asset.assign_perm(self.anon, PERM_VIEW_ASSET)
self.assertTrue(self.anon.has_perm(PERM_VIEW_ASSET, self.asset))
url = self.get_asset_perm_assignment_list_url(self.asset)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
user_urls = []
for username in [self.asset.owner.username, self.anon.username]:
user_urls.append(
self.absolute_reverse(
self._get_endpoint('user-detail'),
kwargs={'username': username},
)
)
self.assertSetEqual(
set((a['user'] for a in response.data)), set(user_urls)
)
def test_user_sees_relevant_permissions_on_assigned_objects(self):
# A user with explicitly-assigned permissions should see their
# own permissions and the owner's permissions, but not permissions
# assigned to other users
self.asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET)
self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, self.asset))
irrelevant_user = User.objects.create(username='mindyourown')
self.asset.assign_perm(irrelevant_user, PERM_VIEW_ASSET)
self.client.login(username=self.anotheruser.username,
password=self.anotheruser_password)
url = self.get_asset_perm_assignment_list_url(self.asset)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
returned_urls = [r['url'] for r in response.data]
all_obj_perms = self.asset.permissions.all()
relevant_obj_perms = all_obj_perms.filter(
user__in=(self.asset.owner, self.anotheruser),
permission__codename__in=self.asset.get_assignable_permissions(
with_partial=False
),
)
self.assertListEqual(
sorted(returned_urls),
sorted(
self.get_urls_for_asset_perm_assignment_objs(
relevant_obj_perms, asset=self.asset
)
),
)
def test_user_cannot_see_permissions_on_unassigned_objects(self):
self.asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET)
self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, self.asset))
self.client.login(username=self.anotheruser.username,
password=self.anotheruser_password)
url = self.get_asset_perm_assignment_list_url(self.collection)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_superuser_sees_all_permissions(self):
self.asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET)
self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, self.asset))
self.client.login(username=self.super.username,
password=self.super_password)
url = self.get_asset_perm_assignment_list_url(self.asset)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
returned_urls = [r['url'] for r in response.data]
all_obj_perms = self.asset.permissions.all()
self.assertListEqual(
sorted(returned_urls),
sorted(
self.get_urls_for_asset_perm_assignment_objs(
all_obj_perms, asset=self.asset
)
),
)
|
agpl-3.0
|
bikeindex/bike_index
|
db/migrate/20180918220604_create_exports.rb
|
421
|
class CreateExports < ActiveRecord::Migration[4.2]
def change
create_table :exports do |t|
t.references :organization, index: true
t.references :user, index: true
t.text :file
t.integer :file_format, default: 0
t.integer :kind, default: 0
t.integer :progress, default: 0
t.integer :rows
t.jsonb :options, default: {}
t.timestamps null: false
end
end
end
|
agpl-3.0
|
FriendSoftwareLabs/friendup
|
interfaces/web_desktop/apps/Server/Templates/server.html
|
2476
|
<div class="ContentFull LayoutButtonbarBottom">
<div class="VContentTop">
<div id="STabs" class="ContentFull">
<div class="Tab IconSmall fa-wrench">
{i18n_settings_attributes}
</div>
<div class="Tab IconSmall fa-archive">
{i18n_software}
</div>
<div class="Tab IconSmall fa-server">
{i18n_services}
</div>
<div class="Tab IconSmall fa-certificate">
{i18n_app_permissions}
</div>
<div class="Tab IconSmall fa-globe">
{i18n_server_globals}
</div>
<div class="Page">
<div id="SystemSettings" class="PageScroll ContentFull Padding ScrollArea">
</div>
</div>
<div class="Page">
<div id="Software" class="PageScroll ContentFull Padding ScrollArea">
</div>
</div>
<div class="Page">
<div id="Services" class="PageScroll ContentFull Padding ScrollArea">
</div>
</div>
<div class="Page">
<div id="SoftwarePermissions" class="PageScroll ContentFull Padding ScrollArea">
</div>
</div>
<div class="Page">
<div id="ServerGlobals" class="PageScroll ContentFull Padding ScrollArea">
</div>
</div>
</div>
</div>
<div class="VContentBottom Padding BackgroundDefault BorderTop" id="Bottom">
<button type="button" id="button-fa-wrench" class="FloatLeft RelatedToTabs Button fa-plus IconSmall" onclick="addItem()">
{i18n_additem}
</button>
<button type="button" id="button-fa-globe" class="FloatLeft RelatedToTabs IconSmall fa-save" onclick="saveGlobals()">
{i18n_save_globals}
</button>
<div id="button-fa-archive"></div>
<div id="button-fa-server"></div>
<div id="button-fa-certificate"></div>
</div>
</div>
<link rel="stylesheet" href="Progdir:Css/server.css"/>
<script src="Progdir:Scripts/serverwindow.js"></script>
<script>
InitTabs( 'STabs', function( e )
{
// Let's just show those buttons related to tabs =)
if( !e ) return;
var cl = e.className.match( /fa\-[a-z]*/i );
if( ge( 'button-' + cl[0] ) )
{
var par = ge( 'button-' + cl[0] ).parentNode;
for( var a = 0; a < par.childNodes.length; a++ )
{
if( par.childNodes[a].classList && par.childNodes[a].classList.contains( 'RelatedToTabs' ) )
{
if( par.childNodes[a].id != 'button-' + cl[0] )
{
par.childNodes[a].style.display = 'none';
}
else
{
par.childNodes[a].style.display = 'block';
}
}
}
}
} );
</script>
|
agpl-3.0
|
RealN-RnD/Test-Automation-C
|
src/netkuliTesting/NetkulixGUI.java
|
9645
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package netkuliTesting;
/**
*
* @author Phildor92 <phillip.evans09@hotmail.com>
*/
public class NetkulixGUI extends javax.swing.JFrame {
/**
* Creates new form NetkulixGUI
*/
public NetkulixGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jInternalFrame1 = new javax.swing.JInternalFrame();
jLabel2 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame1.setBorder(javax.swing.BorderFactory.createTitledBorder("Main.VERSION"));
jInternalFrame1.setVisible(true);
jLabel2.setText("Sanity Testing");
jButton2.setText("Start!");
jScrollPane1.setToolTipText("Fill in comments");
jTextArea1.setColumns(19);
jTextArea1.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
jTextArea1.setLineWrap(true);
jTextArea1.setRows(5);
jTextArea1.setText("Comments (e.g. Mac DUT, mobile device, etc...)");
jTextArea1.setToolTipText("");
jScrollPane1.setViewportView(jTextArea1);
jTextField1.setText("SW version");
jTextField1.setToolTipText("Fill in the AUT version");
jButton1.setText("Start!");
jLabel1.setText("TestRail testing");
jRadioButton1.setText("Mac");
jRadioButton2.setText("Windows");
jRadioButton3.setText("Android/iOS");
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(6, 6, 6)
.addComponent(jButton2))
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(6, 6, 6)
.addComponent(jButton1))
.addComponent(jSeparator1)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButton1)
.addComponent(jRadioButton2)
.addComponent(jRadioButton3))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addContainerGap(39, Short.MAX_VALUE)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton3)))
.addGap(8, 8, 8)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)
.addComponent(jLabel1))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
final String VERSION = "NetkuliGUI 0.2";//version 0.2-16.08.30-A
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NetkulixGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
|
agpl-3.0
|
cchang3/worldview-design
|
src/animation-module/code/web/js/proj/wv.proj.js
|
885
|
/*
* NASA Worldview
*
* This code was originally developed at NASA/Goddard Space Flight Center for
* the Earth Science Data and Information System (ESDIS) project.
*
* Copyright (C) 2013 - 2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*/
var wv = wv || {};
wv.proj = (function(self) {
self.parse = function(state, errors, config) {
// Permalink version 1.0 - 1.1
if ( state["switch"] ) {
state.p = state["switch"];
delete state["switch"];
}
var projId = state.p;
if ( projId ) {
if ( !config.projections[projId] ) {
delete state.p;
errors.push({message: "Unsupported projection: " + projId});
}
}
};
return self;
})(wv.proj || {});
|
agpl-3.0
|
SilverDav/Silverpeas-Core
|
core-war/src/main/java/org/silverpeas/web/notificationserver/channel/silvermail/requesthandlers/ReadMessage.java
|
2242
|
/*
* Copyright (C) 2000 - 2021 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent)
---*/
package org.silverpeas.web.notificationserver.channel.silvermail.requesthandlers;
import org.silverpeas.core.util.logging.SilverLogger;
import org.silverpeas.core.web.mvc.controller.ComponentSessionController;
import org.silverpeas.web.notificationserver.channel.silvermail.SILVERMAILRequestHandler;
import org.silverpeas.web.notificationserver.channel.silvermail.SILVERMAILSessionController;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
@Singleton
@Named("ReadMessage")
public class ReadMessage implements SILVERMAILRequestHandler {
@Override
public String handleRequest(ComponentSessionController componentSC,
HttpServletRequest request) {
try {
String sId = request.getParameter("ID");
long id = Long.parseLong(sId);
((SILVERMAILSessionController) componentSC).setCurrentMessageId(id);
} catch (NumberFormatException e) {
SilverLogger.getLogger(this).error(e.getMessage(), e);
}
return "/SILVERMAIL/jsp/readMessage.jsp";
}
}
|
agpl-3.0
|
DeepFound/deep_platform
|
build/cmake/Common.cmake
|
2676
|
#
# Definitions
#
set(REPOSITORY "$ENV{HOME}/.cmake/deepis")
set(CMAKE_MODULE_PATH "${REPOSITORY}")
#
# Build type and flags
#
include(${TOP}/build/cmake/BuildType.cmake)
include(${TOP}/build/cmake/Defines.cmake)
#
# Compiler
#
set(CMAKE_C_COMPILER gcc)
set(CMAKE_CXX_COMPILER g++)
#
# Verbose make output
#
set(CMAKE_VERBOSE_MAKEFILE ON)
#
# Allow asserts
#
string(REGEX REPLACE "-DNDEBUG" "" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
string(REGEX REPLACE "/D NDEBUG" "" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
#
# Allow a static lib to be compiled into a shared lib on 64b system
#
if(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
endif(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64")
message(STATUS "Build is Linux")
set(DYLIB_EXTENSION "so")
link_libraries("rt")
link_libraries("pthread")
#
# DEEP_DEBUG flag
#
if(DEEP_DEBUG)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DDEEP_DEBUG")
else()
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEEP_DEBUG")
endif()
#
# Compression
#
link_libraries("z")
#
# tinyxml
#
if (NOT ${CMAKE_PROJECT_NAME} STREQUAL "deepis-tinyxml" AND NOT ${CMAKE_PROJECT_NAME} STREQUAL "deepis-google-perftools" AND NOT ${CMAKE_PROJECT_NAME} STREQUAL "deepis-jemalloc")
find_package(deepis-tinyxml REQUIRED)
set(DEEPIS_STANDARD_INCS ${DEEPIS_TINYXML_INC})
set(DEEPIS_STANDARD_LIBS ${DEEPIS_TINYXML_LIB})
endif()
#
# tcmalloc
#
if (CMAKE_CXX_FLAGS MATCHES "TCMALLOC" AND NOT ${CMAKE_PROJECT_NAME} STREQUAL "deepis-google-perftools" AND NOT ${CMAKE_PROJECT_NAME} STREQUAL "deepis-jemalloc")
message(STATUS "Building with tcmalloc")
find_package(deepis-google-perftools REQUIRED)
set(DEEPIS_STANDARD_LIBS ${DEEPIS_STANDARD_LIBS} ${DEEPIS_GOOGLE_PERFTOOLS_LIB})
set(DEEPIS_STANDARD_INCS ${DEEPIS_STANDARD_INCS} ${DEEPIS_GOOGLE_PERFTOOLS_INC})
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-omit-frame-pointer -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-free")
endif()
#
# jemalloc
#
if (CMAKE_CXX_FLAGS MATCHES "JEMALLOC" AND NOT ${CMAKE_PROJECT_NAME} STREQUAL "deepis-jemalloc" AND NOT ${CMAKE_PROJECT_NAME} STREQUAL "deepis-google-perftools")
message(STATUS "Building with jemalloc")
find_package(deepis-jemalloc REQUIRED)
set(DEEPIS_STANDARD_LIBS ${DEEPIS_STANDARD_LIBS} ${DEEPIS_JEMALLOC_LIB})
set(DEEPIS_STANDARD_INCS ${DEEPIS_STANDARD_INCS} ${DEEPIS_JEMALLOC_INC})
endif()
#
# Testing
#
include(CTest)
enable_testing()
macro(add_deep_test testName srcFile)
if(DEEP_TEST)
add_executable(${testName} ${srcFile})
target_link_libraries(${testName} ${ARGN})
add_test(${testName} ${testName})
endif()
endmacro()
|
agpl-3.0
|
lucaswerkmeister/ceylon-herd
|
db/update-11.sql
|
376
|
create table ModuleRating (
id int8 not null,
mark int4 not null,
module_id int8,
owner_id int8,
primary key (id)
);
alter table ModuleRating
add constraint FK52DE174953B2465E
foreign key (module_id)
references Module;
alter table ModuleRating
add constraint FK52DE1749B2FABF16
foreign key (owner_id)
references user_table;
|
agpl-3.0
|
gvSIGAssociation/gvsig-web
|
src/main/java/es/gva/dgti/gvgeoportal/security/SafeLoginController.java
|
1419
|
/*******************************************************************************
* gvGeoportal is sponsored by the General Directorate for Information
* Technologies (DGTI) of the Regional Ministry of Finance and Public
* Administration of the Generalitat Valenciana (Valencian Community,
* Spain), managed by gvSIG Association and led by DISID Corporation.
*
* Copyright (C) 2016 DGTI - Generalitat Valenciana
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package es.gva.dgti.gvgeoportal.security;
import org.gvnix.addon.gva.security.providers.safe.GvNIXSafeLoginController;
import org.springframework.stereotype.Controller;
@GvNIXSafeLoginController
@Controller
public class SafeLoginController {
}
|
agpl-3.0
|
Kaushikbv/Gluster
|
libglusterfs/src/graph.c
|
15858
|
/*
Copyright (c) 2010 Gluster, Inc. <http://www.gluster.com>
This file is part of GlusterFS.
GlusterFS is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
GlusterFS is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see
<http://www.gnu.org/licenses/>.
*/
#ifndef _CONFIG_H
#define _CONFIG_H
#include "config.h"
#endif
#include "xlator.h"
#include <dlfcn.h>
#include <netdb.h>
#include <fnmatch.h>
#include "defaults.h"
#if 0
static void
_gf_dump_details (int argc, char **argv)
{
extern FILE *gf_log_logfile;
int i = 0;
char timestr[256];
time_t utime = 0;
struct tm *tm = NULL;
pid_t mypid = 0;
struct utsname uname_buf = {{0, }, };
int uname_ret = -1;
utime = time (NULL);
tm = localtime (&utime);
mypid = getpid ();
uname_ret = uname (&uname_buf);
/* Which git? What time? */
strftime (timestr, 256, "%Y-%m-%d %H:%M:%S", tm);
fprintf (gf_log_logfile,
"========================================"
"========================================\n");
fprintf (gf_log_logfile, "Version : %s %s built on %s %s\n",
PACKAGE_NAME, PACKAGE_VERSION, __DATE__, __TIME__);
fprintf (gf_log_logfile, "git: %s\n",
GLUSTERFS_REPOSITORY_REVISION);
fprintf (gf_log_logfile, "Starting Time: %s\n", timestr);
fprintf (gf_log_logfile, "Command line : ");
for (i = 0; i < argc; i++) {
fprintf (gf_log_logfile, "%s ", argv[i]);
}
fprintf (gf_log_logfile, "\nPID : %d\n", mypid);
if (uname_ret == 0) {
fprintf (gf_log_logfile, "System name : %s\n",
uname_buf.sysname);
fprintf (gf_log_logfile, "Nodename : %s\n",
uname_buf.nodename);
fprintf (gf_log_logfile, "Kernel Release : %s\n",
uname_buf.release);
fprintf (gf_log_logfile, "Hardware Identifier: %s\n",
uname_buf.machine);
}
fprintf (gf_log_logfile, "\n");
fflush (gf_log_logfile);
}
#endif
static int
_log_if_option_is_invalid (xlator_t *xl, data_pair_t *pair)
{
volume_opt_list_t *vol_opt = NULL;
volume_option_t *opt = NULL;
int i = 0;
int index = 0;
int found = 0;
/* Get the first volume_option */
list_for_each_entry (vol_opt, &xl->volume_options, list) {
/* Warn for extra option */
if (!vol_opt->given_opt)
break;
opt = vol_opt->given_opt;
for (index = 0;
((index < ZR_OPTION_MAX_ARRAY_SIZE) &&
(opt[index].key && opt[index].key[0])); index++)
for (i = 0; (i < ZR_VOLUME_MAX_NUM_KEY) &&
opt[index].key[i]; i++) {
if (fnmatch (opt[index].key[i],
pair->key,
FNM_NOESCAPE) == 0) {
found = 1;
break;
}
}
}
if (!found) {
gf_log (xl->name, GF_LOG_WARNING,
"option '%s' is not recognized",
pair->key);
}
return 0;
}
int
glusterfs_xlator_link (xlator_t *pxl, xlator_t *cxl)
{
xlator_list_t *xlchild = NULL;
xlator_list_t *xlparent = NULL;
xlator_list_t **tmp = NULL;
xlparent = (void *) GF_CALLOC (1, sizeof (*xlparent),
gf_common_mt_xlator_list_t);
if (!xlparent)
return -1;
xlchild = (void *) GF_CALLOC (1, sizeof (*xlchild),
gf_common_mt_xlator_list_t);
if (!xlchild) {
GF_FREE (xlparent);
return -1;
}
xlparent->xlator = pxl;
for (tmp = &cxl->parents; *tmp; tmp = &(*tmp)->next);
*tmp = xlparent;
xlchild->xlator = cxl;
for (tmp = &pxl->children; *tmp; tmp = &(*tmp)->next);
*tmp = xlchild;
return 0;
}
void
glusterfs_graph_set_first (glusterfs_graph_t *graph, xlator_t *xl)
{
xl->next = graph->first;
if (graph->first)
((xlator_t *)graph->first)->prev = xl;
graph->first = xl;
graph->xl_count++;
}
int
glusterfs_graph_insert (glusterfs_graph_t *graph, glusterfs_ctx_t *ctx,
const char *type, const char *name)
{
xlator_t *ixl = NULL;
if (!ctx->master) {
gf_log ("glusterfs", GF_LOG_ERROR,
"volume \"%s\" can be added from command line only "
"on client side", type);
return -1;
}
ixl = GF_CALLOC (1, sizeof (*ixl), gf_common_mt_xlator_t);
if (!ixl)
return -1;
ixl->ctx = ctx;
ixl->graph = graph;
ixl->options = get_new_dict ();
if (!ixl->options)
goto err;
ixl->name = gf_strdup (name);
if (!ixl->name)
goto err;
if (xlator_set_type (ixl, type) == -1) {
gf_log ("glusterfs", GF_LOG_ERROR,
"%s (%s) initialization failed",
name, type);
return -1;
}
if (glusterfs_xlator_link (ixl, graph->top) == -1)
goto err;
glusterfs_graph_set_first (graph, ixl);
graph->top = ixl;
return 0;
err:
xlator_destroy (ixl);
return -1;
}
int
glusterfs_graph_readonly (glusterfs_graph_t *graph, glusterfs_ctx_t *ctx)
{
int ret = 0;
cmd_args_t *cmd_args = NULL;
cmd_args = &ctx->cmd_args;
if (!cmd_args->read_only)
return 0;
ret = glusterfs_graph_insert (graph, ctx, "features/read-only",
"readonly-autoload");
return ret;
}
int
glusterfs_graph_mac_compat (glusterfs_graph_t *graph, glusterfs_ctx_t *ctx)
{
int ret = 0;
cmd_args_t *cmd_args = NULL;
cmd_args = &ctx->cmd_args;
if (cmd_args->mac_compat == GF_OPTION_DISABLE)
return 0;
ret = glusterfs_graph_insert (graph, ctx, "features/mac-compat",
"mac-compat-autoload");
return ret;
}
static void
gf_add_cmdline_options (glusterfs_graph_t *graph, cmd_args_t *cmd_args)
{
int ret = 0;
xlator_t *trav = NULL;
xlator_cmdline_option_t *cmd_option = NULL;
trav = graph->first;
while (trav) {
list_for_each_entry (cmd_option,
&cmd_args->xlator_options, cmd_args) {
if (!fnmatch (cmd_option->volume,
trav->name, FNM_NOESCAPE)) {
ret = dict_set_str (trav->options,
cmd_option->key,
cmd_option->value);
if (ret == 0) {
gf_log (trav->name, GF_LOG_WARNING,
"adding option '%s' for "
"volume '%s' with value '%s'",
cmd_option->key, trav->name,
cmd_option->value);
} else {
gf_log (trav->name, GF_LOG_WARNING,
"adding option '%s' for "
"volume '%s' failed: %s",
cmd_option->key, trav->name,
strerror (-ret));
}
}
}
trav = trav->next;
}
}
int
glusterfs_graph_validate_options (glusterfs_graph_t *graph)
{
volume_opt_list_t *vol_opt = NULL;
xlator_t *trav = NULL;
int ret = -1;
trav = graph->first;
while (trav) {
if (list_empty (&trav->volume_options))
continue;
vol_opt = list_entry (trav->volume_options.next,
volume_opt_list_t, list);
ret = validate_xlator_volume_options (trav,
vol_opt->given_opt);
if (ret) {
gf_log (trav->name, GF_LOG_ERROR,
"validating translator failed");
return ret;
}
trav = trav->next;
}
return 0;
}
int
glusterfs_graph_init (glusterfs_graph_t *graph)
{
xlator_t *trav = NULL;
int ret = -1;
trav = graph->first;
while (trav) {
ret = xlator_init (trav);
if (ret) {
gf_log (trav->name, GF_LOG_ERROR,
"initializing translator failed");
return ret;
}
trav = trav->next;
}
return 0;
}
int
glusterfs_graph_unknown_options (glusterfs_graph_t *graph)
{
data_pair_t *pair = NULL;
xlator_t *trav = NULL;
trav = graph->first;
/* Validate again phase */
while (trav) {
pair = trav->options->members_list;
while (pair) {
_log_if_option_is_invalid (trav, pair);
pair = pair->next;
}
trav = trav->next;
}
return 0;
}
void
fill_uuid (char *uuid, int size)
{
char hostname[256] = {0,};
struct timeval tv = {0,};
struct tm now = {0, };
char now_str[32];
if (gettimeofday (&tv, NULL) == -1) {
gf_log ("graph", GF_LOG_ERROR,
"gettimeofday: failed %s",
strerror (errno));
}
if (gethostname (hostname, 256) == -1) {
gf_log ("graph", GF_LOG_ERROR,
"gethostname: failed %s",
strerror (errno));
}
localtime_r (&tv.tv_sec, &now);
strftime (now_str, 32, "%Y/%m/%d-%H:%M:%S", &now);
snprintf (uuid, size, "%s-%d-%s:%"GF_PRI_SUSECONDS,
hostname, getpid(), now_str, tv.tv_usec);
return;
}
int
glusterfs_graph_settop (glusterfs_graph_t *graph, glusterfs_ctx_t *ctx)
{
const char *volume_name = NULL;
xlator_t *trav = NULL;
volume_name = ctx->cmd_args.volume_name;
if (!volume_name) {
graph->top = graph->first;
return 0;
}
for (trav = graph->first; trav; trav = trav->next) {
if (strcmp (trav->name, volume_name) == 0) {
graph->top = trav;
return 0;
}
}
return -1;
}
int
glusterfs_graph_parent_up (glusterfs_graph_t *graph)
{
xlator_t *trav = NULL;
int ret = -1;
trav = graph->first;
while (trav) {
if (!xlator_has_parent (trav)) {
ret = xlator_notify (trav, GF_EVENT_PARENT_UP, trav);
}
if (ret)
break;
trav = trav->next;
}
return ret;
}
int
glusterfs_graph_prepare (glusterfs_graph_t *graph, glusterfs_ctx_t *ctx)
{
xlator_t *trav = NULL;
int ret = 0;
/* XXX: CHECKSUM */
/* XXX: attach to -n volname */
ret = glusterfs_graph_settop (graph, ctx);
if (ret) {
gf_log ("graph", GF_LOG_ERROR, "glusterfs graph settop failed");
return -1;
}
/* XXX: RO VOLUME */
ret = glusterfs_graph_readonly (graph, ctx);
if (ret) {
gf_log ("graph", GF_LOG_ERROR, "glusterfs graph readonly failed");
return -1;
}
/* XXX: MAC COMPAT */
ret = glusterfs_graph_mac_compat (graph, ctx);
if (ret) {
gf_log ("graph", GF_LOG_ERROR, "glusterfs graph mac compat failed");
return -1;
}
/* XXX: this->ctx setting */
for (trav = graph->first; trav; trav = trav->next) {
trav->ctx = ctx;
}
/* XXX: DOB setting */
gettimeofday (&graph->dob, NULL);
fill_uuid (graph->graph_uuid, 128);
graph->id = ctx->graph_id++;
/* XXX: --xlator-option additions */
gf_add_cmdline_options (graph, &ctx->cmd_args);
return 0;
}
int
glusterfs_graph_activate (glusterfs_graph_t *graph, glusterfs_ctx_t *ctx)
{
int ret = 0;
/* XXX: all xlator options validation */
ret = glusterfs_graph_validate_options (graph);
if (ret) {
gf_log ("graph", GF_LOG_ERROR, "validate options failed");
return ret;
}
/* XXX: perform init () */
ret = glusterfs_graph_init (graph);
if (ret) {
gf_log ("graph", GF_LOG_ERROR, "init failed");
return ret;
}
ret = glusterfs_graph_unknown_options (graph);
if (ret) {
gf_log ("graph", GF_LOG_ERROR, "unknown options failed");
return ret;
}
/* XXX: log full graph (_gf_dump_details) */
list_add (&graph->list, &ctx->graphs);
ctx->active = graph;
/* XXX: attach to master and set active pointer */
if (ctx->master)
ret = xlator_notify (ctx->master, GF_EVENT_GRAPH_NEW, graph);
if (ret) {
gf_log ("graph", GF_LOG_ERROR, "graph new notification failed");
return ret;
}
/* XXX: perform parent up */
ret = glusterfs_graph_parent_up (graph);
if (ret) {
gf_log ("graph", GF_LOG_ERROR, "parent up notification failed");
return ret;
}
return 0;
}
int
glusterfs_graph_reconfigure (glusterfs_graph_t *oldgraph,
glusterfs_graph_t *newgraph)
{
xlator_t *old_xl = NULL;
xlator_t *new_xl = NULL;
GF_ASSERT (oldgraph);
GF_ASSERT (newgraph);
old_xl = oldgraph->first;
new_xl = newgraph->first;
return xlator_tree_reconfigure (old_xl, new_xl);
}
int
glusterfs_graph_destroy (glusterfs_graph_t *graph)
{
return 0;
}
|
agpl-3.0
|
WebsterFolksLabs/cuttlefish
|
spec/models/email_spec.rb
|
6425
|
require 'spec_helper'
describe Email do
describe "create!" do
it "should set the default app if none is given" do
email = FactoryGirl.create(:email, app_id: nil)
email.app.should be_default_app
end
context "One email is created" do
before :each do
FactoryGirl.create(:email,
from: "matthew@foo.com",
to: "foo@bar.com",
data: "From: contact@openaustraliafoundation.org.au\nTo: Matthew Landauer\nSubject: This is a subject\nMessage-ID: <5161ba1c90b10_7837557029c754c8@kedumba.mail>\n\nHello!"
)
end
it "should set the message-id based on the email content" do
Email.first.message_id.should == "5161ba1c90b10_7837557029c754c8@kedumba.mail"
end
it "should set a hash of the full email content" do
Email.first.data_hash.should == "d096b1b1dfbcabf6bd4ef4d4b0ad88f562eedee9"
end
it "should have an identical hash to another email with identical content" do
first_email = Email.first
email = FactoryGirl.create(:email, from: "geoff@foo.com", to: "people@bar.com", data: first_email.data)
email.data_hash.should == first_email.data_hash
end
it "should have a different hash to another email with different content" do
first_email = Email.first
email = FactoryGirl.create(:email, from: "geoff@foo.com", to: "people@bar.com", data: "Something else")
email.data_hash.should_not == first_email.data_hash
end
it "should set the subject of the email based on the data" do
Email.first.subject.should == "This is a subject"
end
end
end
describe "#from" do
it "should return a string for the from email address" do
email = FactoryGirl.create(:email, from_address: Address.create!(text: "matthew@foo.com"))
email.from.should == "matthew@foo.com"
end
it "should allow the from_address to be set by a string" do
email = FactoryGirl.create(:email, from: "matthew@foo.com")
email.from.should == "matthew@foo.com"
end
end
describe "#from_address" do
it "should return an Address object" do
email = FactoryGirl.create(:email, from: "matthew@foo.org")
a1 = Address.find_by_text("matthew@foo.org")
a1.should_not be_nil
email.from_address.should == a1
end
end
describe "#to" do
it "should return an array for all the email addresses" do
email = FactoryGirl.create(:email, to: ["mlandauer@foo.org", "matthew@bar.com"])
email.to.should == ["mlandauer@foo.org", "matthew@bar.com"]
end
it "should be able to give just a single recipient" do
email = Email.new(to: "mlandauer@foo.org")
email.to.should == ["mlandauer@foo.org"]
end
it "should set created_at for deliveries too" do
email = FactoryGirl.create(:email, to: "mlandauer@foo.org")
email.deliveries.first.created_at.should_not be_nil
end
end
describe "#to_addresses" do
it "should return an array of Address objects" do
email = FactoryGirl.create(:email, to: ["mlandauer@foo.org", "matthew@bar.com"])
a1 = Address.find_by_text("mlandauer@foo.org")
a2 = Address.find_by_text("matthew@bar.com")
a1.should_not be_nil
a2.should_not be_nil
email.to_addresses.should == [a1, a2]
end
end
describe "#data" do
context "one email" do
before :each do
FactoryGirl.create(:email, id: 10, data: "This is a main data section")
end
let(:email) { Email.find(10) }
it "should be able to read in the data again" do
email.data.should == "This is a main data section"
end
it "should be able to read in the data again even after being saved again" do
email.save!
email.data.should == "This is a main data section"
end
end
it "should only keep the full data of a certain number of the emails around" do
EmailDataCache.stub!(:max_no_emails_to_store_data).and_return(2)
4.times { FactoryGirl.create(:email, data: "This is a main section") }
Dir.glob(File.join(EmailDataCache.data_filesystem_directory, "*")).count.should == 2
end
end
context "an email with a text part and an html part" do
let(:mail) do
Mail.new do
text_part do
body 'This is plain text'
end
html_part do
content_type 'text/html; charset=UTF-8'
body '<h1>This is HTML</h1>'
end
end
end
let(:email) do
Email.new(data: mail.encoded)
end
describe "#html_part" do
it { email.html_part.should == "<h1>This is HTML</h1>" }
end
describe "#text_part" do
it { email.text_part.should == "This is plain text" }
end
end
context "an email which just consistents of a single text part" do
let(:mail) do
Mail.new do
body 'This is plain text'
end
end
let(:email) do
Email.new(data: mail.encoded)
end
describe "#html_part" do
it { email.html_part.should be_nil }
end
describe "#text_part" do
it { email.text_part.should == "This is plain text" }
end
end
context "an email which just consistents of a single html part" do
let(:mail) do
Mail.new do
content_type 'text/html; charset=UTF-8'
body '<p>This is some html</p>'
end
end
let(:email) do
Email.new(data: mail.encoded)
end
describe "#html_part" do
it { email.html_part.should == "<p>This is some html</p>" }
end
describe "#text_part" do
it { email.text_part.should be_nil }
end
end
context "an email which consistents of a part that is itself multipart" do
let(:html_part) do
Mail::Part.new do
content_type 'text/html; charset=UTF-8'
body '<p>This is some html</p>'
end
end
let(:text_part) do
Mail::Part.new do
body 'This is plain text'
end
end
let(:mail) do
mail = Mail.new
mail.part :content_type => "multipart/alternative" do |p|
p.html_part = html_part
p.text_part = text_part
end
mail
end
let(:email) do
Email.new(data: mail.encoded)
end
describe "#html_part" do
it { email.html_part.should == "<p>This is some html</p>" }
end
describe "#text_part" do
it { email.text_part.should == 'This is plain text' }
end
end
end
|
agpl-3.0
|
pgdurand/Bioinformatics-UI-API
|
src/bzh/plealog/bioinfo/ui/feature/FeatureStatusViewer.java
|
4589
|
/* Copyright (C) 2006-2016 Patrick G. Durand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/agpl-3.0.txt
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*/
package bzh.plealog.bioinfo.ui.feature;
import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import bzh.plealog.bioinfo.api.data.feature.FeatureTable;
/**
* This component is used to display the status information of a FeatureTable.
*
* @author Patrick G. Durand
*/
public class FeatureStatusViewer extends JPanel {
private static final long serialVersionUID = 9153946953865147941L;
private JTextField _date;
private JTextField _source;
private JTextField _status;
private JTextField _message;
private static final SimpleDateFormat DATE_FOMATTER1 =
new SimpleDateFormat("dd-MMM-yyyy", Locale.UK);
private static final SimpleDateFormat DATE_FOMATTER2 =
new SimpleDateFormat("yyyyMMdd");
public FeatureStatusViewer(){
JLabel lbl;
JPanel pnl1, pnl2, pnl3, pnl4, pnl5;
pnl1 = new JPanel(new BorderLayout());
lbl = new JLabel("Retrieval date:");
_date = createTextField();
pnl1.add(lbl, BorderLayout.WEST);
pnl1.add(_date, BorderLayout.CENTER);
lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
pnl1.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0));
pnl2 = new JPanel(new BorderLayout());
lbl = new JLabel("Feature source:");
_source = createTextField();
pnl2.add(lbl, BorderLayout.WEST);
pnl2.add(_source, BorderLayout.CENTER);
lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
pnl2.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0));
pnl3 = new JPanel(new BorderLayout());
lbl = new JLabel("Message:");
_message = createTextField();
pnl3.add(lbl, BorderLayout.WEST);
pnl3.add(_message, BorderLayout.CENTER);
lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
pnl3.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0));
pnl4 = new JPanel(new BorderLayout());
lbl = new JLabel("Feature status:");
_status = createTextField();
pnl4.add(lbl, BorderLayout.WEST);
pnl4.add(_status, BorderLayout.CENTER);
lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
pnl4.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0));
pnl5 = new JPanel();
pnl5.setLayout(new BoxLayout(pnl5, BoxLayout.Y_AXIS));
pnl5.add(pnl1);
pnl5.add(pnl2);
pnl5.add(pnl4);
pnl5.add(pnl3);
this.setLayout(new BorderLayout());
this.add(pnl5, BorderLayout.NORTH);
}
/**
* Utility method to create a JTextField.
*/
private JTextField createTextField(){
JTextField tf;
tf = new JTextField();
tf.setEditable(false);
tf.setBorder(null);
tf.setOpaque(false);
//tf.setForeground(DDResources.getSystemTextColor());
return tf;
}
/**
* Reset the viewer.
*/
public void clear(){
setData(null);
}
/**
* Utility method to conevert date formats.
*/
private String transformDate(String d){
String date="-";
try {
date = DATE_FOMATTER1.format(DATE_FOMATTER2.parse(d));
} catch (Exception e) {
}
return date;
}
/**
* Sets a new FeatureTable.
*
* @param fTable the feature table to display in this component.
*/
public void setData(FeatureTable fTable){
String val;
if (fTable==null){
_date.setText("");
_source.setText("");
_status.setText("");
_message.setText("");
}
else{
val = fTable.getDate();
_date.setText(val!=null?transformDate(val):"?");
val = fTable.getSource();
_source.setText(val!=null?val:"?");
_status.setText(fTable.getStatus()!=FeatureTable.ERROR_STATUS ?
FeatureTable.OK_STATUS_S : FeatureTable.ERROR_STATUS_S);
val = fTable.getMessage();
_message.setText((val!=null && !val.equals("-"))?val:"None");
}
}
}
|
agpl-3.0
|
ging/isabel
|
components/MCU/app2/demux.h
|
2705
|
/*
* ISABEL: A group collaboration tool for the Internet
* Copyright (C) 2009 Agora System S.A.
*
* This file is part of Isabel.
*
* Isabel is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Isabel 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
* Affero GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with Isabel. If not, see <http://www.gnu.org/licenses/>.
*/
/////////////////////////////////////////////////////////////////////////
//
// $Id: demux.h 6859 2005-06-14 09:57:20Z sirvent $
//
/////////////////////////////////////////////////////////////////////////
#ifndef _MCU_DEMUX_H_
#define _MCU_DEMUX_H_
#include <icf2/vector.hh>
#include <icf2/stdTask.hh>
#include "flowProcessor.h"
class flowDesc_t
{
public:
u8 PT; // Payload
ql_t<flowProcessor_t *> flowProcessorList;
RTPFecReceiver_t *RTPFecReceiver;
flowDesc_t(u8 nPT, u8 fecPT);
~flowDesc_t(void);
};
// save all session info
class addrDesc_t
{
private:
sockaddr_storage addr; // user IP
u16 ID; // user ID
vector_t<flowDesc_t*> flowDescArray;
public:
addrDesc_t(void);
~addrDesc_t(void);
friend class portListener_t;
};
#define MAX_USERS 0xffff
class portListener_t: public simpleTask_t
{
private:
u8 data[MAX_PKT_LEN]; // auxiliar for reading
protected:
// Input data
virtual void IOReady(io_ref &io);
private:
addrDesc_t *addrList[MAX_USERS]; // IP list
dgramSocket_t *socket;
u16 getPosition(sockaddr_storage *);
public:
portListener_t(unsigned int port);
virtual ~portListener_t(void);
// put flow : assigns flow processor for an IP/PT pair
// substitutes old flow processor if exists
HRESULT putFlow(flow_t inFlow,
ql_t<flowProcessor_t *> flowProcessorList
);
HRESULT deleteFlow(flow_t inFlow);
// true if addrList is empty.
bool isEmpty(void);
unsigned int getPort(void);
};
class demux_t
{
private:
vector_t<portListener_t *> portListenerArray;
public:
demux_t(void);
~demux_t(void);
// flow Works
HRESULT putFlow(flow_t inFlow,
ql_t<flowProcessor_t *> flowProcessor
);
HRESULT deleteFlow(flow_t inFlow);
};
#endif
|
agpl-3.0
|
openfaux/openfaux-website
|
HTML/faqs.html
|
4424
|
<!DOCTYPE html>
<html>
<head>
<title>FAQs - OpenFaux</title>
<link href="/IMG/openfaux-icon-128px.png" rel="icon" type="image/ico">
<link href="/CSS/app.css" rel="stylesheet" type="text/css">
</head>
<body>
<!--#include virtual="/INC/header.html"-->
<!--#include virtual="/INC/under_construction.html"-->
<!--I'm sorry but this looks janky...but it might possibly contain something useful...so it's a comment for now.-->
<!--<div id="content" class="row">-->
<!--<table cellspacing="0" cellpadding="0" border="0" width="500" align="center">-->
<!--<tr>-->
<!--<td>-->
<!--<table cellspacing="0" cellpadding="0" border="1" width="500" align="center">-->
<!--<th>Generous Contributors</th>-->
<!--</table>-->
<!--<div style="width:500px; height:275px; overflow:auto;">-->
<!--<table cellspacing="0" cellpadding="0" border="1" width="500" align="center">-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--<tr>-->
<!--<td><b><i>Anonymous Donor</i></b> - $</td>-->
<!--</tr>-->
<!--</table>-->
<!--</div>-->
<!--</td>-->
<!--</tr>-->
<!--</table>-->
<!--</div>-->
<!--#include virtual="/INC/footer.html"-->
</body>
</html>
|
agpl-3.0
|
tugelbend/friendica
|
doc/readme.md
|
1439
|
Friendica Documentation and Resources
=====================================
**Contents**
* General functions - first steps
* [Account Basics](help/Account-Basics)
* [New User Quick Start](help/Quick-Start-guide)
* [Creating posts](help/Text_editor)
* [BBCode tag reference](help/BBCode)
* [Comment, sort and delete posts](help/Text_comment)
* [Profiles](help/Profiles)
* You and other user
* [Connectors](help/Connectors)
* [Making Friends](help/Making-Friends)
* [Groups and Privacy](help/Groups-and-Privacy)
* [Tags and Mentions](help/Tags-and-Mentions)
* [Community Forums](help/Forums)
* [Chats](help/Chats)
* Further information
* [Improve Performance](help/Improve-Performance)
* [Move Account](help/Move-Account)
* [Remove Account](help/Remove-Account)
* [Bugs and Issues](help/Bugs-and-Issues)
* [Frequently asked questions (FAQ)](help/FAQ)
**Technical Documentation**
* [Install](help/Install)
* [Settings](help/Settings)
* [Plugins](help/Plugins)
* [Installing Connectors (Twitter/GNU Social)](help/Installing-Connectors)
* [Message Flow](help/Message-Flow)
* [Using SSL with Friendica](help/SSL)
* [Developers](help/Developers)
* [Twitter/GNU Social API Functions](help/api)
* [Translation of Friendica](help/translations)
**External Resources**
* [Main Website](http://friendica.com)
* [Mailing List Archive](http://librelist.com/browser/friendica/)
**About**
* [Site/Version Info](friendica)
|
agpl-3.0
|
rodrigohubner/openvibe
|
contrib/packages/wavelet2d/wavelet2s.h
|
5213
|
#if defined(TARGET_HAS_ThirdPartyFFTW3)
#ifndef WAVELET2S_H
#define WAVELET2S_H
#include <vector>
#include <complex>
using namespace std;
// 1D Functions
// void* dwt(vector<double> &, int ,string , vector<double> &, vector<double> &);
void* dwt1(string, vector<double> &, vector<double> &, vector<double> &);
void* dyadic_zpad_1d(vector<double> &);
double convol(vector<double> &, vector<double> &, vector<double> &);
int filtcoef(string , vector<double> &, vector<double> &, vector<double> &,
vector<double> &);
void downsamp(vector<double> &, int , vector<double> &);
void upsamp(vector<double> &, int, vector<double> &);
void circshift(vector<double> &, int );
int sign(int);
void* idwt1(string wname, vector<double> &, vector<double> &, vector<double> &);
int vecsum(vector<double> &, vector<double> &, vector<double> &);
// 1D Symmetric Extension DWT Functions
void* dwt_sym(vector<double> &, int ,string , vector<double> &,vector<double> &,
vector<int> &);
void* dwt1_sym(string , vector<double> &, vector<double> &, vector<double> &);
void* idwt_sym(vector<double> &,vector<double> &, string,vector<double> &, vector<int> &);
void* symm_ext(vector<double> &, int );
void* idwt1_sym(string, vector<double> &, vector<double> &, vector<double> &); // Not Tested
// 1D Stationary Wavelet Transform
void* swt(vector<double> &, int , string , vector<double> &, int &) ;
void* iswt(vector<double> &,int , string, vector<double> &);
void* per_ext(vector<double> &, int );
// 2D Functions
void* branch_lp_dn(string , vector<double> &, vector<double> &);
void* branch_hp_dn(string , vector<double> &, vector<double> &);
void* branch_lp_hp_up(string ,vector<double> &, vector<double> &, vector<double> &);
// void* dwt_2d(vector<vector<double> > &, int , string , vector<vector<double> > &
// , vector<double> &) ;
// void* idwt_2d(vector<vector<double> > &,vector<double> &, string ,vector<vector<double> > &);
void* dyadic_zpad_2d(vector<vector<double> > &,vector<vector<double> > &);
void* dwt_output_dim(vector<vector<double> >&, int &, int & );
void* zero_remove(vector<vector<double> > &,vector<vector<double> > &) ;
void* getcoeff2d(vector<vector<double> > &, vector<vector<double> > &,
vector<vector<double> > &,vector<vector<double> > &,vector<double> &, int &);
void* idwt2(string ,vector<vector<double> > &, vector<vector<double> > &,
vector<vector<double> > &, vector<vector<double> > &, vector<vector<double> > &);
void* dwt2(string ,vector<vector<double> > &, vector<vector<double> > &,
vector<vector<double> > &, vector<vector<double> > &, vector<vector<double> > &);
void* downsamp2(vector<vector<double> > &,vector<vector<double> > &, int, int);
void* upsamp2(vector<vector<double> > &,vector<vector<double> > &, int, int);
// 2D DWT (Symmetric Extension) Functions
void* dwt_2d_sym(vector<vector<double> > &, int , string , vector<double> &, vector<double> & ,
vector<int> &);
void* dwt2_sym(string ,vector<vector<double> > &, vector<vector<double> > &,
vector<vector<double> > &, vector<vector<double> > &, vector<vector<double> > &);
void* idwt_2d_sym(vector<double> &,vector<double> &, string ,vector<vector<double> > &,
vector<int> &);
void* circshift2d(vector<vector<double> > &, int , int );
void symm_ext2d(vector<vector<double> > &,vector<vector<double> > &, int );
void* dispDWT(vector<double> &,vector<vector<double> > &, vector<int> &, vector<int> &, int ) ;
void* dwt_output_dim_sym(vector<int> &,vector<int> &, int );
//2D Stationary Wavelet Transform
void* swt_2d(vector<vector<double> > &,int , string , vector<double> &);
void* per_ext2d(vector<vector<double> > &,vector<vector<double> > &, int );
// FFT functions
double convfft(vector<double> &, vector<double> &, vector<double> &);
double convfftm(vector<double> &, vector<double> &, vector<double> &);
void* fft(vector<complex<double> > &,int ,unsigned int);
void* bitreverse(vector<complex<double> > &);
void* freq(vector<double> &, vector<double> &);
//New
void* dwt1_sym_m(string wname, vector<double> &signal, vector<double> &cA, vector<double> &cD);//FFTW3 for 2D
void* idwt1_sym_m(string wname, vector<double> &X, vector<double> &app, vector<double> &detail);
void* dwt(vector<double> &sig, int J, string nm, vector<double> &dwt_output
, vector<double> &flag, vector<int> &length );
void* idwt(vector<double> &,vector<double> &, string,vector<double> &, vector<int> &);
void* dwt_2d(vector<vector<double> > &, int , string , vector<double> &, vector<double> & ,
vector<int> &);
void* dwt1_m(string wname, vector<double> &signal, vector<double> &cA, vector<double> &cD) ;
void* idwt_2d(vector<double> &dwtop,vector<double> &flag, string nm,
vector<vector<double> > &idwt_output, vector<int> &length);
void* idwt1_m(string wname, vector<double> &X, vector<double> &cA, vector<double> &cD);
void* dwt_output_dim2(vector<int> &length, vector<int> &length2, int J);
#endif/* WAVELET2S_H */
#endif
|
agpl-3.0
|
Tesora/tesora-dve-pub
|
tesora-dve-core/src/test/java/com/tesora/dve/sql/FunctionsTest.java
|
26017
|
package com.tesora.dve.sql;
/*
* #%L
* Tesora Inc.
* Database Virtualization Engine
* %%
* Copyright (C) 2011 - 2014 Tesora Inc.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.tesora.dve.errmap.MySQLErrors;
import com.tesora.dve.resultset.ResultRow;
import com.tesora.dve.server.bootstrap.BootstrapHost;
import com.tesora.dve.sql.util.DBHelperConnectionResource;
import com.tesora.dve.sql.util.PEDDL;
import com.tesora.dve.sql.util.ProjectDDL;
import com.tesora.dve.sql.util.ProxyConnectionResource;
import com.tesora.dve.sql.util.ResourceResponse;
import com.tesora.dve.sql.util.StorageGroupDDL;
import com.tesora.dve.standalone.PETest;
public class FunctionsTest extends SchemaTest {
private static final ProjectDDL checkDDL = new PEDDL("checkdb",
new StorageGroupDDL("check", 2, "checkg"), "schema");
@BeforeClass
public static void setup() throws Exception {
PETest.projectSetup(checkDDL);
PETest.bootHost = BootstrapHost.startServices(PETest.class);
}
protected ProxyConnectionResource conn;
protected DBHelperConnectionResource dbh;
@Before
public void connect() throws Throwable {
conn = new ProxyConnectionResource();
checkDDL.create(conn);
dbh = new DBHelperConnectionResource();
}
@After
public void disconnect() throws Throwable {
if(conn != null)
conn.disconnect();
conn = null;
if(dbh != null)
dbh.disconnect();
dbh = null;
}
@Test
public void testLowerWithLike() throws Throwable {
conn.execute("create table `a` (`id` int, `mask` varchar(50), primary key (`id`)) ");
String select = "select 1 from a where id=1 and lower('MiXeD cAsE') like lower(mask)";
// query should return empty result set
conn.assertResults(select, br());
// insert a row that does not satisfy the lower clause
conn.execute("insert into a values (1,'some junk')");
// query should return empty result set
conn.assertResults(select, br());
// update row so that it does satisfy the lower clause
conn.execute("update a set mask='MIXED CASE'");
// query should return 1 row
conn.assertResults(select, br(nr, Long.valueOf(1)));
// make sure we didn't break the typical like parameter
select = "select 1 from a where id=1 and mask like '%C%'";
conn.assertResults(select, br(nr, Long.valueOf(1)));
}
@Test
public void testUnix_timestamp() throws Throwable {
conn.execute("create table `tblUnixTS` (`id` int, `d` date, `dt` datetime, `ts` timestamp, primary key (`id`)) ");
// these are the acceptable values that can be put into the unix_timestamp function
String dateLiteral = "'1997-01-01'";
String datetimeLiteral = "'1998-02-02 00:00:01'";
String timestampLiteral = "'1999-03-03 23:59:59'";
long dateFormat1Long = 970101;
long dateFormat2Long = 19970101;
conn.execute("insert into tblUnixTS values (1,"+ dateLiteral + "," + datetimeLiteral + "," + timestampLiteral + ")");
// all the values are before the current time so no rows should be returned
conn.assertResults("select 1 from tblUnixTS where unix_timestamp(d) > unix_timestamp()",
br());
conn.assertResults("select 1 from tblUnixTS where unix_timestamp(dt) > unix_timestamp()",
br());
conn.assertResults("select 1 from tblUnixTS where unix_timestamp(ts) > unix_timestamp()",
br());
// this should return the row if we reverse the comparison operator
conn.assertResults("select 1 from tblUnixTS where unix_timestamp(d) < unix_timestamp()",
br(nr, Long.valueOf(1)));
conn.assertResults("select 1 from tblUnixTS where unix_timestamp(dt) < unix_timestamp()",
br(nr, Long.valueOf(1)));
conn.assertResults("select 1 from tblUnixTS where unix_timestamp(ts) < unix_timestamp()",
br(nr, Long.valueOf(1)));
// make sure using a literal or a column definition as a parameter returns the same value
compareUnixTimestampParamLiteralVSColumn(
"select unix_timestamp(" + dateLiteral + ")",
"select unix_timestamp(d) from tblUnixTS where id=1");
compareUnixTimestampParamLiteralVSColumn(
"select unix_timestamp(" + datetimeLiteral + ")",
"select unix_timestamp(dt) from tblUnixTS where id=1");
compareUnixTimestampParamLiteralVSColumn(
"select unix_timestamp(" + timestampLiteral + ")",
"select unix_timestamp(ts) from tblUnixTS where id=1");
compareUnixTimestampParamLiteralVSColumn(
"select unix_timestamp(" + dateFormat1Long + ")",
"select unix_timestamp(d) from tblUnixTS where id=1");
compareUnixTimestampParamLiteralVSColumn(
"select unix_timestamp(" + dateFormat2Long + ")",
"select unix_timestamp(d) from tblUnixTS where id=1");
}
private void compareUnixTimestampParamLiteralVSColumn(String literalSql,
String columnSql) throws Throwable {
ResourceResponse resp = conn.fetch(literalSql);
List<ResultRow> rows = resp.getResults();
assertEquals("Expected one row only", 1, rows.size());
Long literalLong = (Long) (rows.get(0).getResultColumn(1)
.getColumnValue());
resp = conn.fetch(columnSql);
rows = resp.getResults();
assertEquals("Expected one row only", 1, rows.size());
Long columnLong = (Long) (rows.get(0).getResultColumn(1)
.getColumnValue());
assertEquals("Expected literal query (" + literalSql
+ ") to return same value as column query (" + columnSql + ")",
literalLong, columnLong);
}
@Test
public void testPE167() throws Throwable {
conn.execute("create table ucp (`vid` integer unsigned not null, `length` integer, `width` integer, `height` integer);");
// test length as a column name
String select = "SELECT length, width, height FROM ucp WHERE vid = 7710429";
// query should return empty result set
conn.assertResults(select, br());
}
@Test
public void testPE168() throws Throwable {
conn.execute("create table urs (`uid` integer unsigned not null, `created` timestamp);");
String select;
String[] units = {"MICROSECOND", "SECOND", "MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "QUARTER", "YEAR" };
for (String unit : units) {
select = "SELECT uid FROM `urs` WHERE uid=420185 AND TIMESTAMPDIFF(" + unit + ", FROM_UNIXTIME(created), NOW()) <= 3";
// query should return empty result set
conn.assertResults(select, br());
}
// use a literal as a parameter
select = "SELECT uid FROM `urs` WHERE uid=420185 AND TIMESTAMPDIFF(DAY, '2012-01-01', '2012-01-01')";
// query should return empty result set
conn.assertResults(select, br());
try {
select = "SELECT uid FROM `urs` WHERE uid=420185 AND TIMESTAMPDIFF(JUNK, '2012-01-01', '2012-01-01')";
conn.assertResults(select, br());
fail("JUNK is not a valid unit for timestampdiff");
} catch (Exception e) {
// expected
}
}
@Test
public void test_PE222_utc_timestamp() throws Throwable {
// From the doc: utc_timestamp returns the current UTC date and time
// as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format,
// depending on whether the function is used in a string or numeric context.
Timestamp ts;
// try with and without parens
ResourceResponse resp = conn.fetch("SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0");
List<ResultRow> rows = resp.getResults();
assertEquals("Expected one row only", 1, rows.size());
// If the types don't cast properly then we have a problem
assertNotNull(ts = (Timestamp) (rows.get(0).getResultColumn(1).getColumnValue()));
assertNotNull((rows.get(0).getResultColumn(2).getColumnValue()));
// put function into an insert
conn.execute("create table `tblUTCTS` (`id` int, `ts` timestamp, primary key (`id`)) ");
conn.execute("insert into tblUTCTS values (1, utc_timestamp())");
// just make sure the ts2 is equal or after the above ts
Timestamp ts2;
resp = conn.fetch("select ts from tblUTCTS");
rows = resp.getResults();
assertEquals("Expected one row only", 1, rows.size());
assertNotNull(ts2 = (Timestamp) (rows.get(0).getResultColumn(1).getColumnValue()));
assertTrue(ts.compareTo(ts2)<1);
}
@Test
public void test_PE136_REGEXP() throws Throwable {
StringBuilder buf = new StringBuilder();
buf.append("CREATE TABLE wpo (");
buf.append("oid bigint(20) unsigned NOT NULL auto_increment,");
buf.append("onm varchar(64) NOT NULL default '',");
buf.append("ov longtext NOT NULL,");
buf.append("al varchar(20) NOT NULL default 'yes',");
buf.append("PRIMARY KEY (oid),");
buf.append("UNIQUE KEY onm (onm)");
buf.append(") DEFAULT CHARACTER SET utf8 ");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("INSERT INTO `wpo` (");
buf.append("`onm`, `ov`, `al`) ");
buf.append("VALUES (");
buf.append("'_site_transient_timeout_theme_roots', '1325536233', 'yes') ");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("INSERT INTO `wpo` (");
buf.append("`onm`, `ov`, `al`) ");
buf.append("VALUES (");
buf.append("'rss_00000000000000000000000000000000', '0000000000', 'no') ");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("SELECT `onm`, `ov`, `al` ");
buf.append("FROM wpo WHERE onm REGEXP '^rss_[0-9a-f]{32}(_ts)?$'");
conn.assertResults(buf.toString(),
br(nr, "rss_00000000000000000000000000000000", "0000000000", "no"));
buf = new StringBuilder();
buf.append("SELECT `onm`, `ov`, `al` ");
buf.append("FROM wpo WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'");
conn.assertResults(buf.toString(),
br(nr, "rss_00000000000000000000000000000000", "0000000000", "no"));
buf = new StringBuilder();
buf.append("UPDATE wpo ");
buf.append("SET `ov`='1111111111' ");
buf.append("WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("SELECT `onm`, `ov`, `al` ");
buf.append("FROM wpo WHERE onm RLIKE '^[0-9a-f]{32}(_ts)?$'");
conn.assertResults(buf.toString(),
br());
buf = new StringBuilder();
buf.append("SELECT `onm`, `ov`, `al` ");
buf.append("FROM wpo WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'");
conn.assertResults(buf.toString(),
br(nr, "rss_00000000000000000000000000000000", "1111111111", "no"));
buf = new StringBuilder();
buf.append("DELETE FROM wpo ");
buf.append("WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("SELECT `onm`, `ov`, `al` ");
buf.append("FROM wpo WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'");
conn.assertResults(buf.toString(),
br());
}
@Test
public void test_NULLIF() throws Throwable {
StringBuilder buf = new StringBuilder();
buf.append("CREATE TABLE wp_usermeta (");
buf.append("umid bigint(20) unsigned NOT NULL auto_increment,");
buf.append("uid bigint(20) unsigned NOT NULL default '0',");
buf.append("mk varchar(255) default NULL,");
buf.append("mv longtext,");
buf.append("PRIMARY KEY (umid),");
buf.append("KEY uid (uid),");
buf.append("KEY mk (mk)");
buf.append(") DEFAULT CHARACTER SET utf8 ");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("INSERT INTO `wp_usermeta` (");
buf.append("`uid`,`mk`,`mv`) ");
buf.append("VALUES ");
buf.append("('1','last_name',''),");
buf.append("('1','nickname','admin'),");
buf.append("('1','description',''),");
buf.append("('1','rich_editing','true'),");
buf.append("('1','comment_shortcuts','false'),");
buf.append("('1','admin_color','fresh'),");
buf.append("('1','use_ssl','0'),");
buf.append("('1','show_admin_bar_front','true'),");
buf.append("('1','wp_capabilities','a:1:{s:10:\"subscriber\";s:1:\"1\";}'),");
buf.append("('1','wp_user_level','0'),");
buf.append("('1','dismissed_wp_pointers','wp330_toolbar,wp330_media_uploader,wp330_saving_widgets'),");
buf.append("('1','show_welcome_panel','1'),");
buf.append("('1','wp_dashboard_quick_press_last_post_id','3')");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("SELECT ");
buf.append("COUNT(NULLIF(`mv` LIKE '%administrator%', FALSE)),");
buf.append("COUNT(NULLIF(`mv` LIKE '%editor%', FALSE)),");
buf.append("COUNT(NULLIF(`mv` LIKE '%author%', FALSE)),");
buf.append("COUNT(NULLIF(`mv` LIKE '%contributor%', FALSE)),");
buf.append("COUNT(NULLIF(`mv` LIKE '%subscriber%', FALSE)),");
buf.append("COUNT(*) ");
buf.append("FROM wp_usermeta ");
buf.append("WHERE mk = 'wp_capabilities'");
conn.assertResults(buf.toString(),
br(nr, Long.valueOf(0), Long.valueOf(0), Long.valueOf(0), Long.valueOf(0), Long.valueOf(1), Long.valueOf(1)));
}
@Test
public void test_DATE_SUB_or_ADD_and_YEAR_MONTH() throws Throwable {
StringBuilder buf = new StringBuilder();
buf.append("CREATE TABLE wpp (");
buf.append("ID bigint(20) unsigned NOT NULL auto_increment,");
buf.append("pd datetime NOT NULL default '0000-00-00 00:00:00',");
buf.append("ps varchar(20) NOT NULL default 'publish',");
buf.append("pt varchar(20) NOT NULL default 'post',");
buf.append("PRIMARY KEY (ID)");
buf.append(") DEFAULT CHARACTER SET utf8 ");
buf.append("BROADCAST DISTRIBUTE ");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("CREATE TABLE a_broadcast_table_to_join (");
buf.append("ID bigint(20) unsigned NOT NULL auto_increment,");
buf.append("pt varchar(20) NOT NULL default 'post',");
buf.append("PRIMARY KEY (ID)");
buf.append(") DEFAULT CHARACTER SET utf8 ");
buf.append("BROADCAST DISTRIBUTE ");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("CREATE TABLE a_random_table_to_join (");
buf.append("ID bigint(20) unsigned NOT NULL auto_increment,");
buf.append("pt varchar(20) NOT NULL default 'post',");
buf.append("PRIMARY KEY (ID)");
buf.append(") DEFAULT CHARACTER SET utf8 ");
buf.append("RANDOM DISTRIBUTE ");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("INSERT INTO `wpp` (");
buf.append("`pd`) ");
buf.append("VALUES ");
buf.append("('2012-01-02 18:30:33')");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("INSERT INTO `wpp` (");
buf.append("`pd`,`pt`) ");
buf.append("VALUES ");
buf.append("('2012-02-02 18:30:33','page')");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("INSERT INTO `wpp` (");
buf.append("`pd`,`ps`,`pt`) ");
buf.append("VALUES ");
buf.append("('2012-03-02 18:31:00','auto-draft','post')");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("SELECT ID ");
buf.append("FROM wpp ");
buf.append("WHERE ps = 'auto-draft' ");
buf.append("AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > pd ");
conn.assertResults(buf.toString(),
br(nr, Long.valueOf(3)));
buf = new StringBuilder();
buf.append("SELECT ID ");
buf.append("FROM wpp ");
buf.append("WHERE DATE_ADD( '2012-01-01 18:31:00', INTERVAL 2 DAY ) > pd ");
conn.assertResults(buf.toString(),
br(nr, Long.valueOf(1)));
buf = new StringBuilder();
buf.append("SELECT DISTINCT YEAR( pd ) AS year, MONTH( pd) AS month ");
buf.append("FROM wpp ");
buf.append("WHERE pt = 'page' ");
buf.append("ORDER BY pd desc");
conn.assertResults(buf.toString(),
br(nr, Integer.valueOf(2012), Integer.valueOf(2)));
// make sure the following don't throw exceptions
buf = new StringBuilder();
buf.append("SELECT DISTINCT YEAR( p.pd ) AS year, MONTH( p.pd) AS month ");
buf.append("FROM wpp p INNER JOIN a_broadcast_table_to_join j ");
buf.append("ON p.ID = j.ID ");
buf.append("ORDER BY pd desc");
conn.assertResults(buf.toString(),
br());
buf = new StringBuilder();
buf.append("SELECT DISTINCT YEAR( p.pd ) AS year, MONTH( p.pd) AS month ");
buf.append("FROM wpp p INNER JOIN a_random_table_to_join j ");
buf.append("ON p.ID = j.ID ");
buf.append("ORDER BY pd desc");
conn.assertResults(buf.toString(),
br());
}
@Test
public void testPE775() throws Throwable {
StringBuilder buf = new StringBuilder();
buf.append("CREATE TABLE `umt` ( ");
buf.append("`uid` int(11) NOT NULL, ");
buf.append("`token` varchar(100) NOT NULL, ");
buf.append("`datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, ");
buf.append("PRIMARY KEY (`token`), ");
buf.append("KEY `uid` (`uid`) ");
buf.append(") ENGINE=MyISAM DEFAULT CHARSET=utf8 /*#dve BROADCAST DISTRIBUTE */ ");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("INSERT INTO umt (uid,token,datetime) ");
buf.append("VALUES ");
buf.append("(2904,'c0ab2d0a53de4522223ae0c8d08e871294debbe29a72fba8c38b326ad7261507',now())");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("SELECT count(*) FROM umt");
conn.assertResults(buf.toString(), br(nr, Long.valueOf(1)));
buf = new StringBuilder();
buf.append("SELECT datetime FROM umt");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("UPDATE umt SET datetime=now()");
conn.execute(buf.toString());
}
@Test
public void testPE951_LEFT() throws Throwable {
StringBuilder buf = new StringBuilder();
buf.append("CREATE TABLE `pe951` ( `value` varchar(100) NOT NULL )");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("INSERT INTO pe951 VALUES ('123456789012345678901234567890'), ('This is a test string')");
conn.execute(buf.toString());
buf = new StringBuilder();
buf.append("SELECT value FROM pe951 ORDER BY value");
conn.assertResults(buf.toString(),
br(nr, "123456789012345678901234567890", nr, "This is a test string"));
buf = new StringBuilder();
buf.append("SELECT LEFT(value,10) FROM pe951 ORDER BY value");
conn.assertResults(buf.toString(),
br(nr, "1234567890", nr, "This is a "));
}
@Test
public void testPE988_REPLACE() throws Throwable {
final String test1 = "SELECT REPLACE('Hello, World!', 'Hello', 'Hi')";
conn.assertResults(test1, br(nr, "Hi, World!"));
conn.execute("CREATE TABLE `pe988` ( `id` int(11) NOT NULL"
+ ", `name` varchar(256) NOT NULL )");
conn.execute("INSERT INTO `pe988` VALUES (1, 'float')");
conn.execute("INSERT INTO `pe988` VALUES (2, ' int')");
conn.execute("INSERT INTO `pe988` VALUES (3, 'text ')");
conn.execute("INSERT INTO `pe988` VALUES (4, ' char ')");
conn.execute("INSERT INTO `pe988` VALUES (5, 'long long')");
conn.execute("INSERT INTO `pe988` VALUES (6, ' tiny text')");
conn.execute("INSERT INTO `pe988` VALUES (7, 'unsigned int ')");
conn.execute("INSERT INTO `pe988` VALUES (8, ' long double ')");
conn.execute("INSERT INTO `pe988` VALUES (9, ' some long text with spaces and tabs ');");
final String test2 = "SELECT REPLACE(pe988.name, ' ', '-') FROM pe988 ORDER BY id";
conn.assertResults(test2, br(
nr, "float",
nr, "-int",
nr, "text-",
nr, "-char-",
nr, "long-long",
nr, "-tiny-text",
nr, "unsigned-int-",
nr, "-long-double-",
nr, "--some--long--text---with--spaces--and tabs--"));
}
@Test
public void testPE1156_GroupConcatMaxLen() throws Throwable {
final String test = "SELECT GROUP_CONCAT('a', 'b', 'c', 'd', 'e', 'f', 'g')";
conn.assertResults(test, br(nr, "abcdefg"));
conn.execute("SET SESSION group_concat_max_len = 5");
conn.assertResults(test, br(nr, "abcde"));
}
@Test
public void testPE362_Char() throws Throwable {
final String test1In = "SELECT CHAR(77,121,83,81,'76')";
final String test1Out = "MySQL";
/* By default, CHAR() returns a binary string. */
conn.assertResults(test1In, br(nr, test1Out.getBytes()));
conn.assertResults(
"SELECT CHAR(0x4E, NULL, 0x55, NULL, 0x4C, NULL, 0x4C USING utf8)",
br(nr, "NULL"));
}
@Ignore
@Test
public void testPE347_Interval() throws Throwable {
conn.assertResults("SELECT INTERVAL(55,10,20,30,40,50,60,70,80,90,100)", br(nr, 5));
conn.assertResults("SELECT INTERVAL(3,1,1+1,1+1+1+1)", br(nr, 2));
conn.assertResults("SELECT INTERVAL(0,1,2,3,4)", br(nr, 0));
conn.assertResults("SELECT INTERVAL(NULL,1,2,3,4)", br(nr, -1));
}
@Ignore
@Test
public void testPE347_Elt() throws Throwable {
conn.assertResults("SELECT ELT(2,\"ONE\",\"TWO\",\"THREE\")", br(nr, "TWO"));
conn.assertResults("SELECT ELT(0,\"ONE\",\"TWO\",\"THREE\")", br(nr, null));
conn.assertResults("SELECT ELT(4,\"ONE\",\"TWO\",\"THREE\")", br(nr, null));
conn.assertResults("SELECT ELT(1,1,2,3)|0)", br(nr, 1));
conn.assertResults("SELECT ELT(1,1.1,1.2,1.3)+0)", br(nr, 1.1));
}
@Test
public void testPE347_Field() throws Throwable {
conn.assertResults("SELECT FIELD(\"IBM\",\"NCA\",\"ICL\",\"SUN\",\"IBM\",\"DIGITAL\")", br(nr, 4l));
conn.assertResults("SELECT FIELD(\"TESORA\",\"NCA\",\"ICL\",\"SUN\",\"IBM\",\"DIGITAL\")", br(nr, 0l));
}
@Test
public void testPE1403_Rand() throws Throwable {
new ExpectedSqlErrorTester() {
@Override
public void test() throws Throwable {
conn.execute("SELECT RAND(1,2,3)");
}
}.assertError(SchemaException.class, MySQLErrors.incorrectParamCountFormatter,
"RAND");
assertResultDistribution("SELECT RAND()", 1, 1, 10, true);
assertResultDistribution("SELECT RAND(0)", 1, 1, 10, false);
assertResultDistribution("SELECT RAND(5)", 1, 1, 10, false);
conn.execute("CREATE TABLE pe1403 (id INT NOT NULL)");
conn.execute("INSERT INTO pe1403 VALUES (1), (2), (3), (4), (5), (6)");
assertResultDistribution("SELECT id, RAND() FROM pe1403", 2, 6, 1, true);
assertResultDistribution("SELECT id, RAND(0) FROM pe1403", 2, 6, 1, true);
assertResultDistribution("SELECT id, RAND(5) FROM pe1403", 2, 6, 1, true);
}
private void assertResultDistribution(final String stmt, final int columnIndex, final int expectedNumRows, final int numTrials, final boolean assertRandom)
throws Throwable {
final Set<Object> results = new HashSet<Object>(numTrials);
for (int i = 0; i < numTrials; ++i) {
final ResourceResponse response = conn.execute(stmt);
final List<ResultRow> rows = response.getResults();
assertEquals("Wrong number of rows in the result set.", expectedNumRows, rows.size());
for (final ResultRow row : rows) {
results.add(row.getResultColumn(columnIndex).getColumnValue());
}
}
if (assertRandom) {
assertTrue("Random results expected.", results.size() == (expectedNumRows * numTrials));
} else {
assertTrue("Equal results expected.", results.size() == 1);
}
}
@Test
public void testPE311_XOR() throws Throwable {
conn.assertResults("SELECT 1 XOR 1", br(nr, 0l));
conn.assertResults("SELECT 1 XOR 0", br(nr, 1l));
conn.assertResults("SELECT 1 XOR NULL", br(nr, null));
conn.assertResults("SELECT 1 XOR 1 XOR 1", br(nr, 1l));
conn.execute("CREATE TABLE `pe311` (`id` int, `value` varchar(10), PRIMARY KEY (`id`))");
conn.execute("INSERT INTO `pe311` VALUES (1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')");
conn.assertResults("SELECT id XOR id, value FROM pe311 WHERE ((id > 2) XOR (id < 4)) ORDER BY id ASC",
br(nr, 0l, "one", nr, 0l, "two", nr, 0l, "four", nr, 0l, "five"));
}
@Test
public void testPE761() throws Throwable {
conn.execute("CREATE TABLE `pe761_A` (`value` int)");
conn.execute("INSERT INTO `pe761_A` VALUES (1), (2), (3), (4)");
conn.assertResults("SELECT ROUND(VAR_SAMP(`value`), 4) FROM `pe761_A`", br(nr, 1.6667));
conn.assertResults("SELECT ROUND(VARIANCE(`value`), 4) FROM `pe761_A`", br(nr, 1.2500));
conn.assertResults("SELECT ROUND(VAR_POP(`value`), 4) FROM `pe761_A`", br(nr, 1.2500));
conn.assertResults("SELECT ROUND(STDDEV_SAMP(`value`), 4) FROM `pe761_A`", br(nr, 1.2910));
conn.assertResults("SELECT ROUND(STDDEV(`value`), 4) FROM `pe761_A`", br(nr, 1.1180));
conn.assertResults("SELECT ROUND(STD(`value`), 4) FROM `pe761_A`", br(nr, 1.1180));
conn.assertResults("SELECT ROUND(STDDEV_POP(`value`), 4) FROM `pe761_A`", br(nr, 1.1180));
conn.execute("CREATE TABLE `pe761_B` (`id` int not null, `value` int)");
conn.execute("INSERT INTO `pe761_B` VALUES (1, 1), (1, 2), (1, 3),"
+ "(2, 4), (2, 5), (2, 6), (3, 7), (3, 8), (3, 9)");
conn.assertResults("SELECT ROUND(VAR_SAMP(`value`), 4) FROM `pe761_B` GROUP BY `id`",
br(nr, 1.0, nr, 1.0, nr, 1.0));
conn.assertResults("SELECT ROUND(VARIANCE(`value`), 4) FROM `pe761_B` GROUP BY `id`",
br(nr, 0.6667, nr, 0.6667, nr, 0.6667));
conn.assertResults("SELECT ROUND(VAR_POP(`value`), 4) FROM `pe761_B` GROUP BY `id`",
br(nr, 0.6667, nr, 0.6667, nr, 0.6667));
conn.assertResults("SELECT ROUND(STDDEV_SAMP(`value`), 4) FROM `pe761_B` GROUP BY `id`",
br(nr, 1.0, nr, 1.0, nr, 1.0));
conn.assertResults("SELECT ROUND(STDDEV(`value`), 4) FROM `pe761_B` GROUP BY `id`",
br(nr, 0.8165, nr, 0.8165, nr, 0.8165));
conn.assertResults("SELECT ROUND(STD(`value`), 4) FROM `pe761_B` GROUP BY `id`",
br(nr, 0.8165, nr, 0.8165, nr, 0.8165));
conn.assertResults("SELECT ROUND(STDDEV_POP(`value`), 4) FROM `pe761_B` GROUP BY `id`",
br(nr, 0.8165, nr, 0.8165, nr, 0.8165));
}
@Test
public void testPower() throws Throwable {
conn.assertResults("SELECT POW(3, 2)", br(nr, 9.0));
conn.assertResults("SELECT POWER(3, 3)", br(nr, 27.0));
}
}
|
agpl-3.0
|
mimmi20/Wurfl
|
src/Configuration/FileConfig.php
|
2589
|
<?php
/**
* Copyright (c) 2015 ScientiaMobile, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Refer to the COPYING.txt file distributed with this package.
*
*
* @category WURFL
* @copyright ScientiaMobile, Inc.
* @license GNU Affero General Public License
*/
namespace Wurfl\Configuration;
use Noodlehaus\Config as ConfigLoader;
/**
* XML Configuration
*/
class FileConfig extends Config
{
/**
* Creates a new WURFL Configuration object from $configFilePath
*
* @param string $configFilePath Complete filename of configuration file
*
* @throws \InvalidArgumentException
*/
public function __construct($configFilePath)
{
if (!file_exists($configFilePath)) {
throw new \InvalidArgumentException('The configuration file ' . $configFilePath . ' does not exist.');
}
$this->configFilePath = $configFilePath;
$this->configurationFileDir = dirname($this->configFilePath);
$configLoader = new ConfigLoader($this->configFilePath);
$this->initialize($configLoader->all());
}
/**
* WURFL XML Schema
*
* @var string
*/
const WURFL_CONF_SCHEMA = "<?xml version='1.0' encoding='utf-8' ?>
<element name='wurfl-config' xmlns='http://relaxng.org/ns/structure/1.0'>
<element name='wurfl'>
<element name='main-file'><text/></element>
<element name='patches'>
<zeroOrMore>
<element name='patch'><text/></element>
</zeroOrMore>
</element>
</element>
<optional>
<element name='allow-reload'><text/></element>
</optional>
<optional>
<element name='match-mode'><text/></element>
</optional>
<optional>
<element name='logDir'><text/></element>
</optional>
<element name='persistence'>
<element name='provider'><text/></element>
<optional>
<element name='params'><text/></element>
</optional>
</element>
<element name='cache'>
<element name='provider'><text/></element>
<optional>
<element name='params'><text/></element>
</optional>
</element>
</element>";
}
|
agpl-3.0
|
AtnNn/rethinkdb
|
src/rdb_protocol/exceptions.hpp
|
1921
|
// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_EXCEPTIONS_HPP_
#define RDB_PROTOCOL_EXCEPTIONS_HPP_
#include <string>
#include "utils.hpp"
#include "rdb_protocol/bt.hpp"
#include "rpc/serialize_macros.hpp"
namespace query_language {
/* Thrown if the client sends a malformed or nonsensical query (e.g. a
protocol buffer that doesn't match our schema or STOP for an
unknown token). */
class broken_client_exc_t : public std::exception {
public:
explicit broken_client_exc_t(const std::string &_what) : message(_what) { }
~broken_client_exc_t() throw () { }
const char *what() const throw () {
return message.c_str();
}
std::string message;
};
/* `bad_query_exc_t` is thrown if the user writes a query that
accesses undefined variables or that has mismatched types. The
difference between this and `broken_client_exc_t` is that
`broken_client_exc_t` is the client's fault and
`bad_query_exc_t` is the client's user's fault. */
class bad_query_exc_t : public std::exception {
public:
bad_query_exc_t(const std::string &s, const backtrace_t &bt) : message(s), backtrace(bt) { }
~bad_query_exc_t() throw () { }
const char *what() const throw () {
return message.c_str();
}
std::string message;
backtrace_t backtrace;
};
class runtime_exc_t {
public:
runtime_exc_t() { }
runtime_exc_t(const std::string &_what, const backtrace_t &bt)
: message(_what), backtrace(bt)
{ }
std::string what() const throw() {
return message;
}
std::string as_str() const throw() {
return strprintf("%s\nBacktrace:\n%s",
message.c_str(), backtrace.print().c_str());
}
std::string message;
backtrace_t backtrace;
RDB_MAKE_ME_SERIALIZABLE_2(message, backtrace);
};
}// namespace query_language
#endif /* RDB_PROTOCOL_EXCEPTIONS_HPP_ */
|
agpl-3.0
|
SilverDav/Silverpeas-Core
|
core-library/src/main/java/org/silverpeas/core/security/authentication/password/PasswordEncryptionProvider.java
|
3947
|
/*
* Copyright (C) 2000 - 2021 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.security.authentication.password;
import org.silverpeas.core.security.authentication.password.encryption.UnixSHA512Encryption;
import org.silverpeas.core.util.ServiceProvider;
import java.util.Set;
/**
* Factory of password encryption objects implementing a given algorithm. It wraps the concrete
* implementation of the <code>PasswordEncryption</code> interface used for encrypting a password
* according to a chosen algorithm.
* <p>
* This factory provides all of the available password encryption supported by Silverpeas,
* nevertheless it returns only the main encryption used by default in Silverpeas (the one that is
* considered as the more robust and secure) with the <code>getDefaultPasswordEncryption()</code>
* method. Getting others encryption can be done in order to work with passwords encrypted with
* old (and then deprecated) algorithms with the <code>getPasswordEncryption(digest)</code>
* method.
* @author mmoquillon
*/
public class PasswordEncryptionProvider {
/**
* Gets the password encryption that is used by default in Silverpeas to encrypt the user
* passwords and to check them.
* @return the current default password encryption.
*/
public static PasswordEncryption getDefaultPasswordEncryption() {
return ServiceProvider.getService(UnixSHA512Encryption.class);
}
/**
* Gets the encryption that has computed the specified digest.
* <p>
* As digests in password encryption are usually made up of an encryption algorithm identifier,
* the factory can then find the algorithm that matches the specified digest. If the digest
* doesn't contain any algorithm identifier, then the UnixDES is returned (yet it is the only one
* supported by Silverpeas that doesn't generate an algorithm identifier in the digest). In the
* case the identifier in the digest isn't known, then a exception is thrown.
* @param digest the digest from which the password encryption has be found.
* @return the password encryption that has computed the specified digest.
* @throws IllegalArgumentException if the digest was not computed by any of the password
* encryption supported in Silverpeas.
*/
public static PasswordEncryption getPasswordEncryption(String digest)
throws IllegalArgumentException {
Set<PasswordEncryption> availableEncrypts =
ServiceProvider.getAllServices(PasswordEncryption.class);
PasswordEncryption encryption = availableEncrypts.stream()
.filter(encrypt -> encrypt.doUnderstandDigest(digest))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Digest '" + digest +
"' not understand by any of the available encryption in Silverpeas"));
return encryption;
}
private PasswordEncryptionProvider() {
}
}
|
agpl-3.0
|
Spycho/aimmo
|
aimmo-game/simulation/test/__init__.py
|
23
|
__author__ = 'c.brett'
|
agpl-3.0
|
ChinookBook/ember-simple-validate
|
addon/mixins/simple-validation-mixin.js
|
2032
|
import Ember from 'ember';
import _validate from 'ember-simple-validate/utils/validate';
import Validator from 'ember-simple-validate/lib/validator';
var get = Ember.get;
var set = Ember.set;
var validValidator = function(validator) {
return validator instanceof Validator;
};
export default Ember.Mixin.create({
init: function() {
this._super();
set(this, 'isValid', undefined);
},
validate: function() {
set(this, 'validationErrors', {});
if(!this.canValidate()) {
set(this, 'isValid', true);
} else {
var self = this;
var validators = get(this, 'validators');
set(this, 'isValid', _validate(this, validators));
Ember.keys(validators).forEach(function(key) {
Ember.makeArray(validators[key]).forEach(function(validator) {
self.addErrors(key, get(validator, 'errors'));
});
});
}
return this.get('isValid');
},
canValidate: function() {
var validators = get(this, 'validators') || {};
var canValidate = true;
var keys = Ember.keys(validators);
if(keys && keys.length) {
keys.forEach(function(key) {
var validatorList = Ember.makeArray(validators[key]);
validatorList.forEach(function(validator) {
if(!validValidator(validator)) {
canValidate = false;
return false;
}
});
});
} else {
canValidate = false;
}
return canValidate;
},
addErrors: function(key, errors) {
var self = this;
Ember.makeArray(errors).forEach(function(error) {
self.addError(key, error);
});
},
addError: function(key, error) {
var self = this;
var keyParts = key.split('.');
var path = 'validationErrors';
keyParts.forEach(function(key, i) {
path += '.' + key;
if(!get(self, path)) {
var blank = i === keyParts.length - 1 ? Ember.A() : {};
set(self, path, blank);
}
});
get(this, 'validationErrors.' + key).pushObject(error);
}
});
|
agpl-3.0
|
kalikaneko/leap_mx
|
setup.py
|
2678
|
# -*- coding: utf-8 -*-
# setup.py
# Copyright (C) 2013 LEAP
#
# 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/>.
"""
setup file for leap.mx
"""
import os
from setuptools import setup, find_packages
import versioneer
versioneer.versionfile_source = 'src/leap/mx/_version.py'
versioneer.versionfile_build = 'leap/mx/_version.py'
versioneer.tag_prefix = '' # tags are like 1.2.0
versioneer.parentdir_prefix = 'leap.mx-'
from pkg.utils.reqs import parse_requirements
trove_classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: No Input/Output (Daemon)',
'Framework :: Twisted',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3'
' or later (AGPLv3+)',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Communications :: Email',
'Topic :: Security :: Cryptography',
]
if os.environ.get("VIRTUAL_ENV", None):
data_files = None
else:
# XXX use a script entrypoint for mx instead, it will
# be automatically
# placed by distutils, using whatever interpreter is
# available.
data_files = [("/usr/local/bin/", ["pkg/mx.tac"]),
("/etc/init.d/", ["pkg/leap_mx"])]
setup(
name='leap.mx',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
url="http://github.com/leapcode/leap_mx",
license='AGPLv3+',
author='The LEAP Encryption Access Project',
author_email='info@leap.se',
description=("An asynchronous, transparently-encrypting remailer "
"for the LEAP platform"),
long_description=(
"An asynchronous, transparently-encrypting remailer "
"using BigCouch/CouchDB and PGP/GnuPG, written in Twisted Python."
),
namespace_packages=["leap"],
package_dir={'': 'src'},
packages=find_packages('src'),
#test_suite='leap.mx.tests',
install_requires=parse_requirements(),
classifiers=trove_classifiers,
data_files=data_files
)
|
agpl-3.0
|
jacklicn/owncloud
|
core/doc/user/files/gallery_app.html
|
19787
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Gallery App — ownCloud 10.0.1 User Manual 10.0.1 documentation</title>
<link rel="stylesheet" href="../_static/" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/main.min.css" type="text/css" />
<link rel="stylesheet" href="../_static/styles.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '10.0.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../_static/js/jquery-fix.js"></script>
<script type="text/javascript" src="../_static/bootstrap-3.1.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../_static/bootstrap-sphinx.js"></script>
<link rel="top" title="ownCloud 10.0.1 User Manual 10.0.1 documentation" href="../contents.html" />
<link rel="up" title="Files & Synchronization" href="index.html" />
<link rel="next" title="Managing Deleted Files" href="deleted_file_management.html" />
<link rel="prev" title="Encrypting Your ownCloud Files" href="encrypting_files.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#1d2d44">
</head>
<body role="document">
<div class="wrap container not-front">
<div class="content row">
<main class="main">
<div class="row page-content-header">
<div class="col-md-5 col-md-offset-7">
<form class="headersearch" style="margin-bottom:-3px;" action="../search.html" method="get">
<input type="text" value="" name="q" id="q" class="form-control" />
<button class="btn btn-default" type="submit" id="searchsubmit">Search</button>
</form>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="sidebar">
<div class="menu-support-container">
<ul id="menu-support" class="menu">
<ul>
<li><a href="../contents.html">Table of Contents</a></li>
</ul>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../index.html">Introduction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../whats_new.html">What’s New in ownCloud 10.0.1</a></li>
<li class="toctree-l1"><a class="reference internal" href="../pim/index.html">Contacts & Calendar</a></li>
<li class="toctree-l1"><a class="reference internal" href="../external_storage/index.html">External Storage</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="index.html">Files & Synchronization</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="access_webdav.html">Accessing ownCloud Files Using WebDAV</a></li>
<li class="toctree-l2"><a class="reference internal" href="access_webgui.html">Accessing your Files Using the ownCloud Web Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="desktop_mobile_sync.html">Desktop and Mobile Synchronization</a></li>
<li class="toctree-l2"><a class="reference internal" href="encrypting_files.html">Encrypting Your ownCloud Files</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="">Gallery App</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#custom-configuration">Custom Configuration</a></li>
<li class="toctree-l3"><a class="reference internal" href="#notes">Notes</a></li>
<li class="toctree-l3"><a class="reference internal" href="#examples">Examples</a></li>
<li class="toctree-l3"><a class="reference internal" href="#possible-future-extensions">Possible Future Extensions</a></li>
<li class="toctree-l3"><a class="reference internal" href="#keeping-up-with-new-features">Keeping Up With New Features</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="deleted_file_management.html">Managing Deleted Files</a></li>
<li class="toctree-l2"><a class="reference internal" href="file_drop.html">Making Anonymous Uploads (Enterprise Only)</a></li>
<li class="toctree-l2"><a class="reference internal" href="large_file_upload.html">Large File Uploads</a></li>
<li class="toctree-l2"><a class="reference internal" href="quota.html">Storage Quota</a></li>
<li class="toctree-l2"><a class="reference internal" href="troubleshooting.html">Troubleshooting</a></li>
<li class="toctree-l2"><a class="reference internal" href="federated_cloud_sharing.html">Using Federation Shares</a></li>
<li class="toctree-l2"><a class="reference internal" href="version_control.html">Version Control</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../webdav-api/index.html">WebDAV APIs</a></li>
<li class="toctree-l1"><a class="reference internal" href="../session_management.html">Manage Connected Browsers and Devices</a></li>
<li class="toctree-l1"><a class="reference internal" href="../webinterface.html">The Web Interface</a></li>
<li class="toctree-l1"><a class="reference internal" href="../userpreferences.html">Setting Your Preferences</a></li>
</ul>
</ul>
</div>
</div>
</div>
<div class="col-md-9">
<div class="page-content">
<ul class="prevnext-title list-unstyled list-inline">
<li class="prev">
<a href="encrypting_files.html" title="Previous Chapter: Encrypting Your ownCloud Files"><span class="glyphicon glyphicon-chevron-left visible-sm"></span><span class="hidden-sm">« Encrypting Yo...</span>
</a>
</li>
<li class="next">
<a href="deleted_file_management.html" title="Next Chapter: Managing Deleted Files"><span class="glyphicon glyphicon-chevron-right visible-sm"></span><span class="hidden-sm">Managing Dele... »</span>
</a>
</li>
</ul>
<div class="section" id="gallery-app">
<h1>Gallery App<a class="headerlink" href="#gallery-app" title="Permalink to this headline">¶</a></h1>
<p>The Pictures app has been rewritten and improved, and is now called the Gallery
app. It supports more image formats, sorting, zoom, and scrolling. It also
supports advanced customizations via a simple text file.</p>
<p>On your main ownCloud Files page, click the little icon at the top right,
underneath your username, to open your Gallery. The Gallery app automatically
finds all images in your ownCloud folders, and overlays the thumbnails with the
folder names. Click on the folder thumbnails to open the folders. At the top
left you have two sorting options, alphabetical and by date.</p>
<div class="figure">
<img alt="Gallery folder thumbnails." src="../_images/gallery-1.png" />
</div>
<p>After entering any folder, click on any image to open it in slideshow mode.
This has the following features: a download button at the top center, forward
and back buttons at the right and left sides, an automatic slideshow button at
the bottom right, and a close button at the top right.</p>
<div class="figure">
<img alt="Gallery in slideshow mode." src="../_images/gallery-2.png" />
</div>
<div class="section" id="custom-configuration">
<h2>Custom Configuration<a class="headerlink" href="#custom-configuration" title="Permalink to this headline">¶</a></h2>
<p>You may customize a Gallery album with a simple text file named
<strong>gallery.cnf</strong>, which contains parameters structured using the
<a class="reference external" href="https://en.wikipedia.org/wiki/YAML">Yaml</a> markup language. You may have
multiple <strong>gallery.cnf</strong> files; you need one in your own root ownCloud folder
(your Home folder) that defines global features, and then you may have
individual per-album <strong>gallery.cnf</strong> files if you want to define different
behaviors in different albums.</p>
<div class="section" id="features">
<h3>Features<a class="headerlink" href="#features" title="Permalink to this headline">¶</a></h3>
<p>The following general features are currently implemented:</p>
<ul class="simple">
<li>Native SVG support.</li>
<li>Access to external shares.</li>
</ul>
<p>The following album features are currently implemented:</p>
<ul class="simple">
<li>Adding a link to a file containing a description.</li>
<li>Typing a simple copyright statement directly in the configuration file.</li>
<li>Adding a link to a file containing a copyright statement.</li>
<li>Defining a sort type and order.</li>
<li>Defining the colour of the background.</li>
<li>Defining if sub-albums will inherit the configuration.</li>
</ul>
<p>The following slideshow features are currently implemented:</p>
<ul class="simple">
<li>Showing a button which lets you pick which background, either black or
white, to use for the picture you are currently viewing (for images with
transparent backgrounds).</li>
</ul>
</div>
<div class="section" id="setup">
<h3>Setup<a class="headerlink" href="#setup" title="Permalink to this headline">¶</a></h3>
<p>The configuration file has to be named <strong>gallery.cnf</strong>. You may have multiple
per-album <strong>gallery.cnf</strong> files. To enable global features, place one in your
top-level folder, which is symbolised in the Web GUI by the home icon. (This
puts it in <code class="docutils literal"><span class="pre">data/<user>/files/</span></code>.) See <a class="reference internal" href="#supported-variables-label"><span>an example below</span></a> in the <strong>Global features</strong> section.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You need to refresh your browser after changing your configuration to
see your changes.</p>
</div>
</div>
<div class="section" id="format">
<h3>Format<a class="headerlink" href="#format" title="Permalink to this headline">¶</a></h3>
<p>UTF-8, <strong>without BOM</strong>. A file created from within the ownCloud Web GUI works.</p>
</div>
<div class="section" id="structure">
<h3>Structure<a class="headerlink" href="#structure" title="Permalink to this headline">¶</a></h3>
<p>You should include a comment in the file, so that people stumbling upon
the file know what it’s for. Comments start with #.</p>
<p>Spacing is created using 2 spaces. <strong>Do not use tabs.</strong></p>
<p>Take a look at the <a class="reference external" href="http://symfony.com/doc/current/components/yaml/yaml_format.html">YAML Format documentation</a> if you are
getting error messages.</p>
<p>Here is an example <cite>gallery.cnf</cite>:</p>
<div class="highlight-python"><div class="highlight"><pre> # Gallery configuration file
# Created on 31 Jan 2016 by ownCloud User
features:
external_shares: yes
native_svg: yes
background_colour_toggle: yes
design:
background: "#ff9f00"
inherit: yes
information:
description: This is an **album description** which is only shown if there
is no `description_link`
description_link: readme.md
copyright: Copyright 2003-2016 [interfaSys sàrl](http://www.interfasys.ch),
Switzerland
copyright_link: copyright.md
inherit: yes
sorting:
type: date
order: des
inherit: yes
</pre></div>
</div>
</div>
<div class="section" id="supported-variables">
<span id="supported-variables-label"></span><h3>Supported Variables<a class="headerlink" href="#supported-variables" title="Permalink to this headline">¶</a></h3>
<p><strong>Global Features</strong></p>
<p>Place this in your root ownCloud folder, which is your Home folder.</p>
<ul class="simple">
<li><strong>external_shares</strong>: Set to <strong>yes</strong> in your root configuration file if you
want to load images stored on external locations, when using the
<strong>files_external</strong> app.</li>
<li><strong>native_svg</strong>: Set to <strong>yes</strong> in your root configuration file to enable
rendering SVG images in your browser. This may represent a security risk if
you can’t fully trust your SVG files.</li>
<li><strong>background_colour_toggle</strong>: Set to <strong>yes</strong> in your root configuration file
to enable a button that toggles between black and white backgrounds on
transparent images.</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">External shares are 20-50 times slower than local shares. Be prepared
to wait a long time before being able to see all the images contained in a
shared album.</p>
</div>
<p><strong>Album Configuration</strong></p>
<p>Each album can be individually configured using the following configuration
sections. Use the <strong>inherit</strong> parameter to pass configurations on to
sub-albums.</p>
<p><strong>Design</strong></p>
<ul class="simple">
<li><strong>background</strong>: Defines the colour of the background of the photowall
using the RGB hexadecimal representation of that colour. For example:
<strong>“#ffa033”</strong>. You must use quotes around the value or it will
be ignored. It is strongly recommended to use a custom theme, with a CSS
loading spinner if you intend to use this feature. You can use <a class="reference external" href="http://paletton.com/">this colour
wheel</a> to find a colour you like.</li>
<li><strong>inherit</strong>: Set to <strong>yes</strong> if you want sub-folders to inherit this part of
the configuration.</li>
</ul>
<p><strong>Album Presentation</strong></p>
<ul class="simple">
<li><strong>description</strong>: A markdown-formatted string which will be displayed in the
info box. It can spread over multiple lines using the Yaml markers.</li>
<li><strong>description_link</strong>: A markdown file located within the album which will
be parsed and displayed in the info box instead of the description.</li>
<li><strong>copyright</strong>: A markdown-formatted string. This supports links to external
resources.</li>
<li><strong>copyright_link</strong>: Any file (e.g. copyright.html), in the album itself,
which will be downloaded when the user clicks on the link</li>
<li><strong>inherit</strong>: Set to <strong>yes</strong> if you want sub-folders to inherit this part of
the configuration.</li>
</ul>
<p>See <a class="reference external" href="http://www.markitdown.net/markdown">http://www.markitdown.net/markdown</a> for the markdown syntax.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Do not add links to your <cite>copyright</cite> string if you use the
<strong>copyright_link</strong> variable.</p>
</div>
<p><strong>Sorting</strong></p>
<ul class="simple">
<li><strong>sorting</strong>: <strong>date</strong> or <strong>name</strong>. <strong>date</strong> only works for files.</li>
<li><strong>sort_order</strong>: <strong>asc</strong> or <strong>des</strong> (Ascending or descending).</li>
<li><strong>inherit</strong>: Set to <strong>yes</strong> if you want sub-folders to inherit this part of
the configuration.</li>
</ul>
</div>
</div>
<div class="section" id="notes">
<h2>Notes<a class="headerlink" href="#notes" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>When only the sort <strong>type</strong> variable has been set, the default sort order
will be used.</li>
<li>When only the sort <strong>order</strong> variable has been found, the sort configuration
will be ignored and the script will keep looking for a valid configuration in
upper folders.</li>
<li>To enable a feature such as native SVG in a public share, you need to create
in that folder a configuration file containing that feature.</li>
<li>If you share a folder publicly, don’t forget to add all the files you link to
(e.g. <code class="docutils literal"><span class="pre">description.md</span></code> or <code class="docutils literal"><span class="pre">copyright.md</span></code>) inside the shared folder as
the user won’t have access to files stored in the parent folder.</li>
<li>Since people can download a whole folder as an archive, it’s usually best to
include all files within a shared folder, rather than adding text directly
in the configuration file.</li>
</ul>
</div>
<div class="section" id="examples">
<h2>Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p><strong>Sorting Only</strong></p>
<p>Applies to the current folder only:</p>
<div class="highlight-python"><div class="highlight"><pre># Gallery configuration file
sorting:
type: date
order: asc
</pre></div>
</div>
<p>Short description and link to copyright document, applies to the current folder
and all of its sub-folders. This also shows you the syntax you can use to
spread a description over multiple lines:</p>
<div class="highlight-python"><div class="highlight"><pre># Gallery configuration file
information:
description: | # La Maison Bleue, Winter '16
This is our Winter 2016 collection shot in **Kyoto**
Visit our [website](http://www.secretdesigner.ninja) for more information
copyright: Copyright 2015 La Maison Bleue, France
copyright_link: copyright_2015_lmb.html
inherit: yes
</pre></div>
</div>
<p><strong>Load Images From External Clouds</strong></p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Features can only be defined in the root folder.</p>
</div>
<p>You can add standard configuration items to the same configuration file:</p>
<div class="highlight-python"><div class="highlight"><pre># Gallery configuration file
features:
external_shares: yes
</pre></div>
</div>
<p><strong>Enabling native SVG</strong></p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Special features can only be defined in the root folder.</p>
</div>
<p>You can add standard configuration items to the same configuration file:</p>
<div class="highlight-python"><div class="highlight"><pre># Gallery configuration file
features:
native_svg: yes
</pre></div>
</div>
</div>
<div class="section" id="possible-future-extensions">
<h2>Possible Future Extensions<a class="headerlink" href="#possible-future-extensions" title="Permalink to this headline">¶</a></h2>
<p>Different sorting parameters for albums.</p>
</div>
<div class="section" id="keeping-up-with-new-features">
<h2>Keeping Up With New Features<a class="headerlink" href="#keeping-up-with-new-features" title="Permalink to this headline">¶</a></h2>
<p>See the <a class="reference external" href="https://github.com/owncloud/gallery/wiki">Gallery Wiki page</a> to stay informed of new developments.</p>
</div>
</div>
<ul class="prevnext-title list-unstyled list-inline">
<li class="prev">
<a href="encrypting_files.html" title="Previous Chapter: Encrypting Your ownCloud Files"><span class="glyphicon glyphicon-chevron-left visible-sm"></span><span class="hidden-sm">« Encrypting Yo...</span>
</a>
</li>
<li class="next">
<a href="deleted_file_management.html" title="Next Chapter: Managing Deleted Files"><span class="glyphicon glyphicon-chevron-right visible-sm"></span><span class="hidden-sm">Managing Dele... »</span>
</a>
</li>
</ul>
</div>
</div>
</div>
</main>
</div>
</div>
</body>
</html>
|
agpl-3.0
|
nuagelabsfr/cloud-gateway
|
src/scripts/CloudGatewayStatus.sh
|
4664
|
#!/bin/bash
# Definitions
readonly SCRIPT_DIR=`dirname $0`
readonly ARGC="$#"
# First, try to set up env
if [ -f "${SCRIPT_DIR}/CloudGateway_env.sh" ]; then
. "${SCRIPT_DIR}/CloudGateway_env.sh"
else
echo "Unable to find Cloud Gateway environment file, exiting." 1>&2
exit 1
fi
function usage
{
print_error "Usage: $0 [-v[v]] [-r]"
exit 22
}
VERBOSE=0
RAW=0
while true ; do
if [ $# -eq 0 ]; then
break;
fi
case "$1" in
-v) VERBOSE=1; shift ;;
-vv) VERBOSE=2; shift ;;
-r) RAW=1; shift ;;
--) shift ; break ;;
*) usage;
esac
done
# Get dirty / deleting files count from DB
nb_dirty_files=0
nb_files_to_be_deleted=0
# Dirty
value=$( get_psql_single_value 'select count(*) from inodes_instances WHERE status = 1;' )
result=$?
if [ $? -eq 0 -a -n "${value}" ]; then
readonly nb_dirty_files=${value}
else
print_error "Error getting dirty files count: ${result}"
readonly nb_dirty_files=0
fi
# Deleting
value=$( get_psql_single_value 'select count(*) from inodes_instances WHERE status = 2;' )
result=$?
if [ $? -eq 0 -a -n "${value}" ]; then
readonly nb_files_to_be_deleted=${value}
else
print_error "Error getting deleting files count: ${result}"
readonly nb_files_to_be_deleted=0
fi
# If we have neither dirty nor deleted files, exit with 0.
if [ ${nb_dirty_files} -eq 0 -a ${nb_files_to_be_deleted} -eq 0 ]; then
exit 0
fi
# Print counters
if [ ${nb_dirty_files} -gt 0 ]; then
echo "${nb_dirty_files} files to upload.";
fi
if [ ${nb_files_to_be_deleted} -gt 0 ]; then
echo "${nb_files_to_be_deleted} files to delete."
fi
# If we are in verbose mode, query then print content
if [ ${VERBOSE} -gt 0 ]; then
if [ ${nb_files_to_be_deleted} -gt 0 ]; then
result=$( get_psql_values "select iil.fs_id as FS, iil.inode_number, instances.instance_name,
CASE WHEN deleting='t' THEN 'deleting'
ELSE 'to_be_deleted'
END
AS status
FROM inodes_instances AS ii
INNER JOIN inodes_instances_link AS iil ON (iil.inode_instance_id = ii.inode_instance_id)
INNER JOIN instances ON (ii.instance_id = instances.instance_id)
WHERE status = 2;" ${DISPLAY_PSQL_TABLE})
returned_value=$?
echo "${result}" >&2
fi
if [ ${nb_dirty_files} -gt 0 ]; then
if [ ${VERBOSE} -gt 1 ]; then
full_path="
(SELECT sub.path from (WITH RECURSIVE path(name, path, parent, entry_id, parent_id) AS (
SELECT name, '/', NULL, entries.entry_id, CAST(0 as BIGINT) FROM entries WHERE entries.parent_entry_id IS NULL
UNION
SELECT
entries.name,
parentpath.path ||
CASE parentpath.path
WHEN '/' THEN ''
ELSE '/'
END || entries.name,
parentpath.path, entries.entry_id, parent_entry_id as parent_id
FROM entries, path as parentpath
WHERE entries.parent_entry_id = parentpath.entry_id)
SELECT * FROM path WHERE entry_id = entries.entry_id) as sub) as path
"
else
full_path="entries.name";
fi
time_column="TO_CHAR(TO_TIMESTAMP(inodes.mtime), 'YYYY/MM/DD HH24:MI:SS') as mtime"
if [ ${RAW} -eq 1 ]; then
time_column="inodes.mtime"
fi
size_column="pg_size_pretty(inodes.size) AS size"
if [ ${RAW} -eq 1 ]; then
size_column="inodes.size AS size"
fi
result=$( get_psql_values "
select filesystems.fs_name as FS, inodes.inode_number, instance_name, ${time_column}, ${size_column},
CASE
WHEN status=1 THEN
CASE WHEN uploading='t' THEN 'uploading'
ELSE 'to_be_uploaded'
END
WHEN status=2 THEN
CASE WHEN deleting='t' THEN 'deleting'
ELSE 'to_be_deleted'
END
END
AS status,
$full_path
FROM inodes_instances AS ii
INNER JOIN inodes_instances_link AS iil ON (ii.inode_instance_id = iil.inode_instance_id)
INNER JOIN instances ON (ii.instance_id = instances.instance_id)
INNER JOIN inodes ON (inodes.inode_number = iil.inode_number AND inodes.fs_id = iil.fs_id)
INNER JOIN entries ON (entries.inode_number = iil.inode_number AND entries.fs_id = iil.fs_id)
INNER JOIN filesystems ON (entries.fs_id = filesystems.fs_id)
WHERE status != 0 ORDER BY mtime;" ${DISPLAY_PSQL_TABLE})
returned_value=$?
echo "${result}" >&2
fi
fi
# Different exit codes for each situation (dirty files only, deleted files only, both)
if [ ${nb_dirty_files} -gt 0 -a ${nb_files_to_be_deleted} -gt 0 ]; then
exit 3
elif [ ${nb_files_to_be_deleted} -gt 0 ]; then
exit 2
elif [ ${nb_dirty_files} -gt 0 ]; then
exit 1
fi
exit 0
|
agpl-3.0
|
CoughDrop/coughdrop
|
lib/feature_flags.rb
|
3182
|
module FeatureFlags
# TODO: remove unused feature flags after like December 2019
AVAILABLE_FRONTEND_FEATURES = ['subscriptions', 'assessments', 'custom_sidebar',
'canvas_render', 'snapshots', 'enable_all_buttons',
'video_recording', 'goals', 'app_connections', 'translation', 'geo_sidebar',
'modeling', 'edit_before_copying', 'core_reports', 'lessonpix',
'audio_recordings', 'fast_render', 'badge_progress', 'board_levels', 'premium_symbols',
'find_multiple_buttons', 'new_speak_menu', 'native_keyboard', 'inflections_overlay',
'app_store_purchases', 'emergency_boards', 'evaluations', 'swipe_pages',
'app_store_monthly_purchases', 'ios_head_tracking', 'vertical_ios_head_tracking',
'auto_inflections', 'remote_modeling', 'focus_word_highlighting', 'profiles',
'skin_tones']
ENABLED_FRONTEND_FEATURES = ['subscriptions', 'assessments', 'custom_sidebar', 'snapshots',
'video_recording', 'goals', 'modeling', 'geo_sidebar', 'edit_before_copying',
'core_reports', 'lessonpix', 'translation', 'fast_render',
'audio_recordings', 'app_connections', 'enable_all_buttons', 'badge_progress',
'premium_symbols', 'board_levels', 'native_keyboard', 'app_store_purchases',
'find_multiple_buttons', 'new_speak_menu', 'swipe_pages', 'inflections_overlay',
'ios_head_tracking', 'emergency_boards', 'evaluations',
'vertical_ios_head_tracking', 'remote_modeling', 'auto_inflections', 'focus_word_highlighting']
DISABLED_CANARY_FEATURES = []
FEATURE_DATES = {
'word_suggestion_images' => 'Jan 21, 2017',
'hidden_buttons' => 'Feb 2, 2017',
'browser_no_autosync' => 'Feb 22, 2017',
'folder_icons' => 'Mar 7, 2017',
'symbol_background' => 'May 10, 2017',
'new_index' => 'Feb 17, 2018',
'click_buttons' => 'May 1, 2019',
'token_refresh' => 'July 4, 2019',
'battery_sounds' => 'February 25, 2020',
'auto_capitalize' => 'May 1, 2021',
'utterance_interruptions' => 'May 15, 2021',
'utterance_core_access' => 'May 1, 2021',
'recent_cleared_phrases' => 'Sep 1, 2021',
'skin_tones' => 'Feb 14, 2022'
}
def self.frontend_flags_for(user)
flags = {}
AVAILABLE_FRONTEND_FEATURES.each do |feature|
if ENABLED_FRONTEND_FEATURES.include?(feature)
flags[feature] = true
elsif user && user.settings && user.settings['feature_flags'] && user.settings['feature_flags'][feature]
flags[feature] = true
elsif user && user.settings && user.settings['feature_flags'] && user.settings['feature_flags']['canary'] && !DISABLED_CANARY_FEATURES.include?(feature)
flags[feature] = true
end
end
flags
end
def self.user_created_after?(user, feature)
return false unless FEATURE_DATES[feature]
date = Date.parse(FEATURE_DATES[feature]) rescue Date.today
created = (user.created_at || Time.now).to_date
return !!(created >= date)
end
def self.feature_enabled_for?(feature, user)
flags = frontend_flags_for(user)
!!flags[feature]
end
end
|
agpl-3.0
|
hirakc/eur_crm
|
modules/Administration/vardefs.php
|
5819
|
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$dictionary['Administration'] = array('table' => 'config_eurivex', 'comment' => 'System table containing system-wide definitions'
,'fields' => array (
'category' =>
array (
'name' => 'category',
'vname' => 'LBL_LIST_SYMBOL',
'type' => 'varchar',
'len' => '32',
'comment' => 'Settings are grouped under this category; arbitraily defined based on requirements'
),
'name' =>
array (
'name' => 'name',
'vname' => 'LBL_LIST_NAME',
'type' => 'varchar',
'len' => '32',
'comment' => 'The name given to the setting'
),
'value' =>
array (
'name' => 'value',
'vname' => 'LBL_LIST_RATE',
'type' => 'text',
'comment' => 'The value given to the setting'
),
), 'indices'=>array( array('name'=>'idx_config_cat', 'type'=>'index', 'fields'=>array('category')),)
);
$dictionary['UpgradeHistory'] = array(
'table' => 'upgrade_history', 'comment' => 'Tracks Sugar upgrades made over time; used by Upgrade Wizard and Module Loader',
'fields' => array (
'id' => array (
'name' => 'id',
'type' => 'id',
'required' => true,
'reportable' => false,
'comment' => 'Unique identifier'
),
'filename' => array (
'name' => 'filename',
'type' => 'varchar',
'len' => '255',
'comment' => 'Cached filename containing the upgrade scripts and content'
),
'md5sum' => array (
'name' => 'md5sum',
'type' => 'varchar',
'len' => '32',
'comment' => 'The MD5 checksum of the upgrade file'
),
'type' => array (
'name' => 'type',
'type' => 'varchar',
'len' => '30',
'comment' => 'The upgrade type (module, patch, theme, etc)'
),
'status' => array (
'name' => 'status',
'type' => 'varchar',
'len' => '50',
'comment' => 'The status of the upgrade (ex: "installed")',
),
'version' => array (
'name' => 'version',
'type' => 'varchar',
'len' => '64',
'comment' => 'Version as contained in manifest file'
),
'name' => array (
'name' => 'name',
'type' => 'varchar',
'len' => '255',
),
'description' => array (
'name' => 'description',
'type' => 'text',
),
'id_name' => array (
'name' => 'id_name',
'type' => 'varchar',
'len' => '255',
'comment' => 'The unique id of the module'
),
'manifest' => array (
'name' => 'manifest',
'type' => 'longtext',
'comment' => 'A serialized copy of the manifest file.'
),
'date_entered' => array (
'name' => 'date_entered',
'type' => 'datetime',
'required'=>true,
'comment' => 'Date of upgrade or module load'
),
'enabled' => array(
'name' => 'enabled',
'type' => 'bool',
'len' => '1',
'default' => '1',
),
),
'indices' => array(
array('name'=>'upgrade_history_pk', 'type'=>'primary', 'fields'=>array('id')),
array('name'=>'upgrade_history_md5_uk', 'type'=>'unique', 'fields'=>array('md5sum')),
),
);
?>
|
agpl-3.0
|
LiquidPL/osu-web
|
resources/lang/he-IL/beatmaps.php
|
14321
|
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
return [
'discussion-votes' => [
'update' => [
'error' => 'נכשל בעדכון הצבעה',
],
],
'discussions' => [
'allow_kudosu' => 'אפשר kudosu',
'beatmap_information' => 'דף מפות',
'delete' => 'מחק',
'deleted' => 'נמחק על ידי :editor :delete_time.',
'deny_kudosu' => 'דחה kudosu',
'edit' => 'ערוך',
'edited' => 'נערך לאחרונה על ידי :editor :update_time.',
'guest' => '',
'kudosu_denied' => 'נדחה מקבלת kudosu.',
'message_placeholder_deleted_beatmap' => 'רמת הקושי הזאת נמחקה לכן לא ניתן לדון בה.',
'message_placeholder_locked' => 'דיון למפה זו בוטל.',
'message_placeholder_silenced' => "לא ניתן לדון בזמן שמושתק.",
'message_type_select' => 'בחר סוג תגובה',
'reply_notice' => 'הקש על Enter כדי להגיב.',
'reply_placeholder' => 'הקלד את תגובתך כאן',
'require-login' => 'אנא התחבר על מנת לפרסם הודעה או להגיב',
'resolved' => 'נפתר',
'restore' => 'שחזר',
'show_deleted' => 'הצג שנמחק',
'title' => 'דיונים',
'collapse' => [
'all-collapse' => 'סגור הכל',
'all-expand' => 'הרחב הכל',
],
'empty' => [
'empty' => 'עדיין אין דיונים!',
'hidden' => 'אין דיון שמתאים לסינון שנבחר.',
],
'lock' => [
'button' => [
'lock' => 'נעל דיון',
'unlock' => 'פתח דיון',
],
'prompt' => [
'lock' => 'סיבת הנעילה',
'unlock' => 'האם אתה בטוח שברצונך לפתוח?',
],
],
'message_hint' => [
'in_general' => 'פוסט זה יעבור לדיוני beatmapset כללים. כדי לעשות mod ל- beatmap זה, התחל הודעה עם חותמת זמן (למשל 00:12:345).',
'in_timeline' => 'כדי לבצע mod לחותמות זמן מרובות, פרסם הודעה מספר פעמים (הודעה אחת לחותמת זמן).',
],
'message_placeholder' => [
'general' => 'הקלד כאן כדי לפרסם הודעה ל- כללי (:version)',
'generalAll' => 'הקלד כאן כדי לפרסם הודעה ל- כללי (כל רמות הקושי)',
'review' => 'הקלד כאן כדי לפרסם ביקורת',
'timeline' => 'הקלד כאן כדי לפרסם הודעה ל- "ציר זמן" (:version)',
],
'message_type' => [
'disqualify' => 'פסול',
'hype' => 'הייפ!',
'mapper_note' => 'הערה',
'nomination_reset' => 'איפוס מועמדות',
'praise' => 'שבח',
'problem' => 'בעיה',
'review' => 'ביקורת',
'suggestion' => 'הצעה',
],
'mode' => [
'events' => 'היסטוריה',
'general' => 'כללי :scope',
'reviews' => 'ביקורות',
'timeline' => 'ציר זמן',
'scopes' => [
'general' => 'רמת הקושי הזאת',
'generalAll' => 'כל רמות הקושי',
],
],
'new' => [
'pin' => 'נעץ',
'timestamp' => 'חותמת זמן',
'timestamp_missing' => 'העתק במצב עריכה והדבק בהודעה שלך כדי להוסיף חותמת זמן!',
'title' => 'דיון חדש',
'unpin' => 'בטל נעיצה',
],
'review' => [
'new' => 'ביקורת חדשה',
'embed' => [
'delete' => 'מחק',
'missing' => '[ביקורת נמחקה]',
'unlink' => 'בטל קישור',
'unsaved' => 'לא שמור',
'timestamp' => [
'all-diff' => 'פוסים ב "כל דרגות הקושי" לא יכול להיות תמידיים.',
'diff' => 'אם :type יתחיל בזמן מסוים, הוא יהיה נראה מתחת ציר הזמן.',
],
],
'insert-block' => [
'paragraph' => 'הוסף פסקה',
'praise' => 'הוסף שיבוח',
'problem' => 'הוסף תקלה',
'suggestion' => 'הוסף הצעה',
],
],
'show' => [
'title' => ':title ממופה על ידי :mapper',
],
'sort' => [
'created_at' => 'זמן יצירה',
'timeline' => 'ציר זמן',
'updated_at' => 'עידכון אחרון',
],
'stats' => [
'deleted' => 'נמחק',
'mapper_notes' => 'הערות',
'mine' => 'מוקש',
'pending' => 'ממתין',
'praises' => 'שבחים',
'resolved' => 'נפתר',
'total' => 'הכל',
],
'status-messages' => [
'approved' => 'Beatmap זו אושרה ב :date!',
'graveyard' => "Beatmap זו לא עודכנה מאז :date וקרוב לוודאי שננטשה על ידי היוצר...",
'loved' => 'Beatmap זו הוספה ל "אהובות" ב- :date!',
'ranked' => 'Beatmap זו דורגה ב :date!',
'wip' => 'הערה: Beatmap זו מסומנת כ "עבודה בתהליך" על ידי היוצר.',
],
'votes' => [
'none' => [
'down' => 'עדיין אין מצביעים',
'up' => 'אין הצבעטת עדיין',
],
'latest' => [
'down' => 'ההצבעות האחרונות',
'up' => 'ההצבעות האחרונות',
],
],
],
'hype' => [
'button' => 'הייפ Beatmap!',
'button_done' => 'כבר Hyped!',
'confirm' => "אתה בטוח? זה ישתמש באחד מ- :n ההייפים הנותרים שלך ולא ניתן לבטל זאת.",
'explanation' => 'תן הייפ ל beatmap הזו כדי להפוך אותה לגלויה יותר להיות מועמדת ומדורגת!',
'explanation_guest' => 'התחבר ותן הייף ל beatmap זו כדי להפוך אותה לגלויה יותר להיות מועמדת ומדורגת!',
'new_time' => "תקבל הייפ אחר :new_time.",
'remaining' => 'יש לך :remaining הייפים נותרים.',
'required_text' => 'הייפ: :current/:required',
'section_title' => 'רכבת הייפ',
'title' => 'הייפ',
],
'feedback' => [
'button' => 'השאר משוב',
],
'nominations' => [
'delete' => 'מחק',
'delete_own_confirm' => 'אתה בטוח? Beatmap זו תימחק ואתה תועבר חזרה לפרופיל שלך.',
'delete_other_confirm' => 'אתה בטוח? Beatmap זו תימחק ואתה תועבר חזרה לפרופיל של המשתמש.',
'disqualification_prompt' => 'סיבת הפסילה?',
'disqualified_at' => 'נפסלה :time_ago (:reason).',
'disqualified_no_reason' => 'לא פורטה הסיבה',
'disqualify' => 'פסול',
'incorrect_state' => 'שגיאה בעת ביצוע פעולה זו, נסה לרענן את הדף.',
'love' => 'אוהב',
'love_choose' => '',
'love_confirm' => 'לאהוב מפה זו?',
'nominate' => 'למנות',
'nominate_confirm' => 'למנות מפה זו?',
'nominated_by' => 'מונתה על ידי :users',
'not_enough_hype' => "אין כאן מספיק התעניינות.",
'remove_from_loved' => 'הורד סטטוס ה-Loved',
'remove_from_loved_prompt' => 'סיבה הורדת סטטוס ה-Loved:',
'required_text' => 'מינויים: :current/:required',
'reset_message_deleted' => 'נמחק',
'title' => 'סטטוס המינוי',
'unresolved_issues' => 'ישנן עדיין בעיות שלא נפתרו שחייבות טיפול קודם.',
'rank_estimate' => [
'_' => 'מפה זאת תקבל סטטוס Ranked ב:date במידה ולא ימצאו שגיעות. המפה נמצא ב#:position ב:queue.',
'queue' => 'נבדקת לקבלת Ranking',
'soon' => 'בקרוב',
],
'reset_at' => [
'nomination_reset' => 'תהליך המינוי התאפס :time_ago על ידי :user עם בעיה חדשה :discussion (:message).',
'disqualify' => 'נפסלה :time_ago על ידי :user עם בעיה חדשה :discussion (:message).',
],
'reset_confirm' => [
'nomination_reset' => 'אתה בטוח? פרסום בעיה חדשה יאפס את תהליך המינוי.',
'disqualify' => 'אתה בטוח? זה יסיר את המפה מ- "מוקדמות" ויאפס את תהליך המינוי.',
],
],
'listing' => [
'search' => [
'prompt' => 'הקלד מילות מפתח...',
'login_required' => 'התחבר כדי לחפש.',
'options' => 'אפשרויות חיפוש נוספות',
'supporter_filter' => 'סינון לפי :filters דורש תג osu!supporter פעיל',
'not-found' => 'אין תוצאות',
'not-found-quote' => '... לא, לא נמצא כלום.',
'filters' => [
'extra' => 'נוסף',
'general' => 'כללי',
'genre' => 'ז\'אנר',
'language' => 'שפה',
'mode' => 'מצב',
'nsfw' => '',
'played' => 'שוחקה',
'rank' => 'דרגה הושגה',
'status' => 'קטגוריות',
],
'sorting' => [
'title' => 'כותרת',
'artist' => 'אמן',
'difficulty' => 'דרגת קושי',
'favourites' => 'מועדפות',
'updated' => 'עודכנה',
'ranked' => 'מדורגת',
'rating' => 'דירוג',
'plays' => 'שיחוקים',
'relevance' => 'רלוונטיות',
'nominations' => 'מינויים',
],
'supporter_filter_quote' => [
'_' => 'סינון לפי :filters דורש :link פעיל',
'link_text' => 'תג osu!supporter',
],
],
],
'general' => [
'converts' => 'כלול מפות מומרות',
'featured_artists' => '',
'follows' => '',
'recommended' => 'דרגת קושי מומלצת',
],
'mode' => [
'all' => 'הכל',
'any' => 'הכל',
'osu' => '',
'taiko' => '',
'fruits' => '',
'mania' => '',
],
'status' => [
'any' => 'הכל',
'approved' => 'מאושרת',
'favourites' => 'מועדפים',
'graveyard' => 'קבורה',
'leaderboard' => 'יש לוח מובילים',
'loved' => 'אהובה',
'mine' => 'המפות שלי',
'pending' => 'בתהליך * WIP',
'qualified' => 'מוסמכת',
'ranked' => 'מדורג',
],
'genre' => [
'any' => 'הכל',
'unspecified' => 'לא מוגדר',
'video-game' => 'משחק וידאו',
'anime' => 'אנימה',
'rock' => 'רוק',
'pop' => 'פופ',
'other' => 'אחר',
'novelty' => 'Novelty',
'hip-hop' => 'היפ הופ',
'electronic' => 'אלקטרוני',
'metal' => 'מטאל',
'classical' => 'קלאסי',
'folk' => 'פולק',
'jazz' => 'ג\'אז',
],
'mods' => [
'4K' => '',
'5K' => '',
'6K' => '',
'7K' => '',
'8K' => '',
'9K' => '',
'AP' => '',
'DT' => '',
'EZ' => '',
'FI' => '',
'FL' => '',
'HD' => '',
'HR' => '',
'HT' => '',
'MR' => '',
'NC' => '',
'NF' => '',
'NM' => '',
'PF' => '',
'RX' => '',
'SD' => '',
'SO' => '',
'TD' => '',
'V2' => '',
],
'language' => [
'any' => '',
'english' => 'אנגלית',
'chinese' => 'סינית',
'french' => 'צרפתית',
'german' => 'גרמנית',
'italian' => 'איטלקית',
'japanese' => 'יפנית',
'korean' => 'קוריאנית',
'spanish' => 'ספרדית',
'swedish' => 'שוודית',
'russian' => 'רוסית',
'polish' => 'פולנית',
'instrumental' => 'אינסטרומנטלי',
'other' => 'אחר',
'unspecified' => 'לא מוגדר',
],
'nsfw' => [
'exclude' => '',
'include' => '',
],
'played' => [
'any' => 'הכל',
'played' => 'שוחקה',
'unplayed' => 'לא שוחקה',
],
'extra' => [
'video' => 'יש וידאו',
'storyboard' => 'יש Storyboard',
],
'rank' => [
'any' => 'הכל',
'XH' => 'SS כסוף',
'X' => '',
'SH' => 'S כסוף',
'S' => '',
'A' => '',
'B' => '',
'C' => '',
'D' => '',
],
'panel' => [
'playcount' => 'מספר משחקים: :count',
'favourites' => 'מועדפות: :count',
],
'variant' => [
'mania' => [
'4k' => '4K',
'7k' => '7K',
'all' => 'הכל',
],
],
];
|
agpl-3.0
|
c2corg/v6_ui
|
c2corg_ui/templates/outing/preview.html
|
2361
|
<%namespace file="../helpers/view.html" import="get_document_min_max,
get_document_locale_text, get_activities, get_document_description"/>
<%namespace file="../helpers/preview.html" import="show_preview_warning"/>
<%namespace file="helpers/view.html" import="get_outing_snow, get_outing_access,
get_outing_participants, get_outing_general, get_outing_heights,
show_fulldate, get_conditions, get_outing_location"/>
<%
outing = document
locale = document['locales'][0]
outing['date_end'] = outing['date_end'] if outing.get('date_end') else outing['date_start']
%>
${show_preview_warning()}
<div class="viewdoc viewroute">
<header class="view-title-without-bg" >
<h1 class="routes">
<span class="title">${locale['title']}</span>
<div class="icons-header routes">${get_activities(outing, 'top')}</div>
<div class="outing-date" class="ng-cloak">${show_fulldate(outing['date_start'], outing['date_end'])}</div>
</h1>
</header>
<section class="view-details-section"ng-class="{'row-list' : switchCtrl.showList}">
<div class="row">
<div class="col-xs-12 col-md-4 col-lg-3">
% if outing.get('geometry'):
<app-map class="view-details-map"></app-map>
% endif
</div>
<div class="col-xs-12 col-md-8 col-lg-9">
<section id="document-informations">
<div class="finfo">
<div class="ficontent">
<div class="row">
${get_outing_general(outing)}
${get_outing_location(outing)}
${get_outing_heights(outing)}
${get_outing_access(outing)}
${get_outing_snow(outing)}
</div>
</div>
</div>
${get_document_locale_text(locale, 'route_description', True)}
${get_conditions(locale, True)}
${get_document_locale_text(locale, 'avalanches', True)}
${get_document_locale_text(locale, 'timing', True)}
${get_document_locale_text(locale, 'access', True)}
${get_document_locale_text(locale, 'access_comment', True)}
${get_document_locale_text(locale, 'hut_comment', True)}
${get_document_description(locale, 'outing', 'personal comments')}
</section>
</div>
</div>
</section>
</div>
|
agpl-3.0
|
jerome-poisson/superdesk-client-core
|
scripts/apps/authoring/authoring/directives/SendItem.js
|
35674
|
import _ from 'lodash';
import React from 'react';
import {PreviewModal} from '../previewModal';
SendItem.$inject = ['$q', 'api', 'desks', 'notify', 'authoringWorkspace',
'superdeskFlags', '$location', 'macros', '$rootScope', 'deployConfig',
'authoring', 'send', 'editorResolver', 'confirm', 'archiveService',
'preferencesService', 'multi', 'datetimeHelper', 'config', 'privileges', 'storage', 'modal', 'gettext', 'urls'];
export function SendItem($q, api, desks, notify, authoringWorkspace,
superdeskFlags, $location, macros, $rootScope, deployConfig,
authoring, send, editorResolver, confirm, archiveService,
preferencesService, multi, datetimeHelper, config, privileges, storage, modal, gettext, urls) {
return {
scope: {
item: '=',
view: '=',
orig: '=',
_beforeSend: '&beforeSend',
_editable: '=editable',
_publish: '&publish',
_action: '=action',
mode: '@',
},
controller: function() {
this.userActions = {
send_to: 'send_to',
publish: 'publish',
duplicate_to: 'duplicate_to',
externalsource_to: 'externalsource_to',
};
},
controllerAs: 'vm',
templateUrl: 'scripts/apps/authoring/views/send-item.html',
link: function sendItemLink(scope, elem, attrs, ctrl) {
scope.mode = scope.mode || 'authoring';
scope.desks = null;
scope.stages = null;
scope.macros = null;
scope.userDesks = null;
scope.allDesks = null;
scope.task = null;
scope.selectedDesk = null;
scope.selectedStage = null;
scope.selectedMacro = null;
scope.beforeSend = scope._beforeSend || $q.when;
scope.destination_last = {send_to: null, publish: null, duplicate_to: null};
scope.origItem = angular.extend({}, scope.item);
scope.subscribersWithPreviewConfigured = [];
// key for the storing last desk/stage in the user preferences for send action.
var PREFERENCE_KEY = 'destination:active';
// key for the storing last user action (send to/publish) in the storage.
var USER_ACTION_KEY = 'send_to_user_action';
scope.$watch('item', activateItem);
scope.$watch(send.getConfig, activateConfig);
scope.publish = function() {
scope.loading = true;
var result = scope._publish();
return $q
.resolve(result)
.then(null, (e) => $q.reject(false))
.finally(() => {
scope.loading = false;
});
};
function activateConfig(config, oldConfig) {
if (scope.mode !== 'authoring' && config !== oldConfig) {
scope.isActive = !!config;
scope.item = scope.isActive ? {} : null;
scope.multiItems = multi.count ? multi.getItems() : null;
scope.config = config;
activate();
}
}
function activateItem(item) {
if (scope.mode === 'monitoring') {
superdeskFlags.flags.fetching = !!item;
}
scope.isActive = !!item;
activate();
}
function activate() {
if (scope.isActive) {
api.query('subscribers')
.then((res) => {
const allSubscribers = res['_items'];
scope.subscribersWithPreviewConfigured = allSubscribers
.map(
(subscriber) => {
subscriber.destinations = subscriber.destinations.filter(
(destination) => typeof destination.preview_endpoint_url === 'string'
&& destination.preview_endpoint_url.length > 0
);
return subscriber;
}
)
.filter((subscriber) => subscriber.destinations.length > 0);
});
desks
.initialize()
.then(fetchDesks)
.then(initialize)
.then(setDesksAndStages);
}
}
scope.preview = function() {
if (scope.$parent.save_enabled() === true) {
modal.alert({
headerText: gettext('Preview'),
bodyText: gettext(
'In order to preview the item, save the changes first.'
),
});
} else {
modal.createCustomModal()
.then(({openModal, closeModal}) => {
openModal(
<PreviewModal
subscribersWithPreviewConfigured={scope.subscribersWithPreviewConfigured}
documentId={scope.item._id}
urls={urls}
closeModal={closeModal}
gettext={gettext}
/>
);
});
}
};
scope.close = function() {
if (scope.mode === 'monitoring') {
superdeskFlags.flags.fetching = false;
}
if (scope.$parent.views) {
scope.$parent.views.send = false;
} else if (scope.item) {
scope.item = null;
}
$location.search('fetch', null);
if (scope.config) {
scope.config.reject();
}
};
scope.selectDesk = function(desk) {
scope.selectedDesk = _.cloneDeep(desk);
scope.selectedStage = null;
fetchStages();
fetchMacros();
};
scope.selectStage = function(stage) {
scope.selectedStage = stage;
};
scope.selectMacro = function(macro) {
if (scope.selectedMacro === macro) {
scope.selectedMacro = null;
} else {
scope.selectedMacro = macro;
}
};
scope.send = function(open) {
updateLastDestination();
return runSend(open);
};
scope.$on('item:nextStage', (_e, data) => {
if (scope.item && scope.item._id === data.itemId) {
var oldStage = scope.selectedStage;
scope.selectedStage = data.stage;
scope.send().then((sent) => {
if (!sent) {
scope.selectedStage = oldStage;
}
});
}
});
// events on which panel should close
var closePanelEvents = ['item:spike', 'broadcast:preview'];
angular.forEach(closePanelEvents, (event) => {
scope.$on(event, shouldClosePanel);
});
/**
* @description Closes the opened 'duplicate/send To' panel if the same item getting
* spiked or any item is opening for authoring.
* @param {Object} event
* @param {Object} data - contains the item(=itemId) that was spiked or {item: null} when
* any item opened for authoring (utilising, 'broadcast:preview' with {item: null})
*/
function shouldClosePanel(event, data) {
if (
(scope.config != null && data != null && _.includes(scope.config.itemIds, data.item))
|| (data == null || data.item == null)
) {
scope.close();
}
}
/*
* Returns true if Destination field and Send button needs to be displayed, false otherwise.
* @returns {Boolean}
*/
scope.showSendButtonAndDestination = function() {
if (scope.itemActions) {
var preCondition = scope.mode === 'ingest' ||
scope.mode === 'personal' ||
scope.mode === 'monitoring' ||
scope.mode === 'authoring' &&
scope.isSendEnabled() &&
scope.itemActions.send ||
scope.mode === 'spike';
if (scope.currentUserAction === ctrl.userActions.publish) {
return preCondition && scope.showSendAndPublish();
}
return preCondition;
}
};
/*
* Returns true if Send and Send and Continue button needs to be disabled, false otherwise.
* @returns {Boolean}
*/
scope.disableSendButton = function() {
return !scope.selectedDesk ||
scope.mode !== 'ingest' && scope.selectedStage && scope.mode !== 'spike' &&
(_.get(scope, 'item.task.stage') === scope.selectedStage._id ||
_.includes(_.map(scope.multiItems, 'task.stage'), scope.selectedStage._id));
};
/*
* Returns true if user is not a member of selected desk, false otherwise.
* @returns {Boolean}
*/
scope.disableFetchAndOpenButton = function() {
if (scope.selectedDesk) {
var _isNonMember = _.isEmpty(_.find(desks.userDesks, {_id: scope.selectedDesk._id}));
return _isNonMember;
}
};
/**
* Returns true if Publish Schedule needs to be displayed, false otherwise.
*/
scope.showPublishSchedule = function() {
return scope.item && archiveService.getType(scope.item) !== 'ingest' &&
scope.item.type !== 'composite' && !scope.item.embargo_date && !scope.item.embargo_time &&
['published', 'killed', 'corrected', 'recalled'].indexOf(scope.item.state) === -1 &&
canPublishOnDesk();
};
/**
* Returns true if timezone needs to be displayed, false otherwise.
*/
scope.showTimezone = function() {
return (scope.item.publish_schedule || scope.item.embargo) &&
(scope.showPublishSchedule() || scope.showEmbargo());
};
/**
* Returns true if Embargo needs to be displayed, false otherwise.
*/
scope.showEmbargo = function() {
// If user doesn't have embargo privilege then don't display embargo fields
if (!privileges.privileges.embargo) {
return false;
}
if (config.ui && config.ui.publishEmbargo === false) {
return false;
}
var prePublishCondition = scope.item && archiveService.getType(scope.item) !== 'ingest' &&
scope.item.type !== 'composite' && !scope.item.publish_schedule_date &&
!scope.item.publish_schedule_time;
if (prePublishCondition && authoring.isPublished(scope.item)) {
if (['published', 'corrected'].indexOf(scope.item.state) >= 0) {
return scope.origItem.embargo;
}
// for published states other than 'published', 'corrected'
return false;
}
return prePublishCondition;
};
/**
* Returns true if Embargo needs to be displayed, false otherwise.
*/
scope.isEmbargoEditable = function() {
var publishedCondition = authoring.isPublished(scope.item) && scope.item.schedule_settings &&
scope.item.schedule_settings.utc_embargo &&
datetimeHelper.greaterThanUTC(scope.item.schedule_settings.utc_embargo);
return scope.item && scope.item._editable &&
(!authoring.isPublished(scope.item) || publishedCondition);
};
/**
* Send the content to different desk/stage
* @param {Boolean} open - True to open the item.
* @return {Object} promise
*/
function runSend(open) {
scope.loading = true;
scope.item.sendTo = true;
var deskId = scope.selectedDesk._id;
var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage;
if (scope.mode === 'authoring') {
return sendAuthoring(deskId, stageId, scope.selectedMacro);
} else if (scope.mode === 'archive') {
return sendContent(deskId, stageId, scope.selectedMacro, open);
} else if (scope.config) {
scope.config.promise.finally(() => {
scope.loading = false;
});
return scope.config.resolve({
desk: deskId,
stage: stageId,
macro: scope.selectedMacro ? scope.selectedMacro.name : null,
open: open,
});
} else if (scope.mode === 'ingest') {
return sendIngest(deskId, stageId, scope.selectedMacro, open);
}
}
/**
* Enable Disable the Send and Publish button.
* Send And Publish is enabled using `superdesk.config.js`.
*/
scope.showSendAndPublish = () => !config.ui || angular.isUndefined(config.ui.sendAndPublish) ||
config.ui.sendAndPublish;
/**
* Check if the Send and Publish is allowed or not.
* Following conditions are to met for Send and Publish action
* - Item is not Published i.e. not state Published, Corrected, Killed or Scheduled
* - Selected destination (desk/stage) should be different from item current location (desk/stage)
* - Mode should be authoring
* - Publish Action is allowed on that item.
* @return {Boolean}
*/
scope.canSendAndPublish = function() {
if (scope.mode !== 'authoring' || !scope.item) {
return false;
}
// Selected destination desk should be different from item current location desk
var isDestinationChanged = scope.selectedDesk && scope.item.task.desk !== scope.selectedDesk._id;
return scope.showSendAndPublish() && !authoring.isPublished(scope.item) &&
isDestinationChanged && scope.mode === 'authoring' && scope.itemActions.publish;
};
/**
* Returns true if 'send' button should be displayed. Otherwise, returns false.
* @return {boolean}
*/
scope.isSendEnabled = () => scope.item && !authoring.isPublished(scope.item);
/*
* Send the current item to different desk or stage and publish the item from new location.
*/
scope.sendAndPublish = function() {
return runSendAndPublish();
};
/*
* Returns true if 'send' action is allowed, otherwise false
* @returns {Boolean}
*/
scope.canSendItem = function() {
var itemType = [], typesList;
if (scope.multiItems) {
angular.forEach(scope.multiItems, (item) => {
itemType[item._type] = 1;
});
typesList = Object.keys(itemType);
itemType = typesList.length === 1 ? typesList[0] : null;
}
return scope.mode === 'authoring' || itemType === 'archive' || scope.mode === 'spike' ||
(scope.mode === 'monitoring' && _.get(scope, 'config.action') === scope.vm.userActions.send_to);
};
/**
* Check if it is allowed to publish on current desk
* @returns {Boolean}
*/
function canPublishOnDesk() {
return !(isAuthoringDesk() && config.features.noPublishOnAuthoringDesk);
}
/**
* If the action is correct and kill then the publish privilege needs to be checked.
*/
scope.canPublishItem = function() {
if (!scope.itemActions || !canPublishOnDesk()) {
return false;
}
if (scope._action === 'edit') {
return scope.item ? !scope.item.flags.marked_for_not_publication && scope.itemActions.publish :
scope.itemActions.publish;
} else if (scope._action === 'correct') {
return privileges.privileges.publish && scope.itemActions.correct;
} else if (scope._action === 'kill') {
return privileges.privileges.publish && scope.itemActions.kill;
}
return false;
};
/**
* Set the User Action.
*/
scope.setUserAction = function(action) {
if (scope.currentUserAction === action) {
return;
}
scope.currentUserAction = action;
storage.setItem(USER_ACTION_KEY, action);
setDesksAndStages();
};
/**
* Checks if a given item is valid to publish
*
* @param {Object} item story to be validated
* @return {Object} promise
*/
const validatePublish = (item) => api.save('validate', {act: 'publish', type: item.type, validate: item});
/**
* Sends and publishes the current item in scope
* First checks if the item is dirty and pops up save dialog if needed
* Then checks if the story is valid to publish before sending
* Then sends the story to the destination
* Then publishes it
*
* @param {Object} item story to be validated
* @return {Object} promise
*/
const runSendAndPublish = () => {
var deskId = scope.selectedDesk._id;
var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage;
// send releases lock, increment version.
return scope.beforeSend({action: 'Send and Publish'})
.then(() => validatePublish(scope.item)
.then((validationResult) => {
if (_.get(validationResult, 'errors.length')) {
for (var i = 0; i < validationResult.errors.length; i++) {
notify.error('\'' + _.trim(validationResult.errors[i]) + '\'');
}
return $q.reject();
}
return sendAuthoring(deskId, stageId, scope.selectedMacro, true)
.then((item) => {
scope.loading = true;
// open the item for locking and publish
return authoring.open(scope.item._id, false);
})
.then((item) => {
// update the original item to avoid 412 error.
scope.orig._etag = scope.item._etag = item._etag;
scope.orig._locked = scope.item._locked = item._locked;
scope.orig.task = scope.item.task = item.task;
// change the desk location.
$rootScope.$broadcast('desk_stage:change');
// if locked then publish
if (item._locked) {
return scope.publish();
}
return $q.reject();
})
.then((result) => {
if (result) {
authoringWorkspace.close(false);
}
})
.catch((error) => {
notify.error(gettext('Failed to send and publish.'));
});
})
.finally(() => {
scope.loading = false;
})
);
};
/**
* Run the macro and returns to the modified item.
* @param {Object} item
* @param {String} macro
* @return {Object} promise
*/
function runMacro(item, macro) {
if (macro) {
return macros.call(macro, item, true).then((res) => angular.extend(item, res));
}
return $q.when(item);
}
/**
* Send to different location from authoring.
* @param {String} deskId - selected desk Id
* @param {String} stageId - selected stage Id
* @param {String} macro - macro to apply
* @return {Object} promise
*/
function sendAuthoring(deskId, stageId, macro) {
var msg;
scope.loading = true;
return runMacro(scope.item, macro)
.then((item) => api.find('tasks', scope.item._id)
.then((task) => {
scope.task = task;
msg = 'Send';
return scope.beforeSend({action: msg});
})
.then((result) => {
if (result && result._etag) {
scope.task._etag = result._etag;
}
return api.save('move', {}, {task: {desk: deskId, stage: stageId}}, scope.item);
})
.then((value) => {
notify.success(gettext('Item sent.'));
if (scope.currentUserAction === ctrl.userActions.send_to) {
// Remember last destination desk and stage for send_to.
var lastDestination = scope.destination_last[scope.currentUserAction];
if (!lastDestination ||
(lastDestination.desk !== deskId || lastDestination.stage !== stageId)) {
updateLastDestination();
}
}
authoringWorkspace.close(true);
return true;
}, (err) => {
if (err) {
if (angular.isDefined(err.data._message)) {
notify.error(err.data._message);
} else if (angular.isDefined(err.data._issues['validator exception'])) {
notify.error(err.data._issues['validator exception']);
}
}
}))
.finally(() => {
scope.loading = false;
});
}
/**
* Update the preferences to store last destinations
* @param {String} key
*/
function updateLastDestination() {
var updates = {};
var deskId = scope.selectedDesk._id;
var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage;
updates[PREFERENCE_KEY] = {desk: deskId, stage: stageId};
preferencesService.update(updates, PREFERENCE_KEY);
}
/**
* Send content to different desk and stage
* @param {String} deskId
* @param {String} stageId
* @param {String} macro
* @param {Boolean} open - If true open the item.
*/
function sendContent(deskId, stageId, macro, open) {
var finalItem;
scope.loading = true;
return api.save('duplicate', {}, {desk: scope.item.task.desk}, scope.item)
.then((item) => api.find('archive', item._id))
.then((item) => runMacro(item, macro))
.then((item) => {
finalItem = item;
return api.find('tasks', item._id);
})
.then((_task) => {
scope.task = _task;
api.save('tasks', scope.task, {
task: _.extend(scope.task.task, {desk: deskId, stage: stageId}),
});
})
.then(() => {
notify.success(gettext('Item sent.'));
scope.close();
if (open) {
$location.url('/authoring/' + finalItem._id);
} else {
$rootScope.$broadcast('item:fetch');
}
})
.finally(() => {
scope.loading = false;
});
}
/**
* Fetch content from ingest to a different desk and stage
* @param {String} deskId
* @param {String} stageId
* @param {String} macro
* @param {Boolean} open - If true open the item.
*/
function sendIngest(deskId, stageId, macro, open) {
scope.loading = true;
return send.oneAs(scope.item, {
desk: deskId,
stage: stageId,
macro: macro ? macro.name : macro,
}).then((finalItem) => {
notify.success(gettext('Item fetched.'));
if (open) {
authoringWorkspace.edit(finalItem);
} else {
$rootScope.$broadcast('item:fetch');
}
})
.finally(() => {
scope.loading = false;
});
}
/**
* Fetch desk and last selected desk and stage for send_to and publish action
* @return {Object} promise
*/
function fetchDesks() {
return desks.initialize()
.then(() => {
// get all desks
scope.allDesks = desks.desks._items;
// get user desks
return desks.fetchCurrentUserDesks();
})
.then((deskList) => {
scope.userDesks = deskList;
return preferencesService.get(PREFERENCE_KEY);
})
.then((result) => {
if (result) {
scope.destination_last.send_to = {
desk: result.desk,
stage: result.stage,
};
scope.destination_last.duplicate_to = {
desk: result.desk,
stage: result.stage,
};
}
});
}
/**
* Set the last selected desk based on the user action.
* To be called after currentUserAction is set
*/
function setDesksAndStages() {
if (!scope.currentUserAction) {
return;
}
// set the desks for desk filter
if (scope.currentUserAction === ctrl.userActions.publish) {
scope.desks = scope.userDesks;
} else {
scope.desks = scope.allDesks;
}
if (scope.mode === 'ingest') {
scope.selectDesk(desks.getCurrentDesk());
} else {
// set the last selected desk or current desk
var itemDesk = desks.getItemDesk(scope.item);
var lastDestination = scope.destination_last[scope.currentUserAction];
if (itemDesk) {
if (lastDestination && !_.isNil(lastDestination.desk)) {
scope.selectDesk(desks.deskLookup[lastDestination.desk]);
} else {
scope.selectDesk(itemDesk);
}
} else if (lastDestination && !_.isNil(lastDestination.desk)) {
scope.selectDesk(desks.deskLookup[lastDestination.desk]);
} else {
scope.selectDesk(desks.getCurrentDesk());
}
}
}
/**
* Set stages and last selected stage.
*/
function fetchStages() {
if (!scope.selectedDesk) {
return;
}
scope.stages = desks.deskStages[scope.selectedDesk._id];
var stage = null;
if (scope.currentUserAction === ctrl.userActions.send_to ||
scope.currentUserAction === ctrl.userActions.duplicate_to) {
var lastDestination = scope.destination_last[scope.currentUserAction];
if (lastDestination) {
stage = _.find(scope.stages, {_id: lastDestination.stage});
} else if (scope.item.task && scope.item.task.stage) {
stage = _.find(scope.stages, {_id: scope.item.task.stage});
}
}
if (!stage) {
stage = _.find(scope.stages, {_id: scope.selectedDesk.incoming_stage});
}
scope.selectedStage = stage;
}
/**
* Fetch macros for the selected desk.
*/
function fetchMacros() {
if (!scope.selectedDesk) {
return;
}
macros.getByDesk(scope.selectedDesk.name)
.then((_macros) => {
scope.macros = _macros;
});
}
/**
* Initialize Item Actios and User Actions.
*/
function initialize() {
initializeItemActions();
initializeUserAction();
}
/**
* Initialize User Action
*/
function initializeUserAction() {
// default user action
scope.currentUserAction = storage.getItem(USER_ACTION_KEY) || ctrl.userActions.send_to;
if (scope.orig || scope.item) {
if (scope.config && scope.config.action === 'externalsourceTo') {
scope.currentUserAction = ctrl.userActions.externalsource_to;
}
// if the last action is send to but item is published open publish tab.
if (scope.config && scope.config.action === 'duplicateTo') {
scope.currentUserAction = ctrl.userActions.duplicate_to;
}
if (scope.currentUserAction === ctrl.userActions.send_to &&
scope.canPublishItem() && !scope.isSendEnabled()) {
scope.currentUserAction = ctrl.userActions.publish;
} else if (scope.currentUserAction === ctrl.userActions.publish &&
!scope.canPublishItem() && scope.showSendButtonAndDestination()) {
scope.currentUserAction = ctrl.userActions.send_to;
} else if (scope.currentUserAction === ctrl.userActions.publish &&
isAuthoringDesk() && noPublishOnAuthoringDesk()) {
scope.currentUserAction = ctrl.userActions.send_to;
}
}
}
/**
* The itemActions defined in parent scope (Authoring Directive) is made accessible via this method.
* scope.$parent isn't used as send-item directive is used in multiple places and has different
* hierarchy.
*/
function initializeItemActions() {
if (scope.orig || scope.item) {
scope.itemActions = authoring.itemActions(scope.orig || scope.item);
}
}
/**
* Test if desk of current item is authoring type.
*
* @return {Boolean}
*/
function isAuthoringDesk() {
if (!_.get(scope, 'item.task.desk')) {
return false;
}
const desk = desks.getItemDesk(scope.item);
return desk && desk.desk_type === 'authoring';
}
/**
* Test if noPublishOnAuthoringDesk config is active.
*
* @return {Boolean}
*/
function noPublishOnAuthoringDesk() {
return config.features.noPublishOnAuthoringDesk;
}
// update actions on item save
scope.$watch('orig._current_version', initializeItemActions);
},
};
}
|
agpl-3.0
|
luisivan/on
|
panel/common/cairoutils.h
|
1226
|
/*
* This file is part of unity-2d
*
* Copyright 2011 Canonical Ltd.
*
* Authors:
* - Aurélien Gâteau <aurelien.gateau@canonical.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CAIROUTILS_H
#define CAIROUTILS_H
// Local
#include <common/gscopedpointer.h>
// Qt
// Cairo
#include <cairo.h>
class QImage;
namespace CairoUtils {
typedef GScopedPointer<cairo_surface_t, cairo_surface_destroy> SurfacePointer;
typedef GScopedPointer<cairo_t, cairo_destroy> Pointer;
/**
* Creates a Cairo surface for a QImage.
* QImage format must be Format_ARGB32_Premultiplied.
*/
cairo_surface_t* createSurfaceForQImage(QImage*);
} // namespace
#endif /* CAIROUTILS_H */
|
agpl-3.0
|
andreas-p/nextcloud-server
|
apps/files_versions/lib/Listener/LoadSidebarListener.php
|
1562
|
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Listener;
use OCA\Files\Event\LoadSidebar;
use OCA\Files_Versions\AppInfo\Application;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Util;
class LoadSidebarListener implements IEventListener {
public function handle(Event $event): void {
if (!($event instanceof LoadSidebar)) {
return;
}
// TODO: make sure to only include the sidebar script when
// we properly split it between files list and sidebar
Util::addScript(Application::APP_ID, 'files_versions');
}
}
|
agpl-3.0
|
zielmicha/multilink
|
multilink/transport_targets.h
|
399
|
#ifndef TRANSPROT_TARGETS_H_
#define TRANSPROT_TARGETS_H_
#include "multilink/transport.h"
#include "libreactor/tcp.h"
TargetCreator create_connecting_tcp_target_creator(Reactor& reactor, std::string host, int port);
void create_listening_tcp_target_creator(Reactor& reactor, std::shared_ptr<Transport> transport, std::string host, int port);
TargetCreator unknown_stream_target_creator();
#endif
|
agpl-3.0
|
sjtug/mirror-docker
|
lug/worker-script/archlinux-cn.sh
|
190
|
#!/bin/bash
RSYNC_PASSWORD=$LUG_password rsync -rtlivH --delete-after --delay-updates --safe-links --max-delete=1000 --contimeout=60 $LUG_username@sync.repo.archlinuxcn.org::repo $LUG_path
|
agpl-3.0
|
mvdstruijk/flamingo
|
viewer/src/main/webapp/viewer-html/common/viewercontroller/flamingo/FlamingoLayer.js
|
5324
|
/** The FlamingLayer Class **/
/**
* @constructor
* @augments Layer
* @description The superclass for all flamingolayers
* @param id The id of the layer
* @param options The options to be given to the layer
* @param flamingoObject The flamingo object of the layer
*
*/
Ext.define("viewer.viewercontroller.flamingo.FlamingoLayer",{
enabledEvents: null,
type: null,
constructor :function (config){
if (config.id){
this.id = config.viewerController.mapComponent.makeFlamingoAcceptableId(config.id);
config.id = this.id;
}
this.enabledEvents=new Object();
this.map = this.viewerController ? this.viewerController.mapComponent.getMap() : null;
return this;
},
/**
* Get's the frameworklayer: the viewer specific layer.
*/
getFrameworkLayer : function(){
if (this.map==null){
return null;
}
return this.map.getFrameworkMap();
},
toXML : function(){
Ext.Error.raise({msg: "FlamingoLayer.toXML(): .toXML() must be made!"});
},
getTagName : function(){
Ext.Error.raise({msg: "FlamingoLayer.getTagName: .getTagName() must be made!"});
},
setOption : function(optionKey,optionValue){
this.options[optionKey]=optionValue;
},
getId : function(){
return this.id;
},
getFrameworkId: function(){
return this.map.getId()+"_"+this.getId();
},
setAlpha : function (alpha){
// Fixup wrong Flash alpha, it thinks 0 is transparent and 100 is opaque
if(this.map) {
this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"setAlpha",alpha)
}
},
getAlpha : function (){
return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getAlpha");
},
/**
* Get the last getMap request array
* @see viewer.viewerController.controller.Layer#getLastMapRequest
*/
getLastMapRequest: function(){
var request=this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getLastGetMapRequest");
if (request==null){
return null;
}
return [request];
},
/**
* Returns the type of the layer.
*/
getType: function(){
return this.type;
},
/**
* reloads the framework map
*/
reload: function(){
if (this.map !=null && this.map.getFrameworkMap()){
return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"update");
}
},
/**
* Overwrites the addListener function. Add's the event to allowexternalinterface of flamingo
* so flamingo is allowed to broadcast the event.
*/
addListener : function(event,handler,scope){
//enable flamingo event broadcasting
var flamEvent=this.viewerController.mapComponent.eventList[event];
if (flamEvent!=undefined){
//if not enabled yet, add it
if (this.enabledEvents[flamEvent]==undefined){
this.map.getFrameworkMap().callMethod(this.viewerController.mapComponent.getId(),"addAllowExternalInterface",this.getFrameworkId()+"."+flamEvent);
this.enabledEvents[flamEvent]=true;
}
}
/* fix for infinite loop:
* If this is called from a layer that extends the FlamingoArcLayer the superclass is
* that FlamingoArcLayer and this function is called again when this.superclass.function is called
**/
if (this.superclass.$className == "viewer.viewercontroller.flamingo.FlamingoArcLayer"){
this.superclass.superclass.addListener.call(this,event,handler,scope);
}else{
this.superclass.addListener.call(this,event,handler,scope);
}
//viewer.viewercontroller.controller.Layer.superclass.addListener.call(this,event,handler,scope);
},
setVisible : function (visible){
this.visible = visible;
if (this.options!=null){
this.options["visible"] = visible;
}
if (this.map !=null){
this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "setVisible", visible);
}
},
/**
* Get the visibility
*/
getVisible : function (){
if (this.map !=null){
this.visible = this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "getVisible");
}
if (this.options!=null)
this.options["visible"] = this.visible;
return this.visible;
},
/**
* Overwrite destroy, clear Listeners and forward to super.destroy
*/
destroy: function(){
/* fix for infinite loop:
* If this is called from a layer that extends the FlamingoArcLayer the superclass is
* that FlamingoArcLayer and this function is called again when this.superclass.function is called
**/
if (this.superclass.$className == "viewer.viewercontroller.flamingo.FlamingoArcLayer"){
this.superclass.superclass.destroy.call(this);
}else{
this.superclass.destroy.call(this);
}
}
});
|
agpl-3.0
|
LitusProject/Litus
|
module/ShiftBundle/Controller/Admin/RegistrationSubscriptionController.php
|
5908
|
<?php
namespace ShiftBundle\Controller\Admin;
use Laminas\Mail\Message;
use Laminas\View\Model\ViewModel;
use ShiftBundle\Entity\RegistrationShift;
use ShiftBundle\Entity\Shift\Registered;
/**
* RegistrationSubscriptionController
*
* @author Pieter Maene <pieter.maene@litus.cc>
*/
class RegistrationSubscriptionController extends \CommonBundle\Component\Controller\ActionController\AdminController
{
public function manageAction()
{
$shift = $this->getRegistrationShiftEntity();
if ($shift === null) {
return new ViewModel();
}
$registered = $shift->getRegistered();
$form = $this->getForm('shift_registrationSubscription_add');
if ($this->getRequest()->isPost()) {
$form->setData($this->getRequest()->getPost());
if ($form->isValid()) {
$subscriber = $form->hydrateObject($shift);
if ($subscriber === null) {
$this->flashMessenger()->error(
'Error',
'Unable to add the given person to the registration shift!'
);
$this->redirect()->toRoute(
'shift_admin_registration_shift_subscription',
array(
'action' => 'manage',
'id' => $shift->getId(),
)
);
return new ViewModel();
}
$this->getEntityManager()->persist($subscriber);
$this->getEntityManager()->flush();
$this->redirect()->toRoute(
'shift_admin_registration_shift_subscription',
array(
'action' => 'manage',
'id' => $shift->getId(),
)
);
return new ViewModel();
}
}
return new ViewModel(
array(
'form' => $form,
'shift' => $shift,
'registered' => $registered,
)
);
}
public function deleteAction()
{
$this->initAjax();
$subscription = $this->getSubscriptionEntity();
if ($subscription === null) {
return new ViewModel();
}
$repository = $this->getEntityManager()
->getRepository('ShiftBundle\Entity\RegistrationShift');
$shift = $repository->findOneByRegistered($subscription->getId());
$shift->removeRegistered($subscription->getPerson());
$mailAddress = $this->getEntityManager()
->getRepository('CommonBundle\Entity\General\Config')
->getConfigValue('shift.mail');
$mailName = $this->getEntityManager()
->getRepository('CommonBundle\Entity\General\Config')
->getConfigValue('shift.mail_name');
$language = $subscription->getPerson()->getLanguage();
if ($language === null) {
$language = $this->getEntityManager()->getRepository('CommonBundle\Entity\General\Language')
->findOneByAbbrev('en');
}
$mailData = unserialize(
$this->getEntityManager()
->getRepository('CommonBundle\Entity\General\Config')
->getConfigValue('shift.subscription_deleted_mail')
);
$message = $mailData[$language->getAbbrev()]['content'];
$subject = $mailData[$language->getAbbrev()]['subject'];
$shiftString = $shift->getName() . ' from ' . $shift->getStartDate()->format('d/m/Y h:i') . ' to ' . $shift->getEndDate()->format('d/m/Y h:i');
$mail = new Message();
$mail->setEncoding('UTF-8')
->setBody(str_replace('{{ shift }}', $shiftString, $message))
->setFrom($mailAddress, $mailName)
->addTo($subscription->getPerson()->getEmail(), $subscription->getPerson()->getFullName())
->setSubject($subject);
if (getenv('APPLICATION_ENV') != 'development') {
$this->getMailTransport()->send($mail);
}
$this->getEntityManager()->remove($subscription);
$this->getEntityManager()->flush();
return new ViewModel(
array(
'result' => array(
'status' => 'success',
),
)
);
}
/**
* @return Registered|null
*/
private function getSubscriptionEntity()
{
$subscription = $this->getEntityManager()
->getRepository('ShiftBundle\Entity\Shift\Registered')
->findOneById($this->getParam('id', 0));
if ($subscription === null) {
$this->flashMessenger()->error(
'Error',
'No subscription with the given ID was found!'
);
$this->redirect()->toRoute(
'shift_admin_registration_shift',
array(
'action' => 'manage',
'shift' => $this->getEntityById('ShiftBundle\Entity\RegistrationShift', 'shift'),
)
);
return;
}
return $subscription;
}
/**
* @return RegistrationShift|null
*/
private function getRegistrationShiftEntity()
{
$shift = $this->getEntityById('ShiftBundle\Entity\RegistrationShift', 'shift');
if (!($shift instanceof RegistrationShift)) {
$this->flashMessenger()->error(
'Error',
'No registration shift was found!'
);
$this->redirect()->toRoute(
'shift_admin_registration_shift',
array(
'action' => 'manage',
)
);
return;
}
return $shift;
}
}
|
agpl-3.0
|
virtapi/virtapi
|
controllers/storage_controller.rb
|
569
|
namespace '/storages' do
get do
@storages = Storage.all
return_resource object: @storages
end
post do
@storage = Storage.create!(params[:storage])
return_resource object: @storage
end
before %r{\A/(?<id>\d+)/?.*} do
@storage = Storage.find(params[:id])
end
namespace '/:id' do
delete do
return_resource object: @storage.delete
end
patch do
@storage.assign_attributes(params[:storage]).save!
return_resource object: @storage
end
get do
return_resource object: @storage
end
end
end
|
agpl-3.0
|
nmc-probe/emulab-nome
|
www/netemu.php3
|
1261
|
<?php
#
# Copyright (c) 2000-2003 University of Utah and the Flux Group.
#
# {{{EMULAB-LICENSE
#
# This file is part of the Emulab network testbed software.
#
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this file. If not, see <http://www.gnu.org/licenses/>.
#
# }}}
#
require("defs.php3");
#
# A shameless plug for the web crawlers.
#
PAGEHEADER("Network Emulation using the Utah Network Testbed");
echo "<br>
Emulab.Net provides a great network emulation environment!
<br>
Please see our <a href=\"$TBDOCBASE\">Home Page</a>
for more information.<br><br>\n";
echo "<a href='pix/side-crop-big.jpg'>
<img src='pix/side-crop-med.jpg' align=center></a>\n";
PAGEFOOTER();
?>
|
agpl-3.0
|
routetopa/tet
|
tet/browser/templatetags/keyvalue.py
|
127
|
from django import template
register = template.Library()
@register.simple_tag
def keyvalue(dict, key):
return dict[key]
|
agpl-3.0
|
zcorrecteurs/zcorrecteurs.fr
|
src/Zco/Bundle/GroupesBundle/Form/GroupType.php
|
1347
|
<?php
namespace Zco\Bundle\GroupesBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;
final class GroupType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom', TextType::class, [
'label' => 'Nom du groupe',
'constraints' => [new Assert\NotBlank()],
]);
$builder->add('logo', TextType::class, [
'label' => 'URL du logo masculin',
'required' => false,
]);
$builder->add('logo_feminin', TextType::class, [
'label' => 'URL du logo féminin',
'required' => false,
]);
$builder->add('sanction', CheckboxType::class, [
'label' => 'Sanction',
'required' => false,
]);
$builder->add('team', CheckboxType::class, [
'label' => 'Équipe',
'required' => false,
]);
$builder->add('secondaire', CheckboxType::class, [
'label' => 'Groupe secondaire',
'required' => false,
]);
}
}
|
agpl-3.0
|
RestComm/jss7
|
cap/cap-api/src/main/java/org/restcomm/protocols/ss7/cap/api/service/circuitSwitchedCall/primitive/CollectedInfo.java
|
1352
|
/*
* TeleStax, Open Source Cloud Communications
* Copyright 2012, Telestax Inc and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.protocols.ss7.cap.api.service.circuitSwitchedCall.primitive;
import java.io.Serializable;
/**
*
<code>
CollectedInfo ::= CHOICE {
collectedDigits [0] CollectedDigits
}
</code>
*
*
*
* @author sergey vetyutnev
*
*/
public interface CollectedInfo extends Serializable {
CollectedDigits getCollectedDigits();
}
|
agpl-3.0
|
abhinavvaidya90/8.0
|
multi_duplication/static/description/index.html
|
1715
|
<section class="oe_container">
<div class="oe_row oe_spaced">
<h2 class="oe_slogan">Multiple Duplication</h2>
<h3 class="oe_slogan">Duplicate multiple records in the List View.</h3>
<div class="oe_span8">
<div class="oe_demo oe_picture oe_screenshot">
<a href="">
<img src="duplicate.png">
</a>
</div>
</div>
<div class="oe_span4 ">
<p class='oe_mt32'>
Just by installing this module, you will be able to add multiple duplication functionality on any object you want.
</p>
</div>
</div>
</section>
<section class="oe_container oe_dark">
<div class="oe_row oe_padded">
<h2 class="oe_slogan">Configuration</h2>
<div class="oe_span12">
<p>
Just follow below steps to enable the duplication functionality.
</p>
</div>
</div>
</section>
<section>
<div class="oe_row oe_padded">
<div class="oe_span12">
<h3>Create Record in Settings of Multiple Duplicate</h3>
<div class="oe_row_img oe_centered">
<img class="oe_picture oe_screenshot" src="create.png">
</div>
</div>
</div>
</section>
<section>
<div class="oe_row oe_padded">
<div class="oe_span12">
<h3>Add Models and Apply</h3>
<img class="oe_picture oe_screenshot" src="apply.png">
</div>
</div>
</section>
<section>
<div class="oe_row oe_padded">
<div class="oe_span12">
<h3>Duplicate in List View</h3>
<img class="oe_picture oe_screenshot" src="duplicate.png">
</div>
</div>
</section>
|
agpl-3.0
|
suutari/shoop
|
shuup/admin/utils/str_utils.py
|
605
|
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import re
def camelcase_to_snakecase(string_to_convert):
"""
Convert CamelCase string to snake_case
Original solution in
http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string_to_convert)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
|
agpl-3.0
|
Tesora/tesora-dve-pub
|
tesora-dve-common/src/main/java/com/tesora/dve/errmap/OneParamErrorCode.java
|
910
|
package com.tesora.dve.errmap;
/*
* #%L
* Tesora Inc.
* Database Virtualization Engine
* %%
* Copyright (C) 2011 - 2014 Tesora Inc.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
public class OneParamErrorCode<First> extends ErrorCode {
public OneParamErrorCode(String name, boolean logError) {
super(name, logError);
}
}
|
agpl-3.0
|
mukadder/kc
|
coeus-impl/src/main/java/org/kuali/kra/iacuc/IacucProtocolForm.java
|
16703
|
/*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2016 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kra.iacuc;
import org.apache.commons.lang3.StringUtils;
import org.kuali.coeus.common.framework.module.CoeusModule;
import org.kuali.coeus.common.framework.person.KcPerson;
import org.kuali.coeus.common.notification.impl.NotificationHelper;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.kra.authorization.KraAuthorizationConstants;
import org.kuali.kra.iacuc.actions.IacucActionHelper;
import org.kuali.kra.iacuc.customdata.IacucProtocolCustomDataHelper;
import org.kuali.kra.iacuc.noteattachment.IacucNotesAttachmentsHelper;
import org.kuali.kra.iacuc.notification.IacucProtocolNotificationContext;
import org.kuali.kra.iacuc.onlinereview.IacucOnlineReviewsActionHelper;
import org.kuali.kra.iacuc.onlinereview.IacucProtocolOnlineReviewService;
import org.kuali.kra.iacuc.permission.IacucPermissionsHelper;
import org.kuali.kra.iacuc.personnel.IacucPersonnelHelper;
import org.kuali.kra.iacuc.procedures.IacucProtocolProcedureService;
import org.kuali.kra.iacuc.procedures.IacucProtocolProceduresHelper;
import org.kuali.kra.iacuc.protocol.IacucProtocolHelper;
import org.kuali.kra.iacuc.protocol.reference.IacucProtocolReferenceBean;
import org.kuali.kra.iacuc.questionnaire.IacucQuestionnaireHelper;
import org.kuali.kra.iacuc.specialreview.IacucProtocolSpecialReviewHelper;
import org.kuali.kra.iacuc.species.IacucProtocolSpeciesHelper;
import org.kuali.kra.iacuc.species.exception.IacucProtocolExceptionHelper;
import org.kuali.kra.iacuc.threers.IacucAlternateSearchHelper;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.protocol.ProtocolFormBase;
import org.kuali.kra.protocol.actions.ActionHelperBase;
import org.kuali.kra.protocol.actions.ProtocolStatusBase;
import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionBase;
import org.kuali.kra.protocol.customdata.ProtocolCustomDataHelperBase;
import org.kuali.kra.protocol.onlinereview.OnlineReviewsActionHelperBase;
import org.kuali.kra.protocol.onlinereview.ProtocolOnlineReviewService;
import org.kuali.kra.protocol.protocol.ProtocolHelperBase;
import org.kuali.kra.protocol.protocol.reference.ProtocolReferenceBeanBase;
import org.kuali.kra.protocol.questionnaire.QuestionnaireHelperBase;
import org.kuali.kra.protocol.specialreview.ProtocolSpecialReviewHelperBase;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kns.datadictionary.HeaderNavigation;
import org.kuali.rice.kns.util.ActionFormUtilMap;
import org.kuali.rice.kns.web.ui.HeaderField;
import org.kuali.rice.krad.util.GlobalVariables;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
public class IacucProtocolForm extends ProtocolFormBase {
private static final long serialVersionUID = -535557943052220820L;
private IacucProtocolSpeciesHelper iacucProtocolSpeciesHelper;
private IacucAlternateSearchHelper iacucAlternateSearchHelper;
private IacucProtocolExceptionHelper iacucProtocolExceptionHelper;
private IacucProtocolProceduresHelper iacucProtocolProceduresHelper;
private boolean defaultOpenCopyTab = false;
private boolean reinitializeModifySubmissionFields = true;
public IacucProtocolForm() throws Exception {
super();
initializeIacucProtocolSpecies();
initializeIacucAlternateSearchHelper();
initializeIacucProtocolException();
initializeIacucProtocolProcedures();
}
public void initializeIacucProtocolSpecies() throws Exception {
setIacucProtocolSpeciesHelper(new IacucProtocolSpeciesHelper(this));
}
public void initializeIacucProtocolProcedures() throws Exception {
setIacucProtocolProceduresHelper(new IacucProtocolProceduresHelper(this));
}
public void initializeIacucProtocolException() throws Exception {
setIacucProtocolExceptionHelper(new IacucProtocolExceptionHelper(this));
}
protected void initializeIacucAlternateSearchHelper() throws Exception {
setIacucAlternateSearchHelper(new IacucAlternateSearchHelper(this));
}
@Override
public String getActionName() {
return "iacucProtocol";
}
@Override
protected String getDefaultDocumentTypeName() {
return "IacucProtocolDocument";
}
/**
* Gets a {@link IacucProtocolDocument ProtocolDocument}.
* @return {@link IacucProtocolDocument ProtocolDocument}
*/
public IacucProtocolDocument getIacucProtocolDocument() {
return (IacucProtocolDocument) super.getProtocolDocument();
}
@Override
protected String getLockRegion() {
return KraAuthorizationConstants.LOCK_DESCRIPTOR_IACUC_PROTOCOL;
}
public IacucProtocolHelper getProtocolHelper() {
return (IacucProtocolHelper)super.getProtocolHelper();
}
@Override
protected ProtocolHelperBase createNewProtocolHelperInstanceHook(ProtocolFormBase protocolForm) {
return new IacucProtocolHelper((IacucProtocolForm) protocolForm);
}
public IacucPermissionsHelper getPermissionsHelper(ProtocolFormBase protocolForm) {
return (IacucPermissionsHelper)super.getPermissionsHelper();
}
@Override
protected IacucPermissionsHelper createNewPermissionsHelperInstanceHook(ProtocolFormBase protocolForm) {
return new IacucPermissionsHelper((IacucProtocolForm) protocolForm);
}
public IacucPersonnelHelper getPersonnelHelper(ProtocolFormBase protocolForm) {
return (IacucPersonnelHelper)super.getPersonnelHelper();
}
@Override
protected IacucPersonnelHelper createNewPersonnelHelperInstanceHook(ProtocolFormBase protocolForm) {
return new IacucPersonnelHelper((IacucProtocolForm)protocolForm);
}
public IacucNotesAttachmentsHelper getNotesAttachmentHelper(ProtocolFormBase form) {
return (IacucNotesAttachmentsHelper)super.getNotesAttachmentsHelper();
}
@Override
protected IacucNotesAttachmentsHelper createNewNotesAttachmentsHelperInstanceHook(ProtocolFormBase protocolForm) {
return new IacucNotesAttachmentsHelper((IacucProtocolForm)protocolForm);
}
protected QuestionnaireHelperBase createNewQuestionnaireHelper(ProtocolFormBase form) {
return new IacucQuestionnaireHelper(form);
}
@Override
public String getModuleCode() {
return CoeusModule.IACUC_PROTOCOL_MODULE_CODE;
}
public IacucProtocolSpeciesHelper getIacucProtocolSpeciesHelper() {
return iacucProtocolSpeciesHelper;
}
public void setIacucProtocolSpeciesHelper(IacucProtocolSpeciesHelper iacucProtocolSpeciesHelper) {
this.iacucProtocolSpeciesHelper = iacucProtocolSpeciesHelper;
}
public IacucAlternateSearchHelper getIacucAlternateSearchHelper() {
return iacucAlternateSearchHelper;
}
public void setIacucAlternateSearchHelper(IacucAlternateSearchHelper iacucAlternateSearchHelper) {
this.iacucAlternateSearchHelper = iacucAlternateSearchHelper;
}
@Override
protected ProtocolReferenceBeanBase createNewProtocolReferenceBeanInstance() {
return new IacucProtocolReferenceBean();
}
public IacucProtocolExceptionHelper getIacucProtocolExceptionHelper() {
return iacucProtocolExceptionHelper;
}
public void setIacucProtocolExceptionHelper(IacucProtocolExceptionHelper iacucProtocolExceptionHelper) {
this.iacucProtocolExceptionHelper = iacucProtocolExceptionHelper;
}
@Override
public void populate(HttpServletRequest request) {
super.populate(request);
// Temporary hack for KRACOEUS-489
if (getActionFormUtilMap() instanceof ActionFormUtilMap) {
((ActionFormUtilMap) getActionFormUtilMap()).clear();
}
getIacucProtocolDocument().getIacucProtocol().setIacucProtocolStudyGroupBeans(getIacucProtocolProcedureService().getRevisedStudyGroupBeans(getIacucProtocolDocument().getIacucProtocol(),
getIacucProtocolProceduresHelper().getAllProcedures()));
}
@Override
public void populateHeaderFields(WorkflowDocument workflowDocument) {
super.populateHeaderFields(workflowDocument);
IacucProtocolDocument pd = getIacucProtocolDocument();
HeaderField documentNumber = getDocInfo().get(0);
documentNumber.setDdAttributeEntryName("DataDictionary.IacucProtocolDocument.attributes.documentNumber");
ProtocolStatusBase protocolStatus = (pd == null) ? null : pd.getIacucProtocol().getProtocolStatus();
HeaderField docStatus = new HeaderField("DataDictionary.AttributeReference.attributes.workflowDocumentStatus", protocolStatus == null? "" : protocolStatus.getDescription());
getDocInfo().set(1, docStatus);
String lastUpdatedDateStr = null;
if(pd != null && pd.getUpdateTimestamp() != null) {
lastUpdatedDateStr = getFormattedDateTime(pd.getUpdateTimestamp());
}
if(getDocInfo().size() > 2) {
KcPerson initiator = getKcPersonService().getKcPersonByPersonId(pd.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId());
String modifiedInitiatorFieldStr = initiator == null ? "" : initiator.getUserName();
if(StringUtils.isNotBlank(lastUpdatedDateStr)) {
modifiedInitiatorFieldStr += (" : " + lastUpdatedDateStr);
}
getDocInfo().set(2, new HeaderField("DataDictionary.IacucProtocol.attributes.initiatorLastUpdated", modifiedInitiatorFieldStr));
}
String protocolSubmissionStatusStr = null;
if(pd != null && pd.getIacucProtocol() != null && pd.getIacucProtocol().getProtocolSubmission() != null) {
pd.getIacucProtocol().getProtocolSubmission().refreshReferenceObject("submissionStatus");
protocolSubmissionStatusStr = pd.getIacucProtocol().getProtocolSubmission().getSubmissionStatus().getDescription();
}
HeaderField protocolSubmissionStatus = new HeaderField("DataDictionary.IacucProtocol.attributes.protocolSubmissionStatus", protocolSubmissionStatusStr);
getDocInfo().set(3, protocolSubmissionStatus);
getDocInfo().add(new HeaderField("DataDictionary.IacucProtocol.attributes.protocolNumber", (pd == null) ? null : pd.getIacucProtocol().getProtocolNumber()));
String expirationDateStr = null;
if(pd != null && pd.getProtocol().getExpirationDate() != null) {
expirationDateStr = getFormattedDate(pd.getIacucProtocol().getExpirationDate());
}
HeaderField expirationDate = new HeaderField("DataDictionary.IacucProtocol.attributes.expirationDate", expirationDateStr);
getDocInfo().add(expirationDate);
}
@Override
public HeaderNavigation[] getHeaderNavigationTabs() {
HeaderNavigation[] navigation = super.getHeaderNavigationTabs();
ProtocolOnlineReviewService onlineReviewService = getProtocolOnlineReviewService();
List<HeaderNavigation> resultList = new ArrayList<HeaderNavigation>();
boolean onlineReviewTabEnabled = false;
if (getProtocolDocument() != null && getProtocolDocument().getProtocol() != null) {
String principalId = GlobalVariables.getUserSession().getPrincipalId();
ProtocolSubmissionBase submission = getProtocolDocument().getProtocol().getProtocolSubmission();
boolean isUserOnlineReviewer = onlineReviewService.isProtocolReviewer(principalId, false, submission);
boolean isUserIacucAdmin = getSystemAuthorizationService().hasRole(GlobalVariables.getUserSession().getPrincipalId(), "KC-UNT", "IACUC Administrator");
onlineReviewTabEnabled = (isUserOnlineReviewer || isUserIacucAdmin)
&& onlineReviewService.isProtocolInStateToBeReviewed((IacucProtocol)getProtocolDocument().getProtocol());
}
//We have to copy the HeaderNavigation elements into a new collection as the
//List returned by DD is it's cached copy of the header navigation list.
for (HeaderNavigation nav : navigation) {
if (StringUtils.equals(nav.getHeaderTabNavigateTo(),ONLINE_REVIEW_NAV_TO)) {
nav.setDisabled(!onlineReviewTabEnabled);
if (onlineReviewTabEnabled || ((!onlineReviewTabEnabled) && (!HIDE_ONLINE_REVIEW_WHEN_DISABLED))) {
resultList.add(nav);
}
} else {
resultList.add(nav);
}
}
HeaderNavigation[] result = new HeaderNavigation[resultList.size()];
resultList.toArray(result);
return result;
}
protected ProtocolOnlineReviewService getProtocolOnlineReviewService() {
return KcServiceLocator.getService(IacucProtocolOnlineReviewService.class);
}
@Override
protected QuestionnaireHelperBase createNewQuestionnaireHelperInstanceHook(ProtocolFormBase protocolForm) {
return new IacucQuestionnaireHelper((IacucProtocolForm) protocolForm);
}
@Override
protected ActionHelperBase createNewActionHelperInstanceHook(ProtocolFormBase protocolForm, boolean initializeActions) throws Exception{
IacucActionHelper iacucActionHelper = new IacucActionHelper((IacucProtocolForm) protocolForm);
if(initializeActions) {
iacucActionHelper.initializeProtocolActions();
}
return iacucActionHelper;
}
@Override
protected ProtocolSpecialReviewHelperBase createNewSpecialReviewHelperInstanceHook(ProtocolFormBase protocolForm) {
return new IacucProtocolSpecialReviewHelper((IacucProtocolForm) protocolForm);
}
@Override
protected ProtocolCustomDataHelperBase createNewCustomDataHelperInstanceHook(ProtocolFormBase protocolForm) {
return new IacucProtocolCustomDataHelper((IacucProtocolForm) protocolForm);
}
@Override
protected OnlineReviewsActionHelperBase createNewOnlineReviewsActionHelperInstanceHook(ProtocolFormBase protocolForm) {
return new IacucOnlineReviewsActionHelper((IacucProtocolForm) protocolForm);
}
public IacucProtocolProceduresHelper getIacucProtocolProceduresHelper() {
return iacucProtocolProceduresHelper;
}
public void setIacucProtocolProceduresHelper(IacucProtocolProceduresHelper iacucProtocolProceduresHelper) {
this.iacucProtocolProceduresHelper = iacucProtocolProceduresHelper;
}
@Override
protected NotificationHelper<IacucProtocolNotificationContext> getNotificationHelperHook() {
return new NotificationHelper<IacucProtocolNotificationContext>();
}
protected IacucProtocolProcedureService getIacucProtocolProcedureService() {
return (IacucProtocolProcedureService) KcServiceLocator.getService("iacucProtocolProcedureService");
}
public boolean isReinitializeModifySubmissionFields() {
return reinitializeModifySubmissionFields;
}
public void setReinitializeModifySubmissionFields(boolean reinitializeModifySubmissionFields) {
this.reinitializeModifySubmissionFields = reinitializeModifySubmissionFields;
}
public boolean isDefaultOpenCopyTab() {
return defaultOpenCopyTab;
}
public void setDefaultOpenCopyTab(boolean defaultOpenCopyTab) {
this.defaultOpenCopyTab = defaultOpenCopyTab;
}
@Override
protected List<String> getTerminalNodeNamesHook() {
List<String> retVal = new ArrayList<String>();
retVal.add(Constants.IACUC_PROTOCOL_IACUCREVIEW_ROUTE_NODE_NAME);
return retVal;
}
public String getShortUrl() {
return getBaseShortUrl() + "/kc-common/iacuc-protocols/" + getIacucProtocolDocument().getProtocol().getProtocolNumber();
}
}
|
agpl-3.0
|
dzc34/Asqatasun
|
documentation/fr/README.md
|
367
|
# Asqatasun
@@@TODO
## Fonctionnalités
@@@TODO
## Téléchargement
@@@TODO
## Démo
@@@TODO
## Installation et documentation
@@@TODO
## Contribuer
@@@TODO
## Contact et discussions
* Asqatasun forum @@@TODO
* email à `asqatasun AT asqatasun dot org` (only English, French and klingon is spoken :) )
* [Twitter @Asqatasun](https://twitter.com/Asqatasun)
|
agpl-3.0
|
simonoche/wterritoires
|
lib/model/doctrine/sfGuardGroupUtf8Table.class.php
|
183
|
<?php
class sfGuardGroupUtf8Table extends sfGuardGroupTable
{
public static function getInstance()
{
return Doctrine_Core::getTable('sfGuardGroupUtf8');
}
}
|
agpl-3.0
|
lspitzner/brittany
|
data/Test88.hs
|
62
|
func x | x = simple expression
| otherwise = 0
|
agpl-3.0
|
LtRipley36706/ACE-World
|
Database/3-Core/9 WeenieDefaults/SQL/Creature/Unsorted/25726 Torch.sql
|
3716
|
DELETE FROM `weenie` WHERE `class_Id` = 25726;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (25726, 'torchnoir1', 10, '2019-02-10 00:00:00') /* Creature */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (25726, 1, 16) /* ItemType - Creature */
, (25726, 6, -1) /* ItemsCapacity */
, (25726, 7, -1) /* ContainersCapacity */
, (25726, 16, 32) /* ItemUseable - Remote */
, (25726, 93, 6292504) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity, ReportCollisionsAsEnvironment, EdgeSlide */
, (25726, 95, 3) /* RadarBlipColor - White */
, (25726, 307, 0) /* DamageRating */
, (25726, 308, 0) /* DamageResistRating */
, (25726, 313, 0) /* CritRating */
, (25726, 314, 0) /* CritDamageRating */
, (25726, 315, 0) /* CritResistRating */
, (25726, 316, 0) /* CritDamageResistRating */
, (25726, 370, 0) /* GearDamage */
, (25726, 371, 0) /* GearDamageResist */
, (25726, 372, 0) /* GearCrit */
, (25726, 373, 0) /* GearCritResist */
, (25726, 374, 0) /* GearCritDamage */
, (25726, 375, 0) /* GearCritDamageResist */
, (25726, 376, 0) /* GearHealingBoost */
, (25726, 377, 0) /* GearNetherResist */
, (25726, 378, 0) /* GearLifeResist */
, (25726, 379, 0) /* GearMaxHealth */
, (25726, 381, 0) /* PKDamageRating */
, (25726, 382, 0) /* PKDamageResistRating */
, (25726, 383, 0) /* GearPKDamageRating */
, (25726, 384, 0) /* GearPKDamageResistRating */
, (25726, 386, 0) /* Overpower */
, (25726, 387, 0) /* OverpowerResist */
, (25726, 388, 0) /* GearOverpower */
, (25726, 389, 0) /* GearOverpowerResist */
, (25726, 8007, 0) /* PCAPRecordedAutonomousMovement */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (25726, 1, True ) /* Stuck */
, (25726, 19, False) /* Attackable */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (25726, 54, 3) /* UseRadius */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (25726, 1, 'Torch') /* Name */
, (25726, 15, 'A torch.') /* ShortDesc */
, (25726, 8006, 'AAA9AAAAAAA=') /* PCAPRecordedCurrentMotionState */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (25726, 1, 33554917) /* Setup */
, (25726, 2, 150995094) /* MotionTable */
, (25726, 3, 536870980) /* SoundTable */
, (25726, 8, 100667506) /* Icon */
, (25726, 22, 872415275) /* PhysicsEffectTable */
, (25726, 8001, 1048630) /* PCAPRecordedWeenieHeader - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor */
, (25726, 8003, 4) /* PCAPRecordedObjectDesc - Stuck */
, (25726, 8005, 104451) /* PCAPRecordedPhysicsDesc - CSetup, MTable, STable, PeTable, Position, Movement */;
INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (25726, 8040, 1582104996, 154.308, -78.5632, 2.27875, -0.375149, 0, 0, 0.926964) /* PCAPRecordedLocation */
/* @teleloc 0x5E4D01A4 [154.308000 -78.563200 2.278750] -0.375149 0.000000 0.000000 0.926964 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (25726, 8000, 2923233222) /* PCAPRecordedObjectIID */;
|
agpl-3.0
|
baughj/hybrasylserver
|
XML/XSD/Objects/VariantGroup.cs
|
7438
|
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code++. Version 5.2.0.0. www.xsd2code.com
// </auto-generated>
// ------------------------------------------------------------------------------
#pragma warning disable
namespace Hybrasyl.Xml
{
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.Xml;
using System.IO;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.8")]
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlTypeAttribute(Namespace="http://www.hybrasyl.com/XML/Hybrasyl/2020-02")]
[XmlRootAttribute(Namespace="http://www.hybrasyl.com/XML/Hybrasyl/2020-02", IsNullable=false)]
public partial class VariantGroup
{
#region Private fields
private string _name;
private List<Variant> _variant;
private static XmlSerializer _serializer;
#endregion
public VariantGroup()
{
_variant = new List<Variant>();
}
[StringLengthAttribute(255, MinimumLength=1)]
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
[XmlElement("Variant")]
public List<Variant> Variant
{
get
{
return _variant;
}
set
{
_variant = value;
}
}
private static XmlSerializer SerializerXML
{
get
{
if ((_serializer == null))
{
_serializer = new XmlSerializerFactory().CreateSerializer(typeof(VariantGroup));
}
return _serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serialize VariantGroup object
/// </summary>
/// <returns>XML value</returns>
public virtual string Serialize()
{
StreamReader streamReader = null;
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream();
System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.IndentChars = " ";
System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
SerializerXML.Serialize(xmlWriter, this);
memoryStream.Seek(0, SeekOrigin.Begin);
streamReader = new StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally
{
if ((streamReader != null))
{
streamReader.Dispose();
}
if ((memoryStream != null))
{
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes VariantGroup object
/// </summary>
/// <param name="input">string workflow markup to deserialize</param>
/// <param name="obj">Output VariantGroup object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this Serializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string input, out VariantGroup obj, out Exception exception)
{
exception = null;
obj = default(VariantGroup);
try
{
obj = Deserialize(input);
return true;
}
catch (Exception ex)
{
exception = ex;
return false;
}
}
public static bool Deserialize(string input, out VariantGroup obj)
{
Exception exception = null;
return Deserialize(input, out obj, out exception);
}
public static VariantGroup Deserialize(string input)
{
StringReader stringReader = null;
try
{
stringReader = new StringReader(input);
return ((VariantGroup)(SerializerXML.Deserialize(XmlReader.Create(stringReader))));
}
finally
{
if ((stringReader != null))
{
stringReader.Dispose();
}
}
}
public static VariantGroup Deserialize(Stream s)
{
return ((VariantGroup)(SerializerXML.Deserialize(s)));
}
#endregion
/// <summary>
/// Serializes current VariantGroup object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out Exception exception)
{
exception = null;
try
{
SaveToFile(fileName);
return true;
}
catch (Exception e)
{
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName)
{
StreamWriter streamWriter = null;
try
{
string dataString = Serialize();
FileInfo outputFile = new FileInfo(fileName);
streamWriter = outputFile.CreateText();
streamWriter.WriteLine(dataString);
streamWriter.Close();
}
finally
{
if ((streamWriter != null))
{
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an VariantGroup object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output VariantGroup object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this Serializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out VariantGroup obj, out Exception exception)
{
exception = null;
obj = default(VariantGroup);
try
{
obj = LoadFromFile(fileName);
return true;
}
catch (Exception ex)
{
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out VariantGroup obj)
{
Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static VariantGroup LoadFromFile(string fileName)
{
FileStream file = null;
StreamReader sr = null;
try
{
file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new StreamReader(file);
string dataString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(dataString);
}
finally
{
if ((file != null))
{
file.Dispose();
}
if ((sr != null))
{
sr.Dispose();
}
}
}
}
}
#pragma warning restore
|
agpl-3.0
|
jbreitbart/priceguard_classic
|
branches/first/anmelden.php
|
4179
|
<?php
require_once("conf.php");
$text = $head;
$text .= $body;
$text .= menu("");
$text .= main();
$text .= $foot;
echo gzipoutput($text);
// ===========================================================================
function main()
{
global $email, $pass, $pass2, $mysql_db, $name;
if (($email != "") and ($pass != "")) { // Variablen nicht leer?
if ((validateEmail($email))) { // Email in Ordnung?
if ($pass == $pass2) { // Passwort nicht verschrieben?
$lk = connect();
$db = mysql_db_query($mysql_db, "SELECT * FROM pricewatch_user WHERE EMAIL=\"" . trim(addslashes(strtolower($email))) . "\" LIMIT 1", $lk);
if (!$arr = mysql_fetch_array($db, MYSQL_ASSOC)) { // E-Mail schon eingetragen?
$db = mysql_db_query($mysql_db, "INSERT pricewatch_user (EMAIL, PASSWORT) VALUES (\"" . trim(addslashes(strtolower($email))) . "\", \"" . addslashes($pass) . "\")", $lk);
if ($db == true) { // DB Eintrag erfolgreich?
sendemail ($email, "Anmeldung bei $name", anmeldetext($email, $pass));
$str .= "<br><br><table width='400' align='center' class='rand'>";
$str .= "<tr><td>";
$str .= "<p align='center'><b>Anmeldung erfolgreich abgeschlossen!</b></p>";
$str .= "<p align='justify'>Sie können sich jetzt mit ihrer E-Mail und Passwort auf der Startseite einloggen. Zur Bestätigung haben wir ihnen eine E-Mail mit den angegeben Daten geschickt.</p>";
$str .= "<p align='center'><a href='index.php'>Zurück zur Startseite</a></p>";
$str .= "</td></tr></table><br><br>";
} else { // DB Eintrag erfolgreich?
$fehler = "Es ist ein Datenbankproblem aufgetreten. Bitte probieren sie es später noch einmal.";
} //DB Eintrag erfolgreich? - Else
} else { // E-Mail schon eingetragen?
$fehler = "Die E-Mail Adresse ist bereits bei uns angemeldet!";
} // E-Mail schon eingetragen? - Else
mysql_close($lk);
} else { // Passwort nicht verschrieben?
$fehler = "Das Feld Passwort und das Feld Passwort Wiederholung stimmen nicht überein!";
} // Passwort nicht verschrieben? - Else
} else { // Email in Ordnung?
$fehler = "Bitte geben sie eine echte E-Mail Adresse an!";
} // Email in Ordnung? - Else
} // Variablen nicht leer?
if ((isset($fehler)) OR ($email == "") OR ($pass == "")) {
$str = "<br><br>";
if (isset($fehler)) {
$str .= "<table width='400' align='center' class='rand'>";
$str .= "<tr><td>";
$str .= "<p align='center'><b>Es ist ein Fehler aufgetreten!</b></p><p align='justify'>$fehler</p></td></tr>";
$str .= "</table><br>";
}
$str .= "<table width='400' align='center' class='rand'>";
$str .= "<tr><td>";
$str .= "<p align='justify'>Bitte füllen sie das folgende Formular <b>komplett</b> aus und klicken sie auf anmelden! Nach ihrer Anmeldung wird ihnen eine Bestätigungs per E-Mail zugesandt.<br><br></p></td></tr>";
$str .= "<tr><td><table width='75%' align='center'>";
$str .= "<form method='post' action='anmelden.php'>";
$str .= "<tr><td>E-Mail:</td>";
$str .= "<td align='center'><input type='text' name='email' class='input' value='$email'></td></tr>";
$str .= "<tr><td>Passwort:</td>";
$str .= "<td align='center'><input type='password' name='pass' class='input'></td></tr>";
$str .= "<tr><td>Passwort Wdh.:</td>";
$str .= "<td align='center'><input type='password' name='pass2' class='input'></td></tr>";
$str .= "<tr><td colspan='2' align='center'><br><input type='submit' name='Anmelden' class='forminput' value=' Anmelden '></fotm></td></tr>";
$str .= "</table></td></tr>";
$str .= "</table>";
$str .= "<br><br><br>";
}
return $str;
}
?>
|
agpl-3.0
|
cBioPortal/cbioportal-frontend
|
src/pages/patientView/structuralVariant/column/AnnotationColumnFormatter.tsx
|
9418
|
import * as React from 'react';
import _ from 'lodash';
import {
civicSortValue,
DEFAULT_ANNOTATION_DATA,
GenericAnnotation,
IAnnotation,
USE_DEFAULT_PUBLIC_INSTANCE_FOR_ONCOKB,
oncoKbAnnotationSortValue,
} from 'react-mutation-mapper';
import { CancerStudy, StructuralVariant } from 'cbioportal-ts-api-client';
import { IAnnotationColumnProps } from 'shared/components/mutationTable/column/AnnotationColumnFormatter';
import { CancerGene, IndicatorQueryResp } from 'oncokb-ts-api-client';
import {
RemoteData,
IOncoKbData,
generateQueryStructuralVariantId,
OncoKbCardDataType,
calculateOncoKbAvailableDataType,
} from 'cbioportal-utils';
import AnnotationHeader from 'shared/components/mutationTable/column/annotation/AnnotationHeader';
export default class AnnotationColumnFormatter {
public static getData(
structuralVariantData: StructuralVariant[] | undefined,
oncoKbCancerGenes?: RemoteData<CancerGene[] | Error | undefined>,
oncoKbData?: RemoteData<IOncoKbData | Error | undefined>,
usingPublicOncoKbInstance?: boolean,
uniqueSampleKeyToTumorType?: { [sampleId: string]: string },
studyIdToStudy?: { [studyId: string]: CancerStudy }
) {
let value: IAnnotation;
if (structuralVariantData) {
let oncoKbIndicator: IndicatorQueryResp | undefined = undefined;
let oncoKbStatus: IAnnotation['oncoKbStatus'] = 'complete';
let oncoKbGeneExist = false;
let isOncoKbCancerGene = false;
let isSite1GeneOncoKbAnnotated = false;
let isSite1oncoKbCancerGene = false;
let isSite2GeneOncoKbAnnotated = false;
let isSite2oncoKbCancerGene = false;
if (
oncoKbCancerGenes &&
!(oncoKbCancerGenes instanceof Error) &&
!(oncoKbCancerGenes.result instanceof Error)
) {
const oncoKbCancerGeneSetByEntrezGeneId = _.keyBy(
oncoKbCancerGenes.result,
gene => gene.entrezGeneId
);
isSite1oncoKbCancerGene =
oncoKbCancerGeneSetByEntrezGeneId[
structuralVariantData[0].site1EntrezGeneId
] !== undefined;
isSite2oncoKbCancerGene =
oncoKbCancerGeneSetByEntrezGeneId[
structuralVariantData[0].site2EntrezGeneId
] !== undefined;
isSite1GeneOncoKbAnnotated =
isSite1oncoKbCancerGene &&
oncoKbCancerGeneSetByEntrezGeneId[
structuralVariantData[0].site1EntrezGeneId
].oncokbAnnotated;
isSite2GeneOncoKbAnnotated =
isSite2oncoKbCancerGene &&
oncoKbCancerGeneSetByEntrezGeneId[
structuralVariantData[0].site2EntrezGeneId
].oncokbAnnotated;
oncoKbGeneExist =
isSite1GeneOncoKbAnnotated || isSite2GeneOncoKbAnnotated;
isOncoKbCancerGene =
isSite1oncoKbCancerGene || isSite2oncoKbCancerGene;
}
// Always show oncogenicity icon even when the indicatorMapResult is empty.
// We want to show an icon for genes that haven't been annotated by OncoKB
let oncoKbAvailableDataTypes: OncoKbCardDataType[] = [
OncoKbCardDataType.BIOLOGICAL,
];
// oncoKbData may exist but it might be an instance of Error, in that case we flag the status as error
if (oncoKbData && oncoKbData.result instanceof Error) {
oncoKbStatus = 'error';
} else if (oncoKbGeneExist) {
// actually, oncoKbData.result shouldn't be an instance of Error in this case (we already check it above),
// but we need to check it again in order to avoid TS errors/warnings
if (
oncoKbData &&
oncoKbData.result &&
!(oncoKbData.result instanceof Error) &&
oncoKbData.isComplete
) {
oncoKbIndicator = this.getIndicatorData(
structuralVariantData,
oncoKbData.result,
uniqueSampleKeyToTumorType,
studyIdToStudy
);
oncoKbAvailableDataTypes = _.uniq([
...oncoKbAvailableDataTypes,
...calculateOncoKbAvailableDataType(
_.values(oncoKbData.result.indicatorMap)
),
]);
}
oncoKbStatus = oncoKbData ? oncoKbData.status : 'pending';
}
const site1HugoSymbol = structuralVariantData[0].site1HugoSymbol;
const site2HugoSymbol = structuralVariantData[0].site2HugoSymbol;
let hugoGeneSymbol = site1HugoSymbol;
if (oncoKbGeneExist) {
hugoGeneSymbol = isSite1GeneOncoKbAnnotated
? site1HugoSymbol
: site2HugoSymbol;
} else if (isOncoKbCancerGene) {
hugoGeneSymbol = isSite1oncoKbCancerGene
? site1HugoSymbol
: site2HugoSymbol;
}
value = {
hugoGeneSymbol,
oncoKbStatus,
oncoKbIndicator,
oncoKbGeneExist,
isOncoKbCancerGene,
usingPublicOncoKbInstance:
usingPublicOncoKbInstance === undefined
? USE_DEFAULT_PUBLIC_INSTANCE_FOR_ONCOKB
: usingPublicOncoKbInstance,
civicEntry: undefined,
civicStatus: 'complete',
hasCivicVariants: false,
myCancerGenomeLinks: [],
hotspotStatus: 'complete',
isHotspot: false,
is3dHotspot: false,
oncoKbAvailableDataTypes,
};
} else {
value = DEFAULT_ANNOTATION_DATA;
}
return value;
}
public static getIndicatorData(
structuralVariantData: StructuralVariant[],
oncoKbData: IOncoKbData,
uniqueSampleKeyToTumorType?: { [sampleId: string]: string },
studyIdToStudy?: { [studyId: string]: CancerStudy }
): IndicatorQueryResp | undefined {
if (
uniqueSampleKeyToTumorType === null ||
oncoKbData.indicatorMap === null
) {
return undefined;
}
const id = generateQueryStructuralVariantId(
structuralVariantData[0].site1EntrezGeneId,
structuralVariantData[0].site2EntrezGeneId,
uniqueSampleKeyToTumorType![
structuralVariantData[0].uniqueSampleKey
],
structuralVariantData[0].variantClass.toUpperCase() as any
);
if (oncoKbData.indicatorMap[id]) {
let indicator = oncoKbData.indicatorMap[id];
if (indicator.query.tumorType === null && studyIdToStudy) {
const studyMetaData =
studyIdToStudy[structuralVariantData[0].studyId];
if (studyMetaData.cancerTypeId !== 'mixed') {
indicator.query.tumorType = studyMetaData.cancerType.name;
}
}
return indicator;
} else {
return undefined;
}
}
public static sortValue(
data: StructuralVariant[],
oncoKbCancerGenes?: RemoteData<CancerGene[] | Error | undefined>,
usingPublicOncoKbInstance?: boolean,
oncoKbData?: RemoteData<IOncoKbData | Error | undefined>,
uniqueSampleKeyToTumorType?: { [sampleId: string]: string }
): number[] {
const annotationData: IAnnotation = this.getData(
data,
oncoKbCancerGenes,
oncoKbData,
usingPublicOncoKbInstance,
uniqueSampleKeyToTumorType
);
return _.flatten([
oncoKbAnnotationSortValue(annotationData.oncoKbIndicator),
civicSortValue(annotationData.civicEntry),
annotationData.isOncoKbCancerGene ? 1 : 0,
]);
}
public static headerRender(
name: string,
width: number,
mergeOncoKbIcons?: boolean,
onOncoKbIconToggle?: (mergeIcons: boolean) => void
) {
return (
<AnnotationHeader
name={name}
width={width}
mergeOncoKbIcons={mergeOncoKbIcons}
onOncoKbIconToggle={onOncoKbIconToggle}
/>
);
}
public static renderFunction(
data: StructuralVariant[],
columnProps: IAnnotationColumnProps
) {
const annotation: IAnnotation = this.getData(
data,
columnProps.oncoKbCancerGenes,
columnProps.oncoKbData,
columnProps.usingPublicOncoKbInstance,
columnProps.uniqueSampleKeyToTumorType,
columnProps.studyIdToStudy
);
return <GenericAnnotation {...columnProps} annotation={annotation} />;
}
}
|
agpl-3.0
|
ontohub/ontohub-backend
|
spec/graphql/queries/repository/tag_query_spec.rb
|
1684
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'repository/tag query' do
let(:context) { {} }
let(:query_string) do
<<-QUERY
query ($repositoryId: ID!, $name: String!) {
repository(id: $repositoryId) {
tag(name: $name) {
name
target {
id
}
annotation
}
}
}
QUERY
end
let(:repository) do
create(:repository_compound, :not_empty,
public_access: false,
owner: current_user)
end
let(:git) { repository.git }
let!(:tag) { create(:tag, repository: repository, message: message) }
let(:current_user) { create(:user) }
let(:variables_base) { {'repositoryId' => repository.to_param} }
let(:variables_existent) { variables_base.merge('name' => tag.name) }
let(:variables_not_existent) { variables_base.merge('name' => 'bad') }
let(:expectation_signed_in_existent) do
tag_data = {
'name' => tag.name,
'annotation' => message,
'target' => {'id' => git.commit(tag.target).id},
}
match('data' => {'repository' => {'tag' => tag_data}})
end
let(:expectation_signed_in_not_existent) do
match('data' => {'repository' => {'tag' => nil}})
end
let(:expectation_not_signed_in_existent) do
match('data' => {'repository' => nil})
end
let(:expectation_not_signed_in_not_existent) do
expectation_not_signed_in_existent
end
context 'with annotation' do
let(:message) { 'message' }
it_behaves_like 'a GraphQL query', %w(repository tag)
end
context 'without annotation' do
let(:message) { nil }
it_behaves_like 'a GraphQL query', %w(repository tag)
end
end
|
agpl-3.0
|
teleiakaipavla/diafthoratelos.gr
|
php/wordpress/qa/qa-include/qa-ajax-version.php
|
2412
|
<?php
/*
Question2Answer (c) Gideon Greenspan
http://www.question2answer.org/
File: qa-include/qa-ajax-version.php
Version: See define()s at top of qa-include/qa-base.php
Description: Server-side response to Ajax version check requests
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
More about this license: http://www.question2answer.org/license.php
*/
require_once QA_INCLUDE_DIR.'qa-app-admin.php';
$uri=qa_post_text('uri');
$versionkey=qa_post_text('versionkey');
$urikey=qa_post_text('urikey');
$version=qa_post_text('version');
$metadata=qa_admin_addon_metadata(qa_retrieve_url($uri), array(
'version' => $versionkey,
'uri' => $urikey,
// these two elements are only present for plugins, not themes, so we can hard code them here
'min_q2a' => 'Plugin Minimum Question2Answer Version',
'min_php' => 'Plugin Minimum PHP Version',
));
if (strlen(@$metadata['version'])) {
if (strcmp($metadata['version'], $version)) {
if (qa_qa_version_below(@$metadata['min_q2a']))
$response=strtr(qa_lang_html('admin/version_requires_q2a'), array(
'^1' => qa_html('v'.$metadata['version']),
'^2' => qa_html($metadata['min_q2a']),
));
elseif (qa_php_version_below(@$metadata['min_php']))
$response=strtr(qa_lang_html('admin/version_requires_php'), array(
'^1' => qa_html('v'.$metadata['version']),
'^2' => qa_html($metadata['min_php']),
));
else {
$response=qa_lang_html_sub('admin/version_get_x', qa_html('v'.$metadata['version']));
if (strlen(@$metadata['uri']))
$response='<A HREF="'.qa_html($metadata['uri']).'" STYLE="color:#d00;">'.$response.'</A>';
}
} else
$response=qa_lang_html('admin/version_latest');
} else
$response=qa_lang_html('admin/version_latest_unknown');
echo "QA_AJAX_RESPONSE\n1\n".$response;
/*
Omit PHP closing tag to help avoid accidental output
*/
|
agpl-3.0
|
xujb/odoo
|
doc/_extensions/odoo/translator.py
|
26143
|
# -*- coding: utf-8 -*-
import os.path
import posixpath
import re
import urllib
from docutils import nodes
from sphinx import addnodes, util
from sphinx.locale import admonitionlabels
def _parents(node):
while node.parent:
node = node.parent
yield node
class BootstrapTranslator(nodes.NodeVisitor, object):
head_prefix = 'head_prefix'
head = 'head'
stylesheet = 'stylesheet'
body_prefix = 'body_prefix'
body_pre_docinfo = 'body_pre_docinfo'
docinfo = 'docinfo'
body_suffix = 'body_suffix'
subtitle = 'subtitle'
header = 'header'
footer = 'footer'
html_prolog = 'html_prolog'
html_head = 'html_head'
html_title = 'html_title'
html_subtitle = 'html_subtitle'
# <meta> tags
meta = [
'<meta http-equiv="X-UA-Compatible" content="IE=edge">',
'<meta name="viewport" content="width=device-width, initial-scale=1">'
]
def __init__(self, builder, document):
super(BootstrapTranslator, self).__init__(document)
self.builder = builder
self.body = []
self.fragment = self.body
self.html_body = self.body
# document title
self.title = []
self.start_document_title = 0
self.first_title = False
self.context = []
self.section_level = 0
self.highlightlang = self.highlightlang_base = self.builder.config.highlight_language
self.highlightopts = getattr(builder.config, 'highlight_options', {})
self.first_param = 1
self.optional_param_level = 0
self.required_params_left = 0
self.param_separator = ','
def encode(self, text):
return unicode(text).translate({
ord('&'): u'&',
ord('<'): u'<',
ord('"'): u'"',
ord('>'): u'>',
0xa0: u' '
})
def starttag(self, node, tagname, **attributes):
tagname = unicode(tagname).lower()
# extract generic attributes
attrs = {name.lower(): value for name, value in attributes.iteritems()}
attrs.update(
(name, value) for name, value in node.attributes.iteritems()
if name.startswith('data-')
)
prefix = []
postfix = []
# handle possibly multiple ids
assert 'id' not in attrs, "starttag can't be passed a single id attribute, use a list of ids"
ids = node.get('ids', []) + attrs.pop('ids', [])
if ids:
_ids = iter(ids)
attrs['id'] = next(_ids)
postfix.extend(u'<i id="{}"></i>'.format(_id) for _id in _ids)
# set CSS class
classes = set(node.get('classes', []) + attrs.pop('class', '').split())
if classes:
attrs['class'] = u' '.join(classes)
return u'{prefix}<{tag} {attrs}>{postfix}'.format(
prefix=u''.join(prefix),
tag=tagname,
attrs=u' '.join(u'{}="{}"'.format(name, self.attval(value))
for name, value in attrs.iteritems()),
postfix=u''.join(postfix),
)
# only "space characters" SPACE, CHARACTER TABULATION, LINE FEED,
# FORM FEED and CARRIAGE RETURN should be collapsed, not al White_Space
def attval(self, value, whitespace=re.compile(u'[ \t\n\f\r]')):
return self.encode(whitespace.sub(u' ', unicode(value)))
def astext(self):
return u''.join(self.body)
def unknown_visit(self, node):
print "unknown node", node.__class__.__name__
self.body.append(u'[UNKNOWN NODE {}]'.format(node.__class__.__name__))
raise nodes.SkipNode
def visit_highlightlang(self, node):
self.highlightlang = node['lang']
def depart_highlightlang(self, node):
pass
def visit_document(self, node):
self.first_title = True
def depart_document(self, node):
pass
def visit_section(self, node):
# close "parent" or preceding section, unless this is the opening of
# the first section
if self.section_level:
self.body.append(u'</section>')
self.section_level += 1
self.body.append(self.starttag(node, 'section'))
def depart_section(self, node):
self.section_level -= 1
# close last section of document
if not self.section_level:
self.body.append(u'</section>')
def is_compact_paragraph(self, node):
parent = node.parent
if isinstance(parent, (nodes.document, nodes.compound,
addnodes.desc_content,
addnodes.versionmodified)):
# Never compact paragraphs in document or compound.
return False
for key, value in node.attlist():
# we can ignore a few specific classes, all other non-default
# attributes require that a <p> node remains
if key != 'classes' or value not in ([], ['first'], ['last'], ['first', 'last']):
return False
first = isinstance(node.parent[0], nodes.label)
for child in parent.children[first:]:
# only first paragraph can be compact
if isinstance(child, nodes.Invisible):
continue
if child is node:
break
return False
parent_length = len([
1 for n in parent
if not isinstance(n, (nodes.Invisible, nodes.label))
])
return parent_length == 1
def visit_paragraph(self, node):
if self.is_compact_paragraph(node):
self.context.append(u'')
return
self.body.append(self.starttag(node, 'p'))
self.context.append(u'</p>')
def depart_paragraph(self, node):
self.body.append(self.context.pop())
def visit_compact_paragraph(self, node):
pass
def depart_compact_paragraph(self, node):
pass
def visit_literal_block(self, node):
if node.rawsource != node.astext():
# most probably a parsed-literal block -- don't highlight
self.body.append(self.starttag(node, 'pre'))
return
lang = self.highlightlang
highlight_args = node.get('highlight_args', {})
if 'language' in node:
# code-block directives
lang = node['language']
highlight_args['force'] = True
linenos = node.get('linenos', False)
if lang is self.highlightlang_base:
# only pass highlighter options for original language
opts = self.highlightopts
else:
opts = {}
def warner(msg):
self.builder.warn(msg, (self.builder.current_docname, node.line))
highlighted = self.builder.highlighter.highlight_block(
node.rawsource, lang, opts=opts, warn=warner, linenos=linenos,
**highlight_args)
self.body.append(self.starttag(node, 'div', CLASS='highlight-%s' % lang))
self.body.append(highlighted)
self.body.append(u'</div>\n')
raise nodes.SkipNode
def depart_literal_block(self, node):
self.body.append(u'</pre>')
def visit_bullet_list(self, node):
self.body.append(self.starttag(node, 'ul'))
def depart_bullet_list(self, node):
self.body.append(u'</ul>')
def visit_enumerated_list(self, node):
self.body.append(self.starttag(node, 'ol'))
def depart_enumerated_list(self, node):
self.body.append(u'</ol>')
def visit_list_item(self, node):
self.body.append(self.starttag(node, 'li'))
def depart_list_item(self, node):
self.body.append(u'</li>')
def visit_definition_list(self, node):
self.body.append(self.starttag(node, 'dl'))
def depart_definition_list(self, node):
self.body.append(u'</dl>')
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_term(self, node):
self.body.append(self.starttag(node, 'dt'))
def depart_term(self, node):
self.body.append(u'</dt>')
def visit_termsep(self, node):
self.body.append(self.starttag(node, 'br'))
raise nodes.SkipNode
def visit_definition(self, node):
self.body.append(self.starttag(node, 'dd'))
def depart_definition(self, node):
self.body.append(u'</dd>')
def visit_admonition(self, node, type=None):
clss = {
# ???: 'alert-success',
'note': 'alert-info',
'hint': 'alert-info',
'tip': 'alert-info',
'seealso': 'alert-info',
'warning': 'alert-warning',
'attention': 'alert-warning',
'caution': 'alert-warning',
'important': 'alert-warning',
'danger': 'alert-danger',
'error': 'alert-danger',
'exercise': 'alert-exercise',
}
self.body.append(self.starttag(node, 'div', role='alert', CLASS='alert {}'.format(
clss.get(type, '')
)))
if 'alert-dismissible' in node.get('classes', []):
self.body.append(
u'<button type="button" class="close" data-dismiss="alert" aria-label="Close">'
u'<span aria-hidden="true">×</span>'
u'</button>')
if type:
node.insert(0, nodes.title(type, admonitionlabels[type]))
def depart_admonition(self, node):
self.body.append(u'</div>')
visit_note = lambda self, node: self.visit_admonition(node, 'note')
visit_warning = lambda self, node: self.visit_admonition(node, 'warning')
visit_attention = lambda self, node: self.visit_admonition(node, 'attention')
visit_caution = lambda self, node: self.visit_admonition(node, 'caution')
visit_danger = lambda self, node: self.visit_admonition(node, 'danger')
visit_error = lambda self, node: self.visit_admonition(node, 'error')
visit_hint = lambda self, node: self.visit_admonition(node, 'hint')
visit_important = lambda self, node: self.visit_admonition(node, 'important')
visit_tip = lambda self, node: self.visit_admonition(node, 'tip')
visit_exercise = lambda self, node: self.visit_admonition(node, 'exercise')
visit_seealso = lambda self, node: self.visit_admonition(node, 'seealso')
depart_note = depart_admonition
depart_warning = depart_admonition
depart_attention = depart_admonition
depart_caution = depart_admonition
depart_danger = depart_admonition
depart_error = depart_admonition
depart_hint = depart_admonition
depart_important = depart_admonition
depart_tip = depart_admonition
depart_exercise = depart_admonition
depart_seealso = depart_admonition
def visit_versionmodified(self, node):
self.body.append(self.starttag(node, 'div', CLASS=node['type']))
def depart_versionmodified(self, node):
self.body.append(u'</div>')
def visit_title(self, node):
parent = node.parent
closing = u'</p>'
if isinstance(parent, nodes.Admonition):
self.body.append(self.starttag(node, 'p', CLASS='alert-title'))
elif isinstance(node.parent, nodes.document):
self.body.append(self.starttag(node, 'h1'))
closing = u'</h1>'
self.start_document_title = len(self.body)
else:
assert isinstance(parent, nodes.section), "expected a section node as parent to the title, found {}".format(parent)
if self.first_title:
self.first_title = False
raise nodes.SkipNode()
nodename = 'h{}'.format(self.section_level)
self.body.append(self.starttag(node, nodename))
closing = u'</{}>'.format(nodename)
self.context.append(closing)
def depart_title(self, node):
self.body.append(self.context.pop())
if self.start_document_title:
self.title = self.body[self.start_document_title:-1]
self.start_document_title = 0
del self.body[:]
# the rubric should be a smaller heading than the current section, up to
# h6... maybe "h7" should be a ``p`` instead?
def visit_rubric(self, node):
self.body.append(self.starttag(node, 'h{}'.format(min(self.section_level + 1, 6))))
def depart_rubric(self, node):
self.body.append(u'</h{}>'.format(min(self.section_level + 1, 6)))
def visit_block_quote(self, node):
self.body.append(self.starttag(node, 'blockquote'))
def depart_block_quote(self, node):
self.body.append(u'</blockquote>')
def visit_attribution(self, node):
self.body.append(self.starttag(node, 'footer'))
def depart_attribution(self, node):
self.body.append(u'</footer>')
def visit_container(self, node):
self.body.append(self.starttag(node, 'div'))
def depart_container(self, node):
self.body.append(u'</div>')
def visit_compound(self, node):
self.body.append(self.starttag(node, 'div'))
def depart_compound(self, node):
self.body.append(u'</div>')
def visit_image(self, node):
uri = node['uri']
if uri in self.builder.images:
uri = posixpath.join(self.builder.imgpath,
self.builder.images[uri])
attrs = {'src': uri, 'class': 'img-responsive'}
if 'alt' in node:
attrs['alt'] = node['alt']
# todo: explicit width/height/scale?
self.body.append(self.starttag(node, 'img', **attrs))
def depart_image(self, node): pass
def visit_figure(self, node):
self.body.append(self.starttag(node, 'div'))
def depart_figure(self, node):
self.body.append(u'</div>')
def visit_caption(self, node):
# first paragraph of figure content
self.body.append(self.starttag(node, 'h4'))
def depart_caption(self, node):
self.body.append(u'</h4>')
def visit_legend(self, node): pass
def depart_legend(self, node): pass
def visit_line(self, node):
self.body.append(self.starttag(node, 'div', CLASS='line'))
# ensure the line still takes the room it needs
if not len(node): self.body.append(u'<br />')
def depart_line(self, node):
self.body.append(u'</div>')
def visit_line_block(self, node):
self.body.append(self.starttag(node, 'div', CLASS='line-block'))
def depart_line_block(self, node):
self.body.append(u'</div>')
def visit_table(self, node):
self.body.append(self.starttag(node, 'table', CLASS='table'))
def depart_table(self, node):
self.body.append(u'</table>')
def visit_tgroup(self, node): pass
def depart_tgroup(self, node): pass
def visit_colspec(self, node): raise nodes.SkipNode
def visit_thead(self, node):
self.body.append(self.starttag(node, 'thead'))
def depart_thead(self, node):
self.body.append(u'</thead>')
def visit_tbody(self, node):
self.body.append(self.starttag(node, 'tbody'))
def depart_tbody(self, node):
self.body.append(u'</tbody>')
def visit_row(self, node):
self.body.append(self.starttag(node, 'tr'))
def depart_row(self, node):
self.body.append(u'</tr>')
def visit_entry(self, node):
if isinstance(node.parent.parent, nodes.thead):
tagname = 'th'
else:
tagname = 'td'
self.body.append(self.starttag(node, tagname))
self.context.append(tagname)
def depart_entry(self, node):
self.body.append(u'</{}>'.format(self.context.pop()))
def visit_Text(self, node):
self.body.append(self.encode(node.astext()))
def depart_Text(self, node):
pass
def visit_literal(self, node):
self.body.append(self.starttag(node, 'code'))
def depart_literal(self, node):
self.body.append(u'</code>')
visit_literal_emphasis = visit_literal
depart_literal_emphasis = depart_literal
def visit_emphasis(self, node):
self.body.append(self.starttag(node, 'em'))
def depart_emphasis(self, node):
self.body.append(u'</em>')
def visit_strong(self, node):
self.body.append(self.starttag(node, 'strong'))
def depart_strong(self, node):
self.body.append(u'</strong>')
visit_literal_strong = visit_strong
depart_literal_strong = depart_strong
def visit_inline(self, node):
self.body.append(self.starttag(node, 'span'))
def depart_inline(self, node):
self.body.append(u'</span>')
def visit_abbreviation(self, node):
attrs = {}
if 'explanation' in node:
attrs['title'] = node['explanation']
self.body.append(self.starttag(node, 'abbr', **attrs))
def depart_abbreviation(self, node):
self.body.append(u'</abbr>')
def visit_reference(self, node):
attrs = {
'class': 'reference',
'href': node['refuri'] if 'refuri' in node else '#' + node['refid']
}
attrs['class'] += ' internal' if (node.get('internal') or 'refuri' not in node) else ' external'
if any(isinstance(ancestor, nodes.Admonition) for ancestor in _parents(node)):
attrs['class'] += ' alert-link'
if 'reftitle' in node:
attrs['title'] = node['reftitle']
self.body.append(self.starttag(node, 'a', **attrs))
def depart_reference(self, node):
self.body.append(u'</a>')
def visit_target(self, node): pass
def depart_target(self, node): pass
def visit_footnote(self, node):
self.body.append(self.starttag(node, 'div', CLASS='footnote'))
self.footnote_backrefs(node)
def depart_footnote(self, node):
self.body.append(u'</div>')
def visit_footnote_reference(self, node):
self.body.append(self.starttag(
node, 'a', href='#' + node['refid'], CLASS="footnote-ref"))
def depart_footnote_reference(self, node):
self.body.append(u'</a>')
def visit_label(self, node):
self.body.append(self.starttag(node, 'span', CLASS='footnote-label'))
self.body.append(u'%s[' % self.context.pop())
def depart_label(self, node):
# Context added in footnote_backrefs.
self.body.append(u']%s</span> %s' % (self.context.pop(), self.context.pop()))
def footnote_backrefs(self, node):
# should store following data on context stack (in that order since
# they'll be popped so LIFO)
#
# * outside (after) label
# * after label text
# * before label text
backrefs = node['backrefs']
if not backrefs:
self.context.extend(['', '', ''])
elif len(backrefs) == 1:
self.context.extend([
'',
'</a>',
'<a class="footnote-backref" href="#%s">' % backrefs[0]
])
else:
backlinks = (
'<a class="footnote-backref" href="#%s">%s</a>' % (backref, i)
for i, backref in enumerate(backrefs, start=1)
)
self.context.extend([
'<em class="footnote-backrefs">(%s)</em> ' % ', '.join(backlinks),
'',
''
])
def visit_desc(self, node):
self.body.append(self.starttag(node, 'section', CLASS='code-' + node['objtype']))
def depart_desc(self, node):
self.body.append(u'</section>')
def visit_desc_signature(self, node):
self.body.append(self.starttag(node, 'h6'))
self.body.append(u'<code>')
def depart_desc_signature(self, node):
self.body.append(u'</code>')
self.body.append(u'</h6>')
def visit_desc_addname(self, node): pass
def depart_desc_addname(self, node): pass
def visit_desc_type(self, node): pass
def depart_desc_type(self, node): pass
def visit_desc_returns(self, node):
self.body.append(u' → ')
def depart_desc_returns(self, node):
pass
def visit_desc_name(self, node): pass
def depart_desc_name(self, node): pass
def visit_desc_parameterlist(self, node):
self.body.append(u'(')
self.first_param = True
self.optional_param_level = 0
# How many required parameters are left.
self.required_params_left = sum(isinstance(c, addnodes.desc_parameter) for c in node.children)
self.param_separator = node.child_text_separator
def depart_desc_parameterlist(self, node):
self.body.append(u')')
# If required parameters are still to come, then put the comma after
# the parameter. Otherwise, put the comma before. This ensures that
# signatures like the following render correctly (see issue #1001):
#
# foo([a, ]b, c[, d])
#
def visit_desc_parameter(self, node):
if self.first_param:
self.first_param = 0
elif not self.required_params_left:
self.body.append(self.param_separator)
if self.optional_param_level == 0:
self.required_params_left -= 1
if 'noemph' not in node: self.body.append(u'<em>')
def depart_desc_parameter(self, node):
if 'noemph' not in node: self.body.append(u'</em>')
if self.required_params_left:
self.body.append(self.param_separator)
def visit_desc_optional(self, node):
self.optional_param_level += 1
self.body.append(u'[')
def depart_desc_optional(self, node):
self.optional_param_level -= 1
self.body.append(u']')
def visit_desc_annotation(self, node):
self.body.append(self.starttag(node, 'em'))
def depart_desc_annotation(self, node):
self.body.append(u'</em>')
def visit_desc_content(self, node): pass
def depart_desc_content(self, node): pass
def visit_field_list(self, node):
self.body.append(self.starttag(node, 'div', CLASS='code-fields'))
def depart_field_list(self, node):
self.body.append(u'</div>')
def visit_field(self, node):
self.body.append(self.starttag(node, 'div', CLASS='code-field'))
def depart_field(self, node):
self.body.append(u'</div>')
def visit_field_name(self, node):
self.body.append(self.starttag(node, 'div', CLASS='code-field-name'))
def depart_field_name(self, node):
self.body.append(u'</div>')
def visit_field_body(self, node):
self.body.append(self.starttag(node, 'div', CLASS='code-field-body'))
def depart_field_body(self, node):
self.body.append(u'</div>')
def visit_glossary(self, node): pass
def depart_glossary(self, node): pass
def visit_comment(self, node): raise nodes.SkipNode
def visit_toctree(self, node):
# div class=row {{ section_type }}
# h2 class=col-sm-12
# {{ section title }}
# div class=col-sm-6 col-md-3
# figure class=card
# a href=current_link style=background-image: document-image-attribute class=card-img
# figcaption
# {{ card title }}
env = self.builder.env
conf = self.builder.app.config
for title, ref in ((e[0], e[1]) for e in node['entries']):
# external URL, no toc, can't recurse into
if ref not in env.tocs:
continue
toc = env.tocs[ref].traverse(addnodes.toctree)
classes = env.metadata[ref].get('types', 'tutorials')
classes += ' toc-single-entry' if not toc else ' toc-section'
self.body.append(self.starttag(node, 'div', CLASS="row " + classes))
self.body.append(u'<h2 class="col-sm-12">')
self.body.append(title if title else util.nodes.clean_astext(env.titles[ref]))
self.body.append(u'</h2>')
entries = [(title, ref)] if not toc else ((e[0], e[1]) for e in toc[0]['entries'])
for subtitle, subref in entries:
baseuri = self.builder.get_target_uri(node['parent'])
if subref in env.metadata:
cover = env.metadata[subref].get('banner', conf.odoo_cover_default)
elif subref in conf.odoo_cover_external:
cover = conf.odoo_cover_external[subref]
else:
cover = conf.odoo_cover_default_external
if cover:
banner = '_static/' + cover
base, ext = os.path.splitext(banner)
small = "{}.small{}".format(base, ext)
if os.path.isfile(urllib.url2pathname(small)):
banner = small
style = u"background-image: url('{}')".format(
util.relative_uri(baseuri, banner) or '#')
else:
style = u''
self.body.append(u"""
<div class="col-sm-6 col-md-3">
<figure class="card">
<a href="{link}" class="card-img">
<span style="{style}"></span>
<figcaption>{title}</figcaption>
</a>
</figure>
</div>
""".format(
link=subref if util.url_re.match(subref) else util.relative_uri(
baseuri, self.builder.get_target_uri(subref)),
style=style,
title=subtitle if subtitle else util.nodes.clean_astext(env.titles[subref]),
))
self.body.append(u'</div>')
raise nodes.SkipNode
def visit_index(self, node): raise nodes.SkipNode
def visit_raw(self, node):
if 'html' in node.get('format', '').split():
t = 'span' if isinstance(node.parent, nodes.TextElement) else 'div'
if node['classes']:
self.body.append(self.starttag(node, t))
self.body.append(node.astext())
if node['classes']:
self.body.append('</%s>' % t)
# Keep non-HTML raw text out of output:
raise nodes.SkipNode
|
agpl-3.0
|
akretion/roulier
|
roulier/carriers/laposte_fr/decoder.py
|
4729
|
"""Laposte XML -> Python."""
from datetime import datetime
from lxml import objectify
from ...codec import DecoderGetLabel
from ...codec import DecoderGetPackingSlip
import base64
class _UNSPECIFIED:
pass
def _get_text(xml, tag, default=_UNSPECIFIED):
"""
Returns the text content of a tag to avoid returning an lxml instance
If no default is specified, it will raises the original exception of accessing
to an inexistant tag
"""
if not hasattr(xml, tag):
if default is _UNSPECIFIED:
# raise classic attr error
return getattr(xml, tag)
return default
return getattr(xml, tag).text
def _get_cid(tag, tree):
element = tree.find(tag)
if element is None:
return None
href = element.getchildren()[0].attrib["href"]
# href contains cid:236212...-38932@cfx.apache.org
return href[len("cid:") :] # remove prefix
class LaposteFrDecoderGetLabel(DecoderGetLabel):
"""Laposte XML -> Python."""
def decode(self, response, input_payload):
"""Laposte XML -> Python."""
body = response["body"]
parts = response["parts"]
output_format = input_payload["output_format"]
xml = objectify.fromstring(body)
msg = xml.xpath("//return")[0]
rep = msg.labelV2Response
cn23_cid = _get_cid("cn23", rep)
label_cid = _get_cid("label", rep)
annexes = []
if cn23_cid:
data = parts.get(cn23_cid)
annexes.append(
{"name": "cn23", "data": base64.b64encode(data), "type": "pdf"}
)
if rep.find("pdfUrl"):
annexes.append({"name": "label", "data": rep.find("pdfUrl"), "type": "url"})
parcel = {
"id": 1, # no multi parcel management for now.
"reference": self._get_parcel_number(input_payload),
"tracking": {
# we need to force to real string because of those data can be reused
# and cerberus won't accept an ElementString insteadof a string.
"number": _get_text(rep, "parcelNumber"),
"url": "",
"partner": _get_text(rep, "parcelNumberPartner", ""),
},
"label": {
"data": base64.b64encode(parts.get(label_cid)),
"name": "label_1",
"type": output_format,
},
}
if hasattr(rep, "fields") and hasattr(rep.fields, "field"):
for field in rep.fields.field:
parcel["tracking"][_get_text(field, "key")] = _get_text(field, "value")
self.result["parcels"].append(parcel)
self.result["annexes"] += annexes
class LaposteFrDecoderGetPackingSlip(DecoderGetPackingSlip):
"""Laposte Bordereau Response XML -> Python."""
def decode(self, response, input_payload):
body = response["body"]
parts = response["parts"]
xml = objectify.fromstring(body)
msg = xml.xpath("//return")[0]
header = msg.bordereau.bordereauHeader
published_dt = _get_text(header, "publishingDate", None)
if published_dt:
if "." in published_dt:
# get packing slip with it's number does not return microseconds
# but when creating a new one, it does... We remove microseconds in result
# to have a better homogeneity
published_dt = published_dt.split(".")
published_dt = "%s+%s" % (
published_dt[0],
published_dt[1].split("+")[1],
)
published_datetime = datetime.strptime(published_dt, "%Y-%m-%dT%H:%M:%S%z")
self.result["packing_slip"] = {
"number": _get_text(header, "bordereauNumber", None),
"published_datetime": published_datetime,
"number_of_parcels": int(_get_text(header, "numberOfParcels", 0)),
"site_pch": {
"code": _get_text(header, "codeSitePCH", None),
"name": _get_text(header, "nameSitePCH", None),
},
"client": {
"number": _get_text(header, "clientNumber", None),
"adress": _get_text(header, "Address", None),
"company": _get_text(header, "Company", None),
},
}
packing_slip_cid = _get_cid("bordereauDataHandler", msg.bordereau)
if packing_slip_cid:
self.result["annexes"].append(
{
"name": "packing_slip",
"data": base64.b64encode(parts.get(packing_slip_cid)),
"type": "pdf",
}
)
return self.result
|
agpl-3.0
|
mattcen/alloc
|
bin/alloccli/reminder.py
|
3917
|
"""alloccli subcommand for editing alloc reminders."""
from alloc import alloc
import re
class reminder(alloc):
"""Add or edit a reminder."""
# Setup the options that this cli can accept
ops = []
ops.append(('', 'help ', 'Show this help.'))
ops.append(('q', 'quiet ', 'Run with less output.\n'))
ops.append(('r.', ' ', 'Edit a reminder. Specify an ID or omit -r to create.'))
ops.append(('t.', 'task=ID|NAME ', 'A task ID, or a fuzzy match for a task name.'))
ops.append(('p.', 'project=ID|NAME', 'A project ID, or a fuzzy match for a project name.'))
ops.append(('c.', 'client=ID|NAME ', 'A client ID, or a fuzzy match for a client name.'))
ops.append(('s.', 'subject=TEXT ', 'The subject line of the reminder.'))
ops.append(('b.', 'body=TEXT ', 'The text body of the reminder.'))
ops.append(('', 'frequency=FREQ ', 'How often this reminder is to recur.\n'
'Specify as [number][unit], where unit is one of:\n'
'[h]our, [d]ay, [w]eek, [m]onth, [y]ear.'))
ops.append(('', 'notice=WARNING ', 'Advance warning for this reminder. Same format as frequency.'))
ops.append(('d.', 'date=DATE ', 'When this reminder is to trigger.'))
ops.append(('', 'active=1|0 ', 'Whether this reminder is active or not.'))
ops.append(('T:', 'to=PEOPLE ', 'Recipients. Can be usernames, full names and/or email.'))
ops.append(('D:', 'remove=PEOPLE ', 'Recipients to remove.'))
# Specify some header and footer text for the help text
help_text = "Usage: %s [OPTIONS]\n"
help_text += __doc__
help_text += """\n\n%s
This program allows editing of the fields on a reminder.
Examples:
# Edit a particular reminder.
alloc reminder -r 1234 --title 'Name for the reminder.' --to alla
# Omit -r to create a new reminder
alloc reminder --title 'Name for the reminder.' --to alla"""
def run(self, command_list):
"""Execute subcommand."""
# Get the command line arguments into a dictionary
o, remainder_ = self.get_args(command_list, self.ops, self.help_text)
# Got this far, then authenticate
self.authenticate()
personID = self.get_my_personID()
args = {}
if not o['r']:
o['r'] = 'new'
args['entity'] = 'reminder'
args['id'] = o['r']
if o['date']:
o['date'] = self.parse_date(o['date'])
if o['project'] and not self.is_num(o['project']):
o['project'] = self.search_for_project(o['project'], personID)
if o['task'] and not self.is_num(o['task']):
o['task'] = self.search_for_task({'taskName': o['task']})
if o['client'] and not self.is_num(o['client']):
o['client'] = self.search_for_client({'clientName': o['client']})
if o['frequency'] and not re.match(r'\d+[hdwmy]', o['frequency'], re.IGNORECASE):
self.die("Invalid frequency specification")
if o['notice'] and not re.match(r'\d+[hdwmy]', o['notice'], re.IGNORECASE):
self.die("Invalid advance notice specification")
if o['to']:
o['recipients'] = [x['personID']
for x in self.get_people(o['to']).values()]
if o['remove']:
o['recipients_remove'] = [x['personID']
for x in self.get_people(o['remove']).values()]
package = {}
for key, val in o.items():
if val:
package[key] = val
if isinstance(val, str) and val.lower() == 'null':
package[key] = ''
package['command'] = 'edit_reminder'
args['options'] = package
args['method'] = 'edit_entity'
rtn = self.make_request(args)
self.handle_server_response(rtn, not o['quiet'])
|
agpl-3.0
|
ComPlat/chemotion_ELN
|
app/packs/src/components/SampleDetailsContainersDnd.js
|
2510
|
import React from 'react';
import { DragSource, DropTarget } from 'react-dnd';
import { compose } from 'redux';
import DragDropItemTypes from './DragDropItemTypes';
import { HeaderDeleted, HeaderNormal } from './SampleDetailsContainersAux';
const orderSource = {
beginDrag(props) {
const { container, sample } = props;
return { cId: container.id, sId: sample.id };
},
};
const orderTarget = {
drop(targetProps, monitor) {
const { container, sample, handleMove } = targetProps;
const tgTag = { cId: container.id, sId: sample.id };
const scTag = monitor.getItem();
if (tgTag.sId === scTag.sId && tgTag.cId !== scTag.cId) {
handleMove(scTag, tgTag);
}
},
};
const orderDragCollect = (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
});
const orderDropCollect = (connect, monitor) => ({
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop(),
});
const ContainerRow = ({
sample, container, mode, readOnly, isDisabled, handleRemove,
handleSubmit, handleAccordionOpen, toggleAddToReport, handleUndo,
connectDragSource, connectDropTarget, isDragging, isOver, canDrop,
}) => {
const style = {};
if (canDrop) {
style.borderStyle = 'dashed';
style.borderWidth = 2;
}
if (isOver) {
style.borderColor = '#337ab7';
}
if (isDragging) {
style.opacity = 0.2;
}
const oPanelCN = container.is_deleted ? "order-panel-delete" : "order-panel";
return compose(connectDragSource, connectDropTarget)(
<div className={oPanelCN} style={style}>
<div className="dnd-btn">
<span className="text-info fa fa-arrows" />
</div>
{
container.is_deleted
? <HeaderDeleted
container={container}
handleUndo={handleUndo}
mode={mode}
/>
: <HeaderNormal
sample={sample}
container={container}
mode={mode}
handleUndo={handleUndo}
readOnly={readOnly}
isDisabled={isDisabled}
handleRemove={handleRemove}
handleSubmit={handleSubmit}
handleAccordionOpen={handleAccordionOpen}
toggleAddToReport={toggleAddToReport}
/>
}
</div>,
);
};
export default compose(
DragSource(DragDropItemTypes.CONTAINER, orderSource, orderDragCollect),
DropTarget(DragDropItemTypes.CONTAINER, orderTarget, orderDropCollect),
)(ContainerRow);
|
agpl-3.0
|
whs-poodle/poodle
|
src/main/resources/templates/student/exerciseSearch.html
|
6478
|
<!--/*
Copyright 2015 Westfälische Hochschule
This file is part of Poodle.
Poodle is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Poodle is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Poodle. If not, see <http://www.gnu.org/licenses/>.
*/-->
<!--/* exercise search for students. Is only used by students when they want to
add exercises to one of their self study worksheets (StudentExerciseSearchController). */-->
<html
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layout">
<head th:with="includeMathJax=true,includeDataTables=true">
<title>[[#{title.addExercisesToWorksheet}]]</title>
<link rel="stylesheet" th:href="@{/css/exerciseSearch.css}" />
<script th:src="@{/js/tagFilter.js}"></script>
<script th:src="@{/js/exerciseSearchCommon.js}"></script>
<script th:src="@{/js/exerciseSearch.js}"></script>
</head>
<div layout:fragment="content">
<h2 >
<a th:href="@{/student/selfStudy/{id}(id=${courseTerm.id})}" th:title="#{backToSelfStudyWorksheet}">
<span class="glyphicon glyphicon-chevron-left green"></span>
</a>
<span th:with="courseNameEscaped=${#strings.escapeXml(courseTerm.course.name)}"
th:utext="#{addExercisesToWorksheetInCourse(${courseNameEscaped})}"></span>
</h2>
<form th:object="${searchCriteria}" method="get" class="margin-bottom">
<input type="hidden" name="search" value="1" />
<input type="hidden" name="courseTermId" th:value="${courseTerm.id}" />
<div id="criteriaWrapper">
<fieldset class="criterion">
<legend>[[#{courses}]]</legend>
<div th:each="course : ${courses}" class="checkbox">
<input type="checkbox" th:field="*{courses}" th:value="${course.id}" />
<label th:for="${#ids.prev('courses')}">[[${course.name}]]</label>
</div>
</fieldset>
<fieldset>
<legend>[[#{tags}]]</legend>
<label class="radio-inline">
<input type="radio" th:field="*{tagsAnd}" th:value="true" /> [[#{mustContainAllTags}]]
</label>
<label class="radio-inline">
<input type="radio" th:field="*{tagsAnd}" th:value="false" /> [[#{mustContainAnyTag}]]
</label>
<th:block th:include="fragments/tagFilter (tags=${distinctTags})" />
</fieldset>
<fieldset>
<legend>[[#{difficulty}]]</legend>
<label th:each="mode : ${difficultyModes}" class="radio-inline">
<input type="radio" th:field="*{difficultyMode}" th:value="${mode}" /> [[#{'difficultyMode.' + ${mode}}]]
</label>
<th:block th:include="fragments/ratingStars (
n=${searchCriteria.difficulty},
inputName='difficulty',
idSuffix='search')" />
</fieldset>
<fieldset>
<legend>[[#{text}]]</legend>
<input type="text" th:field="*{text}" class="form-control max-width-sm inline" />
<input type="checkbox" th:field="*{searchTitle}" />
<label class="checkbox-inline" th:for="${#ids.prev('searchTitle')}">
[[#{title}]]
</label>
<input type="checkbox" th:field="*{searchText}" />
<label class="checkbox-inline" th:for="${#ids.prev('searchText')}">
[[#{exerciseText}]]
</label>
</fieldset>
<fieldset>
<legend>[[#{order}]]</legend>
<select th:field="*{order}" class="form-control width-auto inline">
<option value="RANDOM">[[#{order.random}]]</option>
<option value="TITLE">[[#{order.title}]]</option>
<option value="TEXT">[[#{order.text}]]</option>
<option value="DATE">[[#{order.date}]]</option>
</select>
<div id="orderAscendingWrapper" class="inline">
<label class="radio-inline">
<input type="radio" th:field="*{orderAscending}" value="true" /> [[#{order.ascending}]]
</label>
<label class="radio-inline">
<input type="radio" th:field="*{orderAscending}" value="false" /> [[#{order.descending}]]
</label>
</div>
</fieldset>
<div class="checkbox margin-vertical">
<input type="checkbox" th:field="*{studentFilter.hideIfAlreadyCompleted}" />
<label th:for="${#ids.prev('studentFilter.hideIfAlreadyCompleted')}">
[[#{hideIfAlreadyCompleted}]]
</label>
</div>
<input type="hidden" th:value="${courseTerm.id}" />
</div>
<button type="submit" class="btn btn-success">
<span class="glyphicon glyphicon-search"></span> [[#{button.search}]]
</button>
</form>
<!--/* results */-->
<p th:if="${param.containsKey('search')} and ${#lists.isEmpty(exercises)}">
<strong>[[#{noExercisesFound}]]</strong>
</p>
<th:block th:unless="${#lists.isEmpty(exercises)}">
<table id="resultsTable" class="table table-hover table-striped">
<thead>
<tr>
<th data-sortable="false">[[#{title}]]</th>
<th data-sortable="false">[[#{tags}]]</th>
<th data-sortable="false"></th>
</tr>
</thead>
<tbody>
<tr th:each="exercise : ${exercises}" th:attr="data-exercise-id=${exercise.id}">
<td class="studentTitle">
<p class="studentExerciseTitle">
[[${exercise.title}]]
</p>
<div class="feedbackWrapper">
<!--/* feedbacks by other students. we only show these if enough students
have provided feedback because showing averages of one or two feedbacks
doesn't make much sense. */-->
<th:block th:include="fragments/exerciseFeedbackInfo(exercise=${exercise},show=${exercise.enoughFeedbackForStudents})" />
</div>
</td>
<td>
<ul class="commaSeparatedList">
<li th:each="tag : ${exercise.tags}">[[${tag.name}]]</li>
</ul>
</td>
<td>
<!--/* "add to worksheet" link */-->
<ul class="optionButtons">
<li>
<button
type="button"
class="addToSelfStudyWorksheetLink btn-link"
th:title="#{addExerciseToWorksheet}"
th:attr="
data-exercise-id=${exercise.id},
data-course-term-id=${courseTerm.id}">
<span class="glyphicon glyphicon-plus green"></span>
</button>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</th:block>
</div>
</html>
|
agpl-3.0
|
CiviCooP/no.maf.oppgavexml
|
CRM/Oppgavexml/LoadQueue.php
|
716
|
<?php
/**
* @author Jaap Jansma <jaap.jansma@civicoop.org>
* @license AGPL-3.0
*/
class CRM_Oppgavexml_LoadQueue {
const QUEUE_NAME = 'no.maf.oppgavexml.load.queue';
private $queue;
static $singleton;
/**
* @return CRM_Queuehowto_Helper
*/
public static function singleton() {
if (!self::$singleton) {
self::$singleton = new CRM_Oppgavexml_LoadQueue();
}
return self::$singleton;
}
private function __construct() {
$this->queue = CRM_Queue_Service::singleton()->create(array(
'type' => 'Sql',
'name' => self::QUEUE_NAME,
'reset' => true, //do not flush queue upon creation
));
}
public function getQueue() {
return $this->queue;
}
}
|
agpl-3.0
|
esthermm/odoo-addons
|
product_supplierinfo_import/wizard/import_price_files.py
|
6282
|
# -*- coding: utf-8 -*-
# (c) 2017 Daniel Campos - AvanzOSC
# (c) 2017 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import fields, models, api, exceptions, _
import base64
import cStringIO
import tempfile
import csv
class ImportPriceFile(models.TransientModel):
_name = 'import.price.file'
_description = 'Wizard for import price list file'
data = fields.Binary(string='File', required=True)
name = fields.Char(string='Filename', required=False)
delimeter = fields.Char(
string='Delimeter', default=',', help='Default delimeter is ","')
file_type = fields.Selection([('csv', 'CSV'),
('xls', 'XLS')], string='File type',
required=True, default='csv')
def _prepare_data_dict(self, data_dict):
return data_dict
def _import_csv(self, load_id, file_data, delimeter=';'):
""" Imports data from a CSV file in defined object.
@param load_id: Loading id
@param file_data: Input data to load
@param delimeter: CSV file data delimeter
@return: Imported file number
"""
file_line_obj = self.env['product.supplierinfo.load.line']
data = base64.b64decode(file_data)
file_input = cStringIO.StringIO(data)
file_input.seek(0)
reader_info = []
reader = csv.reader(file_input, delimiter=str(delimeter),
lineterminator='\r\n')
try:
reader_info.extend(reader)
except Exception:
raise exceptions.Warning(_("Not a valid file!"))
keys = reader_info[0]
counter = 0
if not isinstance(keys, list):
raise exceptions.Warning(_("Not a valid file!"))
del reader_info[0]
for i in range(len(reader_info)):
field = reader_info[i]
values = dict(zip(keys, field))
data_dict = self._prepare_data_dict(
{'supplier': values.get('Supplier', ''),
'code': values.get('ProductCode', ''),
'sequence': values.get('Sequence', 0),
'supplier_code': values.get('ProductSupplierCode', ''),
'info': values.get('ProductSupplierName', ''),
'delay': values.get('Delay', 0),
'price': values.get('Price', 0.00).replace(',', '.'),
'min_qty': values.get('MinQty', 0.00),
'fail': True,
'fail_reason': _('No processed'),
'file_load': load_id})
file_line_obj.create(data_dict)
counter += 1
return counter
def _import_xls(self, load_id, file_data):
""" Imports data from a XLS file in defined object.
@param load_id: Loading id
@param file_data: Input data to load
@return: Imported file number
"""
try:
import xlrd
except ImportError:
exceptions.Warning(_("xlrd python lib not installed"))
file_line_obj = self.env['product.supplierinfo.load.line']
file_1 = base64.decodestring(file_data)
(fileno, fp_name) = tempfile.mkstemp('.xls', 'openerp_')
openfile = open(fp_name, "w")
openfile.write(file_1)
openfile.seek(0)
book = xlrd.open_workbook(fp_name)
sheet = book.sheet_by_index(0)
values = {}
keys = sheet.row_values(0, 0, end_colx=sheet.ncols)
for counter in range(sheet.nrows - 1):
# grab the current row
rowValues = sheet.row_values(counter + 1, 0,
end_colx=sheet.ncols)
row_lst = []
for val in rowValues: # codification format control
if isinstance(val, unicode):
valor = val.encode('utf8')
row_lst.append(valor)
elif isinstance(val, float):
if float(val) % 1 == 0.0:
row_lst.append(
'{0:.5f}'.format(float(val)).split('.')[0])
else:
row_lst.append('{0:g}'.format(float(val)))
else:
row_lst.append(val)
row = map(lambda x: str(x), row_lst)
values = dict(zip(keys, row))
data_dict = self._prepare_data_dict(
{'supplier': values.get('Supplier', ''),
'code': values.get('ProductCode', ''),
'sequence': values.get('Sequence', 0),
'supplier_code': values.get('ProductSupplierCode', ''),
'info': values.get('ProductSupplierName', ''),
'delay': values.get('Delay', 0),
'price': values.get('Price', 0.00).replace(',', '.'),
'min_qty': values.get('MinQty', 0.00),
'fail': True,
'fail_reason': _('No processed'),
'file_load': load_id
})
file_line_obj.create(data_dict)
counter += 1
return counter
@api.multi
def action_import(self):
file_load_obj = self.env['product.supplierinfo.load']
if self.env.context.get('active_id', False):
load_id = self.env.context.get('active_id')
file_load = file_load_obj.browse(load_id)
for line in file_load.file_lines:
line.unlink()
for wiz in self:
if not wiz.data:
raise exceptions.Warning(_("You need to select a file!"))
date_hour = fields.datetime.now()
actual_date = fields.date.today()
filename = wiz.name
if wiz.file_type == 'csv':
counter = self._import_csv(load_id, wiz.data, wiz.delimeter)
elif wiz.file_type == 'xls':
counter = self._import_xls(load_id, wiz.data)
else:
raise exceptions.Warning(_("Not a .csv/.xls file found"))
file_load.write({'name': ('%s_%s') % (filename, actual_date),
'date': date_hour, 'fails': counter,
'file_name': filename, 'process': counter})
return counter
|
agpl-3.0
|
semantic-web-software/dynagent
|
Elecom/src/gdev/gawt/GListBox.java
|
26370
|
package gdev.gawt;
import gdev.gawt.utils.ItemList;
import gdev.gen.AssignValueException;
import gdev.gen.IComponentData;
import gdev.gen.IComponentListener;
import gdev.gen.NotValidValueException;
import gdev.gfld.GFormEnumerated;
import gdev.gfld.GFormField;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.ItemSelectable;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import dynagent.common.communication.docServer;
import dynagent.common.utils.IUserMessageListener;
import dynagent.common.utils.IdObjectForm;
/**
* Esta clase extiende a GComponent y creará una lista seleccionable.
* Una vez creada se podrá representar en la interfaz gráfica.
* @author Juan
* @author Francisco
*/
public class GListBox implements IComponentData,/*field,*/ ItemListener
{
String m_id2;
String m_id;
ItemList currentValidatedValue=null;//un valor de un item nunca puede ser 0 que corresponde a null
/*fieldControl m_control;*/
public Vector<ItemList> m_listaInicial;
String m_label;
boolean m_nullable, m_modoConsulta, m_modoFilter;
Font m_font;
ItemSelectable m_select;
JComponent m_comp;
docServer m_server;
Dimension m_dim;
/*session m_session;*/
GComponent m_component;
GFormEnumerated m_ff;
boolean m_multivalued;
IComponentListener m_componentListener;
boolean inicializationState;
ItemList[] m_currentListItemList;
boolean itemEvent;
IUserMessageListener m_messageListener;
KeyListener m_keyListener;
public GListBox(GFormField ff,/*session ses,*/docServer server,/*fieldControl control,*/IComponentListener controlValue,IUserMessageListener messageListener,KeyListener keyListener,Font fuente,boolean modoConsulta,boolean modoFilter)
{
/*m_session=ses;*/
m_server=server;
/*m_dim=dim;*/
m_modoConsulta=modoConsulta;
m_multivalued=ff.isMultivalued();
m_font=fuente;
m_nullable= ff.isNullable();
m_label=ff.getLabel();
/*m_listaInicial= (Vector)lista.clone();*/
/*m_listaInicial= (Vector)((GFormEnumerated)ff).getValues().clone();*/
/*m_control= control;*/
m_id= ff.getId();
m_id2=ff.getId2();
//////////////////////////////////////////////////////
m_componentListener=controlValue;
m_messageListener=messageListener;
m_keyListener=keyListener;
m_modoFilter=modoFilter;
m_ff=(GFormEnumerated)ff;
inicializationState=true;
itemEvent=false;
/////////////YA ESTABA COMENTADO/////////////////
//System.out.println("LB_"+getValue());
/*if(color!=null){
if(color.equals("BLUE")) m_comp.setForeground(Color.blue);
if(color.equals("GREEN")) m_comp.setForeground(Color.green);
if(color.equals("RED")) m_comp.setForeground(Color.red);
}*/
////////////////////////////////////////////////
/* System.out.println("Modo filtro GListBox "+m_modoFilter);
if( m_modoFilter ){
/*m_select= new GList( m_dim,lista, new ImageIcon( m_com.getImage("list")) );
m_comp= ((GList)m_select).getComponent();*/
/* GList list=new GList(ff,com,fuente,colorFondo);
m_select=list;
m_comp=list.getComponent();
//m_select=m_comp;
}else{
GComboBox comboBox=new GComboBox(ff);
comboBox.create();
m_select= (JComboBox)comboBox.getComponent();
m_comp=comboBox;
/*m_select= new JComboBox(lista);
m_comp=(JComponent)m_select;*/
/* }
m_select.addItemListener(this);
*/
/* m_comp.setFont(m_font.deriveFont(Font.BOLD));*/
initLista();
/* setInitialSelection();*/
//System.out.println("LB_2"+getValue());
}
/* protected void createComponent()
{
/*LISTA TIENE QUE LEERSE DE LOS ATRIBUTOS DE FF*/
/* Vector lista=new Vector();//Esto es provisional
/*initLista( lista );*/
/////////////////////////////////////////////////
/* if( m_modoFilter ){
/*m_select= new GList( m_dim,lista, new ImageIcon( m_com.getImage("list")) );
m_comp= ((GList)m_select).getComponent();*/
/* }else{
m_component=new GComboBox(ff);
/*m_select= new JComboBox(lista);
m_comp=(JComponent)m_select;*/
/* }
m_select.addItemListener(this);
}
*/
/*public JComponent getComponent(){
return (JComponent)m_select;
}*/
public GComponent getComponent(){
/*if( m_select instanceof GComponent )
return (GComponent)m_select;
if( m_comp instanceof GComponent )*/
return (GComponent)m_comp;
/*return null;*/
}
public void setItemSelectable(ItemSelectable itemSelectable){
m_select=itemSelectable;
}
public void setComponent(GComponent component){
m_comp=component;
}
private void initLista(){
if( m_modoFilter || m_multivalued ){
/*m_select= new GList( m_dim,lista, new ImageIcon( m_com.getImage("list")) );
m_comp= ((GList)m_select).getComponent();*/
GList list=new GList(m_ff,m_server,m_font,m_modoConsulta,m_modoFilter,this);
/*m_select=list;
m_comp=list.getComponent();*///Ultimo
//m_select=m_comp;
m_listaInicial=list.getListaInicial();
currentValidatedValue=list.getValorInicial().get(0);
//Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
//directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
//por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// Object[] o=new Object[] No se puede castear directamente a ItemList[]
// Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
Object[] selected=list.getValorInicial().toArray();
if(selected instanceof ItemList[])
m_currentListItemList=(ItemList[])selected;
else m_currentListItemList= Arrays.copyOf(selected,selected.length,ItemList[].class);
}else{
GComboBox comboBox=new GComboBox(m_ff,m_font,m_modoConsulta,m_modoFilter,this);
/*m_select= (JComboBox)comboBox.getComponent();
m_comp=comboBox;*///Ultimo
/*m_select= new JComboBox(lista);
m_comp=(JComponent)m_select;*/
m_listaInicial=comboBox.getListaInicial();
currentValidatedValue=comboBox.getValorInicial();
m_currentListItemList=new ItemList[1];
m_currentListItemList[0]=comboBox.getValorInicial();
}
/*m_select.addItemListener(this);*/
}
public String getLabel(){
return m_label;
}
public void commitValorInicial(){
if( /*m_modoFilter*/m_multivalued ) return;
Iterator itr= m_listaInicial.iterator();
while(itr.hasNext()){
ItemList it= (ItemList) itr.next();
it.initialSelection=false;
}
ItemList current= (ItemList)m_select.getSelectedObjects()[0];
current.initialSelection=true;
}
private void setSelectedItem( ItemList[] lista ){
Vector<ItemList> v=new Vector<ItemList>();
int size=lista.length;
for(int i=0;i<size;i++)
v.addElement(lista[i]);
setSelectedItem(v);
}
private void setSelectedItem( Vector<ItemList> lista ){
//System.out.println("PRE SETSEL "+lista.size());
if( lista==null || lista.size()==0 ) return;
if( m_select instanceof JComboBox )
((JComboBox)m_select).setSelectedItem(lista.get(0));
if( m_select instanceof GList ){
//System.out.println("ES BOX FILTER");
((GList)m_select).setSelectedValue(lista);
}
}
private boolean isPopupVisible(){
boolean visible=false;
if( m_select instanceof JComboBox )
visible=((JComboBox)m_select).isPopupVisible();
if( m_select instanceof GList ){
//System.out.println("ES BOX FILTER");
visible=((GList)m_select).isPopupVisible();
}
return visible;
}
private void setSelectedItem( ItemList it ){
if( m_select instanceof JComboBox )
((JComboBox)m_select).setSelectedItem(it);
if( m_select instanceof GList )
((GList)m_select).setSelectedValue(it);
}
public int getSize(){
if( m_select instanceof JComboBox )
return ((JComboBox)m_select).getModel().getSize();
if( m_select instanceof GList ){
//System.outprintln("VALORES "+m_select+" "+(((GList)m_select).getComponent()).getModel());
//System.outprintln("VALORES TAMANO"+(((GList)m_select).getComponent()).getModel().getSize());
return (((GList)m_select).getComponent()).getModel().getSize();
}
return 0;
}
public ItemList getItemAt(int i){
if( m_select instanceof JComboBox )
return (ItemList)((JComboBox)m_select).getItemAt(i);
if( m_select instanceof GList )
return (ItemList)(((GList)m_select).getComponent()).getModel().getElementAt(i);
return null;
}
public void setValue(Object newValue,Object oldValue) throws AssignValueException{
//TODO Cuando estamos aun gestionando un itemStateChanged si se llama a este metodo desde el metodo se produce inconsistencia.
//if(!itemEvent)
setValue( false, newValue, oldValue );
}
//Si new es null y old es null entonces no mantenemos ningun valor de la lista
private void setValue(boolean notificar,Object value,Object oldValue) throws AssignValueException{
//TODO Cambiar Object de value por String¿?¿
/*if( value!=null && !(value instanceof Integer)){
System.out.println("LIST BOX: setValue: error en cast");
return;
}*/
//System.out.println("LIST BOX:PRE SET");
// if( (m_modoFilter || m_multivalued) && m_select instanceof GList ){
// //System.out.println("LIST BOX:RESET");
// ((GList)m_select).initLista(m_listaInicial);
// }
int valor= value!=null?(Integer)value:0;
int valorOld= oldValue!=null?(Integer)oldValue:0;
//Si ya esta seleccionado no hacemos nada
Object[] lista= m_select.getSelectedObjects();
int size=lista.length;
for(int i=0;i<size;i++)
if(((ItemList)lista[i]).getIntId()==valor)
return;
Vector<ItemList> addItemList=new Vector<ItemList>();
if(! (valor==0 && valorOld==0)){
for(int i=0;i<size;i++){
if(((ItemList)lista[i]).getIntId()!=valorOld/* && ((ItemList)lista[i]).getIntId()!=0 Esto no es necesario si viene bien el valor y el valorOld en todo momento*/)
addItemList.addElement((ItemList)lista[i]);
}
}
if(valor!=0 || (valor==0 && addItemList.isEmpty())){
//System.err.println("ListaInicial:"+m_listaInicial.toString());
int sizePossibleValues=m_listaInicial.size();
for(int i=0;i<sizePossibleValues;i++){
ItemList it=m_listaInicial.get(i);
//System.err.println("Compara: it.getIntId:"+it.getIntId()+" valor:"+valor);
if(it.getIntId()==valor)
addItemList.addElement(it);
}
}
// try{
// for(int i=0;i< getSize();i++){
// ItemList it= getItemAt(i);
// if(it.getIntId()==valor){
//
// if( /*m_control*/m_controlValue!=null ){
// // if( /*m_control.estateInicialization()*/inicializationState){
// // System.out.println("WARNING:Entra en GListBox.setValue.inicializationState");
// //
// // m_select.removeItemListener(this);
// // setSelectedItem(it);
// // m_select.addItemListener(this);
// // currentValidatedValue = it;
// // inicializationState=false;
// // return;
// // }
// if(notificar && !m_modoConsulta){
// /*if(m_control.changeRequest(m_session,-1,-1,m_idForm, value))
// m_control.eventDataChanged(m_session,-1,-1,m_idForm);
// else{
// String msg="Error, ha sido asignado un valor incorrecto.";
// if(!isNullable() && isNull())
// msg+=" El campo " + getLabel() + " no admite valores nulos";
// m_messageListener.showMessage(msg);
// setSelectedItem(currentValidatedValue);
// }*/
// /*String[] buf = m_id.split(":");
// Integer valueCls = !buf[2].equals("null")?Integer.parseInt(buf[0]):null;*/
// IdObjectForm idObjectForm=new IdObjectForm(m_id);
// Integer valueCls = idObjectForm.getValueCls();
// String valueOld=null;
// /*String value=currValue;*/
// if(valueOld!=null){
// if(value!=null)
// m_controlValue.setValueField(m_id,(String)value,valueOld, valueCls, valueCls);
// else m_controlValue.removeValueField(m_id,valueOld, valueCls);
// }else{
// if(value!=null)
// m_controlValue.addValueField(m_id,(String)value,valueCls);
// //else m_controlValue.removeValueField(m_id, value, valueCls);
// }
// }
// }
// m_select.removeItemListener(this);
// setSelectedItem(it);
// m_select.addItemListener(this);
//
// currentValidatedValue = it;
// /*for(int i=0;i<size;i++)
// m_currentListItemList[i]=(ItemList)lista[i];*/
//
// Object[] listaSelect= m_select.getSelectedObjects();
// int sizeSelect=listaSelect.length;
// //Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
// //directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
// //por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// // Object[] o=new Object[] No se puede castear directamente a ItemList[]
// // Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
// if(listaSelect instanceof ItemList[])
// m_currentListItemList=(ItemList[])listaSelect;
// else m_currentListItemList= Arrays.copyOf(listaSelect,sizeSelect,ItemList[].class);
// }
// }
// }catch(NotValidValueException ex){
// m_messageListener.showErrorMessage(ex.getUserMessage());
// }
m_select.removeItemListener(this);
setSelectedItem(addItemList);
m_select.addItemListener(this);
// Para asignar el current se hace esto porque si en GList solo se deseleccionan valores usando control no habra valor, por lo que tendriamos current
currentValidatedValue= lista.length>0?(ItemList)lista[0]:null;
/*for(int i=0;i<size;i++)
m_currentListItemList[i]=(ItemList)lista[i];*/
Object[] listaSelect= m_select.getSelectedObjects();
int sizeSelect=listaSelect.length;
//Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
//directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
//por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// Object[] o=new Object[] No se puede castear directamente a ItemList[]
// Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
if(listaSelect instanceof ItemList[])
m_currentListItemList=(ItemList[])listaSelect;
else m_currentListItemList= Arrays.copyOf(listaSelect,sizeSelect,ItemList[].class);
}
boolean hasNullItem(){
ItemList it= getItemAt(0);
return it.getId().equals(0);
}
String getId2(){
return m_id2;
}
/* public String getValueToString(){
Object[] lista= m_select.getSelectedObjects();
if( lista.length==0 ) return null;
for( int i=0;i<lista.length;i++)
lista[i]=((ItemList)lista[i]).getId();
return jdomParser.buildMultivalue(lista);
}
public Object getValue(){
if( m_select.getSelectedObjects().length==0 ) return null;
if(m_select.getSelectedObjects().length==1){
ItemList it = (ItemList) m_select.getSelectedObjects()[0];
return new Integer(it.getId());
}else{
ArrayList res= new ArrayList();
for( int i=0;i<m_select.getSelectedObjects().length;i++)
res.add(new Integer((((ItemList)m_select.getSelectedObjects()[i]).getIntId())));
return res;
}
}
*/ public String getId(){
return m_id;
}
public boolean isNull(){
Object[] lista=m_select.getSelectedObjects();
if(lista == null || lista.length==0 ) return true;
return (((ItemList)m_select.getSelectedObjects()[0]).getIntId()==0);
}
public boolean isNull(Object val){
if( val instanceof Integer )
return ((Integer)val).intValue()==0;
if( val instanceof ItemList )
return ((ItemList)val).getIntId()==0;
return true;
}
public boolean isNullable(){
return m_nullable;
}
public void itemStateChanged(ItemEvent e){
//System.err.println(e);
itemEvent=true;
ItemList[] listItemListOld=null;
try{
//Este metodo es llamado tanto para indicar el item seleccionado y para indicar el item que ha sido quitado
//Asi que solo nos interesa uno de ellos, en este caso el seleccionado
if(e.getStateChange()==ItemEvent.SELECTED/* && !isPopupVisible()*/){
if( /*m_control*/m_componentListener==null || m_modoConsulta){
itemEvent=false;
return;
}
// if( /*m_control*/m_controlValue!=null ){
// if( /*m_control.estateInicialization()*/inicializationState){
// currentValidatedValue= (ItemList)m_select.getSelectedObjects()[0];
// /*for(int i=0;i<size;i++)
// m_currentListItemList[i]=(ItemList)lista[i];*/
// Object[] selected=m_select.getSelectedObjects();
//
// //Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
// //directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
// //por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// // Object[] o=new Object[] No se puede castear directamente a ItemList[]
// // Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
// if(selected instanceof ItemList[])
// m_currentListItemList=(ItemList[])selected;
// else m_currentListItemList= Arrays.copyOf(selected,selected.length,ItemList[].class);
//
// inicializationState=false;
// return;
// }
// }
// Obtenemos los objetos seleccionados
Object[] lista= m_select.getSelectedObjects();
int size=lista.length;
listItemListOld=m_currentListItemList.clone();
ArrayList<ItemList> addItemList=new ArrayList<ItemList>();
for(int i=0;i<size;i++){
addItemList.add((ItemList)lista[i]);
}
IdObjectForm idObjectForm=new IdObjectForm(m_id);
Integer valueCls = idObjectForm.getValueCls();
ArrayList<ItemList> replacedItemList=new ArrayList<ItemList>();
for( int i=0;i<size;i++){
ItemList it=(ItemList)lista[i];
/*if(!m_control.changeRequest(m_session,-1,-1,m_idForm,new Integer(it.getIntId()))){
String msg = "Ha escrito un valor incorrecto.";
if (!isNullable() && isNull())
msg += " El campo " + getLabel() +
" no admite valores nulos";
m_messageListener.showErrorMessage(msg);
setSelectedItem(currentValidatedValue);
return;
}*/
/*String[] buf = m_id.split(":");
Integer valueCls = !buf[2].equals("null")?Integer.parseInt(buf[0]):null;;
String value=String.valueOf(it.getIntId());
*/
if(!hasValue(it)){
Integer value=it.getIntId();
if(value.equals(0))
value=null;
Integer valueOld=getNextValueOld(addItemList,replacedItemList);
if(valueOld!=null && valueOld.equals(0))
valueOld=null;
/*if(value.equals(""))
value=null;*/
if(!m_multivalued){
if(valueOld!=null){
if(value!=null)
m_componentListener.setValueField(m_id,value,valueOld, valueCls, valueCls);
else m_componentListener.removeValueField(m_id,valueOld, valueCls);
}else{
if(value!=null)
m_componentListener.addValueField(m_id,value,valueCls);
//else m_controlValue.removeValueField(m_id, value, valueCls);
}
}else{
/*Si es multivalued no reutilizamos el fact haciendo un set como para los de un unico valor ya que:
Si, por ejemplo, tenemos dos valores, primero quitamos uno, y luego sustituimos el dejado por el quitado, se estaría enviando a base de datos un del y un set,
procesando base de datos antes el set que el del por lo que finalmente se quedaría sin ningun valor
*/
if(valueOld!=null)
m_componentListener.removeValueField(m_id,valueOld, valueCls);
if(value!=null)
m_componentListener.addValueField(m_id,value,valueCls);
}
}
}
int sizeOld=listItemListOld.length;
if(size<sizeOld){
for(int i=0;i<sizeOld;i++){
ItemList itemList=listItemListOld[i];
if(!replacedItemList.contains(itemList) && !addItemList.contains(itemList)){
Integer value=itemList.getIntId();
m_componentListener.removeValueField(m_id,value, valueCls);
}
}
}
lista= m_select.getSelectedObjects();//Volvemos a pedir los objetos seleccionados porque las acciones anteriores han podido provocar cambios
// Para asignar el current se hace esto porque si en GList solo se deseleccionan valores usando control no habra valor, por lo que tendriamos current
currentValidatedValue= lista.length>0?(ItemList)lista[0]:null;
/*for(int i=0;i<size;i++)
m_currentListItemList[i]=(ItemList)lista[i];*/
//Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
//directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
//por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// Object[] o=new Object[] No se puede castear directamente a ItemList[]
// Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
if(lista instanceof ItemList[])
m_currentListItemList=(ItemList[])lista;
else m_currentListItemList= Arrays.copyOf(lista,lista.length,ItemList[].class);
itemEvent=false;
/*m_control.eventDataChanged(m_session,-1,-1,m_idForm);*/
}
}catch(NotValidValueException ex){
m_messageListener.showErrorMessage(ex.getUserMessage(),SwingUtilities.getWindowAncestor(this.getComponent()));
setSelectedItem(listItemListOld);
}catch(Exception ex){
m_server.logError(SwingUtilities.getWindowAncestor(this.getComponent()),ex,"Error al seleccionar elemento");
setSelectedItem(listItemListOld);
ex.printStackTrace();
}
}
/*
Obtiene el siguiente valueOld que se puede utilizar para hacer un setValueField. Si en la lista
de los anteriores valores hay un valor que no aparece en addItemList(nuevos valores) ni en
replacedItemList(valores ya usados) sera el valueOld que utilizaremos. Una vez elegido se añade a
la lista replacedItemList para que en las llamadas de los otros values de addItemList no se utilicen
los mismos antiguos valores. Si no hay valores para elegir se devuelve null.
*/
private Integer getNextValueOld(ArrayList<ItemList> addItemList,ArrayList<ItemList> replacedItemList){
Integer valueOld=null;
if(m_currentListItemList!=null){//Si hay alguna seleccion
ArrayList<ItemList> currentList=new ArrayList<ItemList>();
int size=m_currentListItemList.length;
for(int i=0;i<size;i++){
currentList.add(m_currentListItemList[i]);
}
Iterator<ItemList> itr=currentList.iterator();
boolean found=false;
while(!found && itr.hasNext()){
ItemList itemL=itr.next();
if(!addItemList.contains(itemL) && !replacedItemList.contains(itemL)){
valueOld=itemL.getIntId();
replacedItemList.add(itemL);
found=true;
}
}
}
return valueOld;
}
private boolean hasValue(ItemList it){
int size=m_currentListItemList.length;
for(int i=0;i<size;i++){
if(m_currentListItemList[i].equals(it))
return true;
}
return false;
}
public boolean hasChanged() {
//int seleccion= getSelectedIndex();
// ItemList itemSelected= (ItemList)m_select.getSelectedObjects()[0];
// return !itemSelected.isInitialSelected();
/*for(int i= 0; i< seleccion.length; i++){
if(((itemList)getModel().getElementAt(seleccion[i])).isInitialSelected()!=
isSelectedIndex(seleccion[i])) return true;
}*/
ArrayList<ItemList> arrayOld=new ArrayList<ItemList>();
Object[] selected=m_select.getSelectedObjects();
int sizeOld=m_currentListItemList.length;
int size=selected.length;
if(size!=sizeOld) return true;
for(int i=0;i<sizeOld;i++)
arrayOld.add(m_currentListItemList[i]);
for(int i=0;i<size;i++){
ItemList itemList=(ItemList)selected[i];
if(!arrayOld.contains(itemList))
return true;
}
return false;
}
public void initValue() {
// if( /*m_modoFilter*/m_multivalued ) return;
// Iterator itr= m_listaInicial.iterator();
// while(itr.hasNext()){
// ItemList it= (ItemList) itr.next();
// it.initialSelection=false;
// }
// ItemList current= (ItemList)m_select.getSelectedObjects()[0];
// current.initialSelection=true;
if(m_modoFilter || m_multivalued)
((GList)getComponent()).initValue();
else ((GComboBox)getComponent()).initValue();
}
public Object getValue() {
String values=null;
int size=m_currentListItemList.length;
if(size!=0)
values=m_currentListItemList[0].getId();
for(int i=1;i<size;i++)
values+=":"+m_currentListItemList[i].getId();
//System.err.println("WARNING: Llamada al metodo GListBox.getValue() el cual no esta implementado");
return null;
}
public void clean() throws ParseException, AssignValueException {
setValue(false, null, null);
}
public IComponentListener getComponentListener() {
return m_componentListener;
}
}
|
agpl-3.0
|
jondo/paperpile
|
plack/perl5/win32/lib/unicore/lib/CWKCF/N.pl
|
8928
|
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by mktables from the Unicode
# database, Version 5.2.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by the Perl program only. The format and even
# the name or existence of this file are subject to change without notice.
# Don't use it directly.
# This file returns the 1_104_372 code points in Unicode Version 5.2.0 that
# match any of the following regular expression constructs:
#
# \p{Changes_When_NFKC_Casefolded=No}
# \p{CWKCF=N}
# \p{Is_Changes_When_NFKC_Casefolded=F}
# \p{Is_CWKCF=False}
#
# \P{Changes_When_NFKC_Casefolded}
# \P{Is_Changes_When_NFKC_Casefolded}
# \P{CWKCF}
# \P{Is_CWKCF}
#
# perluniprops.pod should be consulted for the syntax rules for any of these,
# including if adding or subtracting white space, underscore, and hyphen
# characters matters or doesn't matter, and other permissible syntactic
# variants. Upper/lower case distinctions never matter.
#
# A colon can be substituted for the equals sign, and anything to the left of
# the equals (or colon) can be combined with anything to the right. Thus,
# for example,
# \p{Is_CWKCF: No}
# is also valid.
#
# The format of the lines of this file is: START\tSTOP\twhere START is the
# starting code point of the range, in hex; STOP is the ending point, or if
# omitted, the range has just one code point. Numbers in comments in
# [brackets] indicate how many code points are in the range.
return <<'END';
0000 0040 # [65]
005B 009F # [69]
00A1 00A7 # [7]
00A9
00AB 00AC # [2]
00AE
00B0 00B1 # [2]
00B6 00B7 # [2]
00BB
00BF
00D7
00E0 00FF # [32]
0101
0103
0105
0107
0109
010B
010D
010F
0111
0113
0115
0117
0119
011B
011D
011F
0121
0123
0125
0127
0129
012B
012D
012F
0131
0135
0137 0138 # [2]
013A
013C
013E
0142
0144
0146
0148
014B
014D
014F
0151
0153
0155
0157
0159
015B
015D
015F
0161
0163
0165
0167
0169
016B
016D
016F
0171
0173
0175
0177
017A
017C
017E
0180
0183
0185
0188
018C 018D # [2]
0192
0195
0199 019B # [3]
019E
01A1
01A3
01A5
01A8
01AA 01AB # [2]
01AD
01B0
01B4
01B6
01B9 01BB # [3]
01BD 01C3 # [7]
01CE
01D0
01D2
01D4
01D6
01D8
01DA
01DC 01DD # [2]
01DF
01E1
01E3
01E5
01E7
01E9
01EB
01ED
01EF 01F0 # [2]
01F5
01F9
01FB
01FD
01FF
0201
0203
0205
0207
0209
020B
020D
020F
0211
0213
0215
0217
0219
021B
021D
021F
0221
0223
0225
0227
0229
022B
022D
022F
0231
0233 0239 # [7]
023C
023F 0240 # [2]
0242
0247
0249
024B
024D
024F 02AF # [97]
02B9 02D7 # [31]
02DE 02DF # [2]
02E5 033F # [91]
0342
0346 034E # [9]
0350 036F # [32]
0371
0373
0375
0377 0379 # [3]
037B 037D # [3]
037F 0383 # [5]
038B
038D
0390
03A2
03AC 03C1 # [22]
03C3 03CE # [12]
03D7
03D9
03DB
03DD
03DF
03E1
03E3
03E5
03E7
03E9
03EB
03ED
03EF
03F3
03F6
03F8
03FB 03FC # [2]
0430 045F # [48]
0461
0463
0465
0467
0469
046B
046D
046F
0471
0473
0475
0477
0479
047B
047D
047F
0481 0489 # [9]
048B
048D
048F
0491
0493
0495
0497
0499
049B
049D
049F
04A1
04A3
04A5
04A7
04A9
04AB
04AD
04AF
04B1
04B3
04B5
04B7
04B9
04BB
04BD
04BF
04C2
04C4
04C6
04C8
04CA
04CC
04CE 04CF # [2]
04D1
04D3
04D5
04D7
04D9
04DB
04DD
04DF
04E1
04E3
04E5
04E7
04E9
04EB
04ED
04EF
04F1
04F3
04F5
04F7
04F9
04FB
04FD
04FF
0501
0503
0505
0507
0509
050B
050D
050F
0511
0513
0515
0517
0519
051B
051D
051F
0521
0523
0525 0530 # [12]
0557 0586 # [48]
0588 0674 # [237]
0679 0957 # [735]
0960 09DB # [124]
09DE
09E0 0A32 # [83]
0A34 0A35 # [2]
0A37 0A58 # [34]
0A5C 0A5D # [2]
0A5F 0B5B # [253]
0B5E 0E32 # [725]
0E34 0EB2 # [127]
0EB4 0EDB # [40]
0EDE 0F0B # [46]
0F0D 0F42 # [54]
0F44 0F4C # [9]
0F4E 0F51 # [4]
0F53 0F56 # [4]
0F58 0F5B # [4]
0F5D 0F68 # [12]
0F6A 0F72 # [9]
0F74
0F7A 0F80 # [7]
0F82 0F92 # [17]
0F94 0F9C # [9]
0F9E 0FA1 # [4]
0FA3 0FA6 # [4]
0FA8 0FAB # [4]
0FAD 0FB8 # [12]
0FBA 109F # [230]
10C6 10FB # [54]
10FD 115E # [98]
1161 17B3 # [1619]
17B6 180A # [85]
180E 1D2B # [1310]
1D2F
1D3B
1D4E
1D6B 1D77 # [13]
1D79 1D9A # [34]
1DC0 1DFF # [64]
1E01
1E03
1E05
1E07
1E09
1E0B
1E0D
1E0F
1E11
1E13
1E15
1E17
1E19
1E1B
1E1D
1E1F
1E21
1E23
1E25
1E27
1E29
1E2B
1E2D
1E2F
1E31
1E33
1E35
1E37
1E39
1E3B
1E3D
1E3F
1E41
1E43
1E45
1E47
1E49
1E4B
1E4D
1E4F
1E51
1E53
1E55
1E57
1E59
1E5B
1E5D
1E5F
1E61
1E63
1E65
1E67
1E69
1E6B
1E6D
1E6F
1E71
1E73
1E75
1E77
1E79
1E7B
1E7D
1E7F
1E81
1E83
1E85
1E87
1E89
1E8B
1E8D
1E8F
1E91
1E93
1E95 1E99 # [5]
1E9C 1E9D # [2]
1E9F
1EA1
1EA3
1EA5
1EA7
1EA9
1EAB
1EAD
1EAF
1EB1
1EB3
1EB5
1EB7
1EB9
1EBB
1EBD
1EBF
1EC1
1EC3
1EC5
1EC7
1EC9
1ECB
1ECD
1ECF
1ED1
1ED3
1ED5
1ED7
1ED9
1EDB
1EDD
1EDF
1EE1
1EE3
1EE5
1EE7
1EE9
1EEB
1EED
1EEF
1EF1
1EF3
1EF5
1EF7
1EF9
1EFB
1EFD
1EFF 1F07 # [9]
1F10 1F17 # [8]
1F1E 1F27 # [10]
1F30 1F37 # [8]
1F40 1F47 # [8]
1F4E 1F58 # [11]
1F5A
1F5C
1F5E
1F60 1F67 # [8]
1F70
1F72
1F74
1F76
1F78
1F7A
1F7C
1F7E 1F7F # [2]
1FB0 1FB1 # [2]
1FB5 1FB6 # [2]
1FC5 1FC6 # [2]
1FD0 1FD2 # [3]
1FD4 1FD7 # [4]
1FDC
1FE0 1FE2 # [3]
1FE4 1FE7 # [4]
1FF0 1FF1 # [2]
1FF5 1FF6 # [2]
1FFF
2010
2012 2016 # [5]
2018 2023 # [12]
2027 2029 # [3]
2030 2032 # [3]
2035
2038 203B # [4]
203D
203F 2046 # [8]
204A 2056 # [13]
2058 205E # [7]
2072 2073 # [2]
208F
2095 20A7 # [19]
20A9 20FF # [87]
2104
2108
2114
2117 2118 # [2]
211E 211F # [2]
2123
2125
2127
2129
212E
213A
2141 2144 # [4]
214A 214F # [6]
2180 2182 # [3]
2184 2188 # [5]
218A 222B # [162]
222E
2231 2328 # [248]
232B 245F # [309]
24EB 2A0B # [1313]
2A0D 2A73 # [103]
2A77 2ADB # [101]
2ADD 2BFF # [291]
2C2F 2C5F # [49]
2C61
2C65 2C66 # [2]
2C68
2C6A
2C6C
2C71
2C73 2C74 # [2]
2C76 2C7B # [6]
2C81
2C83
2C85
2C87
2C89
2C8B
2C8D
2C8F
2C91
2C93
2C95
2C97
2C99
2C9B
2C9D
2C9F
2CA1
2CA3
2CA5
2CA7
2CA9
2CAB
2CAD
2CAF
2CB1
2CB3
2CB5
2CB7
2CB9
2CBB
2CBD
2CBF
2CC1
2CC3
2CC5
2CC7
2CC9
2CCB
2CCD
2CCF
2CD1
2CD3
2CD5
2CD7
2CD9
2CDB
2CDD
2CDF
2CE1
2CE3 2CEA # [8]
2CEC
2CEE 2D6E # [129]
2D70 2E9E # [303]
2EA0 2EF2 # [83]
2EF4 2EFF # [12]
2FD6 2FFF # [42]
3001 3035 # [53]
3037
303B 309A # [96]
309D 309E # [2]
30A0 30FE # [95]
3100 3130 # [49]
318F 3191 # [3]
31A0 31FF # [96]
321F
3248 324F # [8]
327F
32FF
3400 A63F # [29_248]
A641
A643
A645
A647
A649
A64B
A64D
A64F
A651
A653
A655
A657
A659
A65B
A65D
A65F A661 # [3]
A663
A665
A667
A669
A66B
A66D A67F # [19]
A681
A683
A685
A687
A689
A68B
A68D
A68F
A691
A693
A695
A697 A721 # [139]
A723
A725
A727
A729
A72B
A72D
A72F A731 # [3]
A733
A735
A737
A739
A73B
A73D
A73F
A741
A743
A745
A747
A749
A74B
A74D
A74F
A751
A753
A755
A757
A759
A75B
A75D
A75F
A761
A763
A765
A767
A769
A76B
A76D
A76F
A771 A778 # [8]
A77A
A77C
A77F
A781
A783
A785
A787 A78A # [4]
A78C F8FF # [20_852]
FA0E FA0F # [2]
FA11
FA13 FA14 # [2]
FA1F
FA21
FA23 FA24 # [2]
FA27 FA29 # [3]
FA2E FA2F # [2]
FA6E FA6F # [2]
FADA FAFF # [38]
FB07 FB12 # [12]
FB18 FB1C # [5]
FB1E
FB37
FB3D
FB3F
FB42
FB45
FBB2 FBD2 # [33]
FD3E FD4F # [18]
FD90 FD91 # [2]
FDC8 FDEF # [40]
FDFD FDFF # [3]
FE1A FE2F # [22]
FE45 FE46 # [2]
FE53
FE67
FE6C FE6F # [4]
FE73
FE75
FEFD FEFE # [2]
FF00
FFBF FFC1 # [3]
FFC8 FFC9 # [2]
FFD0 FFD1 # [2]
FFD8 FFD9 # [2]
FFDD FFDF # [3]
FFE7
FFEF
FFF9 103FF # [1031]
10428 1D15D # [52_534]
1D165 1D172 # [14]
1D17B 1D1BA # [64]
1D1C1 1D3FF # [575]
1D455
1D49D
1D4A0 1D4A1 # [2]
1D4A3 1D4A4 # [2]
1D4A7 1D4A8 # [2]
1D4AD
1D4BA
1D4BC
1D4C4
1D506
1D50B 1D50C # [2]
1D515
1D51D
1D53A
1D53F
1D545
1D547 1D549 # [3]
1D551
1D6A6 1D6A7 # [2]
1D7CC 1D7CD # [2]
1D800 1F0FF # [6400]
1F10B 1F10F # [5]
1F12F 1F130 # [2]
1F132 1F13C # [11]
1F13E
1F140 1F141 # [2]
1F143 1F145 # [3]
1F147 1F149 # [3]
1F14F 1F18F # [65]
1F191 1F1FF # [111]
1F201 1F20F # [15]
1F232 1F23F # [14]
1F249 2F7FF # [66_999]
2FA1E DFFFF # [722_402]
E1000 10FFFF # [192_512]
END
|
agpl-3.0
|
part-up/part-up
|
app/packages/partup-client-base/client/chatmessages.js
|
2893
|
var round = function(number, increment, offset) {
return Math.ceil((number - offset) / increment) * increment + offset;
};
Partup.client.chatmessages = {
groupByDelay: function(messages, options) {
var delay = options.seconds ? options.seconds * 1000 : 1000;
var outputArray = [];
messages.forEach(function(item, index) {
var outputLastIndex = outputArray.length - 1;
var lastCreatedAt;
if (outputArray[outputLastIndex]) {
lastCreatedAt = new Date(outputArray[outputLastIndex].messages[outputArray[outputLastIndex].messages.length - 1].created_at).getTime();
}
var currentCreatedAt = new Date(item.created_at).getTime();
if (outputArray[outputLastIndex] && lastCreatedAt && (currentCreatedAt - lastCreatedAt) < delay) {
outputArray[outputLastIndex].messages.push(item);
} else {
outputArray.push({
messages: [item]
});
}
});
return outputArray.reverse();
},
groupByCreationDay: function(messages) {
var outputArray = [];
messages.forEach(function(item, index) {
var outputLastIndex = outputArray.length - 1;
if (outputArray[outputLastIndex] && outputArray[outputLastIndex].day === new Date(item.created_at).setHours(0, 0, 0, 0, 0)) {
outputArray[outputLastIndex].messages.push(item);
} else {
outputArray.push({
day: new Date(item.created_at).setHours(0, 0, 0, 0, 0),
messages: [item]
});
}
});
return outputArray.reverse();
},
groupByCreatorId: function(messages) {
var outputArray = [];
messages.forEach(function(item, index) {
var outputLastIndex = outputArray.length - 1;
if (outputArray[outputLastIndex] && outputArray[outputLastIndex].creator_id === item.creator_id) {
outputArray[outputLastIndex].messages.push(item);
} else {
outputArray.push({
creator_id: item.creator_id,
messages: [item]
});
}
});
return outputArray.reverse();
},
groupByChat: function(messages) {
var outputObject = {};
messages.forEach(function(item, index) {
if (outputObject[item.chat_id] && outputObject[item.chat_id].chat_id === item.chat_id) {
outputObject[item.chat_id].messages.push(item);
} else {
outputObject[item.chat_id] = {
chat_id: item.chat_id,
messages: [item]
};
}
});
var outputArray = _.values(outputObject);
return outputArray;
}
};
|
agpl-3.0
|
see-r/SeerDataCruncher
|
src/main/java/com/datacruncher/datastreams/DatastreamsInput.java
|
18067
|
/*
* DataCruncher
* Copyright (c) Mario Altimari. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.datacruncher.datastreams;
import com.datacruncher.datastreams.threads.PersistStreamsAndSendAlertsThread;
import com.datacruncher.constants.GenericType;
import com.datacruncher.constants.SchemaType;
import com.datacruncher.constants.StreamType;
import com.datacruncher.fileupload.FileExtensionType;
import com.datacruncher.fileupload.FileReadObject;
import com.datacruncher.fileupload.FileReadObjectFactory;
import com.datacruncher.jpa.ReadList;
import com.datacruncher.jpa.dao.DaoSet;
import com.datacruncher.jpa.entity.ApplicationEntity;
import com.datacruncher.jpa.entity.EventTriggerEntity;
import com.datacruncher.jpa.entity.SchemaEntity;
import com.datacruncher.jpa.entity.TasksEntity;
import com.datacruncher.utils.generic.CommonUtils;
import com.datacruncher.utils.generic.I18n;
import com.datacruncher.validation.Logical;
import com.datacruncher.validation.ResultStepValidation;
import com.datacruncher.validation.Temporary;
import org.apache.log4j.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.*;
public class DatastreamsInput implements DaoSet {
private final static Logger log = Logger.getLogger(DatastreamsInput.class);
private String uploadedFileName;
List<EventTriggerEntity> okEventList;
List<EventTriggerEntity> koEventList;
List<EventTriggerEntity> warnEventList;
private boolean okEvent = false;
private boolean koEvent = false;
private boolean warnEvent = false;
private boolean bTotalSuccess;
private String resultMsg = "";
public final static String _SINGLE_SUCC_RESP = "bTotalSuccess";
public final static String _SINGLE_STR_RESP = "bTotalResultString";
public final static String _SINGLE_STREAMENT_RESP = "streamEntityResonse";
private static int poolSize = 7;
static {
Properties properties = new Properties();
InputStream in = DatastreamsInput.class.getClassLoader().getResourceAsStream("main.properties");
try {
properties.load(in);
poolSize = Integer.parseInt(properties.get("validation.pool_size").toString());
} catch (IOException e) {
log.error("error reading main.properties", e);
}
}
public void setUploadedFileName(String uploadedFileName) {
this.uploadedFileName = uploadedFileName;
}
public DatastreamsInput() {
}
public String datastreamsInput(String datastream, Long idSchema,byte[] bytes){
return datastreamsInput(datastream, idSchema, bytes, null);
}
public String datastreamsInput(String datastream, Long idSchema, byte[] bytes, Object object) {
SchemaEntity schemaEntity = schemasDao.find(idSchema);
if (schemaEntity != null && schemaEntity.getIsPlanned() && schemaEntity.getPlannedName() > 0) {
TasksEntity tasksEntity = tasksDao.find(schemaEntity.getPlannedName());
boolean isPlanned = true;
Calendar calendar = Calendar.getInstance();
if (tasksEntity != null) {
if (tasksEntity.getIsOneShoot()) {
Date shootDate = tasksEntity.getShootDate();
String shootTime = tasksEntity.getShootTime();
Calendar shootDateTime = Calendar.getInstance();
shootDateTime.setTime(shootDate);
if (calendar.get(Calendar.YEAR) != shootDateTime.get(Calendar.YEAR)) {
isPlanned = false;
} else if (calendar.get(Calendar.MONTH) != shootDateTime.get(Calendar.MONTH)) {
isPlanned = false;
} else if (calendar.get(Calendar.DAY_OF_MONTH) != shootDateTime.get(Calendar.DAY_OF_MONTH)) {
isPlanned = false;
} else if (shootTime.trim().length() > 0 && !shootTime.equalsIgnoreCase("hh:mm")) {
int hour = Integer.parseInt(shootTime.substring(0, shootTime.indexOf(":")));
int min = Integer.parseInt(shootTime.substring(shootTime.indexOf(":") + 1));
if (calendar.get(Calendar.HOUR_OF_DAY) != hour) {
isPlanned = false;
} else if (calendar.get(Calendar.MINUTE) != min) {
isPlanned = false;
}
}
} else if (tasksEntity.getIsPeriodically()) {
if (tasksEntity.getMonth() >= 0 && (calendar.get(Calendar.MONTH) + 1) != tasksEntity.getMonth()) {
isPlanned = false;
} else if (tasksEntity.getDay() >= 0 && calendar.get(Calendar.DAY_OF_MONTH) != tasksEntity.getDay()) {
isPlanned = false;
} else if (tasksEntity.getWeek() >= 0 && calendar.get(Calendar.DAY_OF_WEEK) != tasksEntity.getWeek()) {
isPlanned = false;
} else if (tasksEntity.getHour() >= 0 && calendar.get(Calendar.HOUR_OF_DAY) != tasksEntity.getHour()) {
isPlanned = false;
} else if (tasksEntity.getMinute() >= 0 && calendar.get(Calendar.MINUTE) != tasksEntity.getMinute()) {
isPlanned = false;
}
}
}
if (!isPlanned) {
return I18n.getMessage("error.datastreamnotplanned.invalid");
}
}
return datastreamsInput(datastream, idSchema, bytes, false, object);
}
public String datastreamsInput(String datastream, Long idSchema, byte[] bytes, boolean isUnitTest){
return datastreamsInput(datastream, idSchema, bytes, isUnitTest, null);
}
public String datastreamsInput(String datastream, Long idSchema, byte[] bytes, boolean isUnitTest, Object object){
String resultMsg = "";
SchemaEntity schemaEntity = schemasDao.find(idSchema);
if (schemaEntity == null) {
resultMsg = I18n.getMessage("error.schema.invalid");
return isUnitTest ? "false" : resultMsg;
}
int idStreamType = schemaEntity.getIdStreamType();
ApplicationEntity appEntity = appDao.find(schemaEntity.getIdApplication());
Temporary temporary = new Temporary();
ResultStepValidation resultValidation = temporary.temporaryValidation(schemaEntity, appEntity);
if (resultValidation.isValid()) {
List<String> streamsList = parseStream(datastream, bytes, idSchema, idStreamType);
int i = 1;
if (streamsList.size() > 0) {
long numEvents = schemaTriggerStatusDao.findEventByIdSchema(idSchema);
bTotalSuccess = true;
if (numEvents > 0) {
checkEventTrigger(idSchema);
}
ExecutorService executor = Executors.newFixedThreadPool(poolSize);
// On case of IndexIncrement thread executor is forced to be
// single thred to guarantee order of task executions
if ( schemaEntity.getIsIndexedIncrement() ) {
executor = Executors.newSingleThreadExecutor();
}
long numElemChecked = schemaFieldsDao.findNumExtraCheck(idSchema);
String defaultNsLib = schemaEntity.getIdSchemaLib() == 0 ? null : schemaLibDao.find(schemaEntity.getIdSchemaLib()).getDefaultNsLib();
List<Future<Map<String, Object>>> list = new ArrayList<Future<Map<String, Object>>>();
boolean skipHeader =
schemaEntity.getIdStreamType() == StreamType.flatFileDelimited &&
schemaEntity.getIdSchemaType() == SchemaType.VALIDATION &&
schemaEntity.isNoHeader();
int index = -1;
for (String stream : streamsList) {
index ++;
if ( index == 0 && skipHeader ) {
continue;
}
Callable<Map<String, Object>> callee = new ValidationCallable(
idSchema,
schemaEntity,
stream,
bytes,
isUnitTest,
okEvent,
koEvent,
warnEvent,
okEventList,
koEventList,
warnEventList,
object,
numElemChecked,
appEntity,
defaultNsLib,
index == streamsList.size() - 1,
skipHeader ? index == 1 : index == 0 );
Future<Map<String, Object>> submit = executor.submit(callee);
list.add(submit);
}
Map<String, Object> futureRes;
try {
if (!isUnitTest) {
PersistStreamsAndSendAlertsThread persStreams = new PersistStreamsAndSendAlertsThread(list, executor);
persStreams.start();
persStreams.join();
}
for (Future<Map<String, Object>> future : list) {
try {
futureRes = future.get();
resultMsg += (streamsList.size() == 1 ? "" : i++ + ".Stream: ")
+ futureRes.get(_SINGLE_STR_RESP) + "<br><br>";
bTotalSuccess = bTotalSuccess && (Boolean) futureRes.get(_SINGLE_SUCC_RESP);
} catch (ExecutionException e) {
log.error("ExecutionException", e);
}
}
} catch (InterruptedException e1) {
log.error("InterruptedException", e1);
}
executor.shutdown();
Logical.mapExtraCheck = new HashMap<String, Set<String>>();
} else {
bTotalSuccess = false;
resultMsg = I18n.getMessage("error.validationTraceNoValid");
}
} else {
bTotalSuccess = false;
resultMsg = resultValidation.getMessageResult();
}
this.resultMsg = resultMsg;
return isUnitTest ? String.valueOf(bTotalSuccess) : resultMsg;
}
@SuppressWarnings("unchecked")
private void checkEventTrigger(Long idSchema){
ReadList readList = eventTriggerDao.findByIdSchemaAndIdStatus(idSchema, GenericType.okEvent);
if (readList.getResults() != null && readList.getResults().size() > 0) {
okEvent = true;
okEventList = (List<EventTriggerEntity>) readList.getResults();
}else{
okEvent = false;
}
readList = eventTriggerDao.findByIdSchemaAndIdStatus(idSchema,GenericType.koEvent);
if (readList.getResults() != null && readList.getResults().size() > 0) {
koEvent = true;
koEventList = (List<EventTriggerEntity>) readList.getResults();
}else{
koEvent = false;
}
readList = eventTriggerDao.findByIdSchemaAndIdStatus(idSchema,GenericType.warnEvent);
if (readList.getResults() != null && readList.getResults().size() > 0) {
warnEvent = true;
warnEventList = (List<EventTriggerEntity>) readList.getResults();
}else{
warnEvent = false;
}
}
/**
* Parses current multi datastream.
*
* @param datastream DataStream
* @param idStreamType
* - xml/exi/..
* @return separated streams
*/
private List<String> parseStream(String datastream, byte[] bytes,
Long idSchema, int idStreamType) {
List<String> streamsList = new ArrayList<String>();
try {
if(schemasDao.find(idSchema).getIdSchemaType() == SchemaType.STANDARD){
String defNameSpace = schemaLibDao.find(schemasDao.find(idSchema).getIdSchemaLib()).getDefaultNsLib();
String str = datastream.replaceAll("\\r|\\n|\\t", " ").trim();
if (str.startsWith("<?xml")) {
// xml prolog remove
str = str.replaceFirst("<\\?xml .*\\?>", "");
str = str.trim();
}
if (str.startsWith("<")) {
int r= str.lastIndexOf("</");
String closingNode = str.substring(r);
closingNode = closingNode.trim();
String nodeName = closingNode.substring(closingNode.indexOf("/")+1, closingNode.length()-1);
streamsList = Arrays.asList(str.split(closingNode));
for (int i = 0; i < streamsList.size(); i++) {
String stream=streamsList.get(i).replaceFirst(nodeName,nodeName+" xmlns="+ defNameSpace +" ");
streamsList.set(i, stream + closingNode);
}
}
}else{
if (idStreamType == StreamType.XML ) {
String str = datastream.replaceAll("\\r|\\n|\\t", " ").trim();
if (str.startsWith("<?xml")) {
// xml prolog remove
str = str.replaceFirst("<\\?xml .*\\?>", "");
str = str.trim();
}
if (str.startsWith("<")) {
int r= str.lastIndexOf("</");
String closingNode = str.substring(r);
closingNode = closingNode.trim();
streamsList = Arrays.asList(str.split(closingNode));
for (int i = 0; i < streamsList.size(); i++) {
streamsList.set(i, streamsList.get(i) + closingNode);
}
}
}else if (idStreamType == StreamType.flatFileFixedPosition) {
datastream= datastream.replaceAll("\\r\\n", "\\\n");
datastream= datastream.replaceAll("\\r", "\\\n");
streamsList = Arrays.asList(datastream.split("\\n"));
for (int i = 0; i < streamsList.size(); i++) {
// '/r' appear in file with '/r/n' but in textarea appear
// only '/n'
streamsList
.set(i, streamsList.get(i).replaceAll("\\r", ""));
}
} else if (idStreamType == StreamType.flatFileDelimited) {
datastream= datastream.replaceAll("\\r\\n", "\\\n");
datastream= datastream.replaceAll("\\r", "\\\n");
Character chrDelim = schemasDao.find(idSchema).getChrDelimiter().charAt(0);
if (chrDelim.toString().trim().length() == 1) {
streamsList = Arrays.asList(CommonUtils.lineSplit(datastream, schemasDao.find(idSchema).getDelimiter(),chrDelim));
}else{
streamsList = Arrays.asList(datastream.split("\\n"));
}
for (int i = 0; i < streamsList.size(); i++) {
// '/r' appear in file with '/r/n' but in textarea appear
// only '/n'
streamsList.set(i, streamsList.get(i).replaceAll("\\r", ""));
}
} else if (idStreamType == StreamType.XMLEXI) {
streamsList.add(datastream);
} else if (idStreamType == StreamType.JSON) {
String str = datastream.replaceAll("\\r|\\n|\\t", "").trim();
datastream = str.replaceAll("\\}\\{", "\\}--\\{");
streamsList = Arrays.asList(datastream.split("--"));
for (int i = 0; i < streamsList.size(); i++) {
streamsList.set(i, streamsList.get(i));
}
} else if (idStreamType == StreamType.EXCEL) {
if (!(uploadedFileName.endsWith(FileExtensionType.EXCEL_97
.getAbbreviation()) || uploadedFileName
.endsWith(FileExtensionType.EXCEL_2007
.getAbbreviation()))) {
streamsList.add("File is not a MS Excel file.");
return streamsList;
}
FileReadObject fileReadObject = FileReadObjectFactory
.getFileReadObject(uploadedFileName);
datastream = fileReadObject.parseStream(idSchema,
new ByteArrayInputStream(bytes));
String str = datastream.replaceAll("\\r|\\n|\\t", " ").trim();
if (str.startsWith("<?xml")) {
// xml prolog remove
str = str.replaceFirst("<\\?xml .*\\?>", "");
str = str.trim();
}
if (str.startsWith("<")) {
String rootNodeName = str.substring(1, str.indexOf(">"));
String closingNode = "</" + rootNodeName + ">";
streamsList = Arrays.asList(str.split(closingNode));
for (int i = 0; i < streamsList.size(); i++) {
streamsList.set(i, streamsList.get(i) + closingNode);
}
} else {
streamsList.add(datastream);
}
}
}
} catch (Exception e) {
log.error("Error while parsing stream", e);
}
return streamsList;
}
public boolean getTotalSuccess() {
return bTotalSuccess;
}
public String getResultMsg() {
return resultMsg;
}
}
|
agpl-3.0
|
kj415j45/osu-web
|
resources/lang/zh/beatmaps.php
|
10212
|
<?php
/**
* Copyright 2015-2018 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
return [
'discussion-posts' => [
'store' => [
'error' => '保存失败',
],
],
'discussion-votes' => [
'update' => [
'error' => '更新投票失败',
],
],
'discussions' => [
'allow_kudosu' => '给予 kudosu',
'delete' => '删除',
'deleted' => '被 :editor 于 :delete_time 删除。',
'deny_kudosu' => '收回 kudosu',
'edit' => '编辑',
'edited' => '最后由 :editor 编辑于 :update_time 。',
'kudosu_denied' => 'kudosu 被收回',
'message_placeholder_deleted_beatmap' => '该难度已被删除,无法继续讨论',
'message_type_select' => '选择回复类型',
'reply_notice' => '按下回车以提交',
'reply_placeholder' => '在此处输入您的回复',
'require-login' => '登录以继续',
'resolved' => '已解决',
'restore' => '已修复',
'title' => '讨论',
'collapse' => [
'all-collapse' => '全部折叠',
'all-expand' => '全部展开',
],
'empty' => [
'empty' => '还没有讨论!',
'hidden' => '没有符合过滤条件的讨论。',
],
'message_hint' => [
'in_general' => '这个信息将提交到整个谱面讨论中。如果需要单独针对某处,请在开头使用时间戳 (例如: 00:12:345)。',
'in_timeline' => '需要 Mod 多处,请在每一个时间戳后写下意见并发表。',
],
'message_placeholder' => [
'general' => '在此处输入以发布到常规 (:version)',
'generalAll' => '在此处输入以发布到常规 (所有难度)',
'timeline' => '在此处输入以发布到时间线 (:version)',
],
'message_type' => [
'disqualify' => '取消提名',
'hype' => '推荐!',
'mapper_note' => '备注',
'nomination_reset' => '重置提名',
'praise' => '赞',
'problem' => '问题',
'suggestion' => '建议',
],
'mode' => [
'events' => '历史',
'general' => '常规 :scope',
'timeline' => '时间线',
'scopes' => [
'general' => '当前难度',
'generalAll' => '所有难度',
],
],
'new' => [
'timestamp' => '时间戳',
'timestamp_missing' => '在编辑模式下按 Ctrl+C 然后在您的输入框中粘贴以添加时间戳!',
'title' => '新的讨论',
],
'show' => [
'title' => '由 :mapper 制作的 :title',
],
'sort' => [
'_' => '排序:',
'created_at' => '创建时间',
'timeline' => '时间轴',
'updated_at' => '最后更新时间',
],
'stats' => [
'deleted' => '已删除',
'mapper_notes' => '备注',
'mine' => '我的',
'pending' => '未解决',
'praises' => '赞',
'resolved' => '已解决',
'total' => '所有',
],
'status-messages' => [
'approved' => '这张谱面于 :date 被 Approved !',
'graveyard' => "这张谱面自 :date 就未更新了,或许它已经被作者抛弃了 ;w;",
'loved' => '这张谱面于 :date 被 Loved !',
'ranked' => '这张谱面于 :date 被 Ranked !',
'wip' => '注意:这张谱面被作者标记为 WIP(work-in-progress)',
],
],
'hype' => [
'button' => '推荐谱面!',
'button_done' => '已经推荐!',
'confirm' => "你确定吗?这将会使用你剩下的 :n 次推荐次数并且无法撤销。",
'explanation' => '推荐这张谱面让它更容易被提名然后 ranked !',
'explanation_guest' => '登录并推荐这张谱面让它更容易被提名然后 ranked !',
'new_time' => "你将在 :new_time 后获得新的推荐次数。",
'remaining' => '你还可以推荐 :remaining 次。',
'required_text' => '推荐进度: :current/:required',
'section_title' => '推荐进度',
'title' => '推荐',
],
'feedback' => [
'button' => '留下建议',
],
'nominations' => [
'disqualification_prompt' => 'DQ 的理由?',
'disqualified_at' => '于 :time_ago 被 DQ (:reason)。',
'disqualified_no_reason' => '没有指定原因',
'disqualify' => 'Disqualify',
'incorrect_state' => '操作出错了,请刷新页面。',
'love' => '喜欢',
'love_confirm' => '喜欢这张谱面吗?',
'nominate' => '提名',
'nominate_confirm' => '提名这张谱面?',
'nominated_by' => '被 :users 提名',
'qualified' => '如果没有问题,预计将于 :date 被 Ranked 。',
'qualified_soon' => '如果没有问题,预计不久将被 Ranked 。',
'required_text' => '提名数: :current/:required',
'reset_message_deleted' => '已删除',
'title' => '提名状态',
'unresolved_issues' => '仍然有需解决的问题 。',
'reset_at' => [
'nomination_reset' => '提名于 :time_ago 被新问题 :discussion 重置。',
'disqualify' => ':time_ago 被 :user 因为新问题 :discussion (:message) 而 DQ.',
],
'reset_confirm' => [
'nomination_reset' => '你确定吗?提出新的问题会重置提名。',
],
],
'listing' => [
'search' => [
'prompt' => '输入关键字...',
'login_required' => '登录以搜索。',
'options' => '更多搜索选项',
'supporter_filter' => '按 :filters 筛选需要成为支持者',
'not-found' => '没有结果',
'not-found-quote' => '呃,什么也没有...',
'filters' => [
'general' => '常规',
'mode' => '模式',
'status' => '分类',
'genre' => '流派',
'language' => '语言',
'extra' => '额外',
'rank' => '有成绩',
'played' => '玩过',
],
'sorting' => [
'title' => '标题',
'artist' => '艺术家',
'difficulty' => '难度',
'updated' => '更新时间',
'ranked' => 'rank时间',
'rating' => '评分',
'plays' => '游玩次数',
'relevance' => '相关性',
'nominations' => '提名状态',
],
'supporter_filter_quote' => [
'_' => '按 :filters 筛选需要成为 :link',
'link_text' => '支持者',
],
],
],
'general' => [
'recommended' => '推荐难度',
'converts' => '包括转谱',
],
'mode' => [
'any' => '所有',
'osu' => 'osu!',
'taiko' => 'osu!taiko',
'fruits' => 'osu!catch',
'mania' => 'osu!mania',
],
'status' => [
'any' => '所有',
'ranked-approved' => 'Ranked & Approved',
'approved' => 'Approved',
'qualified' => 'Qualified',
'loved' => 'Loved',
'faves' => 'Favourites',
'pending' => 'Pending & WIP',
'graveyard' => 'Graveyard',
'my-maps' => '我的',
],
'genre' => [
'any' => '所有',
'unspecified' => '尚未指定',
'video-game' => '电子游戏',
'anime' => '动漫',
'rock' => '摇滚',
'pop' => '流行乐',
'other' => '其他',
'novelty' => '新奇',
'hip-hop' => '嘻哈',
'electronic' => '电子',
],
'mods' => [
'4K' => '4K',
'5K' => '5K',
'6K' => '6K',
'7K' => '7K',
'8K' => '8K',
'9K' => '9K',
'AP' => 'Auto Pliot',
'DT' => 'Double Time',
'EZ' => 'Easy Mode',
'FI' => 'Fade In',
'FL' => 'Flashlight',
'HD' => 'Hidden',
'HR' => 'Hard Rock',
'HT' => 'Half Time',
'NC' => 'Nightcore',
'NF' => 'No Fail',
'NM' => 'No mods',
'PF' => 'Perfect',
'Relax' => 'Relax',
'SD' => 'Sudden Death',
'SO' => 'Spun Out',
'TD' => 'Touch Device',
],
'language' => [
'any' => '所有',
'english' => '英语',
'chinese' => '汉语',
'french' => '法语',
'german' => '德语',
'italian' => '意大利语',
'japanese' => '日语',
'korean' => '韩语',
'spanish' => '西班牙语',
'swedish' => '瑞典语',
'instrumental' => '器乐',
'other' => '其他',
],
'played' => [
'any' => '任意',
'played' => '玩过',
'unplayed' => '没玩过',
],
'extra' => [
'video' => '有视频',
'storyboard' => '有 Storyboard',
],
'rank' => [
'any' => '任意',
'XH' => '白银 SS',
'X' => 'SS',
'SH' => '白银 S',
'S' => 'S',
'A' => 'A',
'B' => 'B',
'C' => 'C',
'D' => 'D',
],
];
|
agpl-3.0
|
InfinniPlatform/InfinniPlatform.readthedocs.org.en
|
docs/source/_docfx/api/reference/InfinniPlatform.PrintView.Writers.Pdf.PdfPrintDocumentWriter.html
|
19435
|
<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Class PdfPrintDocumentWriter
</title>
<meta name="viewport" content="width=device-width">
<meta name="title" content="Class PdfPrintDocumentWriter
">
<meta name="generator" content="docfx 2.17.7.15">
<link rel="shortcut icon" href="../../../_static/favicon.png">
<link rel="stylesheet" href="../styles/docfx.vendor.css">
<link rel="stylesheet" href="../styles/docfx.css">
<link rel="stylesheet" href="../styles/main.css">
<meta property="docfx:navrel" content="../toc.html">
<meta property="docfx:tocrel" content="toc.html">
</head>
<body data-spy="scroll" data-target="#affix">
<div id="wrapper">
<header>
<nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html">
<img id="logo" class="svg" src="../../../_static/favicon.png" alt="">
</a>
</div>
<div class="collapse navbar-collapse" id="navbar">
<form class="navbar-form navbar-right" role="search" id="search">
<div class="form-group">
<input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
</div>
</form>
</div>
</div>
</nav>
<div class="subnav navbar navbar-default">
<div class="container hide-when-search" id="breadcrumb">
<ul class="breadcrumb">
<li></li>
</ul>
</div>
</div>
</header>
<div role="main" class="container body-content hide-when-search">
<div class="sidenav hide-when-search">
<a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
<div class="sidetoggle collapse" id="sidetoggle">
<div id="sidetoc"></div>
</div>
</div>
<div class="article row grid-right">
<div class="col-md-10">
<article class="content wrap" id="_content">
<h1 id="InfinniPlatform_PrintView_Writers_Pdf_PdfPrintDocumentWriter" data-uid="InfinniPlatform.PrintView.Writers.Pdf.PdfPrintDocumentWriter">Class PdfPrintDocumentWriter
</h1>
<div class="markdown level0 summary"><p>Предоставляет метод для записи <a class="xref" href="InfinniPlatform.PrintView.PrintDocument.html">PrintDocument</a> в PDF-файл.</p>
</div>
<div class="markdown level0 conceptual"></div>
<div class="inheritance">
<h5>Inheritance</h5>
<div class="level0"><span class="xref">System.Object</span></div>
<div class="level1"><span class="xref">PdfPrintDocumentWriter</span></div>
</div>
<h6><strong>Namespace</strong>:InfinniPlatform.PrintView.Writers.Pdf</h6>
<h6><strong>Assembly</strong>:InfinniPlatform.PrintView.dll</h6>
<h5 id="InfinniPlatform_PrintView_Writers_Pdf_PdfPrintDocumentWriter_syntax">Syntax</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public class PdfPrintDocumentWriter : object, IPrintDocumentWriter</code></pre>
</div>
<h3 id="constructors">Constructors
</h3>
<span class="small pull-right mobile-hide">
<span class="divider">|</span>
<a href="https://github.com/InfinniPlatform/InfinniPlatform/new/master/apiSpec/new?filename=InfinniPlatform_PrintView_Writers_Pdf_PdfPrintDocumentWriter__ctor_InfinniPlatform_PrintView_PrintViewOptions_InfinniPlatform_PrintView_Writers_Html_HtmlPrintDocumentWriter_.md&value=---%0Auid%3A%20InfinniPlatform.PrintView.Writers.Pdf.PdfPrintDocumentWriter.%23ctor(InfinniPlatform.PrintView.PrintViewOptions%2CInfinniPlatform.PrintView.Writers.Html.HtmlPrintDocumentWriter)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a>
</span>
<span class="small pull-right mobile-hide">
<a href="https://github.com/InfinniPlatform/InfinniPlatform/blob/master/InfinniPlatform.PrintView/Writers/Pdf/PdfPrintDocumentWriter.cs/#L16">View Source</a>
</span>
<a id="InfinniPlatform_PrintView_Writers_Pdf_PdfPrintDocumentWriter__ctor_" data-uid="InfinniPlatform.PrintView.Writers.Pdf.PdfPrintDocumentWriter.#ctor*"></a>
<h4 id="InfinniPlatform_PrintView_Writers_Pdf_PdfPrintDocumentWriter__ctor_InfinniPlatform_PrintView_PrintViewOptions_InfinniPlatform_PrintView_Writers_Html_HtmlPrintDocumentWriter_" data-uid="InfinniPlatform.PrintView.Writers.Pdf.PdfPrintDocumentWriter.#ctor(InfinniPlatform.PrintView.PrintViewOptions,InfinniPlatform.PrintView.Writers.Html.HtmlPrintDocumentWriter)">PdfPrintDocumentWriter(PrintViewOptions, HtmlPrintDocumentWriter)</h4>
<div class="markdown level1 summary"><p>Конструктор.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public PdfPrintDocumentWriter(PrintViewOptions options, HtmlPrintDocumentWriter htmlWriter)</code></pre>
</div>
<h5 class="parameters">Parameters</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a class="xref" href="InfinniPlatform.PrintView.PrintViewOptions.html">PrintViewOptions</a></td>
<td><span class="parametername">options</span></td>
<td></td>
</tr>
<tr>
<td><a class="xref" href="InfinniPlatform.PrintView.Writers.Html.HtmlPrintDocumentWriter.html">HtmlPrintDocumentWriter</a></td>
<td><span class="parametername">htmlWriter</span></td>
<td></td>
</tr>
</tbody>
</table>
<h3 id="methods">Methods
</h3>
<span class="small pull-right mobile-hide">
<span class="divider">|</span>
<a href="https://github.com/InfinniPlatform/InfinniPlatform/new/master/apiSpec/new?filename=InfinniPlatform_PrintView_Writers_Pdf_PdfPrintDocumentWriter_Write_Stream_InfinniPlatform_PrintView_PrintDocument_.md&value=---%0Auid%3A%20InfinniPlatform.PrintView.Writers.Pdf.PdfPrintDocumentWriter.Write(Stream%2CInfinniPlatform.PrintView.PrintDocument)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a>
</span>
<span class="small pull-right mobile-hide">
<a href="https://github.com/InfinniPlatform/InfinniPlatform/blob/master/InfinniPlatform.PrintView/Writers/Pdf/PdfPrintDocumentWriter.cs/#L32">View Source</a>
</span>
<a id="InfinniPlatform_PrintView_Writers_Pdf_PdfPrintDocumentWriter_Write_" data-uid="InfinniPlatform.PrintView.Writers.Pdf.PdfPrintDocumentWriter.Write*"></a>
<h4 id="InfinniPlatform_PrintView_Writers_Pdf_PdfPrintDocumentWriter_Write_Stream_InfinniPlatform_PrintView_PrintDocument_" data-uid="InfinniPlatform.PrintView.Writers.Pdf.PdfPrintDocumentWriter.Write(Stream,InfinniPlatform.PrintView.PrintDocument)">Write(Stream, PrintDocument)</h4>
<div class="markdown level1 summary"><p>Записывает документ в файл.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public Task Write(Stream stream, PrintDocument document)</code></pre>
</div>
<h5 class="parameters">Parameters</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">Stream</span></td>
<td><span class="parametername">stream</span></td>
<td><p>Поток для записи в файл.</p>
</td>
</tr>
<tr>
<td><a class="xref" href="InfinniPlatform.PrintView.PrintDocument.html">PrintDocument</a></td>
<td><span class="parametername">document</span></td>
<td><p>Документ печатного представления.</p>
</td>
</tr>
</tbody>
</table>
<h5 class="returns">Returns</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">Task</span></td>
<td></td>
</tr>
</tbody>
</table>
<h3 id="extensionmethods">Extension Methods</h3>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicCollectionExtensions.html#InfinniPlatform_Dynamic_DynamicCollectionExtensions_GetItem_System_Object_System_Int32_">DynamicCollectionExtensions.GetItem(Object, Int32)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicCollectionExtensions.html#InfinniPlatform_Dynamic_DynamicCollectionExtensions_SetItem_System_Object_System_Int32_System_Object_">DynamicCollectionExtensions.SetItem(Object, Int32, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicCollectionExtensions.html#InfinniPlatform_Dynamic_DynamicCollectionExtensions_AddItem_System_Object_System_Object_">DynamicCollectionExtensions.AddItem(Object, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicCollectionExtensions.html#InfinniPlatform_Dynamic_DynamicCollectionExtensions_InsertItem_System_Object_System_Int32_System_Object_">DynamicCollectionExtensions.InsertItem(Object, Int32, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicCollectionExtensions.html#InfinniPlatform_Dynamic_DynamicCollectionExtensions_RemoveItem_System_Object_System_Object_">DynamicCollectionExtensions.RemoveItem(Object, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicCollectionExtensions.html#InfinniPlatform_Dynamic_DynamicCollectionExtensions_RemoveItemAt_System_Object_System_Int32_">DynamicCollectionExtensions.RemoveItemAt(Object, Int32)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicCollectionExtensions.html#InfinniPlatform_Dynamic_DynamicCollectionExtensions_MoveItem_System_Object_System_Object_System_Int32_">DynamicCollectionExtensions.MoveItem(Object, Object, Int32)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicObjectExtensions.html#InfinniPlatform_Dynamic_DynamicObjectExtensions_TryGetPropertyValue_System_Object_System_String_">DynamicObjectExtensions.TryGetPropertyValue(Object, String)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicObjectExtensions.html#InfinniPlatform_Dynamic_DynamicObjectExtensions_TrySetPropertyValue_System_Object_System_String_System_Object_">DynamicObjectExtensions.TrySetPropertyValue(Object, String, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicObjectExtensions.html#InfinniPlatform_Dynamic_DynamicObjectExtensions_TryGetPropertyValueByPath_System_Object_System_String_">DynamicObjectExtensions.TryGetPropertyValueByPath(Object, String)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.DynamicObjectExtensions.html#InfinniPlatform_Dynamic_DynamicObjectExtensions_TrySetPropertyValueByPath_System_Object_System_String_System_Object_">DynamicObjectExtensions.TrySetPropertyValueByPath(Object, String, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_IsInstanceOfType_System_Object_Type_">ReflectionExtensions.IsInstanceOfType(Object, Type)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_GetMemberValue_System_Object_System_String_">ReflectionExtensions.GetMemberValue(Object, String)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_SetMemberValue_System_Object_System_String_System_Object_">ReflectionExtensions.SetMemberValue(Object, String, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_InvokeMember_System_Object_System_String_System_Object___System_Object__Type___">ReflectionExtensions.InvokeMember(Object, String, Object[], out Object, Type[])</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_GetFieldValue_System_Object_FieldInfo_">ReflectionExtensions.GetFieldValue(Object, FieldInfo)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_SetFieldValue_System_Object_FieldInfo_System_Object_">ReflectionExtensions.SetFieldValue(Object, FieldInfo, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_GetPropertyValue_System_Object_PropertyInfo_">ReflectionExtensions.GetPropertyValue(Object, PropertyInfo)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_SetPropertyValue_System_Object_PropertyInfo_System_Object_">ReflectionExtensions.SetPropertyValue(Object, PropertyInfo, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_GetMethodDelegate_System_Object_MethodInfo_">ReflectionExtensions.GetMethodDelegate(Object, MethodInfo)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_GetEventDelegate_System_Object_EventInfo_">ReflectionExtensions.GetEventDelegate(Object, EventInfo)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Dynamic.ReflectionExtensions.html#InfinniPlatform_Dynamic_ReflectionExtensions_SetEventDelegate_System_Object_EventInfo_System_Object_">ReflectionExtensions.SetEventDelegate(Object, EventInfo, Object)</a>
</div>
<div>
<a class="xref" href="InfinniPlatform.Extensions.CommonExtensions.html#InfinniPlatform_Extensions_CommonExtensions_ExecuteSilent__1___0_Action___0__">CommonExtensions.ExecuteSilent<T>(T, Action<T>)</a>
</div>
</article>
</div>
<div class="hidden-sm col-md-2" role="complementary">
<div class="sideaffix">
<div class="contribution">
<ul class="nav">
<li>
<a href="https://github.com/InfinniPlatform/InfinniPlatform/new/master/apiSpec/new?filename=InfinniPlatform_PrintView_Writers_Pdf_PdfPrintDocumentWriter.md&value=---%0Auid%3A%20InfinniPlatform.PrintView.Writers.Pdf.PdfPrintDocumentWriter%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A" class="contribution-link">Improve this Doc</a>
</li>
<li>
<a href="https://github.com/InfinniPlatform/InfinniPlatform/blob/master/InfinniPlatform.PrintView/Writers/Pdf/PdfPrintDocumentWriter.cs/#L11" class="contribution-link">View Source</a>
</li>
</ul>
</div>
<nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
<!-- <p><a class="back-to-top" href="#top">Back to top</a><p> -->
</nav>
</div>
</div>
</div>
</div>
<footer>
<div class="grad-bottom"></div>
<div class="footer">
<div class="container">
<span class="pull-right">
<a href="#top">Back to top</a>
</span>
© Copyright Infinnity Solutions Ltd, 2010–2017.
</div>
</div>
</footer>
</div>
<script type="text/javascript" src="../styles/docfx.vendor.js"></script>
<script type="text/javascript" src="../styles/docfx.js"></script>
<script type="text/javascript" src="../styles/main.js"></script>
</body>
</html>
|
agpl-3.0
|
defudger/nebula
|
code/foundation/iterator/algorithm/move_n.h
|
2531
|
/*--!>
This file is part of Nebula, a multi-purpose library mainly written in C++.
Copyright 2015-2016 outshined (outshined@riseup.net)
(PGP: 0x8A80C12396A4836F82A93FA79CA3D0F7E8FBCED6)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------<!--*/
#ifndef NIC_4C1FF774F62D18CC_NIC
#define NIC_4C1FF774F62D18CC_NIC
#include "../traits.h"
#include "../../type_traits.h"
#include "../../meta.h"
#include "../../mem.h"
#include "../../move.h"
namespace nebula { namespace foundation { namespace iterator {
/** @ingroup Foundation
* @{
*/
//------------------------------------------------------------------------------
template <class I, class O>
struct move_n_impl
{
private:
using I_T = typename iterator_value<I>::type;
using O_T = typename iterator_value<O>::type;
template <class I_, class S, class O_>
inline static O_ apply_(I_ first, const S &n, O_ dest, false_type)
{
if(n > 0) {
*dest++ = *first++;
for(S i = 1; i < n; ++i)
*dest++ = foundation::move(*first++);
}
return dest;
}
template <class I_, class O_>
inline static O_ apply_(I_ first, const size_t n, O_ dest, true_type)
{
foundation::memmove(dest, first, n * sizeof(O_T));
return dest + n;
}
public:
template <class S>
inline static O apply(I first, const S &n, O dest) {
return apply_(first, n, dest,
meta::_and<
is_pointer<I>,
is_pointer<O>,
is_pod<I_T>,
is_same<I_T, O_T>>());
}
};
//------------------------------------------------------------------------------
template <class I, class O, class Size>
inline O move_n(I first, const Size &n, O dest)
{
return move_n_impl<I, O>::apply(first, n, dest);
}
/** @} */
}}} // namespaces
#endif // NIC_4C1FF774F62D18CC_NIC
|
agpl-3.0
|
gale320/sync-engine
|
inbox/crispin.py
|
34132
|
""" IMAPClient wrapper for the Nilas Sync Engine. """
import contextlib
import re
import time
import imaplib
import imapclient
# Even though RFC 2060 says that the date component must have two characters
# (either two digits or space+digit), it seems that some IMAP servers only
# return one digit. Fun times.
imaplib.InternalDate = re.compile(
r'.*INTERNALDATE "'
r'(?P<day>[ 0123]?[0-9])-' # insert that `?` to make first digit optional
r'(?P<mon>[A-Z][a-z][a-z])-'
r'(?P<year>[0-9][0-9][0-9][0-9])'
r' (?P<hour>[0-9][0-9]):'
r'(?P<min>[0-9][0-9]):'
r'(?P<sec>[0-9][0-9])'
r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
r'"')
import functools
import threading
from email.parser import HeaderParser
from collections import namedtuple, defaultdict
import gevent
from gevent import socket
from gevent.lock import BoundedSemaphore
from gevent.queue import Queue
from inbox.util.concurrency import retry
from inbox.util.itert import chunk
from inbox.util.misc import or_none
from inbox.basicauth import GmailSettingError
from inbox.models.session import session_scope
from inbox.models.account import Account
from nylas.logging import get_logger
log = get_logger()
__all__ = ['CrispinClient', 'GmailCrispinClient']
# Unify flags API across IMAP and Gmail
Flags = namedtuple('Flags', 'flags')
# Flags includes labels on Gmail because Gmail doesn't use \Draft.
GmailFlags = namedtuple('GmailFlags', 'flags labels')
GMetadata = namedtuple('GMetadata', 'g_msgid g_thrid size')
RawMessage = namedtuple(
'RawImapMessage',
'uid internaldate flags body g_thrid g_msgid g_labels')
RawFolder = namedtuple('RawFolder', 'display_name role')
# Lazily-initialized map of account ids to lock objects.
# This prevents multiple greenlets from concurrently creating duplicate
# connection pools for a given account.
_lock_map = defaultdict(threading.Lock)
CONN_DISCARD_EXC_CLASSES = (socket.error, imaplib.IMAP4.error)
class FolderMissingError(Exception):
pass
def _get_connection_pool(account_id, pool_size, pool_map, readonly):
with _lock_map[account_id]:
if account_id not in pool_map:
pool_map[account_id] = CrispinConnectionPool(
account_id, num_connections=pool_size, readonly=readonly)
return pool_map[account_id]
def connection_pool(account_id, pool_size=3, pool_map=dict()):
""" Per-account crispin connection pool.
Use like this:
with crispin.connection_pool(account_id).get() as crispin_client:
# your code here
pass
Note that the returned CrispinClient could have ANY folder selected, or
none at all! It's up to the calling code to handle folder sessions
properly. We don't reset to a certain select state because it's slow.
"""
return _get_connection_pool(account_id, pool_size, pool_map, True)
def writable_connection_pool(account_id, pool_size=1, pool_map=dict()):
""" Per-account crispin connection pool, with *read-write* connections.
Use like this:
conn_pool = crispin.writable_connection_pool(account_id)
with conn_pool.get() as crispin_client:
# your code here
pass
"""
return _get_connection_pool(account_id, pool_size, pool_map, False)
class CrispinConnectionPool(object):
"""
Connection pool for Crispin clients.
Connections in a pool are specific to an IMAPAccount.
Parameters
----------
account_id : int
Which IMAPAccount to open up a connection to.
num_connections : int
How many connections in the pool.
readonly : bool
Is the connection to the IMAP server read-only?
"""
def __init__(self, account_id, num_connections, readonly):
log.info('Creating Crispin connection pool for account {} with {} '
'connections'.format(account_id, num_connections))
self.account_id = account_id
self.readonly = readonly
self._queue = Queue(num_connections, items=num_connections * [None])
self._sem = BoundedSemaphore(num_connections)
self._set_account_info()
@contextlib.contextmanager
def get(self):
""" Get a connection from the pool, or instantiate a new one if needed.
If `num_connections` connections are already in use, block until one is
available.
"""
# A gevent semaphore is granted in the order that greenlets tried to
# acquire it, so we use a semaphore here to prevent potential
# starvation of greenlets if there is high contention for the pool.
# The queue implementation does not have that property; having
# greenlets simply block on self._queue.get(block=True) could cause
# individual greenlets to block for arbitrarily long.
self._sem.acquire()
client = self._queue.get()
try:
if client is None:
client = self._new_connection()
yield client
except CONN_DISCARD_EXC_CLASSES as exc:
# Discard the connection on socket or IMAP errors. Technically this
# isn't always necessary, since if you got e.g. a FETCH failure you
# could reuse the same connection. But for now it's the simplest
# thing to do.
log.info('IMAP connection error; discarding connection',
exc_info=True)
if client is not None:
try:
client.logout()
except:
log.error('Error on IMAP logout', exc_info=True)
client = None
raise exc
except:
raise
finally:
self._queue.put(client)
self._sem.release()
def _set_account_info(self):
with session_scope() as db_session:
account = db_session.query(Account).get(self.account_id)
self.sync_state = account.sync_state
self.provider_info = account.provider_info
self.email_address = account.email_address
self.auth_handler = account.auth_handler
if account.provider == 'gmail':
self.client_cls = GmailCrispinClient
else:
self.client_cls = CrispinClient
def _new_raw_connection(self):
"""Returns a new, authenticated IMAPClient instance for the account."""
with session_scope() as db_session:
account = db_session.query(Account).get(self.account_id)
return self.auth_handler.connect_account(account)
def _new_connection(self):
conn = self._new_raw_connection()
return self.client_cls(self.account_id, self.provider_info,
self.email_address, conn,
readonly=self.readonly)
def _exc_callback():
log.info('Connection broken with error; retrying with new connection',
exc_info=True)
gevent.sleep(5)
retry_crispin = functools.partial(
retry, retry_classes=CONN_DISCARD_EXC_CLASSES, exc_callback=_exc_callback)
class CrispinClient(object):
"""
Generic IMAP client wrapper.
One thing to note about crispin clients is that *all* calls operate on
the currently selected folder.
Crispin will NEVER implicitly select a folder for you.
This is very important! IMAP only guarantees that folder message UIDs
are valid for a "session", which is defined as from the time you
SELECT a folder until the connection is closed or another folder is
selected.
Crispin clients *always* return long ints rather than strings for number
data types, such as message UIDs, Google message IDs, and Google thread
IDs.
All inputs are coerced to strings before being passed off to the IMAPClient
connection.
You should really be interfacing with this class via a connection pool,
see `connection_pool()`.
Parameters
----------
account_id : int
Database id of the associated IMAPAccount.
conn : IMAPClient
Open IMAP connection (should be already authed).
readonly : bool
Whether or not to open IMAP connections as readonly.
"""
def __init__(self, account_id, provider_info, email_address, conn,
readonly=True):
self.account_id = account_id
self.provider_info = provider_info
self.email_address = email_address
# IMAP isn't stateless :(
self.selected_folder = None
self._folder_names = None
self.conn = conn
self.readonly = readonly
def _fetch_folder_list(self):
""" NOTE: XLIST is deprecated, so we just use LIST.
An example response with some other flags:
* LIST (\HasNoChildren) "/" "INBOX"
* LIST (\Noselect \HasChildren) "/" "[Gmail]"
* LIST (\HasNoChildren \All) "/" "[Gmail]/All Mail"
* LIST (\HasNoChildren \Drafts) "/" "[Gmail]/Drafts"
* LIST (\HasNoChildren \Important) "/" "[Gmail]/Important"
* LIST (\HasNoChildren \Sent) "/" "[Gmail]/Sent Mail"
* LIST (\HasNoChildren \Junk) "/" "[Gmail]/Spam"
* LIST (\HasNoChildren \Flagged) "/" "[Gmail]/Starred"
* LIST (\HasNoChildren \Trash) "/" "[Gmail]/Trash"
IMAPClient parses this response into a list of
(flags, delimiter, name) tuples.
"""
return self.conn.list_folders()
def select_folder(self, folder, uidvalidity_cb):
""" Selects a given folder.
Makes sure to set the 'selected_folder' attribute to a
(folder_name, select_info) pair.
Selecting a folder indicates the start of an IMAP session. IMAP UIDs
are only guaranteed valid for sessions, so the caller must provide a
callback that checks UID validity.
Starts a new session even if `folder` is already selected, since
this does things like e.g. makes sure we're not getting
cached/out-of-date values for HIGHESTMODSEQ from the IMAP server.
"""
try:
select_info = self.conn.select_folder(
folder, readonly=self.readonly)
except imapclient.IMAPClient.Error as e:
# Specifically point out folders that come back as missing by
# checking for Yahoo / Gmail / Outlook (Hotmail) specific errors:
if '[NONEXISTENT] Unknown Mailbox:' in e.message or \
'does not exist' in e.message or \
"doesn't exist" in e.message:
raise FolderMissingError(folder)
# We can't assume that all errors here are caused by the folder
# being deleted, as other connection errors could occur - but we
# want to make sure we keep track of different providers'
# "nonexistent" messages, so log this event.
log.error("IMAPClient error selecting folder. May be deleted",
error=str(e))
raise
select_info['UIDVALIDITY'] = long(select_info['UIDVALIDITY'])
self.selected_folder = (folder, select_info)
# Don't propagate cached information from previous session
self._folder_names = None
return uidvalidity_cb(self.account_id, folder, select_info)
@property
def selected_folder_name(self):
return or_none(self.selected_folder, lambda f: f[0])
@property
def selected_folder_info(self):
return or_none(self.selected_folder, lambda f: f[1])
@property
def selected_uidvalidity(self):
return or_none(self.selected_folder_info, lambda i: i['UIDVALIDITY'])
@property
def selected_uidnext(self):
return or_none(self.selected_folder_info, lambda i: i.get('UIDNEXT'))
def sync_folders(self):
"""
List of folders to sync.
In generic IMAP, the 'INBOX' folder is required.
Returns
-------
list
Folders to sync (as strings).
"""
to_sync = []
have_folders = self.folder_names()
assert 'inbox' in have_folders, \
"Missing required 'inbox' folder for account_id: {}".\
format(self.account_id)
for names in have_folders.itervalues():
to_sync.extend(names)
return to_sync
def folder_names(self, force_resync=False):
"""
Return the folder names for the account as a mapping from
recognized role: list of folder names,
for example: 'sent': ['Sent Items', 'Sent'].
The list of recognized folder roles is in:
inbox/models/constants.py
Folders that do not belong to a recognized role are mapped to
None, for example: None: ['MyFolder', 'OtherFolder'].
The mapping is also cached in self._folder_names
Parameters:
-----------
force_resync: boolean
Return the cached mapping or return a refreshed mapping
(after refetching from the remote).
"""
if force_resync or self._folder_names is None:
self._folder_names = defaultdict(list)
raw_folders = self.folders()
for f in raw_folders:
self._folder_names[f.role].append(f.display_name)
return self._folder_names
def folders(self):
"""
Fetch the list of folders for the account from the remote, return as a
list of RawFolder objects.
NOTE:
Always fetches the list of folders from the remote.
"""
raw_folders = []
folders = self._fetch_folder_list()
for flags, delimiter, name in folders:
if u'\\Noselect' in flags or u'\\NoSelect' in flags \
or u'\\NonExistent' in flags:
# Special folders that can't contain messages
continue
raw_folder = self._process_folder(name, flags)
raw_folders.append(raw_folder)
return raw_folders
def _process_folder(self, display_name, flags):
"""
Determine the role for the remote folder from its `name` and `flags`.
Returns
-------
RawFolder representing the folder
"""
# TODO[[k]: Important/ Starred for generic IMAP?
# Different providers have different names for folders, here
# we have a default map for common name mapping, additional
# mappings can be provided via the provider configuration file
default_folder_map = {
'inbox': 'inbox',
'drafts': 'drafts',
'draft': 'drafts',
'junk': 'spam',
'spam': 'spam',
'archive': 'archive',
'sent': 'sent',
'trash': 'trash'}
# Additionally we provide a custom mapping for providers that
# don't fit into the defaults.
folder_map = self.provider_info.get('folder_map', {})
# Some providers also provide flags to determine common folders
# Here we read these flags and apply the mapping
flag_map = {'\\Trash': 'trash', '\\Sent': 'sent', '\\Drafts': 'drafts',
'\\Junk': 'spam', '\\Inbox': 'inbox', '\\Spam': 'spam'}
role = default_folder_map.get(display_name.lower())
if not role:
role = folder_map.get(display_name)
if not role:
for flag in flags:
role = flag_map.get(flag)
return RawFolder(display_name=display_name, role=role)
def create_folder(self, name):
self.conn.create_folder(name)
def condstore_supported(self):
# Technically QRESYNC implies CONDSTORE, although this is unlikely to
# matter in practice.
capabilities = self.conn.capabilities()
return 'CONDSTORE' in capabilities or 'QRESYNC' in capabilities
def idle_supported(self):
return 'IDLE' in self.conn.capabilities()
def search_uids(self, criteria):
"""
Find UIDs in this folder matching the criteria. See
http://tools.ietf.org/html/rfc3501.html#section-6.4.4 for valid
criteria.
"""
return sorted([long(uid) for uid in self.conn.search(criteria)])
def all_uids(self):
""" Fetch all UIDs associated with the currently selected folder.
Returns
-------
list
UIDs as integers sorted in ascending order.
"""
# Note that this list may include items which have been marked for
# deletion with the \Deleted flag, but not yet actually removed via
# an EXPUNGE command. I choose to include them here since most clients
# will still display them (sometimes with a strikethrough). If showing
# these is a problem, we can either switch back to searching for
# 'UNDELETED' or doing a fetch for ['UID', 'FLAGS'] and filtering.
try:
t = time.time()
fetch_result = self.conn.search(['ALL'])
except imaplib.IMAP4.error as e:
if e.message.find('UID SEARCH wrong arguments passed') >= 0:
# Mail2World servers fail for the otherwise valid command
# 'UID SEARCH ALL' but strangely pass for 'UID SEARCH ALL UID'
log.debug("Getting UIDs failed when using 'UID SEARCH "
"ALL'. Switching to alternative 'UID SEARCH "
"ALL UID", exception=e)
t = time.time()
fetch_result = self.conn.search(['ALL', 'UID'])
else:
raise
elapsed = time.time() - t
log.debug('Requested all UIDs',
selected_folder=self.selected_folder_name,
search_time=elapsed,
total_uids=len(fetch_result))
return sorted([long(uid) for uid in fetch_result])
def uids(self, uids):
uid_set = set(uids)
messages = []
raw_messages = {}
for uid in uid_set:
try:
raw_messages.update(self.conn.fetch(
uid, ['BODY.PEEK[]', 'INTERNALDATE', 'FLAGS']))
except imapclient.IMAPClient.Error as e:
if ('[UNAVAILABLE] UID FETCH Server error '
'while fetching messages') in str(e):
log.info('Got an exception while requesting an UID',
uid=uid, error=e,
logstash_tag='imap_download_exception')
continue
else:
log.info(('Got an unhandled exception while '
'requesting an UID'),
uid=uid, error=e,
logstash_tag='imap_download_exception')
raise
for uid in sorted(raw_messages.iterkeys(), key=long):
# Skip handling unsolicited FETCH responses
if uid not in uid_set:
continue
msg = raw_messages[uid]
if msg.keys() == ['SEQ']:
log.error('No data returned for UID, skipping', uid=uid)
continue
messages.append(RawMessage(uid=long(uid),
internaldate=msg['INTERNALDATE'],
flags=msg['FLAGS'],
body=msg['BODY[]'],
# TODO: use data structure that isn't
# Gmail-specific
g_thrid=None, g_msgid=None,
g_labels=None))
return messages
def flags(self, uids):
if len(uids) > 100:
# Some backends abort the connection if you give them a really
# long sequence set of individual UIDs, so instead fetch flags for
# all UIDs greater than or equal to min(uids).
seqset = '{}:*'.format(min(uids))
else:
seqset = uids
data = self.conn.fetch(seqset, ['FLAGS'])
uid_set = set(uids)
return {uid: Flags(ret['FLAGS'])
for uid, ret in data.items() if uid in uid_set}
def delete_uids(self, uids):
uids = [str(u) for u in uids]
self.conn.delete_messages(uids)
self.conn.expunge()
def set_starred(self, uids, starred):
if starred:
self.conn.add_flags(uids, ['\\Flagged'])
else:
self.conn.remove_flags(uids, ['\\Flagged'])
def set_unread(self, uids, unread):
uids = [str(u) for u in uids]
if unread:
self.conn.remove_flags(uids, ['\\Seen'])
else:
self.conn.add_flags(uids, ['\\Seen'])
def save_draft(self, message, date=None):
assert self.selected_folder_name in self.folder_names()['drafts'], \
'Must select a drafts folder first ({0})'.\
format(self.selected_folder_name)
self.conn.append(self.selected_folder_name, message, ['\\Draft',
'\\Seen'], date)
def create_message(self, message, date=None):
"""
Create a message on the server. Only used to fix server-side bugs,
like iCloud not saving Sent messages.
"""
assert self.selected_folder_name in self.folder_names()['sent'], \
'Must select sent folder first ({0})'.\
format(self.selected_folder_name)
return self.conn.append(self.selected_folder_name, message, [], date)
def fetch_headers(self, uids):
"""
Fetch headers for the given uids. Chunked because certain providers
fail with 'Command line too large' if you feed them too many uids at
once.
"""
headers = {}
for uid_chunk in chunk(uids, 100):
headers.update(self.conn.fetch(
uid_chunk, ['BODY.PEEK[HEADER]']))
return headers
def find_by_header(self, header_name, header_value):
"""Find all uids in the selected folder with the given header value."""
all_uids = self.all_uids()
# It would be nice to just search by header too, but some backends
# don't support that, at least not if you want to search by X-INBOX-ID
# header. So fetch the header for each draft and see if we
# can find one that matches.
# TODO(emfree): are there other ways we can narrow the result set a
# priori (by subject or date, etc.)
matching_draft_headers = self.fetch_headers(all_uids)
results = []
for uid, response in matching_draft_headers.iteritems():
headers = response['BODY[HEADER]']
parser = HeaderParser()
header = parser.parsestr(headers).get(header_name)
if header == header_value:
results.append(uid)
return results
def delete_draft(self, inbox_uid, message_id_header):
"""
Delete a draft, as identified either by its X-Inbox-Id or by its
Message-Id header. We first delete the message from the Drafts folder,
and then also delete it from the Trash folder if necessary.
"""
drafts_folder_name = self.folder_names()['drafts'][0]
self.conn.select_folder(drafts_folder_name)
self._delete_message(inbox_uid, message_id_header)
trash_folder_name = self.folder_names()['trash'][0]
self.conn.select_folder(trash_folder_name)
self._delete_message(inbox_uid, message_id_header)
def _delete_message(self, inbox_uid, message_id_header):
"""
Delete a message from the selected folder, using either the X-Inbox-Id
header or the Message-Id header to locate it. Does nothing if no
matching messages are found, or if more than one matching message is
found.
"""
assert inbox_uid or message_id_header, 'Need at least one header'
if inbox_uid:
matching_uids = self.find_by_header('X-Inbox-Id', inbox_uid)
else:
matching_uids = self.find_by_header('Message-Id',
message_id_header)
if not matching_uids:
log.error('No remote messages found to delete',
inbox_uid=inbox_uid,
message_id_header=message_id_header)
return
if len(matching_uids) > 1:
log.error('Multiple remote messages found to delete',
inbox_uid=inbox_uid,
message_id_header=message_id_header,
uids=matching_uids)
return
self.conn.delete_messages(matching_uids)
self.conn.expunge()
def logout(self):
self.conn.logout()
def idle(self, timeout):
"""Idle for up to `timeout` seconds. Make sure we take the connection
back out of idle mode so that we can reuse this connection in another
context."""
log.info('Idling', timeout=timeout)
self.conn.idle()
try:
with self._restore_timeout():
r = self.conn.idle_check(timeout)
except:
self.conn.idle_done()
raise
self.conn.idle_done()
return r
@contextlib.contextmanager
def _restore_timeout(self):
# IMAPClient.idle_check() calls setblocking(1) on the underlying
# socket, erasing any previously set timeout. So make sure to restore
# the timeout.
sock = getattr(self.conn._imap, 'sslobj', self.conn._imap.sock)
timeout = sock.gettimeout()
try:
yield
finally:
sock.settimeout(timeout)
def condstore_changed_flags(self, modseq):
data = self.conn.fetch('1:*', ['FLAGS'],
modifiers=['CHANGEDSINCE {}'.format(modseq)])
return {uid: Flags(ret['FLAGS']) for uid, ret in data.items()}
class GmailCrispinClient(CrispinClient):
PROVIDER = 'gmail'
def sync_folders(self):
"""
Gmail-specific list of folders to sync.
In Gmail, every message is in `All Mail`, with the exception of
messages in the Trash and Spam folders. So we only sync the `All Mail`,
Trash and Spam folders.
Returns
-------
list
Folders to sync (as strings).
"""
present_folders = self.folder_names()
if 'all' not in present_folders:
raise GmailSettingError(
"Account {} ({}) is missing the 'All Mail' folder. This is "
"probably due to 'Show in IMAP' being disabled. "
"Please enable at "
"https://mail.google.com/mail/#settings/labels"
.format(self.account_id, self.email_address))
# If the account has Trash, Spam folders, sync those too.
to_sync = []
for folder in ['all', 'trash', 'spam']:
if folder in present_folders:
to_sync.append(present_folders[folder][0])
return to_sync
def flags(self, uids):
"""
Gmail-specific flags.
Returns
-------
dict
Mapping of `uid` : GmailFlags.
"""
data = self.conn.fetch(uids, ['FLAGS', 'X-GM-LABELS'])
uid_set = set(uids)
return {uid: GmailFlags(ret['FLAGS'], ret['X-GM-LABELS'])
for uid, ret in data.items() if uid in uid_set}
def condstore_changed_flags(self, modseq):
data = self.conn.fetch('1:*', ['FLAGS', 'X-GM-LABELS'],
modifiers=['CHANGEDSINCE {}'.format(modseq)])
results = {}
for uid, ret in data.items():
if 'FLAGS' not in ret or 'X-GM-LABELS' not in ret:
# We might have gotten an unsolicited fetch response that
# doesn't have all the data we asked for -- if so, explicitly
# fetch flags and labels for that UID.
log.info('Got incomplete response in flags fetch', uid=uid,
ret=str(ret))
data_for_uid = self.conn.fetch(uid, ['FLAGS', 'X-GM-LABELS'])
if not data_for_uid:
continue
ret = data_for_uid[uid]
results[uid] = GmailFlags(ret['FLAGS'], ret['X-GM-LABELS'])
return results
def g_msgids(self, uids):
"""
X-GM-MSGIDs for the given UIDs.
Returns
-------
dict
Mapping of `uid` (long) : `g_msgid` (long)
"""
data = self.conn.fetch(uids, ['X-GM-MSGID'])
uid_set = set(uids)
return {uid: ret['X-GM-MSGID']
for uid, ret in data.items() if uid in uid_set}
def folder_names(self, force_resync=False):
"""
Return the folder names ( == label names for Gmail) for the account
as a mapping from recognized role: list of folder names in the
role, for example: 'sent': ['Sent Items', 'Sent'].
The list of recognized categories is in:
inbox/models/constants.py
Folders that do not belong to a recognized role are mapped to None, for
example: None: ['MyFolder', 'OtherFolder'].
The mapping is also cached in self._folder_names
Parameters:
-----------
force_resync: boolean
Return the cached mapping or return a refreshed mapping
(after refetching from the remote).
"""
if force_resync or self._folder_names is None:
self._folder_names = defaultdict(list)
raw_folders = self.folders()
for f in raw_folders:
self._folder_names[f.role].append(f.display_name)
return self._folder_names
def folders(self):
"""
Fetch the list of folders for the account from the remote, return as a
list of RawFolder objects.
NOTE:
Always fetches the list of folders from the remote.
"""
raw_folders = []
folders = self._fetch_folder_list()
for flags, delimiter, name in folders:
if u'\\Noselect' in flags or u'\\NoSelect' in flags \
or u'\\NonExistent' in flags:
# Special folders that can't contain messages, usually
# just '[Gmail]'
continue
raw_folder = self._process_folder(name, flags)
raw_folders.append(raw_folder)
return raw_folders
def _process_folder(self, display_name, flags):
"""
Determine the canonical_name for the remote folder from its `name` and
`flags`.
Returns
-------
RawFolder representing the folder
"""
flag_map = {'\\Drafts': 'drafts', '\\Important': 'important',
'\\Sent': 'sent', '\\Junk': 'spam', '\\Flagged': 'starred',
'\\Trash': 'trash'}
role = None
if '\\All' in flags:
role = 'all'
elif display_name.lower() == 'inbox':
# Special-case the display name here. In Gmail, the inbox
# folder shows up in the folder list as 'INBOX', and in sync as
# the label '\\Inbox'. We're just always going to give it the
# display name 'Inbox'.
role = 'inbox'
display_name = 'Inbox'
else:
for flag in flags:
if flag in flag_map:
role = flag_map[flag]
return RawFolder(display_name=display_name, role=role)
def uids(self, uids):
raw_messages = self.conn.fetch(uids, ['BODY.PEEK[]', 'INTERNALDATE',
'FLAGS', 'X-GM-THRID',
'X-GM-MSGID', 'X-GM-LABELS'])
messages = []
uid_set = set(uids)
for uid in sorted(raw_messages.iterkeys(), key=long):
# Skip handling unsolicited FETCH responses
if uid not in uid_set:
continue
msg = raw_messages[uid]
messages.append(RawMessage(uid=long(uid),
internaldate=msg['INTERNALDATE'],
flags=msg['FLAGS'],
body=msg['BODY[]'],
g_thrid=long(msg['X-GM-THRID']),
g_msgid=long(msg['X-GM-MSGID']),
g_labels=msg['X-GM-LABELS']))
return messages
def g_metadata(self, uids):
"""
Download Gmail MSGIDs, THRIDs, and message sizes for the given uids.
Parameters
----------
uids : list
UIDs to fetch data for. Must be from the selected folder.
Returns
-------
dict
uid: GMetadata(msgid, thrid, size)
"""
# Super long sets of uids may fail with BAD ['Could not parse command']
# In that case, just fetch metadata for /all/ uids.
seqset = uids if len(uids) < 1e6 else '1:*'
data = self.conn.fetch(seqset, ['X-GM-MSGID', 'X-GM-THRID',
'RFC822.SIZE'])
uid_set = set(uids)
return {uid: GMetadata(ret['X-GM-MSGID'], ret['X-GM-THRID'],
ret['RFC822.SIZE'])
for uid, ret in data.items() if uid in uid_set}
def expand_thread(self, g_thrid):
"""
Find all message UIDs in the selected folder with X-GM-THRID equal to
g_thrid.
Returns
-------
list
"""
uids = [long(uid) for uid in
self.conn.search('X-GM-THRID {}'.format(g_thrid))]
# UIDs ascend over time; return in order most-recent first
return sorted(uids, reverse=True)
def find_by_header(self, header_name, header_value):
criteria = ['HEADER {} {}'.format(header_name, header_value)]
return self.conn.search(criteria)
|
agpl-3.0
|
zackw/pelican
|
pelican/tests/output/basic/category/bar.html
|
2980
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>A Pelican Blog - bar</title>
<link rel="stylesheet" href="/theme/css/main.css" />
<link href="/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="A Pelican Blog Atom Feed" />
</head>
<body id="index" class="home">
<header id="banner" class="body">
<h1><a href="/">A Pelican Blog </a></h1>
<nav><ul>
<li><a href="/tag/oh.html">Oh Oh Oh</a></li>
<li><a href="/override/">Override url/save_as</a></li>
<li><a href="/pages/this-is-a-test-page.html">This is a test page</a></li>
<li class="active"><a href="/category/bar.html">bar</a></li>
<li><a href="/category/cat1.html">cat1</a></li>
<li><a href="/category/misc.html">misc</a></li>
<li><a href="/category/yeah.html">yeah</a></li>
</ul></nav>
</header><!-- /#banner -->
<aside id="featured" class="body">
<article>
<h1 class="entry-title"><a href="/oh-yeah.html">Oh yeah !</a></h1>
<footer class="post-info">
<abbr class="published" title="2010-10-20T10:14:00+00:00">
Published: Wed 20 October 2010
</abbr>
<address class="vcard author">
By <a class="url fn" href="/author/alexis-metaireau.html">Alexis Métaireau</a>
</address>
<p>In <a href="/category/bar.html">bar</a>.</p>
<p>tags: <a href="/tag/oh.html">oh</a> <a href="/tag/bar.html">bar</a> <a href="/tag/yeah.html">yeah</a> </p>
</footer><!-- /.post-info --><div class="section" id="why-not">
<h2>Why not ?</h2>
<p>After all, why not ? It's pretty simple to do it, and it will allow me to write my blogposts in rst !
YEAH !</p>
<img alt="alternate text" src="|filename|/pictures/Sushi.jpg" style="width: 600px; height: 450px;" />
</div>
</article>
</aside><!-- /#featured -->
<section id="extras" class="body">
<div class="social">
<h2>social</h2>
<ul>
<li><a href="/feeds/all.atom.xml" type="application/atom+xml" rel="alternate">atom feed</a></li>
</ul>
</div><!-- /.social -->
</section><!-- /#extras -->
<footer id="contentinfo" class="body">
<address id="about" class="vcard body">
Proudly powered by <a href="http://getpelican.com/">Pelican</a>, which takes great advantage of <a href="http://python.org">Python</a>.
</address><!-- /#about -->
<p>The theme is by <a href="http://coding.smashingmagazine.com/2009/08/04/designing-a-html-5-layout-from-scratch/">Smashing Magazine</a>, thanks!</p>
</footer><!-- /#contentinfo -->
</body>
</html>
|
agpl-3.0
|
camsys/ridepilot
|
app/models/trip_purpose.rb
|
441
|
class TripPurpose < ApplicationRecord
acts_as_paranoid # soft delete
has_paper_trail
validates :name, presence: true, uniqueness: { :case_sensitive => false, conditions: -> { where(deleted_at: nil) } }
def self.by_provider(provider)
hidden_ids = HiddenLookupTableValue.hidden_ids self.table_name, provider.try(:id)
where.not(id: hidden_ids)
end
def as_api_json
{
name: name,
code: id
}
end
end
|
agpl-3.0
|
kaltura/KalturaGeneratedAPIClientsCsharp
|
KalturaClient/Types/AccessControlContextTypeHolder.cs
|
2292
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
using System;
using System.Xml;
using System.Collections.Generic;
using Kaltura.Enums;
using Kaltura.Request;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Kaltura.Types
{
public class AccessControlContextTypeHolder : ContextTypeHolder
{
#region Constants
#endregion
#region Private Fields
#endregion
#region Properties
#endregion
#region CTor
public AccessControlContextTypeHolder()
{
}
public AccessControlContextTypeHolder(JToken node) : base(node)
{
}
#endregion
#region Methods
public override Params ToParams(bool includeObjectType = true)
{
Params kparams = base.ToParams(includeObjectType);
if (includeObjectType)
kparams.AddReplace("objectType", "KalturaAccessControlContextTypeHolder");
return kparams;
}
protected override string getPropertyName(string apiName)
{
switch(apiName)
{
default:
return base.getPropertyName(apiName);
}
}
#endregion
}
}
|
agpl-3.0
|
Connexions/simulations
|
common/math/vector2.js
|
731
|
define(function (require) {
'use strict';
var Vector2 = require('vector2-node');
/**
* Returns a new unit vector in the direction specified by the angle
*/
Vector2.fromAngle = function(angle) {
return new Vector2(1, 0).rotate(angle);
};
Vector2.prototype.toString = function(precision) {
if (precision === undefined)
precision = 4;
return '(' + this.x.toFixed(precision) + ', ' + this.y.toFixed(precision) + ')';
};
/**
* Rounds each component to the nearest integer.
*/
Vector2.prototype.round = function() {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
};
return Vector2;
});
|
agpl-3.0
|
rolencea/org.civicrm.civisocial2
|
twitterAPI/civisocialtwitter/report/search_dms.php
|
2051
|
<?php
//
require('../config.php');
require('../db_lib.php');
$db = new db();
// If the user clicked one of the buttons
if ((isset($_GET['submit'])) || (isset($_GET['prev'])) || (isset($_GET['next']))) {
$where = '';
$start_date = htmlspecialchars($_GET['start_date'], ENT_QUOTES);
if ($start_date != '0000-00-00') {
$where .= ' AND dms.created_at >= "' . $db->date($start_date) . '"';
}
$end_date = htmlspecialchars($_GET['end_date'], ENT_QUOTES);
if ($end_date != '0000-00-00') {
$where .= ' AND dms.created_at <= "' . $db->date($end_date) . '"';
}
$query = htmlspecialchars($_GET['query'], ENT_QUOTES);
if ($query != '') {
$query_words = explode(' ',$query);
foreach($query_words as $word) {
$word = trim($word);
$where .= " AND dms.dm_text LIKE '%$word%' ";
}
}
if(isset($_GET['prev'])) {
$page = intval($_GET['page']) - 1;
if($page<0) {
$page=0;
}
} elseif ($_GET['next']) {
$page = intval($_GET['page']) + 1;
} else {
$page = 0;
}
} else {
$start_date = '0000-00-00';
$end_date = '0000-00-00';
$query = '';
$page = 0;
}
require('page_top.html');
print '<h2>Search DMs</h2>';
// Display the form with empty fields
// or the values entered before Run button was clicked
print "<form action='search_dms.php' method='get'>";
print "Start Date: <input type='text' name='start_date' value='$start_date'>";
print "End Date: <input type='text' name='end_date' value='$end_date'><br/>";
print "Search Terms: <input type='text' name='query' value='$query' size='50'>";
print "<input type='hidden' name='page' value=$page>";
print '<button type="submit" name="submit" value=1>Search</button>';
print '<button type="submit" name="prev" value=1>< Prev</button>';
print '<button type="submit" name="next" value=1>Next ></button>';
print '</form>';
if (!empty($where)) {
require('../get_all_dms.php');
$dms = get_all_dms($where,$page*$results_per_page, $results_per_page);
require('display_dms.php');
}
require('page_bottom.html');
?>
|
agpl-3.0
|
PrairieLearn/PrairieLearn
|
lib/paginate.js
|
1786
|
const ERR = require('async-stacktrace');
const _ = require('lodash');
const async = require('async');
const sqldb = require('../prairielib/lib/sql-db');
module.exports = {
pages(chosenPage, count, pageSize) {
let lastPage = Math.ceil(count / pageSize);
if (lastPage === 0) lastPage = 1;
let currPage = Number(chosenPage);
if (!_.isInteger(currPage)) currPage = 1;
let prevPage = currPage - 1;
let nextPage = currPage + 1;
currPage = Math.max(1, Math.min(lastPage, currPage));
prevPage = Math.max(1, Math.min(lastPage, prevPage));
nextPage = Math.max(1, Math.min(lastPage, nextPage));
return { currPage, prevPage, nextPage, lastPage };
},
/**
* Utility function to facilitate extremely large queries whose results
* cannot fit in memory all at once. The given query must accept an "offset"
* param that will be used to paginate the query. The "receiveRow" callback
* will be called once for each row in the result set. The "done" callback
* is called either if an error has occurred or when all rows have been
* delivered.
*/
paginateQuery(sql, params, receiveRow, done) {
const _params = Object.assign({}, params);
let offset = 0;
async.doWhilst(
(callback) => {
_params.offset = offset;
sqldb.query(sql, _params, (err, result) => {
if (ERR(err, callback)) return;
async.eachSeries(result.rows, receiveRow, (err) => {
if (ERR(err, callback)) return;
offset += result.rows.length;
callback(null, result.rows.length);
});
});
},
(count, callback) => {
callback(null, count > 0);
},
(err) => {
if (ERR(err, done)) return;
done(null);
}
);
},
};
|
agpl-3.0
|
MostlyOpen/odoo_addons
|
myo_pharmacy/models/tag.py
|
1365
|
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from openerp import fields, models
class Tag(models.Model):
_inherit = 'myo.tag'
pharmacy_ids = fields.Many2many(
'myo.pharmacy',
'myo_pharmacy_tag_rel',
'tag_id',
'pharmacy_id',
'Pharmacies'
)
class Pharmacy(models.Model):
_inherit = 'myo.pharmacy'
tag_ids = fields.Many2many(
'myo.tag',
'myo_pharmacy_tag_rel',
'pharmacy_id',
'tag_id',
'Tags'
)
|
agpl-3.0
|
plentymarkets/plugin-hack-api
|
Modules/ItemSet/Models/ItemSetConfig.php
|
326
|
<?php
namespace Plenty\Modules\ItemSet\Models;
/**
* The ItemSetConfig model.
*/
abstract class ItemSetConfig
{
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
public $setId;
public $rebate;
/**
* Returns this model as an array.
*/
public function toArray(
):array
{
return [];
}
}
|
agpl-3.0
|
bio4j/bio4j-neo4j
|
docs/src/main/java/com/bio4j/neo4j/model/relationships/go/HasPartOfGoRel.java.md
|
64210
|
* Copyright (C) 2010-2011 "Bio4j"
*
* This file is part of Bio4j
*
* Bio4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
```java
package com.bio4j.neo4jdb.model.relationships.go;
import com.bio4j.neo4jdb.BasicRelationship;
import org.neo4j.graphdb.Relationship;
/**
*
* GO term 'has_part' relationship
*
* @author Pablo Pareja Tobes <ppareja@era7.com>
*/
public class HasPartOfGoRel extends BasicRelationship{
public static final String NAME = "HAS_PART_GO";
public static final String OBOXML_RELATIONSHIP_NAME = "has_part";
public HasPartOfGoRel(Relationship rel){
super(rel);
}
@Override
public String name() {
return NAME;
}
}
```
------
### Index
+ src
+ main
+ java
+ com
+ bio4j
+ neo4j
+ [BasicEntity.java][main/java/com/bio4j/neo4j/BasicEntity.java]
+ [BasicRelationship.java][main/java/com/bio4j/neo4j/BasicRelationship.java]
+ codesamples
+ [BiodieselProductionSample.java][main/java/com/bio4j/neo4j/codesamples/BiodieselProductionSample.java]
+ [GetEnzymeData.java][main/java/com/bio4j/neo4j/codesamples/GetEnzymeData.java]
+ [GetGenesInfo.java][main/java/com/bio4j/neo4j/codesamples/GetGenesInfo.java]
+ [GetGOAnnotationsForOrganism.java][main/java/com/bio4j/neo4j/codesamples/GetGOAnnotationsForOrganism.java]
+ [GetProteinsWithInterpro.java][main/java/com/bio4j/neo4j/codesamples/GetProteinsWithInterpro.java]
+ [RealUseCase1.java][main/java/com/bio4j/neo4j/codesamples/RealUseCase1.java]
+ [RetrieveProteinSample.java][main/java/com/bio4j/neo4j/codesamples/RetrieveProteinSample.java]
+ model
+ nodes
+ [AlternativeProductNode.java][main/java/com/bio4j/neo4j/model/nodes/AlternativeProductNode.java]
+ citation
+ [ArticleNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/ArticleNode.java]
+ [BookNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/BookNode.java]
+ [DBNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/DBNode.java]
+ [JournalNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/JournalNode.java]
+ [OnlineArticleNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/OnlineArticleNode.java]
+ [OnlineJournalNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/OnlineJournalNode.java]
+ [PatentNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/PatentNode.java]
+ [PublisherNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/PublisherNode.java]
+ [SubmissionNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/SubmissionNode.java]
+ [ThesisNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/ThesisNode.java]
+ [UnpublishedObservationNode.java][main/java/com/bio4j/neo4j/model/nodes/citation/UnpublishedObservationNode.java]
+ [CityNode.java][main/java/com/bio4j/neo4j/model/nodes/CityNode.java]
+ [CommentTypeNode.java][main/java/com/bio4j/neo4j/model/nodes/CommentTypeNode.java]
+ [ConsortiumNode.java][main/java/com/bio4j/neo4j/model/nodes/ConsortiumNode.java]
+ [CountryNode.java][main/java/com/bio4j/neo4j/model/nodes/CountryNode.java]
+ [DatasetNode.java][main/java/com/bio4j/neo4j/model/nodes/DatasetNode.java]
+ [EnzymeNode.java][main/java/com/bio4j/neo4j/model/nodes/EnzymeNode.java]
+ [FeatureTypeNode.java][main/java/com/bio4j/neo4j/model/nodes/FeatureTypeNode.java]
+ [GoTermNode.java][main/java/com/bio4j/neo4j/model/nodes/GoTermNode.java]
+ [InstituteNode.java][main/java/com/bio4j/neo4j/model/nodes/InstituteNode.java]
+ [InterproNode.java][main/java/com/bio4j/neo4j/model/nodes/InterproNode.java]
+ [IsoformNode.java][main/java/com/bio4j/neo4j/model/nodes/IsoformNode.java]
+ [KeywordNode.java][main/java/com/bio4j/neo4j/model/nodes/KeywordNode.java]
+ ncbi
+ [NCBITaxonNode.java][main/java/com/bio4j/neo4j/model/nodes/ncbi/NCBITaxonNode.java]
+ [OrganismNode.java][main/java/com/bio4j/neo4j/model/nodes/OrganismNode.java]
+ [PersonNode.java][main/java/com/bio4j/neo4j/model/nodes/PersonNode.java]
+ [PfamNode.java][main/java/com/bio4j/neo4j/model/nodes/PfamNode.java]
+ [ProteinNode.java][main/java/com/bio4j/neo4j/model/nodes/ProteinNode.java]
+ reactome
+ [ReactomeTermNode.java][main/java/com/bio4j/neo4j/model/nodes/reactome/ReactomeTermNode.java]
+ refseq
+ [CDSNode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/CDSNode.java]
+ [GeneNode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/GeneNode.java]
+ [GenomeElementNode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/GenomeElementNode.java]
+ rna
+ [MiscRNANode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/rna/MiscRNANode.java]
+ [MRNANode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/rna/MRNANode.java]
+ [NcRNANode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/rna/NcRNANode.java]
+ [RNANode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/rna/RNANode.java]
+ [RRNANode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/rna/RRNANode.java]
+ [TmRNANode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/rna/TmRNANode.java]
+ [TRNANode.java][main/java/com/bio4j/neo4j/model/nodes/refseq/rna/TRNANode.java]
+ [SequenceCautionNode.java][main/java/com/bio4j/neo4j/model/nodes/SequenceCautionNode.java]
+ [SubcellularLocationNode.java][main/java/com/bio4j/neo4j/model/nodes/SubcellularLocationNode.java]
+ [TaxonNode.java][main/java/com/bio4j/neo4j/model/nodes/TaxonNode.java]
+ relationships
+ aproducts
+ [AlternativeProductInitiationRel.java][main/java/com/bio4j/neo4j/model/relationships/aproducts/AlternativeProductInitiationRel.java]
+ [AlternativeProductPromoterRel.java][main/java/com/bio4j/neo4j/model/relationships/aproducts/AlternativeProductPromoterRel.java]
+ [AlternativeProductRibosomalFrameshiftingRel.java][main/java/com/bio4j/neo4j/model/relationships/aproducts/AlternativeProductRibosomalFrameshiftingRel.java]
+ [AlternativeProductSplicingRel.java][main/java/com/bio4j/neo4j/model/relationships/aproducts/AlternativeProductSplicingRel.java]
+ citation
+ article
+ [ArticleAuthorRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/article/ArticleAuthorRel.java]
+ [ArticleJournalRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/article/ArticleJournalRel.java]
+ [ArticleProteinCitationRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/article/ArticleProteinCitationRel.java]
+ book
+ [BookAuthorRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/book/BookAuthorRel.java]
+ [BookCityRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/book/BookCityRel.java]
+ [BookEditorRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/book/BookEditorRel.java]
+ [BookProteinCitationRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/book/BookProteinCitationRel.java]
+ [BookPublisherRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/book/BookPublisherRel.java]
+ onarticle
+ [OnlineArticleAuthorRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/onarticle/OnlineArticleAuthorRel.java]
+ [OnlineArticleJournalRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/onarticle/OnlineArticleJournalRel.java]
+ [OnlineArticleProteinCitationRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/onarticle/OnlineArticleProteinCitationRel.java]
+ patent
+ [PatentAuthorRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/patent/PatentAuthorRel.java]
+ [PatentProteinCitationRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/patent/PatentProteinCitationRel.java]
+ submission
+ [SubmissionAuthorRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/submission/SubmissionAuthorRel.java]
+ [SubmissionDbRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/submission/SubmissionDbRel.java]
+ [SubmissionProteinCitationRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/submission/SubmissionProteinCitationRel.java]
+ thesis
+ [ThesisAuthorRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/thesis/ThesisAuthorRel.java]
+ [ThesisInstituteRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/thesis/ThesisInstituteRel.java]
+ [ThesisProteinCitationRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/thesis/ThesisProteinCitationRel.java]
+ uo
+ [UnpublishedObservationAuthorRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/uo/UnpublishedObservationAuthorRel.java]
+ [UnpublishedObservationProteinCitationRel.java][main/java/com/bio4j/neo4j/model/relationships/citation/uo/UnpublishedObservationProteinCitationRel.java]
+ comment
+ [AllergenCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/AllergenCommentRel.java]
+ [BasicCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/BasicCommentRel.java]
+ [BioPhysicoChemicalPropertiesCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/BioPhysicoChemicalPropertiesCommentRel.java]
+ [BiotechnologyCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/BiotechnologyCommentRel.java]
+ [CatalyticActivityCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/CatalyticActivityCommentRel.java]
+ [CautionCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/CautionCommentRel.java]
+ [CofactorCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/CofactorCommentRel.java]
+ [DevelopmentalStageCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/DevelopmentalStageCommentRel.java]
+ [DiseaseCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/DiseaseCommentRel.java]
+ [DisruptionPhenotypeCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/DisruptionPhenotypeCommentRel.java]
+ [DomainCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/DomainCommentRel.java]
+ [EnzymeRegulationCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/EnzymeRegulationCommentRel.java]
+ [FunctionCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/FunctionCommentRel.java]
+ [InductionCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/InductionCommentRel.java]
+ [MassSpectrometryCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/MassSpectrometryCommentRel.java]
+ [MiscellaneousCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/MiscellaneousCommentRel.java]
+ [OnlineInformationCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/OnlineInformationCommentRel.java]
+ [PathwayCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/PathwayCommentRel.java]
+ [PharmaceuticalCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/PharmaceuticalCommentRel.java]
+ [PolymorphismCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/PolymorphismCommentRel.java]
+ [PostTranslationalModificationCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/PostTranslationalModificationCommentRel.java]
+ [RnaEditingCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/RnaEditingCommentRel.java]
+ [SimilarityCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/SimilarityCommentRel.java]
+ [SubunitCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/SubunitCommentRel.java]
+ [TissueSpecificityCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/TissueSpecificityCommentRel.java]
+ [ToxicDoseCommentRel.java][main/java/com/bio4j/neo4j/model/relationships/comment/ToxicDoseCommentRel.java]
+ features
+ [ActiveSiteFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/ActiveSiteFeatureRel.java]
+ [BasicFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/BasicFeatureRel.java]
+ [BindingSiteFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/BindingSiteFeatureRel.java]
+ [CalciumBindingRegionFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/CalciumBindingRegionFeatureRel.java]
+ [ChainFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/ChainFeatureRel.java]
+ [CoiledCoilRegionFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/CoiledCoilRegionFeatureRel.java]
+ [CompositionallyBiasedRegionFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/CompositionallyBiasedRegionFeatureRel.java]
+ [CrossLinkFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/CrossLinkFeatureRel.java]
+ [DisulfideBondFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/DisulfideBondFeatureRel.java]
+ [DnaBindingRegionFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/DnaBindingRegionFeatureRel.java]
+ [DomainFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/DomainFeatureRel.java]
+ [GlycosylationSiteFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/GlycosylationSiteFeatureRel.java]
+ [HelixFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/HelixFeatureRel.java]
+ [InitiatorMethionineFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/InitiatorMethionineFeatureRel.java]
+ [IntramembraneRegionFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/IntramembraneRegionFeatureRel.java]
+ [LipidMoietyBindingRegionFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/LipidMoietyBindingRegionFeatureRel.java]
+ [MetalIonBindingSiteFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/MetalIonBindingSiteFeatureRel.java]
+ [ModifiedResidueFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/ModifiedResidueFeatureRel.java]
+ [MutagenesisSiteFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/MutagenesisSiteFeatureRel.java]
+ [NonConsecutiveResiduesFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/NonConsecutiveResiduesFeatureRel.java]
+ [NonStandardAminoAcidFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/NonStandardAminoAcidFeatureRel.java]
+ [NonTerminalResidueFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/NonTerminalResidueFeatureRel.java]
+ [NucleotidePhosphateBindingRegionFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/NucleotidePhosphateBindingRegionFeatureRel.java]
+ [PeptideFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/PeptideFeatureRel.java]
+ [PropeptideFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/PropeptideFeatureRel.java]
+ [RegionOfInterestFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/RegionOfInterestFeatureRel.java]
+ [RepeatFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/RepeatFeatureRel.java]
+ [SequenceConflictFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/SequenceConflictFeatureRel.java]
+ [SequenceVariantFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/SequenceVariantFeatureRel.java]
+ [ShortSequenceMotifFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/ShortSequenceMotifFeatureRel.java]
+ [SignalPeptideFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/SignalPeptideFeatureRel.java]
+ [SiteFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/SiteFeatureRel.java]
+ [SpliceVariantFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/SpliceVariantFeatureRel.java]
+ [StrandFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/StrandFeatureRel.java]
+ [TopologicalDomainFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/TopologicalDomainFeatureRel.java]
+ [TransitPeptideFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/TransitPeptideFeatureRel.java]
+ [TransmembraneRegionFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/TransmembraneRegionFeatureRel.java]
+ [TurnFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/TurnFeatureRel.java]
+ [UnsureResidueFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/UnsureResidueFeatureRel.java]
+ [ZincFingerRegionFeatureRel.java][main/java/com/bio4j/neo4j/model/relationships/features/ZincFingerRegionFeatureRel.java]
+ go
+ [BiologicalProcessRel.java][main/java/com/bio4j/neo4j/model/relationships/go/BiologicalProcessRel.java]
+ [CellularComponentRel.java][main/java/com/bio4j/neo4j/model/relationships/go/CellularComponentRel.java]
+ [HasPartOfGoRel.java][main/java/com/bio4j/neo4j/model/relationships/go/HasPartOfGoRel.java]
+ [IsAGoRel.java][main/java/com/bio4j/neo4j/model/relationships/go/IsAGoRel.java]
+ [MainGoRel.java][main/java/com/bio4j/neo4j/model/relationships/go/MainGoRel.java]
+ [MolecularFunctionRel.java][main/java/com/bio4j/neo4j/model/relationships/go/MolecularFunctionRel.java]
+ [NegativelyRegulatesGoRel.java][main/java/com/bio4j/neo4j/model/relationships/go/NegativelyRegulatesGoRel.java]
+ [PartOfGoRel.java][main/java/com/bio4j/neo4j/model/relationships/go/PartOfGoRel.java]
+ [PositivelyRegulatesGoRel.java][main/java/com/bio4j/neo4j/model/relationships/go/PositivelyRegulatesGoRel.java]
+ [RegulatesGoRel.java][main/java/com/bio4j/neo4j/model/relationships/go/RegulatesGoRel.java]
+ [InstituteCountryRel.java][main/java/com/bio4j/neo4j/model/relationships/InstituteCountryRel.java]
+ [IsoformEventGeneratorRel.java][main/java/com/bio4j/neo4j/model/relationships/IsoformEventGeneratorRel.java]
+ ncbi
+ [NCBIMainTaxonRel.java][main/java/com/bio4j/neo4j/model/relationships/ncbi/NCBIMainTaxonRel.java]
+ [NCBITaxonParentRel.java][main/java/com/bio4j/neo4j/model/relationships/ncbi/NCBITaxonParentRel.java]
+ [NCBITaxonRel.java][main/java/com/bio4j/neo4j/model/relationships/ncbi/NCBITaxonRel.java]
+ protein
+ [BasicProteinSequenceCautionRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/BasicProteinSequenceCautionRel.java]
+ [ProteinDatasetRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinDatasetRel.java]
+ [ProteinEnzymaticActivityRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinEnzymaticActivityRel.java]
+ [ProteinErroneousGeneModelPredictionRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinErroneousGeneModelPredictionRel.java]
+ [ProteinErroneousInitiationRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinErroneousInitiationRel.java]
+ [ProteinErroneousTerminationRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinErroneousTerminationRel.java]
+ [ProteinErroneousTranslationRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinErroneousTranslationRel.java]
+ [ProteinFrameshiftRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinFrameshiftRel.java]
+ [ProteinGenomeElementRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinGenomeElementRel.java]
+ [ProteinGoRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinGoRel.java]
+ [ProteinInterproRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinInterproRel.java]
+ [ProteinIsoformInteractionRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinIsoformInteractionRel.java]
+ [ProteinIsoformRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinIsoformRel.java]
+ [ProteinKeywordRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinKeywordRel.java]
+ [ProteinMiscellaneousDiscrepancyRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinMiscellaneousDiscrepancyRel.java]
+ [ProteinOrganismRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinOrganismRel.java]
+ [ProteinPfamRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinPfamRel.java]
+ [ProteinProteinInteractionRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinProteinInteractionRel.java]
+ [ProteinReactomeRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinReactomeRel.java]
+ [ProteinSubcellularLocationRel.java][main/java/com/bio4j/neo4j/model/relationships/protein/ProteinSubcellularLocationRel.java]
+ refseq
+ [GenomeElementCDSRel.java][main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementCDSRel.java]
+ [GenomeElementGeneRel.java][main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementGeneRel.java]
+ [GenomeElementMiscRnaRel.java][main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementMiscRnaRel.java]
+ [GenomeElementMRnaRel.java][main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementMRnaRel.java]
+ [GenomeElementNcRnaRel.java][main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementNcRnaRel.java]
+ [GenomeElementRRnaRel.java][main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementRRnaRel.java]
+ [GenomeElementTmRnaRel.java][main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementTmRnaRel.java]
+ [GenomeElementTRnaRel.java][main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementTRnaRel.java]
+ sc
+ [ErroneousGeneModelPredictionRel.java][main/java/com/bio4j/neo4j/model/relationships/sc/ErroneousGeneModelPredictionRel.java]
+ [ErroneousInitiationRel.java][main/java/com/bio4j/neo4j/model/relationships/sc/ErroneousInitiationRel.java]
+ [ErroneousTerminationRel.java][main/java/com/bio4j/neo4j/model/relationships/sc/ErroneousTerminationRel.java]
+ [ErroneousTranslationRel.java][main/java/com/bio4j/neo4j/model/relationships/sc/ErroneousTranslationRel.java]
+ [FrameshiftRel.java][main/java/com/bio4j/neo4j/model/relationships/sc/FrameshiftRel.java]
+ [MiscellaneousDiscrepancyRel.java][main/java/com/bio4j/neo4j/model/relationships/sc/MiscellaneousDiscrepancyRel.java]
+ [SubcellularLocationParentRel.java][main/java/com/bio4j/neo4j/model/relationships/SubcellularLocationParentRel.java]
+ [TaxonParentRel.java][main/java/com/bio4j/neo4j/model/relationships/TaxonParentRel.java]
+ uniref
+ [UniRef100MemberRel.java][main/java/com/bio4j/neo4j/model/relationships/uniref/UniRef100MemberRel.java]
+ [UniRef50MemberRel.java][main/java/com/bio4j/neo4j/model/relationships/uniref/UniRef50MemberRel.java]
+ [UniRef90MemberRel.java][main/java/com/bio4j/neo4j/model/relationships/uniref/UniRef90MemberRel.java]
+ util
+ [Bio4jManager.java][main/java/com/bio4j/neo4j/model/util/Bio4jManager.java]
+ [GoUtil.java][main/java/com/bio4j/neo4j/model/util/GoUtil.java]
+ [NodeIndexer.java][main/java/com/bio4j/neo4j/model/util/NodeIndexer.java]
+ [NodeRetriever.java][main/java/com/bio4j/neo4j/model/util/NodeRetriever.java]
+ [UniprotStuff.java][main/java/com/bio4j/neo4j/model/util/UniprotStuff.java]
+ [Neo4jManager.java][main/java/com/bio4j/neo4j/Neo4jManager.java]
+ programs
+ [GetProteinData.java][main/java/com/bio4j/neo4j/programs/GetProteinData.java]
+ [ImportEnzymeDB.java][main/java/com/bio4j/neo4j/programs/ImportEnzymeDB.java]
+ [ImportGeneOntology.java][main/java/com/bio4j/neo4j/programs/ImportGeneOntology.java]
+ [ImportIsoformSequences.java][main/java/com/bio4j/neo4j/programs/ImportIsoformSequences.java]
+ [ImportNCBITaxonomy.java][main/java/com/bio4j/neo4j/programs/ImportNCBITaxonomy.java]
+ [ImportNeo4jDB.java][main/java/com/bio4j/neo4j/programs/ImportNeo4jDB.java]
+ [ImportProteinInteractions.java][main/java/com/bio4j/neo4j/programs/ImportProteinInteractions.java]
+ [ImportRefSeq.java][main/java/com/bio4j/neo4j/programs/ImportRefSeq.java]
+ [ImportUniprot.java][main/java/com/bio4j/neo4j/programs/ImportUniprot.java]
+ [ImportUniref.java][main/java/com/bio4j/neo4j/programs/ImportUniref.java]
+ [IndexNCBITaxonomyByGiId.java][main/java/com/bio4j/neo4j/programs/IndexNCBITaxonomyByGiId.java]
+ [InitBio4jDB.java][main/java/com/bio4j/neo4j/programs/InitBio4jDB.java]
+ [UploadRefSeqSequencesToS3.java][main/java/com/bio4j/neo4j/programs/UploadRefSeqSequencesToS3.java]
+ ohnosequences
+ util
+ [Executable.java][main/java/com/ohnosequences/util/Executable.java]
+ [ExecuteFromFile.java][main/java/com/ohnosequences/util/ExecuteFromFile.java]
+ genbank
+ [GBCommon.java][main/java/com/ohnosequences/util/genbank/GBCommon.java]
+ xml
+ api
+ interfaces
+ [IAttribute.java][main/java/com/ohnosequences/xml/api/interfaces/IAttribute.java]
+ [IElement.java][main/java/com/ohnosequences/xml/api/interfaces/IElement.java]
+ [INameSpace.java][main/java/com/ohnosequences/xml/api/interfaces/INameSpace.java]
+ [IXmlThing.java][main/java/com/ohnosequences/xml/api/interfaces/IXmlThing.java]
+ [package-info.java][main/java/com/ohnosequences/xml/api/interfaces/package-info.java]
+ model
+ [NameSpace.java][main/java/com/ohnosequences/xml/api/model/NameSpace.java]
+ [package-info.java][main/java/com/ohnosequences/xml/api/model/package-info.java]
+ [XMLAttribute.java][main/java/com/ohnosequences/xml/api/model/XMLAttribute.java]
+ [XMLElement.java][main/java/com/ohnosequences/xml/api/model/XMLElement.java]
+ [XMLElementException.java][main/java/com/ohnosequences/xml/api/model/XMLElementException.java]
+ util
+ [XMLUtil.java][main/java/com/ohnosequences/xml/api/util/XMLUtil.java]
+ model
+ bio4j
+ [Bio4jNodeIndexXML.java][main/java/com/ohnosequences/xml/model/bio4j/Bio4jNodeIndexXML.java]
+ [Bio4jNodeXML.java][main/java/com/ohnosequences/xml/model/bio4j/Bio4jNodeXML.java]
+ [Bio4jPropertyXML.java][main/java/com/ohnosequences/xml/model/bio4j/Bio4jPropertyXML.java]
+ [Bio4jRelationshipIndexXML.java][main/java/com/ohnosequences/xml/model/bio4j/Bio4jRelationshipIndexXML.java]
+ [Bio4jRelationshipXML.java][main/java/com/ohnosequences/xml/model/bio4j/Bio4jRelationshipXML.java]
+ [UniprotDataXML.java][main/java/com/ohnosequences/xml/model/bio4j/UniprotDataXML.java]
+ go
+ [GoAnnotationXML.java][main/java/com/ohnosequences/xml/model/go/GoAnnotationXML.java]
+ [GOSlimXML.java][main/java/com/ohnosequences/xml/model/go/GOSlimXML.java]
+ [GoTermXML.java][main/java/com/ohnosequences/xml/model/go/GoTermXML.java]
+ [SlimSetXML.java][main/java/com/ohnosequences/xml/model/go/SlimSetXML.java]
+ uniprot
+ [ArticleXML.java][main/java/com/ohnosequences/xml/model/uniprot/ArticleXML.java]
+ [CommentXML.java][main/java/com/ohnosequences/xml/model/uniprot/CommentXML.java]
+ [FeatureXML.java][main/java/com/ohnosequences/xml/model/uniprot/FeatureXML.java]
+ [InterproXML.java][main/java/com/ohnosequences/xml/model/uniprot/InterproXML.java]
+ [IsoformXML.java][main/java/com/ohnosequences/xml/model/uniprot/IsoformXML.java]
+ [KeywordXML.java][main/java/com/ohnosequences/xml/model/uniprot/KeywordXML.java]
+ [ProteinXML.java][main/java/com/ohnosequences/xml/model/uniprot/ProteinXML.java]
+ [SubcellularLocationXML.java][main/java/com/ohnosequences/xml/model/uniprot/SubcellularLocationXML.java]
+ util
+ [Argument.java][main/java/com/ohnosequences/xml/model/util/Argument.java]
+ [Arguments.java][main/java/com/ohnosequences/xml/model/util/Arguments.java]
+ [Error.java][main/java/com/ohnosequences/xml/model/util/Error.java]
+ [Execution.java][main/java/com/ohnosequences/xml/model/util/Execution.java]
+ [FlexXMLWrapperClassCreator.java][main/java/com/ohnosequences/xml/model/util/FlexXMLWrapperClassCreator.java]
+ [ScheduledExecutions.java][main/java/com/ohnosequences/xml/model/util/ScheduledExecutions.java]
+ [XMLWrapperClass.java][main/java/com/ohnosequences/xml/model/util/XMLWrapperClass.java]
+ [XMLWrapperClassCreator.java][main/java/com/ohnosequences/xml/model/util/XMLWrapperClassCreator.java]
[main/java/com/bio4j/neo4j/BasicEntity.java]: ../../../BasicEntity.java.md
[main/java/com/bio4j/neo4j/BasicRelationship.java]: ../../../BasicRelationship.java.md
[main/java/com/bio4j/neo4j/codesamples/BiodieselProductionSample.java]: ../../../codesamples/BiodieselProductionSample.java.md
[main/java/com/bio4j/neo4j/codesamples/GetEnzymeData.java]: ../../../codesamples/GetEnzymeData.java.md
[main/java/com/bio4j/neo4j/codesamples/GetGenesInfo.java]: ../../../codesamples/GetGenesInfo.java.md
[main/java/com/bio4j/neo4j/codesamples/GetGOAnnotationsForOrganism.java]: ../../../codesamples/GetGOAnnotationsForOrganism.java.md
[main/java/com/bio4j/neo4j/codesamples/GetProteinsWithInterpro.java]: ../../../codesamples/GetProteinsWithInterpro.java.md
[main/java/com/bio4j/neo4j/codesamples/RealUseCase1.java]: ../../../codesamples/RealUseCase1.java.md
[main/java/com/bio4j/neo4j/codesamples/RetrieveProteinSample.java]: ../../../codesamples/RetrieveProteinSample.java.md
[main/java/com/bio4j/neo4j/model/nodes/AlternativeProductNode.java]: ../../nodes/AlternativeProductNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/ArticleNode.java]: ../../nodes/citation/ArticleNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/BookNode.java]: ../../nodes/citation/BookNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/DBNode.java]: ../../nodes/citation/DBNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/JournalNode.java]: ../../nodes/citation/JournalNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/OnlineArticleNode.java]: ../../nodes/citation/OnlineArticleNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/OnlineJournalNode.java]: ../../nodes/citation/OnlineJournalNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/PatentNode.java]: ../../nodes/citation/PatentNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/PublisherNode.java]: ../../nodes/citation/PublisherNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/SubmissionNode.java]: ../../nodes/citation/SubmissionNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/ThesisNode.java]: ../../nodes/citation/ThesisNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/citation/UnpublishedObservationNode.java]: ../../nodes/citation/UnpublishedObservationNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/CityNode.java]: ../../nodes/CityNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/CommentTypeNode.java]: ../../nodes/CommentTypeNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/ConsortiumNode.java]: ../../nodes/ConsortiumNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/CountryNode.java]: ../../nodes/CountryNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/DatasetNode.java]: ../../nodes/DatasetNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/EnzymeNode.java]: ../../nodes/EnzymeNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/FeatureTypeNode.java]: ../../nodes/FeatureTypeNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/GoTermNode.java]: ../../nodes/GoTermNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/InstituteNode.java]: ../../nodes/InstituteNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/InterproNode.java]: ../../nodes/InterproNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/IsoformNode.java]: ../../nodes/IsoformNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/KeywordNode.java]: ../../nodes/KeywordNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/ncbi/NCBITaxonNode.java]: ../../nodes/ncbi/NCBITaxonNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/OrganismNode.java]: ../../nodes/OrganismNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/PersonNode.java]: ../../nodes/PersonNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/PfamNode.java]: ../../nodes/PfamNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/ProteinNode.java]: ../../nodes/ProteinNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/reactome/ReactomeTermNode.java]: ../../nodes/reactome/ReactomeTermNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/CDSNode.java]: ../../nodes/refseq/CDSNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/GeneNode.java]: ../../nodes/refseq/GeneNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/GenomeElementNode.java]: ../../nodes/refseq/GenomeElementNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/rna/MiscRNANode.java]: ../../nodes/refseq/rna/MiscRNANode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/rna/MRNANode.java]: ../../nodes/refseq/rna/MRNANode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/rna/NcRNANode.java]: ../../nodes/refseq/rna/NcRNANode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/rna/RNANode.java]: ../../nodes/refseq/rna/RNANode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/rna/RRNANode.java]: ../../nodes/refseq/rna/RRNANode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/rna/TmRNANode.java]: ../../nodes/refseq/rna/TmRNANode.java.md
[main/java/com/bio4j/neo4j/model/nodes/refseq/rna/TRNANode.java]: ../../nodes/refseq/rna/TRNANode.java.md
[main/java/com/bio4j/neo4j/model/nodes/SequenceCautionNode.java]: ../../nodes/SequenceCautionNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/SubcellularLocationNode.java]: ../../nodes/SubcellularLocationNode.java.md
[main/java/com/bio4j/neo4j/model/nodes/TaxonNode.java]: ../../nodes/TaxonNode.java.md
[main/java/com/bio4j/neo4j/model/relationships/aproducts/AlternativeProductInitiationRel.java]: ../aproducts/AlternativeProductInitiationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/aproducts/AlternativeProductPromoterRel.java]: ../aproducts/AlternativeProductPromoterRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/aproducts/AlternativeProductRibosomalFrameshiftingRel.java]: ../aproducts/AlternativeProductRibosomalFrameshiftingRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/aproducts/AlternativeProductSplicingRel.java]: ../aproducts/AlternativeProductSplicingRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/article/ArticleAuthorRel.java]: ../citation/article/ArticleAuthorRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/article/ArticleJournalRel.java]: ../citation/article/ArticleJournalRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/article/ArticleProteinCitationRel.java]: ../citation/article/ArticleProteinCitationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/book/BookAuthorRel.java]: ../citation/book/BookAuthorRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/book/BookCityRel.java]: ../citation/book/BookCityRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/book/BookEditorRel.java]: ../citation/book/BookEditorRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/book/BookProteinCitationRel.java]: ../citation/book/BookProteinCitationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/book/BookPublisherRel.java]: ../citation/book/BookPublisherRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/onarticle/OnlineArticleAuthorRel.java]: ../citation/onarticle/OnlineArticleAuthorRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/onarticle/OnlineArticleJournalRel.java]: ../citation/onarticle/OnlineArticleJournalRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/onarticle/OnlineArticleProteinCitationRel.java]: ../citation/onarticle/OnlineArticleProteinCitationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/patent/PatentAuthorRel.java]: ../citation/patent/PatentAuthorRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/patent/PatentProteinCitationRel.java]: ../citation/patent/PatentProteinCitationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/submission/SubmissionAuthorRel.java]: ../citation/submission/SubmissionAuthorRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/submission/SubmissionDbRel.java]: ../citation/submission/SubmissionDbRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/submission/SubmissionProteinCitationRel.java]: ../citation/submission/SubmissionProteinCitationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/thesis/ThesisAuthorRel.java]: ../citation/thesis/ThesisAuthorRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/thesis/ThesisInstituteRel.java]: ../citation/thesis/ThesisInstituteRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/thesis/ThesisProteinCitationRel.java]: ../citation/thesis/ThesisProteinCitationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/uo/UnpublishedObservationAuthorRel.java]: ../citation/uo/UnpublishedObservationAuthorRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/citation/uo/UnpublishedObservationProteinCitationRel.java]: ../citation/uo/UnpublishedObservationProteinCitationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/AllergenCommentRel.java]: ../comment/AllergenCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/BasicCommentRel.java]: ../comment/BasicCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/BioPhysicoChemicalPropertiesCommentRel.java]: ../comment/BioPhysicoChemicalPropertiesCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/BiotechnologyCommentRel.java]: ../comment/BiotechnologyCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/CatalyticActivityCommentRel.java]: ../comment/CatalyticActivityCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/CautionCommentRel.java]: ../comment/CautionCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/CofactorCommentRel.java]: ../comment/CofactorCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/DevelopmentalStageCommentRel.java]: ../comment/DevelopmentalStageCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/DiseaseCommentRel.java]: ../comment/DiseaseCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/DisruptionPhenotypeCommentRel.java]: ../comment/DisruptionPhenotypeCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/DomainCommentRel.java]: ../comment/DomainCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/EnzymeRegulationCommentRel.java]: ../comment/EnzymeRegulationCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/FunctionCommentRel.java]: ../comment/FunctionCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/InductionCommentRel.java]: ../comment/InductionCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/MassSpectrometryCommentRel.java]: ../comment/MassSpectrometryCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/MiscellaneousCommentRel.java]: ../comment/MiscellaneousCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/OnlineInformationCommentRel.java]: ../comment/OnlineInformationCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/PathwayCommentRel.java]: ../comment/PathwayCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/PharmaceuticalCommentRel.java]: ../comment/PharmaceuticalCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/PolymorphismCommentRel.java]: ../comment/PolymorphismCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/PostTranslationalModificationCommentRel.java]: ../comment/PostTranslationalModificationCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/RnaEditingCommentRel.java]: ../comment/RnaEditingCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/SimilarityCommentRel.java]: ../comment/SimilarityCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/SubunitCommentRel.java]: ../comment/SubunitCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/TissueSpecificityCommentRel.java]: ../comment/TissueSpecificityCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/comment/ToxicDoseCommentRel.java]: ../comment/ToxicDoseCommentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/ActiveSiteFeatureRel.java]: ../features/ActiveSiteFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/BasicFeatureRel.java]: ../features/BasicFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/BindingSiteFeatureRel.java]: ../features/BindingSiteFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/CalciumBindingRegionFeatureRel.java]: ../features/CalciumBindingRegionFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/ChainFeatureRel.java]: ../features/ChainFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/CoiledCoilRegionFeatureRel.java]: ../features/CoiledCoilRegionFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/CompositionallyBiasedRegionFeatureRel.java]: ../features/CompositionallyBiasedRegionFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/CrossLinkFeatureRel.java]: ../features/CrossLinkFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/DisulfideBondFeatureRel.java]: ../features/DisulfideBondFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/DnaBindingRegionFeatureRel.java]: ../features/DnaBindingRegionFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/DomainFeatureRel.java]: ../features/DomainFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/GlycosylationSiteFeatureRel.java]: ../features/GlycosylationSiteFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/HelixFeatureRel.java]: ../features/HelixFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/InitiatorMethionineFeatureRel.java]: ../features/InitiatorMethionineFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/IntramembraneRegionFeatureRel.java]: ../features/IntramembraneRegionFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/LipidMoietyBindingRegionFeatureRel.java]: ../features/LipidMoietyBindingRegionFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/MetalIonBindingSiteFeatureRel.java]: ../features/MetalIonBindingSiteFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/ModifiedResidueFeatureRel.java]: ../features/ModifiedResidueFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/MutagenesisSiteFeatureRel.java]: ../features/MutagenesisSiteFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/NonConsecutiveResiduesFeatureRel.java]: ../features/NonConsecutiveResiduesFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/NonStandardAminoAcidFeatureRel.java]: ../features/NonStandardAminoAcidFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/NonTerminalResidueFeatureRel.java]: ../features/NonTerminalResidueFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/NucleotidePhosphateBindingRegionFeatureRel.java]: ../features/NucleotidePhosphateBindingRegionFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/PeptideFeatureRel.java]: ../features/PeptideFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/PropeptideFeatureRel.java]: ../features/PropeptideFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/RegionOfInterestFeatureRel.java]: ../features/RegionOfInterestFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/RepeatFeatureRel.java]: ../features/RepeatFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/SequenceConflictFeatureRel.java]: ../features/SequenceConflictFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/SequenceVariantFeatureRel.java]: ../features/SequenceVariantFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/ShortSequenceMotifFeatureRel.java]: ../features/ShortSequenceMotifFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/SignalPeptideFeatureRel.java]: ../features/SignalPeptideFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/SiteFeatureRel.java]: ../features/SiteFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/SpliceVariantFeatureRel.java]: ../features/SpliceVariantFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/StrandFeatureRel.java]: ../features/StrandFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/TopologicalDomainFeatureRel.java]: ../features/TopologicalDomainFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/TransitPeptideFeatureRel.java]: ../features/TransitPeptideFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/TransmembraneRegionFeatureRel.java]: ../features/TransmembraneRegionFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/TurnFeatureRel.java]: ../features/TurnFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/UnsureResidueFeatureRel.java]: ../features/UnsureResidueFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/features/ZincFingerRegionFeatureRel.java]: ../features/ZincFingerRegionFeatureRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/BiologicalProcessRel.java]: BiologicalProcessRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/CellularComponentRel.java]: CellularComponentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/HasPartOfGoRel.java]: HasPartOfGoRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/IsAGoRel.java]: IsAGoRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/MainGoRel.java]: MainGoRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/MolecularFunctionRel.java]: MolecularFunctionRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/NegativelyRegulatesGoRel.java]: NegativelyRegulatesGoRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/PartOfGoRel.java]: PartOfGoRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/PositivelyRegulatesGoRel.java]: PositivelyRegulatesGoRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/go/RegulatesGoRel.java]: RegulatesGoRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/InstituteCountryRel.java]: ../InstituteCountryRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/IsoformEventGeneratorRel.java]: ../IsoformEventGeneratorRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/ncbi/NCBIMainTaxonRel.java]: ../ncbi/NCBIMainTaxonRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/ncbi/NCBITaxonParentRel.java]: ../ncbi/NCBITaxonParentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/ncbi/NCBITaxonRel.java]: ../ncbi/NCBITaxonRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/BasicProteinSequenceCautionRel.java]: ../protein/BasicProteinSequenceCautionRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinDatasetRel.java]: ../protein/ProteinDatasetRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinEnzymaticActivityRel.java]: ../protein/ProteinEnzymaticActivityRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinErroneousGeneModelPredictionRel.java]: ../protein/ProteinErroneousGeneModelPredictionRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinErroneousInitiationRel.java]: ../protein/ProteinErroneousInitiationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinErroneousTerminationRel.java]: ../protein/ProteinErroneousTerminationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinErroneousTranslationRel.java]: ../protein/ProteinErroneousTranslationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinFrameshiftRel.java]: ../protein/ProteinFrameshiftRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinGenomeElementRel.java]: ../protein/ProteinGenomeElementRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinGoRel.java]: ../protein/ProteinGoRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinInterproRel.java]: ../protein/ProteinInterproRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinIsoformInteractionRel.java]: ../protein/ProteinIsoformInteractionRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinIsoformRel.java]: ../protein/ProteinIsoformRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinKeywordRel.java]: ../protein/ProteinKeywordRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinMiscellaneousDiscrepancyRel.java]: ../protein/ProteinMiscellaneousDiscrepancyRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinOrganismRel.java]: ../protein/ProteinOrganismRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinPfamRel.java]: ../protein/ProteinPfamRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinProteinInteractionRel.java]: ../protein/ProteinProteinInteractionRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinReactomeRel.java]: ../protein/ProteinReactomeRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/protein/ProteinSubcellularLocationRel.java]: ../protein/ProteinSubcellularLocationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementCDSRel.java]: ../refseq/GenomeElementCDSRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementGeneRel.java]: ../refseq/GenomeElementGeneRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementMiscRnaRel.java]: ../refseq/GenomeElementMiscRnaRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementMRnaRel.java]: ../refseq/GenomeElementMRnaRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementNcRnaRel.java]: ../refseq/GenomeElementNcRnaRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementRRnaRel.java]: ../refseq/GenomeElementRRnaRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementTmRnaRel.java]: ../refseq/GenomeElementTmRnaRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/refseq/GenomeElementTRnaRel.java]: ../refseq/GenomeElementTRnaRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/sc/ErroneousGeneModelPredictionRel.java]: ../sc/ErroneousGeneModelPredictionRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/sc/ErroneousInitiationRel.java]: ../sc/ErroneousInitiationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/sc/ErroneousTerminationRel.java]: ../sc/ErroneousTerminationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/sc/ErroneousTranslationRel.java]: ../sc/ErroneousTranslationRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/sc/FrameshiftRel.java]: ../sc/FrameshiftRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/sc/MiscellaneousDiscrepancyRel.java]: ../sc/MiscellaneousDiscrepancyRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/SubcellularLocationParentRel.java]: ../SubcellularLocationParentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/TaxonParentRel.java]: ../TaxonParentRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/uniref/UniRef100MemberRel.java]: ../uniref/UniRef100MemberRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/uniref/UniRef50MemberRel.java]: ../uniref/UniRef50MemberRel.java.md
[main/java/com/bio4j/neo4j/model/relationships/uniref/UniRef90MemberRel.java]: ../uniref/UniRef90MemberRel.java.md
[main/java/com/bio4j/neo4j/model/util/Bio4jManager.java]: ../../util/Bio4jManager.java.md
[main/java/com/bio4j/neo4j/model/util/GoUtil.java]: ../../util/GoUtil.java.md
[main/java/com/bio4j/neo4j/model/util/NodeIndexer.java]: ../../util/NodeIndexer.java.md
[main/java/com/bio4j/neo4j/model/util/NodeRetriever.java]: ../../util/NodeRetriever.java.md
[main/java/com/bio4j/neo4j/model/util/UniprotStuff.java]: ../../util/UniprotStuff.java.md
[main/java/com/bio4j/neo4j/Neo4jManager.java]: ../../../Neo4jManager.java.md
[main/java/com/bio4j/neo4j/programs/GetProteinData.java]: ../../../programs/GetProteinData.java.md
[main/java/com/bio4j/neo4j/programs/ImportEnzymeDB.java]: ../../../programs/ImportEnzymeDB.java.md
[main/java/com/bio4j/neo4j/programs/ImportGeneOntology.java]: ../../../programs/ImportGeneOntology.java.md
[main/java/com/bio4j/neo4j/programs/ImportIsoformSequences.java]: ../../../programs/ImportIsoformSequences.java.md
[main/java/com/bio4j/neo4j/programs/ImportNCBITaxonomy.java]: ../../../programs/ImportNCBITaxonomy.java.md
[main/java/com/bio4j/neo4j/programs/ImportNeo4jDB.java]: ../../../programs/ImportNeo4jDB.java.md
[main/java/com/bio4j/neo4j/programs/ImportProteinInteractions.java]: ../../../programs/ImportProteinInteractions.java.md
[main/java/com/bio4j/neo4j/programs/ImportRefSeq.java]: ../../../programs/ImportRefSeq.java.md
[main/java/com/bio4j/neo4j/programs/ImportUniprot.java]: ../../../programs/ImportUniprot.java.md
[main/java/com/bio4j/neo4j/programs/ImportUniref.java]: ../../../programs/ImportUniref.java.md
[main/java/com/bio4j/neo4j/programs/IndexNCBITaxonomyByGiId.java]: ../../../programs/IndexNCBITaxonomyByGiId.java.md
[main/java/com/bio4j/neo4j/programs/InitBio4jDB.java]: ../../../programs/InitBio4jDB.java.md
[main/java/com/bio4j/neo4j/programs/UploadRefSeqSequencesToS3.java]: ../../../programs/UploadRefSeqSequencesToS3.java.md
[main/java/com/ohnosequences/util/Executable.java]: ../../../../../ohnosequences/util/Executable.java.md
[main/java/com/ohnosequences/util/ExecuteFromFile.java]: ../../../../../ohnosequences/util/ExecuteFromFile.java.md
[main/java/com/ohnosequences/util/genbank/GBCommon.java]: ../../../../../ohnosequences/util/genbank/GBCommon.java.md
[main/java/com/ohnosequences/xml/api/interfaces/IAttribute.java]: ../../../../../ohnosequences/xml/api/interfaces/IAttribute.java.md
[main/java/com/ohnosequences/xml/api/interfaces/IElement.java]: ../../../../../ohnosequences/xml/api/interfaces/IElement.java.md
[main/java/com/ohnosequences/xml/api/interfaces/INameSpace.java]: ../../../../../ohnosequences/xml/api/interfaces/INameSpace.java.md
[main/java/com/ohnosequences/xml/api/interfaces/IXmlThing.java]: ../../../../../ohnosequences/xml/api/interfaces/IXmlThing.java.md
[main/java/com/ohnosequences/xml/api/interfaces/package-info.java]: ../../../../../ohnosequences/xml/api/interfaces/package-info.java.md
[main/java/com/ohnosequences/xml/api/model/NameSpace.java]: ../../../../../ohnosequences/xml/api/model/NameSpace.java.md
[main/java/com/ohnosequences/xml/api/model/package-info.java]: ../../../../../ohnosequences/xml/api/model/package-info.java.md
[main/java/com/ohnosequences/xml/api/model/XMLAttribute.java]: ../../../../../ohnosequences/xml/api/model/XMLAttribute.java.md
[main/java/com/ohnosequences/xml/api/model/XMLElement.java]: ../../../../../ohnosequences/xml/api/model/XMLElement.java.md
[main/java/com/ohnosequences/xml/api/model/XMLElementException.java]: ../../../../../ohnosequences/xml/api/model/XMLElementException.java.md
[main/java/com/ohnosequences/xml/api/util/XMLUtil.java]: ../../../../../ohnosequences/xml/api/util/XMLUtil.java.md
[main/java/com/ohnosequences/xml/model/bio4j/Bio4jNodeIndexXML.java]: ../../../../../ohnosequences/xml/model/bio4j/Bio4jNodeIndexXML.java.md
[main/java/com/ohnosequences/xml/model/bio4j/Bio4jNodeXML.java]: ../../../../../ohnosequences/xml/model/bio4j/Bio4jNodeXML.java.md
[main/java/com/ohnosequences/xml/model/bio4j/Bio4jPropertyXML.java]: ../../../../../ohnosequences/xml/model/bio4j/Bio4jPropertyXML.java.md
[main/java/com/ohnosequences/xml/model/bio4j/Bio4jRelationshipIndexXML.java]: ../../../../../ohnosequences/xml/model/bio4j/Bio4jRelationshipIndexXML.java.md
[main/java/com/ohnosequences/xml/model/bio4j/Bio4jRelationshipXML.java]: ../../../../../ohnosequences/xml/model/bio4j/Bio4jRelationshipXML.java.md
[main/java/com/ohnosequences/xml/model/bio4j/UniprotDataXML.java]: ../../../../../ohnosequences/xml/model/bio4j/UniprotDataXML.java.md
[main/java/com/ohnosequences/xml/model/go/GoAnnotationXML.java]: ../../../../../ohnosequences/xml/model/go/GoAnnotationXML.java.md
[main/java/com/ohnosequences/xml/model/go/GOSlimXML.java]: ../../../../../ohnosequences/xml/model/go/GOSlimXML.java.md
[main/java/com/ohnosequences/xml/model/go/GoTermXML.java]: ../../../../../ohnosequences/xml/model/go/GoTermXML.java.md
[main/java/com/ohnosequences/xml/model/go/SlimSetXML.java]: ../../../../../ohnosequences/xml/model/go/SlimSetXML.java.md
[main/java/com/ohnosequences/xml/model/uniprot/ArticleXML.java]: ../../../../../ohnosequences/xml/model/uniprot/ArticleXML.java.md
[main/java/com/ohnosequences/xml/model/uniprot/CommentXML.java]: ../../../../../ohnosequences/xml/model/uniprot/CommentXML.java.md
[main/java/com/ohnosequences/xml/model/uniprot/FeatureXML.java]: ../../../../../ohnosequences/xml/model/uniprot/FeatureXML.java.md
[main/java/com/ohnosequences/xml/model/uniprot/InterproXML.java]: ../../../../../ohnosequences/xml/model/uniprot/InterproXML.java.md
[main/java/com/ohnosequences/xml/model/uniprot/IsoformXML.java]: ../../../../../ohnosequences/xml/model/uniprot/IsoformXML.java.md
[main/java/com/ohnosequences/xml/model/uniprot/KeywordXML.java]: ../../../../../ohnosequences/xml/model/uniprot/KeywordXML.java.md
[main/java/com/ohnosequences/xml/model/uniprot/ProteinXML.java]: ../../../../../ohnosequences/xml/model/uniprot/ProteinXML.java.md
[main/java/com/ohnosequences/xml/model/uniprot/SubcellularLocationXML.java]: ../../../../../ohnosequences/xml/model/uniprot/SubcellularLocationXML.java.md
[main/java/com/ohnosequences/xml/model/util/Argument.java]: ../../../../../ohnosequences/xml/model/util/Argument.java.md
[main/java/com/ohnosequences/xml/model/util/Arguments.java]: ../../../../../ohnosequences/xml/model/util/Arguments.java.md
[main/java/com/ohnosequences/xml/model/util/Error.java]: ../../../../../ohnosequences/xml/model/util/Error.java.md
[main/java/com/ohnosequences/xml/model/util/Execution.java]: ../../../../../ohnosequences/xml/model/util/Execution.java.md
[main/java/com/ohnosequences/xml/model/util/FlexXMLWrapperClassCreator.java]: ../../../../../ohnosequences/xml/model/util/FlexXMLWrapperClassCreator.java.md
[main/java/com/ohnosequences/xml/model/util/ScheduledExecutions.java]: ../../../../../ohnosequences/xml/model/util/ScheduledExecutions.java.md
[main/java/com/ohnosequences/xml/model/util/XMLWrapperClass.java]: ../../../../../ohnosequences/xml/model/util/XMLWrapperClass.java.md
[main/java/com/ohnosequences/xml/model/util/XMLWrapperClassCreator.java]: ../../../../../ohnosequences/xml/model/util/XMLWrapperClassCreator.java.md
|
agpl-3.0
|
patrickcmartins/goautodialtraduzido
|
vicidial/AST_LISTS_stats.php
|
37059
|
<?php
# AST_LISTS_stats.php
#
# Copyright (C) 2014 Matt Florell <vicidial@gmail.com> LICENSE: AGPLv2
#
# This is a list inventory report, not a calling report. This report will show
# statistics for all of the lists in the selected campaigns
#
# CHANGES
# 130926-0721 - First build based upon LISTS campaign report
# 130927-2154 - Added summary and full download options
# 140108-0714 - Added webserver and hostname to report logging
# 140328-0005 - Converted division calculations to use MathZDC function
#
$startMS = microtime();
header ("Content-type: text/html; charset=utf-8");
require("dbconnect_mysqli.php");
require("functions.php");
$PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER'];
$PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW'];
$PHP_SELF=$_SERVER['PHP_SELF'];
if (isset($_GET["group"])) {$group=$_GET["group"];}
elseif (isset($_POST["group"])) {$group=$_POST["group"];}
if (isset($_GET["list"])) {$list=$_GET["list"];}
elseif (isset($_POST["list"])) {$list=$_POST["list"];}
if (isset($_GET["DB"])) {$DB=$_GET["DB"];}
elseif (isset($_POST["DB"])) {$DB=$_POST["DB"];}
if (isset($_GET["submit"])) {$submit=$_GET["submit"];}
elseif (isset($_POST["submit"])) {$submit=$_POST["submit"];}
if (isset($_GET["SUBMIT"])) {$SUBMIT=$_GET["SUBMIT"];}
elseif (isset($_POST["SUBMIT"])) {$SUBMIT=$_POST["SUBMIT"];}
if (isset($_GET["file_download"])) {$file_download=$_GET["file_download"];}
elseif (isset($_POST["file_download"])) {$file_download=$_POST["file_download"];}
if (isset($_GET["report_display_type"])) {$report_display_type=$_GET["report_display_type"];}
elseif (isset($_POST["report_display_type"])) {$report_display_type=$_POST["report_display_type"];}
if (isset($_GET["campaigns_or_lists_rpt"])) {$campaigns_or_lists_rpt=$_GET["campaigns_or_lists_rpt"];}
elseif (isset($_POST["campaigns_or_lists_rpt"])) {$campaigns_or_lists_rpt=$_POST["campaigns_or_lists_rpt"];}
$report_name = 'Lists Statuses Report';
$db_source = 'M';
$JS_text="<script language='Javascript'>\n";
$JS_onload="onload = function() {\n";
#############################################
##### START SYSTEM_SETTINGS LOOKUP #####
$stmt = "SELECT use_non_latin,outbound_autodial_active,slave_db_server,reports_use_slave_db FROM system_settings;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$qm_conf_ct = mysqli_num_rows($rslt);
if ($qm_conf_ct > 0)
{
$row=mysqli_fetch_row($rslt);
$non_latin = $row[0];
$outbound_autodial_active = $row[1];
$slave_db_server = $row[2];
$reports_use_slave_db = $row[3];
}
##### END SETTINGS LOOKUP #####
###########################################
if ($non_latin < 1)
{
$PHP_AUTH_USER = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_USER);
$PHP_AUTH_PW = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_PW);
}
else
{
$PHP_AUTH_PW = preg_replace("/'|\"|\\\\|;/","",$PHP_AUTH_PW);
$PHP_AUTH_USER = preg_replace("/'|\"|\\\\|;/","",$PHP_AUTH_USER);
}
$auth=0;
$reports_auth=0;
$admin_auth=0;
$auth_message = user_authorization($PHP_AUTH_USER,$PHP_AUTH_PW,'REPORTS',1);
if ($auth_message == 'GOOD')
{$auth=1;}
if ($auth > 0)
{
$stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 7 and view_reports > 0;";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$admin_auth=$row[0];
$stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 6 and view_reports > 0;";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$reports_auth=$row[0];
if ($reports_auth < 1)
{
$VDdisplayMESSAGE = "You are not allowed to view reports";
Header ("Content-type: text/html; charset=utf-8");
echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n";
exit;
}
if ( ($reports_auth > 0) and ($admin_auth < 1) )
{
$ADD=999999;
$reports_only_user=1;
}
}
else
{
$VDdisplayMESSAGE = "Login incorrect, please try again";
if ($auth_message == 'LOCK')
{
$VDdisplayMESSAGE = "Too many login attempts, try again in 15 minutes";
Header ("Content-type: text/html; charset=utf-8");
echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n";
exit;
}
Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\"");
Header("HTTP/1.0 401 Unauthorized");
echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$PHP_AUTH_PW|$auth_message|\n";
exit;
}
##### BEGIN log visit to the vicidial_report_log table #####
$LOGip = getenv("REMOTE_ADDR");
$LOGbrowser = getenv("HTTP_USER_AGENT");
$LOGscript_name = getenv("SCRIPT_NAME");
$LOGserver_name = getenv("SERVER_NAME");
$LOGserver_port = getenv("SERVER_PORT");
$LOGrequest_uri = getenv("REQUEST_URI");
$LOGhttp_referer = getenv("HTTP_REFERER");
if (preg_match("/443/i",$LOGserver_port)) {$HTTPprotocol = 'https://';}
else {$HTTPprotocol = 'http://';}
if (($LOGserver_port == '80') or ($LOGserver_port == '443') ) {$LOGserver_port='';}
else {$LOGserver_port = ":$LOGserver_port";}
$LOGfull_url = "$HTTPprotocol$LOGserver_name$LOGserver_port$LOGrequest_uri";
$LOGhostname = php_uname('n');
if (strlen($LOGhostname)<1) {$LOGhostname='X';}
if (strlen($LOGserver_name)<1) {$LOGserver_name='X';}
$stmt="SELECT webserver_id FROM vicidial_webservers where webserver='$LOGserver_name' and hostname='$LOGhostname' LIMIT 1;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {echo "$stmt\n";}
$webserver_id_ct = mysqli_num_rows($rslt);
if ($webserver_id_ct > 0)
{
$row=mysqli_fetch_row($rslt);
$webserver_id = $row[0];
}
else
{
##### insert webserver entry
$stmt="INSERT INTO vicidial_webservers (webserver,hostname) values('$LOGserver_name','$LOGhostname');";
if ($DB) {echo "$stmt\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$affected_rows = mysqli_affected_rows($link);
$webserver_id = mysqli_insert_id($link);
}
$stmt="INSERT INTO vicidial_report_log set event_date=NOW(), user='$PHP_AUTH_USER', ip_address='$LOGip', report_name='$report_name', browser='$LOGbrowser', referer='$LOGhttp_referer', notes='$LOGserver_name:$LOGserver_port $LOGscript_name |$group[0], $query_date, $end_date, $shift, $file_download, $report_display_type|', url='$LOGfull_url', webserver='$webserver_id';";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$report_log_id = mysqli_insert_id($link);
##### END log visit to the vicidial_report_log table #####
if ( (strlen($slave_db_server)>5) and (preg_match("/$report_name/",$reports_use_slave_db)) )
{
mysqli_close($link);
$use_slave_server=1;
$db_source = 'S';
require("dbconnect.php");
$MAIN.="<!-- Using slave server $slave_db_server $db_source -->\n";
}
$stmt="SELECT user_group from vicidial_users where user='$PHP_AUTH_USER';";
if ($DB) {$MAIN.="|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$LOGuser_group = $row[0];
$stmt="SELECT allowed_campaigns,allowed_reports from vicidial_user_groups where user_group='$LOGuser_group';";
if ($DB) {$MAIN.="|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$LOGallowed_campaigns = $row[0];
$LOGallowed_reports = $row[1];
if ( (!preg_match("/$report_name/",$LOGallowed_reports)) and (!preg_match("/ALL REPORTS/",$LOGallowed_reports)) )
{
Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\"");
Header("HTTP/1.0 401 Unauthorized");
echo "You are not allowed to view this report: |$PHP_AUTH_USER|$report_name|\n";
exit;
}
$NOW_DATE = date("Y-m-d");
$NOW_TIME = date("Y-m-d H:i:s");
$STARTtime = date("U");
$LOGallowed_campaignsSQL='';
$whereLOGallowed_campaignsSQL='';
if ( (!preg_match('/\-ALL/i', $LOGallowed_campaigns)) )
{
$rawLOGallowed_campaignsSQL = preg_replace("/ -/",'',$LOGallowed_campaigns);
$rawLOGallowed_campaignsSQL = preg_replace("/ /","','",$rawLOGallowed_campaignsSQL);
$LOGallowed_campaignsSQL = "and campaign_id IN('$rawLOGallowed_campaignsSQL')";
$whereLOGallowed_campaignsSQL = "where campaign_id IN('$rawLOGallowed_campaignsSQL')";
}
$regexLOGallowed_campaigns = " $LOGallowed_campaigns ";
###########
if (!isset($list)) {$list = '';}
$i=0;
$list_string='|';
$list_ct = count($list);
while($i < $list_ct)
{
$list_string .= "$list[$i]|";
$i++;
}
$stmt="select list_id, list_name, campaign_id from vicidial_lists $whereLOGallowed_campaignsSQL order by list_id;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$lists_to_print = mysqli_num_rows($rslt);
$i=0;
while ($i < $lists_to_print)
{
$row=mysqli_fetch_row($rslt);
$lists[$i] = $row[0];
$list_names[$i] = $row[1];
$list_campaigns[$i] = $row[2];
if (preg_match('/\-ALL/',$list_string) )
{$list[$i] = $lists[$i];}
$i++;
}
$i=0;
$list_string='|';
$list_ct = count($list);
while($i < $list_ct)
{
$list_string .= "$list[$i]|";
$list_SQL .= "'$list[$i]',";
$listQS .= "&list[]=$list[$i]";
$i++;
}
$list_id_str=substr($list_SQL,0,-1);
$group_SQL = "$LOGallowed_campaignsSQL";
$group_SQLand = "$LOGallowed_campaignsSQL";
#######################
# Get lists to query to avoid using a nested query
$lists_id_str="";
$list_stmt="SELECT list_id from vicidial_lists where active IN('Y','N') $group_SQLand";
$list_rslt=mysql_to_mysqli($list_stmt, $link);
while ($lrow=mysqli_fetch_row($list_rslt)) {
$lists_id_str.="'$lrow[0]',";
}
$lists_id_str=substr($lists_id_str,0,-1);
$stmt="select vsc_id,vsc_name from vicidial_status_categories;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {echo "$stmt\n";}
$statcats_to_print = mysqli_num_rows($rslt);
$i=0;
while ($i < $statcats_to_print)
{
$row=mysqli_fetch_row($rslt);
$vsc_id[$i] = $row[0];
$vsc_name[$i] = $row[1];
$category_statuses="";
$status_stmt="select distinct status from vicidial_statuses where category='$row[0]' UNION select distinct status from vicidial_campaign_statuses where category='$row[0]' $group_SQLand";
if ($DB) {echo "$status_stmt\n";}
$status_rslt=mysql_to_mysqli($status_stmt, $link);
while ($status_row=mysqli_fetch_row($status_rslt))
{
$category_statuses.="'$status_row[0]',";
}
$category_statuses=substr($category_statuses, 0, -1);
$category_stmt="select count(*) from vicidial_list where status in ($category_statuses) and list_id IN($lists_id_str)";
if ($DB) {echo "$category_stmt\n";}
$category_rslt=mysql_to_mysqli($category_stmt, $link);
$category_row=mysqli_fetch_row($category_rslt);
$vsc_count[$i] = $category_row[0];
$i++;
}
### BEGIN gather all statuses that are in status flags ###
$human_answered_statuses='';
$sale_statuses='';
$dnc_statuses='';
$customer_contact_statuses='';
$not_interested_statuses='';
$unworkable_statuses='';
$stmt="select status,human_answered,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,status_name from vicidial_statuses;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$statha_to_print = mysqli_num_rows($rslt);
$i=0;
while ($i < $statha_to_print)
{
$row=mysqli_fetch_row($rslt);
$temp_status = $row[0];
$statname_list["$temp_status"] = "$row[9]";
if ($row[1]=='Y') {$human_answered_statuses .= "'$temp_status',";}
if ($row[2]=='Y') {$sale_statuses .= "'$temp_status',";}
if ($row[3]=='Y') {$dnc_statuses .= "'$temp_status',";}
if ($row[4]=='Y') {$customer_contact_statuses .= "'$temp_status',";}
if ($row[5]=='Y') {$not_interested_statuses .= "'$temp_status',";}
if ($row[6]=='Y') {$unworkable_statuses .= "'$temp_status',";}
if ($row[7]=='Y') {$scheduled_callback_statuses .= "'$temp_status',";}
if ($row[8]=='Y') {$completed_statuses .= "'$temp_status',";}
$i++;
}
$stmt="select status,human_answered,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,status_name from vicidial_campaign_statuses where selectable IN('Y','N') $group_SQLand;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$statha_to_print = mysqli_num_rows($rslt);
$i=0;
while ($i < $statha_to_print)
{
$row=mysqli_fetch_row($rslt);
$temp_status = $row[0];
$statname_list["$temp_status"] = "$row[9]";
if ( ($row[1]=='Y') and (!preg_match("/'$temp_status'/",$human_answered_statuses)) ) {$human_answered_statuses .= "'$temp_status',";}
if ($row[2]=='Y') {$sale_statuses .= "'$temp_status',";}
if ($row[3]=='Y') {$dnc_statuses .= "'$temp_status',";}
if ($row[4]=='Y') {$customer_contact_statuses .= "'$temp_status',";}
if ($row[5]=='Y') {$not_interested_statuses .= "'$temp_status',";}
if ($row[6]=='Y') {$unworkable_statuses .= "'$temp_status',";}
if ($row[7]=='Y') {$scheduled_callback_statuses .= "'$temp_status',";}
if ($row[8]=='Y') {$completed_statuses .= "'$temp_status',";}
$i++;
}
if (strlen($human_answered_statuses)>2) {$human_answered_statuses = substr("$human_answered_statuses", 0, -1);}
else {$human_answered_statuses="''";}
if (strlen($sale_statuses)>2) {$sale_statuses = substr("$sale_statuses", 0, -1);}
else {$sale_statuses="''";}
if (strlen($dnc_statuses)>2) {$dnc_statuses = substr("$dnc_statuses", 0, -1);}
else {$dnc_statuses="''";}
if (strlen($customer_contact_statuses)>2) {$customer_contact_statuses = substr("$customer_contact_statuses", 0, -1);}
else {$customer_contact_statuses="''";}
if (strlen($not_interested_statuses)>2) {$not_interested_statuses = substr("$not_interested_statuses", 0, -1);}
else {$not_interested_statuses="''";}
if (strlen($unworkable_statuses)>2) {$unworkable_statuses = substr("$unworkable_statuses", 0, -1);}
else {$unworkable_statuses="''";}
if (strlen($scheduled_callback_statuses)>2) {$scheduled_callback_statuses = substr("$scheduled_callback_statuses", 0, -1);}
else {$scheduled_callback_statuses="''";}
if (strlen($completed_statuses)>2) {$completed_statuses = substr("$completed_statuses", 0, -1);}
else {$completed_statuses="''";}
$HEADER.="<HTML>\n";
$HEADER.="<HEAD>\n";
$HEADER.="<STYLE type=\"text/css\">\n";
$HEADER.="<!--\n";
$HEADER.=" .green {color: white; background-color: green}\n";
$HEADER.=" .red {color: white; background-color: red}\n";
$HEADER.=" .blue {color: white; background-color: blue}\n";
$HEADER.=" .purple {color: white; background-color: purple}\n";
$HEADER.="-->\n";
$HEADER.=" </STYLE>\n";
$HEADER.="<link rel=\"stylesheet\" href=\"horizontalbargraph.css\">\n";
$HEADER.="<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\">\n";
$HEADER.="<TITLE>$report_name</TITLE></HEAD><BODY BGCOLOR=WHITE marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>\n";
$short_header=1;
$MAIN.="<TABLE CELLPADDING=4 CELLSPACING=0><TR><TD>";
$MAIN.="<FORM ACTION=\"$PHP_SELF\" METHOD=GET name=vicidial_report id=vicidial_report>\n";
$MAIN.="<TABLE CELLSPACING=3><TR><TD VALIGN=TOP>";
$MAIN.="<INPUT TYPE=HIDDEN NAME=DB VALUE=\"$DB\">\n";
$MAIN.="</TD>";
$MAIN.="<TD VALIGN=TOP> Lists:<BR>";
$MAIN.="<SELECT SIZE=5 NAME=list[] multiple>\n";
if (preg_match('/\-\-ALL\-\-/',$list_string))
{$MAIN.="<option value=\"--ALL--\" selected>-- ALL LISTS --</option>\n";}
else
{$MAIN.="<option value=\"--ALL--\">-- ALL LISTS --</option>\n";}
$o=0;
while ($lists_to_print > $o)
{
if (preg_match("/$lists[$o]\|/i",$list_string)) {$MAIN.="<option selected value=\"$lists[$o]\">$lists[$o] - $list_names[$o]</option>\n";}
else {$MAIN.="<option value=\"$lists[$o]\">$lists[$o] - $list_names[$o]</option>\n";}
$o++;
}
$MAIN.="</SELECT><BR><a href=\"AST_LISTS_campaign_stats.php?DB=$DB\">SWITCH TO CAMPAIGNS</a>\n";
$MAIN.="</TD>";
$MAIN.="<TD VALIGN=TOP>";
#$MAIN.="Display as:<BR/>";
#$MAIN.="<select name='report_display_type'>";
#if ($report_display_type) {$MAIN.="<option value='$report_display_type' selected>$report_display_type</option>";}
#$MAIN.="<option value='TEXT'>TEXT</option><option value='HTML'>HTML</option></select> ";
$MAIN.="<BR><BR><BR>\n";
$MAIN.="<INPUT type=submit NAME=SUBMIT VALUE=SUBMIT>\n";
$MAIN.="</TD><TD VALIGN=TOP> ";
$MAIN.="<FONT FACE=\"ARIAL,HELVETICA\" COLOR=BLACK SIZE=2>";
if (strlen($group[0]) > 1)
{
$MAIN.=" <a href=\"./admin.php?ADD=34&campaign_id=$group[0]\">MODIFY</a> | \n";
$MAIN.=" <a href=\"./admin.php?ADD=999999\">REPORTS</a> </FONT>\n";
}
else
{
$MAIN.=" <a href=\"./admin.php?ADD=10\">CAMPAIGNS</a> | \n";
$MAIN.=" <a href=\"./admin.php?ADD=999999\">REPORTS</a> </FONT>\n";
}
$MAIN.="</TD></TR></TABLE>";
$MAIN.="</FORM>\n\n";
$MAIN.="<PRE><FONT SIZE=2>\n\n";
if (strlen($list[0]) < 1)
{
$MAIN.="\n\n";
$MAIN.="PLEASE SELECT A LIST OR LISTS ABOVE AND CLICK SUBMIT\n";
}
else
{
$totalOUToutput = '';
$totalOUToutput .= "List Status Stats $NOW_TIME <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=ALL\">DOWNLOAD FULL REPORT</a>\n";
$totalOUToutput .= "\n";
$list_stmt="select vicidial_list.list_id,list_name,active, count(*) from vicidial_list, vicidial_lists where vicidial_lists.list_id in ($list_id_str) and vicidial_lists.list_id=vicidial_list.list_id group by vicidial_list.list_id, list_name, active order by list_id, list_name asc;";
$list_rslt=mysql_to_mysqli($list_stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$listids_to_print = mysqli_num_rows($list_rslt);
$CSV_text1="\"\",\"LIST ID SUMMARY\"\n";
$CSV_text1.="\"LIST ID\",\"LIST NAME\",\"TOTAL LEADS\",\"ACTIVE/INACTIVE\"\n";
$CSV_text2="";
$CSV_text3="";
$CSV_textALL="";
$i=0;
$totalOUToutput .= "---------- TOTAL LIST ID SUMMARY <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=ALL\">DOWNLOAD FULL REPORT</a>\n";
$totalOUToutput .= "+------------------------------------------+------------+----------+\n";
$totalOUToutput .= "| LIST | LEADS | ACTIVE |\n";
$totalOUToutput .= "+------------------------------------------+------------+----------+\n";
$CSV_textSUMMARY.="\"LIST ID SUMMARY\"\n";
$CSV_textSUMMARY.="\"LIST\",\"LEADS\",\"ACTIVE\"\n";
$OUToutput='';
$OUToutput .= "\n";
$OUToutput .= "---------- INDIVIDUAL LIST ID SUMMARIES\n";
while ($i < $listids_to_print)
{
$list_row=mysqli_fetch_row($list_rslt);
$LISTIDlists[$i] = $list_row[0];
$LISTIDlist_names[$i] = $list_row[1];
if ($list_row[2]=="Y") {$active_txt="ACTIVE";} else {$active_txt="INACTIVE";}
$active_txt=sprintf("%-8s", $active_txt);
$LISTIDcalls[$i] = $list_row[3];
$TOTALleads =$list_row[3];
$totalTOTALleads+=$TOTALleads;
$LISTIDcount = sprintf("%10s", $LISTIDcalls[$i]);while(strlen($LISTIDcount)>10) {$LISTIDcount = substr("$LISTIDcount", 0, -1);}
$LISTIDname = sprintf("%-40s", "$LISTIDlists[$i] - $LISTIDlist_names[$i]");while(strlen($LISTIDname)>40) {$LISTIDname = substr("$LISTIDname", 0, -1);}
$totalOUToutput .= "| $LISTIDname | $LISTIDcount | $active_txt |\n";
$CSV_textSUMMARY.="\"$LISTIDname\",\"$LISTIDcount\",\"$active_txt\"\n";
$OUToutput .= "\n";
$OUToutput .= "---------- LIST ID SUMMARY <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=1\">DOWNLOAD LIST SUMMARIES</a>\n";
$OUToutput .= "+--------------------------------------------------------+\n";
$OUToutput .= "| LIST ID: ".sprintf("%-30s", $list_row[0])." ".sprintf("%-8s", $active_txt)." |\n";
$OUToutput .= "| LIST NAME: ".sprintf("%-30s", $list_row[1])." ".sprintf("%8s", "")." |\n";
$OUToutput .= "| TOTAL LEADS: ".sprintf("%-30s", $list_row[3])." ".sprintf("%8s", "")." |\n";
$OUToutput .= "+--------------------------------------------------------+\n";
$CSV_text1.="\"$list_row[0]\",\"$list_row[1]\",\"$list_row[3]\",\"$active_txt\"\n";
$CSV_textALL.="\"LIST ID #$list_row[0] SUMMARY\",\"\"\n";
$CSV_textALL.="\"LIST NAME\",\"TOTAL LEADS\",\"ACTIVE/INACTIVE\"\n";
$CSV_textALL.="\"$list_row[1]\",\"$list_row[3]\",\"$active_txt\"\n";
# $list_id_SQL .= "'$row[0]',";
# if ($row[0]>$max_calls) {$max_calls=$row[3];}
$i++;
$list_id=$list_row[0];
##############################
######### STATUS FLAGS STATS
$HA_count=0;
$HA_percent=0;
$SALE_count=0;
$SALE_percent=0;
$DNC_count=0;
$DNC_percent=0;
$CC_count=0;
$CC_percent=0;
$NI_count=0;
$NI_percent=0;
$UW_count=0;
$UW_percent=0;
$SC_count=0;
$SC_percent=0;
$COMP_count=0;
$COMP_percent=0;
$stmt="select count(*) from vicidial_list where status IN($human_answered_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$HA_results = mysqli_num_rows($rslt);
if ($HA_results > 0)
{
$row=mysqli_fetch_row($rslt);
$HA_count = $row[0];
$flag_count+=$row[0];
$category_totals["HA"]+=$HA_count;
if ($HA_count>$max_calls) {$max_calls=$HA_count;}
$HA_percent = ( MathZDC($HA_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($sale_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$SALE_results = mysqli_num_rows($rslt);
if ($SALE_results > 0)
{
$row=mysqli_fetch_row($rslt);
$SALE_count = $row[0];
$flag_count+=$row[0];
$category_totals["SALE"]+=$SALE_count;
if ($SALE_count>$max_calls) {$max_calls=$SALE_count;}
$SALE_percent = ( MathZDC($SALE_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($dnc_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$DNC_results = mysqli_num_rows($rslt);
if ($DNC_results > 0)
{
$row=mysqli_fetch_row($rslt);
$DNC_count = $row[0];
$flag_count+=$row[0];
$category_totals["DNC"]+=$DNC_count;
if ($DNC_count>$max_calls) {$max_calls=$DNC_count;}
$DNC_percent = ( MathZDC($DNC_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($customer_contact_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$CC_results = mysqli_num_rows($rslt);
if ($CC_results > 0)
{
$row=mysqli_fetch_row($rslt);
$CC_count = $row[0];
$flag_count+=$row[0];
$category_totals["CC"]+=$CC_count;
if ($C_count>$max_calls) {$max_calls=$CC_count;}
$CC_percent = ( MathZDC($CC_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($not_interested_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$NI_results = mysqli_num_rows($rslt);
if ($NI_results > 0)
{
$row=mysqli_fetch_row($rslt);
$NI_count = $row[0];
$flag_count+=$row[0];
$category_totals["NI"]+=$NI_count;
if ($NI_count>$max_calls) {$max_calls=$NI_count;}
$NI_percent = ( MathZDC($NI_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($unworkable_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$UW_results = mysqli_num_rows($rslt);
if ($UW_results > 0)
{
$row=mysqli_fetch_row($rslt);
$UW_count = $row[0];
$flag_count+=$row[0];
$category_totals["UW"]+=$UW_count;
if ($UW_count>$max_calls) {$max_calls=$UW_count;}
$UW_percent = ( MathZDC($UW_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($scheduled_callback_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$SC_results = mysqli_num_rows($rslt);
if ($SC_results > 0)
{
$row=mysqli_fetch_row($rslt);
$SC_count = $row[0];
$flag_count+=$row[0];
$category_totals["SC"]+=$SC_count;
if ($SC_count>$max_calls) {$max_calls=$SC_count;}
$SC_percent = ( MathZDC($SC_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($completed_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$COMP_results = mysqli_num_rows($rslt);
if ($COMP_results > 0)
{
$row=mysqli_fetch_row($rslt);
$COMP_count = $row[0];
$flag_count+=$row[0];
$category_totals["COMP"]+=$COMP_count;
if ($COMP_count>$max_calls) {$max_calls=$COMP_count;}
$COMP_percent = ( MathZDC($COMP_count, $TOTALleads) * 100);
}
$HA_percent = sprintf("%6.2f", "$HA_percent"); while(strlen($HA_percent)>6) {$HA_percent = substr("$HA_percent", 0, -1);}
$SALE_percent = sprintf("%6.2f", "$SALE_percent"); while(strlen($SALE_percent)>6) {$SALE_percent = substr("$SALE_percent", 0, -1);}
$DNC_percent = sprintf("%6.2f", "$DNC_percent"); while(strlen($DNC_percent)>6) {$DNC_percent = substr("$DNC_percent", 0, -1);}
$CC_percent = sprintf("%6.2f", "$CC_percent"); while(strlen($CC_percent)>6) {$CC_percent = substr("$CC_percent", 0, -1);}
$NI_percent = sprintf("%6.2f", "$NI_percent"); while(strlen($NI_percent)>6) {$NI_percent = substr("$NI_percent", 0, -1);}
$UW_percent = sprintf("%6.2f", "$UW_percent"); while(strlen($UW_percent)>6) {$UW_percent = substr("$UW_percent", 0, -1);}
$SC_percent = sprintf("%6.2f", "$SC_percent"); while(strlen($SC_percent)>6) {$SC_percent = substr("$SC_percent", 0, -1);}
$COMP_percent = sprintf("%6.2f", "$COMP_percent"); while(strlen($COMP_percent)>6) {$COMP_percent = substr("$COMP_percent", 0, -1);}
$HA_count = sprintf("%10s", "$HA_count"); while(strlen($HA_count)>10) {$HA_count = substr("$HA_count", 0, -1);}
$SALE_count = sprintf("%10s", "$SALE_count"); while(strlen($SALE_count)>10) {$SALE_count = substr("$SALE_count", 0, -1);}
$DNC_count = sprintf("%10s", "$DNC_count"); while(strlen($DNC_count)>10) {$DNC_count = substr("$DNC_count", 0, -1);}
$CC_count = sprintf("%10s", "$CC_count"); while(strlen($CC_count)>10) {$CC_count = substr("$CC_count", 0, -1);}
$NI_count = sprintf("%10s", "$NI_count"); while(strlen($NI_count)>10) {$NI_count = substr("$NI_count", 0, -1);}
$UW_count = sprintf("%10s", "$UW_count"); while(strlen($UW_count)>10) {$UW_count = substr("$UW_count", 0, -1);}
$SC_count = sprintf("%10s", "$SC_count"); while(strlen($SC_count)>10) {$SC_count = substr("$SC_count", 0, -1);}
$COMP_count = sprintf("%10s", "$COMP_count"); while(strlen($COMP_count)>10) {$COMP_count = substr("$COMP_count", 0, -1);}
$OUToutput .= "\n";
$OUToutput .= "---------- STATUS FLAGS BREAKDOWN: (and % of total leads in list) <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=2\">DOWNLOAD FLAG BREAKDOWNS</a>\n";
$OUToutput .= "+------------------+------------+----------+\n";
$OUToutput .= "| Human Answer | $HA_count | $HA_percent% |\n";
$OUToutput .= "| Sale | $SALE_count | $SALE_percent% |\n";
$OUToutput .= "| DNC | $DNC_count | $DNC_percent% |\n";
$OUToutput .= "| Customer Contact | $CC_count | $CC_percent% |\n";
$OUToutput .= "| Not Interested | $NI_count | $NI_percent% |\n";
$OUToutput .= "| Unworkable | $UW_count | $UW_percent% |\n";
$OUToutput .= "| Sched Callbacks | $SC_count | $SC_percent% |\n";
$OUToutput .= "| Completed | $COMP_count | $COMP_percent% |\n";
$OUToutput .= "+------------------+------------+----------+\n";
$OUToutput .= "\n";
$CSV_text_block = "\"STATUS FLAGS SUMMARY FOR LIST ID #$list_id:\"\n";
$CSV_text_block .= "\"Human Answer\",\"$HA_count\",\"$HA_percent%\"\n";
$CSV_text_block .= "\"Sale\",\"$SALE_count\",\"$SALE_percent%\"\n";
$CSV_text_block .= "\"DNC\",\"$DNC_count\",\"$DNC_percent%\"\n";
$CSV_text_block .= "\"Customer Contact\",\"$CC_count\",\"$CC_percent%\"\n";
$CSV_text_block .= "\"Not Interested\",\"$NI_count\",\"$NI_percent%\"\n";
$CSV_text_block .= "\"Unworkable\",\"$UW_count\",\"$UW_percent%\"\n";
$CSV_text_block .= "\"Scheduled Callbacks\",\"$SC_count\",\"$SC_percent%\"\n";
$CSV_text_block .= "\"Completed\",\"$COMP_count\",\"$COMP_percent%\"\n\n";
$CSV_text2.=$CSV_text_block;
$CSV_textALL.="\n".$CSV_text_block;
$stmt="select status, count(*) From vicidial_list where list_id='$list_id' group by status order by status asc";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$OUToutput .= "---------- STATUS BREAKDOWN: (and % of total leads in list) <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=3\">DOWNLOAD STAT BREAKDOWNS</a>\n";
$OUToutput .= "+--------+--------------------------------+----------+---------+\n";
$OUToutput .= "| STATUS | STATUS NAME | COUNT | LEAD % |\n";
$OUToutput .= "+--------+--------------------------------+----------+---------+\n";
$CSV_text3.="\"\",\"STATUS BREAKDOWN FOR LIST ID #$list_id:\"\n";
$CSV_text3.="\"STATUS\",\"STATUS NAME\",\"COUNT\",\"LEAD %\"\n";
$CSV_textALL.="\"STATUS BREAKDOWN FOR LIST ID #$list_id:\",\"\"\n";
$CSV_textALL.="\"STATUS\",\"STATUS NAME\",\"COUNT\",\"LEAD %\"\n";
while ($row=mysqli_fetch_row($rslt))
{
$OUToutput .= "| ".sprintf("%6s", $row[0])." | ".sprintf("%30s", $statname_list["$row[0]"])." | ".sprintf("%8s", $row[1])." | ".sprintf("%6.2f", ( MathZDC($row[1], $TOTALleads) * 100))."% |\n";
$CSV_text3.="\"$row[0]\",\"".$statname_list["$row[0]"]."\",\"$row[1]\",\"".sprintf("%6.2f", ( MathZDC($row[1], $TOTALleads) * 100))."%\"\n";
$CSV_textALL.="\"$row[0]\",\"".$statname_list["$row[0]"]."\",\"$row[1]\",\"".sprintf("%6.2f", ( MathZDC($row[1], $TOTALleads) * 100))."%\"\n";
}
$OUToutput .= "+-----------------------------------------+----------+---------+\n";
$OUToutput .= "| | ".sprintf("%8s", $TOTALleads)." | 100.00% |\n";
$OUToutput .= "+-----------------------------------------+----------+---------+\n";
$CSV_text3.="\"\",\"\",\"$TOTALleads\",\"100.00%\"\n\n\n";
$CSV_textALL.="\"\",\"\",\"$TOTALleads\",\"100.00%\"\n\n\n";
$OUToutput .= "\n";
$OUToutput .= "\n";
$OUToutput .= "\n";
}
$total_HA_percent = sprintf("%6.2f", ( MathZDC($category_totals["HA"], $totalTOTALleads) * 100)); while(strlen($total_HA_percent)>6) {$total_HA_percent = substr("$total_HA_percent", 0, -1);}
$total_SALE_percent = sprintf("%6.2f", ( MathZDC($category_totals["SALE"], $totalTOTALleads) * 100)); while(strlen($total_SALE_percent)>6) {$total_SALE_percent = substr("$total_SALE_percent", 0, -1);}
$total_DNC_percent = sprintf("%6.2f", ( MathZDC($category_totals["DNC"], $totalTOTALleads) * 100)); while(strlen($total_DNC_percent)>6) {$total_DNC_percent = substr("$total_DNC_percent", 0, -1);}
$total_CC_percent = sprintf("%6.2f", ( MathZDC($category_totals["CC"], $totalTOTALleads) * 100)); while(strlen($total_CC_percent)>6) {$total_CC_percent = substr("$total_CC_percent", 0, -1);}
$total_NI_percent = sprintf("%6.2f", ( MathZDC($category_totals["NI"], $totalTOTALleads) * 100)); while(strlen($total_NI_percent)>6) {$total_NI_percent = substr("$total_NI_percent", 0, -1);}
$total_UW_percent = sprintf("%6.2f", ( MathZDC($category_totals["UW"], $totalTOTALleads) * 100)); while(strlen($total_UW_percent)>6) {$total_UW_percent = substr("$total_UW_percent", 0, -1);}
$total_SC_percent = sprintf("%6.2f", ( MathZDC($category_totals["SC"], $totalTOTALleads) * 100)); while(strlen($total_SC_percent)>6) {$total_SC_percent = substr("$total_SC_percent", 0, -1);}
$total_COMP_percent = sprintf("%6.2f", ( MathZDC($category_totals["COMP"], $totalTOTALleads) * 100)); while(strlen($total_COMP_percent)>6) {$total_COMP_percent = substr("$total_COMP_percent", 0, -1);}
$total_HA_count = sprintf("%10s", $category_totals["HA"]); while(strlen($total_HA_count)>10) {$total_HA_count = substr("$total_HA_count", 0, -1);}
$total_SALE_count = sprintf("%10s", $category_totals["SALE"]); while(strlen($total_SALE_count)>10) {$total_SALE_count = substr("$total_SALE_count", 0, -1);}
$total_DNC_count = sprintf("%10s", $category_totals["DNC"]); while(strlen($total_DNC_count)>10) {$total_DNC_count = substr("$total_DNC_count", 0, -1);}
$total_CC_count = sprintf("%10s", $category_totals["CC"]); while(strlen($total_CC_count)>10) {$total_CC_count = substr("$total_CC_count", 0, -1);}
$total_NI_count = sprintf("%10s", $category_totals["NI"]); while(strlen($total_NI_count)>10) {$total_NI_count = substr("$total_NI_count", 0, -1);}
$total_UW_count = sprintf("%10s", $category_totals["UW"]); while(strlen($total_UW_count)>10) {$total_UW_count = substr("$total_UW_count", 0, -1);}
$total_SC_count = sprintf("%10s", $category_totals["SC"]); while(strlen($total_SC_count)>10) {$total_SC_count = substr("$total_SC_count", 0, -1);}
$total_COMP_count = sprintf("%10s", $category_totals["COMP"]); while(strlen($total_COMP_count)>10) {$total_COMP_count = substr("$total_COMP_count", 0, -1);}
$totalOUToutput .= "+------------------------------------------+------------+----------+\n";
$totalOUToutput .= "| TOTAL | ".sprintf("%10s", $totalTOTALleads)." |\n";
$totalOUToutput .= "+------------------------------------------+------------+\n";
$CSV_textSUMMARY .= "\"TOTAL\",\"$totalTOTALleads\"\n";
$totalOUToutput .= "\n";
$totalOUToutput .= "\n";
$totalOUToutput .= "---------- TOTAL STATUS FLAGS SUMMARY: (and % of leads in selected lists) <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=ALL\">DOWNLOAD FULL REPORT</a>\n";
$totalOUToutput .= "+------------------+------------+----------+\n";
$totalOUToutput .= "| Human Answer | $total_HA_count | $total_HA_percent% |\n";
$totalOUToutput .= "| Sale | $total_SALE_count | $total_SALE_percent% |\n";
$totalOUToutput .= "| DNC | $total_DNC_count | $total_DNC_percent% |\n";
$totalOUToutput .= "| Customer Contact | $total_CC_count | $total_CC_percent% |\n";
$totalOUToutput .= "| Not Interested | $total_NI_count | $total_NI_percent% |\n";
$totalOUToutput .= "| Unworkable | $total_UW_count | $total_UW_percent% |\n";
$totalOUToutput .= "| Sched Callbacks | $total_SC_count | $total_SC_percent% |\n";
$totalOUToutput .= "| Completed | $total_COMP_count | $total_COMP_percent% |\n";
$totalOUToutput .= "+------------------+------------+----------+\n";
$totalOUToutput .= "\n\n\n";
$CSV_textSUMMARY .= "\n\"STATUS FLAGS SUMMARY:\"\n";
$CSV_textSUMMARY .= "\"Human Answer\",\"$total_HA_count\",\"$total_HA_percent%\"\n";
$CSV_textSUMMARY .= "\"Sale\",\"$total_SALE_count\",\"$total_SALE_percent%\"\n";
$CSV_textSUMMARY .= "\"DNC\",\"$total_DNC_count\",\"$total_DNC_percent%\"\n";
$CSV_textSUMMARY .= "\"Customer Contact\",\"$total_CC_count\",\"$total_CC_percent%\"\n";
$CSV_textSUMMARY .= "\"Not Interested\",\"$total_NI_count\",\"$total_NI_percent%\"\n";
$CSV_textSUMMARY .= "\"Unworkable\",\"$total_UW_count\",\"$total_UW_percent%\"\n";
$CSV_textSUMMARY .= "\"Scheduled Callbacks\",\"$total_SC_count\",\"$total_SC_percent%\"\n";
$CSV_textSUMMARY .= "\"Completed\",\"$total_COMP_count\",\"$total_COMP_percent%\"\n\n\n\n";
$CSV_textALL=$CSV_textSUMMARY.$CSV_textALL;
if ($report_display_type=="HTML")
{
$MAIN.=$GRAPH;
}
else
{
$MAIN.="$totalOUToutput$OUToutput";
}
$ENDtime = date("U");
$RUNtime = ($ENDtime - $STARTtime);
$MAIN.="\nRun Time: $RUNtime seconds|$db_source\n";
$MAIN.="</PRE>\n";
$MAIN.="</TD></TR></TABLE>\n";
$MAIN.="</BODY></HTML>\n";
}
if ($file_download>0 || $file_download=="ALL") {
$FILE_TIME = date("Ymd-His");
$CSVfilename = "AST_LISTS_stats_$US$FILE_TIME.csv";
$CSV_var="CSV_text".$file_download;
$CSV_text=preg_replace('/^ +/', '', $$CSV_var);
$CSV_text=preg_replace('/\n +,/', ',', $CSV_text);
$CSV_text=preg_replace('/ +\"/', '"', $CSV_text);
$CSV_text=preg_replace('/\" +/', '"', $CSV_text);
// We'll be outputting a TXT file
header('Content-type: application/octet-stream');
// It will be called LIST_101_20090209-121212.txt
header("Content-Disposition: attachment; filename=\"$CSVfilename\"");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
echo "$CSV_text";
} else {
$JS_onload.="}\n";
$JS_text.=$JS_onload;
$JS_text.="</script>\n";
echo $HEADER;
echo $JS_text;
require("admin_header.php");
echo $MAIN;
}
if ($db_source == 'S')
{
mysqli_close($link);
$use_slave_server=0;
$db_source = 'M';
require("dbconnect.php");
}
$endMS = microtime();
$startMSary = explode(" ",$startMS);
$endMSary = explode(" ",$endMS);
$runS = ($endMSary[0] - $startMSary[0]);
$runM = ($endMSary[1] - $startMSary[1]);
$TOTALrun = ($runS + $runM);
$stmt="UPDATE vicidial_report_log set run_time='$TOTALrun' where report_log_id='$report_log_id';";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
exit;
?>
|
agpl-3.0
|
d3b-center/pedcbioportal
|
service/src/main/java/org/cbioportal/service/impl/CopyNumberEnrichmentServiceImpl.java
|
5177
|
package org.cbioportal.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.cbioportal.model.AlterationCountByGene;
import org.cbioportal.model.AlterationEnrichment;
import org.cbioportal.model.CopyNumberCountByGene;
import org.cbioportal.model.MolecularProfileCaseIdentifier;
import org.cbioportal.service.CopyNumberEnrichmentService;
import org.cbioportal.service.DiscreteCopyNumberService;
import org.cbioportal.service.exception.MolecularProfileNotFoundException;
import org.cbioportal.service.util.AlterationEnrichmentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CopyNumberEnrichmentServiceImpl implements CopyNumberEnrichmentService {
@Autowired
private DiscreteCopyNumberService discreteCopyNumberService;
@Autowired
private AlterationEnrichmentUtil alterationEnrichmentUtil;
@Override
public List<AlterationEnrichment> getCopyNumberEnrichments(
Map<String, List<MolecularProfileCaseIdentifier>> molecularProfileCaseSets,
List<Integer> alterationTypes,
String enrichmentType) throws MolecularProfileNotFoundException {
Map<String, List<? extends AlterationCountByGene>> copyNumberCountByGeneAndGroup = new HashMap<>();
if (enrichmentType.equals("SAMPLE")) {
copyNumberCountByGeneAndGroup = molecularProfileCaseSets
.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> { //set value of each group to list of CopyNumberCountByGene
List<String> molecularProfileIds = new ArrayList<>();
List<String> sampleIds = new ArrayList<>();
entry.getValue().forEach(molecularProfileCase -> {
molecularProfileIds.add(molecularProfileCase.getMolecularProfileId());
sampleIds.add(molecularProfileCase.getCaseId());
});
return discreteCopyNumberService
.getSampleCountInMultipleMolecularProfiles(
molecularProfileIds,
sampleIds,
null,
alterationTypes,
false);
}));
} else {
copyNumberCountByGeneAndGroup = molecularProfileCaseSets.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> { //set value of each group to list of CopyNumberCountByGene
Map<String, List<MolecularProfileCaseIdentifier>> molecularProfileCaseIdentifiersMap = entry
.getValue().stream()
.collect(Collectors.groupingBy(MolecularProfileCaseIdentifier::getMolecularProfileId));
return molecularProfileCaseIdentifiersMap
.entrySet()
.stream()
.flatMap(molecularProfileCaseIdentifiers -> {
String molecularProfileId = molecularProfileCaseIdentifiers.getKey();
List<String> caseIds = molecularProfileCaseIdentifiers
.getValue()
.stream()
.map(MolecularProfileCaseIdentifier::getCaseId)
.collect(Collectors.toList());
return discreteCopyNumberService
.getPatientCountByGeneAndAlterationAndPatientIds(
molecularProfileId,
caseIds,
null,
alterationTypes)
.stream();
})
.collect(Collectors.toList());
}));
}
return alterationEnrichmentUtil
.createAlterationEnrichments(
copyNumberCountByGeneAndGroup,
molecularProfileCaseSets,
enrichmentType);
}
}
|
agpl-3.0
|
stadt-karlsruhe/ckanext-discovery
|
ckanext/discovery/plugins/discovery.py
|
999
|
# encoding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import logging
import os.path
import sys
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckan.lib.plugins import DefaultTranslation
from . import get_config
log = logging.getLogger(__name__)
class DiscoveryPlugin(plugins.SingletonPlugin, DefaultTranslation):
plugins.implements(plugins.ITemplateHelpers)
plugins.implements(plugins.ITranslation)
#
# ITemplateHelpers
#
def get_helpers(self):
return {
'discovery_get_config': get_config,
'discovery_as_bool': toolkit.asbool,
}
#
# ITranslation
#
def i18n_directory(self):
module = sys.modules['ckanext.discovery']
module_dir = os.path.abspath(os.path.dirname(module.__file__))
return os.path.join(module_dir, 'i18n')
def i18n_domain(self):
return 'ckanext-discovery'
|
agpl-3.0
|
intechWiFi/doatools
|
doc/puppet_providers_iam_policy/awscli.html
|
2443
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
Provider: awscli
— Documentation by YARD 0.9.8
</title>
<link rel="stylesheet" href="../css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8" />
<script type="text/javascript" charset="utf-8">
pathId = "puppet_providers_iam_policy::awscli";
relpath = '../';
</script>
<script type="text/javascript" charset="utf-8" src="../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/app.js"></script>
</head>
<body>
<div class="nav_wrap">
<iframe id="nav" src="../puppet_provider_list.html?1"></iframe>
<div id="resizer"></div>
</div>
<div id="main" tabindex="-1">
<div id="header">
<div id="menu">
<a href="../_index.html">Index (a)</a> »
<span class='title'><span class='object_link'>Providers</span></span>
»
<span class="title">awscli</span>
</div>
<div id="search">
<a class="full_list_link" id="puppet_class_list_link"
href="../puppet_class_list.html">
<svg width="24" height="24">
<rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
<rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
<rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
</svg>
</a>
</div>
<div class="clear"></div>
</div>
<div id="content"><h1>Provider: awscli</h1>
<div class="box_info">
<dl>
<dt>Defined in:</dt>
<dd>
lib/puppet/provider/iam_policy/awscli.rb
</dd>
</dl>
<dl>
<dt>Resource type:</dt>
<dd><span class='object_link'><a href="../puppet_types/iam_policy.html" title="puppet_types::iam_policy (puppet_type)">iam_policy</a></span></dd>
</dl>
</div>
<h2>Overview</h2>
<div class="docstring">
<div class="discussion">
</div>
</div>
<div class="tags">
</div>
<div class="tags">
<p class="tag_title">Commands</p>
<ul>
<li><tt>awscli — aws</tt></li>
</ul>
</div>
</div>
<div id="footer">
Generated on Mon Apr 24 11:16:28 2017 by
<a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_parent">yard</a>
0.9.8 (ruby-2.1.9).
</div>
</div>
</body>
</html>
|
agpl-3.0
|
odoo-arg/odoo_l10n_ar
|
l10n_ar/wizard/__init__.py
|
951
|
# - coding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import models
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
o2oa/o2oa
|
o2server/x_processplatform_assemble_designer/src/main/java/com/x/processplatform/assemble/designer/jaxrs/projection/ActionEnable.java
|
1828
|
//package com.x.processplatform.assemble.designer.jaxrs.projection;
//
//import com.x.base.core.container.EntityManagerContainer;
//import com.x.base.core.container.factory.EntityManagerContainerFactory;
//import com.x.base.core.project.exception.ExceptionAccessDenied;
//import com.x.base.core.project.exception.ExceptionEntityNotExist;
//import com.x.base.core.project.http.ActionResult;
//import com.x.base.core.project.http.EffectivePerson;
//import com.x.base.core.project.jaxrs.WrapBoolean;
//import com.x.processplatform.assemble.designer.Business;
//import com.x.processplatform.core.entity.element.Application;
//import com.x.processplatform.core.entity.element.Projection;
//
//class ActionEnable extends BaseAction {
//
// ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception {
// try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
// ActionResult<Wo> result = new ActionResult<>();
//
// Business business = new Business(emc);
//
// Projection projection = emc.flag(flag, Projection.class);
//
// if (null == projection) {
// throw new ExceptionEntityNotExist(flag, Projection.class);
// }
//
// Application application = emc.flag(projection.getApplication(), Application.class);
//
// if (null == application) {
// throw new ExceptionEntityNotExist(projection.getApplication(), Application.class);
// }
//
// if (!business.editable(effectivePerson, application)) {
// throw new ExceptionAccessDenied(effectivePerson.getDistinguishedName());
// }
//
// emc.beginTransaction(Projection.class);
// projection.setEnable(true);
// emc.commit();
// Wo wo = new Wo();
// wo.setValue(true);
// result.setData(wo);
// return result;
// }
// }
//
// public static class Wo extends WrapBoolean {
//
// }
//
//}
|
agpl-3.0
|
imCodePartnerAB/imcms
|
src/main/webapp/imcms/js/builders/components/page_info_tabs/imcms-templates-tab-builder.js
|
2976
|
define("imcms-templates-tab-builder",
[
"imcms-bem-builder", "imcms-components-builder", "imcms-templates-rest-api", "imcms-document-types",
"imcms-i18n-texts", "imcms-page-info-tab"
],
function (BEM, components, templatesRestApi, docTypes, texts, PageInfoTab) {
texts = texts.pageInfo.appearance;
const tabData = {};
const TemplatesTab = function (name, docType) {
PageInfoTab.apply(this, arguments);
};
TemplatesTab.prototype = Object.create(PageInfoTab.prototype);
TemplatesTab.prototype.tabElementsFactory = () => {
const $templateSelectContainer = components.selects.selectContainer("<div>", {
name: "template",
text: texts.template
}),
$templateSelect = $templateSelectContainer.getSelect(),
$defaultChildTemplateSelectContainer = components.selects.selectContainer("<div>", {
name: "childTemplate",
text: texts.defaultChildTemplate
}),
$defaultChildTemplateSelect = $defaultChildTemplateSelectContainer.getSelect();
tabData.$templateSelect = $templateSelect;
tabData.$defaultChildTemplateSelect = $defaultChildTemplateSelect;
templatesRestApi.read(null)
.done(templates => {
const templatesDataMapped = templates.map(template => ({
text: template.name,
"data-value": template.name
}));
components.selects.addOptionsToSelect(templatesDataMapped, $templateSelect);
components.selects.addOptionsToSelect(templatesDataMapped, $defaultChildTemplateSelect);
});
return [
$templateSelectContainer,
$defaultChildTemplateSelectContainer
];
};
TemplatesTab.prototype.fillTabDataFromDocument = document => {
if (document.template) {
tabData.$templateSelect.selectValue(document.template.templateName);
tabData.$defaultChildTemplateSelect.selectValue(document.template.childrenTemplateName);
}
};
TemplatesTab.prototype.saveData = function (documentDTO) {
if (!this.isDocumentTypeSupported(documentDTO.type)) {
return documentDTO;
}
documentDTO.template.templateName = tabData.$templateSelect.getSelectedValue();
documentDTO.template.childrenTemplateName = tabData.$defaultChildTemplateSelect.getSelectedValue();
return documentDTO;
};
TemplatesTab.prototype.clearTabData = () => {
tabData.$templateSelect.selectFirst();
tabData.$defaultChildTemplateSelect.selectFirst();
};
return new TemplatesTab(texts.name, docTypes.TEXT);
}
);
|
agpl-3.0
|
antoine-de/navitia
|
source/jormungandr/tests/ptref_tests.py
|
38313
|
# encoding: utf-8
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive locomotion way of traveling!
#
# LICENCE: This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# IRC #navitia on freenode
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, unicode_literals, division
from six.moves.urllib.parse import quote, quote_plus
from .check_utils import journey_basic_query
from .tests_mechanism import dataset, AbstractTestFixture
from .check_utils import *
from six.moves import range
@dataset({"main_ptref_test": {}})
class TestPtRef(AbstractTestFixture):
"""
Test the structure of the ptref response
"""
@staticmethod
def _test_links(response, pt_obj_name):
# Test the validity of links of 'previous', 'next', 'last', 'first'
wanted_links_type = ['previous', 'next', 'last', 'first']
for l in response['links']:
if l['type'] in wanted_links_type:
assert pt_obj_name in l['href']
# Test the consistency between links
wanted_links = [l['href'] for l in response['links'] if l['type'] in wanted_links_type]
if len(wanted_links) <= 1:
return
def _get_dict_to_compare(link):
url_dict = query_from_str(link)
url_dict.pop('start_page', None)
url_dict['url'] = link.split('?')[0]
return url_dict
url_dict = _get_dict_to_compare(wanted_links[0])
for l in wanted_links[1:]:
assert url_dict == _get_dict_to_compare(l)
def test_pagination_links_with_count(self):
response = self.query_region("stop_points?count=2&start_page=2", display=True)
for link in response['links']:
if link['type'] in ('previous', 'next', 'first', 'last'):
assert 'count=2' in link['href']
def test_vj_default_depth(self):
"""default depth is 1"""
response = self.query_region("vehicle_journeys")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
assert len(vjs) == 3
vj = vjs[0]
assert vj['id'] == 'vj1'
assert len(vj['stop_times']) == 2
assert vj['stop_times'][0]['arrival_time'] == '101500'
assert vj['stop_times'][0]['departure_time'] == '101500'
assert vj['stop_times'][1]['arrival_time'] == '111000'
assert vj['stop_times'][1]['departure_time'] == '111000'
#we added some comments on the vj, we should have them
com = get_not_null(vj, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == 'hello'
assert "feed_publishers" in response
feed_publishers = response["feed_publishers"]
for feed_publisher in feed_publishers:
is_valid_feed_publisher(feed_publisher)
feed_publisher = feed_publishers[1]
assert (feed_publisher["id"] == "c1")
assert (feed_publisher["name"] == "name-c1")
assert (feed_publisher["license"] == "ls-c1")
assert (feed_publisher["url"] == "ws-c1")
feed_publisher = feed_publishers[0]
assert (feed_publisher["id"] == "builder")
assert (feed_publisher["name"] == "canal tp")
assert (feed_publisher["license"] == "ODBL")
assert (feed_publisher["url"] == "www.canaltp.fr")
def test_vj_depth_0(self):
"""default depth is 1"""
response = self.query_region("vehicle_journeys?depth=0")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=0)
def test_vj_depth_2(self):
"""default depth is 1"""
response = self.query_region("vehicle_journeys?depth=2")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=2)
def test_vj_depth_3(self):
"""default depth is 1"""
response = self.query_region("vehicle_journeys?depth=3")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=3)
def test_vj_show_codes_propagation(self):
"""stop_area:stop1 has a code, we should be able to find it when accessing it by the vj"""
response = self.query_region("stop_areas/stop_area:stop1/vehicle_journeys")
vjs = get_not_null(response, 'vehicle_journeys')
assert vjs
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
stop_points = [get_not_null(st, 'stop_point') for vj in vjs for st in vj['stop_times']]
stops1 = [s for s in stop_points if s['id'] == 'stop_area:stop1']
assert stops1
for stop1 in stops1:
# all reference to stop1 must have it's codes
codes = get_not_null(stop1, 'codes')
code_uic = [c for c in codes if c['type'] == 'code_uic']
assert len(code_uic) == 1 and code_uic[0]['value'] == 'bobette'
def test_ptref_without_current_datetime(self):
"""
stop_area:stop1 without message because _current_datetime is NOW()
"""
response = self.query_region("stop_areas/stop_area:stop1")
assert len(response['disruptions']) == 0
def test_ptref_invalid_type(self):
response, code = self.query_region("AAAAAA/stop_areas", check=False)
assert code == 400
assert response['message'] == 'unknown type: AAAAAA'
coord = "{lon};{lat}".format(lon=1.2, lat=3.4)
response, code = self.query_region("{coord}/stop_areas".format(coord=coord), check=False)
assert code == 400
assert response['message'] == 'unknown type: {coord}'.format(coord=coord)
def test_ptref_with_current_datetime(self):
"""
stop_area:stop1 with _current_datetime
"""
response = self.query_region("stop_areas/stop_area:stop1?_current_datetime=20140115T235959")
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 1
messages = get_not_null(disruptions[0], 'messages')
assert(messages[0]['text']) == 'Disruption on StopArea stop_area:stop1'
def test_contributors(self):
"""test contributor formating"""
response = self.query_region("contributors")
contributors = get_not_null(response, 'contributors')
assert len(contributors) == 1
ctr = contributors[0]
assert(ctr["id"] == 'c1')
assert(ctr["website"] == 'ws-c1')
assert(ctr["license"] == 'ls-c1')
def test_datasets(self):
"""test dataset formating"""
response = self.query_region("datasets")
datasets = get_not_null(response, 'datasets')
assert len(datasets) == 1
ds = datasets[0]
assert(ds["id"] == 'd1')
assert(ds["description"] == 'desc-d1')
assert(ds["system"] == 'sys-d1')
def test_contributor_by_dataset(self):
"""test contributor by dataset formating"""
response = self.query_region("datasets/d1/contributors")
ctrs = get_not_null(response, 'contributors')
assert len(ctrs) == 1
ctr = ctrs[0]
assert(ctr["id"] == 'c1')
assert(ctr["website"] == 'ws-c1')
assert(ctr["license"] == 'ls-c1')
def test_dataset_by_contributor(self):
"""test dataset by contributor formating"""
response = self.query_region("contributors/c1/datasets")
frs = get_not_null(response, 'datasets')
assert len(frs) == 1
fr = frs[0]
assert(fr["id"] == 'd1')
def test_line(self):
"""test line formating"""
response = self.query_region("lines")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
assert l["text_color"] == 'FFD700'
#we know we have a geojson for this test so we can check it
geo = get_not_null(l, 'geojson')
shape(geo)
com = get_not_null(l, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "I'm a happy comment"
physical_modes = get_not_null(l, 'physical_modes')
assert len(physical_modes) == 1
is_valid_physical_mode(physical_modes[0], depth_check=1)
assert physical_modes[0]['id'] == 'physical_mode:Car'
assert physical_modes[0]['name'] == 'name physical_mode:Car'
line_group = get_not_null(l, 'line_groups')
assert len(line_group) == 1
is_valid_line_group(line_group[0], depth_check=0)
assert line_group[0]['name'] == 'A group'
assert line_group[0]['id'] == 'group:A'
self._test_links(response, 'lines')
def test_line_without_shape(self):
"""test line formating with shape disabled"""
response = self.query_region("lines?disable_geojson=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
#we don't want a geojson since we have desactivate them
assert 'geojson' not in l
response = self.query_region("lines")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
#we check our geojson, just to be safe :)
assert 'geojson' in l
geo = get_not_null(l, 'geojson')
shape(geo)
def test_line_with_shape(self):
"""test line formating with shape explicitly enabled"""
response = self.query_region("lines?disable_geojson=false")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
# Test that the geojson is indeed there
geo = get_not_null(l, 'geojson')
shape(geo)
def test_line_groups(self):
"""test line group formating"""
# Test for each possible range to ensure main_line is always at a depth of 0
for depth in range(0,3):
response = self.query_region("line_groups?depth={0}".format(depth))
line_groups = get_not_null(response, 'line_groups')
assert len(line_groups) == 1
lg = line_groups[0]
is_valid_line_group(lg, depth_check=depth)
if depth > 0:
com = get_not_null(lg, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "I'm a happy comment"
# test if line_groups are accessible through the ptref graph
response = self.query_region("routes/line:A:0/line_groups")
line_groups = get_not_null(response, 'line_groups')
assert len(line_groups) == 1
lg = line_groups[0]
is_valid_line_group(lg)
def test_line_with_active_disruption(self):
"""test disruption is active"""
response = self.query_region("lines/line:A?_current_datetime=20140115T235959")
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 1
d = disruptions[0]
# in pt_ref, the status is always active as the checked
# period is the validity period
assert d["status"] == "active"
messages = get_not_null(d, 'messages')
assert(messages[0]['text']) == 'Disruption on Line line:A'
def test_line_codes(self):
"""test line formating"""
response = self.query_region("lines/line:A?show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
l = lines[0]
codes = get_not_null(l, 'codes')
assert len(codes) == 4
is_valid_codes(codes)
def test_route(self):
"""test line formating"""
response = self.query_region("routes")
routes = get_not_null(response, 'routes')
assert len(routes) == 3
r = [r for r in routes if r['id'] == 'line:A:0']
assert len(r) == 1
r = r[0]
is_valid_route(r, depth_check=1)
#we know we have a geojson for this test so we can check it
geo = get_not_null(r, 'geojson')
shape(geo)
com = get_not_null(r, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "I'm a happy comment"
self._test_links(response, 'routes')
def test_stop_areas(self):
"""test stop_areas formating"""
response = self.query_region("stop_areas")
stops = get_not_null(response, 'stop_areas')
assert len(stops) == 3
s = next((s for s in stops if s['name'] == 'stop_area:stop1'))
is_valid_stop_area(s, depth_check=1)
com = get_not_null(s, 'comments')
assert len(com) == 2
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "comment on stop A"
assert com[1]['type'] == 'standard'
assert com[1]['value'] == "the stop is sad"
self._test_links(response, 'stop_areas')
def test_stop_area(self):
"""test stop_areas formating"""
response = self.query_region("stop_areas/stop_area:stop1?depth=2")
stops = get_not_null(response, 'stop_areas')
assert len(stops) == 1
is_valid_stop_area(stops[0], depth_check=2)
modes = get_not_null(stops[0], 'physical_modes')
assert len(modes) == 1
modes = get_not_null(stops[0], 'commercial_modes')
assert len(modes) == 1
def test_stop_points(self):
"""test stop_points formating"""
response = self.query_region("stop_points?depth=2")
stops = get_not_null(response, 'stop_points')
assert len(stops) == 3
s = next((s for s in stops if s['name'] == 'stop_area:stop2'))# yes, that's a stop_point
is_valid_stop_point(s, depth_check=2)
com = get_not_null(s, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "hello bob"
modes = get_not_null(s, 'physical_modes')
assert len(modes) == 1
is_valid_physical_mode(modes[0], depth_check=1)
modes = get_not_null(s, 'commercial_modes')
assert len(modes) == 1
is_valid_commercial_mode(modes[0], depth_check=1)
self._test_links(response, 'stop_points')
def test_company_default_depth(self):
"""default depth is 1"""
response = self.query_region("companies")
companies = get_not_null(response, 'companies')
for company in companies:
is_valid_company(company, depth_check=1)
#we check afterward that we have the right data
#we know there is only one vj in the dataset
assert len(companies) == 1
company = companies[0]
assert company['id'] == 'CMP1'
self._test_links(response, 'companies')
def test_simple_crow_fly(self):
journey_basic_query = "journeys?from=9;9.001&to=stop_area%3Astop2&datetime=20140105T000000"
response = self.query_region(journey_basic_query)
#the response must be still valid (this test the kraken data reloading)
self.is_valid_journey_response(response, journey_basic_query)
def test_forbidden_uris_on_line(self):
"""test forbidden uri for lines"""
response = self.query_region("lines")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
assert len(lines[0]['physical_modes']) == 1
assert lines[0]['physical_modes'][0]['id'] == 'physical_mode:Car'
#there is only one line, so when we forbid it's physical mode, we find nothing
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines"
"?forbidden_uris[]=physical_mode:Car")
assert code == 404
# for retrocompatibility purpose forbidden_id[] is the same
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines"
"?forbidden_id[]=physical_mode:Car")
assert code == 404
# when we forbid another physical_mode, we find again our line
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines"
"?forbidden_uris[]=physical_mode:Bus")
assert code == 200
def test_simple_pt_objects(self):
response = self.query_region('pt_objects?q=stop2')
is_valid_pt_objects_response(response)
pt_objs = get_not_null(response, 'pt_objects')
assert len(pt_objs) == 1
assert get_not_null(pt_objs[0], 'id') == 'stop_area:stop2'
def test_line_label_pt_objects(self):
response = self.query_region('pt_objects?q=line:A&type[]=line')
is_valid_pt_objects_response(response)
pt_objs = get_not_null(response, 'pt_objects')
assert len(pt_objs) == 1
assert get_not_null(pt_objs[0], 'name') == 'base_network Car line:A'
response = self.query_region('pt_objects?q=line:Ca roule&type[]=line')
pt_objs = get_not_null(response, 'pt_objects')
assert len(pt_objs) == 1
# not valid as there is no commercial mode (which impact name)
assert get_not_null(pt_objs[0], 'name') == 'base_network line:Ça roule'
def test_query_with_strange_char(self):
q = b'stop_points/stop_point:stop_with name bob \" , é'
encoded_q = quote(q)
response = self.query_region(encoded_q)
stops = get_not_null(response, 'stop_points')
assert len(stops) == 1
is_valid_stop_point(stops[0], depth_check=1)
assert stops[0]["id"] == u'stop_point:stop_with name bob \" , é'
def test_filter_query_with_strange_char(self):
"""test that the ptref mechanism works an object with a weird id"""
response = self.query_region('stop_points/stop_point:stop_with name bob \" , é/lines')
lines = get_not_null(response, 'lines')
assert len(lines) == 1
for l in lines:
is_valid_line(l)
def test_filter_query_with_strange_char_in_filter(self):
"""test that the ptref mechanism works an object with a weird id passed in filter args"""
response = self.query_region('lines?filter=stop_point.uri="stop_point:stop_with name bob \\\" , é"')
lines = get_not_null(response, 'lines')
assert len(lines) == 1
for l in lines:
is_valid_line(l)
def test_journey_with_strange_char(self):
#we use an encoded url to be able to check the links
query = 'journeys?from={}&to={}&datetime=20140105T070000'.format(quote_plus(b'stop_with name bob \" , é'), quote_plus(b'stop_area:stop1'))
response = self.query_region(query, display=True)
self.is_valid_journey_response(response, query)
def test_vj_period_filter(self):
"""with just a since in the middle of the period, we find vj1"""
response = self.query_region("vehicle_journeys?since=20140105T070000")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
assert 'vj1' in (vj['id'] for vj in vjs)
# same with an until at the end of the day
response = self.query_region("vehicle_journeys?since=20140105T000000&until=20140106T0000")
vjs = get_not_null(response, 'vehicle_journeys')
assert 'vj1' in (vj['id'] for vj in vjs)
# there is no vj after the 8
response, code = self.query_no_assert("v1/coverage/main_ptref_test/vehicle_journeys?since=20140109T070000")
assert code == 404
assert get_not_null(response, 'error')['message'] == 'ptref : Filters: Unable to find object'
def test_line_by_code(self):
"""test the filter=type.has_code(key, value)"""
response = self.query_region("lines?filter=line.has_code(codeB, B)&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'B' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'codeB']
response = self.query_region("lines?filter=line.has_code(codeB, Bise)&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'B' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'codeB']
response = self.query_region("lines?filter=line.has_code(codeC, C)&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'B' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'codeB']
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines?filter=line.has_code(codeB, rien)&show_codes=true")
assert code == 400
assert get_not_null(response, 'error')['message'] == 'ptref : Filters: Unable to find object'
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines?filter=line.has_code(codeC, rien)&show_codes=true")
assert code == 400
assert get_not_null(response, 'error')['message'] == 'ptref : Filters: Unable to find object'
def test_pt_ref_internal_method(self):
from jormungandr import i_manager
from navitiacommon import type_pb2
i = i_manager.instances['main_ptref_test']
assert len([r for r in i.ptref.get_objs(type_pb2.ROUTE)]) == 3
@dataset({"main_ptref_test": {}, "main_routing_test": {}})
class TestPtRefRoutingAndPtrefCov(AbstractTestFixture):
def test_external_code(self):
"""test the strange and ugly external code api"""
response = self.query("v1/lines?external_code=A&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'A' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'external_code']
def test_external_code_no_code(self):
"""the external_code is a mandatory parameter for collection without coverage"""
r, status = self.query_no_assert("v1/lines")
assert status == 400
assert "parameter \"external_code\" invalid: " \
"Missing required parameter in the post body or the query string" \
"\nexternal_code description: An external code to query" == \
r.get('message')
def test_parameter_error_message(self):
"""test the parameter validation error message"""
r, status = self.query_no_assert("v1/coverage/lines?disable_geojson=12")
assert status == 400
assert "parameter \"disable_geojson\" invalid: Invalid literal for boolean(): 12\n" \
"disable_geojson description: hide the coverage geojson to reduce response size" == \
r.get('message')
def test_invalid_url(self):
"""the following bad url was causing internal errors, it should only be a 404"""
_, status = self.query_no_assert("v1/coverage/lines/bob")
assert status == 404
@dataset({"main_routing_test": {}})
class TestPtRefRoutingCov(AbstractTestFixture):
def test_with_coords(self):
"""test with a coord in the pt call, so a place nearby is actually called"""
response = self.query_region("coords/{coord}/stop_areas".format(coord=r_coord))
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
#the default is the search for all stops within 200m, so we should have A and C
assert len(stops) == 2
assert set(["stopA", "stopC"]) == set([s['name'] for s in stops])
def test_with_coord(self):
"""some but with coord and not coords"""
response = self.query_region("coord/{coord}/stop_areas".format(coord=r_coord))
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
#the default is the search for all stops within 200m, so we should have A and C
assert len(stops) == 2
assert set(["stopA", "stopC"]) == set([s['name'] for s in stops])
def test_with_coord_distance_different(self):
"""same as test_with_coord, but with 300m radius. so we find all stops"""
response = self.query_region("coords/{coord}/stop_areas?distance=300".format(coord=r_coord))
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
assert len(stops) == 3
assert set(["stopA", "stopB", "stopC"]) == set([s['name'] for s in stops])
def test_with_coord_and_filter(self):
"""
we now test with a more complex query, we want all stops with a metro within 300m of r
only A and C have a metro line
Note: the metro is physical_mode:0x1
"""
response = self.query_region("physical_modes/physical_mode:0x1/coords/{coord}/stop_areas"
"?distance=300".format(coord=r_coord), display=True)
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
#the default is the search for all stops within 200m, so we should have all 3 stops
#we should have 3 stops
assert len(stops) == 2
assert set(["stopA", "stopC"]) == set([s['name'] for s in stops])
def test_all_lines(self):
"""test with all lines in the pt call"""
response = self.query_region('lines')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 4
assert {"1A", "1B", "1C", "1D"} == {l['code'] for l in lines}
def test_line_filter_line_code(self):
"""test filtering lines from line code 1A in the pt call"""
response = self.query_region('lines?filter=line.code=1A')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert "1A" == lines[0]['code']
def test_line_filter_line_code_with_resource_uri(self):
"""test filtering lines from line code 1A in the pt call with a resource uri"""
response = self.query_region('physical_modes/physical_mode:0x1/lines?filter=line.code=1D')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert "1D" == lines[0]['code']
def test_line_filter_line_code_empty_response(self):
"""test filtering lines from line code bob in the pt call
as no line has the code "bob" response returns no object"""
url = 'v1/coverage/main_routing_test/lines?filter=line.code=bob'
response, status = self.query_no_assert(url)
assert status == 400
assert 'error' in response
assert 'bad_filter' in response['error']['id']
def test_line_filter_route_code_ignored(self):
"""test filtering lines from route code bob in the pt call
as there is no attribute "code" for route, filter is invalid and ignored"""
response_all_lines = self.query_region('lines')
all_lines = get_not_null(response_all_lines, 'lines')
response = self.query_region('lines?filter=route.code=bob')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 4
assert {l['code'] for l in all_lines} == {l['code'] for l in lines}
def test_route_filter_line_code(self):
"""test filtering routes from line code 1B in the pt call"""
response = self.query_region('routes?filter=line.code=1B')
assert 'error' not in response
routes = get_not_null(response, 'routes')
assert len(routes) == 1
assert "1B" == routes[0]['line']['code']
def test_headsign(self):
"""test basic usage of headsign"""
response = self.query_region('vehicle_journeys?headsign=vjA')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
assert len(vjs) == 1
def test_headsign_with_resource_uri(self):
"""test usage of headsign with resource uri"""
response = self.query_region('physical_modes/physical_mode:0x0/vehicle_journeys'
'?headsign=vjA')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
assert len(vjs) == 1
def test_headsign_with_code_filter_and_resource_uri(self):
"""test usage of headsign with code filter and resource uri"""
response = self.query_region('physical_modes/physical_mode:0x0/vehicle_journeys'
'?headsign=vjA&filter=line.code=1A')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
assert len(vjs) == 1
def test_multiple_resource_uri_no_final_collection_uri(self):
"""test usage of multiple resource uris with line and physical mode giving result,
then with multiple resource uris giving no result as nothing matches"""
response = self.query_region('physical_modes/physical_mode:0x0/lines/A')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
response = self.query_region('lines/D')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
response = self.query_region('physical_modes/physical_mode:0x1/lines/D')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
response, status = self.query_region('physical_modes/physical_mode:0x0/lines/D', False)
assert status == 404
assert 'error' in response
assert 'unknown_object' in response['error']['id']
def test_multiple_resource_uri_with_final_collection_uri(self):
"""test usage of multiple resource uris with line and physical mode giving result,
as we match it with a final collection, so the intersection is what we want"""
response = self.query_region('physical_modes/physical_mode:0x1/lines/D/stop_areas')
assert 'error' not in response
stop_areas = get_not_null(response, 'stop_areas')
assert len(stop_areas) == 2
response = self.query_region('physical_modes/physical_mode:0x0/lines/D/stop_areas')
assert 'error' not in response
stop_areas = get_not_null(response, 'stop_areas')
assert len(stop_areas) == 1
def test_headsign_stop_time_vj(self):
"""test basic print of headsign in stop_times for vj"""
response = self.query_region('vehicle_journeys?filter=vehicle_journey.name="vjA"')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
assert len(vjs) == 1
assert len(vjs[0]['stop_times']) == 2
assert vjs[0]['stop_times'][0]['headsign'] == "A00"
assert vjs[0]['stop_times'][1]['headsign'] == "vjA"
def test_headsign_display_info_journeys(self):
"""test basic print of headsign in section for journeys"""
response = self.query_region('journeys?from=stop_point:stopB&to=stop_point:stopA&datetime=20120615T000000&max_duration_to_pt=0')
assert 'error' not in response
journeys = get_not_null(response, 'journeys')
assert len(journeys) == 1
assert len(journeys[0]['sections']) == 1
assert journeys[0]['sections'][0]['display_informations']['headsign'] == "A00"
def test_headsign_display_info_departures(self):
"""test basic print of headsign in display informations for departures"""
response = self.query_region('stop_points/stop_point:stopB/departures?from_datetime=20120615T000000')
assert 'error' not in response
departures = get_not_null(response, 'departures')
assert len(departures) == 2
assert {"A00", "vjB"} == {d['display_informations']['headsign'] for d in departures}
def test_headsign_display_info_arrivals(self):
"""test basic print of headsign in display informations for arrivals"""
response = self.query_region('stop_points/stop_point:stopB/arrivals?from_datetime=20120615T000000')
assert 'error' not in response
arrivals = get_not_null(response, 'arrivals')
assert len(arrivals) == 2
assert arrivals[0]['display_informations']['headsign'] == "vehicle_journey 2"
def test_headsign_display_info_route_schedules(self):
"""test basic print of headsign in display informations for route schedules"""
response = self.query_region('routes/A:0/route_schedules?from_datetime=20120615T000000')
assert 'error' not in response
route_schedules = get_not_null(response, 'route_schedules')
assert len(route_schedules) == 1
assert len(route_schedules[0]['table']['headers']) == 1
display_info = route_schedules[0]['table']['headers'][0]['display_informations']
assert display_info['headsign'] == "vjA"
assert {"A00", "vjA"} == set(display_info['headsigns'])
def test_trip_id_vj(self):
"""test basic print of trip and its id in vehicle_journeys"""
response = self.query_region('vehicle_journeys')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
assert any(vj['name'] == "vjB" and vj['trip']['id'] == "vjB" for vj in vjs)
def test_disruptions(self):
"""test the /disruptions api"""
response = self.query_region('disruptions')
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 9
for d in disruptions:
is_valid_disruption(d)
# we test that we can access a specific disruption
response = self.query_region('disruptions/too_bad_line_C')
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 1
# we can also display all disruptions of an object
response = self.query_region('lines/C/disruptions')
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 2
disruptions_uris = set([d['uri'] for d in disruptions])
assert {"too_bad_line_C", "too_bad_all_lines"} == disruptions_uris
# we can't access object from the disruption though (we don't think it to be useful for the moment)
response, status = self.query_region('disruptions/too_bad_line_C/lines', check=False)
assert status == 404
e = get_not_null(response, 'error')
assert e['id'] == 'unknown_object'
assert e['message'] == 'ptref : Filters: Unable to find object'
def test_trips(self):
"""test the /trips api"""
response = self.query_region('trips')
trips = get_not_null(response, 'trips')
assert len(trips) == 5
for t in trips:
is_valid_trip(t)
# we test that we can access a specific trip
response = self.query_region('trips/vjA')
trips = get_not_null(response, 'trips')
assert len(trips) == 1
assert get_not_null(trips[0], 'id') == "vjA"
# we can also display trip of a vj
response = self.query_region('vehicle_journeys/vjB/trips')
trips = get_not_null(response, 'trips')
assert len(trips) == 1
assert get_not_null(trips[0], 'id') == "vjB"
def test_attributs_in_display_info_journeys(self):
"""test some attributs in display_information of a section for journeys"""
response = self.query_region('journeys?from=stop_point:stopB&to=stop_point:stopA&datetime=20120615T000000&max_duration_to_pt=0')
assert 'error' not in response
journeys = get_not_null(response, 'journeys')
assert len(journeys) == 1
assert len(journeys[0]['sections']) == 1
assert journeys[0]['sections'][0]['display_informations']['headsign'] == "A00"
assert journeys[0]['sections'][0]['display_informations']['color'] == "289728"
assert journeys[0]['sections'][0]['display_informations']['text_color'] == "FFD700"
assert journeys[0]['sections'][0]['display_informations']['label'] == "1A"
assert journeys[0]['sections'][0]['display_informations']['code'] == "1A"
assert journeys[0]['sections'][0]['display_informations']['name'] == "A"
def test_stop_points_depth_3(self):
"""
test stop_points formating in depth 3
Note: done in main_routing_test because we need a routing graph to have all the attributes
"""
response = self.query_region("stop_points?depth=3")
for s in get_not_null(response, 'stop_points'):
is_valid_stop_point(s, depth_check=3)
def test_pois_uri_poi_types(self):
response = self.query_region("pois/poi:station_1/poi_types")
assert len(response["poi_types"]) == 1
assert response["poi_types"][0]["id"] == "poi_type:amenity:bicycle_rental"
|
agpl-3.0
|
jdesboeufs/geogw-datagouvfr
|
app/partials/services/index.html
|
2135
|
<ol class="breadcrumb">
<li>Accueil</li>
<li>Services</li>
<li class="active">{{ protocol | uppercase }}</li>
</ol>
<div class="alert alert-info">
Choisissez parmi les types de service pris en charge :
<a class="alert-link" ui-sref="root.services({ serviceProtocol: 'csw' })">CSW</a>,
<a class="alert-link" ui-sref="root.services({ serviceProtocol: 'wfs' })">WFS</a>
</div>
</div>
<table class="table table-hover">
<tr ng-repeat="service in services | orderBy:'name'">
<td class="vert" style="width:70px"><span class="label" ng-class="{ 'label-warning': service.protocol === 'csw', 'label-success': service.protocol === 'wfs', 'label-info': service.protocol === 'wms' }">{{ service.protocol | uppercase }}</span></td>
<td class="vert">
<a ui-sref="root.service.records({ serviceId: service._id })">{{ service.name }}</a>
<div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 500px"><em>{{ service.location }}</em></div>
</td>
<td class="vert" style="width:30px">
<i ng-if="!isNew(service)" ng-class="{ 'fa-refresh': service.sync.processing, 'fa-spin': service.sync.processing, 'fa-history': service.sync.pending }" class="fa"></i>
</div>
<td class="vert" style="font-size: 85%; width: 280px">
<div ng-if="service.sync.itemsFound">Entrées : <strong>{{ service.sync.itemsFound | number }}</strong></div>
<div ng-if="!isNew(service)">
État de la synchronisation :
<span style="color: green" ng-show="service.sync.status === 'successful'">OK</span>
<span style="color: purple" ng-show="service.sync.pending">En attente</span>
<span style="color: orange" ng-show="service.sync.processing">En cours</span>
<span style="color: red" ng-show="service.sync.status === 'failed'">Erreur</span>
</div>
<div ng-if="service.lastSuccessfulSync">Dernier succès : <em>{{ service.sync.finishedAt | timeago }}</em></div>
</td>
<td class="vert">
<a style="cursor: pointer" ng-show="canBeSynced(service)" ng-click="syncService(service)">Synchroniser</a>
</td>
</tr>
</table>
|
agpl-3.0
|
wkeyuan/DWSurvey
|
src/main/resources/static/static/diaowen/design.html
|
102923
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>问卷编辑</title>
<link href="js/plugs/jquery-ui-1.10.3.custom/css/mycss/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/plugs/jquery-ui-1.10.3.custom/js/jquery-1.10.1.js"></script>
<script type="text/javascript" src="js/plugs/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.js"></script>
<link href="js/plugs/validate/jquery.validate.css" type="text/css" rel="stylesheet" />
<script src="js/plugs/validate/jquery.validate.js" type="text/javascript"></script>
<script src="js/plugs/validate/messages_cn.js" type="text/javascript"></script>
<script src="js/plugs/validate/jquery.metadata.js" type="text/javascript"></script>
<script src="js/plugs/ueditor1_4_2-utf8-jsp/ueditor.config.js" type="text/javascript" charset="utf-8" ></script>
<script src="js/plugs/ueditor1_4_2-utf8-jsp/ueditor.all.min.js" type="text/javascript" charset="utf-8"> </script>
<!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
<script type="text/javascript" charset="utf-8" src="js/plugs/ueditor1_4_2-utf8-jsp/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" src="js/common/common.js"></script>
<script type="text/javascript" src="js/dw/design-data.js"></script>
<script type="text/javascript" src="js/dw/dwsurvey-design.js"></script>
<script type="text/javascript" src="js/dw/address.js"></script>
<script type="text/javascript" src="js/plugs/laydate/laydate.js"></script>
<link href="css/design-survey.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 7]><link rel="stylesheet" href="ie-stuff.css" type="text/css" media="screen"/><![endif]-->
<script type="text/javascript">
</script>
</head>
<body>
<div id="wrap">
<input type="hidden" id="id" name="id" value="">
<input type="hidden" id="ctx" value="/api/dwsurvey/app">
<input type="hidden" id="surveyModel_hidden" value="${survey.surveyModel }">
<div id="header" >
<div id="header_left">
<!-- <div id="header_title">DIAOWEN-在线问卷编辑器</div> -->
<div class="header_Item header_logo">
<a href="/#/dw/survey"><img alt="调问网" src="images/logo/LOGO.png" ></a>
<span style="font-family: '微软雅黑';font-size: 16px;line-height: 46px;" id="pageHeaderSpan">在线问卷编辑器</span>
</div>
</div>
<div id="header_right">
<div style="line-height: 22px;">
<a href="/#/dw/survey">问卷</a> <a href="#">账号</a>
</div>
</div>
</div>
<div id="tools_wrap">
<div id="tools">
<div class="tools_tabs">
<div class="tools_tabs_left"><ul><li class="current" id="tools_tab1_li">基本</li></ul></div>
<div class="tools_tabs_right"><ul><li style="padding: 0px;font-size: 12px;line-height: 28px;"><a href="http://www.diaowen.net" target="_black" style="text-decoration: none;color: gray;">升级到企业版</a></li></ul></div>
</div>
<div class="tools_contents">
<div id="tools_tab1" class="tools_tab_div" style="display: inline;">
<div id="toolsBashQu" class="tools_item">
<div class="toolbars">
<ul class="dragQuUl" >
<li id="radioQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="RADIO">
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="0">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >题标题?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">选项1</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">选项2</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
</ul></div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="checkboxQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="CHECKBOX" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="0">
<input type="hidden" name="paramInt01" value="0">
<input type="hidden" name="paramInt02" value="0">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >题标题?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul>
<li class="quCoItemUlLi">
<input type="checkbox"><label class="editAble quCoOptionEdit">选项1</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="checkbox"><label class="editAble quCoOptionEdit">选项2</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="checkbox"><label class="editAble quCoOptionEdit">选项3</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
</ul></div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="fillblankQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="FILLBLANK" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="answerInputWidth" value="300">
<input type="hidden" name="answerInputRow" value="1">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="0">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >题标题?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul>
<li class="quCoItemUlLi">
<!-- <input type="text" style="width:200px;padding:5px;"> -->
<div class="quFillblankItem">
<input type="text" style="width:200px;padding:5px;" class="quFillblankAnswerInput" />
<textarea rows="5" style="width:300px;display: none;"class="quFillblankAnswerTextarea" ></textarea>
<div class="dwFbMenuBtn" ></div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="mfillblankQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="MULTIFILLBLANK" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="paramInt01" value="0">
<input type="hidden" name="paramInt02" value="5">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >请问你的年级是?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem">
<table class="mFillblankTable">
<tr class="mFillblankTableTr">
<td align="right" class="mFillblankTableEditTd"><label class="editAble quCoOptionEdit">选项1</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div>
</td>
<td><input type="text" style="width:200px;padding:5px;"></td>
</tr>
<tr class="mFillblankTableTr">
<td align="right" class="mFillblankTableEditTd"><label class="editAble quCoOptionEdit">选项2</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div>
</td>
<td><input type="text" style="width:200px;padding:5px;"></td>
</tr>
<tr class="mFillblankTableTr">
<td align="right" class="mFillblankTableEditTd"><label class="editAble quCoOptionEdit">选项3</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div>
</td>
<td><input type="text" style="width:200px;padding:5px;"></td>
</tr>
</table>
</div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="orderQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="ORDERQU" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<!-- <li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li> -->
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >题标题?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem">
<div class="quOrderByLeft">
<ul>
<li class="quCoItemUlLi"><label class="editAble quCoOptionEdit">选项1</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div></li>
<li class="quCoItemUlLi"><label class="editAble quCoOptionEdit">选项2</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div></li>
<li class="quCoItemUlLi"><label class="editAble quCoOptionEdit">选项3</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div></li>
</ul></div>
<div class="quOrderByRight">
<table class="quOrderByTable">
<tr><td class="quOrderyTableTd">1</td><td></td></tr>
<tr><td class="quOrderyTableTd">2</td><td></td></tr>
<tr><td class="quOrderyTableTd">3</td><td></td></tr>
</table>
</div>
<div style="clear: both;"></div>
</div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="scoreQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="SCORE" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="paramInt01" value="1">
<input type="hidden" name="paramInt02" value="5">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >题标题?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem">
<table class="quCoItemTable" cellpadding="0" cellspacing="0">
<tr class="quScoreOptionTr">
<td class="quCoItemTableTd quOptionEditTd">
<label class="editAble quCoOptionEdit">分项1</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div>
</td>
<td class="quCoItemTableTd"><table class="scoreNumTable"><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr></table></td>
<td class="quCoItemTableTd">分</td>
</tr>
<tr class="quScoreOptionTr">
<td class="quCoItemTableTd quOptionEditTd">
<label class="editAble quCoOptionEdit">分项2</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div>
</td>
<td class="quCoItemTableTd"><table class="scoreNumTable"><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr></table></td>
<td class="quCoItemTableTd">分</td>
</tr>
</table>
</div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="selectQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="RADIO">
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="4">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="0">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >题标题?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem">
<div class="selectItems" style="margin-top: 6px;">
<select style="padding: 5px;" class="radioSelect" name="qu_RADIO_402880e56beac087016bee02c9e90003">
<option value="0">--真实下拉数据在发布后出现--</option>
<option value="402880e56beac087016bee02c9e90004"> 选项1 </option>
<option value="402880e56beac087016bee02c9ea0005"> 选项2 </option>
</select>
</div>
<ul class="selectRadioUl">
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">选项1</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">选项2</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
</ul></div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="uploadFileQuModel">
<div class="dwToolbar_icon dwsurveyfont icon-dwsurvey-shangchuan"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="UPLOADFILE" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="answerInputWidth" value="300">
<input type="hidden" name="answerInputRow" value="1">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="0">
<input type="hidden" name="paramInt01" value="1">
<input type="hidden" name="paramInt02" value="10">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >请上传文件?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoQuNote">
<div class="editAble quCoNoteEdit" ></div>
</div>
<div class="quCoItem"><ul>
<li class="quCoItemUlLi">
<!-- <input type="text" style="width:200px;padding:5px;"> -->
<div class="quFillblankItem">
<input type="file" >
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="tooltext">基本题型</div>
</div>
<div id="contactPersonQuestion" class="tools_item">
<div class="toolbars">
<ul class="dragQuUl">
<li id="dateQuModel" style="">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="FILLBLANK" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="checkType" value="DATE">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="0">
<input type="hidden" name="answerInputWidth" value="300">
<input type="hidden" name="answerInputRow" value="1">
<input type="hidden" name="paramInt01" value="3">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<!-- <li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>-->
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >日期控件?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul>
<li class="quCoItemUlLi">
<!-- <input type="text" style="width:200px;padding:5px;"> -->
<div class="quFillblankItem">
<input type="text" style="width:200px;padding:5px;" class="quFillblankAnswerInput" />
<textarea rows="5" style="width:300px;display: none;"class="quFillblankAnswerTextarea" ></textarea>
<div class="dwFbMenuBtn" ></div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="timeQuModel" style="">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="FILLBLANK" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="checkType" value="DATE">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="0">
<input type="hidden" name="answerInputWidth" value="300">
<input type="hidden" name="answerInputRow" value="1">
<input type="hidden" name="paramInt01" value="5">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<!-- <li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>-->
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >时间控件?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul>
<li class="quCoItemUlLi">
<!-- <input type="text" style="width:200px;padding:5px;"> -->
<div class="quFillblankItem">
<input type="text" style="width:200px;padding:5px;" class="quFillblankAnswerInput" />
<textarea rows="5" style="width:300px;display: none;"class="quFillblankAnswerTextarea" ></textarea>
<div class="dwFbMenuBtn" ></div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="birthdayQuModel" style="display: none;">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="FILLBLANK" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="checkType" value="DATE">
<input type="hidden" name="answerInputWidth" value="300">
<input type="hidden" name="answerInputRow" value="1">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<!-- <li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>-->
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >您的生日是?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul>
<li class="quCoItemUlLi">
<!-- <input type="text" style="width:200px;padding:5px;"> -->
<div class="quFillblankItem">
<input type="text" style="width:200px;padding:5px;" class="quFillblankAnswerInput" />
<textarea rows="5" style="width:300px;display: none;"class="quFillblankAnswerTextarea" ></textarea>
<div class="dwFbMenuBtn" ></div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="emailQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="FILLBLANK" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="checkType" value="EMAIL">
<input type="hidden" name="answerInputWidth" value="300">
<input type="hidden" name="answerInputRow" value="1">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="5">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >您的邮箱是?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul>
<li class="quCoItemUlLi">
<div class="quFillblankItem">
<input type="text" style="width:200px;padding:5px;" class="quFillblankAnswerInput" />
<textarea rows="5" style="width:300px;display: none;"class="quFillblankAnswerTextarea" ></textarea>
<div class="dwFbMenuBtn" ></div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="genderQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="RADIO">
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="1">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="6">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >您的性别是?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul class="transverse">
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">男</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">女</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
</ul></div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="educationQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="RADIO">
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="1">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="6">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >您的最高学历是?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul class="transverse">
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">博士</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">硕士</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">本科</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">专科</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
</ul></div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="maritalQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="RADIO">
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="1">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="6">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >请问您婚否?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul class="transverse">
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">是</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">否</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
</ul></div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
<li id="salaryQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="RADIO">
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="1">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<input type="hidden" name="contactsAttr" value="0">
<input type="hidden" name="contactsField" value="6">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="移动排序" class="dwQuMove"><div class="dwQuIcon"></div></li>
<li title="设置" class="dwQuSet"><div class=dwQuIcon></div></li>
<li title="逻辑" class="dwQuLogic"><div class="dwQuIcon"><div class="quLogicInfo"></div></div></li>
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent">
<div class="quCoTitle">
<div class="quCoNum">1、</div>
<div class="editAble quCoTitleEdit" >您的月平均收入是?</div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
<div class="quCoItem"><ul class="transverse">
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">3000元以下</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">3000-5000元</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">5000-10000元</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">10000-20000元</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
<li class="quCoItemUlLi">
<input type="radio"><label class="editAble quCoOptionEdit">20000元以上</label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</li>
</ul></div>
<div class="quCoBottomTools" >
<ul class="quCoBottomToolsUl" >
<li class="addOption" title="添加"><div class="dwQuIcon"></div></li>
<li class="addMoreOption" title="批量添加"><div class="dwQuIcon" ></div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="tooltext">常用题型</div>
</div>
<div id="toolsAuxiliaryQu" class="tools_item">
<div class="toolbars">
<ul class="dragQuUl">
<li id="pageQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="PAGETAG" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools" style="margin-top:0px;">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="pageBorderTop" ></div>
<div class="surveyQuItemContent" style="min-height: 10px;text-align: right;">
<div class="pageQuContent">下一页(1/2)</div>
</div>
</div>
</div>
</div>
</li>
<li id="paragraphQuModel">
<div class="dwToolbar_icon"></div>
<div class="dwQuTypeModel">
<div class="surveyQuItemBody quDragBody">
<div class="initLine"></div>
<div class="quInputCase" style="display: none;">
<input type="hidden" name="quType" value="PARAGRAPH" >
<input type="hidden" name="quId" value="">
<input type="hidden" name="orderById" value="0"/>
<input type="hidden" name="saveTag" value="0">
<input type="hidden" name="hoverTag" value="0">
<input type="hidden" name="isRequired" value="1">
<input type="hidden" name="hv" value="2">
<input type="hidden" name="randOrder" value="0">
<input type="hidden" name="cellCount" value="0">
<div class="quLogicInputCase">
<input type="hidden" name="quLogicItemNum" value="0">
</div>
</div>
<div class="surveyQuItem">
<div class="surveyQuItemLeftTools">
<ul class="surveyQuItemLeftToolsUl">
<li title="删除" class="dwQuDelete"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemRightTools">
<ul class="surveyQuItemRightToolsUl">
<li class="questionUp"><div class="dwQuIcon"></div></li>
<li class="questionDown"><div class="dwQuIcon"></div></li>
</ul>
</div>
<div class="surveyQuItemContent" style="min-height: 45px;">
<div class="quCoTitle">
<div class="quCoNum" style="display: none;">1、</div>
<div class="editAble quCoTitleEdit" ><p><strong>分段标记</strong></p></div>
<input type="hidden" name="quTitleSaveTag" value="0">
</div>
</div>
</div>
</div>
</div>
</li>
<li id="surveyAttrSetToolbar" class="surveyAttrSetToolbar_li">
<a href="#" >
<span class="dwToolbar_icon" title="问卷设置"></span>
</a>
</li>
</ul>
</div>
<div class="tooltext">辅助组件</div>
</div>
</div>
<div id="toolsPubBtn" >
<div class="toolbars" style="padding:10px 15px 10px 0px;">
<ul>
<li id="publishBtn" >
<div class="dwToolbar_icon"></div>
</li>
<li id="saveBtn" >
<div class="dwToolbar_icon"></div>
</li>
<li id="previewBtn" >
<div class="dwToolbar_icon"></div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div id="dw_body">
<div id="dw_body_left">
<div class="dw_body_title" style="text-align: center;">设计目录</div>
<div id="dwBodyLeftContent">
<h2 class=""><a href="" class="ellipsis">欢迎页</a></h2>
<div>
<div><h2 class=""><a href="" class="ellipsis">问卷页</a></h2></div>
<div style="padding-left: 5px;">
<h2 class=""><a href="" class="ellipsis">1、请问你的年级是?</a></h2>
<h2 class=""><a href="" class="ellipsis">2、请问你的年级是?</a></h2>
<h2 class=""><a href="" class="ellipsis">3、请问你的年级是?</a></h2>
<h2 class=""><a href="" class="ellipsis">4、请问你的年级是?</a></h2>
<h2 class=""><a href="" class="ellipsis">下一页</a></h2>
<h2 class=""><a href="" class="ellipsis">5、请问你的年级是?</a></h2>
<h2 class=""><a href="" class="ellipsis">6、请问你的年级是级是级是?</a></h2>
</div>
</div>
<h2 class=""><a href="" class="ellipsis">结束页</a></h2>
</div>
</div>
<div id="dw_body_right" style="display: none;"><div class="dw_body_title">题目推荐</div></div>
<div id="dw_body_content">
<div id="dwSurveyTitle">
<div id="dwSurveyName" class="editAble dwSvyName">${survey.surveyName }</div>
</div>
<input type="hidden" name="svyNmSaveTag" value="1">
<div id="dwSurveyNote">
<div id="dwSurveyNoteTools">参考样例</div>
<div id="dwSurveyNoteEdit" class="editAble dwSvyNoteEdit" >${survey.surveyDetail.surveyNote }</div>
<input type="hidden" name="svyNoteSaveTag" value="1">
</div>
<div id="dwSurveyQuContent" style="min-height: 500px;">
<ul id="dwSurveyQuContentAppUl">
<!-- 题目内容 -->
</ul>
</div>
</div>
</div>
</div>
<!-- 各种模板 -->
<!-- 单选选项模板 -->
<div id="quRadioItem" class="modelHtml">
<input type="radio"><label class="editAble quCoOptionEdit"></label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</div>
<!-- 多选选项模板 -->
<div id="quCheckboxItem" class="modelHtml">
<input type="checkbox"><label class="editAble quCoOptionEdit"></label>
<div class="quItemInputCase">
<input type="hidden" name="quItemId" value="">
<input type="hidden" name="quItemSaveTag" value="0">
<input type="hidden" name="isNote" value="0">
<input type="hidden" name="checkType" value="NO">
<input type="hidden" name="isRequiredFill" value="0">
</div>
</div>
<!-- 评分题选项模板 -->
<table class="modelHtml">
<tr id="quScoreItemModel" class="quScoreOptionTr">
<td class="quCoItemTableTd quOptionEditTd">
<label class="editAble quCoOptionEdit">评分项</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div>
</td>
<td class="quCoItemTableTd"><table class="scoreNumTable"><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr></table></td>
<td class="quCoItemTableTd">分</td>
</tr>
</table>
<!-- 排序题模板 -->
<div id="quOrderItemLeftModel" class="modelHtml">
<label class="editAble quCoOptionEdit"> </label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div>
</div>
<table class="modelHtml">
<tr id="quOrderItemRightModel"><td class="quOrderyTableTd">1</td><td></td></tr>
</table>
<table class="modelHtml" >
<tr id="mFillblankTableModel" >
<td align="right" class="mFillblankTableEditTd">
<label class="editAble quCoOptionEdit" >大一</label>
<div class="quItemInputCase"><input type="hidden" name="quItemId" value=""><input type="hidden" name="quItemSaveTag" value="0"></div>
</td>
<td><input type="text" style="width:200px;padding:5px;"></td>
</tr>
</table>
<!-- 逻辑值保存模板 -->
<div id="quLogicItemModel" class="modelHtml">
<div class="quLogicItem">
<input type="hidden" name="quLogicId" value=""/>
<input type="hidden" name="cgQuItemId" value="0"/>
<input type="hidden" name="skQuId" value="0"/>
<input type="hidden" name="visibility" value="0">
<input type="hidden" name="logicSaveTag" value="0">
<input type="hidden" name="geLe" value="le">
<input type="hidden" name="scoreNum" value="2">
<input type="hidden" name="logicType" value="1">
</div>
</div>
<table id="setQuLogicItem" style="display: none;">
<tr id="setQuLogicItemTrModel">
<td class="ifSpanText1">如果本题回答</td>
<td><select name="option_id" class="logicQuOptionSel" ></select></td>
<td>则 <select name="option_id" class="logicType" style="width: 60px;"><option value="2">显示</option><%--<option value="1">跳到</option>--%></select> </td>
<td><select name="jump_to_qid" class="logicQuSel" ></select></td>
<td><div class="dialogRemoveLogic"></div></td>
</tr>
</table>
<div id="dwCommonEditRoot" >
<div class="dwCommonEdit">
<ul class="dwComEditMenuUl" >
<li><a href="javascript:;" class="SeniorEdit"><i class="menu_edit2_icon"></i>高级编辑</a></li>
<li class="option_Set_Li"><a href="javascript:;" class="option_Set"><i class="menu_edit4_icon"></i>选项设置</a></li>
<!-- <li><a href="javascript:;" class="reference_Set" style="display: none;"><i class="menu_edit4_icon"></i>引用设置</a></li> -->
</ul>
<ul class="dwComEditOptionUl">
<li class="dwOptionUp"><div class=dwQuIcon></div></li>
<li class="dwOptionDown"><div class=dwQuIcon></div></li>
<li class="dwOptionDel"><div class=dwQuIcon></div></li>
</ul>
<div class="dwComEditMenuBtn"></div>
<div id="dwComEditContent" contenteditable="true" >请问你的年级是?</div>
</div>
</div>
<div id="dialog" title="Basic dialog">
<div id="editDialogCenter" class="editDialogCenter">
<div id="dialogUeditor" ></div>
</div>
<div id="dialogUeBottom">
<div class="dwQuDialogBtnCon" ><input type="button" value="保存" class="quDialogBtn" id="dwDialogUeOk"/></div>
</div>
</div>
<div id="dwCommonDialog">
<form action="#" id="dwCommonDialogForm">
<div class="dwCommonRefIcon"><div class="dwCommonRefIcon1"></div><div class="dwCommonRefIcon2"></div></div>
<div class="dwCommonDialogBody">
<div class="dwCommonDialogTitle"><span id="dwComDialogTitleText">标题文本</span><span id="dwCommonDialogClose" class="closeDialog"></span></div>
<div class="dwCommonDialogContent">
<!-- 默认显示的LOAD -->
<div class="dwQuDialogLoad dwQuDialogCon"><img alt="" src="images/load.gif"></div>
<!-- 题目设置 -->
<div class="dwQuSetCon dwQuFormSetDialog dwQuDialogCon" >
<ul>
<!-- <li><input type="checkbox" name="quChage"><label>切换为多选</label> </li> -->
<li><label><input type="checkbox" name="setIsRequired" >此题必答</label> </li>
<li class="optionAutoOrder" style="display: none;"><label><input type="checkbox" name="setRandOrder" >选择随机排列</label> </li>
<li class="contactsAttrLi" style="display: none;"><label><input type="checkbox" name="setAutoContacts" >关联到联系人属性</label> </li>
<li class="contactsFieldLi"><label>用户填写的内容,会成为联系人的</label>
<select class="contacts_range" name="setContactsField" style="width:120px;">
<option value="1">姓名</option>
<option value="2">手机</option>
<option value="3">地址</option>
<option value="4">生日</option>
<option value="5">Email</option>
<option value="6">性别</option>
<option value="7">公司</option>
<option value="8">城市</option>
<option value="9">婚姻</option>
<option value="10">收入</option>
</select>
</li>
<li class="optionRangeHv"><label>选项排放:</label>
<select class="option_range" name="setHv" style="width:120px;">
<option value="2">竖排</option>
<!-- <option value="1">横排</option>-->
<!-- <option value="3">按列</option>-->
<!-- <option value="4">下拉显示</option> -->
</select>
<span class="option_range_3" style="display:none;"><input type="text" name="setCellCount" size="2" value="3" class="" > 列</span>
</li>
<li class="minNumLi">最少选 <input type="text" size="3" name="minNum" value="0"> 项 </li>
<li class="maxNumLi">最多选 <input type="text" size="3" name="maxNum" value="0"> 项 </li>
<li class="minMaxLi">
<span class="minSpan"><label class="lgleftLabel"> 最低分</label> <input class="minNum" value="1" type="text" size="2" > <label class="lgRightLabel">分</label></span>
<span class="maxSpan"><label class="lgLeftLabel">最高分</label> <input class="maxNum" value="5" type="text" size="2" > <label class="lgRightLabel">分</label> </span>
</li>
<li class="scoreMinMax"> <label>最高分</label> <select class="maxScore" ><option value="5">5分</option><option value="10">10分</option></select> </li>
<li class="fileTypeExtsLi">
<div><label> 上传文件类型</label>
<select class="fileTypeExts" ><option value="0">不限</option><option value="1">图片文件</option><option value="2">文本文件</option></select> <br/>
</div>
<div style="margin-top: 8px;"><label> 上传附件数</label> <label><input type="text" class="uploadNum" size="5" value="0" > 0 表示不限制</label></div>
<div style="margin-top: 8px;"><label> 单个文件最大支持</label> <input class="maxSize" value="10" type="text" size="5" ><label> M</label></div>
</li>
</ul>
<div class="dwQuDialogBtnCon" ><input type="button" value="保存" class="quDialogBtn" id="dwDialogQuSetSave"/></div>
</div>
<!-- 逻辑设置 -->
<div class="dwQuDialogLogic dwQuDialogCon">
<div class="dwQuDialogLogicTitle">逻辑设置</div>
<table id="dwQuLogicTable">
</table>
<div class="dwQuDialogBotEvent"><div class="dwQuDialogAddLogic"><div class="dwQuIcon"></div></div></div>
<div class="dwQuDialogBtnCon" ><input type="button" value="保存" class="quDialogBtn" id="dwDialogSaveLogic"/></div>
</div>
<!-- 批量添加,单选 -->
<div class="dwQuAddMore dwQuDialogCon" >
<div class="dwQuTextSpan">每行一个选项</div>
<textarea id="dwQuMoreTextarea"></textarea>
<div class="dwQuDialogBtnCon" ><input type="button" value="保存" class="quDialogBtn" id="dwDialogSaveMoreItem"/></div>
</div>
</div>
</div>
</form>
</div>
<div id="modelUIDialog">
<div id="modelUIDialogContent" >
<!-- 填空题 填空数据类型设置 -->
<div class="dwQuFillDataTypeOption dwQuFormSetDialog dwQuDialogCon" >
<ul>
<li><label>输入框宽:</label>
<input type="text" name="qu_inputWidth" value="300"><span> 像素</span>
</li>
<li><label>输入框高:</label>
<input type="text" name="qu_inputRow" value="1"><span> 行</span>
</li>
<li class="checkTypeLi" ><label>数据类型:</label>
<select class="option_range" name="quFill_checkType" style="width:158px;">
<option value="NO">无验证</option>
<option value="EMAIL">Email</option>
<option value="NUM">数字</option>
<option value="DIGITS">整数</option>
<option value="TELE_PHONE_NUM">手机或电话</option>
<option value="DATE">日期</option>
<option value="ZIPCODE">邮政编码</option>
<option value="TELENUM">电话号码</option>
<option value="PHONENUM">手机号码</option>
<option value="IDENTCODE">身份证号</option>
<option value="URL">网址</option>
<option value="UNSTRCN">禁止中文</option>
<option value="STRCN">仅许中文</option>
</select>
<span class="option_range_3" style="display:none;"> 列</span>
</li>
<li class="option_range_date_li" style="display: list-item;"><label>日期格式:</label>
<select class="option_range_date">
<option value="3">年月日(YYYY-MM-DD)</option>
<option value="2">年月(YYYY-MM)</option>
<option value="1">年(YYYY)</option>
<option value="4">年月日时分秒(YYYY-MM-DD HH:mm:ss)</option>
<option value="5">时分秒(HH:mm:ss)</option>
<option value="6">时分(HH:mm)</option>
<option value="0">直接输入日期(不使用控件,格式不限)</option>
</select>
</li>
</ul>
<div class="dwQuDialogBtnCon" ><input type="button" value="保存" class="quDialogBtn" id="dwDialogQuFillOptionSave"/></div>
</div>
<div class="dwQuRadioCheckboxOption dwQuFormSetDialog dwQuDialogCon" >
<ul>
<li><label>选项设置</label></li>
<li class="quOptionAddFill"><label><input type="checkbox" name="quOption_isNote" >选项后添加填空</label> </li>
</ul>
<div class="dwQuDialogBtnCon" ><input type="button" value="保存" class="quDialogBtn" id="dwDialogQuOptionSetSave"/></div>
</div>
<div class="dwSurveyAttrSetDialog dwQuFormSetDialog dwQuDialogCon" >
<div class="tabbarDialog_1" >
<div class="p_DialogContent" >
<input type="hidden" name="svyAttrSaveTag" value="1">
<div class="p_DialogContentTitle">回答限制</div>
<div class="p_DialogContentRoot">
<div class="p_DialogContentItem"><label><input type="checkbox" name="effective" value="4"> 每台电脑或手机只能答一次</label></div>
<div class="p_DialogContentItem"><label><input type="checkbox" name="effectiveIp" value="1"> 每个IP只能答一次</label></div>
<div class="p_DialogContentItem"><label><input type="checkbox" name="rule" value="3"> 启用访问密码</label>
设置密码:<input type="text" size="10" name="ruleCode" class="inputSytle_1">
</div>
<div class="p_DialogContentItem"><label><input type="checkbox" name="refresh" value="1"> 有重复回答启用验证码</label></div>
<div class="p_DialogContentItem" style="display: none;"><label><input type="checkbox" name="mailOnly" value="1"> 只有邮件邀请唯一链接的受访者可回答</label></div>
</div>
</div>
<div class="p_DialogContent" >
<div class="p_DialogContentTitle">何时结束</div>
<div class="p_DialogContentRoot">
<div class="p_DialogContentItem"><label><input type="checkbox" name="ynEndNum" value="1"> 收集到 <input type="text" size="12" class="inputSytle_1" name="endNum"> 份答卷时结束</label></div>
<div class="p_DialogContentItem"><label><input type="checkbox" name="ynEndTime" value="1"> 到 <input type="text" size="20" class="inputSytle_1 Wdate" name="endTime" id="surveyEndTime" value="" pattern="yyyy-MM-dd HH:mm:ss" />" > 时结束 </label></div>
</div>
</div>
</div>
<div class="dwQuDialogBtnCon" ><input type="button" value="保存" class="quDialogBtn" id="dwDialogSurveyAttrSave"/></div>
</div>
</div>
</div>
<script type="text/javascript">
if("${survey.surveyDetail.effective}">1){
$("input[name='effective']").attr("checked",true);
}else{
$("input[name='effective']").attr("checked",false);
}
$("input[name='effectiveIp'][value='${survey.surveyDetail.effectiveIp}']").attr("checked",true);
$("input[name='rule'][value='${survey.surveyDetail.rule}']").attr("checked",true);
$("input[name='ruleCode']").val("${survey.surveyDetail.ruleCode}");
$("input[name='refresh'][value='${survey.surveyDetail.refresh}']").attr("checked",true);
$("input[name='mailOnly'][value='${survey.surveyDetail.mailOnly}']").attr("checked",true);
$("input[name='ynEndNum'][value='${survey.surveyDetail.ynEndNum}']").attr("checked",true);
$("input[name='endNum']").val("${survey.surveyDetail.endNum}");
$("input[name='ynEndTime'][value='${survey.surveyDetail.ynEndTime}']").attr("checked",true);
$("input[name='showShareSurvey'][value='${survey.surveyDetail.showShareSurvey}']").attr("checked",true);
$("input[name='showAnswerDa'][value='${survey.surveyDetail.showAnswerDa}']").attr("checked",true);
laydate.render({
elem: '#surveyEndTime' //指定元素
,type: 'datetime'
});
</script>
<div style="text-align: center;">
<div class="dw_foot" style="padding-bottom: 30px;">
<div class="footer-copyright" style="color: gray;padding-top: 0px;font-size: 16px;">
Powered by <a href="http://www.diaowen.net" target="_blank" style="text-decoration: none;color: gray;"> DWSurvey OSS V5.0 </a>
Copyright © 2012-2021
<a href="http://www.diaowen.net" target="_blank" style="text-decoration: none;color: rgb(53, 117, 136);">调问网</a>
</div>
</div>
</div>
</body>
</html>
|
agpl-3.0
|
sagemathinc/smc
|
src/smc-webapp/editors/slate/elements/hashtag.tsx
|
1639
|
/*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { CSS, React } from "smc-webapp/app-framework";
import { FOCUSED_COLOR } from "../util";
import {
SlateElement,
register,
useFocused,
useSelected,
useSlateStatic,
} from "./register";
export interface Hashtag extends SlateElement {
type: "hashtag";
content: string;
}
// Looks like antd tag but scales (and a lot simpler).
const STYLE = {
padding: "0 7px",
color: "#1b95e0",
borderRadius: "5px",
cursor: "pointer",
} as CSS;
register({
slateType: "hashtag",
fromSlate: ({ node }) => `#${node.content}`,
Element: ({ attributes, children, element }) => {
if (element.type != "hashtag") throw Error("bug");
const focused = useFocused();
const selected = useSelected();
const editor = useSlateStatic();
const border =
focused && selected ? `1px solid ${FOCUSED_COLOR}` : "1px solid #d9d9d9";
const backgroundColor = focused && selected ? "#1990ff" : "#fafafa";
const color = focused && selected ? "white" : undefined;
return (
<span {...attributes}>
<span
style={{ ...STYLE, border, backgroundColor, color }}
onClick={() => editor.search.focus("#" + element.content)}
>
#{element.content}
</span>
{children}
</span>
);
},
toSlate: ({ token }) => {
return {
type: "hashtag",
isVoid: true,
isInline: true,
content: token.content,
children: [{ text: " " }],
markup: token.markup,
};
},
});
|
agpl-3.0
|
CoherentLogic/fis-gtm-netbsd
|
sr_port/format_targ_key.c
|
4061
|
/****************************************************************
* *
* Copyright 2001, 2014 Fidelity Information Services, Inc *
* *
* This source code contains the intellectual property *
* of its copyright holder(s), and is made available *
* under a license. If you do not know the terms of *
* the license, please stop and do not read further. *
* *
****************************************************************/
#include "mdef.h"
#include "gdsroot.h"
#include "gdsblk.h"
#include "gtm_facility.h"
#include "fileinfo.h"
#include "gdsbt.h"
#include "gdsfhead.h"
#include "format_targ_key.h"
#include "gvsub2str.h"
/* return a pointer that points after the last char added */
unsigned char *format_targ_key(unsigned char *out_char_ptr, int4 max_size, gv_key *key, boolean_t dollarc)
{
unsigned char ch, *gvkey_char_ptr, *out_top, *work_char_ptr, work_buff[MAX_ZWR_KEY_SZ], *work_top;
boolean_t is_string;
mstr opstr;
DEBUG_ONLY(unsigned char *gvkey_top_ptr;)
assert(12 < max_size);
out_top = out_char_ptr + max_size - 2; /* - 2, as could add comma left-paren or TWO double quotes between checks */
gvkey_char_ptr = key->base;
DEBUG_ONLY(gvkey_top_ptr = gvkey_char_ptr + key->end;)
/* Ensure input key is well-formed (i.e. double null terminated) */
assert(KEY_DELIMITER == *(gvkey_top_ptr - 1));
assert(KEY_DELIMITER == *gvkey_top_ptr);
/* The following assert (in the for loop) assumes that a global name will be able to fit in completely into any key.
* But that is not true. For exmaple I can have a maxkeysize of 10 and try to set a global variable name of length 20.
* That will have issues below. Until C9J10-003204 is fixed to handle long global names and small maxkeysizes, we
* let the below code stay as it is (asserts only) to avoid overheads (of if checks for whether end is reached) in pro.
* When that is fixed, it is possible, we see the key terminate before even the global name is finished. In that case,
* we should return without '(' or ')' in the formatted buffer. The caller will know this is a case of too long global name.
*/
for (*out_char_ptr++ = '^'; (*out_char_ptr = *gvkey_char_ptr++); out_char_ptr++)
assert(gvkey_char_ptr <= gvkey_top_ptr);
assert(gvkey_char_ptr <= gvkey_top_ptr);
if (0 == *gvkey_char_ptr) /* no subscipts */
return (out_char_ptr);
*out_char_ptr++ = '(';
for ( ; ; )
{
assert(gvkey_char_ptr <= gvkey_top_ptr);
if (0x01 == *gvkey_char_ptr) /* this must be a null string which was adjusted by op_gvorder */
{
*out_char_ptr++ = '"';
*out_char_ptr++ = '"';
} else
{
is_string = FALSE;
if ((STR_SUB_PREFIX == *gvkey_char_ptr) && !dollarc)
{
is_string = TRUE;
*out_char_ptr++ = '"';
}
opstr.addr = (char *)work_buff;
opstr.len = MAX_ZWR_KEY_SZ;
work_top = gvsub2str(gvkey_char_ptr, &opstr, dollarc);
if (!is_string)
{
for (work_char_ptr = work_buff; work_char_ptr < work_top;)
{
if (out_char_ptr >= out_top)
{
assert(FALSE);
return (NULL);
}
*out_char_ptr++ = *work_char_ptr++;
}
} else
{ /* replace double-quote with TWO double-quotes since this subs is already double-quote-enclosed */
for (work_char_ptr = work_buff; work_char_ptr < work_top;)
{
if (out_char_ptr >= out_top)
{
assert(FALSE);
return (NULL);
}
*out_char_ptr++ = (ch = *work_char_ptr++);
if ('"' == ch)
{
if (out_char_ptr >= out_top)
{
assert(FALSE);
return (NULL);
}
*out_char_ptr++ = ch;
}
}
if (out_char_ptr >= out_top)
{
assert(FALSE);
return (NULL);
}
*out_char_ptr++ = '"';
}
}
if (out_char_ptr >= out_top)
{
assert(FALSE);
return (NULL);
}
for ( ; *gvkey_char_ptr++; )
assert(gvkey_char_ptr <= gvkey_top_ptr);
assert(gvkey_char_ptr <= gvkey_top_ptr);
if (*gvkey_char_ptr)
*out_char_ptr++ = ',';
else
break;
}
*out_char_ptr++ = ')';
assert(gvkey_char_ptr <= gvkey_top_ptr);
return (out_char_ptr);
}
|
agpl-3.0
|