code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
#https://python-docx.readthedocs.io/en/latest/user/install.html
#python-docx may be installed with pip if you have it available:
# pip install python-docx
#python-docx can also be installed using easy_install, although this is #discouraged:
# easy_install python-docx
#If neither pip nor easy_install is available, it can be installed manually by downloading the distribution from PyPI, unpacking the tarball, and running setup.py:
# tar xvzf python-docx-{version}.tar.gz
# cd python-docx-{version}
# python setup.py install
#python-docx depends on the lxml package. Both pip and easy_install will take care of satisfying those dependencies for you, but if you use this last method you will need to install those yourself.
from docx import Document
import datetime
from schedule.Assignment import *
#indices for row cells in the template table
DATE = 0
SECTION_A_PARTICIPANTS = 1
SECTION_A_LESSON = 2
SECTION_B_PARTICIPANTS = 3
SECTION_B_LESSON = 4
# csv column header
HEADER = 'Date,Type,Assignee,Householder,Lesson,Classroom'
def getWeekDate(weekHeaderRow, year, month):
'''extract the date from the date row from table'''
raw_date = weekHeaderRow.cells[DATE].text.strip()
if raw_date == '':
return raw_date
# convert to nice date format
# split up to look for a number for the day of the month
date_parts = raw_date.split()
# list comprehension to select numbeic strings
numericParts = [part for part in date_parts if part.isnumeric()]
# assume there will only be one
day = int( numericParts[0] )
# this is the format for MySQL date
date = '{:%Y-%m-%d}'.format( datetime.date(year, month, day) )
return date
def parseAssignmentRow(row, date, aType):
'''parse an assignment row from table, returns an array with the assignments'''
assignments = []
# participants for first assgn
participants = row.cells[SECTION_A_PARTICIPANTS].text.strip()
if participants != '': # if there are participants
assgn = Assignment() # new empty assignment
# begin populating fields
assgn.date = date
assgn.type = aType
assgn.lesson = row.cells[SECTION_A_LESSON].text.strip()
assgn.section = SECTION_A
# be sure to strip each element of the array `students` in case split leaves white space
students = participants.split('\n') # assume at most 2 elements, and at least one
# the assignee should come 1st
assgn.assignee = students[0].strip()
if len(students) > 1: # the householder second
# '> 1' in case there is an additinal helper (will be ignored)
assgn.hholder = students[1].strip()
assignments.append( assgn )
# the same for the second
participants = row.cells[SECTION_B_PARTICIPANTS].text.strip() # participants for second assgn
if participants != '':
assgn = Assignment() # new empty assignment
assgn.date = date
assgn.type = aType
assgn.lesson = row.cells[SECTION_B_LESSON].text.strip()
assgn.section = SECTION_B
students = participants.split('\n')
assgn.assignee = students[0].strip()
if len(students) > 1:
assgn.hholder = students[1].strip()
assignments.append( assgn )
return assignments
def to_csv(path, year, month):
'''path to docx file, year and month as int, will convert into a csv file'''
docxsched = Document(path)
#find tables in the doc
tables = docxsched.tables
if len(tables) != 1:
#should be raising an exception...
print('uh oh, there should be exactly one table in the document')
#select the first table
table = tables[0]
# Assume everything else is as expected
#there are 5 weeks for every schedule
# pick up the date
# then the type
# if a name and a lesson are found write the csv String
# if only a name is found write the csv string
# if no name is found continue looking for date or type (which ever appears first)
csvSched = [] #this is an array of strings for the csv file
row_iter = iter(table.rows[1:]) #skipping the first row (header)
row = next(row_iter)
# The first week of every month is different (has only 1 assgn)
date = getWeekDate(row, year, month)
#advance to the only participation for first week (Reading)
row = next(row_iter)
assgnRow = parseAssignmentRow(row, date, READING)
for assgn in assgnRow:
csvSched.append(assgn.makeCSV() + '\n')
# Now continue with the remaining 4 weeks
for week in range(4):
row = next(row_iter)
# Extract date for this week
date = getWeekDate(row, year, month)
if date == '': # no date will be available for assignments
continue
for assgnType in TYPES:
row = next(row_iter)
assgnRow = parseAssignmentRow(row, date, assgnType)
for assgn in assgnRow:
# print(assgn)
csvSched.append( assgn.makeCSV() + '\n' )
#path will only work when called from main.py
csvfilename = '../csv/%d-%d.csv' % (year, month)
with open(csvfilename, encoding='utf-8', mode='w') as parsed:
parsed.write(HEADER+'\n')
for line in csvSched:
parsed.write(line)
if __name__ == '__main__':
print('Running as main. Doing nothing.')
| fidelcoria/AYFM-Scheduling | ScheduleParsing/scripts/schedule/convert_docx.py | Python | agpl-3.0 | 5,644 |
describe Instructeurs::InstructeurController, type: :controller do
describe 'before actions: authenticate_instructeur!' do
it 'is present' do
before_actions = Instructeurs::InstructeurController
._process_action_callbacks
.filter { |process_action_callbacks| process_action_callbacks.kind == :before }
.map(&:filter)
expect(before_actions).to include(:authenticate_instructeur!)
end
end
end
| sgmap/tps | spec/controllers/instructeurs/instructeur_controller_spec.rb | Ruby | agpl-3.0 | 440 |
#include "tsp.h"
#include <assert.h>
#include <algorithm>
#include <limits>
#include <map>
#include "astar/astar.h"
using namespace amos;
bool operator<(const player_pose2d_t &a, const player_pose2d_t &b)
{
return (a.px != b.px) ? a.px < b.px : a.py < b.py;
}
TSPThread::TSPThread(Map *map, const double accuracy)
: Thread(), map(map), accuracy(accuracy)
{
assert(map);
}
TSPThread::~TSPThread()
{
}
void TSPThread::set(const std::vector<player_pose2d_t> &waypoints)
{
mutex.lock();
this->waypoints = waypoints;
mutex.unlock();
}
void TSPThread::get(std::vector<player_pose2d_t> *path, double *cost)
{
mutex.lock();
if (path) *path = this->path;
if (cost) *cost = this->cost;
mutex.unlock();
}
void TSPThread::run()
{
std::map<std::pair<player_pose2d_t, player_pose2d_t>, double> costs;
std::vector<player_pose2d_t> path, candidate_path;
double cost, candidate_cost;
std::vector<player_pose2d_t> waypoints;
for(;;)
{
this->testcancel();
// make a copy of the inputs so that they don't get modified when we are calculating
mutex.lock();
waypoints = this->waypoints;
mutex.unlock();
if (waypoints.size() >= 2)
{
// initialize
map->refresh();
costs.clear();
path.clear();
cost = std::numeric_limits<double>::infinity();
candidate_path = std::vector<player_pose2d_t>(waypoints);
sort(candidate_path.begin() + 1, candidate_path.end() - 1);
// evaluate each permutation
do
{
candidate_cost = 0.0;
for(std::vector<player_pose2d_t>::const_iterator i = candidate_path.begin(); i != candidate_path.end() - 1; i++)
{
std::pair<player_pose2d_t, player_pose2d_t> key = (*i < *(i + 1)) ? std::make_pair(*i, *(i + 1)) : std::make_pair(*(i + 1), *i);
// if no cost is calculated for this path yet, use astar to calculate it
if (!costs[key])
{
printf("igvcgps: cost from (%f, %f) to (%f, %f) is calculated to be ... ", i->px, i->py, (i+1)->px, (i+1)->py);
fflush(stdout);
if (!astar_search(map, *i, *(i+1), NULL, &costs[key], accuracy))
{
// no path found, try another permutation
printf("IMPOSSIBLE!\n");
candidate_cost = std::numeric_limits<double>::infinity();
break;
}
printf("%f\n", costs[key]);
}
candidate_cost += costs[key];
// if candidate cost already larger than best, then we can quit calculating the rest
if (candidate_cost >= cost) break;
}
// save best
if (candidate_cost < cost)
{
path = candidate_path;
cost = candidate_cost;
}
}
while(next_permutation(candidate_path.begin() + 1, candidate_path.end() - 1));
if (path.size() != 0)
{
printf("igvcgps: optimal path found with cost = %f\n", cost);
for (std::vector<player_pose2d_t>::const_iterator i = path.begin(); i != path.end(); i++)
{
printf("\t(%f, %f)\n", i->px, i->py);
}
}
else
{
printf("igvcgps: optimal path not found\n");
}
mutex.lock();
this->path = path;
this->cost = cost;
mutex.unlock();
}
usleep(100000);
}
}
| ziyan/amos | player/clients/igvcgps/tsp.cpp | C++ | agpl-3.0 | 3,075 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
********************************************************************************/
$mod_strings = array (
'LBL_DOCUMENTS_SUBPANEL_TITLE' => 'Dokumendid',
'LBL_PARENT_ACCOUNT_ID' => 'Parent Account ID',
'LBL_PUSH_BILLING' => 'Push Billing',
'LBL_PUSH_SHIPPING' => 'Push Billing',
'LBL_TICKER_SYMBOL' => 'Tikkeri sümbol:',
'LBL_MISC' => 'Misc',
'LBL_UTILS' => 'Utils',
'LBL_EMAIL_OPT_OUT' => 'Email Opt Out:',
'LBL_FAX' => 'Fax:',
'LBL_CONTRACTS' => 'Lepingud',
'LBL_CONTRACTS_SUBPANEL_TITLE' => 'Lepingud',
'LBL_PRODUCTS_SUBPANEL_TITLE' => 'Artiklid',
'LBL_QUOTES_SUBPANEL_TITLE' => 'Pakkumised',
'LNK_ACCOUNT_REPORTS' => 'Vaata ettevõtte aruandeid',
'LBL_CHARTS' => 'Diagrammid',
'LBL_DEFAULT' => 'Vaatamisi',
'ACCOUNT_REMOVE_PROJECT_CONFIRM' => 'Oled kindel, et soovid selle ettevõtte projektist eemaldada?',
'ERR_DELETE_RECORD' => 'Ettevõtte kustutamiseks täpsusta kirje numbrit.',
'LBL_ACCOUNT_INFORMATION' => 'Ettevõtte ülevaade',
'LBL_ACCOUNT_NAME' => 'Ettevõtte nimi:',
'LBL_ACCOUNT' => 'Ettevõte:',
'LBL_ACTIVITIES_SUBPANEL_TITLE' => 'Tegevused',
'LBL_ADDRESS_INFORMATION' => 'Aadress:',
'LBL_ANNUAL_REVENUE' => 'Aastane tulu:',
'LBL_ANY_ADDRESS' => 'Muu aadress:',
'LBL_ANY_EMAIL' => 'Muu E-post:',
'LBL_ANY_PHONE' => 'Muu telefon:',
'LBL_ASSIGNED_TO_NAME' => 'Vastutaja:',
'LBL_ASSIGNED_TO_ID' => 'Määratud kasutaja:',
'LBL_BILLING_ADDRESS_CITY' => 'Linn arvel:',
'LBL_BILLING_ADDRESS_COUNTRY' => 'Maakond arvel:',
'LBL_BILLING_ADDRESS_POSTALCODE' => 'Postiindeks arvel:',
'LBL_BILLING_ADDRESS_STATE' => 'Riik arvel:',
'LBL_BILLING_ADDRESS_STREET_2' => 'Tänav 2 arvel',
'LBL_BILLING_ADDRESS_STREET_3' => 'Tänav 3 arvel',
'LBL_BILLING_ADDRESS_STREET_4' => 'Tänav 4 arvel',
'LBL_BILLING_ADDRESS_STREET' => 'Tänav arvel:',
'LBL_BILLING_ADDRESS' => 'Aadress arvel:',
'LBL_BUG_FORM_TITLE' => 'Ettevõtted',
'LBL_BUGS_SUBPANEL_TITLE' => 'Vead',
'LBL_CALLS_SUBPANEL_TITLE' => 'Telefonikõned',
'LBL_CAMPAIGN_ID' => 'Kampaania ID',
'LBL_CASES_SUBPANEL_TITLE' => 'Juhtumid',
'LBL_CITY' => 'Linn:',
'LBL_CONTACTS_SUBPANEL_TITLE' => 'Kontaktid',
'LBL_COUNTRY' => 'Riik',
'LBL_DATE_ENTERED' => 'Loodud',
'LBL_DATE_MODIFIED' => 'Muudetud',
'LBL_MODIFIED_ID' => 'Muutja Id',
'LBL_DEFAULT_SUBPANEL_TITLE' => 'Ettevõtted',
'LBL_DESCRIPTION_INFORMATION' => 'Kirjelduse info',
'LBL_DESCRIPTION' => 'Kirjeldus:',
'LBL_DUPLICATE' => 'Võimalikud topelt ettevõte',
'LBL_EMAIL' => 'E-post:',
'LBL_EMPLOYEES' => 'Töötajaid:',
'LBL_HISTORY_SUBPANEL_TITLE' => 'Ajalugu',
'LBL_HOMEPAGE_TITLE' => 'Minu ettevõtted',
'LBL_INDUSTRY' => 'Tööstusharu:',
'LBL_INVALID_EMAIL' => 'Kehtetu e-post:',
'LBL_INVITEE' => 'Kontaktid',
'LBL_LEADS_SUBPANEL_TITLE' => 'Müügivihjed',
'LBL_LIST_ACCOUNT_NAME' => 'Ettevõtte nimi',
'LBL_LIST_CITY' => 'Linn:',
'LBL_LIST_CONTACT_NAME' => 'Kontaktisiku nimi',
'LBL_LIST_EMAIL_ADDRESS' => 'E-post:',
'LBL_LIST_FORM_TITLE' => 'Ettevõtete loend',
'LBL_LIST_PHONE' => 'Tlf number',
'LBL_LIST_STATE' => 'Maakond:',
'LBL_LIST_WEBSITE' => 'Veebisait',
'LBL_MEETINGS_SUBPANEL_TITLE' => 'Kohtumised',
'LBL_MEMBER_OF' => 'Liige:',
'LBL_MEMBER_ORG_FORM_TITLE' => 'Liikmesorganisatsioonid',
'LBL_MEMBER_ORG_SUBPANEL_TITLE' => 'Liikmesorganisatsioonid',
'LBL_MODULE_NAME' => 'Ettevõtted',
'LBL_MODULE_TITLE' => 'Ettevõtted: Avaleht',
'LBL_MODULE_ID' => 'Ettevõtted',
'LBL_NAME' => 'Nimi:',
'LBL_NEW_FORM_TITLE' => 'Uus ettevõte',
'LBL_OPPORTUNITIES_SUBPANEL_TITLE' => 'Müügivõimalused',
'LBL_OTHER_EMAIL_ADDRESS' => 'Teine e-post:',
'LBL_OTHER_PHONE' => 'Teine telefon:',
'LBL_OWNERSHIP' => 'Omandivorm:',
'LBL_PHONE_ALT' => 'Alternatiivne telefon:',
'LBL_PHONE_FAX' => 'Fax:',
'LBL_PHONE_OFFICE' => 'Töötelefon:',
'LBL_PHONE' => 'Tlf number:',
'LBL_POSTAL_CODE' => 'Postiindeks:',
'LBL_PRODUCTS_TITLE' => 'Artiklid',
'LBL_PROJECTS_SUBPANEL_TITLE' => 'Projektid',
'LBL_PUSH_CONTACTS_BUTTON_LABEL' => 'Kopeeri kontaktidele',
'LBL_PUSH_CONTACTS_BUTTON_TITLE' => 'Kopeeri...',
'LBL_RATING' => 'Hindamine:',
'LBL_SAVE_ACCOUNT' => 'Salvesta ettevõte',
'LBL_SEARCH_FORM_TITLE' => 'Ettevõtte otsing',
'LBL_SHIPPING_ADDRESS_CITY' => 'Tarne linn:',
'LBL_SHIPPING_ADDRESS_COUNTRY' => 'Tarne maakond:',
'LBL_SHIPPING_ADDRESS_POSTALCODE' => 'Tarne postiindeks:',
'LBL_SHIPPING_ADDRESS_STATE' => 'Tarne riik:',
'LBL_SHIPPING_ADDRESS_STREET_2' => 'Tarne tänav 2',
'LBL_SHIPPING_ADDRESS_STREET_3' => 'Tarne tänav 3',
'LBL_SHIPPING_ADDRESS_STREET_4' => 'Tarne tänav 4',
'LBL_SHIPPING_ADDRESS_STREET' => 'Tarne tänav:',
'LBL_SHIPPING_ADDRESS' => 'Tarne aadress:',
'LBL_SIC_CODE' => 'SIC kood:',
'LBL_STATE' => 'Maakond:',
'LBL_TASKS_SUBPANEL_TITLE' => 'Ülesanded',
'LBL_TEAMS_LINK' => 'Meeskonnad',
'LBL_TYPE' => 'Tüüp:',
'LBL_USERS_ASSIGNED_LINK' => 'Määratud kasutajad',
'LBL_USERS_CREATED_LINK' => 'Loodud kasutajate poolt',
'LBL_USERS_MODIFIED_LINK' => 'Muudetud kasutajad',
'LBL_VIEW_FORM_TITLE' => 'Ettevõtte vaade',
'LBL_WEBSITE' => 'Veebisait:',
'LBL_CREATED_ID' => 'Looja Id',
'LBL_CAMPAIGNS' => 'Kampaaniad',
'LNK_ACCOUNT_LIST' => 'Vaata ettevõtteid',
'LNK_NEW_ACCOUNT' => 'Loo ettevõte',
'LNK_IMPORT_ACCOUNTS' => 'Impordi ettevõtted',
'MSG_DUPLICATE' => 'Ettevõtte kirje, mida hetkel lood võib olla duplikaat juba olemasolevast ettevõtte kirjest. Kirjed, mis sisaldavad sarnaseid nimesid on väljatoodud allpool. Kliki Salvesta selle uue konto loomiseks või kliki Tühista moodulisse tagasiminemiseks kontot loomata.',
'MSG_SHOW_DUPLICATES' => 'Ettevõtte kirje, mida hetkel lood võib olla duplikaat juba olemasolevast ettevõtte kirjest. Kirjed, mis sisaldavad sarnaseid nimesid on väljatoodud allpool. Kliki Salvesta selle uue konto loomiseks või kliki Tühista moodulisse tagasiminemiseks kontot loomata.',
'NTC_COPY_BILLING_ADDRESS' => 'Kopeeri arve aadress tarne aadressiks',
'NTC_COPY_BILLING_ADDRESS2' => 'Kopeeri tarnimiseks',
'NTC_COPY_SHIPPING_ADDRESS' => 'Kopeeri tarneaadress arve aadressiks',
'NTC_COPY_SHIPPING_ADDRESS2' => 'Kopeeri arvelduseks',
'NTC_DELETE_CONFIRMATION' => 'Oled kindel, et soovid seda kirjet kustutada?',
'NTC_REMOVE_ACCOUNT_CONFIRMATION' => 'Oled kindel, et soovid selle kirje eemaldada?',
'NTC_REMOVE_MEMBER_ORG_CONFIRMATION' => 'Oled kindel, et soovid selle kirje eemaldada liikmesorganisatsioonina?',
'LBL_ASSIGNED_USER_NAME' => 'Vastutaja',
'LBL_PROSPECT_LIST' => 'Kuuma kontakti loend',
'LBL_ACCOUNTS_SUBPANEL_TITLE' => 'Ettevõtted',
'LBL_PROJECT_SUBPANEL_TITLE' => 'Projektid',
);
| harish-patel/ecrm | modules/Accounts/language/et_EE.lang.php | PHP | agpl-3.0 | 8,369 |
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2015 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
// ===================================================================================================
package com.kaltura.client.types;
import org.w3c.dom.Element;
import com.kaltura.client.KalturaParams;
import com.kaltura.client.KalturaApiException;
import com.kaltura.client.utils.ParseUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaAccessControlLimitFlavorsAction extends KalturaRuleAction {
/** Comma separated list of flavor ids */
public String flavorParamsIds;
public boolean isBlockedList;
public KalturaAccessControlLimitFlavorsAction() {
}
public KalturaAccessControlLimitFlavorsAction(Element node) throws KalturaApiException {
super(node);
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node aNode = childNodes.item(i);
String nodeName = aNode.getNodeName();
String txt = aNode.getTextContent();
if (nodeName.equals("flavorParamsIds")) {
this.flavorParamsIds = ParseUtils.parseString(txt);
continue;
} else if (nodeName.equals("isBlockedList")) {
this.isBlockedList = ParseUtils.parseBool(txt);
continue;
}
}
}
public KalturaParams toParams() throws KalturaApiException {
KalturaParams kparams = super.toParams();
kparams.add("objectType", "KalturaAccessControlLimitFlavorsAction");
kparams.add("flavorParamsIds", this.flavorParamsIds);
kparams.add("isBlockedList", this.isBlockedList);
return kparams;
}
}
| moskiteau/KalturaGeneratedAPIClientsJava | src/main/java/com/kaltura/client/types/KalturaAccessControlLimitFlavorsAction.java | Java | agpl-3.0 | 3,076 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage DublinCore
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @see Zend_Gdata_Extension
*/
require_once 'Zend/Gdata/Extension.php';
/**
* Point or period of time associated with an event in the lifecycle of the
* resource
*
* @category Zend
* @package Zend_Gdata
* @subpackage DublinCore
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_DublinCore_Extension_Date extends Zend_Gdata_Extension
{
protected $_rootNamespace = 'dc';
protected $_rootElement = 'date';
/**
* Constructor for Zend_Gdata_DublinCore_Extension_Date which
* Point or period of time associated with an event in the lifecycle of the
* resource
*
* @param DOMElement $element (optional) DOMElement from which this
* object should be constructed.
*/
public function __construct($value = null)
{
$this->registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces);
parent::__construct();
$this->_text = $value;
}
}
| RajkumarSelvaraju/FixNix_CRM | Zend/Gdata/DublinCore/Extension/Date.php | PHP | agpl-3.0 | 1,835 |
/*
* BerrySys SigTran USSDGW
* Copyright (C) 2015 BerrySys S.A. de C.V.
*
* This program is free software: you can redistribute it and/or modify
* 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.berrysys.ussdgw;
import org.fusesource.hawtdispatch.Dispatch;
import org.fusesource.hawtdispatch.DispatchQueue;
/**
* The Class HawtDispatchUtil.
*/
public class HawtDispatchUtil {
/**
* Gets the single instance of HawtDispatchUtil.
*
* @return single instance of HawtDispatchUtil
*/
public static HawtDispatchUtil getInstance() {
return HawtDispatchUtil.instance;
}
/** The Constant instance. */
private final static HawtDispatchUtil instance = new HawtDispatchUtil();
/** The queue. */
DispatchQueue queue = Dispatch.getGlobalQueue(Dispatch.HIGH);
/**
* Queue execute.
*
* @param runnable the runnable
*/
public void queueExecute(final Runnable runnable) {
this.queue.execute(runnable);
}
}
| BerrySys/berrysys-ussdgw | src/main/java/com/berrysys/ussdgw/HawtDispatchUtil.java | Java | agpl-3.0 | 1,517 |
define([
'backbone.associations',
'../qt_basemodel'
],
function (Backbone,BaseModel) {
'use strict';
return BaseModel.extend({
defaults: {
url : '',
uuid : '',
title : '',
preset : '', //url du preset
sub_processor : '', //url du subprocessor
parameters_schema : '' //schema des paramètres
},
relations: [],
//////////////////////////////////////////
});
});
| Parisson/TimeSide | timeside/player/static/timeside2/app/scripts/core/models/client/analysis.js | JavaScript | agpl-3.0 | 430 |
#!/usr/bin/env bash
/run.sh &
sleep 5
cd /builds/salsah-suite/rapier-scala
./webapi/scripts/graphdb-free-ci-prepare.sh
kill $!
/run.sh &
sleep 5
cd /builds/salsah-suite/rapier-scala
sbt "project webapi" "graphdb-free:test"
| nie-ine/Knora | webapi/scripts/docker/build_graphdb_free_script.sh | Shell | agpl-3.0 | 227 |
<?php
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* 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 and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
$mod_strings = array (
'LBL_ASSIGNED_TO_ID' => 'Toegewezen gebruiker',
'LBL_ASSIGNED_TO_NAME' => 'Toegewezen aan',
'LBL_ID' => 'ID',
'LBL_DATE_ENTERED' => 'Ingevoerd',
'LBL_DATE_MODIFIED' => 'Laatste wijziging',
'LBL_MODIFIED' => 'Gewijzigd door',
'LBL_MODIFIED_ID' => 'Gewijzigd door Id',
'LBL_MODIFIED_NAME' => 'Gewijzigd op Naam',
'LBL_CREATED' => 'Gecreëerd Door',
'LBL_CREATED_ID' => 'Gemaakt door ID',
'LBL_DESCRIPTION' => 'Omschrijving',
'LBL_DELETED' => 'Verwijderd',
'LBL_NAME' => 'Naam',
'LBL_CREATED_USER' => 'Gecreëerd door Gebruiker',
'LBL_MODIFIED_USER' => 'Gewijzigd door Gebruiker',
'LBL_LIST_NAME' => 'Naam',
'LBL_EDIT_BUTTON' => 'Wijzig',
'LBL_REMOVE' => 'Verwijder',
'LBL_LIST_FORM_TITLE' => 'Index Lijst',
'LBL_MODULE_NAME' => 'Indexeer',
'LBL_MODULE_TITLE' => 'Indexeer',
'LBL_HOMEPAGE_TITLE' => 'Mijn Index',
'LNK_NEW_RECORD' => 'Creeër Index',
'LNK_LIST' => 'Bekijk Index',
'LNK_IMPORT_AOD_INDEX' => 'Importeer Index',
'LBL_SEARCH_FORM_TITLE' => 'Zoek Index',
'LBL_HISTORY_SUBPANEL_TITLE' => 'Bekijk Geschiedenis',
'LBL_ACTIVITIES_SUBPANEL_TITLE' => 'Activiteiten',
'LBL_AOD_INDEX_SUBPANEL_TITLE' => 'Indexeer',
'LBL_NEW_FORM_TITLE' => 'Nieuwe Index',
'LBL_LAST_OPTIMISED' => 'Geoptimaliseerd op',
'LBL_LOCATION' => 'Locatie',
'LBL_SEARCH_DOCUMENTS' => 'Zoek Documenten',
'LBL_SEARCH_BUTTON' => 'Zoek',
'LBL_SEARCH_QUERY_PLACEHOLDER' => 'Invoer zoeken...',
'LBL_INDEX_STATS' => 'Indexeer statistiek',
'LBL_SEARCH_LABEL' => "Zoeken...",
'LBL_OPTIMISE_NOW' => "Optimaliseer Nu",
'LBL_TOTAL_RECORDS' => 'Totaal aantal records',
'LBL_INDEXED_RECORDS' => 'Geindexeerde records',
'LBL_UNINDEXED_RECORDS' => 'Niet Geindexeerde records',
'LBL_FAILED_RECORDS' => 'Mislukte records',
'LBL_INDEX_FILES' => 'Index aantal Bestanden',
'LBL_SEARCH_RESULT_SCORE' => 'Zoek Score',
'LBL_SEARCH_RESULT_MODULE' => 'Module',
'LBL_SEARCH_RESULT_NAME' => 'Naam',
'LBL_SEARCH_RESULT_DATE_CREATED' => 'Datum Gecreëerd',
'LBL_SEARCH_RESULT_DATE_MODIFIED' => 'Datum Gewijzigd',
'LBL_SEARCH_RESULT_EMPTY' => 'Geen resultaat',
'LBL_SEARCH_RESULT_SUMMARY' => 'Samenvattig',
'LBL_FAILED_INDEX_MODULE' => 'Module',
'LBL_FAILED_INDEX_NAME' => 'Naam',
'LBL_FAILED_INDEX_DATE' => 'Datum',
'LBL_FAILED_INDEX_ERROR' => 'Fout',
'LBL_NEVER_OPTIMISED' => 'Nooit',
'LBL_USE_AOD_SEARCH' => 'Geavanceerd zoeken',
'LBL_USE_VANILLA_SEARCH' => 'Standaard zoeken',
);
| codesquad36/dc_guidoCRM | modules/AOD_Index/language/nl_NL.lang.php | PHP | agpl-3.0 | 4,685 |
/*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* This file is part of Tanaguru.
*
* Tanaguru 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/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.keystore;
/**
* Utility class that stores css-like queries as static String
*/
public final class CssLikeQueryStore {
// Image theme css-like queries
public static final String IMG_WITHOUT_ALT_CSS_LIKE_QUERY="img:not([alt])";
public static final String IMG_WITH_ALT_CSS_LIKE_QUERY="img[alt]";
public static final String IMG_WITH_ALT_NOT_IN_LINK_CSS_LIKE_QUERY=
"img[alt]:not(a img)";
public static final String IMG_WITH_ALT_NOT_IN_LINK_WITHOUT_LONGDESC_CSS_LIKE_QUERY=
"img[alt]:not(a img):not([longdesc])";
public static final String IMG_NOT_IN_LINK_CSS_LIKE_QUERY="img:not(a img)";
public static final String IMG_WITH_ISMAP_ATTR_CSS_LIKE_QUERY=
"img[ismap] , "
+"input[type=image][ismap]";
public static final String IMG_WITH_ALT_WITHOUT_LONGDESC_CSS_LIKE_QUERY=
"img[alt]:not([longdesc])";
public static final String APPLET_WITH_ALT_CSS_LIKE_QUERY=
"applet[alt]";
public static final String APPLET_WITH_ALT_NOT_IN_LINK_CSS_LIKE_QUERY=
"applet[alt]:not(a applet)";
public static final String APPLET_NOT_IN_LINK_CSS_LIKE_QUERY=
"applet:not(a applet)";
public static final String OBJECT_TYPE_IMG_CSS_LIKE_QUERY=
"object[type^=image]";
public static final String OBJECT_TYPE_IMG_NOT_IN_LINK_CSS_LIKE_QUERY=
"object[type^=image]:not(a object)";
public static final String EMBED_TYPE_IMG_CSS_LIKE_QUERY=
"embed[type^=image]";
public static final String EMBED_TYPE_IMG_NOT_IN_LINK_CSS_LIKE_QUERY=
"embed[type^=image]:not(a embed)";
public static final String AREA_WITH_ALT_CSS_LIKE_QUERY=
"area[alt]";
public static final String AREA_WITH_ALT_NOT_IN_LINK_CSS_LIKE_QUERY=
"area[alt]:not(a area)";
public static final String AREA_NOT_IN_LINK_CSS_LIKE_QUERY=
"area:not(a area)";
public static final String AREA_WITH_ALT_WITHOUT_HREF_ATTR_CSS_LIKE_QUERY=
"area[alt]:not([href])";
public static final String FORM_BUTTON_CSS_LIKE_QUERY="input[type=image]";
public static final String FORM_BUTTON_WITH_ALT_CSS_LIKE_QUERY=
"input[type=image][alt]";
public static final String MAP_WITH_AREA_CHILD_AND_NAME_ATTR_CSS_LIKE_QUERY =
"map:has(area)[name]:not([name~=^\\s*$])";
public static final String NOT_EMPTY_ALT_ATTR_NOT_IN_LINK_CSS_LIKE_QUERY =
"[alt]:not([alt~=^\\s*$]):not(a [alt])";
//aria
public static final String ARIA_ATTRIBUTES_CSS_LIKE_QUERY="[^aria]";
public static final String ARIA_DESCRIBEDBY_CSS_LIKE_QUERY="[aria-describedby]";
public static final String ARIA_LABEL_CSS_LIKE_QUERY="[aria-label]";
public static final String ARIA_LABELLEDBY_CSS_LIKE_QUERY="[aria-labelledby]";
//svg children
public static final String NOT_EMPTY_ARIA_TITLE_CSS_LIKE_QUERY =
"title:not(:matchesOwn(^\\s*$))";
public static final String NOT_EMPTY_ARIA_DESC_CSS_LIKE_QUERY =
"desc:not(:matchesOwn(^\\s*$))";
public static final String SVG_NOT_IN_LINK_CSS_LIKE_QUERY=
"svg:not(a svg)";
public static final String SVG_NOT_IN_LINK_WITH_DESC_CHILD_CSS_LIKE_QUERY=
"svg:not(a svg):has(desc:not(:matchesOwn(^\\s*$))";
public static final String SVG_NOT_IN_LINK_WITH_ARIA_LABEL_CSS_LIKE_QUERY=
"svg[aria-label]:not([aria-label~=^\\s*$]:not(a svg)";
public static final String SVG_NOT_IN_LINK_WITH_DESC_CHILD_AND_ROLE_IMG_CSS_LIKE_QUERY=
"svg[role=img]:not(a svg):has(desc:not(:matchesOwn(^\\s*$))";
public static final String SVG_NOT_IN_LINK_WITH_ARIA_LABEL_AND_ROLE_IMG_CSS_LIKE_QUERY=
"svg[role=img][aria-label]:not([aria-label~=^\\s*$]:not(a svg)";
public static final String CANVAS_NOT_IN_LINK_CSS_LIKE_QUERY=
"canvas:not(a canvas)";
public static final String CANVAS_NOT_IN_LINK_WITH_NOT_EMPTY_CONTENT_CSS_LIKE_QUERY=
"canvas:not(a canvas):not(:matchesOwn(^\\s*$))";
// Table theme css-like queries
public static final String TABLE_WITH_SUMMARY_CSS_LIKE_QUERY="table[summary]";
public static final String TABLE_WITH_CAPTION_CSS_LIKE_QUERY="table:has(caption)";
public static final String TABLE_WITH_TH_CSS_LIKE_QUERY="table:has(th)";
public static final String TABLE_WITH_TH_OR_TD_CSS_LIKE_QUERY=
"table:has(th), table:has(td)";
public static final String DATA_TABLE_MARKUP_CSS_LIKE_QUERY =
"caption , "
+ "th , "
+ "thead , "
+ "tfoot , "
+ "colgroup , "
+ "td[scope] , "
+ "td[headers] , "
+ "td[axis]";
// Frame theme css-like queries
public static final String FRAME_WITH_TITLE_CSS_LIKE_QUERY="frame[title]";
public static final String IFRAME_WITH_TITLE_CSS_LIKE_QUERY="iframe[title]";
public static final String IFRAME_WITH_NOT_EMPTY_TITLE_CSS_LIKE_QUERY=
"iframe[title]:not([title~=^\\s*$])";
public static final String FRAME_WITH_NOT_EMPTY_TITLE_CSS_LIKE_QUERY=
"frame[title]:not([title~=^\\s*$])";
// Form theme css-like queries
public static final String FORM_WITHOUT_FIELDSET_CSS_LIKE_QUERY =
"form:not(:has(fieldset))";
public static final String FORM_ELEMENT_CSS_LIKE_QUERY=
"textarea , "
+"select , "
+"datalist , "
+"keygen , "
+"input[type=password] , "
+"input[type=checkbox] , "
+"input[type=file] , "
+"input[type=text] , "
+"input[type=search] , "
+"input[type=tel] , "
+"input[type=email] , "
+"input[type=number] , "
+"input[type=url] , "
+"input[type=date] , "
+"input[type=range] , "
+"input[type=color] , "
+"input[type=time] , "
+"input[type=radio]";
public static final String INPUT_ELEMENT_INSIDE_FORM_CSS_LIKE_QUERY=
"form textarea:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form select:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form datalist:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form keygen:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=password]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=checkbox]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=file]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=text]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=search]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=tel]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=email]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=number]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=url]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=date]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=range]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=color]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=time]:not([title]):not([aria-label]):not([aria-labelledby]) , "
+"form input[type=radio]:not([title]):not([aria-label]):not([aria-labelledby])";
public static final String INPUT_ELEMENT_WITH_ARIA_INSIDE_FORM_CSS_LIKE_QUERY=
"form textarea[aria-labelledby] , "
+"form select[aria-labelledby] , "
+"form datalist[aria-labelledby] , "
+"form keygen[aria-labelledby] , "
+"form input[type=password][aria-labelledby] , "
+"form input[type=checkbox][aria-labelledby] , "
+"form input[type=file][aria-labelledby] , "
+"form input[type=text][aria-labelledby] , "
+"form input[type=search][aria-labelledby] , "
+"form input[type=tel][aria-labelledby] , "
+"form input[type=email][aria-labelledby] , "
+"form input[type=number][aria-labelledby] , "
+"form input[type=url][aria-labelledby] , "
+"form input[type=date][aria-labelledby] , "
+"form input[type=range][aria-labelledby] , "
+"form input[type=color][aria-labelledby] , "
+"form input[type=time][aria-labelledby] , "
+"form input[type=radio][aria-labelledby]";
public static final String FORM_ELEMENT_WITH_ID_CSS_LIKE_QUERY =
"textarea[id] , "
+ "select[id] , "
+ "datalist[id] , "
+ "keygen[id] , "
+ "input[type=password][id] , "
+ "input[type=checkbox][id] , "
+ "input[type=file][id] , "
+ "input[type=text][id] , "
+ "input[type=search][id] , "
+ "input[type=tel][id] , "
+ "input[type=email][id] , "
+ "input[type=number][id] , "
+ "input[type=url][id] , "
+ "input[type=date][id] , "
+ "input[type=range][id] , "
+ "input[type=color][id] , "
+ "input[type=time][id] , "
+ "input[type=radio][id]";
public static final String FORM_ELEMENT_WITH_TITLE_CSS_LIKE_QUERY =
"textarea[title] , "
+ "select[title] , "
+ "datalist[title] , "
+ "keygen[title] , "
+ "input[type=password][title] , "
+ "input[type=checkbox][title] , "
+ "input[type=file][title] , "
+ "input[type=text][title] , "
+ "input[type=search][title] , "
+ "input[type=tel][title] , "
+ "input[type=email][title] , "
+ "input[type=number][title] , "
+ "input[type=url][title] , "
+ "input[type=date][title] , "
+ "input[type=range][title] , "
+ "input[type=color][title] , "
+ "input[type=time][title] , "
+ "input[type=radio][title]";
public static final String FORM_TEXT_INPUT_CSS_LIKE_QUERY =
"form:has(textarea) , "
+ "form:has(input[type=password]) , "
+ "form:has(input[type=text])";
public static final String LABEL_WITHIN_FORM_CSS_LIKE_QUERY=
"form:has("+ FORM_ELEMENT_CSS_LIKE_QUERY +") label";
public static final String FORM_LABEL_WITH_INNER_FORM_ELEMENT_CSS_LIKE_QUERY=
"form label:has(input[type=text]) , "
+ "form label:has(input[type=password]) , "
+ "form label:has(input[type=checkbox]) , "
+ "form label:has(input[type=radio]) , "
+ "form label:has(input[type=file]) , "
+ "form label:has(input[type=search]) , "
+ "form label:has(input[type=tel]) , "
+ "form label:has(input[type=email]) , "
+ "form label:has(input[type=number]) , "
+ "form label:has(input[type=url]) , "
+ "form label:has(input[type=date]) , "
+ "form label:has(input[type=range]) , "
+ "form label:has(input[type=color]) , "
+ "form label:has(input[type=time]) , "
+ "form label:has(textarea) , "
+ "form label:has(select) , "
+ "form label:has(datalist) , "
+ "form label:has(keygen)";
public static final String LEGEND_WITHIN_FIELDSET_CSS_LIKE_QUERY =
"fieldset legend";
public static final String SELECT_WITHOUT_OPTGROUP_CSS_LIKE_QUERY =
"select:not(:has(optgroup))";
public static final String SELECT_WITHIN_FORM_CSS_LIKE_QUERY =
"form select";
public static final String OPTGROUP_WITH_LABEL_ATTR_CSS_LIKE_QUERY =
"optgroup[label]";
public static final String OPTGROUP_WITHIN_SELECT_WITH_LABEL_ATTR_CSS_LIKE_QUERY =
"select optgroup[label]";
public static final String OPTGROUP_WITHIN_SELECT_CSS_LIKE_QUERY =
"select optgroup";
public static final String BUTTON_FORM_CSS_LIKE_QUERY =
"form input[type=submit] , "
+ "form input[type=reset] , "
+ "form input[type=button] , "
+ "form input[type=image] , "
+ "form button ";
// Lang css-like queries
public static final String ELEMENT_WITH_LANG_ATTR_CSS_LIKE_QUERY =
"html [lang], html [xml:lang]";
public static final String ELEMENT_WITHOUT_LANG_ATTR_CSS_LIKE_QUERY =
"html *:not(:matchesOwn(^\\s*$)):not([lang]):not([xml:lang]), "
+ "html *[alt]:not([alt~=^\\s*$]):not([lang]):not([xml:lang]), "
+ "html *[title]:not([title~=^\\s*$]):not([lang]):not([xml:lang]), "
+ "html *[summary]:not([summary~=^\\s*$]):not([lang]):not([xml:lang])"
+ "html *[content]:not([content~=^\\s*$]):not([lang]):not([xml:lang])"
+ "hmtl *[value]:not([value~=^\\s*$]):not([lang]):not([xml:lang])";
// Mandatory elements css-like queries
public static final String TITLE_WITHIN_HEAD_CSS_LIKE_QUERY =
"head title";
public static final String HTML_WITH_LANG_CSS_LIKE_QUERY =
"html[lang], html[xml:lang]";
// Links css-like queries
public static final String NOT_ANCHOR_LINK_CSS_LIKE_QUERY =
"a:not([name]):not([id])";
public static final String TEXT_LINK_CSS_LIKE_QUERY =
"a[href]:not(:has(*))";
public static final String LINK_WITH_CHILDREN_CSS_LIKE_QUERY =
"a[href]:has(*)";
public static final String LINK_WITH_HREF_CSS_LIKE_QUERY =
"a[href]";
public static final String IMAGE_LINK_CHILDREN_CSS_LIKE_QUERY =
"img[alt] , object[type^=image], object[data^=data:image],"
+ "object[data$=png], object[data$=jpeg], object[data$=jpg],"
+ "object[data$=bmp], object[data$=gif], canvas" ;
public static final String CLICKABLE_AREA_CSS_LIKE_QUERY = "area[href][alt]";
public static final String LINK_WITHOUT_TARGET_CSS_LIKE_QUERY =
"a:not([href]):not([name]):not([id])";
public static final String FIELDSET_NOT_WITHIN_FORM_CSS_LIKE_QUERY =
"fieldset:not(form fieldset):not(*[role=search] fieldset):not(*[role=form] fieldset)";
public static final String LINK_WITH_TARGET_ATTR_CSS_LIKE_QUERY =
"a[href][target]:not([target=_self]):not([target~=^\\s*$])"
+ ":not([target=_top]):not([target=_parent])";
// Scripts css-like queries
public static final String CHANGE_CONTEXT_SCRIPT_CSS_LIKE_QUERY =
"select[onchange], "
+ "form:has(select)"
+ ":not(:has(button))"
+ ":not(:has(input[type=submit]))"
+ ":not(:has(input[type=button]))"
+ ":not(:has(input[type=reset]))";
// Consultation css-like queries
public static final String META_WITH_REFRESH_CSS_LIKE_QUERY =
"meta[http-equiv=refresh][content*=url]";
public static final String FORM_CONTROL_CSS_LIKE_QUERY =
"form, "
+ "select:not(form select), "
+ "textarea:not(form textarea), "
+ "input:not(form input):not([type=hidden]), "
+ "button:not(form button)";
// Structuration of information css-like queries
public static final String HEADINGS_CSS_LIKE_QUERY =
"h1, h2, h3, h4, h5, h6";
// Structuration of information css-like queries
public static final String ARIA_HEADINGS_CSS_LIKE_QUERY =
"[role=heading][aria-level]";
// Structuration of information css-like queries
public static final String ARIA_LEVEL1_HEADINGS_CSS_LIKE_QUERY =
"[role=heading][aria-level=1]";
// Elements with attributes (minus element exceptions)
public static final String ELEMENT_WITH_WITDH_ATTR_NOT_IMG =
":not(img):not(svg)[width]:not(svg [width])";
public static final String ELEMENT_WITH_HEIGHT_ATTR_NOT_IMG =
":not(img):not(svg)[height]:not(svg [height])";
// Elements with attributes (minus element exceptions)
public static final String ELEMENT_WITH_WITDH_ATTR_NOT_IMG_V2 =
":not(img):not(svg):not(object):not(embed):not(canvas)[width]:not(svg [width])";
public static final String ELEMENT_WITH_HEIGHT_ATTR_NOT_IMG_V2 =
":not(img):not(svg):not(object):not(embed):not(canvas)[height]:not(svg [height])";
public static final String IMG_CSS_LIKE_QUERY=
IMAGE_LINK_CHILDREN_CSS_LIKE_QUERY
+ "embed[type^=image]"
+ "input[type^=image]";
// scripts
public static final String ONCLICK_CSS_LIKE_QUERY=
"*[onclick]"
+ ":not(a[onlick])"
+ ":not(area[onclick])"
+ ":not(button[onlick])"
+ ":not(input[type=button][onclick])"
+ ":not(input[type=submit][onclick])"
+ ":not(input[type=reset][onclick])"
+ ":not(input[type=image][onclick])"
+ ":not(input[type=password][onclick])"
+ ":not(input[type=radio][onclick])"
+ ":not(input[type=checkbox][onclick])"
+ ":not(input[type=button][onclick])";
// Seo
public static final String META_DESC_CSS_LIKE_QUERY =
"head meta[name=description][content]";
public static final String FLASH_CONTENT_CSS_LIKE_QUERY =
"[type=application/x-shockwave-flash], "
+ "object[data$=swf], "
+ "embed[src$=swf]";
public static final String REL_CANONICAL_CSS_LIKE_QUERY =
"head link[rel=canonical][href]";
/**
* Private constructor. This class handles keys and must not be instanciated
*/
private CssLikeQueryStore() {}
}
| medsob/Tanaguru | rules/rules-commons/src/main/java/org/tanaguru/rules/keystore/CssLikeQueryStore.java | Java | agpl-3.0 | 20,806 |
/*
* Copyright © 2015-2019 the contributors (see Contributors.md).
*
* This file is part of Knora.
*
* Knora 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.
*
* Knora 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 Knora. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Lukas Rosenthaler <lukas.rosenthaler@unibas.ch>
* @package jqplugins
*
* This plugin creates an edit-form for the properties of a resource
*
* <pre>
* <em>Title:</em><div class="propedit" data-propname="title" />
* <em>Autor:</em><div class="propedit" data-propname="author" />
* </pre>
*
* <pre>
* <script type="text/javascript">
* $('div.propedit').propedit(resdata, propdata);
* </script>
* </pre>
*/
(function( $ ){
'use strict';
var spin_up = new Image();
spin_up.src = SITE_URL + '/app/icons/up.png';
var spin_down = new Image();
spin_down.src = SITE_URL + '/app/icons/down.png';
/*
var spin_up2 = new Image();
spin_up2.src = SITE_URL + '/app/icons/spin-up2.png';
var spin_down2 = new Image();
spin_down2.src = SITE_URL + '/app/icons/spin-down2.png';
var spin_up3 = new Image();
spin_up3.src = SITE_URL + '/app/icons/spin-up3.png';
var spin_down3 = new Image();
spin_down3.src = SITE_URL + '/app/icons/spin-down3.png';
*/
// TODO: temporary fix due to async loading problem of strings, https://github.com/dhlab-basel/Knora/issues/92
var cal_strings = {
"_day_su" : "Sun",
"_day_mo" : "Mon",
"_day_tu" : "Tue",
"_day_we" : "Wed",
"_day_th" : "Thu",
"_day_fr" : "Fri",
"_day_sa" : "Sat",
"_mon_jan_short" : "Jan",
"_mon_feb_short" : "Feb",
"_mon_mar_short" : "Mar",
"_mon_apr_short" : "Apr",
"_mon_may_short" : "May",
"_mon_jun_short" : "Jun",
"_mon_jul_short" : "Jul",
"_mon_aug_short" : "Aug",
"_mon_sep_short" : "Sep",
"_mon_oct_short" : "Oct",
"_mon_nov_short" : "Nov",
"_mon_dec_short" : "Dec",
"_mon_jan_long" : "January",
"_mon_feb_long" : "February",
"_mon_mar_long" : "March",
"_mon_apr_long" : "April",
"_mon_may_long" : "May",
"_mon_jun_long" : "June",
"_mon_jul_long" : "July",
"_mon_aug_long" : "August",
"_mon_sep_long" : "September",
"_mon_oct_long" : "October",
"_mon_nov_long" : "November",
"_mon_dec_long" : "December",
"_not_stated" : "Not stated",
"_change_year" : "Change Year",
"_change_decade" : "Change decade",
"_change_century" : "Change century",
"_period" : "Period"
};
var weekday = [cal_strings._day_su, cal_strings._day_mo, cal_strings._day_tu, cal_strings._day_we, cal_strings._day_th, cal_strings._day_fr, cal_strings._day_sa];
var months = {
GREGORIAN: ['ZERO', cal_strings._mon_jan_short, cal_strings._mon_feb_short, cal_strings._mon_mar_short, cal_strings._mon_apr_short, cal_strings._mon_may_short, cal_strings._mon_jun_short, cal_strings._mon_jul_short, cal_strings._mon_aug_short, cal_strings._mon_sep_short, cal_strings._mon_oct_short, cal_strings._mon_nov_short, cal_strings._mon_dec_short],
JULIAN: ['ZERO', cal_strings._mon_jan_short, cal_strings._mon_feb_short, cal_strings._mon_mar_short, cal_strings._mon_apr_short, cal_strings._mon_may_short, cal_strings._mon_jun_short, cal_strings._mon_jul_short, cal_strings._mon_aug_short, cal_strings._mon_sep_short, cal_strings._mon_oct_short, cal_strings._mon_nov_short, cal_strings._mon_dec_short],
JEWISH: ['ZERO', 'Tishri', 'Heshvan', 'Kislev', 'Tevet', 'Shevat', 'AdarI', 'AdarII', 'Nisan', 'Iyyar', 'Sivan', 'Tammuz', 'Av', 'Elul'],
FRENCH: ['ZERO', 'Vendemiaire', 'Brumaire', 'Frimaire', 'Nivose', 'Pluviose', 'Ventose', 'Germinal', 'Floreal', 'Prairial', 'Messidor', 'Thermidor', 'Fructidor', 'Extra']
};
var months_long = {
GREGORIAN: ['ZERO', cal_strings._mon_jan_long, cal_strings._mon_feb_long, cal_strings._mon_mar_long, cal_strings._mon_apr_long, cal_strings._mon_may_long, cal_strings._mon_jun_long, cal_strings._mon_jul_long, cal_strings._mon_aug_long, cal_strings._mon_sep_long, cal_strings._mon_oct_long, cal_strings._mon_nov_long, cal_strings._mon_dec_long],
JULIAN: ['ZERO', cal_strings._mon_jan_long, cal_strings._mon_feb_long, cal_strings._mon_mar_long, cal_strings._mon_mapr_long, cal_strings._mon_may_long, cal_strings._mon_jun_long, cal_strings._mon_jul_long, cal_strings._mon_aug_long, cal_strings._mon_sep_long, cal_strings._mon_oct_long, cal_strings._mon_nov_long, cal_strings._mon_dec_long],
JEWISH: ['ZERO', 'Tishri', 'Heshvan', 'Kislev', 'Tevet', 'Shevat', 'AdarI', 'AdarII', 'Nisan', 'Iyyar', 'Sivan', 'Tammuz', 'Av', 'Elul'],
FRENCH: ['ZERO', 'Vendemiaire', 'Brumaire', 'Frimaire', 'Nivose', 'Pluviose', 'Ventose', 'Germinal', 'Floreal', 'Prairial', 'Messidor', 'Thermidor', 'Fructidor', 'Extra']
};
var precision = {
DAY: 'Day',
MONTH: 'Month',
YEAR: 'Year'
};
var day_popoup_is_open = false;
var open_daysel_popup = function(daysel, month, year, era, current_cal, precision) {
// console.log("open_daysel_popup: year is " + year.toString() + ", era is " + era.toString());
if (era === "BCE" || era === "BC") {
year = -year;
}
var p = daysel.offset(); // relative to browser window
var tmpcss = {
position: 'fixed',
left: p.left + daysel.width(),
top: p.top,
'z-index': 2 /* :( i don't like black magic numbers or const */
};
if (day_popoup_is_open) {
return;
}
var __daysel = $('<div>').addClass('daysel').css(tmpcss);
$('<div>').css({'text-align': 'center', 'font-style': 'italic', 'font-weight': 'bold', 'font-size': 'large'}).text(months_long[current_cal][month]).appendTo(__daysel);
var daytab = $('<table>').appendTo(__daysel);
var line = $('<tr>').appendTo(daytab);
for (var i = 0; i < 7; i++) {
$('<th>').text(weekday[i]).appendTo(line);
}
var data2 = SALSAH.daycnt(current_cal, year, month);
var i, cnt, td_ele;
line = $('<tr>').appendTo(daytab);
for (cnt = 0; cnt < data2.weekday_first; cnt++) {
$('<td>').text(' ').appendTo(line);
}
for (i = 1; i <= data2.days; i++) {
if ((cnt % 7) == 0) {
line = $('<tr>').appendTo(daytab);
}
td_ele = $('<td>').text(i).data('day', i).on('click', function(e) {
e.stopPropagation();
daysel.val($(this).data('day'));
__daysel.remove();
$(document).off('click.daysel');
day_popoup_is_open = false;
}).appendTo(line);
if ((i == daysel.val()) && (precision == 'DAY')) {
td_ele.addClass('highlight');
}
cnt++;
}
line = $('<tr>').appendTo(daytab);
td_ele = $('<td>', {colspan: 7}).text(cal_strings._not_stated).on('click', function(e) {
e.stopPropagation();
daysel.val('-');
__daysel.remove();
$(document).off('click.daysel');
day_popoup_is_open = false;
}).appendTo(line);
if ((daysel.val() == '-') || (precision != 'DAY')) {
td_ele.addClass('highlight');
}
$(document).on('click.daysel', function() {
__daysel.remove();
$(document).off('click.daysel');
day_popoup_is_open = false;
});
day_popoup_is_open = true;
return __daysel;
}
var create_date_entry = function (ele, jdc, current_cal, precision, no_day, no_month) {
var postdata = {
func: 'jdc2date',
jdc: jdc,
cal: current_cal
};
var tmparr;
var day, month, year, era;
switch (current_cal) {
case 'GREGORIAN':
case 'gregorian': {
tmparr = SALSAH.jd_to_gregorian(jdc);
year = tmparr[0];
month = tmparr[1];
day = tmparr[2];
break;
}
case 'JULIAN':
case 'julian': {
tmparr = SALSAH.jd_to_julian(jdc);
year = tmparr[0];
month = tmparr[1];
day = tmparr[2];
break;
}
case 'JEWISH':
case 'jewish': {
tmparr = SALSAH.jd_to_hebrew(jdc);
year = tmparr[0];
month = tmparr[1];
day = tmparr[2];
break;
}
case 'FRENCH':
case 'french': {
//list($m, $d, $y) = explode('/', jdtofrench($jdc));
break;
}
}
if (year < 0) {
era = "BCE";
} else {
era = "CE";
}
year = Math.abs(year);
// console.log("year is " + year.toString() + ", era is " + era.toString());
var daysel, monthsel, yearsel, erasel;
var dayval;
//
// selection for day
//
if (precision != 'DAY') {
dayval = '-';
}
else {
dayval = day > 0 ? day : '-';
}
var dayselattr = {type: 'text', size: 1, maxlength: 1, readonly: true};
if (precision == 'YEAR') {
dayselattr.disabled = true;
}
daysel = $('<input>').attr(dayselattr).addClass('propedit').addClass('daysel').on('click.dayselin', function(e){
e.stopPropagation();
ele.append(open_daysel_popup(daysel, monthsel.val(), yearsel.val(), erasel.val(), current_cal, precision));
}).val(dayval).appendTo(ele);
if ((no_day !== undefined) && no_day) {
daysel.css('display', 'none');
}
//
// pulldown for month
//
monthsel = $('<select>', {'class': 'propedit monthsel'}).change(function(event) {
//
// month changed...
//
month = event.target.value;
if (month == 0) {
daysel.val('-').attr({disabled: 'disabled'});
}
else {
var actual_day = daysel.val(); // save current day for use below...
daysel.empty();
daysel.removeAttr('disabled');
if (precision != 'DAY') {
$('<option>').attr({selected: 'selected'}).append('-').appendTo(daysel);
}
else {
$('<option>').append('-').appendTo(daysel);
}
var data2 = SALSAH.daycnt(current_cal, year, month);
if (actual_day > data2.days) actual_day = data2.days;
for (var i = 1; i <= data2.days; i++) {
var attributes = {Class: 'propedit'};
if ((precision == 'DAY') && (i == actual_day)) {
attributes.selected = 'selected';
}
attributes.value = i;
$('<option>', attributes).append(i).appendTo(daysel);
}
}
});
var monthattr = {'class': 'propedit monthsel', value: 0};
if (precision != 'MONTH') {
monthattr.selected = 'selected';
}
$('<option>', monthattr).append('-').appendTo(monthsel);
for (var i = 1; i <= SALSAH.calendars[current_cal].n_months; i++) {
var attributes = {Class: 'propedit monthsel'};
if ((i == month) && ((precision == 'MONTH') || (precision == 'DAY'))) {
attributes.selected = 'selected';
}
attributes.value = i;
$('<option>', attributes).append(months[current_cal][i]).appendTo(monthsel);
}
ele.append(monthsel);
//
// textfield for year
//
yearsel = $('<input>', {type: 'text', 'class': 'propedit yearsel', value: year, size: '4', maxlength: '4'}).appendTo(ele);
ele.append($('<span>').attr({title: cal_strings._change_year})
.append($('<img>', {src: spin_up.src}).css({'vertical-align': 'middle', cursor: 'pointer'}).attr({title: 'click: +1\nshift+click: +10\nshift+alt+click: +100'}).click(function(event){
if (event.shiftKey && event.altKey){
yearsel.val(parseInt(yearsel.val()) + 100);
}
else if (event.shiftKey) {
yearsel.val(parseInt(yearsel.val()) + 10);
}
else {
yearsel.val(parseInt(yearsel.val()) + 1);
}
}))
.append($('<img>', {src: spin_down.src}).css({'vertical-align': 'middle', cursor: 'pointer'}).attr({title: 'click: -1\nshift+click: -10\nshift+alt+click: -100'}).click(function(event){
if (event.shiftKey && event.altKey){
yearsel.val(parseInt(yearsel.val()) - 100);
}
else if (event.shiftKey) {
yearsel.val(parseInt(yearsel.val()) - 10);
}
else {
yearsel.val(parseInt(yearsel.val()) - 1);
}
}))
);
erasel = $('<select>', {'class': 'propedit erasel'});
var ceOption = $('<option>').append('CE');
var bceOption = $('<option>').append('BCE');
if (era === "BCE") {
bceOption.attr({selected: 'selected'});
} else {
ceOption.attr({selected: 'selected'});
}
ceOption.appendTo(erasel);
bceOption.appendTo(erasel);
ele.append(erasel);
};
var parse_datestr = function(datestr, calendar, era, periodpart) {
var d = {};
var dd;
var d_arr = datestr.split('-');
var year_sign = 1;
if (era === "BC" || era === "BCE") {
year_sign = -1;
}
if (d_arr.length == 3) {
d.precision = 'DAY';
d.jdc = SALSAH.date_to_jdc(d_arr[2], d_arr[1], d_arr[0] * year_sign, calendar, periodpart);
}
else if (d_arr.length == 2) {
d.precision = 'MONTH';
d.jdc = SALSAH.date_to_jdc(0, d_arr[1], d_arr[0] * year_sign, calendar, periodpart);
}
else if (d_arr.length == 1) {
d.precision = 'YEAR';
d.jdc = SALSAH.date_to_jdc(0, 0, d_arr[0] * year_sign, calendar, periodpart);
}
else {
alert('ERROR: Invalid datestr: ' + datestr);
}
dd = SALSAH.jdc_to_date(d.jdc, calendar);
d.year = dd.year;
d.month = dd.month;
d.day = dd.day;
d.weekday = dd.weekday;
d.calendar = calendar;
// console.log("in parse_datestr: datestr is " + datestr.toString() + ", era is " + era + ", and d is " + JSON.stringify(d));
return d;
};
/**
* Dateobject:
* - <i>name</i>.dateval1 (YYYY-MM-DD)
* - <i>name</i>.dateval2 (YYYY-MM-DD)
* - <i>name</i>.calendar ("GREGORIAN", "JULIAN", "JEWISH", "FRENCH")
*/
var methods = {
init: function (dateobj) {
var $that = this;
var d1;
var d2;
var d1_abs_year, d2_abs_year;
var d1_era, d2_era;
var d1_year_str, d2_year_str;
d1 = parse_datestr(dateobj.dateval1, dateobj.calendar, dateobj.era1, 'START');
d2 = parse_datestr(dateobj.dateval2, dateobj.calendar, dateobj.era2, 'END');
if (d1.year < 0) {
d1_era = "BCE";
} else {
d1_era = "CE";
}
if (d2.year < 0) {
d2_era = "BCE";
} else {
d2_era = "CE";
}
d1_abs_year = Math.abs(d1.year);
d2_abs_year = Math.abs(d2.year);
d1_year_str = d1_abs_year + ' ' + d1_era;
d2_year_str = d2_abs_year + ' ' + d2_era;
var datestr = '';
if (d1.precision == d2.precision) {
//
// same precisions for start- and end-date
//
switch (d1.precision) {
case 'DAY': {
if ((d1.year == d2.year) && (d1.month == d2.month) && (d1.day == d2.day)) {
datestr = weekday[d1.weekday] + ' ' + d1.day + '. ' + months[dateobj.calendar][d1.month] + ' ' + d1_year_str;
}
else {
datestr = weekday[d1.weekday] + ' ' + d1.day + '. ' + months[dateobj.calendar][d1.month] + ' ' + d1_year_str + ' - ' + weekday[d2.weekday] + ' ' + d2.day + '. ' + months[dateobj.calendar][d2.month] + ' ' + d2_year_str;
}
break;
}
case 'MONTH': {
if ((d1.year == d2.year) && (d1.month == d2.month)) {
datestr = months[dateobj.calendar][d1.month] + ' ' + d1_year_str;
}
else {
datestr = months[dateobj.calendar][d1.month] + ' ' + d1.year + ' - ' + months[dateobj.calendar][d2.month] + ' ' + d2_year_str;
}
break;
}
case 'YEAR': {
if (d1.year == d2.year) {
datestr = d1_year_str;
}
else {
datestr = d1.year + ' - ' + d2_year_str;
}
break;
}
} // switch(precision1)
}
else {
//
// different precisions for start- and end-date
//
switch (d1.precision) {
case 'DAY': {
datestr = weekday[d1.weekday] + ' ' + d1.day + '. ' + months[dateobj.calendar][d1.month] + ' ' + d1_year_str;
break;
}
case 'MONTH': {
datestr = months[dateobj.calendar][d1.month] + ' ' + d1_year_str;
break;
}
case 'YEAR': {
datestr = d1_year_str;
break;
}
} // switch(propinfo.values[value_index].precision1)
datestr += ' - ';
switch (d2.precision) {
case 'DAY': {
datestr += weekday[d2.weekday] + ' ' + d2.day + '. ' + months[dateobj.calendar][d2.month] + ' ' + d2_year_str;
break;
}
case 'MONTH': {
datestr += months[dateobj.calendar][d2.month] + ' ' + d2_year_str;
break;
}
case 'YEAR': {
datestr += d2_year_str;
break;
}
} // switch(precision2)
}
datestr += ' (' + SALSAH.calendars[d1.calendar].name + ')';
return this.each(function() {
$(this).append(datestr);
});
},
/*
* defvals: {
* current_cal: 'GREGORIAN' | 'JULIAN',
* date1: {
* day: <int>,
* month: <int>,
* year: <int>
* }
* date2: {
* day: <int>,
* month: <int>,
* year: <int>
* }
* no_calsel: true | false,
* no_day: true | false
* }
*/
edit: function(dateobj, defvals) {
var period = false;
var d1 = {};
var d2 = {};
if (dateobj === undefined) {
var jsdateobj = new Date();
if (defvals === undefined) {
d1.calendar = 'GREGORIAN';
d1.day = jsdateobj.getDate();
d1.month = jsdateobj.getMonth() + 1;
d1.year = jsdateobj.getFullYear();
d1.precision = 'DAY';
d2 = $.extend({}, d1);
}
else {
d1.calendar = (defvals.current_cal === undefined) ? 'GREGORIAN' : defvals.current_cal;
if (defvals.date1 === undefined) {
d1.day = jsdateobj.getDate();
d1.month = jsdateobj.getMonth() + 1;
d1.year = jsdateobj.getFullYear();
}
else {
d1.day = defvals.date1.day === undefined ? jsdateobj.getDate() : defvals.date1.day;
d1.month = defvals.date1.month === undefined ? jsdateobj.getMonth() + 1 : defvals.date1.month;
d1.year = defvals.date1.year === undefined ? jsdateobj.getFullYear() : defvals.date1.year;
}
if (defvals.date2 === undefined) {
d2 = $.extend({}, d1);
}
else {
d2.day = defvals.date2.day === undefined ? jsdateobj.getDate() : defvals.date2.day;
d2.month = defvals.date2.month === undefined ? jsdateobj.getMonth() + 1 : defvals.date2.month;
d2.year = defvals.date2.year === undefined ? jsdateobj.getFullYear() : defvals.date2.year;
d2.calendar = d1.calendar;
}
d1.precision = defvals.dateprecision1 === undefined ? 'DAY' : defvals.dateprecision1;
d2.precision = defvals.dateprecision2 === undefined ? 'DAY' : defvals.dateprecision2;
}
d1.jdc = SALSAH.date_to_jdc(d1.day, d1.month, d1.year, d1.calendar, 'START');
d2.jdc = SALSAH.date_to_jdc(d2.day, d2.month, d2.year, d2.calendar, 'END');
}
else {
var current_cal = dateobj.calendar;
if (dateobj.dateprecision1 !== undefined) {
alert('OLD DATE FORMAT!!!')
d1.jdc = dateobj.dateval1;
d2.jdc = dateobj.dateval2;
var date1 = SALSAH.jdc_to_date(dateval1, current_cal);
var date2 = SALSAH.jdc_to_date(dateval2, current_cal);
var dateprecision1 = dateobj.dateprecision1;
var dateprecision2 = dateobj.dateprecision2;
}
else {
d1 = parse_datestr(dateobj.dateval1, dateobj.calendar, dateobj.era1, 'START');
d2 = parse_datestr(dateobj.dateval2, dateobj.calendar, dateobj.era2, 'END');
}
}
var datecontainer1 = $('<span>').appendTo(this);
var datecontainer2 = $('<span>').appendTo(this);
if (d1.precision == d2.precision) {
switch (d1.precision) {
case 'DAY': {
if ((d1.day != d2.day) || (d1.month != d2.month) || (d1.year != d2.year)) period = true;
break;
}
case 'MONTH': {
if ((d1.month != d2.month) || (d1.year != d2.year)) period = true;
break;
}
case 'YEAR': {
if (d1.year != d2.year) period = true;
break;
}
default: {
period = true;
}
}
}
else {
period = true; // different date precisions imply a period!
}
var no_day = false;
if ((defvals !== undefined) && (defvals.no_day !== undefined)) no_day = defvals.no_day
create_date_entry(datecontainer1, d1.jdc, d1.calendar, d1.precision, no_day);
if (period) {
datecontainer2.append(' – ');
create_date_entry(datecontainer2, d2.jdc, d2.calendar, d2.precision, no_day);
}
//
// period...
//
var periodattr = {
'class': 'propedit periodsel',
type: 'checkbox'
};
if (period) periodattr.checked = 'checked';
this.append(' ' + cal_strings._period + ':');
var periodsel = $('<input>', periodattr).click(function(event) {
if (event.target.checked) {
datecontainer2.append(' - ');
create_date_entry(datecontainer2, d2.jdc, d2.calendar, d2.precision);
period = true;
}
else {
datecontainer2.empty();
period = false;
}
}).appendTo(this);
this.append(' ');
//
// calendar selection
//
var calsel = $('<select>', {'class': 'propedit calsel'}).change(function(event) {
//
// calendar selection changed...
//
//
// first dave the actual date into a calendar independant JDC
//
var day1 = datecontainer1.find('.daysel').val();
var month1 = datecontainer1.find('.monthsel').val();
var year1 = datecontainer1.find('.yearsel').val();
if ((day1 == '-') && (month1 == 0)) {
d1.precision = 'YEAR';
day1 = 0;
}
else if (day1 == '-') {
d1.precision = 'MONTH';
day1 = 0;
}
else {
d1.precision = 'DAY';
}
d1.jdc = SALSAH.date_to_jdc(day1, month1, year1, d1.calendar, 'START');
if (period) {
var day2 = datecontainer2.find('.daysel').val();
var month2 = datecontainer2.find('.monthsel').val();
var year2 = datecontainer2.find('.yearsel').val();
if ((day2 == '-') && (month2 == 0)) {
d2.precision = 'YEAR';
day2 = 0;
}
else if (day2 == '-') {
d2.precision = 'MONTH';
day2 = 0;
}
else {
d2.precision = 'DAY';
}
d2.jdc = SALSAH.date_to_jdc(day2, month2, year2, d2.calendar, 'END');
}
d1.calendar = event.target.value; // get new calendar value
d2.calendar = event.target.value; // get new calendar value
datecontainer1.empty();
create_date_entry(datecontainer1, d1.jdc, d1.calendar, d1.precision);
if (period) {
datecontainer2.empty();
datecontainer2.append(' - ');
create_date_entry(datecontainer2, d2.jdc, d2.calendar, d2.precision);
}
}).appendTo(this);
for (var i in SALSAH.calendars) {
if (i == 'FRENCH') continue; // no french revolutionary at the moment!
if (i == 'JEWISH') continue; // no hebrew at the moment!
var attributes = {Class: 'propedit'};
if (i == d1.calendar) {
attributes.selected = 'selected';
}
attributes.value = i;
$('<option>', attributes).append(SALSAH.calendars[i].name).appendTo(calsel); // !!!!!!!!!!!!!!!!!!!!!!!!!!
}
if ((defvals !== undefined) && (defvals.no_calsel !== undefined) && defvals.no_calsel) {
calsel.css('display', 'none');
}
return $(this);
},
value: function() {
var dateobj = {};
var datecontainer1 = $(this.children('span').get(0));
var datecontainer2 = $(this.children('span').get(1));
var period = this.find('.periodsel').prop('checked'); // attr() -> prop()
dateobj.calendar = this.find('.calsel').val();
dateobj.dateval1 = '';
var year1 = datecontainer1.find('.yearsel').val();
if (isNaN(year1) || (year1 == 0)) {
alert('Date with invalid year! Assumed year 1');
year1 = 1;
}
dateobj.dateval1 += year1;
var month1 = datecontainer1.find('.monthsel').val();
if (month1 > 0) {
dateobj.dateval1 += '-' + month1;
var day1 = datecontainer1.find('.daysel').val();
if ((day1 != '-') && (day1 > 0)) {
dateobj.dateval1 += '-' + day1;
}
}
dateobj.era1 = datecontainer1.find('.erasel').val();
if (period) {
dateobj.dateval2 = '';
var year2 = datecontainer2.find('.yearsel').val();
if (isNaN(year2) || (year2 == 0)) {
alert('Period with invalid year! Assumed year ' + year1);
year2 = year1;
}
dateobj.dateval2 += year2;
var month2 = datecontainer2.find('.monthsel').val();
if (month2 > 0) {
dateobj.dateval2 += '-' + month2;
var day2 = datecontainer2.find('.daysel').val();
if ((day2 != '-') && (day2 > 0)) {
dateobj.dateval2 += '-' + day2;
}
}
dateobj.era2 = datecontainer2.find('.erasel').val();
}
// console.log("in function value: dateobj is " + JSON.stringify(dateobj));
return dateobj;
},
}
$.fn.dateobj = function(method) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
throw 'Method ' + method + ' does not exist on jQuery.tooltip';
}
};
})( jQuery );
| musicEnfanthen/Knora | salsah1/src/public/js/jquery.dateobj.js | JavaScript | agpl-3.0 | 24,825 |
<?php
/*
* Copyright 2004-2015, AfterLogic Corp.
* Licensed under AGPLv3 license or AfterLogic license
* if commercial version of the product was purchased.
* See the LICENSE file for a full license statement.
*/
namespace afterlogic\DAV\Auth;
class Backend
{
protected static $instance;
public static function getInstance()
{
if(null === self::$instance)
{
self::$instance = (\CApi::GetConf('labs.dav.use-digest-auth', false)) ? new Backend\Digest() : new Backend\Basic();
}
return self::$instance;
}
} | Git-Host/email | libraries/afterlogic/DAV/Auth/Backend.php | PHP | agpl-3.0 | 558 |
import React from 'react';
import InputSelectImage from '../../../src/js/components/RegisterFields/InputSelectImage/InputSelectImage.js';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
describe('Test InputSelectImage component', () => {
const mockFn = jest.fn();
const options = [
{
id: "lorem",
text: "Lorem",
image: "http://via.placeholder.com/300x300"
},
{
id: "ipsum",
text: "Ipsum",
image: "http://via.placeholder.com/300x300"
},
{
id: "lorem-ipsum",
text: "Lorem ipsum",
image: "http://via.placeholder.com/300x300"
},
{
id: "sed-ut-perspiciatis",
text: "Sed ut perspiciatis",
image: "http://via.placeholder.com/300x300"
},
{
id: "perspiciatis",
text: "perspiciatis",
image: "http://via.placeholder.com/300x300"
},
];
const inputSelectImage = shallow(<InputSelectImage options={options} placeholder={"Foo"} onClickHandler={mockFn}/>);
it('should be defined', () => {
expect(inputSelectImage).toBeDefined();
});
it('should render correctly', () => {
expect(inputSelectImage).toMatchSnapshot();
});
});
| nekuno/client | __tests__/components/RegisterFields/InputSelectImage.test.js | JavaScript | agpl-3.0 | 1,402 |
package org.opencps.api.controller.impl;
import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.Role;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.UserLocalServiceUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.Validator;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.opencps.api.constants.ConstantUtils;
import org.opencps.api.controller.OneGateController;
import org.opencps.api.controller.util.OneGateUtils;
import org.opencps.api.dossier.model.DossierDetailModel;
import org.opencps.api.dossier.model.DossierOnegateInputModel;
import org.opencps.auth.api.BackendAuth;
import org.opencps.auth.api.BackendAuthImpl;
import org.opencps.auth.api.exception.UnauthenticationException;
import org.opencps.datamgt.utils.DateTimeUtils;
import org.opencps.dossiermgt.action.DossierActions;
import org.opencps.dossiermgt.action.ServiceProcessActions;
import org.opencps.dossiermgt.action.impl.DossierActionsImpl;
import org.opencps.dossiermgt.action.impl.DossierPermission;
import org.opencps.dossiermgt.action.impl.ServiceProcessActionsImpl;
import org.opencps.dossiermgt.action.util.OpenCPSConfigUtil;
import org.opencps.dossiermgt.constants.DossierTemplateTerm;
import org.opencps.dossiermgt.constants.DossierTerm;
import org.opencps.dossiermgt.constants.ProcessOptionTerm;
import org.opencps.dossiermgt.constants.ServiceConfigTerm;
import org.opencps.dossiermgt.constants.ServiceInfoTerm;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.DossierTemplate;
import org.opencps.dossiermgt.model.ProcessAction;
import org.opencps.dossiermgt.model.ProcessOption;
import org.opencps.dossiermgt.model.ServiceConfig;
import org.opencps.dossiermgt.model.ServiceInfo;
import org.opencps.dossiermgt.model.ServiceInfoMapping;
import org.opencps.dossiermgt.model.ServiceProcess;
import org.opencps.dossiermgt.model.ServiceProcessRole;
import org.opencps.dossiermgt.service.DossierLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierTemplateLocalServiceUtil;
import org.opencps.dossiermgt.service.ProcessActionLocalServiceUtil;
import org.opencps.dossiermgt.service.ProcessOptionLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceConfigLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceInfoLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceInfoMappingLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceProcessRoleLocalServiceUtil;
import org.opencps.usermgt.model.Employee;
import org.opencps.usermgt.service.EmployeeLocalServiceUtil;
import backend.auth.api.exception.BusinessExceptionImpl;
public class OneGateControllerImpl implements OneGateController {
@Override
public Response getServiceconfigs(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
User user, ServiceContext serviceContext, String domain, String public_, Request requestCC) {
long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
BackendAuth auth = new BackendAuthImpl();
// TODO need implement user in GovAgency
try {
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
List<Role> userRoles = user.getRoles();
boolean isAdmin = false;
for (Role r : userRoles) {
if (r.getName().startsWith(ConstantUtils.ROLE_ADMIN)) {
isAdmin = true;
break;
}
}
// long startTime = System.currentTimeMillis();
List<ServiceConfig> serviceConfigs = ServiceConfigLocalServiceUtil.getByGroupId(groupId);
Map<Long, ServiceInfo> mapServiceInfos = new HashMap<>();
List<ServiceInfo> lstServiceInfos = null;
if (Validator.isNotNull(public_) && !Boolean.parseBoolean(public_)) {
lstServiceInfos = ServiceInfoLocalServiceUtil.findByGroupAndPublic(groupId,
Boolean.parseBoolean(public_));
} else {
lstServiceInfos = ServiceInfoLocalServiceUtil.findByGroupAndPublic(groupId, true);
}
if (lstServiceInfos != null && lstServiceInfos.size() > 0) {
for (ServiceInfo serviceInfo : lstServiceInfos) {
mapServiceInfos.put(serviceInfo.getServiceInfoId(), serviceInfo);
}
}
// long endTime = System.currentTimeMillis();
// startTime = System.currentTimeMillis();
JSONObject results = JSONFactoryUtil.createJSONObject();
Map<Long, List<ProcessOption>> mapProcessOptions = new HashMap<>();
// startTime = System.currentTimeMillis();
List<ProcessOption> lstOptions = ProcessOptionLocalServiceUtil.findByGroup(groupId);
// endTime = System.currentTimeMillis();
// startTime = System.currentTimeMillis();
long[] spArr = new long[lstOptions.size()];
int count = 0;
Employee e = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, user.getUserId());
for (ProcessOption po : lstOptions) {
if (mapProcessOptions.get(po.getServiceConfigId()) == null) {
List<ProcessOption> lstPos = new ArrayList<>();
mapProcessOptions.put(po.getServiceConfigId(), lstPos);
lstPos.add(po);
}
else {
List<ProcessOption> lstPos = mapProcessOptions.get(po.getServiceConfigId());
lstPos.add(po);
}
spArr[count++] = po.getServiceProcessId();
}
// endTime = System.currentTimeMillis();
// startTime = System.currentTimeMillis();
JSONArray data = JSONFactoryUtil.createJSONArray();
int total = 0;
long[] roleIds = UserLocalServiceUtil.getRolePrimaryKeys(user.getUserId());
// List<ServiceProcessRole> lstPRoles = ServiceProcessRoleLocalServiceUtil.getServiceProcessRoles(QueryUtil.ALL_POS, QueryUtil.ALL_POS);
List<ServiceProcessRole> lstPRoles = (spArr != null && spArr.length > 0) ? ServiceProcessRoleLocalServiceUtil.findBySPS(spArr) : new ArrayList<ServiceProcessRole>();
Map<Long, List<ServiceProcessRole>> mapPRoles = new HashMap<Long, List<ServiceProcessRole>>();
for (ServiceProcessRole spr : lstPRoles) {
List<ServiceProcessRole> lstTempSprs = new ArrayList<ServiceProcessRole>();
if (mapPRoles.containsKey(spr.getServiceProcessId())) {
lstTempSprs = mapPRoles.get(spr.getServiceProcessId());
}
else {
mapPRoles.put(spr.getServiceProcessId(), lstTempSprs);
}
lstTempSprs.add(spr);
}
// endTime = System.currentTimeMillis();
// startTime = System.currentTimeMillis();
List<DossierTemplate> lstTemplates = DossierTemplateLocalServiceUtil.findByG(groupId);
Map<Long, DossierTemplate> mapTemplates = new HashMap<Long, DossierTemplate>();
for (DossierTemplate dt : lstTemplates) {
mapTemplates.put(dt.getDossierTemplateId(), dt);
}
// endTime = System.currentTimeMillis();
for (ServiceConfig serviceConfig : serviceConfigs) {
// if (((e != null && (Validator.isNull(e.getScope()))) || (e != null && Validator.isNotNull(e.getScope()) && serviceConfig.getGovAgencyCode().contentEquals(e.getScope())))) {
// _log.debug("SERVICE CONFIG SCOPE: " + e.getScope());
// _log.debug("SERVICE CONFIG LEVEL: " + serviceConfig.getServiceLevel());
// }
if (serviceConfig.getServiceLevel() >= 2 && ((e != null && (Validator.isNull(e.getScope()))) || (e != null && Validator.isNotNull(e.getScope()) && e.getScope().indexOf(serviceConfig.getGovAgencyCode()) >= 0))) {
JSONObject elmData = JSONFactoryUtil.createJSONObject();
elmData.put(ServiceConfigTerm.SERVICECONFIG_ID, serviceConfig.getServiceConfigId());
//Hot fix
ServiceInfo serviceInfo = null;
ServiceInfoMapping serviceInfoMapping = null;
if (mapServiceInfos.containsKey(serviceConfig.getServiceInfoId())) {
serviceInfo = mapServiceInfos.get(serviceConfig.getServiceInfoId());
if (Validator.isNull(domain) || serviceInfo.getDomainCode().equals(domain)) {
// try {
// serviceInfo = ServiceInfoLocalServiceUtil.getServiceInfo(serviceConfig.getServiceInfoId());
// } catch (Exception e1) {
// _log.debug(e1);
// break;
// }
serviceInfoMapping = ServiceInfoMappingLocalServiceUtil.fetchDVCQGServiceCode(groupId, serviceInfo.getServiceCode());
elmData.put(ServiceInfoTerm.SERVICE_CODE, serviceInfo.getServiceCode());
elmData.put(ServiceInfoTerm.SERVICE_NAME, serviceInfo.getServiceName());
elmData.put(ServiceInfoTerm.SERVICE_CODE_DVCQG, serviceInfoMapping != null ? serviceInfoMapping.getServiceCodeDVCQG() : StringPool.BLANK);
elmData.put(ServiceInfoTerm.SERVICE_NAME_DVCQG, serviceInfoMapping != null ? serviceInfoMapping.getServiceNameDVCQG() : StringPool.BLANK);
elmData.put(ServiceConfigTerm.GOVAGENCY_CODE, serviceConfig.getGovAgencyCode());
elmData.put(ServiceConfigTerm.GOVAGENCY_NAME, serviceConfig.getGovAgencyName());
// List<ProcessOption> processOptions = ProcessOptionLocalServiceUtil
// .getByServiceProcessId(serviceConfig.getServiceConfigId());
List<ProcessOption> processOptions = mapProcessOptions.get(serviceConfig.getServiceConfigId()) != null ? mapProcessOptions.get(serviceConfig.getServiceConfigId())
: new ArrayList<>();
JSONArray options = JSONFactoryUtil.createJSONArray();
for (ProcessOption processOption : processOptions) {
// _log.info("processOptionId"+ processOption.getDossierTemplateId());
long serviceProcessId = processOption.getServiceProcessId();
// List<ServiceProcessRole> lstRoles = ServiceProcessRoleLocalServiceUtil.findByS_P_ID(serviceProcessId);
List<ServiceProcessRole> lstRoles = mapPRoles.get(serviceProcessId);
boolean hasPermission = false;
// _log.info("List role: " + lstRoles);
if (lstRoles != null && lstRoles.size() > 0) {
// _log.info("Role of users : " + user);
for (ServiceProcessRole spr : lstRoles) {
for (int i = 0; i < roleIds.length; i++) {
if (roleIds[i] == spr.getRoleId()) {
hasPermission = true;
break;
}
}
if (hasPermission) break;
}
}
if (isAdmin) {
hasPermission = true;
}
if (e != null) {
if (Validator.isNotNull(e.getScope()) && Arrays.asList(e.getScope().split(StringPool.COMMA)).indexOf(serviceConfig.getGovAgencyCode()) < 0) {
hasPermission = false;
}
}
// if (((e != null && Validator.isNotNull(e.getScope()) && serviceConfig.getGovAgencyCode().contentEquals(e.getScope())))) {
// hasPermission = true;
// }
if (hasPermission) {
JSONObject elmOption = JSONFactoryUtil.createJSONObject();
elmOption.put(ProcessOptionTerm.PROCESSOPTION_ID, processOption.getProcessOptionId());
elmOption.put(ProcessOptionTerm.OPTION_NAME, processOption.getOptionName());
elmOption.put(ProcessOptionTerm.INSTRUCTION_NOTE, processOption.getInstructionNote());
// try {
// DossierTemplate dossierTemplate = DossierTemplateLocalServiceUtil.getDossierTemplate(processOption.getDossierTemplateId());
DossierTemplate dossierTemplate = mapTemplates.get(processOption.getDossierTemplateId());
if (dossierTemplate != null) {
elmOption.put(DossierTemplateTerm.TEMPLATE_NO, dossierTemplate.getTemplateNo());
elmOption.put(DossierTemplateTerm.TEMPLATE_NAME, dossierTemplate.getTemplateName());
}
// }
// catch (NoSuchDossierTemplateException e) {
// _log.error(e);
// }
options.put(elmOption);
}
if (options.length() > 0) {
elmData.put(ProcessOptionTerm.OPTIONS, options);
}
}
if (elmData.has(ProcessOptionTerm.OPTIONS)) {
total++;
data.put(elmData);
}
}
}
}
}
results.put(ConstantUtils.TOTAL, total);
results.put(ConstantUtils.DATA, data);
// _log.info(results.toJSONString());
EntityTag etag = new EntityTag(Integer.toString((groupId + domain).hashCode()));
ResponseBuilder builder = requestCC.evaluatePreconditions(etag);
if (OpenCPSConfigUtil.isHttpCacheEnable() && builder == null) {
builder = Response.status(HttpURLConnection.HTTP_OK);
CacheControl cc = new CacheControl();
cc.setMaxAge(OpenCPSConfigUtil.getHttpCacheMaxAge());
cc.setPrivate(true);
builder.tag(etag);
return builder.status(HttpURLConnection.HTTP_OK).entity(results.toJSONString()).build();
}
else {
return Response.status(HttpURLConnection.HTTP_OK).entity(results.toJSONString()).build();
}
} catch (Exception e) {
return BusinessExceptionImpl.processException(e);
}
}
@Override
public Response createDossierOngate(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
User user, ServiceContext serviceContext, DossierOnegateInputModel input) {
long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
BackendAuth auth = new BackendAuthImpl();
// backend.auth.api.BackendAuth auth2 = new backend.auth.api.BackendAuthImpl();
DossierPermission dossierPermission = new DossierPermission();
DossierActions actions = new DossierActionsImpl();
_log.info("__INPUT_ONEGATE");
_log.info(JSONFactoryUtil.looseSerialize(input));
_log.info("__XXXXXXXXXXXXX");
try {
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
// if (!auth2.checkToken(request, header)) {
// throw new UnauthenticationException();
// }
dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(),
input.getGovAgencyCode(), input.getDossierTemplateNo());
Dossier dossier = actions.createDossier(groupId, input.getServiceCode(), input.getGovAgencyCode(),
input.getApplicantName(), input.getApplicantIdType(), input.getApplicantIdNo(),
DateTimeUtils.convertDateTimeToString(input.getApplicantIdDate()), input.getAddress(),
input.getCityCode(), input.getDistrictCode(), input.getWardCode(), input.getContactName(),
input.getContactTelNo(), input.getContactEmail(), input.isSameAsApplicant(),
input.getDelegateName(), input.getDelegateIdNo(), input.getDelegateTelNo(),
input.getDelegateEmail(), input.getDelegateAddress(), input.getDelegateCityCode(),
input.getDelegateDistrictCode(), input.getDelegateWardCode(), input.getApplicantNote(),
StringPool.BLANK, input.getDossierNo(), input.getDossierTemplateNo(), input.getViaPostal(),
input.getPostalServiceCode(), input.getPostalServiceName(), input.getPostalAddress(),
input.getPostalCityCode(), input.getPostalDistrictCode(), input.getPostalWardCode(),
input.getPostalTelNo(), DossierTerm.ORIGINALITY_MOTCUA, serviceContext);
DossierDetailModel result = null;
if (dossier != null ) {
result = OneGateUtils.mappingForGetDetail(dossier);
}
return Response.status(HttpURLConnection.HTTP_OK).entity(result).build();
} catch (Exception e) {
return BusinessExceptionImpl.processException(e);
}
}
private Log _log = LogFactoryUtil.getLog(OneGateControllerImpl.class);
@Override
public Response updateDossierOngate(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
User user, ServiceContext serviceContext, DossierOnegateInputModel input, long dossierId) {
//long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
BackendAuth auth = new BackendAuthImpl();
//DossierPermission dossierPermission = new DossierPermission();
long dActionId = GetterUtil.getLong(input.getDossierActionId());
_log.info("__INPUT_ONEGATE_UPDATE");
_log.info(JSONFactoryUtil.looseSerialize(input));
_log.info("__XXXXXXXXXXXXX_UPDATE");
try {
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = DossierLocalServiceUtil.updateDossierOneGate(dossierId, input.getApplicantName(),
input.getApplicantIdType(), input.getApplicantIdNo(),
DateTimeUtils.convertDateTimeToString(input.getApplicantIdDate()), input.getAddress(),
input.getCityCode(), input.getDistrictCode(), input.getWardCode(), input.getContactName(),
input.getContactTelNo(), input.getContactEmail(), input.isSameAsApplicant(),
input.getDelegateName(), input.getDelegateIdNo(), input.getDelegateTelNo(),
input.getDelegateEmail(), input.getDelegateAddress(), input.getDelegateCityCode(),
input.getDelegateDistrictCode(), input.getDelegateWardCode(), input.getApplicantNote(),
StringPool.BLANK, input.getDossierNo(), input.getViaPostal(), input.getPostalServiceCode(),
input.getPostalServiceName(), input.getPostalAddress(), input.getPostalCityCode(),
input.getPostalDistrictCode(), input.getPostalWardCode(), input.getPostalTelNo(), dActionId,
input.getPaymentFee(), input.getPaymentFeeNote(), serviceContext);
DossierDetailModel result = null;
if (dossier != null ) {
result = OneGateUtils.mappingForGetDetail(dossier);
}
return Response.status(HttpURLConnection.HTTP_OK).entity(result).build();
} catch (Exception e) {
return BusinessExceptionImpl.processException(e);
}
}
@Override
public Response getDossierOngate(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
User user, ServiceContext serviceContext, long dossierId) {
//long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
BackendAuth auth = new BackendAuthImpl();
//DossierPermission dossierPermission = new DossierPermission();
try {
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
Dossier dossier = DossierLocalServiceUtil.fetchDossier(dossierId);
DossierDetailModel result = null;
if (dossier != null ) {
result = OneGateUtils.mappingForGetDetail(dossier);
}
return Response.status(HttpURLConnection.HTTP_OK).entity(result).build();
// return Response.status(HttpURLConnection.HTTP_OK).entity(JSONFactoryUtil.looseSerialize(dossier)).build();
} catch (Exception e) {
return BusinessExceptionImpl.processException(e);
}
}
@Override
public Response getServiceProcess(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
User user, ServiceContext serviceContext, long dossierId, String serviceCode, String govAgencyCode,
String dossierTemplateNo, String dossierActionId) {
long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
// long dActionId = GetterUtil.getLong(dossierActionId);
ServiceProcessActions actions = new ServiceProcessActionsImpl();
BackendAuth auth = new BackendAuthImpl();
try {
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
JSONObject results = JSONFactoryUtil.createJSONObject();
ServiceProcess serviceProcess = actions.getServiceProcessByCode(groupId, serviceCode, govAgencyCode,
dossierTemplateNo);
if (serviceProcess != null) {
results.put(ConstantUtils.ONEGATE_PAYMENTFEEREQUEST, serviceProcess.getPaymentFee());
ProcessAction process = ProcessActionLocalServiceUtil
.getByServiceProcess(serviceProcess.getServiceProcessId(), String.valueOf(10000));
if (process != null) {
results.put(ConstantUtils.ONEGATE_PAYMENTFEETOTAL, process.getPaymentFee());
} else {
results.put(ConstantUtils.ONEGATE_PAYMENTFEETOTAL, 0);
}
} else {
results.put(ConstantUtils.ONEGATE_PAYMENTFEEREQUEST, 0);
results.put(ConstantUtils.ONEGATE_PAYMENTFEETOTAL, 0);
}
// if (dActionId > 0) {
// DossierAction dAction = DossierActionLocalServiceUtil.fetchDossierAction(dActionId);
// ProcessAction process = ProcessActionLocalServiceUtil.getByServiceProcess(dAction.getServiceProcessId(), dAction.getActionCode());
// results.put("paymentFeeTotal", process.getPaymentFee());
// } else
// if (serviceProcess != null) {
// ProcessAction process = ProcessActionLocalServiceUtil
// .getByServiceProcess(serviceProcess.getServiceProcessId(), String.valueOf(10000));
// if (process != null) {
// results.put("paymentFeeTotal", process.getPaymentFee());
// } else {
// results.put("paymentFeeTotal", 0);
// }
// } else {
// results.put("paymentFeeTotal", 0);
// }
return Response.status(HttpURLConnection.HTTP_OK).entity(JSONFactoryUtil.looseSerialize(results)).build();
} catch (Exception e) {
return BusinessExceptionImpl.processException(e);
}
}
@Override
public Response getGovAgencies(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
User user, ServiceContext serviceContext) {
long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
try {
List<ServiceConfig> lstConfigs = ServiceConfigLocalServiceUtil.getByGroupId(groupId);
Map<String, String> mapConfigs = new HashMap<String, String>();
Map<String, Set<Long>> mapSis = new HashMap<String, Set<Long>>();
for (ServiceConfig sc : lstConfigs) {
mapConfigs.put(sc.getGovAgencyCode(), sc.getGovAgencyName());
Set<Long> sInfos = new HashSet<Long>();
if (mapSis.containsKey(sc.getGovAgencyCode())) {
sInfos = mapSis.get(sc.getGovAgencyCode());
}
else {
mapSis.put(sc.getGovAgencyCode(), sInfos);
}
if (!sInfos.contains(sc.getServiceInfoId())) {
sInfos.add(sc.getServiceInfoId());
}
}
Map<String, Integer> countConfigs = new HashMap<String, Integer>();
for (ServiceConfig sc : lstConfigs) {
if (mapSis.containsKey(sc.getGovAgencyCode())) {
countConfigs.put(sc.getGovAgencyCode(), mapSis.get(sc.getGovAgencyCode()).size());
}
}
JSONObject result = JSONFactoryUtil.createJSONObject();
int total = 0;
JSONArray results = JSONFactoryUtil.createJSONArray();
for (String govAgencyCode : mapConfigs.keySet()) {
JSONObject govObj = JSONFactoryUtil.createJSONObject();
govObj.put(ServiceConfigTerm.GOVAGENCY_NAME, mapConfigs.get(govAgencyCode));
govObj.put(ServiceConfigTerm.GOVAGENCY_CODE, govAgencyCode);
if (countConfigs.containsKey(govAgencyCode)) {
govObj.put(ConstantUtils.API_JSON_COUNT, countConfigs.get(govAgencyCode));
}
else {
govObj.put(ConstantUtils.API_JSON_COUNT, 0);
}
total += govObj.getInt(ConstantUtils.API_JSON_COUNT);
results.put(govObj);
}
result.put(ConstantUtils.TOTAL, total);
result.put(ConstantUtils.DATA, results);
return Response.status(HttpURLConnection.HTTP_OK).entity(JSONFactoryUtil.looseSerialize(result)).build();
} catch (Exception e) {
return BusinessExceptionImpl.processException(e);
}
}
// @Override
// public Response getToken(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
// User user) {
//
// try {
//
// String token = (String) request.getSession().getAttribute(CSRF_TOKEN_FOR_SESSION_NAME);
//
// _log.info("CHECK::TOKEN:::::" + token);
//
// if (Validator.isNull(token)) {
// token = PortalUUIDUtil.generate();
//
// _log.info("GENERATE_TOKEN:::::" + token);
//
// request.getSession().setAttribute(CSRF_TOKEN_FOR_SESSION_NAME, token);
// }
// return Response.status(HttpURLConnection.HTTP_OK).entity(token).build();
// } catch (Exception e) {
// _log.info(e);
// return _processException(e);
// }
//
// }
}
| VietOpenCPS/opencps-v2 | modules/backend-api-rest/src/main/java/org/opencps/api/controller/impl/OneGateControllerImpl.java | Java | agpl-3.0 | 24,234 |
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var sys = require('sys');
var exec = require('child_process').exec;
var rootdir = process.argv[2];
if (rootdir) {
exec("gulp", function puts(error, stdout, stderr) {
sys.puts(error);
sys.puts(stderr);
sys.puts(stdout);
if (error) {
process.exit(1);
}
});
}
| blocktrail/blocktrail-wallet | hooks/before_prepare/010_gulp.js | JavaScript | agpl-3.0 | 392 |
/*
* ProjectGeneralPreferencesPane.java
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.projects.ui.prefs;
import org.rstudio.core.client.prefs.PreferencesDialogBaseResources;
import org.rstudio.core.client.prefs.RestartRequirement;
import org.rstudio.core.client.resources.ImageResource2x;
import org.rstudio.core.client.widget.FormLabel;
import org.rstudio.core.client.widget.LayoutGrid;
import org.rstudio.studio.client.packrat.model.PackratContext;
import org.rstudio.studio.client.projects.model.RProjectConfig;
import org.rstudio.studio.client.projects.model.RProjectOptions;
import org.rstudio.studio.client.projects.model.RProjectRVersion;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.model.SessionInfo;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Label;
import com.google.inject.Inject;
public class ProjectGeneralPreferencesPane extends ProjectPreferencesPane
{
@Inject
public ProjectGeneralPreferencesPane(Session session)
{
sessionInfo_ = session.getSessionInfo();
LayoutGrid grid = new LayoutGrid(6, 2);
grid.addStyleName(RESOURCES.styles().workspaceGrid());
grid.setCellSpacing(8);
Label infoLabel = new Label("Use (Default) to inherit the global default setting");
infoLabel.addStyleName(PreferencesDialogBaseResources.INSTANCE.styles().infoLabel());
grid.setWidget(0, 0, infoLabel);
// restore workspace
restoreWorkspace_ = new YesNoAskDefault(false);
grid.setWidget(1, 0, new FormLabel("Restore .RData into workspace at startup", restoreWorkspace_));
grid.setWidget(1, 1, restoreWorkspace_);
// save workspace
saveWorkspace_ = new YesNoAskDefault(true);
grid.setWidget(2, 0, new FormLabel("Save workspace to .RData on exit", saveWorkspace_));
grid.setWidget(2, 1, saveWorkspace_);
// always save history
alwaysSaveHistory_ = new YesNoAskDefault(false);
grid.setWidget(3, 0, new FormLabel("Always save history (even if not saving .RData)", alwaysSaveHistory_));
grid.setWidget(3, 1, alwaysSaveHistory_);
// disable execute .Rprofile
grid.setWidget(4, 0, disableExecuteRprofile_ = new CheckBox("Disable .Rprofile execution on session start/resume"));
// quit child processes
grid.setWidget(5, 0, quitChildProcessesOnExit_ = new CheckBox("Quit child processes on exit"));
add(grid);
}
@Override
public ImageResource getIcon()
{
return new ImageResource2x(PreferencesDialogBaseResources.INSTANCE.iconR2x());
}
@Override
public String getName()
{
return "General";
}
@Override
protected void initialize(RProjectOptions options)
{
RProjectConfig config = options.getConfig();
PackratContext context = options.getPackratContext();
restoreWorkspace_.setSelectedIndex(config.getRestoreWorkspace());
saveWorkspace_.setSelectedIndex(config.getSaveWorkspace());
alwaysSaveHistory_.setSelectedIndex(config.getAlwaysSaveHistory());
tutorialPath_ = config.getTutorialPath();
rVersion_ = config.getRVersion();
// if we are in packrat mode, disable the ability to set the disable execute Rprofile setting
// the Rprofile always executes on session start in this case as it is required by packrat
if (context != null && context.isModeOn())
{
disableExecuteRprofile_.setEnabled(false);
disableExecuteRprofile_.setValue(false);
}
else
disableExecuteRprofile_.setValue(config.getDisableExecuteRprofile());
// check or uncheck the checkbox for child processes based on the configuration value
// if default is specified, we need to use the current session setting
// otherwise, yes or no indicate the check state exactly
int quitChildProcessesOnExit = config.getQuitChildProcessesOnExit();
boolean quitChildProcessesChecked = sessionInfo_.quitChildProcessesOnExit();
switch (quitChildProcessesOnExit)
{
case YesNoAskDefault.YES_VALUE:
quitChildProcessesChecked = true;
break;
case YesNoAskDefault.NO_VALUE:
quitChildProcessesChecked = false;
break;
}
quitChildProcessesOnExit_.setValue(quitChildProcessesChecked);
}
@Override
public RestartRequirement onApply(RProjectOptions options)
{
RProjectConfig config = options.getConfig();
config.setRestoreWorkspace(restoreWorkspace_.getSelectedIndex());
config.setSaveWorkspace(saveWorkspace_.getSelectedIndex());
config.setAlwaysSaveHistory(alwaysSaveHistory_.getSelectedIndex());
config.setTutorialPath(tutorialPath_);
config.setRVersion(rVersion_);
config.setDisableExecuteRprofile(disableExecuteRprofile_.getValue());
// turn the quit child processes checkbox from a boolean into the
// YesNoAsk value that it should be in the configuration
boolean quitChildProcessesChecked = quitChildProcessesOnExit_.getValue();
int quitChildProcessesOnExit = 0;
if (quitChildProcessesChecked != sessionInfo_.quitChildProcessesOnExit())
{
quitChildProcessesOnExit = (quitChildProcessesChecked ? YesNoAskDefault.YES_VALUE : YesNoAskDefault.NO_VALUE);
}
config.setQuitChildProcessesOnExit(quitChildProcessesOnExit);
return new RestartRequirement();
}
private YesNoAskDefault restoreWorkspace_;
private YesNoAskDefault saveWorkspace_;
private YesNoAskDefault alwaysSaveHistory_;
private CheckBox disableExecuteRprofile_;
private CheckBox quitChildProcessesOnExit_;
private SessionInfo sessionInfo_;
private String tutorialPath_;
private RProjectRVersion rVersion_;
}
| JanMarvin/rstudio | src/gwt/src/org/rstudio/studio/client/projects/ui/prefs/ProjectGeneralPreferencesPane.java | Java | agpl-3.0 | 6,362 |
#! python
#Python Serial Port Extension for Win32, Linux, BSD, Jython
#serial driver for win32
#see __init__.py
#
#(C) 2001-2003 Chris Liechti <cliechti@gmx.net>
# this is distributed under a free software license, see license.txt
import win32file # The base COM port and file IO functions.
import win32event # We use events and the WaitFor[Single|Multiple]Objects functions.
import win32con # constants.
from serialutil import *
VERSION = "$Revision: 1527 $".split()[1] #extract CVS version
#from winbase.h. these should realy be in win32con
MS_CTS_ON = 16
MS_DSR_ON = 32
MS_RING_ON = 64
MS_RLSD_ON = 128
def device(portnum):
"""Turn a port number into a device name"""
#the "//./COMx" format is required for devices >= 9
#not all versions of windows seem to support this propperly
#so that the first few ports are used with the DOS device name
if portnum < 9:
return 'COM%d' % (portnum+1) #numbers are transformed to a string
else:
return r'\\.\COM%d' % (portnum+1)
class Serial(SerialBase):
"""Serial port implemenation for Win32. This implemenatation requires a
win32all installation."""
BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
19200,38400,57600,115200)
def open(self):
"""Open port with current settings. This may throw a SerialException
if the port cannot be opened."""
if self._port is None:
raise SerialException("Port must be configured before it can be used.")
self.hComPort = None
try:
self.hComPort = win32file.CreateFile(self.portstr,
win32con.GENERIC_READ | win32con.GENERIC_WRITE,
0, # exclusive access
None, # no security
win32con.OPEN_EXISTING,
win32con.FILE_ATTRIBUTE_NORMAL | win32con.FILE_FLAG_OVERLAPPED,
None)
except Exception, msg:
self.hComPort = None #'cause __del__ is called anyway
raise SerialException("could not open port: %s" % msg)
# Setup a 4k buffer
win32file.SetupComm(self.hComPort, 4096, 4096)
#Save original timeout values:
self._orgTimeouts = win32file.GetCommTimeouts(self.hComPort)
self._reconfigurePort()
# Clear buffers:
# Remove anything that was there
win32file.PurgeComm(self.hComPort,
win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT |
win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)
self._overlappedRead = win32file.OVERLAPPED()
self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
self._overlappedWrite = win32file.OVERLAPPED()
self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)
self._isOpen = True
def _reconfigurePort(self):
"""Set commuication parameters on opened port."""
if not self.hComPort:
raise SerialException("Can only operate on a valid port handle")
#Set Windows timeout values
#timeouts is a tuple with the following items:
#(ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
# ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
# WriteTotalTimeoutConstant)
if self._timeout is None:
timeouts = (0, 0, 0, 0, 0)
elif self._timeout == 0:
timeouts = (win32con.MAXDWORD, 0, 0, 0, 0)
else:
timeouts = (0, 0, int(self._timeout*1000), 0, 0)
win32file.SetCommTimeouts(self.hComPort, timeouts)
win32file.SetCommMask(self.hComPort, win32file.EV_ERR)
# Setup the connection info.
# Get state and modify it:
comDCB = win32file.GetCommState(self.hComPort)
comDCB.BaudRate = self._baudrate
if self._bytesize == FIVEBITS:
comDCB.ByteSize = 5
elif self._bytesize == SIXBITS:
comDCB.ByteSize = 6
elif self._bytesize == SEVENBITS:
comDCB.ByteSize = 7
elif self._bytesize == EIGHTBITS:
comDCB.ByteSize = 8
else:
raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
if self._parity == PARITY_NONE:
comDCB.Parity = win32file.NOPARITY
comDCB.fParity = 0 # Dis/Enable Parity Check
elif self._parity == PARITY_EVEN:
comDCB.Parity = win32file.EVENPARITY
comDCB.fParity = 1 # Dis/Enable Parity Check
elif self._parity == PARITY_ODD:
comDCB.Parity = win32file.ODDPARITY
comDCB.fParity = 1 # Dis/Enable Parity Check
else:
raise ValueError("Unsupported parity mode: %r" % self._parity)
if self._stopbits == STOPBITS_ONE:
comDCB.StopBits = win32file.ONESTOPBIT
elif self._stopbits == STOPBITS_TWO:
comDCB.StopBits = win32file.TWOSTOPBITS
else:
raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
comDCB.fBinary = 1 # Enable Binary Transmission
# Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE)
if self._rtscts:
comDCB.fRtsControl = win32file.RTS_CONTROL_HANDSHAKE
comDCB.fDtrControl = win32file.DTR_CONTROL_HANDSHAKE
else:
comDCB.fRtsControl = win32file.RTS_CONTROL_ENABLE
comDCB.fDtrControl = win32file.DTR_CONTROL_ENABLE
comDCB.fOutxCtsFlow = self._rtscts
comDCB.fOutxDsrFlow = self._rtscts
comDCB.fOutX = self._xonxoff
comDCB.fInX = self._xonxoff
comDCB.fNull = 0
comDCB.fErrorChar = 0
comDCB.fAbortOnError = 0
win32file.SetCommState(self.hComPort, comDCB)
#~ def __del__(self):
#~ self.close()
def close(self):
"""Close port"""
if self._isOpen:
if self.hComPort:
#Restore original timeout values:
win32file.SetCommTimeouts(self.hComPort, self._orgTimeouts)
#Close COM-Port:
win32file.CloseHandle(self.hComPort)
self.hComPort = None
self._isOpen = False
def makeDeviceName(self, port):
return device(port)
# - - - - - - - - - - - - - - - - - - - - - - - -
def inWaiting(self):
"""Return the number of characters currently in the input buffer."""
flags, comstat = win32file.ClearCommError(self.hComPort)
return comstat.cbInQue
def read(self, size=1):
"""Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read."""
if not self.hComPort: raise portNotOpenError
if size > 0:
win32event.ResetEvent(self._overlappedRead.hEvent)
flags, comstat = win32file.ClearCommError(self.hComPort)
if self.timeout == 0:
n = min(comstat.cbInQue, size)
if n > 0:
rc, buf = win32file.ReadFile(self.hComPort, win32file.AllocateReadBuffer(n), self._overlappedRead)
win32event.WaitForSingleObject(self._overlappedRead.hEvent, win32event.INFINITE)
read = str(buf)
else:
read = ''
else:
rc, buf = win32file.ReadFile(self.hComPort, win32file.AllocateReadBuffer(size), self._overlappedRead)
n = win32file.GetOverlappedResult(self.hComPort, self._overlappedRead, 1)
read = str(buf[:n])
else:
read = ''
return read
def write(self, s):
"""Output the given string over the serial port."""
if not self.hComPort: raise portNotOpenError
#print repr(s),
if s:
err, n = win32file.WriteFile(self.hComPort, s, self._overlappedWrite)
if err: #will be ERROR_IO_PENDING:
# Wait for the write to complete.
win32event.WaitForSingleObject(self._overlappedWrite.hEvent, win32event.INFINITE)
def flushInput(self):
"""Clear input buffer, discarding all that is in the buffer."""
if not self.hComPort: raise portNotOpenError
win32file.PurgeComm(self.hComPort, win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)
def flushOutput(self):
"""Clear output buffer, aborting the current output and
discarding all that is in the buffer."""
if not self.hComPort: raise portNotOpenError
win32file.PurgeComm(self.hComPort, win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT)
def sendBreak(self):
"""Send break condition."""
if not self.hComPort: raise portNotOpenError
import time
win32file.SetCommBreak(self.hComPort)
#TODO: how to set the correct duration??
time.sleep(0.020)
win32file.ClearCommBreak(self.hComPort)
def setRTS(self,level=1):
"""Set terminal status line: Request To Send"""
if not self.hComPort: raise portNotOpenError
if level:
win32file.EscapeCommFunction(self.hComPort, win32file.SETRTS)
else:
win32file.EscapeCommFunction(self.hComPort, win32file.CLRRTS)
def setDTR(self,level=1):
"""Set terminal status line: Data Terminal Ready"""
if not self.hComPort: raise portNotOpenError
if level:
win32file.EscapeCommFunction(self.hComPort, win32file.SETDTR)
else:
win32file.EscapeCommFunction(self.hComPort, win32file.CLRDTR)
def getCTS(self):
"""Read terminal status line: Clear To Send"""
if not self.hComPort: raise portNotOpenError
return MS_CTS_ON & win32file.GetCommModemStatus(self.hComPort) != 0
def getDSR(self):
"""Read terminal status line: Data Set Ready"""
if not self.hComPort: raise portNotOpenError
return MS_DSR_ON & win32file.GetCommModemStatus(self.hComPort) != 0
def getRI(self):
"""Read terminal status line: Ring Indicator"""
if not self.hComPort: raise portNotOpenError
return MS_RING_ON & win32file.GetCommModemStatus(self.hComPort) != 0
def getCD(self):
"""Read terminal status line: Carrier Detect"""
if not self.hComPort: raise portNotOpenError
return MS_RLSD_ON & win32file.GetCommModemStatus(self.hComPort) != 0
#Nur Testfunktion!!
if __name__ == '__main__':
print __name__
s = Serial()
print s
s = Serial(0)
print s
s.baudrate = 19200
s.databits = 7
s.close()
s.port = 3
s.open()
print s
| emilydolson/forestcat | pyrobot/system/serial/serialwin32.py | Python | agpl-3.0 | 10,927 |
<?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.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* 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 and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
$mod_strings = array (
'LBL_MODULE_NAME' => 'Project',
'LBL_MODULE_TITLE' => 'Projects: Home',
'LBL_SEARCH_FORM_TITLE' => 'Project Search',
'LBL_LIST_FORM_TITLE' => 'Project List',
'LBL_HISTORY_TITLE' => 'History',
'LBL_ID' => 'Id:',
'LBL_DATE_ENTERED' => 'Date Created:',
'LBL_DATE_MODIFIED' => 'Date Modified:',
'LBL_ASSIGNED_USER_ID' => 'Assigned To:',
'LBL_ASSIGNED_USER_NAME' => 'Assigned to:',
'LBL_MODIFIED_USER_ID' => 'Modified User Id:',
'LBL_CREATED_BY' => 'Created By:',
'LBL_TEAM_ID' => 'Team:',
'LBL_NAME' => 'Name:',
'LBL_PDF_PROJECT_NAME' => 'Project Name:',
'LBL_DESCRIPTION' => 'Description:',
'LBL_DELETED' => 'Deleted:',
'LBL_DATE' => 'Date:',
'LBL_DATE_START' => 'Start Date:',
'LBL_DATE_END' => 'End Date:',
'LBL_PRIORITY' => 'Priority:',
'LBL_STATUS' => 'Status:',
'LBL_MY_PROJECTS' => 'My Projects',
'LBL_MY_PROJECT_TASKS' => 'My Project Tasks',
'LBL_TOTAL_ESTIMATED_EFFORT' => 'Total Estimated Effort (hrs):',
'LBL_TOTAL_ACTUAL_EFFORT' => 'Total Actual Effort (hrs):',
'LBL_LIST_NAME' => 'Name',
'LBL_LIST_DAYS' => 'days',
'LBL_LIST_ASSIGNED_USER_ID' => 'Assigned To',
'LBL_LIST_TOTAL_ESTIMATED_EFFORT' => 'Total Estimated Effort (hrs)',
'LBL_LIST_TOTAL_ACTUAL_EFFORT' => 'Total Actual Effort (hrs)',
'LBL_LIST_UPCOMING_TASKS' => 'Upcoming Tasks (1 Week)',
'LBL_LIST_OVERDUE_TASKS' => 'Overdue Tasks',
'LBL_LIST_OPEN_CASES' => 'Open Cases',
'LBL_LIST_END_DATE' => 'End Date',
'LBL_LIST_TEAM_ID' => 'Team',
'LBL_PROJECT_SUBPANEL_TITLE' => 'Projects',
'LBL_PROJECT_TASK_SUBPANEL_TITLE' => 'Project Tasks',
'LBL_CONTACT_SUBPANEL_TITLE' => 'Contacts',
'LBL_ACCOUNT_SUBPANEL_TITLE' => 'Accounts',
'LBL_OPPORTUNITY_SUBPANEL_TITLE' => 'Opportunities',
'LBL_QUOTE_SUBPANEL_TITLE' => 'Quotes',
// quick create label
'LBL_NEW_FORM_TITLE' => 'New Project',
'CONTACT_REMOVE_PROJECT_CONFIRM' => 'Are you sure you want to remove this contact from this project?',
'LNK_NEW_PROJECT' => 'Create Project',
'LNK_PROJECT_LIST' => 'View Project List',
'LNK_NEW_PROJECT_TASK' => 'Create Project Task',
'LNK_PROJECT_TASK_LIST' => 'View Project Tasks',
'LBL_DEFAULT_SUBPANEL_TITLE' => 'Projects',
'LBL_ACTIVITIES_TITLE'=>'Activities',
'LBL_ACTIVITIES_SUBPANEL_TITLE'=>'Activities',
'LBL_HISTORY_SUBPANEL_TITLE'=>'History',
'LBL_QUICK_NEW_PROJECT' => 'New Project',
'LBL_PROJECT_TASKS_SUBPANEL_TITLE' => 'Project Tasks',
'LBL_CONTACTS_SUBPANEL_TITLE' => 'Contacts',
'LBL_ACCOUNTS_SUBPANEL_TITLE' => 'Accounts',
'LBL_OPPORTUNITIES_SUBPANEL_TITLE' => 'Opportunities',
'LBL_CASES_SUBPANEL_TITLE' => 'Cases',
'LBL_BUGS_SUBPANEL_TITLE' => 'Bugs',
'LBL_PRODUCTS_SUBPANEL_TITLE' => 'Products',
'LBL_TASK_ID' => 'ID',
'LBL_TASK_NAME' => 'Task Name',
'LBL_DURATION' => 'Duration',
'LBL_ACTUAL_DURATION' => 'Actual Duration',
'LBL_START' => 'Start',
'LBL_FINISH' => 'Finish',
'LBL_PREDECESSORS' => 'Predecessors',
'LBL_PERCENT_COMPLETE' => '% Complete',
'LBL_MORE' => 'More...',
'LBL_PERCENT_BUSY' => '% Busy',
'LBL_TASK_ID_WIDGET' => 'id',
'LBL_TASK_NAME_WIDGET' => 'description',
'LBL_DURATION_WIDGET' => 'duration',
'LBL_START_WIDGET' => 'date_start',
'LBL_FINISH_WIDGET' => 'date_finish',
'LBL_PREDECESSORS_WIDGET' => 'predecessors_',
'LBL_PERCENT_COMPLETE_WIDGET' => 'percent_complete',
'LBL_EDIT_PROJECT_TASKS_TITLE'=> 'Edit Project Tasks',
'LBL_OPPORTUNITIES' => 'Opportunities',
'LBL_LAST_WEEK' => 'Previous',
'LBL_NEXT_WEEK' => 'Next',
'LBL_PROJECTRESOURCES_SUBPANEL_TITLE' => 'Project Resources',
'LBL_PROJECTTASK_SUBPANEL_TITLE' => 'Project Task',
'LBL_HOLIDAYS_SUBPANEL_TITLE' => 'Holidays',
'LBL_PROJECT_INFORMATION' => 'Project Overview',
'LBL_EDITLAYOUT' => 'Edit Layout' /*for 508 compliance fix*/,
'LBL_INSERTROWS' => 'Insert Rows' /*for 508 compliance fix*/,
);
?>
| nlv/suitecrm | modules/Project/language/en_us.lang.php | PHP | agpl-3.0 | 6,210 |
/* MODULE: auth_krb5 */
/* COPYRIGHT
* Copyright (c) 1997 Messaging Direct Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY MESSAGING DIRECT LTD. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MESSAGING DIRECT LTD. OR
* ITS EMPLOYEES OR AGENTS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
* END COPYRIGHT */
/* ok, this is wrong but the most convenient way of doing
* it for now. We assume (possibly incorrectly) that if GSSAPI exists then
* the Kerberos 5 headers and libraries exist.
* What really should be done is a configure.in check for krb5.h and use
* that since none of this code is GSSAPI but rather raw Kerberos5.
*/
/* Also, at some point one would hope it would be possible to
* have less divergence between Heimdal and MIT Kerberos 5.
*
* As of the summer of 2003, the obvious issues are that
* MIT doesn't have krb5_verify_opt_*() and Heimdal doesn't
* have krb5_sname_to_principal().
*/
/* PUBLIC DEPENDENCIES */
#include "mechanisms.h"
#include "globals.h" /* mech_option */
#include "cfile.h"
#include "krbtf.h"
#ifdef AUTH_KRB5
# include <krb5.h>
static cfile config = 0;
static char *keytabname = NULL; /* "system default" */
static char *verify_principal = "host"; /* a principal in the default keytab */
#endif /* AUTH_KRB5 */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/stat.h>
#include "auth_krb5.h"
/* END PUBLIC DEPENDENCIES */
int /* R: -1 on failure, else 0 */
auth_krb5_init (
/* PARAMETERS */
void /* no parameters */
/* END PARAMETERS */
)
{
#ifdef AUTH_KRB5
char *configname = 0;
if (krbtf_init() == -1) {
syslog(LOG_ERR, "auth_krb5_init krbtf_init failed");
return -1;
}
if (mech_option)
configname = mech_option;
else if (access(SASLAUTHD_CONF_FILE_DEFAULT, F_OK) == 0)
configname = SASLAUTHD_CONF_FILE_DEFAULT;
if (configname) {
char complaint[1024];
if (!(config = cfile_read(configname, complaint, sizeof (complaint)))) {
syslog(LOG_ERR, "auth_krb5_init %s", complaint);
return -1;
}
}
if (config) {
keytabname = (char *) cfile_getstring(config, "krb5_keytab", keytabname);
verify_principal = (char *) cfile_getstring(config, "krb5_verify_principal", verify_principal);
}
return 0;
#else
return -1;
#endif
}
#ifdef AUTH_KRB5
static int
form_principal_name (
const char *user,
const char *service,
const char *realm,
char *pname,
int pnamelen
)
{
const char *forced_instance = 0;
int plen;
plen = strlcpy(pname, user, pnamelen);
user = pname;
if (config && cfile_getswitch(config, "krb5_conv_krb4_instance", 0)) {
char *krb4_instance;
if ((krb4_instance = strchr(pname, '.'))) *krb4_instance = '/';
}
if (config) {
char keyname[1024];
snprintf(keyname, sizeof (keyname), "krb5_%s_instance", service);
forced_instance = cfile_getstring(config, keyname, 0);
}
if (forced_instance) {
char *user_specified;
if ((user_specified = strchr(user, '/'))) {
if (strcmp(user_specified + 1, forced_instance)) {
/* user not allowed to override sysadmin */
return -1;
} else {
/* don't need to force--user already asked for it */
forced_instance = 0;
}
}
}
/* form user[/instance][@realm] */
plen += snprintf(pname+plen, pnamelen-plen, "%s%s%s%s",
(forced_instance ? "/" : ""),
(forced_instance ? forced_instance : ""),
((realm && realm[0]) ? "@" : ""),
((realm && realm[0]) ? realm : "")
);
if ((plen <= 0) || (plen >= pnamelen))
return -1;
/* Perhaps we should uppercase the realm? */
return 0;
}
#ifdef KRB5_HEIMDAL
char * /* R: allocated response string */
auth_krb5 (
/* PARAMETERS */
const char *user, /* I: plaintext authenticator */
const char *password, /* I: plaintext password */
const char *service, /* I: service authenticating to */
const char *realm, /* I: user's realm */
const char *remote /* I: remote host address */
/* END PARAMETERS */
)
{
/* VARIABLES */
krb5_context context;
krb5_ccache ccache = NULL;
krb5_keytab kt = NULL;
krb5_principal auth_user;
krb5_verify_opt opt;
char * result;
char tfname[2048];
char principalbuf[2048];
/* END VARIABLES */
if (!user || !password) {
syslog(LOG_ERR, "auth_krb5: NULL password or username?");
return strdup("NO saslauthd internal NULL password or username");
}
if (krb5_init_context(&context)) {
syslog(LOG_ERR, "auth_krb5: krb5_init_context");
return strdup("NO saslauthd internal krb5_init_context error");
}
if (form_principal_name(user, service, realm, principalbuf, sizeof (principalbuf))) {
syslog(LOG_ERR, "auth_krb5: form_principal_name");
return strdup("NO saslauthd principal name error");
}
if (krb5_parse_name (context, principalbuf, &auth_user)) {
krb5_free_context(context);
syslog(LOG_ERR, "auth_krb5: krb5_parse_name");
return strdup("NO saslauthd internal krb5_parse_name error");
}
if (krbtf_name(tfname, sizeof (tfname)) != 0) {
syslog(LOG_ERR, "auth_krb5: could not generate ccache name");
return strdup("NO saslauthd internal error");
}
if (krb5_cc_resolve(context, tfname, &ccache)) {
krb5_free_principal(context, auth_user);
krb5_free_context(context);
syslog(LOG_ERR, "auth_krb5: krb5_cc_resolve");
return strdup("NO saslauthd internal error");
}
if (keytabname) {
if (krb5_kt_resolve(context, keytabname, &kt)) {
krb5_free_principal(context, auth_user);
krb5_cc_destroy(context, ccache);
krb5_free_context(context);
syslog(LOG_ERR, "auth_krb5: krb5_kt_resolve");
return strdup("NO saslauthd internal error");
}
}
krb5_verify_opt_init(&opt);
krb5_verify_opt_set_secure(&opt, 1);
krb5_verify_opt_set_ccache(&opt, ccache);
if (kt)
krb5_verify_opt_set_keytab(&opt, kt);
krb5_verify_opt_set_service(&opt, verify_principal);
if (krb5_verify_user_opt(context, auth_user, password, &opt)) {
result = strdup("NO krb5_verify_user_opt failed");
} else {
result = strdup("OK");
}
krb5_free_principal(context, auth_user);
krb5_cc_destroy(context, ccache);
if (kt)
krb5_kt_close(context, kt);
krb5_free_context(context);
return result;
}
#else /* !KRB5_HEIMDAL */
static void k5support_log_err(int priority,
krb5_context context,
krb5_error_code code,
char const *msg)
{
const char *k5_msg = krb5_get_error_message(context, code);
syslog(priority, "auth_krb5: %s: %s (%d)\n", msg, k5_msg, code);
krb5_free_error_message(context, k5_msg);
}
/* returns 0 for failure, 1 for success */
static int k5support_verify_tgt(krb5_context context,
krb5_ccache ccache)
{
krb5_principal server;
krb5_data packet;
krb5_keyblock *keyblock = NULL;
krb5_auth_context auth_context = NULL;
krb5_error_code k5_retcode;
krb5_keytab kt = NULL;
char thishost[BUFSIZ];
int result = 0;
memset(&packet, 0, sizeof(packet));
if ((k5_retcode = krb5_sname_to_principal(context, NULL, verify_principal,
KRB5_NT_SRV_HST, &server))) {
k5support_log_err(LOG_DEBUG, context, k5_retcode, "krb5_sname_to_principal()");
return 0;
}
if (keytabname) {
if ((k5_retcode = krb5_kt_resolve(context, keytabname, &kt))) {
k5support_log_err(LOG_DEBUG, context, k5_retcode, "krb5_kt_resolve()");
goto fini;
}
}
if ((k5_retcode = krb5_kt_read_service_key(context, kt, server, 0,
0, &keyblock))) {
k5support_log_err(LOG_DEBUG, context, k5_retcode, "krb5_kt_read_service_key()");
goto fini;
}
if (keyblock) {
krb5_free_keyblock(context, keyblock);
}
/* this duplicates work done in krb5_sname_to_principal
* oh well.
*/
if (gethostname(thishost, BUFSIZ) < 0) {
goto fini;
}
thishost[BUFSIZ-1] = '\0';
if ((k5_retcode = krb5_mk_req(context, &auth_context, 0, verify_principal,
thishost, NULL, ccache, &packet))) {
k5support_log_err(LOG_DEBUG, context, k5_retcode, "krb5_mk_req()");
}
if (auth_context) {
krb5_auth_con_free(context, auth_context);
auth_context = NULL;
}
if (k5_retcode) {
goto fini;
}
if ((k5_retcode = krb5_rd_req(context, &auth_context, &packet,
server, NULL, NULL, NULL))) {
k5support_log_err(LOG_DEBUG, context, k5_retcode, "krb5_rd_req()");
goto fini;
}
if (auth_context) {
krb5_auth_con_free(context, auth_context);
auth_context = NULL;
}
/* all is good now */
result = 1;
fini:
if (!k5_retcode) {
krb5_free_data_contents(context, &packet);
}
krb5_free_principal(context, server);
return result;
}
/* FUNCTION: auth_krb5 */
/* SYNOPSIS
* Authenticate against Kerberos V.
* END SYNOPSIS */
char * /* R: allocated response string */
auth_krb5 (
/* PARAMETERS */
const char *user, /* I: plaintext authenticator */
const char *password, /* I: plaintext password */
const char *service, /* I: service authenticating to */
const char *realm, /* I: user's realm */
const char *remote /* I: remote host address */
/* END PARAMETERS */
)
{
/* VARIABLES */
krb5_context context;
krb5_ccache ccache = NULL;
krb5_principal auth_user;
krb5_creds creds;
krb5_get_init_creds_opt opts;
char * result;
char tfname[2048];
char principalbuf[2048];
krb5_error_code code;
/* END VARIABLES */
if (!user|| !password) {
syslog(LOG_ERR, "auth_krb5: NULL password or username?");
return strdup("NO saslauthd internal error");
}
if (krb5_init_context(&context)) {
syslog(LOG_ERR, "auth_krb5: krb5_init_context");
return strdup("NO saslauthd internal error");
}
if (form_principal_name(user, service, realm, principalbuf, sizeof (principalbuf))) {
syslog(LOG_ERR, "auth_krb5: form_principal_name");
return strdup("NO saslauthd principal name error");
}
if ((code = krb5_parse_name (context, principalbuf, &auth_user))) {
k5support_log_err(LOG_ERR, context, code, "krb5_parse_name()");
krb5_free_context(context);
return strdup("NO saslauthd internal error");
}
if (krbtf_name(tfname, sizeof (tfname)) != 0) {
syslog(LOG_ERR, "auth_krb5: could not generate ticket file name");
return strdup("NO saslauthd internal error");
}
if ((code = krb5_cc_resolve(context, tfname, &ccache))) {
k5support_log_err(LOG_ERR, context, code, "krb5_cc_resolve()");
krb5_free_principal(context, auth_user);
krb5_free_context(context);
return strdup("NO saslauthd internal error");
}
if ((code = krb5_cc_initialize (context, ccache, auth_user))) {
k5support_log_err(LOG_ERR, context, code, "krb5_cc_initialize()");
krb5_free_principal(context, auth_user);
krb5_free_context(context);
return strdup("NO saslauthd internal error");
}
krb5_get_init_creds_opt_init(&opts);
/* 15 min should be more than enough */
krb5_get_init_creds_opt_set_tkt_life(&opts, 900);
if ((code = krb5_get_init_creds_password(context, &creds,
auth_user, password, NULL, NULL,
0, NULL, &opts))) {
k5support_log_err(LOG_ERR, context, code, "krb5_get_init_creds_password()");
krb5_cc_destroy(context, ccache);
krb5_free_principal(context, auth_user);
krb5_free_context(context);
return strdup("NO saslauthd internal error");
}
/* at this point we should have a TGT. Let's make sure it is valid */
if ((code = krb5_cc_store_cred(context, ccache, &creds))) {
k5support_log_err(LOG_ERR, context, code, "krb5_cc_store_cred()");
krb5_free_principal(context, auth_user);
krb5_cc_destroy(context, ccache);
krb5_free_context(context);
return strdup("NO saslauthd internal error");
}
if (!k5support_verify_tgt(context, ccache)) {
syslog(LOG_ERR, "auth_krb5: k5support_verify_tgt");
result = strdup("NO saslauthd internal error");
goto fini;
}
/*
* fall through -- user is valid beyond this point
*/
result = strdup("OK");
fini:
/* destroy any tickets we had */
krb5_free_cred_contents(context, &creds);
krb5_free_principal(context, auth_user);
krb5_cc_destroy(context, ccache);
krb5_free_context(context);
return result;
}
#endif /* KRB5_HEIMDAL */
#else /* ! AUTH_KRB5 */
char *
auth_krb5 (
const char *login __attribute__((unused)),
const char *password __attribute__((unused)),
const char *service __attribute__((unused)),
const char *realm __attribute__((unused)),
const char *remote __attribute__((unused))
)
{
return NULL;
}
#endif /* ! AUTH_KRB5 */
/* END FUNCTION: auth_krb5 */
/* END MODULE: auth_krb5 */
| papyrussolution/OpenPapyrus | Src/OSF/cyrus-sasl/saslauthd/auth_krb5.c | C | agpl-3.0 | 14,041 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
ADMINS = (
("David Barragán", "bameda@dbarragan.com"),
)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0q)_&-!hu%%en55a&cx!a2c^7aiw*7*+^zg%_&vk9&4&-4&qg#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
# Media files
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'monarch.base',
'monarch.documents',
'monarch.users',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'monarch.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'TEMPLATE_DEBUG': False,
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
| bameda/monarch | back/settings/common.py | Python | agpl-3.0 | 3,078 |
<?php
/**
* Email template.You can change the content of this template
* @copyright Copyright (c) 2014-2016 Benjamin BALET
* @license http://opensource.org/licenses/AGPL-3.0 AGPL-3.0
* @link https://github.com/bbalet/jorani
* @since 0.1.0
*/
?>
<html lang="it">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta charset="UTF-8">
<style>
table {width:50%;margin:5px;border-collapse:collapse;}
table, th, td {border: 1px solid black;}
th, td {padding: 20px;}
h5 {color:red;}
</style>
</head>
<body>
<h3>{Title}</h3>
{Firstname} {Lastname} richiede un congedo. Qui di seguito <a href="{BaseUrl}leaves/requests/{LeaveId}">i dettagli</a>:
<table border="0">
<tr>
<td>Da </td><td>{StartDate} ({StartDateType})</td>
</tr>
<tr>
<td>Per </td><td>{EndDate} ({EndDateType})</td>
</tr>
<tr>
<td>Tipo </td><td>{Type}</td>
</tr>
<tr>
<td>Durata </td><td>{Duration}</td>
</tr>
<tr>
<td>Equilibrio </td><td>{Balance}</td>
</tr>
<tr>
<td>Motivo </td><td>{Reason}</td>
</tr>
<tr>
<td><a href="{BaseUrl}requests/accept/{LeaveId}">Accetta</a> </td><td><a href="{BaseUrl}requests/reject/{LeaveId}">Rifiuta</a></td>
</tr>
</table>
<br />
È possibile controllare il <a href="{BaseUrl}hr/counters/collaborators/{UserId}">bilanciamento del congedo</a> prima di convalidare la richiesta di congedo.
<hr>
<h5>*** Questo è un messaggio generato automaticamente, si prega di non rispondere a questo messaggio ***</h5>
</body>
</html> | guillaumeblaquiere/jorani | application/views/emails/it/request.php | PHP | agpl-3.0 | 1,960 |
// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"fmt"
"strings"
"github.com/juju/errors"
"github.com/juju/names"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/constraints"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/mongo"
"github.com/juju/juju/state/watcher"
)
// Open connects to the server described by the given
// info, waits for it to be initialized, and returns a new State
// representing the environment connected to.
//
// A policy may be provided, which will be used to validate and
// modify behaviour of certain operations in state. A nil policy
// may be provided.
//
// Open returns unauthorizedError if access is unauthorized.
func Open(tag names.EnvironTag, info *mongo.MongoInfo, opts mongo.DialOpts, policy Policy) (*State, error) {
st, err := open(tag, info, opts, policy)
if err != nil {
return nil, errors.Trace(err)
}
if _, err := st.Environment(); err != nil {
if err := st.Close(); err != nil {
logger.Errorf("error closing state for unreadable environment %s: %v", tag.Id(), err)
}
return nil, errors.Annotatef(err, "cannot read environment %s", tag.Id())
}
// State should only be Opened on behalf of a state server environ; all
// other *States should be created via ForEnviron.
if err := st.start(tag); err != nil {
return nil, errors.Trace(err)
}
return st, nil
}
func open(tag names.EnvironTag, info *mongo.MongoInfo, opts mongo.DialOpts, policy Policy) (*State, error) {
logger.Infof("opening state, mongo addresses: %q; entity %v", info.Addrs, info.Tag)
logger.Debugf("dialing mongo")
session, err := mongo.DialWithInfo(info.Info, opts)
if err != nil {
return nil, maybeUnauthorized(err, "cannot connect to mongodb")
}
logger.Debugf("connection established")
err = mongodbLogin(session, info)
if err != nil {
session.Close()
return nil, errors.Trace(err)
}
logger.Debugf("mongodb login successful")
// In rare circumstances, we may be upgrading from pre-1.23, and not have the
// environment UUID available. In that case we need to infer what it might be;
// we depend on the assumption that this is the only circumstance in which
// the the UUID might not be known.
if tag.Id() == "" {
logger.Warningf("creating state without environment tag; inferring bootstrap environment")
ssInfo, err := readRawStateServerInfo(session)
if err != nil {
session.Close()
return nil, errors.Trace(err)
}
tag = ssInfo.EnvironmentTag
}
st, err := newState(tag, session, info, policy)
if err != nil {
session.Close()
return nil, errors.Trace(err)
}
return st, nil
}
// mongodbLogin logs in to the mongodb admin database.
func mongodbLogin(session *mgo.Session, mongoInfo *mongo.MongoInfo) error {
admin := session.DB("admin")
if mongoInfo.Tag != nil {
if err := admin.Login(mongoInfo.Tag.String(), mongoInfo.Password); err != nil {
return maybeUnauthorized(err, fmt.Sprintf("cannot log in to admin database as %q", mongoInfo.Tag))
}
} else if mongoInfo.Password != "" {
if err := admin.Login(mongo.AdminUser, mongoInfo.Password); err != nil {
return maybeUnauthorized(err, "cannot log in to admin database")
}
}
return nil
}
// Initialize sets up an initial empty state and returns it.
// This needs to be performed only once for the initial state server environment.
// It returns unauthorizedError if access is unauthorized.
func Initialize(owner names.UserTag, info *mongo.MongoInfo, cfg *config.Config, opts mongo.DialOpts, policy Policy) (_ *State, err error) {
uuid, ok := cfg.UUID()
if !ok {
return nil, errors.Errorf("environment uuid was not supplied")
}
envTag := names.NewEnvironTag(uuid)
st, err := open(envTag, info, opts, policy)
if err != nil {
return nil, errors.Trace(err)
}
defer func() {
if err != nil {
if closeErr := st.Close(); closeErr != nil {
logger.Errorf("error closing state while aborting Initialize: %v", closeErr)
}
}
}()
// A valid environment is used as a signal that the
// state has already been initalized. If this is the case
// do nothing.
if _, err := st.Environment(); err == nil {
return nil, errors.New("already initialized")
} else if !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
// When creating the state server environment, the new environment
// UUID is also used as the state server UUID.
logger.Infof("initializing state server environment %s", uuid)
ops, err := st.envSetupOps(cfg, uuid, uuid, owner)
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops,
createInitialUserOp(st, owner, info.Password),
txn.Op{
C: stateServersC,
Id: environGlobalKey,
Assert: txn.DocMissing,
Insert: &stateServersDoc{
EnvUUID: st.EnvironUUID(),
},
},
txn.Op{
C: stateServersC,
Id: apiHostPortsKey,
Assert: txn.DocMissing,
Insert: &apiHostPortsDoc{},
},
txn.Op{
C: stateServersC,
Id: stateServingInfoKey,
Assert: txn.DocMissing,
Insert: &StateServingInfo{},
},
txn.Op{
C: stateServersC,
Id: hostedEnvCountKey,
Assert: txn.DocMissing,
Insert: &hostedEnvCountDoc{},
},
)
if err := st.runTransaction(ops); err != nil {
return nil, errors.Trace(err)
}
if err := st.start(envTag); err != nil {
return nil, errors.Trace(err)
}
return st, nil
}
func (st *State) envSetupOps(cfg *config.Config, envUUID, serverUUID string, owner names.UserTag) ([]txn.Op, error) {
if err := checkEnvironConfig(cfg); err != nil {
return nil, errors.Trace(err)
}
// When creating the state server environment, the new environment
// UUID is also used as the state server UUID.
if serverUUID == "" {
serverUUID = envUUID
}
envUserOp := createEnvUserOp(envUUID, owner, owner, owner.Name())
ops := []txn.Op{
createConstraintsOp(st, environGlobalKey, constraints.Value{}),
createSettingsOp(environGlobalKey, cfg.AllAttrs()),
incHostedEnvironCountOp(),
createEnvironmentOp(st, owner, cfg.Name(), envUUID, serverUUID),
createUniqueOwnerEnvNameOp(owner, cfg.Name()),
envUserOp,
}
return ops, nil
}
func maybeUnauthorized(err error, msg string) error {
if err == nil {
return nil
}
if isUnauthorized(err) {
return errors.Unauthorizedf("%s: unauthorized mongo access: %v", msg, err)
}
return errors.Annotatef(err, msg)
}
func isUnauthorized(err error) bool {
if err == nil {
return false
}
// Some unauthorized access errors have no error code,
// just a simple error string; and some do have error codes
// but are not of consistent types (LastError/QueryError).
for _, prefix := range []string{"auth fail", "not authorized"} {
if strings.HasPrefix(err.Error(), prefix) {
return true
}
}
if err, ok := err.(*mgo.QueryError); ok {
return err.Code == 10057 ||
err.Message == "need to login" ||
err.Message == "unauthorized"
}
return false
}
// newState creates an incomplete *State, with a configured watcher but no
// pwatcher, leadershipManager, or serverTag. You must start() the returned
// *State before it will function correctly.
func newState(environTag names.EnvironTag, session *mgo.Session, mongoInfo *mongo.MongoInfo, policy Policy) (_ *State, resultErr error) {
// Set up database.
rawDB := session.DB(jujuDB)
database, err := allCollections().Load(rawDB, environTag.Id())
if err != nil {
return nil, errors.Trace(err)
}
if err := InitDbLogs(session); err != nil {
return nil, errors.Trace(err)
}
// Create State.
return &State{
environTag: environTag,
mongoInfo: mongoInfo,
session: session,
database: database,
policy: policy,
watcher: watcher.New(rawDB.C(txnLogC)),
}, nil
}
// MongoConnectionInfo returns information for connecting to mongo
func (st *State) MongoConnectionInfo() *mongo.MongoInfo {
return st.mongoInfo
}
// CACert returns the certificate used to validate the state connection.
func (st *State) CACert() string {
return st.mongoInfo.CACert
}
func (st *State) Close() (err error) {
defer errors.DeferredAnnotatef(&err, "closing state failed")
// TODO(fwereade): we have no defence against these components failing
// and leaving other parts of state going. They should be managed by a
// dependency.Engine (or perhaps worker.Runner).
var errs []error
handle := func(name string, err error) {
if err != nil {
errs = append(errs, errors.Annotatef(err, "error stopping %s", name))
}
}
handle("transaction watcher", st.watcher.Stop())
if st.pwatcher != nil {
handle("presence watcher", st.pwatcher.Stop())
}
if st.leadershipManager != nil {
st.leadershipManager.Kill()
handle("leadership manager", st.leadershipManager.Wait())
}
st.mu.Lock()
if st.allManager != nil {
handle("allwatcher manager", st.allManager.Stop())
}
if st.allEnvManager != nil {
handle("allenvwatcher manager", st.allEnvManager.Stop())
}
if st.allEnvWatcherBacking != nil {
handle("allenvwatcher backing", st.allEnvWatcherBacking.Release())
}
st.session.Close()
st.mu.Unlock()
if len(errs) > 0 {
for _, err := range errs[1:] {
logger.Errorf("while closing state: %v", err)
}
return errs[0]
}
logger.Debugf("closed state without error")
return nil
}
| cloud-green/juju | state/open.go | GO | agpl-3.0 | 9,235 |
# Contextualizar
:clock430: **16:15-16:30**
## Comezo da Fase 1 Contextualización. Dinámica "Tecer a rede".
Comezamos coa dinámica "tecer a rede" coa que nos coñecemos todos un pouco mellor (nome, perfil, que podemos aportar ao grupo).


Vese que as participantes proveñen a maior parte de disciplinas técnicas (Enxeñería e Arquitectura) relacionadas coa temática, pero tamén de colectivos de acción social en xeral e en particular que traballan con persoas afectadas por enfermidades ou con discapacidade funcional.
---
:clock430: **16:45**
## Dinámica "Árbore". Brainstorming.

Decídese facer un *brainstorming* empregando *post-its* para cada idea suxerida nos paneis.
Primeiro identificanse problemáticas, ainda que inicialmente se suxería unha por persoa, este límite excediuse amplamente. Aínda así as participantes puideron facer unha breve explicación dos problemas aportados.
### Problemáticas que foron identificadas:

- **Modelo territorial disperso. Alto custo de sistema de transporte público.**
- Ocupación do espazo de forma dispersa e polo tanto é dificil ter un transporte público para todos. Cuestionase o sistema de transporte público tal e como está concebido.
- **Barrios periféricos a lugares moi referenciais da cidade.**
- **Conexión en bici cos concellos veciños.**
- Falta de conexión a pé e en bici cos Concellos do lado (Arteixo e Oleiros) e o perigo que conleva.
Persoas con mobilidade reducida entre a cidade e a súa contorna.
- **Bici en entornos difíciles. Non se pode chegar en bici a tódolos lados (rapaces). Trasporte en bicicleta dos adolescentes por toda a cidade.**
- **Separación das funcións no territorio. Crean a necesidade de desprazarse longas distancias.**
- **Reparto do espazo público. Ter espazos para cada tipo de mobilidade ao final non deixa contento a ninguén.**
- O territorio ten usos diferentes e polo tanto as necesidades de mobilidade son moitas, habería que buscar medidas que non sexan estándar.
- **Acceso universal dende todos os puntos da cidade aos espazos de lecer. Necesidade de espazo común para todas (sen barreiras).**
- **Descoñecemento *cultural* da cidade. Falta de coñecemento das posibilidades da cidade: como moverse pola cidade, falta divulgación (non hai > non podemos). Dificultade para desprazarse entre lugares cercanos simplemente por descoñecemento das redes e posibilidades que ten a cidade. Falta de información sinxela sobre a cidade.**
- **Problema de desprazamento para carriños bebés e persoas con discapacidade funcional con mobilidade reducida (a veces o que fai falla é información). Tampouco o sabemos facer.**
- **Uso preferente do coche particular e de forma individual para desprazamento ao traballo.**
- **Concienciación de educación vial tanto conductores como peóns.**
- **Pouca pedagoxía da da saúde de da mobilidade sostible.**
- **Concentración en sitios e horas puntuais.**
- Identificar puntos da cidade con moita afluencia de tráfico en horarios concretos (por temas laborais) para poñer transporte público.
- **Falta de aparcamentos públicos de bicicletas. Non hai espazos para gardar bicis para un particular, promover sitios públicos onde poder gardalas.**
- **O coche como elemento de prestixo. Coche = prestixio e éxito.**
- **Fai falta información en tempo real nas liñas e frecuencia do autobús (non funcionan ben).**
- **Prezo do transporte público.**
- **Liñas do bus (hai sitios que tardan 45 minutos en pasar).**
- **Exceso de coche no espazo público. Ocupación polos coches dos espazos públicos.**
- Empoderamento cidadá probando a peonalización pechando provisionalmente as rúas.
Peonalización do centro. Non ter o coche diante todo o tempo.
- **Velocidade dos coches.**
- **Seguridade das persoas.**
- **Sinalización.**
- **Choiva. Promove o uso do coche e dificulta a adopción doutros medios (bici, a pé).**
- **Mobilidade dos animais salvaxes. Corredores ecolóxicos.**
- **Contaminación (polución, ruido...)**
- **Dureza do espazo cando vas a pé. Espazo desolador, non agradable.**
- **Mobilidade peoníl difícil e perigosa.**
- **Percorridos peonís complexos (liñas de desexo).**
- **Moito tráfico.**
- Falta de cálculo de coste/beneficio real do uso do coche.
- **Pouca amabilidade dos condutores do transporte público. Velocidade excesiva.**
- **Autobús adaptado.**
- **Alteración e desaparición de camiños tradicionais para construir cousas novas. Necesidade de recuperación e respecto dos camiños de sempre.**
- **Falta de espazo para aparcar (e subir e baixar) nos aparcamentos para persoas con discapacidade.**
- **Beirarrúas estreitas.**
- **Falta de visibilidade dos pasos de peóns.**
- **Paseo marítimo (aspectos de deseño, distribución dos espazos).**
- **Horario BiciCoruña. Que as bicicletas de alquiler poidan ser por un tempo longo no que as usuarias se poidan facer responsables delas.**
### Axentes identificados:

Nesta parte identificáronse dous tipos de axentes, uns serían axentes que realizan proxectos interesantes e na liña de mobilidade sustentable, e outros, que simplemente son axentes importantes que prestan un servizo na cidade e é preciso ter en conta.
#### Axentes ou actores importantes a ter en conta:
- **Porto da Coruña (tamén en canto a tráfico de camións)**
- **Compañía de Tranvías**
- **Autos Cal-Pita**
- **Autocares Vázquez**
- **Taxistas**
- **Sector automoción (tamén concesionarios)**
- **Grandes centros traballo (Inditex, A Grela...)**
- **Renfe**
- **Clubes deportivos (*running*, bicicleta, triatlón)**
- *Fixie Coruña Club* ¿?
#### Axentes que fan proxectos ou iniciativas interesantes ou minorías que se creiu que deben ter voz e participar:
- **Mobiliza-Reciclos**
- **Plataforma pola mobilidade**
- **Rede Salud y Bienestar - UDC Saludable**
- **Ecoloxistas (Adega...)**
- **Stop Accidentes**
- **Cartolab**
- **AMPAS**
- **Adolescentes que queren ir en bici**
- **Colectivo 1 a 1**
- **ONCE**
- **Asociacións persoas con afeccións e mobilidade reducida (Alzheimer, transplantados, cardiopatías...)**
- ***Personas andarinas por prescripción médica* (refírese en xeral a grupos de persoas que realizan actividade de andar a pé de forma análoga á xente que corre).**
- **Ergosfera**
- *Arquitectos Mobilidade con proceso participativos* ¿?
- *Velaivai*
### Proxectos interesantes:

##### *(Os proxectos surxidos teñen base en proxectos existentes ainda que non se faga referencia explícita a eles, de moitos non se puido referenciar o nome ou proxecto real).*
- **Proxecto de peonalización Times Square, Nova Iorque (pintando liñas e con conos na rúa. Prototipar as rúas peonís a través de pintado do espazo.**
- **Jane Jacobs. A solución a todo non é a peonalización nin os carriles bici, senón que tamén pasa pola redistribución e uso compartido do espazo público).**
- **Servizo que suxire rutas en bici alternativas. Non só ruta rápida senón agradable, cómoda, con árbores... (Nova Iorque?)**
- **Transporte baixo demanda (non se poden poñer liñas contínuas), sobre todo en zonas rurais.**
- **Estudos de accesibilidade peonil (Instituto Tecnolóxico de Deusto) para planificación de equipamentos accesibles.**
- **Condución autonoma (Google)**
- **Cooperativas de usuarias de coche compartido, ou alternativas con grupos máis pechados/familiares.**
- **Servizos de compartir / alquiler coches como as bicis (*Uber*, *Bla bla car*)**
- **Proxecto que estudou a dispersión para reducir a necesidade de mobilidade (plurirreparto e pluriservizo, en Finlandia).**
- **Soportais de Santiago (non é un proxecto pero a idea de deseñar a cidade dun xeito máis vivible).**
- **Zonas 30**
- **Camiños escolares (rás pintadas no chan).**
- **Buses especializados para eventos/festas en Galicia (por exemplo, en veráns en Ourense).**
- **Autobuses nocturnos, BUHO. Incentivar para eventos susceptibles de interese para a mocidade.**
- **Proxectos premiados de accesibilidade e deseño para todos (Vancouver, Xapón) que fan fincapé no mapeo e a sua divulgación de forma escrita. Indican se hai barreiras, relieve, etc. de traxectos a lugares habituais en diferentes medios de transporte, por exemplo, cómo ir ó CHUAC, á praza X, á escola Z...**
- **Amplitude do tamaño dos sinais de autobuses (para facilitar a lectura por parte persoas con visibilidade reducida; nenos, maiores...), Madrid.**
- **Semáforo adaptado para diferentes alturas (Colombia).**
- ***Conozcamos la ciudad* (mapeo en Zaragoza)**
- **Quedadas para andar en grupo como as feitas por Masa crítica, Mobiliza, Plataforma mobilidade...**
- **Carril bus**
- **Peatonalización do centro**
- Corredor verde do oleoducto.
- Proxecto *Tomar medidas* (na Normal?)
- Proxectos de *Bici-Ciudad*, bicis compartidas
- Proxectos de compartir garaxe (Coruña ten?)
- Transporte incentivado por parte das empresas.
- Colocar bicis nos hospitais da cidade.
- Amberes ¿?
#### Resultado da identificación dos problemas, axentes e proxectos:

---
:clock6: **18:00**
## Clusterización


No proceso de clusterización agrupáronse as distintas problemáticas, axentes e proxectos en conxuntos amplos.
### Problemática:
- **Uso do coche e problemática do tráfico**
- Exceso de tráfico, de velocidade dos coches. Contaminación. Coche=Prestixio social.
- **Criterios xerais para o deseño universal do espazo público e a accesibilidade**
- Seguridade. Camiños tradicionais. Corredores ecolóxicos. Modelo disperso. Paseo marítimo...
- **Mobilidade a pé e en bicicleta pola cidade**
- Mobilidade peoníl difícil e perigosa. Beirarrúas estreitas. Dureza do espazo, non agradable para ir a pé. Percorridos a pé complexos...
- **Pedagoxía, conciencia, comunicación e información para a cidadanía**
- Concienciación. Descoñecemento da cidade e necesidade de información. Información de liñas e percorridos e comportamento dos condutores do transporte público. Sinalización. Visibilidade dos pasos de peóns. Pedagoxía da saúde e da mobilidade sostible.
- **Servizo público de mobilidade**
- Prezo do transporte. Liñas de bus. Autobuses adaptados. Horario BiciCoruña.

### Proxectos:
- **Amortiguar o uso do coche**
- Servizos para compartir desprazamentos e aparcamento
- **Deseño universal do espazo público e accesibilidade**
- Peonalización do centro, deseño accesible, camiños escolares, soportais, zonas 30
- **Servizos públicos**
- Buses nocturnos e especializados para eventos/festas, semáforo adaptado a diferentes alturas, transporte baixo demanda
- **Coñecemento compartido**
- Quedadas, servizos de suxerencia de rutas alternativas en bici, *Times Square*, Estudos de accesibilidade e deseño...
### Axentes:
- Axentes especializados
- Plataforma pola mobilidade, Stop accidentes, Reciclos-Mobiliza, grupos ecoloxistas (Adega...), grupos de traballo da UDC (Cartolab, Salud y Bienestar - UDC Saludable), Colectivo 1 a 1, Ergosfera...
- Organizacións de persoas usuarias
- ONCE, AMPAS, asociacións que traballan con persoas con discapacidade funcional, grandes centros de traballo (Porto, Polígonos Industriais...), persoas *andarinas por prescripción médica*...
- Outros actores a ter en conta
- Empresas autobuses (Compañía de tranvías, Autos Cal-Pita, Autocares Vázquez), taxistas, Renfe, Industria automoción, Porto da Coruña, Clubes deportivos (*running*, bicicleta, triatlón)...

---
:clock7: **19:00**
## Posta en común plenaria
Finalmente Senén e Inés espuxeron o resultado desta fase en plenario:

| ForxaCoLab/obradoiro | mobilidade/contextualizar/README.md | Markdown | agpl-3.0 | 12,393 |
<?php
namespace KREDA\Sphere\Common\Database\Schema;
use Doctrine\DBAL\Logging\SQLLogger;
use KREDA\Sphere\Common\AbstractExtension;
/**
* Class Logger
*
* @package KREDA\Sphere\Common\Database\Schema
*/
class Logger extends AbstractExtension implements SQLLogger
{
private $Data = array();
/**
* Logs a SQL statement somewhere.
*
* @param string $sql The SQL to be executed.
* @param array|null $params The SQL parameters.
* @param array|null $types The SQL parameter types.
*
* @return void
*/
public function startQuery( $sql, array $params = null, array $types = null )
{
$this->Data = func_get_args();
$this->Data[3] = self::extensionDebugger()->getTimeGap();
$Log = $sql;
ob_start();
var_dump( $params );
$params = ob_get_clean();
$Log .= ' '.$params;
ob_start();
var_dump( $types );
$types = ob_get_clean();
$Log .= ' '.$types;
self::extensionDebugger()->protocolDump( $Log );
}
/**
* Marks the last started query as stopped. This can be used for timing of queries.
*
* @return void
*/
public function stopQuery()
{
self::extensionDebugger()->addProtocol(
number_format( ( self::extensionDebugger()->getTimeGap() - $this->Data[3] ) * 1000, 3, ',', '' )
);
}
}
| KWZwickau/KREDA-Sphere | Sphere/Common/Database/Schema/Logger.php | PHP | agpl-3.0 | 1,413 |
'use strict';
var util = require('util');
var Promise = require('bluebird');
var uuid = require('../../utils/uuid');
var errors = require('../../errors');
var EmbeddedModel = require('../../EmbeddedModel');
// Schema Validator
// ----------------
var validator = require('jjv')();
validator.addSchema(require('../../schemas/cycle'));
// EmbeddedModel Constructor
// -------------------------
function Status (conn, data, parent) {
return EmbeddedModel.call(this, conn, data, parent)
.then(function(self) {
// check authorizations
if(!self.parent.authorizations['cycle/statuses:read'])
return Promise.reject(new errors.ForbiddenError());
// cycle_id
self.cycle_id = self.parent.id;
return self;
});
}
// EmbeddedModel Configuration
// ---------------------------
Status.key = 'statuses';
Status.collections = {};
Status.validate = function(data) {
return validator.validate('http://www.gandhi.io/schema/cycle#/definitions/status', data, {useDefault: true, removeAdditional: true});
};
Status.create = function(conn, data, parent) {
if(!parent.authorizations['cycle/statuses:write'])
return Promise.reject(new errors.ForbiddenError());
// generate a new uuid
data.id = uuid();
var err = Status.validate(data);
if(err) return Promise.reject(new errors.ValidationError('The input is invalid.', err));
return new Status(conn, data, parent)
.then(function(status) {
return status.save(conn);
});
};
// Public Methods
// --------------
util.inherits(Status, EmbeddedModel);
// check authorizations for update
Status.prototype.update = function(conn, delta) {
var self = this;
if(!self.parent.authorizations['cycle/statuses:write'])
return Promise.reject(new errors.ForbiddenError());
return EmbeddedModel.prototype.update.call(self, conn, delta);
};
// check authorizations for delete
Status.prototype.delete = function(conn) {
var self = this;
if(!self.parent.authorizations['cycle/statuses:write'])
return Promise.reject(new errors.ForbiddenError());
return EmbeddedModel.prototype.delete.call(self, conn);
};
module.exports = Status;
| mike-marcacci/gandhi | lib/api/models/Cycle/Status.js | JavaScript | agpl-3.0 | 2,129 |
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for Oauth2Server/managers/clientRoleUriManager.js</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="../../prettify.css" />
<link rel="stylesheet" href="../../base.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(../../sort-arrow-sprite.png);
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='pad1'>
<h1>
<a href="../../index.html">all files</a> / <a href="index.html">Oauth2Server/managers/</a> clientRoleUriManager.js
</h1>
<div class='clearfix'>
<div class='fl pad1y space-right2'>
<span class="strong">85.71% </span>
<span class="quiet">Statements</span>
<span class='fraction'>18/21</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">50% </span>
<span class="quiet">Branches</span>
<span class='fraction'>3/6</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">100% </span>
<span class="quiet">Functions</span>
<span class='fraction'>4/4</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">85.71% </span>
<span class="quiet">Lines</span>
<span class='fraction'>18/21</span>
</div>
</div>
</div>
<div class='status-line high'></div>
<pre><table class="coverage">
<tr><td class="line-count quiet">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61</td><td class="line-coverage quiet"><span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-yes">4×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span></td><td class="text"><pre class="prettyprint lang-js">/*
Copyright (C) 2016 Ulbora Labs LLC. (www.ulboralabs.com)
All rights reserved.
Copyright (C) 2016 Ken Williamson
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/>.
*/
var manager = require("./manager");
var db;
exports.init = function (database) {
db = database;
};
exports.addClientRoleUri = function (json, callback) {
var returnVal = {
success: false
};
var isOk = manager.securityCheck(json);
<span class="missing-if-branch" title="else path not taken" >E</span>if (isOk) {
db.addClientRoleUri(json, callback);
} else {
<span class="cstat-no" title="statement not covered" > callback(returnVal);</span>
}
};
exports.getClientRoleAllowedUriList = function (clientRoleId, callback) {
var isOk = manager.securityCheck(clientRoleId);
<span class="missing-if-branch" title="else path not taken" >E</span>if (isOk) {
db.getClientRoleAllowedUriList(clientRoleId, callback);
}else {
<span class="cstat-no" title="statement not covered" > callback({});</span>
}
};
exports.deleteClientRoleUri = function (json, callback) {
var returnVal = {
success: false
};
var isOk = manager.securityCheck(json);
<span class="missing-if-branch" title="else path not taken" >E</span>if (isOk) {
db.deleteClientRoleUri(json, callback);
} else {
<span class="cstat-no" title="statement not covered" > callback(returnVal);</span>
}
};</pre></td></tr>
</table></pre>
<div class='push'></div><!-- for sticky footer -->
</div><!-- /wrapper -->
<div class='footer quiet pad2 space-top1 center small'>
Code coverage
generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Sun Apr 15 2018 16:55:14 GMT-0400 (EDT)
</div>
</div>
<script src="../../prettify.js"></script>
<script>
window.onload = function () {
if (typeof prettyPrint === 'function') {
prettyPrint();
}
};
</script>
<script src="../../sorter.js"></script>
</body>
</html>
| Ulbora/nodeJsOauth2Server | coverage/lcov-report/Oauth2Server/managers/clientRoleUriManager.js.html | HTML | agpl-3.0 | 7,549 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Rgaa32016 Test.6.3.4 NA 03</title>
</head>
<body>
<div>
<div class="test-detail" lang="fr">
Chaque lien composite (contenu texte et de l'attribut <code>alt</code>) est-il explicite hors contexte (hors cas particuliers)
</div>
<div class="testcase">
<a href="my-link.html"> <img src="image.jpg" alt="" /> <b> </b> </a>
<a href="my-link.html"> <span> </span> <object data="data.png"> </object> </a>
</div>
<p class="test-explanation">NA : The page contains any <a> tag with a "title" attribute but the link text is missing. In this case, the tag is ignored</p>
</div>
</body>
</html> | Tanaguru/Tanaguru | rules/rgaa3-2016/src/test/resources/testcases/rgaa32016/Rgaa32016Rule060303/Rgaa32016.Test.06.03.03-4NA-03.html | HTML | agpl-3.0 | 1,035 |
<?php
// created: 2016-12-05 07:54:48
$mod_strings = array (
'LBL_ID' => 'ID',
'LBL_DATE_ENTERED' => 'Дата создания',
'LBL_DATE_MODIFIED' => 'Дата изменения',
'LBL_MODIFIED' => 'Изменено',
'LBL_MODIFIED_ID' => 'Изменено(ID)',
'LBL_MODIFIED_NAME' => 'Изменено (Имя)',
'LBL_CREATED' => 'Создано',
'LBL_CREATED_ID' => 'Создано(ID)',
'LBL_DESCRIPTION' => 'Описание',
'LBL_DELETED' => 'Удалён',
'LBL_NAME' => 'Условие',
'LBL_CREATED_USER' => 'Создано',
'LBL_MODIFIED_USER' => 'Изменено',
'LBL_LIST_NAME' => 'Название',
'LBL_EDIT_BUTTON' => 'Править',
'LBL_REMOVE' => 'Удалить',
'LBL_MODULE_NAME' => 'Условия',
'LBL_MODULE_TITLE' => 'Условия',
'LBL_MODULE_PATH' => 'Модуль',
'LBL_FIELD' => 'Поле',
'LBL_OPERATOR' => 'Оператор сравнения',
'LBL_VALUE_TYPE' => 'Тип',
'LBL_VALUE' => 'Значение',
'LBL_ORDER' => 'Сортировка',
'LBL_CONDITION_OPERATOR' => 'Оператор сравнения',
'LBL_AOW_WORKFLOW_ID' => 'WorkFlow Id',
); | PiterIrene/test1 | cache/modules/AOW_Conditions/language/ru_ru.lang.php | PHP | agpl-3.0 | 1,162 |
declare module '*.scss' {
const content: {[className: string]: string};
export default content;
}
declare module '*.png' {
const src: string;
export default src;
}
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<
SVGSVGElement
> & { title?: string }>;
const src: string;
export default src;
}
| nukeop/nuclear | packages/app/typings/import-types.d.ts | TypeScript | agpl-3.0 | 395 |
package com.x.base.core.project.cache;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.project.cache.Cache.CacheCategory;
import com.x.base.core.project.cache.Cache.CacheKey;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.jaxrs.WrapClearCacheRequest;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.base.core.project.tools.StringTools;
public abstract class CacheManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CacheManager.class);
private CacheManager() {
}
private static Cache cache;
private static String name = StringTools.uniqueToken();
public static void init(String name) throws Exception {
CacheManager.name = name;
cache();
}
private static synchronized Cache cache() throws Exception {
if (null == cache) {
if (StringUtils.equals(Config.cache().getType(), Cache.TYPE_REDIS)) {
cache = new CacheRedisImpl(name);
} else if (StringUtils.equals(Config.cache().getType(), Cache.TYPE_EHCACHE)) {
cache = new CacheEhcacheImpl(name);
} else {
cache = new CacheGuavaImpl(name);
}
}
return cache;
}
public static void put(CacheCategory category, CacheKey key, Object o) {
try {
cache().put(category, key, o);
} catch (Exception e) {
LOGGER.error(e);
}
}
public static Optional<Object> get(CacheCategory category, CacheKey key) {
try {
return cache().get(category, key);
} catch (Exception e) {
LOGGER.error(e);
}
return Optional.empty();
}
public static void shutdown() {
try {
if (null != cache) {
cache.shutdown();
}
} catch (Exception e) {
LOGGER.error(e);
}
}
public static void receive(WrapClearCacheRequest wi) {
try {
if (null != cache) {
cache.receive(wi);
}
} catch (Exception e) {
LOGGER.error(e);
}
}
public static void notify(Class<?> clz, List<Object> keys) {
try {
if (null != cache) {
cache.notify(clz, keys);
}
} catch (Exception e) {
LOGGER.error(e);
}
}
public static void notify(Class<?> clz) {
try {
if (null != cache) {
cache.notify(clz, new ArrayList<Object>());
}
} catch (Exception e) {
LOGGER.error(e);
}
}
public static void notify(Class<?> clz, Object... objects) {
try {
if (null != cache) {
cache.notify(clz, ListTools.toList(objects));
}
} catch (Exception e) {
LOGGER.error(e);
}
}
public static String detail() throws Exception {
return cache().detail();
}
}
| o2oa/o2oa | o2server/x_base_core_project/src/main/java/com/x/base/core/project/cache/CacheManager.java | Java | agpl-3.0 | 2,655 |
###########################################################################
# Copyright 2017 ZT Prentner IT GmbH (www.ztp.at)
#
# 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/>.
###########################################################################
"""
This module provides functions to parse a DEP.
"""
from builtins import int
from builtins import range
from .gettext_helper import _
import copy
import ijson
from math import ceil
from six import string_types
from . import utils
from . import receipt
class DEPException(utils.RKSVVerifyException):
"""
An exception that is thrown if something is wrong with a DEP.
"""
pass
class DEPParseException(DEPException):
"""
Indicates that an error occurred while parsing the DEP.
"""
def __init__(self, msg):
super(DEPParseException, self).__init__(msg)
self._initargs = (msg,)
class MalformedDEPException(DEPParseException):
"""
Indicates that the DEP is not properly formed.
"""
def __init__(self, msg=None, groupidx=None):
if msg is None:
super(MalformedDEPException, self).__init__(_("Malformed DEP"))
else:
if groupidx is None:
super(MalformedDEPException, self).__init__(
_('{}.').format(msg))
else:
super(MalformedDEPException, self).__init__(
_("In group {}: {}.").format(groupidx, msg))
self._initargs = (msg, groupidx)
class MissingDEPElementException(MalformedDEPException):
"""
Indicates that an element in the DEP is missing.
"""
def __init__(self, elem, groupidx=None):
super(MissingDEPElementException, self).__init__(
_("Element \"{}\" missing").format(elem),
groupidx)
self._initargs = (elem, groupidx)
class MalformedDEPElementException(MalformedDEPException):
"""
Indicates that an element in the DEP is malformed.
"""
def __init__(self, elem, detail=None, groupidx=None):
if detail is None:
super(MalformedDEPElementException, self).__init__(
_("Element \"{}\" malformed").format(elem),
groupidx)
else:
super(MalformedDEPElementException, self).__init__(
_("Element \"{}\" malformed: {}").format(elem, detail),
groupidx)
self._initargs = (elem, detail, groupidx)
class DuplicateDEPElementException(MalformedDEPException):
"""
Indicates that an element in the DEP is redundant.
"""
def __init__(self, elem, groupidx=None):
super(DuplicateDEPElementException, self).__init__(
_("Duplicate element \"{}\"").format(elem),
groupidx)
self._initargs = (elem, groupidx)
class MalformedCertificateException(DEPParseException):
"""
Indicates that a certificate in the DEP is not properly formed.
"""
def __init__(self, cert):
super(MalformedCertificateException, self).__init__(
_("Certificate \"{}\" malformed.").format(cert))
self._initargs = (cert,)
class DEPState(object):
def __init__(self, upper = None):
self.upper = upper
def parse(self, prefix, event, value):
raise NotImplementedError("Please implement this yourself.")
def ready(self):
return False
def getChunk(self):
raise NotImplementedError("Please implement this yourself.")
def needCrt(self):
return None
def setCrt(self, cert, cert_chain):
raise NotImplementedError("Please implement this yourself.")
class DEPStateWithData(DEPState):
def __init__(self, chunksize, upper = None):
super(DEPStateWithData, self).__init__(upper)
self.chunksize = chunksize
if upper:
self.chunk = self.upper.chunk
else:
self.chunk = list()
def currentChunksize(self):
return sum(len(recs) for recs, cert, cert_chain in self.chunk)
def ready(self):
if self.chunksize == 0:
return False
return self.currentChunksize() >= self.chunksize
def getChunk(self):
if self.currentChunksize() <= 0:
return []
# Note that we only copy the groups (of which there are hopefully few)
# FIXME: but still...
ret = copy.copy(self.chunk)
del self.chunk[:]
return ret
class DEPStateWithIncompleteData(DEPStateWithData):
class WIPData(object):
def __init__(self):
self.cert = None
self.cert_chain = None
self.recs = list()
def __init__(self, chunksize, upper, idx):
super(DEPStateWithIncompleteData, self).__init__(chunksize, upper)
if hasattr(upper, 'wip'):
self.wip = upper.wip
else:
self.wip = DEPStateWithIncompleteData.WIPData()
self.idx = idx
def needCrt(self):
if self.wip.cert is None or self.wip.cert_chain is None:
return self.idx
return None
def setCrt(self, cert, cert_chain):
self.wip.cert = cert
self.wip.cert_chain = cert_chain
def mergeIntoChunk(self):
if len(self.wip.recs) > 0:
clist = self.wip.cert_chain
if clist is None:
clist = list()
self.chunk.append((self.wip.recs, self.wip.cert, clist))
self.wip.recs = list()
def ready(self):
if self.chunksize == 0:
return False
return self.currentChunksize() + len(self.wip.recs) >= self.chunksize
def getChunk(self):
self.mergeIntoChunk()
return super(DEPStateWithIncompleteData, self).getChunk()
class DEPStateRoot(DEPStateWithData):
def __init__(self, chunksize):
super(DEPStateRoot, self).__init__(chunksize)
self.root_seen = False
def parse(self, prefix, event, value):
if prefix == '' and event == 'start_map' and value == None:
if self.root_seen:
raise MalformedDEPException(_('Duplicate DEP root'))
self.root_seen = True
return DEPStateRootMap(self.chunksize, self)
raise MalformedDEPException(_('Malformed DEP root'))
class DEPStateRootMap(DEPStateWithData):
def __init__(self, chunksize, upper):
super(DEPStateRootMap, self).__init__(chunksize, upper)
self.groups_seen = False
def parse(self, prefix, event, value):
if prefix == '' and event == 'end_map':
if not self.groups_seen:
raise MissingDEPElementException('Belege-Gruppe')
return self.upper
if prefix == 'Belege-Gruppe':
if event != 'start_array':
raise MalformedDEPException(_('Malformed DEP root'))
if self.groups_seen:
raise MalformedDEPException(_('Duplicate DEP root'))
self.groups_seen = True
return DEPStateBGList(self.chunksize, self)
# TODO: handle other elements
return self
class DEPStateBGList(DEPStateWithData):
def __init__(self, chunksize, upper):
super(DEPStateBGList, self).__init__(chunksize, upper)
self.curIdx = 0
def parse(self, prefix, event, value):
if prefix == 'Belege-Gruppe' and event == 'end_array':
return self.upper
if prefix == 'Belege-Gruppe.item' and event == 'start_map':
nextState = DEPStateGroup(self.chunksize, self, self.curIdx)
self.curIdx += 1
return nextState
raise MalformedDEPElementException('Belege-Gruppe')
class DEPStateGroup(DEPStateWithIncompleteData):
def __init__(self, chunksize, upper, idx):
super(DEPStateGroup, self).__init__(chunksize, upper, idx)
self.recs_seen = False
self.cert_seen = False
self.cert_list_seen = False
def parse(self, prefix, event, value):
if prefix == 'Belege-Gruppe.item' and event == 'end_map':
if not self.cert_seen:
raise MissingDEPElementException('Signaturzertifikat', self.idx)
if not self.cert_list_seen:
raise MissingDEPElementException('Zertifizierungsstellen', self.idx)
if not self.recs_seen:
raise MissingDEPElementException('Belege-kompakt', self.idx)
self.mergeIntoChunk()
return self.upper
if prefix == 'Belege-Gruppe.item.Signaturzertifikat':
if self.cert_seen:
raise DuplicateDEPElementException('Signaturzertifikat', self.idx)
if event != 'string':
raise MalformedDEPElementException('Signaturzertifikat',
_('not a string'), self.idx)
self.cert_seen = True
self.wip.cert = parseDEPCert(value) if value != '' else None
elif prefix == 'Belege-Gruppe.item.Zertifizierungsstellen':
if self.cert_list_seen:
raise DuplicateDEPElementException('Zertifizierungsstellen', self.idx)
if event != 'start_array':
raise MalformedDEPElementException('Zertifizierungsstellen',
_('not a list'), self.idx)
self.wip.cert_chain = list()
self.cert_list_seen = True
return DEPStateCertList(self.chunksize, self, self.idx)
elif prefix == 'Belege-Gruppe.item.Belege-kompakt':
if self.recs_seen:
raise DuplicateDEPElementException('Belege-kompakt', self.idx)
if event != 'start_array':
raise MalformedDEPElementException('Belege-kompakt',
_('not a list'), self.idx)
self.recs_seen = True
return DEPStateReceiptList(self.chunksize, self, self.idx)
# TODO: handle other elements
return self
class DEPStateCertList(DEPStateWithIncompleteData):
def parse(self, prefix, event, value):
if prefix == 'Belege-Gruppe.item.Zertifizierungsstellen' and event == 'end_array':
return self.upper
if prefix == 'Belege-Gruppe.item.Zertifizierungsstellen.item' \
and event == 'string':
self.wip.cert_chain.append(parseDEPCert(value))
return self
raise MalformedDEPElementException('Zertifizierungsstellen', self.idx)
class DEPStateReceiptList(DEPStateWithIncompleteData):
def parse(self, prefix, event, value):
if prefix == 'Belege-Gruppe.item.Belege-kompakt' and event == 'end_array':
return self.upper
if prefix == 'Belege-Gruppe.item.Belege-kompakt.item' \
and event == 'string':
self.wip.recs.append(shrinkDEPReceipt(value))
return self
raise MalformedDEPElementException('Belege-kompakt', self.idx)
def shrinkDEPReceipt(rec, idx = None):
"""
Encode a JWS receipt string to a bytes representation. This takes up less
memory.
:param rec: The receipt JWS as a string.
:param idx: The index of the group in the DEP to which the receipt belongs
or None if it is unknown. This is only used to generate error messages.
:return: The receipt JWS as a byte array.
"""
try:
return rec.encode('utf-8')
except TypeError:
if idx is None:
raise MalformedDEPElementException(_('Receipt \"{}\"').format(rec))
else:
raise MalformedDEPElementException(_('Receipt \"{}\"').format(rec), idx)
def expandDEPReceipt(rec, idx = None):
"""
Decodes a receipt JWS byte array to a regular string.
:param rec: The receipt JWS as a byte array.
:param idx: The index of the group in the DEP to which the receipt belongs
or None if it is unknown. This is only used to generate error messages.
:return: The receipt JWS as a string.
"""
try:
return rec.decode('utf-8')
except UnicodeDecodeError:
if idx is None:
raise MalformedDEPElementException(_('Receipt \"{}\"').format(rec))
else:
raise MalformedDEPElementException(_('Receipt \"{}\"').format(rec), idx)
def parseDEPCert(cert_str):
"""
Turns a certificate string as used in a DEP into a certificate object.
:param cert_str: A certificate in PEM format without header and footer
and on a single line.
:return: A cryptography certificate object.
:throws: MalformedCertificateException
"""
if not isinstance(cert_str, string_types):
raise MalformedCertificateException(cert_str)
try:
return utils.loadCert(utils.addPEMCertHeaders(cert_str))
except ValueError:
raise MalformedCertificateException(cert_str)
class DEPParserI(object):
"""
The base class for DEP parsers. This interface allows reading a DEP in
small chunks without having to store it in memory entirely. Do not use this
directly, use one of the subclasses.
"""
def parse(self, chunksize = 0):
"""
This function parses a DEP and yields chunks of at most chunksize
receipts. A chunk is a list of group tuples. Every group tuple consists
of a list of receipt JWS as byte arrays, a certificate object
containing the certificate used to sign the receipts (or None) and a
list of certificate objects with the certificates used to sign the
first certificate (or an empty list) in that order.
If the chunksize is non-zero, every chunk is guaranteed to contain at
most chunksize receipts in total (over all groups). Otherwise, the
maximum number of receipts is implementation dependent. Every yielded
chunk is guaranteed to contain at least one group tuple.
:param chunksize: A positive number specifying the maximum number of
receipts in one chunk or zero.
:yield: One chunk at a time as described above.
:throws: DEPParseException
"""
raise NotImplementedError("Please implement this yourself.")
class IncrementalDEPParser(DEPParserI):
"""
A DEP parser that reads a DEP from a file descriptor. Do not use this
directly, use one of the subclasses or the fromFd() method which will return
an appropriate parser object.
"""
def __init__(self, fd):
# skipBOM checks if we can seek, so no harm in doing it to a non-file
self.startpos = utils.skipBOM(fd)
self.fd = fd
@staticmethod
def fromFd(fd, need_certs=True):
"""
Returns a new IncrementalDEPParser object using the specified file
descriptor. If chunks don't necessarily have to contain the DEP group
certificates (because, for example, no signature verification is
performed), the need_certs parameter can be set to False. In this case
fromFd() will return a CertlessStreamDEPParser. If need_certs is True,
it will return a FileDEPParser for a seekable file descriptor and a
StreamDEPParser for a non-seekable one.
:param fd: The file descriptor to use.
:param need_certs: Whether chunks need to contain the group
certificates.
:return: An IncrementalDEPParser object using fd as data source.
"""
if not need_certs:
return CertlessStreamDEPParser(fd)
try:
fd.tell()
return FileDEPParser(fd)
except IOError:
return StreamDEPParser(fd)
def _needCerts(self, state, chunksize, groupidx):
raise NotImplementedError("Please implement this yourself.")
def parse(self, chunksize = 0):
parser = ijson.parse(self.fd)
state = DEPStateRoot(chunksize)
got_something = False
try:
for prefix, event, value in parser:
nextState = state.parse(prefix, event, value)
if state.ready():
needed = state.needCrt()
if needed is not None:
self._needCerts(state, chunksize, needed)
yield state.getChunk()
got_something = True
state = nextState
# The entire DEP is parsed, get the rest.
# We should have found any certs here, so no check needed.
last = state.getChunk()
if len(last) > 0:
yield last
elif not got_something:
raise MalformedDEPException(_('No receipts found'))
except ijson.JSONError as e:
raise DEPParseException(_('Malformed JSON: {}.').format(e))
class StreamDEPParser(IncrementalDEPParser):
"""
A DEP parser that reads a DEP from a stream type file descriptor. Such a
file descriptor is not seekable. The parse() method will raise an exception
if an element needed to construct a chunk was not read by the time the
chunk has to be yielded. It will not perform any look-ahead operations
because all receipts read until the missing elements are found would need
to be stored in memory, thus defeating the purpose of the parser API.
A chunksize of zero for the parse() method will cause all receipts in the
DEP to be returned in a single chunk.
"""
def _needCerts(self, state, chunksize, groupidx):
raise MalformedDEPException(
_("Element \"Signaturzertifikat\" or \"Zertifizierungsstellen\" missing"),
groupidx)
def parse(self, chunksize = 0):
return super(StreamDEPParser, self).parse(chunksize)
class CertlessStreamDEPParser(StreamDEPParser):
"""
This DEP parser behaves identically to StreamDEPParser, except for the
fact, that it will not raise an exception if a DEP element needed to
construct the current chunk has not been read yet. Instead, the yielded
chunk will have these elements set to None (for Signaturzertifikat) and the
empty list (for Zertifizierungsstellen) respectively.
Note that the parser will still not tolerate if the elements are missing
altogether.
"""
def _needCerts(self, state, chunksize, groupidx):
# Do nothing, we don't really care about certs.
# The parser will still fail if they are outright missing, but we are ok
# with returning chunks without certs even though the DEP contains some.
pass
class FileDEPParser(IncrementalDEPParser):
"""
A DEP parser that reads a DEP from a seekable file. If DEP elements needed
to construct the current chunk are missing, this parser will perform an
additional parsing pass to locate these elements before returning the
chunk. If the total number of such elements is less than the given
chunksize, they will be cached in memory to avoid having to do even more
parsing passes.
A chunksize of zero for the parse() method will cause all receipts in the
DEP to be returned in a single chunk.
"""
def __getItems(self, prefix, chunksize):
if prefix in self.cache:
return self.cache[prefix]
# cache miss, gotta parse the JSON again
ofs = self.fd.tell()
self.fd.seek(self.startpos)
items = list(ijson.items(self.fd, prefix))
self.fd.seek(ofs)
if chunksize == 0 or len(items) <= chunksize:
self.cache[prefix] = items
return items
def _needCerts(self, state, chunksize, groupidx):
cert_str = self.__getItems(
'Belege-Gruppe.item.Signaturzertifikat', chunksize)[groupidx]
cert_str_list = self.__getItems(
'Belege-Gruppe.item.Zertifizierungsstellen', chunksize)[groupidx]
cert = parseDEPCert(cert_str) if cert_str != '' else None
cert_list = [ parseDEPCert(cs) for cs in cert_str_list ]
state.setCrt(cert, cert_list)
def parse(self, chunksize = 0):
self.fd.seek(self.startpos)
self.cache = dict()
return super(FileDEPParser, self).parse(chunksize)
def totalRecsInDictDEP(dep):
def _nrecs(group):
try:
recs = group['Belege-kompakt']
if not isinstance(recs, list):
return 0
return len(recs)
except (TypeError, KeyError):
return 0
bg = dep.get('Belege-Gruppe', [])
if not isinstance(bg, list):
return 0
return sum(_nrecs(g) for g in bg)
class DictDEPParser(DEPParserI):
"""
A DEP parser that accepts an already parsed dictionary data structure and
yields chunks of the requested size. This parser is intended to parse DEPs
that are already completely in memory anyway but emulates the parser API
for compatibility.
If the chunksize is zero and the nparts parameter equals 1, the parse()
method will return each group in the DEP in its own chunk.
If the chunksize is zero and the nparts parameter is greater than 1, the
parse() method will try to evenly distribute the receipts over nparts
chunks. It will then yield at most nparts chunks.
"""
def __init__(self, dep, nparts = 1):
self.dep = dep
self.nparts = nparts
pass
def _parseDEPGroup(self, group, idx):
if not isinstance(group, dict):
raise MalformedDEPElementException('Belege-Gruppe', idx)
if 'Belege-kompakt' not in group:
raise MissingDEPElementException('Belege-kompakt', idx)
if 'Signaturzertifikat' not in group:
raise MissingDEPElementException('Signaturzertifikat', idx)
if 'Zertifizierungsstellen' not in group:
raise MissingDEPElementException('Zertifizierungsstellen', idx)
cert_str = group['Signaturzertifikat']
cert_str_list = group['Zertifizierungsstellen']
receipts = (shrinkDEPReceipt(r) for r in group['Belege-kompakt'])
if not isinstance(cert_str, string_types):
raise MalformedDEPElementException('Signaturzertifikat',
_('not a string'), idx)
if not isinstance(cert_str_list, list):
raise MalformedDEPElementException('Zertifizierungsstellen',
_('not a list'), idx)
try:
iter(receipts)
except TypeError:
raise MalformedDEPElementException('Belege-kompakt',
_('not a list'), idx)
cert = parseDEPCert(cert_str) if cert_str != '' else None
cert_list = [ parseDEPCert(cs) for cs in cert_str_list ]
return receipts, cert, cert_list
def _groupChunkGen(self, chunksize, groups):
if chunksize == 0:
groupidx = 0
for group in groups:
recgen, cert, certs = self._parseDEPGroup(group, groupidx)
recs = list(recgen)
if len(recs) > 0:
yield [(recs, cert, certs)]
groupidx += 1
return
chunk = list()
chunklen = 0
groupidx = 0
for group in groups:
recgen, cert, cert_list = self._parseDEPGroup(group, groupidx)
nextrecs = list()
for rec in recgen:
nextrecs.append(rec)
chunklen += 1
if chunklen >= chunksize:
chunk.append((nextrecs, cert, cert_list))
yield chunk
nextrecs = list()
chunk = list()
chunklen = 0
if len(nextrecs) > 0:
chunk.append((nextrecs, cert, cert_list))
groupidx += 1
if chunklen > 0:
yield chunk
def parse(self, chunksize = 0):
if not isinstance(self.dep, dict):
raise MalformedDEPException(_('Malformed DEP root'))
if 'Belege-Gruppe' not in self.dep:
raise MissingDEPElementException('Belege-Gruppe')
bg = self.dep['Belege-Gruppe']
if not isinstance(bg, list) or not bg:
raise MalformedDEPElementException('Belege-Gruppe')
if self.nparts > 1 and not chunksize:
nrecs = totalRecsInDictDEP(self.dep)
chunksize = int(ceil(float(nrecs) / self.nparts))
got_something = False
for chunk in self._groupChunkGen(chunksize, bg):
yield chunk
got_something = True
if not got_something:
raise MalformedDEPException(_('No receipts found'))
class FullFileDEPParser(DEPParserI):
"""
This parser behaves like DictDEPParser but accepts a file descriptor from
which to read the JSON instead of an already parsed dictionary structure.
The file is read in its entirety on the first call to parse() and JSON
parsed contents are kept in memory. Subsequent calls reuse these contents.
"""
def __init__(self, fd, nparts = 1):
self.fd = fd
self.nparts = nparts
self.dictParser = None
def parse(self, chunksize = 0):
if not self.dictParser:
try:
dep = utils.readJsonStream(self.fd)
except (IOError, UnicodeDecodeError, ValueError) as e:
raise DEPParseException(_('Malformed JSON: {}.').format(e))
self.dictParser = DictDEPParser(dep, self.nparts)
return self.dictParser.parse(chunksize)
def receiptGroupAdapter(depgen):
for chunk in depgen:
for recs, cert, cert_list in chunk:
rec_tuples = [ receipt.Receipt.fromJWSString(expandDEPReceipt(r))
for r in recs ]
recs = None
yield (rec_tuples, cert, cert_list)
rec_tuples = None
chunk = None
| ztp-at/RKSV | librksv/depparser.py | Python | agpl-3.0 | 26,170 |
<?php
/*** COPYRIGHT NOTICE *********************************************************
*
* Copyright 2009-2016 ProjeQtOr - Pascal BERNARD - support@projeqtor.org
* Contributors : -
*
* This file is part of ProjeQtOr.
*
* ProjeQtOr 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.
*
* ProjeQtOr 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
* ProjeQtOr. If not, see <http://www.gnu.org/licenses/>.
*
* You can get complete code of ProjeQtOr, other resource, help and information
* about contributors at http://www.projeqtor.org
*
*** DO NOT REMOVE THIS NOTICE ************************************************/
/** ============================================================================
* Milestone is a target or entry key point
*/
require_once('_securityCheck.php');
class Milestone extends MilestoneMain {
/** ==========================================================================
* Constructor
* @param $id the id of the object in the database (null if not stored yet)
* @return void
*/
function __construct($id = NULL, $withoutDependentObjects=false) {
parent::__construct($id,$withoutDependentObjects);
}
/** ==========================================================================
* Destructor
* @return void
*/
function __destruct() {
parent::__destruct();
}
}
?> | papjul/projeqtor | model/Milestone.php | PHP | agpl-3.0 | 1,837 |
def migrate(cr, version):
if not version:
return
# Replace ids of better_zip by ids of city_zip
cr.execute("""
ALTER TABLE crm_event_compassion
DROP CONSTRAINT crm_event_compassion_zip_id_fkey;
UPDATE crm_event_compassion e
SET zip_id = (
SELECT id FROM res_city_zip
WHERE openupgrade_legacy_12_0_better_zip_id = e.zip_id)
""")
| CompassionCH/compassion-modules | crm_compassion/migrations/12.0.1.0.0/pre-migration.py | Python | agpl-3.0 | 409 |
function humanize(string) {
string = string.replace(/-/g, ' ');
string = string.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
return string;
}
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 32;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
}
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var generateUserToken = function( m_conn ) {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
token = S4()+S4()+S4()+S4()+S4()+S4();
m_conn.set( memcachePrefix + token, '1', memcache_memorize_time, function( err ) {
if (err) {
if (debug) console.log("MEMCACHE ERROR DURING SET");
}
});
return token;
}
| ronanguilloux/Javascript-helpers | String.js | JavaScript | agpl-3.0 | 1,257 |
#!/bin/bash
exec `dirname $0`/jruby.sh -S irb $@
| stuartsierra/altlaw-backend | script/jirb.sh | Shell | agpl-3.0 | 50 |
package endpoints
import (
"encoding/json"
"fmt"
"net/http"
log "github.com/Sirupsen/logrus"
)
// MkdirHandler implements http.Handler.
type MkdirHandler struct {
*State
}
// NewMkdirHandler creates a new mkdir handler.
func NewMkdirHandler(s *State) *MkdirHandler {
return &MkdirHandler{State: s}
}
// MkdirRequest is the request that can be sent to this endpoint as JSON.
type MkdirRequest struct {
// Path to create.
Path string `json:"path"`
}
func (mh *MkdirHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
mkdirReq := MkdirRequest{}
if err := json.NewDecoder(r.Body).Decode(&mkdirReq); err != nil {
jsonifyErrf(w, http.StatusBadRequest, "bad json")
return
}
if !mh.validatePath(mkdirReq.Path, w, r) {
jsonifyErrf(w, http.StatusUnauthorized, "path forbidden")
return
}
if err := mh.fs.Mkdir(mkdirReq.Path, true); err != nil {
log.Debugf("failed to mkdir %s: %v", mkdirReq.Path, err)
jsonifyErrf(w, http.StatusInternalServerError, "failed to mkdir")
return
}
msg := fmt.Sprintf("mkdir'd »%s«", mkdirReq.Path)
if !mh.commitChange(msg, w, r) {
return
}
jsonifySuccess(w)
}
| disorganizer/brig | gateway/endpoints/mkdir.go | GO | agpl-3.0 | 1,133 |
<?php
#
# Copyright (c) 2000-2007 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/>.
#
# }}}
#
#
# Wrapper Wrapper script for cvsweb.cgi
#
chdir("../");
require("defs.php3");
# Must be logged in.
$this_user = CheckLoginOrDie();
$uid = $this_user->uid();
$isadmin = ISADMIN();
#
# Verify form arguments.
#
$optargs = OptionalPageArguments("template", PAGEARG_TEMPLATE,
"project", PAGEARG_PROJECT,
"embedded", PAGEARG_BOOLEAN);
if (!isset($embedded)) {
$embedded = 0;
}
#
# Form the real url.
#
$newurl = preg_replace("/cvswebwrap/", "cvsweb", $_SERVER['REQUEST_URI']);
$newurl = preg_replace("/php3/","php3/",$newurl);
#
# Standard Testbed Header
#
PAGEHEADER("Emulab CVS Repository");
if (isset($project)) {
;
}
elseif (isset($template)) {
echo $template->PageHeader();
}
echo "<div><iframe src='$newurl' class='outputframe' ".
"id='outputframe' name='outputframe'></iframe></div>\n";
echo "</center><br>\n";
echo "<script type='text/javascript' language='javascript'>\n";
echo "SetupOutputArea('outputframe', false);\n";
echo "</script>\n";
#
# Standard Testbed Footer
#
PAGEFOOTER();
?>
| nmc-probe/emulab-nome | www/cvsweb/cvswebwrap.php3 | PHP | agpl-3.0 | 1,865 |
<widget ng-if="vm.account" widget-name="'Account info'" widget-scrollable="true" class="js-cq-widget-container">
<widget-header>
<div class="widget-label"></div>
<div class="widget-name">
<i class="lilicon hl-company-icon"></i>
<a ng-if="vm.clickableHeader && !vm.account.is_deleted" ui-sref="base.accounts.detail({ id: vm.settings.email.data.account.id || vm.account.id })">{{ vm.account.name }}</a>
<span ng-if="!vm.clickableHeader || vm.account.is_deleted">{{ vm.account.name }}</span>
</div>
</widget-header>
<widget-filters>
<a ng-href="{{ vm.tenant.primary_external_app_link.getUrl(vm.account.customer_id) }}" target="_blank" class="hl-primary-btn" ng-if="vm.account.customer_id && vm.tenant.primary_external_app_link">
<i class="fa fa-external-link fa-sm"></i>
<span class="external-link-name">{{ vm.tenant.primary_external_app_link.name }}</span>
</a>
</widget-filters>
<widget-body>
<table class="widget-table vertical-top-align">
<tbody>
<tr>
<td><i class="lilicon hl-status-icon"></i> <strong>Status</strong></td>
<td>
<editable-select field="status" view-model="vm" type="Account">{{ vm.account.status.name }}</editable-select>
</td>
</tr>
<tr>
<td><i class="lilicon hl-mail-icon"></i> <strong>Email</strong></td>
<td>
<editable-related model="vm.account" type="Account" field="email_addresses"></editable-related>
</td>
</tr>
<tr>
<td><i class="lilicon hl-phone-icon"></i> <strong>Phone</strong></td>
<td>
<editable-related model="vm.account" type="Account" field="phone_numbers"></editable-related>
</td>
</tr>
<tr>
<td><i class="fa fa-globe"></i> <strong>Website</strong></td>
<td>
<editable-related model="vm.account" type="Account" field="websites"></editable-related>
</td>
</tr>
<tr>
<td><i class="lilicon hl-entity-icon"></i> <strong>Assigned to</strong></td>
<td>
<editable-select field="assigned_to" view-model="vm" type="Account" search="true"
select-options="{type: 'User', field: 'assignOptions', display: 'full_name', sortColumn: 'full_name', nameColumn: 'full_name'}">
{{ vm.account.assigned_to.full_name || 'Nobody' }}
</editable-select>
<div ng-if="vm.account.assigned_to.id != vm.currentUser.id">
<button class="hl-primary-btn-link" ng-click="vm.assignAccount()">Assign to me</button>
</div>
</td>
</tr>
<tr>
<td><i class="fa fa-map-marker"></i> <strong>Address</strong></td>
<td>
<editable-related model="vm.account" type="Account" field="addresses"></editable-related>
</td>
</tr>
<tr>
<td><i class="fa fa-twitter"></i> <strong>Twitter</strong></td>
<td>
<editable-link view-model="vm" type="Account" object="vm.account.twitter" field="username" social-media-name="twitter">
<a ng-if="vm.account.twitter" ng-href="{{ vm.account.twitter.profile_url }}" target="_blank" rel="noopener noreferrer">{{ vm.account.twitter.username }}</a>
<span ng-if="!vm.account.twitter">No Twitter profile</span>
</editable-link>
</td>
</tr>
<tr>
<td><i class="lilicon hl-entity-icon"></i> <strong>Customer ID</strong></td>
<td>
<editable-text field="customer_id" object="vm.account" update-callback="vm.updateModel">{{ vm.account.customer_id || 'No customer id' }}</editable-text>
</td>
</tr>
<tr>
<td><i class="fa fa-tag"></i> <strong>Tags</strong></td>
<td>
<editable-tags view-model="vm" type="account"></editable-tags>
</td>
</tr>
<tr>
<td colspan="2">
<strong class="m-b-5">Description</strong>
<div>
<editable-textarea view-model="vm" field="description" object="vm.account"></editable-textarea>
</div>
</td>
</tr>
</tbody>
</table>
</widget-body>
</widget>
| HelloLily/hellolily | frontend/app/accounts/directives/detail_widget.html | HTML | agpl-3.0 | 5,116 |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import $ from 'jquery'
import _ from 'lodash'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.min.js'
require('jquery-ui-bundle');
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App }
});
| elebymax/Scheduler | src/main.js | JavaScript | agpl-3.0 | 448 |
<?php foreach($pager->getResults() as $c)
{
$nomPartial = (isset($partial)) ? 'show'.ucfirst($partial).'Commentaire' : 'showCommentaire';
$options = array('c' => $c);
if (isset($presentation)) $options = array_merge($options, array('presentation' => $presentation));
include_partial($nomPartial, $options); ?>
<?php } ?>
<?php if ($pager->haveToPaginate()) :
$uri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$uri = preg_replace('/page=\d+\&?/', '', $uri);
if (!preg_match('/[\&\?]$/', $uri)) {
if (preg_match('/\?/', $uri)) {
$uri .= '&';
}else{
$uri .= '?';
}
}
include_partial('parlementaire/paginate', array('pager'=>$pager, 'link'=>$uri));
endif;
| regardscitoyens/nosdeputes.fr | apps/frontend/modules/commentaire/templates/_pager.php | PHP | agpl-3.0 | 691 |
#!/usr/bin/env bash
THIS_DIR=$(cd $(dirname $0); pwd)
cd $THIS_DIR
update() {
git pull
git submodule update --init --recursive
install_rocks
}
# Will install luarocks on THIS_DIR/.luarocks
install_luarocks() {
git clone https://github.com/keplerproject/luarocks.git
cd luarocks
git checkout tags/v2.2.1 # Current stable
PREFIX="$THIS_DIR/.luarocks"
./configure --prefix=$PREFIX --sysconfdir=$PREFIX/luarocks --force-config
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
make build && make install
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting.";exit $RET;
fi
cd ..
rm -rf luarocks
}
install_rocks() {
./.luarocks/bin/luarocks install luasocket
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install oauth
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install redis-lua
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install lua-cjson
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install fakeredis
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install luafilesystem
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install lub
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install luaexpat
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install xml
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install feedparser
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
./.luarocks/bin/luarocks install serpent
RET=$?; if [ $RET -ne 0 ];
then echo "Error. Exiting."; exit $RET;
fi
}
install() {
git pull
git submodule update --init --recursive
patch -i "patches/disable-python-and-libjansson.patch" -p 0 --batch --forward
RET=$?;
cd tg
if [ $RET -ne 0 ]; then
autoconf -i
fi
./configure && make
RET=$?; if [ $RET -ne 0 ]; then
echo "Error. Exiting."; exit $RET;
fi
cd ..
install_luarocks
install_rocks
}
if [ "$1" = "install" ]; then
install
elif [ "$1" = "update" ]; then
update
else
if [ ! -f ./tg/telegram.h ]; then
echo "tg not found"
echo "Run $0 install"
exit 1
fi
if [ ! -f ./tg/bin/telegram-cli ]; then
echo "tg binary not found"
echo "Run $0 install"
exit 1
fi
./tg/bin/telegram-cli -k ./tg/tg-server.pub -s ./bot/TeamTopbot.lua -l 1 -E $@
fi
| ahmedjabbar1/TeamTop | launch.sh | Shell | agpl-3.0 | 2,776 |
#####Use Case ID: UC-TS10
#####Use Case Name: Update Code System Version Status
**Level:** User Level Goal
**Primary Actors:** Terminology Author
**Purpose:** The main intent of this use case is to update code system version status in a terminology service.
**Pre Condition:** Terminology Author must be identified and authenticated.
**Post Condition:** Code system status will be updated successfully.
**Frequency of Occurrence:** low
**Conformance:** CTS2 (Common Terminology Standard)
**Priority:** Low
__________________________________________________________
**Main Success Scenario: (Update Code System Version Status)**
1. Terminology Author requests to update code system version status.
2. System displays the list the code systems.
3. User selects the code system to status update.
4. System asks user to modify the specified code system version status.
5. User modifies the code system version status.
6. System records code system successfully.
7. The system will also notify users who registered for content update notifications.
__________________________________________________________
**Alternate Flows**
**Alt-1:**
1. Code System Version Identifier does not exist.
2. Invalid state change.
_______________________________________________________________
**Open Issues**
-NA-
_______________________________________________________________
**Reference Hl7 V3 Interaction Identifiers:**
-NA-
_______________________________________________________________
**Reference CCHIT Criteria:**
-NA-
_______________________________________________________________
**Reference Hl7 RMIM (Domain: CTS):** [More Details](http://www.hl7.org/implement/standards/product_brief.cfm?product_id=306)
-NA-
_______________________________________________________________
**Reference FHIR Resource:** [More Details](http://www.hl7.org/implement/standards/fhir/resourcelist.html)
-NA-
_______________________________________________________________
**Reference CDA Template:** [More Details](http://www.hl7.org/Special/committees/structure/index.cfm)
-NA-
_______________________________________________________________
**Reference OpenEHR Archetypes (Version 1.4):** [More Details](http://www.openehr.org/ckm/)
-NA-
| semr/specs | terminology-service/manage-code-system/update-code-system-version-status.md | Markdown | agpl-3.0 | 2,346 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-08-13 03:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0036_auto_20170813_0049'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='follows',
field=models.ManyToManyField(blank=True, related_name='follower', to='website.UserProfile'),
),
]
| goyal-sidd/BLT | website/migrations/0037_auto_20170813_0319.py | Python | agpl-3.0 | 510 |
DELETE FROM `weenie` WHERE `class_Id` = 10654;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (10654, 'housevilla962', 53, '2019-02-10 00:00:00') /* House */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (10654, 1, 128) /* ItemType - Misc */
, (10654, 5, 10) /* EncumbranceVal */
, (10654, 16, 1) /* ItemUseable - No */
, (10654, 93, 52) /* PhysicsState - Ethereal, IgnoreCollisions, NoDraw */
, (10654, 155, 2) /* HouseType - Villa */
, (10654, 8041, 101) /* PCAPRecordedPlacement - Resting */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (10654, 1, True ) /* Stuck */
, (10654, 24, True ) /* UiHidden */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (10654, 39, 0.1) /* DefaultScale */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (10654, 1, 'Villa') /* Name */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (10654, 1, 0x02000A42) /* Setup */
, (10654, 8, 0x0600218E) /* Icon */
, (10654, 30, 152) /* PhysicsScript - RestrictionEffectBlue */
, (10654, 8001, 236978192) /* PCAPRecordedWeenieHeader - Usable, Burden, HouseOwner, HouseRestrictions, PScript */
, (10654, 8003, 148) /* PCAPRecordedObjectDesc - Stuck, Attackable, UiHidden */
, (10654, 8005, 163969) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, Position, AnimationFrame */;
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 (10654, 8040, 0xDE7A016C, 162.739, 89.7574, 3.9995, -0.7136, 0, 0, 0.700553) /* PCAPRecordedLocation */
/* @teleloc 0xDE7A016C [162.739000 89.757400 3.999500] -0.713600 0.000000 0.000000 0.700553 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (10654, 8000, 0x7DE7A08B) /* PCAPRecordedObjectIID */;
| ACEmulator/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/House/Villa/10654 Villa.sql | SQL | agpl-3.0 | 2,087 |
/*
Copyright (c) 2014-2021 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/
#include "IpBanMgr.h"
#include <utility>
#include <Logging/Logger.hpp>
#include <Database/Database.h>
#include "Server/Master.hpp"
#include <Log.hpp>
IpBanMgr& IpBanMgr::getInstance()
{
static IpBanMgr mInstance;
return mInstance;
}
void IpBanMgr::initialize()
{
sLogger.info("IpBanMgr : Started loading bans");
reload();
sLogger.info("IpBanMgr : loaded %u IP bans.", static_cast<uint32_t>(_ipBanList.size()));
}
void IpBanMgr::reload()
{
ipBanMutex.Acquire();
_ipBanList.clear();
QueryResult* result = sLogonSQL->Query("SELECT ip, expire FROM ipbans");
if (result)
{
do
{
std::string ipString = result->Fetch()[0].GetString();
const uint32_t expireTime = result->Fetch()[1].GetUInt32();
std::string smask = "32";
std::string::size_type i = ipString.find('/');
std::string stmp = ipString.substr(0, i);
if (i == std::string::npos)
sLogger.info("IP ban '%s' netmask not specified. assuming /32", ipString.c_str());
else
smask = ipString.substr(i + 1);
const unsigned int ipraw = MakeIP(stmp.c_str());
const unsigned int ipmask = atoi(smask.c_str());
if (ipraw == 0 || ipmask == 0)
{
sLogger.failure("IP ban '%s' could not be parsed. Ignoring", ipString.c_str());
continue;
}
IPBan ipBan;
ipBan.Bytes = static_cast<unsigned char>(ipmask);
ipBan.Mask = ipraw;
ipBan.Expire = expireTime;
ipBan.db_ip = ipString;
_ipBanList.push_back(ipBan);
} while (result->NextRow());
delete result;
}
ipBanMutex.Release();
}
bool IpBanMgr::add(std::string ip, uint32_t duration)
{
const std::string& ipString = ip;
const std::string::size_type i = ipString.find('/');
if (i == std::string::npos)
return false;
std::string stmp = ipString.substr(0, i);
std::string smask = ipString.substr(i + 1);
const unsigned int ipraw = MakeIP(stmp.c_str());
const unsigned int ipmask = atoi(smask.c_str());
if (ipraw == 0 || ipmask == 0)
return false;
IPBan ipBan;
ipBan.db_ip = ipString;
ipBan.Bytes = static_cast<unsigned char>(ipmask);
ipBan.Mask = ipraw;
ipBan.Expire = duration;
ipBanMutex.Acquire();
_ipBanList.push_back(ipBan);
ipBanMutex.Release();
return true;
}
bool IpBanMgr::remove(const std::string& ip)
{
ipBanMutex.Acquire();
for (auto itr = _ipBanList.begin(); itr != _ipBanList.end();)
{
if (itr->db_ip == ip)
{
_ipBanList.erase(itr);
ipBanMutex.Release();
return true;
}
++itr;
}
ipBanMutex.Release();
return false;
}
IpBanStatus IpBanMgr::getBanStatus(in_addr ip_address)
{
ipBanMutex.Acquire();
for (auto itr2 = _ipBanList.begin(); itr2 != _ipBanList.end();)
{
const auto bannedIp = itr2;
++itr2;
if (ParseCIDRBan(ip_address.s_addr, bannedIp->Mask, bannedIp->Bytes))
{
if (bannedIp->Expire == 0)
{
ipBanMutex.Release();
return BAN_STATUS_PERMANENT_BAN;
}
if (static_cast<uint32_t>(UNIXTIME) >= bannedIp->Expire)
{
sLogonSQL->Execute("DELETE FROM ipbans WHERE expire = %u AND ip = \"%s\"", bannedIp->Expire, sLogonSQL->EscapeString(bannedIp->db_ip).c_str());
_ipBanList.erase(bannedIp);
}
else
{
ipBanMutex.Release();
return BAN_STATUS_TIME_LEFT_ON_BAN;
}
}
}
ipBanMutex.Release();
return BAN_STATUS_NOT_BANNED;
}
| Appled/AscEmu | src/logonserver/Server/IpBanMgr.cpp | C++ | agpl-3.0 | 4,001 |
/**
* Copyright (C) 2009-2014 BIMserver.org
*
* 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.bimserver.models.ifc4;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* 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 {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
public interface IfcWarpingMomentMeasure extends IfcDerivedMeasureValue, IfcWarpingStiffnessSelect {
/**
* Returns the value of the '<em><b>Wrapped Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Wrapped Value</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Wrapped Value</em>' attribute.
* @see #isSetWrappedValue()
* @see #unsetWrappedValue()
* @see #setWrappedValue(double)
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcWarpingMomentMeasure_WrappedValue()
* @model unsettable="true"
* @generated
*/
double getWrappedValue();
/**
* Sets the value of the '{@link org.bimserver.models.ifc4.IfcWarpingMomentMeasure#getWrappedValue <em>Wrapped Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Wrapped Value</em>' attribute.
* @see #isSetWrappedValue()
* @see #unsetWrappedValue()
* @see #getWrappedValue()
* @generated
*/
void setWrappedValue(double value);
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcWarpingMomentMeasure#getWrappedValue <em>Wrapped Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetWrappedValue()
* @see #getWrappedValue()
* @see #setWrappedValue(double)
* @generated
*/
void unsetWrappedValue();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcWarpingMomentMeasure#getWrappedValue <em>Wrapped Value</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Wrapped Value</em>' attribute is set.
* @see #unsetWrappedValue()
* @see #getWrappedValue()
* @see #setWrappedValue(double)
* @generated
*/
boolean isSetWrappedValue();
/**
* Returns the value of the '<em><b>Wrapped Value As String</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Wrapped Value As String</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Wrapped Value As String</em>' attribute.
* @see #isSetWrappedValueAsString()
* @see #unsetWrappedValueAsString()
* @see #setWrappedValueAsString(String)
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcWarpingMomentMeasure_WrappedValueAsString()
* @model unsettable="true"
* annotation="asstring"
* annotation="hidden"
* @generated
*/
String getWrappedValueAsString();
/**
* Sets the value of the '{@link org.bimserver.models.ifc4.IfcWarpingMomentMeasure#getWrappedValueAsString <em>Wrapped Value As String</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Wrapped Value As String</em>' attribute.
* @see #isSetWrappedValueAsString()
* @see #unsetWrappedValueAsString()
* @see #getWrappedValueAsString()
* @generated
*/
void setWrappedValueAsString(String value);
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcWarpingMomentMeasure#getWrappedValueAsString <em>Wrapped Value As String</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetWrappedValueAsString()
* @see #getWrappedValueAsString()
* @see #setWrappedValueAsString(String)
* @generated
*/
void unsetWrappedValueAsString();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcWarpingMomentMeasure#getWrappedValueAsString <em>Wrapped Value As String</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Wrapped Value As String</em>' attribute is set.
* @see #unsetWrappedValueAsString()
* @see #getWrappedValueAsString()
* @see #setWrappedValueAsString(String)
* @generated
*/
boolean isSetWrappedValueAsString();
} // IfcWarpingMomentMeasure
| opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc4/IfcWarpingMomentMeasure.java | Java | agpl-3.0 | 5,807 |
<?php
# Copyright 2003-2015 Opmantek Limited (www.opmantek.com)
#
# ALL CODE MODIFICATIONS MUST BE SENT TO CODE@OPMANTEK.COM
#
# This file is part of Open-AudIT.
#
# Open-AudIT 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.
#
# Open-AudIT 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 Open-AudIT (most likely in a file named LICENSE).
# If not, see <http://www.gnu.org/licenses/>
#
# For further information on Open-AudIT or for a license other than AGPL please see
# www.opmantek.com or email contact@opmantek.com
#
# *****************************************************************************
/**
* @author Mark Unwin <marku@opmantek.com>
*
* @version 1.12.6
*
* @copyright Copyright (c) 2014, Opmantek
* @license http://www.gnu.org/licenses/agpl-3.0.html aGPL v3
*/
class M_attachment extends MY_Model
{
public function __construct()
{
parent::__construct();
}
public function create_system_attachment($system_id, $attachment_title, $attachment_name)
{
$sql = "INSERT INTO sys_man_attachment (att_id, system_id, user_id, att_title, att_filename, timestamp) VALUES (NULL, ?, ?, ?, ?, ?)";
$sql = $this->clean_sql($sql);
$data = array("$system_id", $this->session->userdata['user_id'], "$attachment_title", "$attachment_name", date('Y-m-d H:i:s'));
$query = $this->db->query($sql, $data);
echo $this->db->last_query();
return;
}
public function get_system_attachment($system_id)
{
$sql = "SELECT * FROM sys_man_attachment WHERE system_id = ?";
$sql = $this->clean_sql($sql);
$data = array("$system_id");
$query = $this->db->query($sql, $data);
$result = $query->result();
return ($result);
}
public function get_attachment($attachment_id)
{
$sql = "SELECT * FROM sys_man_attachment WHERE att_id = ?";
$sql = $this->clean_sql($sql);
$data = array("$attachment_id");
$query = $this->db->query($sql, $data);
$result = $query->result();
return ($result[0]);
}
public function delete_attachment($attachment_id)
{
$sql = "DELETE FROM sys_man_attachment WHERE att_id = ?";
$sql = $this->clean_sql($sql);
$data = array("$attachment_id");
$query = $this->db->query($sql, $data);
#$result = $query->result();
return;
}
}
| wnoisephx/OpenAuditMT | code_igniter/application/models/m_attachment.php | PHP | agpl-3.0 | 2,876 |
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 Asqatasun.org
*
* 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/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa32016;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.entity.audit.ProcessResult;
import org.asqatasun.rules.rgaa32016.test.Rgaa32016RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 13.3.1 of the referential RGAA 3.2016
*
* @author
*/
public class Rgaa32016Rule130301Test extends Rgaa32016RuleImplementationTestCase {
/**
* Default constructor
* @param testName
*/
public Rgaa32016Rule130301Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.asqatasun.rules.rgaa32016.Rgaa32016Rule130301");
}
@Override
protected void setUpWebResourceMap() {
// addWebResource("Rgaa32016.Test.13.3.1-1Passed-01");
// addWebResource("Rgaa32016.Test.13.3.1-2Failed-01");
addWebResource("Rgaa32016.Test.13.3.1-3NMI-01");
// addWebResource("Rgaa32016.Test.13.3.1-4NA-01");
}
@Override
protected void setProcess() {
//----------------------------------------------------------------------
//------------------------------1Passed-01------------------------------
//----------------------------------------------------------------------
// checkResultIsPassed(processPageTest("Rgaa32016.Test.13.3.1-1Passed-01"), 1);
//----------------------------------------------------------------------
//------------------------------2Failed-01------------------------------
//----------------------------------------------------------------------
// ProcessResult processResult = processPageTest("Rgaa32016.Test.13.3.1-2Failed-01");
// checkResultIsFailed(processResult, 1, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.FAILED,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------3NMI-01---------------------------------
//----------------------------------------------------------------------
ProcessResult processResult = processPageTest("Rgaa32016.Test.13.3.1-3NMI-01");
checkResultIsNotTested(processResult); // temporary result to make the result buildable before implementation
// checkResultIsPreQualified(processResult, 2, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.NEED_MORE_INFO,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------4NA-01------------------------------
//----------------------------------------------------------------------
// checkResultIsNotApplicable(processPageTest("Rgaa32016.Test.13.3.1-4NA-01"));
}
@Override
protected void setConsolidate() {
// The consolidate method can be removed when real implementation is done.
// The assertions are automatically tested regarding the file names by
// the abstract parent class
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa32016.Test.13.3.1-3NMI-01").getValue());
}
}
| dzc34/Asqatasun | rules/rules-rgaa3.2016/src/test/java/org/asqatasun/rules/rgaa32016/Rgaa32016Rule130301Test.java | Java | agpl-3.0 | 4,471 |
<?php
/**
* plentymarkets shopware connector
* Copyright © 2013 plentymarkets GmbH
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License, supplemented by an additional
* permission, and of our proprietary license can be found
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "plentymarkets" is a registered trademark of plentymarkets GmbH.
* "shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, titles and interests in the
* above trademarks remain entirely with the trademark owners.
*
* @copyright Copyright (c) 2013, plentymarkets GmbH (http://www.plentymarkets.com)
* @author Daniel Bächtle <daniel.baechtle@plentymarkets.com>
*/
require_once PY_COMPONENTS . 'Mapping/Entity/PlentymarketsMappingEntityAbstract.php';
/**
* PlentymarketsMappingEntityItem provides the actual item mapping functionality.
* Like the other mapping entities this class is called in PlentymarketsMappingController. This entity
* inherits the most methods from the entity class PlentymarketsMappingEntityAbstract.
*
* @author Daniel Bächtle <daniel.baechtle@plentymarkets.com>
*/
class PlentymarketsMappingEntityItem extends PlentymarketsMappingEntityAbstract
{
/**
* Returns the name of the database table
*
* @return string
*/
protected function getName()
{
return 'plenty_mapping_item';
}
}
| k-30/plentymarkets-shopware-connector | Components/Mapping/Entity/PlentymarketsMappingEntityItem.php | PHP | agpl-3.0 | 1,889 |
# frozen_string_literal: true
FactoryBot.define do
data = {
'conceptID' => 'Jl4ByYtUfo4VhIKpMt23yA',
'cues' => [''],
'cuesLabel' => '',
'flag' => 'production',
'focusPoints' => {
'-LNLfzKfwaoZUVeSIH8o' => {
'conceptResults' => {
'Jl4ByYtUfo4VhIKpMt23yA' => {
'conceptUID' => 'Jl4ByYtUfo4VhIKpMt23yA',
'correct' => false,
'name' => 'Structure | Compound Subjects, Objects, and Predicates | Compound Subjects'
}
},
'feedback' => '<p>Revise your work. Use the hint as an example of how to combine the sentences.</p>',
'order' => 1,
'text' => 'and'
}
},
'incorrectSequences' => {
'0' => {
'conceptResults' => {
'GiUZ6KPkH958AT8S413nJg' => {
'conceptUID' => 'GiUZ6KPkH958AT8S413nJg',
'correct' => false,
'name' => 'Conjunctions | Coordinating Conjunctions | Comma Before Coordinating Conjunctions'
}
},
'feedback' => '<p>Revise your work. Look at the hint, and update your punctuation.</p>',
'text' => 'ter [Bb]ut ([Ss]om|[Mm]os)|||[Bb]ut( )?,'
},
'1' => {
'conceptResults' => {
'tN84RPXWJwYBUh-LJn7xRA' => {
'conceptUID' => 'tN84RPXWJwYBUh-LJn7xRA',
'correct' => false,
'name' => 'Adjectives & Adverbs | Adjective Structures | Paired Coordinate Adjectives'
}
},
'feedback' => '<p>Revise your work. When two describing words can go in any order (like <em>warm</em> and <em>shallow</em>), join them with a comma.</p>',
'text' => 'arm sha|||low war|||arm( )?(,)?( )?and( )?(,)?( )?sha|||low( )?(,)?( )?and( )?(,)?( )?war'
},
'2' => {
'conceptResults' => {
'Q8FfGSv4Z9L2r1CYOfvO9A' => {
'conceptUID' => 'Q8FfGSv4Z9L2r1CYOfvO9A',
'correct' => false,
'name' => 'Conjunctions | Subordinating Conjunctions | Subordinating Conjunctions at the Beginning of a Sentence'
}
},
'feedback' => '<p>Revise your work. Look at the hint, and update your punctuation.</p>',
'text' => '^([Aa]lt|[Tt]ho|[Ee]ve|[Ww]hil)&&ter(s)? ([Ss]om|[Mm]os)'
},
'3' => {
'conceptResults' => {
'nb0JW1r5pRB5ouwAzTgMbQ' => {
'conceptUID' => 'nb0JW1r5pRB5ouwAzTgMbQ',
'correct' => false,
'name' => 'Conjunctions | Subordinating Conjunctions | Subordinating Conjunction in the Middle of a Sentence'
}
},
'feedback' => '<p>Revise your work. Look at the hint, and update your punctuation.</p>',
'text' => ', ( )?([Aa]lt|[Ee]ve|[Tt]ho|[Ww]hil)'
},
'-Lg8q380379SvrQOz_kx' => {
'conceptResults' => {
'N5VXCdTAs91gP46gATuvPQ' => {
'conceptUID' => 'N5VXCdTAs91gP46gATuvPQ',
'correct' => false,
'name' => 'Structure | Sentence Quality | Including Details From Prompt'
}
},
'feedback' => '<p>Revise your work. Make <em>coral reef</em> plural to show that there's more than one.</p>',
'text' => 'reef(?!s)'
},
'-Lg8vs_PALeRY87EO1LU' => {
'conceptResults' => {
'QYHg1tpDghy5AHWpsIodAg' => {
'conceptUID' => 'QYHg1tpDghy5AHWpsIodAg',
'correct' => false,
'name' => 'Structure | Sentence Quality | Writing Concise Sentences'
}
},
'feedback' => '<p>Revise your work. Make your sentence more concise by removing the words <em>of them</em>.</p>',
'text' => '(some|most) of them'
},
'-Lg9CmPJ3cF0IxX1YtbW' => {
'conceptResults' => {
'VvW4L8CA5Oi8N4aNQ7bFdg' => {
'conceptUID' => 'VvW4L8CA5Oi8N4aNQ7bFdg',
'correct' => false,
'name' => 'Nouns & Pronouns | Pronoun Antecedent Agreement | Pronoun Reference'
}
},
'feedback' => '<p>Revise your work. Move <em>coral reefs</em> earlier in the sentence so it's clear what you're talking about.</p>',
'text' => '^([Mm]ost|[Ss]ome) form&&[Cc]or'
},
'-Lg9K-VWW12CozHkfTk5' => {
'conceptResults' => {
'QYHg1tpDghy5AHWpsIodAg' => {
'conceptUID' => 'QYHg1tpDghy5AHWpsIodAg',
'correct' => false,
'name' => 'Structure | Sentence Quality | Writing Concise Sentences'
}
},
'feedback' => '<p>Revise your work. Make your sentence more concise by only saying <em>reefs </em>once.</p>',
'text' => 'but (some|most) ree&&ral re'
}
},
'instructions' => '',
'itemLevel' => '',
'modelConceptUID' => 'Jl4ByYtUfo4VhIKpMt23yA',
'prompt' => '<p>The moon is smaller than the sun.</p><p>Earth is smaller than the sun.</p>'
}
factory :question do
uid { SecureRandom.uuid }
data data
question_type "connect_sentence_combining"
end
end
| empirical-org/Empirical-Core | services/QuillLMS/spec/factories/question.rb | Ruby | agpl-3.0 | 5,023 |
<?php /* Smarty version 2.6.11, created on 2017-06-02 12:25:22
compiled from themes/Sugar5/tpls/_head.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'sugar_getimagepath', 'themes/Sugar5/tpls/_head.tpl', 52, false),array('function', 'sugar_getjspath', 'themes/Sugar5/tpls/_head.tpl', 61, false),)), $this); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html <?php echo $this->_tpl_vars['langHeader']; ?>
>
<head>
<link rel="SHORTCUT ICON" href="<?php echo $this->_tpl_vars['FAVICON_URL']; ?>
">
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $this->_tpl_vars['APP']['LBL_CHARSET']; ?>
">
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title><?php echo $this->_tpl_vars['APP']['LBL_BROWSER_TITLE']; ?>
</title>
<?php echo $this->_tpl_vars['SUGAR_CSS']; ?>
<?php echo $this->_tpl_vars['SUGAR_JS']; ?>
<?php echo '
<script type="text/javascript">
<!--
SUGAR.themes.theme_name = \''; echo $this->_tpl_vars['THEME']; echo '\';
SUGAR.themes.theme_ie6compat = '; echo $this->_tpl_vars['THEME_IE6COMPAT']; echo ';
SUGAR.themes.hide_image = \''; echo smarty_function_sugar_getimagepath(array('file' => "hide.gif"), $this); echo '\';
SUGAR.themes.show_image = \''; echo smarty_function_sugar_getimagepath(array('file' => "show.gif"), $this); echo '\';
SUGAR.themes.loading_image = \''; echo smarty_function_sugar_getimagepath(array('file' => "img_loading.gif"), $this); echo '\';
SUGAR.themes.allThemes = eval('; echo $this->_tpl_vars['allThemes']; echo ');
if ( YAHOO.env.ua )
UA = YAHOO.env.ua;
-->
</script>
'; ?>
<script type="text/javascript" src='<?php echo smarty_function_sugar_getjspath(array('file' => "cache/include/javascript/sugar_field_grp.js"), $this);?>
'></script>
</head> | witxo/bonos | cache/smarty/templates_c/%%02^028^028621F5%%_head.tpl.php | PHP | agpl-3.0 | 1,918 |
import { fromNullable } from 'fp-ts/lib/Option';
import { queryK } from 'sdi/shape';
import { uuid } from 'sdi/source';
const attachments = queryK('data/attachments');
export const getAttachments =
() => attachments();
export const getAttachment =
(id: uuid) => fromNullable(attachments().find(a => a.id === id));
| be-lb/sdi-clients | view/src/queries/attachments.ts | TypeScript | agpl-3.0 | 328 |
module Ontology::Distributed
extend ActiveSupport::Concern
included do
def self.homogeneous
select_with_character_selector(HOMOGENEOUS_SELECTOR)
end
def self.heterogeneous
select_with_character_selector(HETEROGENEOUS_SELECTOR)
end
def self.heterogeneous_children
where(parent_id: self.heterogeneous)
end
# Fetches homogeneous Ontologies which are distributed
# and have children in the logic
def self.distributed_in(logic)
distributed_with(logic, HOMOGENEOUS_SELECTOR)
end
# Fetches heterogeneous Ontologies which are distributed
# and have children in the logic
def self.also_distributed_in(logic)
distributed_with(logic, HETEROGENEOUS_SELECTOR)
end
private
HOMOGENEOUS_SELECTOR = '='
HETEROGENEOUS_SELECTOR = '>'
def self.distributed_with(logic, selector='=')
query = <<-STMT
WITH parents AS (
SELECT (ontologies.parent_id) AS id FROM ontologies WHERE ontologies.logic_id = #{logic.id}
)
SELECT * FROM ontologies JOIN parents ON ontologies.parent_id = parents.id
STMT
select_with_character_selector(selector, query)
end
def self.select_with_character_selector(selector="=", ontologies_query=nil)
query = ontologies_query ? "(#{ontologies_query}) AS ontologies" : "ontologies"
stmt = <<-STMT
(
SELECT distributed.id FROM
(SELECT distributed_count.id, COUNT(distributed_count.id) AS occurrences FROM
(SELECT (ontologies.parent_id) as id FROM #{query}
GROUP BY ontologies.logic_id, ontologies.parent_id)
AS distributed_count
GROUP BY distributed_count.id) AS distributed
WHERE distributed.occurrences #{selector} 1
)
STMT
where(type: DistributedOntology).where("ontologies.id IN #{stmt}")
end
end
public
def distributed?
is_a? DistributedOntology
end
def in_distributed?
!! self.parent
end
def homogeneous?
return true unless distributed?
return true unless self.children.any?
base_logic = self.children.first.logic
self.children.count == self.children.where(logic_id: base_logic).count
end
def heterogeneous?
return false unless distributed?
not homogeneous?
end
end
| ontohub/ontohub | app/models/ontology/distributed.rb | Ruby | agpl-3.0 | 2,209 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_121) on Thu Jan 25 12:48:25 CET 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.metreeca.tray.rdf (Metreeca Resource Sharing Framework 0.46 API)</title>
<meta name="date" content="2018-01-25">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.metreeca.tray.rdf (Metreeca Resource Sharing Framework 0.46 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/metreeca/tray/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/metreeca/tray/rdf/graphs/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/metreeca/tray/rdf/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package com.metreeca.tray.rdf</h1>
<div class="docSummary">
<div class="block">Shared RDF-related tools.</div>
</div>
<p>See: <a href="#package.description">Description</a></p>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/metreeca/tray/rdf/Graph.html" title="class in com.metreeca.tray.rdf">Graph</a></td>
<td class="colLast">
<div class="block">Graph store.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package.description">
<!-- -->
</a>
<h2 title="Package com.metreeca.tray.rdf Description">Package com.metreeca.tray.rdf Description</h2>
<div class="block">Shared RDF-related tools.</div>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/metreeca/tray/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/metreeca/tray/rdf/graphs/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/metreeca/tray/rdf/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2013–2018 <a href="https://www.metreeca.com/">Metreeca</a>. All rights reserved.</small></p>
</body>
</html>
| metreeca/metreeca | docs/versions/0.46/com.metreeca.tray/javadocs/com/metreeca/tray/rdf/package-summary.html | HTML | agpl-3.0 | 5,507 |
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package azure
import (
"github.com/juju/loggo"
"github.com/juju/core/environs"
"github.com/juju/core/environs/config"
)
// Register the Azure provider with Juju.
func init() {
environs.RegisterProvider("azure", azureEnvironProvider{})
}
// Logger for the Azure provider.
var logger = loggo.GetLogger("juju.provider.azure")
type azureEnvironProvider struct{}
// azureEnvironProvider implements EnvironProvider.
var _ environs.EnvironProvider = (*azureEnvironProvider)(nil)
// Open is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) {
logger.Debugf("opening environment %q.", cfg.Name())
// We can't return NewEnviron(cfg) directly here because otherwise,
// when err is not nil, we end up with a non-nil returned environ and
// this breaks the loop in cmd/jujud/upgrade.go:run() (see
// http://golang.org/doc/faq#nil_error for the gory details).
environ, err := NewEnviron(cfg)
if err != nil {
return nil, err
}
return environ, nil
}
// Prepare is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) Prepare(ctx environs.BootstrapContext, cfg *config.Config) (environs.Environ, error) {
// Set availability-sets-enabled to true
// by default, unless the user set a value.
if _, ok := cfg.AllAttrs()["availability-sets-enabled"]; !ok {
var err error
cfg, err = cfg.Apply(map[string]interface{}{"availability-sets-enabled": true})
if err != nil {
return nil, err
}
}
return prov.Open(cfg)
}
| jkary/core | provider/azure/environprovider.go | GO | agpl-3.0 | 1,626 |
/*=========================================================================================
File Name: stacked-clustered-column.js
Description: echarts stacked clustered column chart
----------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Version: 2.0
Author: PIXINVENT
Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
// Stacked clustered column chart
// ------------------------------
$(window).on("load", function(){
// Set paths
// ------------------------------
require.config({
paths: {
echarts: '../../../app-assets/vendors/js/charts/echarts'
}
});
// Configuration
// ------------------------------
require(
[
'echarts',
'echarts/chart/bar',
'echarts/chart/line'
],
// Charts setup
function (ec) {
// Initialize chart
// ------------------------------
var myChart = ec.init(document.getElementById('stacked-clustered-column'));
// Chart Options
// ------------------------------
chartOptions = {
// Setup grid
grid: {
x: 40,
x2: 20,
y: 70,
y2: 30
},
// Add tooltip
tooltip: {
trigger: 'axis'
},
// Add legend
legend: {
data: [
'ECharts1 - 2k Data','ECharts1 - 2w Data','ECharts1 - 20w Data','',
'ECharts2 - 2k Data','ECharts2 - 2w Data','ECharts2 - 20w Data'
]
},
// Enable drag recalculate
calculable: true,
// Horizontal axis
xAxis: [{
type : 'category',
data : ['Line','Bar','Scatter','K','Map']
},
{
type : 'category',
axisLine: {show:false},
axisTick: {show:false},
axisLabel: {show:false},
splitArea: {show:false},
splitLine: {show:false},
data : ['Line','Bar','Scatter','K','Map']
}
],
// Vertical axis
yAxis: [{
type : 'value',
axisLabel:{formatter:'{value} ms'}
}],
// Add series
series : [
{
name:'ECharts2 - 2k Data',
type:'bar',
itemStyle: {normal: {color:'rgba(22,211,154,1)', label:{show:true}}},
data:[40,155,95,75, 0]
},
{
name:'ECharts2 - 2w Data',
type:'bar',
itemStyle: {normal: {color:'rgba(45,206,227,1)', label:{show:true,textStyle:{color:'#27727B'}}}},
data:[100,200,105,100,156]
},
{
name:'ECharts2 - 20w Data',
type:'bar',
itemStyle: {normal: {color:'rgba(249,142,118,1)', label:{show:true,textStyle:{color:'#E87C25'}}}},
data:[906,911,908,778,0]
},
{
name:'ECharts1 - 2k Data',
type:'bar',
xAxisIndex:1,
itemStyle: {normal: {color:'rgba(22,211,154,0.7)', label:{show:true,formatter:function(p){return p.value > 0 ? (p.value +'\n'):'';}}}},
data:[96,224,164,124,0]
},
{
name:'ECharts1 - 2w Data',
type:'bar',
xAxisIndex:1,
itemStyle: {normal: {color:'rgba(45,206,227,0.7)', label:{show:true}}},
data:[491,2035,389,955,347]
},
{
name:'ECharts1 - 20w Data',
type:'bar',
xAxisIndex:1,
itemStyle: {normal: {color:'rgba(249,142,118,0.7)', label:{show:true,formatter:function(p){return p.value > 0 ? (p.value +'+'):'';}}}},
data:[3000,3000,2817,3000,0]
}
]
};
// Apply options
// ------------------------------
myChart.setOption(chartOptions);
// Resize chart
// ------------------------------
$(function () {
// Resize chart on menu width change and window resize
$(window).on('resize', resize);
$(".menu-toggle").on('click', resize);
// Resize function
function resize() {
setTimeout(function() {
// Resize chart
myChart.resize();
}, 200);
}
});
}
);
}); | Zahajamaan/Fudulbank | core/static/stack/js/scripts/charts/echarts/bar-column/stacked-clustered-column.js | JavaScript | agpl-3.0 | 5,461 |
/*/////////////////////////////////////////////////////////////////////////
//
// File: String_InternalMember.h
// Description:
//
// Rel: 01.00
// Created: November, 2002
//
// Revised:
//
// (C) Copyright 2009 Telefonica Investigacion y Desarrollo
// S.A.Unipersonal (Telefonica I+D)
//
// This file is part of Morfeo CORBA Platform.
//
// Morfeo CORBA Platform 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.
//
// Morfeo CORBA Platform 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 Morfeo CORBA Platform. If not, see
//
// http://www.gnu.org/licenses
//
// Info about members and contributors of the MORFEO project
// is available at
//
// http://morfeo-project.org
//
/////////////////////////////////////////////////////////////////////////*/
#ifndef _TIDORB_TYPES_STRING_INTERNAL_MEMBER_H_
#define _TIDORB_TYPES_STRING_INTERNAL_MEMBER_H_
#include <string.h>
#ifdef TIDORB_HAVE_IOSTREAM
#include <iostream>
#else
#include <iostream.h>
#endif
#ifdef TIDORB_HAVE_NAMESPACE_STD
using namespace std;
#endif
namespace TIDorb {
namespace types {
// Tipo String_InternalMember
//
// Este es un tipo auxiliar no accesible al usuario disenado para
// tipar los miembros string de structs, unions y arrays.
// Su implementacion es similar a la de CORBA::String_var, pero se inicializa
// por defecto con una cadena vacia
//
class String_InternalMember
{
public:
String_InternalMember(): m_ptr(CORBA::string_dup("")){}
String_InternalMember(char *p): m_ptr(p){}
String_InternalMember(const char *p) : m_ptr (CORBA::string_dup(p)){}
String_InternalMember(const CORBA::String_var &s): m_ptr(CORBA::string_dup(s)) {};
String_InternalMember(const String_InternalMember &s): m_ptr(CORBA::string_dup(s.m_ptr)) {};
~String_InternalMember() {CORBA::string_free(m_ptr);}
String_InternalMember& operator=(char *p)
{
if(m_ptr != p) {
CORBA::string_free(m_ptr);
m_ptr = p;
}
return *this;
}
String_InternalMember& operator=(const char *p)
{
if(m_ptr != p) {
CORBA::string_free(m_ptr);
m_ptr = CORBA::string_dup(p);
}
return *this;
}
String_InternalMember& operator=(const CORBA::String_var &s)
{
CORBA::string_free(m_ptr);
m_ptr = CORBA::string_dup(s);
return *this;
}
String_InternalMember& operator=(const String_InternalMember &s)
{
if(this != &s) {
CORBA::string_free(m_ptr);
m_ptr = CORBA::string_dup(s.m_ptr);
}
return *this;
}
operator char*&() { return m_ptr;}
operator const char*&() const {
const char*& aux = (const char*&) m_ptr;
return aux;
}
const char* in() const { return m_ptr;}
char*& inout() { return m_ptr;}
char*& out()
{
if(m_ptr)
CORBA::string_free(m_ptr);
return m_ptr;
}
char* _retn()
{
char* tmp_ptr = m_ptr;
m_ptr = 0;
return tmp_ptr;
}
char& operator[](CORBA::ULong index)
{
return m_ptr[index];
}
char operator[](CORBA::ULong index) const
{
return m_ptr[index];
}
private:
char* m_ptr;
};
} // end of namespace types
} // end of namespace TIDorb
inline ostream& operator<<(ostream& os, const ::TIDorb::types::String_InternalMember& s)
{
os << (const char *) s;
return os;
}
inline istream& operator>>(istream& is, ::TIDorb::types::String_InternalMember& s)
{
is >> (char *) s;
return is;
}
#endif
| AlvaroVega/TIDorbC | source/TIDorbC/orb/include/TIDorb/types/String_InternalMember.h | C | agpl-3.0 | 4,207 |
class Organization < ActiveRecord::Base
include ActionView::Helpers::SanitizeHelper
attr_accessible :available_invitation_count,
:sent_invitation_count,
:name,
:short_name,
:slug,
:website,
:default_bike_token_count,
:show_on_map,
:is_suspended,
:org_type,
:locations_attributes,
:embedable_user_email,
:auto_user_id,
:api_access_approved,
:access_token,
:new_bike_notification,
:lightspeed_cloud_api_key,
:wants_to_be_shown
attr_accessor :embedable_user_email, :lightspeed_cloud_api_key
acts_as_paranoid
has_many :memberships, dependent: :destroy
has_many :organization_deals, dependent: :destroy
has_many :users, through: :memberships
has_many :organization_invitations, dependent: :destroy
belongs_to :auto_user, class_name: "User"
has_many :bikes, foreign_key: 'creation_organization_id'
has_many :locations, dependent: :destroy
accepts_nested_attributes_for :locations, allow_destroy: true
validates_presence_of :name, :default_bike_token_count
validates_uniqueness_of :slug, message: "Slug error. You shouldn't see this - please contact admin@bikeindex.org"
default_scope order(:name)
scope :shown_on_map, where(show_on_map: true)
scope :shop, where(org_type: 'shop')
scope :police, where(org_type: 'police')
scope :advocacy, where(org_type: 'advocacy')
scope :college, where(org_type: 'college')
scope :manufacturer, where(org_type: 'manufacturer')
def to_param
slug
end
before_save :set_and_clean_attributes
def set_and_clean_attributes
self.name = strip_tags(name)
self.name = "Stop messing about" unless name[/\d|\w/].present?
self.website = Urlifyer.urlify(website) if website.present?
self.short_name = name unless short_name.present?
new_slug = Slugifyer.slugify(self.short_name).gsub(/\Aadmin/, '')
# If the organization exists, don't invalidate because of it's own slug
orgs = id.present? ? Organization.where('id != ?', id) : Organization.scoped
while orgs.where(slug: new_slug).exists?
i = i.present? ? i + 1 : 2
new_slug = "#{new_slug}-#{i}"
end
self.slug = new_slug
end
before_save :set_auto_user
def set_auto_user
if self.embedable_user_email.present?
u = User.fuzzy_email_find(embedable_user_email)
self.auto_user_id = u.id if u.is_member_of?(self)
if auto_user_id.blank? && embedable_user_email == ENV['AUTO_ORG_MEMBER']
Membership.create(user_id: u.id, organization_id: id, role: 'member')
self.auto_user_id = u.id
end
elsif self.auto_user_id.blank?
return nil unless self.users.any?
self.auto_user_id = self.users.first.id
end
end
before_save :set_locations_shown
def set_locations_shown
locations.each { |l| l.update_attribute :shown, show_on_map }
end
def suspended?
is_suspended?
end
before_save :truncate_short_name
def truncate_short_name
self.short_name = self.short_name.truncate(20)
end
before_save :set_access_token
def set_access_token
generate_access_token unless self.access_token.present?
end
after_save :clear_map_cache
def clear_map_cache
Rails.cache.delete "views/info_where_page"
end
def generate_access_token
begin
self.access_token = SecureRandom.hex
end while self.class.exists?(access_token: access_token)
end
end
| Loos/bike_index | app/models/organization.rb | Ruby | agpl-3.0 | 3,394 |
<?php
/**
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Lukas Reschke <lukas@owncloud.com>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @copyright Copyright (c) 2016, ownCloud, Inc.
* @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 OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* Class StreamResponse
*
* @package OCP\AppFramework\Http
* @since 8.1.0
*/
class StreamResponse extends Response implements ICallbackResponse {
/** @var string */
private $filePath;
/**
* @param string $filePath the path to the file which should be streamed
* @since 8.1.0
*/
public function __construct ($filePath) {
$this->filePath = $filePath;
}
/**
* Streams the file using readfile
*
* @param IOutput $output a small wrapper that handles output
* @since 8.1.0
*/
public function callback (IOutput $output) {
// handle caching
if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
if (!file_exists($this->filePath)) {
$output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
} elseif ($output->setReadfile($this->filePath) === false) {
$output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
}
}
}
}
| sakukode/owncloud-custom | lib/public/appframework/http/streamresponse.php | PHP | agpl-3.0 | 1,791 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 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.kfs.coreservice.impl.namespace;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.coreservice.api.namespace.Namespace;
import org.kuali.kfs.coreservice.api.namespace.NamespaceService;
import org.kuali.kfs.krad.service.BusinessObjectService;
import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static java.util.Collections.singletonMap;
public class NamespaceServiceImpl implements NamespaceService {
private BusinessObjectService boService;
@Override
public Namespace getNamespace(String code) {
if (StringUtils.isBlank(code)) {
throw new RiceIllegalArgumentException("the code is blank");
}
return NamespaceBo.to(boService.findByPrimaryKey(NamespaceBo.class, singletonMap("code", code)));
}
@Override
public List<Namespace> findAllNamespaces() {
List<NamespaceBo> namespaceBos = (List<NamespaceBo>) boService.findAll(NamespaceBo.class);
List<Namespace> namespaces = new ArrayList<Namespace>();
for (NamespaceBo bo : namespaceBos) {
namespaces.add(NamespaceBo.to(bo));
}
return Collections.unmodifiableList(namespaces);
}
public void setBusinessObjectService(BusinessObjectService boService) {
this.boService = boService;
}
}
| quikkian-ua-devops/will-financials | kfs-kns/src/main/java/org/kuali/kfs/coreservice/impl/namespace/NamespaceServiceImpl.java | Java | agpl-3.0 | 2,220 |
# |ALPHA| Hub - an authorization server for alpha-ioq3
# See files README and COPYING for copyright and licensing details.
"""
A throwaway thread pool with thread-local storage.
Throwaway Tasks
===============
A throwaway task is one you'd *like* to get done, but it's
not a big deal if it doesn't actually get done.
Scary as it may be, throwaway tasks are quite common in the
wild. They usually compute for a while and then *end* with
*one* operation that permanently changes the state of the
world: think of committing to a database or sending a lone
network packet.
Tasks that iterate while modifying the world, or tasks that
need to apply more than one operation to change the world
consistently, are *not* throwaway. You have been warned.
This thread pool assumes that all tasks are throwaway. It
doesn't care if they finish and it certainly doesn't care
to tell anyone that a task is done. Also, while some pools
go to great lengths to cope with blocked threads, this one
assumes that your application is broken if no progress can
be made for a certain amount of time; see add() below.
Thread-local Storage
====================
Threads frequently require some local storage of their own,
for example it may be necessary for each thread to hold its
own database connection.
This thread pool automatically equips each worker with local
storage; see __init__() and add() below.
"""
import inspect as I
import logging as L
import Queue as Q
import threading as T
class _NullHandler(L.Handler):
"""Logging handler that does nothing."""
def emit(self, _record):
pass
L.getLogger("com.urbanban.threading.throwaway.pool").addHandler(_NullHandler())
class _Worker(T.Thread):
"""Worker thread, don't instantiate directly!"""
def __init__(self, task_queue, init_local=None):
"""Initialize and start a new worker."""
super(_Worker, self).__init__()
assert isinstance(task_queue, Q.Queue)
assert init_local is None or callable(init_local)
self.__task_queue = task_queue
self.__init_local = init_local
self.daemon = True
self.start()
def run(self):
"""Worker thread main loop."""
storage = self.__make_local()
self.__run_forever(storage)
def __make_local(self):
"""Create and initialize thread-local storage."""
storage = T.local()
if self.__init_local is not None:
self.__init_local(storage)
return storage
def __run_forever(self, storage):
"""Grab the next task and run it."""
while True:
task = self.__task_queue.get()
self.__run_task(task, storage)
self.__task_queue.task_done()
def __run_task(self, task, storage):
"""Run a single task."""
func, args, kwargs = task
required_args, _, _, _ = I.getargspec(func)
try:
if '_tp_local' in required_args:
func(_tp_local=storage, *args, **kwargs)
else:
func(*args, **kwargs)
except Exception as exc:
L.exception(
"exception %s during %s ignored by thread pool",
exc, func
)
class ThreadPool(object):
"""The thread pool."""
def __init__(self, num_threads=4, max_tasks=16, timeout=32,
init_local=None, stack_size=None):
"""
Initialize and start a new thread pool.
Exactly num_threads will be spawned. At most max_tasks
can be queued before add() blocks; add() blocks for at
most timeout seconds before raising an exception.
You can pass a callable with one argument as init_local
to initialize thread-local storage for each thread; see
add() below for how to access thread-local storage from
your tasks. For example:
import sqlite3
...
def init_local(local):
local.connection = sqlite3.connect("some.db")
...
pool = ThreadPool(init_local=init_local)
"""
assert num_threads > 0
assert max_tasks > 0
assert timeout > 0
# TODO: undocumented and probably a very bad idea
assert stack_size is None or stack_size > 16*4096
if stack_size is not None:
T.stack_size(stack_size)
self.__queue = Q.Queue(max_tasks)
self.__timeout = timeout
for _ in range(num_threads):
_Worker(self.__queue, init_local)
def add(self, func, *args, **kwargs):
"""
Add a task.
A task consists of a callable func and arguments for
func. For example:
def task(some, argu, ments=None):
...
pool.add(task, act, ual, ments=parameters)
You can access thread-local storage by requiring the
special "_tp_local" argument for func. For example:
def task(_tp_local, some, argu, ments=None):
_tp_local.connection.rollback()
...
_tp_local.connection.commit()
...
pool.add(task, act, ual, ments=parameters)
"""
assert callable(func)
self.__queue.put((func, args, kwargs), True, self.__timeout)
def test():
"""Simple example and test case."""
from random import uniform
from time import sleep
from signal import pause
def init_local(local):
"""A silly local. :-D"""
local.x = uniform(0, 1)
local.y = 0
L.info("init_local local.x %s", local.x)
def task(number, _tp_local):
"""A silly task. :-D"""
L.info("task %s thread local.x %s", number, _tp_local.x)
L.info("task %s started", number)
sleep(uniform(1, 4))
L.info("task %s finished", number)
_tp_local.y += 1
L.info("thread %s has finished %s tasks", _tp_local.x, _tp_local.y)
pool = ThreadPool(init_local=init_local)
L.info("starting to add tasks to pool")
for i in range(32):
pool.add(task, i)
L.info("all tasks added, press CTRL-C to exit")
pause()
if __name__ == "__main__":
L.basicConfig(level=L.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s")
test()
| madprof/alpha-hub | prototype/pool.py | Python | agpl-3.0 | 6,257 |
require 'spec_helper'
require 'requests_helper'
require 'cancan/matchers'
describe NotificationProposalCreate, type: :model, emails: true, notifications: true, seeds: true do
it ' when a new proposal is created sends correctly an email to all people which can view proposals in the group' do
user1 = create(:user)
group = create(:group, current_user_id: user1.id)
participants = []
5.times do
user = create(:user)
participants << user
create_participation(user, group)
end
proposal = create(:group_proposal, current_user_id: participants[1].id, group_proposals: [GroupProposal.new(group: group)])
expect(described_class.jobs.size).to eq 1
described_class.drain
AlertsWorker.drain
EmailsWorker.drain
deliveries = ActionMailer::Base.deliveries.last 5
receivers = [participants[0], participants[2], participants[3], participants[4], user1]
emails = deliveries.map { |m| m.to[0] }
receiver_emails = receivers.map(&:email)
expect(emails).to match_array receiver_emails
expect(Alert.unscoped.count).to eq 5
expect(Alert.last(5).map(&:user)).to match_array receivers
expect(Alert.last(5).map { |a| a.notification_type.id }).to match_array Array.new(5, NotificationType::NEW_PROPOSALS)
end
it ' when a new proposal is created users do not receive notifications for public proposals by default' do
user1 = create(:user)
participants = []
5.times do
user = create(:user)
end
proposal = create(:public_proposal, current_user_id: user1.id)
expect(described_class.jobs.size).to eq 1
described_class.drain
AlertsWorker.drain
EmailsWorker.drain
expect(Alert.unscoped.count).to eq 0
end
it ' when a new proposal is created users can receive notifications for public proposals' do
user1 = create(:user)
participants = []
2.times do
user = create(:user)
user.blocked_alerts.find_by(notification_type_id: NotificationType::NEW_PUBLIC_PROPOSALS).destroy
end
proposal = create(:public_proposal, current_user_id: user1.id)
expect(described_class.jobs.size).to eq 1
described_class.drain
AlertsWorker.drain
EmailsWorker.drain
expect(Alert.unscoped.count).to eq 2
end
end
| giovanisp/Airesis | spec/models/notifications/notification_proposal_create_spec.rb | Ruby | agpl-3.0 | 2,260 |
package org.kareha.hareka.server.game;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import org.kareha.hareka.annotation.GuardedBy;
import org.kareha.hareka.annotation.Private;
import org.kareha.hareka.field.Direction;
import org.kareha.hareka.field.FieldObject;
import org.kareha.hareka.field.Placement;
import org.kareha.hareka.field.TileType;
import org.kareha.hareka.field.Transformation;
import org.kareha.hareka.field.Vector;
import org.kareha.hareka.field.Vectors;
import org.kareha.hareka.server.game.entity.CharacterEntity;
import org.kareha.hareka.server.game.entity.FieldEntity;
import org.kareha.hareka.server.game.field.ServerField;
import org.kareha.hareka.server.game.field.ServerFieldObject;
import org.kareha.hareka.server.game.stat.NormalCharacterStat;
import org.kareha.hareka.server.game.stat.Species;
import org.kareha.hareka.util.JaxbUtil;
public class CharacterSpawner {
private static final String resourceFile = "org/kareha/hareka/server/game/resource/CharacterSpawner.xml";
private final File file;
@GuardedBy("this")
@Private
final Map<TileType, Map<String, Float>> map = new EnumMap<>(TileType.class);
private volatile Map<TileType, List<RateEntry>> table;
public CharacterSpawner(final File file) throws JAXBException {
this.file = file;
final Adapted adapted;
if (file.isFile()) {
adapted = JaxbUtil.unmarshal(file, Adapted.class);
} else {
try (final InputStream in = getClass().getClassLoader().getResourceAsStream(resourceFile)) {
adapted = JaxbUtil.unmarshal(in, JAXBContext.newInstance(Adapted.class));
} catch (final IOException e) {
throw new JAXBException(e);
}
}
if (adapted != null && adapted.rates != null) {
for (final Rates rates : adapted.rates) {
final Map<String, Float> table = new HashMap<>();
for (final Rate rate : rates.rate) {
table.put(rate.species, rate.value);
}
map.put(rates.tileType, table);
}
}
update();
}
@XmlType(name = "rate")
@XmlAccessorType(XmlAccessType.NONE)
private static class Rate {
@XmlAttribute
@Private
String species;
@XmlValue
@Private
float value;
@SuppressWarnings("unused")
private Rate() {
// used by JAXB
}
Rate(final String id, final float value) {
this.species = id;
this.value = value;
}
}
@XmlType(name = "rates")
@XmlAccessorType(XmlAccessType.NONE)
private static class Rates {
@XmlAttribute(name = "tile")
@Private
TileType tileType;
@XmlElement
@Private
List<Rate> rate;
@SuppressWarnings("unused")
private Rates() {
// used by JAXB
}
Rates(final TileType tileType, final Map<String, Float> table) {
this.tileType = tileType;
rate = new ArrayList<>();
for (final Map.Entry<String, Float> entry : table.entrySet()) {
rate.add(new Rate(entry.getKey(), entry.getValue()));
}
}
}
@XmlRootElement(name = "characterSpawner")
@XmlAccessorType(XmlAccessType.NONE)
private static class Adapted {
@XmlElement
@Private
List<Rates> rates;
@SuppressWarnings("unused")
private Adapted() {
// used by JAXB
}
@Private
Adapted(final CharacterSpawner v) {
rates = new ArrayList<>();
synchronized (v) {
for (final Map.Entry<TileType, Map<String, Float>> entry : v.map.entrySet()) {
rates.add(new Rates(entry.getKey(), entry.getValue()));
}
}
}
}
public void save() throws JAXBException {
JaxbUtil.marshal(new Adapted(this), file);
}
private static class RateEntry {
final String species;
final float value;
RateEntry(final String species, final float value) {
this.species = species;
this.value = value;
}
}
private void update() {
final Map<TileType, List<RateEntry>> newTable = new EnumMap<>(TileType.class);
for (final TileType tileType : TileType.values()) {
final Map<String, Float> rateMap = map.get(tileType);
if (rateMap == null) {
continue;
}
float total = 0;
for (final Float value : rateMap.values()) {
total += value;
}
final List<RateEntry> list = new ArrayList<>();
float current = 0;
for (final Map.Entry<String, Float> entry : rateMap.entrySet()) {
current += entry.getValue() / total;
list.add(new RateEntry(entry.getKey(), current));
}
if (!list.isEmpty()) {
final RateEntry last = list.remove(list.size() - 1);
list.add(new RateEntry(last.species, 1));
}
newTable.put(tileType, list);
}
table = newTable;
}
private String findSpecies(final TileType tileType, final float randomValue) {
final List<RateEntry> list = table.get(tileType);
if (list == null) {
return null;
}
for (final RateEntry rateEntry : list) {
if (rateEntry.value > randomValue) {
return rateEntry.species;
}
}
return null;
}
public boolean trySpawnCharacter(final ServerFieldObject fo, final Direction newDirection,
final Vector newPosition) {
if (newDirection == Direction.NULL) {
return false;
}
if (ThreadLocalRandom.current().nextInt(8) != 0) {
return false;
}
final ServerField field = fo.getField();
final Vector[] edge = Vectors.edge(newPosition, field.getViewSize() + 1, newDirection);
final int i = ThreadLocalRandom.current().nextInt(edge.length);
final Vector center = edge[i];
final TileType tileType = field.getTile(center).type();
if (!tileType.isWalkable()) {
return false;
}
if (tileType == TileType.AIR) {
return false;
}
final List<FieldObject> fos = field.getInViewObjects(center);
int aliveCount = 0;
int deadCount = 0;
int spiritCount = 0;
for (final FieldObject j : fos) {
final FieldEntity fe = ((ServerFieldObject) j).getFieldEntity();
if (!(fe instanceof CharacterEntity)) {
continue;
}
final CharacterEntity ce = (CharacterEntity) fe;
if (!ce.getStat().getHealthPoints().isAlive()) {
deadCount++;
continue;
}
if (!ce.isFieldDriversEmpty()) {
return false;
}
if (ce.getStat().getSpecies().getId().equals("Spirit")) {
spiritCount++;
continue;
}
aliveCount++;
}
// create character
String raceId = null;
if (deadCount > 0 && spiritCount < 4) {
if (ThreadLocalRandom.current().nextInt(8) < 1) {
raceId = "Spirit";
}
}
if (raceId == null) {
raceId = findSpecies(tileType, ThreadLocalRandom.current().nextFloat());
}
if (raceId == null) {
return false;
}
if (!raceId.equals("Spirit") && aliveCount >= 8) {
return false;
}
final Species race = Global.INSTANCE.context().getSpeciesTable().getSpecies(raceId);
final List<String> shapes = new ArrayList<>(race.getShapes());
final String shape = shapes.get(ThreadLocalRandom.current().nextInt(shapes.size()));
final CharacterEntity.Builder builder = new CharacterEntity.Builder();
builder.name(race.getName());
builder.shape(shape);
final NormalCharacterStat.Builder statBuilder = new NormalCharacterStat.Builder();
statBuilder.species(race).shape(shape);
builder.stat(statBuilder.build());
builder.fieldId(field.getId());
builder.placement(Placement.valueOf(center, Direction.NULL));
builder.transformation(Transformation.random(Vector.ZERO));
final CharacterEntity entity = Global.INSTANCE.context().getEntities().createCharacterEntity(builder);
entity.mount(Global.INSTANCE.context().getFields());
entity.startMotion();
return true;
}
}
| tyatsumi/hareka | server/src/main/java/org/kareha/hareka/server/game/CharacterSpawner.java | Java | agpl-3.0 | 7,899 |
package org.mezuro.scalability_tests.strategy;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
public abstract class RESTStrategy implements Strategy<String>{
protected final String REPOSITORY_PATH = "repositories";
protected final String PROCESSING_PATH = "processings";
protected final String PROJECT_PATH = "projects";
protected final String MODULE_RESULT_PATH = "module_results";
protected final String METRIC_COLLECTOR_DETAILS_PATH = "metric_collector_details";
protected final String KALIBRO_MODULE_PATH = "kalibro_modules";
protected final String METRIC_RESULT_PATH = "metric_results";
protected final String TREE_METRIC_RESULT_PATH = "tree_metric_results";
protected final String HOTSPOT_METRIC_RESULT_PATH = "hotspot_metric_results";
protected final String READING_GROUP_PATH = "reading_groups";
protected final String READING_PATH = "readings";
protected final String KALIBRO_CONFIGURATION_PATH = "kalibro_configurations";
protected final String METRIC_CONFIGURATION_PATH = "metric_configurations";
protected final String KALIBRO_RANGE_PATH = "kalibro_ranges";
protected List<String> urls;
protected String basePath;
protected int currentUrlIndex;
public void configure(Map<Object, Object> options, String serviceKey) {
Map<Object, Object> serviceOptions = (Map<Object, Object>)options.get(serviceKey);
urls = (List<String>)serviceOptions.get("base_uris");
basePath = (String)serviceOptions.get("base_path");
currentUrlIndex = 0;
}
public String getCurrentUrl() {
return urls.get(currentUrlIndex);
}
public String buildUrl(String path) {
return getCurrentUrl() + basePath + path;
}
public void changeToNextUrl() {
++currentUrlIndex;
if(currentUrlIndex >= urls.size()) {
// TODO: blow up
}
}
public void beforeExperiment() throws Exception {}
public void beforeIteration() throws Exception {}
public String beforeRequest() throws Exception {
return null;
}
public abstract String request(String string) throws Exception;
public void afterRequest(String requestResponse) throws Exception {}
public void afterIteration() throws Exception {}
public void afterExperiment() throws Exception {}
public abstract void configure(Map<Object, Object> options);
public HttpResponse<JsonNode> get(String url) throws Exception {
return Unirest.get(url)
.header("Content-Type", "application/json")
.header("accept", "application/json")
.asJson();
}
public HttpResponse<JsonNode> get(String url, String key, String queryString) throws Exception {
return Unirest.get(url)
.header("Content-Type", "application/json")
.header("accept", "application/json")
.queryString(key, queryString)
.asJson();
}
public HttpResponse<JsonNode> post(String url, JSONObject body) throws Exception {
return Unirest.post(url)
.header("Content-Type", "application/json")
.header("accept", "application/json")
.body(body.toString())
.asJson();
}
public HttpResponse<JsonNode> delete(String url) throws Exception {
return Unirest.delete(url)
.header("Content-Type", "application/json")
.header("accept", "application/json")
.asJson();
}
public HttpResponse<JsonNode> put(String url, JSONObject body) throws Exception {
return Unirest.put(url)
.header("Content-Type", "application/json")
.header("accept", "application/json")
.body(body.toString())
.asJson();
}
}
| mezuro/scalability_tests | scalability_tests/src/main/java/org/mezuro/scalability_tests/strategy/RESTStrategy.java | Java | agpl-3.0 | 3,559 |
/*
* CreatureTemplate.cpp
*
* Created on: 22/01/2012
* Author: victor
*/
#include "CreatureTemplate.h"
CreatureTemplate::CreatureTemplate() {
conversationTemplate = 0;
kinetic = 0;
energy = 0;
electricity = 0;
stun = 0;
blast = 0;
heat = 0;
cold = 0;
acid = 0;
lightSaber = 0;
scale = 1.f;
objectName = "";
randomNameType = 0;
randomNameTag = false;
customName = "";
socialGroup = "";
faction = "";
level = 0;
chanceHit = 0.f;
damageMin = 0;
damageMax = 0;
specialDamageMult = 1.f;
range = 0;
baseXp = 0;
baseHAM = 0;
baseHAMmax = 0;
armor = 0;
meatType = "";
meatAmount = 0;
hideType = "";
hideAmount = 0;
boneType = "";
boneAmount = 0;
milkType = "";
milk = 0.f;
tamingChance = 0.f;
ferocity = 0;
aggroRadius = 0;
pvpBitmask = 0;
creatureBitmask = 0;
diet = 0;
optionsBitmask = 0;
templates.removeAll();
weapons.removeAll();
attacks = new CreatureAttackMap();
aiTemplate = "example";
defaultWeapon = "";
defaultAttack = "defaultattack";
controlDeviceTemplate = "object/intangible/pet/pet_control.iff";
containerComponentTemplate = "";
reactionStf = "";
personalityStf = "";
}
CreatureTemplate::~CreatureTemplate() {
templates.removeAll();
weapons.removeAll();
delete attacks;
attacks = NULL;
}
void CreatureTemplate::readObject(LuaObject* templateData) {
conversationTemplate = String(templateData->getStringField("conversationTemplate").trim()).hashCode();
objectName = templateData->getStringField("objectName").trim();
randomNameType = templateData->getIntField("randomNameType");
randomNameTag = templateData->getBooleanField("randomNameTag");
customName = templateData->getStringField("customName").trim();
socialGroup = templateData->getStringField("socialGroup").trim();
faction = templateData->getStringField("faction").trim().toLowerCase();
level = templateData->getIntField("level");
chanceHit = templateData->getFloatField("chanceHit");
damageMin = templateData->getIntField("damageMin");
damageMax = templateData->getIntField("damageMax");
specialDamageMult = templateData->getFloatField("specialDamageMult");
if (specialDamageMult < 0.001f) specialDamageMult = 1.f; // could use numeric_limit here, but this will prevent people from putting tiny modifiers in as well.
baseXp = templateData->getIntField("baseXp");
baseHAM = templateData->getIntField("baseHAM");
baseHAMmax = templateData->getIntField("baseHAMmax");
armor = templateData->getIntField("armor");
meatType = templateData->getStringField("meatType").trim();
meatAmount = templateData->getIntField("meatAmount");
hideType = templateData->getStringField("hideType").trim();
hideAmount = templateData->getIntField("hideAmount");
boneType = templateData->getStringField("boneType").trim();
boneAmount = templateData->getIntField("boneAmount");
milk = templateData->getIntField("milk");
tamingChance = templateData->getFloatField("tamingChance");
ferocity = templateData->getIntField("ferocity");
aggroRadius = templateData->getIntField("aggroRadius");
pvpBitmask = templateData->getIntField("pvpBitmask");
creatureBitmask = templateData->getIntField("creatureBitmask");
diet = templateData->getIntField("diet");
optionsBitmask = templateData->getIntField("optionsBitmask");
patrolPathTemplate = templateData->getStringField("patrolPathTemplate");
defaultWeapon = templateData->getStringField("defaultWeapon");
if(!templateData->getStringField("defaultAttack").isEmpty())
defaultAttack = templateData->getStringField("defaultAttack");
scale = templateData->getFloatField("scale");
if (!templateData->getStringField("milkType").isEmpty()) {
milkType = templateData->getStringField("milkType").trim();
}
LuaObject res = templateData->getObjectField("resists");
if (res.getTableSize() == 9) {
kinetic = res.getFloatAt(1);
energy = res.getFloatAt(2);
blast = res.getFloatAt(3);
heat = res.getFloatAt(4);
cold = res.getFloatAt(5);
electricity = res.getFloatAt(6);
acid = res.getFloatAt(7);
stun = res.getFloatAt(8);
lightSaber = res.getFloatAt(9);
}
res.pop();
LuaObject temps = templateData->getObjectField("templates");
if (temps.isValidTable()) {
for (int i = 1; i <= temps.getTableSize(); ++i) {
templates.add(temps.getStringAt(i).trim());
}
}
temps.pop();
LuaObject lootCollections = templateData->getObjectField("lootGroups");
lootgroups.readObject(&lootCollections, level);
lootCollections.pop();
LuaObject weps = templateData->getObjectField("weapons");
if (weps.isValidTable()) {
for (int i = 1; i <= weps.getTableSize(); ++i) {
weapons.add(weps.getStringAt(i).trim());
}
}
weps.pop();
LuaObject attackList = templateData->getObjectField("attacks");
if (attackList.isValidTable()) {
int size = attackList.getTableSize();
lua_State* L = attackList.getLuaState();
for (int i = 1; i <= size; ++i) {
lua_rawgeti(L, -1, i);
LuaObject atk(L);
if (atk.isValidTable()) {
int atkSize = atk.getTableSize();
if (atkSize == 2) {
String com = atk.getStringAt(1).trim();
String arg = atk.getStringAt(2).trim();
attacks->addAttack(com, arg);
}
}
atk.pop();
}
}
attackList.pop();
outfit = templateData->getStringField("outfit");
aiTemplate = templateData->getStringField("aiTemplate");
if(!templateData->getStringField("controlDeviceTemplate").isEmpty())
controlDeviceTemplate = templateData->getStringField("controlDeviceTemplate");
containerComponentTemplate = templateData->getStringField("containerComponentTemplate");
reactionStf = templateData->getStringField("reactionStf");
personalityStf = templateData->getStringField("personalityStf");
}
| Tatwi/legend-of-hondo | MMOCoreORB/src/server/zone/objects/creature/ai/CreatureTemplate.cpp | C++ | agpl-3.0 | 5,660 |
package org.flightreservationsserverinterface;
import java.rmi.Remote;
import java.rmi.RemoteException;
import org.flightreservationsserverinterface.exceptions.ErrorInServerException;
import org.flightreservationsserverinterface.exceptions.InvalidLoginException;
/**
* @author Facundo Quiroga
* Creation date: Feb 3, 2009 10:59:20 PM
*/
public interface FlightReservationsLoginInterface extends Remote {
/**
* @param username
* @param password
* @return
* @throws InvalidLoginException
* @throws ErrorInServerException
*/
FlightReservationsAirlineInterface loginAsAirline(String username, String password) throws InvalidLoginException, ErrorInServerException, RemoteException;
/**
* @param reservationAgencyName
* @param password
* @return
* @throws InvalidLoginException
* @throws ErrorInServerException
*/
FlightReservationsAgencyInterface loginAsReservationAgency(String reservationAgencyName, String password) throws InvalidLoginException,
ErrorInServerException, RemoteException;
}
| facundoq/toys | crappydbms/FlightReservationsServerInterface/src/org/flightreservationsserverinterface/FlightReservationsLoginInterface.java | Java | agpl-3.0 | 1,034 |
// @flow
import { createSelector, type OutputSelector } from 'reselect'
import { sortOrderSort } from 'utils'
import type { EntityState, WrappedEntityState } from 'ducks/entities'
import type { Player, Character, fullQc, Battlegroup } from 'utils/flow-types'
export type entitySelector<T> = OutputSelector<WrappedEntityState, any, T>
type CharacterListSelector = entitySelector<Array<Character>>
type QcListSelector = entitySelector<Array<fullQc>>
type BgListSelector = entitySelector<Array<Battlegroup>>
export const entities = (state: WrappedEntityState): EntityState =>
state.entities.current
export const getSpecificPlayer = (
state: WrappedEntityState,
id: number
): Player => ({
characters: [],
qcs: [],
battlegroups: [],
chronicles: [],
own_chronicles: [],
...entities(state).players[id],
})
export const getCurrentPlayer = (state: WrappedEntityState): Player =>
getSpecificPlayer(state, state.session.id)
const getCharacters = state => entities(state).characters
export const getMyCharacters: CharacterListSelector = createSelector(
[getCurrentPlayer, getCharacters],
(currentPlayer, characters) =>
currentPlayer.characters.map(c => characters[c]).sort(sortOrderSort)
)
export const getMyCharactersWithoutChronicles: CharacterListSelector = createSelector(
[getMyCharacters],
characters => characters.filter(c => c.chronicle_id == null)
)
const getQCs = state => entities(state).qcs
export const getMyQCs: QcListSelector = createSelector(
[getCurrentPlayer, getQCs],
(currentPlayer, qcs) => currentPlayer.qcs.map(c => qcs[c]).sort(sortOrderSort)
)
export const getMyQcsWithoutChronicles: QcListSelector = createSelector(
[getMyQCs],
qcs => qcs.filter(c => c.chronicle_id == null)
)
const getBattlegroups = state => entities(state).battlegroups
export const getMyBattlegroups: BgListSelector = createSelector(
[getCurrentPlayer, getBattlegroups],
(currentPlayer, battlegroups) =>
currentPlayer.battlegroups.map(c => battlegroups[c]).sort(sortOrderSort)
)
export const getMyBattlegroupsWithoutChronicles: BgListSelector = createSelector(
[getMyBattlegroups],
battlegroups => battlegroups.filter(c => c.chronicle_id == null)
)
| makzu/lotcastingatemi | app/javascript/lca/selectors/entities.js | JavaScript | agpl-3.0 | 2,197 |
CREATE TABLE codes_postaux (
CODE_COMMUNE varchar(5),
NOM_COMMUNE varchar(100),
CODE_POSTAL varchar(5),
ACHEMINEMENT varchar(100),
LIGNE5 varchar(100)
);
\COPY codes_postaux FROM 'insee_codes_postaux.csv' WITH CSV HEADER DELIMITER ';';
CREATE INDEX codes_postaux_code_commune_idx
ON codes_postaux (CODE_COMMUNE);
CREATE INDEX codes_postaux_code_postal_idx
ON codes_postaux (CODE_POSTAL);
| mapkiwiz/sectorisation | ref/insee_codes_postaux.sql | SQL | agpl-3.0 | 411 |
/*
Uniform Theme: Uniform Default
Version: 1.8
By: Josh Pyles
License: MIT License
---
For use with the Uniform plugin:
http://uniformjs.com/
*/
div.selector span {
background-image: url("../images/sprite.png");
background-repeat: no-repeat;
-webkit-font-smoothing: antialiased;
}
div.selector, div.checker, div.button, div.radio, div.uploader {
display: -moz-inline-box;
display: inline-block;
*display: inline;
zoom: 1;
vertical-align: middle;
/* Keeping this as :focus to remove browser styles */
}
/* custom for the document drop in Classis*/
div.uploader span.action, div.uploader span.filename {
display: none;
}
div.selector:focus, div.checker:focus, div.button:focus, div.radio:focus, div.uploader:focus {
outline: 0;
border: solid 2px #f39c12;
}
div.selector, div.selector *, div.radio, div.radio *, div.checker, div.checker *, div.uploader, div.uploader *, div.button, div.button * {
margin: 0;
padding: 0;
}
.highContrastDetect {
background: url("../images/bg-input.png") repeat-x 0 0;
width: 0px;
height: 0px;
}
/* Select */
div.selector {
background-color: #34495e;
line-height: 40px;
height: 40px;
padding: 0 0 0 10px;
position: relative;
overflow: hidden;
border-radius: 3px;
font-size: 12px;
}
div.selector span {
text-overflow: ellipsis;
display: block;
overflow: hidden;
white-space: nowrap;
background-position: right -50px;
height: 40px;
line-height: 40px;
padding-right: 45px;
cursor: pointer !important;
width: 100%;
display: block;
color: #cad5da;
text-shadow: none;
}
div.selector select {
opacity: 0;
filter: alpha(opacity=0);
-moz-opacity: 0;
border: none;
background: none;
position: absolute;
height: 40px;
top: 2px;
left: 0px;
width: 100%;
font-family: 'Lato', sans-serif;
font-size: 14px;
cursor: pointer !important;
}
div.selector select option {
background: #ebedef;
color: #657585;
}
div.selector select option[value=""], div.selector select option[disabled="disabled"] {
background-color: #eeeeee;
color: #aaaaaa;
}
div.selector.default {
min-width: 130px !important;
width: 19% !important;
float: left;
margin-right: 10px;
margin-bottom: 10px;
}
div.selector.default span {
width: 90% !important;
}
div.selector.loginlang {
min-width: 245px !important;
max-width: 245px !important;
width: 245px !important;
float: left;
margin-left: 20px;
background-color: #4d5f72;
}
div.selector.loginlang span {
width: 80% !important;
max-width: 80% !important;
background-position: right 0;
}
div.selector.registerEdit {
background-color: #FFFFFF;
height: 25px;
margin-right: 5px;
border: solid 1px #bac1c8;
}
div.selector.registerEdit.hover {
border: solid 1px #f39c12;
}
div.selector.registerEdit.focus {
border: solid 1px #f39c12;
}
div.selector.registerEdit span {
background-position: right -135px;
height: 25px;
line-height: 25px;
padding-right: 25px;
color: #34495e;
}
div.selector.registerEdit select {
height: 25px;
}
div.selector.blueLight {
background-color: #4d5f72;
}
div.selector.blueLight span {
background-position: right 0;
}
/* PRESENTATION */
/* CheckBox*/
/*Reset Uniform*/
div.checker {
width: 20px;
height: 20px;
display: inline-block;
margin: 0 3px;
*display: inline;
zoom: 1;
vertical-align: middle;
position: relative;
}
.listmenu.sidtable div.checker {
float: left;
}
div.checker:focus {
outline: 0;
cursor: pointer;
}
/* Checkbox */
div.checker span.checked input {
position: absolute;
z-index: 1;
left: -1px;
top: -1px;
cursor: pointer;
}
div.checker span.checked:before {
font-family: FontAwesome;
content: "\f00c";
color: #FFFFFF;
display: block;
margin-top: 3px;
cursor: pointer;
font-size: 14px;
font-weight: normal;
}
div.checker span, div.checker input {
width: 20px;
height: 20px;
}
div.checker span {
display: -moz-inline-box;
display: inline-block;
*display: inline;
zoom: 1;
text-align: center;
background-color: #bac1c8;
cursor: pointer;
}
div.checker input {
opacity: 0;
filter: alpha(opacity=0);
-moz-opacity: 0;
border: none;
background: none;
display: -moz-inline-box;
display: inline-block;
*display: inline;
zoom: 1;
cursor: pointer;
}
.checkall div.checker {
border: 1px solid;
background-color: #bac1c8;
display: inline-block;
zoom: 1;
cursor: pointer;
width: 15px;
height: 15px;
}
.checkall .checker span {
margin: 3px;
border: 1px solid;
width: 15px;
height: 15px;
}
.checkall .checker span.checked:before {
margin-top: 0;
}
div.checker.hover span {
background-color: #bac1c8;
cursor: pointer;
}
.checkall.checked div.checker, div.checker span.checked, div.checker.hover span.checked {
background-color: #91c73e;
}
/* Radio */
div.radio {
position: relative;
margin-right: 5px;
margin-left: 10px;
}
div.radio, div.radio span, div.radio input {
cursor: pointer;
}
div.radio span {
display: -moz-inline-box;
display: inline-block;
*display: inline;
zoom: 1;
text-align: center;
position: relative;
}
div.radio span:before, div.radio span.checked:before {
font-family: FontAwesome;
content: "\f111";
color: #bac1c8;
display: block;
cursor: pointer;
font-size: 16px;
font-weight: normal;
font-style: normal;
}
div.radio span.checked:before {
content: "\f192";
color: #91c73e;
font-weight: normal;
}
div.radio input {
opacity: 0;
filter: alpha(opacity=0);
-moz-opacity: 0;
border: none;
background: none;
display: -moz-inline-box;
display: inline-block;
*display: inline;
zoom: 1;
text-align: center;
position: absolute;
top: 0;
left: 0;
}
/* INPUT & TEXTAREA */
select.uniform-multiselect {
min-width: 150px;
height: 120px;
border: solid 1px #34495e;
padding: 0;
margin: 0;
margin-bottom: 10px;
width: 98%;
font-size: x-small;
background-color: #ebedef;
}
select.uniform-multiselect:focus {
border: 2px solid #f39c12;
z-index: 10000;
}
select.uniform-multiselect option {
font-size: 12px;
background-color: #ebedef;
color: #657585;
padding: 0 5px;
font-family: 'Lato', sans-serif;
cursor: pointer;
}
/*these select widths are not ideal but seem to solve a firefox bug for 100%!*/
select#mids:focus option {
width: 100%;
}
select.uniform-multiselect option.report {
background-color: #eeeeee;
}
select.uniform-multiselect option.derived {
background-color: #ddeeff;
}
select.uniform-multiselect option.other {
background-color: #bfde8f;
}
/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
select.uniform-multiselect {
height: auto !important;
}
} | LearningData/class | css/uniform.edit.css | CSS | agpl-3.0 | 6,723 |
#!/usr/bin/python -S
#
# Copyright 2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Process one email message, read from stdin."""
import _pythonpath
import sys
from lp.services.config import config
from lp.services.mail.helpers import save_mail_to_librarian
from lp.services.mail.incoming import handle_one_mail
from lp.services.mail.signedmessage import signed_message_from_string
from lp.services.scripts.base import LaunchpadScript
class ProcessMail(LaunchpadScript):
usage = """%prog [options] [MAIL_FILE]
Process one incoming email, read from the specified file or from stdin.
Any mail generated in response is printed to stdout.
""" + __doc__
def main(self):
self.txn.begin()
# NB: This somewhat duplicates handleMail, but there it's mixed in
# with handling a mailbox, which we're avoiding here.
if len(self.args) >= 1:
from_file = file(self.args[0], 'rb')
else:
from_file = sys.stdin
self.logger.debug("reading message from %r" % (from_file,))
raw_mail = from_file.read()
self.logger.debug("got %d bytes" % len(raw_mail))
file_alias = save_mail_to_librarian(raw_mail)
self.logger.debug("saved to librarian as %r" % (file_alias,))
parsed_mail = signed_message_from_string(raw_mail)
# Kinda kludgey way to cause sendmail to just print it.
config.sendmail_to_stdout = True
handle_one_mail(
self.logger, parsed_mail,
file_alias, file_alias.http_url,
signature_timestamp_checker=None)
self.logger.debug("mail handling complete")
self.txn.commit()
if __name__ == '__main__':
script = ProcessMail('process-one-mail', dbuser=config.processmail.dbuser)
# No need to lock; you can run as many as you want as they use no global
# resources (like a mailbox).
script.run(use_web_security=True)
| abramhindle/UnnaturalCodeFork | python/testdata/launchpad/scripts/process-one-mail.py | Python | agpl-3.0 | 2,007 |
import flask
mod = flask.Blueprint('api', __name__)
| erik/sketches | projects/700c/web/views/api.py | Python | agpl-3.0 | 54 |
<?php
namespace Ilex\Core;
class Session
{
const SID = 'sid';
const UID = 'uid';
const USERNAME = 'username';
const LOGIN = 'login';
private static $booted = FALSE;
private static $fakeSession;
public static function boot()
{
if (!self::$booted) {
self::start();
self::$booted = TRUE;
if (ENVIRONMENT !== 'TEST') {
self::$fakeSession = &$_SESSION;
} else {
self::$fakeSession = array();
}
if (!static::has(static::SID)) {
static::newSid();
}
if (!static::has(static::UID)) {
static::makeGuest();
}
}
}
public static function start()
{
if (ENVIRONMENT !== 'TEST') {
session_name(SYS_SESSNAME);
session_start();
}
}
public static function forget()
{
if (ENVIRONMENT !== 'TEST') {
session_unset();
session_destroy();
}
self::start();
self::newSid();
self::makeGuest();
}
public static function newSid()
{
return static::let(static::SID, sha1(uniqid().mt_rand()));
}
public static function makeGuest()
{
static::let(static::UID, 0);
static::let(static::USERNAME, 'Guest');
static::let(static::LOGIN, FALSE);
}
public static function has($key)
{
return isset(self::$fakeSession[$key]);
}
public static function get($key = FALSE, $default = FALSE)
{
return $key ?
(isset(self::$fakeSession[$key]) ? self::$fakeSession[$key] : $default) :
self::$fakeSession;
}
public static function let($key, $value)
{
return self::$fakeSession[$key] = $value;
}
public static function assign($vars)
{
$tmp = array_merge(self::$fakeSession, $vars);
if (ENVIRONMENT !== 'TEST') {
$_SESSION = $tmp;
self::$fakeSession = &$_SESSION;
} else {
self::$fakeSession = $tmp;
}
}
} | arrowrowe/ilex | src/Core/Session.php | PHP | agpl-3.0 | 2,200 |
---
layout: default
tag: eng
---
<div class="post">
<header class="post-header">
<h1 class="post-title">{{ page.title }}</h1>
</header>
<article class="post-content">
{{ content }}
</article>
</div>
| talexand/the-glow | _layouts/page.html | HTML | agpl-3.0 | 218 |
<?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 LICENSE file distributed with this package.
*
*
* @category WURFL
*
* @copyright ScientiaMobile, Inc.
* @license GNU Affero General Public License
*/
namespace Wurfl\Handlers\Normalizer\Generic;
use Wurfl\Handlers\Normalizer\NormalizerInterface;
/**
* User Agent Normalizer - removes UP.Link garbage from user agent
*/
class UPLink implements NormalizerInterface
{
/**
* This method remove the 'UP.Link' substring from user agent string.
*
* @param string $userAgent
*
* @return string Normalized user agent
*/
public function normalize($userAgent)
{
$index = strpos($userAgent, 'UP.Link');
if ($index !== false) {
return substr($userAgent, 0, $index);
}
return $userAgent;
}
}
| mimmi20/Wurfl | src/Handlers/Normalizer/Generic/UPLink.php | PHP | agpl-3.0 | 1,122 |
const HTTP_TIMEOUT = 30000;
export function httpAsync(theUrl, callback, type, payload, errorCB) {
const xmlHttp = new XMLHttpRequest();
const timeout = setTimeout(() => {
xmlHttp.abort();
if (typeof errorCB === 'function') errorCB();
}, HTTP_TIMEOUT);
xmlHttp.timeout = HTTP_TIMEOUT; // Set timeout to 30s 'cause ESPs are slow
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
clearTimeout(timeout);
if (typeof callback === 'function') callback(xmlHttp.responseText);
else if (typeof errorCB === 'function') errorCB();
}
};
xmlHttp.onerror = () => {
clearTimeout(timeout);
if (typeof errorCB === 'function') errorCB();
};
xmlHttp.open(type ? type : "GET", theUrl, true); // true for asynchronous
xmlHttp.send(payload);
}
export function reboot() {
if (!PRODUCTION)
setTimeout(() => {
window.location.href = window.location.href;
}, 3000);
if (PRODUCTION)
httpAsync('/reboot', function (res) {
window.location.href = window.location.href;
});
}
| TheMegaTB/FINDTracker | http/src/js/api/networking.js | JavaScript | agpl-3.0 | 1,184 |
SUBROUTINE read_SedPar (model, inp, out, Lwrite)
!
!=======================================================================
! !
! This routine reads in cohesive and non-cohesive sediment model !
! parameters. !
! !
!=======================================================================
!
USE mod_param
USE mod_parallel
USE mod_ncparam
USE mod_scalars
USE mod_sediment
!
implicit none
!
! Imported variable declarations
!
logical, intent(in) :: Lwrite
integer, intent(in) :: model, inp, out
!
! Local variable declarations.
!
integer :: Npts, Nval
integer :: iTrcStr, iTrcEnd
integer :: i, ifield, igrid, itracer, itrc, ng, nline, status
integer :: decode_line, load_i, load_l, load_lbc, load_r
logical, dimension(Ngrids) :: Lbed
logical, dimension(MBOTP,Ngrids) :: Lbottom
logical, dimension(NCS,Ngrids) :: Lmud
logical, dimension(NNS,Ngrids) :: Lsand
real(r8), dimension(Ngrids) :: Rbed
real(r8), dimension(NCS,Ngrids) :: Rmud
real(r8), dimension(NNS,Ngrids) :: Rsand
real(r8), dimension(100) :: Rval
character (len=40 ) :: KeyWord
character (len=256) :: line
character (len=256), dimension(200) :: Cval
!
!-----------------------------------------------------------------------
! Initialize.
!-----------------------------------------------------------------------
!
igrid=1 ! nested grid counter
itracer=0 ! LBC tracer counter
iTrcStr=1 ! first LBC tracer to process
iTrcEnd=NST ! last LBC tracer to process
nline=0 ! LBC multi-line counter
!
!-----------------------------------------------------------------------
! Read in cohesive and non-cohesive model parameters.
!-----------------------------------------------------------------------
!
DO WHILE (.TRUE.)
READ (inp,'(a)',ERR=10,END=20) line
status=decode_line(line, KeyWord, Nval, Cval, Rval)
IF (status.gt.0) THEN
SELECT CASE (TRIM(KeyWord))
CASE ('Lsediment')
Npts=load_l(Nval, Cval, Ngrids, Lsediment)
CASE ('NEWLAYER_THICK')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
newlayer_thick(ng)=Rbed(ng)
END DO
CASE ('MINLAYER_THICK')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
minlayer_thick(ng)=Rbed(ng)
END DO
#ifdef MIXED_BED
CASE ('TRANSC')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
transC(ng)=Rbed(ng)
END DO
CASE ('TRANSN')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
transN(ng)=Rbed(ng)
END DO
#endif
CASE ('BEDLOAD_COEFF')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
bedload_coeff(ng)=Rbed(ng)
END DO
CASE ('LBC(isTvar)')
IF (itracer.lt.NST) THEN
itracer=itracer+1
ELSE
itracer=1 ! next nested grid
END IF
ifield=isTvar(idsed(itracer))
Npts=load_lbc(Nval, Cval, line, nline, ifield, igrid, &
& idsed(iTrcStr), idsed(iTrcEnd), &
& Vname(1,idTvar(idsed(itracer))), LBC)
#if defined ADJOINT || defined TANGENT || defined TL_IOMS
CASE ('ad_LBC(isTvar)')
IF (itracer.lt.NST) THEN
itracer=itracer+1
ELSE
itracer=1 ! next nested grid
END IF
ifield=isTvar(idsed(itracer))
Npts=load_lbc(Nval, Cval, line, nline, ifield, igrid, &
& idsed(iTrcStr), idsed(iTrcEnd), &
& Vname(1,idTvar(idsed(itracer))), ad_LBC)
#endif
CASE ('MUD_SD50')
IF (.not.allocated(Sd50)) allocate (Sd50(NST,Ngrids))
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
Sd50(itrc,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_CSED')
IF (.not.allocated(Csed)) allocate (Csed(NST,Ngrids))
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud )
DO ng=1,Ngrids
DO itrc=1,NCS
Csed(itrc,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_SRHO')
IF (.not.allocated(Srho)) allocate (Srho(NST,Ngrids))
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
Srho(itrc,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_WSED')
IF (.not.allocated(Wsed)) allocate (Wsed(NST,Ngrids))
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
Wsed(itrc,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_ERATE')
IF (.not.allocated(Erate)) allocate (Erate(NST,Ngrids))
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
Erate(itrc,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_TAU_CE')
IF (.not.allocated(tau_ce)) allocate (tau_ce(NST,Ngrids))
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
tau_ce(itrc,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_TAU_CD')
IF (.not.allocated(tau_cd)) allocate (tau_cd(NST,Ngrids))
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
tau_cd(itrc,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_POROS')
IF (.not.allocated(poros)) allocate (poros(NST,Ngrids))
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
poros(itrc,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_TNU2')
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
nl_tnu2(i,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_TNU4')
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
nl_tnu4(i,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('ad_MUD_TNU2')
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
ad_tnu2(i,ng)=Rmud(itrc,ng)
tl_tnu2(i,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('ad_MUD_TNU4')
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
ad_tnu4(i,ng)=Rmud(itrc,ng)
nl_tnu4(i,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_Sponge')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
LtracerSponge(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('MUD_AKT_BAK')
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
Akt_bak(i,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_AKT_fac')
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
ad_Akt_fac(i,ng)=Rmud(itrc,ng)
tl_Akt_fac(i,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_TNUDG')
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
Tnudg(i,ng)=Rmud(itrc,ng)
END DO
END DO
CASE ('MUD_MORPH_FAC')
IF (.not.allocated(morph_fac)) THEN
allocate (morph_fac(NST,Ngrids))
END IF
Npts=load_r(Nval, Rval, NCS*Ngrids, Rmud)
DO ng=1,Ngrids
DO itrc=1,NCS
morph_fac(itrc,ng)=Rmud(itrc,ng)
END DO
END DO
#if defined COHESIVE_BED || defined MIXED_BED
CASE ('MUD_TAUCR_MIN')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
tcr_min(ng)=Rbed(ng)
END DO
CASE ('MUD_TAUCR_MAX')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
tcr_max(ng)=Rbed(ng)
END DO
CASE ('MUD_TAUCR_SLOPE')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
tcr_slp(ng)=Rbed(ng)
END DO
CASE ('MUD_TAUCR_OFF')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
tcr_off(ng)=Rbed(ng)
END DO
CASE ('MUD_TAUCR_TIME')
Npts=load_r(Nval, Rval, Ngrids, Rbed)
DO ng=1,Ngrids
tcr_tim(ng)=Rbed(ng)
END DO
#endif
CASE ('MUD_Ltsrc', 'MUD_Ltracer')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
LtracerSrc(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('MUD_Ltclm')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
LtracerCLM(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('MUD_Tnudge')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idsed(itrc)
LnudgeTCLM(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Hout(idmud)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idTvar(idsed(itrc))
Hout(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Hout(iMfrac)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idfrac(itrc)
Hout(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Hout(iMmass)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idBmas(itrc)
Hout(i,ng)=Lmud(itrc,ng)
END DO
END DO
#ifdef BEDLOAD
CASE ('Hout(iMUbld)')
DO ng=1,Ngrids
DO itrc=1,NCS
IF (idUbld(itrc).eq.0) THEN
IF (Master) WRITE (out,30) 'idUbld'
exit_flag=5
RETURN
END IF
END DO
END DO
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idUbld(itrc)
Hout(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Hout(iMVbld)')
DO ng=1,Ngrids
DO itrc=1,NCS
IF (idVbld(itrc).eq.0) THEN
IF (Master) WRITE (out,30) 'idVbld'
exit_flag=5
RETURN
END IF
END DO
END DO
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idVbld(itrc)
Hout(i,ng)=Lmud(itrc,ng)
END DO
END DO
#endif
#if defined AVERAGES || \
(defined AD_AVERAGES && defined ADJOINT) || \
(defined RP_AVERAGES && defined TL_IOMS) || \
(defined TL_AVERAGES && defined TANGENT)
CASE ('Aout(idmud)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idTvar(idsed(itrc))
Aout(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Aout(iMTTav)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idTTav(idsed(itrc))
Aout(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Aout(iMUTav)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idUTav(idsed(itrc))
Aout(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Aout(iMVTav)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idVTav(idsed(itrc))
Aout(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Aout(MHUTav)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=iHUTav(idsed(itrc))
Aout(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Aout(MHVTav)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=iHVTav(idsed(itrc))
Aout(i,ng)=Lmud(itrc,ng)
END DO
END DO
# ifdef BEDLOAD
CASE ('Aout(iMUbld)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idUbld(itrc)
Aout(i,ng)=Lmud(itrc,ng)
END DO
END DO
CASE ('Aout(iMVbld)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO itrc=1,NCS
i=idVbld(itrc)
Aout(i,ng)=Lmud(itrc,ng)
END DO
END DO
# endif
#endif
#ifdef DIAGNOSTICS_TS
CASE ('Dout(MTrate)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iTrate),ng)=Lmud(i,ng)
END DO
END DO
CASE ('Dout(MThadv)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iThadv),ng)=Lmud(i,ng)
END DO
END DO
CASE ('Dout(MTxadv)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iTxadv),ng)=Lmud(i,ng)
END DO
END DO
CASE ('Dout(MTyadv)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iTyadv),ng)=Lmud(i,ng)
END DO
END DO
CASE ('Dout(MTvadv)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iTvadv),ng)=Lmud(i,ng)
END DO
END DO
# if defined TS_DIF2 || defined TS_DIF4
CASE ('Dout(MThdif)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iThdif),ng)=Lmud(i,ng)
END DO
END DO
CASE ('Dout(MTxdif)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iTxdif),ng)=Lmud(i,ng)
END DO
END DO
CASE ('Dout(MTydif)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iTydif),ng)=Lmud(i,ng)
END DO
END DO
# if defined MIX_GEO_TS || defined MIX_ISO_TS
CASE ('Dout(MTsdif)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iTsdif),ng)=Lmud(i,ng)
END DO
END DO
# endif
# endif
CASE ('Dout(MTvdif)')
Npts=load_l(Nval, Cval, NCS*Ngrids, Lmud)
DO ng=1,Ngrids
DO i=1,NCS
itrc=idsed(i)
Dout(idDtrc(itrc,iTvdif),ng)=Lmud(i,ng)
END DO
END DO
#endif
CASE ('SAND_SD50')
IF (.not.allocated(Sd50)) allocate (Sd50(NST,Ngrids))
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=NCS+itrc
Sd50(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_CSED')
IF (.not.allocated(Csed)) allocate (Csed(NST,Ngrids))
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand )
DO ng=1,Ngrids
DO itrc=1,NNS
i=NCS+itrc
Csed(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_SRHO')
IF (.not.allocated(Srho)) allocate (Srho(NST,Ngrids))
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=NCS+itrc
Srho(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_WSED')
IF (.not.allocated(Wsed)) allocate (Wsed(NST,Ngrids))
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=NCS+itrc
Wsed(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_ERATE')
IF (.not.allocated(Erate)) allocate (Erate(NST,Ngrids))
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=NCS+itrc
Erate(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_TAU_CE')
IF (.not.allocated(tau_ce)) allocate (tau_ce(NST,Ngrids))
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=NCS+itrc
tau_ce(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_TAU_CD')
IF (.not.allocated(tau_cd)) allocate (tau_cd(NST,Ngrids))
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=NCS+itrc
tau_cd(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_POROS')
IF (.not.allocated(poros)) allocate (poros(NST,Ngrids))
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=NCS+itrc
poros(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_TNU2')
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
nl_tnu2(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_TNU4')
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
nl_tnu4(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('ad_SAND_TNU2')
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
ad_tnu2(i,ng)=Rsand(itrc,ng)
tl_tnu2(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('ad_SAND_TNU4')
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
ad_tnu4(i,ng)=Rsand(itrc,ng)
tl_tnu4(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_Sponge')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
LtracerSponge(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('SAND_AKT_BAK')
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
Akt_bak(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_AKT_fac')
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
ad_Akt_fac(i,ng)=Rsand(itrc,ng)
tl_Akt_fac(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_TNUDG')
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
Tnudg(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_MORPH_FAC')
IF (.not.allocated(morph_fac)) THEN
allocate (morph_fac(NST,Ngrids))
END IF
Npts=load_r(Nval, Rval, NNS*Ngrids, Rsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=NCS+itrc
morph_fac(i,ng)=Rsand(itrc,ng)
END DO
END DO
CASE ('SAND_Ltsrc', 'SAND_Ltracer')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
LtracerSrc(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('SAND_Ltclm')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
LtracerCLM(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('SAND_Tnudge')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idsed(NCS+itrc)
LnudgeTCLM(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Hout(idsand)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idTvar(idsed(NCS+itrc))
Hout(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Hout(iSfrac)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idfrac(NCS+itrc)
Hout(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Hout(iSmass)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idBmas(NCS+itrc)
Hout(i,ng)=Lsand(itrc,ng)
END DO
END DO
#ifdef BEDLOAD
CASE ('Hout(iSUbld)')
DO ng=1,Ngrids
DO itrc=NCS+1,NST
IF (idUbld(itrc).eq.0) THEN
IF (Master) WRITE (out,30) 'idUbld'
exit_flag=5
RETURN
END IF
END DO
END DO
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idUbld(NCS+itrc)
Hout(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Hout(iSVbld)')
DO ng=1,Ngrids
DO itrc=NCS+1,NST
IF (idVbld(itrc).eq.0) THEN
IF (Master) WRITE (out,30) 'idVbld'
exit_flag=5
RETURN
END IF
END DO
END DO
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idVbld(NCS+itrc)
Hout(i,ng)=Lsand(itrc,ng)
END DO
END DO
#endif
#if defined AVERAGES || \
(defined AD_AVERAGES && defined ADJOINT) || \
(defined RP_AVERAGES && defined TL_IOMS) || \
(defined TL_AVERAGES && defined TANGENT)
CASE ('Aout(idsand)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idTvar(idsed(NCS+itrc))
Aout(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Aout(iSTTav)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idTTav(idsed(NCS+itrc))
Aout(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Aout(iSUTav)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idUTav(idsed(NCS+itrc))
Aout(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Aout(iSVTav)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idVTav(idsed(NCS+itrc))
Aout(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Aout(SHUTav)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=iHUTav(idsed(NCS+itrc))
Aout(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Aout(SHVTav)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=iHVTav(idsed(NCS+itrc))
Aout(i,ng)=Lsand(itrc,ng)
END DO
END DO
# ifdef BEDLOAD
CASE ('Aout(iSUbld)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idUbld(NCS+itrc)
Aout(i,ng)=Lsand(itrc,ng)
END DO
END DO
CASE ('Aout(iSVbld)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO itrc=1,NNS
i=idVbld(NCS+itrc)
Aout(i,ng)=Lsand(itrc,ng)
END DO
END DO
# endif
#endif
#ifdef DIAGNOSTICS_TS
CASE ('Dout(STrate)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iTrate),ng)=Lsand(i,ng)
END DO
END DO
CASE ('Dout(SThadv)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iThadv),ng)=Lsand(i,ng)
END DO
END DO
CASE ('Dout(STxadv)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iTxadv),ng)=Lsand(i,ng)
END DO
END DO
CASE ('Dout(STyadv)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iTyadv),ng)=Lsand(i,ng)
END DO
END DO
CASE ('Dout(STvadv)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iTvadv),ng)=Lsand(i,ng)
END DO
END DO
# if defined TS_DIF2 || defined TS_DIF4
CASE ('Dout(SThdif)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iThdif),ng)=Lsand(i,ng)
END DO
END DO
CASE ('Dout(STxdif)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iTxdif),ng)=Lsand(i,ng)
END DO
END DO
CASE ('Dout(STydif)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iTydif),ng)=Lsand(i,ng)
END DO
END DO
# if defined MIX_GEO_TS || defined MIX_ISO_TS
CASE ('Dout(STsdif)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iTsdif),ng)=Lsand(i,ng)
END DO
END DO
# endif
# endif
CASE ('Dout(STvdif)')
Npts=load_l(Nval, Cval, NNS*Ngrids, Lsand)
DO ng=1,Ngrids
DO i=1,NNS
itrc=idsed(NCS+i)
Dout(idDtrc(itrc,iTvdif),ng)=Lsand(i,ng)
END DO
END DO
#endif
CASE ('Hout(ithck)')
Npts=load_l(Nval, Cval, Ngrids, Lbed)
i=idSbed(ithck)
DO ng=1,Ngrids
Hout(i,ng)=Lbed(ng)
END DO
CASE ('Hout(iaged)')
Npts=load_l(Nval, Cval, Ngrids, Lbed)
i=idSbed(iaged)
DO ng=1,Ngrids
Hout(i,ng)=Lbed(ng)
END DO
CASE ('Hout(iporo)')
Npts=load_l(Nval, Cval, Ngrids, Lbed)
i=idSbed(iporo)
DO ng=1,Ngrids
Hout(i,ng)=Lbed(ng)
END DO
#if defined COHESIVE_BED || defined SED_BIODIFF || defined MIXED_BED
CASE ('Hout(ibtcr)')
Npts=load_l(Nval, Cval, Ngrids, Lbed)
i=idSbed(ibtcr)
DO ng=1,Ngrids
Hout(i,ng)=Lbed(ng)
END DO
#endif
CASE ('Hout(idiff)')
Npts=load_l(Nval, Cval, Ngrids, Lbed)
i=idSbed(idiff)
DO ng=1,Ngrids
Hout(i,ng)=Lbed(ng)
END DO
END SELECT
END IF
END DO
10 IF (Master) WRITE (out,40) line
exit_flag=4
RETURN
20 CONTINUE
!
!-----------------------------------------------------------------------
! Report input parameters.
!-----------------------------------------------------------------------
!
IF (Lwrite) THEN
DO ng=1,Ngrids
IF (Lsediment(ng)) THEN
WRITE (out,50) ng
WRITE (out,60)
DO itrc=1,NST
WRITE (out,70) itrc, Sd50(itrc,ng), Csed(itrc,ng), &
& Srho(itrc,ng), Wsed(itrc,ng), &
& Erate(itrc,ng), poros(itrc,ng)
END DO
WRITE (out,80)
DO itrc=1,NST
i=idsed(itrc)
WRITE (out,70) itrc, tau_ce(itrc,ng), tau_cd(itrc,ng), &
& nl_tnu2(i,ng), nl_tnu4(i,ng), &
& Akt_bak(i,ng), Tnudg(i,ng)
END DO
WRITE (out,90)
DO itrc=1,NST
WRITE (out,70) itrc, morph_fac(itrc,ng)
END DO
WRITE (out,100) newlayer_thick(ng)
WRITE (out,110) minlayer_thick(ng)
WRITE (out,120) bedload_coeff(ng)
#ifdef MIXED_BED
WRITE (out,130) transC(ng)
WRITE (out,140) transN(ng)
#endif
DO itrc=1,NST
i=idsed(itrc)
IF (LtracerSponge(i,ng)) THEN
WRITE (out,150) LtracerSponge(i,ng), 'LtracerSponge', &
& i, 'Turning ON sponge on tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
ELSE
WRITE (out,150) LtracerSponge(i,ng), 'LtracerSponge', &
& i, 'Turning OFF sponge on tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
END IF
END DO
DO itrc=1,NST
i=idsed(itrc)
IF (LtracerSrc(i,ng)) THEN
WRITE (out,150) LtracerSrc(i,ng), 'LtracerSrc', i, &
& 'Turning ON point sources/Sink on tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
ELSE
WRITE (out,150) LtracerSrc(i,ng), 'LtracerSrc', i, &
& 'Turning OFF point sources/Sink on tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
END IF
END DO
DO itrc=1,NST
i=idsed(itrc)
IF (LtracerCLM(i,ng)) THEN
WRITE (out,150) LtracerCLM(i,ng), 'LtracerCLM', i, &
& 'Turning ON processing of climatology tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
ELSE
WRITE (out,150) LtracerCLM(i,ng), 'LtracerCLM', i, &
& 'Turning OFF processing of climatology tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
END IF
END DO
DO itrc=1,NST
i=idsed(itrc)
IF (LnudgeTCLM(i,ng)) THEN
WRITE (out,150) LnudgeTCLM(i,ng), 'LnudgeTCLM', i, &
& 'Turning ON nudging of climatology tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
ELSE
WRITE (out,150) LnudgeTCLM(i,ng), 'LnudgeTCLM', i, &
& 'Turning OFF nudging of climatology tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
END IF
END DO
DO itrc=1,NST
i=idTvar(idsed(itrc))
IF (Hout(i,ng)) WRITE (out,160) Hout(i,ng), &
& 'Hout(idTvar)', &
& 'Write out sediment', itrc, TRIM(Vname(1,i))
END DO
DO itrc=1,NST
i=idfrac(itrc)
IF (Hout(i,ng)) WRITE (out,160) Hout(i,ng), &
& 'Hout(idfrac)', &
& 'Write out bed fraction, sediment ', itrc, &
& TRIM(Vname(1,i))
END DO
DO itrc=1,NST
i=idBmas(itrc)
IF (Hout(i,ng)) WRITE (out,160) Hout(i,ng), &
& 'Hout(idfrac)', &
& 'Write out mass, sediment ', itrc, &
& TRIM(Vname(1,i))
END DO
#ifdef BEDLOAD
DO itrc=1,NST
i=idUbld(itrc)
IF (Hout(i,ng)) WRITE (out,160) Hout(i,ng), &
& 'Hout(idUbld)', &
& 'Write out U-bedload, sediment ', itrc, &
& TRIM(Vname(1,i))
i=idVbld(itrc)
IF (Hout(i,ng)) WRITE (out,160) Hout(i,ng), &
& 'Hout(idVbld)', &
& 'Write out V-bedload, sediment ', itrc, &
& TRIM(Vname(1,i))
END DO
#endif
DO itrc=1,MBEDP
i=idSbed(itrc)
IF (Hout(i,ng)) WRITE (out,160) Hout(i,ng), &
& 'Hout(idSbed)', &
& 'Write out BED property ', itrc, TRIM(Vname(1,i))
END DO
#if defined AVERAGES || \
(defined AD_AVERAGES && defined ADJOINT) || \
(defined RP_AVERAGES && defined TL_IOMS) || \
(defined TL_AVERAGES && defined TANGENT)
WRITE (out,'(1x)')
DO itrc=1,NST
i=idTvar(idsed(itrc))
IF (Aout(i,ng)) WRITE (out,160) Aout(i,ng), &
& 'Aout(idTvar)', &
& 'Write out averaged sediment', itrc, TRIM(Vname(1,i))
END DO
DO itrc=1,NST
i=idsed(itrc)
IF (Aout(idTTav(i),ng)) WRITE (out,160) &
& Aout(idTTav(i),ng), 'Aout(idTTav)', &
& 'Write out averaged <t*t> for tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
END DO
DO itrc=1,NST
i=idsed(itrc)
IF (Aout(idUTav(i),ng)) WRITE (out,160) &
& Aout(idUTav(i),ng), 'Aout(idUTav)', &
& 'Write out averaged <u*t> for tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
END DO
DO itrc=1,NST
i=idsed(itrc)
IF (Aout(idVTav(i),ng)) WRITE (out,160) &
& Aout(idVTav(i),ng), 'Aout(idVTav)', &
& 'Write out averaged <v*t> for tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
END DO
DO itrc=1,NST
i=idsed(itrc)
IF (Aout(iHUTav(i),ng)) WRITE (out,160) &
& Aout(iHUTav(i),ng), 'Aout(iHUTav)', &
& 'Write out averaged <Huon*t> for tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
END DO
DO itrc=1,NST
i=idsed(itrc)
IF (Aout(iHVTav(i),ng)) WRITE (out,160) &
& Aout(iHVTav(i),ng), 'Aout(iHVTav)', &
& 'Write out averaged <Hvom*t> for tracer ', i, &
& TRIM(Vname(1,idTvar(i)))
END DO
# ifdef BEDLOAD
DO itrc=1,NST
i=idUbld(itrc)
IF (Aout(i,ng)) WRITE (out,160) Aout(i,ng), &
& 'Aout(idUbld)', &
& 'Write out U-bedload, sediment ', itrc, &
& TRIM(Vname(1,i))
i=idVbld(itrc)
IF (Aout(i,ng)) WRITE (out,160) Aout(i,ng), &
& 'Aout(idVbld)', &
& 'Write out V-bedload, sediment ', itrc, &
& TRIM(Vname(1,i))
END DO
# endif
#endif
#ifdef DIAGNOSTICS_TS
WRITE (out,'(1x)')
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(itrc,iTrate),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iTrate)', &
& 'Write out rate of change of tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(itrc,iThadv),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iThadv)', &
& 'Write out horizontal advection, tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(itrc,iTxadv),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iTxadv)', &
& 'Write out horizontal X-advection, tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(itrc,iTyadv),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iTyadv)', &
& 'Write out horizontal Y-advection, tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(itrc,iTvadv),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iTvadv)', &
& 'Write out vertical advection, tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
# if defined TS_DIF2 || defined TS_DIF4
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(itrc,iThdif),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iThdif)', &
& 'Write out horizontal diffusion, tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(i,iTxdif),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iTxdif)', &
& 'Write out horizontal X-diffusion, tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(itrc,iTydif),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iTydif)', &
& 'Write out horizontal Y-diffusion, tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
# if defined MIX_GEO_TS || defined MIX_ISO_TS
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(itrc,iTsdif),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iTsdif)', &
& 'Write out horizontal S-diffusion, tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
# endif
# endif
DO i=1,NST
itrc=idsed(i)
IF (Dout(idDtrc(itrc,iTvdif),ng)) &
& WRITE (out,160) .TRUE., 'Dout(iTvdif)', &
& 'Write out vertical diffusion, tracer ', itrc, &
& TRIM(Vname(1,idTvar(itrc)))
END DO
#endif
END IF
END DO
END IF
!
!-----------------------------------------------------------------------
! Scale relevant input parameters
!-----------------------------------------------------------------------
!
DO ng=1,Ngrids
DO i=1,NST
Sd50(i,ng)=Sd50(i,ng)*0.001_r8
Wsed(i,ng)=Wsed(i,ng)*0.001_r8
tau_ce(i,ng)=tau_ce(i,ng)/rho0
tau_cd(i,ng)=tau_cd(i,ng)/rho0
nl_tnu4(idsed(i),ng)=SQRT(ABS(nl_tnu4(idsed(i),ng)))
#ifdef ADJOINT
ad_tnu4(idsed(i),ng)=SQRT(ABS(ad_tnu4(idsed(i),ng)))
#endif
#if defined TANGENT || defined TL_IOMS
tl_tnu4(idsed(i),ng)=SQRT(ABS(tl_tnu4(idsed(i),ng)))
#endif
IF (Tnudg(idsed(i),ng).gt.0.0_r8) THEN
Tnudg(idsed(i),ng)=1.0_r8/(Tnudg(idsed(i),ng)*86400.0_r8)
ELSE
Tnudg(idsed(i),ng)=0.0_r8
END IF
END DO
END DO
30 FORMAT (/,' READ_SedPar - variable info not yet loaded, ', a)
40 FORMAT (/,' READ_SedPar - Error while processing line: ',/,a)
50 FORMAT (/,/,' Sediment Parameters, Grid: ',i2.2, &
& /, ' =============================',/)
60 FORMAT (/,1x,'Size',5x,'Sd50',8x,'Csed',8x,'Srho',8x,'Wsed', &
& 8x,'Erate',7x,'poros',/,1x,'Class',4x,'(mm)',7x, &
& '(kg/m3)',5x,'(kg/m3)',5x,'(mm/s)',5x,'(kg/m2/s)',4x, &
& '(nondim)',/)
70 FORMAT (2x,i2,2x,6(1x,1p,e11.4))
80 FORMAT (/,9x,'tau_ce',6x,'tau_cd',6x,'nl_tnu2',5x,'nl_tnu4',5x, &
& 'Akt_bak',6x,'Tnudg',/,9x,'(N/m2)',6x,'(N/m2)',6x, &
& '(m2/s)',6x,'(m4/s)',7x,'(m2/s)',6x,'(day)',/)
90 FORMAT (/,9x,'morph_fac',/,9x,'(nondim)',/)
100 FORMAT (/,' New bed layer formed when deposition exceeds ',e11.4, &
& ' (m).')
110 FORMAT (' Two first layers are combined when 2nd layer smaller ', &
& 'than ',e11.4,' (m).')
120 FORMAT (' Rate coefficient for bed load transport = ',e11.4,/)
130 FORMAT (' Transition for mixed sediment =',e11.4,/)
140 FORMAT (' Transition for cohesive sediment =',e11.4,/)
150 FORMAT (10x,l1,2x,a,'(',i2.2,')',t30,a,i2.2,':',1x,a)
160 FORMAT (10x,l1,2x,a,t29,a,i2.2,':',1x,a)
RETURN
END SUBROUTINE read_SedPar
| theelectricbrain/ROMS-Tidal-Array | ROMS/Nonlinear/Sediment/sediment_inp.h | C | agpl-3.0 | 47,376 |
# == License
# Ekylibre - Simple agricultural ERP
# Copyright (C) 2008-2009 Brice Texier, Thibaud Merigon
# Copyright (C) 2010-2012 Brice Texier
# Copyright (C) 2012-2015 Brice Texier, David Joulin
#
# 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
# 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/>.
#
module Backend
class TrialBalancesController < Backend::BaseController
before_action :save_search_preference, only: :show
def show
set_period_params
unsafe_params = params.to_unsafe_h
dataset_params = {
states: unsafe_params[:states],
natures: unsafe_params[:natures],
balance: unsafe_params[:balance],
accounts: unsafe_params[:accounts],
centralize: unsafe_params[:centralize],
period: unsafe_params[:period],
started_on: unsafe_params[:started_on],
stopped_on: unsafe_params[:stopped_on],
vat_details: unsafe_params[:vat_details],
previous_year: unsafe_params[:previous_year],
levels: unsafe_params.select{|k, v| k =~ /\Alevel_/ && v.to_s == "1"}.map{|k, _v| k.sub('level_', '').to_i}
}
respond_to do |format|
format.html do
@balance = Journal.trial_balance_dataset(dataset_params)
@empty_balances = @balance.length <= 1
notify_now(:please_select_a_period_containing_journal_entries) if @empty_balances
end
format.ods do
return unless template = DocumentTemplate.find_by_nature(:trial_balance)
printer = Printers::TrialBalancePrinter.new(template: template, **dataset_params)
send_data printer.run_ods.bytes, filename: "#{printer.document_name}.ods"
end
format.csv do
return unless template = DocumentTemplate.find_by_nature(:trial_balance)
printer = Printers::TrialBalancePrinter.new(template: template, **dataset_params)
csv_string = CSV.generate(headers: true) do |csv|
printer.run_csv(csv)
end
send_data csv_string, filename: "#{printer.document_name}.csv"
end
format.xcsv do
return unless template = DocumentTemplate.find_by_nature(:trial_balance)
printer = Printers::TrialBalancePrinter.new(template: template, **dataset_params)
csv_string = CSV.generate(headers: true, col_sep: ';', encoding: 'CP1252') do |csv|
printer.run_csv(csv)
end
send_data csv_string, filename: "#{printer.document_name}.csv"
end
format.pdf do
return unless template = find_and_check(:document_template, params[:template])
PrinterJob.perform_later('Printers::TrialBalancePrinter', template: template, perform_as: current_user, **dataset_params)
notify_success(:document_in_preparation)
redirect_back(fallback_location: { action: :index })
end
end
end
end
end
| ekylibre/ekylibre | app/controllers/backend/trial_balances_controller.rb | Ruby | agpl-3.0 | 3,439 |
<?php
namespace FR3D\LdapBundle\Driver;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
class LdapConnection implements LdapConnectionInterface {
private $params = array();
private $logger;
private $ldap_res;
public function __construct(array $params, LoggerInterface $logger = null) {
$this->params = $params;
$this->logger = $logger;
$this->ldap_res = NULL;
}
public function search($baseDn, $filter, array $attributes = array()) {
if ($this->ldap_res == NULL) {
$this->connect();
}
$this
->logDebug(
sprintf("ldap_search(%s, %s, %s, %s)", $this->ldap_res,
$baseDn, $filter, json_encode($attributes)));
$search = ldap_search($this->ldap_res, $baseDn, $filter, $attributes);
if ($search) {
$entries = ldap_get_entries($this->ldap_res, $search);
if (is_array($entries)) {
return $entries;
}
}
return false;
}
public function bind($user_dn, $password) {
if ($this->ldap_res == NULL) {
$this->connect();
}
if (!$user_dn) {
$this->logInfo('You must bind with an ldap user_dn');
return false;
}
if (!$password) {
$this->logInfo('Password can not be null to bind');
return false;
}
return @ldap_bind($this->ldap_res, $user_dn, $password);
}
private function connect() {
$host = $this->params['host'];
if (isset($this->params['useSsl']) && (boolean) $this->params['useSsl']) {
$host = 'ldaps://' . $host;
}
$ress = @ldap_connect($host, $this->params['port']);
if (isset($this->params['useStartTls'])
&& (boolean) $this->params['useStartTls']) {
ldap_start_tls($ress);
}
if (isset($this->params['version'])
&& $this->params['version'] !== null) {
ldap_set_option($ress, LDAP_OPT_PROTOCOL_VERSION,
$this->params['version']);
}
if (isset($this->params['optReferrals'])
&& $this->params['optReferrals'] !== null) {
ldap_set_option($ress, LDAP_OPT_REFERRALS,
$this->params['optReferrals']);
}
if (isset($this->params['username'])
&& $this->params['version'] !== null) {
if (!isset($this->params['password'])) {
throw new \Exception('You must uncomment password key');
}
$bindress = @ldap_bind($ress, $this->params['username'],
$this->params['password']);
if (!$bindress) {
throw new \Exception(
'The credentials you have configured are not valid');
}
} else {
$bindress = @ldap_bind($ress);
if (!$bindress) {
throw new \Exception('Unable to connect Ldap');
}
}
$this->ldap_res = $ress;
}
private function logDebug($message) {
if (!$this->logger) {
return;
}
$this->logger->debug($message);
}
private function logInfo($message) {
if (!$this->logger) {
return;
}
$this->logger->info($message);
}
}
| lolostates/Lap | vendor/bundles/FR3D/LdapBundle/Driver/LdapConnection.php | PHP | agpl-3.0 | 2,745 |
/*
@(#) $RCSfile: InvalidUserAddressException.java,v $ $Name: $($Revision: 1.1.2.1 $) $Date: 2009-06-21 11:34:29 $ <p>
Copyright © 2008-2009 Monavacon Limited <a href="http://www.monavacon.com/"><http://www.monavacon.com/></a>. <br>
Copyright © 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/"><http://www.openss7.com/></a>. <br>
Copyright © 1997-2001 Brian F. G. Bidulock <a href="mailto:bidulock@openss7.org"><bidulock@openss7.org></a>. <p>
All Rights Reserved. <p>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, version 3 of the license. <p>
This program is distributed in the hope that it will be useful, but <b>WITHOUT
ANY WARRANTY</b>; without even the implied warranty of <b>MERCHANTABILITY</b>
or <b>FITNESS FOR A PARTICULAR PURPOSE</b>. See the GNU Affero General Public
License for more details. <p>
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see
<a href="http://www.gnu.org/licenses/"><http://www.gnu.org/licenses/></a>,
or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
02139, USA. <p>
<em>U.S. GOVERNMENT RESTRICTED RIGHTS</em>. If you are licensing this
Software on behalf of the U.S. Government ("Government"), the following
provisions apply to you. If the Software is supplied by the Department of
Defense ("DoD"), it is classified as "Commercial Computer Software" under
paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition
Regulations ("DFARS") (or any successor regulations) and the Government is
acquiring only the license rights granted herein (the license rights
customarily provided to non-Government users). If the Software is supplied to
any unit or agency of the Government other than DoD, it is classified as
"Restricted Computer Software" and the Government's rights in the Software are
defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR")
(or any successor regulations) or, in the cases of NASA, in paragraph
18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). <p>
Commercial licensing and support of this software is available from OpenSS7
Corporation at a fee. See
<a href="http://www.openss7.com/">http://www.openss7.com/</a> <p>
Last Modified $Date: 2009-06-21 11:34:29 $ by $Author: brian $
*/
package jain.protocol.ss7.tcap;
import jain.protocol.ss7.*;
import jain.*;
/**
* This JAIN InvalidUserAddressException is a run time exception thrown
* if a listener with a user-address whose point-code does not match
* that of the stack that owns the provider the listener is registered
* on (i.e. the point code of the Listener does not match the point
* code of the Stack, which the provider is registered on, to which the
* Listener is registered to).
* @version 1.2.2
* @author Monavacon Limited
* @deprecated As of JAIN TCAP v1.1. This class is no longer needed as
* a result of the addition of the InvalidAddressException class.
*/
public class InvalidUserAddressException extends java.lang.RuntimeException {
/** @deprecated
* Constructs a new InvalidUserAddressException with the specified
* detail message.
* @param msg
* The detail message. */
public InvalidUserAddressException(java.lang.String msg) {
super(msg);
}
/** @deprecated
* Constructs a new InvalidUserAddressException. */
public InvalidUserAddressException() {
super();
}
}
// vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
| 0x7678/openss7 | src/java/jain/protocol/ss7/tcap/InvalidUserAddressException.java | Java | agpl-3.0 | 3,786 |
<?php namespace Inkwell\HTTP
{
interface CookieWrapperInterface
{
/**
*
*/
public function wrap($value);
/**
*
*/
public function unwrap($value);
}
}
| dotink/inkwell-http | src/Interfaces/CookieWrapperInterface.php | PHP | agpl-3.0 | 175 |
<?php
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
********************************************************************************/
$mod_strings = array (
'db_last_name' => 'LBL_LIST_LAST_NAME',
'db_first_name' => 'LBL_LIST_FIRST_NAME',
'db_title' => 'LBL_LIST_TITLE',
'db_email1' => 'LBL_LIST_EMAIL_ADDRESS',
'db_email2' => 'LBL_LIST_OTHER_EMAIL_ADDRESS',
'LBL_CONVERT_BUTTON_KEY' => 'V',
'LBL_MODULE_NAME' => 'Потенциальные клиенты',
'LBL_MODULE_ID' => 'Потенциальные клиенты',
'LBL_INVITEE' => 'Прямые отчеты',
'LBL_MODULE_TITLE' => 'Потенциальные клиенты: Главная',
'LBL_SEARCH_FORM_TITLE' => 'Поиск потенциального клиента',
'LBL_LIST_FORM_TITLE' => 'Целевой список',
'LBL_NEW_FORM_TITLE' => 'Новый потенциальный клиент',
'LBL_PROSPECT' => 'Потенциальный клиент:',
'LBL_BUSINESSCARD' => 'Визитная карточка',
'LBL_LIST_NAME' => 'Имя',
'LBL_LIST_LAST_NAME' => 'Фамилия',
'LBL_LIST_PROSPECT_NAME' => 'Имя потенциального клиента',
'LBL_LIST_TITLE' => 'Должность',
'LBL_LIST_EMAIL_ADDRESS' => 'E-mail',
'LBL_LIST_OTHER_EMAIL_ADDRESS' => 'Другой e-mail-адрес',
'LBL_LIST_PHONE' => 'Телефон',
'LBL_LIST_PROSPECT_ROLE' => 'Роль',
'LBL_LIST_FIRST_NAME' => 'Имя',
'LBL_ASSIGNED_TO_NAME' => 'Ответственный (-ая)',
'LBL_ASSIGNED_TO_ID' => 'Ответственный (-ая)',
'LBL_CAMPAIGN_ID' => 'Маркетинговая кампания',
'LBL_EXISTING_PROSPECT' => 'Использован существующий контакт',
'LBL_CREATED_PROSPECT' => 'Создан новый контакт',
'LBL_EXISTING_ACCOUNT' => 'Использован существующий контрагент',
'LBL_CREATED_ACCOUNT' => 'Создан новый контрагент',
'LBL_CREATED_CALL' => 'Создан новый звонок',
'LBL_CREATED_MEETING' => 'Создана новая встреча',
'LBL_ADDMORE_BUSINESSCARD' => 'Добавить еще одну визитную карточку',
'LBL_ADD_BUSINESSCARD' => 'Добавить визитную карточку',
'LBL_NAME' => 'Имя',
'LBL_FULL_NAME' => 'Имя',
'LBL_PROSPECT_NAME' => 'Имя потенциального клиента:',
'LBL_PROSPECT_INFORMATION' => 'Описание потенциального клиента',
'LBL_MORE_INFORMATION' => 'Подробная информация',
'LBL_FIRST_NAME' => 'Имя',
'LBL_OFFICE_PHONE' => 'Рабочий тел.:',
'LBL_ANY_PHONE' => 'Тел.:',
'LBL_PHONE' => 'Телефон:',
'LBL_LAST_NAME' => 'Фамилия:',
'LBL_MOBILE_PHONE' => 'Мобильный тел.:',
'LBL_HOME_PHONE' => 'Домашний тел.:',
'LBL_OTHER_PHONE' => 'Дополнительный тел.:',
'LBL_FAX_PHONE' => 'Факс:',
'LBL_PRIMARY_ADDRESS_STREET' => 'Основной адрес - улица:',
'LBL_PRIMARY_ADDRESS_CITY' => 'Основной адрес - город:',
'LBL_PRIMARY_ADDRESS_COUNTRY' => 'Основной адрес - страна:',
'LBL_PRIMARY_ADDRESS_STATE' => 'Основной адрес - область:',
'LBL_PRIMARY_ADDRESS_POSTALCODE' => 'Основной адрес - индекс:',
'LBL_ALT_ADDRESS_STREET' => 'Альтернативный адрес - улица:',
'LBL_ALT_ADDRESS_CITY' => 'Альтернативный адрес - город:',
'LBL_ALT_ADDRESS_COUNTRY' => 'Альтернативный адрес - страна:',
'LBL_ALT_ADDRESS_STATE' => 'Альтернативный адрес - область:',
'LBL_ALT_ADDRESS_POSTALCODE' => 'Альтернативный адрес - индекс:',
'LBL_TITLE' => 'Должность',
'LBL_DEPARTMENT' => 'Отдел:',
'LBL_BIRTHDATE' => 'Дата рождения:',
'LBL_EMAIL_ADDRESS' => 'E-mail-адрес:',
'LBL_OTHER_EMAIL_ADDRESS' => 'Другой E-mail:',
'LBL_ANY_EMAIL' => 'E-mail:',
'LBL_ASSISTANT' => 'Ассистент:',
'LBL_ASSISTANT_PHONE' => 'Телефон ассистента:',
'LBL_DO_NOT_CALL' => 'Не звонить:',
'LBL_EMAIL_OPT_OUT' => 'Не писать на E-mail:',
'LBL_PRIMARY_ADDRESS' => 'Основной адрес:',
'LBL_ALTERNATE_ADDRESS' => 'Другой адрес:',
'LBL_ANY_ADDRESS' => 'Адрес:',
'LBL_CITY' => 'Город:',
'LBL_STATE' => 'Область:',
'LBL_POSTAL_CODE' => 'Индекс:',
'LBL_COUNTRY' => 'Страна:',
'LBL_DESCRIPTION_INFORMATION' => 'Описание',
'LBL_ADDRESS_INFORMATION' => 'Адресная информация',
'LBL_DESCRIPTION' => 'Описание:',
'LBL_PROSPECT_ROLE' => 'Роль:',
'LBL_OPP_NAME' => 'Сделка:',
'LBL_IMPORT_VCARD' => 'Импортирование vCard',
'LBL_IMPORT_VCARDTEXT' => 'Автоматическое создание нового контакта при импортировании файла vCard.',
'LBL_DUPLICATE' => 'Возможно дублирующий потенциальный клиент',
'MSG_SHOW_DUPLICATES' => 'Запись, которую Вы создаете, возможно, дублирует уже имеющуюся запись. Похожие потенциальные клиенты показаны ниже. Нажмите кнопку "Сохранить" для продолжения создания нового потенциального клиента или кнопку "Отмена" для возврата в модуль без создания потенциального клиента.',
'MSG_DUPLICATE' => 'Запись, которую Вы создаете, возможно, дублирует уже имеющуюся запись. Похожие потенциальные клиенты показаны ниже. Нажмите кнопку "Сохранить" для продолжения создания нового потенциального клиента или кнопку "Отмена" для возврата в модуль без создания потенциального клиента.',
'LNK_IMPORT_VCARD' => 'Создать из vCard',
'LNK_NEW_ACCOUNT' => 'Новый контрагент',
'LNK_NEW_OPPORTUNITY' => 'Новая сделка',
'LNK_NEW_CASE' => 'Новое обращение',
'LNK_NEW_NOTE' => 'Создать заметку или вложение',
'LNK_NEW_CALL' => 'Журнал звонков',
'LNK_NEW_EMAIL' => 'Отправить E-mail в архив',
'LNK_NEW_MEETING' => 'Назначить встречу',
'LNK_NEW_TASK' => 'Новая задача',
'LNK_NEW_APPOINTMENT' => 'Назначить встречу',
'LNK_IMPORT_PROSPECTS' => 'Импорт потенциальных клиентов',
'NTC_DELETE_CONFIRMATION' => 'Вы действительно хотите удалить эту запись?',
'NTC_REMOVE_CONFIRMATION' => 'Вы действительно хотите удалить этот контакт из данного обращения?',
'NTC_REMOVE_DIRECT_REPORT_CONFIRMATION' => 'Вы уверены, что хотите удалить эту запись из прямых отчетов?',
'ERR_DELETE_RECORD' => 'Вы должны указать номер записи перед удалением контакта.',
'NTC_COPY_PRIMARY_ADDRESS' => 'Копировать основной адрес в альтернативный',
'NTC_COPY_ALTERNATE_ADDRESS' => 'Копировать альтернативный адрес в основной',
'LBL_SALUTATION' => 'Обращение',
'LBL_SAVE_PROSPECT' => 'Сохранить потенциального клиента',
'LBL_CREATED_OPPORTUNITY' => 'Создана новая сделка',
'NTC_OPPORTUNITY_REQUIRES_ACCOUNT' => 'Для создания сделки необходим контрагент.\\n Пожалуйста, или создайте новый контрагент или выберите один из уже существующих.',
'LNK_SELECT_ACCOUNT' => 'Выбрать контрагента',
'LNK_NEW_PROSPECT' => 'Создать потенциального клиента',
'LNK_PROSPECT_LIST' => 'Обзор потенциальных клиантов',
'LNK_NEW_CAMPAIGN' => 'Создать маркетинговую кампанию',
'LNK_CAMPAIGN_LIST' => 'Маркетинговые кампании',
'LNK_NEW_PROSPECT_LIST' => 'Создать целевой список',
'LNK_PROSPECT_LIST_LIST' => 'Целевые списки',
'LNK_IMPORT_PROSPECT' => 'Импорт потенциальных клиентов',
'LBL_SELECT_CHECKED_BUTTON_LABEL' => 'Выбрать отмеченных потенциальных клиентов',
'LBL_SELECT_CHECKED_BUTTON_TITLE' => 'Выбрать отмеченных потенциальных клиентов',
'LBL_INVALID_EMAIL' => 'Неверный E-mail:',
'LBL_DEFAULT_SUBPANEL_TITLE' => 'Потенциальные клиенты',
'LBL_PROSPECT_LIST' => 'Список потенциальных клиентов',
'LBL_CONVERT_BUTTON_TITLE' => 'Преобразовать потенциального клиента',
'LBL_CONVERT_BUTTON_LABEL' => 'Преобразовать потенциального клиента',
'LBL_CONVERTPROSPECT' => 'Преобразовать потенциального клиента',
'LNK_NEW_CONTACT' => 'Новый контакт',
'LBL_CREATED_CONTACT' => 'Создан новый контакт',
'LBL_BACKTO_PROSPECTS' => 'Вернуться к потенциальным клиентам',
'LBL_CAMPAIGNS' => 'Маркетинговые кампании',
'LBL_CAMPAIGN_LIST_SUBPANEL_TITLE' => 'Журнал маркетинговых кампании',
'LBL_TRACKER_KEY' => 'Трекер: ',
'LBL_LEAD_ID' => 'Предварительный контакт',
'LBL_CONVERTED_LEAD' => 'Преобразованный предварительный контакт',
'LBL_ACCOUNT_NAME' => 'Контрагент',
'LBL_EDIT_ACCOUNT_NAME' => 'Контрагент:',
'LBL_CREATED_USER' => 'Создано пользователем',
'LBL_MODIFIED_USER' => 'Изменено пользователем',
'LBL_CAMPAIGNS_SUBPANEL_TITLE' => 'Маркетинговые кампании',
'LBL_HISTORY_SUBPANEL_TITLE' => 'Заметки',
);
| harish-patel/ecrm | modules/Prospects/language/ru_RU.lang.php | PHP | agpl-3.0 | 12,231 |
# Copyright (C) 2021 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class SaleOrder(models.Model):
_inherit = "sale.order"
def action_confirm(self):
res = super(SaleOrder, self).action_confirm()
for order in self:
order.procurement_group_id.stock_move_ids.created_production_id.write(
{"analytic_account_id": order.analytic_account_id}
)
return res
| OCA/account-analytic | mrp_analytic_sale_project/models/sale_order.py | Python | agpl-3.0 | 490 |
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 Asqatasun.org
*
* 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/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.accessiweb22;
import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of the rule 10.1.3 of the referential Accessiweb 2.2.
* <br/>
* For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/accessiweb2.2/10.Presentation_of_information/Rule-10.1.3.html">the rule 10.1.3 design page.</a>
* @see <a href="http://www.accessiweb.org/index.php/accessiweb-22-english-version.html#test-10-1-3"> 10.1.3 rule specification</a>
*
*/
public class Aw22Rule10013 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Aw22Rule10013 () {
super();
}
}
| dzc34/Asqatasun | rules/rules-accessiweb2.2/src/main/java/org/asqatasun/rules/accessiweb22/Aw22Rule10013.java | Java | agpl-3.0 | 1,536 |
package com.gildorymrp.core.feat;
import com.gildorymrp.api.plugin.core.ActiveFeat;
import com.gildorymrp.api.plugin.core.Character;
import com.gildorymrp.api.plugin.core.Feat;
public class ManyShot implements ActiveFeat {
@Override
public String getDescription() {
return "Shoot two or more arrows simultaneously";
}
@Override
public boolean hasPrerequisites(Character character) {
if (character.getDexterity() >= 17) {
if (character.getAttackBonus() >= 6) {
for (Feat feat : character.getFeats()) {
if (feat instanceof RapidShot) {
return true;
}
}
}
}
return false;
}
@Override
public boolean isFighterBonusFeat() {
return true;
}
}
| Hohahihehu/GildorymCore | src/com/gildorymrp/core/feat/ManyShot.java | Java | agpl-3.0 | 691 |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'blog.views.entry_list', name="entry-list"),
url(r'^archive/(?P<year>\d{4})/$', 'blog.views.entry_archive_year', name="year-archive"),
url(r'^archive/(?P<year>\d{4})/(?P<month>\d{1,2})/$', 'blog.views.entry_archive_month', name="month-archive"),
url(r'^(?P<slug>[-\w]+)/$', 'blog.views.entry_detail', name="entry-detail"),
)
| tsoporan/tehorng | blog/urls.py | Python | agpl-3.0 | 421 |
<?php
//*****************************************************************************
// This will allow an occurrences of a database table to be updated.
// The identity of the selected occurrence is passed down from the previous screen.
//*****************************************************************************
$table_id = 'survey_section'; // table id
$screen = 'survey_section.detail.screen.inc'; // file identifying screen structure
// identify extra parameters for a JOIN
$sql_select = NULL;
$sql_from = NULL;
$sql_where = NULL;
require 'std.update1.inc'; // activate page controller
?>
| apmuthu/radicore | radicore/survey/survey_section_upd.php | PHP | agpl-3.0 | 639 |
from twisted.trial.unittest import TestCase
from mock import Mock
from twisted.web.test.test_web import DummyRequest
from twisted.web.http import OK, NOT_FOUND
from cryptosync.resources import make_site
def make_request(uri='', method='GET', args={}):
site = make_site(authenticator=Mock())
request = DummyRequest(uri.split('/'))
request.method = method
request.args = args
resource = site.getResourceFor(request)
request.render(resource)
request.data = "".join(request.written)
return request
class RootResourceResponseCodesTestCase(TestCase):
def test_root_resource_ok(self):
request = make_request()
self.assertEquals(request.responseCode, OK)
def test_root_resource_not_found_url(self):
request = make_request(uri='shouldneverfindthisthing')
self.assertEquals(request.responseCode, NOT_FOUND)
class AuthResourceTestCase(TestCase):
def _try_auth(self, credentials, expected):
request = make_request(uri='/auth/', method='POST', args=credentials)
self.assertEquals(request.responseCode, OK)
self.assertEquals(request.data, expected)
def test_auth_success_with_good_parameters(self):
credentials = {'username': 'myself', 'password': 'somethingawesome'}
self._try_auth(credentials, '{"status": "success"}')
def test_auth_failure_with_missing_parameters(self):
credentials = {'username': 'myself', 'password': 'somethingawesome'}
for (k, v) in credentials.items():
self._try_auth({k: v}, '{"status": "failure"}')
| shyba/cryptosync | cryptosync/tests/test_webserver.py | Python | agpl-3.0 | 1,579 |
class EvaluationCommentNotifier
def initialize(args = {})
@comment = args.fetch(:comment)
end
def process
send_evaluation_comment_email
end
private
def send_evaluation_comment_email
EvaluationCommentEmail.new(@comment).to.each do |to|
Mailer.evaluation_comment(@comment, to).deliver_later
end
end
end
| AyuntamientoPuertoReal/decidePuertoReal | app/models/evaluation_comment_notifier.rb | Ruby | agpl-3.0 | 349 |
DELETE FROM `weenie` WHERE `class_Id` = 8637;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (8637, 'swordbludgeoning', 6, '2019-02-10 00:00:00') /* MeleeWeapon */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (8637, 1, 1) /* ItemType - MeleeWeapon */
, (8637, 5, 350) /* EncumbranceVal */
, (8637, 9, 1048576) /* ValidLocations - MeleeWeapon */
, (8637, 16, 1) /* ItemUseable - No */
, (8637, 19, 1) /* Value */
, (8637, 51, 1) /* CombatUse - Melee */
, (8637, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (8637, 151, 2) /* HookType - Wall */
, (8637, 8041, 101) /* PCAPRecordedPlacement - Resting */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (8637, 22, True ) /* Inscribable */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (8637, 39, 1.25) /* DefaultScale */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (8637, 1, 'Bludgeoning Sword') /* Name */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (8637, 1, 33554731) /* Setup */
, (8637, 3, 536870932) /* SoundTable */
, (8637, 6, 67111919) /* PaletteBase */
, (8637, 8, 100668855) /* Icon */
, (8637, 22, 872415275) /* PhysicsEffectTable */
, (8637, 8001, 270615064) /* PCAPRecordedWeenieHeader - Value, Usable, CombatUse, Container, ValidLocations, Burden, HookType */
, (8637, 8003, 18) /* PCAPRecordedObjectDesc - Inscribable, Attackable */
, (8637, 8005, 137345) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, STable, PeTable, AnimationFrame */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (8637, 8000, 2154335152) /* PCAPRecordedObjectIID */;
INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (8637, 67111919, 0, 0);
INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (8637, 0, 83888778, 83888778);
INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`)
VALUES (8637, 0, 16777893);
| LtRipley36706/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/MeleeWeapon/MeleeWeapon/08637 Bludgeoning Sword.sql | SQL | agpl-3.0 | 2,300 |
SUBDIRS = doxel-dev docker-atom
.PHONY: subdirs $(SUBDIRS)
subdirs: $(SUBDIRS)
$(SUBDIRS):
$(MAKE) -C $@
| doxel/doxel-docker | Makefile | Makefile | agpl-3.0 | 110 |
# encoding: utf-8
#--
###############################################################################
# #
# A component of rss2mail, the RSS to e-mail forwarder. #
# #
# Copyright (C) 2007-2014 Jens Wille #
# #
# Authors: #
# Jens Wille <jens.wille@gmail.com> #
# #
# rss2mail 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. #
# #
# rss2mail 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 rss2mail. If not, see <http://www.gnu.org/licenses/>. #
# #
###############################################################################
#++
module RSS2Mail
module Transport
HOST = ENV['HOSTNAME'] || ENV['HOST'] || %x{hostname}.chomp.freeze
FROM = "From: rss2mail@#{HOST}".freeze
module Mail
require 'open3'
require 'nuggets/file/which'
CMD = ENV['RSS2MAIL_MAIL_CMD'] || 'mail'.freeze
BIN = ENV['RSS2MAIL_MAIL_BIN'] || File.which(CMD)
def check_deliver_requirements
raise "Mail command not found: #{CMD}" unless BIN
end
def deliver_mail(to, subject, body, type)
Open3.popen3(
BIN, '-e',
'-a', type,
'-a', FROM,
'-s', subject,
*to
) { |mail, _, _|
mail.puts body
}
end
end
module SMTP
require 'net/smtp'
require 'securerandom'
DEFAULT_HOST = 'localhost'.freeze
DEFAULT_PORT = Net::SMTP.default_port
MESSAGE_TEMPLATE = <<-EOT
<%= FROM %>
To: <%= Array(to).join(', ') %>
Date: <%= Time.now.rfc822 %>
Subject: <%= subject %>
Message-Id: <%= SecureRandom.uuid %>
<%= type %>
<%= body %>
EOT
def deliver_mail(to, *args)
deliver_smtp(Net::SMTP, [to], *args)
end
private
def deliver_smtp(klass, tos, subject, body, type)
klass.start(*@smtp) { |smtp|
tos.each { |to|
smtp.send_message(
ERB.new(MESSAGE_TEMPLATE).result(binding),
FROM,
*to
)
}
}
end
end
module LMTP
include SMTP
DEFAULT_PORT = SMTP::DEFAULT_PORT - 1
def deliver_mail(to, *args)
deliver_smtp(Net::LMTP, to, *args)
end
end
end
end
module Net
class LMTP < SMTP
# Send LMTP's LHLO command instead of SMTP's HELO command
def helo(domain)
getok("LHLO #{domain}")
end
# Send LMTP's LHLO command instead of ESMTP's EHLO command
def ehlo(domain)
getok("LHLO #{domain}")
end
end
end
| blackwinter/rss2mail | lib/rss2mail/transport.rb | Ruby | agpl-3.0 | 3,813 |
DELETE FROM `weenie` WHERE `class_Id` = 15203;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (15203, 'ahrzonasign', 1, '2019-02-10 00:00:00') /* Generic */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (15203, 1, 128) /* ItemType - Misc */
, (15203, 5, 9000) /* EncumbranceVal */
, (15203, 16, 1) /* ItemUseable - No */
, (15203, 19, 125) /* Value */
, (15203, 93, 1048) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (15203, 1, True ) /* Stuck */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (15203, 1, 'Ahr-Zona') /* Name */
, (15203, 16, 'Welcome to Ahr-Zona') /* LongDesc */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (15203, 1, 0x02000BD7) /* Setup */
, (15203, 8, 0x060012D3) /* Icon */
, (15203, 8001, 2097176) /* PCAPRecordedWeenieHeader - Value, Usable, Burden */
, (15203, 8003, 20) /* PCAPRecordedObjectDesc - Stuck, Attackable */
, (15203, 8005, 32769) /* PCAPRecordedPhysicsDesc - CSetup, Position */;
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 (15203, 8040, 0x96640024, 108.896, 82.0406, 14, -0.92537, 0, 0, -0.379064) /* PCAPRecordedLocation */
/* @teleloc 0x96640024 [108.896000 82.040600 14.000000] -0.925370 0.000000 0.000000 -0.379064 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (15203, 8000, 0x796641B1) /* PCAPRecordedObjectIID */;
| ACEmulator/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/Generic/Misc/15203 Ahr-Zona.sql | SQL | agpl-3.0 | 1,767 |
<?php
/**
* \details © 2018 Open Ximdex Evolution SL [http://www.ximdex.org]
*
* Ximdex a Semantic Content Management System (CMS)
*
* 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.
*
* See the Affero GNU General Public License for more details.
* You should have received a copy of the Affero GNU General Public License
* version 3 along with Ximdex (see LICENSE file).
*
* If not, visit http://gnu.org/licenses/agpl-3.0.html.
*
* @author Ximdex DevTeam <dev@ximdex.com>
* @version $Revision$
*/
namespace Ximdex\MVC\Render;
use Ximdex\Models\Action;
use Ximdex\Models\Node;
use Ximdex\Runtime\App;
use Ximdex\Runtime\Session;
/**
* @brief Abstract renderer who acts as base for all renderers
*
* Pseudo Abstract renderer class who stablish a base for all renderers, provides
* some basic functionality and deals with some session parameters
*/
class AbstractRenderer
{
var $_template;
/**
* @var \Ximdex\Behaviours\AssociativeArray
*/
var $_parameters;
/**
* AbstractRenderer constructor
*
* @param null $fileName
*/
function __construct($fileName = NULL)
{
$this->displayEncoding = App::getValue('displayEncoding');
$this->_template = $fileName;
$this->_parameters = new \Ximdex\Behaviours\AssociativeArray();
}
function getTemplate()
{
return $this->_template;
}
function setTemplate($fileName)
{
$this->_template = $fileName;
}
function add($key, $value)
{
return $this->_parameters->add($key, $value);
}
/**
* @return array
*/
function & getParameters()
{
return $this->_parameters->getArray();
}
function setParameters($array)
{
if (is_array($array)) {
foreach ($array as $idx => $data) {
$this->set($idx, $data);
}
}
}
function set($key, $value)
{
return $this->_parameters->set($key, $value);
}
function render($view = null)
{
$actionID = $this->get('actionid');
$nodeID = $this->get('nodeid');
$actionName = $this->get('actionName');
$module = $this->get('module');
$method = $this->get('method');
$method = empty($method) ? 'index' : $method;
$method = empty($view) ? $method : $view;
$action = new Action($actionID);
$_ACTION_COMMAND = ($actionName) ? $actionName : $action->get('Command');
$base_action = null;
// Si se ha lanzado una accion se visualiza la accion, sino se ejecuta el composer
if (! isset($_ACTION_COMMAND) || $_ACTION_COMMAND != "composer") {
// Definicion de algunos parametros utiles
if ($nodeID > 0) {
$this->_set_node_params($nodeID);
}
$this->set('id_action', $actionID);
$this->_set_action_url($this->get('action_url'), $nodeID, $actionID, $actionName);
$base_action = $this->_set_module($module, $_ACTION_COMMAND);
$this->_set_action_property($action->get('Name'), $action->get('Description'), $_ACTION_COMMAND, $base_action);
} else {
//Visualizamos el composer(al no haber accion)
$_ACTION_COMMAND = "composer";
$this->_set_action_property("composer", "visualiza los componentes de la web", "composer", "/actions/composer/");
}
$this->set('_URL_ROOT', App::getValue('UrlRoot'));
$this->set('_APP_ROOT', XIMDEX_ROOT_PATH);
// Si es la misma accion que se ha ejecutado en FrontControllerHttp:
// Guardamos los datos en los valores de session
$this->_set_session_params($actionID, $_ACTION_COMMAND, $method, $nodeID, $module, $base_action);
// Encode the content to the display Encoding from Config
foreach ($this->_parameters->_data as $key => $value) {
if (is_array($value)) {
$this->_parameters->_data[$key] = \Ximdex\XML\Base::encodeArrayElement($this->_parameters->_data[$key], $this->displayEncoding);
} else {
$this->_parameters->_data[$key] = \Ximdex\XML\Base::encodeSimpleElement($this->_parameters->_data[$key], $this->displayEncoding);
}
}
}
function & get($key)
{
return $this->_parameters->get($key);
}
private function _set_node_params($nodeID)
{
$node = new Node($nodeID);
// Mandamos el padre a la plantilla para cuando toque recargar el node
$this->set('id_node_parent', $node->get('IdParent'));
$this->set('node_name', $node->get('Name'));
$this->set('id_node', $nodeID);
$path = pathinfo($node->getPath());
$ruta = "";
if (! empty($path) && array_key_exists("dinarme", $path)) {
$path_split = explode("/", $path['dirname']);
$max = count($path_split);
for ($i = 0; $i < $max; $i++) {
if (!empty($path_split[$i]))
$path_split[$i] = _($path_split[$i]) . " ";
}
$path["dirname"] = implode("/", $path_split);
$ruta .= $path['dirname'] . '/<b>';
}
if (! empty($path["basename"])) {
$path["basename"] = _($path['basename']);
$ruta .= $path["basename"] . "</b>";
} else {
$ruta .= "</b>";
}
$ruta = str_replace("/", "/ ", $ruta);
$ruta = str_replace("</ b>", "</b>", $ruta);
$this->set('_NODE_PATH', $ruta);
}
private function _set_action_url($action_url = null, $nodeID = null, $actionID = null, $actionName = null)
{
// If a destination URL have not been given, we add the default action
if ($action_url == null) {
$query = App::get('\Ximdex\Utils\QueryManager');
$go_method = $this->get('go_method');
if (! empty($go_method)) {
$query->add('method', $go_method);
}
if (! empty($actionID)) {
$query->add('actionid', $actionID);
}
if (! empty($actionName)) {
$query->add('action', $actionName);
}
if (! empty($nodeID)) {
$query->add('nodeid', $nodeID);
$query->add('nodes', array($nodeID));
}
$this->set('action_url', $query->getPage() . $query->build());
}
}
private function _set_module($module, $action_command)
{
if ($module) {
$base_action = XIMDEX_ROOT_PATH . \Ximdex\Modules\Manager::path($module) . "/actions/" . $action_command . "/";
// We indicate the specfieds module parameters
$this->set("base_module", XIMDEX_ROOT_PATH . \Ximdex\Modules\Manager::path($module) . "/");
$this->set("module", $module);
} else {
$base_action = App::getValue('UrlFrontController') . "/actions/" . $action_command . "/";
}
return $base_action;
}
private function _set_action_property($_name, $_desc, $_command, $_base)
{
$this->set('_ACTION_COMMAND', $_command);
$this->set("base_action", $_base);
}
/**
* @param $actionID
* @param $_ACTION_COMMAND
* @param $method
* @param $nodeID
* @param $module
* @param $base_action
*/
private function _set_session_params($actionID, $action_command, $method, $nodeID, $module, $base_action)
{
if (Session::get("actionId") == $actionID) {
Session::set("action", $action_command);
Session::set("method", $method);
Session::set("nodeId", $nodeID);
Session::set("module", $module);
Session::set("base_action", $base_action);
}
}
}
| XIMDEX/ximdex | src/MVC/Render/AbstractRenderer.php | PHP | agpl-3.0 | 8,343 |
--[[
Illarion Server
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/>.
]]
-- triggerfields for better atmosphere
--[[ SQL Statements:
INSERT INTO triggerfields VALUES (X,Y,Z,'triggerfield.akaltutschamber_ambient');
]]
local common = require("base.common")
local ambient_base = require("triggerfield.base.ambient")
local M = {}
--[[
position: coordinates
direction: array with directions, 0=North,2=East,4=South,6=West. Set nil for always
german/english: text
hours: array with hours when text shall be shown, in range of 0 to 23. Set to nil for always.
months: array with months when text shall be shown, in range of 1 to 16. Set to nil for always.
chance: Chance that this triggerfield is triggered in percent (integer)
for script:
DragorogList.add( position(x,y,z), {0,1,7}, "german", "english", {0,1,23}, {1,2,16}, chance );
for db:
INSERT INTO triggerfields VALUES (x,y,z,'triggerfield.dragorog_cult_ambient');
]]
local DragorogList = ambient_base()
DragorogList.add( position(384,465,2),nil,"Es liegt ein beissender Gestank nach Schwefel, verrottendem Abfall und Verwesung in der Luft.","There is an acrid stench of a mixture of sulphur, rotting waste and decay in the air.",nil,nil,50);
DragorogList.add( position(410,477,2),nil,"Der ganze Boden ist mit abgenagten Knochen bedeckt und nicht alle davon sehen aus, als ob sie von Tieren stammen würden.","The entire floor is covered with gnawed off bones and not all of them look, as though they belonged to animals.",nil,nil,50);
DragorogList.add( position(438,448,2),nil,"Das Gebäude ist erstaunlich gemütlich eingerichtet und wirkt gut gepflegt.","The building seems surprisingly comfortablly furnished and looks well-kept.",nil,nil,50);
DragorogList.add( position(410,443,2),nil,"Von der anderen Seite der Brücke her, hörst du ein leises Kratzen, als würde jemand mit einer besonders drahtigen Bürste über Stein fahren.","From across the bridge you hear a faint scratching noise, as though somebody is scrubbing over a stone with a particularly wiry brush.",nil,nil,50);
function M.MoveToField(Char)
local this = DragorogList.get(Char)
if this then
common.InformNLS(Char, this.german, this.english)
end
end
return M
| Illarion-eV/Illarion-Content | triggerfield/dragorog_cult_ambient.lua | Lua | agpl-3.0 | 2,790 |
# Copyright 2017 ForgeFlow S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Order Approved",
"summary": "Add a new state 'Approved' in purchase orders.",
"version": "14.0.1.1.0",
"category": "Purchases",
"website": "https://github.com/OCA/purchase-workflow",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["purchase_stock"],
"data": ["views/purchase_order_view.xml", "views/res_config_view.xml"],
}
| OCA/purchase-workflow | purchase_order_approved/__manifest__.py | Python | agpl-3.0 | 569 |
/*
*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
/**
* EquationGroups.js
*
* Created by Alexey Musinov on 29/10/14
* Copyright (c) 2018 Ascensio System SIA. All rights reserved.
*
*/
define([
'backbone',
'documenteditor/main/app/model/EquationGroup'
], function(Backbone){ 'use strict';
DE.Collections = DE.Collections || {};
DE.Collections.EquationGroups = Backbone.Collection.extend({
model: DE.Models.EquationGroup
});
});
| ONLYOFFICE/web-apps | apps/documenteditor/main/app/collection/EquationGroups.js | JavaScript | agpl-3.0 | 1,970 |
"""
Copyright (C) 2008 by Steven Wallace
snwallace@gmail.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the
Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""
from __future__ import with_statement
import struct
import threading
import sys, traceback, time
def cascadeSetIn(a, b):
a.setIn(b)
return b
class NetworkException(Exception):
pass
class Filter:
def __init__(self, *args):
self.input = None
self.output = None
self.server = False
self.master = None
self.initialized = threading.Event()
self.wlock = threading.Lock()
self.rlock = threading.Lock()
self.init_lock = threading.Lock()
self._init(*args)
def _init(self, *args):
pass
def disconnect(self):
if self.input:
self.input.disconnect()
def begin(self):
with self.init_lock:
if not self.initialized.isSet():
self._begin()
if self.input:
if not self.initialized.isSet():
self.initialized.wait()
self.input.begin()
def _begin(self):
self.initialized.set()
def end(self):
if self.output:
self.output.end()
def setIn(self, input = None):
self.input = input
if input:
input.setOut(self)
def setOut(self, output = None):
self.output = output
def readIn(self, data):
self.writeOut(data)
def readOut(self, data):
with self.rlock:
self._readOut(data)
def _readOut(self, data):
self.writeIn(data)
def writeIn(self, data):
if self.input:
self.input.readOut(data)
def writeOut(self, data):
self.initialized.wait()
with self.wlock:
self._writeOut(data)
def _writeOut(self, data):
if self.output:
self.output.readIn(data)
def error(self, error):
raise NetworkException(error)
class PacketizerFilter(Filter):
def _init(self):
self.received = ""
def _readOut(self, data):
self.received += data
while len(self.received) > 3:
length ,= struct.unpack("!i",self.received[:4])
if length + 4 <= len(self.received):
self.writeIn(self.received[4:length+4])
self.received = self.received[length+4:]
else:
return
def _writeOut(self, data):
Filter._writeOut(self, struct.pack("!i",len(data))+data)
class CompressionFilter(Filter):
def _init(self):
self.algorithms = {}
self.otherAlgorithms = []
try:
import zlib
self.algorithms['z'] = zlib
except:
pass
try:
import bz2
self.algorithms['b'] = bz2
except:
pass
try:
import noCompress
self.algorithms['n'] = noCompress
except:
pass
def _begin(self):
if self.server:
self._writeOut(''.join(self.algorithms.keys()))
def _readOut(self, data):
if not self.initialized.isSet():
if self.server:
self.otherAlgorithms = [i for i in data]
self.initialized.set()
self.begin()
else:
self.otherAlgorithms = [i for i in data]
self._writeOut(''.join(self.algorithms.keys()))
self.initialized.set()
self.begin()
else:
algorithm = data[0]
if algorithm not in self.algorithms:
self.error("UNKNOWN COMPRESSION ALGORITHM " + data)
self.writeIn(self.algorithms[algorithm].decompress(data[1:]))
def _writeOut(self, data):
if not self.initialized:
Filter._writeOut(self, data)
else:
algorithm = 'n'
newData = data
for i in self.otherAlgorithms:
if i in self.algorithms:
tmpData = self.algorithms[i].compress(data, 9)
if len(tmpData) < len(newData):
newData = tmpData
algorithm = i
Filter._writeOut(self, ''.join((algorithm, newData)))
def EncryptionFilter(Filter):
pass #TODO
class TCPFilter(Filter):
def _init(self, connection = None):
self.connection = connection
def _writeOut(self, data):
if self.connection:
try:
self.connection.send(data)
except:
pass
def poll(self):
try:
data = self.connection.recv(4096)
if data:
self.readOut(data)
else:
self.disconnect()
except:
print "bleh!"
traceback.print_exc(file=sys.stdout)
self.disconnect()
def disconnect(self):
self.master.remove(self.connection)
if self.connection:
self.connection.close()
Filter.disconnect(self)
def end(self):
self.disconnect()
| joshbohde/megaminer-framework | server/networking/Filter.py | Python | agpl-3.0 | 5,766 |
PREFIX=/usr/local
all::
doc::
clean::
install::
all::botvot
botvot: com.informatimago.small-cl-pgms.botvot.asd botvot.lisp generate-application.lisp
ccl --no-init --load generate-application.lisp --eval '(ccl:quit)'
install::botvot
install -m 755 botvot /usr/local/sbin/botvot
# pandoc -f org -t asciidoc < botvot.org > botvot-fr.asc
.PHONY:doc html
#### THE END ####
| informatimago/lisp | small-cl-pgms/botvot/Makefile | Makefile | agpl-3.0 | 376 |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- template designed by Marco Von Ballmoos -->
<title>Docs for page Transparency.php</title>
<link rel="stylesheet" href="../../media/stylesheet.css" />
<script src="../../media/lib/classTree.js"></script>
<script language="javascript" type="text/javascript">
var imgPlus = new Image();
var imgMinus = new Image();
imgPlus.src = "../../media/images/plus.png";
imgMinus.src = "../../media/images/minus.png";
function showNode(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
var oImg = document.layers["img" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
var oImg = document.all["img" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
var oImg = document.getElementById("img" + Node);
break;
}
oImg.src = imgMinus.src;
oTable.style.display = "block";
}
function hideNode(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
var oImg = document.layers["img" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
var oImg = document.all["img" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
var oImg = document.getElementById("img" + Node);
break;
}
oImg.src = imgPlus.src;
oTable.style.display = "none";
}
function nodeIsVisible(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
break;
}
return (oTable && oTable.style.display == "block");
}
function toggleNodeVisibility(Node){
if (nodeIsVisible(Node)){
hideNode(Node);
}else{
showNode(Node);
}
}
</script>
</head>
<body>
<div class="page-body">
<h2 class="file-name"><img src="../../media/images/Page_logo.png" alt="File" style="vertical-align: middle">/Gdata/Extension/Transparency.php</h2>
<a name="sec-description"></a>
<div class="info-box">
<div class="info-box-title">Description</div>
<div class="nav-bar">
<span class="disabled">Description</span> |
<a href="#sec-classes">Classes</a>
| <a href="#sec-includes">Includes</a>
</div>
<div class="info-box-body">
<!-- ========== Info from phpDoc block ========= -->
<p class="short-description">Zend Framework</p>
<p class="description"><p>LICENSE</p><p>This source file is subject to the new BSD license that is bundled with this package in the file LICENSE.txt. It is also available through the world-wide-web at this URL: http://framework.zend.com/license/new-bsd If you did not receive a copy of the license and are unable to obtain it through the world-wide-web, please send an email to license@zend.com so we can send you a copy immediately.</p></p>
<ul class="tags">
<li><span class="field">copyright:</span> Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)</li>
<li><span class="field">license:</span> <a href="http://framework.zend.com/license/new-bsd">New BSD License</a></li>
</ul>
</div>
</div>
<a name="sec-classes"></a>
<div class="info-box">
<div class="info-box-title">Classes</div>
<div class="nav-bar">
<a href="#sec-description">Description</a> |
<span class="disabled">Classes</span>
| <a href="#sec-includes">Includes</a>
</div>
<div class="info-box-body">
<table cellpadding="2" cellspacing="0" class="class-table">
<tr>
<th class="class-table-header">Class</th>
<th class="class-table-header">Description</th>
</tr>
<tr>
<td style="padding-right: 2em; vertical-align: top; white-space: nowrap">
<img src="../../media/images/Class.png"
alt=" class"
title=" class"/>
<a href="../../Zend_Gdata/Gdata/Zend_Gdata_Extension_Transparency.html">Zend_Gdata_Extension_Transparency</a>
</td>
<td>
Data model class to represent an entry's transparency
</td>
</tr>
</table>
</div>
</div>
<a name="sec-includes"></a>
<div class="info-box">
<div class="info-box-title">Includes</div>
<div class="nav-bar">
<a href="#sec-description">Description</a> |
<a href="#sec-classes">Classes</a>
| <span class="disabled">Includes</span>
</div>
<div class="info-box-body">
<a name="_Zend/Gdata/Extension_php"><!-- --></a>
<div class="oddrow">
<div>
<img src="../../media/images/Page.png" alt=" " />
<span class="include-title">
<span class="include-type">require_once</span>
(<span class="include-name">'Zend/Gdata/Extension.php'</span>)
(line <span class="line-number">26</span>)
</span>
</div>
<!-- ========== Info from phpDoc block ========= -->
<ul class="tags">
<li><span class="field">see:</span> <a href="../../Zend_Gdata/Gdata/Zend_Gdata_Extension.html">Zend_Gdata_Extension</a></li>
</ul>
</div>
</div>
</div>
<p class="notes" id="credit">
Documentation generated on Fri, 12 Dec 2008 11:54:54 -0800 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.2</a>
</p>
</div></body>
</html> | ftrotter/btg | trunk/ZendGdata-1.7.1+Health/documentation/api/core/Zend_Gdata/Gdata/_Gdata---Extension---Transparency.php.html | HTML | agpl-3.0 | 6,124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.