code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.plannodes; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.json_voltpatches.JSONStringer; import org.voltdb.VoltType; import org.voltdb.catalog.Database; import org.voltdb.expressions.AbstractExpression; import org.voltdb.expressions.TupleValueExpression; /** * This class encapsulates the data and operations needed to track columns * in the planner. * */ public class SchemaColumn { public enum Members { COLUMN_NAME, EXPRESSION, } /** * Create a new SchemaColumn * @param tableName The name of the table where this column originated, * if any. Currently, internally created columns will be assigned * the table name "VOLT_TEMP_TABLE" for disambiguation. * @param columnName The name of this column, if any * @param columnAlias The alias assigned to this column, if any * @param expression The input expression which generates this * column. SchemaColumn needs to have exclusive ownership * so that it can adjust the index of any TupleValueExpressions * without affecting other nodes/columns/plan iterations, so * it clones this expression. */ public SchemaColumn(String tableName, String columnName, String columnAlias, AbstractExpression expression) { m_tableName = tableName; m_columnName = columnName; m_columnAlias = columnAlias; try { m_expression = (AbstractExpression) expression.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); } } /** * Clone a schema column */ @Override protected SchemaColumn clone() { return new SchemaColumn(m_tableName, m_columnName, m_columnAlias, m_expression); } /** * Return a copy of this SchemaColumn, but with the input expression * replaced by an appropriate TupleValueExpression. */ public SchemaColumn copyAndReplaceWithTVE() { TupleValueExpression new_exp = null; if (m_expression instanceof TupleValueExpression) { try { new_exp = (TupleValueExpression) m_expression.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); } } else { new_exp = new TupleValueExpression(); // XXX not sure this is right new_exp.setTableName(m_tableName); new_exp.setColumnName(m_columnName); new_exp.setColumnAlias(m_columnAlias); new_exp.setValueType(m_expression.getValueType()); new_exp.setValueSize(m_expression.getValueSize()); } return new SchemaColumn(m_tableName, m_columnName, m_columnAlias, new_exp); } public String getTableName() { return m_tableName; } public String getColumnName() { return m_columnName; } public String getColumnAlias() { return m_columnAlias; } public AbstractExpression getExpression() { return m_expression; } public VoltType getType() { return m_expression.getValueType(); } public int getSize() { return m_expression.getValueSize(); } /** * Check if this SchemaColumn provides the column specified by the input * arguments. A match is defined as matching both the table name and * the column name if it is provided, otherwise matching the provided alias. * @param tableName * @param columnName * @param columnAlias * @return */ public boolean matches(String tableName, String columnName, String columnAlias) { boolean retval = false; if (tableName.equals(m_tableName)) { if (columnName != null && !columnName.equals("")) { if (columnName.equals(m_columnName)) { retval = true; } } else if (columnAlias != null && !columnAlias.equals("")) { if (columnAlias.equals(m_columnAlias)) { retval = true; } } else if (tableName.equals("VOLT_TEMP_TABLE")) { retval = true; } else { throw new RuntimeException("Attempted to match a SchemaColumn " + "but provided no name or alias."); } } return retval; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SchemaColumn:\n"); sb.append("\tTable Name: ").append(m_tableName).append("\n"); sb.append("\tColumn Name: ").append(m_columnName).append("\n"); sb.append("\tColumn Alias: ").append(m_columnAlias).append("\n"); sb.append("\tColumn Type: ").append(getType()).append("\n"); sb.append("\tColumn Size: ").append(getSize()).append("\n"); sb.append("\tExpression: ").append(m_expression.toString()).append("\n"); return sb.toString(); } public void toJSONString(JSONStringer stringer) throws JSONException { stringer.object(); // Tell the EE that the column name is either a valid column // alias or the original column name if no alias exists. This is a // bit hacky, but it's the easiest way for the EE to generate // a result set that has all the aliases that may have been specified // by the user (thanks to chains of setOutputTable(getInputTable)) if (getColumnAlias() != null && !getColumnAlias().equals("")) { stringer.key(Members.COLUMN_NAME.name()).value(getColumnAlias()); } else if (getColumnName() != null) { stringer.key(Members.COLUMN_NAME.name()).value(getColumnName()); } else { stringer.key(Members.COLUMN_NAME.name()).value(""); } if (m_expression != null) { stringer.key(Members.EXPRESSION.name()); stringer.object(); m_expression.toJSONString(stringer); stringer.endObject(); } else { stringer.key(Members.EXPRESSION.name()).value(""); } stringer.endObject(); } public static SchemaColumn fromJSONObject( JSONObject jobj, Database db ) throws JSONException { String tableName = ""; String columnName = ""; String columnAlias = ""; AbstractExpression expression = null; if( !jobj.isNull( Members.COLUMN_NAME.name() ) ){ columnName = jobj.getString( Members.COLUMN_NAME.name() ); } if( !jobj.isNull( Members.EXPRESSION.name() ) ) { expression = AbstractExpression.fromJSONObject( jobj.getJSONObject( Members.EXPRESSION.name() ), db); } return new SchemaColumn( tableName, columnName, columnAlias, expression ); } private String m_tableName; private String m_columnName; private String m_columnAlias; private AbstractExpression m_expression; }
kobronson/cs-voltdb
src/frontend/org/voltdb/plannodes/SchemaColumn.java
Java
agpl-3.0
8,242
/** * 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 cn.dlb.bim.models.store; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Double Type</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link cn.dlb.bim.models.store.DoubleType#getValue <em>Value</em>}</li> * </ul> * * @see cn.dlb.bim.models.store.StorePackage#getDoubleType() * @model * @generated */ public interface DoubleType extends PrimitiveType { /** * Returns the value of the '<em><b>Value</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>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>Value</em>' attribute. * @see #setValue(double) * @see cn.dlb.bim.models.store.StorePackage#getDoubleType_Value() * @model * @generated */ double getValue(); /** * Sets the value of the '{@link cn.dlb.bim.models.store.DoubleType#getValue <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Value</em>' attribute. * @see #getValue() * @generated */ void setValue(double value); } // DoubleType
shenan4321/BIMplatform
generated/cn/dlb/bim/models/store/DoubleType.java
Java
agpl-3.0
1,970
package placebooks.client.parser; import com.google.gwt.core.client.JsonUtils; public abstract class EnumParser<T extends Enum<?>> implements JSONParser<Enum<?>> { @Override public void write(final StringBuilder builder, final Enum<?> object) { builder.append(JsonUtils.escapeValue(object.toString())); } }
cdparra/reminiscens-book
placebooks-webapp/src/placebooks/client/parser/EnumParser.java
Java
agpl-3.0
314
/* This file is part of Ingen. Copyright 2007-2016 David Robillard <http://drobilla.net/> Ingen 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. Ingen 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 details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #include "ingen/Log.hpp" #include "ingen/ColorContext.hpp" #include "ingen/Node.hpp" #include "ingen/URIs.hpp" #include "ingen/World.hpp" #include "lv2/core/lv2.h" #include "lv2/log/log.h" #include "lv2/urid/urid.h" #include "raul/Path.hpp" #include <cstdio> #include <cstdlib> namespace ingen { Log::Log(LV2_Log_Log* log, URIs& uris) : _log(log) , _uris(uris) , _flush(false) , _trace(false) {} void Log::rt_error(const char* msg) { #ifndef NDEBUG va_list args; vtprintf(_uris.log_Error, msg, args); #endif } void Log::error(const std::string& msg) { va_list args; vtprintf(_uris.log_Error, msg.c_str(), args); } void Log::warn(const std::string& msg) { va_list args; vtprintf(_uris.log_Warning, msg.c_str(), args); } void Log::info(const std::string& msg) { va_list args; vtprintf(_uris.log_Note, msg.c_str(), args); } void Log::trace(const std::string& msg) { va_list args; vtprintf(_uris.log_Trace, msg.c_str(), args); } void Log::print(FILE* stream, const std::string& msg) const { fprintf(stream, "%s", msg.c_str()); if (_flush) { fflush(stdout); } } int Log::vtprintf(LV2_URID type, const char* fmt, va_list args) { int ret = 0; if (type == _uris.log_Trace && !_trace) { return 0; } else if (_sink) { _sink(type, fmt, args); } if (_log) { ret = _log->vprintf(_log->handle, type, fmt, args); } else if (type == _uris.log_Error) { ColorContext ctx(stderr, ColorContext::Color::RED); ret = vfprintf(stderr, fmt, args); } else if (type == _uris.log_Warning) { ColorContext ctx(stderr, ColorContext::Color::YELLOW); ret = vfprintf(stderr, fmt, args); } else if (type == _uris.log_Note) { ColorContext ctx(stderr, ColorContext::Color::GREEN); ret = vfprintf(stdout, fmt, args); } else if (_trace && type == _uris.log_Trace) { ColorContext ctx(stderr, ColorContext::Color::GREEN); ret = vfprintf(stderr, fmt, args); } else { fprintf(stderr, "Unknown log type %u\n", type); return 0; } if (_flush) { fflush(stdout); } return ret; } static int log_vprintf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list args) { auto* f = static_cast<Log::Feature::Handle*>(handle); va_list noargs = {}; int ret = f->log->vtprintf(type, f->node->path().c_str(), noargs); ret += f->log->vtprintf(type, ": ", noargs); ret += f->log->vtprintf(type, fmt, args); return ret; } static int log_printf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, ...) { va_list args; va_start(args, fmt); const int ret = log_vprintf(handle, type, fmt, args); va_end(args); return ret; } static void free_log_feature(LV2_Feature* feature) { auto* lv2_log = static_cast<LV2_Log_Log*>(feature->data); free(lv2_log->handle); free(feature); } std::shared_ptr<LV2_Feature> Log::Feature::feature(World& world, Node* block) { auto* handle = static_cast<Handle*>(calloc(1, sizeof(Handle))); handle->lv2_log.handle = handle; handle->lv2_log.printf = log_printf; handle->lv2_log.vprintf = log_vprintf; handle->log = &world.log(); handle->node = block; auto* f = static_cast<LV2_Feature*>(malloc(sizeof(LV2_Feature))); f->URI = LV2_LOG__log; f->data = &handle->lv2_log; return std::shared_ptr<LV2_Feature>(f, &free_log_feature); } } // namespace ingen
drobilla/ingen
src/Log.cpp
C++
agpl-3.0
3,977
""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email})
nttks/edx-platform
biz/djangoapps/gx_login/views.py
Python
agpl-3.0
3,215
<?php // created: 2015-04-10 14:10:28 $mod_strings = array ( 'LBL_LEADS' => 'Sellers', 'LBL_ACCOUNTS_SUBPANEL_TITLE' => 'Buyers', 'LBL_AOS_PRODUCTS_DOCUMENTS_2_FROM_AOS_PRODUCTS_TITLE' => 'Properties Information', 'LBL_DOC_ACTIVE_DATE' => 'Document Dated', 'LBL_TEMPLATE_TYPE' => 'Template Type', );
shoaib-fazal16/yourown
custom/modules/Documents/language/en_us.lang.php
PHP
agpl-3.0
309
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.opencps.dossiermgt.service.persistence; import com.liferay.portal.kernel.dao.orm.BaseActionableDynamicQuery; import com.liferay.portal.kernel.exception.SystemException; import org.opencps.dossiermgt.model.ServiceConfig; import org.opencps.dossiermgt.service.ServiceConfigLocalServiceUtil; /** * @author trungnt * @generated */ public abstract class ServiceConfigActionableDynamicQuery extends BaseActionableDynamicQuery { public ServiceConfigActionableDynamicQuery() throws SystemException { setBaseLocalService(ServiceConfigLocalServiceUtil.getService()); setClass(ServiceConfig.class); setClassLoader(org.opencps.dossiermgt.service.ClpSerializer.class.getClassLoader()); setPrimaryKeyPropertyName("serviceConfigId"); } }
hltn/opencps
portlets/opencps-portlet/docroot/WEB-INF/service/org/opencps/dossiermgt/service/persistence/ServiceConfigActionableDynamicQuery.java
Java
agpl-3.0
1,346
# This file is part of VoltDB. # Copyright (C) 2008-2018 VoltDB Inc. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # All the commands supported by the Voter application. import os @VOLT.Command(description = 'Build the Voter application and catalog.', options = VOLT.BooleanOption('-C', '--conditional', 'conditional', 'only build when the catalog file is missing')) def build(runner): if not runner.opts.conditional or not os.path.exists('voter.jar'): runner.java.compile('obj', 'src/voter/*.java', 'src/voter/procedures/*.java') runner.call('volt.compile', '-c', 'obj', '-o', 'voter.jar', 'ddl.sql') @VOLT.Command(description = 'Clean the Voter build output.') def clean(runner): runner.shell('rm', '-rfv', 'obj', 'debugoutput', 'voter.jar', 'voltdbroot') @VOLT.Server('create', description = 'Start the Voter VoltDB server.', command_arguments = 'voter.jar', classpath = 'obj') def server(runner): runner.call('build', '-C') runner.go() @VOLT.Java('voter.AsyncBenchmark', classpath = 'obj', description = 'Run the Voter asynchronous benchmark.') def async(runner): runner.call('build', '-C') runner.go() @VOLT.Java('voter.SyncBenchmark', classpath = 'obj', description = 'Run the Voter synchronous benchmark.') def sync(runner): runner.call('build', '-C') runner.go() @VOLT.Java('voter.JDBCBenchmark', classpath = 'obj', description = 'Run the Voter JDBC benchmark.') def jdbc(runner): runner.call('build', '-C') runner.go() @VOLT.Java('voter.SimpleBenchmark', classpath = 'obj', description = 'Run the Voter simple benchmark.') def simple(runner): runner.call('build', '-C') runner.go()
simonzhangsm/voltdb
tools/voter.d/voter.py
Python
agpl-3.0
2,792
'use strict'; describe('itemListService', function() { beforeEach(module('superdesk.mocks')); beforeEach(module('superdesk.templates-cache')); beforeEach(module('superdesk.itemList')); beforeEach(module(function($provide) { $provide.service('api', function($q) { return function ApiService(endpoint, endpointParam) { return { query: function(params) { params._endpoint = endpoint; params._endpointParam = endpointParam; return $q.when(params); } }; }; }); })); it('can query with default values', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch() .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams).toEqual({ _endpoint: 'search', _endpointParam: undefined, source: { query: { filtered: {} }, size: 25, from: 0, sort: [{_updated: 'desc'}] } }); })); it('can query with endpoint', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ endpoint: 'archive', endpointParam: 'param' }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams._endpoint).toBe('archive'); expect(queryParams._endpointParam).toBe('param'); })); it('can query with page', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ pageSize: 15, page: 3 }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.size).toBe(15); expect(queryParams.source.from).toBe(30); })); it('can query with sort', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ sortField: '_id', sortDirection: 'asc' }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.sort).toEqual([{_id: 'asc'}]); })); it('can query with repos', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ repos: ['archive', 'ingest'] }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.repo).toBe('archive,ingest'); })); it('can query with types', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ types: ['text', 'picture', 'composite'] }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and[0].terms.type).toEqual( ['text', 'picture', 'composite'] ); })); it('can query with states', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ states: ['spiked', 'published'] }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and[0].or).toEqual([ {term: {state: 'spiked'}}, {term: {state: 'published'}} ]); })); it('can query with notStates', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ notStates: ['spiked', 'published'] }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and).toEqual([ {not: {term: {state: 'spiked'}}}, {not: {term: {state: 'published'}}} ]); })); it('can query with dates', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ creationDateBefore: 1, creationDateAfter: 2, modificationDateBefore: 3, modificationDateAfter: 4 }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and).toEqual([ {range: {_created: {lte: 1, gte: 2}}}, {range: {_updated: {lte: 3, gte: 4}}} ]); })); it('can query with provider, source and urgency', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ provider: 'reuters', source: 'reuters_1', urgency: 5 }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and).toEqual([ {term: {provider: 'reuters'}}, {term: {source: 'reuters_1'}}, {term: {urgency: 5}} ]); })); it('can query with headline, subject, keyword, uniqueName and body search', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ headline: 'h', subject: 's', keyword: 'k', uniqueName: 'u', body: 'b' }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.query).toEqual({ query_string: { query: 'headline:(*h*) subject.name:(*s*) slugline:(*k*) unique_name:(*u*) body_html:(*b*)', lenient: false, default_operator: 'AND' } }); })); it('can query with general search', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ search: 's' }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.query).toEqual({ query_string: { query: 'headline:(*s*) subject.name:(*s*) slugline:(*s*) unique_name:(*s*) body_html:(*s*)', lenient: false, default_operator: 'OR' } }); })); it('can query with saved search', inject(function($rootScope, itemListService, api, $q) { var params; api.get = angular.noop; spyOn(api, 'get').and.returnValue($q.when({filter: {query: {type: '["text"]'}}})); itemListService.fetch({ savedSearch: {_links: {self: {href: 'url'}}} }).then(function(_params) { params = _params; }); $rootScope.$digest(); expect(params.source.post_filter.and).toContain({ terms: {type: ['text']} }); })); it('related items query without hypen', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ keyword: 'kilo', related: true }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.query).toEqual({ prefix: { 'slugline.phrase': 'kilo' } }); })); it('related items query with hypen', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ keyword: 'kilo-gram', related: true }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.query).toEqual({ prefix: { 'slugline.phrase': 'kilo gram' } }); })); });
plamut/superdesk
client/app/scripts/superdesk/itemList/itemList_spec.js
JavaScript
agpl-3.0
8,544
/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "clustering.h" #include "seeks_proxy.h" #include "errlog.h" #include "miscutil.h" #include "lsh_configuration.h" using sp::errlog; using sp::miscutil; using sp::seeks_proxy; using lsh::lsh_configuration; using lsh::stopwordlist; namespace seeks_plugins { /*- centroid. -*/ centroid::centroid() { } /*- cluster. -*/ cluster::cluster() :_rank(0.0) { } void cluster::add_point(const uint32_t &id, hash_map<uint32_t,float,id_hash_uint> *p) { hash_map<uint32_t,hash_map<uint32_t,float,id_hash_uint>*,id_hash_uint>::iterator hit; if ((hit=_cpoints.find(id))!=_cpoints.end()) { errlog::log_error(LOG_LEVEL_ERROR, "Trying to add a snippet multiple times to the same cluster"); } else _cpoints.insert(std::pair<uint32_t,hash_map<uint32_t,float,id_hash_uint>*>(id,p)); } void cluster::compute_rank(const query_context *qc) { _rank = 0.0; hash_map<uint32_t,hash_map<uint32_t,float,id_hash_uint>*,id_hash_uint>::const_iterator hit = _cpoints.begin(); while (hit!=_cpoints.end()) { search_snippet *sp = qc->get_cached_snippet((*hit).first); _rank += sp->_seeks_rank; // summing up the seeks rank yields a cluster rank (we could use the mean instead). ++hit; } } void cluster::compute_label(const query_context *qc) { // compute total tf-idf weight for features of docs belonging to this cluster. hash_map<uint32_t,float,id_hash_uint> f_totals; hash_map<uint32_t,float,id_hash_uint>::iterator fhit,hit2; hash_map<uint32_t,hash_map<uint32_t,float,id_hash_uint>*,id_hash_uint>::const_iterator hit = _cpoints.begin(); while (hit!=_cpoints.end()) { hit2 = (*hit).second->begin(); while (hit2!=(*hit).second->end()) { if ((fhit=f_totals.find((*hit2).first))!=f_totals.end()) { (*fhit).second += (*hit2).second; } else f_totals.insert(std::pair<uint32_t,float>((*hit2).first,(*hit2).second)); ++hit2; } ++hit; } // grab features with the highest tf-idf weight. std::map<float,uint32_t,std::greater<float> > f_mtotals; fhit = f_totals.begin(); while (fhit!=f_totals.end()) { f_mtotals.insert(std::pair<float,uint32_t>((*fhit).second,(*fhit).first)); ++fhit; } f_totals.clear(); // we need query words and a stopword list for rejecting labels. std::vector<std::string> words; miscutil::tokenize(qc->_query,words," "); size_t nwords = words.size(); stopwordlist *swl = seeks_proxy::_lsh_config->get_wordlist(qc->_auto_lang); // turn features into word labels. int k=0; int KW = 2; // number of words per label. TODO: use weights for less/more words... std::map<float,uint32_t,std::greater<float> >::iterator mit = f_mtotals.begin(); while (mit!=f_mtotals.end()) { bool found = false; if (k>KW) break; else { hit = _cpoints.begin(); while (hit!=_cpoints.end()) { uint32_t id = (*hit).first; search_snippet *sp = qc->get_cached_snippet(id); hash_map<uint32_t,std::string,id_hash_uint>::const_iterator bit; if ((bit=sp->_bag_of_words->find((*mit).second))!=sp->_bag_of_words->end()) { // two checks needed: whether the word already belongs to the query // (can happen after successive use of cluster label queries); // whether the word belongs to the english stop word list (because // whatever the query language, some english results sometimes gets in). bool reject = false; for (size_t i=0; i<nwords; i++) { if (words.at(i) == (*bit).second) // check against query word. { reject = true; break; } } if (!reject) { reject = swl->has_word((*bit).second); // check against the english stopword list. } if (reject) { ++hit; continue; } /* std::cerr << "adding to label: " << (*bit).second << " --> " << (*mit).first << std::endl; */ if (!_label.empty()) _label += " "; _label += (*bit).second; found = true; break; } ++hit; } } ++mit; if (found) k++; } //std::cerr << "label: " << _label << std::endl; } /*- clustering. -*/ clustering::clustering() :_qc(NULL),_K(0),_clusters(NULL),_cluster_labels(NULL) { } clustering::clustering(query_context *qc, const std::vector<search_snippet*> &snippets, const short &K) :_qc(qc),_K(K),_snippets(snippets) { _clusters = new cluster[_K]; _cluster_labels = new std::vector<std::string>[_K]; // setup points and dimensions. size_t nsp = _snippets.size(); for (size_t s=0; s<nsp; s++) { search_snippet *sp = _snippets.at(s); if (sp->_features_tfidf) _points.insert(std::pair<uint32_t,hash_map<uint32_t,float,id_hash_uint>*>(sp->_id,sp->_features_tfidf)); } } clustering::~clustering() { if (_clusters) delete[] _clusters; if (_cluster_labels) delete[] _cluster_labels; }; void clustering::post_processing() { // rank snippets within clusters. rank_clusters_elements(); // rank clusters. compute_clusters_rank(); // sort clusters. std::stable_sort(_clusters,_clusters+_K,cluster::max_rank_cluster); // compute labels. compute_cluster_labels(); } // default ranking is as computed by seeks on the main list of results. void clustering::rank_elements(cluster &cl) { hash_map<uint32_t,hash_map<uint32_t,float,id_hash_uint>*,id_hash_uint>::iterator hit = cl._cpoints.begin(); while (hit!=cl._cpoints.end()) { search_snippet *sp = _qc->get_cached_snippet((*hit).first); sp->_seeks_ir = sp->_seeks_rank; ++hit; } } void clustering::rank_clusters_elements() { for (short c=0; c<_K; c++) rank_elements(_clusters[c]); } void clustering::compute_clusters_rank() { for (short c=0; c<_K; c++) _clusters[c].compute_rank(_qc); } void clustering::compute_cluster_labels() { for (short c=0; c<_K; c++) _clusters[c].compute_label(_qc); } hash_map<uint32_t,float,id_hash_uint>* clustering::get_point_features(const short &np) { short p = 0; hash_map<uint32_t,hash_map<uint32_t,float,id_hash_uint>*,id_hash_uint>::const_iterator hit = _points.begin(); while (hit!=_points.end()) { if (p == np) return (*hit).second; p++; ++hit; } return NULL; } } /* end of namespace. */
Psycojoker/seeks
src/plugins/websearch/clustering.cpp
C++
agpl-3.0
8,174
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace Merp.Accountancy.Drafts.Model { [ComplexType] public class PartyInfo { public Guid OriginalId { get; set; } //[Index] [MaxLength(100)] public string Name { get; set; } public string StreetName { get; set; } public string PostalCode { get; set; } public string City { get; set; } public string Country { get; set; } public string VatIndex { get; set; } public string NationalIdentificationNumber { get; set; } } }
mastreeno/Merp
src/Merp.Accountancy.Drafts/Model/PartyInfo.cs
C#
agpl-3.0
687
package com.x.message.assemble.communicate.jaxrs.connector; import com.x.base.core.project.exception.PromptException; class ExceptionZhengwuDingdingMessage extends PromptException { private static final long serialVersionUID = 4132300948670472899L; ExceptionZhengwuDingdingMessage(Integer retCode, String retMessage) { super("发送政务钉钉消息失败,错误代码:{},错误消息:{}.", retCode, retMessage); } }
o2oa/o2oa
o2server/x_message_assemble_communicate/src/main/java/com/x/message/assemble/communicate/jaxrs/connector/ExceptionZhengwuDingdingMessage.java
Java
agpl-3.0
427
package org.neo4j.extensions.spring.indexes; import java.util.Map; /** * UserIndex indexed properties. * * * @author bradnussbaum * @version 0.1.0 * * @since 0.1.0 * */ public enum UserIndex { lastModifiedTime(IndexType.user_exact), email(IndexType.user_fulltext), name(IndexType.user_fulltext), username(IndexType.user_fulltext); private IndexType type; private UserIndex(IndexType type) { this.type = type; } public Map<String, String> getIndexType() { return type.getIndexType(); } public String getIndexName() { return type.name(); } }
objectundefined/neo4j-extensions
neo4j-extensions-spring/src/main/java/org/neo4j/extensions/spring/indexes/UserIndex.java
Java
agpl-3.0
632
<?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 Health * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: ProfileEntry.php 23772 2011-02-28 21:35:29Z ralph $ */ /** * @see Zend_Gdata_Entry */ require_once 'Zend/Gdata/Entry.php'; /** * @see Zend_Gdata_Health_Extension_Ccr */ require_once 'Zend/Gdata/Health/Extension/Ccr.php'; /** * Concrete class for working with Health profile entries. * * @link http://code.google.com/apis/health/ * * @category Zend * @package Zend_Gdata * @subpackage Health * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Health_ProfileEntry extends Zend_Gdata_Entry { /** * The classname for individual profile entry elements. * * @var string */ protected $_entryClassName = 'Zend_Gdata_Health_ProfileEntry'; /** * Google Health CCR data * * @var Zend_Gdata_Health_Extension_Ccr */ protected $_ccrData = null; /** * Constructs a new Zend_Gdata_Health_ProfileEntry object. * @param DOMElement $element (optional) The DOMElement on which to base this object. */ public function __construct($element = null) { foreach (Zend_Gdata_Health::$namespaces as $nsPrefix => $nsUri) { $this->registerNamespace($nsPrefix, $nsUri); } parent::__construct($element); } /** * Retrieves a DOMElement which corresponds to this element and all * child properties. This is used to build an entry back into a DOM * and eventually XML text for application storage/persistence. * * @param DOMDocument $doc The DOMDocument used to construct DOMElements * @return DOMElement The DOMElement representing this element and all * child properties. */ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_ccrData !== null) { $element->appendChild($this->_ccrData->getDOM($element->ownerDocument)); } return $element; } /** * Creates individual Entry objects of the appropriate type and * stores them as members of this entry based upon DOM data. * * @param DOMNode $child The DOMNode to process */ protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; if (strstr($absoluteNodeName, $this->lookupNamespace('ccr') . ':')) { $ccrElement = new Zend_Gdata_Health_Extension_Ccr(); $ccrElement->transferFromDOM($child); $this->_ccrData = $ccrElement; } else { parent::takeChildFromDOM($child); } } /** * Sets the profile entry's CCR data * @param string $ccrXMLStr The CCR as an xml string * @return Zend_Gdata_Health_Extension_Ccr */ public function setCcr($ccrXMLStr) { $ccrElement = null; if ($ccrXMLStr != null) { $ccrElement = new Zend_Gdata_Health_Extension_Ccr(); $ccrElement->transferFromXML($ccrXMLStr); $this->_ccrData = $ccrElement; } return $ccrElement; } /** * Returns all the CCR data in a profile entry * @return Zend_Gdata_Health_Extension_Ccr */ public function getCcr() { return $this->_ccrData; } }
WhiteLabelReady/WhiteLabelTransfer
library/Zend/Gdata/Health/ProfileEntry.php
PHP
agpl-3.0
4,260
<?php /*-------------------------------------------------------+ | SYSTOPIA Donation Receipts Extension | | Copyright (C) 2013-2019 SYSTOPIA | | Author: N. Bochan | | B. Endres | | http://www.systopia.de/ | +--------------------------------------------------------+ | License: AGPLv3, see LICENSE file | +--------------------------------------------------------*/ use CRM_Donrec_ExtensionUtil as E; /** * This class holds German language helper functions * @param number any number that should be converted to words * @author Karl Rixon (http://www.karlrixon.co.uk/writing/convert-numbers-to-words-with-php/) * modified by Niko Bochan to support the German language */ class CRM_Donrec_Lang_De_Xx extends CRM_Donrec_Lang { /** * Get the (localised) name of the language * * @return string name of the language */ public function getName() { return E::ts("German (with spaces)"); } /** * Render a full text expressing the amount in the given currency * * * @param $amount string amount * @param $currency string currency. Leave empty to render without currency * @param $params array additional parameters * @return string rendered string in the given language * * @author Karl Rixon (http://www.karlrixon.co.uk/writing/convert-numbers-to-words-with-php/) * modified by Niko Bochan to support the German language * refactored by Björn Endres for DONREC-50 */ public function amount2words($amount, $currency, $params = []) { return $this->convert_number_to_words($amount, $currency, FALSE); } /** * Get a spoken word representation for the given currency * * @param $currency string currency symbol, e.g 'EUR' or 'USD' * @param $quantity int count, e.g. for plural * @return string spoken word, e.g. 'Euro' or 'Dollar' */ public function currency2word($currency, $quantity) { switch ($currency) { case 'EUR': return 'Euro'; case 'USD': return 'Dollar'; case 'GBP': return 'Britische Pfund'; case 'CHF': return 'Schweizer Franken'; default: return parent::currency2word($currency, $quantity); } } /** * Internal (legacy) function * * @param $number string any number that should be converted to words * @param $currency string currency * @param $recursion bool recursion protection * @author Karl Rixon (http://www.karlrixon.co.uk/writing/convert-numbers-to-words-with-php/) * modified by Niko Bochan to support the German language * refactored by Björn Endres for DONREC-50 * @return string language */ protected function convert_number_to_words($number, $currency='EUR', $recursion=false) { $hyphen = 'und'; $conjunction = ' '; $separator = ' '; $negative = 'minus '; $decimal = ' ' . $this->currency2word($currency, $number) . ' '; $dictionary = array( 0 => 'null', 1 => 'ein', 2 => 'zwei', 3 => 'drei', 4 => 'vier', 5 => 'fünf', 6 => 'sechs', 7 => 'sieben', 8 => 'acht', 9 => 'neun', 10 => 'zehn', 11 => 'elf', 12 => 'zwölf', 13 => 'dreizehn', 14 => 'vierzehn', 15 => 'fünfzehn', 16 => 'sechzehn', 17 => 'siebzehn', 18 => 'achtzehn', 19 => 'neunzehn', 20 => 'zwanzig', 30 => 'dreißig', 40 => 'vierzig', 50 => 'fünfzig', 60 => 'sechzig', 70 => 'siebzig', 80 => 'achtzig', 90 => 'neunzig', 100 => 'hundert', 1000 => 'tausend', 1000000 => 'millionen', 1000000000 => 'milliarden', 1000000000000 => 'billionen' ); if (!is_numeric($number)) { return false; } if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) { // overflow return false; } if ($number < 0) { return $negative . $this->convert_number_to_words(abs($number), $currency, true); } $string = null; // make sure, the values are set correctly (#1582) $fraction = (int) round( ($number - floor($number)) * 100); $number = (int) $number; switch (true) { case $number < 21: $string = $dictionary[$number]; break; case $number < 100: $tens = ((int) ($number / 10)) * 10; $units = $number % 10; if ($units) { $string = $dictionary[$units] . $hyphen . $dictionary[$tens]; }else{ $string = $dictionary[$tens]; } break; case $number < 1000: $hundreds = $number / 100; $remainder = $number % 100; $string = $dictionary[$hundreds] . ' ' . $dictionary[100]; if ($remainder) { $string .= $conjunction . $this->convert_number_to_words($remainder, $currency, true); } break; default: $baseUnit = pow(1000, floor(log($number, 1000))); $numBaseUnits = (int) ($number / $baseUnit); $remainder = $number % $baseUnit; $string .= $this->convert_number_to_words($numBaseUnits, $currency, true); // FIXME: the following doesn't work for units > 10^6 if ($baseUnit == 1000000 && $numBaseUnits == 1) { $string .= 'e '; // ein_e_ $string .= substr($dictionary[$baseUnit], 0, -2); // million (ohne 'en') } else { $string .= ' '; $string .= $dictionary[$baseUnit]; } if ($remainder) { $string .= ($remainder < 100) ? $conjunction : $separator; $string .= $this->convert_number_to_words($remainder, $currency, true); } break; } if ($fraction) { $string .= $decimal; if(is_numeric($fraction) && $fraction != 0.00) { switch (true) { case $fraction < 21: $string .= $dictionary[$fraction]; break; case $fraction < 100: $tens = ((int) ($fraction / 10)) * 10; $units = $fraction % 10; if ($units) { $string .= $dictionary[$units] . $hyphen . $dictionary[$tens]; }else{ $string .= $dictionary[$tens]; } break; } } } elseif (!$recursion) { $string .= $decimal; } return trim($string); } }
systopia/de.systopia.donrec
CRM/Donrec/Lang/De/Xx.php
PHP
agpl-3.0
7,174
var status = 0; var minlvl = 100; var maxlvl = 255; var minplayers = 1; var maxplayers = 6; var time = 15; var open = true; function start() { status = -1; // and when they click lets fight make it turn to a really cool ifght song :D LOL ok like the Zakum battle song? kk and btw uhm can you add a message like after they click OK to say "Matt: Meet me near the top of the map." ? o-o in other words, a action(1, 0, 0); } function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else if (mode == 0) { cm.sendOk("I spy a chicken :O"); // lLOL cm.dispose(); } else { if (mode == 1) status++; else status--; if (status == 0) { cm.sendYesNo("Hello #b #h ##k! Would you like to fight #rSuper Horntail?#k He is waiting :)"); } else if (status == 1) { if (cm.getPlayer().warning[1] == false && cm.isLeader()) { cm.getPlayer().warning[1] = true; cm.mapMessage("On behalf of MapleZtory, please defeat Big Puff Daddy! rawrawrawr"); var mf = cm.getPlayer().getMap().getMapFactory(); var bossmap = mf.getMap(240030103); bossmap.removePortals(); var mob = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810018); var mob1 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810002); var mob2 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810003); var mob3 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810004); var mob4 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810005); var mob5 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810006); var mob6 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810007); var mob7 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810008); var mob8 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810009); var overrideStats = new net.sf.odinms.server.life.MapleMonsterStats(); overrideStats.setHp(2147000000); overrideStats.setExp(2147000000); overrideStats.setMp(mob.getMaxMp()); // mob.setOverrideStats(overrideStats); mob1.setOverrideStats(overrideStats); mob2.setOverrideStats(overrideStats); mob3.setOverrideStats(overrideStats); mob4.setOverrideStats(overrideStats); mob5.setOverrideStats(overrideStats); mob6.setOverrideStats(overrideStats); mob7.setOverrideStats(overrideStats); mob8.setOverrideStats(overrideStats); mob.setHp(overrideStats.getHp()); //eim.registerMonster(mob); bossmap.spawnMonsterOnGroudBelow(mob, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob1, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob2, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob3, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob4, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob5, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob6, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob7, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob8, new java.awt.Point(-182, -178)); // bossmap.killAllMonsters(false); // bossmap.killMonster(8810018); // i like that funkshun :( // this one looks pro though :Dlol ur right XD // spawnMonster(int mobid, int HP, int MP, int level, int EXP, int boss, int undead, int amount, int x, int y); cm.dispose(); } else { cm.sendOk("Super Horntail has already been spawned or you are not leader!"); cm.dispose(); } } } }
ZenityMS/forgottenstorysource
scripts/npc/2102000.js
JavaScript
agpl-3.0
3,619
package scrum.server.files; import ilarkesto.io.IO; import scrum.server.admin.User; public class File extends GFile { // --- dependencies --- // --- --- public void deleteFile() { IO.delete(getJavaFile()); } public java.io.File getJavaFile() { return new java.io.File(getProject().getFileRepositoryPath() + "/" + getFilename()); } public void updateNumber() { if (isNumber(0)) setNumber(getProject().generateFileNumber()); } public boolean isVisibleFor(User user) { return getProject().isVisibleFor(user); } public String getReferenceAndLabel() { return getReference() + " (" + getLabel() + ")"; } public String getReference() { return scrum.client.files.File.REFERENCE_PREFIX + getNumber(); } public boolean isEditableBy(User user) { return getProject().isEditableBy(user); } @Override public String toString() { return getReferenceAndLabel(); } @Override public void ensureIntegrity() { super.ensureIntegrity(); updateNumber(); } }
hogi/kunagi
src/main/java/scrum/server/files/File.java
Java
agpl-3.0
989
/** * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'uploadwidget', 'ja', { abort: 'アップロードを中止しました。', doneOne: 'ファイルのアップロードに成功しました。', doneMany: '%1個のファイルのアップロードに成功しました。', uploadOne: 'ファイルのアップロード中 ({percentage}%)...', uploadMany: '{max} 個中 {current} 個のファイルをアップロードしました。 ({percentage}%)...' } );
astrobin/astrobin
astrobin/static/astrobin/ckeditor/plugins/uploadwidget/lang/ja.js
JavaScript
agpl-3.0
624
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2012-2013 Canonical 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. */ 'use strict'; /** * Provide the notification classes. * * @module views * @submodule views.notifications */ YUI.add('juju-notifications', function(Y) { var views = Y.namespace('juju.views'), widgets = Y.namespace('juju.widgets'), Templates = views.Templates; /** * Abstract base class used to view a ModelList of notifications. * * @class NotificationsBaseView */ var NotificationsBaseView = Y.Base.create('NotificationsBaseView', Y.View, [views.JujuBaseView], { initializer: function() { NotificationsView.superclass.constructor.apply(this, arguments); var notifications = this.get('notifications'), env = this.get('env'); // Bind view to model list in a number of ways notifications.addTarget(this); // Re-render the model list changes notifications.after('add', this.slowRender, this); notifications.after('create', this.slowRender, this); notifications.after('remove', this.slowRender, this); notifications.after('reset', this.slowRender, this); // Bind new notifications to the notifier widget. notifications.after('add', this.addNotifier, this); // Env connection state watcher env.on('connectedChange', this.slowRender, this); }, /** * Create and display a notifier widget when a notification is added. * The notifier is created only if: * - the notifier box exists in the DOM; * - the notification is a local one (not related to the delta stream); * - the notification is an error. * * @method addNotifier * @param {Object} ev An event object (with a "model" attribute). * @return {undefined} Mutates only. */ addNotifier: function(ev) { var notification = ev.model, notifierBox = Y.one('.notifications-nav .notifier-box'); // Show error notifications only if the DOM contain the notifier box. if (notifierBox && !notification.get('isDelta') && (notification.get('level') === 'error' || notification.get('level') === 'important')) { var msg = notification.get('message'); if (msg) { msg = new Y.Handlebars.SafeString(msg); } new widgets.Notifier({ title: notification.get('title'), message: msg }).render(notifierBox); } }, /** * Select/click on a notice. Currently this just removes it from the * model_list. * * @method notificationSelect */ notificationSelect: function(evt) { var notifications = this.get('notifications'), target = evt.target, model; if (!target) { return; } if (target.get('tagName') !== 'LI') { target = target.ancestor('li'); } model = notifications.getByClientId(target.get('id')); if (this.selection.seen) { model.set('seen', true); } if (this.selection.hide) { target.hide(true); } this.slowRender(); }, /** * A flow of events can trigger many renders, from the event system * we debounce render requests with this method. * * @method slowRender */ slowRender: function() { var self = this, container = self.get('container'); clearTimeout(this._renderTimeout); this._renderTimeout = setTimeout(function() { if (!container) { return; } self.render(); }, 200); }, render: function() { var container = this.get('container'), env = this.get('env'), connected = env.get('connected'), notifications = this.get('notifications'), state, open = '', btngroup = container.one('.btn-group'); // Honor the current active state if the view is already // rendered if (btngroup && btngroup.hasClass('open')) { open = 'open'; } // However if the size of the message list is now // zero we can close the dialog if (notifications.size() === 0) { open = ''; } var showable = this.getShowable(), show_count = showable.length || 0; if (!connected) { state = 'btn-warning'; } else if (show_count > 0) { state = 'btn-danger'; } else { state = 'btn-info'; } container.setHTML(this.template({ notifications: showable, count: show_count, state: state, open: open, viewAllUri: this.get('nsRouter').url({ gui: '/notifications' }) })); return this; } }, { ATTRS: { /** Applications router utility methods @attribute nsRouter */ nsRouter: {} } }); /** * The view associated with the notifications indicator. * * @class NotificationsView */ var NotificationsView = Y.Base.create('NotificationsView', NotificationsBaseView, [ Y.Event.EventTracker, Y.juju.Dropdown ], { template: Templates.notifications, /* * Actions associated with events. In this case selection events * represent policy flags inside the 'notificationSelect' callback. * * :hide: should the selected element be hidden on selection */ selection: { hide: false, seen: false }, /** * @method getShowable */ getShowable: function() { var notifications = this.get('notifications'); return notifications.filter(function(n) { return n.get('level') === 'error' && n.get('seen') === false; }).map(function(n) { return n.getAttrs(); }); }, /** Renders the notification view and the dropdown widget. @method render */ render: function() { NotificationsView.superclass.render.apply(this, arguments); // Added by the view-dropdown-extension.js this._addDropdownFunc(); return this; } }); views.NotificationsView = NotificationsView; }, '0.1.0', { requires: [ 'view', 'juju-view-utils', 'node', 'handlebars', 'notifier', 'view-dropdown-extension', 'event-tracker' ] });
jrwren/juju-gui
app/views/notifications.js
JavaScript
agpl-3.0
7,674
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## from openerp import fields, models, api, _ from openerp.exceptions import Warning import logging _logger = logging.getLogger(__name__) class afip_incoterm(models.Model): _name = 'afip.incoterm' _description = 'Afip Incoterm' afip_code = fields.Char( 'Code', required=True) name = fields.Char( 'Name', required=True) class afip_point_of_sale(models.Model): _name = 'afip.point_of_sale' _description = 'Afip Point Of Sale' prefix = fields.Char( 'Prefix' ) sufix = fields.Char( 'Sufix' ) type = fields.Selection([ ('manual', 'Manual'), ('preprinted', 'Preprinted'), ('online', 'Online'), # Agregados por otro modulo # ('electronic', 'Electronic'), # ('fiscal_printer', 'Fiscal Printer'), ], 'Type', default='manual', required=True, ) name = fields.Char( compute='get_name', ) number = fields.Integer( 'Number', required=True ) company_id = fields.Many2one( 'res.company', 'Company', required=True, default=lambda self: self.env['res.company']._company_default_get( 'afip.point_of_sale') ) journal_ids = fields.One2many( 'account.journal', 'point_of_sale_id', 'Journals', ) document_sequence_type = fields.Selection( [('own_sequence', 'Own Sequence'), ('same_sequence', 'Same Invoice Sequence')], string='Document Sequence Type', default='own_sequence', required=True, help="Use own sequence or invoice sequence on Debit and Credit Notes?" ) journal_document_class_ids = fields.One2many( 'account.journal.afip_document_class', compute='get_journal_document_class_ids', string='Documents Classes', ) @api.one @api.depends('type', 'sufix', 'prefix', 'number') def get_name(self): # TODO mejorar esto y que tome el lable traducido del selection if self.type == 'manual': name = 'Manual' elif self.type == 'preprinted': name = 'Preimpresa' elif self.type == 'online': name = 'Online' elif self.type == 'electronic': name = 'Electronica' if self.prefix: name = '%s %s' % (self.prefix, name) if self.sufix: name = '%s %s' % (name, self.sufix) name = '%04d - %s' % (self.number, name) self.name = name @api.one @api.depends('journal_ids.journal_document_class_ids') def get_journal_document_class_ids(self): journal_document_class_ids = self.env[ 'account.journal.afip_document_class'].search([ ('journal_id.point_of_sale_id', '=', self.id)]) self.journal_document_class_ids = journal_document_class_ids _sql_constraints = [('number_unique', 'unique(number, company_id)', 'Number Must be Unique per Company!'), ] class afip_document_class(models.Model): _name = 'afip.document_class' _description = 'Afip Document Class' name = fields.Char( 'Name', size=120) doc_code_prefix = fields.Char( 'Document Code Prefix', help="Prefix for Documents Codes on Invoices \ and Account Moves. For eg. 'FA ' will build 'FA 0001-0000001' Document Number") afip_code = fields.Integer( 'AFIP Code', required=True) document_letter_id = fields.Many2one( 'afip.document_letter', 'Document Letter') report_name = fields.Char( 'Name on Reports', help='Name that will be printed in reports, for example "CREDIT NOTE"') document_type = fields.Selection([ ('invoice', 'Invoices'), ('credit_note', 'Credit Notes'), ('debit_note', 'Debit Notes'), ('receipt', 'Receipt'), ('ticket', 'Ticket'), ('in_document', 'In Document'), ('other_document', 'Other Documents') ], string='Document Type', help='It defines some behaviours on automatic journal selection and\ in menus where it is shown.') active = fields.Boolean( 'Active', default=True) class afip_document_letter(models.Model): _name = 'afip.document_letter' _description = 'Afip Document letter' name = fields.Char( 'Name', size=64, required=True) afip_document_class_ids = fields.One2many( 'afip.document_class', 'document_letter_id', 'Afip Document Classes') issuer_ids = fields.Many2many( 'afip.responsability', 'afip_doc_letter_issuer_rel', 'letter_id', 'responsability_id', 'Issuers',) receptor_ids = fields.Many2many( 'afip.responsability', 'afip_doc_letter_receptor_rel', 'letter_id', 'responsability_id', 'Receptors',) active = fields.Boolean( 'Active', default=True) vat_discriminated = fields.Boolean( 'Vat Discriminated on Invoices?', help="If True, the vat will be discriminated on invoice report.") _sql_constraints = [('name', 'unique(name)', 'Name must be unique!'), ] class afip_responsability(models.Model): _name = 'afip.responsability' _description = 'AFIP VAT Responsability' name = fields.Char( 'Name', size=64, required=True) code = fields.Char( 'Code', size=8, required=True) active = fields.Boolean( 'Active', default=True) issued_letter_ids = fields.Many2many( 'afip.document_letter', 'afip_doc_letter_issuer_rel', 'responsability_id', 'letter_id', 'Issued Document Letters') received_letter_ids = fields.Many2many( 'afip.document_letter', 'afip_doc_letter_receptor_rel', 'responsability_id', 'letter_id', 'Received Document Letters') vat_tax_required_on_sales_invoices = fields.Boolean( 'VAT Tax Required on Sales Invoices?', help='If True, then a vay tax is mandatory on each sale invoice for companies of this responsability', ) _sql_constraints = [('name', 'unique(name)', 'Name must be unique!'), ('code', 'unique(code)', 'Code must be unique!')] class afip_document_type(models.Model): _name = 'afip.document_type' _description = 'AFIP document types' name = fields.Char( 'Name', size=120, required=True) code = fields.Char( 'Code', size=16, required=True) afip_code = fields.Integer( 'AFIP Code', required=True) active = fields.Boolean( 'Active', default=True)
adrianpaesani/odoo-argentina
l10n_ar_invoice/models/afip.py
Python
agpl-3.0
6,822
<?php /* * e-additives.server RESTful API * Copyright (C) 2013 VEXELON.NET Services * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace Eadditives; use \Eadditives\Models\LocalesModel; /** * MyRequest * * Reads input HTTP request header and parameters and prepares data fetch criteria. * * @package Eadditives * @author p.petrov */ class MyRequest { const X_AUTH_HEADER = "X-Authorization"; const X_AUTH_HEADER_MASHAPE = "X-Mashape-Proxy-Secret"; const X_AUTH_SCHEME = "EAD-TOKENS"; const PARAM_CATEGORY = 'category'; const PARAM_SORT = 'sort'; const PARAM_ORDER = 'order'; const PARAM_LOCALE = 'locale'; /** * @var array */ protected $validParams = array( self::PARAM_CATEGORY => array(), self::PARAM_SORT => array(), self::PARAM_ORDER => array(), self::PARAM_LOCALE => array() ); /** * Slim app instance * @var mixed */ protected $app; /** * Slim app request * @var mixed */ protected $request; function __construct($app) { $this->app = $app; $this->request = $app->request; } public function isParam($name) { return !is_null($this->request->params($name)); } public function getParam($name) { return $this->request->params($name); } protected function getFilteredParams() { $result = array_intersect_key($this->request->params(), $this->validParams); if ($this->app->log->getEnabled() && !empty($result)) $this->app->log->debug('Request params: ' . print_r($result, true)); return $result; } /** * Resolve and validate criteria parameters * @param array $criteria category id * @return array */ public function getCriteria() { $criteria = $this->getFilteredParams(); $locale = $criteria[MyRequest::PARAM_LOCALE]; if (is_null($locale)) { // default locale is EN $criteria[MyRequest::PARAM_LOCALE] = LocalesModel::LOCALE_EN; } else if ($locale !== LocalesModel::LOCALE_EN && $locale !== LocalesModel::LOCALE_BG) { $this->app->log->error("Invalid locale - [$locale]!"); throw new RequestException('Not Found', MyResponse::HTTP_STATUS_NOT_FOUND); } $sort = $criteria[MyRequest::PARAM_SORT]; if (!is_null($sort)) { $order = $criteria[MyRequest::PARAM_ORDER]; if (is_null($order)) { $criteria[MyRequest::PARAM_ORDER] = 'DESC'; } else if ($order !== 'asc' && $order !== 'desc') { $this->app->log->error("Invalid order - [$order]!"); throw new RequestException('Not Found', MyResponse::HTTP_STATUS_NOT_FOUND); } } return $criteria; } /** * Validate required headers. * * Expects: * User-Agent: <any string> * X-Authorization: EAD-TOKENS apiKey="quoted-string" * * @throws RequestException If authorization header was not passed or wrong formatted. */ public function authorize() { // header: User-Agent $userAgent = trim($this->request->headers('User-Agent')); if (empty($userAgent)) { throw new RequestException('Forbidden', MyResponse::HTTP_STATUS_FORBIDDEN); } $apiKeys = unserialize(X_AUTH_KEY); $tokens = array(); try { // header: X-Mashape-Proxy $authorizationMashape = $this->request->headers(self::X_AUTH_HEADER_MASHAPE); if (!is_null($authorizationMashape)) { $tokenMashape = trim(str_replace(self::X_AUTH_HEADER_MASHAPE . ':', '', $authorizationMashape)); $tokens['apiKey'] = $tokenMashape; } else { // header: X-Authorization $authorization = $this->request->headers(self::X_AUTH_HEADER); $tokens = $this->parseXAuthorization($authorization); } // verify keys if (!isset($tokens['apiKey']) || !in_array($tokens['apiKey'], $apiKeys)) { throw new \Exception('Invalid API key!'); } // save API key info in app $this->app->container->singleton('apiKey', function() use ($tokens) { return $tokens['apiKey']; }); } catch (\Exception $e) { throw new RequestException('Authorization required', MyResponse::HTTP_STATUS_UNAUTHORIZED, $e); } } /** * Parses X-Authorization header components. * @param $header * @throws Exception If one or more components of X-Authorization could not be parsed. * @return array */ private function parseXAuthorization($header) { if (is_null($header)) { throw new \Exception('X-Authorization header is empty!'); } $headerNoScheme = strstr($header, self::X_AUTH_SCHEME); if ($headerNoScheme === FALSE) { throw new \Exception('X-Authorization header scheme is invalid!'); } $headerNoScheme = trim(str_replace(self::X_AUTH_SCHEME, "", $headerNoScheme)); // expects to get no more than 10 items! $items = explode(",", $headerNoScheme, 10); $results = array(); // parse key/value for each item foreach ($items as $item) { $pair = explode("=", $item); $key = trim(strval($pair[0])); $value = trim(str_replace('"', "", $pair[1])); $results[$key] = $value; } if (DEBUG) { $this->app->log->debug(self::X_AUTH_HEADER . ' values: ' . print_r($results, true)); } return $results; } } ?>
vexelon-dot-net/e-additives.server
src/Eadditives/MyRequest.php
PHP
agpl-3.0
6,416
/* * Copyright (c) 2011, Aperis GmbH <agplsources@aperis.com> * Autor: Achim 'ahzf' Friedland <code@ahzf.de> * This file is part of CanonDSLR * * Licensed under the Affero GPL license, Version 3.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/agpl.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace com.aperis.CanonDSLR.CanonSDK { public enum CameraState : uint { UILock = 0x00000000, UIUnLock = 0x00000001, EnterDirectTransfer = 0x00000002, ExitDirectTransfer = 0x00000003 } }
nareenb/CanonDSLR.NET
CanonDSLR/Commands/CameraState.cs
C#
agpl-3.0
977
"""Add is_loud and pronouns columns to PanelApplicant Revision ID: bba880ef5bbd Revises: 8f8419ebcf27 Create Date: 2019-07-20 02:57:17.794469 """ # revision identifiers, used by Alembic. revision = 'bba880ef5bbd' down_revision = '8f8419ebcf27' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa try: is_sqlite = op.get_context().dialect.name == 'sqlite' except Exception: is_sqlite = False if is_sqlite: op.get_context().connection.execute('PRAGMA foreign_keys=ON;') utcnow_server_default = "(datetime('now', 'utc'))" else: utcnow_server_default = "timezone('utc', current_timestamp)" def sqlite_column_reflect_listener(inspector, table, column_info): """Adds parenthesis around SQLite datetime defaults for utcnow.""" if column_info['default'] == "datetime('now', 'utc')": column_info['default'] = utcnow_server_default sqlite_reflect_kwargs = { 'listeners': [('column_reflect', sqlite_column_reflect_listener)] } # =========================================================================== # HOWTO: Handle alter statements in SQLite # # def upgrade(): # if is_sqlite: # with op.batch_alter_table('table_name', reflect_kwargs=sqlite_reflect_kwargs) as batch_op: # batch_op.alter_column('column_name', type_=sa.Unicode(), server_default='', nullable=False) # else: # op.alter_column('table_name', 'column_name', type_=sa.Unicode(), server_default='', nullable=False) # # =========================================================================== def upgrade(): op.add_column('panel_applicant', sa.Column('other_pronouns', sa.Unicode(), server_default='', nullable=False)) op.add_column('panel_applicant', sa.Column('pronouns', sa.Unicode(), server_default='', nullable=False)) op.add_column('panel_application', sa.Column('is_loud', sa.Boolean(), server_default='False', nullable=False)) def downgrade(): op.drop_column('panel_application', 'is_loud') op.drop_column('panel_applicant', 'pronouns') op.drop_column('panel_applicant', 'other_pronouns')
magfest/ubersystem
alembic/versions/bba880ef5bbd_add_is_loud_and_pronouns_columns_to_.py
Python
agpl-3.0
2,103
/** * Copyright (C) 2016 The Language Archive, Max Planck Institute for Psycholinguistics * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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. */ package nl.mpi.arbil.userstorage; import java.awt.GraphicsEnvironment; import java.awt.HeadlessException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import nl.mpi.flap.plugin.PluginDialogHandler; import nl.mpi.flap.plugin.PluginSessionStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created on : Nov 8, 2012, 4:25:54 PM * * @author Peter Withers <peter.withers@mpi.nl> */ public abstract class CommonsSessionStorage implements PluginSessionStorage { private final static Logger logger = LoggerFactory.getLogger(CommonsSessionStorage.class); protected File localCacheDirectory = null; private File storageDirectory = null; protected PluginDialogHandler messageDialogHandler; protected abstract String[] getAppDirectoryAlternatives(); protected abstract String getProjectDirectoryName(); protected abstract void logError(Exception exception); protected abstract void logError(String message, Exception exception); public abstract Object loadObject(String filename) throws Exception; private void checkForMultipleStorageDirectories(String[] locationOptions) { // look for any additional storage directories int foundDirectoryCount = 0; StringBuilder storageDirectoryMessageString = new StringBuilder(); for (String currentStorageDirectory : locationOptions) { File storageFile = new File(currentStorageDirectory); if (storageFile.exists()) { foundDirectoryCount++; storageDirectoryMessageString.append(currentStorageDirectory).append("\n"); } } if (foundDirectoryCount > 1) { String errorMessage = "More than one storage directory has been found.\nIt is recommended to remove any unused directories in this list.\nNote that the first occurrence is currently in use:\n" + storageDirectoryMessageString; logError(new Exception(errorMessage)); try { if (!GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog(null, "More than one storage directory has been found.\nIt is recommended to remove any unused directories in this list.\nNote that the first occurrence is currently in use:\n" + storageDirectoryMessageString, "Multiple storage directories", JOptionPane.WARNING_MESSAGE); } } catch (HeadlessException hEx) { // Should never occur since we're checking whether headless throw new AssertionError(hEx); } } } protected String[] getLocationOptions() { List<String> locationOptions = new ArrayList<String>(); for (String appDir : getAppDirectoryAlternatives()) { locationOptions.add(System.getProperty("user.home") + File.separatorChar + "Local Settings" + File.separatorChar + "Application Data" + File.separatorChar + appDir + File.separatorChar); locationOptions.add(System.getenv("APPDATA") + File.separatorChar + appDir + File.separatorChar); locationOptions.add(System.getProperty("user.home") + File.separatorChar + appDir + File.separatorChar); locationOptions.add(System.getenv("USERPROFILE") + File.separatorChar + appDir + File.separatorChar); locationOptions.add(System.getProperty("user.dir") + File.separatorChar + appDir + File.separatorChar); } List<String> uniqueArray = new ArrayList<String>(); for (String location : locationOptions) { if (location != null && !location.startsWith("null") && !uniqueArray.contains(location)) { uniqueArray.add(location); } } locationOptions = uniqueArray; for (String currentLocationOption : locationOptions) { logger.debug("LocationOption: " + currentLocationOption); } return locationOptions.toArray(new String[]{}); } private File determineStorageDirectory() throws RuntimeException { File storageDirectoryFile = null; String storageDirectoryArray[] = getLocationOptions(); // look for an existing storage directory for (String currentStorageDirectory : storageDirectoryArray) { File storageFile = new File(currentStorageDirectory); if (storageFile.exists()) { logger.debug("existing storage directory found: " + currentStorageDirectory); storageDirectoryFile = storageFile; break; } } String testedStorageDirectories = ""; if (storageDirectoryFile == null) { for (String currentStorageDirectory : storageDirectoryArray) { if (!currentStorageDirectory.startsWith("null")) { File storageFile = new File(currentStorageDirectory); if (!storageFile.exists()) { if (!storageFile.mkdir()) { testedStorageDirectories = testedStorageDirectories + currentStorageDirectory + "\n"; logError("failed to create: " + currentStorageDirectory, null); } else { logger.debug("created new storage directory: " + currentStorageDirectory); storageDirectoryFile = storageFile; break; } } } } } if (storageDirectoryFile == null) { logError("Could not create a working directory in any of the potential location:\n" + testedStorageDirectories + "Please check that you have write permissions in at least one of these locations.\nThe application will now exit.", null); System.exit(-1); } else { try { File testFile = File.createTempFile("testfile", ".tmp", storageDirectoryFile); boolean success = testFile.exists(); if (!success) { success = testFile.createNewFile(); } if (success) { testFile.deleteOnExit(); success = testFile.exists(); if (success) { success = testFile.delete(); } } if (!success) { // test the storage directory is writable and add a warning message box here if not logError("Could not write to the working directory.\nThere will be issues creating, editing and saving any file.", null); } } catch (IOException exception) { logger.debug("Sending exception to logger", exception); logError(exception); messageDialogHandler.addMessageDialogToQueue("Could not create a test file in the working directory.", "Arbil Critical Error"); throw new RuntimeException("Exception while testing working directory writability", exception); } } logger.debug("storageDirectory: " + storageDirectoryFile); checkForMultipleStorageDirectories(storageDirectoryArray); return storageDirectoryFile; } /** * @return the storageDirectory */ public synchronized File getApplicationSettingsDirectory() { if (storageDirectory == null) { storageDirectory = determineStorageDirectory(); } return storageDirectory; } /** * @return the project directory */ public File getProjectDirectory() { return getProjectWorkingDirectory().getParentFile(); } /** * Tests that the project directory exists and creates it if it does not. * * @return the project working files directory */ public File getProjectWorkingDirectory() { if (localCacheDirectory == null) { // load from the text based properties file String localCacheDirectoryPathString = loadString("cacheDirectory"); if (localCacheDirectoryPathString != null) { localCacheDirectory = new File(localCacheDirectoryPathString); } else { // otherwise load from the to be replaced binary based storage file try { File localWorkingDirectory = (File) loadObject("cacheDirectory"); localCacheDirectory = localWorkingDirectory; } catch (Exception exception) { if (new File(getApplicationSettingsDirectory(), "imdicache").exists()) { localCacheDirectory = new File(getApplicationSettingsDirectory(), "imdicache"); } else { localCacheDirectory = new File(getApplicationSettingsDirectory(), getProjectDirectoryName()); } } saveString("cacheDirectory", localCacheDirectory.getAbsolutePath()); } boolean cacheDirExists = localCacheDirectory.exists(); if (!cacheDirExists) { if (!localCacheDirectory.mkdirs()) { logError("Could not create cache directory", null); return null; } } } return localCacheDirectory; } }
TheLanguageArchive/Arbil
arbil-commons/src/main/java/nl/mpi/arbil/userstorage/CommonsSessionStorage.java
Java
agpl-3.0
10,338
// // Aurio: Audio Processing, Analysis and Retrieval Library // Copyright (C) 2010-2017 Mario Guggenberger <mg@protyposis.net> // // 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/>. // using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Aurio { /// <summary> /// Volume calculations. /// </summary> /// <seealso cref="NAudio.Utils.Decibels"/> /// <seealso cref="http://stackoverflow.com/questions/6627288/audio-spectrum-analysis-using-fft-algorithm-in-java"/> public static class VolumeUtil { private static readonly double LOG_2_DB; private static readonly double DB_2_LOG; static VolumeUtil() { // precalculate factors to speed up calculations LOG_2_DB = 20 / Math.Log(10); DB_2_LOG = Math.Log(10) / 20; } /// <summary> /// Converts a linear value (e.g. a sample value) to decibel. /// decibel = 20 * ln(linearValue) / ln(10) = 20 * log10(linearValue) /// </summary> /// <param name="linear">linear value</param> /// <returns>decibel value</returns> public static double LinearToDecibel(double linear) { //return 20 * Math.Log10(linear); return Math.Log(linear) * LOG_2_DB; } /// <summary> /// Converts decibel to a linear value. /// </summary> /// <param name="decibel">decibel value</param> /// <returns>linear value</returns> public static double DecibelToLinear(double decibel) { return Math.Exp(decibel * DB_2_LOG); } /// <summary> /// Calculates the percentage of a decibel value where minDecibel is 0.0 (0%) and maxDecibel is 1.0 (100%). /// </summary> /// <param name="decibel">decibel value of which the percentage should be calculated</param> /// <param name="minDecibel">lower bound os the decibel range (0%)</param> /// <param name="maxDecibel">upper bound of the decibel range (100%)</param> /// <returns>the percentage of a decibel value between two bounding decibel values</returns> public static double DecibelToPercentage(double decibel, double minDecibel, double maxDecibel) { return (decibel - minDecibel) / (maxDecibel - minDecibel); } } }
protyposis/Aurio
Aurio/Aurio/VolumeUtil.cs
C#
agpl-3.0
3,045
/* * SPDX-FileCopyrightText: 2006-2009 Dirk Riehle <dirk@riehle.org> https://dirkriehle.com * SPDX-License-Identifier: AGPL-3.0-or-later */ package org.wahlzeit.servlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** * A null servlet. */ public class NullServlet extends AbstractServlet { /** * */ private static final long serialVersionUID = 42L; // any one does; class never serialized /** * */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { displayNullPage(request, response); } /** * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { displayNullPage(request, response); } }
dirkriehle/wahlzeit
src/main/java/org/wahlzeit/servlets/NullServlet.java
Java
agpl-3.0
786
def keysetter(key): if not isinstance(key, str): raise TypeError('key name must be a string') resolve = key.split('.') head, last = tuple(resolve[:-1]), resolve[-1] def g(obj,value): for key in head : obj = obj[key] obj[last] = value return g def keygetter(key): if not isinstance(key, str): raise TypeError('key name must be a string') return lambda obj : resolve_key(obj, key) def resolve_key(obj, key): for name in key.split('.'): obj = obj[name] return obj
aureooms/sak
lib/nice/operator.py
Python
agpl-3.0
554
<?php /* Smarty version 2.6.11, created on 2012-05-02 15:43:38 compiled from include/SugarFields/Fields/Phone/DetailView.tpl */ ?> <?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins(array('plugins' => array(array('function', 'sugarvar', 'include/SugarFields/Fields/Phone/DetailView.tpl', 38, false),array('function', 'sugarvar_connector', 'include/SugarFields/Fields/Phone/DetailView.tpl', 44, false),)), $this); ?> {* /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ *} {if !empty(<?php echo smarty_function_sugarvar(array('key' => 'value','string' => true), $this);?> )} {assign var="phone_value" value=<?php echo smarty_function_sugarvar(array('key' => 'value','string' => true), $this);?> } {sugar_phone value=$phone_value usa_format="<?php if (! empty ( $this->_tpl_vars['vardef']['validate_usa_format'] )): ?>1<?php else: ?>0<?php endif; ?>"} <?php if (! empty ( $this->_tpl_vars['displayParams']['enableConnectors'] )): echo smarty_function_sugarvar_connector(array('view' => 'DetailView'), $this);?> <?php endif; ?> {/if}
jmertic/sugarplatformdemo
cache/smarty/templates_c/%%FA^FA9^FA9EA62F%%DetailView.tpl.php
PHP
agpl-3.0
3,047
/* * RapidMiner * * Copyright (C) 2001-2011 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.flow; import java.awt.BorderLayout; import java.awt.Component; import java.util.List; import javax.swing.Action; import javax.swing.JPanel; import javax.swing.JScrollPane; import com.rapidminer.Process; import com.rapidminer.gui.MainFrame; import com.rapidminer.gui.actions.AutoWireAction; import com.rapidminer.gui.processeditor.ProcessEditor; import com.rapidminer.gui.tools.PrintingTools; import com.rapidminer.gui.tools.ResourceDockKey; import com.rapidminer.gui.tools.SwingTools; import com.rapidminer.gui.tools.ViewToolBar; import com.rapidminer.gui.tools.components.DropDownButton; import com.rapidminer.operator.ExecutionUnit; import com.rapidminer.operator.Operator; import com.rapidminer.operator.OperatorChain; import com.rapidminer.operator.ports.metadata.CompatibilityLevel; import com.vlsolutions.swing.docking.DockKey; import com.vlsolutions.swing.docking.Dockable; /** * Contains the main {@link ProcessRenderer} and a {@link ProcessButtonBar} * to navigate through the process. * * @author Simon Fischer, Tobias Malbrecht */ public class ProcessPanel extends JPanel implements Dockable, ProcessEditor { private static final long serialVersionUID = -4419160224916991497L; private final ProcessRenderer renderer; private final ProcessButtonBar processButtonBar; private OperatorChain operatorChain; public ProcessPanel(final MainFrame mainFrame) { processButtonBar = new ProcessButtonBar(mainFrame); renderer = new ProcessRenderer(this, mainFrame); renderer.setBackground(SwingTools.LIGHTEST_BLUE); ViewToolBar toolBar = new ViewToolBar(); toolBar.add(processButtonBar); final Action autoWireAction = new AutoWireAction(mainFrame, "wire", CompatibilityLevel.PRE_VERSION_5, false, true); DropDownButton autoWireDropDownButton = DropDownButton.makeDropDownButton(autoWireAction); autoWireDropDownButton.add(autoWireAction); autoWireDropDownButton.add(new AutoWireAction(mainFrame, "wire_recursive", CompatibilityLevel.PRE_VERSION_5, true, true)); autoWireDropDownButton.add(new AutoWireAction(mainFrame, "rewire", CompatibilityLevel.PRE_VERSION_5, false, false)); autoWireDropDownButton.add(new AutoWireAction(mainFrame, "rewire_recursive", CompatibilityLevel.PRE_VERSION_5, true, false)); autoWireDropDownButton.addToToolBar(toolBar, ViewToolBar.RIGHT); toolBar.add(renderer.getFlowVisualizer().SHOW_ORDER_TOGGLEBUTTON, ViewToolBar.RIGHT); toolBar.add(renderer.ARRANGE_OPERATORS_ACTION, ViewToolBar.RIGHT); toolBar.add(renderer.AUTO_FIT_ACTION, ViewToolBar.RIGHT); String name = "process"; if (mainFrame.getActions().getProcess() != null && mainFrame.getActions().getProcess().getProcessLocation() != null) { name = mainFrame.getActions().getProcess().getProcessLocation().getShortName(); } DropDownButton exportDropDownButton = PrintingTools.makeExportPrintDropDownButton(renderer, name); exportDropDownButton.addToToolBar(toolBar, ViewToolBar.RIGHT); setLayout(new BorderLayout()); add(toolBar, BorderLayout.NORTH); JScrollPane scrollPane = new JScrollPane(renderer); scrollPane.getVerticalScrollBar().setUnitIncrement(10); scrollPane.setBorder(null); add(scrollPane, BorderLayout.CENTER); } public void showOperatorChain(OperatorChain operatorChain) { this.operatorChain = operatorChain; if (operatorChain == null) { processButtonBar.setSelectedNode(null); renderer.showOperatorChain(null); } else { renderer.showOperatorChain(operatorChain); processButtonBar.setSelectedNode(operatorChain); StringBuilder b = new StringBuilder("<html><strong>"); b.append(operatorChain.getName()); b.append("</strong>&nbsp;<emph>("); b.append(operatorChain.getOperatorDescription().getName()); b.append(")</emph><br/>"); b.append("Subprocesses: "); boolean first = true; for (ExecutionUnit executionUnit : operatorChain.getSubprocesses()) { if (first) { first = false; } else { b.append(", "); } b.append("<em>"); b.append(executionUnit.getName()); b.append("</em> ("); b.append(executionUnit.getOperators().size()); b.append(" operators)"); } b.append("</html>"); } } public void setSelection(List<Operator> selection) { Operator first = selection.isEmpty() ? null : selection.get(0); if (first != null) { processButtonBar.addToHistory(first); } if (renderer.getSelection().equals(selection)) { return; } if (first == null) { showOperatorChain(null); } else { OperatorChain target; if (first instanceof OperatorChain) { target = (OperatorChain) first; } else { target = first.getParent(); } showOperatorChain(target); renderer.setSelection(selection); } } @Override public void processChanged(Process process) { processButtonBar.clearHistory(); } @Override public void processUpdated(Process process) { renderer.processUpdated(); processButtonBar.setSelectedNode(this.operatorChain); } public ProcessRenderer getProcessRenderer() { return renderer; } public static final String PROCESS_PANEL_DOCK_KEY = "process_panel"; private final DockKey DOCK_KEY = new ResourceDockKey(PROCESS_PANEL_DOCK_KEY); { DOCK_KEY.setDockGroup(MainFrame.DOCK_GROUP_ROOT); } @Override public Component getComponent() { return this; } @Override public DockKey getDockKey() { return DOCK_KEY; } }
aborg0/rapidminer-vega
src/com/rapidminer/gui/flow/ProcessPanel.java
Java
agpl-3.0
6,427
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, setRead }; function countForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } return UserNotification.count(q).exec(callback); } function create(usernotification, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } new UserNotification(usernotification).save(callback); } function get(id, callback) { if (!id) { return callback(new Error('id is not defined')); } return UserNotification.findById(id).exec(callback); } function getAll(ids, callback) { if (!ids) { return callback(new Error('id is not defined')); } const formattedIds = ids.map(id => mongoose.Types.ObjectId(id)); const query = { _id: { $in: formattedIds } }; return UserNotification.find(query).exec(callback); } function getForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } const mq = UserNotification.find(q); mq.limit(+query.limit || DEFAULT_LIMIT); mq.skip(+query.offset || DEFAULT_OFFSET); mq.sort('-timestamps.creation'); mq.exec(callback); } function remove(query, callback) { UserNotification.remove(query, callback); } function setAcknowledged(usernotification, acknowledged, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.acknowledged = acknowledged; usernotification.save(callback); } function setAllRead(usernotifications, read, callback) { if (!usernotifications) { return callback(new Error('usernotification is required')); } async.each(usernotifications, setRead, callback); function setRead(usernotification, cb) { usernotification.read = read; usernotification.save(cb); } } function setRead(usernotification, read, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.read = read; usernotification.save(callback); }
heroandtn3/openpaas-esn
backend/core/notification/usernotification.js
JavaScript
agpl-3.0
2,510
<?php /** * @deprecated (will be removed in 4.0) */ class form_BlockFormOldDummyView extends block_BlockView { /** * @param block_BlockContext $context * @param block_BlockRequest $request */ public function execute($context, $request) { $this->setTemplateName('Form-Dummy'); $form = $this->getParameter('form'); $this->setAttribute('form', $form); } }
RBSChange/modules.compatibilityos
lib/form/lib/blocks/BlockFormOldDummyView.class.php
PHP
agpl-3.0
383
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class EventType(models.Model): _inherit = "event.type" community_menu = fields.Boolean( "Community Menu", compute="_compute_community_menu", readonly=False, store=True, help="Display community tab on website") @api.depends('website_menu') def _compute_community_menu(self): for event_type in self: event_type.community_menu = event_type.website_menu
ygol/odoo
addons/website_event_track_online/models/event_type.py
Python
agpl-3.0
551
'use strict'; angular.module('hopsWorksApp') .controller('DatasetsCtrl', ['$scope', '$q', '$mdSidenav', '$mdUtil', '$log', 'DataSetService', 'JupyterService', '$routeParams', '$route', 'ModalService', 'growl', '$location', 'MetadataHelperService', '$rootScope', 'DelaProjectService', 'DelaClusterProjectService', function ($scope, $q, $mdSidenav, $mdUtil, $log, DataSetService, JupyterService, $routeParams, $route, ModalService, growl, $location, MetadataHelperService, $rootScope, DelaProjectService, DelaClusterProjectService) { var self = this; self.itemsPerPage = 14; self.working = false; //Some variables to keep track of state. self.files = []; //A list of files currently displayed to the user. self.projectId = $routeParams.projectID; //The id of the project we're currently working in. self.pathArray; //An array containing all the path components of the current path. If empty: project root directory. self.sharedPathArray; //An array containing all the path components of a path in a shared dataset self.highlighted; self.parentDS = $rootScope.parentDS; // Details of the currently selecte file/dir self.selected = null; //The index of the selected file in the files array. self.sharedPath = null; //The details about the currently selected file. self.routeParamArray = []; $scope.readme = null; var dataSetService = DataSetService(self.projectId); //The datasetservice for the current project. var delaHopsService = DelaProjectService(self.projectId); var delaClusterService = DelaClusterProjectService(self.projectId); $scope.all_selected = false; self.selectedFiles = {}; //Selected files self.dir_timing; self.isPublic = undefined; self.shared = undefined; self.status = undefined; self.tgState = true; self.onSuccess = function (e) { growl.success("Copied to clipboard", {title: '', ttl: 1000}); e.clearSelection(); }; self.metadataView = {}; self.availableTemplates = []; self.closeSlider = false; self.breadcrumbLen = function () { if (self.pathArray === undefined || self.pathArray === null) { return 0; } var displayPathLen = 10; if (self.pathArray.length <= displayPathLen) { return self.pathArray.length - 1; } return displayPathLen; }; self.cutBreadcrumbLen = function () { if (self.pathArray === undefined || self.pathArray === null) { return false; } if (self.pathArray.length - self.breadcrumbLen() > 0) { return true; } return false; }; $scope.sort = function (keyname) { $scope.sortKey = keyname; //set the sortKey to the param passed $scope.reverse = !$scope.reverse; //if true make it false and vice versa }; /** * watch for changes happening in service variables from the other controller */ $scope.$watchCollection(MetadataHelperService.getAvailableTemplates, function (availTemplates) { if (!angular.isUndefined(availTemplates)) { self.availableTemplates = availTemplates; } }); $scope.$watch(MetadataHelperService.getDirContents, function (response) { if (response === "true") { getDirContents(); MetadataHelperService.setDirContents("false"); } }); self.isSharedDs = function (name) { var top = name.split("::"); if (top.length === 1) { return false; } return true; }; self.isShared = function () { var top = self.pathArray[0].split("::"); if (top.length === 1) { return false; } return true; }; self.sharedDatasetPath = function () { var top = self.pathArray[0].split("::"); if (top.length === 1) { self.sharedPathArray = []; return; } // /proj::shared_ds/path/to -> /proj/ds/path/to // so, we add '1' to the pathLen self.sharedPathArray = new Array(self.pathArray.length + 1); self.sharedPathArray[0] = top[0]; self.sharedPathArray[1] = top[1]; for (var i = 1; i < self.pathArray.length; i++) { self.sharedPathArray[i + 1] = self.pathArray[i]; } return self.sharedPathArray; }; /* * Get all datasets under the current project. * @returns {undefined} */ self.getAllDatasets = function () { //Get the path for an empty patharray: will get the datasets var path = getPath([]); dataSetService.getContents(path).then( function (success) { self.files = success.data; self.pathArray = []; console.log(success); }, function (error) { console.log("Error getting all datasets in project " + self.projectId); console.log(error); }); }; /** * Get the contents of the directory at the path with the given path components and load it into the frontend. * @param {type} The array of path compontents to fetch. If empty, fetches the current path. * @returns {undefined} */ var getDirContents = function (pathComponents) { //Construct the new path array var newPathArray; if (pathComponents) { newPathArray = pathComponents; } else if (self.routeParamArray) { newPathArray = self.pathArray.concat(self.routeParamArray); } else { newPathArray = self.pathArray; } //Convert into a path var newPath = getPath(newPathArray); self.files = []; self.working = true; self.dir_timing = new Date().getTime(); //Get the contents and load them dataSetService.getContents(newPath).then( function (success) { //Clear any selections self.all_selected = false; self.selectedFiles = {}; //Reset the selected file self.selected = null; self.working = false; //Set the current files and path self.files = success.data; self.pathArray = newPathArray; console.log(success); // alert('Execution time: ' + (new Date().getTime() - self.dir_timing)); console.log('Execution time: ' + (new Date().getTime() - self.dir_timing)); if ($rootScope.selectedFile) { var filePathArray = self.pathArray.concat($rootScope.selectedFile); self.getFile(filePathArray); $rootScope.selectedFile = undefined; } }, function (error) { if (error.data.errorMsg.indexOf("Path is not a directory.") > -1) { var popped = newPathArray.pop(); console.log(popped); self.openDir({name: popped, dir: false, underConstruction: false}); self.pathArray = newPathArray; self.routeParamArray = []; //growl.info(error.data.errorMsg, {title: 'Info', ttl: 2000}); getDirContents(); } else if (error.data.errorMsg.indexOf("Path not found :") > -1) { self.routeParamArray = []; //$route.updateParams({fileName:''}); growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); getDirContents(); } self.working = false; console.log("Error getting the contents of the path " + getPath(newPathArray)); console.log(error); }); }; self.getFile = function (pathComponents) { var newPathArray; newPathArray = pathComponents; //Convert into a path var newPath = getPath(newPathArray); dataSetService.getFile(newPath).then( function (success) { self.highlighted = success.data; self.select(self.highlighted.name, self.highlighted, undefined); $scope.search = self.highlighted.name; }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); }; var init = function () { //Check if the current dataset is set if ($routeParams.datasetName) { //Dataset is set: get the contents self.pathArray = [$routeParams.datasetName]; } else { //No current dataset is set: get all datasets. self.pathArray = []; } if ($routeParams.datasetName && $routeParams.fileName) { //file name is set: get the contents var paths = $routeParams.fileName.split("/"); paths.forEach(function (entry) { if (entry !== "") { self.routeParamArray.push(entry); } }); } getDirContents(); self.tgState = true; }; init(); /** * Upload a file to the specified path. * @param {type} path * @returns {undefined} */ var upload = function (path) { dataSetService.upload(path).then( function (success) { console.log("upload success"); console.log(success); getDirContents(); }, function (error) { console.log("upload error"); console.log(error); }); }; /** * Remove the inode at the given path. If called on a folder, will * remove the folder and all its contents recursively. * @param {type} path. The project-relative path to the inode to be removed. * @returns {undefined} */ var removeInode = function (path) { dataSetService.removeDataSetDir(path).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 1000}); getDirContents(); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000}); }); }; /** * Open a modal dialog for folder creation. The folder is created at the current path. * @returns {undefined} */ self.newDataSetModal = function () { ModalService.newFolder('md', getPath(self.pathArray)).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 1000}); getDirContents(); }, function (error) { //The user changed his/her mind. Don't really need to do anything. // getDirContents(); }); }; /** * Delete the file with the given name under the current path. * If called on a folder, will remove the folder * and all its contents recursively. * @param {type} fileName * @returns {undefined} */ self.deleteFile = function (fileName) { var removePathArray = self.pathArray.slice(0); removePathArray.push(fileName); removeInode('file/' + getPath(removePathArray)); }; /** * Delete the dataset with the given name under the current path. * @param {type} fileName * @returns {undefined} */ self.deleteDataset = function (fileName) { var removePathArray = self.pathArray.slice(0); removePathArray.push(fileName); removeInode(getPath(removePathArray)); }; // self.deleteSelected = function () { // var removePathArray = self.pathArray.slice(0); // for(var fileName in self.selectedFiles){ // removePathArray.push(fileName); // removeInode(getPath(removePathArray)); // } // }; /** * Makes the dataset public for anybody within the local cluster or any outside cluster. * @param id inodeId */ self.sharingDataset = {}; self.shareWithHops = function (id) { ModalService.confirm('sm', 'Confirm', 'Are you sure you want to make this DataSet public? \n\ This will make all its files available for any registered user to download and process.').then( function (success) { self.sharingDataset[id] = true; delaHopsService.shareWithHopsByInodeId(id).then( function (success) { self.sharingDataset[id] = false; growl.success(success.data.successMessage, {title: 'The DataSet is now Public(Hops Site).', ttl: 1500}); getDirContents(); }, function (error) { self.sharingDataset[id] = false; growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000}); }); } ); }; /** * Makes the dataset public for anybody within the local cluster * @param id inodeId */ self.shareWithCluster = function (id) { ModalService.confirm('sm', 'Confirm', 'Are you sure you want to make this DataSet public? \n\ This will make all its files available for any cluster user to share and process.').then( function (success) { self.sharingDataset[id] = true; delaClusterService.shareWithClusterByInodeId(id).then( function (success) { self.sharingDataset[id] = false; growl.success(success.data.successMessage, {title: 'The DataSet is now Public(Cluster).', ttl: 1500}); getDirContents(); }, function (error) { self.sharingDataset[id] = false; growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000}); }); } ); }; self.showManifest = function(publicDSId){ delaHopsService.getManifest(publicDSId).then(function(success){ var manifest = success.data; ModalService.json('md','Manifest', manifest).then(function(){ }); }); }; self.unshareFromHops = function (publicDSId) { ModalService.confirm('sm', 'Confirm', 'Are you sure you want to make this DataSet private? ').then( function (success) { delaHopsService.unshareFromHops(publicDSId, false).then( function (success) { growl.success(success.data.successMessage, {title: 'The DataSet is not Public(internet) anymore.', ttl: 1500}); getDirContents(); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); } ); }; self.unshareFromCluster = function (inodeId) { ModalService.confirm('sm', 'Confirm', 'Are you sure you want to make this DataSet private? ').then( function (success) { delaClusterService.unshareFromCluster(inodeId).then( function (success) { growl.success(success.data.successMessage, {title: 'The DataSet is not Public(cluster) anymore.', ttl: 1500}); getDirContents(); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); } ); }; self.parentPathArray = function () { var newPathArray = self.pathArray.slice(0); var clippedPath = newPathArray.splice(1, newPathArray.length - 1); return clippedPath; }; self.unzip = function (filename) { var pathArray = self.pathArray.slice(0); // pathArray.push(self.selected); pathArray.push(filename); var filePath = getPath(pathArray); growl.info("Started unzipping...", {title: 'Unzipping Started', ttl: 2000, referenceId: 4}); dataSetService.unzip(filePath).then( function (success) { growl.success("Refresh your browser when finished", {title: 'Unzipping in Background', ttl: 5000, referenceId: 4}); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error unzipping file', ttl: 5000, referenceId: 4}); }); }; self.isZippedfile = function () { // https://stackoverflow.com/questions/680929/how-to-extract-extension-from-filename-string-in-javascript var re = /(?:\.([^.]+))?$/; var ext = re.exec(self.selected)[1]; switch (ext) { case "zip": return true; case "rar": return true; case "tar": return true; case "tgz": return true; case "gz": return true; case "bz2": return true; case "7z": return true; } return false; }; self.convertIPythonNotebook = function (filename) { var pathArray = self.pathArray.slice(0); pathArray.push(filename); //self.selected var filePath = getPath(pathArray); growl.info("Converting...", {title: 'Conversion Started', ttl: 2000, referenceId: 4}); JupyterService.convertIPythonNotebook(self.projectId, filePath).then( function (success) { growl.success("Finished - refresh your browser", {title: 'Converting in Background', ttl: 3000, referenceId: 4}); getDirContents(); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error converting notebook', ttl: 5000, referenceId: 4}); }); }; self.isIPythonNotebook = function () { if (self.selected === null || self.selected === undefined) { return false; } if (self.selected.indexOf('.') == -1) { return false; } var ext = self.selected.split('.').pop(); if (ext === null || ext === undefined) { return false; } switch (ext) { case "ipynb": return true; } return false; }; /** * Preview the requested file in a Modal. If the file is README.md * and the preview flag is false, preview the file in datasets. * @param {type} dataset * @param {type} preview * @returns {undefined} */ self.filePreview = function (dataset, preview, readme) { var fileName = ""; //handle README.md filename for datasets browser viewing here if (readme && !preview) { if (dataset.shared === true) { fileName = dataset.selectedIndex + "/README.md"; } else { fileName = dataset.path.substring(dataset.path.lastIndexOf('/')).replace('/', '') + "/README.md"; } } else { fileName = dataset; } var previewPathArray = self.pathArray.slice(0); previewPathArray.push(fileName); var filePath = getPath(previewPathArray); //If filename is README.md then try fetching it without the modal if (readme && !preview) { dataSetService.filePreview(filePath, "head").then( function (success) { var fileDetails = JSON.parse(success.data.data); var content = fileDetails.filePreviewDTO[0].content; var conv = new showdown.Converter({parseImgDimensions: true}); $scope.readme = conv.makeHtml(content); }, function (error) { //To hide README from UI growl.error(error.data.errorMsg, {title: 'Error retrieving README file', ttl: 5000, referenceId: 4}); $scope.readme = null; }); } else { ModalService.filePreview('lg', fileName, filePath, self.projectId, "head").then( function (success) { }, function (error) { }); } }; self.copy = function (inodeId, name) { ModalService.selectDir('lg', "/[^]*/", "problem selecting folder").then(function (success) { var destPath = success; // Get the relative path of this DataSet, relative to the project home directory // replace only first occurrence var relPath = destPath.replace("/Projects/" + self.projectId + "/", ""); var finalPath = relPath + "/" + name; dataSetService.copy(inodeId, finalPath).then( function (success) { getDirContents(); growl.success('', {title: 'Copied ' + name + ' successfully', ttl: 5000, referenceId: 4}); }, function (error) { growl.error(error.data.errorMsg, {title: name + ' was not copied', ttl: 5000, referenceId: 4}); }); }, function (error) { }); }; self.copySelected = function () { //Check if we are to move one file or many if (Object.keys(self.selectedFiles).length === 0 && self.selectedFiles.constructor === Object) { if (self.selected !== null && self.selected !== undefined) { self.copy(self.selected.id, self.selected.name); } } else if (Object.keys(self.selectedFiles).length !== 0 && self.selectedFiles.constructor === Object) { ModalService.selectDir('lg', "/[^]*/", "problem selecting folder").then( function (success) { var destPath = success; // Get the relative path of this DataSet, relative to the project home directory // replace only first occurrence var relPath = destPath.replace("/Projects/" + self.projectId + "/", ""); //var finalPath = relPath + "/" + name; var names = []; var i = 0; //Check if have have multiple files for (var name in self.selectedFiles) { names[i] = name; i++; } var errorMsg = ''; for (var name in self.selectedFiles) { dataSetService.copy(self.selectedFiles[name].id, relPath + "/" + name).then( function (success) { //If we copied the last file if (name === names[names.length - 1]) { getDirContents(); for (var i = 0; i < names.length; i++) { delete self.selectedFiles[names[i]]; } self.all_selected = false; } //growl.success('',{title: 'Copied successfully', ttl: 5000, referenceId: 4}); }, function (error) { growl.error(error.data.errorMsg, {title: name + ' was not copied', ttl: 5000}); errorMsg = error.data.errorMsg; }); if (errorMsg === 'Can not copy/move to a public dataset.') { break; } } }, function (error) { //The user changed their mind. }); } }; self.move = function (inodeId, name) { ModalService.selectDir('lg', "/[^]*/", "problem selecting folder").then( function (success) { var destPath = success; // Get the relative path of this DataSet, relative to the project home directory // replace only first occurrence var relPath = destPath.replace("/Projects/" + self.projectId + "/", ""); var finalPath = relPath + "/" + name; dataSetService.move(inodeId, finalPath).then( function (success) { getDirContents(); growl.success(success.data.successMessage, {title: 'Moved successfully. Opened dest dir: ' + relPath, ttl: 2000}); }, function (error) { growl.error(error.data.errorMsg, {title: name + ' was not moved', ttl: 5000}); }); }, function (error) { }); }; self.isSelectedFiles = function () { return Object.keys(self.selectedFiles).length; }; self.moveSelected = function () { //Check if we are to move one file or many if (Object.keys(self.selectedFiles).length === 0 && self.selectedFiles.constructor === Object) { if (self.selected !== null && self.selected !== undefined) { self.move(self.selected.id, self.selected.name); } } else if (Object.keys(self.selectedFiles).length !== 0 && self.selectedFiles.constructor === Object) { ModalService.selectDir('lg', "/[^]*/", "problem selecting folder").then( function (success) { var destPath = success; // Get the relative path of this DataSet, relative to the project home directory // replace only first occurrence var relPath = destPath.replace("/Projects/" + self.projectId + "/", ""); //var finalPath = relPath + "/" + name; var names = []; var i = 0; //Check if have have multiple files for (var name in self.selectedFiles) { names[i] = name; i++; } var errorMsg = ''; for (var name in self.selectedFiles) { dataSetService.move(self.selectedFiles[name].id, relPath + "/" + name).then( function (success) { //If we moved the last file if (name === names[names.length - 1]) { getDirContents(); for (var i = 0; i < names.length; i++) { delete self.selectedFiles[names[i]]; } self.all_selected = false; } }, function (error) { growl.error(error.data.errorMsg, {title: name + ' was not moved', ttl: 5000}); errorMsg = error.data.errorMsg; }); if (errorMsg === 'Can not copy/move to a public dataset.') { break; } } }, function (error) { //The user changed their mind. }); } }; var renameModal = function (inodeId, name) { var pathComponents = self.pathArray.slice(0); var newPath = getPath(pathComponents); var destPath = newPath + '/'; ModalService.enterName('sm', "Rename File or Directory", name).then( function (success) { var fullPath = destPath + success.newName; dataSetService.move(inodeId, fullPath).then( function (success) { getDirContents(); self.all_selected = false; self.selectedFiles = {}; self.selected = null; }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); self.all_selected = false; self.selectedFiles = {}; self.selected = null; }); }); }; self.rename = function (inodeId, name) { renameModal(inodeId, name); }; self.renameSelected = function () { if (self.isSelectedFiles() === 1) { var inodeId, inodeName; for (var name in self.selectedFiles) { inodeName = name; } inodeId = self.selectedFiles[inodeName]['id']; renameModal(inodeId, inodeName); } }; /** * Opens a modal dialog for file upload. * @returns {undefined} */ self.uploadFile = function () { var templateId = -1; ModalService.upload('lg', self.projectId, getPath(self.pathArray), templateId).then( function (success) { growl.success(success, {ttl: 5000}); getDirContents(); }, function (error) { // growl.info("Closed without saving.", {title: 'Info', ttl: 5000}); getDirContents(); }); }; /** * Sends a request to erasure code a file represented by the given path. * It checks * .. if the given path resolves to a file or a dir * .. if the given path is an existing file * .. if the given file is large enough (comprises more than 10 blocks) * * If all of the above are met, the compression takes place in an asynchronous operation * and the user gets notified when it finishes via a message * * @param {type} file * @returns {undefined} */ self.compress = function (file) { var pathArray = self.pathArray.slice(0); pathArray.push(file.name); var filePath = getPath(pathArray); //check if the path is a dir dataSetService.isDir(filePath).then( function (success) { var object = success.data.successMessage; switch (object) { case "DIR": ModalService.alert('sm', 'Alert', 'You can only compress files'); break; case "FILE": //if the path is a file go on dataSetService.checkFileExist(filePath).then( function (successs) { //check the number of blocks in the file dataSetService.checkFileBlocks(filePath).then( function (successss) { var noOfBlocks = parseInt(successss.data); console.log("NO OF BLOCKS " + noOfBlocks); if (noOfBlocks >= 10) { ModalService.alert('sm', 'Confirm', 'This operation is going to run in the background').then( function (modalSuccess) { console.log("FILE PATH IS " + filePath); dataSetService.compressFile(filePath); }); } else { growl.error("The requested file is too small to be compressed", {title: 'Error', ttl: 5000, referenceId: 4}); } }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); }); } }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); }; /** * Opens a modal dialog for sharing. * @returns {undefined} */ self.share = function (name) { ModalService.shareDataset('md', name).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 5000}); getDirContents(); }, function (error) { }); }; /** * Opens a modal dialog to make dataset editable * @param {type} name * @param {type} permissions * @returns {undefined} */ self.permissions = function (name, permissions) { ModalService.permissions('md', name, permissions).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 5000}); getDirContents(); }, function (error) { }); }; /** * Opens a modal dialog for unsharing. * @param {type} name * @returns {undefined} */ self.unshare = function (name) { ModalService.unshareDataset('md', name).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 5000}); getDirContents(); }, function (error) { }); }; /** * Upon click on a inode in the browser: * + If folder: open folder, fetch contents from server and display. * + If file: open a confirm dialog prompting for download. * @param {type} file * @returns {undefined} */ self.openDir = function (file) { if (file.dir) { var newPathArray = self.pathArray.slice(0); newPathArray.push(file.name); getDirContents(newPathArray); } else if (!file.underConstruction) { ModalService.confirm('sm', 'Confirm', 'Do you want to download this file?').then( function (success) { var downloadPathArray = self.pathArray.slice(0); downloadPathArray.push(file.name); var filePath = getPath(downloadPathArray); //growl.success("Asdfasdf", {title: 'asdfasd', ttl: 5000}); dataSetService.checkFileForDownload(filePath).then( function (success) { dataSetService.fileDownload(filePath); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000}); }); } ); } else { growl.info("File under construction.", {title: 'Info', ttl: 5000}); } }; /** * Go up to parent directory. * @returns {undefined} */ self.back = function () { var newPathArray = self.pathArray.slice(0); newPathArray.pop(); if (newPathArray.length === 0) { $location.path('/project/' + self.projectId + '/datasets'); } else { getDirContents(newPathArray); } }; self.goToDataSetsDir = function () { $location.path('/project/' + self.projectId + '/datasets'); }; /** * Go to the folder at the index in the pathArray array. * @param {type} index * @returns {undefined} */ self.goToFolder = function (index) { var newPathArray = self.pathArray.slice(0); newPathArray.splice(index, newPathArray.length - index); getDirContents(newPathArray); }; self.menustyle = { "opacity": 0.2 }; /** * Select an inode; updates details panel. * @param {type} selectedIndex * @param {type} file * @param {type} event * @returns {undefined} */ self.select = function (selectedIndex, file, event) { // 1. Turn off the selected file at the top of the browser. // Add existing selected file (idempotent, if already added) // If file already selected, deselect it. if (event && event.ctrlKey) { } else { self.selectedFiles = {}; } if (self.isSelectedFiles() > 0) { self.selected = null; } else { self.selected = file.name; } self.selectedFiles[file.name] = file; self.selectedFiles[file.name].selectedIndex = selectedIndex; self.menustyle.opacity = 1.0; console.log(self.selectedFiles); }; self.haveSelected = function (file) { if (file === undefined || file === null || file.name === undefined || file.name === null) { return false; } if (file.name in self.selectedFiles) { return true; } return false; }; self.selectAll = function () { var i = 0; var min = Math.min(self.itemsPerPage, self.files.length); for (i = 0; i < min; i++) { var f = self.files[i]; self.selectedFiles[f.name] = f; self.selectedFiles[f.name].selectedIndex = i; } self.menustyle.opacity = 1; self.selected = null; self.all_selected = true; if (Object.keys(self.selectedFiles).length === 1 && self.selectedFiles.constructor === Object) { self.selected = Object.keys(self.selectedFiles)[0]; } }; //TODO: Move files to hdfs trash folder self.trashSelected = function () { }; self.deleteSelected = function () { var i = 0; var names = []; for (var name in self.selectedFiles) { names[i] = name; self.deleteFile(name); } for (var i = 0; i < names.length; i++) { delete self.selectedFiles[names[i]]; } self.all_selected = false; self.selectedFiles = {}; self.selected = null; }; self.deselect = function (selectedIndex, file, event) { var i = 0; if (Object.keys(self.selectedFiles).length === 1 && self.selectedFiles.constructor === Object) { for (var name in self.selectedFiles) { if (file.name === name) { delete self.selectedFiles[name]; //break; } } } else { if (event.ctrlKey) { for (var name in self.selectedFiles) { if (file.name === name) { delete self.selectedFiles[name]; break; } } } else { for (var name in self.selectedFiles) { if (file.name !== name) { delete self.selectedFiles[name]; //break; } } } } if (Object.keys(self.selectedFiles).length === 0 && self.selectedFiles.constructor === Object) { self.menustyle.opacity = 0.2; self.selected = null; } else if (Object.keys(self.selectedFiles).length === 1 && self.selectedFiles.constructor === Object) { self.menustyle.opacity = 1.0; self.selected = Object.keys(self.selectedFiles)[0]; } self.all_selected = false; }; self.deselectAll = function () { self.selectedFiles = {}; self.selected = null; self.sharedPath = null; self.menustyle.opacity = 0.2; }; self.toggleLeft = buildToggler('left'); self.toggleRight = buildToggler('right'); function buildToggler(navID) { var debounceFn = $mdUtil.debounce(function () { $mdSidenav(navID).toggle() .then(function () { MetadataHelperService.fetchAvailableTemplates() .then(function (response) { self.availableTemplates = JSON.parse(response.board).templates; }); }); }, 300); return debounceFn; } ; self.getSelectedPath = function (selectedFile) { if (self.isSelectedFiles() !== 1) { return ""; } return "hdfs://" + selectedFile.path; }; }]); /** * Turn the array <i>pathArray</i> containing, path components, into a path string. * @param {type} pathArray * @returns {String} */ var getPath = function (pathArray) { return pathArray.join("/"); };
FilotasSiskos/hopsworks
hopsworks-web/yo/app/scripts/controllers/datasetsCtrl.js
JavaScript
agpl-3.0
46,695
<?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 - 2018 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". */ global $sugar_version; if(!defined('sugarEntry') || !sugarEntry) { die('Not A Valid Entry Point'); } /////////////////////////////////////////////////////////////////////////////// //// DYNAMICALLY GENERATE UPGRADEWIZARD MODULE FILE LIST $uwFilesCurrent = findAllFiles('modules/UpgradeWizard/', array()); // handle 4.x to 4.5.x+ (no UpgradeWizard module) if(count($uwFilesCurrent) < 5) { $uwFiles = array( 'modules/UpgradeWizard/language/en_us.lang.php', 'modules/UpgradeWizard/cancel.php', 'modules/UpgradeWizard/commit.php', 'modules/UpgradeWizard/commitJson.php', 'modules/UpgradeWizard/end.php', 'modules/UpgradeWizard/Forms.php', 'modules/UpgradeWizard/index.php', 'modules/UpgradeWizard/Menu.php', 'modules/UpgradeWizard/preflight.php', 'modules/UpgradeWizard/preflightJson.php', 'modules/UpgradeWizard/start.php', 'modules/UpgradeWizard/su_utils.php', 'modules/UpgradeWizard/su.php', 'modules/UpgradeWizard/systemCheck.php', 'modules/UpgradeWizard/systemCheckJson.php', 'modules/UpgradeWizard/upgradeWizard.js', 'modules/UpgradeWizard/upload.php', 'modules/UpgradeWizard/uw_ajax.php', 'modules/UpgradeWizard/uw_files.php', 'modules/UpgradeWizard/uw_main.tpl', 'modules/UpgradeWizard/uw_utils.php', ); } else { $uwFilesCurrent = findAllFiles('ModuleInstall', $uwFilesCurrent); $uwFilesCurrent = findAllFiles('include/javascript/yui', $uwFilesCurrent); $uwFilesCurrent[] = 'HandleAjaxCall.php'; $uwFiles = array(); foreach($uwFilesCurrent as $file) { $uwFiles[] = str_replace("./", "", clean_path($file)); } } //// END DYNAMICALLY GENERATE UPGRADEWIZARD MODULE FILE LIST /////////////////////////////////////////////////////////////////////////////// $uw_files = array( // standard files we steamroll with no warning 'log4php.properties', 'include/utils/encryption_utils.php', 'include/Pear/Crypt_Blowfish/Blowfish.php', 'include/Pear/Crypt_Blowfish/Blowfish/DefaultKey.php', 'include/utils.php', 'include/language/en_us.lang.php', 'include/modules.php', 'include/Localization/Localization.php', 'install/language/en_us.lang.php', 'XTemplate/xtpl.php', 'include/database/DBHelper.php', 'include/database/DBManager.php', 'include/database/DBManagerFactory.php', 'include/database/MssqlHelper.php', 'include/database/MssqlManager.php', 'include/database/MysqlHelper.php', 'include/database/MysqlManager.php', 'include/database/DBManagerFactory.php', ); $uw_files = array_merge($uw_files, $uwFiles);
willrennie/SuiteCRM
modules/UpgradeWizard/uw_files.php
PHP
agpl-3.0
4,610
/** * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.workflow.api; /** * The workflow engine services related to timeout (on active states) management. */ public interface TimeoutManager { /** * Initialize the timeout manager */ public void initialize(); }
NicolasEYSSERIC/Silverpeas-Core
ejb-core/formtemplate/src/main/java/com/silverpeas/workflow/api/TimeoutManager.java
Java
agpl-3.0
1,384
# frozen_string_literal: true require "rails_helper" describe PagesController, type: :controller do describe "#index", type: :controller do before do get :index end it { is_expected.to respond_with(200) } it { is_expected.to render_template(:index) } end end
tristandunn/miroha
spec/controllers/pages_controller_spec.rb
Ruby
agpl-3.0
288
/** * Carousel controller * * @author Hein Bekker <hein@netbek.co.za> * @copyright (c) 2015 Hein Bekker * @license http://www.gnu.org/licenses/agpl-3.0.txt AGPLv3 */ (function (window, angular, undefined) { 'use strict'; angular .module('nb.carousel') .controller('nbCarouselController', nbCarouselController); nbCarouselController.$inject = ['$scope', '$element', '$timeout', '$interval', '$animate', 'GSAP', '$window', 'nbWindow', '_']; function nbCarouselController ($scope, $element, $timeout, $interval, $animate, GSAP, $window, nbWindow, _) { /*jshint validthis: true */ var self = this; var $$window = angular.element($window); var deregister = []; var currentInterval; // {Promise} var deferGotoInterval; // {Promise} var deferGotoIndex; var deferGotoDirection; var flags = { skipAnimation: true, // {Boolean} Prevents slide transition during the first gotoIndex(). destroyed: false, // {Boolean} Whether the scope has been destroyed. transitioning: false // {Boolean} Whether there is a transition in progress. }; var oldSlide; // {Scope} var newSlide; // {Scope} var maxWidth = 0, maxHeight = 0; $scope.complete = false; // {Boolean} Whether all slides have loaded or failed to load. $scope.slides = []; $scope.direction = self.direction = 'left'; $scope.currentIndex = -1; $scope.isPlaying = self.isPlaying = false; /** * * @param {int} index * @returns {Boolean} */ $scope.isCurrentSlideIndex = function (index) { return $scope.currentIndex === index; }; /** * * @param {int} index * @param {string} direction left, right */ $scope.gotoIndex = function (index, direction) { cancelDeferGoto(); // Stop here if there is a transition in progress or if the index has not changed. if (flags.transitioning || $scope.currentIndex === index) { return; } oldSlide = $scope.slides[$scope.currentIndex]; newSlide = $scope.slides[index]; // Stop here if the slide is not loaded. if (!newSlide.complete) { // Periodically check if the slide is loaded, and then try gotoIndex() again. deferGoto(index, direction); return; } $animate.addClass(newSlide.$element, 'fade-in', angular.noop); if (angular.isUndefined(direction)) { direction = (index < $scope.currentIndex) ? 'left' : 'right'; } $scope.direction = self.direction = direction; $scope.currentIndex = index; // Reset the timer when changing slides. restartTimer(); if (flags.skipAnimation || $scope.noTransition) { flags.skipAnimation = false; gotoDone(); } else { $timeout(function () { // Stop here if the scope has been destroyed. if (flags.destroyed) { return; } flags.transitioning = true; // Force reflow. var reflow = newSlide.$element[0].offsetWidth; $animate.removeClass(oldSlide.$element, 'active', angular.noop); $animate.addClass(newSlide.$element, 'active', gotoDone) .then(function () { flags.transitioning = false; }); }); } }; /** * Callback function fired after transition has been completed. */ function gotoDone () { // Stop here if the scope has been destroyed. if (flags.destroyed) { return; } if (oldSlide) { oldSlide.$element.removeClass('active'); } if (newSlide) { newSlide.$element.addClass('active'); } } /** * * @param {int} index * @param {string} direction left, right */ function deferGoto (index, direction) { deferGotoIndex = index; deferGotoDirection = direction; deferGotoFn(); } /** * Periodically checks if a slide is loaded. If so, fires gotoIndex(). */ function deferGotoFn () { cancelDeferGoto(); if ($scope.slides[deferGotoIndex].complete) { $scope.gotoIndex(deferGotoIndex, deferGotoDirection); } else { deferGotoInterval = $interval(deferGotoFn, 50); } } function cancelDeferGoto () { if (deferGotoInterval) { $interval.cancel(deferGotoInterval); deferGotoInterval = null; } } /** * Go to previous slide. */ $scope.prev = function () { var newIndex = $scope.currentIndex > 0 ? $scope.currentIndex - 1 : $scope.slides.length - 1; $scope.gotoIndex(newIndex, 'left'); }; /** * Go to next slide. */ $scope.next = function () { var newIndex = $scope.currentIndex < $scope.slides.length - 1 ? $scope.currentIndex + 1 : 0; $scope.gotoIndex(newIndex, 'right'); }; function restartTimer () { cancelTimer(); var interval = +$scope.interval; if (!isNaN(interval) && interval > 0) { currentInterval = $interval(timerFn, interval); } } function cancelTimer () { if (currentInterval) { $interval.cancel(currentInterval); currentInterval = null; } } function timerFn () { var interval = +$scope.interval; if (self.isPlaying && !isNaN(interval) && interval > 0) { $scope.next(); } else { $scope.pause(); } } $scope.play = function () { if (!self.isPlaying) { $scope.isPlaying = self.isPlaying = true; restartTimer(); } }; $scope.pause = function () { if (!$scope.noPause) { $scope.isPlaying = self.isPlaying = false; cancelTimer(); } }; /** * * @param {Scope} slide Slide scope * @param {DOM element} element Slide DOM element */ self.addSlide = function (slide, element) { slide.$element = element; $scope.slides.push(slide); if ($scope.slides.length === 1 || slide.active) { $scope.gotoIndex($scope.slides.length - 1); if ($scope.slides.length == 1) { $scope.play(); } } else { slide.active = false; } }; /** * * @param {Scope} slide */ self.removeSlide = function (slide) { GSAP.TweenMax.killTweensOf(slide.$element); var index = _.indexOf($scope.slides, slide); $scope.slides.splice(index, 1); if ($scope.slides.length > 0 && slide.active) { if (index >= $scope.slides.length) { $scope.gotoIndex(index - 1); } else { $scope.gotoIndex(index); } } else if ($scope.currentIndex > index) { $scope.currentIndex--; } }; /** * Checks if all the slides are loaded and sets the carousel load state. * * @param {Scope} slide */ self.setSlideComplete = function (slide) { var length = $scope.slides.length; var i = 0; angular.forEach($scope.slides, function (slide) { if (slide.complete) { i++; } }); $scope.complete = (length === i); }; /** * Sets maximum width of slides (allows for slides of different sizes). * * @param {int} value */ self.setMaxWidth = function (value) { if (value > maxWidth) { maxWidth = value; resize(); } }; /** * Sets maximum height of slides (allows for slides of different sizes). * * @param {int} value */ self.setMaxHeight = function (value) { if (value > maxHeight) { maxHeight = value; resize(); } }; /** * Resizes carousel and slides. */ function resize (apply) { if (maxWidth && maxHeight) { var windowHeight = nbWindow.windowHeight() * 0.8; var width = $element[0].scrollWidth; var height = Math.min(windowHeight, maxHeight / maxWidth * width); if (width && height) { // Set height of carousel. $element.css('height', height + 'px'); // Set width and height of slides. angular.forEach($scope.slides, function (slide, index) { slide.resize(width, height); }); } } } // Reset the timer when the interval property changes. deregister.push($scope.$watch('interval', restartTimer)); // Gives the $animate service access to carousel properties. deregister.push($scope.$watch('noTransition', function (value) { self.noTransition = value; })); deregister.push($scope.$watch('transitionDuration', function (value) { self.transitionDuration = value; })); deregister.push($scope.$watch('transitionEase', function (value) { self.transitionEase = value; })); var onWindowResize = _.throttle(function () { resize(true); }, 60); // On window resize, resize carousel and slides. $$window.on('resize', onWindowResize); $scope.$on('$destroy', function () { flags.destroyed = true; // Deregister watchers. angular.forEach(deregister, function (fn) { fn(); }); // Cancel deferred goto interval. cancelDeferGoto(); // Cancel timer interval. cancelTimer(); // Unbind window resize event listener. $$window.off('resize', onWindowResize); }); } })(window, window.angular);
netbek/nb-carousel
src/js/nb-carousel.controller.js
JavaScript
agpl-3.0
8,617
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.repository.gui.actions; import com.rapidminer.repository.Entry; import com.rapidminer.repository.gui.RepositoryTree; import java.awt.event.ActionEvent; import javax.swing.Action; /** * This action is the standard paste action. * * @author Simon Fischer */ public class PasteEntryRepositoryAction extends AbstractRepositoryAction<Entry> { private static final long serialVersionUID = 1L; public PasteEntryRepositoryAction(RepositoryTree tree) { super(tree, Entry.class, false, "repository_paste"); putValue(ACTION_COMMAND_KEY, "paste"); } @Override public void actionPerformed(ActionEvent e) { String action = e.getActionCommand(); Action a = tree.getActionMap().get(action); if (a != null) { a.actionPerformed(new ActionEvent(tree, ActionEvent.ACTION_PERFORMED, null)); } } @Override public void actionPerformed(Entry cast) { // not needed because we override actionPerformed(ActionEvent e) which is the only caller } }
boob-sbcm/3838438
src/main/java/com/rapidminer/repository/gui/actions/PasteEntryRepositoryAction.java
Java
agpl-3.0
1,862
import subprocess def release(): subprocess.call(["python3", "setup.py", "sdist", "upload"])
aureooms/sak
sak/pip3.py
Python
agpl-3.0
100
/* * EditPresentationSourceEvent.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.workbench.views.source.events; import org.rstudio.core.client.files.FileSystemItem; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; public class EditPresentationSourceEvent extends GwtEvent<EditPresentationSourceEvent.Handler> { public interface Handler extends EventHandler { void onEditPresentationSource(EditPresentationSourceEvent e); } public EditPresentationSourceEvent(FileSystemItem sourceFile, int slideIndex) { sourceFile_ = sourceFile; slideIndex_ = slideIndex; } public FileSystemItem getSourceFile() { return sourceFile_; } public int getSlideIndex() { return slideIndex_; } @Override public Type<Handler> getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onEditPresentationSource(this); } private final FileSystemItem sourceFile_; private final int slideIndex_; public static final Type<Handler> TYPE = new Type<>(); }
JanMarvin/rstudio
src/gwt/src/org/rstudio/studio/client/workbench/views/source/events/EditPresentationSourceEvent.java
Java
agpl-3.0
1,714
/* * ToroDB * Copyright © 2014 8Kdata Technology (www.8kdata.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.torodb.mongodb.repl.topology; import com.google.inject.Exposed; import com.google.inject.PrivateModule; import com.google.inject.Provides; import com.torodb.core.concurrent.ConcurrentToolsFactory; import com.torodb.core.supervision.Supervisor; import com.torodb.mongodb.repl.SyncSourceProvider; import com.torodb.mongodb.repl.guice.MongoDbRepl; import java.time.Clock; import java.time.Duration; import java.util.concurrent.ThreadFactory; import javax.inject.Singleton; /** * */ public class TopologyGuiceModule extends PrivateModule { @Override protected void configure() { bind(HeartbeatNetworkHandler.class) .to(MongoClientHeartbeatNetworkHandler.class) .in(Singleton.class); bind(SyncSourceProvider.class) .to(RetrierTopologySyncSourceProvider.class) .in(Singleton.class); expose(SyncSourceProvider.class); bind(TopologyErrorHandler.class) .to(DefaultTopologyErrorHandler.class) .in(Singleton.class); bind(SyncSourceRetrier.class) .in(Singleton.class); bind(TopologyHeartbeatHandler.class) .in(Singleton.class); bind(TopologySyncSourceProvider.class) .in(Singleton.class); } @Provides @Topology Supervisor getTopologySupervisor(@MongoDbRepl Supervisor replSupervisor) { return replSupervisor; } @Provides @Singleton @Exposed public TopologyService createTopologyService(ThreadFactory threadFactory, TopologyHeartbeatHandler heartbeatHandler, TopologyExecutor executor, Clock clock) { return new TopologyService(heartbeatHandler, threadFactory, executor, clock); } @Provides @Singleton TopologyExecutor createTopologyExecutor( ConcurrentToolsFactory concurrentToolsFactory) { //TODO: Being able to configure max sync source lag and replication delay return new TopologyExecutor(concurrentToolsFactory, Duration.ofMinutes(1), Duration.ZERO); } }
jerolba/torodb
engine/mongodb/repl/src/main/java/com/torodb/mongodb/repl/topology/TopologyGuiceModule.java
Java
agpl-3.0
2,693
<?php /* ------------------------------------------------------------------------ FusionInventory Copyright (C) 2010-2016 by the FusionInventory Development Team. http://www.fusioninventory.org/ http://forge.fusioninventory.org/ ------------------------------------------------------------------------ LICENSE This file is part of FusionInventory project. FusionInventory 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. FusionInventory 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 FusionInventory. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------ @package FusionInventory @author David Durieux @co-author @copyright Copyright (c) 2010-2016 FusionInventory team @license AGPL License 3.0 or (at your option) any later version http://www.gnu.org/licenses/agpl-3.0-standalone.html @link http://www.fusioninventory.org/ @link http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/ @since 2010 ------------------------------------------------------------------------ */ class PluginFusioninventoryTaskjoblog extends CommonDBTM { /* * Define different state */ const TASK_STARTED = 1; const TASK_OK = 2; const TASK_ERROR_OR_REPLANNED = 3; const TASK_ERROR = 4; const TASK_INFO = 5; const TASK_RUNNING = 6; const TASK_PREPARED = 7; /** * return array with state mapping name * * @return array with all elements */ static function dropdownStateValues() { $elements = array( self::TASK_PREPARED => __('Prepared', 'fusioninventory'), self::TASK_STARTED => __('Started', 'fusioninventory'), self::TASK_RUNNING => __('Running'), self::TASK_OK => __('Ok', 'fusioninventory'), self::TASK_ERROR_OR_REPLANNED => __('Error / rescheduled', 'fusioninventory'), self::TASK_ERROR => __('Error'), self::TASK_INFO => __('Info', 'fusioninventory'), ); return $elements; } static function getStateName($state=-1) { $state_names = self::dropdownStateValues(); if(isset($state_names[$state])) { return $state_names[$state]; } else { return "N/A"; } } //TODO: move this in the view class static function getStateCSSName($state=-1) { $cssnames = array( self::TASK_PREPARED => "log_prepared", self::TASK_STARTED => "log_started", self::TASK_RUNNING => "log_running", self::TASK_OK => "log_ok", self::TASK_ERROR_OR_REPLANNED => "log_error_replanned", self::TASK_ERROR => "log_error", self::TASK_INFO => "log_info", ); if (isset($cssnames[$state]) ) { return $cssnames[$state]; } else { return ""; } } /** * Return name of state * * @param type $states_id * * @return string name of state number */ function getState($states_id) { $elements = $this->dropdownStateValues(); return $elements[$states_id]; } static function getStateItemtype($taskjoblogs_id) { global $DB; $query = "SELECT * FROM glpi_plugin_fusioninventory_taskjobstates LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` ON `plugin_fusioninventory_taskjobstates_id`=". "`glpi_plugin_fusioninventory_taskjobstates`.`id` WHERE `glpi_plugin_fusioninventory_taskjoblogs`.`id`='".$taskjoblogs_id."' LIMIT 1"; $result=$DB->query($query); while ($data=$DB->fetch_array($result)) { return $data["itemtype"]; } return ''; } /** * Display history of taskjob * * @param $taskjobs_id integer id of the taskjob * @param $width integer how large in pixel display array * @param $options array to display with specific options * - items_id integer id of item to display history * - itemtype value type of item to display * * @return bool TRUE if form is ok * **/ function showHistory($taskjobs_id, $width="950", $options=array()) { global $DB, $CFG_GLPI; $this->javascriptHistory(); $a_uniqid = array(); $start = 0; if (isset($_REQUEST["start"])) { $start = $_REQUEST["start"]; } $where = ''; if (isset($options['items_id']) AND isset($options['itemtype'])) { $where = " AND `items_id`='".$options['items_id']."' AND `itemtype`='".$options['itemtype']."' "; } if (isset($options['uniqid'])) { $where .= " AND `uniqid`='".$options['uniqid']."' "; } echo "<center>"; $query = 'SELECT * FROM `glpi_plugin_fusioninventory_taskjobstates` WHERE `plugin_fusioninventory_taskjobs_id`="'.$taskjobs_id.'" AND `state`!="3" '.$where.' GROUP BY uniqid, plugin_fusioninventory_agents_id ORDER BY `id` DESC'; $result = $DB->query($query); // ***** Display for all status running / prepared if (isset($options['uniqid']) AND $DB->numrows($result) == '0') { } else { // Display echo "<table class='tab_cadre' style='width: ".$width."px'>"; echo "<tr class='tab_bg_1'>"; echo "<th width='32'>"; echo "<img src='".$CFG_GLPI['root_doc']. "/plugins/fusioninventory/pics/task_running.png'/>"; echo "</th>"; echo "<td>"; if ($DB->numrows($result) > 0) { echo "<table class='tab_cadre'>"; echo "<tr>"; echo "<th></th>"; echo "<th>".__('Unique id', 'fusioninventory')."</th>"; echo "<th>".__('Process number', 'fusioninventory')."</th>"; echo "<th>".__('Agent', 'fusioninventory')."</th>"; echo "<th>"; echo __('Date'); echo "</th>"; echo "<th>"; echo __('Status'); echo "</th>"; echo "<th>"; echo __('Comments'); echo "</th>"; echo "</tr>"; while ($data=$DB->fetch_array($result)) { $this->showHistoryLines($data['id'], 1, 0, 7); $a_uniqid[] = $data['uniqid']; } echo "</table>"; } echo "</td>"; echo "</tr>"; echo "</table><br/>"; } // ***** Display for statejob OK if (count($a_uniqid) > 0) { $where .= " AND `uniqid` NOT IN ('".implode("', '", $a_uniqid)."')"; $query = 'SELECT * FROM `glpi_plugin_fusioninventory_taskjobstates` WHERE `plugin_fusioninventory_taskjobs_id`="'.$taskjobs_id.'" AND `state`!="3" '.$where.' GROUP BY uniqid, plugin_fusioninventory_agents_id ORDER BY `id` DESC'; } $querycount = 'SELECT count(*) AS cpt FROM `glpi_plugin_fusioninventory_taskjobstates` WHERE `plugin_fusioninventory_taskjobs_id`="'.$taskjobs_id.'" AND `state`="3" '.$where.' GROUP BY uniqid, plugin_fusioninventory_agents_id'; $resultcount = $DB->query($querycount); $a_datacount = $DB->fetch_assoc($resultcount); $number = $a_datacount['cpt']; if (isset($options['uniqid']) AND $number == '0') { } else { // display echo "<table class='tab_cadre' width='".$width."'>"; echo "<tr class='tab_bg_1'>"; echo "<th width='32'>"; echo "<img src='".$CFG_GLPI['root_doc']. "/plugins/fusioninventory/pics/task_finished.png'/>"; echo "</td>"; echo "<td>"; echo "<table class='tab_cadre' >"; echo "<tr>"; echo "<td colspan='5'>"; Html::printAjaxPager('', $start, $number); echo "</td>"; echo "</tr>"; $query = str_replace('`state`!="3"', '`state`="3"', $query); $query .= ' LIMIT '.intval($start).', '.intval($_SESSION['glpilist_limit']); $result = $DB->query($query); echo "<tr>"; echo "<th></th>"; echo "<th>".__('Unique id', 'fusioninventory')."</th>"; echo "<th>".__('Agent', 'fusioninventory')."</th>"; echo "<th>"; echo __('Date'); echo "</th>"; echo "<th>"; echo __('Status'); echo "</th>"; echo "</tr>"; while ($data=$DB->fetch_array($result)) { $this->showHistoryLines($data['id'], 0, 0, 5); } echo "<tr>"; echo "<td colspan='5'>"; Html::printAjaxPager('', $start, $number); echo "</td>"; echo "</tr>"; echo "</table>"; echo "</td>"; echo "</tr>"; echo "</table>"; } echo "</center>"; return TRUE; } /** * Display javascript functions for history */ function javascriptHistory() { global $CFG_GLPI; echo "<script type='text/javascript'> function close_array(id){ document.getElementById('plusmoins'+id).innerHTML = '<img src=\'". $CFG_GLPI['root_doc']."/plugins/fusioninventory/pics/collapse.png\''+ 'onClick=\'document.getElementById(\"viewfollowup'+id+'\").hide();appear_array('+id+');\' />". "&nbsp;<img src=\'".$CFG_GLPI['root_doc']."/plugins/fusioninventory/pics/refresh.png\' />'; document.getElementById('plusmoins'+id).style.backgroundColor = '#e4e4e2'; } function appear_array(id){ document.getElementById('plusmoins'+id).innerHTML = '<img src=\'". $CFG_GLPI['root_doc']."/plugins/fusioninventory/pics/expand.png\''+ 'onClick=\'document.getElementById(\"viewfollowup'+id+'\").show();close_array('+id+');\' />'; document.getElementById('plusmoins'+id).style.backgroundColor = '#f2f2f2'; } </script>"; echo "<script type='text/javascript' src='". $CFG_GLPI['root_doc']."/plugins/fusioninventory/prototype.js'></script>"; echo "<script type='text/javascript' src='". $CFG_GLPI['root_doc']."/plugins/fusioninventory/effects.js'></script>"; } /** * Display each history line * * @param $taskjobstates_id integer id of the taskjobstate * * @return nothing * **/ function showHistoryLines($taskjobstates_id, $displayprocess = 1, $displaytaskjob=0, $nb_td='5') { global $CFG_GLPI; $pfTaskjobstate = new PluginFusioninventoryTaskjobstate(); $pfAgent = new PluginFusioninventoryAgent(); $pfTaskjobstate->getFromDB($taskjobstates_id); $displayforceend = 0; $a_history = $this->find('`plugin_fusioninventory_taskjobstates_id` = "'. $pfTaskjobstate->fields['id'].'"', 'id DESC', '1'); echo "<tr class='tab_bg_1'>"; echo "<td width='40' id='plusmoins".$pfTaskjobstate->fields["id"]."'><img src='". $CFG_GLPI['root_doc']. "/plugins/fusioninventory/pics/expand.png' ". "onClick='document.getElementById(\"viewfollowup".$pfTaskjobstate->fields["id"]. "\").show();close_array(".$pfTaskjobstate->fields["id"].");' /></td>"; echo "<td>"; echo $pfTaskjobstate->fields['uniqid']; echo "</td>"; if ($displayprocess == '1') { echo "<td>"; echo $pfTaskjobstate->fields['id']; echo "</td>"; } if ($displaytaskjob == '1') { $pfTaskjob = new PluginFusioninventoryTaskjob(); $pfTask = new PluginFusioninventoryTask(); $pfTaskjob->getFromDB($pfTaskjobstate->fields['plugin_fusioninventory_taskjobs_id']); $pfTask->getFromDB($pfTaskjob->fields['plugin_fusioninventory_tasks_id']); echo "<td>"; echo $pfTaskjob->getLink(1)." (".$pfTask->getLink().")"; echo "</td>"; } echo "<td>"; $pfAgent->getFromDB($pfTaskjobstate->fields['plugin_fusioninventory_agents_id']); echo $pfAgent->getLink(1); Ajax::UpdateItemOnEvent('plusmoins'.$pfTaskjobstate->fields["id"], 'viewfollowup'.$pfTaskjobstate->fields["id"], $CFG_GLPI['root_doc']. "/plugins/fusioninventory/ajax/showtaskjoblogdetail.php", array('agents_id' => $pfTaskjobstate->fields['plugin_fusioninventory_agents_id'], 'uniqid' => $pfTaskjobstate->fields['uniqid']), array("click")); echo "</td>"; $a_return = $this->displayHistoryDetail(array_pop($a_history), 0); $count = $a_return[0]; $displayforceend += $count; echo $a_return[1]; if ($displayforceend == "0") { echo "<td align='center'>"; echo "<form name='form' method='post' action='". $CFG_GLPI['root_doc']."/plugins/fusioninventory/front/taskjob.form.php'>"; echo "<input type='hidden' name='taskjobstates_id' value='". $pfTaskjobstate->fields['id']."' />"; echo "<input type='hidden' name='taskjobs_id' value='". $pfTaskjobstate->fields['plugin_fusioninventory_taskjobs_id']."' />"; echo '<input name="forceend" value="'.__('Force the end', 'fusioninventory').'" class="submit" type="submit">'; Html::closeForm(); echo "</td>"; } echo "</tr>"; echo "<tr>"; echo "<td colspan='".$nb_td."' style='display: none;' id='viewfollowup". $pfTaskjobstate->fields["id"]."' class='tab_bg_4'>"; echo "</td>"; echo "</tr>"; } /** * Display detail of each history line * * @param $agents_id integer id of the agent * @param $uniqid integer uniq id of each taskjobs runing * @param $width integer how large in pixel display array * * @return value all text to display * **/ function showHistoryInDetail($agents_id, $uniqid, $width="950") { global $CFG_GLPI; $pfTaskjobstate = new PluginFusioninventoryTaskjobstate(); $pfAgent = new PluginFusioninventoryAgent(); $text = "<center><table class='tab_cadrehov' style='width: ".$width."px'>"; $a_jobstates = $pfTaskjobstate->find('`plugin_fusioninventory_agents_id`="'.$agents_id.'" '. 'AND `uniqid`="'.$uniqid.'"', '`id` DESC'); $a_devices_merged = array(); foreach ($a_jobstates as $data) { $displayforceend = 0; $a_history = $this->find('`plugin_fusioninventory_taskjobstates_id` = "'.$data['id'].'"', 'id'); if (strstr(exportArrayToDB($a_history), "Merged with ")) { $classname = $data['itemtype']; $Class = new $classname; $Class->getFromDB($data['items_id']); $a_devices_merged[] = $Class->getLink(1)."&nbsp;(".$Class->getTypeName().")"; } else { $text .= "<tr>"; $text .= "<th colspan='2'><img src='".$CFG_GLPI['root_doc']."/pics/puce.gif' />". __('Process number', 'fusioninventory')."&nbsp;: ".$data['id']."</th>"; $text .= "<th>"; $text .= __('Date'); $text .= "</th>"; $text .= "<th>"; $text .= __('Status'); $text .= "</th>"; $text .= "<th>"; $text .= __('Comments'); $text .= "</th>"; $text .= "</tr>"; $text .= "<tr class='tab_bg_1'>"; $text .= "<th colspan='2'>"; $text .= __('Agent', 'fusioninventory'); $text .= "</th>"; $a_return = $this->displayHistoryDetail(array_shift($a_history)); $count = $a_return[0]; $text .= $a_return[1]; $displayforceend += $count; $text .= "</tr>"; $text .= "<tr class='tab_bg_1'>"; $text .= "<td colspan='2'>"; $pfAgent->getFromDB($data['plugin_fusioninventory_agents_id']); $text .= $pfAgent->getLink(1); $text .= "</td>"; $a_return = $this->displayHistoryDetail(array_shift($a_history)); $count = $a_return[0]; $text .= $a_return[1]; $displayforceend += $count; $text .= "</tr>"; $text .= "<tr class='tab_bg_1'>"; $text .= "<th colspan='2'>"; $text .= __('Definition', 'fusioninventory'); $text .= "<sup>(".(count($a_devices_merged) + 1).")</sup>"; $text .= "</th>"; $a_return = $this->displayHistoryDetail(array_shift($a_history)); $count = $a_return[0]; $text .= $a_return[1]; $displayforceend += $count; $text .= "</tr>"; $text .= "<tr class='tab_bg_1'>"; $text .= "<td colspan='2'>"; if (!empty($data["itemtype"])) { $device = new $data["itemtype"](); $device->getFromDB($data["items_id"]); $text .= $device->getLink(1); $text .= "&nbsp;"; $text .= "(".$device->getTypeName().")"; } $text .= "</td>"; $a_return = $this->displayHistoryDetail(array_shift($a_history)); $count = $a_return[0]; $text .= $a_return[1]; $displayforceend += $count; $text .= "</tr>"; while (count($a_history) != 0) { if (count($a_devices_merged) > 0) { $text .= "<tr class='tab_bg_1'>"; $text .= "<td colspan='2'>"; $text .= array_pop($a_devices_merged); $text .= "</td>"; $a_return = $this->displayHistoryDetail(array_shift($a_history)); $count = $a_return[0]; $text .= $a_return[1]; $displayforceend += $count; $text .= "</tr>"; } else { $text .= "<tr class='tab_bg_1'>"; $text .= "<td colspan='2' rowspan='".count($a_history)."'>"; $text .= "</td>"; $a_return = $this->displayHistoryDetail(array_shift($a_history)); $count = $a_return[0]; $text .= $a_return[1]; $displayforceend += $count; $text .= "</tr>"; while (count($a_history) != 0) { $text .= "<tr class='tab_bg_1'>"; $a_return = $this->displayHistoryDetail(array_shift($a_history)); $count = $a_return[0]; $text .= $a_return[1]; $displayforceend += $count; $text .= "</tr>"; } } } $display = 1; while (count($a_devices_merged) != 0) { $text .= "<tr class='tab_bg_1'>"; $text .= "<td colspan='2'>"; $text .= array_pop($a_devices_merged); $text .= "</td>"; if ($display == "1") { $text .= "<td colspan='3' rowspan='".(count($a_devices_merged) + 1)."'></td>"; $display = 0; } $text .= "</tr>"; } $text .= "<tr class='tab_bg_4'>"; $text .= "<td colspan='5' height='4'>"; $text .= "</td>"; $text .= "</tr>"; } } $text .= "</table></center>"; return $text; } /** * Display high detail of each history line * * @param $datas array datas of history * @param $comment boolean 0/1 display comment or not * * @return array * - boolean 0/1 if this log = finish * - text to display * **/ function displayHistoryDetail($datas, $comment=1) { $text = "<td align='center'>"; $text .= Html::convDateTime($datas['date']); $text .= "</td>"; $finish = 0; switch ($datas['state']) { case self::TASK_PREPARED : $text .= "<td align='center'>"; $text .= __('Prepared', 'fusioninventory'); break; case self::TASK_STARTED : $text .= "<td align='center'>"; $text .= __('Started', 'fusioninventory'); break; case self::TASK_OK : $text .= "<td style='background-color: rgb(0, 255, 0);-moz-border-radius:". " 4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' ". "align='center'>"; $text .= "<strong>".__('Ok', 'fusioninventory')."</strong>"; $finish++; break; case self::TASK_ERROR_OR_REPLANNED : $text .= "<td style='background-color: rgb(255, 120, 0);-moz-border-radius: ". "4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' ". "align='center'>"; $text .= "<strong>".__('Error / rescheduled', 'fusioninventory')."</strong>"; $finish++; break; case self::TASK_ERROR : $text .= "<td style='background-color: rgb(255, 0, 0);-moz-border-radius: ". "4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' ". "align='center'>"; $text .= "<strong>".__('Error')."</strong>"; $finish++; break; case self::TASK_INFO : $text .= "<td style='background-color: rgb(255, 200, 0);-moz-border-radius: ". "4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' ". "align='center'>"; $text .= "<strong>".__('Info', 'fusioninventory')."</strong>"; $finish++; break; case self::TASK_RUNNING : $text .= "<td style='background-color: rgb(255, 200, 0);-moz-border-radius: ". "4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' ". "align='center'>"; $text .= "<strong>".__('Running')."</strong>"; break; default: $text .= "<td>"; break; } $text .= "</td>"; if ($comment == '1') { $text .= "<td class='fusinv_task_comment'>"; $datas['comment'] = PluginFusioninventoryTaskjoblog::convertComment($datas['comment']); $text .= $datas['comment']; $text .= "</td>"; } return array($finish, $text); } /** * Add a new line of log for a taskjob status * * @param $taskjobstates_id integer id of the taskjobstate * @param $items_id integer id of the item associated with taskjob status * @param $itemtype value type name of the item associated with taskjob status * @param $state value state of this taskjobstate * @param $comment value the comment of this insertion * * @return nothing * **/ function addTaskjoblog($taskjobstates_id, $items_id, $itemtype, $state, $comment) { global $DB; $this->getEmpty(); unset($this->fields['id']); $this->fields['plugin_fusioninventory_taskjobstates_id'] = $taskjobstates_id; $this->fields['date'] = date("Y-m-d H:i:s"); $this->fields['items_id'] = $items_id; $this->fields['itemtype'] = $itemtype; $this->fields['state'] = $state; $this->fields['comment'] = $DB->escape($comment); $this->addToDB(); } /** * Display the graph of finished tasks * * @param $taskjobs_id integer id of the taskjob * * @return nothing * **/ function graphFinish($taskjobs_id) { global $DB; $finishState = array(); $finishState[2] = 0; $finishState[3] = 0; $finishState[4] = 0; $finishState[5] = 0; $query = "SELECT `glpi_plugin_fusioninventory_taskjoblogs`.`state` FROM glpi_plugin_fusioninventory_taskjobstates LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` ON plugin_fusioninventory_taskjobstates_id=". "`glpi_plugin_fusioninventory_taskjobstates`.`id` WHERE `plugin_fusioninventory_taskjobs_id`='".$taskjobs_id."' AND (`glpi_plugin_fusioninventory_taskjoblogs`.`state` = '2' OR `glpi_plugin_fusioninventory_taskjoblogs`.`state` = '3' OR `glpi_plugin_fusioninventory_taskjoblogs`.`state` = '4' OR `glpi_plugin_fusioninventory_taskjoblogs`.`state` = '5') GROUP BY glpi_plugin_fusioninventory_taskjobstates.uniqid, ". "plugin_fusioninventory_agents_id"; $result=$DB->query($query); if ($result) { while ($datajob=$DB->fetch_array($result)) { $finishState[$datajob['state']]++; } } $input = array(); $input[__('Started', 'fusioninventory')] = $finishState[2]; $input[__('Ok', 'fusioninventory')] = $finishState[3]; $input[__('Error / rescheduled', 'fusioninventory')] = $finishState[4]; $input[__('Error')] = $finishState[5]; Stat::showGraph(array('status'=>$input), array('title' => '', 'unit' => '', 'type' => 'pie', 'height' => 150, 'showtotal' => FALSE)); } /** * Get taskjobstate by uniqid * * @param type $uuid value uniqid * * @return array with data of table glpi_plugin_fusioninventory_taskjobstates */ static function getByUniqID($uuid) { $a_datas = getAllDatasFromTable('glpi_plugin_fusioninventory_taskjobstates', "`uniqid`='$uuid'", "1"); foreach ($a_datas as $a_data) { return $a_data; } return array(); } /** * Display short logs * * @param $taskjobs_id integer id of taskjob * @param $veryshort boolean activation to have very very short display * * @return nothing */ function displayShortLogs($taskjobs_id, $veryshort=0) { global $DB, $CFG_GLPI; $pfTaskjobstate = new PluginFusioninventoryTaskjobstate(); echo "<td colspan='2' valign='top'>"; if ($veryshort == '0') { echo "<table width='100%'>"; echo "<tr class='tab_bg_3'>"; } else { echo "<table>"; echo "<tr class='tab_bg_1'>"; } $query = "SELECT * FROM `glpi_plugin_fusioninventory_taskjobstates` WHERE `plugin_fusioninventory_taskjobs_id`='".$taskjobs_id."' ORDER BY `uniqid` DESC LIMIT 1"; $result=$DB->query($query); $uniqid = 0; while ($data=$DB->fetch_array($result)) { $uniqid = $data['uniqid']; } $query = "SELECT `glpi_plugin_fusioninventory_taskjoblogs`.* FROM `glpi_plugin_fusioninventory_taskjoblogs` LEFT JOIN `glpi_plugin_fusioninventory_taskjobstates` ON plugin_fusioninventory_taskjobstates_id = ". "`glpi_plugin_fusioninventory_taskjobstates`.`id` WHERE `uniqid`='".$uniqid."' ORDER BY `glpi_plugin_fusioninventory_taskjoblogs`.`id` DESC LIMIT 1"; $state = 0; $date = ''; $comment = ''; $taskstates_id = 0; $result=$DB->query($query); while ($data=$DB->fetch_array($result)) { $state = $data['state']; $date = $data['date']; $comment = $data['comment']; $taskstates_id = $data['plugin_fusioninventory_taskjobstates_id']; } if (strstr($comment, "Merged with")) { $state = '7'; } $a_taskjobstates = count($pfTaskjobstate->find("`plugin_fusioninventory_taskjobs_id`='". $taskjobs_id."' AND `state` != '3' AND `uniqid`='".$uniqid."'")); if ( $state == '1' OR $state == '6' OR $state == '7') { // not finish if ($veryshort == '0') { echo "<th>"; echo "<img src='".$CFG_GLPI['root_doc']. "/plugins/fusioninventory/pics/task_running.png'/>"; echo "</th>"; } echo $this->getDivState($state, 'td'); echo "<td align='center'>"; echo " <a href='".$CFG_GLPI['root_doc']. "/plugins/fusioninventory/front/taskjoblog.php?sort=1&order=DESC&field[0]=6&". "searchtype[0]=contains&contains[0]=".$uniqid."&". "itemtype=PluginFusioninventoryTaskjoblog&start=0'>". __('View logs of this execution', 'fusioninventory')."</a>"; echo "<form name='form' method='post' action='". $CFG_GLPI['root_doc']."/plugins/fusioninventory/front/taskjob.form.php'>"; echo "<input type='hidden' name='taskjobstates_id' value='".$taskstates_id."' />"; echo "<input type='hidden' name='taskjobs_id' value='".$taskjobs_id."' />"; echo '&nbsp;&nbsp;&nbsp;<input name="forceend" value="'. __('Force the end', 'fusioninventory').'" class="submit" type="submit">'; Html::closeForm(); echo "</td>"; if ($veryshort == '0') { echo "</tr>"; echo "<tr class='tab_bg_3'>"; echo "<th>"; echo "<img src='".$CFG_GLPI['root_doc']. "/plugins/fusioninventory/pics/task_finished.png'/>"; echo "</th>"; echo "<td colspan='2' align='center'>"; echo " <a href='".$CFG_GLPI['root_doc']. "/plugins/fusioninventory/front/taskjoblog.php?sort=1&order=DESC&". "field[0]=3&searchtype[0]=equals&contains[0]=".$taskjobs_id."&". "itemtype=PluginFusioninventoryTaskjoblog&start=0'>". __('See all executions', 'fusioninventory')."</a>"; echo "</td>"; echo "</tr>"; } } else { // Finish if ($veryshort == '0') { echo "<th rowspan='2' height='64'>"; echo "<img src='".$CFG_GLPI['root_doc']. "/plugins/fusioninventory/pics/task_finished.png'/>"; echo "</th>"; } echo $this->getDivState($state, 'td'); if ($veryshort == '0') { echo "<td align='center'>"; } else { echo "<td>"; } if ($taskstates_id == '0') { echo __('Last run')."&nbsp;:&nbsp;".__('Never'); } else { if ($veryshort == '0') { if ($a_taskjobstates == '0') { echo __('Last run')." (".Html::convDateTime($date).") : "; } echo "<a href='".$CFG_GLPI['root_doc']. "/plugins/fusioninventory/front/taskjoblog.php?field[0]=6&". "searchtype[0]=contains&contains[0]=".$uniqid."&". "itemtype=PluginFusioninventoryTaskjoblog&start=0'>". __('View logs of this execution', 'fusioninventory')."</a>"; } else { if ($a_taskjobstates == '0') { echo __('Last run')." :<br/> ".Html::convDateTime($date).""; } } } if ($a_taskjobstates != '0') { echo "<form name='form' method='post' action='". $CFG_GLPI['root_doc']."/plugins/fusioninventory/front/taskjob.form.php'>"; echo "<input type='hidden' name='taskjobstates_id' value='".$taskstates_id."' />"; echo "<input type='hidden' name='taskjobs_id' value='".$taskjobs_id."' />"; echo '&nbsp;&nbsp;&nbsp;<input name="forceend" value="'. __('Force the end', 'fusioninventory').'" class="submit" type="submit">'; Html::closeForm(); } echo "</td>"; echo "</tr>"; if ($veryshort == '0') { echo "<tr class='tab_bg_3'>"; echo "<td colspan='2' align='center'>"; echo " <a href='".$CFG_GLPI['root_doc']. "/plugins/fusioninventory/front/taskjoblog.php?field[0]=3&". "searchtype[0]=equals&contains[0]=".$taskjobs_id."&". "itemtype=PluginFusioninventoryTaskjoblog&start=0'>". __('See all executions', 'fusioninventory')."</a>"; echo "</td>"; echo "</tr>"; } } echo "</table>"; echo "</td>"; } /** * Get div with text/color depend on state * * @param $state integer state number * @param $type string div / td * * @return string complete node (openned and closed) */ function getDivState($state, $type='div') { $width = '50'; switch ($state) { case 7: return "<".$type." align='center' width='".$width."'>". __('Prepared', 'fusioninventory')."</".$type.">"; break; case 1: return "<".$type." align='center' width='".$width."'>". __('Started', 'fusioninventory')."</".$type.">"; break; case 2: return "<".$type." style='background-color: rgb(0, 255, 0);-moz-border-radius: 4px;". "-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' ". "align='center' width='".$width."'>". "<strong>".__('Ok', 'fusioninventory')."</strong></".$type.">"; break; case 3: return "<".$type." style='background-color: rgb(255, 120, 0);-moz-border-radius: 4px;". "-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' ". "align='center' width='".$width."'>". "<strong>".__('Error / rescheduled', 'fusioninventory'). "</strong></".$type.">"; break; case 4: return "<".$type." style='background-color: rgb(255, 0, 0);-moz-border-radius: 4px;". "-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' align='center' ". "width='".$width."'>". "<strong>".__('Error')."</strong></".$type.">"; break; case 5: return "<".$type." style='background-color: rgb(255, 200, 0);-moz-border-radius: 4px;". "-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' ". "align='center' width='".$width."'>". "<strong>".__('unknown', 'fusioninventory')."</strong></".$type.">"; break; case 6: return "<".$type." style='background-color: rgb(255, 200, 0);-moz-border-radius: 4px;". "-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' ". "align='center' width='".$width."'>". "<strong>".__('Running')."</strong></".$type.">"; break; } } /** * Display quick list logs * * @param $tasks_id integer id of task * * @return nothing */ static function quickListLogs($tasks_id) { global $DB; $query = "SELECT * FROM `glpi_plugin_fusioninventory_taskjobstates` LEFT JOIN `glpi_plugin_fusioninventory_taskjobs` ON `plugin_fusioninventory_taskjobs_id` = `glpi_plugin_fusioninventory_taskjobs`.`id` WHERE `plugin_fusioninventory_tasks_id`='".$tasks_id."' ORDER BY uniqid DESC LIMIT 1"; $result = $DB->query($query); $uniqid = 0; $action = ''; while ($data=$DB->fetch_array($result)) { $uniqid = $data['uniqid']; $action = $data['action']; } if ($uniqid == '0') { if ($action == '') { echo "<center><strong>No agent found for this task</strong></center>"; } } else { $params = array(); $params['field'][0] = '6'; $params['searchtype'][0] = 'contains'; $params['contains'][0] = $uniqid; $params['itemtype'] = 'PluginFusioninventoryTaskjoblog'; $params['start'] = '0'; Search::manageGetValues('PluginFusioninventoryTaskjoblog'); Search::showList('PluginFusioninventoryTaskjoblog', $params); } } static function convertComment($comment) { $matches = array(); // Search for replace [[itemtype::items_id]] by link preg_match_all("/\[\[(.*)\:\:(.*)\]\]/", $comment, $matches); foreach($matches[0] as $num=>$commentvalue) { $classname = $matches[1][$num]; if ($classname != '') { $Class = new $classname; $Class->getFromDB($matches[2][$num]); $comment = str_replace($commentvalue, $Class->getLink(), $comment); } } if (strstr($comment, "==")) { preg_match_all("/==([\w\d]+)==/", $comment, $matches); $a_text = array( 'devicesqueried' => __('devices queried', 'fusioninventory'), 'devicesfound' => __('devices found', 'fusioninventory'), 'diconotuptodate' => __("SNMP equipment definition isn't up to date on agent. For the next run, it will get new version from server.", 'fusioninventory'), 'addtheitem' => __('Add the item', 'fusioninventory'), 'updatetheitem' => __('Update the item', 'fusioninventory'), 'inventorystarted' => __('Inventory started', 'fusioninventory'), 'detail' => __('Detail', 'fusioninventory'), 'badtoken' => __('Agent communication error, impossible to start agent', 'fusioninventory'), 'agentcrashed' => __('Agent stopped/crashed', 'fusioninventory'), 'importdenied' => __('Import denied', 'fusioninventory') ); foreach($matches[0] as $num=>$commentvalue) { $comment = str_replace($commentvalue, $a_text[$matches[1][$num]], $comment); } } $comment = str_replace(",[", "<br/>[", $comment); return $comment; } // ********** Functions for Monitoring / Logs ********** // function listTasks() { global $DB; $query = "SELECT `glpi_plugin_fusioninventory_taskjobstates`.`id`," . "`glpi_plugin_fusioninventory_taskjobs`.`method`," . "`glpi_plugin_fusioninventory_taskjobs`.`name`" . " FROM `glpi_plugin_fusioninventory_taskjobstates` " . "LEFT JOIN `glpi_plugin_fusioninventory_taskjobs` ON " . "`plugin_fusioninventory_taskjobs_id`=`glpi_plugin_fusioninventory_taskjobs`.`id` " . "GROUP BY `glpi_plugin_fusioninventory_taskjobstates`.`plugin_fusioninventory_taskjobs_id`," . "`glpi_plugin_fusioninventory_taskjobstates`.`execution_id` " . "ORDER BY `glpi_plugin_fusioninventory_taskjobstates`.`id` DESC "; $result = $DB->query($query); $i = 1; $nb = $DB->numrows($result); while ($data = $DB->fetch_assoc($result)) { $begintable = 0; $endtable = 0; if ($i == 1) { $begintable = 1; } else if ($i == $nb) { $endtable = 1; } $this->_showLine( $data['method'], $data['name'], '80 deployments (ok: 50, ko : 12, unneeded : 3)', '81', 'RUNNING', $begintable, $endtable); $i++; } } function _showLine ($module, $name, $text, $percent, $state, $begintable=0, $endtable=0) { global $CFG_GLPI; if ($begintable) { echo "<table class='tab_cadrehov'>"; } echo "<tr class='tab_bg_1'>"; echo "<td width='27'>"; echo "<img src='".$CFG_GLPI["root_doc"]."/plugins/fusioninventory/pics/icon_".$module.".png'/>"; echo "</td>"; echo "<td width='27'>"; echo "<img src='".$CFG_GLPI["root_doc"]."/plugins/fusioninventory/pics/icon_plus.png'/>"; echo "</td>"; echo "<td><strong>"; echo $name; echo "</strong></td>"; echo "<td>"; echo $text; echo "</td>"; echo "<td>"; echo __('Completion', 'fusioninventory').' : '.$percent.'%'; echo "</td>"; echo "<td>"; // image status echo "</td>"; if ($endtable) { echo "</table>"; } } } ?>
orthagh/fusioninventory-for-glpi
inc/taskjoblog.class.php
PHP
agpl-3.0
41,270
/* * This file is part of Splice Machine. * Splice Machine 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, or (at your option) any later version. * Splice Machine 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 Splice Machine. * If not, see <http://www.gnu.org/licenses/>. * * Some parts of this source code are based on Apache Derby, and the following notices apply to * Apache Derby: * * Apache Derby is a subproject of the Apache DB project, and is licensed under * the Apache License, Version 2.0 (the "License"); you may not use these files * except in compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Splice Machine, Inc. has modified the Apache Derby code in this file. * * All such Splice Machine modifications are Copyright 2012 - 2020 Splice Machine, Inc., * and are licensed to you under the GNU Affero General Public License. */ package com.splicemachine.db.iapi.sql.compile; import com.splicemachine.db.iapi.error.StandardException; import com.splicemachine.db.iapi.util.JBitSet; /** * This interface provides a representation of the required ordering of rows * from a ResultSet. Different operations can require ordering: ORDER BY, * DISTINCT, GROUP BY. Some operations, like ORDER BY, require that the * columns be ordered a particular way, while others, like DISTINCT and * GROUP BY, reuire only that there be no duplicates in the result. */ public interface RequiredRowOrdering { int SORT_REQUIRED = 1; int ELIMINATE_DUPS = 2; int NOTHING_REQUIRED = 3; /** * Tell whether sorting is required for this RequiredRowOrdering, * given a RowOrdering. * * @param rowOrdering The order of rows in question * @param optimizableList The current join order being considered by * the optimizer. We need to look into this to determine if the outer * optimizables are single row resultset if the order by column is * on an inner optimizable and that inner optimizable is not a one * row resultset. DERBY-3926 * * @return SORT_REQUIRED if sorting is required, * ELIMINATE_DUPS if no sorting is required but duplicates * must be eliminated (i.e. the rows are in * the right order but there may be duplicates), * NOTHING_REQUIRED is no operation is required * * @exception StandardException Thrown on error */ int sortRequired(RowOrdering rowOrdering, OptimizableList optimizableList) throws StandardException; /** * Tell whether sorting is required for this RequiredRowOrdering, * given a RowOrdering representing a partial join order, and * a bit map telling what tables are represented in the join order. * This is useful for reducing the number of cases the optimizer * has to consider. * * @param rowOrdering The order of rows in the partial join order * @param tableMap A bit map of the tables in the partial join order * @param optimizableList The current join order being considered by * the optimizer. We need to look into this to determine if the outer * optimizables are single row resultset if the order by column is * on an inner optimizable and that inner optimizable is not a one * row resultset. DERBY-3926 * * @return SORT_REQUIRED if sorting is required, * ELIMINATE_DUPS if no sorting is required by duplicates * must be eliminated (i.e. the rows are in * the right order but there may be duplicates), * NOTHING_REQUIRED is no operation is required * * @exception StandardException Thrown on error */ int sortRequired(RowOrdering rowOrdering, JBitSet tableMap, OptimizableList optimizableList) throws StandardException; /** * Estimate the cost of doing a sort for this row ordering, given * the number of rows to be sorted. This does not take into account * whether the sort is really needed. It also estimates the number of * result rows. * * @param rowOrdering The ordering of the input rows * * @exception StandardException Thrown on error */ void estimateCost(Optimizer optimizer, RowOrdering rowOrdering, CostEstimate baseCost, CostEstimate sortCost) throws StandardException; /** * Indicate that a sort is necessary to fulfill this required ordering. * This method may be called many times during a single optimization. */ void sortNeeded(); /** * Indicate that a sort is *NOT* necessary to fulfill this required * ordering. This method may be called many times during a single * optimization. */ void sortNotNeeded(); /** * @return Whether or not a sort is needed. */ boolean isSortNeeded(); }
splicemachine/spliceengine
db-engine/src/main/java/com/splicemachine/db/iapi/sql/compile/RequiredRowOrdering.java
Java
agpl-3.0
5,820
package realtime import ( "context" "fmt" "net/http" "strings" "time" "github.com/cozy/cozy-stack/model/instance" "github.com/cozy/cozy-stack/model/permission" "github.com/cozy/cozy-stack/model/vfs" "github.com/cozy/cozy-stack/pkg/consts" "github.com/cozy/cozy-stack/pkg/couchdb" "github.com/cozy/cozy-stack/pkg/jsonapi" "github.com/cozy/cozy-stack/pkg/logger" "github.com/cozy/cozy-stack/pkg/prefixer" "github.com/cozy/cozy-stack/pkg/realtime" "github.com/cozy/cozy-stack/web/middlewares" "github.com/gorilla/websocket" "github.com/labstack/echo/v4" ) const ( // Time allowed to write a message to the peer writeWait = 10 * time.Second // Time allowed to read the next pong message from the peer pongWait = 60 * time.Second // Send pings to peer with this period (must be less than pongWait) pingPeriod = (pongWait * 9) / 10 // Maximum message size allowed from peer maxMessageSize = 1024 ) var upgrader = websocket.Upgrader{ // Don't check the origin of the connexion, we check authorization later CheckOrigin: func(r *http.Request) bool { return true }, Subprotocols: []string{"io.cozy.websocket"}, ReadBufferSize: 1024, WriteBufferSize: 1024, } type command struct { Method string `json:"method"` Payload struct { Type string `json:"type"` ID string `json:"id"` } `json:"payload"` } type wsResponsePayload struct { Type string `json:"type"` ID string `json:"id"` Doc interface{} `json:"doc,omitempty"` } type wsResponse struct { Event string `json:"event"` Payload wsResponsePayload `json:"payload"` } type wsErrorPayload struct { Status string `json:"status"` Code string `json:"code"` Title string `json:"title"` Source interface{} `json:"source"` } type wsError struct { Event string `json:"event"` Payload wsErrorPayload `json:"payload"` } func unauthorized(cmd interface{}) *wsError { return &wsError{ Event: "error", Payload: wsErrorPayload{ Status: "401 Unauthorized", Code: "unauthorized", Title: "The authentication has failed", Source: cmd, }, } } func forbidden(cmd *command) *wsError { return &wsError{ Event: "error", Payload: wsErrorPayload{ Status: "403 Forbidden", Code: "forbidden", Title: fmt.Sprintf("The application can't subscribe to %s", cmd.Payload.Type), Source: cmd, }, } } func unknownMethod(method string, cmd interface{}) *wsError { return &wsError{ Event: "error", Payload: wsErrorPayload{ Status: "405 Method Not Allowed", Code: "method not allowed", Title: fmt.Sprintf("The %s method is not supported", method), Source: cmd, }, } } func missingType(cmd *command) *wsError { return &wsError{ Event: "error", Payload: wsErrorPayload{ Status: "404 Page Not Found", Code: "page not found", Title: "The type parameter is mandatory for SUBSCRIBE", Source: cmd, }, } } func sendErr(ctx context.Context, errc chan *wsError, e *wsError) { select { case errc <- e: case <-ctx.Done(): } } func authorized(i *instance.Instance, perms permission.Set, permType, id string) bool { if perms.AllowWholeType(permission.GET, permType) { return true } else if id == "" { return false } else if permType == consts.Files { fs := i.VFS() dir, file, err := fs.DirOrFileByID(id) if dir != nil { err = vfs.Allows(fs, perms, permission.GET, dir) } else if file != nil { err = vfs.Allows(fs, perms, permission.GET, file) } return err == nil } else { return perms.AllowID(permission.GET, permType, id) } } func readPump(ctx context.Context, c echo.Context, i *instance.Instance, ws *websocket.Conn, ds *realtime.DynamicSubscriber, errc chan *wsError, withAuthentication bool) { defer close(errc) var err error var pdoc *permission.Permission if withAuthentication { var auth map[string]string if err = ws.ReadJSON(&auth); err != nil { sendErr(ctx, errc, unknownMethod(auth["method"], auth)) return } if strings.ToUpper(auth["method"]) != "AUTH" { sendErr(ctx, errc, unknownMethod(auth["method"], auth)) return } if auth["payload"] == "" { sendErr(ctx, errc, unauthorized(auth)) return } pdoc, err = middlewares.ParseJWT(c, i, auth["payload"]) if err != nil { sendErr(ctx, errc, unauthorized(auth)) return } } for { cmd := &command{} if err = ws.ReadJSON(cmd); err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNoStatusReceived) { logger. WithDomain(ds.DomainName()). WithField("nspace", "realtime"). Debugf("Error: %s", err) } break } method := strings.ToUpper(cmd.Method) if method != "SUBSCRIBE" && method != "UNSUBSCRIBE" { sendErr(ctx, errc, unknownMethod(cmd.Method, cmd)) continue } if cmd.Payload.Type == "" { sendErr(ctx, errc, missingType(cmd)) continue } permType := cmd.Payload.Type // XXX: thumbnails is a synthetic doctype, listening to its events // requires a permissions on io.cozy.files. Same for note events. if permType == consts.Thumbnails || permType == consts.NotesEvents { permType = consts.Files } // XXX: no permissions are required for io.cozy.sharings.initial_sync // and io.cozy.auth.confirmations if withAuthentication && cmd.Payload.Type != consts.SharingsInitialSync && cmd.Payload.Type != consts.AuthConfirmations { if !authorized(i, pdoc.Permissions, permType, cmd.Payload.ID) { sendErr(ctx, errc, forbidden(cmd)) continue } } if method == "SUBSCRIBE" { if cmd.Payload.ID == "" { err = ds.Subscribe(cmd.Payload.Type) } else { err = ds.Watch(cmd.Payload.Type, cmd.Payload.ID) } } else if method == "UNSUBSCRIBE" { if cmd.Payload.ID == "" { err = ds.Unsubscribe(cmd.Payload.Type) } else { err = ds.Unwatch(cmd.Payload.Type, cmd.Payload.ID) } } if err != nil { logger. WithDomain(ds.DomainName()). WithField("nspace", "realtime"). Warnf("Error: %s", err) } } } // Ws is the API handler for realtime via a websocket connection. func Ws(c echo.Context) error { var db prefixer.Prefixer // The realtime webservice can be plugged in a context without instance // fetching. For instance in the administration server. In such case, we do // not need authentication inst, withAuthentication := middlewares.GetInstanceSafe(c) if !withAuthentication { db = prefixer.GlobalPrefixer } else { db = inst } ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil) if err != nil { return err } defer ws.Close() ws.SetReadLimit(maxMessageSize) if err = ws.SetReadDeadline(time.Now().Add(pongWait)); err != nil { return nil } ws.SetPongHandler(func(string) error { return ws.SetReadDeadline(time.Now().Add(pongWait)) }) ds := realtime.GetHub().Subscriber(db) defer ds.Close() ctx, cancel := context.WithCancel(context.Background()) defer cancel() errc := make(chan *wsError) go readPump(ctx, c, inst, ws, ds, errc, withAuthentication) ticker := time.NewTicker(pingPeriod) defer ticker.Stop() for { select { case e, ok := <-errc: if !ok { // Websocket has been closed by the client return nil } if err := ws.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { return nil } if err := ws.WriteJSON(e); err != nil { return nil } case e := <-ds.Channel: if err := ws.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { return err } res := wsResponse{ Event: e.Verb, Payload: wsResponsePayload{ Type: e.Doc.DocType(), ID: e.Doc.ID(), Doc: e.Doc, }, } if err := ws.WriteJSON(res); err != nil { return nil } case <-ticker.C: if err := ws.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { return err } if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil { return nil } } } } // Notify is the API handler for POST /realtime/:doctype/:id: this route can be // used to send documents in the real-time without having to persist them in // CouchDB. func Notify(c echo.Context) error { inst := middlewares.GetInstance(c) doctype := c.Param("doctype") id := c.Param("id") if err := permission.CheckReadable(doctype); err != nil { return jsonapi.BadRequest(err) } var payload couchdb.JSONDoc if err := c.Bind(&payload); err != nil { return jsonapi.BadRequest(err) } payload.SetID(id) payload.Type = doctype if err := middlewares.Allow(c, permission.POST, &payload); err != nil { return err } realtime.GetHub().Publish(inst, realtime.EventNotify, &payload, nil) return c.NoContent(http.StatusNoContent) } // Routes set the routing for the realtime service func Routes(router *echo.Group) { router.GET("/", Ws) router.POST("/:doctype/:id", Notify) }
nono/cozy-stack
web/realtime/realtime.go
GO
agpl-3.0
8,794
<?php namespace Melisa\core; class Messages { public function __construct() { log_message('debug', __CLASS__ . ' Class Initialized'); } public function add(&$input) { $message = array_default($input, [ 'type'=>'error', 'line'=>FALSE, 'log'=>TRUE, 'file'=>FALSE, 'message'=>'' ]); if($message['log']) { log_message($message['type'], $message['message']); } /* unset variables de mas */ if( !$message['file']) unset($message['file']); if( !$message['line']) unset($message['line']); if( !$message['log']) unset($message['log']); if(ENVIRONMENT != 'development') { unset($message['line'], $message['file'], $message['log']); } $this->addMessage($message); } public function get() { return $this->addMessage(NULL, TRUE); } private function addMessage($message, $get = FALSE) { static $messages = array(); static $count = 0; if($get) { /* verify enviroment, delete message debug */ if(ENVIRONMENT != 'development' && isset($messages['d'])) { unset($messages['d']); } return $messages; } if( $count > 50) { $messages = []; $count = 0; } /* agrupamos los mensajes por type */ switch ($message['type']) { case 'debug': $tipo = 'd'; break; case 'warning': $tipo = 'w'; break; case 'benchmark': /* benchmark points ya que bm es usado por el sistema */ $tipo = 'bmp'; break; default: $tipo = 'e'; break; } /* exec event */ Event()->fire('core.message.add', [ $message ]); unset($message['type']); /* add message */ $messages[$tipo][] = $message; } }
melisamx/melisa-kernel
third_party/melisa-kernel/release/libraries/Melisa/core/Messages.php
PHP
agpl-3.0
2,453
package org.kuali.kra.negotiations.lookup; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.kuali.coeus.common.framework.custom.attr.CustomAttribute; import org.kuali.coeus.common.framework.person.KcPerson; import org.kuali.kra.negotiations.bo.Negotiation; import org.kuali.kra.negotiations.customdata.NegotiationCustomData; import org.kuali.rice.kns.lookup.HtmlData.AnchorHtmlData; import org.kuali.rice.kns.web.struts.form.LookupForm; import org.kuali.rice.kns.web.ui.Column; import org.kuali.rice.kns.web.ui.Field; import org.kuali.rice.kns.web.ui.ResultRow; import org.kuali.rice.kns.web.ui.Row; import org.kuali.rice.krad.bo.BusinessObject; import org.kuali.rice.krad.lookup.CollectionIncomplete; import org.kuali.rice.krad.util.BeanPropertyComparator; import org.kuali.coeus.common.framework.person.KcPersonService; import org.kuali.coeus.sys.framework.util.CollectionUtils; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import edu.iu.uits.kra.negotiations.lookup.IUNegotiationDaoOjb; /** * Negotiation Lookup Helper Service */ public class IUNegotiationLookupableHelperServiceImpl extends NegotiationLookupableHelperServiceImpl { private static final long serialVersionUID = -7144337780492481726L; private static final String USER_ID = "userId"; private NegotiationDao negotiationDao; private KcPersonService kcPersonService; @SuppressWarnings("unchecked") @Override public List<? extends BusinessObject> getSearchResults(Map<String, String> fieldValues) { super.setBackLocationDocFormKey(fieldValues); if (this.getParameters().containsKey(USER_ID)) { fieldValues.put("associatedNegotiable.piId", ((String[]) this.getParameters().get(USER_ID))[0]); fieldValues.put("negotiatorPersonId", ((String[]) this.getParameters().get(USER_ID))[0]); } List<Long> ids = null; /* Begin IU Customization */ //UITSRA-2543 Map<String, String> formProps = new HashMap<String, String>(); if (!StringUtils.isEmpty(fieldValues.get("sponsorAwardNumber")) && !StringUtils.equals("*", fieldValues.get("sponsorAwardNumber").trim())) { formProps.put("value", fieldValues.get("sponsorAwardNumber")); formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "SPON_AWD_ID")); ids = getCustomDataIds(formProps, null); } fieldValues.remove("sponsorAwardNumber"); //UITSRA-2893, UITSRA-2894 if (!StringUtils.isEmpty(fieldValues.get("gsTeam")) && !StringUtils.equals("*", fieldValues.get("gsTeam").trim())) { formProps.put("value", fieldValues.get("gsTeam")); formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "gsTeam")); ids = getCustomDataIds(formProps, ids); } if (!StringUtils.isEmpty(fieldValues.get("recordResidesWith")) && !StringUtils.equals("*", fieldValues.get("recordResidesWith").trim())) { formProps.put("value", fieldValues.get("recordResidesWith")); formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "recordLocation")); ids = getCustomDataIds(formProps, ids); } if (!StringUtils.isEmpty(fieldValues.get("accountId")) && !StringUtils.equals("*", fieldValues.get("accountId").trim())) { formProps.put("value", fieldValues.get("accountId")); formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "accountID")); ids = getCustomDataIds(formProps, ids); } fieldValues.remove("recordResidesWith"); fieldValues.remove("gsTeam"); fieldValues.remove("accountId"); //End of UITSRA-2893, UITSRA-2894 // UITSRA-4218 if (!StringUtils.isEmpty(fieldValues.get("contractDate")) && !StringUtils.equals("*", fieldValues.get("contractDate").trim())) { formProps.put("value", fieldValues.get("contractDate")); formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "contractDate")); ids = getCustomDataIds(formProps, ids); } fieldValues.remove("contractDate"); // End of UITSRA-4218 // UITSRA-3190 -Add Person Lookup capability to Search screens List<Long> piNegotiationIds = null; if (fieldValues.containsKey("associatedNegotiable.principalInvestigatorUserName")) { String piUserName = fieldValues.get("associatedNegotiable.principalInvestigatorUserName"); if (StringUtils.isNotBlank(piUserName)) { // UITSRA-3477 if (StringUtils.contains(piUserName, "*")) { piUserName = StringUtils.remove(piUserName, '*'); } // End of UITSRA-3477 KcPerson person = getKcPersonService().getKcPersonByUserName(piUserName); if (person != null && person.getPersonId() != null) { piNegotiationIds = new ArrayList<Long>(((IUNegotiationDaoOjb) getNegotiationDao()).getNegotiationIdsByPI(person.getPersonId())); if (piNegotiationIds.size() > 0) { if (fieldValues.containsKey("negotiationId") && StringUtils.isNotBlank(fieldValues.get("negotiationId"))) { String regex = "[0-9]+"; String negotiationId = fieldValues.get("negotiationId"); if (negotiationId.matches(regex)) { if (!piNegotiationIds.contains(new Long(negotiationId))) { return new ArrayList<Negotiation>(); } } } else { fieldValues.put("negotiationId", StringUtils.join(piNegotiationIds, '|')); } } else { fieldValues.put("associatedDocumentId", "Invalid PI Id"); } } else { fieldValues.put("associatedDocumentId", "Invalid PI Id"); } } fieldValues.remove("associatedNegotiable.principalInvestigatorUserName"); } // End of UITSRA-3190 // UITSRA-3191 - Change Negotiator Lookup field in Negotiation search options KcPerson negotiator = null; if (fieldValues.containsKey("negotiatorUserName") && StringUtils.isNotBlank(fieldValues.get("negotiatorUserName")) ) { negotiator = getKcPersonService().getKcPersonByUserName(fieldValues.get("negotiatorUserName")); if (negotiator != null && StringUtils.isNotBlank(negotiator.getPersonId())) { fieldValues.put("negotiatorPersonId", negotiator.getPersonId()); } else { fieldValues.put("negotiatorPersonId", "Invalid Negotiator Person Id"); } fieldValues.remove("negotiatorUserName"); } // End of UITSRA-3191 // UITSRA-3761 - Update Negotiation Search Options and Results List<Long> subAwardNegotiationIds = null; if (fieldValues.containsKey("associatedNegotiable.requisitionerUserName")) { String requisitionerUserName = fieldValues.get("associatedNegotiable.requisitionerUserName"); if (StringUtils.isNotBlank(requisitionerUserName)) { if (StringUtils.contains(requisitionerUserName, "*")) { requisitionerUserName = StringUtils.remove(requisitionerUserName, '*'); } KcPerson person = getKcPersonService().getKcPersonByUserName(requisitionerUserName); if (person != null && person.getPersonId() != null) { subAwardNegotiationIds = new ArrayList<Long>(((IUNegotiationDaoOjb) getNegotiationDao()).getNegotiationIdsByRequisitioner(person.getPersonId())); if (subAwardNegotiationIds.size() > 0) { if (fieldValues.containsKey("negotiationId") && StringUtils.isNotBlank(fieldValues.get("negotiationId"))) { String regex = "[0-9]+"; String negotiationId = fieldValues.get("negotiationId"); if (negotiationId.matches(regex)) { if (!subAwardNegotiationIds.contains(new Long(negotiationId))) { return new ArrayList<Negotiation>(); } } } else { fieldValues.put("negotiationId", StringUtils.join(subAwardNegotiationIds, '|')); } } else { fieldValues.put("associatedDocumentId", "Invalid PI Id"); } } else { fieldValues.put("associatedDocumentId", "Invalid PI Id"); } } fieldValues.remove("associatedNegotiable.requisitionerUserName"); fieldValues.remove("associatedNegotiable.subAwardRequisitionerId"); } if (!StringUtils.isEmpty(fieldValues.get("modification_id")) && !StringUtils.equals("*", fieldValues.get("modification_id").trim())) { formProps.put("value", fieldValues.get("modification_id")); formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "MOD_NUM")); ids = getCustomDataIds(formProps, ids); } if (!StringUtils.isEmpty(fieldValues.get("proposalDocID")) && !StringUtils.equals("*", fieldValues.get("proposalDocID").trim())) { formProps.put("value", fieldValues.get("proposalDocID")); formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "proposalDocID")); ids = getCustomDataIds(formProps, ids); } if (!StringUtils.isEmpty(fieldValues.get("ipid")) && !StringUtils.equals("*", fieldValues.get("ipid").trim())) { formProps.put("value", fieldValues.get("ipid")); formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "CSU_REF_NUM")); ids = getCustomDataIds(formProps, ids); } if (!StringUtils.isEmpty(fieldValues.get("proposalType")) && !StringUtils.equals("*", fieldValues.get("proposalType").trim())) { formProps.put("value", fieldValues.get("proposalType")); formProps.put("customAttributeId", getCustomAttributeId("Grant Services Negotiations", "proposalType")); ids = getCustomDataIds(formProps, ids); } fieldValues.remove("modification_id"); fieldValues.remove("proposalDocID"); fieldValues.remove("ipid"); fieldValues.remove("proposalType"); // End of UITSRA-3761 if (!StringUtils.isEmpty(fieldValues.get("ricroCleared")) ) { formProps.put("value", fieldValues.get("ricroCleared")); formProps.put("customAttributeId", getCustomAttributeId("SP Office Negotiations", "RICRO_CLEARED")); ids = getCustomDataIds(formProps, ids); } fieldValues.remove("ricroCleared"); if (!StringUtils.isEmpty(fieldValues.get("coiCleared")) ) { formProps.put("value", fieldValues.get("coiCleared")); formProps.put("customAttributeId", getCustomAttributeId("SP Office Negotiations", "COI_CLEARED")); ids = getCustomDataIds(formProps, ids); } fieldValues.remove("coiCleared"); if (!StringUtils.isEmpty(fieldValues.get("proposalActionType")) ) { formProps.put("value", fieldValues.get("proposalActionType")); formProps.put("customAttributeId", getCustomAttributeId("SP Office Negotiations", "PROP_ACTION_TYPE")); ids = getCustomDataIds(formProps, ids); } fieldValues.remove("proposalActionType"); if (!StringUtils.isEmpty(fieldValues.get("csuRefNum")) && !StringUtils.equals("*", fieldValues.get("csuRefNum").trim())) { formProps.put("value", fieldValues.get("csuRefNum")); formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "CSU_REF_NUM")); ids = getCustomDataIds(formProps, ids); } fieldValues.remove("csuRefNum"); /* CSU customization custom data arg search fix */ fieldValues.put("negotiationCustomDataList.negotiationCustomDataId", StringUtils.join(ids, '|')); /* End IU Customization */ // UITSRA-3138 // In class LookupDaoOjb.java (method addCriteria()), a String data type is required in order to create the // search criteria for a Negotiation Id wild card search. Currently negotiationId is Long rather than String, // which is not consistent with other KC modules like Award, IP etc. The ideal fix is to change the Negotiation Id's // data type from Long to String, but it requires a major design change on the foundation side. List<Long> wildcardNegotiationIds = null; if (fieldValues.containsKey("negotiationId") && fieldValues.get("negotiationId").contains("*")) { wildcardNegotiationIds = new ArrayList<Long>(((IUNegotiationDaoOjb) getNegotiationDao()).getNegotiationIdsWithWildcard(fieldValues.get("negotiationId"))); fieldValues.put("negotiationId", StringUtils.join(wildcardNegotiationIds, '|')); } List<Negotiation> searchResults = new ArrayList<Negotiation>(); CollectionIncomplete<Negotiation> limitedSearchResults; // UITSRA-3138 if (wildcardNegotiationIds == null || wildcardNegotiationIds.size() != 0 || piNegotiationIds == null || piNegotiationIds.size() != 0) { // UITSRA-4033 limitedSearchResults = (CollectionIncomplete<Negotiation>) getNegotiationDao().getNegotiationResults(fieldValues); searchResults.addAll(limitedSearchResults); List defaultSortColumns = getDefaultSortColumns(); if (defaultSortColumns.size() > 0) { org.kuali.coeus.sys.framework.util.CollectionUtils.sort(searchResults, new BeanPropertyComparator(defaultSortColumns, true)); //UITSRA-4320 return new CollectionIncomplete<Negotiation>(searchResults, limitedSearchResults.getActualSizeIfTruncated()); } return limitedSearchResults; } return searchResults; } /** * @see org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#getRows() */ @Override public List<Row> getRows() { List<Row> rows = super.getRows(); for (Row row : rows) { for (Field field : row.getFields()) { if (field.getPropertyName().equals("negotiatorUserName")) { field.setFieldConversions("principalName:negotiatorUserName,principalId:negotiatorPersonId"); } if (field.getPropertyName().equals("associatedNegotiable.principalInvestigatorUserName")) { field.setFieldConversions("principalName:associatedNegotiable.principalInvestigatorUserName,principalId:associatedNegotiable.principalInvestigatorPersonId"); } if (field.getPropertyName().equals("associatedNegotiable.requisitionerUserName")) { field.setFieldConversions("principalName:associatedNegotiable.requisitionerUserName,principalId:associatedNegotiable.subAwardRequisitionerId"); } } } return rows; } public KcPersonService getKcPersonService() { if (this.kcPersonService == null) { this.kcPersonService = KcServiceLocator.getService(KcPersonService.class); } return this.kcPersonService; } /* Begin IU Customization */ public String getCustomAttributeId(String groupName, String attributeName) { Map<String, String> fieldValues = new HashMap<String, String>(); fieldValues.put("groupName", groupName); fieldValues.put("name", attributeName); List<CustomAttribute> customAttributes = (List<CustomAttribute>) getBusinessObjectService().findMatching(CustomAttribute.class, fieldValues); if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(customAttributes)) { return customAttributes.get(0).getId().toString(); } else { return null; } } /** * Call's the super class's performLookup function and edits the URLs for the unit name, unit number, sponsor name, subAwardOrganization name, and pi name. * @see org.kuali.kra.lookup.KraLookupableHelperServiceImpl#performLookup(LookupForm, Collection, boolean) */ @Override public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) { final String leadUnitName = "associatedNegotiable.leadUnitName"; final String leadUnitNumber = "associatedNegotiable.leadUnitNumber"; final String sponsorName = "associatedNegotiable.sponsorName"; final String piName = "associatedNegotiable.piName"; final String subAwardOrganizationName = "associatedNegotiable.subAwardOrganizationName"; Collection lookupStuff = super.performLookup(lookupForm, resultTable, bounded); Iterator i = resultTable.iterator(); while (i.hasNext()) { ResultRow row = (ResultRow) i.next(); for (Column column : row.getColumns()) { //the Subaward Organization name, unit name, pi Name and sponsor name don't need to generate links. if (StringUtils.equalsIgnoreCase(column.getPropertyName(), leadUnitName) || StringUtils.equalsIgnoreCase(column.getPropertyName(), sponsorName) || StringUtils.equalsIgnoreCase(column.getPropertyName(), subAwardOrganizationName) || StringUtils.equalsIgnoreCase(column.getPropertyName(), piName)) { column.setPropertyURL(""); for (AnchorHtmlData data : column.getColumnAnchors()) { if (data != null) { data.setHref(""); } } } if (StringUtils.equalsIgnoreCase(column.getPropertyName(), leadUnitNumber)){ String unitNumber = column.getPropertyValue(); //String newUrl = "http://127.0.0.1:8080/kc-dev/kr/inquiry.do?businessObjectClassName=org.kuali.kra.bo.Unit&unitNumber=" + unitNumber + "&methodToCall=start"; String newUrl = "inquiry.do?businessObjectClassName=org.kuali.kra.bo.Unit&unitNumber=" + unitNumber + "&methodToCall=start"; column.setPropertyURL(newUrl); for (AnchorHtmlData data : column.getColumnAnchors()) { if (data != null) { data.setHref(newUrl); } } } } } return lookupStuff; } /* End IU Customization */ protected List<Long> getCustomDataIds(Map<String, String> formProps, List<Long> commonIds) { List<Long> ids = null; // UITSRA-3138 Collection<NegotiationCustomData> customDatas = getLookupService().findCollectionBySearchUnbounded(NegotiationCustomData.class, formProps); if (!customDatas.isEmpty()) { ids = new ArrayList<Long>(); for (NegotiationCustomData customData : customDatas) { ids.add(customData.getNegotiationCustomDataId()); } } if (commonIds != null && ids !=null ) { ids.retainAll(commonIds); } return ids; } }
ColostateResearchServices/kc
coeus-impl/src/main/java/org/kuali/kra/negotiations/lookup/IUNegotiationLookupableHelperServiceImpl.java
Java
agpl-3.0
19,905
using System; using System.Windows.Threading; namespace Sedentary.Framework { public static class TimerFactory { public static DispatcherTimer StartTimer(TimeSpan interval, Action tick) { var timer = new DispatcherTimer {Interval = interval}; timer.Tick += (sender, args) => tick(); timer.Start(); return timer; } } }
BorysLevytskyi/Sedentary
Sedentary/Framework/TimerFactory.cs
C#
agpl-3.0
342
package com.sapienter.jbilling.client.jspc.user; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import com.sapienter.jbilling.client.util.Constants;; public final class listSubAccountsTop_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.AnnotationProcessor _jsp_annotationprocessor; public Object getDependants() { return _jspx_dependants; } public void _jspInit() { _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName()); } public void _jspDestroy() { _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.release(); _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.release(); _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.release(); _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.release(); _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.release(); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n<p class=\"title\">\r\n"); if (_jspx_meth_bean_005fmessage_005f0(_jspx_page_context)) return; out.write("\r\n</p>\r\n<p class=\"instr\">\r\n"); if (_jspx_meth_bean_005fmessage_005f1(_jspx_page_context)) return; out.write("\r\n</p>\r\n\r\n"); // html:messages org.apache.struts.taglib.html.MessagesTag _jspx_th_html_005fmessages_005f0 = (org.apache.struts.taglib.html.MessagesTag) _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.get(org.apache.struts.taglib.html.MessagesTag.class); _jspx_th_html_005fmessages_005f0.setPageContext(_jspx_page_context); _jspx_th_html_005fmessages_005f0.setParent(null); // /user/listSubAccountsTop.jsp(36,0) name = message type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_html_005fmessages_005f0.setMessage("true"); // /user/listSubAccountsTop.jsp(36,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_html_005fmessages_005f0.setId("myMessage"); int _jspx_eval_html_005fmessages_005f0 = _jspx_th_html_005fmessages_005f0.doStartTag(); if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { java.lang.String myMessage = null; if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_html_005fmessages_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_html_005fmessages_005f0.doInitBody(); } myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage"); do { out.write("\r\n\t<p>"); if (_jspx_meth_bean_005fwrite_005f0(_jspx_th_html_005fmessages_005f0, _jspx_page_context)) return; out.write("</p>\r\n"); int evalDoAfterBody = _jspx_th_html_005fmessages_005f0.doAfterBody(); myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage"); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.popBody(); } } if (_jspx_th_html_005fmessages_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0); return; } _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0); out.write("\r\n\r\n"); out.write('\r'); out.write('\n'); // bean:define org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f0 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class); _jspx_th_bean_005fdefine_005f0.setPageContext(_jspx_page_context); _jspx_th_bean_005fdefine_005f0.setParent(null); // /user/listSubAccountsTop.jsp(42,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f0.setId("forward_from"); // /user/listSubAccountsTop.jsp(42,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f0.setValue(Constants.FORWARD_USER_MAINTAIN); // /user/listSubAccountsTop.jsp(42,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f0.setToScope("session"); int _jspx_eval_bean_005fdefine_005f0 = _jspx_th_bean_005fdefine_005f0.doStartTag(); if (_jspx_th_bean_005fdefine_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0); return; } _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0); java.lang.String forward_from = null; forward_from = (java.lang.String) _jspx_page_context.findAttribute("forward_from"); out.write("\r\n\r\n"); // bean:define org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f1 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class); _jspx_th_bean_005fdefine_005f1.setPageContext(_jspx_page_context); _jspx_th_bean_005fdefine_005f1.setParent(null); // /user/listSubAccountsTop.jsp(46,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f1.setId("forward_to"); // /user/listSubAccountsTop.jsp(46,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f1.setValue(Constants.FORWARD_USER_VIEW); // /user/listSubAccountsTop.jsp(46,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f1.setToScope("session"); int _jspx_eval_bean_005fdefine_005f1 = _jspx_th_bean_005fdefine_005f1.doStartTag(); if (_jspx_th_bean_005fdefine_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1); return; } _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1); java.lang.String forward_to = null; forward_to = (java.lang.String) _jspx_page_context.findAttribute("forward_to"); out.write("\r\n\r\n"); // jbilling:genericList com.sapienter.jbilling.client.list.GenericListTag _jspx_th_jbilling_005fgenericList_005f0 = (com.sapienter.jbilling.client.list.GenericListTag) _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.get(com.sapienter.jbilling.client.list.GenericListTag.class); _jspx_th_jbilling_005fgenericList_005f0.setPageContext(_jspx_page_context); _jspx_th_jbilling_005fgenericList_005f0.setParent(null); // /user/listSubAccountsTop.jsp(50,0) name = setup type = java.lang.Boolean reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_jbilling_005fgenericList_005f0.setSetup(new Boolean(true)); // /user/listSubAccountsTop.jsp(50,0) name = type type = java.lang.String reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_jbilling_005fgenericList_005f0.setType(Constants.LIST_TYPE_SUB_ACCOUNTS); int _jspx_eval_jbilling_005fgenericList_005f0 = _jspx_th_jbilling_005fgenericList_005f0.doStartTag(); if (_jspx_th_jbilling_005fgenericList_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0); return; } _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0); out.write('\r'); out.write('\n'); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_bean_005fmessage_005f0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // bean:message org.apache.struts.taglib.bean.MessageTag _jspx_th_bean_005fmessage_005f0 = (org.apache.struts.taglib.bean.MessageTag) _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.get(org.apache.struts.taglib.bean.MessageTag.class); _jspx_th_bean_005fmessage_005f0.setPageContext(_jspx_page_context); _jspx_th_bean_005fmessage_005f0.setParent(null); // /user/listSubAccountsTop.jsp(30,0) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fmessage_005f0.setKey("user.subaccount.title"); int _jspx_eval_bean_005fmessage_005f0 = _jspx_th_bean_005fmessage_005f0.doStartTag(); if (_jspx_th_bean_005fmessage_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_bean_005fmessage_005f0); return true; } _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_bean_005fmessage_005f0); return false; } private boolean _jspx_meth_bean_005fmessage_005f1(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // bean:message org.apache.struts.taglib.bean.MessageTag _jspx_th_bean_005fmessage_005f1 = (org.apache.struts.taglib.bean.MessageTag) _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.get(org.apache.struts.taglib.bean.MessageTag.class); _jspx_th_bean_005fmessage_005f1.setPageContext(_jspx_page_context); _jspx_th_bean_005fmessage_005f1.setParent(null); // /user/listSubAccountsTop.jsp(33,0) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fmessage_005f1.setKey("customer.list.instr"); int _jspx_eval_bean_005fmessage_005f1 = _jspx_th_bean_005fmessage_005f1.doStartTag(); if (_jspx_th_bean_005fmessage_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_bean_005fmessage_005f1); return true; } _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_bean_005fmessage_005f1); return false; } private boolean _jspx_meth_bean_005fwrite_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_005fmessages_005f0, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // bean:write org.apache.struts.taglib.bean.WriteTag _jspx_th_bean_005fwrite_005f0 = (org.apache.struts.taglib.bean.WriteTag) _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.get(org.apache.struts.taglib.bean.WriteTag.class); _jspx_th_bean_005fwrite_005f0.setPageContext(_jspx_page_context); _jspx_th_bean_005fwrite_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_005fmessages_005f0); // /user/listSubAccountsTop.jsp(37,4) name = name type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fwrite_005f0.setName("myMessage"); int _jspx_eval_bean_005fwrite_005f0 = _jspx_th_bean_005fwrite_005f0.doStartTag(); if (_jspx_th_bean_005fwrite_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0); return true; } _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0); return false; } }
othmanelmoulat/jbilling-2.2-Extentions
src/build/jsp-classes/com/sapienter/jbilling/client/jspc/user/listSubAccountsTop_jsp.java
Java
agpl-3.0
16,631
Meteor.publish('card-vocoder-vocoders',function(simulatorId){ return Flint.collection('vocoders').find({simulatorId:simulatorId}); });
infinitedg/flint
packages/card-vocoder/publish.js
JavaScript
agpl-3.0
136
/* * Aphelion * Copyright (c) 2013 Joris van der Wel * * This file is part of Aphelion * * Aphelion 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. * * Aphelion is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Aphelion. If not, see <http://www.gnu.org/licenses/>. * * In addition, the following supplemental terms apply, based on section 7 of * the GNU Affero General Public License (version 3): * a) Preservation of all legal notices and author attributions * b) Prohibition of misrepresentation of the origin of this material, and * modified versions are required to be marked in reasonable ways as * different from the original version (for example by appending a copyright notice). * * Linking this library statically or dynamically with other modules is making a * combined work based on this library. Thus, the terms and conditions of the * GNU Affero General Public License cover the whole combination. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. */ package aphelion.shared.event.promise; /** * * @author Joris */ public interface PromiseRejected { void rejected(PromiseException error); }
Periapsis/aphelion
src/main/java/aphelion/shared/event/promise/PromiseRejected.java
Java
agpl-3.0
2,044
import React from "react"; import basicComponent from "core/basicComponent"; import Radium from "radium"; import ReactAplayer from "react-aplayer"; import mergeAdvanced from "object-merge-advanced"; class audioPlayer extends basicComponent { constructor(props) { super(props); if (!this.isRestored) { this.state = { ...this.state, audios: [] }; } this.myRef = React.createRef(); } onInit = ap => { this.ap = ap; }; play = () => this.ap.play(); pause = () => this.ap.pause(); seek = timePos => this.ap.seek(timePos); addAudio(audioProps) { this.setState(prevState => { const prevAudios = prevState.audios; const nextAudios = prevAudios.concat([audioProps]); const nextState = mergeAdvanced(prevState, { audios: nextAudios }); return nextState; }); } thisComponent = () => { const state = this.getState(); const styles = this.getStyles(); return ( <ReactAplayer ref={this.myRef} theme="#F57F17" lrcType={3} audio={state.audios || []} onInit={this.onInit} style={styles} {...this.getEvents()} /> ); }; } export default Radium(audioPlayer);
project-jste/framework
src/JS/components/audioPlayer.js
JavaScript
agpl-3.0
1,207
package com.tesora.dve.sql.statement; /* * #%L * Tesora Inc. * Database Virtualization Engine * %% * Copyright (C) 2011 - 2014 Tesora Inc. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ import com.tesora.dve.lockmanager.LockType; import com.tesora.dve.sql.expression.TableKey; import com.tesora.dve.sql.util.ListSet; public interface CacheableStatement { public LockType getLockType(); public ListSet<TableKey> getAllTableKeys(); }
Tesora/tesora-dve-pub
tesora-dve-core/src/main/java/com/tesora/dve/sql/statement/CacheableStatement.java
Java
agpl-3.0
1,022
import { expect, fixture, fixtureCleanup, fixtureSync } from '@open-wc/testing'; import sinon from 'sinon'; import volumesProvider from '../../../../src/BookNavigator/volumes/volumes-provider'; const brOptions = { "options": { "enableMultipleBooks": true, "multipleBooksList": { "by_subprefix": { "/details/SubBookTest": { "url_path": "/details/SubBookTest", "file_subprefix": "book1/GPORFP", "orig_sort": 1, "title": "book1/GPORFP.pdf", "file_source": "/book1/GPORFP_jp2.zip" }, "/details/SubBookTest/subdir/book2/brewster_kahle_internet_archive": { "url_path": "/details/SubBookTest/subdir/book2/brewster_kahle_internet_archive", "file_subprefix": "subdir/book2/brewster_kahle_internet_archive", "orig_sort": 2, "title": "subdir/book2/brewster_kahle_internet_archive.pdf", "file_source": "/subdir/book2/brewster_kahle_internet_archive_jp2.zip" }, "/details/SubBookTest/subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume": { "url_path": "/details/SubBookTest/subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume", "file_subprefix": "subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume", "orig_sort": 3, "title": "subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume.pdf", "file_source": "/subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume_jp2.zip" } } } } }; afterEach(() => { sinon.restore(); fixtureCleanup(); }); describe('Volumes Provider', () => { it('constructor', () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); const files = brOptions.options.multipleBooksList.by_subprefix; const volumeCount = Object.keys(files).length; expect(provider.onProviderChange).to.equal(onProviderChange); expect(provider.id).to.equal('volumes'); expect(provider.icon).to.exist; expect(fixtureSync(provider.icon).tagName).to.equal('svg'); expect(provider.label).to.equal(`Viewable files (${volumeCount})`); expect(provider.viewableFiles).to.exist; expect(provider.viewableFiles.length).to.equal(3); expect(provider.component.hostUrl).to.exist; expect(provider.component.hostUrl).to.equal(baseHost); expect(provider.component).to.exist; }); it('sorting cycles - render sort actionButton', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); expect(provider.sortOrderBy).to.equal("default"); provider.sortVolumes("title_asc"); expect(provider.sortOrderBy).to.equal("title_asc"); expect(fixtureSync(provider.sortButton).outerHTML).includes("sort-by asc-icon"); provider.sortVolumes("title_desc"); expect(provider.sortOrderBy).to.equal("title_desc"); expect(fixtureSync(provider.sortButton).outerHTML).includes("sort-by desc-icon"); provider.sortVolumes("default"); expect(provider.sortOrderBy).to.equal("default"); expect(fixtureSync(provider.sortButton).outerHTML).includes("sort-by neutral-icon"); }); it('sort volumes in initial order', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); const parsedFiles = brOptions.options.multipleBooksList.by_subprefix; const files = Object.keys(parsedFiles).map(item => parsedFiles[item]).sort((a, b) => a.orig_sort - b.orig_sort); const origSortTitles = files.map(item => item.title); provider.sortVolumes("default"); expect(provider.sortOrderBy).to.equal("default"); expect(provider.actionButton).to.exist; const providerFileTitles = provider.viewableFiles.map(item => item.title); // use `.eql` for "lose equality" in order to deeply compare values. expect(providerFileTitles).to.eql([...origSortTitles]); }); it('sort volumes in ascending title order', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); const parsedFiles = brOptions.options.multipleBooksList.by_subprefix; const files = Object.keys(parsedFiles).map(item => parsedFiles[item]); const ascendingTitles = files.map(item => item.title).sort((a, b) => a.localeCompare(b)); provider.sortVolumes("title_asc"); expect(provider.sortOrderBy).to.equal("title_asc"); expect(provider.actionButton).to.exist; const providerFileTitles = provider.viewableFiles.map(item => item.title); // use `.eql` for "lose equality" in order to deeply compare values. expect(providerFileTitles).to.eql([...ascendingTitles]); }); it('sort volumes in descending title order', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); provider.isSortAscending = false; const parsedFiles = brOptions.options.multipleBooksList.by_subprefix; const files = Object.keys(parsedFiles).map(item => parsedFiles[item]); const descendingTitles = files.map(item => item.title).sort((a, b) => b.localeCompare(a)); provider.sortVolumes("title_desc"); expect(provider.sortOrderBy).to.equals("title_desc"); expect(provider.actionButton).to.exist; const providerFileTitles = provider.viewableFiles.map(item => item.title); // use `.eql` for "lose equality" in order to deeply compare values. expect(providerFileTitles).to.eql([...descendingTitles]); }); describe('Sorting icons', () => { it('has 3 icons', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); provider.sortOrderBy = 'default'; const origSortButton = await fixture(provider.sortButton); expect(origSortButton.classList.contains('neutral-icon')).to.be.true; provider.sortOrderBy = 'title_asc'; const ascButton = await fixture(provider.sortButton); expect(ascButton.classList.contains('asc-icon')).to.be.true; provider.sortOrderBy = 'title_desc'; const descButton = await fixture(provider.sortButton); expect(descButton.classList.contains('desc-icon')).to.be.true; }); }); });
internetarchive/bookreader
tests/karma/BookNavigator/volumes/volumes-provider.test.js
JavaScript
agpl-3.0
6,945
from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs)
flowersteam/naminggamesal
naminggamesal/ngstrat/word_choice/word_preference.py
Python
agpl-3.0
997
describe('Service: can', function () { var api beforeEach(angular.mock.inject(function (can) { api = can })) describe('.can()', function () { it('returns true when the resource includes a method', function () { var project = { '_links': { repositories: { update: 'PUT' } } } expect(api.can('update-repositories', project)).toBeTruthy() }) it('returns false when resource excludes method', function () { var project = { '_links': { repositories: {} } } expect(api.can('update-repositories', project)).toBeFalsy() }) it('returns false otherwise', function () { expect(api.can('update-repositories', {})).toBeFalsy() }) }) })
harrowio/harrow
frontend/test/spec/service/can_test.js
JavaScript
agpl-3.0
779
/** * Copyright (C) 2001-2019 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.viewer; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextPane; import com.rapidminer.datatable.SimpleDataTable; import com.rapidminer.datatable.SimpleDataTableRow; import com.rapidminer.gui.actions.export.PrintableComponent; import com.rapidminer.gui.look.Colors; import com.rapidminer.gui.plotter.PlotterConfigurationModel; import com.rapidminer.gui.tools.ExtendedJScrollPane; import com.rapidminer.report.Tableable; import com.rapidminer.tools.I18N; /** * This viewer class can be used to display performance criteria based on a multi class confusion * matrix. The viewer consists of two parts, first a part containing the general performance info * string and second a table with the complete confusion matrix. * * @author Ingo Mierswa */ public class ConfusionMatrixViewer extends JPanel implements Tableable, PrintableComponent { private static final long serialVersionUID = 3448880915145528006L; private ConfusionMatrixViewerTable table; private JComponent plotter; private String performanceName; public ConfusionMatrixViewer(String performanceName, String performanceString, String[] classNames, double[][] counter) { this.performanceName = performanceName; setLayout(new BorderLayout()); final JPanel mainPanel = new JPanel(); mainPanel.setOpaque(true); mainPanel.setBackground(Colors.WHITE); final CardLayout cardLayout = new CardLayout(); mainPanel.setLayout(cardLayout); add(mainPanel, BorderLayout.CENTER); // *** table panel *** JPanel tablePanel = new JPanel(new BorderLayout()); tablePanel.setOpaque(true); tablePanel.setBackground(Colors.WHITE); tablePanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10)); // info string JPanel infoPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); infoPanel.setOpaque(true); infoPanel.setBackground(Colors.WHITE); JTextPane infoText = new JTextPane(); infoText.setEditable(false); infoText.setBackground(infoPanel.getBackground()); infoText.setFont(infoText.getFont().deriveFont(Font.BOLD)); infoText.setText(performanceString); infoPanel.add(infoText); tablePanel.add(infoPanel, BorderLayout.NORTH); // table table = new ConfusionMatrixViewerTable(classNames, counter); table.setBorder(BorderFactory.createLineBorder(Colors.TABLE_CELL_BORDER)); JScrollPane scrollPane = new ExtendedJScrollPane(table); scrollPane.setBorder(null); scrollPane.setBackground(Colors.WHITE); scrollPane.getViewport().setBackground(Colors.WHITE); tablePanel.add(scrollPane, BorderLayout.CENTER); table.setTableHeader(null); // *** plot panel *** SimpleDataTable dataTable = new SimpleDataTable("Confusion Matrix", new String[] { "True Class", "Predicted Class", "Confusion Matrix (x: true class, y: pred. class, z: counters)" }); for (int row = 0; row < classNames.length; row++) { for (int column = 0; column < classNames.length; column++) { dataTable.add(new SimpleDataTableRow(new double[] { row, column, counter[row][column] })); } } PlotterConfigurationModel settings = new PlotterConfigurationModel(PlotterConfigurationModel.STICK_CHART_3D, dataTable); settings.setAxis(0, 0); settings.setAxis(1, 1); settings.enablePlotColumn(2); mainPanel.add(tablePanel, "table"); plotter = settings.getPlotter().getPlotter(); mainPanel.add(plotter, "plot"); // toggle radio button for views final JRadioButton metaDataButton = new JRadioButton("Table View", true); metaDataButton.setToolTipText("Changes to a table showing the confusion matrix."); metaDataButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (metaDataButton.isSelected()) { cardLayout.show(mainPanel, "table"); } } }); final JRadioButton plotButton = new JRadioButton("Plot View", false); plotButton.setToolTipText("Changes to a plot view of the confusion matrix."); plotButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (plotButton.isSelected()) { cardLayout.show(mainPanel, "plot"); } } }); ButtonGroup group = new ButtonGroup(); group.add(metaDataButton); group.add(plotButton); JPanel togglePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); togglePanel.setOpaque(true); togglePanel.setBackground(Colors.WHITE); togglePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0)); togglePanel.add(metaDataButton); togglePanel.add(plotButton); add(togglePanel, BorderLayout.NORTH); } @Override public void prepareReporting() { table.prepareReporting(); } @Override public void finishReporting() { table.finishReporting(); } @Override public boolean isFirstLineHeader() { return true; } @Override public boolean isFirstColumnHeader() { return true; } @Override public String getColumnName(int columnIndex) { return table.getColumnName(columnIndex); } @Override public String getCell(int row, int column) { return table.getCell(row, column); } @Override public int getColumnNumber() { return table.getColumnNumber(); } @Override public int getRowNumber() { return table.getRowNumber(); } @Override public Component getExportComponent() { return plotter; } @Override public String getExportName() { return I18N.getGUIMessage("gui.cards.result_view.confusion_matrix.title"); } @Override public String getIdentifier() { return performanceName; } @Override public String getExportIconName() { return I18N.getGUIMessage("gui.cards.result_view.confusion_matrix.icon"); } }
aborg0/rapidminer-studio
src/main/java/com/rapidminer/gui/viewer/ConfusionMatrixViewer.java
Java
agpl-3.0
7,016
package android.support.v7.a; final class ad implements Runnable { final /* synthetic */ ac a; ad(ac acVar) { this.a = acVar; } public final void run() { if ((this.a.I & 1) != 0) { ac.a(this.a, 0); } if ((this.a.I & 4096) != 0) { ac.a(this.a, 108); } this.a.H = false; this.a.I = 0; } }
WenbinHou/PKUAutoGateway.Android
Reference/IPGWAndroid/android/support/v7/a/ad.java
Java
agpl-3.0
390
/** * 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 cn.dlb.bim.models.ifc4.impl; import org.eclipse.emf.ecore.EClass; import cn.dlb.bim.models.ifc4.Ifc4Package; import cn.dlb.bim.models.ifc4.IfcSlabType; import cn.dlb.bim.models.ifc4.IfcSlabTypeEnum; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Slab Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc4.impl.IfcSlabTypeImpl#getPredefinedType <em>Predefined Type</em>}</li> * </ul> * * @generated */ public class IfcSlabTypeImpl extends IfcBuildingElementTypeImpl implements IfcSlabType { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcSlabTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc4Package.Literals.IFC_SLAB_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IfcSlabTypeEnum getPredefinedType() { return (IfcSlabTypeEnum) eGet(Ifc4Package.Literals.IFC_SLAB_TYPE__PREDEFINED_TYPE, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPredefinedType(IfcSlabTypeEnum newPredefinedType) { eSet(Ifc4Package.Literals.IFC_SLAB_TYPE__PREDEFINED_TYPE, newPredefinedType); } } //IfcSlabTypeImpl
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc4/impl/IfcSlabTypeImpl.java
Java
agpl-3.0
2,127
/* * Copyright 2015 Westfälische Hochschule * * This file is part of Poodle. * * Poodle is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Poodle is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Poodle. If not, see <http://www.gnu.org/licenses/>. */ /* * This code is mostly responsible for creating the * diagrams with the Google Charts API. * * The server sends us the statistics as a 2 dimensional JSON array. * This way we can directly use it with Google's dataTable.addRows() * function. All diagrams are created from this table. * * Column 0: completion status (partly, not at all...) * Column 1: Difficulty * Column 2: Fun * Column 3: Time * * The difficulty, fun and completion status diagrams are Column Charts, * the time diagrams is a Histogram. * * https://developers.google.com/chart/ * https://developers.google.com/chart/interactive/docs/gallery/columnchart * https://developers.google.com/chart/interactive/docs/gallery/histogram */ $(document).ready(function() { /* global exercise */ /* global messages */ "use strict"; /* Minimum amount of data we need to create a diagram. * If we have less than this, the diagram is not rendered and * the tab is disabled. */ var MIN_DATA_COUNT = 2; // global options for all diagrams var OPTIONS_ALL = { backgroundColor: "transparent", legend: { position: "none" }, hAxis: { titleTextStyle: { bold: true, italic: false } }, vAxis: { titleTextStyle: { bold: true, italic: false }, title: messages.count, minValue: 0 } }; var $chartsTabs = $("#chartsTabs"); function loadChartData() { $.ajax({ url: window.location.pathname + "/chartData", type: "GET", success: onChartDataLoaded }); } function onChartDataLoaded(data) { // create dataTable var dataTable = new google.visualization.DataTable(); dataTable.addColumn("string", messages.completed); dataTable.addColumn("number", messages.difficulty); dataTable.addColumn("number", messages.fun); dataTable.addColumn("number", messages.time); dataTable.addRows(data); /* Create all charts. * We are doing this _before_ creating the tabs on purpose, * since the API is not able to render into a hidden * div i.e. inactice tab. * * Every draw function returns whether the diagram was created or * not (MIN_DATA_COUNT). If not, we disable the tab on this index. */ var disabledTabs = []; if (!drawDifficultyChart(dataTable)) disabledTabs.push(0); if (!drawTimeChart(dataTable)) disabledTabs.push(1); if (!drawFunChart(dataTable)) disabledTabs.push(2); if (!drawCompletedChart(dataTable)) disabledTabs.push(3); if ($("#textList > li").length === 0) disabledTabs.push(4); var tabCount = $chartsTabs.find("#tabList > li").length; // all tabs disabled, hide them and abort if (disabledTabs.length === tabCount) { $chartsTabs.hide(); return; } // get index of the first tab that is not disabled var activeTab = 0; for (var i = 0; i < tabCount; i++) { if ($.inArray(i, disabledTabs) === -1) { activeTab = i; break; } } // generate tabs $chartsTabs.tabs({ disabled: disabledTabs, active: activeTab }); } function drawDifficultyChart(dataTable) { var $difficultyChart =$("#difficultyChart"); var avgDifficulty = $difficultyChart.data("avg"); var difficultyOptions = $.extend(true, {}, OPTIONS_ALL, { hAxis: { title: messages.difficultyTitle.format(avgDifficulty) } }); var counts = new google.visualization.DataTable(); // this column must be of type string. Otherwise not all values are displayed on the x axis. counts.addColumn("string", messages.difficulty); counts.addColumn("number", messages.count); var dataCount = 0; for (var difficulty = 1; difficulty <= 10; difficulty++) { var count = dataTable.getFilteredRows([{column: 1, value: difficulty}]).length; counts.addRow([difficulty.toString(), count]); dataCount += count; } if (dataCount < MIN_DATA_COUNT) return false; var chart = new google.visualization.ColumnChart($difficultyChart.get(0)); chart.draw(counts, difficultyOptions); return true; } function drawTimeChart(dataTable) { var $timeChart = $("#timeChart"); var avgTime = $timeChart.data("avg"); var view = new google.visualization.DataView(dataTable); view.setRows(view.getFilteredRows( [{ column: 3, // only columns with time >= 1 minValue: 1 }]) ); view.setColumns([3]); // only time column if (view.getNumberOfRows() < MIN_DATA_COUNT) return false; var timeOptions = $.extend(true, {}, OPTIONS_ALL, { hAxis: { title: messages.timeTitle.format(avgTime) } }); var chart = new google.visualization.Histogram($timeChart.get(0)); chart.draw(view, timeOptions); return true; } function drawFunChart(dataTable) { var $funChart = $("#funChart"); var avgFun = $funChart.data("avg"); var funOptions = $.extend(true, {}, OPTIONS_ALL, { hAxis: { title: messages.funTitle.format(avgFun) } }); var counts = new google.visualization.DataTable(); // this column must be of type string. Otherwise not all values are displayed on the x axis. counts.addColumn("string", messages.fun); counts.addColumn("number", messages.count); var dataCount = 0; for (var fun = 1; fun <= 10; fun++) { var count = dataTable.getFilteredRows([{column: 2, value: fun}]).length; counts.addRow([fun.toString(), count]); dataCount += count; } if (dataCount < MIN_DATA_COUNT) return false; var chart = new google.visualization.ColumnChart($funChart.get(0)); chart.draw(counts, funOptions); return true; } function drawCompletedChart(dataTable) { var counts = new google.visualization.DataTable(); counts.addColumn("string", messages.completed); counts.addColumn("number", messages.count); var dataCount = 0; /* messages.completedStatus contains the Java enum values (which are also * in the dataTable) as the keys and the localized description as the values. * Iterate over the keys and add a row for each. */ var completedStatus = messages.completedStatus; for (var s in completedStatus) { var count = dataTable.getFilteredRows([{column: 0, value: s}]).length; counts.addRow([completedStatus[s], count]); dataCount += count; } if (dataCount < MIN_DATA_COUNT) return false; var completedOptions = $.extend(true, {}, OPTIONS_ALL, { hAxis: { title: messages.completed } }); var chart = new google.visualization.ColumnChart(document.getElementById("completedChart")); chart.draw(counts, completedOptions); return true; } // confirm exercise deletion $("#deleteForm").submit(function() { return exercise.confirmDelete(); }); /* * Load diagram, if statistics exist. * (#chartsTabs doesn't exist if the statistics are empty). */ if ($chartsTabs.length > 0) { google.load( "visualization", "1.0", { callback: loadChartData, packages: ["corechart"] } ); } // initialize DataTables for feedback table $("#feedbackTable").DataTable({ "order": [[ 1, "desc" ]] // date descending }); });
whs-poodle/poodle
src/main/resources/static/js/instructor/exercise.js
JavaScript
agpl-3.0
7,646
/*############################################################################## Copyright (C) 2011 HPCC Systems. 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/>. ############################################################################## */ #ifndef _ESPWIZ_WsDeploy_HPP__ #define _ESPWIZ_WsDeploy_HPP__ #include "WsDeploy_esp.ipp" #include "environment.hpp" #include "jmutex.hpp" #include "dasds.hpp" #include "deployutils.hpp" #include "buildset.hpp" #include "jsocket.hpp" #include "XMLTags.h" #include "httpclient.hpp" typedef enum EnvAction_ { CLOUD_NONE, CLOUD_LOCK_ENV, CLOUD_UNLOCK_ENV, CLOUD_SAVE_ENV, CLOUD_ROLLBACK_ENV, CLOUD_NOTIFY_INITSYSTEM, CLOUD_CHECK_LOCKER } EnvAction; #define CLOUD_SOAPCALL_TIMEOUT 10000 class CCloudTask; class CCloudActionHandler; class CWsDeployEx; class CWsDeployExCE; class CWsDeployFileInfo : public CInterface, implements IInterface { private: //========================================================================================== // the following class implements notification handler for subscription to dali for environment // updates by other clients. //========================================================================================== class CSdsSubscription : public CInterface, implements ISDSSubscription { public: CSdsSubscription(CWsDeployFileInfo* pFileInfo) { m_pFileInfo.set(pFileInfo); sub_id = querySDS().subscribe("/Environment", *this); } virtual ~CSdsSubscription() { unsubscribe(); } void unsubscribe() { if (sub_id) { if (sub_id) { querySDS().unsubscribe(sub_id); sub_id = 0; } } } IMPLEMENT_IINTERFACE; //another client (like configenv) may have updated the environment and we got notified //(thanks to our subscription) but don't just reload it yet since this notification is sent on //another thread asynchronously and we may be actively working with the old environment. Just //invoke handleEnvironmentChange() when we are ready to invalidate cache in environment factory. // void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen=0, const void *valueData=NULL); private: SubscriptionId sub_id; Owned<CWsDeployFileInfo> m_pFileInfo; }; //========================================================================================== // the following class generates JavaScript files required by the service gui, at startup or // whenever the environment is updated. //========================================================================================== class CGenerateJSFactoryThread : public CInterface, implements IThreaded, implements IInterface { public: CGenerateJSFactoryThread(CWsDeployExCE* pService,IConstEnvironment* pConstEnv) { m_pService.set(pService); m_pWorkerThread = NULL; m_constEnv.set(pConstEnv); } virtual ~CGenerateJSFactoryThread() { bool joinedOk = m_pWorkerThread->join(); if(NULL != m_pWorkerThread) { delete m_pWorkerThread; m_pWorkerThread = NULL; } } IMPLEMENT_IINTERFACE; virtual void main() { generateHeaders(&m_constEnv->getPTree(), m_constEnv); } void init() { m_pWorkerThread = new CThreaded("CGenerateJSFactoryThread"); IThreaded* pIThreaded = this; m_pWorkerThread->init(pIThreaded); } void refresh(IConstEnvironment* pConstEnv) { m_constEnv.set(pConstEnv); } private: CThreaded* m_pWorkerThread; Linked<CWsDeployExCE> m_pService; Linked<IConstEnvironment> m_constEnv; }; class CClientAliveThread : public CInterface, implements IThreaded, implements IInterface { public: CClientAliveThread(CWsDeployFileInfo* pFileInfo, unsigned brokenConnTimeout) { m_pFileInfo = pFileInfo; m_pWorkerThread = NULL; m_quitThread = false; m_brokenConnTimeout = brokenConnTimeout; } virtual ~CClientAliveThread() { m_quitThread = true; m_sem.signal(); bool joinedOk = m_pWorkerThread->join(); m_pFileInfo = NULL; if(NULL != m_pWorkerThread) { delete m_pWorkerThread; m_pWorkerThread = NULL; } } IMPLEMENT_IINTERFACE; virtual void main() { while (!m_quitThread) { if (!m_sem.wait(m_brokenConnTimeout)) { if (m_pFileInfo) m_pFileInfo->activeUserNotResponding(); break; } } } void init() { m_quitThread = false; m_pWorkerThread = new CThreaded("CClientAliveThread"); IThreaded* pIThreaded = this; m_pWorkerThread->init(pIThreaded); } void signal() { m_sem.signal(); } private: CThreaded* m_pWorkerThread; CWsDeployFileInfo* m_pFileInfo; Semaphore m_sem; bool m_quitThread; unsigned m_brokenConnTimeout; }; class CLockerAliveThread : public CInterface, implements IThreaded, implements IInterface { public: CLockerAliveThread(CWsDeployFileInfo* pFileInfo, unsigned brokenConnTimeout, const char* uname, const char* ip) { m_pFileInfo = pFileInfo; m_pWorkerThread = NULL; m_quitThread = false; m_brokenConnTimeout = brokenConnTimeout; StringBuffer sb; sb.appendf("<Computers><Computer netAddress='%s'/></Computers>", ip); m_pComputers.setown(createPTreeFromXMLString(sb.str())); m_user.clear().append(uname); } virtual ~CLockerAliveThread() { m_quitThread = true; m_sem.signal(); bool joinedOk = m_pWorkerThread->join(); m_pFileInfo = NULL; if(NULL != m_pWorkerThread) { delete m_pWorkerThread; m_pWorkerThread = NULL; } } IMPLEMENT_IINTERFACE; virtual void main(); void init() { m_quitThread = false; m_pWorkerThread = new CThreaded("CLockerAliveThread"); IThreaded* pIThreaded = this; m_pWorkerThread->init(pIThreaded); } void signal() { m_quitThread = true; m_sem.signal(); } private: CThreaded* m_pWorkerThread; CWsDeployFileInfo* m_pFileInfo; bool m_quitThread; unsigned m_brokenConnTimeout; Owned<IPropertyTree> m_pComputers; StringBuffer m_user; Semaphore m_sem; }; public: IMPLEMENT_IINTERFACE; CWsDeployFileInfo(CWsDeployExCE* pService, const char* pEnvFile, bool bCloud):m_pService(pService),m_bCloud(bCloud) { m_envFile.clear().append(pEnvFile); } ~CWsDeployFileInfo(); void initFileInfo(bool createFile); virtual bool deploy(IEspContext &context, IEspDeployRequest &req, IEspDeployResponse &resp); virtual bool graph(IEspContext &context, IEspEmptyRequest& req, IEspGraphResponse& resp); virtual bool navMenuEvent(IEspContext &context, IEspNavMenuEventRequest &req, IEspNavMenuEventResponse &resp); virtual bool displaySettings(IEspContext &context, IEspDisplaySettingsRequest &req, IEspDisplaySettingsResponse &resp); virtual bool saveSetting(IEspContext &context, IEspSaveSettingRequest &req, IEspSaveSettingResponse &resp); virtual bool getBuildSetInfo(IEspContext &context, IEspGetBuildSetInfoRequest &req, IEspGetBuildSetInfoResponse &resp); virtual bool getDeployableComps(IEspContext &context, IEspGetDeployableCompsRequest &req, IEspGetDeployableCompsResponse &resp); virtual bool startDeployment(IEspContext &context, IEspStartDeploymentRequest &req, IEspStartDeploymentResponse &resp); virtual bool getBuildServerDirs(IEspContext &context, IEspGetBuildServerDirsRequest &req, IEspGetBuildServerDirsResponse &resp); virtual bool importBuild(IEspContext &context, IEspImportBuildRequest &req, IEspImportBuildResponse &resp); virtual bool getComputersForRoxie(IEspContext &context, IEspGetComputersForRoxieRequest &req, IEspGetComputersForRoxieResponse &resp); virtual bool handleRoxieOperation(IEspContext &context, IEspHandleRoxieOperationRequest &req, IEspHandleRoxieOperationResponse &resp); virtual bool handleThorTopology(IEspContext &context, IEspHandleThorTopologyRequest &req, IEspHandleThorTopologyResponse &resp); virtual bool handleComponent(IEspContext &context, IEspHandleComponentRequest &req, IEspHandleComponentResponse &resp); virtual bool handleInstance(IEspContext &context, IEspHandleInstanceRequest &req, IEspHandleInstanceResponse &resp); virtual bool handleEspServiceBindings(IEspContext &context, IEspHandleEspServiceBindingsRequest &req, IEspHandleEspServiceBindingsResponse &resp); virtual bool handleComputer(IEspContext &context, IEspHandleComputerRequest &req, IEspHandleComputerResponse &resp); virtual bool handleTopology(IEspContext &context, IEspHandleTopologyRequest &req, IEspHandleTopologyResponse &resp); virtual bool handleRows(IEspContext &context, IEspHandleRowsRequest &req, IEspHandleRowsResponse &resp); virtual bool getNavTreeDefn(IEspContext &context, IEspGetNavTreeDefnRequest &req, IEspGetNavTreeDefnResponse &resp); virtual bool getValue(IEspContext &context, IEspGetValueRequest &req, IEspGetValueResponse &resp); virtual bool unlockUser(IEspContext &context, IEspUnlockUserRequest &req, IEspUnlockUserResponse &resp); virtual bool clientAlive(IEspContext &context, IEspClientAliveRequest &req, IEspClientAliveResponse &resp); virtual bool getEnvironment(IEspContext &context, IEspGetEnvironmentRequest &req, IEspGetEnvironmentResponse &resp); virtual bool setEnvironment(IEspContext &context, IEspSetEnvironmentRequest &req, IEspSetEnvironmentResponse &resp); virtual bool lockEnvironmentForCloud(IEspContext &context, IEspLockEnvironmentForCloudRequest &req, IEspLockEnvironmentForCloudResponse &resp); virtual bool unlockEnvironmentForCloud(IEspContext &context, IEspUnlockEnvironmentForCloudRequest &req, IEspUnlockEnvironmentForCloudResponse &resp); virtual bool buildEnvironment(IEspContext &context, IEspBuildEnvironmentRequest &req, IEspBuildEnvironmentResponse &resp); virtual bool getSubnetIPAddr(IEspContext &context, IEspGetSubnetIPAddrRequest &req, IEspGetSubnetIPAddrResponse &resp); virtual bool saveEnvironmentForCloud(IEspContext &context, IEspSaveEnvironmentForCloudRequest &req, IEspSaveEnvironmentForCloudResponse &resp); virtual bool rollbackEnvironmentForCloud(IEspContext &context, IEspRollbackEnvironmentForCloudRequest &req, IEspRollbackEnvironmentForCloudResponse &resp); virtual bool notifyInitSystemSaveEnvForCloud(IEspContext &context, IEspNotifyInitSystemSaveEnvForCloudRequest &req, IEspNotifyInitSystemSaveEnvForCloudResponse &resp); virtual bool getSummary(IEspContext &context, IEspGetSummaryRequest &req, IEspGetSummaryResponse &resp); void environmentUpdated() { if (m_skipEnvUpdateFromNotification) return; synchronized block(m_mutex); m_pEnvXml.clear(); m_pGraphXml.clear(); m_pNavTree.clear(); Owned<IEnvironmentFactory> factory = getEnvironmentFactory(); m_constEnvRdOnly.set(factory->openEnvironment()); m_constEnvRdOnly->clearCache(); } void getNavigationData(IEspContext &context, IPropertyTree* pData); IPropertyTree* queryComputersForCloud(); bool getUserWithLock(StringBuffer& sbUser, StringBuffer& sbIp); bool updateEnvironment(const char* xml); bool isLocked(StringBuffer& sbUser, StringBuffer& ip); void getLastSaved(StringBuffer& sb) { m_lastSaved.getString(sb);} private: void generateGraph(IEspContext &context, IConstWsDeployReqInfo *reqInfo); void addDeployableComponentAndInstances( IPropertyTree* pEnvRoot, IPropertyTree* pComp, IPropertyTree* pDst, IPropertyTree* pFolder, const char* displayType); IPropertyTree* findComponentForFolder(IPropertyTree* pFolder, IPropertyTree* pEnvSoftware); const char* GetDisplayProcessName(const char* processName, char* buf) const; void addInstance( IPropertyTree* pDst, const char* comp, const char* displayType, const char* compName, const char* build, const char* instType, const char* instName, const char* computer); void checkForRefresh(IEspContext &context, IConstWsDeployReqInfo *reqInfo, bool checkWriteAccess); IPropertyTree* getEnvTree(IEspContext &context, IConstWsDeployReqInfo *reqInfo); void activeUserNotResponding(); void saveEnvironment(IEspContext* pContext, IConstWsDeployReqInfo *reqInfo, bool saveAs = false); void unlockEnvironment(IEspContext* pContext, IConstWsDeployReqInfo *reqInfo, const char* xmlarg, StringBuffer& sbMsg, bool saveEnv = false); void setEnvironment(IEspContext &context, IConstWsDeployReqInfo *reqInfo, const char* newEnv, const char* fnName, StringBuffer& sbBackup, bool validate = true, bool updateDali = true); Owned<CSdsSubscription> m_pSubscription; Owned<IConstEnvironment> m_constEnvRdOnly; Owned<SCMStringBuffer> m_pEnvXml; Owned<IPropertyTree> m_pNavTree; Owned<SCMStringBuffer> m_pGraphXml; Mutex m_mutex; Owned<IEnvironment> m_Environment; StringBuffer m_userWithLock; StringBuffer m_userIp; StringBuffer m_daliServer; StringBuffer m_envFile; StringBuffer m_cloudEnvBkupFileName; StringBuffer m_cloudEnvId; short m_daliServerPort; Owned<CGenerateJSFactoryThread> m_pGenJSFactoryThread; bool m_skipEnvUpdateFromNotification; bool m_activeUserNotResp; bool m_bCloud; Owned<IFile> m_pFile; Owned<IFileIO> m_pFileIO; MapStringToMyClass<CClientAliveThread> m_keepAliveHTable; CDateTime m_lastSaved; Owned<CLockerAliveThread> m_cloudLockerAliveThread; Owned<IPropertyTree> m_lockedNodesBeforeEnv; CWsDeployExCE* m_pService; }; class CCloudTaskThread : public CInterface, implements IPooledThread { public: IMPLEMENT_IINTERFACE; CCloudTaskThread() { } virtual ~CCloudTaskThread() { } void init(void *startInfo) { m_pTask.set((CCloudTask*)startInfo); } void main(); bool canReuse() { return true; } bool stop() { return true; } virtual bool getAbort() const { return s_abort; } virtual void setAbort(bool bAbort) { s_abort = bAbort; } private: Owned<CCloudTask> m_pTask; static bool s_abort; }; class CCloudTaskThreadFactory : public CInterface, public IThreadFactory { public: IMPLEMENT_IINTERFACE; IPooledThread *createNew() { return new CCloudTaskThread(); } }; CCloudTask* createCloudTask(CCloudActionHandler* pHandler, EnvAction eA, const char* ip); void expandRange(IPropertyTree* pComputers); const char* getFnString(EnvAction ea); class CCloudActionHandler : public CInterface, implements IInterface { public: CCloudActionHandler(CWsDeployFileInfo* pFileInfo, EnvAction eA, EnvAction cancelEA, const char* user, const char* port, IPropertyTree* pComputers) { m_pFileInfo = pFileInfo; m_opFailed = false; m_eA = eA; m_cancelEA = cancelEA; m_port.append(port); m_user.append(user); m_pComputers = pComputers; } virtual ~CCloudActionHandler() { m_pFileInfo = NULL; } void setSaveActionParams(const char* newEnv, const char* id) { m_newEnv.clear().append(newEnv); m_newEnvId.clear().append(id); } void setFailed(bool flag){m_opFailed = flag;} IMPLEMENT_IINTERFACE; bool start(StringBuffer& msg) { try { IPropertyTree* pComputers = m_pComputers; if (!m_pComputers) pComputers = m_pFileInfo->queryComputersForCloud(); else if (pComputers && pComputers->hasProp("@hasRange")) expandRange(pComputers); if (!pComputers) throw MakeStringException(-1, "No computers found for Cloud Operation %s", getFnString(m_eA)); if (m_threadPool == NULL) { IThreadFactory* pThreadFactory = new CCloudTaskThreadFactory(); m_threadPool.setown(createThreadPool("WsDeploy Cloud Task Thread Pool", pThreadFactory, NULL, pComputers->numChildren())); pThreadFactory->Release(); } else { int nThreads = m_threadPool->runningCount(); if (nThreads > 0) throw MakeOsException(-1, "Unfinished threads detected!"); } Owned<IPropertyTreeIterator> iter = pComputers->getElements(XML_TAG_COMPUTER); StringBuffer localip; queryHostIP().getIpText(localip); ForEach(*iter) { IPropertyTree* pComputer = &iter->query(); const char* netAddr = pComputer->queryProp(XML_ATTR_NETADDRESS); if (!strcmp(netAddr, ".") || !strcmp(netAddr, "127.0.0.1") || !strcmp(netAddr, "0.0.0.0") || !strcmp(netAddr, localip.str())) continue; else { Owned<CCloudTask> task = createCloudTask(this, m_eA, netAddr); m_threadPool->start(task);//start a thread for this task } } m_threadPool->joinAll(); if (!m_opFailed && m_eA == CLOUD_SAVE_ENV) { ForEach(*iter) { IPropertyTree* pComputer = &iter->query(); const char* netAddr = pComputer->queryProp(XML_ATTR_NETADDRESS); if (!strcmp(netAddr, ".") || !strcmp(netAddr, "127.0.0.1") || !strcmp(netAddr, "0.0.0.0") || !strcmp(netAddr, localip.str())) continue; else { Owned<CCloudTask> task = createCloudTask(this, CLOUD_NOTIFY_INITSYSTEM, netAddr); m_threadPool->start(task);//start a thread for this task } } m_threadPool->joinAll(); } if (m_opFailed) { HashIterator iterHash(m_resultMap); ForEach(iterHash) { const char* key = (const char*)iterHash.query().getKey(); String str((m_resultMap.mapToValue(&iterHash.query()))->str()); if (str.startsWith("SOAP Connection error")) msg.appendf("\nIpAddress: %s\nResult:%s\n", key, "SOAP Connection error - Could not connect to the target"); else msg.appendf("\nIpAddress: %s\nResult:%s\n", key, str.toCharArray()); } //Perform the appropriate cancel action if (m_cancelEA != CLOUD_NONE) { ForEach(*iter) { IPropertyTree* pComputer = &iter->query(); const char* netAddr = pComputer->queryProp(XML_ATTR_NETADDRESS); if (!strcmp(netAddr, ".") || !strcmp(netAddr, "127.0.0.1") || !strcmp(netAddr, "0.0.0.0") || !strcmp(netAddr, localip.str())) continue; else { Owned<CCloudTask> task = createCloudTask(this, m_cancelEA, netAddr); m_threadPool->start(task);//start a thread for this task } } m_threadPool->joinAll(); } return false; } return true; } catch (IException* e) { if (m_threadPool) m_threadPool->joinAll(); StringBuffer sErrMsg; e->errorMessage(sErrMsg); e->Release(); msg.appendf("Exception throw during cloud operation %s.\nMessage:%s", getFnString(m_eA), sErrMsg.str()); } catch (...) { if (m_threadPool) m_threadPool->joinAll(); throw MakeErrnoException("Unknown Exception during cloud operation %s", getFnString(m_eA)); } return false; } void setResult(const char* ip, const char* msg) { synchronized block(m_mutex); StringBuffer* pSb = new StringBuffer(msg); m_resultMap.setValue(ip, *pSb); } const char* getPort() {return m_port.str();} const char* getUser() {return m_user.str();} const char* getNewEnv() {return m_newEnv.str();} const char* getNewEnvId() {return m_newEnvId.str();} const char* getCurIp(){ if (m_curIp.length() == 0) queryHostIP().getIpText(m_curIp); return m_curIp.str(); } private: CWsDeployFileInfo* m_pFileInfo; Mutex m_mutex; bool m_opFailed; EnvAction m_eA; EnvAction m_cancelEA; Owned<IThreadPool> m_threadPool; MapStrToBuf m_resultMap; StringBuffer m_port; StringBuffer m_user; StringBuffer m_newEnv; StringBuffer m_newEnvId; StringBuffer m_curIp; IPropertyTree* m_pComputers; }; class CCloudTask : public CInterface, implements IInterface { public: IMPLEMENT_IINTERFACE; CCloudTask(CCloudActionHandler* pHandler, EnvAction eA, const char* ip) { m_caHandler.set(pHandler); m_eA = eA; m_ip.append(ip); } bool makeSoapCall() { try { Owned<CRpcCall> rpccall; rpccall.setown(new CRpcCall); StringBuffer sb("http://"); sb.append(m_ip.str()).append(":").append(m_caHandler->getPort()).append("/WsDeploy"); rpccall->set_url(sb.str()); rpccall->set_name(getFnString(m_eA)); SoapStringParam uName(m_caHandler->getUser()); uName.marshall(*rpccall.get(), "UserName","", "", ""); SoapStringParam ipAddr(m_caHandler->getCurIp()); ipAddr.marshall(*rpccall.get(), "Ip","", "", ""); if (m_eA == CLOUD_SAVE_ENV) { SoapStringParam newEnv(m_caHandler->getNewEnv()); newEnv.marshall(*rpccall.get(), "NewEnv","", "", ""); } if (m_eA == CLOUD_SAVE_ENV || m_eA == CLOUD_ROLLBACK_ENV) { SoapStringParam newEnvId(m_caHandler->getNewEnvId()); newEnvId.marshall(*rpccall.get(), "Id","", "", ""); } Owned<IHttpClientContext> httpctx = getHttpClientContext(); Owned<IHttpClient> httpclient = httpctx->createHttpClient(rpccall->getProxy(), rpccall->get_url()); httpclient->setUserID("soapclient"); httpclient->setPassword(""); httpclient->setTimeOut(CLOUD_SOAPCALL_TIMEOUT); Owned<ISoapClient> soapclient; httpclient->Link(); soapclient.setown(new CSoapClient(httpclient)); soapclient->setUsernameToken("soapclient", "", ""); StringBuffer soapAction, resultbuf; int result = soapclient->postRequest("text/xml","", *rpccall.get(), resultbuf, NULL); IPropertyTree* pResult = createPTreeFromXMLString(resultbuf); StringBuffer xpath; xpath.appendf("soap:Body/%sResponse/Msg", getFnString(m_eA)); const char* msg = pResult->queryProp(xpath.str()); xpath.clear().appendf("soap:Body/%sResponse/ReturnCode", getFnString(m_eA)); int retCode = pResult->getPropInt(xpath.str()); if (retCode != 1) { m_caHandler->setFailed(true); m_caHandler->setResult(m_ip.str(), msg?msg:""); } return true; } catch(IException* e) { StringBuffer sb; e->errorMessage(sb); m_caHandler->setFailed(true); m_caHandler->setResult(m_ip, sb.str()); } return false; } private: Linked<CCloudActionHandler> m_caHandler; EnvAction m_eA; StringBuffer m_ip; }; class CWsDeployExCE : public CWsDeploy { public: IMPLEMENT_IINTERFACE; virtual ~CWsDeployExCE(); virtual void init(IPropertyTree *cfg, const char *process, const char *service); virtual bool onInit(IEspContext &context, IEspEmptyRequest& req, IEspInitResponse& resp); virtual bool onDeploy(IEspContext &context, IEspDeployRequest &req, IEspDeployResponse &resp); virtual bool onGraph(IEspContext &context, IEspEmptyRequest& req, IEspGraphResponse& resp); virtual bool onNavMenuEvent(IEspContext &context, IEspNavMenuEventRequest &req, IEspNavMenuEventResponse &resp); virtual bool onDisplaySettings(IEspContext &context, IEspDisplaySettingsRequest &req, IEspDisplaySettingsResponse &resp); virtual bool onSaveSetting(IEspContext &context, IEspSaveSettingRequest &req, IEspSaveSettingResponse &resp); virtual bool onGetBuildSetInfo(IEspContext &context, IEspGetBuildSetInfoRequest &req, IEspGetBuildSetInfoResponse &resp); virtual bool onGetDeployableComps(IEspContext &context, IEspGetDeployableCompsRequest &req, IEspGetDeployableCompsResponse &resp); virtual bool onStartDeployment(IEspContext &context, IEspStartDeploymentRequest &req, IEspStartDeploymentResponse &resp); virtual bool onGetBuildServerDirs(IEspContext &context, IEspGetBuildServerDirsRequest &req, IEspGetBuildServerDirsResponse &resp); virtual bool onImportBuild(IEspContext &context, IEspImportBuildRequest &req, IEspImportBuildResponse &resp); virtual bool onGetComputersForRoxie(IEspContext &context, IEspGetComputersForRoxieRequest &req, IEspGetComputersForRoxieResponse &resp); virtual bool onHandleRoxieOperation(IEspContext &context, IEspHandleRoxieOperationRequest &req, IEspHandleRoxieOperationResponse &resp); virtual bool onHandleThorTopology(IEspContext &context, IEspHandleThorTopologyRequest &req, IEspHandleThorTopologyResponse &resp); virtual bool onHandleComponent(IEspContext &context, IEspHandleComponentRequest &req, IEspHandleComponentResponse &resp); virtual bool onHandleInstance(IEspContext &context, IEspHandleInstanceRequest &req, IEspHandleInstanceResponse &resp); virtual bool onHandleEspServiceBindings(IEspContext &context, IEspHandleEspServiceBindingsRequest &req, IEspHandleEspServiceBindingsResponse &resp); virtual bool onHandleComputer(IEspContext &context, IEspHandleComputerRequest &req, IEspHandleComputerResponse &resp); virtual bool onHandleTopology(IEspContext &context, IEspHandleTopologyRequest &req, IEspHandleTopologyResponse &resp); virtual bool onHandleRows(IEspContext &context, IEspHandleRowsRequest &req, IEspHandleRowsResponse &resp); virtual bool onGetNavTreeDefn(IEspContext &context, IEspGetNavTreeDefnRequest &req, IEspGetNavTreeDefnResponse &resp); virtual bool onGetValue(IEspContext &context, IEspGetValueRequest &req, IEspGetValueResponse &resp); virtual bool onUnlockUser(IEspContext &context, IEspUnlockUserRequest &req, IEspUnlockUserResponse &resp); virtual bool onClientAlive(IEspContext &context, IEspClientAliveRequest &req, IEspClientAliveResponse &resp); virtual bool onGetEnvironment(IEspContext &context, IEspGetEnvironmentRequest &req, IEspGetEnvironmentResponse &resp); virtual bool onSetEnvironment(IEspContext &context, IEspSetEnvironmentRequest &req, IEspSetEnvironmentResponse &resp); virtual bool onLockEnvironmentForCloud(IEspContext &context, IEspLockEnvironmentForCloudRequest &req, IEspLockEnvironmentForCloudResponse &resp); virtual bool onUnlockEnvironmentForCloud(IEspContext &context, IEspUnlockEnvironmentForCloudRequest &req, IEspUnlockEnvironmentForCloudResponse &resp); virtual bool onBuildEnvironment(IEspContext &context, IEspBuildEnvironmentRequest &req, IEspBuildEnvironmentResponse &resp); virtual bool onGetSubnetIPAddr(IEspContext &context, IEspGetSubnetIPAddrRequest &req, IEspGetSubnetIPAddrResponse &resp); virtual bool onSaveEnvironmentForCloud(IEspContext &context, IEspSaveEnvironmentForCloudRequest &req, IEspSaveEnvironmentForCloudResponse &resp); virtual bool onRollbackEnvironmentForCloud(IEspContext &context, IEspRollbackEnvironmentForCloudRequest &req, IEspRollbackEnvironmentForCloudResponse &resp); virtual bool onNotifyInitSystemSaveEnvForCloud(IEspContext &context, IEspNotifyInitSystemSaveEnvForCloudRequest &req, IEspNotifyInitSystemSaveEnvForCloudResponse &resp); virtual bool onGetSummary(IEspContext &context, IEspGetSummaryRequest &req, IEspGetSummaryResponse &resp); void getNavigationData(IEspContext &context, IPropertyTree* pData); CWsDeployFileInfo* getFileInfo(const char* fileName, bool addIfNotFound=false, bool createFile = false); IPropertyTree* getCfg() { return m_pCfg;} const char* getName() { return m_service.str();} void getLastStarted(StringBuffer& sb); const char* getBackupDir() { return m_backupDir.str(); } const char* getProcessName() { return m_process.str(); } const char* getSourceDir() { return m_sourceDir.str(); } private: virtual void getWizOptions(StringBuffer& sb); protected: Mutex m_mutexSrv; StringBuffer m_envFile; StringBuffer m_backupDir; StringBuffer m_sourceDir; StringBuffer m_process; StringBuffer m_service; typedef MapStringTo<StringBuffer, StringBuffer&> CompHTMLMap; CompHTMLMap m_compHtmlMap; bool m_bCloud; Owned<IPropertyTree> m_pCfg; CDateTime m_lastStarted; MapStringToMyClass<CWsDeployFileInfo> m_fileInfos; }; class CWsDeployEx : public CWsDeployExCE { public: IMPLEMENT_IINTERFACE; virtual ~CWsDeployEx(){} virtual bool onDeploy(IEspContext &context, IEspDeployRequest &req, IEspDeployResponse &resp); virtual bool onGraph(IEspContext &context, IEspEmptyRequest& req, IEspGraphResponse& resp); virtual bool onNavMenuEvent(IEspContext &context, IEspNavMenuEventRequest &req, IEspNavMenuEventResponse &resp); virtual bool onDisplaySettings(IEspContext &context, IEspDisplaySettingsRequest &req, IEspDisplaySettingsResponse &resp); virtual bool onSaveSetting(IEspContext &context, IEspSaveSettingRequest &req, IEspSaveSettingResponse &resp); virtual bool onGetBuildSetInfo(IEspContext &context, IEspGetBuildSetInfoRequest &req, IEspGetBuildSetInfoResponse &resp); virtual bool onGetDeployableComps(IEspContext &context, IEspGetDeployableCompsRequest &req, IEspGetDeployableCompsResponse &resp); virtual bool onStartDeployment(IEspContext &context, IEspStartDeploymentRequest &req, IEspStartDeploymentResponse &resp); virtual bool onGetBuildServerDirs(IEspContext &context, IEspGetBuildServerDirsRequest &req, IEspGetBuildServerDirsResponse &resp); virtual bool onImportBuild(IEspContext &context, IEspImportBuildRequest &req, IEspImportBuildResponse &resp); virtual bool onGetComputersForRoxie(IEspContext &context, IEspGetComputersForRoxieRequest &req, IEspGetComputersForRoxieResponse &resp); virtual bool onHandleRoxieOperation(IEspContext &context, IEspHandleRoxieOperationRequest &req, IEspHandleRoxieOperationResponse &resp); virtual bool onHandleThorTopology(IEspContext &context, IEspHandleThorTopologyRequest &req, IEspHandleThorTopologyResponse &resp); virtual bool onHandleComponent(IEspContext &context, IEspHandleComponentRequest &req, IEspHandleComponentResponse &resp); virtual bool onHandleInstance(IEspContext &context, IEspHandleInstanceRequest &req, IEspHandleInstanceResponse &resp); virtual bool onHandleEspServiceBindings(IEspContext &context, IEspHandleEspServiceBindingsRequest &req, IEspHandleEspServiceBindingsResponse &resp); virtual bool onHandleComputer(IEspContext &context, IEspHandleComputerRequest &req, IEspHandleComputerResponse &resp); virtual bool onHandleTopology(IEspContext &context, IEspHandleTopologyRequest &req, IEspHandleTopologyResponse &resp); virtual bool onHandleRows(IEspContext &context, IEspHandleRowsRequest &req, IEspHandleRowsResponse &resp); virtual bool onGetNavTreeDefn(IEspContext &context, IEspGetNavTreeDefnRequest &req, IEspGetNavTreeDefnResponse &resp); virtual bool onGetValue(IEspContext &context, IEspGetValueRequest &req, IEspGetValueResponse &resp); virtual bool onLockEnvironmentForCloud(IEspContext &context, IEspLockEnvironmentForCloudRequest &req, IEspLockEnvironmentForCloudResponse &resp); virtual bool onUnlockEnvironmentForCloud(IEspContext &context, IEspUnlockEnvironmentForCloudRequest &req, IEspUnlockEnvironmentForCloudResponse &resp); virtual bool onSaveEnvironmentForCloud(IEspContext &context, IEspSaveEnvironmentForCloudRequest &req, IEspSaveEnvironmentForCloudResponse &resp); virtual bool onRollbackEnvironmentForCloud(IEspContext &context, IEspRollbackEnvironmentForCloudRequest &req, IEspRollbackEnvironmentForCloudResponse &resp); virtual bool onNotifyInitSystemSaveEnvForCloud(IEspContext &context, IEspNotifyInitSystemSaveEnvForCloudRequest &req, IEspNotifyInitSystemSaveEnvForCloudResponse &resp); private: virtual void getWizOptions(StringBuffer& sb); }; #endif //_ESPWIZ_WsDeploy_HPP__
RussWhitehead/HPCC-Platform
esp/services/WsDeploy/WsDeployService.hpp
C++
agpl-3.0
35,325
<?php /** * StatusNet, the distributed open-source microblogging tool * * User profile page * * PHP version 5 * * LICENCE: This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @category Personal * @package StatusNet * @author Evan Prodromou <evan@status.net> * @author Sarven Capadisli <csarven@status.net> * @copyright 2008-2009 StatusNet, Inc. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @link http://status.net/ */ if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } require_once INSTALLDIR.'/lib/personalgroupnav.php'; require_once INSTALLDIR.'/lib/noticelist.php'; require_once INSTALLDIR.'/lib/profileminilist.php'; require_once INSTALLDIR.'/lib/groupminilist.php'; require_once INSTALLDIR.'/lib/feedlist.php'; /** * User profile page * * When I created this page, "show stream" seemed like the best name for it. * Now, it seems like a really bad name. * * It shows a stream of the user's posts, plus lots of profile info, links * to subscriptions and stuff, etc. * * @category Personal * @package StatusNet * @author Evan Prodromou <evan@status.net> * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @link http://status.net/ */ class ShowstreamAction extends ProfileAction { var $notice; function prepare($args) { parent::prepare($args); $p = Profile::current(); if (empty($this->tag)) { $stream = new ProfileNoticeStream($this->profile, $p); } else { $stream = new TaggedProfileNoticeStream($this->profile, $this->tag, $p); } $this->notice = $stream->getNotices(($this->page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); return true; } function isReadOnly($args) { return true; } function title() { $base = $this->profile->getFancyName(); if (!empty($this->tag)) { if ($this->page == 1) { // TRANS: Page title showing tagged notices in one user's timeline. // TRANS: %1$s is the username, %2$s is the hash tag. return sprintf(_('Notices by %1$s tagged %2$s'), $base, $this->tag); } else { // TRANS: Page title showing tagged notices in one user's timeline. // TRANS: %1$s is the username, %2$s is the hash tag, %3$d is the page number. return sprintf(_('Notices by %1$s tagged %2$s, page %3$d'), $base, $this->tag, $this->page); } } else { if ($this->page == 1) { return $base; } else { // TRANS: Extended page title showing tagged notices in one user's timeline. // TRANS: %1$s is the username, %2$d is the page number. return sprintf(_('Notices by %1$s, page %2$d'), $base, $this->page); } } } function handle($args) { // Looks like we're good; start output // For YADIS discovery, we also have a <meta> tag $this->showPage(); } function showContent() { $this->showNotices(); } function showProfileBlock() { $block = new AccountProfileBlock($this, $this->profile); $block->show(); } function showPageNoticeBlock() { return; } function getFeeds() { if (!empty($this->tag)) { return array(new Feed(Feed::RSS1, common_local_url('userrss', array('nickname' => $this->user->nickname, 'tag' => $this->tag)), // TRANS: Title for link to notice feed. // TRANS: %1$s is a user nickname, %2$s is a hashtag. sprintf(_('Notice feed for %1$s tagged %2$s (RSS 1.0)'), $this->user->nickname, $this->tag))); } return array(new Feed(Feed::JSON, common_local_url('ApiTimelineUser', array( 'id' => $this->user->id, 'format' => 'as')), // TRANS: Title for link to notice feed. // TRANS: %s is a user nickname. sprintf(_('Notice feed for %s (Activity Streams JSON)'), $this->user->nickname)), new Feed(Feed::RSS1, common_local_url('userrss', array('nickname' => $this->user->nickname)), // TRANS: Title for link to notice feed. // TRANS: %s is a user nickname. sprintf(_('Notice feed for %s (RSS 1.0)'), $this->user->nickname)), new Feed(Feed::RSS2, common_local_url('ApiTimelineUser', array( 'id' => $this->user->id, 'format' => 'rss')), // TRANS: Title for link to notice feed. // TRANS: %s is a user nickname. sprintf(_('Notice feed for %s (RSS 2.0)'), $this->user->nickname)), new Feed(Feed::ATOM, common_local_url('ApiTimelineUser', array( 'id' => $this->user->id, 'format' => 'atom')), // TRANS: Title for link to notice feed. // TRANS: %s is a user nickname. sprintf(_('Notice feed for %s (Atom)'), $this->user->nickname)), new Feed(Feed::FOAF, common_local_url('foaf', array('nickname' => $this->user->nickname)), // TRANS: Title for link to notice feed. FOAF stands for Friend of a Friend. // TRANS: More information at http://www.foaf-project.org. %s is a user nickname. sprintf(_('FOAF for %s'), $this->user->nickname))); } function extraHead() { if ($this->profile->bio) { $this->element('meta', array('name' => 'description', 'content' => $this->profile->bio)); } if ($this->user->emailmicroid && $this->user->email && $this->profile->profileurl) { $id = new Microid('mailto:'.$this->user->email, $this->selfUrl()); $this->element('meta', array('name' => 'microid', 'content' => $id->toString())); } // See https://wiki.mozilla.org/Microsummaries $this->element('link', array('rel' => 'microsummary', 'href' => common_local_url('microsummary', array('nickname' => $this->profile->nickname)))); $rsd = common_local_url('rsd', array('nickname' => $this->profile->nickname)); // RSD, http://tales.phrasewise.com/rfc/rsd $this->element('link', array('rel' => 'EditURI', 'type' => 'application/rsd+xml', 'href' => $rsd)); if ($this->page != 1) { $this->element('link', array('rel' => 'canonical', 'href' => $this->profile->profileurl)); } } function showEmptyListMessage() { // TRANS: First sentence of empty list message for a timeline. $1%s is a user nickname. $message = sprintf(_('This is the timeline for %1$s, but %1$s hasn\'t posted anything yet.'), $this->user->nickname) . ' '; if (common_logged_in()) { $current_user = common_current_user(); if ($this->user->id === $current_user->id) { // TRANS: Second sentence of empty list message for a stream for the user themselves. // $message .= _('Seen anything interesting recently? You haven\'t posted any notices yet, now would be a good time to start :)'); $message .= _('何か投稿してみましょうヽ(´ー`)ノ'); } else { // TRANS: Second sentence of empty list message for a non-self timeline. %1$s is a user nickname, %2$s is a part of a URL. // TRANS: This message contains a Markdown link. Keep "](" together. $message .= sprintf(_('You can try to nudge %1$s or [post something to them](%%%%action.newnotice%%%%?status_textarea=%2$s).'), $this->user->nickname, '@' . $this->user->nickname); } } else { // TRANS: Second sentence of empty message for anonymous users. %s is a user nickname. // TRANS: This message contains a Markdown link. Keep "](" together. $message .= sprintf(_('Why not [register an account](%%%%action.register%%%%) and then nudge %s or post a notice to them.'), $this->user->nickname); } $this->elementStart('div', 'guide'); $this->raw(common_markup_to_html($message)); $this->elementEnd('div'); } function showNotices() { $pnl = null; if (Event::handle('ShowStreamNoticeList', array($this->notice, $this, &$pnl))) { $pnl = new ProfileNoticeList($this->notice, $this); } $cnt = $pnl->show(); if (0 == $cnt) { $this->showEmptyListMessage(); } $args = array('nickname' => $this->user->nickname); if (!empty($this->tag)) { $args['tag'] = $this->tag; } $this->pagination($this->page>1, $cnt>NOTICES_PER_PAGE, $this->page, 'showstream', $args); } function showAnonymousMessage() { if (!(common_config('site','closed') || common_config('site','inviteonly'))) { // TRANS: Announcement for anonymous users showing a timeline if site registrations are open. // TRANS: This message contains a Markdown link. Keep "](" together. $m = sprintf(_('**%s** has an account on %%%%site.name%%%%, a [micro-blogging](http://en.wikipedia.org/wiki/Micro-blogging) service ' . 'based on the Free Software [StatusNet](http://status.net/) tool. ' . '[Join now](%%%%action.register%%%%) to follow **%s**\'s notices and many more! ([Read more](%%%%doc.help%%%%))'), $this->user->nickname, $this->user->nickname); } else { // TRANS: Announcement for anonymous users showing a timeline if site registrations are closed or invite only. // TRANS: This message contains a Markdown link. Keep "](" together. $m = sprintf(_('**%s** has an account on %%%%site.name%%%%, a [micro-blogging](http://en.wikipedia.org/wiki/Micro-blogging) service ' . 'based on the Free Software [StatusNet](http://status.net/) tool.'), $this->user->nickname, $this->user->nickname); } $this->elementStart('div', array('id' => 'anon_notice')); $this->raw(common_markup_to_html($m)); $this->elementEnd('div'); } function showSections() { parent::showSections(); if (!common_config('performance', 'high')) { $cloud = new PersonalTagCloudSection($this, $this->user); $cloud->show(); } } function noticeFormOptions() { $options = parent::noticeFormOptions(); $cur = common_current_user(); if (empty($cur) || $cur->id != $this->profile->id) { $options['to_profile'] = $this->profile; } return $options; } } // We don't show the author for a profile, since we already know who it is! /** * Slightly modified from standard list; the author & avatar are hidden * in CSS. We used to remove them here too, but as it turns out that * confuses the inline reply code... and we hide them in CSS anyway * since realtime updates come through in original form. * * Remaining customization right now is for the repeat marker, where * it'll list who the original poster was instead of who did the repeat * (since the repeater is you, and the repeatee isn't shown!) * This will remain inconsistent if realtime updates come through, * since those'll get rendered as a regular NoticeListItem. */ class ProfileNoticeList extends NoticeList { function newListItem($notice) { return new ProfileNoticeListItem($notice, $this->out); } } class ProfileNoticeListItem extends DoFollowListItem { /** * show a link to the author of repeat * * @return void */ function showRepeat() { if (!empty($this->repeat)) { // FIXME: this code is almost identical to default; need to refactor $attrs = array('href' => $this->profile->profileurl, 'class' => 'url'); if (!empty($this->profile->fullname)) { $attrs['title'] = $this->profile->getFancyName(); } $this->out->elementStart('span', 'repeat'); $text_link = XMLStringer::estring('a', $attrs, $this->profile->nickname); // TRANS: Link to the author of a repeated notice. %s is a linked nickname. $this->out->raw(sprintf(_('Repeat of %s'), $text_link)); $this->out->elementEnd('span'); } } }
fuzzy31u/mt-clone-app
actions/showstream.php
PHP
agpl-3.0
15,044
module PreferenceSections class FooterAndExternalLinksSection def name I18n.t('admin.contents.edit.footer_and_external_links') end def preferences [ :footer_logo, :footer_facebook_url, :footer_twitter_url, :footer_instagram_url, :footer_linkedin_url, :footer_googleplus_url, :footer_pinterest_url, :footer_email, :community_forum_url, :footer_links_md, :footer_about_url ] end end end
lin-d-hop/openfoodnetwork
app/models/preference_sections/footer_and_external_links_section.rb
Ruby
agpl-3.0
512
/** * Copyright by Michael Weiss, weiss.michael@gmx.ch * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.spectrumauctions.sats.core.util.random; import java.math.BigDecimal; import java.util.Date; import java.util.Random; public class UniformJavaUtilRandomWrapper implements UniformDistributionRNG { /** * */ private static final long serialVersionUID = 4285241684660761136L; private Random rng; public UniformJavaUtilRandomWrapper() { this(new Date().getTime()); } public UniformJavaUtilRandomWrapper(long seed) { this.rng = new Random(seed); } @Override public int nextInt() { return rng.nextInt(); } @Override public int nextInt(int lowerLimit, int upperLimit) { if (upperLimit == Integer.MAX_VALUE) upperLimit--; return rng.nextInt((upperLimit - lowerLimit) + 1) + lowerLimit; } @Override public int nextInt(IntegerInterval interval) { return nextInt(interval.getMinValue(), interval.getMaxValue()); } @Override public double nextDouble() { return rng.nextDouble(); } @Override public double nextDouble(double lowerLimit, double upperLimit) { return rng.nextDouble() * (upperLimit - lowerLimit) + lowerLimit; } @Override public long nextLong() { return rng.nextLong(); } @Override public double nextDouble(DoubleInterval interval) { return nextDouble(interval.getMinValue(), interval.getMaxValue()); } /* * (non-Javadoc) * * @see UniformDistributionRNG#nextBigDecimal() */ @Override public BigDecimal nextBigDecimal() { return new BigDecimal(nextDouble()); } /* * (non-Javadoc) * * @see UniformDistributionRNG#nextBigDecimal(double, double) */ @Override public BigDecimal nextBigDecimal(double lowerLimit, double upperLimit) { return new BigDecimal(nextDouble(lowerLimit, upperLimit)); } /* * (non-Javadoc) * * @see * UniformDistributionRNG#nextBigDecimal(org.spectrumauctions.sats.core.util * .random.DoubleInterval) */ @Override public BigDecimal nextBigDecimal(DoubleInterval interval) { return new BigDecimal(nextDouble(interval)); } /* * (non-Javadoc) * * @see UniformDistributionRNG#nextInt(int) */ @Override public int nextInt(int upperLimit) { return rng.nextInt(upperLimit); } }
spectrumauctions/sats-core
src/main/java/org/spectrumauctions/sats/core/util/random/UniformJavaUtilRandomWrapper.java
Java
agpl-3.0
2,952
# # In development mode, rails is very aggressive about unloading and reloading # classes as needed. Unfortunately, for crabgrass page types, rails always gets # it wrong. To get around this, we create static proxy representation of the # classes of each page type and load the actually class only when we have to. # module Crabgrass::Page class ClassProxy attr_accessor :creation_controller, :model, :icon, :class_group, :form_sections, :class_name, :full_class_name, :internal, :order, :short_class_name, :forbid_new attr_writer :controller ORDER = ['text', 'media', 'vote', 'calendar'] def initialize(arg=nil) raise 'error' unless arg.is_a? Hash if arg[:class_name] arg.each do |key,value| method = key.to_s + '=' self.send(method,value) if self.respond_to?(method) end self.class_group = [self.class_group] unless self.class_group.is_a? Array self.full_class_name = self.class_name self.short_class_name = self.class_name.sub("Page","") self.order ||= 100 end end def definition self end def class_display_name symbol = (class_name.underscore + '_display').to_sym I18n.t(symbol) end def class_description symbol = (class_name.underscore + '_description').to_sym I18n.t(symbol) end def actual_class get_const(self.full_class_name) end # allows us to get constants that might be namespaced def get_const(str) str.split('::').inject(Object) {|x,y| x.const_get(y) } end def create(hash, &block) actual_class.create(hash, &block) end def create!(hash, &block) actual_class.create!(hash, &block) end def build!(hash, &block) actual_class.build!(hash, &block) end def to_s full_class_name end # returns a unique identifier suited to put in a url # eg RateManyPage => "rate-many" def url @url ||= short_class_name.underscore.gsub('_','-').nameize end # # return an array of all the controllers # def controllers @controllers ||= begin ary = [] if @controller.is_a? Array ary += @controller elsif @controller.is_a? String ary << @controller end if @creation_controller ary << @creation_controller end ary end end # # returns the primary controller # def controller @first_controller ||= begin if @controller.is_a? Array @controller.first elsif @controller.is_a? String @controller end end end end end
elijh/crabgrass-core
lib/crabgrass/page/class_proxy.rb
Ruby
agpl-3.0
2,690
<?php /** * Custom Achievement Rules * * @package BadgeOS LearnDash * @subpackage Achievements * @author Credly, LLC * @license http://www.gnu.org/licenses/agpl.txt GNU AGPL v3.0 * @link https://credly.com */ /** * Load up our LearnDash triggers so we can add actions to them * * @since 1.0.0 */ function badgeos_learndash_load_triggers() { // Grab our LearnDash triggers $learndash_triggers = $GLOBALS[ 'badgeos_learndash' ]->triggers; if ( !empty( $learndash_triggers ) ) { foreach ( $learndash_triggers as $trigger => $trigger_label ) { if ( is_array( $trigger_label ) ) { $triggers = $trigger_label; foreach ( $triggers as $trigger_hook => $trigger_name ) { add_action( $trigger_hook, 'badgeos_learndash_trigger_event', 10, 20 ); } } else { add_action( $trigger, 'badgeos_learndash_trigger_event', 10, 20 ); } } } } add_action( 'init', 'badgeos_learndash_load_triggers' ); /** * Handle each of our LearnDash triggers * * @since 1.0.0 */ function badgeos_learndash_trigger_event() { // Setup all our important variables global $blog_id, $wpdb; // Setup args $args = func_get_args(); $userID = get_current_user_id(); if ( is_array( $args ) && isset( $args[ 0 ] ) && isset( $args[ 0 ][ 'user' ] ) ) { if ( is_object( $args[ 0 ][ 'user' ] ) ) { $userID = (int) $args[ 0 ][ 'user' ]->ID; } else { $userID = (int) $args[ 0 ][ 'user' ]; } } if ( empty( $userID ) ) { return; } $user_data = get_user_by( 'id', $userID ); if ( empty( $user_data ) ) { return; } // Grab the current trigger $this_trigger = current_filter(); // Update hook count for this user $new_count = badgeos_update_user_trigger_count( $userID, $this_trigger, $blog_id ); // Mark the count in the log entry badgeos_post_log_entry( null, $userID, null, sprintf( __( '%1$s triggered %2$s (%3$dx)', 'badgeos' ), $user_data->user_login, $this_trigger, $new_count ) ); // Now determine if any badges are earned based on this trigger event $triggered_achievements = $wpdb->get_results( $wpdb->prepare( " SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_badgeos_learndash_trigger' AND meta_value = %s ", $this_trigger ) ); foreach ( $triggered_achievements as $achievement ) { badgeos_maybe_award_achievement_to_user( $achievement->post_id, $userID, $this_trigger, $blog_id, $args ); } } /** * Check if user deserves a LearnDash trigger step * * @since 1.0.0 * * @param bool $return Whether or not the user deserves the step * @param integer $user_id The given user's ID * @param integer $achievement_id The given achievement's post ID * @param string $trigger The trigger * @param integer $site_id The triggered site id * @param array $args The triggered args * * @return bool True if the user deserves the step, false otherwise */ function badgeos_learndash_user_deserves_learndash_step( $return, $user_id, $achievement_id, $this_trigger = '', $site_id = 1, $args = array() ) { // If we're not dealing with a step, bail here if ( 'step' != get_post_type( $achievement_id ) ) { return $return; } // Grab our step requirements $requirements = badgeos_get_step_requirements( $achievement_id ); // If the step is triggered by LearnDash actions... if ( 'learndash_trigger' == $requirements[ 'trigger_type' ] ) { // Do not pass go until we say you can $return = false; // Unsupported trigger if ( !isset( $GLOBALS[ 'badgeos_learndash' ]->triggers[ $this_trigger ] ) ) { return $return; } // LearnDash requirements not met yet $learndash_triggered = false; // Set our main vars $learndash_trigger = $requirements[ 'learndash_trigger' ]; $object_id = $requirements[ 'learndash_object_id' ]; // Extra arg handling for further expansion $object_arg1 = null; if ( isset( $requirements[ 'learndash_object_arg1' ] ) ) $object_arg1 = $requirements[ 'learndash_object_arg1' ]; // Object-specific triggers $learndash_object_triggers = array( 'learndash_quiz_completed' => 'quiz', 'badgeos_learndash_quiz_completed_specific' => 'quiz', 'badgeos_learndash_quiz_completed_fail' => 'quiz', 'learndash_lesson_completed' => 'lesson', 'learndash_topic_completed' => 'topic', 'learndash_course_completed' => 'course' ); // Category-specific triggers $learndash_category_triggers = array( 'badgeos_learndash_course_completed_tag' ); // Triggered object ID (used in these hooks, generally 2nd arg) $triggered_object_id = 0; $arg_data = $args[ 0 ]; if ( is_array( $arg_data ) && isset( $learndash_object_triggers[ $learndash_trigger ] ) && isset( $arg_data[ $learndash_object_triggers[ $learndash_trigger ] ] ) && !empty( $arg_data[ $learndash_object_triggers[ $learndash_trigger ] ] ) ) { $triggered_object_id = (int) $arg_data[ $learndash_object_triggers[ $learndash_trigger ] ]->ID; } // Use basic trigger logic if no object set if ( empty( $object_id ) ) { $learndash_triggered = true; } // Object specific elseif ( $triggered_object_id == $object_id ) { $learndash_triggered = true; // Forcing count due to BadgeOS bug tracking triggers properly $requirements[ 'count' ] = 1; } // Category specific elseif ( in_array( $learndash_trigger, $learndash_category_triggers ) && has_term( $object_id, 'post_tag', $triggered_object_id ) ) { $learndash_triggered = true; // Forcing count due to BadgeOS bug tracking triggers properly $requirements[ 'count' ] = 1; } // Quiz triggers if ( $learndash_triggered && isset( $learndash_object_triggers[ $learndash_trigger ] ) && 'quiz' == $learndash_object_triggers[ $learndash_trigger ] ) { // Check for fail if ( 'badgeos_learndash_quiz_completed_fail' == $learndash_trigger ) { if ( $arg_data[ 'pass' ] ) { $learndash_triggered = false; } } // Check for a specific grade elseif ( 'badgeos_learndash_quiz_completed_specific' == $learndash_trigger ) { $percentage = (int) $arg_data[ 'percentage' ]; $object_arg1 = (int) $object_arg1; if ( $percentage < $object_arg1 ) { $learndash_triggered = false; } } // Check for passing elseif ( !$arg_data[ 'pass' ] ) { $learndash_triggered = false; } } // LearnDash requirements met if ( $learndash_triggered ) { // Grab the trigger count $trigger_count = badgeos_get_user_trigger_count( $user_id, $this_trigger, $site_id ); // If we meet or exceed the required number of checkins, they deserve the step if ( 1 == $requirements[ 'count' ] || $requirements[ 'count' ] <= $trigger_count ) { // OK, you can pass go now $return = true; } } if ( $learndash_triggered && $return ) { $user_data = get_userdata( $user_id ); badgeos_post_log_entry( null, $user_id, null, sprintf( __( '%1$s deserves %2$s', 'badgeos' ), $user_data->user_login, $this_trigger ) ); } } return $return; } add_filter( 'user_deserves_achievement', 'badgeos_learndash_user_deserves_learndash_step', 15, 6 );
bethadele/BadgeOS-LearnDash-Add-on
includes/rules-engine.php
PHP
agpl-3.0
7,065
<?php namespace spec\TH\OAuth2; use PhpSpec\ObjectBehavior; use Symfony\Component\HttpFoundation\Request; class OAuth2EntryPointSpec extends ObjectBehavior { public function let() { $this->beConstructedWith('AppName'); } public function it_is_initializable() { $this->shouldHaveType('TH\OAuth2\OAuth2EntryPoint'); $this->shouldImplement('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface'); } public function it_starts(Request $request) { $response = $this->start($request); $response->shouldHaveType('Symfony\Component\HttpFoundation\Response'); $response->getStatusCode()->shouldReturn(401); $response->headers->get('WWW-Authenticate')->shouldReturn('Bearer realm="AppName"'); } }
texthtml/oauth2-provider
spec/OAuth2EntryPointSpec.php
PHP
agpl-3.0
808
<?php // Return array of langs return array( 'username' => 'Brugernavn', 'password' => 'Adgangskode', 'password again' => 'Gentag adgangskode', 'old password' => 'Tidligere adgangskode', 'remember me' => 'Husk brugernavn/adgangskode i 14 dage', 'email address' => 'Email adresse', 'display name' => 'Vist navn', 'overview' => 'Overblik', 'search' => 'Søg', 'search results' => 'Søgeresultater', 'account' => 'Konto', 'settings' => 'Indstillinger', 'index' => 'Indeks', 'view' => 'Vis', 'edit' => 'Redigér', 'delete' => 'Slet', 'save' => 'Gem', 'update' => 'Opdatér', 'submit' => 'Send', 'reset' => 'Nulstil', 'name' => 'Navn', 'title' => 'Titel', 'description' => 'Beskrivelse', 'text' => 'Tekst', 'additional text' => 'Yderligere tekst', 'due date' => 'Afslutningsdato', 'assign to' => 'Tildel', 'late' => 'Forsinket', 'upcoming' => 'Kommende', 'today' => 'Idag', 'yesterday' => 'Igår', 'tomorrow' => 'Imorgen', 'n/a' => '<acronym title="Ikke tilgængelig">(blank)</acronym>', 'anyone' => 'Hvemsomhelst', 'nobody' => 'Ingen', 'none' => '-- Ingen --', 'please select' => '-- Vælg --', 'reorder' => 'Organisér', 'cancel' => 'Annullér', 'size' => 'Størrelse', 'type' => 'Type', 'status' => 'Status', 'options' => 'Valgmuligheder', 'active' => 'Aktiv', 'completed' => 'Gennemført', 'administrator' => 'Administrator', 'error' => 'Fejl', 'yes' => 'Ja', 'no' => 'Nej', 'all' => 'Alle', 'or' => 'Eller', 'by' => 'Af', 'on' => 'd.', 'in' => 'i', 'people' => 'Brugere', 'permission' => 'Tilladelse', 'permissions' => 'Tilladelser', 'reset' => 'Nulstil', 'owner' => 'Ejer', 'instant messengers' => 'Besked-tjenester', 'value' => 'Værdi', 'phone number' => 'Telefonnr.', 'phone numbers' => 'Telefonnumre', 'office phone number' => 'Kontor', 'fax number' => 'Fax', 'mobile phone number' => 'Mobil', 'home phone number' => 'Hjemme', 'settings' => 'Indstillinger', 'homepage' => 'Website', 'address' => 'Adresse', 'address2' => 'Adresse 2', 'city' => 'By', 'state' => 'Stat', 'zipcode' => 'Postnr.', 'country' => 'Land', 'n/a' => '<acronym title="Ikke tilgængelig">(blank)</acronym>', 'contact' => 'Kontakt', 'pagination page' => 'Side:', 'pagination first' => 'Første side', 'pagination previous' => 'Forrige side', 'pagination next' => 'Næste side', 'pagination last' => 'Sidste side', 'pagination current page' => 'Side: %s', 'download' => 'Download', 'downloads' => 'Downloads', 'replace' => 'Erstat', 'expand' => 'Fold ud', 'collapse' => 'Fold sammen', 'author' => 'Forfatter', 'user title' => 'Titel', 'more' => 'Mere', 'order by' => 'Sortér efter', 'filename' => 'Filnavn', 'permalink' => 'Permalink', 'timezone' => 'Tidszone', 'upgrade' => 'Opgradér', 'changelog' => 'Changelog', 'hint' => 'Tip', 'order' => 'Sortér', 'project calendar' => '%s kalender', 'user calendar' => '%s\'s kalender', 'month 1' => 'Januar', 'month 2' => 'Februar', 'month 3' => 'Marts', 'month 4' => 'April', 'month 5' => 'Maj', 'month 6' => 'Juni', 'month 7' => 'Juli', 'month 8' => 'August', 'month 9' => 'September', 'month 10' => 'Oktober', 'month 11' => 'November', 'month 12' => 'December', ); // array ?>
bbguitar/ProjectPier
language/da_dk/general.php
PHP
agpl-3.0
3,553
<?php /** * @copyright 2017-2020 City of Bloomington, Indiana * @license http://www.gnu.org/licenses/agpl.txt GNU/AGPL, see LICENSE */ declare (strict_types=1); namespace Application\Models\Legislation; use Web\ActiveRecord; use Web\Database; class Status extends ActiveRecord { protected $tablename = 'legislationStatuses'; public function __construct($id=null) { if ($id) { if (is_array($id)) { $this->exchangeArray($id); } else { $db = Database::getConnection(); $sql = ActiveRecord::isId($id) ? 'select * from legislationStatuses where id=?' : 'select * from legislationStatuses where name=?'; $result = $db->createStatement($sql)->execute([$id]); if (count($result)) { $this->exchangeArray($result->current()); } else { throw new \Exception('legislationActions/unknown'); } } } else { // This is where the code goes to generate a new, empty instance. // Set any default values for properties that need it here } } public function validate() { if (!$this->getName()) { throw new \Exception('missingRequiredFields'); } } public function save() { parent::save(); } public function delete() { $db = Database::getConnection(); $sql = 'update legislation set status_id=null where status_id=?'; $db->createStatement($sql)->execute([$this->getId()]); parent::delete(); } //---------------------------------------------------------------- // Generic Getters & Setters //---------------------------------------------------------------- public function getId() { return parent::get('id' ); } public function getName() { return parent::get('name'); } public function getActive() { return parent::get('active') ? 1 : 0; } public function setName ($s) { parent::set('name', $s); } public function setActive ($i) { $this->data['active'] = $i ? 1 : 0; } public function handleUpdate(array $post) { $this->setName ($post['name' ]); $this->setActive($post['active'] ?? false); } }
City-of-Bloomington/civic-legislation
src/Application/Models/Legislation/Status.php
PHP
agpl-3.0
2,098
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT 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 Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.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 "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.gxt.rv.client.event; import com.ephesoft.dcma.batch.schema.Document; import com.ephesoft.dcma.batch.schema.Page; import com.google.web.bindery.event.shared.binder.GenericEvent; public class DocumentSplitStartEvent extends GenericEvent { private Document bindedDocument; private Page fromPage; private boolean stickFields; private boolean stickTables; public DocumentSplitStartEvent(Document bindedDocument, Page fromPage, boolean stickFields, boolean stickTables) { this.bindedDocument = bindedDocument; this.fromPage = fromPage; this.stickFields = stickFields; this.stickTables = stickTables; } /** * @return the bindedDocument */ public Document getBindedDocument() { return bindedDocument; } /** * @return the fromPage */ public Page getFromPage() { return fromPage; } public boolean isStickFields() { return stickFields; } public void setStickFields(boolean stickFields) { this.stickFields = stickFields; } public boolean isStickTables() { return stickTables; } public void setStickTables(boolean stickTables) { this.stickTables = stickTables; } }
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/gxt/gxt-review-validate/src/main/java/com/ephesoft/gxt/rv/client/event/DocumentSplitStartEvent.java
Java
agpl-3.0
3,107
/* * * Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker 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. * * Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Fermin Galan */ #include "orionTypes/QueryContextRequestVector.h" #include "unittests/unittest.h" /* **************************************************************************** * * present - no output expected, just exercising the code */ TEST(QueryContextRequestVector, present) { utInit(); QueryContextRequestVector qcrV; QueryContextRequest qcr; EntityId en = EntityId("E1", "T1", "false"); qcr.entityIdVector.push_back(&en); qcr.attributeList.push_back("A"); qcrV.vec.push_back(&qcr); qcrV.present(); utExit(); }
McMutton/fiware-orion
test/unittests/orionTypes/QueryContextRequestVector_test.cpp
C++
agpl-3.0
1,469
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'link', 'cs', { acccessKey: 'Přístupový klíč', advanced: 'Rozšířené', advisoryContentType: 'Pomocný typ obsahu', advisoryTitle: 'Pomocný titulek', anchor: { toolbar: 'Záložka', menu: 'Vlastnosti záložky', title: 'Vlastnosti záložky', name: 'Název záložky', errorName: 'Zadejte prosím název záložky', remove: 'Odstranit záložku' }, anchorId: 'Podle Id objektu', anchorName: 'Podle jména kotvy', charset: 'Přiřazená znaková sada', cssClasses: 'Třída stylu', download: 'Force Download', // MISSING displayText: 'Zobrazit text', emailAddress: 'E-mailová adresa', emailBody: 'Tělo zprávy', emailSubject: 'Předmět zprávy', id: 'Id', info: 'Informace o odkazu', langCode: 'Kód jazyka', langDir: 'Směr jazyka', langDirLTR: 'Zleva doprava (LTR)', langDirRTL: 'Zprava doleva (RTL)', menu: 'Změnit odkaz', name: 'Jméno', noAnchors: '(Ve stránce není definována žádná kotva!)', noEmail: 'Zadejte prosím e-mailovou adresu', noUrl: 'Zadejte prosím URL odkazu', other: '<jiný>', popupDependent: 'Závislost (Netscape)', popupFeatures: 'Vlastnosti vyskakovacího okna', popupFullScreen: 'Celá obrazovka (IE)', popupLeft: 'Levý okraj', popupLocationBar: 'Panel umístění', popupMenuBar: 'Panel nabídky', popupResizable: 'Umožňující měnit velikost', popupScrollBars: 'Posuvníky', popupStatusBar: 'Stavový řádek', popupToolbar: 'Panel nástrojů', popupTop: 'Horní okraj', rel: 'Vztah', selectAnchor: 'Vybrat kotvu', styles: 'Styl', tabIndex: 'Pořadí prvku', target: 'Cíl', targetFrame: '<rámec>', targetFrameName: 'Název cílového rámu', targetPopup: '<vyskakovací okno>', targetPopupName: 'Název vyskakovacího okna', title: 'Odkaz', toAnchor: 'Kotva v této stránce', toEmail: 'E-mail', toUrl: 'URL', toolbar: 'Odkaz', type: 'Typ odkazu', unlink: 'Odstranit odkaz', upload: 'Odeslat' } );
afshinnj/php-mvc
assets/framework/ckeditor/plugins/link/lang/cs.js
JavaScript
agpl-3.0
2,156
package com.simplyian.superplots; import java.util.logging.Level; import net.milkbowl.vault.economy.Economy; import org.bukkit.plugin.RegisteredServiceProvider; public class EconHook { private final SuperPlotsPlugin main; private Economy economy = null; public EconHook(SuperPlotsPlugin main) { this.main = main; } public void setupEconomy() { RegisteredServiceProvider<Economy> economyProvider = main.getServer() .getServicesManager().getRegistration(Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } if (economy == null) { main.getLogger() .log(Level.SEVERE, "No supported economy by Vault detected! Things WILL go wrong!"); } } /** * Gets the balance of a player. * * @param player * @return */ public double getBalance(String player) { return economy.getBalance(player); } /** * Sets the balance of a player. * * @param player * @param amt */ public void setBalance(String player, double amt) { economy.depositPlayer(player, amt); } /** * Adds money to a player's account. * * @param player * @param cost */ public void addBalance(String name, int cost) { setBalance(name, getBalance(name) + cost); } /** * Subtracts an amount of money from a player's account. * * @param name * @param cost */ public void subtractBalance(String name, int cost) { setBalance(name, getBalance(name) - cost); } }
simplyianm/SuperPlots
src/main/java/com/simplyian/superplots/EconHook.java
Java
agpl-3.0
1,693
package org.kareha.hareka.server.game.item; import org.kareha.hareka.field.TileType; import org.kareha.hareka.game.ItemType; import org.kareha.hareka.server.game.entity.CharacterEntity; import org.kareha.hareka.server.game.entity.FieldEntity; import org.kareha.hareka.server.game.entity.ItemEntity; import org.kareha.hareka.util.Name; import org.kareha.hareka.wait.WaitType; public class NoticeItem implements Item { private final Name name; public NoticeItem() { name = new Name("Notice"); name.put("ja", "掲示板"); } @Override public ItemType getType() { return ItemType.NOTICE; } @Override public Name getName() { return name; } @Override public String getShape() { return "Notice"; } @Override public boolean isExclusive() { return true; } @Override public boolean isStackable() { return false; } @Override public boolean isConsumable() { return false; } @Override public int getWeight() { return 8192; } @Override public int getReach() { return 1; } @Override public WaitType getWaitType() { return WaitType.ATTACK; } @Override public int getWait(final CharacterEntity entity, final TileType tileType) { return entity.getStat().getAttackWait(tileType); } @Override public void use(final CharacterEntity characterEntity, final ItemEntity itemEntity, final FieldEntity target) { // TODO item function characterEntity.sendMessage("not implemented"); } }
tyatsumi/hareka
server/src/main/java/org/kareha/hareka/server/game/item/NoticeItem.java
Java
agpl-3.0
1,439
<?php /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method void pause() * * @SuppressWarnings(PHPMD) */ class UnitTester extends \Codeception\Actor { use _generated\UnitTesterActions; /** * Define custom actions here */ }
GreenMeteor/humhub-discordapp-module
tests/_support/UnitTester.php
PHP
agpl-3.0
548
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('maposmatic', '0004_maprenderingjob_track'), ] operations = [ migrations.AlterField( model_name='maprenderingjob', name='track', field=models.FileField(null=True, upload_to=b'upload/tracks/', blank=True), ), ]
hholzgra/maposmatic
www/maposmatic/migrations/0005_auto_20170521_0103.py
Python
agpl-3.0
453
<?php if (! defined ( 'sugarEntry' ) || ! sugarEntry) die ( 'Not A Valid Entry Point' ) ; /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ /********************************************************************************* * Description: This file is used to override the default Meta-data EditView behavior * to provide customization specific to the Calls module. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. * All Rights Reserved. * Contributor(s): ______________________________________.. ********************************************************************************/ require_once ('include/MVC/View/views/view.edit.php') ; require_once ('modules/ModuleBuilder/parsers/ParserFactory.php') ; require_once ('modules/ModuleBuilder/MB/AjaxCompose.php') ; require_once 'modules/ModuleBuilder/parsers/constants.php' ; //require_once('include/Utils.php'); class ViewLayoutView extends ViewEdit { function ViewLayoutView () { $GLOBALS [ 'log' ]->debug ( 'in ViewLayoutView' ) ; $this->editModule = $_REQUEST [ 'view_module' ] ; $this->editLayout = $_REQUEST [ 'view' ] ; $this->package = null; $this->fromModuleBuilder = isset ( $_REQUEST [ 'MB' ] ) || !empty($_REQUEST [ 'view_package' ]); if ($this->fromModuleBuilder) { $this->package = $_REQUEST [ 'view_package' ] ; } else { global $app_list_strings ; $moduleNames = array_change_key_case ( $app_list_strings [ 'moduleList' ] ) ; $this->translatedEditModule = $moduleNames [ strtolower ( $this->editModule ) ] ; } } /** * @see SugarView::_getModuleTitleParams() */ protected function _getModuleTitleParams() { global $mod_strings; return array( translate('LBL_MODULE_NAME','Administration'), $mod_strings['LBL_MODULEBUILDER'], ); } // DO NOT REMOVE - overrides parent ViewEdit preDisplay() which attempts to load a bean for a non-existent module function preDisplay () { } function display ($preview = false) { global $mod_strings ; $parser = ParserFactory::getParser($this->editLayout,$this->editModule,$this->package); $history = $parser->getHistory () ; $smarty = new Sugar_Smarty ( ) ; //Add in the module we are viewing to our current mod strings if (! $this->fromModuleBuilder) { global $current_language; $editModStrings = return_module_language($current_language, $this->editModule); $mod_strings = sugarArrayMerge($editModStrings, $mod_strings); } $smarty->assign('mod', $mod_strings); $smarty->assign('MOD', $mod_strings); // assign buttons $images = array ( 'icon_save' => 'studio_save' , 'icon_publish' => 'studio_publish' , 'icon_address' => 'icon_Address' , 'icon_emailaddress' => 'icon_EmailAddress' , 'icon_phone' => 'icon_Phone' ) ; foreach ( $images as $image => $file ) { $smarty->assign ( $image, SugarThemeRegistry::current()->getImage($file) ) ; } $requiredFields = implode($parser->getRequiredFields () , ','); $slashedRequiredFields = addslashes($requiredFields); $buttons = array ( ) ; if ($preview) { $smarty->assign ( 'layouttitle', translate ( 'LBL_LAYOUT_PREVIEW', 'ModuleBuilder' ) ) ; } else { $smarty->assign ( 'layouttitle', translate ( 'LBL_CURRENT_LAYOUT', 'ModuleBuilder' ) ) ; if (! $this->fromModuleBuilder) { $buttons [] = array ( 'id' => 'saveBtn' , 'text' => translate ( 'LBL_BTN_SAVE' ) , 'actionScript' => "onclick='if(Studio2.checkGridLayout()) Studio2.handleSave();'" ) ; $buttons [] = array ( 'id' => 'publishBtn' , 'text' => translate ( 'LBL_BTN_SAVEPUBLISH' ) , 'actionScript' => "onclick='if(Studio2.checkGridLayout()) Studio2.handlePublish();'" ) ; $buttons [] = array ( 'id' => 'spacer' , 'width' => '50px' ) ; $buttons [] = array ( 'id' => 'historyBtn' , 'text' => translate ( 'LBL_HISTORY' ) , 'actionScript' => "onclick='ModuleBuilder.history.browse(\"{$this->editModule}\", \"{$this->editLayout}\")'") ; $buttons [] = array ( 'id' => 'historyDefault' , 'text' => translate ( 'LBL_RESTORE_DEFAULT' ) , 'actionScript' => "onclick='ModuleBuilder.history.revert(\"{$this->editModule}\", \"{$this->editLayout}\", \"{$history->getLast()}\", \"\")'" ) ; } else { $buttons [] = array ( 'id' => 'saveBtn' , 'text' => $GLOBALS [ 'mod_strings' ] [ 'LBL_BTN_SAVE' ] , 'actionScript' => "onclick='if(Studio2.checkGridLayout()) Studio2.handlePublish();'" ) ; $buttons [] = array ( 'id' => 'spacer' , 'width' => '50px' ) ; $buttons [] = array ( 'id' => 'historyBtn' , 'text' => translate ( 'LBL_HISTORY' ) , 'actionScript' => "onclick='ModuleBuilder.history.browse(\"{$this->editModule}\", \"{$this->editLayout}\")'" ) ; $buttons [] = array ( 'id' => 'historyDefault' , 'text' => translate ( 'LBL_RESTORE_DEFAULT' ) , 'actionScript' => "onclick='ModuleBuilder.history.revert(\"{$this->editModule}\", \"{$this->editLayout}\", \"{$history->getLast()}\", \"\")'" ) ; } } $html = "" ; foreach ( $buttons as $button ) { if ($button['id'] == "spacer") { $html .= "<td style='width:{$button['width']}'> </td>"; } else { $html .= "<td><input id='{$button['id']}' type='button' valign='center' class='button' style='cursor:pointer' " . "onmousedown='this.className=\"buttonOn\";return false;' onmouseup='this.className=\"button\"' " . "onmouseout='this.className=\"button\"' {$button['actionScript']} value = '{$button['text']}' ></td>" ; } } $smarty->assign ( 'buttons', $html ) ; // assign fields and layout $smarty->assign ( 'available_fields', $parser->getAvailableFields () ) ; $smarty->assign ( 'required_fields', $requiredFields) ; $smarty->assign ( 'layout', $parser->getLayout () ) ; $smarty->assign ( 'view_module', $this->editModule ) ; $smarty->assign ( 'view', $this->editLayout ) ; $smarty->assign ( 'maxColumns', $parser->getMaxColumns() ) ; $smarty->assign ( 'nextPanelId', $parser->getFirstNewPanelId() ) ; $smarty->assign ( 'displayAsTabs', $parser->getUseTabs() ) ; $smarty->assign ( 'fieldwidth', 150 ) ; $smarty->assign ( 'translate', $this->fromModuleBuilder ? false : true ) ; if ($this->fromModuleBuilder) { $smarty->assign ( 'fromModuleBuilder', $this->fromModuleBuilder ) ; $smarty->assign ( 'view_package', $this->package ) ; } $labels = array ( MB_EDITVIEW => 'LBL_EDITVIEW' , MB_DETAILVIEW => 'LBL_DETAILVIEW' , MB_QUICKCREATE => 'LBL_QUICKCREATE', ) ; $layoutLabel = 'LBL_LAYOUTS' ; $layoutView = 'layouts' ; $ajax = new AjaxCompose ( ) ; $viewType; $translatedViewType = '' ; if ( isset ( $labels [ strtolower ( $this->editLayout ) ] ) ) $translatedViewType = translate ( $labels [ strtolower( $this->editLayout ) ] , 'ModuleBuilder' ) ; if ($this->fromModuleBuilder) { $ajax->addCrumb ( translate ( 'LBL_MODULEBUILDER', 'ModuleBuilder' ), 'ModuleBuilder.main("mb")' ) ; $ajax->addCrumb ( $this->package, 'ModuleBuilder.getContent("module=ModuleBuilder&action=package&package=' . $this->package . '")' ) ; $ajax->addCrumb ( $this->editModule, 'ModuleBuilder.getContent("module=ModuleBuilder&action=module&view_package=' . $this->package . '&view_module=' . $this->editModule . '")' ) ; $ajax->addCrumb ( translate ( $layoutLabel, 'ModuleBuilder' ), 'ModuleBuilder.getContent("module=ModuleBuilder&MB=true&action=wizard&view='.$layoutView.'&view_module=' . $this->editModule . '&view_package=' . $this->package . '")' ) ; $ajax->addCrumb ( $translatedViewType, '' ) ; } else { $ajax->addCrumb ( translate ( 'LBL_STUDIO', 'ModuleBuilder' ), 'ModuleBuilder.main("studio")' ) ; $ajax->addCrumb ( $this->translatedEditModule, 'ModuleBuilder.getContent("module=ModuleBuilder&action=wizard&view_module=' . $this->editModule . '")' ) ; $ajax->addCrumb ( translate ( $layoutLabel, 'ModuleBuilder' ), 'ModuleBuilder.getContent("module=ModuleBuilder&action=wizard&view='.$layoutView.'&view_module=' . $this->editModule . '")' ) ; $ajax->addCrumb ( $translatedViewType, '' ) ; } // set up language files $smarty->assign ( 'language', $parser->getLanguage() ) ; // for sugar_translate in the smarty template $smarty->assign('from_mb',$this->fromModuleBuilder); if ($this->fromModuleBuilder) { $mb = new ModuleBuilder ( ) ; $module = & $mb->getPackageModule ( $this->package, $this->editModule ) ; $smarty->assign('current_mod_strings', $module->getModStrings()); } $ajax->addSection ( 'center', $translatedViewType, $smarty->fetch ( 'modules/ModuleBuilder/tpls/layoutView.tpl' ) ) ; if ($preview) { echo $smarty->fetch ( 'modules/ModuleBuilder/tpls/Preview/layoutView.tpl' ); } else { echo $ajax->getJavascript () ; } } }
yinhm/sugarcrm
modules/ModuleBuilder/views/view.layoutview.php
PHP
agpl-3.0
11,446
package com.google.gson; public enum LongSerializationPolicy { DEFAULT { public final JsonElement serialize(Long l) { return new JsonPrimitive((Number) l); } }, STRING { public final JsonElement serialize(Long l) { return new JsonPrimitive(String.valueOf(l)); } }; public abstract JsonElement serialize(Long l); }
WenbinHou/PKUAutoGateway.Android
Reference/IPGWAndroid/com/google/gson/LongSerializationPolicy.java
Java
agpl-3.0
392
/* ListJS 1.1.1 (www.listjs.com) License (MIT) Copyright (c) 2012 Jonny Strömberg <jonny.stromberg@gmail.com> http://jonnystromberg.com */ ;(function(){ /** * Require the given path. * * @param {String} path * @return {Object} exports * @api public */ function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module._resolving && !module.exports) { var mod = {}; mod.exports = {}; mod.client = mod.component = true; module._resolving = true; module.call(this, mod.exports, require.relative(resolved), mod); delete module._resolving; module.exports = mod.exports; } return module.exports; } /** * Registered modules. */ require.modules = {}; /** * Registered aliases. */ require.aliases = {}; /** * Resolve `path`. * * Lookup: * * - PATH/index.js * - PATH.js * - PATH * * @param {String} path * @return {String} path or null * @api private */ require.resolve = function(path) { if (path.charAt(0) === '/') path = path.slice(1); var paths = [ path, path + '.js', path + '.json', path + '/index.js', path + '/index.json' ]; for (var i = 0; i < paths.length; i++) { var path = paths[i]; if (require.modules.hasOwnProperty(path)) return path; if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; } }; /** * Normalize `path` relative to the current path. * * @param {String} curr * @param {String} path * @return {String} * @api private */ require.normalize = function(curr, path) { var segs = []; if ('.' != path.charAt(0)) return path; curr = curr.split('/'); path = path.split('/'); for (var i = 0; i < path.length; ++i) { if ('..' == path[i]) { curr.pop(); } else if ('.' != path[i] && '' != path[i]) { segs.push(path[i]); } } return curr.concat(segs).join('/'); }; /** * Register module at `path` with callback `definition`. * * @param {String} path * @param {Function} definition * @api private */ require.register = function(path, definition) { require.modules[path] = definition; }; /** * Alias a module definition. * * @param {String} from * @param {String} to * @api private */ require.alias = function(from, to) { if (!require.modules.hasOwnProperty(from)) { throw new Error('Failed to alias "' + from + '", it does not exist'); } require.aliases[to] = from; }; /** * Return a require function relative to the `parent` path. * * @param {String} parent * @return {Function} * @api private */ require.relative = function(parent) { var p = require.normalize(parent, '..'); /** * lastIndexOf helper. */ function lastIndexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * The relative require() itself. */ function localRequire(path) { var resolved = localRequire.resolve(path); return require(resolved, parent, path); } /** * Resolve relative to the parent. */ localRequire.resolve = function(path) { var c = path.charAt(0); if ('/' == c) return path.slice(1); if ('.' == c) return require.normalize(p, path); // resolve deps by returning // the dep in the nearest "deps" // directory var segs = parent.split('/'); var i = lastIndexOf(segs, 'deps') + 1; if (!i) i = 0; path = segs.slice(0, i + 1).join('/') + '/deps/' + path; return path; }; /** * Check if module is defined at `path`. */ localRequire.exists = function(path) { return require.modules.hasOwnProperty(localRequire.resolve(path)); }; return localRequire; }; require.register("component-classes/index.js", function(exports, require, module){ /** * Module dependencies. */ var index = require('indexof'); /** * Whitespace regexp. */ var re = /\s+/; /** * toString reference. */ var toString = Object.prototype.toString; /** * Wrap `el` in a `ClassList`. * * @param {Element} el * @return {ClassList} * @api public */ module.exports = function(el){ return new ClassList(el); }; /** * Initialize a new ClassList for `el`. * * @param {Element} el * @api private */ function ClassList(el) { if (!el) throw new Error('A DOM element reference is required'); this.el = el; this.list = el.classList; } /** * Add class `name` if not already present. * * @param {String} name * @return {ClassList} * @api public */ ClassList.prototype.add = function(name){ // classList if (this.list) { this.list.add(name); return this; } // fallback var arr = this.array(); var i = index(arr, name); if (!~i) arr.push(name); this.el.className = arr.join(' '); return this; }; /** * Remove class `name` when present, or * pass a regular expression to remove * any which match. * * @param {String|RegExp} name * @return {ClassList} * @api public */ ClassList.prototype.remove = function(name){ if ('[object RegExp]' == toString.call(name)) { return this.removeMatching(name); } // classList if (this.list) { this.list.remove(name); return this; } // fallback var arr = this.array(); var i = index(arr, name); if (~i) arr.splice(i, 1); this.el.className = arr.join(' '); return this; }; /** * Remove all classes matching `re`. * * @param {RegExp} re * @return {ClassList} * @api private */ ClassList.prototype.removeMatching = function(re){ var arr = this.array(); for (var i = 0; i < arr.length; i++) { if (re.test(arr[i])) { this.remove(arr[i]); } } return this; }; /** * Toggle class `name`, can force state via `force`. * * For browsers that support classList, but do not support `force` yet, * the mistake will be detected and corrected. * * @param {String} name * @param {Boolean} force * @return {ClassList} * @api public */ ClassList.prototype.toggle = function(name, force){ // classList if (this.list) { if ("undefined" !== typeof force) { if (force !== this.list.toggle(name, force)) { this.list.toggle(name); // toggle again to correct } } else { this.list.toggle(name); } return this; } // fallback if ("undefined" !== typeof force) { if (!force) { this.remove(name); } else { this.add(name); } } else { if (this.has(name)) { this.remove(name); } else { this.add(name); } } return this; }; /** * Return an array of classes. * * @return {Array} * @api public */ ClassList.prototype.array = function(){ var str = this.el.className.replace(/^\s+|\s+$/g, ''); var arr = str.split(re); if ('' === arr[0]) arr.shift(); return arr; }; /** * Check if class `name` is present. * * @param {String} name * @return {ClassList} * @api public */ ClassList.prototype.has = ClassList.prototype.contains = function(name){ return this.list ? this.list.contains(name) : !! ~index(this.array(), name); }; }); require.register("segmentio-extend/index.js", function(exports, require, module){ module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }); require.register("component-indexof/index.js", function(exports, require, module){ module.exports = function(arr, obj){ if (arr.indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; }); require.register("component-event/index.js", function(exports, require, module){ var bind = window.addEventListener ? 'addEventListener' : 'attachEvent', unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent', prefix = bind !== 'addEventListener' ? 'on' : ''; /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, type, fn, capture){ el[bind](prefix + type, fn, capture || false); return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.unbind = function(el, type, fn, capture){ el[unbind](prefix + type, fn, capture || false); return fn; }; }); require.register("javve-to-array/index.js", function(exports, require, module){ /** * Convert an array-like object into an `Array`. * If `collection` is already an `Array`, then will return a clone of `collection`. * * @param {Array | Mixed} collection An `Array` or array-like object to convert e.g. `arguments` or `NodeList` * @return {Array} Naive conversion of `collection` to a new `Array`. * @api public */ module.exports = function toArray(collection) { if (typeof collection === 'undefined') return [] if (collection === null) return [null] if (collection === window) return [window] if (typeof collection === 'string') return [collection] if (collection instanceof Array) return collection if (typeof collection.length != 'number') return [collection] if (typeof collection === 'function') return [collection] var arr = [] for (var i = 0; i < collection.length; i++) { if (Object.prototype.hasOwnProperty.call(collection, i) || i in collection) { arr.push(collection[i]) } } if (!arr.length) return [] return arr } }); require.register("javve-events/index.js", function(exports, require, module){ var events = require('event'), toArray = require('to-array'); /** * Bind `el` event `type` to `fn`. * * @param {Element} el, NodeList, HTMLCollection or Array * @param {String} type * @param {Function} fn * @param {Boolean} capture * @api public */ exports.bind = function(el, type, fn, capture){ el = toArray(el); for ( var i = 0; i < el.length; i++ ) { events.bind(el[i], type, fn, capture); } }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el, NodeList, HTMLCollection or Array * @param {String} type * @param {Function} fn * @param {Boolean} capture * @api public */ exports.unbind = function(el, type, fn, capture){ el = toArray(el); for ( var i = 0; i < el.length; i++ ) { events.unbind(el[i], type, fn, capture); } }; }); require.register("javve-get-by-class/index.js", function(exports, require, module){ /** * Find all elements with class `className` inside `container`. * Use `single = true` to increase performance in older browsers * when only one element is needed. * * @param {String} className * @param {Element} container * @param {Boolean} single * @api public */ module.exports = (function() { if (document.getElementsByClassName) { return function(container, className, single) { if (single) { return container.getElementsByClassName(className)[0]; } else { return container.getElementsByClassName(className); } }; } else if (document.querySelector) { return function(container, className, single) { className = '.' + className; if (single) { return container.querySelector(className); } else { return container.querySelectorAll(className); } }; } else { return function(container, className, single) { var classElements = [], tag = '*'; if (container == null) { container = document; } var els = container.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)"+className+"(\\s|$)"); for (var i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { if (single) { return els[i]; } else { classElements[j] = els[i]; j++; } } } return classElements; }; } })(); }); require.register("javve-get-attribute/index.js", function(exports, require, module){ /** * Return the value for `attr` at `element`. * * @param {Element} el * @param {String} attr * @api public */ module.exports = function(el, attr) { var result = (el.getAttribute && el.getAttribute(attr)) || null; if( !result ) { var attrs = el.attributes; var length = attrs.length; for(var i = 0; i < length; i++) { if (attr[i] !== undefined) { if(attr[i].nodeName === attr) { result = attr[i].nodeValue; } } } } return result; } }); require.register("javve-natural-sort/index.js", function(exports, require, module){ /* * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license * Author: Jim Palmer (based on chunking idea from Dave Koelle) */ module.exports = function(a, b, options) { var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi, sre = /(^[ ]*|[ ]*$)/g, dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, hre = /^0x[0-9a-f]+$/i, ore = /^0/, options = options || {}, i = function(s) { return options.insensitive && (''+s).toLowerCase() || ''+s }, // convert all to strings strip whitespace x = i(a).replace(sre, '') || '', y = i(b).replace(sre, '') || '', // chunk/tokenize xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), // numeric, hex or date detection xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)), yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null, oFxNcL, oFyNcL, mult = options.desc ? -1 : 1; // first try and sort Hex codes or Dates if (yD) if ( xD < yD ) return -1 * mult; else if ( xD > yD ) return 1 * mult; // natural sorting through split numeric strings and default strings for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { // find floats not starting with '0', string or 0 if not defined (Clint Priest) oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; // handle numeric vs string comparison - number < string - (Kyle Adams) if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; } // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' else if (typeof oFxNcL !== typeof oFyNcL) { oFxNcL += ''; oFyNcL += ''; } if (oFxNcL < oFyNcL) return -1 * mult; if (oFxNcL > oFyNcL) return 1 * mult; } return 0; }; /* var defaultSort = getSortFunction(); module.exports = function(a, b, options) { if (arguments.length == 1) { options = a; return getSortFunction(options); } else { return defaultSort(a,b); } } */ }); require.register("javve-to-string/index.js", function(exports, require, module){ module.exports = function(s) { s = (s === undefined) ? "" : s; s = (s === null) ? "" : s; s = s.toString(); return s; }; }); require.register("component-type/index.js", function(exports, require, module){ /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object Error]': return 'error'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val !== val) return 'nan'; if (val && val.nodeType === 1) return 'element'; return typeof val.valueOf(); }; }); require.register("list.js/index.js", function(exports, require, module){ /* ListJS with beta 1.0.0 By Jonny Strömberg (www.jonnystromberg.com, www.listjs.com) */ (function( window, undefined ) { "use strict"; var document = window.document, getByClass = require('get-by-class'), extend = require('extend'), indexOf = require('indexof'); var List = function(id, options, values) { var self = this, init, Item = require('./src/item')(self), addAsync = require('./src/add-async')(self), parse = require('./src/parse')(self); init = { start: function() { self.listClass = "list"; self.searchClass = "search"; self.sortClass = "sort"; self.page = 200; self.i = 1; self.items = []; self.visibleItems = []; self.matchingItems = []; self.searched = false; self.filtered = false; self.handlers = { 'updated': [] }; self.plugins = {}; self.helpers = { getByClass: getByClass, extend: extend, indexOf: indexOf }; extend(self, options); self.listContainer = (typeof(id) === 'string') ? document.getElementById(id) : id; if (!self.listContainer) { return; } self.list = getByClass(self.listContainer, self.listClass, true); self.templater = require('./src/templater')(self); self.search = require('./src/search')(self); self.filter = require('./src/filter')(self); self.sort = require('./src/sort')(self); this.items(); self.update(); this.plugins(); }, items: function() { parse(self.list); if (values !== undefined) { self.add(values); } }, plugins: function() { for (var i = 0; i < self.plugins.length; i++) { var plugin = self.plugins[i]; self[plugin.name] = plugin; plugin.init(self); } } }; /* * Add object to list */ this.add = function(values, callback) { if (callback) { addAsync(values, callback); return; } var added = [], notCreate = false; if (values[0] === undefined){ values = [values]; } for (var i = 0, il = values.length; i < il; i++) { var item = null; if (values[i] instanceof Item) { item = values[i]; item.reload(); } else { notCreate = (self.items.length > self.page) ? true : false; item = new Item(values[i], undefined, notCreate); } self.items.push(item); added.push(item); } self.update(); return added; }; this.show = function(i, page) { this.i = i; this.page = page; self.update(); return self; }; /* Removes object from list. * Loops through the list and removes objects where * property "valuename" === value */ this.remove = function(valueName, value, options) { var found = 0; for (var i = 0, il = self.items.length; i < il; i++) { if (self.items[i].values()[valueName] == value) { self.templater.remove(self.items[i], options); self.items.splice(i,1); il--; i--; found++; } } self.update(); return found; }; /* Gets the objects in the list which * property "valueName" === value */ this.get = function(valueName, value) { var matchedItems = []; for (var i = 0, il = self.items.length; i < il; i++) { var item = self.items[i]; if (item.values()[valueName] == value) { matchedItems.push(item); } } return matchedItems; }; /* * Get size of the list */ this.size = function() { return self.items.length; }; /* * Removes all items from the list */ this.clear = function() { self.templater.clear(); self.items = []; return self; }; this.on = function(event, callback) { self.handlers[event].push(callback); return self; }; this.off = function(event, callback) { var e = self.handlers[event]; var index = indexOf(e, callback); if (index > -1) { e.splice(index, 1); } return self; }; this.trigger = function(event) { var i = self.handlers[event].length; while(i--) { self.handlers[event][i](self); } return self; }; this.reset = { filter: function() { var is = self.items, il = is.length; while (il--) { is[il].filtered = false; } return self; }, search: function() { var is = self.items, il = is.length; while (il--) { is[il].found = false; } return self; } }; this.update = function() { var is = self.items, il = is.length; self.visibleItems = []; self.matchingItems = []; self.templater.clear(); for (var i = 0; i < il; i++) { if (is[i].matching() && ((self.matchingItems.length+1) >= self.i && self.visibleItems.length < self.page)) { is[i].show(); self.visibleItems.push(is[i]); self.matchingItems.push(is[i]); } else if (is[i].matching()) { self.matchingItems.push(is[i]); is[i].hide(); } else { is[i].hide(); } } self.trigger('updated'); return self; }; init.start(); }; module.exports = List; })(window); }); require.register("list.js/src/search.js", function(exports, require, module){ var events = require('events'), getByClass = require('get-by-class'), toString = require('to-string'); module.exports = function(list) { var item, text, columns, searchString, customSearch; var prepare = { resetList: function() { list.i = 1; list.templater.clear(); customSearch = undefined; }, setOptions: function(args) { if (args.length == 2 && args[1] instanceof Array) { columns = args[1]; } else if (args.length == 2 && typeof(args[1]) == "function") { customSearch = args[1]; } else if (args.length == 3) { columns = args[1]; customSearch = args[2]; } }, setColumns: function() { columns = (columns === undefined) ? prepare.toArray(list.items[0].values()) : columns; }, setSearchString: function(s) { s = toString(s).toLowerCase(); s = s.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&"); // Escape regular expression characters searchString = s; }, toArray: function(values) { var tmpColumn = []; for (var name in values) { tmpColumn.push(name); } return tmpColumn; } }; var search = { list: function() { for (var k = 0, kl = list.items.length; k < kl; k++) { search.item(list.items[k]); } }, item: function(item) { item.found = false; for (var j = 0, jl = columns.length; j < jl; j++) { if (search.values(item.values(), columns[j])) { item.found = true; return; } } }, values: function(values, column) { if (values.hasOwnProperty(column)) { text = toString(values[column]).toLowerCase(); if ((searchString !== "") && (text.search(searchString) > -1)) { return true; } } return false; }, reset: function() { list.reset.search(); list.searched = false; } }; var searchMethod = function(str) { list.trigger('searchStart'); prepare.resetList(); prepare.setSearchString(str); prepare.setOptions(arguments); // str, cols|searchFunction, searchFunction prepare.setColumns(); if (searchString === "" ) { search.reset(); } else { list.searched = true; if (customSearch) { customSearch(searchString, columns); } else { search.list(); } } list.update(); list.trigger('searchComplete'); return list.visibleItems; }; list.handlers.searchStart = list.handlers.searchStart || []; list.handlers.searchComplete = list.handlers.searchComplete || []; events.bind(getByClass(list.listContainer, list.searchClass), 'keyup', function(e) { var target = e.target || e.srcElement; // IE have srcElement searchMethod(target.value); }); list.helpers.toString = toString; return searchMethod; }; }); require.register("list.js/src/sort.js", function(exports, require, module){ var naturalSort = require('natural-sort'), classes = require('classes'), events = require('events'), getByClass = require('get-by-class'), getAttribute = require('get-attribute'); module.exports = function(list) { list.sortFunction = list.sortFunction || function(itemA, itemB, options) { options.desc = options.order == "desc" ? true : false; // Natural sort uses this format return naturalSort(itemA.values()[options.valueName], itemB.values()[options.valueName], options); }; var buttons = { els: undefined, clear: function() { for (var i = 0, il = buttons.els.length; i < il; i++) { classes(buttons.els[i]).remove('asc'); classes(buttons.els[i]).remove('desc'); } }, getOrder: function(btn) { var predefinedOrder = getAttribute(btn, 'data-order'); if (predefinedOrder == "asc" || predefinedOrder == "desc") { return predefinedOrder; } else if (classes(btn).has('desc')) { return "asc"; } else if (classes(btn).has('asc')) { return "desc"; } else { return "asc"; } }, getInSensitive: function(btn, options) { var insensitive = getAttribute(btn, 'data-insensitive'); if (insensitive === "true") { options.insensitive = true; } else { options.insensitive = false; } }, setOrder: function(options) { for (var i = 0, il = buttons.els.length; i < il; i++) { var btn = buttons.els[i]; if (getAttribute(btn, 'data-sort') !== options.valueName) { continue; } var predefinedOrder = getAttribute(btn, 'data-order'); if (predefinedOrder == "asc" || predefinedOrder == "desc") { if (predefinedOrder == options.order) { classes(btn).add(options.order); } } else { classes(btn).add(options.order); } } } }; var sort = function() { list.trigger('sortStart'); options = {}; var target = arguments[0].currentTarget || arguments[0].srcElement || undefined; if (target) { options.valueName = getAttribute(target, 'data-sort'); buttons.getInSensitive(target, options); options.order = buttons.getOrder(target); } else { options = arguments[1] || options; options.valueName = arguments[0]; options.order = options.order || "asc"; options.insensitive = (typeof options.insensitive == "undefined") ? true : options.insensitive; } buttons.clear(); buttons.setOrder(options); options.sortFunction = options.sortFunction || list.sortFunction; list.items.sort(function(a, b) { return options.sortFunction(a, b, options); }); list.update(); list.trigger('sortComplete'); }; // Add handlers list.handlers.sortStart = list.handlers.sortStart || []; list.handlers.sortComplete = list.handlers.sortComplete || []; buttons.els = getByClass(list.listContainer, list.sortClass); events.bind(buttons.els, 'click', sort); list.on('searchStart', buttons.clear); list.on('filterStart', buttons.clear); // Helpers list.helpers.classes = classes; list.helpers.naturalSort = naturalSort; list.helpers.events = events; list.helpers.getAttribute = getAttribute; return sort; }; }); require.register("list.js/src/item.js", function(exports, require, module){ module.exports = function(list) { return function(initValues, element, notCreate) { var item = this; this._values = {}; this.found = false; // Show if list.searched == true and this.found == true this.filtered = false;// Show if list.filtered == true and this.filtered == true var init = function(initValues, element, notCreate) { if (element === undefined) { if (notCreate) { item.values(initValues, notCreate); } else { item.values(initValues); } } else { item.elm = element; var values = list.templater.get(item, initValues); item.values(values); } }; this.values = function(newValues, notCreate) { if (newValues !== undefined) { for(var name in newValues) { item._values[name] = newValues[name]; } if (notCreate !== true) { list.templater.set(item, item.values()); } } else { return item._values; } }; this.show = function() { list.templater.show(item); }; this.hide = function() { list.templater.hide(item); }; this.matching = function() { return ( (list.filtered && list.searched && item.found && item.filtered) || (list.filtered && !list.searched && item.filtered) || (!list.filtered && list.searched && item.found) || (!list.filtered && !list.searched) ); }; this.visible = function() { return (item.elm.parentNode == list.list) ? true : false; }; init(initValues, element, notCreate); }; }; }); require.register("list.js/src/templater.js", function(exports, require, module){ var getByClass = require('get-by-class'); var Templater = function(list) { var itemSource = getItemSource(list.item), templater = this; function getItemSource(item) { if (item === undefined) { var nodes = list.list.childNodes, items = []; for (var i = 0, il = nodes.length; i < il; i++) { // Only textnodes have a data attribute if (nodes[i].data === undefined) { return nodes[i]; } } return null; } else if (item.indexOf("<") !== -1) { // Try create html element of list, do not work for tables!! var div = document.createElement('div'); div.innerHTML = item; return div.firstChild; } else { return document.getElementById(list.item); } } /* Get values from element */ this.get = function(item, valueNames) { templater.create(item); var values = {}; for(var i = 0, il = valueNames.length; i < il; i++) { var elm = getByClass(item.elm, valueNames[i], true); values[valueNames[i]] = elm ? elm.innerHTML : ""; } return values; }; /* Sets values at element */ this.set = function(item, values) { if (!templater.create(item)) { for(var v in values) { if (values.hasOwnProperty(v)) { // TODO speed up if possible var elm = getByClass(item.elm, v, true); if (elm) { /* src attribute for image tag & text for other tags */ if (elm.tagName === "IMG" && values[v] !== "") { elm.src = values[v]; } else { elm.innerHTML = values[v]; } } } } } }; this.create = function(item) { if (item.elm !== undefined) { return false; } /* If item source does not exists, use the first item in list as source for new items */ var newItem = itemSource.cloneNode(true); newItem.removeAttribute('id'); item.elm = newItem; templater.set(item, item.values()); return true; }; this.remove = function(item) { list.list.removeChild(item.elm); }; this.show = function(item) { templater.create(item); list.list.appendChild(item.elm); }; this.hide = function(item) { if (item.elm !== undefined && item.elm.parentNode === list.list) { list.list.removeChild(item.elm); } }; this.clear = function() { /* .innerHTML = ''; fucks up IE */ if (list.list.hasChildNodes()) { while (list.list.childNodes.length >= 1) { list.list.removeChild(list.list.firstChild); } } }; }; module.exports = function(list) { return new Templater(list); }; }); require.register("list.js/src/filter.js", function(exports, require, module){ module.exports = function(list) { // Add handlers list.handlers.filterStart = list.handlers.filterStart || []; list.handlers.filterComplete = list.handlers.filterComplete || []; return function(filterFunction) { list.trigger('filterStart'); list.i = 1; // Reset paging list.reset.filter(); if (filterFunction === undefined) { list.filtered = false; } else { list.filtered = true; var is = list.items; for (var i = 0, il = is.length; i < il; i++) { var item = is[i]; if (filterFunction(item)) { item.filtered = true; } else { item.filtered = false; } } } list.update(); list.trigger('filterComplete'); return list.visibleItems; }; }; }); require.register("list.js/src/add-async.js", function(exports, require, module){ module.exports = function(list) { return function(values, callback, items) { var valuesToAdd = values.splice(0, 100); items = items || []; items = items.concat(list.add(valuesToAdd)); if (values.length > 0) { setTimeout(function() { addAsync(values, callback, items); }, 10); } else { list.update(); callback(items); } }; }; }); require.register("list.js/src/parse.js", function(exports, require, module){ module.exports = function(list) { var Item = require('./item')(list); var getChildren = function(parent) { var nodes = parent.childNodes, items = []; for (var i = 0, il = nodes.length; i < il; i++) { // Only textnodes have a data attribute if (nodes[i].data === undefined) { items.push(nodes[i]); } } return items; }; var parse = function(itemElements, valueNames) { for (var i = 0, il = itemElements.length; i < il; i++) { list.items.push(new Item(valueNames, itemElements[i])); } }; var parseAsync = function(itemElements, valueNames) { var itemsToIndex = itemElements.splice(0, 100); // TODO: If < 100 items, what happens in IE etc? parse(itemsToIndex, valueNames); if (itemElements.length > 0) { setTimeout(function() { init.items.indexAsync(itemElements, valueNames); }, 10); } else { list.update(); // TODO: Add indexed callback } }; return function() { var itemsToIndex = getChildren(list.list), valueNames = list.valueNames; if (list.indexAsync) { parseAsync(itemsToIndex, valueNames); } else { parse(itemsToIndex, valueNames); } }; }; }); require.alias("component-classes/index.js", "list.js/deps/classes/index.js"); require.alias("component-classes/index.js", "classes/index.js"); require.alias("component-indexof/index.js", "component-classes/deps/indexof/index.js"); require.alias("segmentio-extend/index.js", "list.js/deps/extend/index.js"); require.alias("segmentio-extend/index.js", "extend/index.js"); require.alias("component-indexof/index.js", "list.js/deps/indexof/index.js"); require.alias("component-indexof/index.js", "indexof/index.js"); require.alias("javve-events/index.js", "list.js/deps/events/index.js"); require.alias("javve-events/index.js", "events/index.js"); require.alias("component-event/index.js", "javve-events/deps/event/index.js"); require.alias("javve-to-array/index.js", "javve-events/deps/to-array/index.js"); require.alias("javve-get-by-class/index.js", "list.js/deps/get-by-class/index.js"); require.alias("javve-get-by-class/index.js", "get-by-class/index.js"); require.alias("javve-get-attribute/index.js", "list.js/deps/get-attribute/index.js"); require.alias("javve-get-attribute/index.js", "get-attribute/index.js"); require.alias("javve-natural-sort/index.js", "list.js/deps/natural-sort/index.js"); require.alias("javve-natural-sort/index.js", "natural-sort/index.js"); require.alias("javve-to-string/index.js", "list.js/deps/to-string/index.js"); require.alias("javve-to-string/index.js", "list.js/deps/to-string/index.js"); require.alias("javve-to-string/index.js", "to-string/index.js"); require.alias("javve-to-string/index.js", "javve-to-string/index.js"); require.alias("component-type/index.js", "list.js/deps/type/index.js"); require.alias("component-type/index.js", "type/index.js"); if (typeof exports == "object") { module.exports = require("list.js"); } else if (typeof define == "function" && define.amd) { define(function(){ return require("list.js"); }); } else { this["List"] = require("list.js"); }})();
studentenportal/web
apps/front/static/js/list.js
JavaScript
agpl-3.0
40,148
app.controller('LeadStatusEditCtrl', ['$scope', 'Auth', 'Leadstatus', function ($scope, Auth, Leadstatus) { $("ul.page-sidebar-menu li").removeClass("active"); $("#id_LeadStatus").addClass("active"); $scope.isSignedIn = false; $scope.immediateFailed = false; $scope.nbLoads = 0; $scope.isLoading = false; $scope.isSelectedAll = false; $scope.nbrSelected = 0; $scope.selectStatus = function (status) { status.isSelected = !status.isSelected; if (status.isSelected) $scope.nbrSelected++; else $scope.nbrSelected--; }; $scope.$watch('isSelectedAll', function (newValue, oldValue) { if (newValue) $scope.nbrSelected = $scope.leadstatuses.length; else $scope.nbrSelected = 0; angular.forEach($scope.leadstatuses, function (value, key) { $scope.leadstatuses[key].isSelected = newValue; }); }); $scope.deleteSelected = function () { angular.forEach($scope.leadstatuses, function (value, index) { if (value.isSelected) { $scope.deletleadstatus(value); } }); }; $scope.inProcess = function (varBool, message) { if (varBool) { $scope.nbLoads += 1; if ($scope.nbLoads == 1) { $scope.isLoading = true; } ; } else { $scope.nbLoads -= 1; if ($scope.nbLoads == 0) { $scope.isLoading = false; } ; } ; }; $scope.apply = function () { if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') { $scope.$apply(); } return false; }; // What to do after authentication $scope.runTheProcess = function () { Leadstatus.list($scope, {}); ga('send', 'pageview', '/admin/lead_status'); }; // We need to call this to refresh token when user credentials are invalid $scope.refreshToken = function () { Auth.refreshToken(); }; $scope.addLeadsStatusModal = function () { $("#addLeadsStatusModal").modal('show') }; $scope.saveLeadStatus = function (lead) { var params = { 'status': lead.status }; Leadstatus.insert($scope, params); $('#addLeadsStatusModal').modal('hide'); $scope.lead.status = ''; }; $scope.editleadstatus = function (leadStatus) { $scope.leadstat = $scope.leadstat || {}; $scope.leadstat.status = leadStatus.status; $scope.leadstat.id = leadStatus.id; $('#EditLeadStatus').modal('show'); }; $scope.updateLeadstatus = function (stat) { var params = { 'id': $scope.leadstat.id, 'status': stat.status }; Leadstatus.update($scope, params) $('#EditLeadStatus').modal('hide'); }; //HKA 22.12.2013 Delete Lead status $scope.deletleadstatus = function (leadstat) { var params = {'entityKey': leadstat.entityKey}; Leadstatus.delete($scope, params); }; $scope.listleadstatus = function () { Leadstatus.list($scope, {}); }; Auth.init($scope); }]);
ioGrow/iogrowCRM
static/app/scripts/controllers/admin/LeadStatusEditController.js
JavaScript
agpl-3.0
3,220
import { Component, Inject } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { BehaviorSubject } from 'rxjs'; import { Gap, PlaybackRange } from '../client'; import { YamcsService } from '../core/services/YamcsService'; import { Option } from '../shared/forms/Select'; import * as utils from '../shared/utils'; @Component({ selector: 'app-request-playback-dialog', templateUrl: './RequestPlaybackDialog.html', }) export class RequestPlaybackDialog { gaps: Gap[]; linkOptions$ = new BehaviorSubject<Option[]>([]); form = new FormGroup({ mergeTolerance: new FormControl(30), link: new FormControl('', Validators.required) }); constructor( private dialogRef: MatDialogRef<RequestPlaybackDialog>, private yamcs: YamcsService, @Inject(MAT_DIALOG_DATA) readonly data: any, ) { this.gaps = this.data.gaps; this.yamcs.yamcsClient.getLinks(yamcs.instance!).then(links => { const linkOptions = []; for (const link of links) { if (link.type.indexOf('DassPlaybackPacketProvider') !== -1) { linkOptions.push({ id: link.name, label: link.name, }); } } this.linkOptions$.next(linkOptions); if (linkOptions.length) { this.form.get('link')!.setValue(linkOptions[0].id); } }); } sendRequest() { const ranges = []; const rangeCache = new Map<number, PlaybackRange>(); const tolerance = this.form.value['mergeTolerance'] * 60 * 1000; for (const gap of this.gaps) { const prev = rangeCache.get(gap.apid); if (prev && (this.toMillis(gap.start) - this.toMillis(prev.stop)) < tolerance) { prev.stop = gap.stop; } else { const range = { apid: gap.apid, start: gap.start, stop: gap.stop, }; ranges.push(range); rangeCache.set(gap.apid, range); } } this.dialogRef.close({ link: this.form.value['link'], ranges, }); } private toMillis(dateString: string) { return utils.toDate(dateString).getTime(); } }
m-sc/yamcs
yamcs-web/src/main/webapp/src/app/gaps/RequestPlaybackDialog.ts
TypeScript
agpl-3.0
2,209
package de.hub.cses.ces.jsf.bean.game.play; /* * #%L * CES-Game * %% * Copyright (C) 2015 Humboldt-Universität zu Berlin, * Department of Computer Science, * Research Group "Computer Science Education / Computer Science and Society" * Sebastian Gross <sebastian.gross@hu-berlin.de> * Sven Strickroth <sven.strickroth@hu-berlin.de> * %% * 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 General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ import de.hub.cses.ces.entity.production.Production; import de.hub.cses.ces.entity.production.ProductionPlan; import de.hub.cses.ces.jsf.bean.game.PlayBean; import de.hub.cses.ces.jsf.config.GamePlayComponent; import de.hub.cses.ces.service.persistence.production.ProductionFacade; import de.hub.cses.ces.service.persistence.production.ProductionPlanFacade; import de.hub.cses.ces.util.ComponentUpdateUtil; import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; /** * * @author Sebastian Gross <sebastian.gross@hu-berlin.de> */ @Named("ProductionPanel") @ViewScoped public class ProductionPanel implements Serializable { @Inject @SuppressWarnings("NonConstantLogger") private transient Logger logger; @Inject private PlayBean gamePlay; @Inject private ComponentUpdateUtil componentUpdateUtil; @EJB private ProductionFacade productionFacade; @EJB private ProductionPlanFacade productionPlanFacade; /** * */ @PostConstruct public void init() { } /** * * @return */ public Production getProduction() { return gamePlay.getCooperator().getCompany().getProduction(); } /** * * @param event * @throws Exception */ public void edit(org.primefaces.event.RowEditEvent event) throws Exception { ProductionPlan productionPlan = (ProductionPlan) event.getObject(); try { logger.log(Level.INFO, "edit production plan {0}", (productionPlan != null) ? productionPlan.getId() : null); logger.log(Level.INFO, "workforce {0}", (productionPlan != null) ? productionPlan.getWorkforce() : null); productionPlanFacade.edit(productionPlan); } catch (Exception ex) { Exception ne = (Exception) ex.getCause(); if ("org.eclipse.persistence.exceptions.OptimisticLockException".equals(ne.getClass().getName()) || "javax.persistence.OptimisticLockException".equals(ne.getClass().getName())) { throw new javax.persistence.OptimisticLockException("fehler..."); } } finally { componentUpdateUtil.companyUpdate(gamePlay.getCooperator().getCompany().getId(), GamePlayComponent.PRODUCTION); } } /** * * @param event */ public void cancel(org.primefaces.event.RowEditEvent event) { //gamePlay.updateData(); } }
sozialemedienprojekt/ces-game
src/main/java/de/hub/cses/ces/jsf/bean/game/play/ProductionPanel.java
Java
agpl-3.0
3,632
import React, { createRef, useState } from 'react'; import { css } from '@emotion/css'; import { Button, ButtonGroup, useStyles2 } from '@grafana/ui'; import { GrafanaTheme2 } from '@grafana/data'; import { FocusScope } from '@react-aria/focus'; import { useDialog } from '@react-aria/dialog'; import { useOverlay } from '@react-aria/overlays'; import { MediaType, PickerTabType, ResourceFolderName } from '../types'; import { FolderPickerTab } from './FolderPickerTab'; import { URLPickerTab } from './URLPickerTab'; interface Props { value?: string; //img/icons/unicons/0-plus.svg onChange: (value?: string) => void; mediaType: MediaType; folderName: ResourceFolderName; } export const ResourcePickerPopover = (props: Props) => { const { value, onChange, mediaType, folderName } = props; const styles = useStyles2(getStyles); const onClose = () => { onChange(value); }; const ref = createRef<HTMLElement>(); const { dialogProps } = useDialog({}, ref); const { overlayProps } = useOverlay({ onClose, isDismissable: true, isOpen: true }, ref); const [newValue, setNewValue] = useState<string>(value ?? ''); const [activePicker, setActivePicker] = useState<PickerTabType>(PickerTabType.Folder); const getTabClassName = (tabName: PickerTabType) => { return `${styles.resourcePickerPopoverTab} ${activePicker === tabName && styles.resourcePickerPopoverActiveTab}`; }; const renderFolderPicker = () => ( <FolderPickerTab value={value} mediaType={mediaType} folderName={folderName} newValue={newValue} setNewValue={setNewValue} /> ); const renderURLPicker = () => <URLPickerTab newValue={newValue} setNewValue={setNewValue} mediaType={mediaType} />; const renderPicker = () => { switch (activePicker) { case PickerTabType.Folder: return renderFolderPicker(); case PickerTabType.URL: return renderURLPicker(); default: return renderFolderPicker(); } }; return ( <FocusScope contain autoFocus restoreFocus> <section ref={ref} {...overlayProps} {...dialogProps}> <div className={styles.resourcePickerPopover}> <div className={styles.resourcePickerPopoverTabs}> <button className={getTabClassName(PickerTabType.Folder)} onClick={() => setActivePicker(PickerTabType.Folder)} > Folder </button> <button className={getTabClassName(PickerTabType.URL)} onClick={() => setActivePicker(PickerTabType.URL)}> URL </button> </div> <div className={styles.resourcePickerPopoverContent}> {renderPicker()} <ButtonGroup className={styles.buttonGroup}> <Button className={styles.button} variant={'secondary'} onClick={() => onClose()}> Cancel </Button> <Button className={styles.button} variant={newValue && newValue !== value ? 'primary' : 'secondary'} onClick={() => onChange(newValue)} > Select </Button> </ButtonGroup> </div> </div> </section> </FocusScope> ); }; const getStyles = (theme: GrafanaTheme2) => ({ resourcePickerPopover: css` border-radius: ${theme.shape.borderRadius()}; box-shadow: ${theme.shadows.z3}; background: ${theme.colors.background.primary}; border: 1px solid ${theme.colors.border.medium}; `, resourcePickerPopoverTab: css` width: 50%; text-align: center; padding: ${theme.spacing(1, 0)}; background: ${theme.colors.background.secondary}; color: ${theme.colors.text.secondary}; font-size: ${theme.typography.bodySmall.fontSize}; cursor: pointer; border: none; &:focus:not(:focus-visible) { outline: none; box-shadow: none; } :focus-visible { position: relative; } `, resourcePickerPopoverActiveTab: css` color: ${theme.colors.text.primary}; font-weight: ${theme.typography.fontWeightMedium}; background: ${theme.colors.background.primary}; `, resourcePickerPopoverContent: css` width: 315px; font-size: ${theme.typography.bodySmall.fontSize}; min-height: 184px; padding: ${theme.spacing(1)}; display: flex; flex-direction: column; `, resourcePickerPopoverTabs: css` display: flex; width: 100%; border-radius: ${theme.shape.borderRadius()} ${theme.shape.borderRadius()} 0 0; `, buttonGroup: css` align-self: center; flex-direction: row; `, button: css` margin: 12px 20px 5px; `, });
grafana/grafana
public/app/features/dimensions/editors/ResourcePickerPopover.tsx
TypeScript
agpl-3.0
4,688
import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import SPELLS from 'common/SPELLS'; import { formatThousands } from 'common/format'; import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY'; import Statistic from 'parser/ui/Statistic'; import BoringSpellValueText from 'parser/ui/BoringSpellValueText'; import ItemDamageDone from 'parser/ui/ItemDamageDone'; import DemoPets from '../pets/DemoPets'; const BONUS_DAMAGE_PER_PET = 0.04; const MAX_TRAVEL_TIME = 3000; // Shadow Bolt is the slowest, takes around 2 seconds to land from max distance, add a little more to account for target movement const debug = false; /* Sacrificed Souls: Shadow Bolt and Demonbolt deal 5% additional damage per demon you have summoned. */ class SacrificedSouls extends Analyzer { get totalBonusDamage() { return this._shadowBoltDamage + this._demonboltDamage; } static dependencies = { demoPets: DemoPets, }; _shadowBoltDamage = 0; _demonboltDamage = 0; _queue = []; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.SACRIFICED_SOULS_TALENT.id); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleCast); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleDamage); } // essentially same snapshotting mechanic as in Destruction's Eradication handleCast(event) { const bonus = this.demoPets.getPetCount() * BONUS_DAMAGE_PER_PET; this._queue.push({ timestamp: event.timestamp, spellId: event.ability.guid, targetID: event.targetID, targetInstance: event.targetInstance, bonus, }); debug && this.log('Pushed a cast into queue', JSON.parse(JSON.stringify(this._queue))); } handleDamage(event) { // filter out old casts if there are any this._queue = this._queue.filter(cast => cast.timestamp > (event.timestamp - MAX_TRAVEL_TIME)); const castIndex = this._queue .findIndex(cast => cast.targetID === event.targetID && cast.targetInstance === event.targetInstance && cast.spellId === event.ability.guid); if (castIndex === -1) { debug && this.error('Encountered damage event with no cast associated. Queue', JSON.parse(JSON.stringify(this._queue)), 'event', event); return; } debug && this.log('Paired damage event', event, 'with queued cast', JSON.parse(JSON.stringify(this._queue[castIndex]))); const bonusDamage = calculateEffectiveDamage(event, this._queue[castIndex].bonus); this._queue.splice(castIndex, 1); if (event.ability.guid === SPELLS.SHADOW_BOLT_DEMO.id) { this._shadowBoltDamage += bonusDamage; } else { this._demonboltDamage += bonusDamage; } } statistic() { const hasPS = this.selectedCombatant.hasTalent(SPELLS.POWER_SIPHON_TALENT.id); return ( <Statistic category={STATISTIC_CATEGORY.TALENTS} size="flexible" tooltip={( <> {formatThousands(this.totalBonusDamage)} bonus damage<br /> Bonus Shadow Bolt damage: {formatThousands(this._shadowBoltDamage)} ({this.owner.formatItemDamageDone(this._shadowBoltDamage)})<br /> Bonus Demonbolt damage: {formatThousands(this._demonboltDamage)} ({this.owner.formatItemDamageDone(this._demonboltDamage)}) {hasPS && ( <> <br /><br />* Since you have Power Siphon talent, it's highly likely that it messes up getting current pets at certain time because sometimes the number of Imps we sacrifice in code doesn't agree with what happens in logs. Therefore, this value is most likely a little wrong. </> )} </> )} > <BoringSpellValueText spell={SPELLS.SACRIFICED_SOULS_TALENT}> <ItemDamageDone amount={this.totalBonusDamage} /> </BoringSpellValueText> </Statistic> ); } } export default SacrificedSouls;
yajinni/WoWAnalyzer
analysis/warlockdemonology/src/modules/talents/SacrificedSouls.js
JavaScript
agpl-3.0
4,211
package astutil import ( "go/ast" "github.com/juju/errors" ) // SameIdent returns true if a and b are the same. func SameIdent(a, b *ast.Ident) bool { // TODO(waigani) Don't rely on name, it could change and still be the same // ident. if a.String() != b.String() { return false } // TODO(waigani) this happens if ident decl is outside of current // file. We need to use the FileSet to find it. if a.Obj == nil && b.Obj == nil { return true } pa, err := DeclPos(a) if err != nil { // TODO(waigani) log error return false } pb, err := DeclPos(b) if err != nil { // TODO(waigani) log error return false } if pa != pb { return false } return true } // IdentDeclExpr returns the expression that the identifier was declared with. func IdentDeclExpr(ident *ast.Ident) (ast.Expr, error) { if ident.Obj == nil { return nil, errors.Errorf("ident object is nil for ident %q", ident.Name) } switch n := ident.Obj.Decl.(type) { case *ast.AssignStmt: // find position of ident on lhs of assignment var identPos int for i, exp := range n.Lhs { if a, ok := exp.(*ast.Ident); ok && SameIdent(a, ident) { identPos = i break } } return n.Rhs[identPos], nil case *ast.ValueSpec: // find position of ident on lhs of assignment var identPos int for i, name := range n.Names { if name.String() == ident.String() { identPos = i } } if n.Values != nil { // get the rhs counterpart return n.Values[identPos], nil } } return nil, errors.Errorf("no expr found for %T", ident.Name) } // DeclLhsPos returns the position of the ident's variable on the left hand // side of the assignment operator with which it was declared. func DeclLhsPos(ident *ast.Ident) (int, error) { var identPos int switch n := ident.Obj.Decl.(type) { case *ast.AssignStmt: // find position of ident on lhs of assignment for i, exp := range n.Lhs { if a, ok := exp.(*ast.Ident); ok && SameIdent(a, ident) { identPos = i break } } case *ast.ValueSpec: // find position of ident on lhs of assignment for i, name := range n.Names { if name.String() == ident.String() { identPos = i break } } default: return 0, errors.New("could not get lhs position of ident: unknown decl type") } return identPos, nil } // DeclPos returns the possition the ident was declared. func DeclPos(n *ast.Ident) (int, error) { if n.Obj == nil { // TODO(waigani) this happens if ident decl is outside of current // file. We need to use the FileSet to find it. return 0, errors.New("ident object is nil") } switch t := n.Obj.Decl.(type) { case *ast.AssignStmt: if t.TokPos.IsValid() { return int(t.TokPos), nil } return 0, errors.New("token not valid") case *ast.ValueSpec: if len(t.Names) == 0 { return 0, errors.New("decl statement has no names") } // Even if this is not the name of the ident, it is in the same decl // statement. We are interested in the pos of the decl statement. return int(t.Names[0].NamePos), nil default: // TODO(waigani) log } return 0, errors.New("could not get declaration position") } func DeclaredWithLit(ident *ast.Ident) (bool, error) { // TODO(waigani) decl is outside current file. Assume yes until we can be sure of an issue. if ident.Obj == nil { return true, nil } expr, err := IdentDeclExpr(ident) if err != nil { return false, errors.Trace(err) } switch n := expr.(type) { case *ast.CompositeLit: return true, nil case *ast.CallExpr: if f, ok := n.Fun.(*ast.Ident); ok { if f.Name == "make" { return true, nil } } } return false, nil } // Expects ident to have an object of type func and returns the returned vars // of that func. func FuncResults(ident *ast.Ident) ([]*ast.Field, error) { if ident.Obj == nil { return nil, errors.New("ident has no object") } if ident.Obj.Kind.String() != "func" { return nil, errors.New("expected type func") } if funcDecl, ok := ident.Obj.Decl.(*ast.FuncDecl); ok { return funcDecl.Type.Results.List, nil } return nil, errors.New("could not get func results") } // Returns a string representation of the identifier's type. func TypeOf(ident *ast.Ident) (string, error) { switch n := ident.Obj.Decl.(type) { case *ast.AssignStmt: expr, err := IdentDeclExpr(ident) if err != nil { return "", errors.Trace(err) } switch n := expr.(type) { case *ast.CallExpr: pos, err := DeclLhsPos(ident) if err != nil { return "", errors.Trace(err) } if fun, ok := n.Fun.(*ast.Ident); ok { results, err := FuncResults(fun) if err != nil { return "", errors.Trace(err) } if p, ok := results[pos].Type.(*ast.Ident); ok { return p.Name, nil } } } case *ast.ValueSpec: if x, ok := n.Type.(*ast.Ident); ok { return x.Name, nil } default: // TODO(waigani) log } return "", errors.New("could not find type") }
lingo-reviews/tenets
go/dev/tenet/astutil/ident.go
GO
agpl-3.0
4,924
<?php /** * Model for ParcellaireIrrigueDeclaration * */ class ParcellaireIrrigueDeclaration extends BaseParcellaireIrrigueDeclaration { public function getParcellesByCommune() { $parcelles = array(); foreach($this->getParcelles() as $parcelle) { if(!isset($parcelles[$parcelle->commune])) { $parcelles[$parcelle->commune] = array(); } $parcelles[$parcelle->commune][$parcelle->getHash()] = $parcelle; } ksort($parcelles); return $parcelles; } public function getParcelles() { $parcelles = array(); foreach($this as $produit) { foreach ($produit->detail as $parcelle) { $parcelles[$parcelle->getHash()] = $parcelle; } } return $parcelles; } }
24eme/AVA
project/plugins/acVinParcellaireIrriguePlugin/lib/model/ParcellaireIrrigue/ParcellaireIrrigueDeclaration.class.php
PHP
agpl-3.0
832
// SIMPLETZ.H // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* Copyright (C) 1997-2013, International Business Machines Corporation and others. All Rights Reserved. * Modification History: * Date Name Description * 12/05/96 clhuang Creation. * 04/21/97 aliu Fixed miscellaneous bugs found by inspection and * testing. * 07/29/97 aliu Ported source bodies back from Java version with * numerous feature enhancements and bug fixes. * 08/10/98 stephen JDK 1.2 sync. * 09/17/98 stephen Fixed getOffset() for last hour of year and DST * 12/02/99 aliu Added TimeMode and constructor and setStart/EndRule * methods that take TimeMode. Whitespace cleanup. ******************************************************************************** */ #include <icu-internal.h> #pragma hdrstop #if !UCONFIG_NO_FORMATTING #include "gregoimp.h" U_NAMESPACE_BEGIN UOBJECT_DEFINE_RTTI_IMPLEMENTATION(SimpleTimeZone) // Use only for decodeStartRule() and decodeEndRule() where the year is not // available. Set February to 29 days to accommodate rules with that date // and day-of-week-on-or-before-that-date mode (DOW_LE_DOM_MODE). // The compareToRule() method adjusts to February 28 in non-leap years. // // For actual getOffset() calculations, use Grego::monthLength() and // Grego::previousMonthLength() which take leap years into account. // We handle leap years assuming always // Gregorian, since we know they didn't have daylight time when // Gregorian calendar started. const int8_t SimpleTimeZone::STATICMONTHLENGTH[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static const UChar DST_STR[] = {0x0028, 0x0044, 0x0053, 0x0054, 0x0029, 0}; // "(DST)" static const UChar STD_STR[] = {0x0028, 0x0053, 0x0054, 0x0044, 0x0029, 0}; // "(STD)" // ***************************************************************************** // class SimpleTimeZone // ***************************************************************************** SimpleTimeZone::SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString & ID) : BasicTimeZone(ID), startMonth(0), startDay(0), startDayOfWeek(0), startTime(0), startTimeMode(WALL_TIME), endTimeMode(WALL_TIME), endMonth(0), endDay(0), endDayOfWeek(0), endTime(0), startYear(0), rawOffset(rawOffsetGMT), useDaylight(FALSE), startMode(DOM_MODE), endMode(DOM_MODE), dstSavings(U_MILLIS_PER_HOUR) { clearTransitionRules(); } SimpleTimeZone::SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString & ID, int8_t savingsStartMonth, int8_t savingsStartDay, int8_t savingsStartDayOfWeek, int32_t savingsStartTime, int8_t savingsEndMonth, int8_t savingsEndDay, int8_t savingsEndDayOfWeek, int32_t savingsEndTime, UErrorCode & status) : BasicTimeZone(ID) { clearTransitionRules(); construct(rawOffsetGMT, savingsStartMonth, savingsStartDay, savingsStartDayOfWeek, savingsStartTime, WALL_TIME, savingsEndMonth, savingsEndDay, savingsEndDayOfWeek, savingsEndTime, WALL_TIME, U_MILLIS_PER_HOUR, status); } SimpleTimeZone::SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString & ID, int8_t savingsStartMonth, int8_t savingsStartDay, int8_t savingsStartDayOfWeek, int32_t savingsStartTime, int8_t savingsEndMonth, int8_t savingsEndDay, int8_t savingsEndDayOfWeek, int32_t savingsEndTime, int32_t savingsDST, UErrorCode & status) : BasicTimeZone(ID) { clearTransitionRules(); construct(rawOffsetGMT, savingsStartMonth, savingsStartDay, savingsStartDayOfWeek, savingsStartTime, WALL_TIME, savingsEndMonth, savingsEndDay, savingsEndDayOfWeek, savingsEndTime, WALL_TIME, savingsDST, status); } SimpleTimeZone::SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString & ID, int8_t savingsStartMonth, int8_t savingsStartDay, int8_t savingsStartDayOfWeek, int32_t savingsStartTime, TimeMode savingsStartTimeMode, int8_t savingsEndMonth, int8_t savingsEndDay, int8_t savingsEndDayOfWeek, int32_t savingsEndTime, TimeMode savingsEndTimeMode, int32_t savingsDST, UErrorCode & status) : BasicTimeZone(ID) { clearTransitionRules(); construct(rawOffsetGMT, savingsStartMonth, savingsStartDay, savingsStartDayOfWeek, savingsStartTime, savingsStartTimeMode, savingsEndMonth, savingsEndDay, savingsEndDayOfWeek, savingsEndTime, savingsEndTimeMode, savingsDST, status); } /** * Internal construction method. */ void SimpleTimeZone::construct(int32_t rawOffsetGMT, int8_t savingsStartMonth, int8_t savingsStartDay, int8_t savingsStartDayOfWeek, int32_t savingsStartTime, TimeMode savingsStartTimeMode, int8_t savingsEndMonth, int8_t savingsEndDay, int8_t savingsEndDayOfWeek, int32_t savingsEndTime, TimeMode savingsEndTimeMode, int32_t savingsDST, UErrorCode & status) { this->rawOffset = rawOffsetGMT; this->startMonth = savingsStartMonth; this->startDay = savingsStartDay; this->startDayOfWeek = savingsStartDayOfWeek; this->startTime = savingsStartTime; this->startTimeMode = savingsStartTimeMode; this->endMonth = savingsEndMonth; this->endDay = savingsEndDay; this->endDayOfWeek = savingsEndDayOfWeek; this->endTime = savingsEndTime; this->endTimeMode = savingsEndTimeMode; this->dstSavings = savingsDST; this->startYear = 0; this->startMode = DOM_MODE; this->endMode = DOM_MODE; decodeRules(status); if(savingsDST == 0) { status = U_ILLEGAL_ARGUMENT_ERROR; } } SimpleTimeZone::~SimpleTimeZone() { deleteTransitionRules(); } // Called by TimeZone::createDefault(), then clone() inside a Mutex - be careful. SimpleTimeZone::SimpleTimeZone(const SimpleTimeZone &source) : BasicTimeZone(source) { *this = source; } // Called by TimeZone::createDefault(), then clone() inside a Mutex - be careful. SimpleTimeZone &SimpleTimeZone::operator = (const SimpleTimeZone &right) { if(this != &right) { TimeZone::operator = (right); rawOffset = right.rawOffset; startMonth = right.startMonth; startDay = right.startDay; startDayOfWeek = right.startDayOfWeek; startTime = right.startTime; startTimeMode = right.startTimeMode; startMode = right.startMode; endMonth = right.endMonth; endDay = right.endDay; endDayOfWeek = right.endDayOfWeek; endTime = right.endTime; endTimeMode = right.endTimeMode; endMode = right.endMode; startYear = right.startYear; dstSavings = right.dstSavings; useDaylight = right.useDaylight; clearTransitionRules(); } return *this; } bool SimpleTimeZone::operator == (const TimeZone& that) const { return ((this == &that) || (typeid(*this) == typeid(that) && TimeZone::operator == (that) && hasSameRules(that))); } // Called by TimeZone::createDefault() inside a Mutex - be careful. SimpleTimeZone* SimpleTimeZone::clone() const { return new SimpleTimeZone(*this); } /** * Sets the daylight savings starting year, that is, the year this time zone began * observing its specified daylight savings time rules. The time zone is considered * not to observe daylight savings time prior to that year; SimpleTimeZone doesn't * support historical daylight-savings-time rules. * @param year the daylight savings starting year. */ void SimpleTimeZone::setStartYear(int32_t year) { startYear = year; transitionRulesInitialized = FALSE; } /** * Sets the daylight savings starting rule. For example, in the U.S., Daylight Savings * Time starts at the first Sunday in April, at 2 AM in standard time. * Therefore, you can set the start rule by calling: * setStartRule(TimeFields.APRIL, 1, TimeFields.SUNDAY, 2*60*60*1000); * The dayOfWeekInMonth and dayOfWeek parameters together specify how to calculate * the exact starting date. Their exact meaning depend on their respective signs, * allowing various types of rules to be constructed, as follows:<ul> * <li>If both dayOfWeekInMonth and dayOfWeek are positive, they specify the * day of week in the month (e.g., (2, WEDNESDAY) is the second Wednesday * of the month). * <li>If dayOfWeek is positive and dayOfWeekInMonth is negative, they specify * the day of week in the month counting backward from the end of the month. * (e.g., (-1, MONDAY) is the last Monday in the month) * <li>If dayOfWeek is zero and dayOfWeekInMonth is positive, dayOfWeekInMonth * specifies the day of the month, regardless of what day of the week it is. * (e.g., (10, 0) is the tenth day of the month) * <li>If dayOfWeek is zero and dayOfWeekInMonth is negative, dayOfWeekInMonth * specifies the day of the month counting backward from the end of the * month, regardless of what day of the week it is (e.g., (-2, 0) is the * next-to-last day of the month). * <li>If dayOfWeek is negative and dayOfWeekInMonth is positive, they specify the * first specified day of the week on or after the specified day of the month. * (e.g., (15, -SUNDAY) is the first Sunday after the 15th of the month * [or the 15th itself if the 15th is a Sunday].) * <li>If dayOfWeek and DayOfWeekInMonth are both negative, they specify the * last specified day of the week on or before the specified day of the month. * (e.g., (-20, -TUESDAY) is the last Tuesday before the 20th of the month * [or the 20th itself if the 20th is a Tuesday].)</ul> * @param month the daylight savings starting month. Month is 0-based. * eg, 0 for January. * @param dayOfWeekInMonth the daylight savings starting * day-of-week-in-month. Please see the member description for an example. * @param dayOfWeek the daylight savings starting day-of-week. Please see * the member description for an example. * @param time the daylight savings starting time. Please see the member * description for an example. */ void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, int32_t time, TimeMode mode, UErrorCode & status) { startMonth = (int8_t)month; startDay = (int8_t)dayOfWeekInMonth; startDayOfWeek = (int8_t)dayOfWeek; startTime = time; startTimeMode = mode; decodeStartRule(status); transitionRulesInitialized = FALSE; } void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth, int32_t time, TimeMode mode, UErrorCode & status) { setStartRule(month, dayOfMonth, 0, time, mode, status); } void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, int32_t time, TimeMode mode, bool after, UErrorCode & status) { setStartRule(month, after ? dayOfMonth : -dayOfMonth, -dayOfWeek, time, mode, status); } /** * Sets the daylight savings ending rule. For example, in the U.S., Daylight * Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time. * Therefore, you can set the end rule by calling: * setEndRule(TimeFields.OCTOBER, -1, TimeFields.SUNDAY, 2*60*60*1000); * Various other types of rules can be specified by manipulating the dayOfWeek * and dayOfWeekInMonth parameters. For complete details, see the documentation * for setStartRule(). * @param month the daylight savings ending month. Month is 0-based. * eg, 0 for January. * @param dayOfWeekInMonth the daylight savings ending * day-of-week-in-month. See setStartRule() for a complete explanation. * @param dayOfWeek the daylight savings ending day-of-week. See setStartRule() * for a complete explanation. * @param time the daylight savings ending time. Please see the member * description for an example. */ void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, int32_t time, TimeMode mode, UErrorCode & status) { endMonth = (int8_t)month; endDay = (int8_t)dayOfWeekInMonth; endDayOfWeek = (int8_t)dayOfWeek; endTime = time; endTimeMode = mode; decodeEndRule(status); transitionRulesInitialized = FALSE; } void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth, int32_t time, TimeMode mode, UErrorCode & status) { setEndRule(month, dayOfMonth, 0, time, mode, status); } void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, int32_t time, TimeMode mode, bool after, UErrorCode & status) { setEndRule(month, after ? dayOfMonth : -dayOfMonth, -dayOfWeek, time, mode, status); } int32_t SimpleTimeZone::getOffset(uint8 era, int32_t year, int32_t month, int32_t day, uint8 dayOfWeek, int32_t millis, UErrorCode & status) const { // Check the month before calling Grego::monthLength(). This // duplicates the test that occurs in the 7-argument getOffset(), // however, this is unavoidable. We don't mind because this method, in // fact, should not be called; internal code should always call the // 7-argument getOffset(), and outside code should use Calendar.get(int // field) with fields ZONE_OFFSET and DST_OFFSET. We can't get rid of // this method because it's public API. - liu 8/10/98 if(month < UCAL_JANUARY || month > UCAL_DECEMBER) { status = U_ILLEGAL_ARGUMENT_ERROR; return 0; } return getOffset(era, year, month, day, dayOfWeek, millis, Grego::monthLength(year, month), status); } int32_t SimpleTimeZone::getOffset(uint8 era, int32_t year, int32_t month, int32_t day, uint8 dayOfWeek, int32_t millis, int32_t /*monthLength*/, UErrorCode & status) const { // Check the month before calling Grego::monthLength(). This // duplicates a test that occurs in the 9-argument getOffset(), // however, this is unavoidable. We don't mind because this method, in // fact, should not be called; internal code should always call the // 9-argument getOffset(), and outside code should use Calendar.get(int // field) with fields ZONE_OFFSET and DST_OFFSET. We can't get rid of // this method because it's public API. - liu 8/10/98 if(month < UCAL_JANUARY || month > UCAL_DECEMBER) { status = U_ILLEGAL_ARGUMENT_ERROR; return -1; } // We ignore monthLength because it can be derived from year and month. // This is so that February in leap years is calculated correctly. // We keep this argument in this function for backwards compatibility. return getOffset(era, year, month, day, dayOfWeek, millis, Grego::monthLength(year, month), Grego::previousMonthLength(year, month), status); } int32_t SimpleTimeZone::getOffset(uint8 era, int32_t year, int32_t month, int32_t day, uint8 dayOfWeek, int32_t millis, int32_t monthLength, int32_t prevMonthLength, UErrorCode & status) const { if(U_FAILURE(status)) return 0; if((era != GregorianCalendar::AD && era != GregorianCalendar::BC) || month < UCAL_JANUARY || month > UCAL_DECEMBER || day < 1 || day > monthLength || dayOfWeek < UCAL_SUNDAY || dayOfWeek > UCAL_SATURDAY || millis < 0 || millis >= U_MILLIS_PER_DAY || monthLength < 28 || monthLength > 31 || prevMonthLength < 28 || prevMonthLength > 31) { status = U_ILLEGAL_ARGUMENT_ERROR; return -1; } int32_t result = rawOffset; // Bail out if we are before the onset of daylight savings time if(!useDaylight || year < startYear || era != GregorianCalendar::AD) return result; // Check for southern hemisphere. We assume that the start and end // month are different. bool southern = (startMonth > endMonth); // Compare the date to the starting and ending rules.+1 = date>rule, -1 // = date<rule, 0 = date==rule. int32_t startCompare = compareToRule((int8_t)month, (int8_t)monthLength, (int8_t)prevMonthLength, (int8_t)day, (int8_t)dayOfWeek, millis, startTimeMode == UTC_TIME ? -rawOffset : 0, startMode, (int8_t)startMonth, (int8_t)startDayOfWeek, (int8_t)startDay, startTime); int32_t endCompare = 0; /* We don't always have to compute endCompare. For many instances, * startCompare is enough to determine if we are in DST or not. In the * northern hemisphere, if we are before the start rule, we can't have * DST. In the southern hemisphere, if we are after the start rule, we * must have DST. This is reflected in the way the next if statement * (not the one immediately following) short circuits. */ if(southern != (startCompare >= 0)) { endCompare = compareToRule((int8_t)month, (int8_t)monthLength, (int8_t)prevMonthLength, (int8_t)day, (int8_t)dayOfWeek, millis, endTimeMode == WALL_TIME ? dstSavings : (endTimeMode == UTC_TIME ? -rawOffset : 0), endMode, (int8_t)endMonth, (int8_t)endDayOfWeek, (int8_t)endDay, endTime); } // Check for both the northern and southern hemisphere cases. We // assume that in the northern hemisphere, the start rule is before the // end rule within the calendar year, and vice versa for the southern // hemisphere. if((!southern && (startCompare >= 0 && endCompare < 0)) || (southern && (startCompare >= 0 || endCompare < 0))) result += dstSavings; return result; } void SimpleTimeZone::getOffsetFromLocal(UDate date, UTimeZoneLocalOption nonExistingTimeOpt, UTimeZoneLocalOption duplicatedTimeOpt, int32_t& rawOffsetGMT, int32_t& savingsDST, UErrorCode & status) const { if(U_FAILURE(status)) { return; } rawOffsetGMT = getRawOffset(); int32_t year, month, dom, dow; double day = uprv_floor(date / U_MILLIS_PER_DAY); int32_t millis = (int32_t)(date - day * U_MILLIS_PER_DAY); Grego::dayToFields(day, year, month, dom, dow); savingsDST = getOffset(GregorianCalendar::AD, year, month, dom, (uint8)dow, millis, Grego::monthLength(year, month), status) - rawOffsetGMT; if(U_FAILURE(status)) { return; } bool recalc = FALSE; // Now we need some adjustment if(savingsDST > 0) { if((nonExistingTimeOpt & kStdDstMask) == kStandard || ((nonExistingTimeOpt & kStdDstMask) != kDaylight && (nonExistingTimeOpt & kFormerLatterMask) != kLatter)) { date -= getDSTSavings(); recalc = TRUE; } } else { if((duplicatedTimeOpt & kStdDstMask) == kDaylight || ((duplicatedTimeOpt & kStdDstMask) != kStandard && (duplicatedTimeOpt & kFormerLatterMask) == kFormer)) { date -= getDSTSavings(); recalc = TRUE; } } if(recalc) { day = uprv_floor(date / U_MILLIS_PER_DAY); millis = (int32_t)(date - day * U_MILLIS_PER_DAY); Grego::dayToFields(day, year, month, dom, dow); savingsDST = getOffset(GregorianCalendar::AD, year, month, dom, (uint8)dow, millis, Grego::monthLength(year, month), status) - rawOffsetGMT; } } /** * Compare a given date in the year to a rule. Return 1, 0, or -1, depending * on whether the date is after, equal to, or before the rule date. The * millis are compared directly against the ruleMillis, so any * standard-daylight adjustments must be handled by the caller. * * @return 1 if the date is after the rule date, -1 if the date is before * the rule date, or 0 if the date is equal to the rule date. */ int32_t SimpleTimeZone::compareToRule(int8_t month, int8_t monthLen, int8_t prevMonthLen, int8_t dayOfMonth, int8_t dayOfWeek, int32_t millis, int32_t millisDelta, EMode ruleMode, int8_t ruleMonth, int8_t ruleDayOfWeek, int8_t ruleDay, int32_t ruleMillis) { // Make adjustments for startTimeMode and endTimeMode millis += millisDelta; while(millis >= U_MILLIS_PER_DAY) { millis -= U_MILLIS_PER_DAY; ++dayOfMonth; dayOfWeek = (int8_t)(1 + (dayOfWeek % 7)); // dayOfWeek is one-based if(dayOfMonth > monthLen) { dayOfMonth = 1; /* When incrementing the month, it is desirable to overflow * from DECEMBER to DECEMBER+1, since we use the result to * compare against a real month. Wraparound of the value * leads to bug 4173604. */ ++month; } } while(millis < 0) { millis += U_MILLIS_PER_DAY; --dayOfMonth; dayOfWeek = (int8_t)(1 + ((dayOfWeek+5) % 7)); // dayOfWeek is one-based if(dayOfMonth < 1) { dayOfMonth = prevMonthLen; --month; } } // first compare months. If they're different, we don't have to worry about days // and times if(month < ruleMonth) return -1; else if(month > ruleMonth) return 1; // calculate the actual day of month for the rule int32_t ruleDayOfMonth = 0; // Adjust the ruleDay to the monthLen, for non-leap year February 29 rule days. if(ruleDay > monthLen) { ruleDay = monthLen; } switch(ruleMode) { // if the mode is day-of-month, the day of month is given case DOM_MODE: ruleDayOfMonth = ruleDay; break; // if the mode is day-of-week-in-month, calculate the day-of-month from it case DOW_IN_MONTH_MODE: // In this case ruleDay is the day-of-week-in-month (this code is using // the dayOfWeek and dayOfMonth parameters to figure out the day-of-week // of the first day of the month, so it's trusting that they're really // consistent with each other) if(ruleDay > 0) ruleDayOfMonth = 1 + (ruleDay - 1) * 7 + (7 + ruleDayOfWeek - (dayOfWeek - dayOfMonth + 1)) % 7; // if ruleDay is negative (we assume it's not zero here), we have to do // the same calculation figuring backward from the last day of the month. else { // (again, this code is trusting that dayOfWeek and dayOfMonth are // consistent with each other here, since we're using them to figure // the day of week of the first of the month) ruleDayOfMonth = monthLen + (ruleDay + 1) * 7 - (7 + (dayOfWeek + monthLen - dayOfMonth) - ruleDayOfWeek) % 7; } break; case DOW_GE_DOM_MODE: ruleDayOfMonth = ruleDay + (49 + ruleDayOfWeek - ruleDay - dayOfWeek + dayOfMonth) % 7; break; case DOW_LE_DOM_MODE: ruleDayOfMonth = ruleDay - (49 - ruleDayOfWeek + ruleDay + dayOfWeek - dayOfMonth) % 7; // Note at this point ruleDayOfMonth may be <1, although it will // be >=1 for well-formed rules. break; } // now that we have a real day-in-month for the rule, we can compare days... if(dayOfMonth < ruleDayOfMonth) return -1; else if(dayOfMonth > ruleDayOfMonth) return 1; // ...and if they're equal, we compare times if(millis < ruleMillis) return -1; else if(millis > ruleMillis) return 1; else return 0; } int32_t SimpleTimeZone::getRawOffset() const { return rawOffset; } void SimpleTimeZone::setRawOffset(int32_t offsetMillis) { rawOffset = offsetMillis; transitionRulesInitialized = FALSE; } void SimpleTimeZone::setDSTSavings(int32_t millisSavedDuringDST, UErrorCode & status) { if(millisSavedDuringDST == 0) { status = U_ILLEGAL_ARGUMENT_ERROR; } else { dstSavings = millisSavedDuringDST; } transitionRulesInitialized = FALSE; } int32_t SimpleTimeZone::getDSTSavings() const { return dstSavings; } bool SimpleTimeZone::useDaylightTime() const { return useDaylight; } /** * Overrides TimeZone * Queries if the given date is in Daylight Savings Time. */ bool SimpleTimeZone::inDaylightTime(UDate date, UErrorCode & status) const { // This method is wasteful since it creates a new GregorianCalendar and // deletes it each time it is called. However, this is a deprecated method // and provided only for Java compatibility as of 8/6/97 [LIU]. if(U_FAILURE(status)) return FALSE; GregorianCalendar * gc = new GregorianCalendar(*this, status); /* test for NULL */ if(gc == 0) { status = U_MEMORY_ALLOCATION_ERROR; return FALSE; } gc->setTime(date, status); bool result = gc->inDaylightTime(status); delete gc; return result; } /** * Return true if this zone has the same rules and offset as another zone. * @param other the TimeZone object to be compared with * @return true if the given zone has the same rules and offset as this one */ bool SimpleTimeZone::hasSameRules(const TimeZone& other) const { if(this == &other) return TRUE; if(typeid(*this) != typeid(other)) return FALSE; SimpleTimeZone * that = (SimpleTimeZone*)&other; return rawOffset == that->rawOffset && useDaylight == that->useDaylight && (!useDaylight // Only check rules if using DST || (dstSavings == that->dstSavings && startMode == that->startMode && startMonth == that->startMonth && startDay == that->startDay && startDayOfWeek == that->startDayOfWeek && startTime == that->startTime && startTimeMode == that->startTimeMode && endMode == that->endMode && endMonth == that->endMonth && endDay == that->endDay && endDayOfWeek == that->endDayOfWeek && endTime == that->endTime && endTimeMode == that->endTimeMode && startYear == that->startYear)); } // // Rule representation // // We represent the following flavors of rules: // 5 the fifth of the month // lastSun the last Sunday in the month // lastMon the last Monday in the month // Sun>=8 first Sunday on or after the eighth // Sun<=25 last Sunday on or before the 25th // This is further complicated by the fact that we need to remain // backward compatible with the 1.1 FCS. Finally, we need to minimize // API changes. In order to satisfy these requirements, we support // three representation systems, and we translate between them. // // INTERNAL REPRESENTATION // This is the format SimpleTimeZone objects take after construction or // streaming in is complete. Rules are represented directly, using an // unencoded format. We will discuss the start rule only below; the end // rule is analogous. // startMode Takes on enumerated values DAY_OF_MONTH, // DOW_IN_MONTH, DOW_AFTER_DOM, or DOW_BEFORE_DOM. // startDay The day of the month, or for DOW_IN_MONTH mode, a // value indicating which DOW, such as +1 for first, // +2 for second, -1 for last, etc. // startDayOfWeek The day of the week. Ignored for DAY_OF_MONTH. // // ENCODED REPRESENTATION // This is the format accepted by the constructor and by setStartRule() // and setEndRule(). It uses various combinations of positive, negative, // and zero values to encode the different rules. This representation // allows us to specify all the different rule flavors without altering // the API. // MODE startMonth startDay startDayOfWeek // DOW_IN_MONTH_MODE >=0 !=0 >0 // DOM_MODE >=0 >0 ==0 // DOW_GE_DOM_MODE >=0 >0 <0 // DOW_LE_DOM_MODE >=0 <0 <0 // (no DST) don't care ==0 don't care // // STREAMED REPRESENTATION // We must retain binary compatibility with the 1.1 FCS. The 1.1 code only // handles DOW_IN_MONTH_MODE and non-DST mode, the latter indicated by the // flag useDaylight. When we stream an object out, we translate into an // approximate DOW_IN_MONTH_MODE representation so the object can be parsed // and used by 1.1 code. Following that, we write out the full // representation separately so that contemporary code can recognize and // parse it. The full representation is written in a "packed" format, // consisting of a version number, a length, and an array of bytes. Future // versions of this class may specify different versions. If they wish to // include additional data, they should do so by storing them after the // packed representation below. // /** * Given a set of encoded rules in startDay and startDayOfMonth, decode * them and set the startMode appropriately. Do the same for endDay and * endDayOfMonth. Upon entry, the day of week variables may be zero or * negative, in order to indicate special modes. The day of month * variables may also be negative. Upon exit, the mode variables will be * set, and the day of week and day of month variables will be positive. * This method also recognizes a startDay or endDay of zero as indicating * no DST. */ void SimpleTimeZone::decodeRules(UErrorCode & status) { decodeStartRule(status); decodeEndRule(status); } /** * Decode the start rule and validate the parameters. The parameters are * expected to be in encoded form, which represents the various rule modes * by negating or zeroing certain values. Representation formats are: * <p> * <pre> * DOW_IN_MONTH DOM DOW>=DOM DOW<=DOM no DST * ------------ ----- -------- -------- ---------- * month 0..11 same same same don't care * day -5..5 1..31 1..31 -1..-31 0 * dayOfWeek 1..7 0 -1..-7 -1..-7 don't care * time 0..ONEDAY same same same don't care * </pre> * The range for month does not include UNDECIMBER since this class is * really specific to GregorianCalendar, which does not use that month. * The range for time includes ONEDAY (vs. ending at ONEDAY-1) because the * end rule is an exclusive limit point. That is, the range of times that * are in DST include those >= the start and < the end. For this reason, * it should be possible to specify an end of ONEDAY in order to include the * entire day. Although this is equivalent to time 0 of the following day, * it's not always possible to specify that, for example, on December 31. * While arguably the start range should still be 0..ONEDAY-1, we keep * the start and end ranges the same for consistency. */ void SimpleTimeZone::decodeStartRule(UErrorCode & status) { if(U_FAILURE(status)) return; useDaylight = (bool)((startDay != 0) && (endDay != 0) ? TRUE : FALSE); if(useDaylight && dstSavings == 0) { dstSavings = U_MILLIS_PER_HOUR; } if(startDay != 0) { if(startMonth < UCAL_JANUARY || startMonth > UCAL_DECEMBER) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } if(startTime < 0 || startTime > U_MILLIS_PER_DAY || startTimeMode < WALL_TIME || startTimeMode > UTC_TIME) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } if(startDayOfWeek == 0) { startMode = DOM_MODE; } else { if(startDayOfWeek > 0) { startMode = DOW_IN_MONTH_MODE; } else { startDayOfWeek = (int8_t)-startDayOfWeek; if(startDay > 0) { startMode = DOW_GE_DOM_MODE; } else { startDay = (int8_t)-startDay; startMode = DOW_LE_DOM_MODE; } } if(startDayOfWeek > UCAL_SATURDAY) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } } if(startMode == DOW_IN_MONTH_MODE) { if(startDay < -5 || startDay > 5) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } } else if(startDay<1 || startDay > STATICMONTHLENGTH[startMonth]) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } } } /** * Decode the end rule and validate the parameters. This method is exactly * analogous to decodeStartRule(). * @see decodeStartRule */ void SimpleTimeZone::decodeEndRule(UErrorCode & status) { if(U_FAILURE(status)) return; useDaylight = (bool)((startDay != 0) && (endDay != 0) ? TRUE : FALSE); if(useDaylight && dstSavings == 0) { dstSavings = U_MILLIS_PER_HOUR; } if(endDay != 0) { if(endMonth < UCAL_JANUARY || endMonth > UCAL_DECEMBER) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } if(endTime < 0 || endTime > U_MILLIS_PER_DAY || endTimeMode < WALL_TIME || endTimeMode > UTC_TIME) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } if(endDayOfWeek == 0) { endMode = DOM_MODE; } else { if(endDayOfWeek > 0) { endMode = DOW_IN_MONTH_MODE; } else { endDayOfWeek = (int8_t)-endDayOfWeek; if(endDay > 0) { endMode = DOW_GE_DOM_MODE; } else { endDay = (int8_t)-endDay; endMode = DOW_LE_DOM_MODE; } } if(endDayOfWeek > UCAL_SATURDAY) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } } if(endMode == DOW_IN_MONTH_MODE) { if(endDay < -5 || endDay > 5) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } } else if(endDay<1 || endDay > STATICMONTHLENGTH[endMonth]) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } } } bool SimpleTimeZone::getNextTransition(UDate base, bool inclusive, TimeZoneTransition& result) const { if(!useDaylight) { return FALSE; } UErrorCode status = U_ZERO_ERROR; checkTransitionRules(status); if(U_FAILURE(status)) { return FALSE; } UDate firstTransitionTime = firstTransition->getTime(); if(base < firstTransitionTime || (inclusive && base == firstTransitionTime)) { result = *firstTransition; } UDate stdDate, dstDate; bool stdAvail = stdRule->getNextStart(base, dstRule->getRawOffset(), dstRule->getDSTSavings(), inclusive, stdDate); bool dstAvail = dstRule->getNextStart(base, stdRule->getRawOffset(), stdRule->getDSTSavings(), inclusive, dstDate); if(stdAvail && (!dstAvail || stdDate < dstDate)) { result.setTime(stdDate); result.setFrom((const TimeZoneRule&)*dstRule); result.setTo((const TimeZoneRule&)*stdRule); return TRUE; } if(dstAvail && (!stdAvail || dstDate < stdDate)) { result.setTime(dstDate); result.setFrom((const TimeZoneRule&)*stdRule); result.setTo((const TimeZoneRule&)*dstRule); return TRUE; } return FALSE; } bool SimpleTimeZone::getPreviousTransition(UDate base, bool inclusive, TimeZoneTransition& result) const { if(!useDaylight) { return FALSE; } UErrorCode status = U_ZERO_ERROR; checkTransitionRules(status); if(U_FAILURE(status)) { return FALSE; } UDate firstTransitionTime = firstTransition->getTime(); if(base < firstTransitionTime || (!inclusive && base == firstTransitionTime)) { return FALSE; } UDate stdDate, dstDate; bool stdAvail = stdRule->getPreviousStart(base, dstRule->getRawOffset(), dstRule->getDSTSavings(), inclusive, stdDate); bool dstAvail = dstRule->getPreviousStart(base, stdRule->getRawOffset(), stdRule->getDSTSavings(), inclusive, dstDate); if(stdAvail && (!dstAvail || stdDate > dstDate)) { result.setTime(stdDate); result.setFrom((const TimeZoneRule&)*dstRule); result.setTo((const TimeZoneRule&)*stdRule); return TRUE; } if(dstAvail && (!stdAvail || dstDate > stdDate)) { result.setTime(dstDate); result.setFrom((const TimeZoneRule&)*stdRule); result.setTo((const TimeZoneRule&)*dstRule); return TRUE; } return FALSE; } void SimpleTimeZone::clearTransitionRules() { initialRule = NULL; firstTransition = NULL; stdRule = NULL; dstRule = NULL; transitionRulesInitialized = FALSE; } void SimpleTimeZone::deleteTransitionRules() { if(initialRule != NULL) { delete initialRule; } if(firstTransition != NULL) { delete firstTransition; } if(stdRule != NULL) { delete stdRule; } if(dstRule != NULL) { delete dstRule; } clearTransitionRules(); } /* * Lazy transition rules initializer * * Note On the removal of UMTX_CHECK from checkTransitionRules(): * * It would be faster to have a UInitOnce as part of a SimpleTimeZone object, * which would avoid needing to lock a mutex to check the initialization state. * But we can't easily because simpletz.h is a public header, and including * a UInitOnce as a member of SimpleTimeZone would publicly expose internal ICU headers. * * Alternatively we could have a pointer to a UInitOnce in the SimpleTimeZone object, * allocate it in the constructors. This would be a more intrusive change, but doable * if performance turns out to be an issue. */ void SimpleTimeZone::checkTransitionRules(UErrorCode & status) const { if(U_FAILURE(status)) { return; } static UMutex gLock; umtx_lock(&gLock); if(!transitionRulesInitialized) { SimpleTimeZone * ncThis = const_cast<SimpleTimeZone*>(this); ncThis->initTransitionRules(status); } umtx_unlock(&gLock); } void SimpleTimeZone::initTransitionRules(UErrorCode & status) { if(U_FAILURE(status)) { return; } if(transitionRulesInitialized) { return; } deleteTransitionRules(); UnicodeString tzid; getID(tzid); if(useDaylight) { DateTimeRule* dtRule; DateTimeRule::TimeRuleType timeRuleType; UDate firstStdStart, firstDstStart; // Create a TimeZoneRule for daylight saving time timeRuleType = (startTimeMode == STANDARD_TIME) ? DateTimeRule::STANDARD_TIME : ((startTimeMode == UTC_TIME) ? DateTimeRule::UTC_TIME : DateTimeRule::WALL_TIME); switch(startMode) { case DOM_MODE: dtRule = new DateTimeRule(startMonth, startDay, startTime, timeRuleType); break; case DOW_IN_MONTH_MODE: dtRule = new DateTimeRule(startMonth, startDay, startDayOfWeek, startTime, timeRuleType); break; case DOW_GE_DOM_MODE: dtRule = new DateTimeRule(startMonth, startDay, startDayOfWeek, true, startTime, timeRuleType); break; case DOW_LE_DOM_MODE: dtRule = new DateTimeRule(startMonth, startDay, startDayOfWeek, false, startTime, timeRuleType); break; default: status = U_INVALID_STATE_ERROR; return; } // Check for Null pointer if(dtRule == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return; } // For now, use ID + "(DST)" as the name dstRule = new AnnualTimeZoneRule(tzid+UnicodeString(DST_STR), getRawOffset(), getDSTSavings(), dtRule, startYear, AnnualTimeZoneRule::MAX_YEAR); // Check for Null pointer if(dstRule == NULL) { status = U_MEMORY_ALLOCATION_ERROR; deleteTransitionRules(); return; } // Calculate the first DST start time dstRule->getFirstStart(getRawOffset(), 0, firstDstStart); // Create a TimeZoneRule for standard time timeRuleType = (endTimeMode == STANDARD_TIME) ? DateTimeRule::STANDARD_TIME : ((endTimeMode == UTC_TIME) ? DateTimeRule::UTC_TIME : DateTimeRule::WALL_TIME); switch(endMode) { case DOM_MODE: dtRule = new DateTimeRule(endMonth, endDay, endTime, timeRuleType); break; case DOW_IN_MONTH_MODE: dtRule = new DateTimeRule(endMonth, endDay, endDayOfWeek, endTime, timeRuleType); break; case DOW_GE_DOM_MODE: dtRule = new DateTimeRule(endMonth, endDay, endDayOfWeek, true, endTime, timeRuleType); break; case DOW_LE_DOM_MODE: dtRule = new DateTimeRule(endMonth, endDay, endDayOfWeek, false, endTime, timeRuleType); break; } // Check for Null pointer if(dtRule == NULL) { status = U_MEMORY_ALLOCATION_ERROR; deleteTransitionRules(); return; } // For now, use ID + "(STD)" as the name stdRule = new AnnualTimeZoneRule(tzid+UnicodeString(STD_STR), getRawOffset(), 0, dtRule, startYear, AnnualTimeZoneRule::MAX_YEAR); //Check for Null pointer if(stdRule == NULL) { status = U_MEMORY_ALLOCATION_ERROR; deleteTransitionRules(); return; } // Calculate the first STD start time stdRule->getFirstStart(getRawOffset(), dstRule->getDSTSavings(), firstStdStart); // Create a TimeZoneRule for initial time if(firstStdStart < firstDstStart) { initialRule = new InitialTimeZoneRule(tzid+UnicodeString(DST_STR), getRawOffset(), dstRule->getDSTSavings()); if(initialRule == NULL) { status = U_MEMORY_ALLOCATION_ERROR; deleteTransitionRules(); return; } firstTransition = new TimeZoneTransition(firstStdStart, *initialRule, *stdRule); } else { initialRule = new InitialTimeZoneRule(tzid+UnicodeString(STD_STR), getRawOffset(), 0); if(initialRule == NULL) { status = U_MEMORY_ALLOCATION_ERROR; deleteTransitionRules(); return; } firstTransition = new TimeZoneTransition(firstDstStart, *initialRule, *dstRule); } if(firstTransition == NULL) { status = U_MEMORY_ALLOCATION_ERROR; deleteTransitionRules(); return; } } else { // Create a TimeZoneRule for initial time initialRule = new InitialTimeZoneRule(tzid, getRawOffset(), 0); // Check for null pointer. if(initialRule == NULL) { status = U_MEMORY_ALLOCATION_ERROR; deleteTransitionRules(); return; } } transitionRulesInitialized = TRUE; } int32_t SimpleTimeZone::countTransitionRules(UErrorCode & /*status*/) const { return (useDaylight) ? 2 : 0; } void SimpleTimeZone::getTimeZoneRules(const InitialTimeZoneRule*& initial, const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode & status) const { if(U_FAILURE(status)) { return; } checkTransitionRules(status); if(U_FAILURE(status)) { return; } initial = initialRule; int32_t cnt = 0; if(stdRule != NULL) { if(cnt < trscount) { trsrules[cnt++] = stdRule; } if(cnt < trscount) { trsrules[cnt++] = dstRule; } } trscount = cnt; } U_NAMESPACE_END #endif /* #if !UCONFIG_NO_FORMATTING */
papyrussolution/OpenPapyrus
Src/OSF/icu/icu4c/source/i18n/simpletz.cpp
C++
agpl-3.0
40,478
<?php /** * uiSelectionState maintains a selection of items between requests. * * @package UiParts * @author Fabrice Denis */ class uiSelectionState { protected static $user = null; protected $items = array(); public function __construct() { $this->items = array(); } public function clear() { $this->items = array(); } /** * Update selection with values from request parameters. * Hidden input values indicate item ids and selected state. * * @param * * @return */ public function update($paramName, $params) { $pattern = '/^sel_'.$paramName.'-([0-9]{1,10})$/'; foreach ($params as $param => $value) { if (preg_match($pattern, $param, $matches)) { $id = $matches[1]; $state = $value; $this->items[$id] = $state === '1'; } } } public function store($name) { self::getUser()->setAttribute($name, serialize($this)); } /** * Checks if an item is selected. * * @return mixed Boolean for state, or null if id doesn't exist */ public function getState($id) { return isset($this->items[$id]) ? $this->items[$id] : null; } public function getInputTag($paramName, $id) { $state = $this->getState($id); $value = $state===true ? '1' : '0'; $inputName = 'sel_' . $paramName . '-' . $id; return input_hidden_tag($inputName, $value); } public function getCheckboxTag($paramName, $id) { $state = $this->getState($id); $inputName = 'chk_' . $paramName . '-' . $id; // todo: FIXME!!! problème avec le helper? return '<input type="checkbox" class="checkbox" name="'.$inputName.'" '.($state ? 'checked ':'').'/>'; // return checkbox_tag($inputName, $id, $state===true, array('class' => 'checkbox')); } /** * Return the id of all selected items. * * @return array */ public function getAll() { $selected = array(); foreach ($this->items as $id => $state) { if ($state) { $selected[] = $id; } } return $selected; } /** * Serialize method * * @return */ public function __sleep() { return array('items'); } /** * Serialize method * * @return */ public function __wakeup() { } /** * Returns active user session. * * @return coreUser */ static public function getUser() { if (self::$user === null) { self::$user = coreContext::getInstance()->getUser(); } return self::$user; } /** * Returns named selection from user session, create a new one if it doesn't exist yet. * * @return uiSelectionState */ static public function getSelection($name) { $selection = self::getUser()->getAttribute($name); if (!is_string($selection)) { $selection = new uiSelectionState(); } else { $selection = unserialize($selection); } return $selection; } /** * Update selection with request variable. * */ static public function updateSelection($name, $paramName, $params) { $selection = self::getSelection($name); $selection->update($paramName, $params); $selection->store($name); } /** * Clear selected items. * */ static public function clearSelection($name) { $selection = self::getSelection($name); $selection->clear(); $selection->store($name); } }
kc5nra/RevTK
lib/uiparts/uiSelectionState.php
PHP
agpl-3.0
3,446
# -*- coding: utf-8 -*- # Copyright (C) 2010 Eduardo Robles Elvira <edulix AT gmail DOT com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.contrib.auth.models import User, UserManager from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import signals, Avg, Q from datetime import date import os from django.conf import settings def create_profile_for_user(sender, **kwargs): ''' This way everytime a User is created, a Profile is created too. ''' if kwargs['created']: profile = Profile() if not kwargs['instance'].__dict__.has_key("birth_date"): profile.birth_date = date.today() if not kwargs['instance'].__dict__.has_key("address"): profile.address = _("address") profile.__dict__.update(kwargs['instance'].__dict__) profile.save() #signals.post_save.connect(create_profile_for_user, sender=User) class Profile(User): ''' <<<<<<< HEAD User with timebank settings. ======= User with time bank settings. >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 ''' photo = models.ImageField(_("Avatar"), blank=True, null=True, upload_to=os.path.join(settings.STATIC_DOC_ROOT, "photos")) <<<<<<< HEAD birth_date = models.DateField(_("Rojstni datum"), default=date.today()) address = models.CharField(_("Naslov"), max_length=100, default=_("address")) org_name = models.CharField(_("Ime organizacije"), max_length=30, default=_("org_name")) first_name1 = models.CharField(_("Ime zastopnika"), max_length=30, default=_("first_name")) last_name1 = models.CharField(_("Priimek zastopnika"), max_length=30, default=_("last_name")) email1 = models.CharField(_("E-mail zastopnika"), max_length=30, default=_("email")) # credits in minutes balance = models.IntegerField(default=600) ======= birth_date = models.DateField(_("Birth date"), default=date.today()) address = models.CharField(_("Address"), max_length=100, default=_("address")) # credits in minutes balance = models.IntegerField(default=0) >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 def balance_hours(self): if self.balance % 60 == 0: return self.balance/60 return self.balance/60.0 <<<<<<< HEAD description = models.TextField(_("Opis"), max_length=300, blank=True) land_line = models.CharField(_("Stacionarni telefon"), max_length=20) mobile_tlf = models.CharField(_("Mobilni telefon"), max_length=20) email_updates = models.BooleanField(_(u"Želim prejemati novice Časovne banke"), ======= description = models.TextField(_("Personal address"), max_length=300, blank=True) land_line = models.CharField(_("Land line"), max_length=20) mobile_tlf = models.CharField(_("Mobile phone"), max_length=20) email_updates = models.BooleanField(_("Receive email updates"), >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 default=True) # Saving the user language allows sending emails to him in his desired # language (among other things) <<<<<<< HEAD lang_code = models.CharField(_("Jezik"), max_length=10, default='') class Meta: verbose_name = _("user") verbose_name_plural = _("users") ======= lang_code = models.CharField(_("Language Code"), max_length=10, default='') class Meta: verbose_name = _("User") verbose_name_plural = _("Users") >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 def __unicode__(self): return self.username # Use UserManager to get the create_user method, etc. objects = UserManager() def __eq__(self, value): return value and self.id == value.id or False def transfers_pending(self): ''' Transfers from this user which are not in a final state ''' from serv.models import Transfer return Transfer.objects.filter(Q(credits_payee=self) \ | Q(credits_payee=self)).filter(status__in=['r', 'd']) def karma(self): ''' Average of the user's transfer scores ''' karma = self.transfers_received.aggregate(Avg('rating_score')) if karma['rating_score__avg']: return int(karma['rating_score__avg']) else: return 0
miaerbus/timebank
user/models.py
Python
agpl-3.0
4,968
#!/usr/bin/env ruby # Brightbox - Statistics class loader # Copyright (c) 2011, Brightbox Systems # Author: Neil Wilson require 'yaml' module DomtrixStats %w( triggerable domain_info_decoder stats_processor domain_info interface_info uptime_info inet_info ).each do |file| autoload(file.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase },"domtrix_stats/#{file}") end end
NeilW/domtrix
lib/domtrix_stats.rb
Ruby
agpl-3.0
436
MarkItNow::Application.routes.draw do root to: 'page#index', as: :index get 'search' => 'page#search' get 'image' => 'page#image' get 'read/:id' => 'page#read', as: :read get 'text/:id' => 'page#text', as: :text get 'info/:id' => 'page#info' get 'aozora/:id' => 'page#aozora', as: :aozora get 'save_recent/:id' => 'page#save_recent' get 'save_recent_text/:id' => 'page#save_recent_text' get 'img_from_name/:id' => 'page#img_from_name' get 'to/:id' => 'page#from_path', constraints: {id: /.*/} get 'memo/:id' => 'page#memo', as: :memo post 'memo/:id' => 'page#save_memo' match ':controller(/:action(/:id(.:format)))', via: [:post, :get] end
ssig33/Mark-It-now
config/routes.rb
Ruby
agpl-3.0
668
class SongPolicy < ApplicationPolicy def create? user.church_admin? || user.admin? end def update? user.admin? end end
jcuenod/songswesing
app/policies/song_policy.rb
Ruby
agpl-3.0
135
<?php return array( 'edit' => 'تعديل', 'delete' => 'حذف', 'restore' => 'إستعادة', 'actions' => 'الإجراءات', 'submit' => 'إرسال', );
supriyap-webonise/snipeit
app/lang/ar/button.php
PHP
agpl-3.0
189
############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # 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/>. # ############################################################################## { 'name': 'Products Management Group', 'version': '13.0.1.0.0', 'category': 'base.module_category_knowledge_management', 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'license': 'AGPL-3', 'depends': [ 'sale', ], 'data': [ 'security/product_management_security.xml', ], 'installable': False, }
ingadhoc/product
product_management_group/__manifest__.py
Python
agpl-3.0
1,296
import * as Actions from './actions' import * as Controls from './controls' import Editor from './editor' import Panel from './panel' export {Actions} export {Editor} export {Panel} export {Controls}
ChuckDaniels87/pydio-core
core/src/plugins/meta.exif/res/js/index.js
JavaScript
agpl-3.0
201
class Author < ActiveRecord::Base has_many :posts has_many :posts_with_comments, :include => :comments, :class_name => "Post" has_many :posts_with_categories, :include => :categories, :class_name => "Post" has_many :posts_with_comments_and_categories, :include => [ :comments, :categories ], :order => "posts.id", :class_name => "Post" has_many :posts_with_extension, :class_name => "Post" do #, :extend => ProxyTestExtension def testing_proxy_owner proxy_owner end def testing_proxy_reflection proxy_reflection end def testing_proxy_target proxy_target end end has_many :comments, :through => :posts has_many :comments_desc, :through => :posts, :source => :comments, :order => 'comments.id DESC' has_many :limited_comments, :through => :posts, :source => :comments, :limit => 1 has_many :funky_comments, :through => :posts, :source => :comments has_many :ordered_uniq_comments, :through => :posts, :source => :comments, :uniq => true, :order => 'comments.id' has_many :ordered_uniq_comments_desc, :through => :posts, :source => :comments, :uniq => true, :order => 'comments.id DESC' has_many :readonly_comments, :through => :posts, :source => :comments, :readonly => true has_many :special_posts has_many :special_post_comments, :through => :special_posts, :source => :comments has_many :special_nonexistant_posts, :class_name => "SpecialPost", :conditions => "posts.body = 'nonexistant'" has_many :special_nonexistant_post_comments, :through => :special_nonexistant_posts, :source => :comments, :conditions => "comments.post_id = 0" has_many :nonexistant_comments, :through => :posts has_many :hello_posts, :class_name => "Post", :conditions => "posts.body = 'hello'" has_many :hello_post_comments, :through => :hello_posts, :source => :comments has_many :posts_with_no_comments, :class_name => 'Post', :conditions => 'comments.id is null', :include => :comments has_many :other_posts, :class_name => "Post" has_many :posts_with_callbacks, :class_name => "Post", :before_add => :log_before_adding, :after_add => :log_after_adding, :before_remove => :log_before_removing, :after_remove => :log_after_removing has_many :posts_with_proc_callbacks, :class_name => "Post", :before_add => Proc.new {|o, r| o.post_log << "before_adding#{r.id || '<new>'}"}, :after_add => Proc.new {|o, r| o.post_log << "after_adding#{r.id || '<new>'}"}, :before_remove => Proc.new {|o, r| o.post_log << "before_removing#{r.id}"}, :after_remove => Proc.new {|o, r| o.post_log << "after_removing#{r.id}"} has_many :posts_with_multiple_callbacks, :class_name => "Post", :before_add => [:log_before_adding, Proc.new {|o, r| o.post_log << "before_adding_proc#{r.id || '<new>'}"}], :after_add => [:log_after_adding, Proc.new {|o, r| o.post_log << "after_adding_proc#{r.id || '<new>'}"}] has_many :unchangable_posts, :class_name => "Post", :before_add => :raise_exception, :after_add => :log_after_adding has_many :categorizations has_many :categories, :through => :categorizations has_many :categories_like_general, :through => :categorizations, :source => :category, :class_name => 'Category', :conditions => { :name => 'General' } has_many :categorized_posts, :through => :categorizations, :source => :post has_many :unique_categorized_posts, :through => :categorizations, :source => :post, :uniq => true has_many :nothings, :through => :kateggorisatons, :class_name => 'Category' has_many :author_favorites has_many :favorite_authors, :through => :author_favorites, :order => 'name' has_many :tagging, :through => :posts # through polymorphic has_one has_many :taggings, :through => :posts, :source => :taggings # through polymorphic has_many has_many :tags, :through => :posts # through has_many :through has_many :post_categories, :through => :posts, :source => :categories belongs_to :author_address, :dependent => :destroy belongs_to :author_address_extra, :dependent => :delete, :class_name => "AuthorAddress" attr_accessor :post_log def after_initialize @post_log = [] end def label "#{id}-#{name}" end private def log_before_adding(object) @post_log << "before_adding#{object.id || '<new>'}" end def log_after_adding(object) @post_log << "after_adding#{object.id}" end def log_before_removing(object) @post_log << "before_removing#{object.id}" end def log_after_removing(object) @post_log << "after_removing#{object.id}" end def raise_exception(object) raise Exception.new("You can't add a post") end end class AuthorAddress < ActiveRecord::Base has_one :author def self.destroyed_author_address_ids @destroyed_author_address_ids ||= Hash.new { |h,k| h[k] = [] } end before_destroy do |author_address| if author_address.author AuthorAddress.destroyed_author_address_ids[author_address.author.id] << author_address.id end true end end class AuthorFavorite < ActiveRecord::Base belongs_to :author belongs_to :favorite_author, :class_name => "Author" end
Gitorious-backup/samgranieris-clone
vendor/rails/activerecord/test/models/author.rb
Ruby
agpl-3.0
5,235
<?php /*-----8<-------------------------------------------------------------------- * * BEdita - a semantic content management framework * * Copyright 2008 ChannelWeb Srl, Chialab Srl * * This file is part of BEdita: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * BEdita is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the Affero GNU General Public License for more details. * You should have received a copy of the Affero GNU General Public License * version 3 along with BEdita (see LICENSE.AGPL). * If not, see <http://gnu.org/licenses/agpl-3.0.html>. * *------------------------------------------------------------------->8----- */ /** * * * @version $Revision: 2887 $ * @modifiedby $LastChangedBy: ste $ * @lastmodified $LastChangedDate: 2010-06-22 12:10:32 +0200 (Tue, 22 Jun 2010) $ * * $Id: delete_object.php 2887 2010-06-22 10:10:32Z ste $ */ /** * * Delete object using dependence of foreign key. * Delete only the record of base table then database's referential integrity do the rest * */ class DeleteObjectBehavior extends ModelBehavior { /** * contain base table */ var $config = array(); function setup(&$model, $config = array()) { $this->config[$model->name] = $config ; } /** * Delete all associations, they will be re-established after deleting * Considering foreignKeys among tables, force deleting records on table 'objects' * * if specified delete related object too * @return unknown */ function beforeDelete(&$model) { $model->tmpAssociations = array(); $model->tmpTable = $model->table ; $associations = array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany'); foreach ($associations as $association) { $model->tmpAssociations[$association] = $model->$association ; $model->$association = array() ; } $configure = $this->config[$model->name] ; if (!empty($configure)) { if (is_string($configure)) { $model->table = $configure; } elseif (is_array($configure) && count($configure) == 1) { if (is_string(key($configure))) { $model->table = key($configure); if (!empty($configure[$model->table]["relatedObjects"])) { $this->delRelatedObjects($configure[$model->table]["relatedObjects"], $model->id); } } else { $model->table = array_shift($configure); } } } $model->table = (isset($configure) && is_string($configure)) ? $configure : $model->table ; // Delete object references on tree as well $tree = ClassRegistry::init('Tree'); if (!$tree->deleteAll(array("id" => $model->id))) { throw new BeditaException(__("Error deleting tree",true)); } if (!$tree->deleteAll(array("object_path LIKE '%/".$model->id."/%'"))) { throw new BeditaException(__("Error deleting children tree",true)); } $st = ClassRegistry::init('SearchText'); $st->deleteAll("object_id=".$model->id) ; $this->deleteAnnotations($model->id); return true ; } /** * Re-establish associations (insert associations) * */ function afterDelete(&$model) { if (!empty($model->tmpTable)) { $model->table = $model->tmpTable ; unset($model->tmpTable) ; } if (!empty($model->tmpAssociations)) { // Re-establish associations foreach ($model->tmpAssociations as $association => $v) { $model->$association = $v ; } unset($model->tmpAssociations) ; } } /** * Delete related objects * * @param array $relations: array of relations type. * The object related to main object by a relation in $relations will be deleted * @param int $object_id: main object that has to be deleted */ private function delRelatedObjects($relations, $object_id) { $o = ClassRegistry::init('BEObject') ; $res = $o->find("first", array( "contain" => array("RelatedObject"), "conditions" => array("BEObject.id" => $object_id) ) ); if (!empty($res["RelatedObject"])) { $conf = Configure::getInstance(); foreach ($res["RelatedObject"] as $obj) { if (in_array($obj["switch"],$relations)) { $modelClass = $o->getType($obj['object_id']); $model = ClassRegistry::init($modelClass); if (!$model->del($obj["object_id"])) throw new BeditaException(__("Error deleting related object ", true), "id: ". $obj["object_id"] . ", switch: " . $obj["switch"]); } } } } /** * delete annotation objects like Comment, EditorNote, etc... related to main object * * @param int $object_id main object */ private function deleteAnnotations($object_id) { // delete annotations $annotation = ClassRegistry::init("Annotation"); $aList = $annotation->find("list", array( "fields" => array("id"), "conditions" => array("object_id" => $object_id) )); if (!empty($aList)) { $o = ClassRegistry::init('BEObject'); foreach ($aList as $id) { $modelClass = $o->getType($id); $model = ClassRegistry::init($modelClass); if (!$model->del($id)) { throw new BeditaException(__("Error deleting annotation " . $modelClass, true), "id: ". $id); } } } } } ?>
danfreak/BEdita
bedita-app/models/behaviors/delete_object.php
PHP
agpl-3.0
5,395
<?php return array( 'does_not_exist' => 'Categoría inexistente.', 'user_does_not_exist' => 'Usuario inexistente.', 'asset_does_not_exist' => 'El equipo que intentas asignar a esta licencia no existe.', 'owner_doesnt_match_asset' => 'El equipo al que estas intentando asignar esta licencia, está asignado a un usuario diferente que el de la licencia.', 'assoc_users' => 'Esta categoría está asignada al menos a un modelo y no puede ser eliminada.', 'create' => array( 'error' => 'La categoría no se ha creado, intentalo de nuevo.', 'success' => 'Categoría creada correctamente.' ), 'deletefile' => array( 'error' => 'Archivo no eliminado. Por favor, vuelva a intentarlo.', 'success' => 'Archivo eliminado correctamente.', ), 'upload' => array( 'error' => 'Archivo(s) no cargado. Por favor, vuelva a intentarlo.', 'success' => 'Archivo(s) cargado correctamente.', 'nofiles' => 'No ha seleccionado ningún archivo para subir', 'invalidfiles' => 'Uno o más de sus archivos es demasiado grande o es un tipo de archivo que no está permitido. Los tipos de archivo permitidos son png, gif, jpg, doc, docx, pdf y txt.', ), 'update' => array( 'error' => 'La categoría no se ha actualizado, intentalo de nuevo.', 'success' => 'Categoría actualizada correctamente.' ), 'delete' => array( 'confirm' => 'Estás seguro de eliminar esta categoría?', 'error' => 'Ha habido un problema eliminando la categoría. Intentalo de nuevo.', 'success' => 'Categoría eliminada.' ), 'checkout' => array( 'error' => 'Equipo no asignado, intentalo de nuevo', 'success' => 'Equipo asignado.' ), 'checkin' => array( 'error' => 'No se ha quitado el equipo. Intentalo de nuevo.', 'success' => 'Equipo quitado correctamente.' ), );
thomas1216/snipe-it
app/lang/es-LATAM/admin/licenses/message.php
PHP
agpl-3.0
1,950
/** * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.scheduleevent.servlets.handlers; import javax.servlet.http.HttpServletRequest; import com.silverpeas.scheduleevent.control.ScheduleEventSessionController; public class ScheduleEventAddOptionsNextRequestHandler implements ScheduleEventRequestHandler { @Override public String getDestination(String function, ScheduleEventSessionController scheduleeventSC, HttpServletRequest request) throws Exception { // keep session object identical -> nothing to do request.setAttribute(CURRENT_SCHEDULE_EVENT, scheduleeventSC.getCurrentScheduleEvent()); return "form/optionshour.jsp"; } }
CecileBONIN/Silverpeas-Components
scheduleevent/scheduleevent-war/src/main/java/com/silverpeas/scheduleevent/servlets/handlers/ScheduleEventAddOptionsNextRequestHandler.java
Java
agpl-3.0
1,773
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details. * * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/ */ package org.openlmis.report.model.params; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.openlmis.report.model.ReportData; import org.openlmis.report.model.ReportParameter; @Data @EqualsAndHashCode(callSuper=false) @NoArgsConstructor @AllArgsConstructor public class StockImbalanceReportParam extends BaseParam implements ReportParameter { private int facilityTypeId; private String facilityType; // private int productId; private String productId; private String product; // private int productCategoryId; private String productCategoryId; private String productCategory; private String facility; private int programId; private String program; private int scheduleId; private String schedule; private int periodId; private Long zoneId; private String period; private Integer year; @Override public String toString() { StringBuilder filtersValue = new StringBuilder(""); filtersValue.append("Period : ").append(this.period).append("\n"). append("Schedule : ").append(this.schedule).append("\n"). append("Program : ").append(this.program).append("\n"). append("Product Category : ").append(this.productCategory).append("\n"). append("Product : ").append(this.product).append("\n"). append("Facility Types : ").append(this.getFacilityType()).append("\n"); return filtersValue.toString(); } }
vimsvarcode/elmis
modules/report/src/main/java/org/openlmis/report/model/params/StockImbalanceReportParam.java
Java
agpl-3.0
2,440
/** * */ /* * Cacheonix Systems licenses this file to You under the LGPL 2.1 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cacheonix.impl.transformer; /** * Enum used for maintaing the state of the reader while reading the bytes in the class file */ public enum ETransformationState { // States ENUMs INITIAL_STATE { /* * (non-Javadoc) * * @see java.lang.Objectr#toString() */ public String toString() { return "INITIAL_STATE"; } }, READING_CONFIG_ANNOTATION // Found Configuration Annotation - Class level { /* * (non-Javadoc) * * @see java.lang.Objectr#toString() */ public String toString() { return "READING_CONFIG_ANNOTATION"; } }, READING_METHOD_ANNOTATION // Found Method Annotation { /* * (non-Javadoc) * * @see java.lang.Objectr#toString() */ public String toString() { return "READING_METHOD_ANNOTATION"; } }; /* * (non-Javadoc) * * @see java.lang.Objectr#toString() */ public String toString() { return "UNKNOWN"; } }
cacheonix/cacheonix-core
annotations/core/src/org/cacheonix/impl/transformer/ETransformationState.java
Java
lgpl-2.1
1,806