repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
harish-patel/ecrm | modules/WorkFlowAlerts/CreateStep1.php | 6939 | <?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
********************************************************************************/
/*********************************************************************************
* Description:
********************************************************************************/
global $theme;
global $app_strings;
global $app_list_strings;
global $mod_strings;
global $urlPrefix;
global $currentModule;
$focus = new WorkFlowAlert();
if(!empty($_REQUEST['parent_id']) && $_REQUEST['parent_id']!="") {
$focus->parent_id = $_REQUEST['parent_id'];
} else {
sugar_die("You shouldn't be here");
}
$workflow_object = $focus->get_workflow_object();
if(!empty($_REQUEST['record']) && $_REQUEST['record']!="") {
$focus->retrieve($_REQUEST['record']);
}
$target_workflow_object = $workflow_object->get_parent_object();
////////////////////////////////////////////////////////
// Start the output
////////////////////////////////////////////////////////
$form =new XTemplate ('modules/WorkFlowAlerts/CreateStep1.html');
$GLOBALS['log']->debug("using file modules/WorkFlowAlerts/CreateStep1.html");
//Bug 12335: We need to include the javascript language file first. And also the language file in WorkFlow is needed.
if(!is_file($GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/' . $GLOBALS['current_language'] . '.js')) {
require_once('include/language/jsLanguage.php');
jsLanguage::createAppStringsCache($GLOBALS['current_language']);
}
$javascript_language_files = '<script type="text/javascript" src="' . $GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/' . $GLOBALS['current_language'] . '.js?s=' . $GLOBALS['sugar_version'] . '&c=' . $GLOBALS['sugar_config']['js_custom_version'] . '&j=' . $GLOBALS['sugar_config']['js_lang_version'] . '"></script>';
if(!is_file($GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/' . $this->module . '/' . $GLOBALS['current_language'] . '.js')) {
require_once('include/language/jsLanguage.php');
jsLanguage::createModuleStringsCache($this->module, $GLOBALS['current_language']);
}
$javascript_language_files .= '<script type="text/javascript" src="' . $GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/' . $this->module . '/' . $GLOBALS['current_language'] . '.js?s=' . $GLOBALS['sugar_version'] . '&c=' . $GLOBALS['sugar_config']['js_custom_version'] . '&j=' . $GLOBALS['sugar_config']['js_lang_version'] . '"></script>';
if(!is_file($GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/WorkFLow/' . $GLOBALS['current_language'] . '.js')) {
require_once('include/language/jsLanguage.php');
jsLanguage::createModuleStringsCache('WorkFlow', $GLOBALS['current_language']);
}
$javascript_language_files .= '<script type="text/javascript" src="' . $GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/WorkFlow/' . $GLOBALS['current_language'] . '.js?s=' . $GLOBALS['sugar_version'] . '&c=' . $GLOBALS['sugar_config']['js_custom_version'] . '&j=' . $GLOBALS['sugar_config']['js_lang_version'] . '"></script>';
$the_javascript = "<script type='text/javascript' language='JavaScript'>\n";
$the_javascript .= "function set_return() {\n";
$the_javascript .= " window.opener.document.EditView.submit();";
$the_javascript .= "}\n";
$the_javascript .= "</script>\n";
$form->assign("MOD", $mod_strings);
$form->assign("APP", $app_strings);
$form->assign("JAVASCRIPT_LANGUAGE_FILES", $javascript_language_files);
$form->assign("MODULE_NAME", $currentModule);
$form->assign("GRIDLINE", $gridline);
$form->assign("SET_RETURN_JS", $the_javascript);
// $form->assign("BASE_MODULE", $_REQUEST['base_module']);
$form->assign("BASE_MODULE", $target_workflow_object->base_module);
$form->assign("PARENT_ID", $focus->parent_id);
$form->assign("ID", $focus->id);
$form->assign("REL_MODULE1", $focus->rel_module1);
$form->assign("REL_MODULE2", $focus->rel_module2);
$form->assign("FIELD_VALUE", $focus->field_value);
////////Middle Items/////////////////////////////
/////////////////End Items //////////////////////
insert_popup_header($theme);
$form->parse("embeded");
$form->out("embeded");
//////////New way of processing page
require_once('include/ListView/ProcessView.php');
//Check to see if this workflow object is bridging, and if so, use its parent workflow object as the object
$ProcessView = new ProcessView($target_workflow_object, $focus);
$ProcessView->no_count = true;
$ProcessView->write("AlertsCreateStep1");
$form->assign("TOP_BLOCK", $ProcessView->top_block);
$form->assign("BOTTOM_BLOCK", $ProcessView->bottom_block);
//close window and refresh parent if needed
if(!empty($_REQUEST['special_action']) && $_REQUEST['special_action'] == "refresh"){
$special_javascript = "window.opener.document.DetailView.action.value = 'DetailView'; \n";
$special_javascript .= "window.opener.document.DetailView.submit(); \n";
$special_javascript .= "window.close();";
$form->assign("SPECIAL_JAVASCRIPT", $special_javascript);
}
$form->parse("main");
$form->out("main");
?>
<?php insert_popup_footer(); ?>
| agpl-3.0 |
axiomsoftware/axiom-stack | src/java/axiom/scripting/rhino/debug/AxiomDebugger.java | 13108 | /*
* Axiom Stack Web Application Framework
* Copyright (C) 2008 Axiom Software Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Axiom Software Inc., 11480 Commerce Park Drive, Third Floor, Reston, VA 20191 USA
* email: info@axiomsoftwareinc.com
*/
package axiom.scripting.rhino.debug;
import java.util.Arrays;
import java.util.HashMap;
import org.mozilla.javascript.*;
import org.mozilla.javascript.debug.*;
import axiom.framework.ErrorReporter;
import axiom.framework.core.Application;
import axiom.framework.core.RequestEvaluator;
import axiom.framework.core.Session;
import axiom.scripting.rhino.AxiomObject;
import axiom.scripting.rhino.RhinoEngine;
public class AxiomDebugger implements Debugger {
private Application app;
private int callDepth = 0;
private boolean isStepping = false;
private boolean isJumping = false;
public AxiomDebugger(Application app) {
this.app = app;
}
public void handleCompilationDone(Context cx, DebuggableScript fnOrScript, String source) { }
public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript) {
return new AxiomDebugFrame(this.app, fnOrScript);
}
private static HashMap<String, AxiomDebugger> debuggers = new HashMap<String, AxiomDebugger>();
public static synchronized AxiomDebugger getDebugger(Application app) {
AxiomDebugger debugger = debuggers.get(app.getName());
if (debugger == null) {
debugger = new AxiomDebugger(app);
debuggers.put(app.getName(), debugger);
}
return debugger;
}
public static synchronized void removeDebugger(Application app) {
debuggers.remove(app.getName());
}
class AxiomDebugFrame implements DebugFrame {
Application app;
DebuggableScript script;
Scriptable activation;
Scriptable thisObj;
int[] sortedLineNums = null;
AxiomDebugFrame(Application app, DebuggableScript script) {
this.app = app;
this.script = script;
}
public void onDebuggerStatement(Context cx) { }
public void onEnter(Context cx, Scriptable activation, Scriptable thisObj, Object[] args) {
this.activation = activation;
this.thisObj = thisObj;
AxiomDebugger debugger = (AxiomDebugger) cx.getDebugger();
if (debugger != null) {
if (skipFunction() || debugger.isJumping) {
synchronized (debugger) {
debugger.callDepth++;
}
return;
}
boolean ignoreDebugging = false;
synchronized (debugger) {
if (debugger.callDepth > 0) {
ignoreDebugging = true;
}
}
if (ignoreDebugging) {
return;
}
}
RequestEvaluator re = this.app.getCurrentRequestEvaluator();
if (re != null && isOnFunctionEnterSet()) {
debugger.isStepping = false;
Debug debug = re.getSession().getDebugObject();
DebugMonitor monitor = debug.addWaitingEvaluator(re);
Scriptable scope = ((RhinoEngine) re.getScriptingEngine()).getGlobal();
DebugEvent event = new DebugEvent();
event.resourceName = this.script.getSourceName();
event.functionName = this.script.getFunctionName();
event.scope = activationToScope(cx, scope, this.activation);
event.parentScope = this.activation.getParentScope();
event.thisObj = this.thisObj;
event.lineNumber = this.getStartLineNum();
event.requestId = re.hashCode();
event.eventType = DebugEvent.FUNCTION_ENTRY;
debug.pushEvent(event);
try {
synchronized (monitor) {
monitor.wait();
}
} catch (Exception ex) {
this.app.logError(ErrorReporter.errorMsg(this.getClass(), "onEnter"), ex);
}
debugger.isStepping = monitor.isStepping;
monitor.isStepping = false;
monitor.isJumping = false;
}
}
public void onExit(Context cx, boolean byThrow, Object resultOrException) {
AxiomDebugger debugger = (AxiomDebugger) cx.getDebugger();
if (debugger != null) {
boolean ignoreDebugging = false;
synchronized (debugger) {
if (debugger.callDepth > 0) {
ignoreDebugging = true;
}
}
if (skipFunction() || debugger.isJumping) {
synchronized (debugger) {
if (ignoreDebugging) {
debugger.callDepth--;
}
}
return;
}
if (ignoreDebugging) {
return;
}
}
RequestEvaluator re = this.app.getCurrentRequestEvaluator();
if (re != null && isOnFunctionExitSet()) {
debugger.isStepping = false;
Debug debug = re.getSession().getDebugObject();
DebugMonitor monitor = debug.addWaitingEvaluator(re);
Scriptable scope = ((RhinoEngine) re.getScriptingEngine()).getGlobal();
DebugEvent event = new DebugEvent();
event.resourceName = this.script.getSourceName();
event.functionName = this.script.getFunctionName();
event.scope = activationToScope(cx, scope, this.activation);
event.parentScope = this.activation.getParentScope();
event.thisObj = this.thisObj;
event.lineNumber = this.getEndLineNum();
event.requestId = re.hashCode();
event.eventType = DebugEvent.FUNCTION_EXIT;
debug.pushEvent(event);
try {
synchronized (monitor) {
monitor.wait();
}
} catch (Exception ex) {
this.app.logError(ErrorReporter.errorMsg(this.getClass(), "onExit"), ex);
}
debugger.isStepping = monitor.isStepping;
monitor.isStepping = false;
monitor.isJumping = false;
}
}
public void onLineChange(Context cx, int lineNumber) {
RequestEvaluator re = this.app.getCurrentRequestEvaluator();
AxiomDebugger debugger = (AxiomDebugger) cx.getDebugger();
if (debugger != null) {
boolean ignoreDebugging = false;
synchronized (debugger) {
if (debugger.callDepth > 0) {
ignoreDebugging = true;
}
}
if (ignoreDebugging) {
return;
}
}
if (re != null
&& (isBreakpoint(this.script.getSourceName(), lineNumber)
|| debugger.isStepping)) {
debugger.isStepping = false;
debugger.isJumping = false;
Debug debug = re.getSession().getDebugObject();
DebugMonitor monitor = debug.addWaitingEvaluator(re);
Scriptable scope = ((RhinoEngine) re.getScriptingEngine()).getGlobal();
DebugEvent event = new DebugEvent();
event.resourceName = this.script.getSourceName();
event.lineNumber = lineNumber;
event.functionName = this.script.getFunctionName();
event.scope = activationToScope(cx, scope, this.activation);
event.parentScope = this.activation.getParentScope();
event.thisObj = this.thisObj;
event.requestId = re.hashCode();
debug.pushEvent(event);
try {
synchronized (monitor) {
monitor.wait();
}
} catch (Exception ex) {
this.app.logError(ErrorReporter.errorMsg(this.getClass(), "onLineChange"), ex);
}
debugger.isStepping = monitor.isStepping;
debugger.isJumping = monitor.isJumping;
monitor.isStepping = false;
monitor.isJumping = false;
}
}
public void onExceptionThrown(Context cx, Throwable ex) {
AxiomDebugger debugger = (AxiomDebugger) cx.getDebugger();
if (debugger != null) {
boolean ignoreDebugging = false;
synchronized (debugger) {
if (debugger.callDepth > 0) {
ignoreDebugging = true;
}
}
if (ignoreDebugging) {
return;
}
}
RequestEvaluator re = this.app.getCurrentRequestEvaluator();
if (re != null && isOnExceptionSet()) {
Debug debug = re.getSession().getDebugObject();
DebugMonitor monitor = debug.addWaitingEvaluator(re);
Scriptable scope = ((RhinoEngine) re.getScriptingEngine()).getGlobal();
DebugEvent event = new DebugEvent();
event.resourceName = this.script.getSourceName();
event.functionName = this.script.getFunctionName();
event.scope = activationToScope(cx, scope, this.activation);
event.parentScope = this.activation.getParentScope();
event.thisObj = this.thisObj;
if (ex instanceof RhinoException) {
event.lineNumber = ((RhinoException) ex).lineNumber();
}
event.requestId = re.hashCode();
event.exception = ex;
event.eventType = DebugEvent.EXCEPTION;
debug.pushEvent(event);
try {
synchronized (monitor) {
monitor.wait();
}
} catch (Exception iex) {
this.app.logError(ErrorReporter.errorMsg(this.getClass(), "onExceptionThrown"), ex);
}
debugger.isStepping = monitor.isStepping;
monitor.isStepping = false;
monitor.isJumping = false;
}
}
private boolean isBreakpoint(String sourceName, int lineNumber) {
boolean isBreakpoint = false;
try {
Debug debug = this.app.getCurrentRequestEvaluator().getSession().getDebugObject();
isBreakpoint = debug.isBreakpointSet(sourceName, lineNumber);
} catch (Exception ex) {
isBreakpoint = false;
}
return isBreakpoint;
}
private boolean isOnExceptionSet() {
boolean isExceptionSet = false;
try {
Debug debug = this.app.getCurrentRequestEvaluator().getSession().getDebugObject();
isExceptionSet = debug.jsFunction_getBreakOnException();
} catch (Exception ex) {
isExceptionSet = false;
}
return isExceptionSet;
}
private boolean skipFunction() {
boolean skip = false;
try {
Debug debug = this.app.getCurrentRequestEvaluator().getSession().getDebugObject();
String funcName = null, protoName = null;
if (this.script != null) {
funcName = this.script.getFunctionName();
}
if (this.thisObj != null) {
protoName = this.thisObj.getClassName();
}
skip = debug.isWhitelisted(protoName, funcName);
} catch (Exception ex) {
skip = false;
}
return skip;
}
private boolean isOnFunctionEnterSet() {
boolean isEnterSet = false;
try {
Debug debug = this.app.getCurrentRequestEvaluator().getSession().getDebugObject();
isEnterSet = debug.jsFunction_getBreakOnFunctionEntry();
} catch (Exception ex) {
isEnterSet = false;
}
return isEnterSet;
}
private boolean isOnFunctionExitSet() {
boolean isExitSet = false;
try {
Debug debug = this.app.getCurrentRequestEvaluator().getSession().getDebugObject();
isExitSet = debug.jsFunction_getBreakOnFunctionExit();
} catch (Exception ex) {
isExitSet = false;
}
return isExitSet;
}
private Scriptable activationToScope(Context cx, Scriptable scope,
Scriptable activation) {
Scriptable obj = cx.newObject(scope);
Object[] ids = activation.getIds();
for (int i = 0; i < ids.length; i++) {
String id = (String) ids[i];
obj.put(id, obj, activation.get(id, activation));
}
return obj;
}
private int getStartLineNum() {
int line = -1;
int[] linenums = this.script.getLineNumbers();
if (linenums != null && linenums.length > 0) {
Arrays.sort(linenums);
this.sortedLineNums = linenums;
line = linenums[0];
}
return line;
}
private int getEndLineNum() {
if (this.sortedLineNums != null) {
return this.sortedLineNums[this.sortedLineNums.length - 1];
}
int line = -1;
int[] linenums = this.script.getLineNumbers();
if (linenums != null && linenums.length > 0) {
Arrays.sort(linenums);
line = linenums[linenums.length - 1];
}
return line;
}
}
} | agpl-3.0 |
Metatavu/kunta-api-spec | jaxrs-spec-generated/src/main/java/fi/metatavu/kuntaapi/server/rest/model/PrintableFormServiceChannel.java | 13567 | package fi.metatavu.kuntaapi.server.rest.model;
import fi.metatavu.kuntaapi.server.rest.model.Address;
import fi.metatavu.kuntaapi.server.rest.model.Area;
import fi.metatavu.kuntaapi.server.rest.model.Email;
import fi.metatavu.kuntaapi.server.rest.model.LocalizedValue;
import fi.metatavu.kuntaapi.server.rest.model.Phone;
import fi.metatavu.kuntaapi.server.rest.model.ServiceChannelAttachment;
import fi.metatavu.kuntaapi.server.rest.model.ServiceHour;
import fi.metatavu.kuntaapi.server.rest.model.WebPage;
import java.util.ArrayList;
import java.util.List;
import io.swagger.annotations.*;
import java.util.Objects;
public class PrintableFormServiceChannel implements java.io.Serializable {
private String id = null;
private String organizationId = null;
private List<LocalizedValue> names = new ArrayList<LocalizedValue>();
private List<LocalizedValue> descriptions = new ArrayList<LocalizedValue>();
private List<LocalizedValue> formIdentifier = new ArrayList<LocalizedValue>();
private List<LocalizedValue> formReceiver = new ArrayList<LocalizedValue>();
private Address deliveryAddress = null;
private List<LocalizedValue> channelUrls = new ArrayList<LocalizedValue>();
private List<ServiceChannelAttachment> attachments = new ArrayList<ServiceChannelAttachment>();
private List<Phone> supportPhones = new ArrayList<Phone>();
private List<Email> supportEmails = new ArrayList<Email>();
private List<String> languages = new ArrayList<String>();
private List<WebPage> webPages = new ArrayList<WebPage>();
private List<ServiceHour> serviceHours = new ArrayList<ServiceHour>();
private String publishingStatus = null;
private String areaType = null;
private List<Area> areas = new ArrayList<Area>();
/**
* Identifier for the service channel.
**/
public PrintableFormServiceChannel id(String id) {
this.id = id;
return this;
}
@ApiModelProperty(example = "null", value = "Identifier for the service channel.")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* Organization identifier responsible for the channel.
**/
public PrintableFormServiceChannel organizationId(String organizationId) {
this.organizationId = organizationId;
return this;
}
@ApiModelProperty(example = "null", value = "Organization identifier responsible for the channel.")
public String getOrganizationId() {
return organizationId;
}
public void setOrganizationId(String organizationId) {
this.organizationId = organizationId;
}
/**
* Localized list of service channel names.
**/
public PrintableFormServiceChannel names(List<LocalizedValue> names) {
this.names = names;
return this;
}
@ApiModelProperty(example = "null", value = "Localized list of service channel names.")
public List<LocalizedValue> getNames() {
return names;
}
public void setNames(List<LocalizedValue> names) {
this.names = names;
}
/**
* List of localized service channel descriptions.
**/
public PrintableFormServiceChannel descriptions(List<LocalizedValue> descriptions) {
this.descriptions = descriptions;
return this;
}
@ApiModelProperty(example = "null", value = "List of localized service channel descriptions.")
public List<LocalizedValue> getDescriptions() {
return descriptions;
}
public void setDescriptions(List<LocalizedValue> descriptions) {
this.descriptions = descriptions;
}
/**
* List of localized form identifier. One per language.
**/
public PrintableFormServiceChannel formIdentifier(List<LocalizedValue> formIdentifier) {
this.formIdentifier = formIdentifier;
return this;
}
@ApiModelProperty(example = "null", value = "List of localized form identifier. One per language.")
public List<LocalizedValue> getFormIdentifier() {
return formIdentifier;
}
public void setFormIdentifier(List<LocalizedValue> formIdentifier) {
this.formIdentifier = formIdentifier;
}
/**
* List of localized form receiver. One per language.
**/
public PrintableFormServiceChannel formReceiver(List<LocalizedValue> formReceiver) {
this.formReceiver = formReceiver;
return this;
}
@ApiModelProperty(example = "null", value = "List of localized form receiver. One per language.")
public List<LocalizedValue> getFormReceiver() {
return formReceiver;
}
public void setFormReceiver(List<LocalizedValue> formReceiver) {
this.formReceiver = formReceiver;
}
/**
* Form delivery address.
**/
public PrintableFormServiceChannel deliveryAddress(Address deliveryAddress) {
this.deliveryAddress = deliveryAddress;
return this;
}
@ApiModelProperty(example = "null", value = "Form delivery address.")
public Address getDeliveryAddress() {
return deliveryAddress;
}
public void setDeliveryAddress(Address deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
/**
* List of localized channel urls.
**/
public PrintableFormServiceChannel channelUrls(List<LocalizedValue> channelUrls) {
this.channelUrls = channelUrls;
return this;
}
@ApiModelProperty(example = "null", value = "List of localized channel urls.")
public List<LocalizedValue> getChannelUrls() {
return channelUrls;
}
public void setChannelUrls(List<LocalizedValue> channelUrls) {
this.channelUrls = channelUrls;
}
/**
* List of attachments.
**/
public PrintableFormServiceChannel attachments(List<ServiceChannelAttachment> attachments) {
this.attachments = attachments;
return this;
}
@ApiModelProperty(example = "null", value = "List of attachments.")
public List<ServiceChannelAttachment> getAttachments() {
return attachments;
}
public void setAttachments(List<ServiceChannelAttachment> attachments) {
this.attachments = attachments;
}
/**
* List of support phone numbers for the service channel.
**/
public PrintableFormServiceChannel supportPhones(List<Phone> supportPhones) {
this.supportPhones = supportPhones;
return this;
}
@ApiModelProperty(example = "null", value = "List of support phone numbers for the service channel.")
public List<Phone> getSupportPhones() {
return supportPhones;
}
public void setSupportPhones(List<Phone> supportPhones) {
this.supportPhones = supportPhones;
}
/**
* List of support email addresses for the service channel.
**/
public PrintableFormServiceChannel supportEmails(List<Email> supportEmails) {
this.supportEmails = supportEmails;
return this;
}
@ApiModelProperty(example = "null", value = "List of support email addresses for the service channel.")
public List<Email> getSupportEmails() {
return supportEmails;
}
public void setSupportEmails(List<Email> supportEmails) {
this.supportEmails = supportEmails;
}
/**
* List of languages the service channel is available in (two letter language code).
**/
public PrintableFormServiceChannel languages(List<String> languages) {
this.languages = languages;
return this;
}
@ApiModelProperty(example = "null", value = "List of languages the service channel is available in (two letter language code).")
public List<String> getLanguages() {
return languages;
}
public void setLanguages(List<String> languages) {
this.languages = languages;
}
/**
* List of service channel web pages.
**/
public PrintableFormServiceChannel webPages(List<WebPage> webPages) {
this.webPages = webPages;
return this;
}
@ApiModelProperty(example = "null", value = "List of service channel web pages.")
public List<WebPage> getWebPages() {
return webPages;
}
public void setWebPages(List<WebPage> webPages) {
this.webPages = webPages;
}
/**
* List of service channel service hours.
**/
public PrintableFormServiceChannel serviceHours(List<ServiceHour> serviceHours) {
this.serviceHours = serviceHours;
return this;
}
@ApiModelProperty(example = "null", value = "List of service channel service hours.")
public List<ServiceHour> getServiceHours() {
return serviceHours;
}
public void setServiceHours(List<ServiceHour> serviceHours) {
this.serviceHours = serviceHours;
}
/**
* Service channel publishing status. Values: Draft, Published, Deleted, Modified or OldPublished.
**/
public PrintableFormServiceChannel publishingStatus(String publishingStatus) {
this.publishingStatus = publishingStatus;
return this;
}
@ApiModelProperty(example = "null", value = "Service channel publishing status. Values: Draft, Published, Deleted, Modified or OldPublished.")
public String getPublishingStatus() {
return publishingStatus;
}
public void setPublishingStatus(String publishingStatus) {
this.publishingStatus = publishingStatus;
}
/**
* Area type (WholeCountry, WholeCountryExceptAlandIslands, AreaType).
**/
public PrintableFormServiceChannel areaType(String areaType) {
this.areaType = areaType;
return this;
}
@ApiModelProperty(example = "null", value = "Area type (WholeCountry, WholeCountryExceptAlandIslands, AreaType).")
public String getAreaType() {
return areaType;
}
public void setAreaType(String areaType) {
this.areaType = areaType;
}
/**
* List of service channel areas.
**/
public PrintableFormServiceChannel areas(List<Area> areas) {
this.areas = areas;
return this;
}
@ApiModelProperty(example = "null", value = "List of service channel areas.")
public List<Area> getAreas() {
return areas;
}
public void setAreas(List<Area> areas) {
this.areas = areas;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PrintableFormServiceChannel printableFormServiceChannel = (PrintableFormServiceChannel) o;
return Objects.equals(id, printableFormServiceChannel.id) &&
Objects.equals(organizationId, printableFormServiceChannel.organizationId) &&
Objects.equals(names, printableFormServiceChannel.names) &&
Objects.equals(descriptions, printableFormServiceChannel.descriptions) &&
Objects.equals(formIdentifier, printableFormServiceChannel.formIdentifier) &&
Objects.equals(formReceiver, printableFormServiceChannel.formReceiver) &&
Objects.equals(deliveryAddress, printableFormServiceChannel.deliveryAddress) &&
Objects.equals(channelUrls, printableFormServiceChannel.channelUrls) &&
Objects.equals(attachments, printableFormServiceChannel.attachments) &&
Objects.equals(supportPhones, printableFormServiceChannel.supportPhones) &&
Objects.equals(supportEmails, printableFormServiceChannel.supportEmails) &&
Objects.equals(languages, printableFormServiceChannel.languages) &&
Objects.equals(webPages, printableFormServiceChannel.webPages) &&
Objects.equals(serviceHours, printableFormServiceChannel.serviceHours) &&
Objects.equals(publishingStatus, printableFormServiceChannel.publishingStatus) &&
Objects.equals(areaType, printableFormServiceChannel.areaType) &&
Objects.equals(areas, printableFormServiceChannel.areas);
}
@Override
public int hashCode() {
return Objects.hash(id, organizationId, names, descriptions, formIdentifier, formReceiver, deliveryAddress, channelUrls, attachments, supportPhones, supportEmails, languages, webPages, serviceHours, publishingStatus, areaType, areas);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PrintableFormServiceChannel {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" organizationId: ").append(toIndentedString(organizationId)).append("\n");
sb.append(" names: ").append(toIndentedString(names)).append("\n");
sb.append(" descriptions: ").append(toIndentedString(descriptions)).append("\n");
sb.append(" formIdentifier: ").append(toIndentedString(formIdentifier)).append("\n");
sb.append(" formReceiver: ").append(toIndentedString(formReceiver)).append("\n");
sb.append(" deliveryAddress: ").append(toIndentedString(deliveryAddress)).append("\n");
sb.append(" channelUrls: ").append(toIndentedString(channelUrls)).append("\n");
sb.append(" attachments: ").append(toIndentedString(attachments)).append("\n");
sb.append(" supportPhones: ").append(toIndentedString(supportPhones)).append("\n");
sb.append(" supportEmails: ").append(toIndentedString(supportEmails)).append("\n");
sb.append(" languages: ").append(toIndentedString(languages)).append("\n");
sb.append(" webPages: ").append(toIndentedString(webPages)).append("\n");
sb.append(" serviceHours: ").append(toIndentedString(serviceHours)).append("\n");
sb.append(" publishingStatus: ").append(toIndentedString(publishingStatus)).append("\n");
sb.append(" areaType: ").append(toIndentedString(areaType)).append("\n");
sb.append(" areas: ").append(toIndentedString(areas)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| agpl-3.0 |
Kachachan/musicblocks | js/rhythmruler.js | 30098 | // Copyright (c) 2016 Walter Bender
// Copyright (c) 2016 Hemant Kasat
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
// This widget enable us to create a rhythms which can be imported
// into the pitch-time matrix and hence used to create chunks of
// notes.
function RhythmRuler () {
// There is one ruler per drum.
this.Drums = [];
// Rulers, one per drum, contain the subdivisions defined by rhythm blocks.
this.Rulers = [];
// Save the history of divisions so as to be able to restore them.
this._dissectHistory = [];
this._playing = false;
this._playingOne = false;
this._playingAll = false;
this._cellCounter = 0;
// Keep a running time for each ruler to maintain sync.
this._runningTimes = [];
// Starting time from which we measure for sync.
this._startingTime = null;
this._offset = 0;
this._rulerSelected = 0;
this._rulerPlaying = -1;
this._noteWidth = function (noteValue) {
return Math.floor(EIGHTHNOTEWIDTH * (8 / noteValue) * this._cellScale * 3) + 'px';
};
this._calculateZebraStripes = function(rulerno) {
var ruler = docById('ruler' + rulerno);
if (this._rulerSelected % 2 === 0) {
var evenColor = MATRIXNOTECELLCOLOR;
} else {
var evenColor = MATRIXNOTECELLCOLORHOVER;
}
for (var i = 0; i < ruler.cells.length; i++) {
var newCell = ruler.cells[i];
if (evenColor === MATRIXNOTECELLCOLOR) {
if (i % 2 === 0) {
newCell.style.backgroundColor = MATRIXNOTECELLCOLOR;
} else {
newCell.style.backgroundColor = MATRIXNOTECELLCOLORHOVER;
}
}
if (evenColor === MATRIXNOTECELLCOLORHOVER) {
if (i % 2 === 0) {
newCell.style.backgroundColor = MATRIXNOTECELLCOLORHOVER;
} else {
newCell.style.backgroundColor = MATRIXNOTECELLCOLOR;
}
}
}
};
this._dissectRuler = function (event) {
var inputNum = docById('dissectNumber').value;
if (isNaN(inputNum)) {
inputNum = 2;
} else {
inputNum = Math.abs(Math.floor(inputNum));
}
docById('dissectNumber').value = inputNum;
var cell = event.target;
this._rulerSelected = cell.parentNode.id[5];
this.__dissect(cell, inputNum);
};
this.__dissect = function (cell, inputNum) {
var that = this;
var ruler = docById('ruler' + this._rulerSelected);
var newCellIndex = cell.cellIndex;
var noteValues = this.Rulers[this._rulerSelected][0];
var divisionHistory = this.Rulers[this._rulerSelected][1];
divisionHistory.push([newCellIndex, inputNum]);
ruler.deleteCell(newCellIndex);
var noteValue = noteValues[newCellIndex];
var newNoteValue = inputNum * noteValue;
var tempwidth = this._noteWidth(newNoteValue);
var tempwidthPixels = parseFloat(inputNum) * parseFloat(tempwidth) + 'px';
var difference = parseFloat(this._noteWidth(noteValue)) - parseFloat(inputNum) * parseFloat(tempwidth);
var newCellWidth = parseFloat(this._noteWidth(newNoteValue)) + parseFloat(difference) / inputNum + 'px';
noteValues.splice(newCellIndex, 1);
for (var i = 0; i < inputNum; i++) {
var newCell = ruler.insertCell(newCellIndex+i);
noteValues.splice(newCellIndex + i, 0, newNoteValue);
newCell.innerHTML = calcNoteValueToDisplay(newNoteValue, 1);
newCell.style.width = newCellWidth;
newCell.style.minWidth = newCell.style.width;
newCell.style.maxWidth = newCell.style.width;
newCell.addEventListener('click', function(event) {
that._dissectRuler(event);
});
}
this._calculateZebraStripes(that._rulerSelected);
};
this._undo = function() {
var divisionHistory = this.Rulers[this._rulerSelected][1];
if (divisionHistory.length === 0) {
// FIXME: Cycle through other rulers if necessary.
return;
}
var ruler = docById('ruler' + this._rulerSelected);
var noteValues = this.Rulers[this._rulerSelected][0];
var inputNum = divisionHistory[divisionHistory.length - 1][1];
var newCellIndex = divisionHistory[divisionHistory.length - 1][0];
var cellWidth = ruler.cells[newCellIndex].style.width;
var newCellWidth = parseFloat(cellWidth)*inputNum;
var oldCellNoteValue = noteValues[newCellIndex];
var newNoteValue = oldCellNoteValue/inputNum;
var newCell = ruler.insertCell(newCellIndex);
newCell.style.width = this._noteWidth(newNoteValue);
newCell.style.minWidth = newCell.style.width;
newCell.style.maxWidth = newCell.style.width;
newCell.style.backgroundColor = MATRIXNOTECELLCOLOR;
newCell.innerHTML = calcNoteValueToDisplay(oldCellNoteValue/inputNum, 1);
noteValues[newCellIndex] = oldCellNoteValue/inputNum;
noteValues.splice(newCellIndex + 1, inputNum - 1);
var that = this;
newCell.addEventListener('click', function(event) {
console.log('adding DISSECT event too');
that._dissectRuler(event);
});
for (var i = 0; i < inputNum; i++) {
ruler.deleteCell(newCellIndex + 1);
}
divisionHistory.pop();
this._calculateZebraStripes(this._rulerSelected);
};
this.__playNote = function(i) {
var noteValues = this.Rulers[i][0];
var noteValue = noteValues[0];
var drumBlockNo = this._logo.blocks.blockList[this.Drums[i]].connections[1];
var drum = this._logo.blocks.blockList[drumBlockNo].value;
var ruler = docById('ruler' + i);
var cell = ruler.cells[0];
cell.style.backgroundColor = MATRIXBUTTONCOLOR;
this._logo.synth.trigger(0, this._logo.defaultBPMFactor / noteValue, drum);
if (this._playingAll || this._playingOne) {
this.__loop(0, 0, i, 1);
}
}
this._playAll = function() {
this._logo.synth.stop();
if (this._startingTime == null) {
var d = new Date();
this._startingTime = d.getTime();
this._offset = 0;
}
for (var i = 0; i < this.Rulers.length; i++) {
this.__playNote(i);
}
};
this._playOne = function() {
this._logo.synth.stop();
if (this._startingTime == null) {
var d = new Date();
this._startingTime = d.getTime();
this._offset = 0;
}
this.__playNote(this._rulerSelected);
};
this.__loop = function(time, notesCounter, rulerNo, colIndex) {
if (docById('rulerBody').style.visibility === 'hidden') {
return;
}
if (docById('drumDiv').style.visibility === 'hidden') {
return;
}
var noteValues = this.Rulers[rulerNo][0];
var noteValue = noteValues[notesCounter];
time = 1 / noteValue;
var drumblockno = this._logo.blocks.blockList[this.Drums[rulerNo]].connections[1];
var drum = this._logo.blocks.blockList[drumblockno].value;
var that = this;
setTimeout(function() {
var ruler = docById('ruler' + rulerNo);
if (ruler == null) {
console.log('Cannot find ruler ' + rulerNo + '. Widget closed?');
return;
}
if (notesCounter === noteValues.length - 1) {
// When we get to the end of the rulers, reset the background color.
for (var i = 0; i < ruler.cells.length; i++) {
var cell = ruler.cells[i];
cell.style.backgroundColor = MATRIXNOTECELLCOLOR;
}
} else {
// Mark the current cell.
var cell = ruler.cells[colIndex];
if (that._playing) {
cell.style.backgroundColor = MATRIXBUTTONCOLOR;
}
}
if (notesCounter >= noteValues.length) {
notesCounter = 1;
that._logo.synth.stop()
}
notesCounter += 1;
colIndex += 1;
if (that._playing) {
var d = new Date();
that._offset = d.getTime() - that._startingTime - that._runningTimes[rulerNo];
that._logo.synth.trigger([0], that._logo.defaultBPMFactor / noteValue, drum);
}
if (notesCounter < noteValues.length) {
if (that._playing) {
that.__loop(time, notesCounter, rulerNo, colIndex);
}
} else {
that._cellCounter += 1;
}
if (that._playingAll) {
if (that._cellCounter === that.Rulers.length) {
that._cellCounter = 0;
var cell = ruler.cells[0];
cell.style.backgroundColor = MATRIXNOTECELLCOLOR;
for (var i = 0; i < that.Rulers.length; i++) {
that._calculateZebraStripes(i);
}
that._playAll();
}
} else if (that._playingOne) {
if (that._cellCounter === 1) {
that._cellCounter = 0;
var cell = ruler.cells[0];
cell.style.backgroundColor = MATRIXNOTECELLCOLOR;
that._calculateZebraStripes(that._rulerPlaying);
that._playOne();
}
}
}, this._logo.defaultBPMFactor * 1000 * time - this._offset);
that._runningTimes[rulerNo] += that._logo.defaultBPMFactor * 1000 * time;
};
this._save = function(selectedRuler) {
var that = this;
for (var name in this._logo.blocks.palettes.dict) {
this._logo.blocks.palettes.dict[name].hideMenu(true);
}
this._logo.refreshCanvas();
setTimeout(function() {
var ruler = docById('ruler' + selectedRuler);
var noteValues = that.Rulers[selectedRuler][0];
var stack_value = (that._logo.blocks.blockList[that._logo.blocks.blockList[that.Drums[selectedRuler]].connections[1]].value).split(" ")[0] + "_rhythm"; //get first word of drum's name (skip "drum" word itself) and add "rhythm"
var delta = selectedRuler * 42;
var newStack = [[0, ['action', {'collapsed': false}], 100 + delta, 100 + delta, [null, 1, 2, null]], [1, ['text', {'value': stack_value}], 0, 0, [0]]];
var previousBlock = 0;
var sameNoteValue = 1;
for (var i = 0; i < ruler.cells.length; i++) {
if (noteValues[i] === noteValues[i + 1] && i < ruler.cells.length - 1) {
sameNoteValue += 1;
continue;
} else {
var idx = newStack.length;
var noteValue = noteValues[i];
newStack.push([idx, 'rhythm', 0, 0, [previousBlock, idx + 1, idx + 2, idx + 3]]);
newStack.push([idx + 1, ['number', {'value': sameNoteValue}], 0, 0, [idx]]);
newStack.push([idx + 2, ['number', {'value': noteValue}], 0, 0, [idx]]);
if (i == ruler.cells.length - 1) {
newStack.push([idx + 3, 'hidden', 0, 0, [idx, null]]);
}
else {
newStack.push([idx + 3, 'hidden', 0, 0, [idx, idx + 4]]);
}
previousBlock = idx + 3;
sameNoteValue = 1;
}
}
that._logo.blocks.loadNewBlocks(newStack);
if (selectedRuler > that.Rulers.length - 2) {
return;
} else {
that._save(selectedRuler + 1);
}
}, 500);
};
this._saveDrumMachine = function(selectedRuler) {
var that = this;
for (var name in this._logo.blocks.palettes.dict) {
this._logo.blocks.palettes.dict[name].hideMenu(true);
}
this._logo.refreshCanvas();
setTimeout(function() {
var ruler = docById('ruler' + selectedRuler);
var noteValues = that.Rulers[selectedRuler][0];
var delta = selectedRuler * 42;
var newStack = [[0, ['start', {'collapsed': false}], 100 + delta, 100 + delta, [null, 1, null]]];
newStack.push([1, 'forever', 0, 0, [0, 2, null]]);
var previousBlock = 1;
var sameNoteValue = 1;
for (var i = 0; i < ruler.cells.length; i++) {
if (noteValues[i] === noteValues[i + 1] && i < ruler.cells.length - 1) {
sameNoteValue += 1;
continue;
} else {
var idx = newStack.length;
var noteValue = noteValues[i];
var drumBlockNo = that._logo.blocks.blockList[that.Drums[selectedRuler]].connections[1];
var drum = that._logo.blocks.blockList[drumBlockNo].value;
if (sameNoteValue === 1) {
// Add a note block
newStack.push([idx, 'newnote', 0, 0, [previousBlock, idx + 1, idx + 4, idx + 7]]);
newStack.push([idx + 1, 'divide', 0, 0, [idx, idx + 2, idx + 3]]);
newStack.push([idx + 2, ['number', {'value': 1}], 0, 0, [idx + 1]]);
newStack.push([idx + 3, ['number', {'value': noteValue}], 0, 0, [idx + 1]]);
newStack.push([idx + 4, 'vspace', 0, 0, [idx, idx + 5]]);
newStack.push([idx + 5, 'playdrum', 0, 0, [idx + 4, idx + 6, null]]);
newStack.push([idx + 6, ['drumname', {'value': drum}], 0, 0, [idx + 5]]);
if (i == ruler.cells.length - 1) {
newStack.push([idx + 7, 'hidden', 0, 0, [idx, null]]);
} else {
newStack.push([idx + 7, 'hidden', 0, 0, [idx, idx + 8]]);
previousBlock = idx + 7;
}
} else {
// Add a note block inside a repeat block
if (i == ruler.cells.length - 1) {
newStack.push([idx, 'repeat', 0, 0, [previousBlock, idx + 1, idx + 2, null]]);
} else {
newStack.push([idx, 'repeat', 0, 0, [previousBlock, idx + 1, idx + 2, idx + 10]]);
previousBlock = idx;
}
newStack.push([idx + 1, ['number', {'value': sameNoteValue}], 0, 0, [idx]]);
newStack.push([idx + 2, 'newnote', 0, 0, [idx, idx + 3, idx + 6, idx + 9]]);
newStack.push([idx + 3, 'divide', 0, 0, [idx + 2, idx + 4, idx + 5]]);
newStack.push([idx + 4, ['number', {'value': 1}], 0, 0, [idx + 3]]);
newStack.push([idx + 5, ['number', {'value': noteValue}], 0, 0, [idx + 3]]);
newStack.push([idx + 6, 'vspace', 0, 0, [idx + 2, idx + 7]]);
newStack.push([idx + 7, 'playdrum', 0, 0, [idx + 6, idx + 8, null]]);
newStack.push([idx + 8, ['drumname', {'value': drum}], 0, 0, [idx + 7]]);
newStack.push([idx + 9, 'hidden', 0, 0, [idx + 2, null]]);
}
sameNoteValue = 1;
}
}
that._logo.blocks.loadNewBlocks(newStack);
if (selectedRuler > that.Rulers.length - 2) {
return;
} else {
that._saveDrumMachine(selectedRuler + 1);
}
}, 500);
};
this.init = function(logo) {
console.log('init RhythmRuler');
this._logo = logo;
docById('rulerBody').style.display = 'inline';
console.log('setting RhythmRuler visible');
docById('rulerBody').style.visibility = 'visible';
docById('rulerBody').style.border = 2;
docById('drumDiv').style.display = 'inline';
docById('drumDiv').style.visibility = 'visible';
docById('drumDiv').style.border = 2;
var w = window.innerWidth;
this._cellScale = w / 1200;
var iconSize = Math.floor(this._cellScale * 24);
docById('rulerBody').style.width = Math.floor(w / 2) + 'px';
docById('rulerBody').style.overflowX = 'auto';
docById('drumDiv').style.width = Math.max(iconSize, Math.floor(w / 24)) + 'px';
docById('drumDiv').style.overflowX = 'auto';
var that = this;
var table = docById('buttonTable');
if (table !== null) {
table.remove();
}
var table = docById('drum');
if (table !== null) {
table.remove();
}
this._runningTimes = [];
for (var i = 0; i < this.Rulers.length; i++) {
var rulertable = docById('rulerTable' + i);
var rulerdrum = docById('rulerdrum' + i);
this._runningTimes.push(0);
}
// The play all button
var x = document.createElement('TABLE');
x.setAttribute('id', 'drum');
x.style.textAlign = 'center';
x.style.borderCollapse = 'collapse';
x.cellSpacing = 0;
x.cellPadding = 0;
var drumDiv = docById('drumDiv');
drumDiv.style.paddingTop = 0 + 'px';
drumDiv.style.paddingLeft = 0 + 'px';
drumDiv.appendChild(x);
drumDivPosition = drumDiv.getBoundingClientRect();
var table = docById('drum');
var row = table.insertRow(0);
row.setAttribute('id', 'playalldrums');
row.style.left = Math.floor(drumDivPosition.left) + 'px';
row.style.top = Math.floor(drumDivPosition.top) + 'px';
var cell = this._addButton(row, -1, 'play-button.svg', iconSize, _('play all'));
cell.onclick=function() {
if (that._playing) {
if (that._playingAll) {
this.innerHTML = ' <img src="header-icons/play-button.svg" title="' + _('play all') + '" alt="' + _('play all') + '" height="' + iconSize + '" width="' + iconSize + '" vertical-align="middle"> ';
that._playing = false;
that._playingAll = false;
that._playingOne = false;
that._rulerPlaying = -1;
that._startingTime = null;
for (var i = 0; i < that.Rulers.length; i++) {
that._calculateZebraStripes(i);
}
}
}
else {
if (!that._playingAll) {
this.innerHTML = ' <img src="header-icons/pause-button.svg" title="' + _('pause') + '" alt="' + _('pause') + '" height="' + iconSize + '" width="' + iconSize + '" vertical-align="middle"> ';
that._logo.setTurtleDelay(0);
that._playingAll = true;
that._playing = true;
that._playingOne = false;
that._cellCounter = 0;
that._rulerPlaying = -1;
for (var i = 0; i < that.Rulers.length; i++) {
that._runningTimes[i] = 0;
}
that._playAll();
}
}
};
// Add rows for drum play buttons.
for (var i = 0; i < this.Rulers.length; i++) {
var row = table.insertRow(i + 1);
row.setAttribute('id', 'drum' + i);
}
// Add tool buttons to top row
var x = document.createElement('TABLE');
x.setAttribute('id', 'buttonTable');
x.style.textAlign = 'center';
x.style.borderCollapse = 'collapse';
x.cellSpacing = 0;
x.cellPadding = 0;
var rulerBodyDiv = docById('rulerBody');
rulerBodyDiv.style.paddingTop = 0 + 'px';
rulerBodyDiv.style.paddingLeft = 0 + 'px';
rulerBodyDiv.appendChild(x);
rulerBodyDivPosition = rulerBodyDiv.getBoundingClientRect();
var table = docById('buttonTable');
var header = table.createTHead();
var row = header.insertRow(0);
var cell = this._addButton(row, -1, 'export-chunk.svg', iconSize, _('save rhythms'));
cell.onclick=function() {
that._save(0);
};
var cell = this._addButton(row, 1, 'export-drums.svg', iconSize, _('save drum machine'));
cell.onclick=function() {
that._saveDrumMachine(0);
};
var cell = this._addButton(row, 2, 'restore-button.svg', iconSize, _('undo'));
cell.onclick=function() {
that._undo();
};
// An input for setting the dissect number
var cell = row.insertCell(2);
cell.innerHTML = '<input id="dissectNumber" style="-webkit-user-select: text;-moz-user-select: text;-ms-user-select: text;" class="dissectNumber" type="dussectNumber" value="' + 2 + '" />';
cell.style.top = 0;
cell.style.left = 0;
cell.style.width = Math.floor(MATRIXBUTTONHEIGHT * this._cellScale) + 'px';
cell.style.minWidth = cell.style.width;
cell.style.maxWidth = cell.style.width;
cell.style.height = Math.floor(MATRIXBUTTONHEIGHT * this._cellScale) + 'px';
cell.style.backgroundColor = MATRIXBUTTONCOLOR;
var cell = this._addButton(row, 4, 'close-button.svg', iconSize, _('close'));
cell.onclick=function() {
// Save the new dissect history
var dissectHistory = [];
var drums = [];
for (var i = 0; i < that.Rulers.length; i++) {
var history = [];
for (var j = 0; j < that.Rulers[i][1].length; j++) {
history.push(that.Rulers[i][1][j]);
}
docById('dissectNumber').classList.add('hasKeyboard');
dissectHistory.push([history, that.Drums[i]]);
drums.push(that.Drums[i]);
}
// Look for any old entries that we may have missed.
for (var i = 0; i < that._dissectHistory.length; i++) {
var drum = that._dissectHistory[i][1];
if (drums.indexOf(drum) === -1) {
var history = JSON.parse(JSON.stringify(that._dissectHistory[i][0]));
dissectHistory.push([history, drum]);
}
}
that._dissectHistory = JSON.parse(JSON.stringify(dissectHistory));
for (var i = 0; i < that.Rulers.length; i++) {
var rulertable = docById('rulerTable' + i);
var rulerdrum = docById('rulerdrum' + i);
if (rulertable !== null) {
rulertable.remove();
}
if (rulerdrum !== null) {
rulerdrum.remove();
}
}
docById('rulerBody').style.visibility = 'hidden';
docById('drumDiv').style.visibility = 'hidden';
docById('rulerBody').style.border = 0;
docById('drumDiv').style.border = 0;
that._playing = false;
that._playingOne = false;
that._playingAll = false;
};
// Create a play button for each ruler
var table = docById('drum');
for (var i = 0; i < this.Rulers.length; i++) {
var row = table.rows[i + 1];
var drumcell = this._addButton(row, -1, 'play-button.svg', iconSize, _('play'));
drumcell.onclick=function() {
if (that._playing) {
if (this.parentNode.id[4] === that._rulerPlaying) {
this.innerHTML = ' <img src="header-icons/play-button.svg" title="' + _('play') + '" alt="' + _('play') + '" height="' + iconSize + '" width="' + iconSize + '" vertical-align="middle"> ';
that._playing = false;
that._playingOne = false;
that._playingAll = false;
that._rulerPlaying = -1;
that._startingTime = null;
setTimeout(that._calculateZebraStripes(this.parentNode.id[4]),1000);
}
}
else {
if (that._playingOne === false) {
that._rulerSelected = this.parentNode.id[4];
that._logo.setTurtleDelay(0);
that._playing = true;
that._playingOne = true;
that._playingAll = false;
that._cellCounter = 0;
that._rulerPlaying = this.parentNode.id[4];
this.innerHTML = ' <img src="header-icons/pause-button.svg" title="' + _('pause') + '" alt="' + _('pause') + '" height="' + iconSize + '" width="' + iconSize + '" vertical-align="middle"> ';
that._runningTimes[i] = 0;
that._playOne();
}
}
};
// Create individual rulers as tables.
var rulerTable = document.createElement('TABLE');
rulerTable.setAttribute('id', 'rulerTable' + i);
rulerTable.style.textAlign = 'center';
rulerTable.style.borderCollapse = 'collapse';
rulerTable.cellSpacing = 0;
rulerTable.cellPadding = 0;
rulerBodyDiv.appendChild(rulerTable);
var row = rulerTable.insertRow(-1);
row.style.left = Math.floor(rulerBodyDivPosition.left) + 'px';
row.style.top = Math.floor(MATRIXBUTTONHEIGHT * this._cellScale) + 'px';
row.setAttribute('id', 'ruler' + i);
for (var j = 0; j < that.Rulers[i][0].length; j++) {
var noteValue = that.Rulers[i][0][j];
var rulercell = row.insertCell(j);
rulercell.innerHTML = calcNoteValueToDisplay(noteValue, 1);
rulercell.style.width = that._noteWidth(noteValue);
rulercell.minWidth = rulercell.style.width;
rulercell.maxWidth = rulercell.style.width;
rulercell.style.lineHeight = 60 + ' % ';
if (i % 2 === 0) {
if (j % 2 === 0) {
rulercell.style.backgroundColor = MATRIXNOTECELLCOLOR;
} else {
rulercell.style.backgroundColor = MATRIXNOTECELLCOLORHOVER;
}
} else {
if (j % 2 === 0) {
rulercell.style.backgroundColor = MATRIXNOTECELLCOLORHOVER;
} else {
rulercell.style.backgroundColor = MATRIXNOTECELLCOLOR;
}
}
rulercell.addEventListener('click', function(event) {
that._dissectRuler(event);
});
}
// Match the play button height to the ruler height.
table.rows[i + 1].cells[0].style.height = row.offsetHeight + 'px';
}
// Restore dissect history.
for (var drum = 0; drum < this.Drums.length; drum++) {
for (var i = 0; i < this._dissectHistory.length; i++) {
if (this._dissectHistory[i][1] !== this.Drums[drum]) {
continue;
}
var rulerTable = docById('rulerTable' + drum);
for (var j = 0; j < this._dissectHistory[i].length; j++) {
this._rulerSelected = drum;
if (this._dissectHistory[i][0][j] == undefined) {
continue;
}
var cell = rulerTable.rows[0].cells[this._dissectHistory[i][0][j][0]];
if (cell != undefined) {
this.__dissect(cell, this._dissectHistory[i][0][j][1]);
} else {
console.log('Could not find cell to divide. Did the order of the rhythm blocks change?');
}
}
}
}
};
this._addButton = function(row, colIndex, icon, iconSize, label) {
var cell = row.insertCell();
cell.innerHTML = ' <img src="header-icons/' + icon + '" title="' + label + '" alt="' + label + '" height="' + iconSize + '" width="' + iconSize + '" vertical-align="middle"> ';
cell.style.width = Math.floor(MATRIXBUTTONHEIGHT * this._cellScale) + 'px';
cell.style.minWidth = cell.style.width;
cell.style.maxWidth = cell.style.width;
cell.style.height = Math.floor(MATRIXBUTTONHEIGHT * this._cellScale) + 'px';
cell.style.backgroundColor = MATRIXBUTTONCOLOR;
cell.onmouseover=function() {
this.style.backgroundColor = MATRIXBUTTONCOLORHOVER;
}
cell.onmouseout=function() {
this.style.backgroundColor = MATRIXBUTTONCOLOR;
}
return cell;
};
};
| agpl-3.0 |
decidim/decidim | decidim-admin/lib/decidim/admin/test/filters_participatory_space_users_examples.rb | 2034 | # frozen_string_literal: true
shared_examples "filterable participatory space users" do
context "when filtering by invitation sent at" do
context "when filtering by null" do
it "returns participatory space users" do
apply_filter("Invitation sent", "Not sent")
within ".stack tbody" do
expect(page).to have_content(invited_user_2.name)
expect(page).to have_css("tr", count: 1)
end
end
end
context "when filtering by not null" do
it "returns participatory space users" do
apply_filter("Invitation sent", "Sent")
within ".stack tbody" do
expect(page).to have_content(invited_user_1.name)
expect(page).to have_css("tr", count: 1)
end
end
end
end
context "when filtering by invitation accepted at" do
context "when filtering by null" do
it "returns participatory space users" do
apply_filter("Invitation accepted", "Not accepted")
within ".stack tbody" do
expect(page).to have_content(invited_user_2.name)
expect(page).to have_css("tr", count: 1)
end
end
end
context "when filtering by not null" do
it "returns participatory space users" do
apply_filter("Invitation accepted", "Accepted")
within ".stack tbody" do
expect(page).to have_content(invited_user_1.name)
expect(page).to have_css("tr", count: 1)
end
end
end
end
end
shared_examples "searchable participatory space users" do
context "when searching by name or nickname or email" do
it "can be searched by name" do
search_by_text(name)
within ".stack tbody" do
expect(page).to have_content(name)
expect(page).to have_css("tr", count: 1)
end
end
it "can be searched by email" do
search_by_text(email)
within ".stack tbody" do
expect(page).to have_content(email)
expect(page).to have_css("tr", count: 1)
end
end
end
end
| agpl-3.0 |
InfinniPlatform/InfinniPlatform | InfinniPlatform.SandboxApp/Program.cs | 3038 | using System;
using System.IO;
using InfinniPlatform.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Filters;
namespace InfinniPlatform.SandboxApp
{
public class Program
{
public static void Main(string[] args)
{
ConfigureLogger();
try
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://*:9900")
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("AppConfig.json", true, true)
.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.UseStartup<Startup>()
.UseSerilog()
.Build();
host.Run();
}
catch (Exception e)
{
Log.Fatal(e, "Host terminated unexpectedly.");
}
finally
{
Log.CloseAndFlush();
}
}
private static void ConfigureLogger()
{
const string outputTemplate = "{Timestamp:o}|{Level:u3}|{RequestId}|{UserName}|{SourceContext}|{Message}{NewLine}{Exception}";
const string outputTemplatePerf = "{Timestamp:o}|{RequestId}|{UserName}|{SourceContext}|{Message}{NewLine}";
var performanceLoggerFilter = Matching.WithProperty<string>(Constants.SourceContextPropertyName,
p => p.StartsWith(nameof(IPerformanceLogger)));
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
//.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Logger(lc => lc.Filter.ByExcluding(performanceLoggerFilter)
.WriteTo.RollingFile("logs/events-{Date}.log",
outputTemplate: outputTemplate)
.WriteTo.LiterateConsole(outputTemplate: outputTemplate))
.WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(performanceLoggerFilter)
.WriteTo.RollingFile("logs/performance-{Date}.log",
outputTemplate: outputTemplatePerf))
.CreateLogger();
}
}
} | agpl-3.0 |
Tanaguru/Tanaguru | rules/rgaa4-2019/src/test/java/org/tanaguru/rules/rgaa42019/Rgaa42019Rule131002Test.java | 4472 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.rgaa42019;
import org.tanaguru.entity.audit.TestSolution;
import org.tanaguru.entity.audit.ProcessResult;
import org.tanaguru.rules.rgaa42019.test.Rgaa42019RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 13-10-2 of the referential Rgaa 4-2019.
*
* @author edaconceicao
*/
public class Rgaa42019Rule131002Test extends Rgaa42019RuleImplementationTestCase {
/**
* Default constructor
*/
public Rgaa42019Rule131002Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.tanaguru.rules.rgaa42019.Rgaa42019Rule131002");
}
@Override
protected void setUpWebResourceMap() {
// addWebResource("Rgaa4-2019.Test.13.10.2-1Passed-01");
// addWebResource("Rgaa4-2019.Test.13.10.2-2Failed-01");
addWebResource("Rgaa4-2019.Test.13.10.2-3NMI-01");
// addWebResource("Rgaa4-2019.Test.13.10.2-4NA-01");
}
@Override
protected void setProcess() {
//----------------------------------------------------------------------
//------------------------------1Passed-01------------------------------
//----------------------------------------------------------------------
// checkResultIsPassed(processPageTest("Rgaa4-2019.Test.13.10.2-1Passed-01"), 1);
//----------------------------------------------------------------------
//------------------------------2Failed-01------------------------------
//----------------------------------------------------------------------
// ProcessResult processResult = processPageTest("Rgaa4-2019.Test.13.10.2-2Failed-01");
// checkResultIsFailed(processResult, 1, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.FAILED,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------3NMI-01---------------------------------
//----------------------------------------------------------------------
ProcessResult processResult = processPageTest("Rgaa4-2019.Test.13.10.2-3NMI-01");
checkResultIsNotTested(processResult); // temporary result to make the result buildable before implementation
// checkResultIsPreQualified(processResult, 2, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.NEED_MORE_INFO,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------4NA-01------------------------------
//----------------------------------------------------------------------
// checkResultIsNotApplicable(processPageTest("Rgaa4-2019.Test.13.10.2-4NA-01"));
}
@Override
protected void setConsolidate() {
// The consolidate method can be removed when real implementation is done.
// The assertions are automatically tested regarding the file names by
// the abstract parent class
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa4-2019.Test.13.10.2-3NMI-01").getValue());
}
}
| agpl-3.0 |
dev-pnt/gers-pruebas | cache/modules/Contacts/Contactvardefs.php | 34165 | <?php
$GLOBALS["dictionary"]["Contact"]=array (
'table' => 'contacts',
'audited' => true,
'unified_search' => true,
'full_text_search' => true,
'unified_search_default_enabled' => true,
'duplicate_merge' => true,
'fields' =>
array (
'id' =>
array (
'name' => 'id',
'vname' => 'LBL_ID',
'type' => 'id',
'required' => true,
'reportable' => true,
'comment' => 'Unique identifier',
),
'name' =>
array (
'name' => 'name',
'rname' => 'name',
'vname' => 'LBL_NAME',
'type' => 'name',
'link' => true,
'fields' =>
array (
0 => 'first_name',
1 => 'last_name',
),
'sort_on' => 'last_name',
'source' => 'non-db',
'group' => 'last_name',
'len' => '255',
'db_concat_fields' =>
array (
0 => 'first_name',
1 => 'last_name',
),
'importable' => 'false',
),
'date_entered' =>
array (
'name' => 'date_entered',
'vname' => 'LBL_DATE_ENTERED',
'type' => 'datetime',
'group' => 'created_by_name',
'comment' => 'Date record created',
'enable_range_search' => true,
'options' => 'date_range_search_dom',
),
'date_modified' =>
array (
'name' => 'date_modified',
'vname' => 'LBL_DATE_MODIFIED',
'type' => 'datetime',
'group' => 'modified_by_name',
'comment' => 'Date record last modified',
'enable_range_search' => true,
'options' => 'date_range_search_dom',
),
'modified_user_id' =>
array (
'name' => 'modified_user_id',
'rname' => 'user_name',
'id_name' => 'modified_user_id',
'vname' => 'LBL_MODIFIED',
'type' => 'assigned_user_name',
'table' => 'users',
'isnull' => 'false',
'group' => 'modified_by_name',
'dbType' => 'id',
'reportable' => true,
'comment' => 'User who last modified record',
'massupdate' => false,
),
'modified_by_name' =>
array (
'name' => 'modified_by_name',
'vname' => 'LBL_MODIFIED_NAME',
'type' => 'relate',
'reportable' => false,
'source' => 'non-db',
'rname' => 'user_name',
'table' => 'users',
'id_name' => 'modified_user_id',
'module' => 'Users',
'link' => 'modified_user_link',
'duplicate_merge' => 'disabled',
'massupdate' => false,
),
'created_by' =>
array (
'name' => 'created_by',
'rname' => 'user_name',
'id_name' => 'modified_user_id',
'vname' => 'LBL_CREATED',
'type' => 'assigned_user_name',
'table' => 'users',
'isnull' => 'false',
'dbType' => 'id',
'group' => 'created_by_name',
'comment' => 'User who created record',
'massupdate' => false,
),
'created_by_name' =>
array (
'name' => 'created_by_name',
'vname' => 'LBL_CREATED',
'type' => 'relate',
'reportable' => false,
'link' => 'created_by_link',
'rname' => 'user_name',
'source' => 'non-db',
'table' => 'users',
'id_name' => 'created_by',
'module' => 'Users',
'duplicate_merge' => 'disabled',
'importable' => 'false',
'massupdate' => false,
),
'description' =>
array (
'name' => 'description',
'vname' => 'LBL_DESCRIPTION',
'type' => 'text',
'comment' => 'Full text of the note',
'rows' => 6,
'cols' => 80,
),
'deleted' =>
array (
'name' => 'deleted',
'vname' => 'LBL_DELETED',
'type' => 'bool',
'default' => '0',
'reportable' => false,
'comment' => 'Record deletion indicator',
),
'created_by_link' =>
array (
'name' => 'created_by_link',
'type' => 'link',
'relationship' => 'contacts_created_by',
'vname' => 'LBL_CREATED_BY_USER',
'link_type' => 'one',
'module' => 'Users',
'bean_name' => 'User',
'source' => 'non-db',
),
'modified_user_link' =>
array (
'name' => 'modified_user_link',
'type' => 'link',
'relationship' => 'contacts_modified_user',
'vname' => 'LBL_MODIFIED_BY_USER',
'link_type' => 'one',
'module' => 'Users',
'bean_name' => 'User',
'source' => 'non-db',
),
'assigned_user_id' =>
array (
'name' => 'assigned_user_id',
'rname' => 'user_name',
'id_name' => 'assigned_user_id',
'vname' => 'LBL_ASSIGNED_TO_ID',
'group' => 'assigned_user_name',
'type' => 'relate',
'table' => 'users',
'module' => 'Users',
'reportable' => true,
'isnull' => 'false',
'dbType' => 'id',
'audited' => true,
'comment' => 'User ID assigned to record',
'duplicate_merge' => 'disabled',
),
'assigned_user_name' =>
array (
'name' => 'assigned_user_name',
'link' => 'assigned_user_link',
'vname' => 'LBL_ASSIGNED_TO_NAME',
'rname' => 'user_name',
'type' => 'relate',
'reportable' => false,
'source' => 'non-db',
'table' => 'users',
'id_name' => 'assigned_user_id',
'module' => 'Users',
'duplicate_merge' => 'disabled',
),
'assigned_user_link' =>
array (
'name' => 'assigned_user_link',
'type' => 'link',
'relationship' => 'contacts_assigned_user',
'vname' => 'LBL_ASSIGNED_TO_USER',
'link_type' => 'one',
'module' => 'Users',
'bean_name' => 'User',
'source' => 'non-db',
'rname' => 'user_name',
'id_name' => 'assigned_user_id',
'table' => 'users',
'duplicate_merge' => 'enabled',
),
'salutation' =>
array (
'name' => 'salutation',
'vname' => 'LBL_SALUTATION',
'type' => 'enum',
'options' => 'salutation_dom',
'massupdate' => false,
'len' => '255',
'comment' => 'Contact salutation (e.g., Mr, Ms)',
),
'first_name' =>
array (
'name' => 'first_name',
'vname' => 'LBL_FIRST_NAME',
'type' => 'varchar',
'len' => '100',
'unified_search' => true,
'full_text_search' =>
array (
'boost' => 3,
),
'comment' => 'First name of the contact',
'merge_filter' => 'selected',
),
'last_name' =>
array (
'name' => 'last_name',
'vname' => 'LBL_LAST_NAME',
'type' => 'varchar',
'len' => '100',
'unified_search' => true,
'full_text_search' =>
array (
'boost' => 3,
),
'comment' => 'Last name of the contact',
'merge_filter' => 'selected',
'required' => true,
'importable' => 'required',
),
'full_name' =>
array (
'name' => 'full_name',
'rname' => 'full_name',
'vname' => 'LBL_NAME',
'type' => 'fullname',
'fields' =>
array (
0 => 'first_name',
1 => 'last_name',
),
'sort_on' => 'last_name',
'source' => 'non-db',
'group' => 'last_name',
'len' => '510',
'db_concat_fields' =>
array (
0 => 'first_name',
1 => 'last_name',
),
'studio' =>
array (
'listview' => false,
),
),
'title' =>
array (
'name' => 'title',
'vname' => 'LBL_TITLE',
'type' => 'varchar',
'len' => '100',
'comment' => 'The title of the contact',
),
'department' =>
array (
'name' => 'department',
'vname' => 'LBL_DEPARTMENT',
'type' => 'varchar',
'len' => '255',
'comment' => 'The department of the contact',
'merge_filter' => 'enabled',
),
'do_not_call' =>
array (
'name' => 'do_not_call',
'vname' => 'LBL_DO_NOT_CALL',
'type' => 'bool',
'default' => '0',
'audited' => true,
'comment' => 'An indicator of whether contact can be called',
),
'phone_home' =>
array (
'name' => 'phone_home',
'vname' => 'LBL_HOME_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => 100,
'unified_search' => true,
'full_text_search' =>
array (
'boost' => 1,
),
'comment' => 'Home phone number of the contact',
'merge_filter' => 'enabled',
),
'email' =>
array (
'name' => 'email',
'type' => 'email',
'query_type' => 'default',
'source' => 'non-db',
'operator' => 'subquery',
'subquery' => 'SELECT eabr.bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (ea.id = eabr.email_address_id) WHERE eabr.deleted=0 AND ea.email_address LIKE',
'db_field' =>
array (
0 => 'id',
),
'vname' => 'LBL_ANY_EMAIL',
'studio' =>
array (
'visible' => false,
'searchview' => true,
),
),
'phone_mobile' =>
array (
'name' => 'phone_mobile',
'vname' => 'LBL_MOBILE_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => 100,
'unified_search' => true,
'full_text_search' =>
array (
'boost' => 1,
),
'comment' => 'Mobile phone number of the contact',
'merge_filter' => 'enabled',
),
'phone_work' =>
array (
'name' => 'phone_work',
'vname' => 'LBL_OFFICE_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => 100,
'audited' => true,
'unified_search' => true,
'full_text_search' =>
array (
'boost' => 1,
),
'comment' => 'Work phone number of the contact',
'merge_filter' => 'enabled',
),
'phone_other' =>
array (
'name' => 'phone_other',
'vname' => 'LBL_OTHER_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => 100,
'unified_search' => true,
'full_text_search' =>
array (
'boost' => 1,
),
'comment' => 'Other phone number for the contact',
'merge_filter' => 'enabled',
),
'phone_fax' =>
array (
'name' => 'phone_fax',
'vname' => 'LBL_FAX_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => 100,
'unified_search' => true,
'full_text_search' =>
array (
'boost' => 1,
),
'comment' => 'Contact fax number',
'merge_filter' => 'enabled',
),
'email1' =>
array (
'name' => 'email1',
'vname' => 'LBL_EMAIL_ADDRESS',
'type' => 'varchar',
'function' =>
array (
'name' => 'getEmailAddressWidget',
'returns' => 'html',
),
'source' => 'non-db',
'group' => 'email1',
'merge_filter' => 'enabled',
'studio' =>
array (
'editField' => true,
'searchview' => false,
'popupsearch' => false,
),
'full_text_search' =>
array (
'boost' => 3,
'index' => 'not_analyzed',
),
),
'email2' =>
array (
'name' => 'email2',
'vname' => 'LBL_OTHER_EMAIL_ADDRESS',
'type' => 'varchar',
'function' =>
array (
'name' => 'getEmailAddressWidget',
'returns' => 'html',
),
'source' => 'non-db',
'group' => 'email2',
'merge_filter' => 'enabled',
'studio' => 'false',
),
'invalid_email' =>
array (
'name' => 'invalid_email',
'vname' => 'LBL_INVALID_EMAIL',
'source' => 'non-db',
'type' => 'bool',
'massupdate' => false,
'studio' => 'false',
),
'email_opt_out' =>
array (
'name' => 'email_opt_out',
'vname' => 'LBL_EMAIL_OPT_OUT',
'source' => 'non-db',
'type' => 'bool',
'massupdate' => false,
'studio' => 'false',
),
'primary_address_street' =>
array (
'name' => 'primary_address_street',
'vname' => 'LBL_PRIMARY_ADDRESS_STREET',
'type' => 'varchar',
'len' => '150',
'group' => 'primary_address',
'comment' => 'Street address for primary address',
'merge_filter' => 'enabled',
),
'primary_address_street_2' =>
array (
'name' => 'primary_address_street_2',
'vname' => 'LBL_PRIMARY_ADDRESS_STREET_2',
'type' => 'varchar',
'len' => '150',
'source' => 'non-db',
),
'primary_address_street_3' =>
array (
'name' => 'primary_address_street_3',
'vname' => 'LBL_PRIMARY_ADDRESS_STREET_3',
'type' => 'varchar',
'len' => '150',
'source' => 'non-db',
),
'primary_address_city' =>
array (
'name' => 'primary_address_city',
'vname' => 'LBL_PRIMARY_ADDRESS_CITY',
'type' => 'varchar',
'len' => '100',
'group' => 'primary_address',
'comment' => 'City for primary address',
'merge_filter' => 'enabled',
),
'primary_address_state' =>
array (
'name' => 'primary_address_state',
'vname' => 'LBL_PRIMARY_ADDRESS_STATE',
'type' => 'varchar',
'len' => '100',
'group' => 'primary_address',
'comment' => 'State for primary address',
'merge_filter' => 'enabled',
),
'primary_address_postalcode' =>
array (
'name' => 'primary_address_postalcode',
'vname' => 'LBL_PRIMARY_ADDRESS_POSTALCODE',
'type' => 'varchar',
'len' => '20',
'group' => 'primary_address',
'comment' => 'Postal code for primary address',
'merge_filter' => 'enabled',
),
'primary_address_country' =>
array (
'name' => 'primary_address_country',
'vname' => 'LBL_PRIMARY_ADDRESS_COUNTRY',
'type' => 'varchar',
'group' => 'primary_address',
'comment' => 'Country for primary address',
'merge_filter' => 'enabled',
),
'alt_address_street' =>
array (
'name' => 'alt_address_street',
'vname' => 'LBL_ALT_ADDRESS_STREET',
'type' => 'varchar',
'len' => '150',
'group' => 'alt_address',
'comment' => 'Street address for alternate address',
'merge_filter' => 'enabled',
),
'alt_address_street_2' =>
array (
'name' => 'alt_address_street_2',
'vname' => 'LBL_ALT_ADDRESS_STREET_2',
'type' => 'varchar',
'len' => '150',
'source' => 'non-db',
),
'alt_address_street_3' =>
array (
'name' => 'alt_address_street_3',
'vname' => 'LBL_ALT_ADDRESS_STREET_3',
'type' => 'varchar',
'len' => '150',
'source' => 'non-db',
),
'alt_address_city' =>
array (
'name' => 'alt_address_city',
'vname' => 'LBL_ALT_ADDRESS_CITY',
'type' => 'varchar',
'len' => '100',
'group' => 'alt_address',
'comment' => 'City for alternate address',
'merge_filter' => 'enabled',
),
'alt_address_state' =>
array (
'name' => 'alt_address_state',
'vname' => 'LBL_ALT_ADDRESS_STATE',
'type' => 'varchar',
'len' => '100',
'group' => 'alt_address',
'comment' => 'State for alternate address',
'merge_filter' => 'enabled',
),
'alt_address_postalcode' =>
array (
'name' => 'alt_address_postalcode',
'vname' => 'LBL_ALT_ADDRESS_POSTALCODE',
'type' => 'varchar',
'len' => '20',
'group' => 'alt_address',
'comment' => 'Postal code for alternate address',
'merge_filter' => 'enabled',
),
'alt_address_country' =>
array (
'name' => 'alt_address_country',
'vname' => 'LBL_ALT_ADDRESS_COUNTRY',
'type' => 'varchar',
'group' => 'alt_address',
'comment' => 'Country for alternate address',
'merge_filter' => 'enabled',
),
'assistant' =>
array (
'name' => 'assistant',
'vname' => 'LBL_ASSISTANT',
'type' => 'varchar',
'len' => '75',
'unified_search' => true,
'full_text_search' =>
array (
'boost' => 2,
),
'comment' => 'Name of the assistant of the contact',
'merge_filter' => 'enabled',
),
'assistant_phone' =>
array (
'name' => 'assistant_phone',
'vname' => 'LBL_ASSISTANT_PHONE',
'type' => 'phone',
'dbType' => 'varchar',
'len' => 100,
'group' => 'assistant',
'unified_search' => true,
'full_text_search' =>
array (
'boost' => 1,
),
'comment' => 'Phone number of the assistant of the contact',
'merge_filter' => 'enabled',
),
'email_addresses_primary' =>
array (
'name' => 'email_addresses_primary',
'type' => 'link',
'relationship' => 'contacts_email_addresses_primary',
'source' => 'non-db',
'vname' => 'LBL_EMAIL_ADDRESS_PRIMARY',
'duplicate_merge' => 'disabled',
),
'email_addresses' =>
array (
'name' => 'email_addresses',
'type' => 'link',
'relationship' => 'contacts_email_addresses',
'module' => 'EmailAddress',
'bean_name' => 'EmailAddress',
'source' => 'non-db',
'vname' => 'LBL_EMAIL_ADDRESSES',
'reportable' => false,
'rel_fields' =>
array (
'primary_address' =>
array (
'type' => 'bool',
),
),
'unified_search' => true,
),
'email_and_name1' =>
array (
'name' => 'email_and_name1',
'rname' => 'email_and_name1',
'vname' => 'LBL_NAME',
'type' => 'varchar',
'source' => 'non-db',
'len' => '510',
'importable' => 'false',
),
'lead_source' =>
array (
'name' => 'lead_source',
'vname' => 'LBL_LEAD_SOURCE',
'type' => 'enum',
'options' => 'lead_source_dom',
'len' => '255',
'comment' => 'How did the contact come about',
),
'account_name' =>
array (
'name' => 'account_name',
'rname' => 'name',
'id_name' => 'account_id',
'vname' => 'LBL_ACCOUNT_NAME',
'join_name' => 'accounts',
'type' => 'relate',
'link' => 'accounts',
'table' => 'accounts',
'isnull' => 'true',
'module' => 'Accounts',
'dbType' => 'varchar',
'len' => '255',
'source' => 'non-db',
'unified_search' => true,
),
'account_id' =>
array (
'name' => 'account_id',
'rname' => 'id',
'id_name' => 'account_id',
'vname' => 'LBL_ACCOUNT_ID',
'type' => 'relate',
'table' => 'accounts',
'isnull' => 'true',
'module' => 'Accounts',
'dbType' => 'id',
'reportable' => false,
'source' => 'non-db',
'massupdate' => false,
'duplicate_merge' => 'disabled',
'hideacl' => true,
),
'opportunity_role_fields' =>
array (
'name' => 'opportunity_role_fields',
'rname' => 'id',
'relationship_fields' =>
array (
'id' => 'opportunity_role_id',
'contact_role' => 'opportunity_role',
),
'vname' => 'LBL_ACCOUNT_NAME',
'type' => 'relate',
'link' => 'opportunities',
'link_type' => 'relationship_info',
'join_link_name' => 'opportunities_contacts',
'source' => 'non-db',
'importable' => 'false',
'duplicate_merge' => 'disabled',
'studio' => false,
),
'opportunity_role_id' =>
array (
'name' => 'opportunity_role_id',
'type' => 'varchar',
'source' => 'non-db',
'vname' => 'LBL_OPPORTUNITY_ROLE_ID',
'studio' =>
array (
'listview' => false,
),
),
'opportunity_role' =>
array (
'name' => 'opportunity_role',
'type' => 'enum',
'source' => 'non-db',
'vname' => 'LBL_OPPORTUNITY_ROLE',
'options' => 'opportunity_relationship_type_dom',
),
'twitter' =>
array (
'name' => 'twitter',
'vname' => 'LBL_TWITTER',
'type' => 'varchar',
'audited' => true,
'len' => 15,
),
'correos_gers' =>
array (
'name' => 'correos_gers',
'vname' => 'LBL_CORREOS_GERS',
'type' => 'bool',
'default' => '0',
'audited' => true,
),
'tips_del_trato' =>
array (
'name' => 'tips_del_trato',
'vname' => 'LBL_TIPS_TRATO',
'type' => 'text',
'rows' => 6,
'cols' => 70,
'audited' => true,
),
'posicion_gers' =>
array (
'name' => 'posicion_gers',
'vname' => 'LBL_POSICION_GERS',
'type' => 'enum',
'options' => 'posicion_gers_list',
'len' => '255',
'audited' => true,
),
'contacto_area' =>
array (
'name' => 'contacto_area',
'vname' => 'LBL_CONTACTO_AREA',
'type' => 'multienum',
'options' => 'contacto_area_list',
'len' => '255',
'audited' => true,
),
'rol_negociacion' =>
array (
'name' => 'rol_negociacion',
'vname' => 'LBL_ROL_NEGOCIACION',
'type' => 'enum',
'options' => 'rol_negociacion_list',
'len' => '255',
'audited' => true,
),
'reports_to_id' =>
array (
'name' => 'reports_to_id',
'vname' => 'LBL_REPORTS_TO_ID',
'type' => 'id',
'required' => false,
'reportable' => false,
'comment' => 'The contact this contact reports to',
),
'report_to_name' =>
array (
'name' => 'report_to_name',
'rname' => 'last_name',
'id_name' => 'reports_to_id',
'vname' => 'LBL_REPORTS_TO',
'type' => 'relate',
'link' => 'reports_to_link',
'table' => 'contacts',
'isnull' => 'true',
'module' => 'Contacts',
'dbType' => 'varchar',
'len' => 'id',
'reportable' => false,
'source' => 'non-db',
),
'birthdate' =>
array (
'name' => 'birthdate',
'vname' => 'LBL_BIRTHDATE',
'massupdate' => false,
'type' => 'date',
'comment' => 'The birthdate of the contact',
),
'accounts' =>
array (
'name' => 'accounts',
'type' => 'link',
'relationship' => 'accounts_contacts',
'link_type' => 'one',
'source' => 'non-db',
'vname' => 'LBL_ACCOUNT',
'duplicate_merge' => 'disabled',
),
'reports_to_link' =>
array (
'name' => 'reports_to_link',
'type' => 'link',
'relationship' => 'contact_direct_reports',
'link_type' => 'one',
'side' => 'right',
'source' => 'non-db',
'vname' => 'LBL_REPORTS_TO',
),
'opportunities' =>
array (
'name' => 'opportunities',
'type' => 'link',
'relationship' => 'opportunities_contacts',
'source' => 'non-db',
'module' => 'Opportunities',
'bean_name' => 'Opportunity',
'vname' => 'LBL_OPPORTUNITIES',
),
'bugs' =>
array (
'name' => 'bugs',
'type' => 'link',
'relationship' => 'contacts_bugs',
'source' => 'non-db',
'vname' => 'LBL_BUGS',
),
'calls' =>
array (
'name' => 'calls',
'type' => 'link',
'relationship' => 'calls_contacts',
'source' => 'non-db',
'vname' => 'LBL_CALLS',
),
'cases' =>
array (
'name' => 'cases',
'type' => 'link',
'relationship' => 'contacts_cases',
'source' => 'non-db',
'vname' => 'LBL_CASES',
),
'direct_reports' =>
array (
'name' => 'direct_reports',
'type' => 'link',
'relationship' => 'contact_direct_reports',
'source' => 'non-db',
'vname' => 'LBL_DIRECT_REPORTS',
),
'emails' =>
array (
'name' => 'emails',
'type' => 'link',
'relationship' => 'emails_contacts_rel',
'source' => 'non-db',
'vname' => 'LBL_EMAILS',
),
'documents' =>
array (
'name' => 'documents',
'type' => 'link',
'relationship' => 'documents_contacts',
'source' => 'non-db',
'vname' => 'LBL_DOCUMENTS_SUBPANEL_TITLE',
),
'leads' =>
array (
'name' => 'leads',
'type' => 'link',
'relationship' => 'contact_leads',
'source' => 'non-db',
'vname' => 'LBL_LEADS',
),
'meetings' =>
array (
'name' => 'meetings',
'type' => 'link',
'relationship' => 'meetings_contacts',
'source' => 'non-db',
'vname' => 'LBL_MEETINGS',
),
'notes' =>
array (
'name' => 'notes',
'type' => 'link',
'relationship' => 'contact_notes',
'source' => 'non-db',
'vname' => 'LBL_NOTES',
),
'project' =>
array (
'name' => 'project',
'type' => 'link',
'relationship' => 'projects_contacts',
'source' => 'non-db',
'vname' => 'LBL_PROJECTS',
),
'project_resource' =>
array (
'name' => 'project_resource',
'type' => 'link',
'relationship' => 'projects_contacts_resources',
'source' => 'non-db',
'vname' => 'LBL_PROJECTS_RESOURCES',
),
'tasks' =>
array (
'name' => 'tasks',
'type' => 'link',
'relationship' => 'contact_tasks',
'source' => 'non-db',
'vname' => 'LBL_TASKS',
),
'tasks_parent' =>
array (
'name' => 'tasks_parent',
'type' => 'link',
'relationship' => 'contact_tasks_parent',
'source' => 'non-db',
'vname' => 'LBL_TASKS',
'reportable' => false,
),
'user_sync' =>
array (
'name' => 'user_sync',
'type' => 'link',
'relationship' => 'contacts_users',
'source' => 'non-db',
'vname' => 'LBL_USER_SYNC',
),
'campaign_id' =>
array (
'name' => 'campaign_id',
'comment' => 'Campaign that generated lead',
'vname' => 'LBL_CAMPAIGN_ID',
'rname' => 'id',
'id_name' => 'campaign_id',
'type' => 'id',
'table' => 'campaigns',
'isnull' => 'true',
'module' => 'Campaigns',
'massupdate' => false,
'duplicate_merge' => 'disabled',
),
'campaign_name' =>
array (
'name' => 'campaign_name',
'rname' => 'name',
'vname' => 'LBL_CAMPAIGN',
'type' => 'relate',
'link' => 'campaign_contacts',
'isnull' => 'true',
'reportable' => false,
'source' => 'non-db',
'table' => 'campaigns',
'id_name' => 'campaign_id',
'module' => 'Campaigns',
'duplicate_merge' => 'disabled',
'comment' => 'The first campaign name for Contact (Meta-data only)',
),
'campaigns' =>
array (
'name' => 'campaigns',
'type' => 'link',
'relationship' => 'contact_campaign_log',
'module' => 'CampaignLog',
'bean_name' => 'CampaignLog',
'source' => 'non-db',
'vname' => 'LBL_CAMPAIGNLOG',
),
'campaign_contacts' =>
array (
'name' => 'campaign_contacts',
'type' => 'link',
'vname' => 'LBL_CAMPAIGN_CONTACT',
'relationship' => 'campaign_contacts',
'source' => 'non-db',
),
'c_accept_status_fields' =>
array (
'name' => 'c_accept_status_fields',
'rname' => 'id',
'relationship_fields' =>
array (
'id' => 'accept_status_id',
'accept_status' => 'accept_status_name',
),
'vname' => 'LBL_LIST_ACCEPT_STATUS',
'type' => 'relate',
'link' => 'calls',
'link_type' => 'relationship_info',
'source' => 'non-db',
'importable' => 'false',
'duplicate_merge' => 'disabled',
'studio' => false,
),
'm_accept_status_fields' =>
array (
'name' => 'm_accept_status_fields',
'rname' => 'id',
'relationship_fields' =>
array (
'id' => 'accept_status_id',
'accept_status' => 'accept_status_name',
),
'vname' => 'LBL_LIST_ACCEPT_STATUS',
'type' => 'relate',
'link' => 'meetings',
'link_type' => 'relationship_info',
'source' => 'non-db',
'importable' => 'false',
'hideacl' => true,
'duplicate_merge' => 'disabled',
'studio' => false,
),
'accept_status_id' =>
array (
'name' => 'accept_status_id',
'type' => 'varchar',
'source' => 'non-db',
'vname' => 'LBL_LIST_ACCEPT_STATUS',
'studio' =>
array (
'listview' => false,
),
),
'accept_status_name' =>
array (
'massupdate' => false,
'name' => 'accept_status_name',
'type' => 'enum',
'studio' => 'false',
'source' => 'non-db',
'vname' => 'LBL_LIST_ACCEPT_STATUS',
'options' => 'dom_meeting_accept_status',
'importable' => 'false',
),
'prospect_lists' =>
array (
'name' => 'prospect_lists',
'type' => 'link',
'relationship' => 'prospect_list_contacts',
'module' => 'ProspectLists',
'source' => 'non-db',
'vname' => 'LBL_PROSPECT_LIST',
),
'sync_contact' =>
array (
'massupdate' => false,
'name' => 'sync_contact',
'vname' => 'LBL_SYNC_CONTACT',
'type' => 'bool',
'source' => 'non-db',
'comment' => 'Synch to outlook? (Meta-Data only)',
'studio' => 'true',
),
),
'indices' =>
array (
'id' =>
array (
'name' => 'contactspk',
'type' => 'primary',
'fields' =>
array (
0 => 'id',
),
),
0 =>
array (
'name' => 'idx_cont_last_first',
'type' => 'index',
'fields' =>
array (
0 => 'last_name',
1 => 'first_name',
2 => 'deleted',
),
),
1 =>
array (
'name' => 'idx_contacts_del_last',
'type' => 'index',
'fields' =>
array (
0 => 'deleted',
1 => 'last_name',
),
),
2 =>
array (
'name' => 'idx_cont_del_reports',
'type' => 'index',
'fields' =>
array (
0 => 'deleted',
1 => 'reports_to_id',
2 => 'last_name',
),
),
3 =>
array (
'name' => 'idx_reports_to_id',
'type' => 'index',
'fields' =>
array (
0 => 'reports_to_id',
),
),
4 =>
array (
'name' => 'idx_del_id_user',
'type' => 'index',
'fields' =>
array (
0 => 'deleted',
1 => 'id',
2 => 'assigned_user_id',
),
),
5 =>
array (
'name' => 'idx_cont_assigned',
'type' => 'index',
'fields' =>
array (
0 => 'assigned_user_id',
),
),
),
'relationships' =>
array (
'contacts_modified_user' =>
array (
'lhs_module' => 'Users',
'lhs_table' => 'users',
'lhs_key' => 'id',
'rhs_module' => 'Contacts',
'rhs_table' => 'contacts',
'rhs_key' => 'modified_user_id',
'relationship_type' => 'one-to-many',
),
'contacts_created_by' =>
array (
'lhs_module' => 'Users',
'lhs_table' => 'users',
'lhs_key' => 'id',
'rhs_module' => 'Contacts',
'rhs_table' => 'contacts',
'rhs_key' => 'created_by',
'relationship_type' => 'one-to-many',
),
'contacts_assigned_user' =>
array (
'lhs_module' => 'Users',
'lhs_table' => 'users',
'lhs_key' => 'id',
'rhs_module' => 'Contacts',
'rhs_table' => 'contacts',
'rhs_key' => 'assigned_user_id',
'relationship_type' => 'one-to-many',
),
'contacts_email_addresses' =>
array (
'lhs_module' => 'Contacts',
'lhs_table' => 'contacts',
'lhs_key' => 'id',
'rhs_module' => 'EmailAddresses',
'rhs_table' => 'email_addresses',
'rhs_key' => 'id',
'relationship_type' => 'many-to-many',
'join_table' => 'email_addr_bean_rel',
'join_key_lhs' => 'bean_id',
'join_key_rhs' => 'email_address_id',
'relationship_role_column' => 'bean_module',
'relationship_role_column_value' => 'Contacts',
),
'contacts_email_addresses_primary' =>
array (
'lhs_module' => 'Contacts',
'lhs_table' => 'contacts',
'lhs_key' => 'id',
'rhs_module' => 'EmailAddresses',
'rhs_table' => 'email_addresses',
'rhs_key' => 'id',
'relationship_type' => 'many-to-many',
'join_table' => 'email_addr_bean_rel',
'join_key_lhs' => 'bean_id',
'join_key_rhs' => 'email_address_id',
'relationship_role_column' => 'primary_address',
'relationship_role_column_value' => '1',
),
'contact_direct_reports' =>
array (
'lhs_module' => 'Contacts',
'lhs_table' => 'contacts',
'lhs_key' => 'id',
'rhs_module' => 'Contacts',
'rhs_table' => 'contacts',
'rhs_key' => 'reports_to_id',
'relationship_type' => 'one-to-many',
),
'contact_leads' =>
array (
'lhs_module' => 'Contacts',
'lhs_table' => 'contacts',
'lhs_key' => 'id',
'rhs_module' => 'Leads',
'rhs_table' => 'leads',
'rhs_key' => 'contact_id',
'relationship_type' => 'one-to-many',
),
'contact_notes' =>
array (
'lhs_module' => 'Contacts',
'lhs_table' => 'contacts',
'lhs_key' => 'id',
'rhs_module' => 'Notes',
'rhs_table' => 'notes',
'rhs_key' => 'contact_id',
'relationship_type' => 'one-to-many',
),
'contact_tasks' =>
array (
'lhs_module' => 'Contacts',
'lhs_table' => 'contacts',
'lhs_key' => 'id',
'rhs_module' => 'Tasks',
'rhs_table' => 'tasks',
'rhs_key' => 'contact_id',
'relationship_type' => 'one-to-many',
),
'contact_tasks_parent' =>
array (
'lhs_module' => 'Contacts',
'lhs_table' => 'contacts',
'lhs_key' => 'id',
'rhs_module' => 'Tasks',
'rhs_table' => 'tasks',
'rhs_key' => 'parent_id',
'relationship_type' => 'one-to-many',
'relationship_role_column' => 'parent_type',
'relationship_role_column_value' => 'Contacts',
),
'contact_campaign_log' =>
array (
'lhs_module' => 'Contacts',
'lhs_table' => 'contacts',
'lhs_key' => 'id',
'rhs_module' => 'CampaignLog',
'rhs_table' => 'campaign_log',
'rhs_key' => 'target_id',
'relationship_type' => 'one-to-many',
),
),
'optimistic_locking' => true,
'templates' =>
array (
'person' => 'person',
'assignable' => 'assignable',
'basic' => 'basic',
),
'custom_fields' => false,
); | agpl-3.0 |
carthach/essentia | test/src/unittests/synthesis/test_hprmodel_streaming.py | 9212 | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), 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 Affero GNU General Public License
# version 3 along with this program. If not, see http://www.gnu.org/licenses/
from essentia_test import *
import math
import essentia
import essentia.streaming as es
import essentia.standard as std
def cutFrames(params, input = range(100)):
if not 'validFrameThresholdRatio' in params:
params['validFrameThresholdRatio'] = 0
framegen = std.FrameGenerator(input,
frameSize = params['frameSize'],
hopSize = params['hopSize'],
validFrameThresholdRatio = params['validFrameThresholdRatio'],
startFromZero = params['startFromZero'])
return [ frame for frame in framegen ]
def cleaningHarmonicTracks(freqsTotal, minFrames, pitchConf):
confThreshold = 0.5
nFrames = freqsTotal.shape[0];
begTrack = 0;
freqsClean = freqsTotal.copy()
if (nFrames > 0 ):
f = 0;
nTracks = freqsTotal.shape[1]# we assume all frames have a fix number of tracks
for t in range (nTracks):
f = 0;
begTrack = f;
while (f < nFrames-1):
#// check if f is begin of track
if (freqsClean[f][t] <= 0 and freqsClean[f+1][t] > 0 ):
begTrack = f+1;
# clean track if shorter than min duration
if ((freqsClean[f][t] > 0 and freqsClean[f+1][t] <= 0 ) and ( (f - begTrack) < minFrames)) :
for i in range(begTrack, f+1):
freqsClean[i][t] = 0;
# clean track if pitch confidence for that frameis below a ionfidence threshold
if (pitchConf[f] < confThreshold) :
freqsClean[f][t] = 0;
f+=1;
return freqsClean
# converts audio frames to a single array
def framesToAudio(frames):
audio = frames.flatten()
return audio
# computes analysis only
def analHprModelStreaming(params, signal):
#out = numpy.array(0)
pool = essentia.Pool()
fcut = es.FrameCutter(frameSize = params['frameSize'], hopSize = params['hopSize'], startFromZero = False);
w = es.Windowing(type = "blackmanharris92");
spec = es.Spectrum(size = params['frameSize']);
# pitch detection
pitchDetect = es.PitchYinFFT(frameSize=params['frameSize'], sampleRate = params['sampleRate'])
smanal = es.HprModelAnal(sampleRate = params['sampleRate'], hopSize = params['hopSize'], maxnSines = params['maxnSines'], magnitudeThreshold = params['magnitudeThreshold'], freqDevOffset = params['freqDevOffset'], freqDevSlope = params['freqDevSlope'], minFrequency = params['minFrequency'], maxFrequency = params['maxFrequency'])
# add half window of zeros to input signal to reach same ooutput length
signal = numpy.append(signal, zeros(params['frameSize']/2))
insignal = VectorInput (signal)
# analysis
insignal.data >> fcut.signal
fcut.frame >> w.frame
w.frame >> spec.frame
spec.spectrum >> pitchDetect.spectrum
fcut.frame >> smanal.frame
pitchDetect.pitch >> smanal.pitch
pitchDetect.pitch >> (pool, 'pitch')
pitchDetect.pitchConfidence >> (pool, 'pitchConfidence')
smanal.magnitudes >> (pool, 'magnitudes')
smanal.frequencies >> (pool, 'frequencies')
smanal.phases >> (pool, 'phases')
smanal.res >> (pool, 'res')
essentia.run(insignal)
# remove first half window frames
mags = pool['magnitudes']
freqs = pool['frequencies']
phases = pool['phases']
pitchConf = pool['pitchConfidence']
# remove short tracks
minFrames = int( params['minSineDur'] * params['sampleRate'] / params['hopSize']);
freqsClean = cleaningHarmonicTracks(freqs, minFrames, pitchConf)
pool['frequencies'].data = freqsClean
return mags, freqsClean, phases
# computes analysis/stynthesis
def analsynthHprModelStreaming(params, signal):
out = array([0.])
pool = essentia.Pool()
# windowing and FFT
fcut = es.FrameCutter(frameSize = params['frameSize'], hopSize = params['hopSize'], startFromZero = False);
w = es.Windowing(type = "blackmanharris92");
spec = es.Spectrum(size = params['frameSize']);
# pitch detection
pitchDetect = es.PitchYinFFT(frameSize=params['frameSize'], sampleRate = params['sampleRate'])
smanal = es.HprModelAnal(sampleRate = params['sampleRate'], hopSize = params['hopSize'], maxnSines = params['maxnSines'], magnitudeThreshold = params['magnitudeThreshold'], freqDevOffset = params['freqDevOffset'], freqDevSlope = params['freqDevSlope'], minFrequency = params['minFrequency'], maxFrequency = params['maxFrequency'])
synFFTSize = min(int(params['frameSize']/4), 4*params['hopSize']) # make sure the FFT size is appropriate
smsyn = es.SprModelSynth(sampleRate=params['sampleRate'],
fftSize=synFFTSize,
hopSize=params['hopSize'])
# add half window of zeros to input signal to reach same ooutput length
signal = numpy.append(signal, zeros(params['frameSize']/2))
insignal = VectorInput (signal)
# analysis
insignal.data >> fcut.signal
fcut.frame >> w.frame
w.frame >> spec.frame
spec.spectrum >> pitchDetect.spectrum
fcut.frame >> smanal.frame
pitchDetect.pitch >> smanal.pitch
pitchDetect.pitchConfidence >> (pool, 'pitchConfidence')
pitchDetect.pitch >> (pool, 'pitch')
# synthesis
smanal.magnitudes >> smsyn.magnitudes
smanal.frequencies >> smsyn.frequencies
smanal.phases >> smsyn.phases
smanal.res >> smsyn.res
smsyn.frame >> (pool, 'frames')
smsyn.sineframe >> (pool, 'sineframes')
smsyn.resframe >> (pool, 'resframes')
essentia.run(insignal)
outaudio = framesToAudio(pool['frames'])
outaudio = outaudio[2*params['hopSize']:]
return outaudio, pool
#-------------------------------------
class TestHprModel(TestCase):
params = { 'frameSize': 2048, 'hopSize': 128, 'startFromZero': False, 'sampleRate': 44100,'maxnSines': 100,'magnitudeThreshold': -74,'minSineDur': 0.02,'freqDevOffset': 10, 'freqDevSlope': 0.001, 'maxFrequency': 550.,'minFrequency': 65.}
precisiondB = -40. # -40dB of allowed noise floor for sinusoidal model
precisionDigits = int(-numpy.round(precisiondB/20.) -1) # -1 due to the rounding digit comparison.
def testZero(self):
# generate test signal
signalSize = 20 * self.params['frameSize']
signal = zeros(signalSize)
[mags, freqs, phases] = analHprModelStreaming(self.params, signal)
# compare
zerofreqs = numpy.zeros(freqs.shape)
self.assertAlmostEqualMatrix(freqs, zerofreqs)
def testWhiteNoise(self):
from random import random
# generate test signal
signalSize = 20 * self.params['frameSize']
signal = array([2*(random()-0.5)*i for i in ones(signalSize)])
# for white noise test set sine minimum duration to 350ms, and min threshold of -20dB
self.params['minSineDur'] = 0.35 # limit pitch tracks of a nimumim length of 350ms for the case of white noise input
self.params['magnitudeThreshold']= -20
[mags, freqs, phases] = analHprModelStreaming(self.params, signal)
# compare: no frequencies should be found
zerofreqs = numpy.zeros(freqs.shape)
self.assertAlmostEqualMatrix(freqs, zerofreqs)
def testRegression(self):
# generate test signal: sine 220Hz @44100kHz
signalSize = 20 * self.params['frameSize']
signal = .5 * numpy.sin( (array(range(signalSize))/self.params['sampleRate']) * 220 * 2*math.pi)
# generate noise components
from random import random
noise = 0.1 * array([2*(random()-0.5)*i for i in ones(signalSize)]) # -10dB
signal = signal + noise
outsignal,pool = analsynthHprModelStreaming(self.params, signal)
outsignal = outsignal[:signalSize] # cut to durations of input and output signal
# compare without half-window bounds to avoid windowing effect
halfwin = (self.params['frameSize']/2)
self.assertAlmostEqualVectorFixedPrecision(outsignal[halfwin:-halfwin], signal[halfwin:-halfwin], self.precisionDigits)
suite = allTests(TestHprModel)
if __name__ == '__main__':
TextTestRunner(verbosity=2).run(suite)
| agpl-3.0 |
hivam/doctor_biological_risk | __init__.py | 34 | from models import *
import report | agpl-3.0 |
shoaib-fazal16/yourown | modules/yo_Subdivisions/Dashlets/yo_SubdivisionsDashlet/yo_SubdivisionsDashlet.meta.php | 3143 | <?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
/*********************************************************************************
* Description: Defines the English language pack for the base application.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
global $app_strings;
$dashletMeta['yo_SubdivisionsDashlet'] = array('module' => 'yo_Subdivisions',
'title' => translate('LBL_HOMEPAGE_TITLE', 'yo_Subdivisions'),
'description' => 'A customizable view into yo_Subdivisions',
'icon' => 'icon_yo_Subdivisions_32.gif',
'category' => 'Module Views'); | agpl-3.0 |
opblanco/facturascripts | model/articulo.php | 33603 | <?php
/*
* This file is part of FacturaSctipts
* Copyright (C) 2014 Carlos Garcia Gomez neorazorx@gmail.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/>.
*/
require_once 'base/fs_model.php';
require_model('albaran_cliente.php');
require_model('albaran_proveedor.php');
require_model('familia.php');
require_model('impuesto.php');
require_model('tarifa_articulo.php');
require_model('stock.php');
require_model('cliente.php');
require_model('direccion_cliente.php');
require_model('fs_var.php');
/**
* Representa el artículo que se vende o compra.
*/
class articulo extends fs_model
{
public $referencia;
public $codfamilia;
public $descripcion;
public $pvp;
public $pvp_ant;
public $factualizado;
public $costemedio;
public $preciocoste;
public $codimpuesto;
public $iva;
public $destacado;
public $bloqueado;
public $secompra;
public $sevende;
public $publico;
public $equivalencia;
public $stockfis;
public $stockmin;
public $stockmax;
public $controlstock; /// permitir ventas sin stock
public $codbarras;
public $observaciones;
// Campos nuevos
public $dueno;
public $telefonodueno;
public $tipodni;
public $fentrada;
public $fsalida;
private $imagen;
private $has_imagen;
private $exists;
private static $impuestos;
private static $search_tags;
private static $cleaned_cache;
public function __construct($a=FALSE)
{
parent::__construct('articulos');
if( !isset(self::$impuestos) )
self::$impuestos = array();
if($a)
{
$this->referencia = $a['referencia'];
$this->codfamilia = $a['codfamilia'];
$this->descripcion = $this->no_html($a['descripcion']);
$this->pvp = floatval($a['pvp']);
$this->factualizado = Date('d-m-Y', strtotime($a['factualizado']));
$this->costemedio = floatval($a['costemedio']);
$this->preciocoste = floatval($a['preciocoste']);
$this->codimpuesto = $a['codimpuesto'];
$this->stockfis = floatval($a['stockfis']);
$this->stockmin = floatval($a['stockmin']);
$this->stockmax = floatval($a['stockmax']);
$this->controlstock = $this->str2bool($a['controlstock']);
$this->destacado = $this->str2bool($a['destacado']);
$this->bloqueado = $this->str2bool($a['bloqueado']);
$this->secompra = $this->str2bool($a['secompra']);
$this->sevende = $this->str2bool($a['sevende']);
$this->publico = $this->str2bool($a['publico']);
$this->equivalencia = $a['equivalencia'];
$this->codbarras = $a['codbarras'];
$this->observaciones = $this->no_html($a['observaciones']);
// Campos nuevos
$this->dueno = $this->no_html($a['dueno']);
$this->telefonodueno = $a['telefonodueno'];
$this->tipodni = $a['tipodni'];
$this->fentrada = Date('d-m-Y', strtotime($a['fentrada']));
$this->fsalida = Date('d-m-Y', strtotime($a['fentrada']));
/// no cargamos la imagen directamente por cuestión de rendimiento
$this->imagen = NULL;
$this->has_imagen = isset($a['imagen']);
$this->exists = TRUE;
}
else
{
$this->referencia = NULL;
$this->codfamilia = NULL;
$this->descripcion = '';
$this->pvp = 0;
$this->factualizado = Date('d-m-Y');
$this->costemedio = 0;
$this->preciocoste = 0;
$this->codimpuesto = NULL;
$this->stockfis = 0;
$this->stockmin = 0;
$this->stockmax = 0;
$this->controlstock = TRUE;
$this->destacado = FALSE;
$this->bloqueado = FALSE;
$this->secompra = TRUE;
$this->sevende = TRUE;
$this->publico = FALSE;
$this->equivalencia = NULL;
$this->codbarras = '';
$this->observaciones = '';
$this->imagen = NULL;
$this->has_imagen = FALSE;
$this->exists = FALSE;
// Campos nuevos
$this->dueno = '';
$this->telefonodueno = '';
$this->tipodni = '';
$this->fentrada = Date('d-m-Y');
$this->fsalida = Date('d-m-Y');
}
$this->pvp_ant = 0;
$this->iva = NULL;
}
protected function install()
{
/// la tabla articulos tiene claves ajeas a familias, impuestos y stocks
new familia();
new impuesto();
$this->clean_cache();
/// borramos todas las imágenes de artículos
if( file_exists('tmp/articulos') )
{
foreach(glob('tmp/articulos/*') as $file)
{
if( is_file($file) )
unlink($file);
}
}
return '';
}
public function get_descripcion_64()
{
return base64_encode($this->descripcion);
}
public function pvp_iva($coma=TRUE)
{
return $this->pvp * (100+$this->get_iva()) / 100;
}
public function costemedio_iva()
{
return $this->costemedio * (100+$this->get_iva()) / 100;
}
public function preciocoste()
{
return ( $this->secompra AND $GLOBALS['config2']['cost_is_average'] ) ? $this->costemedio : $this->preciocoste ;
}
public function preciocoste_iva()
{
return $this-> preciocoste() * (100+$this->get_iva()) / 100;
}
public function factualizado()
{
return $this->var2timesince($this->factualizado);
}
public function url()
{
if( is_null($this->referencia) )
return "index.php?page=ventas_articulos";
else
return "index.php?page=ventas_articulo&ref=".urlencode($this->referencia);
}
public function get($ref)
{
$art = $this->db->select("SELECT * FROM ".$this->table_name." WHERE referencia = ".$this->var2str($ref).";");
if($art)
return new articulo($art[0]);
else
return FALSE;
}
public function get_familia()
{
$fam = new familia();
return $fam->get($this->codfamilia);
}
public function get_stock()
{
$stock = new stock();
return $stock->all_from_articulo($this->referencia);
}
public function get_impuesto()
{
$imp = new impuesto();
return $imp->get($this->codimpuesto);
}
public function get_iva()
{
if( is_null($this->iva) )
{
$encontrado = FALSE;
foreach(self::$impuestos as $i)
{
if($i->codimpuesto == $this->codimpuesto)
{
$this->iva = floatval($i->iva);
$encontrado = TRUE;
break;
}
}
if( !$encontrado )
{
$imp = new impuesto();
$imp0 = $imp->get($this->codimpuesto);
if($imp0)
{
$this->iva = floatval($imp0->iva);
self::$impuestos[] = $imp0;
}
else
$this->iva = 0;
}
}
return $this->iva;
}
public function get_equivalentes()
{
$artilist = array();
if( isset($this->equivalencia) )
{
$articulos = $this->db->select("SELECT * FROM ".$this->table_name.
" WHERE equivalencia = ".$this->var2str($this->equivalencia).
" ORDER BY referencia ASC;");
if($articulos)
{
foreach($articulos as $a)
{
if($a['referencia'] != $this->referencia)
$artilist[] = new articulo($a);
}
}
}
return $artilist;
}
/*
* Devuelve un array con las tarifas asignadas a ese artículo.
* Si todas = TRUE -> devuelve además las que no están asignadas.
*/
public function get_tarifas($todas = FALSE)
{
$tarifa = new tarifa();
$tarifas = $tarifa->all();
$tarifa_articulo = new tarifa_articulo();
$tas = $tarifa_articulo->all_from_articulo($this->referencia);
if($todas)
{
foreach($tarifas as $t)
{
$encontrada = FALSE;
foreach($tas as $ta)
{
if( $ta->codtarifa == $t->codtarifa )
{
$encontrada = TRUE;
break;
}
}
if(!$encontrada)
{
/// añadimos las tarifas que no tiene asignadas
$tas[] = new tarifa_articulo( array('id' => NULL, 'codtarifa' => $t->codtarifa,
'referencia' => $this->referencia, 'descuento' => 0 - $t->incporcentual) );
}
}
}
/// rellenamos las tarifas
foreach($tas as $ta)
{
foreach($tarifas as $t)
{
if($t->codtarifa == $ta->codtarifa)
{
$ta->nombre = $t->nombre;
$ta->pvp = $this->pvp;
$ta->iva = $this->get_iva();
break;
}
}
}
return $tas;
}
public function get_lineas_albaran_cli($offset=0, $limit=FS_ITEM_LIMIT)
{
$linea = new linea_albaran_cliente();
return $linea->all_from_articulo($this->referencia, $offset, $limit);
}
public function get_lineas_albaran_prov($offset=0, $limit=FS_ITEM_LIMIT)
{
$linea = new linea_albaran_proveedor();
return $linea->all_from_articulo($this->referencia, $offset, $limit);
}
public function get_costemedio()
{
foreach($this->get_lineas_albaran_prov(0, 1) as $linea)
$this->costemedio = $linea->pvptotal/$linea->cantidad;
return $this->costemedio;
}
public function imagen_url()
{
if( $this->has_imagen )
{
if( file_exists('tmp/articulos/'.$this->referencia.'.png') )
{
return 'tmp/articulos/'.$this->referencia.'.png';
}
else
{
if( is_null($this->imagen) )
{
$imagen = $this->db->select("SELECT imagen FROM ".$this->table_name." WHERE referencia = ".$this->var2str($this->referencia).";");
if($imagen)
{
$this->imagen = $this->str2bin($imagen[0]['imagen']);
}
else
$this->has_imagen = FALSE;
}
if( isset($this->imagen) )
{
if( !file_exists('tmp/articulos') )
mkdir('tmp/articulos');
$f = fopen('tmp/articulos/'.$this->referencia.'.png', 'a');
fwrite($f, $this->imagen);
fclose($f);
return 'tmp/articulos/'.$this->referencia.'.png';
}
else
return FALSE;
}
}
else
return FALSE;
}
public function set_imagen($img)
{
if( is_null($img) )
{
$this->imagen = NULL;
$this->has_imagen = FALSE;
$this->clean_image_cache();
}
else
{
$this->imagen = $img;
$this->has_imagen = TRUE;
}
}
public function set_pvp($p)
{
$this->pvp_ant = $this->pvp;
$this->factualizado = Date('d-m-Y');
$this->pvp = round($p, 3);
}
public function set_pvp_iva($p)
{
$this->pvp_ant = $this->pvp;
$this->factualizado = Date('d-m-Y');
$this->pvp = round((100*$p)/(100+$this->get_iva()), 3);
}
public function set_referencia($ref)
{
$ref = str_replace(' ', '_', trim($ref));
if( !preg_match("/^[A-Z0-9_\+\.\*\/\-]{1,18}$/i", $ref) )
{
$this->new_error_msg("¡Referencia de artículo no válida! Debe tener entre 1 y 18 caracteres.
Se admiten letras, números, '_', '.', '*', '/' ó '-'.");
}
else if($ref != $this->referencia)
{
$sql = "UPDATE ".$this->table_name." SET referencia = ".$this->var2str($ref)." WHERE referencia = ".$this->var2str($this->referencia).";";
if( $this->db->exec($sql) )
{
$this->referencia = $ref;
}
else
{
$this->new_error_msg('Imposible modificar la referencia.');
}
}
}
public function set_impuesto($codimpuesto)
{
if($codimpuesto != $this->codimpuesto)
{
$this->codimpuesto = $codimpuesto;
$encontrado = FALSE;
foreach(self::$impuestos as $i)
{
if($i->codimpuesto == $this->codimpuesto)
{
$this->iva = floatval($i->iva);
$encontrado = TRUE;
break;
}
}
if( !$encontrado )
{
$imp = new impuesto();
$imp0 = $imp->get($this->codimpuesto);
if($imp0)
{
$this->iva = floatval($imp0->iva);
self::$impuestos[] = $imp0;
}
else
$this->iva = 0;
}
}
}
public function set_stock($almacen, $cantidad=1)
{
$result = FALSE;
$stock = new stock();
$encontrado = FALSE;
$stocks = $stock->all_from_articulo($this->referencia);
foreach($stocks as $k => $value)
{
if($value->codalmacen == $almacen)
{
$stocks[$k]->set_cantidad($cantidad);
$result = $stocks[$k]->save();
$encontrado = TRUE;
break;
}
}
if( !$encontrado )
{
$stock->referencia = $this->referencia;
$stock->codalmacen = $almacen;
$stock->set_cantidad($cantidad);
$result = $stock->save();
}
if($result)
{
$nuevo_stock = $stock->total_from_articulo($this->referencia);
if($this->stockfis != $nuevo_stock)
{
$this->stockfis = $nuevo_stock;
$this->get_costemedio();
if($this->exists)
{
$this->clean_cache();
$result = $this->db->exec("UPDATE ".$this->table_name." SET stockfis = ".$this->var2str($this->stockfis).",
costemedio = ".$this->var2str($this->costemedio)." WHERE referencia = ".$this->var2str($this->referencia).";");
}
else if( !$this->save() )
{
$this->new_error_msg("¡Error al actualizar el stock del artículo!");
}
}
}
else
$this->new_error_msg("Error al guardar el stock");
return $result;
}
public function sum_stock($almacen, $cantidad=1)
{
$result = FALSE;
$stock = new stock();
$encontrado = FALSE;
$stocks = $stock->all_from_articulo($this->referencia);
foreach($stocks as $k => $value)
{
if($value->codalmacen == $almacen)
{
$stocks[$k]->sum_cantidad($cantidad);
$result = $stocks[$k]->save();
$encontrado = TRUE;
break;
}
}
if( !$encontrado )
{
$stock->referencia = $this->referencia;
$stock->codalmacen = $almacen;
$stock->set_cantidad($cantidad);
$result = $stock->save();
}
if($result)
{
$nuevo_stock = $stock->total_from_articulo($this->referencia);
if($this->stockfis != $nuevo_stock)
{
$this->stockfis = $nuevo_stock;
$this->get_costemedio();
if($this->exists)
{
$this->clean_cache();
$result = $this->db->exec("UPDATE ".$this->table_name." SET stockfis = ".$this->var2str($this->stockfis).",
costemedio = ".$this->var2str($this->costemedio)." WHERE referencia = ".$this->var2str($this->referencia).";");
}
else if( !$this->save() )
{
$this->new_error_msg("¡Error al actualizar el stock del artículo!");
}
}
}
else
$this->new_error_msg("¡Error al guardar el stock!");
return $result;
}
/**
* Esta función devuelve TRUE si el artículo ya existe en la base de datos.
* Por motivos de rendimiento y al ser esta una clase de uso intensivo,
* se utiliza la variable $this->exists para almacenar el resultado.
* @return type
*/
public function exists()
{
if( !$this->exists )
{
if( $this->db->select("SELECT referencia FROM ".$this->table_name." WHERE referencia = ".$this->var2str($this->referencia).";") )
$this->exists = TRUE;
}
return $this->exists;
}
public function test()
{
$status = FALSE;
/// cargamos la imágen si todavía no lo habíamos hecho
if( $this->has_imagen )
{
if( is_null($this->imagen) )
{
$imagen = $this->db->select("SELECT imagen FROM ".$this->table_name." WHERE referencia = ".$this->var2str($this->referencia).";");
if($imagen)
{
$this->imagen = $this->str2bin($imagen[0]['imagen']);
}
else
{
$this->imagen = NULL;
$this->has_imagen = FALSE;
}
}
}
$this->referencia = str_replace(' ', '_', trim($this->referencia));
$this->descripcion = $this->no_html($this->descripcion);
if( strlen($this->descripcion) > 100 )
$this->descripcion = substr($this->descripcion, 0, 99);
$this->equivalencia = str_replace(' ', '_', trim($this->equivalencia));
$this->codbarras = $this->no_html($this->codbarras);
$this->observaciones = $this->no_html($this->observaciones);
if($this->equivalencia == '')
{
$this->equivalencia = NULL;
$this->destacado = FALSE;
}
if( !preg_match("/^[A-Z0-9_\+\.\*\/\-]{1,18}$/i", $this->referencia) )
{
$this->new_error_msg("¡Referencia de artículo no válida! Debe tener entre 1 y 18 caracteres.
Se admiten letras (excepto Ñ), números, '_', '.', '*', '/' ó '-'.");
}
else if( isset($this->equivalencia) AND !preg_match("/^[A-Z0-9_\+\.\*\/\-]{1,18}$/i", $this->equivalencia) )
{
$this->new_error_msg("¡Código de equivalencia del artículos no válido! Debe tener entre 1 y 18 caracteres.
Se admiten letras (excepto Ñ), números, '_', '.', '*', '/' ó '-'.");
}
else
$status = TRUE;
return $status;
}
public function save()
{
$update_referencia = false;
if( $this->test() )
{
$this->clean_cache();
$this->clean_image_cache();
if( $this->exists() )
{
$sql = "UPDATE ".$this->table_name." SET descripcion = ".$this->var2str($this->descripcion).",
codfamilia = ".$this->var2str($this->codfamilia).", pvp = ".$this->var2str($this->pvp).",
factualizado = ".$this->var2str($this->factualizado).",
costemedio = ".$this->var2str($this->costemedio).",
preciocoste = ".$this->var2str($this->preciocoste).",
codimpuesto = ".$this->var2str($this->codimpuesto).",
stockfis = ".$this->var2str($this->stockfis).", stockmin = ".$this->var2str($this->stockmin).",
stockmax = ".$this->var2str($this->stockmax).",
controlstock = ".$this->var2str($this->controlstock).",
destacado = ".$this->var2str($this->destacado).",
bloqueado = ".$this->var2str($this->bloqueado).", sevende = ".$this->var2str($this->sevende).",
publico = ".$this->var2str($this->publico).", secompra = ".$this->var2str($this->secompra).",
equivalencia = ".$this->var2str($this->equivalencia).",
codbarras = ".$this->var2str($this->codbarras).",
observaciones = ".$this->var2str($this->observaciones).",
dueno = ".$this->var2str($this->dueno).",
telefonodueno= ".$this->var2str($this->telefonodueno).",
tipodni = ".$this->var2str($this->tipodni).",
fentrada = ".$this->var2str($this->fentrada).",
fsalida = ".$this->var2str($this->fsalida).",
imagen = ".$this->bin2str($this->imagen)."
WHERE referencia = ".$this->var2str($this->referencia).";";
}
else
{
$sql = "INSERT INTO ".$this->table_name." (referencia,codfamilia,descripcion,pvp,
factualizado,costemedio,preciocoste,codimpuesto,stockfis,stockmin,stockmax,controlstock,destacado,bloqueado,
secompra,sevende,equivalencia,codbarras,dueno,fentrada,fsalida,tipodni,telefonodueno,observaciones,imagen,publico)
VALUES (".$this->var2str($this->referencia).",".$this->var2str($this->codfamilia).",
".$this->var2str($this->descripcion).",".$this->var2str($this->pvp).",
".$this->var2str($this->factualizado).",".$this->var2str($this->costemedio).",".$this->var2str($this->preciocoste).",
".$this->var2str($this->codimpuesto).",".$this->var2str($this->stockfis).",".$this->var2str($this->stockmin).",
".$this->var2str($this->stockmax).",".$this->var2str($this->controlstock).",
".$this->var2str($this->destacado).",".$this->var2str($this->bloqueado).",
".$this->var2str($this->secompra).",".$this->var2str($this->sevende).",
".$this->var2str($this->equivalencia).",".$this->var2str($this->codbarras).",
".$this->var2str($this->dueno).",
".$this->var2str($this->fentrada).",
".$this->var2str($this->fsalida).",
".$this->var2str($this->tipodni).",
".$this->var2str($this->telefonodueno).",
".$this->var2str($this->observaciones).",".$this->bin2str($this->imagen).",
".$this->var2str($this->publico).");";
$update_referencia = true;
}
if( $this->db->exec($sql) )
{
$this->exists = TRUE;
// Si es un articulo nuevo actualizamos la referencia
if ($update_referencia) {
$fs_var = new fs_var();
$fs_var->simple_save('ultima_referencia_articulo', $this->referencia);
}
// Creamos un nuevo cliente si no existe ningún cliente con el dni
$cliente = new cliente();
$clientes = $cliente->search_by_dni($this->tipodni);
if (empty($clientes)) {
$cliente->codcliente = $cliente->get_new_codigo();
$cliente->nombre = $this->dueno;
$cliente->nombrecomercial = $this->dueno;
$cliente->cifnif = $this->tipodni;
$cliente->telefono1 = $this->telefonodueno;
$cliente->save();
// Creamos la direccion del cliente
$dir_cliente = new direccion_cliente();
$dir_cliente->codcliente = $cliente->codcliente;
$dir_cliente->codpais = 'ESP';
$dir_cliente->descripcion = 'Direccion Facturación';
$dir_cliente->save();
}
return TRUE;
}
else
return FALSE;
}
else
return FALSE;
}
public function delete()
{
$this->clean_cache();
$this->clean_image_cache();
$sql = "DELETE FROM ".$this->table_name." WHERE referencia = ".$this->var2str($this->referencia).";";
if( $this->db->exec($sql) )
{
$this->exists = FALSE;
return TRUE;
}
else
return FALSE;
}
/**
* Comprueba y añade una cadena a la lista de búsquedas precargadas
* en memcache. Devuelve TRUE si la cadena ya está en la lista de
* precargadas.
* @param type $tag
* @return boolean
*/
private function new_search_tag($tag)
{
$encontrado = FALSE;
$actualizar = FALSE;
if( strlen($tag) > 1 )
{
/// obtenemos los datos de memcache
$this->get_search_tags();
foreach(self::$search_tags as $i => $value)
{
if( $value['tag'] == $tag )
{
$encontrado = TRUE;
if( time()+5400 > $value['expires']+300 )
{
self::$search_tags[$i]['count']++;
self::$search_tags[$i]['expires'] = time() + (self::$search_tags[$i]['count'] * 5400);
$actualizar = TRUE;
}
break;
}
}
if( !$encontrado )
{
self::$search_tags[] = array('tag' => $tag, 'expires' => time()+5400, 'count' => 1);
$actualizar = TRUE;
}
if( $actualizar )
$this->cache->set('articulos_searches', self::$search_tags, 5400);
}
return $encontrado;
}
public function get_search_tags()
{
if( !isset(self::$search_tags) )
self::$search_tags = $this->cache->get_array('articulos_searches');
return self::$search_tags;
}
public function cron_job()
{
/*
* Eliminamos el stock de los artículos bloqueados
*/
$this->db->exec("DELETE FROM stocks WHERE referencia IN
(SELECT referencia FROM ".$this->table_name." WHERE bloqueado = true);
UPDATE ".$this->table_name." SET stockfis = 0 WHERE referencia IN
(SELECT referencia FROM ".$this->table_name." WHERE bloqueado = true);");
/// aceleramos las búsquedas
if( $this->get_search_tags() )
{
foreach(self::$search_tags as $i => $value)
{
if( $value['expires'] < time() )
{
/// eliminamos las búsquedas antiguas
unset(self::$search_tags[$i]);
}
else if( $value['count'] > 1 )
{
/// guardamos los resultados de la búsqueda en memcache
$this->cache->set('articulos_search_'.$value['tag'], $this->search($value['tag']), 5400);
echo '.';
}
}
/// guardamos en memcache la lista de búsquedas
$this->cache->set('articulos_searches', self::$search_tags, 5400);
}
}
private function clean_image_cache()
{
if( file_exists('tmp/articulos/'.$this->referencia.'.png') )
unlink('tmp/articulos/'.$this->referencia.'.png');
}
private function clean_cache()
{
/*
* Durante las actualizaciones masivas de artículos se ejecuta esta
* función cada vez que se guarda un artículo, por eso es mejor limitarla.
*/
if( !self::$cleaned_cache )
{
/// obtenemos los datos de memcache
$this->get_search_tags();
if( self::$search_tags )
{
foreach(self::$search_tags as $value)
$this->cache->delete('articulos_search_'.$value['tag']);
}
/// eliminamos también la cache de tpv_yamyam
$this->cache->delete('tpv_yamyam_articulos');
self::$cleaned_cache = TRUE;
}
}
public function search($query, $offset=0, $codfamilia='', $con_stock=FALSE)
{
$artilist = array();
$query = $this->no_html( strtolower($query) );
if($offset == 0 AND $codfamilia == '' AND !$con_stock)
{
/// intentamos obtener los datos de memcache
if( $this->new_search_tag($query) )
$artilist = $this->cache->get_array('articulos_search_'.$query);
}
if( count($artilist) == 0 )
{
if($codfamilia == '')
$sql = "SELECT * FROM ".$this->table_name." WHERE ";
else
$sql = "SELECT * FROM ".$this->table_name." WHERE codfamilia = ".$this->var2str($codfamilia)." AND ";
if($con_stock)
$sql .= "stockfis > 0 AND ";
if( is_numeric($query) )
{
$sql .= "(referencia LIKE '%".$query."%' OR equivalencia LIKE '%".$query."%' OR descripcion LIKE '%".$query."%'
OR codbarras = '".$query."')";
}
else
{
$buscar = str_replace(' ', '%', $query);
$sql .= "(lower(referencia) LIKE '%".$buscar."%' OR lower(equivalencia) LIKE '%".$buscar."%'
OR lower(descripcion) LIKE '%".$buscar."%')";
}
$sql .= " ORDER BY referencia ASC";
$articulos = $this->db->select_limit($sql, FS_ITEM_LIMIT, $offset);
if($articulos)
{
foreach($articulos as $a)
$artilist[] = new articulo($a);
}
}
return $artilist;
}
public function search_by_codbar($cod)
{
$artilist = array();
$articulos = $this->db->select("SELECT * FROM ".$this->table_name." WHERE codbarras = ".$this->var2str($cod)." ORDER BY referencia ASC");
if($articulos)
{
foreach($articulos as $a)
$artilist[] = new articulo($a);
}
return $artilist;
}
/**
* Buscamos un articulo que tenga como referencia $ref . '/'
* para obtener los datos del dueño
*/
public function search_by_ref($ref) {
$tmp_data = explode("/", $ref);
$head_ref = $tmp_data[0] . '/' . $tmp_data[1];
$art_data = array();
$sql = "SELECT * FROM articulos WHERE referencia LIKE '" . $head_ref . "/%' AND referencia <> '" . $ref . "'";
$articulos = $this->db->select($sql);
if ($articulos) {
$art_data['dueno'] = $articulos[0]['dueno'];
$art_data['tipodni'] = $articulos[0]['tipodni'];
$art_data['telefonodueno'] = $articulos[0]['telefonodueno'];
}
return $art_data;
}
public function multiplicar_precios($codfam, $m=1)
{
if( isset($codfam) AND $m != 1 )
{
$this->clean_cache();
return $this->db->exec("UPDATE ".$this->table_name." SET pvp = (pvp*".floatval($m).")
WHERE codfamilia = ".$this->var2str($codfam).";");
}
else
return TRUE;
}
public function all($offset=0, $limit=FS_ITEM_LIMIT)
{
$artilist = array();
$articulos = $this->db->select_limit("SELECT * FROM ".$this->table_name.
" ORDER BY referencia ASC", $limit, $offset);
if($articulos)
{
foreach($articulos as $a)
$artilist[] = new articulo($a);
}
return $artilist;
}
public function all_publico($offset=0, $limit=FS_ITEM_LIMIT)
{
$artilist = array();
$articulos = $this->db->select_limit("SELECT * FROM ".$this->table_name.
" WHERE publico ORDER BY referencia ASC", $limit, $offset);
if($articulos)
{
foreach($articulos as $a)
$artilist[] = new articulo($a);
}
return $artilist;
}
public function all_from_familia($codfamilia, $offset=0, $limit=FS_ITEM_LIMIT)
{
$artilist = array();
$articulos = $this->db->select_limit("SELECT * FROM ".$this->table_name.
" WHERE codfamilia = ".$this->var2str($codfamilia).
" ORDER BY referencia ASC", $limit, $offset);
if($articulos)
{
foreach($articulos as $a)
$artilist[] = new articulo($a);
}
return $artilist;
}
public function count($codfamilia=FALSE)
{
$num = 0;
if( $codfamilia )
{
$articulos = $this->db->select("SELECT COUNT(*) as total FROM ".$this->table_name.
" WHERE codfamilia = ".$this->var2str($codfamilia).";");
}
else
$articulos = $this->db->select("SELECT COUNT(*) as total FROM ".$this->table_name.";");
if($articulos)
$num = intval($articulos[0]['total']);
return $num;
}
public function move_codimpuesto($cod0, $cod1, $mantener=FALSE)
{
if($mantener)
{
$this->clean_cache();
$impuesto = new impuesto();
$impuesto0 = $impuesto->get($cod0);
$impuesto1 = $impuesto->get($cod1);
$multiplo = (100 + $impuesto0->iva) / (100 + $impuesto1->iva);
return $this->db->exec("UPDATE ".$this->table_name." SET codimpuesto = ".$this->var2str($cod1).
", pvp = (pvp*".$multiplo.") WHERE codimpuesto = ".$this->var2str($cod0).";");
}
else
return $this->db->exec("UPDATE ".$this->table_name." SET codimpuesto = ".$this->var2str($cod1).
" WHERE codimpuesto = ".$this->var2str($cod0).";");
}
}
| agpl-3.0 |
carbonadona/pm | workflow/engine/methods/reports/reports_View.php | 8434 | <?php
/**
* reports_View.php
*
* ProcessMaker Open Source Edition
* Copyright (C) 2004 - 2008 Colosa Inc.23
*
* 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/>.
*
* For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
* Coral Gables, FL, 33134, USA, or email info@colosa.com.
*
*/
/**
* Report - Report view
* @package ProcessMaker
* @author Everth S. Berrios Morales
* @copyright 2008 COLOSA
*/
global $RBAC;
switch ($RBAC->userCanAccess('PM_REPORTS'))
{
case -2:
G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_SYSTEM', 'error', 'labels');
G::header('location: ../login/login');
die;
break;
case -1:
G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels');
G::header('location: ../login/login');
die;
break;
}
try {
//form type format hours in the form xml
G::LoadClass('xmlfield_InputPM');
$G_MAIN_MENU = 'processmaker';
$G_ID_MENU_SELECTED = 'REPORTS';
$RPT_UID = $_GET['RPT_UID'];
switch($RPT_UID)
{
case 1:
$sw=0;
if (isset($_POST['form']))
{ if($_POST['form']['FROM']!='0000-00-00' || $_POST['form']['TO']!='0000-00-00') $sw=1;
$fields['FROM']=$_POST['form']['FROM'];
$fields['TO']=$_POST['form']['TO'];
$fields['STARTEDBY']= $_POST['form']['STARTEDBY'];
}
else
{ $fields['FROM']=date('Y-m-d');
$fields['TO']=date('Y-m-d');
}
G::LoadClass('report');
$oReport= new Report();
if($sw==0)
$c = $oReport->generatedReport1();
else
$c = $oReport->generatedReport1_filter($_POST['form']['FROM'], $_POST['form']['TO'], $_POST['form']['STARTEDBY']);
$oHeadPublisher =& headPublisher::getSingleton();
$oHeadPublisher->addScriptFile('/jscore/reports/reports.js');
$G_PUBLISH = new Publisher;
$G_PUBLISH->AddContent('propeltable', 'paged-table', 'reports/report1', $c);
if(isset($_POST['form']))
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report1_search', '', $fields);
else
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report1_search');
G::RenderPage('publish');
break;
case 2:
$sw=0;
if (isset($_POST['form']))
{ if($_POST['form']['FROM']!='0000-00-00' || $_POST['form']['TO']!='0000-00-00') $sw=1;
$fields['FROM']=$_POST['form']['FROM'];
$fields['TO']=$_POST['form']['TO'];
$fields['STARTEDBY']= $_POST['form']['STARTEDBY'];
}
else
{ $fields['FROM']=date('Y-m-d');
$fields['TO']=date('Y-m-d');
}
G::LoadClass('report');
$oReport= new Report();
if($sw==0)
$c = $oReport->generatedReport2();
else
$c = $oReport->generatedReport2_filter($_POST['form']['FROM'], $_POST['form']['TO'], $_POST['form']['STARTEDBY']);
$oHeadPublisher =& headPublisher::getSingleton();
$oHeadPublisher->addScriptFile('/jscore/reports/reports.js');
$G_PUBLISH = new Publisher;
$G_PUBLISH->AddContent('propeltable', 'paged-table', 'reports/report2', $c );
if(isset($_POST['form']))
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report1_search', '', $fields);
else
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report1_search');
G::RenderPage('publish');
break;
case 3:
$sw=0;
if (isset($_POST['form']))
{
$sw=1;
$fields['PROCESS']=$_POST['form']['PROCESS'];
$fields['TASKS']=$_POST['form']['TASKS'];
}
else
{ $fields['FROM']=date('Y-m-d');
$fields['TO']=date('Y-m-d');
}
G::LoadClass('report');
$oReport= new Report();
if($sw==0)
$c = $oReport->generatedReport3();
else
$c = $oReport->generatedReport3_filter($_POST['form']['PROCESS'], $_POST['form']['TASKS']);
$oHeadPublisher =& headPublisher::getSingleton();
$oHeadPublisher->addScriptFile('/jscore/reports/reports.js');
$G_PUBLISH = new Publisher;
if(isset($_POST['form']))
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report_filter', '', $fields);
else
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report_filter');
$G_PUBLISH->AddContent('propeltable', 'paged-table', 'reports/report3', $c);
G::RenderPage('publish');
break;
case 4:
$sw=0;
if (isset($_POST['form']))
{
$sw=1;
$fields['PROCESS']=$_POST['form']['PROCESS'];
$fields['TASKS']=$_POST['form']['TASKS'];
}
G::LoadClass('report');
$oReport= new Report();
if($sw==0)
$c = $oReport->generatedReport4();
else
$c = $oReport->generatedReport4_filter($_POST['form']['PROCESS'], $_POST['form']['TASKS']);
$oHeadPublisher =& headPublisher::getSingleton();
$oHeadPublisher->addScriptFile('/jscore/reports/reports.js');
$G_PUBLISH = new Publisher;
if(isset($_POST['form']))
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report_filter', '', $fields);
else
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report_filter');
$G_PUBLISH->AddContent('propeltable', 'paged-table', 'reports/report4', $c);
G::RenderPage('publish');
break;
case 5:
$sw=0;
if (isset($_POST['form']))
{
$sw=1;
$fields['PROCESS']=$_POST['form']['PROCESS'];
$fields['TASKS']=$_POST['form']['TASKS'];
}
G::LoadClass('report');
$oReport= new Report();
if($sw==0)
$c = $oReport->generatedReport5();
else
$c = $oReport->generatedReport5_filter($_POST['form']['PROCESS'], $_POST['form']['TASKS']);
$oHeadPublisher =& headPublisher::getSingleton();
$oHeadPublisher->addScriptFile('/jscore/reports/reports.js');
$G_PUBLISH = new Publisher;
if(isset($_POST['form']))
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report_filter', '', $fields);
else
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'reports/report_filter');
$G_PUBLISH->AddContent('propeltable', 'paged-table', 'reports/report5', $c);
G::RenderPage('publish');
break;
default :
$foundReport = false;
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$aAvailableReports = $oPluginRegistry->getReports();
foreach ($aAvailableReports as $sReportClass) {
require_once PATH_PLUGINS. $sReportClass . PATH_SEP . 'class.' . $sReportClass . '.php';
$sClassName = $sReportClass . 'Class';
$oInstance = new $sClassName();
$aReports = $oInstance->getAvailableReports();
foreach ($aReports as $oReport) {
if ( $RPT_UID == $oReport['uid'] && method_exists( $oInstance, $RPT_UID )) {
$foundReport = true;
$result = $oInstance->{$RPT_UID} ();
}
}
}
//now check if there are customized reports inside the processes
if ( file_exists ( PATH_DATA_PUBLIC) && is_dir (PATH_DATA_PUBLIC) ) {
if ($handle = opendir( PATH_DATA_PUBLIC ) ) {
while ( false !== ($dir = readdir($handle)) ) {
if ( $dir[0] != '.' && file_exists( PATH_DATA_PUBLIC.$dir.PATH_SEP.'reports.php' ) ) {
include_once (PATH_DATA_PUBLIC.$dir.PATH_SEP.'reports.php');
$className = 'report' . $dir;
if (class_exists ( $className )) {
$oInstance = new $className();
$aReports = $oInstance->getAvailableReports();
foreach ($aReports as $oReport ) {
if ( $RPT_UID == $oReport['uid'] && method_exists( $oInstance, $RPT_UID ) ) {
$foundReport = true;
$result = $oInstance->{$RPT_UID} ();
}
}
}
}
}
}
closedir($handle);
}
if ( !$foundReport )
throw ( new Exception ( "Call to an nonexistent member function " . $RPT_UID . "() ") );
}
}
catch ( Exception $e ) {
$G_PUBLISH = new Publisher;
$aMessage['MESSAGE'] = $e->getMessage();
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'login/showMessage', '', $aMessage );
G::RenderPage( 'publish', 'blank' );
}
| agpl-3.0 |
jzinedine/CMDBuild | cmdbuild/src/main/webapp/javascripts/cmdbuild/controller/administration/classes/CMGeoAttributePanelController.js | 4137 | (function() {
Ext.define("CMDBuild.controller.administration.classes.CMGeoAttributeController", {
constructor: function(view) {
this.view = view;
this.form = view.form;
this.grid = view.grid;
this.gridSM = this.grid.getSelectionModel();
this.gridSM.on('selectionchange', onSelectionChanged , this);
this.currentClassId = null;
this.currentAttribute = null;
this.form.saveButton.on("click", onSaveButtonFormClick, this);
this.form.abortButton.on("click", onAbortButtonFormClick, this);
this.form.cancelButton.on("click", onCancelButtonFormClick, this);
this.form.modifyButton.on("click", onModifyButtonFormClick, this);
this.grid.addAttributeButton.on("click", onAddAttributeClick, this);
},
onClassSelected: function(classId) {
if (CMDBuild.Config.gis.enabled && !_CMUtils.isSimpleTable(classId)) {
this.view.enable();
} else {
this.view.disable();
}
this.currentClassId = classId;
this.currentAttribute = null;
if (this.view.isActive()) {
this.view.onClassSelected(this.currentClassId);
} else {
this.view.mon(this.view, "activate", function() {
this.view.onClassSelected(this.currentClassId);
}, this, {single: true});
}
},
onAddClassButtonClick: function() {
this.view.disable();
}
});
function onSelectionChanged(selection) {
if (selection.selected.length > 0) {
this.currentAttribute = selection.selected.items[0];
this.form.onAttributeSelected(this.currentAttribute);
}
}
function onSaveButtonFormClick() {
var nonValid = this.form.getNonValidFields();
if (nonValid.length > 0) {
CMDBuild.Msg.error(CMDBuild.Translation.common.failure, CMDBuild.Translation.errors.invalid_fields, false);
return;
}
this.form.enableModify(all = true);
CMDBuild.LoadMask.get().show();
var attributeConfig = this.form.getData();
attributeConfig.style = Ext.encode(this.form.getStyle());
var me = this;
var params = {
name: this.form.name.getValue(),
params: Ext.apply(attributeConfig, {
className: _CMCache.getEntryTypeNameById(this.currentClassId)
}),
callback: callback,
success: function(a, b, decoded) {
_CMCache.onGeoAttributeSaved();
me.view.grid.refreshStore(me.currentClassId, attributeConfig.name);
}
};
if (this.currentAttribute != null) {
CMDBuild.ServiceProxy.geoAttribute.modify(params);
} else {
CMDBuild.ServiceProxy.geoAttribute.save(params);
}
}
function onAbortButtonFormClick() {
this.form.disableModify();
if (this.currentAttribute != null) {
this.form.onAttributeSelected(this.currentAttribute);
} else {
this.form.reset();
}
}
function onCancelButtonFormClick() {
Ext.Msg.show({
title: CMDBuild.Translation.management.findfilter.msg.attention,
msg: CMDBuild.Translation.common.confirmpopup.areyousure,
scope: this,
buttons: Ext.Msg.YESNO,
fn: function(button) {
if (button == "yes") {
deleteAttribute.call(this);
}
}
});
}
function deleteAttribute() {
var me = this;
var params = {
"masterTableName": me.currentAttribute.getMasterTableName(),
"name": me.currentAttribute.get("name")
};
CMDBuild.LoadMask.get().show();
CMDBuild.ServiceProxy.geoAttribute.remove({
params: params,
success: function onDeleteGeoAttributeSuccess(response, request, decoded) {
_CMCache.onGeoAttributeDeleted(params.masterTableName, params.name);
me.view.onClassSelected(me.currentClassId);
},
callback: callback
});
}
function onModifyButtonFormClick() {
this.form.enableModify();
}
function onAddAttributeClick() {
this.currentAttribute = null;
this.form.reset();
this.form.enableModify(enableAllFields = true);
this.form.setDefaults();
this.form.hideStyleFields();
this.gridSM.deselectAll();
}
function callback() {
CMDBuild.LoadMask.get().hide();
}
function isItMineOrOfMyParents(attr, classId) {
var table = CMDBuild.Cache.getTableById(classId);
while (table) {
if (attr.masterTableId == table.id) {
return true;
} else {
table = CMDBuild.Cache.getTableById(table.parent);
}
}
return false;
};
})(); | agpl-3.0 |
ging/isabel | lib/SDK/src/sources/v4lUnified/v4luStub.cc | 3482 | /////////////////////////////////////////////////////////////////////////
//
// ISABEL: A group collaboration tool for the Internet
// Copyright (C) 2009 Agora System S.A.
//
// This file is part of Isabel.
//
// Isabel is free software: you can redistribute it and/or modify
// it under the terms of the Affero GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Isabel is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// Affero GNU General Public License for more details.
//
// You should have received a copy of the Affero GNU General Public License
// along with Isabel. If not, see <http://www.gnu.org/licenses/>.
//
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
//
// $Id: v4luStub.cc 20996 2010-07-30 10:43:32Z gabriel $
//
/////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <icf2/general.h>
#include <icf2/notify.hh>
#include <Isabel_SDK/isabelSDK.hh>
#include <Isabel_SDK/systemRegistry.hh>
#include "v4luGrabber.hh"
int
registerV4LuGrabber(void)
{
NOTIFY("%s: starting up\n", V4LU_NAME);
//
// start registration
//
sourceFactory_ref fact= v4luGrabberFactory_t::createFactory();
if ( ! fact.isValid())
{
NOTIFY("---Hardware not found or insufficients rights\n");
NOTIFY("---Bailing out\n");
return -1;
}
srcDescList_ref sdlr= new ql_t<sourceDescriptor_ref>;
for (unsigned i= 0; i < v4luGrabberFactory_t::getNumDevices(); i++)
{
VideoHandler_t *devStat = v4luGrabberFactory_t::getVideoHandler(i);
const char *inputPorts= devStat->getInputPorts();
sourceDescriptor_ref desc=
new v4luGrabberDescriptor_t(devStat->getID(), inputPorts);
if ( ! desc.isValid())
{
NOTIFY("---Module internal error\n");
NOTIFY("---Bailing out\n");
return -1;
}
sdlr->insert(desc);
}
for (ql_t<sourceDescriptor_ref>::iterator_t i= sdlr->begin();
i != sdlr->end();
i++
)
{
sourceDescriptor_ref desc= i;
if (registerSourceFactory(desc, fact))
{
NOTIFY("+++Registered grabber '%s'\n", desc->getID());
}
else
{
NOTIFY("---Unable to register grabber '%s'\n", desc->getID());
NOTIFY("---Bailing out\n");
return -1;
}
}
return 0;
}
void
releaseV4LuGrabber(void)
{
for (unsigned i= 0; i < v4luGrabberFactory_t::getNumDevices(); i++)
{
VideoHandler_t *devStat = v4luGrabberFactory_t::getVideoHandler(i);
if (releaseSourceFactory(devStat->getID()))
{
NOTIFY("+++Released grabber '%s'\n", devStat->getName());
}
else
{
NOTIFY("---Unable to release grabber '%s'\n", devStat->getName());
}
}
sourceFactoryInfoArray_ref sfia= getSourceFactoryInfoArray();
for (int i= 0; i < sfia->size(); i++)
{
sourceFactoryInfo_ref sfi= sfia->elementAt(i);
NOTIFY("%d %s\n", i, sfi->getDescriptor()->getID());
}
NOTIFY("%s: shutting down\n", V4LU_NAME);
}
| agpl-3.0 |
lolgzs/opacce | library/Class/Folder/Manager.php | 1839 | <?php
/**
* Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
*
* AFI-OPAC 2.0 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.
*
* There are special exceptions to the terms and conditions of the AGPL as it
* is applied to this software (see README file).
*
* AFI-OPAC 2.0 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 AFI-OPAC 2.0; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
class Class_Folder_Manager {
/** @var string */
protected $_allowedBasePath;
/**
* @param string $path
* @return Class_Folder_Manager
*/
public static function newInstanceLimitedTo($path) {
$instance = new self();
return $instance->setAllowedBasePath($path);
}
/**
* @category testing
* @param string $path
* @return Class_Folder_Manager
*/
public function setAllowedBasePath($path) {
$this->_allowedBasePath = $path;
return $this;
}
/**
* @codeCoverageIgnore
* @return string
*/
public function getAllowedBasePath() {
if (null === $this->_allowedBasePath) {
$this->_allowedBasePath = USERFILESPATH;
}
return $this->_allowedBasePath;
}
/**
* @param string $path
* @return bool
*/
public function ensure($path) {
if (0 !== strpos($path, $this->getAllowedBasePath())) {
return false;
}
if (file_exists($path)) {
return true;
}
return @mkdir($path, 0777, true);
}
}
?> | agpl-3.0 |
gelnior/newebe | newebe/apps/activities/_design/views/full/map.js | 81 | function(doc) {
if("Activity" == doc.doc_type) {
emit(doc._id, doc);
}
}
| agpl-3.0 |
DraXus/andaluciapeople | tracking/templatetags/tracking_tags.py | 1704 | from django import template
from tracking.models import Visitor
register = template.Library()
class VisitorsOnSite(template.Node):
"""
Injects the number of active users on your site as an integer into the context
"""
def __init__(self, varname, same_page=None):
self.varname = varname
self.same_page = same_page
def render(self, context):
if self.same_page:
try:
request = context['request']
count = Visitor.objects.active().filter(url=request.path).count()
except KeyError:
raise template.TemplateSyntaxError("Please add 'django.core.context_processors.request' to your TEMPLATE_CONTEXT_PROCESSORS if you want to see how many users are on the same page.")
else:
count = Visitor.objects.active().count()
context[self.varname] = count
return ''
def visitors_on_site(parser, token):
"""
Determines the number of active users on your site and puts it into the context
"""
try:
tag, a, varname = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError('visitors_on_site usage: {% visitors_on_site as visitors %}')
return VisitorsOnSite(varname)
register.tag(visitors_on_site)
def visitors_on_page(parser, token):
"""
Determines the number of active users on the same page and puts it into the context
"""
try:
tag, a, varname = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError('visitors_on_page usage: {% visitors_on_page as visitors %}')
return VisitorsOnSite(varname, same_page=True)
register.tag(visitors_on_page)
| agpl-3.0 |
addradio/mpeg-audio-streams | src/main/java/net/addradio/codec/mpeg/audio/model/BitMaskFlag.java | 687 | /**
* Class: BitMaskFlag<br/>
* <br/>
* Created: 20.10.2017<br/>
* Filename: BitMaskFlag.java<br/>
* Version: $Revision: $<br/>
* <br/>
* last modified on $Date: $<br/>
* by $Author: $<br/>
* <br/>
* @author <a href="mailto:sebastian.weiss@nacamar.de">Sebastian A. Weiss, nacamar GmbH</a>
* @version $Author: $ -- $Revision: $ -- $Date: $
* <br/>
* (c) Sebastian A. Weiss, nacamar GmbH 2012 - All rights reserved.
*/
package net.addradio.codec.mpeg.audio.model;
/**
* BitMaskFlag
*/
public interface BitMaskFlag {
/**
* getBitMask.
*
* @return {@code int} the bit mask associated with the flag.
*/
int getBitMask();
}
| agpl-3.0 |
harish-patel/ecrm | modules/Charts/Dashlets/OutcomeByMonthDashlet/OutcomeByMonthDashlet.nb_NO.lang.php | 1966 | <?php
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
********************************************************************************/
$dashletStrings = array (
'OutcomeByMonthDashlet' =>
array (
'LBL_TITLE' => 'Resultat etter måned',
'LBL_DESCRIPTION' => 'Diagram av månedlig resultat',
'LBL_REFRESH' => 'Oppdater diagram',
),
);
| agpl-3.0 |
gnosygnu/xowa_android | _100_core/src/main/java/gplx/core/lists/Iterator_null.java | 446 | package gplx.core.lists; import gplx.*; import gplx.core.*;
public class Iterator_null implements java.util.Iterator {//_20110320 //#<>java.util.Iterator~java.util.Iterator
public boolean hasNext() {return false;}//#<>MoveNext~hasNext
public Object next() {return null;}//#<>Current {get {return null;}}~next() {return null;}
public void remove() {}//#<>Reset~remove
public static final Iterator_null Instance = new Iterator_null();
}
| agpl-3.0 |
cejebuto/OrfeoWind | include/class/adodb/tests/test5.php | 1321 | <?php
/*
V4.80 8 Mar 2006 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
*/
// Select an empty record from the database
include('../adodb.inc.php');
include('../tohtml.inc.php');
include('../adodb-errorpear.inc.php');
if (0) {
$conn = &ADONewConnection('mysql');
$conn->PConnect("localhost","root","","xphplens");
print $conn->databaseType.':'.$conn->GenID().'<br>';
}
if (0) {
$conn = &ADONewConnection("oci8"); // create a connection
$conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); // connect to MySQL, testdb
print $conn->databaseType.':'.$conn->GenID();
}
if (0) {
$conn = &ADONewConnection("ibase"); // create a connection
$conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); // connect to MySQL, testdb
print $conn->databaseType.':'.$conn->GenID().'<br>';
}
if (0) {
$conn = &ADONewConnection('postgres');
@$conn->PConnect("susetikus","tester","test","test");
print $conn->databaseType.':'.$conn->GenID().'<br>';
}
?>
| agpl-3.0 |
PRX/feeder.prx.org | db/migrate/20151008163401_fix_deleted_at_type.rb | 387 | class FixDeletedAtType < ActiveRecord::Migration
def change
to_delete = Episode.deleted.all.collect{|e| e.id}
remove_column :episodes, :deleted_at
remove_column :podcasts, :deleted_at
add_column :episodes, :deleted_at, :timestamp
add_column :podcasts, :deleted_at, :timestamp
to_delete.each{ |id| Episode.with_deleted.find_by_id(id).try(:destroy) }
end
end
| agpl-3.0 |
hivetech/judo | juju-core/state/relationunit.go | 13025 | // Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
stderrors "errors"
"fmt"
"strings"
"labix.org/v2/mgo"
"labix.org/v2/mgo/txn"
"launchpad.net/juju-core/charm"
errors "launchpad.net/juju-core/errors"
"launchpad.net/juju-core/names"
"launchpad.net/juju-core/utils"
)
// RelationUnit holds information about a single unit in a relation, and
// allows clients to conveniently access unit-specific functionality.
type RelationUnit struct {
st *State
relation *Relation
unit *Unit
endpoint Endpoint
scope string
}
// Relation returns the relation associated with the unit.
func (ru *RelationUnit) Relation() *Relation {
return ru.relation
}
// Endpoint returns the relation endpoint that defines the unit's
// participation in the relation.
func (ru *RelationUnit) Endpoint() Endpoint {
return ru.endpoint
}
// PrivateAddress returns the private address of the unit and whether it is valid.
func (ru *RelationUnit) PrivateAddress() (string, bool) {
return ru.unit.PrivateAddress()
}
// ErrCannotEnterScope indicates that a relation unit failed to enter its scope
// due to either the unit or the relation not being Alive.
var ErrCannotEnterScope = stderrors.New("cannot enter scope: unit or relation is not alive")
// ErrCannotEnterScopeYet indicates that a relation unit failed to enter its
// scope due to a required and pre-existing subordinate unit that is not Alive.
// Once that subordinate has been removed, a new one can be created.
var ErrCannotEnterScopeYet = stderrors.New("cannot enter scope yet: non-alive subordinate unit has not been removed")
// EnterScope ensures that the unit has entered its scope in the relation.
// When the unit has already entered its relation scope, EnterScope will report
// success but make no changes to state.
//
// Otherwise, assuming both the relation and the unit are alive, it will enter
// scope and create or overwrite the unit's settings in the relation according
// to the supplied map.
//
// If the unit is a principal and the relation has container scope, EnterScope
// will also create the required subordinate unit, if it does not already exist;
// this is because there's no point having a principal in scope if there is no
// corresponding subordinate to join it.
//
// Once a unit has entered a scope, it stays in scope without further
// intervention; the relation will not be able to become Dead until all units
// have departed its scopes.
func (ru *RelationUnit) EnterScope(settings map[string]interface{}) error {
// Verify that the unit is not already in scope, and abort without error
// if it is.
ruKey, err := ru.key(ru.unit.Name())
if err != nil {
return err
}
if count, err := ru.st.relationScopes.FindId(ruKey).Count(); err != nil {
return err
} else if count != 0 {
return nil
}
// Collect the operations necessary to enter scope, as follows:
// * Check unit and relation state, and incref the relation.
// * TODO(fwereade): check unit status == params.StatusStarted (this
// breaks a bunch of tests in a boring but noisy-to-fix way, and is
// being saved for a followup).
unitName, relationKey := ru.unit.doc.Name, ru.relation.doc.Key
ops := []txn.Op{{
C: ru.st.units.Name,
Id: unitName,
Assert: isAliveDoc,
}, {
C: ru.st.relations.Name,
Id: relationKey,
Assert: isAliveDoc,
Update: D{{"$inc", D{{"unitcount", 1}}}},
}}
// * Create the unit settings in this relation, if they do not already
// exist; or completely overwrite them if they do. This must happen
// before we create the scope doc, because the existence of a scope doc
// is considered to be a guarantee of the existence of a settings doc.
settingsChanged := func() (bool, error) { return false, nil }
if count, err := ru.st.settings.FindId(ruKey).Count(); err != nil {
return err
} else if count == 0 {
ops = append(ops, createSettingsOp(ru.st, ruKey, settings))
} else {
var rop txn.Op
rop, settingsChanged, err = replaceSettingsOp(ru.st, ruKey, settings)
if err != nil {
return err
}
ops = append(ops, rop)
}
// * Create the scope doc.
ops = append(ops, txn.Op{
C: ru.st.relationScopes.Name,
Id: ruKey,
Assert: txn.DocMissing,
Insert: relationScopeDoc{ruKey},
})
// * If the unit should have a subordinate, and does not, create it.
var existingSubName string
if subOps, subName, err := ru.subordinateOps(); err != nil {
return err
} else {
existingSubName = subName
ops = append(ops, subOps...)
}
// Now run the complete transaction, or figure out why we can't.
if err := ru.st.runTransaction(ops); err != txn.ErrAborted {
return err
}
if count, err := ru.st.relationScopes.FindId(ruKey).Count(); err != nil {
return err
} else if count != 0 {
// The scope document exists, so we're actually already in scope.
return nil
}
// The relation or unit might no longer be Alive. (Note that there is no
// need for additional checks if we're trying to create a subordinate
// unit: this could fail due to the subordinate service's not being Alive,
// but this case will always be caught by the check for the relation's
// life (because a relation cannot be Alive if its services are not).)
if alive, err := isAlive(ru.st.units, unitName); err != nil {
return err
} else if !alive {
return ErrCannotEnterScope
}
if alive, err := isAlive(ru.st.relations, relationKey); err != nil {
return err
} else if !alive {
return ErrCannotEnterScope
}
// Maybe a subordinate used to exist, but is no longer alive. If that is
// case, we will be unable to enter scope until that unit is gone.
if existingSubName != "" {
if alive, err := isAlive(ru.st.units, existingSubName); err != nil {
return err
} else if !alive {
return ErrCannotEnterScopeYet
}
}
// It's possible that there was a pre-existing settings doc whose version
// has changed under our feet, preventing us from clearing it properly; if
// that is the case, something is seriously wrong (nobody else should be
// touching that doc under our feet) and we should bail out.
prefix := fmt.Sprintf("cannot enter scope for unit %q in relation %q: ", ru.unit, ru.relation)
if changed, err := settingsChanged(); err != nil {
return err
} else if changed {
return fmt.Errorf(prefix + "concurrent settings change detected")
}
// Apparently, all our assertions should have passed, but the txn was
// aborted: something is really seriously wrong.
return fmt.Errorf(prefix + "inconsistent state in EnterScope")
}
// subordinateOps returns any txn operations necessary to ensure sane
// subordinate state when entering scope. If a required subordinate unit
// exists and is Alive, its name will be returned as well; if one exists
// but is not Alive, ErrCannotEnterScopeYet is returned.
func (ru *RelationUnit) subordinateOps() ([]txn.Op, string, error) {
if !ru.unit.IsPrincipal() || ru.endpoint.Scope != charm.ScopeContainer {
return nil, "", nil
}
related, err := ru.relation.RelatedEndpoints(ru.endpoint.ServiceName)
if err != nil {
return nil, "", err
}
if len(related) != 1 {
return nil, "", fmt.Errorf("expected single related endpoint, got %v", related)
}
serviceName, unitName := related[0].ServiceName, ru.unit.doc.Name
selSubordinate := D{{"service", serviceName}, {"principal", unitName}}
var lDoc lifeDoc
if err := ru.st.units.Find(selSubordinate).One(&lDoc); err == mgo.ErrNotFound {
service, err := ru.st.Service(serviceName)
if err != nil {
return nil, "", err
}
_, ops, err := service.addUnitOps(unitName, nil)
return ops, "", err
} else if err != nil {
return nil, "", err
} else if lDoc.Life != Alive {
return nil, "", ErrCannotEnterScopeYet
}
return []txn.Op{{
C: ru.st.units.Name,
Id: lDoc.Id,
Assert: isAliveDoc,
}}, lDoc.Id, nil
}
// LeaveScope signals that the unit has left its scope in the relation.
// After the unit has left its relation scope, it is no longer a member
// of the relation; if the relation is dying when its last member unit
// leaves, it is removed immediately. It is not an error to leave a scope
// that the unit is not, or never was, a member of.
func (ru *RelationUnit) LeaveScope() error {
key, err := ru.key(ru.unit.Name())
if err != nil {
return err
}
// The logic below is involved because we remove a dying relation
// with the last unit that leaves a scope in it. It handles three
// possible cases:
//
// 1. Relation is alive: just leave the scope.
//
// 2. Relation is dying, and other units remain: just leave the scope.
//
// 3. Relation is dying, and this is the last unit: leave the scope
// and remove the relation.
//
// In each of those cases, proper assertions are done to guarantee
// that the condition observed is still valid when the transaction is
// applied. If an abort happens, it observes the new condition and
// retries. In theory, a worst case will try at most all of the
// conditions once, because units cannot join a scope once its relation
// is dying.
//
// Keep in mind that in the first iteration of the loop it's possible
// to have a Dying relation with a smaller-than-real unit count, because
// Destroy changes the Life attribute in memory (units could join before
// the database is actually changed).
desc := fmt.Sprintf("unit %q in relation %q", ru.unit, ru.relation)
for attempt := 0; attempt < 3; attempt++ {
count, err := ru.st.relationScopes.FindId(key).Count()
if err != nil {
return fmt.Errorf("cannot examine scope for %s: %v", desc, err)
} else if count == 0 {
return nil
}
ops := []txn.Op{{
C: ru.st.relationScopes.Name,
Id: key,
Assert: txn.DocExists,
Remove: true,
}}
if ru.relation.doc.Life == Alive {
ops = append(ops, txn.Op{
C: ru.st.relations.Name,
Id: ru.relation.doc.Key,
Assert: D{{"life", Alive}},
Update: D{{"$inc", D{{"unitcount", -1}}}},
})
} else if ru.relation.doc.UnitCount > 1 {
ops = append(ops, txn.Op{
C: ru.st.relations.Name,
Id: ru.relation.doc.Key,
Assert: D{{"unitcount", D{{"$gt", 1}}}},
Update: D{{"$inc", D{{"unitcount", -1}}}},
})
} else {
relOps, err := ru.relation.removeOps("", ru.unit)
if err != nil {
return err
}
ops = append(ops, relOps...)
}
if err = ru.st.runTransaction(ops); err != txn.ErrAborted {
if err != nil {
return fmt.Errorf("cannot leave scope for %s: %v", desc, err)
}
return err
}
if err := ru.relation.Refresh(); errors.IsNotFoundError(err) {
return nil
} else if err != nil {
return err
}
}
return fmt.Errorf("cannot leave scope for %s: inconsistent state", desc)
}
// WatchScope returns a watcher which notifies of counterpart units
// entering and leaving the unit's scope.
func (ru *RelationUnit) WatchScope() *RelationScopeWatcher {
role := counterpartRole(ru.endpoint.Role)
scope := ru.scope + "#" + string(role)
return newRelationScopeWatcher(ru.st, scope, ru.unit.Name())
}
// Settings returns a Settings which allows access to the unit's settings
// within the relation.
func (ru *RelationUnit) Settings() (*Settings, error) {
key, err := ru.key(ru.unit.Name())
if err != nil {
return nil, err
}
return readSettings(ru.st, key)
}
// ReadSettings returns a map holding the settings of the unit with the
// supplied name within this relation. An error will be returned if the
// relation no longer exists, or if the unit's service is not part of the
// relation, or the settings are invalid; but mere non-existence of the
// unit is not grounds for an error, because the unit settings are
// guaranteed to persist for the lifetime of the relation, regardless
// of the lifetime of the unit.
func (ru *RelationUnit) ReadSettings(uname string) (m map[string]interface{}, err error) {
defer utils.ErrorContextf(&err, "cannot read settings for unit %q in relation %q", uname, ru.relation)
if !names.IsUnit(uname) {
return nil, fmt.Errorf("%q is not a valid unit name", uname)
}
key, err := ru.key(uname)
if err != nil {
return nil, err
}
node, err := readSettings(ru.st, key)
if err != nil {
return nil, err
}
return node.Map(), nil
}
// key returns a string, based on the relation and the supplied unit name,
// which is used as a key for that unit within this relation in the settings,
// presence, and relationScopes collections.
func (ru *RelationUnit) key(uname string) (string, error) {
uparts := strings.Split(uname, "/")
sname := uparts[0]
ep, err := ru.relation.Endpoint(sname)
if err != nil {
return "", err
}
parts := []string{ru.scope, string(ep.Role), uname}
return strings.Join(parts, "#"), nil
}
// relationScopeDoc represents a unit which is in a relation scope.
// The relation, container, role, and unit are all encoded in the key.
type relationScopeDoc struct {
Key string `bson:"_id"`
}
func (d *relationScopeDoc) unitName() string {
parts := strings.Split(d.Key, "#")
return parts[len(parts)-1]
}
| agpl-3.0 |
metelkinp/CRM | custom/modulebuilder/builds/test/SugarModules/modules/test_module/metadata/listviewdefs.php | 2563 | <?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 - 2017 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".
*/
if (!defined('sugarEntry') || !sugarEntry) {
die('Not A Valid Entry Point');
}
$module_name = 'test_module';
$listViewDefs[$module_name] = array(
'NAME' => array(
'width' => '32',
'label' => 'LBL_NAME',
'default' => true,
'link' => true
),
'ASSIGNED_USER_NAME' => array(
'width' => '9',
'label' => 'LBL_ASSIGNED_TO_NAME',
'module' => 'Employees',
'id' => 'ASSIGNED_USER_ID',
'default' => true
),
);
| agpl-3.0 |
trezy/eidetica | src/panes/components/Switch.js | 642 | import PropTypes from 'prop-types'
import React from 'react'
const Switch = (props) => {
const {
checked,
id,
onChange,
} = props
return (
<React.Fragment>
<input
checked={checked}
className="switch-control"
hidden
id={id}
onChange={onChange}
type="checkbox" />
<label
className={['switch']}
htmlFor={id} />
</React.Fragment>
)
}
Switch.defaultProps = {
checked: false,
}
Switch.propTypes = {
checked: PropTypes.bool,
id: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
}
export default Switch
| agpl-3.0 |
pku9104038/edx-platform | common/djangoapps/student/tests/test_login.py | 13422 | '''
Tests for student activation and login
'''
import json
import unittest
from mock import patch
from django.test import TestCase
from django.test.client import Client
from django.test.utils import override_settings
from django.conf import settings
from django.core.cache import cache
from django.core.urlresolvers import reverse, NoReverseMatch
from student.tests.factories import UserFactory, RegistrationFactory, UserProfileFactory
from student.views import _parse_course_id_from_string, _get_course_enrollment_domain
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, mixed_store_config
from xmodule.modulestore.inheritance import own_metadata
from xmodule.modulestore.django import editable_modulestore
from external_auth.models import ExternalAuthMap
TEST_DATA_MIXED_MODULESTORE = mixed_store_config(settings.COMMON_TEST_DATA_ROOT, {})
class LoginTest(TestCase):
'''
Test student.views.login_user() view
'''
def setUp(self):
# Create one user and save it to the database
self.user = UserFactory.build(username='test', email='test@edx.org')
self.user.set_password('test_password')
self.user.save()
# Create a registration for the user
RegistrationFactory(user=self.user)
# Create a profile for the user
UserProfileFactory(user=self.user)
# Create the test client
self.client = Client()
cache.clear()
# Store the login url
try:
self.url = reverse('login_post')
except NoReverseMatch:
self.url = reverse('login')
def test_login_success(self):
response, mock_audit_log = self._login_response('test@edx.org', 'test_password', patched_audit_log='student.models.AUDIT_LOG')
self._assert_response(response, success=True)
self._assert_audit_log(mock_audit_log, 'info', [u'Login success', u'test@edx.org'])
def test_login_success_unicode_email(self):
unicode_email = u'test' + unichr(40960) + u'@edx.org'
self.user.email = unicode_email
self.user.save()
response, mock_audit_log = self._login_response(unicode_email, 'test_password', patched_audit_log='student.models.AUDIT_LOG')
self._assert_response(response, success=True)
self._assert_audit_log(mock_audit_log, 'info', [u'Login success', unicode_email])
def test_login_fail_no_user_exists(self):
nonexistent_email = u'not_a_user@edx.org'
response, mock_audit_log = self._login_response(nonexistent_email, 'test_password')
self._assert_response(response, success=False,
value='Email or password is incorrect')
self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'Unknown user email', nonexistent_email])
def test_login_fail_wrong_password(self):
response, mock_audit_log = self._login_response('test@edx.org', 'wrong_password')
self._assert_response(response, success=False,
value='Email or password is incorrect')
self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'password for', u'test@edx.org', u'invalid'])
def test_login_not_activated(self):
# De-activate the user
self.user.is_active = False
self.user.save()
# Should now be unable to login
response, mock_audit_log = self._login_response('test@edx.org', 'test_password')
self._assert_response(response, success=False,
value="This account has not been activated")
self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'Account not active for user'])
def test_login_unicode_email(self):
unicode_email = u'test@edx.org' + unichr(40960)
response, mock_audit_log = self._login_response(unicode_email, 'test_password')
self._assert_response(response, success=False)
self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', unicode_email])
def test_login_unicode_password(self):
unicode_password = u'test_password' + unichr(1972)
response, mock_audit_log = self._login_response('test@edx.org', unicode_password)
self._assert_response(response, success=False)
self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'password for', u'test@edx.org', u'invalid'])
def test_logout_logging(self):
response, _ = self._login_response('test@edx.org', 'test_password')
self._assert_response(response, success=True)
logout_url = reverse('logout')
with patch('student.models.AUDIT_LOG') as mock_audit_log:
response = self.client.post(logout_url)
self.assertEqual(response.status_code, 302)
self._assert_audit_log(mock_audit_log, 'info', [u'Logout', u'test'])
def test_login_ratelimited_success(self):
# Try (and fail) logging in with fewer attempts than the limit of 30
# and verify that you can still successfully log in afterwards.
for i in xrange(20):
password = u'test_password{0}'.format(i)
response, _audit_log = self._login_response('test@edx.org', password)
self._assert_response(response, success=False)
# now try logging in with a valid password
response, _audit_log = self._login_response('test@edx.org', 'test_password')
self._assert_response(response, success=True)
def test_login_ratelimited(self):
# try logging in 30 times, the default limit in the number of failed
# login attempts in one 5 minute period before the rate gets limited
for i in xrange(30):
password = u'test_password{0}'.format(i)
self._login_response('test@edx.org', password)
# check to see if this response indicates that this was ratelimited
response, _audit_log = self._login_response('test@edx.org', 'wrong_password')
self._assert_response(response, success=False, value='Too many failed login attempts')
def _login_response(self, email, password, patched_audit_log='student.views.AUDIT_LOG'):
''' Post the login info '''
post_params = {'email': email, 'password': password}
with patch(patched_audit_log) as mock_audit_log:
result = self.client.post(self.url, post_params)
return result, mock_audit_log
def _assert_response(self, response, success=None, value=None):
'''
Assert that the response had status 200 and returned a valid
JSON-parseable dict.
If success is provided, assert that the response had that
value for 'success' in the JSON dict.
If value is provided, assert that the response contained that
value for 'value' in the JSON dict.
'''
self.assertEqual(response.status_code, 200)
try:
response_dict = json.loads(response.content)
except ValueError:
self.fail("Could not parse response content as JSON: %s"
% str(response.content))
if success is not None:
self.assertEqual(response_dict['success'], success)
if value is not None:
msg = ("'%s' did not contain '%s'" %
(str(response_dict['value']), str(value)))
self.assertTrue(value in response_dict['value'], msg)
def _assert_audit_log(self, mock_audit_log, level, log_strings):
"""
Check that the audit log has received the expected call as its last call.
"""
method_calls = mock_audit_log.method_calls
name, args, _kwargs = method_calls[-1]
self.assertEquals(name, level)
self.assertEquals(len(args), 1)
format_string = args[0]
for log_string in log_strings:
self.assertIn(log_string, format_string)
class UtilFnTest(TestCase):
"""
Tests for utility functions in student.views
"""
def test__parse_course_id_from_string(self):
"""
Tests the _parse_course_id_from_string util function
"""
COURSE_ID = u'org/num/run' # pylint: disable=C0103
COURSE_URL = u'/courses/{}/otherstuff'.format(COURSE_ID) # pylint: disable=C0103
NON_COURSE_URL = u'/blahblah' # pylint: disable=C0103
self.assertEqual(_parse_course_id_from_string(COURSE_URL), COURSE_ID)
self.assertIsNone(_parse_course_id_from_string(NON_COURSE_URL))
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
class ExternalAuthShibTest(ModuleStoreTestCase):
"""
Tests how login_user() interacts with ExternalAuth, in particular Shib
"""
def setUp(self):
self.store = editable_modulestore()
self.course = CourseFactory.create(org='Stanford', number='456', display_name='NO SHIB')
self.shib_course = CourseFactory.create(org='Stanford', number='123', display_name='Shib Only')
self.shib_course.enrollment_domain = 'shib:https://idp.stanford.edu/'
metadata = own_metadata(self.shib_course)
metadata['enrollment_domain'] = self.shib_course.enrollment_domain
self.store.update_metadata(self.shib_course.location.url(), metadata)
self.user_w_map = UserFactory.create(email='withmap@stanford.edu')
self.extauth = ExternalAuthMap(external_id='withmap@stanford.edu',
external_email='withmap@stanford.edu',
external_domain='shib:https://idp.stanford.edu/',
external_credentials="",
user=self.user_w_map)
self.user_w_map.save()
self.extauth.save()
self.user_wo_map = UserFactory.create(email='womap@gmail.com')
self.user_wo_map.save()
@unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set")
def test_login_page_redirect(self):
"""
Tests that when a shib user types their email address into the login page, they get redirected
to the shib login.
"""
response = self.client.post(reverse('login'), {'email': self.user_w_map.email, 'password': ''})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, json.dumps({'success': False, 'redirect': reverse('shib-login')}))
@unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set")
def test__get_course_enrollment_domain(self):
"""
Tests the _get_course_enrollment_domain utility function
"""
self.assertIsNone(_get_course_enrollment_domain("I/DONT/EXIST"))
self.assertIsNone(_get_course_enrollment_domain(self.course.id))
self.assertEqual(self.shib_course.enrollment_domain, _get_course_enrollment_domain(self.shib_course.id))
@unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set")
def test_login_required_dashboard(self):
"""
Tests redirects to when @login_required to dashboard, which should always be the normal login,
since there is no course context
"""
response = self.client.get(reverse('dashboard'))
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], 'http://testserver/accounts/login?next=/dashboard')
@unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set")
def test_externalauth_login_required_course_context(self):
"""
Tests the redirects when visiting course-specific URL with @login_required.
Should vary by course depending on its enrollment_domain
"""
TARGET_URL = reverse('courseware', args=[self.course.id]) # pylint: disable=C0103
noshib_response = self.client.get(TARGET_URL, follow=True)
self.assertEqual(noshib_response.redirect_chain[-1],
('http://testserver/accounts/login?next={url}'.format(url=TARGET_URL), 302))
self.assertContains(noshib_response, ("Log into your {platform_name} Account | {platform_name}"
.format(platform_name=settings.PLATFORM_NAME)))
self.assertEqual(noshib_response.status_code, 200)
TARGET_URL_SHIB = reverse('courseware', args=[self.shib_course.id]) # pylint: disable=C0103
shib_response = self.client.get(**{'path': TARGET_URL_SHIB,
'follow': True,
'REMOTE_USER': self.extauth.external_id,
'Shib-Identity-Provider': 'https://idp.stanford.edu/'})
# Test that the shib-login redirect page with ?next= and the desired page are part of the redirect chain
# The 'courseware' page actually causes a redirect itself, so it's not the end of the chain and we
# won't test its contents
self.assertEqual(shib_response.redirect_chain[-3],
('http://testserver/shib-login/?next={url}'.format(url=TARGET_URL_SHIB), 302))
self.assertEqual(shib_response.redirect_chain[-2],
('http://testserver{url}'.format(url=TARGET_URL_SHIB), 302))
self.assertEqual(shib_response.status_code, 200)
| agpl-3.0 |
moneypot/shiba | Cmd/Profit.js | 1302 | 'use strict';
const debug = require('debug')('shiba:cmd:profit');
const ProfitParser = require('./ProfitParser').parser;
const Pg = require('../Pg');
function Profit() {
}
Profit.prototype.handle = function*(client, msg, rawInput) {
debug('Handling profit: %s', JSON.stringify(rawInput));
let input;
try {
input = ProfitParser.parse(rawInput.replace(/^\s+|\s+$/g, ''));
} catch(err) {
client.doSay('wow. very usage failure. such retry', msg.channelName);
throw err;
}
try {
let username = input.user ? input.user : msg.username;
// TODO: Move this constant.
let isOwner = username.toLowerCase() === 'ryan';
let result;
if (isOwner && input.time)
result = yield* Pg.getSiteProfitTime(input.time);
else if (isOwner)
result = yield* Pg.getSiteProfitGames(input.games);
else if (input.time)
result = yield* Pg.getProfitTime(username, input.time);
else
result = yield* Pg.getProfitGames(username, input.games);
let response = (result / 100).toFixed(2) + ' bits';
client.doSay(response, msg.channelName);
} catch(err) {
client.doSay('wow. such database fail', msg.channelName);
console.error('ERROR:', err && err.stack || err);
throw err;
}
};
module.exports = exports = Profit;
| agpl-3.0 |
Power-to-the-People/p2p | P2P EE/model/api/P2P EE model api/src/nz/org/p2p/model/member/api/DefaultPassKeyIdentifier.java | 1472 | package nz.org.p2p.model.member.api;
import java.util.Map;
import java.util.WeakHashMap;
/**
* <p>The pass key class provides Provide a type safe object for PassKeys .</p>
*
* <p>This software is offered under the terms of the GNU AFERO GENERAL PUBLIC LICENCE of 2007,
* <b>See</b> {@link nz.org.p2p.model.member package documentation} for more information.</p>
*
* @author John Hutcheson <witerat.test@gmail.com>
* @author Richard Thomas <richard@kanecta.com>
* @see MemberManagerService#getMember(PassKeyService)
*/
public class DefaultPassKeyIdentifier implements PassKeyIdentifierService{
/** The passkey. */
String passKey;
/** The identifier cache. */
private static Map<String, PassKeyIdentifierService> passKeys=
new WeakHashMap<String, PassKeyIdentifierService>();
/**
* Gets a named identifier from a cache or creates a new one.
*
* @param passKey the address
* @return A member identifier
*/
public static PassKeyIdentifierService get(String passKey) {
if(!passKeys.containsKey(passKey)) {
passKeys.put(passKey, new DefaultPassKeyIdentifier(passKey));
}
return passKeys.get(passKey);
}
/**
* create a passkey key record.
*
* @param passKey the passkey
*/
private DefaultPassKeyIdentifier(String passKey) {
this.passKey=passKey;
}
/**
* Gets The passkey property.
*
* @return A passkey
* @see PassKeyService
*/
@Override
public String getPassKey() {
return passKey;
}
}
| agpl-3.0 |
BernardFW/bernard | src/bernard/engine/responder.py | 2501 | # coding: utf-8
from typing import (
TYPE_CHECKING,
List,
Union,
)
from bernard.layers import (
BaseLayer,
Stack,
)
if TYPE_CHECKING:
from .platform import Platform
from .request import Request
Layers = Union[Stack, List[BaseLayer]]
class ResponderError(Exception):
"""
Base responder exception
"""
class UnacceptableStack(ResponderError):
"""
The stack you're tryping to send can't be accepted by the platform
"""
class Responder(object):
"""
The responder is the abstract object that allows to talk back to the
conversation.
If you implement a platform, you can overload this class but you probably
won't need to change anything.
"""
def __init__(self, platform: 'Platform'):
self.platform = platform
self._stacks = [] # type: List[Stack]
def send(self, stack: Layers):
"""
Add a message stack to the send list.
"""
if not isinstance(stack, Stack):
stack = Stack(stack)
if not self.platform.accept(stack):
raise UnacceptableStack('The platform does not allow "{}"'
.format(stack.describe()))
self._stacks.append(stack)
def clear(self):
"""
Reset the send list.
"""
self._stacks = []
async def flush(self, request: 'Request'):
"""
Send all queued messages.
The first step is to convert all media in the stacked layers then the
second step is to send all messages as grouped in time as possible.
"""
from bernard.middleware import MiddlewareManager
for stack in self._stacks:
await stack.convert_media(self.platform)
func = MiddlewareManager.instance().get('flush', self._flush)
await func(request, self._stacks)
async def _flush(self, request: 'Request', stacks: List[Stack]):
"""
Perform the actual sending to platform. This is separated from
`flush()` since it needs to be inside a middleware call.
"""
for stack in stacks:
await self.platform.send(request, stack)
async def make_transition_register(self, request: 'Request'):
"""
Use all underlying stacks to generate the next transition register.
"""
register = {}
for stack in self._stacks:
register = await stack.patch_register(register, request)
return register
| agpl-3.0 |
grafana/loki | pkg/querier/queryrange/ordering.go | 2309 | package queryrange
import (
"sort"
"github.com/grafana/loki/pkg/logproto"
)
/*
Utils for manipulating ordering
*/
type entries []logproto.Entry
func (m entries) start() int64 {
if len(m) == 0 {
return 0
}
return m[0].Timestamp.UnixNano()
}
type byDir struct {
markers []entries
direction logproto.Direction
labels string
}
func (a byDir) Len() int { return len(a.markers) }
func (a byDir) Swap(i, j int) { a.markers[i], a.markers[j] = a.markers[j], a.markers[i] }
func (a byDir) Less(i, j int) bool {
x, y := a.markers[i].start(), a.markers[j].start()
if a.direction == logproto.BACKWARD {
return x > y
}
return y > x
}
func (a byDir) EntriesCount() (n int) {
for _, m := range a.markers {
n += len(m)
}
return n
}
func (a byDir) merge() []logproto.Entry {
result := make([]logproto.Entry, 0, a.EntriesCount())
sort.Sort(a)
for _, m := range a.markers {
result = append(result, m...)
}
return result
}
// priorityqueue is used for extracting a limited # of entries from a set of sorted streams
type priorityqueue struct {
streams []*logproto.Stream
direction logproto.Direction
}
func (pq *priorityqueue) Len() int { return len(pq.streams) }
func (pq *priorityqueue) Less(i, j int) bool {
if pq.direction == logproto.FORWARD {
return pq.streams[i].Entries[0].Timestamp.UnixNano() < pq.streams[j].Entries[0].Timestamp.UnixNano()
}
return pq.streams[i].Entries[0].Timestamp.UnixNano() > pq.streams[j].Entries[0].Timestamp.UnixNano()
}
func (pq *priorityqueue) Swap(i, j int) {
pq.streams[i], pq.streams[j] = pq.streams[j], pq.streams[i]
}
func (pq *priorityqueue) Push(x interface{}) {
stream := x.(*logproto.Stream)
pq.streams = append(pq.streams, stream)
}
// Pop returns a stream with one entry. It pops the first entry of the first stream
// then re-pushes the remainder of that stream if non-empty back into the queue
func (pq *priorityqueue) Pop() interface{} {
n := pq.Len()
stream := pq.streams[n-1]
pq.streams[n-1] = nil // avoid memory leak
pq.streams = pq.streams[:n-1]
// put the rest of the stream back into the priorityqueue if more entries exist
if len(stream.Entries) > 1 {
remaining := *stream
remaining.Entries = remaining.Entries[1:]
pq.Push(&remaining)
}
stream.Entries = stream.Entries[:1]
return stream
}
| agpl-3.0 |
sameetb-cuelogic/edx-platform-test | common/djangoapps/student/views.py | 86478 | """
Student Views
"""
import datetime
import logging
import uuid
import time
import json
from collections import defaultdict
from pytz import UTC
from ipware.ip import get_ip
from django.conf import settings
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import password_reset_confirm
from django.contrib import messages
from django.core.context_processors import csrf
from django.core import mail
from django.core.urlresolvers import reverse
from django.core.validators import validate_email, ValidationError
from django.db import IntegrityError, transaction
from django.http import (HttpResponse, HttpResponseBadRequest, HttpResponseForbidden,
Http404)
from django.shortcuts import redirect
from django.utils.translation import ungettext
from django_future.csrf import ensure_csrf_cookie
from django.utils.http import cookie_date, base36_to_int
from django.utils.translation import ugettext as _, get_language
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_GET
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.template.response import TemplateResponse
from ratelimitbackend.exceptions import RateLimitException
from requests import HTTPError
from social.apps.django_app import utils as social_utils
from social.backends import oauth as social_oauth
from edxmako.shortcuts import render_to_response, render_to_string
from course_modes.models import CourseMode
from shoppingcart.api import order_history
from student.models import (
Registration, UserProfile, PendingNameChange,
PendingEmailChange, CourseEnrollment, unique_id_for_user,
CourseEnrollmentAllowed, UserStanding, LoginFailures,
create_comments_service_user, PasswordHistory, UserSignupSource,
DashboardConfiguration, LinkedInAddToProfileConfiguration)
from student.forms import AccountCreationForm, PasswordResetFormNoActive
from verify_student.models import SoftwareSecurePhotoVerification, MidcourseReverificationWindow
from certificates.models import CertificateStatuses, certificate_status_for_student
from dark_lang.models import DarkLangConfig
from xmodule.modulestore.django import modulestore
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from opaque_keys.edx.locator import CourseLocator
from xmodule.modulestore import ModuleStoreEnum
from collections import namedtuple
from courseware.courses import get_courses, sort_by_announcement, sort_by_start_date # pylint: disable=import-error
from courseware.access import has_access
from django_comment_common.models import Role
from external_auth.models import ExternalAuthMap
import external_auth.views
from external_auth.login_and_register import (
login as external_auth_login,
register as external_auth_register
)
from bulk_email.models import Optout, CourseAuthorization
import shoppingcart
from lang_pref import LANGUAGE_KEY
import track.views
import dogstats_wrapper as dog_stats_api
from util.db import commit_on_success_with_read_committed
from util.json_request import JsonResponse
from util.bad_request_rate_limiter import BadRequestRateLimiter
from util.milestones_helpers import (
get_pre_requisite_courses_not_completed,
)
from microsite_configuration import microsite
from util.password_policy_validators import (
validate_password_length, validate_password_complexity,
validate_password_dictionary
)
import third_party_auth
from third_party_auth import pipeline, provider
from student.helpers import (
auth_pipeline_urls, set_logged_in_cookie,
check_verify_status_by_course
)
from xmodule.error_module import ErrorDescriptor
from shoppingcart.models import DonationConfiguration, CourseRegistrationCode
from embargo import api as embargo_api
import analytics
from eventtracking import tracker
# Note that this lives in LMS, so this dependency should be refactored.
from notification_prefs.views import enable_notifications
# Note that this lives in openedx, so this dependency should be refactored.
from openedx.core.djangoapps.user_api.preferences import api as preferences_api
log = logging.getLogger("edx.student")
AUDIT_LOG = logging.getLogger("audit")
ReverifyInfo = namedtuple('ReverifyInfo', 'course_id course_name course_number date status display') # pylint: disable=invalid-name
def csrf_token(context):
"""A csrf token that can be included in a form."""
token = context.get('csrf_token', '')
if token == 'NOTPROVIDED':
return ''
return (u'<div style="display:none"><input type="hidden"'
' name="csrfmiddlewaretoken" value="%s" /></div>' % (token))
# NOTE: This view is not linked to directly--it is called from
# branding/views.py:index(), which is cached for anonymous users.
# This means that it should always return the same thing for anon
# users. (in particular, no switching based on query params allowed)
def index(request, extra_context=None, user=AnonymousUser()):
"""
Render the edX main page.
extra_context is used to allow immediate display of certain modal windows, eg signup,
as used by external_auth.
"""
if extra_context is None:
extra_context = {}
# The course selection work is done in courseware.courses.
domain = settings.FEATURES.get('FORCE_UNIVERSITY_DOMAIN') # normally False
# do explicit check, because domain=None is valid
if domain is False:
domain = request.META.get('HTTP_HOST')
courses = get_courses(user, domain=domain)
if microsite.get_value("ENABLE_COURSE_SORTING_BY_START_DATE",
settings.FEATURES["ENABLE_COURSE_SORTING_BY_START_DATE"]):
courses = sort_by_start_date(courses)
else:
courses = sort_by_announcement(courses)
context = {'courses': courses}
context.update(extra_context)
return render_to_response('index.html', context)
def process_survey_link(survey_link, user):
"""
If {UNIQUE_ID} appears in the link, replace it with a unique id for the user.
Currently, this is sha1(user.username). Otherwise, return survey_link.
"""
return survey_link.format(UNIQUE_ID=unique_id_for_user(user))
def cert_info(user, course, course_mode):
"""
Get the certificate info needed to render the dashboard section for the given
student and course. Returns a dictionary with keys:
'status': one of 'generating', 'ready', 'notpassing', 'processing', 'restricted'
'show_download_url': bool
'download_url': url, only present if show_download_url is True
'show_disabled_download_button': bool -- true if state is 'generating'
'show_survey_button': bool
'survey_url': url, only if show_survey_button is True
'grade': if status is not 'processing'
"""
if not course.may_certify():
return {}
return _cert_info(user, course, certificate_status_for_student(user, course.id), course_mode)
def reverification_info(course_enrollment_pairs, user, statuses):
"""
Returns reverification-related information for *all* of user's enrollments whose
reverification status is in status_list
Args:
course_enrollment_pairs (list): list of (course, enrollment) tuples
user (User): the user whose information we want
statuses (list): a list of reverification statuses we want information for
example: ["must_reverify", "denied"]
Returns:
dictionary of lists: dictionary with one key per status, e.g.
dict["must_reverify"] = []
dict["must_reverify"] = [some information]
"""
reverifications = defaultdict(list)
for (course, enrollment) in course_enrollment_pairs:
info = single_course_reverification_info(user, course, enrollment)
if info:
reverifications[info.status].append(info)
# Sort the data by the reverification_end_date
for status in statuses:
if reverifications[status]:
reverifications[status].sort(key=lambda x: x.date)
return reverifications
def single_course_reverification_info(user, course, enrollment): # pylint: disable=invalid-name
"""Returns midcourse reverification-related information for user with enrollment in course.
If a course has an open re-verification window, and that user has a verified enrollment in
the course, we return a tuple with relevant information. Returns None if there is no info..
Args:
user (User): the user we want to get information for
course (Course): the course in which the student is enrolled
enrollment (CourseEnrollment): the object representing the type of enrollment user has in course
Returns:
ReverifyInfo: (course_id, course_name, course_number, date, status)
OR, None: None if there is no re-verification info for this enrollment
"""
window = MidcourseReverificationWindow.get_window(course.id, datetime.datetime.now(UTC))
# If there's no window OR the user is not verified, we don't get reverification info
if (not window) or (enrollment.mode != "verified"):
return None
return ReverifyInfo(
course.id, course.display_name, course.number,
window.end_date.strftime('%B %d, %Y %X %p'),
SoftwareSecurePhotoVerification.user_status(user, window)[0],
SoftwareSecurePhotoVerification.display_status(user, window),
)
def get_course_enrollment_pairs(user, course_org_filter, org_filter_out_set):
"""
Get the relevant set of (Course, CourseEnrollment) pairs to be displayed on
a student's dashboard.
"""
for enrollment in CourseEnrollment.enrollments_for_user(user):
store = modulestore()
with store.bulk_operations(enrollment.course_id):
course = store.get_course(enrollment.course_id)
if course and not isinstance(course, ErrorDescriptor):
# if we are in a Microsite, then filter out anything that is not
# attributed (by ORG) to that Microsite
if course_org_filter and course_org_filter != course.location.org:
continue
# Conversely, if we are not in a Microsite, then let's filter out any enrollments
# with courses attributed (by ORG) to Microsites
elif course.location.org in org_filter_out_set:
continue
yield (course, enrollment)
else:
log.error(
u"User %s enrolled in %s course %s",
user.username,
"broken" if course else "non-existent",
enrollment.course_id
)
def _cert_info(user, course, cert_status, course_mode):
"""
Implements the logic for cert_info -- split out for testing.
"""
# simplify the status for the template using this lookup table
template_state = {
CertificateStatuses.generating: 'generating',
CertificateStatuses.regenerating: 'generating',
CertificateStatuses.downloadable: 'ready',
CertificateStatuses.notpassing: 'notpassing',
CertificateStatuses.restricted: 'restricted',
}
default_status = 'processing'
default_info = {'status': default_status,
'show_disabled_download_button': False,
'show_download_url': False,
'show_survey_button': False,
}
if cert_status is None:
return default_info
is_hidden_status = cert_status['status'] in ('unavailable', 'processing', 'generating', 'notpassing')
if course.certificates_display_behavior == 'early_no_info' and is_hidden_status:
return None
status = template_state.get(cert_status['status'], default_status)
status_dict = {
'status': status,
'show_download_url': status == 'ready',
'show_disabled_download_button': status == 'generating',
'mode': cert_status.get('mode', None),
'linked_in_url': None
}
if (status in ('generating', 'ready', 'notpassing', 'restricted') and
course.end_of_course_survey_url is not None):
status_dict.update({
'show_survey_button': True,
'survey_url': process_survey_link(course.end_of_course_survey_url, user)})
else:
status_dict['show_survey_button'] = False
if status == 'ready':
if 'download_url' not in cert_status:
log.warning(
u"User %s has a downloadable cert for %s, but no download url",
user.username,
course.id
)
return default_info
else:
status_dict['download_url'] = cert_status['download_url']
# If enabled, show the LinkedIn "add to profile" button
# Clicking this button sends the user to LinkedIn where they
# can add the certificate information to their profile.
linkedin_config = LinkedInAddToProfileConfiguration.current()
if linkedin_config.enabled:
status_dict['linked_in_url'] = linkedin_config.add_to_profile_url(
course.id,
course.display_name,
cert_status.get('mode'),
cert_status['download_url']
)
if status in ('generating', 'ready', 'notpassing', 'restricted'):
if 'grade' not in cert_status:
# Note: as of 11/20/2012, we know there are students in this state-- cs169.1x,
# who need to be regraded (we weren't tracking 'notpassing' at first).
# We can add a log.warning here once we think it shouldn't happen.
return default_info
else:
status_dict['grade'] = cert_status['grade']
return status_dict
@ensure_csrf_cookie
def signin_user(request):
"""Deprecated. To be replaced by :class:`student_account.views.login_and_registration_form`."""
external_auth_response = external_auth_login(request)
if external_auth_response is not None:
return external_auth_response
if request.user.is_authenticated():
return redirect(reverse('dashboard'))
course_id = request.GET.get('course_id')
email_opt_in = request.GET.get('email_opt_in')
context = {
'course_id': course_id,
'email_opt_in': email_opt_in,
'enrollment_action': request.GET.get('enrollment_action'),
# Bool injected into JS to submit form if we're inside a running third-
# party auth pipeline; distinct from the actual instance of the running
# pipeline, if any.
'pipeline_running': 'true' if pipeline.running(request) else 'false',
'pipeline_url': auth_pipeline_urls(pipeline.AUTH_ENTRY_LOGIN, course_id=course_id, email_opt_in=email_opt_in),
'platform_name': microsite.get_value(
'platform_name',
settings.PLATFORM_NAME
),
}
return render_to_response('login.html', context)
@ensure_csrf_cookie
def register_user(request, extra_context=None):
"""Deprecated. To be replaced by :class:`student_account.views.login_and_registration_form`."""
if request.user.is_authenticated():
return redirect(reverse('dashboard'))
external_auth_response = external_auth_register(request)
if external_auth_response is not None:
return external_auth_response
course_id = request.GET.get('course_id')
email_opt_in = request.GET.get('email_opt_in')
context = {
'course_id': course_id,
'email_opt_in': email_opt_in,
'email': '',
'enrollment_action': request.GET.get('enrollment_action'),
'name': '',
'running_pipeline': None,
'pipeline_urls': auth_pipeline_urls(pipeline.AUTH_ENTRY_REGISTER, course_id=course_id, email_opt_in=email_opt_in),
'platform_name': microsite.get_value(
'platform_name',
settings.PLATFORM_NAME
),
'selected_provider': '',
'username': '',
}
if extra_context is not None:
context.update(extra_context)
if context.get("extauth_domain", '').startswith(external_auth.views.SHIBBOLETH_DOMAIN_PREFIX):
return render_to_response('register-shib.html', context)
# If third-party auth is enabled, prepopulate the form with data from the
# selected provider.
if third_party_auth.is_enabled() and pipeline.running(request):
running_pipeline = pipeline.get(request)
current_provider = provider.Registry.get_by_backend_name(running_pipeline.get('backend'))
overrides = current_provider.get_register_form_data(running_pipeline.get('kwargs'))
overrides['running_pipeline'] = running_pipeline
overrides['selected_provider'] = current_provider.NAME
context.update(overrides)
return render_to_response('register.html', context)
def complete_course_mode_info(course_id, enrollment, modes=None):
"""
We would like to compute some more information from the given course modes
and the user's current enrollment
Returns the given information:
- whether to show the course upsell information
- numbers of days until they can't upsell anymore
"""
if modes is None:
modes = CourseMode.modes_for_course_dict(course_id)
mode_info = {'show_upsell': False, 'days_for_upsell': None}
# we want to know if the user is already verified and if verified is an
# option
if 'verified' in modes and enrollment.mode != 'verified':
mode_info['show_upsell'] = True
# if there is an expiration date, find out how long from now it is
if modes['verified'].expiration_datetime:
today = datetime.datetime.now(UTC).date()
mode_info['days_for_upsell'] = (modes['verified'].expiration_datetime.date() - today).days
return mode_info
def is_course_blocked(request, redeemed_registration_codes, course_key):
"""Checking either registration is blocked or not ."""
blocked = False
for redeemed_registration in redeemed_registration_codes:
# registration codes may be generated via Bulk Purchase Scenario
# we have to check only for the invoice generated registration codes
# that their invoice is valid or not
if redeemed_registration.invoice_item:
if not getattr(redeemed_registration.invoice_item.invoice, 'is_valid'):
blocked = True
# disabling email notifications for unpaid registration courses
Optout.objects.get_or_create(user=request.user, course_id=course_key)
log.info(
u"User %s (%s) opted out of receiving emails from course %s",
request.user.username,
request.user.email,
course_key
)
track.views.server_track(request, "change-email1-settings", {"receive_emails": "no", "course": course_key.to_deprecated_string()}, page='dashboard')
break
return blocked
@login_required
@ensure_csrf_cookie
def dashboard(request):
user = request.user
# for microsites, we want to filter and only show enrollments for courses within
# the microsites 'ORG'
course_org_filter = microsite.get_value('course_org_filter')
# Let's filter out any courses in an "org" that has been declared to be
# in a Microsite
org_filter_out_set = microsite.get_all_orgs()
# remove our current Microsite from the "filter out" list, if applicable
if course_org_filter:
org_filter_out_set.remove(course_org_filter)
# Build our (course, enrollment) list for the user, but ignore any courses that no
# longer exist (because the course IDs have changed). Still, we don't delete those
# enrollments, because it could have been a data push snafu.
course_enrollment_pairs = list(get_course_enrollment_pairs(user, course_org_filter, org_filter_out_set))
# sort the enrollment pairs by the enrollment date
course_enrollment_pairs.sort(key=lambda x: x[1].created, reverse=True)
# Retrieve the course modes for each course
enrolled_course_ids = [course.id for course, __ in course_enrollment_pairs]
all_course_modes, unexpired_course_modes = CourseMode.all_and_unexpired_modes_for_courses(enrolled_course_ids)
course_modes_by_course = {
course_id: {
mode.slug: mode
for mode in modes
}
for course_id, modes in unexpired_course_modes.iteritems()
}
# Check to see if the student has recently enrolled in a course.
# If so, display a notification message confirming the enrollment.
enrollment_message = _create_recent_enrollment_message(
course_enrollment_pairs, course_modes_by_course
)
course_optouts = Optout.objects.filter(user=user).values_list('course_id', flat=True)
message = ""
if not user.is_active:
message = render_to_string(
'registration/activate_account_notice.html',
{'email': user.email, 'platform_name': settings.PLATFORM_NAME}
)
# Global staff can see what courses errored on their dashboard
staff_access = False
errored_courses = {}
if has_access(user, 'staff', 'global'):
# Show any courses that errored on load
staff_access = True
errored_courses = modulestore().get_errored_courses()
show_courseware_links_for = frozenset(
course.id for course, _enrollment in course_enrollment_pairs
if has_access(request.user, 'load', course)
and has_access(request.user, 'view_courseware_with_prerequisites', course)
)
# Construct a dictionary of course mode information
# used to render the course list. We re-use the course modes dict
# we loaded earlier to avoid hitting the database.
course_mode_info = {
course.id: complete_course_mode_info(
course.id, enrollment,
modes=course_modes_by_course[course.id]
)
for course, enrollment in course_enrollment_pairs
}
# Determine the per-course verification status
# This is a dictionary in which the keys are course locators
# and the values are one of:
#
# VERIFY_STATUS_NEED_TO_VERIFY
# VERIFY_STATUS_SUBMITTED
# VERIFY_STATUS_APPROVED
# VERIFY_STATUS_MISSED_DEADLINE
#
# Each of which correspond to a particular message to display
# next to the course on the dashboard.
#
# If a course is not included in this dictionary,
# there is no verification messaging to display.
verify_status_by_course = check_verify_status_by_course(
user,
course_enrollment_pairs,
all_course_modes
)
cert_statuses = {
course.id: cert_info(request.user, course, _enrollment.mode)
for course, _enrollment in course_enrollment_pairs
}
# only show email settings for Mongo course and when bulk email is turned on
show_email_settings_for = frozenset(
course.id for course, _enrollment in course_enrollment_pairs if (
settings.FEATURES['ENABLE_INSTRUCTOR_EMAIL'] and
modulestore().get_modulestore_type(course.id) != ModuleStoreEnum.Type.xml and
CourseAuthorization.instructor_email_enabled(course.id)
)
)
# Verification Attempts
# Used to generate the "you must reverify for course x" banner
verification_status, verification_msg = SoftwareSecurePhotoVerification.user_status(user)
# Gets data for midcourse reverifications, if any are necessary or have failed
statuses = ["approved", "denied", "pending", "must_reverify"]
reverifications = reverification_info(course_enrollment_pairs, user, statuses)
show_refund_option_for = frozenset(course.id for course, _enrollment in course_enrollment_pairs
if _enrollment.refundable())
block_courses = frozenset(course.id for course, enrollment in course_enrollment_pairs
if is_course_blocked(request, CourseRegistrationCode.objects.filter(course_id=course.id, registrationcoderedemption__redeemed_by=request.user), course.id))
enrolled_courses_either_paid = frozenset(course.id for course, _enrollment in course_enrollment_pairs
if _enrollment.is_paid_course())
# get info w.r.t ExternalAuthMap
external_auth_map = None
try:
external_auth_map = ExternalAuthMap.objects.get(user=user)
except ExternalAuthMap.DoesNotExist:
pass
# If there are *any* denied reverifications that have not been toggled off,
# we'll display the banner
denied_banner = any(item.display for item in reverifications["denied"])
language_options = DarkLangConfig.current().released_languages_list
# add in the default language if it's not in the list of released languages
if settings.LANGUAGE_CODE not in language_options:
language_options.append(settings.LANGUAGE_CODE)
# Re-alphabetize language options
language_options.sort()
# try to get the preferred language for the user
preferred_language_code = preferences_api.get_user_preference(request.user, LANGUAGE_KEY)
# try and get the current language of the user
current_language_code = get_language()
if preferred_language_code and preferred_language_code in settings.LANGUAGE_DICT:
# if the user has a preference, get the name from the code
current_language = settings.LANGUAGE_DICT[preferred_language_code]
elif current_language_code in settings.LANGUAGE_DICT:
# if the user's browser is showing a particular language,
# use that as the current language
current_language = settings.LANGUAGE_DICT[current_language_code]
else:
# otherwise, use the default language
current_language = settings.LANGUAGE_DICT[settings.LANGUAGE_CODE]
# Populate the Order History for the side-bar.
order_history_list = order_history(user, course_org_filter=course_org_filter, org_filter_out_set=org_filter_out_set)
# get list of courses having pre-requisites yet to be completed
courses_having_prerequisites = frozenset(course.id for course, _enrollment in course_enrollment_pairs
if course.pre_requisite_courses)
courses_requirements_not_met = get_pre_requisite_courses_not_completed(user, courses_having_prerequisites)
context = {
'enrollment_message': enrollment_message,
'course_enrollment_pairs': course_enrollment_pairs,
'course_optouts': course_optouts,
'message': message,
'external_auth_map': external_auth_map,
'staff_access': staff_access,
'errored_courses': errored_courses,
'show_courseware_links_for': show_courseware_links_for,
'all_course_modes': course_mode_info,
'cert_statuses': cert_statuses,
'show_email_settings_for': show_email_settings_for,
'reverifications': reverifications,
'verification_status': verification_status,
'verification_status_by_course': verify_status_by_course,
'verification_msg': verification_msg,
'show_refund_option_for': show_refund_option_for,
'block_courses': block_courses,
'denied_banner': denied_banner,
'billing_email': settings.PAYMENT_SUPPORT_EMAIL,
'language_options': language_options,
'current_language': current_language,
'current_language_code': current_language_code,
'user': user,
'duplicate_provider': None,
'logout_url': reverse(logout_user),
'platform_name': settings.PLATFORM_NAME,
'enrolled_courses_either_paid': enrolled_courses_either_paid,
'provider_states': [],
'order_history_list': order_history_list,
'courses_requirements_not_met': courses_requirements_not_met,
}
if third_party_auth.is_enabled():
context['duplicate_provider'] = pipeline.get_duplicate_provider(messages.get_messages(request))
context['provider_user_states'] = pipeline.get_provider_user_states(user)
return render_to_response('dashboard.html', context)
def _create_recent_enrollment_message(course_enrollment_pairs, course_modes):
"""Builds a recent course enrollment message
Constructs a new message template based on any recent course enrollments for the student.
Args:
course_enrollment_pairs (list): A list of tuples containing courses, and the associated enrollment information.
course_modes (dict): Mapping of course ID's to course mode dictionaries.
Returns:
A string representing the HTML message output from the message template.
None if there are no recently enrolled courses.
"""
recently_enrolled_courses = _get_recently_enrolled_courses(course_enrollment_pairs)
if recently_enrolled_courses:
messages = [
{
"course_id": course.id,
"course_name": course.display_name,
"allow_donation": _allow_donation(course_modes, course.id, enrollment)
}
for course, enrollment in recently_enrolled_courses
]
return render_to_string(
'enrollment/course_enrollment_message.html',
{'course_enrollment_messages': messages, 'platform_name': settings.PLATFORM_NAME}
)
def _get_recently_enrolled_courses(course_enrollment_pairs):
"""Checks to see if the student has recently enrolled in courses.
Checks to see if any of the enrollments in the course_enrollment_pairs have been recently created and activated.
Args:
course_enrollment_pairs (list): A list of tuples containing courses, and the associated enrollment information.
Returns:
A list of courses
"""
seconds = DashboardConfiguration.current().recent_enrollment_time_delta
time_delta = (datetime.datetime.now(UTC) - datetime.timedelta(seconds=seconds))
return [
(course, enrollment) for course, enrollment in course_enrollment_pairs
# If the enrollment has no created date, we are explicitly excluding the course
# from the list of recent enrollments.
if enrollment.is_active and enrollment.created > time_delta
]
def _allow_donation(course_modes, course_id, enrollment):
"""Determines if the dashboard will request donations for the given course.
Check if donations are configured for the platform, and if the current course is accepting donations.
Args:
course_modes (dict): Mapping of course ID's to course mode dictionaries.
course_id (str): The unique identifier for the course.
enrollment(CourseEnrollment): The enrollment object in which the user is enrolled
Returns:
True if the course is allowing donations.
"""
donations_enabled = DonationConfiguration.current().enabled
return donations_enabled and enrollment.mode in course_modes[course_id] and course_modes[course_id][enrollment.mode].min_price == 0
def try_change_enrollment(request):
"""
This method calls change_enrollment if the necessary POST
parameters are present, but does not return anything in most cases. It
simply logs the result or exception. This is usually
called after a registration or login, as secondary action.
It should not interrupt a successful registration or login.
"""
if 'enrollment_action' in request.POST:
try:
enrollment_response = change_enrollment(request)
# There isn't really a way to display the results to the user, so we just log it
# We expect the enrollment to be a success, and will show up on the dashboard anyway
log.info(
u"Attempted to automatically enroll after login. Response code: %s; response body: %s",
enrollment_response.status_code,
enrollment_response.content
)
# Hack: since change_enrollment delivers its redirect_url in the content
# of its response, we check here that only the 200 codes with content
# will return redirect_urls.
if enrollment_response.status_code == 200 and enrollment_response.content != '':
return enrollment_response.content
except Exception as exc: # pylint: disable=broad-except
log.exception(u"Exception automatically enrolling after login: %s", exc)
def _update_email_opt_in(request, org):
"""Helper function used to hit the profile API if email opt-in is enabled."""
email_opt_in = request.POST.get('email_opt_in')
if email_opt_in is not None:
email_opt_in_boolean = email_opt_in == 'true'
preferences_api.update_email_opt_in(request.user, org, email_opt_in_boolean)
@require_POST
@commit_on_success_with_read_committed
def change_enrollment(request, check_access=True):
"""
Modify the enrollment status for the logged-in user.
The request parameter must be a POST request (other methods return 405)
that specifies course_id and enrollment_action parameters. If course_id or
enrollment_action is not specified, if course_id is not valid, if
enrollment_action is something other than "enroll" or "unenroll", if
enrollment_action is "enroll" and enrollment is closed for the course, or
if enrollment_action is "unenroll" and the user is not enrolled in the
course, a 400 error will be returned. If the user is not logged in, 403
will be returned; it is important that only this case return 403 so the
front end can redirect the user to a registration or login page when this
happens. This function should only be called from an AJAX request or
as a post-login/registration helper, so the error messages in the responses
should never actually be user-visible.
Args:
request (`Request`): The Django request object
Keyword Args:
check_access (boolean): If True, we check that an accessible course actually
exists for the given course_key before we enroll the student.
The default is set to False to avoid breaking legacy code or
code with non-standard flows (ex. beta tester invitations), but
for any standard enrollment flow you probably want this to be True.
Returns:
Response
"""
# Get the user
user = request.user
# Ensure the user is authenticated
if not user.is_authenticated():
return HttpResponseForbidden()
# Ensure we received a course_id
action = request.POST.get("enrollment_action")
if 'course_id' not in request.POST:
return HttpResponseBadRequest(_("Course id not specified"))
try:
course_id = SlashSeparatedCourseKey.from_deprecated_string(request.POST.get("course_id"))
except InvalidKeyError:
log.warning(
u"User %s tried to %s with invalid course id: %s",
user.username,
action,
request.POST.get("course_id"),
)
return HttpResponseBadRequest(_("Invalid course id"))
if action == "enroll":
# Make sure the course exists
# We don't do this check on unenroll, or a bad course id can't be unenrolled from
if not modulestore().has_course(course_id):
log.warning(
u"User %s tried to enroll in non-existent course %s",
user.username,
course_id
)
return HttpResponseBadRequest(_("Course id is invalid"))
# Record the user's email opt-in preference
if settings.FEATURES.get('ENABLE_MKTG_EMAIL_OPT_IN'):
_update_email_opt_in(request, course_id.org)
available_modes = CourseMode.modes_for_course_dict(course_id)
# Check whether the user is blocked from enrolling in this course
# This can occur if the user's IP is on a global blacklist
# or if the user is enrolling in a country in which the course
# is not available.
redirect_url = embargo_api.redirect_if_blocked(
course_id, user=user, ip_address=get_ip(request),
url=request.path
)
if redirect_url:
return HttpResponse(redirect_url)
# Check that auto enrollment is allowed for this course
# (= the course is NOT behind a paywall)
if CourseMode.can_auto_enroll(course_id):
# Enroll the user using the default mode (honor)
# We're assuming that users of the course enrollment table
# will NOT try to look up the course enrollment model
# by its slug. If they do, it's possible (based on the state of the database)
# for no such model to exist, even though we've set the enrollment type
# to "honor".
try:
CourseEnrollment.enroll(user, course_id, check_access=check_access)
except Exception:
return HttpResponseBadRequest(_("Could not enroll"))
# If we have more than one course mode or professional ed is enabled,
# then send the user to the choose your track page.
# (In the case of no-id-professional/professional ed, this will redirect to a page that
# funnels users directly into the verification / payment flow)
if CourseMode.has_verified_mode(available_modes) or CourseMode.has_professional_mode(available_modes):
return HttpResponse(
reverse("course_modes_choose", kwargs={'course_id': unicode(course_id)})
)
# Otherwise, there is only one mode available (the default)
return HttpResponse()
elif action == "add_to_cart":
# Pass the request handling to shoppingcart.views
# The view in shoppingcart.views performs error handling and logs different errors. But this elif clause
# is only used in the "auto-add after user reg/login" case, i.e. it's always wrapped in try_change_enrollment.
# This means there's no good way to display error messages to the user. So we log the errors and send
# the user to the shopping cart page always, where they can reasonably discern the status of their cart,
# whether things got added, etc
shoppingcart.views.add_course_to_cart(request, course_id.to_deprecated_string())
return HttpResponse(
reverse("shoppingcart.views.show_cart")
)
elif action == "unenroll":
if not CourseEnrollment.is_enrolled(user, course_id):
return HttpResponseBadRequest(_("You are not enrolled in this course"))
CourseEnrollment.unenroll(user, course_id)
return HttpResponse()
else:
return HttpResponseBadRequest(_("Enrollment action is invalid"))
@never_cache
@ensure_csrf_cookie
def accounts_login(request):
"""Deprecated. To be replaced by :class:`student_account.views.login_and_registration_form`."""
external_auth_response = external_auth_login(request)
if external_auth_response is not None:
return external_auth_response
redirect_to = request.GET.get('next')
context = {
'pipeline_running': 'false',
'pipeline_url': auth_pipeline_urls(pipeline.AUTH_ENTRY_LOGIN, redirect_url=redirect_to),
'platform_name': settings.PLATFORM_NAME,
}
return render_to_response('login.html', context)
# Need different levels of logging
@ensure_csrf_cookie
def login_user(request, error=""): # pylint: disable-msg=too-many-statements,unused-argument
"""AJAX request to log in the user."""
backend_name = None
email = None
password = None
redirect_url = None
response = None
running_pipeline = None
third_party_auth_requested = third_party_auth.is_enabled() and pipeline.running(request)
third_party_auth_successful = False
trumped_by_first_party_auth = bool(request.POST.get('email')) or bool(request.POST.get('password'))
user = None
if third_party_auth_requested and not trumped_by_first_party_auth:
# The user has already authenticated via third-party auth and has not
# asked to do first party auth by supplying a username or password. We
# now want to put them through the same logging and cookie calculation
# logic as with first-party auth.
running_pipeline = pipeline.get(request)
username = running_pipeline['kwargs'].get('username')
backend_name = running_pipeline['backend']
requested_provider = provider.Registry.get_by_backend_name(backend_name)
try:
user = pipeline.get_authenticated_user(username, backend_name)
third_party_auth_successful = True
except User.DoesNotExist:
AUDIT_LOG.warning(
u'Login failed - user with username {username} has no social auth with backend_name {backend_name}'.format(
username=username, backend_name=backend_name))
return HttpResponse(
_("You've successfully logged into your {provider_name} account, but this account isn't linked with an {platform_name} account yet.").format(
platform_name=settings.PLATFORM_NAME, provider_name=requested_provider.NAME
)
+ "<br/><br/>" +
_("Use your {platform_name} username and password to log into {platform_name} below, "
"and then link your {platform_name} account with {provider_name} from your dashboard.").format(
platform_name=settings.PLATFORM_NAME, provider_name=requested_provider.NAME
)
+ "<br/><br/>" +
_("If you don't have an {platform_name} account yet, click <strong>Register Now</strong> at the top of the page.").format(
platform_name=settings.PLATFORM_NAME
),
content_type="text/plain",
status=403
)
else:
if 'email' not in request.POST or 'password' not in request.POST:
return JsonResponse({
"success": False,
"value": _('There was an error receiving your login information. Please email us.'), # TODO: User error message
}) # TODO: this should be status code 400 # pylint: disable=fixme
email = request.POST['email']
password = request.POST['password']
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
AUDIT_LOG.warning(u"Login failed - Unknown user email")
else:
AUDIT_LOG.warning(u"Login failed - Unknown user email: {0}".format(email))
# check if the user has a linked shibboleth account, if so, redirect the user to shib-login
# This behavior is pretty much like what gmail does for shibboleth. Try entering some @stanford.edu
# address into the Gmail login.
if settings.FEATURES.get('AUTH_USE_SHIB') and user:
try:
eamap = ExternalAuthMap.objects.get(user=user)
if eamap.external_domain.startswith(external_auth.views.SHIBBOLETH_DOMAIN_PREFIX):
return JsonResponse({
"success": False,
"redirect": reverse('shib-login'),
}) # TODO: this should be status code 301 # pylint: disable=fixme
except ExternalAuthMap.DoesNotExist:
# This is actually the common case, logging in user without external linked login
AUDIT_LOG.info(u"User %s w/o external auth attempting login", user)
# see if account has been locked out due to excessive login failures
user_found_by_email_lookup = user
if user_found_by_email_lookup and LoginFailures.is_feature_enabled():
if LoginFailures.is_user_locked_out(user_found_by_email_lookup):
return JsonResponse({
"success": False,
"value": _('This account has been temporarily locked due to excessive login failures. Try again later.'),
}) # TODO: this should be status code 429 # pylint: disable=fixme
# see if the user must reset his/her password due to any policy settings
if user_found_by_email_lookup and PasswordHistory.should_user_reset_password_now(user_found_by_email_lookup):
return JsonResponse({
"success": False,
"value": _('Your password has expired due to password policy on this account. You must '
'reset your password before you can log in again. Please click the '
'"Forgot Password" link on this page to reset your password before logging in again.'),
}) # TODO: this should be status code 403 # pylint: disable=fixme
# if the user doesn't exist, we want to set the username to an invalid
# username so that authentication is guaranteed to fail and we can take
# advantage of the ratelimited backend
username = user.username if user else ""
if not third_party_auth_successful:
try:
user = authenticate(username=username, password=password, request=request)
# this occurs when there are too many attempts from the same IP address
except RateLimitException:
return JsonResponse({
"success": False,
"value": _('Too many failed login attempts. Try again later.'),
}) # TODO: this should be status code 429 # pylint: disable=fixme
if user is None:
# tick the failed login counters if the user exists in the database
if user_found_by_email_lookup and LoginFailures.is_feature_enabled():
LoginFailures.increment_lockout_counter(user_found_by_email_lookup)
# if we didn't find this username earlier, the account for this email
# doesn't exist, and doesn't have a corresponding password
if username != "":
if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
loggable_id = user_found_by_email_lookup.id if user_found_by_email_lookup else "<unknown>"
AUDIT_LOG.warning(u"Login failed - password for user.id: {0} is invalid".format(loggable_id))
else:
AUDIT_LOG.warning(u"Login failed - password for {0} is invalid".format(email))
return JsonResponse({
"success": False,
"value": _('Email or password is incorrect.'),
}) # TODO: this should be status code 400 # pylint: disable=fixme
# successful login, clear failed login attempts counters, if applicable
if LoginFailures.is_feature_enabled():
LoginFailures.clear_lockout_counter(user)
# Track the user's sign in
if settings.FEATURES.get('SEGMENT_IO_LMS') and hasattr(settings, 'SEGMENT_IO_LMS_KEY'):
tracking_context = tracker.get_tracker().resolve_context()
analytics.identify(user.id, {
'email': email,
'username': username,
})
analytics.track(
user.id,
"edx.bi.user.account.authenticated",
{
'category': "conversion",
'label': request.POST.get('course_id'),
'provider': None
},
context={
'Google Analytics': {
'clientId': tracking_context.get('client_id')
}
}
)
if user is not None and user.is_active:
try:
# We do not log here, because we have a handler registered
# to perform logging on successful logins.
login(request, user)
if request.POST.get('remember') == 'true':
request.session.set_expiry(604800)
log.debug("Setting user session to never expire")
else:
request.session.set_expiry(0)
except Exception as exc: # pylint: disable=broad-except
AUDIT_LOG.critical("Login failed - Could not create session. Is memcached running?")
log.critical("Login failed - Could not create session. Is memcached running?")
log.exception(exc)
raise
redirect_url = try_change_enrollment(request)
if third_party_auth_successful:
redirect_url = pipeline.get_complete_url(backend_name)
response = JsonResponse({
"success": True,
"redirect_url": redirect_url,
})
# Ensure that the external marketing site can
# detect that the user is logged in.
return set_logged_in_cookie(request, response)
if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
AUDIT_LOG.warning(u"Login failed - Account not active for user.id: {0}, resending activation".format(user.id))
else:
AUDIT_LOG.warning(u"Login failed - Account not active for user {0}, resending activation".format(username))
reactivation_email_for_user(user)
not_activated_msg = _("This account has not been activated. We have sent another activation message. Please check your email for the activation instructions.")
return JsonResponse({
"success": False,
"value": not_activated_msg,
}) # TODO: this should be status code 400 # pylint: disable=fixme
@csrf_exempt
@require_POST
@social_utils.strategy("social:complete")
def login_oauth_token(request, backend):
"""
Authenticate the client using an OAuth access token by using the token to
retrieve information from a third party and matching that information to an
existing user.
"""
backend = request.social_strategy.backend
if isinstance(backend, social_oauth.BaseOAuth1) or isinstance(backend, social_oauth.BaseOAuth2):
if "access_token" in request.POST:
# Tell third party auth pipeline that this is an API call
request.session[pipeline.AUTH_ENTRY_KEY] = pipeline.AUTH_ENTRY_API
user = None
try:
user = backend.do_auth(request.POST["access_token"])
except HTTPError:
pass
# do_auth can return a non-User object if it fails
if user and isinstance(user, User):
login(request, user)
return JsonResponse(status=204)
else:
# Ensure user does not re-enter the pipeline
request.social_strategy.clean_partial_pipeline()
return JsonResponse({"error": "invalid_token"}, status=401)
else:
return JsonResponse({"error": "invalid_request"}, status=400)
raise Http404
@ensure_csrf_cookie
def logout_user(request):
"""
HTTP request to log out the user. Redirects to marketing page.
Deletes both the CSRF and sessionid cookies so the marketing
site can determine the logged in state of the user
"""
# We do not log here, because we have a handler registered
# to perform logging on successful logouts.
logout(request)
if settings.FEATURES.get('AUTH_USE_CAS'):
target = reverse('cas-logout')
else:
target = '/'
response = redirect(target)
response.delete_cookie(
settings.EDXMKTG_COOKIE_NAME,
path='/', domain=settings.SESSION_COOKIE_DOMAIN,
)
return response
@require_GET
@login_required
@ensure_csrf_cookie
def manage_user_standing(request):
"""
Renders the view used to manage user standing. Also displays a table
of user accounts that have been disabled and who disabled them.
"""
if not request.user.is_staff:
raise Http404
all_disabled_accounts = UserStanding.objects.filter(
account_status=UserStanding.ACCOUNT_DISABLED
)
all_disabled_users = [standing.user for standing in all_disabled_accounts]
headers = ['username', 'account_changed_by']
rows = []
for user in all_disabled_users:
row = [user.username, user.standing.all()[0].changed_by]
rows.append(row)
context = {'headers': headers, 'rows': rows}
return render_to_response("manage_user_standing.html", context)
@require_POST
@login_required
@ensure_csrf_cookie
def disable_account_ajax(request):
"""
Ajax call to change user standing. Endpoint of the form
in manage_user_standing.html
"""
if not request.user.is_staff:
raise Http404
username = request.POST.get('username')
context = {}
if username is None or username.strip() == '':
context['message'] = _('Please enter a username')
return JsonResponse(context, status=400)
account_action = request.POST.get('account_action')
if account_action is None:
context['message'] = _('Please choose an option')
return JsonResponse(context, status=400)
username = username.strip()
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
context['message'] = _("User with username {} does not exist").format(username)
return JsonResponse(context, status=400)
else:
user_account, _success = UserStanding.objects.get_or_create(
user=user, defaults={'changed_by': request.user},
)
if account_action == 'disable':
user_account.account_status = UserStanding.ACCOUNT_DISABLED
context['message'] = _("Successfully disabled {}'s account").format(username)
log.info(u"%s disabled %s's account", request.user, username)
elif account_action == 'reenable':
user_account.account_status = UserStanding.ACCOUNT_ENABLED
context['message'] = _("Successfully reenabled {}'s account").format(username)
log.info(u"%s reenabled %s's account", request.user, username)
else:
context['message'] = _("Unexpected account status")
return JsonResponse(context, status=400)
user_account.changed_by = request.user
user_account.standing_last_changed_at = datetime.datetime.now(UTC)
user_account.save()
return JsonResponse(context)
@login_required
@ensure_csrf_cookie
def change_setting(request):
"""JSON call to change a profile setting: Right now, location"""
# TODO (vshnayder): location is no longer used
u_prof = UserProfile.objects.get(user=request.user) # request.user.profile_cache
if 'location' in request.POST:
u_prof.location = request.POST['location']
u_prof.save()
return JsonResponse({
"success": True,
"location": u_prof.location,
})
class AccountValidationError(Exception):
def __init__(self, message, field):
super(AccountValidationError, self).__init__(message)
self.field = field
@receiver(post_save, sender=User)
def user_signup_handler(sender, **kwargs): # pylint: disable=unused-argument
"""
handler that saves the user Signup Source
when the user is created
"""
if 'created' in kwargs and kwargs['created']:
site = microsite.get_value('SITE_NAME')
if site:
user_signup_source = UserSignupSource(user=kwargs['instance'], site=site)
user_signup_source.save()
log.info(u'user {} originated from a white labeled "Microsite"'.format(kwargs['instance'].id))
def _do_create_account(form):
"""
Given cleaned post variables, create the User and UserProfile objects, as well as the
registration for this user.
Returns a tuple (User, UserProfile, Registration).
Note: this function is also used for creating test users.
"""
if not form.is_valid():
raise ValidationError(form.errors)
user = User(
username=form.cleaned_data["username"],
email=form.cleaned_data["email"],
is_active=False
)
user.set_password(form.cleaned_data["password"])
registration = Registration()
# TODO: Rearrange so that if part of the process fails, the whole process fails.
# Right now, we can have e.g. no registration e-mail sent out and a zombie account
try:
user.save()
except IntegrityError:
# Figure out the cause of the integrity error
if len(User.objects.filter(username=user.username)) > 0:
raise AccountValidationError(
_("An account with the Public Username '{username}' already exists.").format(username=user.username),
field="username"
)
elif len(User.objects.filter(email=user.email)) > 0:
raise AccountValidationError(
_("An account with the Email '{email}' already exists.").format(email=user.email),
field="email"
)
else:
raise
# add this account creation to password history
# NOTE, this will be a NOP unless the feature has been turned on in configuration
password_history_entry = PasswordHistory()
password_history_entry.create(user)
registration.register(user)
profile_fields = [
"name", "level_of_education", "gender", "mailing_address", "city", "country", "goals",
"year_of_birth"
]
profile = UserProfile(
user=user,
**{key: form.cleaned_data.get(key) for key in profile_fields}
)
extended_profile = form.cleaned_extended_profile
if extended_profile:
profile.meta = json.dumps(extended_profile)
try:
profile.save()
except Exception: # pylint: disable=broad-except
log.exception("UserProfile creation failed for user {id}.".format(id=user.id))
raise
preferences_api.set_user_preference(user, LANGUAGE_KEY, get_language())
return (user, profile, registration)
def create_account_with_params(request, params):
"""
Given a request and a dict of parameters (which may or may not have come
from the request), create an account for the requesting user, including
creating a comments service user object and sending an activation email.
This also takes external/third-party auth into account, updates that as
necessary, and authenticates the user for the request's session.
Does not return anything.
Raises AccountValidationError if an account with the username or email
specified by params already exists, or ValidationError if any of the given
parameters is invalid for any other reason.
"""
# Copy params so we can modify it; we can't just do dict(params) because if
# params is request.POST, that results in a dict containing lists of values
params = dict(params.items())
# allow for microsites to define their own set of required/optional/hidden fields
extra_fields = microsite.get_value(
'REGISTRATION_EXTRA_FIELDS',
getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {})
)
if third_party_auth.is_enabled() and pipeline.running(request):
params["password"] = pipeline.make_random_password()
# if doing signup for an external authorization, then get email, password, name from the eamap
# don't use the ones from the form, since the user could have hacked those
# unless originally we didn't get a valid email or name from the external auth
# TODO: We do not check whether these values meet all necessary criteria, such as email length
do_external_auth = 'ExternalAuthMap' in request.session
if do_external_auth:
eamap = request.session['ExternalAuthMap']
try:
validate_email(eamap.external_email)
params["email"] = eamap.external_email
except ValidationError:
pass
if eamap.external_name.strip() != '':
params["name"] = eamap.external_name
params["password"] = eamap.internal_password
log.debug(u'In create_account with external_auth: user = %s, email=%s', params["name"], params["email"])
extended_profile_fields = microsite.get_value('extended_profile_fields', [])
enforce_password_policy = (
settings.FEATURES.get("ENFORCE_PASSWORD_POLICY", False) and
not do_external_auth
)
# Can't have terms of service for certain SHIB users, like at Stanford
tos_required = (
not settings.FEATURES.get("AUTH_USE_SHIB") or
not settings.FEATURES.get("SHIB_DISABLE_TOS") or
not do_external_auth or
not eamap.external_domain.startswith(
external_auth.views.SHIBBOLETH_DOMAIN_PREFIX
)
)
form = AccountCreationForm(
data=params,
extra_fields=extra_fields,
extended_profile_fields=extended_profile_fields,
enforce_username_neq_password=True,
enforce_password_policy=enforce_password_policy,
tos_required=tos_required
)
with transaction.commit_on_success():
ret = _do_create_account(form)
(user, profile, registration) = ret
if settings.FEATURES.get('ENABLE_DISCUSSION_EMAIL_DIGEST'):
try:
enable_notifications(user)
except Exception:
log.exception("Enable discussion notifications failed for user {id}.".format(id=user.id))
dog_stats_api.increment("common.student.account_created")
# Track the user's registration
if settings.FEATURES.get('SEGMENT_IO_LMS') and hasattr(settings, 'SEGMENT_IO_LMS_KEY'):
tracking_context = tracker.get_tracker().resolve_context()
analytics.identify(user.id, {
'email': user.email,
'username': user.username,
})
# If the user is registering via 3rd party auth, track which provider they use
provider_name = None
if third_party_auth.is_enabled() and pipeline.running(request):
running_pipeline = pipeline.get(request)
current_provider = provider.Registry.get_by_backend_name(running_pipeline.get('backend'))
provider_name = current_provider.NAME
analytics.track(
user.id,
"edx.bi.user.account.registered",
{
'category': 'conversion',
'label': params.get('course_id'),
'provider': provider_name
},
context={
'Google Analytics': {
'clientId': tracking_context.get('client_id')
}
}
)
create_comments_service_user(user)
context = {
'name': profile.name,
'key': registration.activation_key,
}
# composes activation email
subject = render_to_string('emails/activation_email_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
message = render_to_string('emails/activation_email.txt', context)
# don't send email if we are doing load testing or random user generation for some reason
# or external auth with bypass activated
send_email = (
not settings.FEATURES.get('AUTOMATIC_AUTH_FOR_TESTING') and
not (do_external_auth and settings.FEATURES.get('BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH'))
)
if send_email:
from_address = microsite.get_value(
'email_from_address',
settings.DEFAULT_FROM_EMAIL
)
try:
if settings.FEATURES.get('REROUTE_ACTIVATION_EMAIL'):
dest_addr = settings.FEATURES['REROUTE_ACTIVATION_EMAIL']
message = ("Activation for %s (%s): %s\n" % (user, user.email, profile.name) +
'-' * 80 + '\n\n' + message)
mail.send_mail(subject, message, from_address, [dest_addr], fail_silently=False)
else:
user.email_user(subject, message, from_address)
except Exception: # pylint: disable=broad-except
log.error(u'Unable to send activation email to user from "%s"', from_address, exc_info=True)
# Immediately after a user creates an account, we log them in. They are only
# logged in until they close the browser. They can't log in again until they click
# the activation link from the email.
new_user = authenticate(username=user.username, password=params['password'])
login(request, new_user)
request.session.set_expiry(0)
# TODO: there is no error checking here to see that the user actually logged in successfully,
# and is not yet an active user.
if new_user is not None:
AUDIT_LOG.info(u"Login success on new account creation - {0}".format(new_user.username))
if do_external_auth:
eamap.user = new_user
eamap.dtsignup = datetime.datetime.now(UTC)
eamap.save()
AUDIT_LOG.info(u"User registered with external_auth %s", new_user.username)
AUDIT_LOG.info(u'Updated ExternalAuthMap for %s to be %s', new_user.username, eamap)
if settings.FEATURES.get('BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH'):
log.info('bypassing activation email')
new_user.is_active = True
new_user.save()
AUDIT_LOG.info(u"Login activated on extauth account - {0} ({1})".format(new_user.username, new_user.email))
def set_marketing_cookie(request, response):
"""
Set the login cookie for the edx marketing site on the given response. Its
expiration will match that of the given request's session.
"""
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = cookie_date(expires_time)
# we want this cookie to be accessed via javascript
# so httponly is set to None
response.set_cookie(
settings.EDXMKTG_COOKIE_NAME,
'true',
max_age=max_age,
expires=expires,
domain=settings.SESSION_COOKIE_DOMAIN,
path='/',
secure=None,
httponly=None
)
@csrf_exempt
def create_account(request, post_override=None):
"""
JSON call to create new edX account.
Used by form in signup_modal.html, which is included into navigation.html
"""
try:
create_account_with_params(request, post_override or request.POST)
except AccountValidationError as exc:
return JsonResponse({'success': False, 'value': exc.message, 'field': exc.field}, status=400)
except ValidationError as exc:
field, error_list = next(exc.message_dict.iteritems())
return JsonResponse(
{
"success": False,
"field": field,
"value": error_list[0],
},
status=400
)
redirect_url = try_change_enrollment(request)
# Resume the third-party-auth pipeline if necessary.
if third_party_auth.is_enabled() and pipeline.running(request):
running_pipeline = pipeline.get(request)
redirect_url = pipeline.get_complete_url(running_pipeline['backend'])
response = JsonResponse({
'success': True,
'redirect_url': redirect_url,
})
set_marketing_cookie(request, response)
return response
def auto_auth(request):
"""
Create or configure a user account, then log in as that user.
Enabled only when
settings.FEATURES['AUTOMATIC_AUTH_FOR_TESTING'] is true.
Accepts the following querystring parameters:
* `username`, `email`, and `password` for the user account
* `full_name` for the user profile (the user's full name; defaults to the username)
* `staff`: Set to "true" to make the user global staff.
* `course_id`: Enroll the student in the course with `course_id`
* `roles`: Comma-separated list of roles to grant the student in the course with `course_id`
* `no_login`: Define this to create the user but not login
If username, email, or password are not provided, use
randomly generated credentials.
"""
# Generate a unique name to use if none provided
unique_name = uuid.uuid4().hex[0:30]
# Use the params from the request, otherwise use these defaults
username = request.GET.get('username', unique_name)
password = request.GET.get('password', unique_name)
email = request.GET.get('email', unique_name + "@example.com")
full_name = request.GET.get('full_name', username)
is_staff = request.GET.get('staff', None)
course_id = request.GET.get('course_id', None)
course_key = None
if course_id:
course_key = CourseLocator.from_string(course_id)
role_names = [v.strip() for v in request.GET.get('roles', '').split(',') if v.strip()]
login_when_done = 'no_login' not in request.GET
form = AccountCreationForm(
data={
'username': username,
'email': email,
'password': password,
'name': full_name,
},
tos_required=False
)
# Attempt to create the account.
# If successful, this will return a tuple containing
# the new user object.
try:
user, _profile, reg = _do_create_account(form)
except AccountValidationError:
# Attempt to retrieve the existing user.
user = User.objects.get(username=username)
user.email = email
user.set_password(password)
user.save()
reg = Registration.objects.get(user=user)
# Set the user's global staff bit
if is_staff is not None:
user.is_staff = (is_staff == "true")
user.save()
# Activate the user
reg.activate()
reg.save()
# Enroll the user in a course
if course_key is not None:
CourseEnrollment.enroll(user, course_key)
# Apply the roles
for role_name in role_names:
role = Role.objects.get(name=role_name, course_id=course_key)
user.roles.add(role)
# Log in as the user
if login_when_done:
user = authenticate(username=username, password=password)
login(request, user)
create_comments_service_user(user)
# Provide the user with a valid CSRF token
# then return a 200 response
success_msg = u"{} user {} ({}) with password {} and user_id {}".format(
u"Logged in" if login_when_done else "Created",
username, email, password, user.id
)
response = HttpResponse(success_msg)
response.set_cookie('csrftoken', csrf(request)['csrf_token'])
return response
@ensure_csrf_cookie
def activate_account(request, key):
"""When link in activation e-mail is clicked"""
regs = Registration.objects.filter(activation_key=key)
if len(regs) == 1:
user_logged_in = request.user.is_authenticated()
already_active = True
if not regs[0].user.is_active:
regs[0].activate()
already_active = False
# Enroll student in any pending courses he/she may have if auto_enroll flag is set
student = User.objects.filter(id=regs[0].user_id)
if student:
ceas = CourseEnrollmentAllowed.objects.filter(email=student[0].email)
for cea in ceas:
if cea.auto_enroll:
CourseEnrollment.enroll(student[0], cea.course_id)
resp = render_to_response(
"registration/activation_complete.html",
{
'user_logged_in': user_logged_in,
'already_active': already_active
}
)
return resp
if len(regs) == 0:
return render_to_response(
"registration/activation_invalid.html",
{'csrf': csrf(request)['csrf_token']}
)
return HttpResponse(_("Unknown error. Please e-mail us to let us know how it happened."))
@csrf_exempt
@require_POST
def password_reset(request):
""" Attempts to send a password reset e-mail. """
# Add some rate limiting here by re-using the RateLimitMixin as a helper class
limiter = BadRequestRateLimiter()
if limiter.is_rate_limit_exceeded(request):
AUDIT_LOG.warning("Rate limit exceeded in password_reset")
return HttpResponseForbidden()
form = PasswordResetFormNoActive(request.POST)
if form.is_valid():
form.save(use_https=request.is_secure(),
from_email=settings.DEFAULT_FROM_EMAIL,
request=request,
domain_override=request.get_host())
else:
# bad user? tick the rate limiter counter
AUDIT_LOG.info("Bad password_reset user passed in.")
limiter.tick_bad_request_counter(request)
return JsonResponse({
'success': True,
'value': render_to_string('registration/password_reset_done.html', {}),
})
def password_reset_confirm_wrapper(
request,
uidb36=None,
token=None,
):
""" A wrapper around django.contrib.auth.views.password_reset_confirm.
Needed because we want to set the user as active at this step.
"""
# cribbed from django.contrib.auth.views.password_reset_confirm
try:
uid_int = base36_to_int(uidb36)
user = User.objects.get(id=uid_int)
user.is_active = True
user.save()
except (ValueError, User.DoesNotExist):
pass
# tie in password strength enforcement as an optional level of
# security protection
err_msg = None
if request.method == 'POST':
password = request.POST['new_password1']
if settings.FEATURES.get('ENFORCE_PASSWORD_POLICY', False):
try:
validate_password_length(password)
validate_password_complexity(password)
validate_password_dictionary(password)
except ValidationError, err:
err_msg = _('Password: ') + '; '.join(err.messages)
# also, check the password reuse policy
if not PasswordHistory.is_allowable_password_reuse(user, password):
if user.is_staff:
num_distinct = settings.ADVANCED_SECURITY_CONFIG['MIN_DIFFERENT_STAFF_PASSWORDS_BEFORE_REUSE']
else:
num_distinct = settings.ADVANCED_SECURITY_CONFIG['MIN_DIFFERENT_STUDENT_PASSWORDS_BEFORE_REUSE']
err_msg = ungettext(
"You are re-using a password that you have used recently. You must have {num} distinct password before reusing a previous password.",
"You are re-using a password that you have used recently. You must have {num} distinct passwords before reusing a previous password.",
num_distinct
).format(num=num_distinct)
# also, check to see if passwords are getting reset too frequent
if PasswordHistory.is_password_reset_too_soon(user):
num_days = settings.ADVANCED_SECURITY_CONFIG['MIN_TIME_IN_DAYS_BETWEEN_ALLOWED_RESETS']
err_msg = ungettext(
"You are resetting passwords too frequently. Due to security policies, {num} day must elapse between password resets.",
"You are resetting passwords too frequently. Due to security policies, {num} days must elapse between password resets.",
num_days
).format(num=num_days)
if err_msg:
# We have an password reset attempt which violates some security policy, use the
# existing Django template to communicate this back to the user
context = {
'validlink': True,
'form': None,
'title': _('Password reset unsuccessful'),
'err_msg': err_msg,
}
return TemplateResponse(request, 'registration/password_reset_confirm.html', context)
else:
# we also want to pass settings.PLATFORM_NAME in as extra_context
extra_context = {"platform_name": settings.PLATFORM_NAME}
if request.method == 'POST':
# remember what the old password hash is before we call down
old_password_hash = user.password
result = password_reset_confirm(
request, uidb36=uidb36, token=token, extra_context=extra_context
)
# get the updated user
updated_user = User.objects.get(id=uid_int)
# did the password hash change, if so record it in the PasswordHistory
if updated_user.password != old_password_hash:
entry = PasswordHistory()
entry.create(updated_user)
return result
else:
return password_reset_confirm(
request, uidb36=uidb36, token=token, extra_context=extra_context
)
def reactivation_email_for_user(user):
try:
reg = Registration.objects.get(user=user)
except Registration.DoesNotExist:
return JsonResponse({
"success": False,
"error": _('No inactive user with this e-mail exists'),
}) # TODO: this should be status code 400 # pylint: disable=fixme
context = {
'name': user.profile.name,
'key': reg.activation_key,
}
subject = render_to_string('emails/activation_email_subject.txt', context)
subject = ''.join(subject.splitlines())
message = render_to_string('emails/activation_email.txt', context)
try:
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
except Exception: # pylint: disable=broad-except
log.error(u'Unable to send reactivation email from "%s"', settings.DEFAULT_FROM_EMAIL, exc_info=True)
return JsonResponse({
"success": False,
"error": _('Unable to send reactivation email')
}) # TODO: this should be status code 500 # pylint: disable=fixme
return JsonResponse({"success": True})
# TODO: delete this method and redirect unit tests to validate_new_email and do_email_change_request
# after accounts page work is done.
@ensure_csrf_cookie
def change_email_request(request):
""" AJAX call from the profile page. User wants a new e-mail.
"""
## Make sure it checks for existing e-mail conflicts
if not request.user.is_authenticated():
raise Http404
user = request.user
if not user.check_password(request.POST['password']):
return JsonResponse({
"success": False,
"error": _('Invalid password'),
}) # TODO: this should be status code 400 # pylint: disable=fixme
new_email = request.POST['new_email']
try:
validate_new_email(request.user, new_email)
do_email_change_request(request.user, new_email)
except ValueError as err:
return JsonResponse({
"success": False,
"error": err.message,
})
return JsonResponse({"success": True})
def validate_new_email(user, new_email):
"""
Given a new email for a user, does some basic verification of the new address If any issues are encountered
with verification a ValueError will be thrown.
"""
try:
validate_email(new_email)
except ValidationError:
raise ValueError(_('Valid e-mail address required.'))
if new_email == user.email:
raise ValueError(_('Old email is the same as the new email.'))
if User.objects.filter(email=new_email).count() != 0:
raise ValueError(_('An account with this e-mail already exists.'))
def do_email_change_request(user, new_email, activation_key=uuid.uuid4().hex):
"""
Given a new email for a user, does some basic verification of the new address and sends an activation message
to the new address. If any issues are encountered with verification or sending the message, a ValueError will
be thrown.
"""
pec_list = PendingEmailChange.objects.filter(user=user)
if len(pec_list) == 0:
pec = PendingEmailChange()
pec.user = user
else:
pec = pec_list[0]
pec.new_email = new_email
pec.activation_key = activation_key
pec.save()
context = {
'key': pec.activation_key,
'old_email': user.email,
'new_email': pec.new_email
}
subject = render_to_string('emails/email_change_subject.txt', context)
subject = ''.join(subject.splitlines())
message = render_to_string('emails/email_change.txt', context)
from_address = microsite.get_value(
'email_from_address',
settings.DEFAULT_FROM_EMAIL
)
try:
mail.send_mail(subject, message, from_address, [pec.new_email])
except Exception: # pylint: disable=broad-except
log.error(u'Unable to send email activation link to user from "%s"', from_address, exc_info=True)
raise ValueError(_('Unable to send email activation link. Please try again later.'))
@ensure_csrf_cookie
@transaction.commit_manually
def confirm_email_change(request, key): # pylint: disable=unused-argument
"""
User requested a new e-mail. This is called when the activation
link is clicked. We confirm with the old e-mail, and update
"""
try:
try:
pec = PendingEmailChange.objects.get(activation_key=key)
except PendingEmailChange.DoesNotExist:
response = render_to_response("invalid_email_key.html", {})
transaction.rollback()
return response
user = pec.user
address_context = {
'old_email': user.email,
'new_email': pec.new_email
}
if len(User.objects.filter(email=pec.new_email)) != 0:
response = render_to_response("email_exists.html", {})
transaction.rollback()
return response
subject = render_to_string('emails/email_change_subject.txt', address_context)
subject = ''.join(subject.splitlines())
message = render_to_string('emails/confirm_email_change.txt', address_context)
u_prof = UserProfile.objects.get(user=user)
meta = u_prof.get_meta()
if 'old_emails' not in meta:
meta['old_emails'] = []
meta['old_emails'].append([user.email, datetime.datetime.now(UTC).isoformat()])
u_prof.set_meta(meta)
u_prof.save()
# Send it to the old email...
try:
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
except Exception: # pylint: disable=broad-except
log.warning('Unable to send confirmation email to old address', exc_info=True)
response = render_to_response("email_change_failed.html", {'email': user.email})
transaction.rollback()
return response
user.email = pec.new_email
user.save()
pec.delete()
# And send it to the new email...
try:
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
except Exception: # pylint: disable=broad-except
log.warning('Unable to send confirmation email to new address', exc_info=True)
response = render_to_response("email_change_failed.html", {'email': pec.new_email})
transaction.rollback()
return response
response = render_to_response("email_change_successful.html", address_context)
transaction.commit()
return response
except Exception: # pylint: disable=broad-except
# If we get an unexpected exception, be sure to rollback the transaction
transaction.rollback()
raise
# TODO: DELETE AFTER NEW ACCOUNT PAGE DONE
@ensure_csrf_cookie
@require_POST
def change_name_request(request):
""" Log a request for a new name. """
if not request.user.is_authenticated():
raise Http404
try:
pnc = PendingNameChange.objects.get(user=request.user.id)
except PendingNameChange.DoesNotExist:
pnc = PendingNameChange()
pnc.user = request.user
pnc.new_name = request.POST['new_name'].strip()
pnc.rationale = request.POST['rationale']
if len(pnc.new_name) < 2:
return JsonResponse({
"success": False,
"error": _('Name required'),
}) # TODO: this should be status code 400 # pylint: disable=fixme
pnc.save()
# The following automatically accepts name change requests. Remove this to
# go back to the old system where it gets queued up for admin approval.
accept_name_change_by_id(pnc.id)
return JsonResponse({"success": True})
# TODO: DELETE AFTER NEW ACCOUNT PAGE DONE
def accept_name_change_by_id(uid):
"""
Accepts the pending name change request for the user represented
by user id `uid`.
"""
try:
pnc = PendingNameChange.objects.get(id=uid)
except PendingNameChange.DoesNotExist:
return JsonResponse({
"success": False,
"error": _('Invalid ID'),
}) # TODO: this should be status code 400 # pylint: disable=fixme
user = pnc.user
u_prof = UserProfile.objects.get(user=user)
# Save old name
meta = u_prof.get_meta()
if 'old_names' not in meta:
meta['old_names'] = []
meta['old_names'].append([u_prof.name, pnc.rationale, datetime.datetime.now(UTC).isoformat()])
u_prof.set_meta(meta)
u_prof.name = pnc.new_name
u_prof.save()
pnc.delete()
return JsonResponse({"success": True})
@require_POST
@login_required
@ensure_csrf_cookie
def change_email_settings(request):
"""Modify logged-in user's setting for receiving emails from a course."""
user = request.user
course_id = request.POST.get("course_id")
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
receive_emails = request.POST.get("receive_emails")
if receive_emails:
optout_object = Optout.objects.filter(user=user, course_id=course_key)
if optout_object:
optout_object.delete()
log.info(
u"User %s (%s) opted in to receive emails from course %s",
user.username,
user.email,
course_id
)
track.views.server_track(request, "change-email-settings", {"receive_emails": "yes", "course": course_id}, page='dashboard')
else:
Optout.objects.get_or_create(user=user, course_id=course_key)
log.info(
u"User %s (%s) opted out of receiving emails from course %s",
user.username,
user.email,
course_id
)
track.views.server_track(request, "change-email-settings", {"receive_emails": "no", "course": course_id}, page='dashboard')
return JsonResponse({"success": True})
| agpl-3.0 |
Tisseo/EndivBundle | Entity/LineStatus.php | 2499 | <?php
namespace Tisseo\EndivBundle\Entity;
/**
* LineStatus
*/
class LineStatus
{
/**
* @var int
*/
private $id;
/**
* @var \DateTime
*/
private $dateTime;
/**
* @var string
*/
private $login;
/**
* @var int
*/
private $status;
/**
* @var Line
*/
private $line;
/**
* @var string
*/
private $comment;
public function __toString()
{
return sprintf('%s / %s / %s / %s version %s', $this->login, $this->status, $this->comment, $this->dateTime->format('d/m/Y'), $this->line->getId());
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set login
*
* @param string $login
*
* @return LineStatus
*/
public function setLogin($login)
{
$this->login = $login;
return $this;
}
/**
* Get login
*
* @return string
*/
public function getLogin()
{
return $this->login;
}
/**
* Set comment
*
* @param string $comment
*
* @return LineStatus
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* Get comment
*
* @return string
*/
public function getComment()
{
return $this->comment;
}
/**
* Set status
*
* @param int $status
*
* @return LineStatus
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set dateTime
*
* @param \DateTime $dateTime
*
* @return LineStatus
*/
public function setDateTime($dateTime)
{
$this->dateTime = $dateTime;
return $this;
}
/**
* Get dateTime
*
* @return \DateTime
*/
public function getDateTime()
{
return $this->dateTime;
}
/**
* Set line
*
* @param Line $line
*
* @return LineStatus
*/
public function setLine(Line $line = null)
{
$this->line = $line;
return $this;
}
/**
* Get line
*
* @return Line
*/
public function getLine()
{
return $this->line;
}
}
| agpl-3.0 |
printedheart/opennars | nars_lab/src/main/java/ptrman/difficultyEnvironment/interactionComponents/BiasedRandomAIComponent.java | 1782 | package ptrman.difficultyEnvironment.interactionComponents;
import ptrman.difficultyEnvironment.EntityDescriptor;
import ptrman.difficultyEnvironment.JavascriptDescriptor;
import java.util.Random;
/**
* A random generator of movement of an agent.
* The output for the controller is biased because else the actor would do a nonsensical random walk (where the sum of all movements over time is roughtly zero)
*
*/
public class BiasedRandomAIComponent implements IComponent {
public float ratioOfMoveRotation;
public float timerNextMovechange;
public float remainingTimerNextMovechange = -0.01f;
public float angleScale;
public TopDownViewWheeledControllerComponent topDownViewWheeledControllerComponent; // can be null
public BiasedRandomAIComponent(float timerNextMovechange, float ratioOfMoveRotation, float angleScale) {
this.timerNextMovechange = timerNextMovechange;
this.ratioOfMoveRotation = ratioOfMoveRotation;
this.angleScale = angleScale;
}
@Override
public void frameInteraction(JavascriptDescriptor javascriptDescriptor, EntityDescriptor entityDescriptor, float timedelta) {
remainingTimerNextMovechange -= timedelta;
if( remainingTimerNextMovechange < 0.0f ) {
remainingTimerNextMovechange = timerNextMovechange;
if( topDownViewWheeledControllerComponent != null ) {
topDownViewWheeledControllerComponent.relativeSpeed = -1.0f + random.nextFloat()*2.0f;
topDownViewWheeledControllerComponent.relativeAngle = (-1.0f + random.nextFloat()*2.0f)*angleScale;
}
}
}
@Override
public String getLongName() {
return "BiasedRandomAIComponent";
}
private Random random = new Random();
}
| agpl-3.0 |
frafra/remotelauncher | remotelauncher/urls.py | 415 | from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Examples:
# url(r'^$', 'remotelauncher.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('launcher.urls')),
]
admin.site.site_header = "Remote launcher administration"
admin.site.site_title = "Remote launcher site admin"
| agpl-3.0 |
DDMoReThoughtflow/ThoughtflowGUI | DDMoRe-BWF-Web/src/main/java/eu/ddmore/workflow/bwf/web/bean/FileBean.java | 3049 | package eu.ddmore.workflow.bwf.web.bean;
import org.primefaces.model.ByteArrayContent;
import org.primefaces.model.StreamedContent;
import eu.ddmore.workflow.bwf.client.enumeration.ProvType;
import eu.ddmore.workflow.bwf.client.model.Activity;
import eu.ddmore.workflow.bwf.client.model.File;
public class FileBean extends BaseProvModelBean<File> {
private static final long serialVersionUID = 1L;
private static final int MAX_PATH_LENGHT = 17;
private Boolean isModel;
private Boolean isPicture;
private Boolean hasData;
private String path;
private Boolean pathAbbreviated;
private String activitiesString;
private String strContent;
private StreamedContent picData;
public FileBean(File model) {
super(model);
}
public FileBean(boolean selected, File model) {
super(selected, model);
}
@Override
protected void init() {
this.isModel = (ProvType.MODEL == getModel().getProvType());
this.isPicture = (ProvType.IMAGE == getModel().getProvType());
this.hasData = (getModel().getData() != null && getModel().getData().length > 0);
if (getModel().getActivities().hasActivitys()) {
activitiesString = "";
for (Activity activity : getModel().getActivities().getActivities()) {
boolean added = false;
if (added) {
this.activitiesString += ",";
}
this.activitiesString += activity.getLabel();
added = true;
}
}
this.pathAbbreviated = false;
if (isNotEmpty(getModel().getPath())) {
this.path = getModel().getPath();
if (this.path.length() > MAX_PATH_LENGHT) {
this.path = (this.path.substring(0, MAX_PATH_LENGHT) + "...");
this.pathAbbreviated = true;
}
}
}
public Boolean getIsModel() {
return this.isModel;
}
public void setIsModel(Boolean isModel) {
this.isModel = isModel;
}
public Boolean getIsPicture() {
return this.isPicture;
}
public void setIsPicture(Boolean isPicture) {
this.isPicture = isPicture;
}
public Boolean getHasData() {
return this.hasData;
}
public void setHasData(Boolean hasData) {
this.hasData = hasData;
}
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
}
public Boolean getPathAbbreviated() {
return this.pathAbbreviated;
}
public void setPathAbbreviated(Boolean pathAbbreviated) {
this.pathAbbreviated = pathAbbreviated;
}
public String getActivitiesString() {
return this.activitiesString;
}
public void setActivitiesString(String activitiesString) {
this.activitiesString = activitiesString;
}
public String getStrContent() {
if (this.strContent == null && getHasData()) {
this.strContent = new String(getModel().getData());
}
return this.strContent;
}
public void setStrContent(String strContent) {
this.strContent = strContent;
}
public StreamedContent getPicData() {
if (this.picData == null && getHasData()) {
this.picData = new ByteArrayContent(getModel().getData());
}
return this.picData;
}
public void setPic(StreamedContent picData) {
this.picData = picData;
}
}
| agpl-3.0 |
coast-team/mute-structs | src/operations/delete/logootsdel.ts | 4305 | /*
This file is part of MUTE-structs.
Copyright (C) 2017 Matthieu Nicolas, Victorien Elvinger
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 <https://www.gnu.org/licenses/>.
*/
import {isObject} from "../../data-validation"
import { IdentifierInterval } from "../../identifierinterval"
import { isInt32 } from "../../int32"
import { LogootSRopes } from "../../logootsropes"
import { LogootSOperation } from "../logootsoperation"
import { TextDelete } from "./textdelete"
const arrayConcat = Array.prototype.concat
class LogootSDelV1 {
static fromPlain (o: unknown): LogootSDel | null {
if (isObject<LogootSDelV1>(o) &&
Array.isArray(o.lid) && o.lid.length > 0) {
let isOk = true
let i = 0
const lid: IdentifierInterval[] = []
while (isOk && i < o.lid.length) {
const idi = IdentifierInterval.fromPlain( o.lid[i])
if (idi !== null) {
lid.push(idi)
} else {
isOk = false
}
i++
}
if (isOk) {
return new LogootSDel(lid, -1)
}
}
return null
}
readonly lid?: IdentifierInterval[]
}
/**
* Represents a LogootSplit delete operation.
*/
export class LogootSDel extends LogootSOperation {
static fromPlain (o: unknown): LogootSDel | null {
if (isObject<LogootSDel>(o) &&
Array.isArray(o.lid) && o.lid.length > 0 && isInt32(o.author)) {
let isOk = true
let i = 0
const lid: IdentifierInterval[] = []
while (isOk && i < o.lid.length) {
const idi = IdentifierInterval.fromPlain(o.lid[i])
if (idi !== null) {
lid.push(idi)
} else {
isOk = false
}
i++
}
if (isOk) {
return new LogootSDel(lid, o.author)
}
}
// For backward compatibility
// Allow to replay and update previous log of operations
return LogootSDelV1.fromPlain(o)
}
readonly lid: IdentifierInterval[]
readonly author: number
/**
* @constructor
* @param {IdentifierInterval[]} lid - the list of identifier that localise the deletion in the logoot sequence.
* @param {number} author - the author of the operation.
*/
constructor (lid: IdentifierInterval[], author: number) {
console.assert(lid.length > 0, "lid must not be empty")
console.assert(isInt32(author), "author ∈ int32")
super()
this.lid = lid
this.author = author
}
equals (aOther: LogootSDel): boolean {
return (
this.lid.length === aOther.lid.length &&
this.lid.every(
(idInterval: IdentifierInterval, index: number): boolean => {
const otherIdInterval: IdentifierInterval = aOther.lid[index]
return idInterval.equals(otherIdInterval)
},
)
)
}
/**
* Apply the current delete operation to a LogootSplit document.
* @param {LogootSRopes} doc - the LogootSplit document on which the deletions wil be performed.
* @return {TextDelete[]} the list of deletions to be applied on the sequence representing the document content.
*/
execute (doc: LogootSRopes): TextDelete[] {
return arrayConcat.apply(
[],
this.lid.map(
(aId: IdentifierInterval): TextDelete[] =>
doc.delBlock(aId, this.author),
),
)
}
}
| agpl-3.0 |
dmeltzer/snipe-it | app/Http/Controllers/SettingsController.php | 42459 | <?php
namespace App\Http\Controllers;
use enshrined\svgSanitize\Sanitizer;
use App\Helpers\Helper;
use App\Http\Requests\ImageUploadRequest;
use App\Http\Requests\SetupUserRequest;
use App\Models\Setting;
use App\Models\User;
use App\Notifications\FirstAdminNotification;
use App\Notifications\MailTest;
use Artisan;
use Auth;
use Crypt;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Image;
use Input;
use Redirect;
use Response;
/**
* This controller handles all actions related to Settings for
* the Snipe-IT Asset Management application.
*
* @version v1.0
*/
class SettingsController extends Controller
{
/**
* Checks to see whether or not the database has a migrations table
* and a user, otherwise display the setup view.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function getSetupIndex()
{
$start_settings['php_version_min'] = false;
if (version_compare(PHP_VERSION, config('app.min_php'), '<')) {
return response('<center><h1>This software requires PHP version ' . config('app.min_php') . ' or greater. This server is running ' . PHP_VERSION . '. </h1><h2>Please upgrade PHP on this server and try again. </h2></center>', 500);
}
try {
$conn = DB::select('select 2 + 2');
$start_settings['db_conn'] = true;
$start_settings['db_name'] = DB::connection()->getDatabaseName();
$start_settings['db_error'] = null;
} catch (\PDOException $e) {
$start_settings['db_conn'] = false;
$start_settings['db_name'] = config('database.connections.mysql.database');
$start_settings['db_error'] = $e->getMessage();
}
$protocol = array_key_exists('HTTPS', $_SERVER) && ('on' == $_SERVER['HTTPS']) ? 'https://' : 'http://';
$host = array_key_exists('SERVER_NAME', $_SERVER) ? $_SERVER['SERVER_NAME'] : null;
$port = array_key_exists('SERVER_PORT', $_SERVER) ? $_SERVER['SERVER_PORT'] : null;
if (('http://' === $protocol && '80' != $port) || ('https://' === $protocol && '443' != $port)) {
$host .= ':' . $port;
}
$pageURL = $protocol . $host . $_SERVER['REQUEST_URI'];
$start_settings['url_valid'] = (url('/') . '/setup' === $pageURL);
$start_settings['url_config'] = url('/');
$start_settings['real_url'] = $pageURL;
$start_settings['php_version_min'] = true;
// Curl the .env file to make sure it's not accessible via a browser
$ch = curl_init($protocol . $host . '/.env');
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (404 == $httpcode || 403 == $httpcode || 0 == $httpcode) {
$start_settings['env_exposed'] = false;
} else {
$start_settings['env_exposed'] = true;
}
if (\App::Environment('production') && (true == config('app.debug'))) {
$start_settings['debug_exposed'] = true;
} else {
$start_settings['debug_exposed'] = false;
}
$environment = app()->environment();
if ('production' != $environment) {
$start_settings['env'] = $environment;
$start_settings['prod'] = false;
} else {
$start_settings['env'] = $environment;
$start_settings['prod'] = true;
}
if (function_exists('posix_getpwuid')) { // Probably Linux
$owner = posix_getpwuid(fileowner($_SERVER['SCRIPT_FILENAME']));
$start_settings['owner'] = $owner['name'];
} else { // Windows
// TODO: Is there a way of knowing if a windows user has elevated permissions
// This just gets the user name, which likely isn't 'root'
// $start_settings['owner'] = getenv('USERNAME');
$start_settings['owner'] = '';
}
if (('root' === $start_settings['owner']) || ('0' === $start_settings['owner'])) {
$start_settings['owner_is_admin'] = true;
} else {
$start_settings['owner_is_admin'] = false;
}
if ((is_writable(storage_path()))
&& (is_writable(storage_path() . '/framework'))
&& (is_writable(storage_path() . '/framework/cache'))
&& (is_writable(storage_path() . '/framework/sessions'))
&& (is_writable(storage_path() . '/framework/views'))
&& (is_writable(storage_path() . '/logs'))
) {
$start_settings['writable'] = true;
} else {
$start_settings['writable'] = false;
}
$start_settings['gd'] = extension_loaded('gd');
return view('setup/index')
->with('step', 1)
->with('start_settings', $start_settings)
->with('section', 'Pre-Flight Check');
}
/**
* Save the first admin user from Setup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return Redirect
*/
public function postSaveFirstAdmin(SetupUserRequest $request)
{
$user = new User();
$user->first_name = $data['first_name'] = $request->input('first_name');
$user->last_name = $request->input('last_name');
$user->email = $data['email'] = $request->input('email');
$user->activated = 1;
$permissions = ['superuser' => 1];
$user->permissions = json_encode($permissions);
$user->username = $data['username'] = $request->input('username');
$user->password = bcrypt($request->input('password'));
$data['password'] = $request->input('password');
$settings = new Setting();
$settings->full_multiple_companies_support = $request->input('full_multiple_companies_support', 0);
$settings->site_name = $request->input('site_name');
$settings->alert_email = $request->input('email');
$settings->alerts_enabled = 1;
$settings->pwd_secure_min = 10;
$settings->brand = 1;
$settings->locale = $request->input('locale', 'en');
$settings->default_currency = $request->input('default_currency', 'USD');
$settings->user_id = 1;
$settings->email_domain = $request->input('email_domain');
$settings->email_format = $request->input('email_format');
$settings->next_auto_tag_base = 1;
$settings->auto_increment_assets = $request->input('auto_increment_assets', 0);
$settings->auto_increment_prefix = $request->input('auto_increment_prefix');
if ((! $user->isValid()) || (! $settings->isValid())) {
return redirect()->back()->withInput()->withErrors($user->getErrors())->withErrors($settings->getErrors());
} else {
$user->save();
Auth::login($user, true);
$settings->save();
if ('1' == Input::get('email_creds')) {
$data = [];
$data['email'] = $user->email;
$data['username'] = $user->username;
$data['first_name'] = $user->first_name;
$data['last_name'] = $user->last_name;
$data['password'] = $request->input('password');
$user->notify(new FirstAdminNotification($data));
}
return redirect()->route('setup.done');
}
}
/**
* Return the admin user creation form in Setup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function getSetupUser()
{
return view('setup/user')
->with('step', 3)
->with('section', 'Create a User');
}
/**
* Return the view that tells the user that the Setup is done.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function getSetupDone()
{
return view('setup/done')
->with('step', 4)
->with('section', 'Done!');
}
/**
* Migrate the database tables, and return the output
* to a view for Setup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function getSetupMigrate()
{
Artisan::call('migrate', ['--force' => true]);
if ((! file_exists(storage_path() . '/oauth-private.key')) || (! file_exists(storage_path() . '/oauth-public.key'))) {
Artisan::call('migrate', ['--path' => 'vendor/laravel/passport/database/migrations', '--force' => true]);
Artisan::call('passport:install');
}
return view('setup/migrate')
->with('output', 'Databases installed!')
->with('step', 2)
->with('section', 'Create Database Tables');
}
/**
* Return a view that shows some of the key settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function index()
{
$settings = Setting::getSettings();
return view('settings/index', compact('settings'));
}
/**
* Return the admin settings page.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getEdit()
{
$setting = Setting::getSettings();
return view('settings/general', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getSettings()
{
$setting = Setting::getSettings();
return view('settings/general', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postSettings(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->modellist_displays = '';
if (($request->filled('show_in_model_list')) && (count($request->input('show_in_model_list')) > 0))
{
$setting->modellist_displays = implode(',', $request->input('show_in_model_list'));
}
$setting->full_multiple_companies_support = $request->input('full_multiple_companies_support', '0');
$setting->unique_serial = $request->input('unique_serial', '0');
$setting->show_images_in_email = $request->input('show_images_in_email', '0');
$setting->show_archived_in_list = $request->input('show_archived_in_list', '0');
$setting->dashboard_message = $request->input('dashboard_message');
$setting->email_domain = $request->input('email_domain');
$setting->email_format = $request->input('email_format');
$setting->username_format = $request->input('username_format');
$setting->require_accept_signature = $request->input('require_accept_signature');
$setting->show_assigned_assets = $request->input('show_assigned_assets', '0');
if (! config('app.lock_passwords')) {
$setting->login_note = $request->input('login_note');
}
$setting->default_eula_text = $request->input('default_eula_text');
$setting->thumbnail_max_h = $request->input('thumbnail_max_h');
$setting->privacy_policy_link = $request->input('privacy_policy_link');
$setting->depreciation_method = $request->input('depreciation_method');
if ('' != Input::get('per_page')) {
$setting->per_page = $request->input('per_page');
} else {
$setting->per_page = 200;
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getBranding()
{
$setting = Setting::getSettings();
return view('settings.branding', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postBranding(ImageUploadRequest $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->brand = $request->input('brand', '1');
$setting->header_color = $request->input('header_color');
$setting->support_footer = $request->input('support_footer');
$setting->version_footer = $request->input('version_footer');
$setting->footer_text = $request->input('footer_text');
$setting->skin = $request->input('skin');
$setting->show_url_in_emails = $request->input('show_url_in_emails', '0');
$setting->logo_print_assets = $request->input('logo_print_assets', '0');
// Only allow the site name and CSS to be changed if lock_passwords is false
// Because public demos make people act like dicks
if (! config('app.lock_passwords')) {
$setting->site_name = $request->input('site_name');
$setting->custom_css = $request->input('custom_css');
}
if ($request->hasFile('logo')) {
$image = $request->file('logo');
$ext = $image->getClientOriginalExtension();
$setting->logo = $file_name = 'logo-.'.date('Y-m-d').'.'. $ext;
if ('svg' != $image->getClientOriginalExtension()) {
$upload = Image::make($image->getRealPath())->resize(null, 150, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
// This requires a string instead of an object, so we use ($string)
Storage::disk('public')->put($file_name, (string) $upload->encode());
// Remove Current image if exists
if (($setting->logo) && (file_exists($file_name))) {
Storage::disk('public')->delete($file_name);
}
} elseif ('1' == $request->input('clear_logo')) {
Storage::disk('public')->delete($setting->logo);
$setting->logo = null;
$setting->brand = 1;
}
if ($request->hasFile('email_logo')) {
$email_image = $email_upload = $request->file('email_logo');
$email_ext = $email_image->getClientOriginalExtension();
$setting->email_logo = $email_file_name = 'email_logo.' . $email_ext;
if ('svg' != $email_image->getClientOriginalExtension()) {
$email_upload = Image::make($email_image->getRealPath())->resize(null, 100, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
// This requires a string instead of an object, so we use ($string)
Storage::disk('public')->put($email_file_name, (string) $email_upload->encode());
// Remove Current image if exists
if (($setting->email_logo) && (file_exists($email_file_name))) {
Storage::disk('public')->delete($email_file_name);
}
} elseif ('1' == $request->input('clear_email_logo')) {
Storage::disk('public')->delete($setting->email_logo);
$setting->email_logo = null;
// If they are uploading an image, validate it and upload it
}
// If the user wants to clear the label logo...
if ($request->hasFile('label_logo')) {
$image = $request->file('label_logo');
$ext = $image->getClientOriginalExtension();
$setting->label_logo = $label_file_name = 'label_logo.' . $ext;
if ('svg' != $image->getClientOriginalExtension()) {
$upload = Image::make($image->getRealPath())->resize(null, 100, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
// This requires a string instead of an object, so we use ($string)
Storage::disk('public')->put($label_file_name, (string) $upload->encode());
// Remove Current image if exists
if (($setting->label_logo) && (file_exists($label_file_name))) {
Storage::disk('public')->delete($label_file_name);
}
} elseif ('1' == $request->input('clear_label_logo')) {
Storage::disk('public')->delete($setting->label_logo);
$setting->label_logo = null;
// If they are uploading an image, validate it and upload it
}
// If the user wants to clear the favicon...
if ($request->hasFile('favicon')) {
$favicon_image = $favicon_upload = $request->file('favicon');
$favicon_ext = $favicon_image->getClientOriginalExtension();
$setting->favicon = $favicon_file_name = 'favicon-uploaded.' . $favicon_ext;
if (('ico' != $favicon_image->getClientOriginalExtension()) && ('svg' != $favicon_image->getClientOriginalExtension())) {
$favicon_upload = Image::make($favicon_image->getRealPath())->resize(null, 36, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
// This requires a string instead of an object, so we use ($string)
Storage::disk('public')->put($favicon_file_name, (string) $favicon_upload->encode());
} else {
Storage::disk('public')->put($favicon_file_name, file_get_contents($request->file('favicon')));
}
// Remove Current image if exists
if (($setting->favicon) && (file_exists($favicon_file_name))) {
Storage::disk('public')->delete($favicon_file_name);
}
} elseif ('1' == $request->input('clear_favicon')) {
Storage::disk('public')->delete($setting->clear_favicon);
$setting->favicon = null;
// If they are uploading an image, validate it and upload it
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getSecurity()
{
$setting = Setting::getSettings();
return view('settings.security', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postSecurity(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
if (! config('app.lock_passwords')) {
if ('' == $request->input('two_factor_enabled')) {
$setting->two_factor_enabled = null;
} else {
$setting->two_factor_enabled = $request->input('two_factor_enabled');
}
// remote user login
$setting->login_remote_user_enabled = (int) $request->input('login_remote_user_enabled');
$setting->login_common_disabled = (int) $request->input('login_common_disabled');
$setting->login_remote_user_custom_logout_url = $request->input('login_remote_user_custom_logout_url');
$setting->login_remote_user_header_name = $request->input('login_remote_user_header_name');
}
$setting->pwd_secure_uncommon = (int) $request->input('pwd_secure_uncommon');
$setting->pwd_secure_min = (int) $request->input('pwd_secure_min');
$setting->pwd_secure_complexity = '';
if ($request->filled('pwd_secure_complexity')) {
$setting->pwd_secure_complexity = implode('|', $request->input('pwd_secure_complexity'));
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getLocalization()
{
$setting = Setting::getSettings();
return view('settings.localization', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postLocalization(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
if (! config('app.lock_passwords')) {
$setting->locale = $request->input('locale', 'en');
}
$setting->default_currency = $request->input('default_currency', '$');
$setting->date_display_format = $request->input('date_display_format');
$setting->time_display_format = $request->input('time_display_format');
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getAlerts()
{
$setting = Setting::getSettings();
return view('settings.alerts', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postAlerts(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$alert_email = rtrim($request->input('alert_email'), ',');
$alert_email = trim($alert_email);
$admin_cc_email = rtrim($request->input('admin_cc_email'), ',');
$admin_cc_email = trim($admin_cc_email);
$setting->alert_email = $alert_email;
$setting->admin_cc_email = $admin_cc_email;
$setting->alerts_enabled = $request->input('alerts_enabled', '0');
$setting->alert_interval = $request->input('alert_interval');
$setting->alert_threshold = $request->input('alert_threshold');
$setting->audit_interval = $request->input('audit_interval');
$setting->audit_warning_days = $request->input('audit_warning_days');
$setting->show_alerts_in_menu = $request->input('show_alerts_in_menu', '0');
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getSlack()
{
$setting = Setting::getSettings();
return view('settings.slack', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postSlack(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$validatedData = $request->validate([
'slack_channel' => 'regex:/(?<!\w)#\w+/|required_with:slack_endpoint|nullable',
]);
if ($validatedData) {
$setting->slack_endpoint = $request->input('slack_endpoint');
$setting->slack_channel = $request->input('slack_channel');
$setting->slack_botname = $request->input('slack_botname');
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getAssetTags()
{
$setting = Setting::getSettings();
return view('settings.asset_tags', compact('setting'));
}
/**
* Saves settings from form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postAssetTags(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->auto_increment_prefix = $request->input('auto_increment_prefix');
$setting->auto_increment_assets = $request->input('auto_increment_assets', '0');
$setting->zerofill_count = $request->input('zerofill_count');
$setting->next_auto_tag_base = $request->input('next_auto_tag_base');
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getBarcodes()
{
$setting = Setting::getSettings();
$is_gd_installed = extension_loaded('gd');
return view('settings.barcodes', compact('setting'))->with('is_gd_installed', $is_gd_installed);
}
/**
* Saves settings from form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postBarcodes(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->qr_code = $request->input('qr_code', '0');
$setting->alt_barcode = $request->input('alt_barcode');
$setting->alt_barcode_enabled = $request->input('alt_barcode_enabled', '0');
$setting->barcode_type = $request->input('barcode_type');
$setting->qr_text = $request->input('qr_text');
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function getPhpInfo()
{
if (true === config('app.debug')) {
return view('settings.phpinfo');
}
return redirect()->route('settings.index')
->with('error', 'PHP syetem debugging information is only available when debug is enabled in your .env file.');
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function getLabels()
{
$setting = Setting::getSettings();
return view('settings.labels', compact('setting'));
}
/**
* Saves settings from form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function postLabels(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->labels_per_page = $request->input('labels_per_page');
$setting->labels_width = $request->input('labels_width');
$setting->labels_height = $request->input('labels_height');
$setting->labels_pmargin_left = $request->input('labels_pmargin_left');
$setting->labels_pmargin_right = $request->input('labels_pmargin_right');
$setting->labels_pmargin_top = $request->input('labels_pmargin_top');
$setting->labels_pmargin_bottom = $request->input('labels_pmargin_bottom');
$setting->labels_display_bgutter = $request->input('labels_display_bgutter');
$setting->labels_display_sgutter = $request->input('labels_display_sgutter');
$setting->labels_fontsize = $request->input('labels_fontsize');
$setting->labels_pagewidth = $request->input('labels_pagewidth');
$setting->labels_pageheight = $request->input('labels_pageheight');
$setting->labels_display_company_name = $request->input('labels_display_company_name', '0');
$setting->labels_display_company_name = $request->input('labels_display_company_name', '0');
if ($request->filled('labels_display_name')) {
$setting->labels_display_name = 1;
} else {
$setting->labels_display_name = 0;
}
if ($request->filled('labels_display_serial')) {
$setting->labels_display_serial = 1;
} else {
$setting->labels_display_serial = 0;
}
if ($request->filled('labels_display_tag')) {
$setting->labels_display_tag = 1;
} else {
$setting->labels_display_tag = 0;
}
if ($request->filled('labels_display_tag')) {
$setting->labels_display_tag = 1;
} else {
$setting->labels_display_tag = 0;
}
if ($request->filled('labels_display_model')) {
$setting->labels_display_model = 1;
} else {
$setting->labels_display_model = 0;
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function getLdapSettings()
{
$setting = Setting::getSettings();
return view('settings.ldap', compact('setting'));
}
/**
* Saves settings from form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function postLdapSettings(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->ldap_enabled = $request->input('ldap_enabled', '0');
$setting->ldap_server = $request->input('ldap_server');
$setting->ldap_server_cert_ignore = $request->input('ldap_server_cert_ignore', false);
$setting->ldap_uname = $request->input('ldap_uname');
if ($request->input('ldap_pword') !== '') {
$setting->ldap_pword = Crypt::encrypt($request->input('ldap_pword'));
}
$setting->ldap_basedn = $request->input('ldap_basedn');
$setting->ldap_filter = $request->input('ldap_filter');
$setting->ldap_username_field = $request->input('ldap_username_field');
$setting->ldap_lname_field = $request->input('ldap_lname_field');
$setting->ldap_fname_field = $request->input('ldap_fname_field');
$setting->ldap_auth_filter_query = $request->input('ldap_auth_filter_query');
$setting->ldap_version = $request->input('ldap_version');
$setting->ldap_active_flag = $request->input('ldap_active_flag');
$setting->ldap_emp_num = $request->input('ldap_emp_num');
$setting->ldap_email = $request->input('ldap_email');
$setting->ad_domain = $request->input('ad_domain');
$setting->is_ad = $request->input('is_ad', '0');
$setting->ldap_tls = $request->input('ldap_tls', '0');
$setting->ldap_pw_sync = $request->input('ldap_pw_sync', '0');
$setting->custom_forgot_pass_url = $request->input('custom_forgot_pass_url');
if ($setting->save()) {
return redirect()->route('settings.ldap.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Show the listing of backups.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.8]
*
* @return View
*/
public function getBackups()
{
$path = storage_path() . '/app/' . config('backup.backup.name');
$path = 'backups';
$backup_files = Storage::files($path);
$files = [];
if (count($backup_files) > 0) {
for ($f = 0; $f < count($backup_files); ++$f) {
$files[] = [
'filename' => basename($backup_files[$f]),
'filesize' => Setting::fileSizeConvert(Storage::size($backup_files[$f])),
'modified' => Storage::lastModified($backup_files[$f]),
];
}
}
return view('settings/backups', compact('path', 'files'));
}
/**
* Process the backup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.8]
*
* @return Redirect
*/
public function postBackups()
{
if (! config('app.lock_passwords')) {
Artisan::call('backup:run');
$output = Artisan::output();
// Backup completed
if (! preg_match('/failed/', $output)) {
return redirect()->route('settings.backups.index')
->with('success', trans('admin/settings/message.backup.generated'));
}
$formatted_output = str_replace('Backup completed!', '', $output);
$output_split = explode('...', $formatted_output);
if (array_key_exists(2, $output_split)) {
return redirect()->route('settings.backups.index')->with('error', $output_split[2]);
}
return redirect()->route('settings.backups.index')->with('error', $formatted_output);
}
return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
}
/**
* Download the backup file.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.8]
*
* @return Redirect
*/
public function downloadFile($filename = null)
{
if (! config('app.lock_passwords')) {
if (Storage::exists($filename)) {
return Response::download(Storage::url('') . e($filename));
} else {
// Redirect to the backup page
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
}
} else {
// Redirect to the backup page
return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
}
}
/**
* Delete the backup file.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.8]
*
* @return View
*/
public function deleteFile($filename = null)
{
if (! config('app.lock_passwords')) {
$path = 'backups';
if (Storage::exists($path . '/' . $filename)) {
try {
Storage::delete($path . '/' . $filename);
return redirect()->route('settings.backups.index')->with('success', trans('admin/settings/message.backup.file_deleted'));
} catch (\Exception $e) {
\Log::debug($e);
}
} else {
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
}
} else {
return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
}
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function getPurge()
{
return view('settings.purge-form');
}
/**
* Purges soft-deletes.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function postPurge()
{
if (! config('app.lock_passwords')) {
if ('DELETE' == Input::get('confirm_purge')) {
// Run a backup immediately before processing
Artisan::call('backup:run');
Artisan::call('snipeit:purge', ['--force' => 'true', '--no-interaction' => true]);
$output = Artisan::output();
return view('settings/purge')
->with('output', $output)->with('success', trans('admin/settings/message.purge.success'));
} else {
return redirect()->back()->with('error', trans('admin/settings/message.purge.validation_failed'));
}
} else {
return redirect()->back()->with('error', trans('general.feature_disabled'));
}
}
/**
* Returns a page with the API token generation interface.
*
* We created a controller method for this because closures aren't allowed
* in the routes file if you want to be able to cache the routes.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function api()
{
return view('settings.api');
}
/**
* Test the email configuration.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return Redirect
*/
public function ajaxTestEmail()
{
try {
(new User())->forceFill([
'name' => config('mail.from.name'),
'email' => config('mail.from.address'),
])->notify(new MailTest());
return response()->json(Helper::formatStandardApiResponse('success', null, 'Maiol sent!'));
} catch (Exception $e) {
return response()->json(Helper::formatStandardApiResponse('success', null, $e->getMessage()));
}
}
public function getLoginAttempts()
{
return view('settings.logins');
}
} | agpl-3.0 |
openmole/openmole | openmole/plugins/org.openmole.plugin.sampling.combine/src/test/scala/org/openmole/plugin/sampling/combine/CombineSpec.scala | 2049 | package org.openmole.plugin.sampling.combine
import org.scalatest._
/*
* Copyright (C) 2021 Romain Reuillon
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import org.openmole.core.dsl._
import org.openmole.core.dsl.extension._
import org.openmole.plugin.domain.collection._
class CombineSpec extends FlatSpec with Matchers {
import org.openmole.core.workflow.test.Stubs._
"x keyword" should "create a complete sampling" in {
val x1 = Val[Int]
val x2 = Val[Double]
val x3 = Val[String]
val s = (x1 in (0 until 2)) x (x2 in (0.0 until 1.0 by 0.1)) x (x3 in List("a", "b"))
(s: Sampling).outputs.toSet should equal(Set(x1, x2, x3))
(s: Sampling).sampling.from(Context.empty).size should equal(40)
}
"++ keyword" should "concatenate samplings" in {
val x1 = Val[Int]
val x2 = Val[Double]
val s = (x1 in (0 until 2)) ++ (x1 in (8 until 10)) ++ ((x1 in List(100, 101)) x (x2 in List(8.9, 9.0)))
(s: Sampling).outputs.toSet should equal(Set(x1))
(s: Sampling).sampling.from(Context.empty).size should equal(8)
}
"zip keyword" should "zip samplings" in {
val x1 = Val[Int]
val x2 = Val[Double]
val x3 = Val[String]
val s = (x1 in (0 until 2)) zip (x2 in (8.0 until 9.0 by 0.5)) zip (x3 in List("a", "b"))
(s: Sampling).outputs.toSet should equal(Set(x1, x2, x3))
(s: Sampling).sampling.from(Context.empty).size should equal(2)
}
}
| agpl-3.0 |
harish-patel/ecrm | modules/Connectors/connectors/sources/ext/rest/zoominfoperson/language/cs_CZ.lang.php | 4168 | <?php
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
********************************************************************************/
$connector_strings = array (
'LBL_LICENSING_INFO' => '<table border="0" cellspacing="1"><tr><td valign="top" width="35%" class="dataLabel"><image src="modules/Connectors/connectors/sources/ext/rest/zoominfoperson/images/zoominfo.gif" border="0"></td><td width="65%" valign="top" class="dataLabel">ZoomInfo© provides deep information on over 45 million business people at over 5 million companies. Learn more. <a target="_blank" href="http://www.zoominfo.com/about">http://www.zoominfo.com/about</a></td></tr></table>',
'LBL_SEARCH_FIELDS_INFO' => 'Následující pole jsou podporovány Zoominfo© Person, API: Jméno, Příjmení a E-mailová adresa.',
'LBL_ID' => 'ID',
'LBL_FAX' => 'Fax',
'LBL_EMAIL' => 'E-mailová adresa',
'LBL_FIRST_NAME' => 'Jméno',
'LBL_LAST_NAME' => 'Příjmení',
'LBL_JOB_TITLE' => 'Pracovní pozice',
'LBL_IMAGE_URL' => 'URL obrázku',
'LBL_SUMMARY_URL' => 'URL Shrnutí',
'LBL_COMPANY_NAME' => 'Název společnosti',
'LBL_ZOOMPERSON_URL' => 'Zoominfo URL Osoby',
'LBL_DIRECT_PHONE' => 'Přímý telefon',
'LBL_COMPANY_PHONE' => 'Služobní telefon',
'LBL_CURRENT_JOB_TITLE' => 'Aktuální pracovní pozice',
'LBL_CURRENT_JOB_START_DATE' => 'Dátum začátku aktualního zaměstnání',
'LBL_CURRENT_JOB_COMPANY_NAME' => 'Název firmy aktualního zaměstnání',
'LBL_CURRENT_JOB_COMPANY_STREET' => 'Ulice aktualního zaměstnání',
'LBL_CURRENT_JOB_COMPANY_CITY' => 'Město aktualního zaměstnání',
'LBL_CURRENT_JOB_COMPANY_STATE' => 'Stát aktualního zaměstnání',
'LBL_CURRENT_JOB_COMPANY_ZIP' => 'PSČ aktualního zaměstnání',
'LBL_CURRENT_JOB_COMPANY_COUNTRY_CODE' => 'Lód země aktualního zaměstnání',
'LBL_CURRENT_INDUSTRY' => 'Odvětví aktualního zaměstnání',
'LBL_BIOGRAPHY' => 'Životopis',
'LBL_EDUCATION_SCHOOL' => 'Vzdělaní',
'LBL_AFFILIATION_TITLE' => 'Přidružený název pracovní pozice',
'LBL_AFFILIATION_COMPANY_PHONE' => 'Přidružený Phone',
'LBL_AFFILIATION_COMPANY_NAME' => 'Přidružený název společnosti',
'LBL_AFFILIATION_COMPANY_WEBSITE' => 'Přidružena stránka společnosti',
'person_search_url' => 'URL vyhledáváni společností',
'person_detail_url' => 'URL vyhledáváni osoby',
'partner_code' => 'API kod partnera',
'api_key' => 'API Klíč',
'ERROR_LBL_CONNECTION_PROBLEM' => 'Chyba: Nelze se připojit k serveru pro Zoominfo - Konektor osob.',
);
| agpl-3.0 |
archesproject/arches | arches/app/models/migrations/3210_card_components.py | 2035 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-05-09 14:45
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('models', '3201_remove_node_and_nodetype_branches'),
]
operations = [
migrations.CreateModel(
name='CardComponent',
fields=[
('componentid', models.UUIDField(default=uuid.uuid1, primary_key=True, serialize=False)),
('name', models.TextField(blank=True, null=True)),
('description', models.TextField(blank=True, null=True)),
('component', models.TextField()),
('componentname', models.TextField()),
('defaultconfig', django.contrib.postgres.fields.jsonb.JSONField(blank=True, db_column='defaultconfig', null=True)),
],
options={
'db_table': 'card_components',
'managed': True,
},
),
migrations.RunSQL("""
INSERT INTO card_components(componentid, name, description, component, componentname, defaultconfig)
VALUES ('f05e4d3a-53c1-11e8-b0ea-784f435179ea', 'Default Card', 'Default Arches card UI', 'views/components/cards/default', 'default-card', '{}');
""",
"""
DELETE FROM card_components WHERE componentid = 'f05e4d3a-53c1-11e8-b0ea-784f435179ea';
"""),
migrations.AddField(
model_name='cardmodel',
name='config',
field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, db_column='config', null=True),
),
migrations.AddField(
model_name='cardmodel',
name='component',
field=models.ForeignKey(db_column='componentid', default=uuid.UUID('f05e4d3a-53c1-11e8-b0ea-784f435179ea'), on_delete=django.db.models.deletion.CASCADE, to='models.CardComponent'),
),
]
| agpl-3.0 |
gladk/palabos | jlabos/src/precompiled/lattice/parallelMultiBlockLattice3D.cpp | 1445 | /* This file is part of the Palabos library.
*
* Copyright (C) 2011-2017 FlowKit Sarl
* Route d'Oron 2
* 1010 Lausanne, Switzerland
* E-mail contact: contact@flowkit.com
*
* The most recent release of Palabos can be downloaded at
* <http://www.palabos.org/>
*
* The library Palabos 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.
*
* The 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 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/>.
*/
/** \file
* Parallel dynamics object -- template instantiation.
*/
#ifdef COMPILE_3D
#include "parallelism/mpiManager.h"
#include "parallelism/parallelMultiBlockLattice3D.h"
#include "parallelism/parallelMultiBlockLattice3D.hh"
#include "latticeBoltzmann/nearestNeighborLattices3D.h"
#include "latticeBoltzmann/nearestNeighborLattices3D.hh"
namespace plb {
#ifdef PLB_MPI_PARALLEL
template class ParallelCellAccess3D<FLOAT_T, descriptors::DESCRIPTOR_3D>;
#endif
}
#endif // COMPILE_3D
| agpl-3.0 |
jzinedine/CMDBuild | bim/bimserver/src/main/java/org/cmdbuild/bim/service/bimserver/BimserverListAttribute.java | 1411 | package org.cmdbuild.bim.service.bimserver;
import java.util.ArrayList;
import java.util.List;
import org.bimserver.interfaces.objects.SDataValue;
import org.bimserver.interfaces.objects.SListDataValue;
import org.bimserver.interfaces.objects.SReferenceDataValue;
import org.bimserver.interfaces.objects.SSimpleDataValue;
import org.cmdbuild.bim.model.Attribute;
import org.cmdbuild.bim.service.ListAttribute;
public class BimserverListAttribute extends BimserverAttribute implements
ListAttribute {
protected BimserverListAttribute(final SListDataValue value) {
super(value);
}
@Override
public List<Attribute> getValues() {
final List<SDataValue> datavalues = ((SListDataValue) getDatavalue())
.getValues();
final List<Attribute> values = new ArrayList<Attribute>();
for (final SDataValue datavalue : datavalues) {
if (datavalue instanceof SSimpleDataValue) {
final Attribute attribute = new BimserverSimpleAttribute(
(SSimpleDataValue) datavalue);
values.add(attribute);
} else if (datavalue instanceof SListDataValue) {
final Attribute attribute = new BimserverListAttribute(
(SListDataValue) datavalue);
values.add(attribute);
} else if (datavalue instanceof SReferenceDataValue) {
final Attribute attribute = new BimserverReferenceAttribute(
(SReferenceDataValue) datavalue);
values.add(attribute);
}
}
return values;
}
}
| agpl-3.0 |
orthagh/fusioninventory-for-glpi | ajax/taskjob_itemtypes.php | 1944 | <?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
------------------------------------------------------------------------
*/
if (strpos($_SERVER['PHP_SELF'], "taskjob_itemtypes.php")) {
include ("../../../inc/includes.php");
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
}
Session::checkCentralAccess();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->ajaxModuleTypesDropdown($_GET);
?>
| agpl-3.0 |
pixiv/mastodon | app/policies/pawoo/report_target_policy.rb | 149 | # frozen_string_literal: true
class Pawoo::ReportTargetPolicy < ApplicationPolicy
def index?
staff?
end
def create?
staff?
end
end
| agpl-3.0 |
k10r/shopware | engine/Shopware/Bundle/StoreFrontBundle/Service/Core/ManufacturerService.php | 3389 | <?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace Shopware\Bundle\StoreFrontBundle\Service\Core;
use Shopware\Bundle\StoreFrontBundle\Gateway;
use Shopware\Bundle\StoreFrontBundle\Service;
use Shopware\Bundle\StoreFrontBundle\Struct;
use Shopware\Bundle\StoreFrontBundle\Struct\Product\Manufacturer;
use Shopware\Components\Routing\RouterInterface;
/**
* @category Shopware
*
* @copyright Copyright (c) shopware AG (http://www.shopware.de)
*/
class ManufacturerService implements Service\ManufacturerServiceInterface
{
/**
* @var Gateway\ManufacturerGatewayInterface
*/
private $manufacturerGateway;
/**
* @var RouterInterface
*/
private $router;
/**
* @param Gateway\ManufacturerGatewayInterface $manufacturerGateway
* @param RouterInterface $router
*/
public function __construct(
Gateway\ManufacturerGatewayInterface $manufacturerGateway,
RouterInterface $router
) {
$this->manufacturerGateway = $manufacturerGateway;
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public function get($id, Struct\ShopContextInterface $context)
{
$manufacturers = $this->getList([$id], $context);
return array_shift($manufacturers);
}
/**
* {@inheritdoc}
*/
public function getList(array $ids, Struct\ShopContextInterface $context)
{
$manufacturers = $this->manufacturerGateway->getList($ids, $context);
// fetch all manufacturer links instead of calling {url ...} smarty function which executes a query for each link
$links = $this->collectLinks($manufacturers);
$urls = $this->router->generateList($links);
foreach ($manufacturers as $manufacturer) {
if (array_key_exists($manufacturer->getId(), $urls)) {
$manufacturer->setLink($urls[$manufacturer->getId()]);
}
}
return $manufacturers;
}
/**
* @param Manufacturer[] $manufacturers
*
* @return array[]
*/
private function collectLinks(array $manufacturers)
{
$links = [];
foreach ($manufacturers as $manufacturer) {
$manufacturerId = $manufacturer->getId();
$links[$manufacturerId] = [
'controller' => 'listing',
'action' => 'manufacturer',
'sSupplier' => $manufacturerId,
];
}
return $links;
}
}
| agpl-3.0 |
Zarel/Pokemon-Showdown-Client | website/news/manage.php | 6399 | <?php
error_reporting(E_ALL);
include_once '../../lib/ntbb-session.lib.php';
include_once __DIR__ . '/../../config/news.inc.php';
include_once 'include.php';
if (!$users->isLeader()) die('access denied');
function saveNews() {
global $newsCache, $latestNewsCache;
file_put_contents(__DIR__ . '/../../config/news.inc.php', '<?php
$latestNewsCache = '.var_export($GLOBALS['latestNewsCache'], true).';
$newsCache = '.var_export($GLOBALS['newsCache'], true).';
');
date_default_timezone_set('America/Los_Angeles');
$indexData = file_get_contents('../../index.html');
$indexData = preg_replace('/ <div class="pm-log" style="max-height:none">
.*?
<\/div>
/', ' <div class="pm-log" style="max-height:none">
'.renderNews().'
</div>
', $indexData, 1);
$indexData = preg_replace('/ data-newsid="[^"]*">/', ' data-newsid="'.getNewsId().'">', $indexData, 1);
file_put_contents('../../index.html', $indexData);
}
include '../style/wrapper.inc.php';
$page = 'news';
$pageTitle = "News";
includeHeader();
?>
<div class="main" style="max-width:8in;">
<p>
<button onclick="$('#newpostform').show(); return false">New news post</button>
</p>
<form id="newpostform" style="display:none" method="post">
<input type="hidden" name="act" value="newentry" /><input type="hidden" name="topic_id" value="<?= @$topic_id ?>" /><?php $users->csrfData(); ?>
<input type="text" name="title" size="80" placeholder="Title" value="<?= htmlspecialchars(@$topic['title']) ?>" /><br /><br />
<textarea name="summary" cols="80" rows="10" placeholder="Summary"><?= htmlspecialchars(@$topic['summary']) ?></textarea>
<br /><button type="submit"><strong>Make New Post</strong></button>
</form>
<?php
if (@$_POST['act'] === 'editentry') {
if (!$users->csrfCheck()) die('csrf error');
$topic_id = $_POST['topic_id'];
$title = $_POST['title'];
// summary parse
$summary = $_POST['summary'];
$newsCache[$topic_id]['summary'] = $summary;
$summary = str_replace("\r", '', $summary);
$summary = str_replace("\n\n", '</p><p>', $summary);
$summary = str_replace("\n", '<br />', $summary);
$summary = str_replace("\n", '<br />', $summary);
$summary = preg_replace('/\[url="([^\]]+)"\]/', '<a href="$1" target="_blank">', $summary);
$summary = preg_replace('/\[url=([^\]]+)\]/', '<a href="$1" target="_blank">', $summary);
$summary = str_replace("[/url]", '</a>', $summary);
$summary = str_replace("[b]", '<strong>', $summary);
$summary = str_replace("[/b]", '</strong>', $summary);
$summary = '<p>'.$summary.'</p>';
$newsCache[$topic_id]['summary_html'] = $summary;
// details parse
if (isset($_POST['details'])) {
$details = $_POST['details'];
if ($details) {
$newsCache[$topic_id]['details'] = $details;
$details = str_replace("\r", '', $details);
$details = str_replace("\n\n", '</p><p>', $details);
$details = str_replace("\n", '<br />', $details);
$details = str_replace("\n", '<br />', $details);
$details = preg_replace('/\[url="([^\]]+)"\]/', '<a href="$1" target="_blank">', $details);
$details = preg_replace('/\[url=([^\]]+)\]/', '<a href="$1" target="_blank">', $details);
$details = str_replace("[/url]", '</a>', $details);
$details = str_replace("[b]", '<strong>', $details);
$details = str_replace("[/b]", '</strong>', $details);
$details = '<p>'.$details.'</p>';
$newsCache[$topic_id]['details_html'] = $details;
} else {
unset($newsCache[$topic_id]['details']);
unset($newsCache[$topic_id]['details_html']);
}
}
if ($title) {
$newsCache[$topic_id]['title'] = $title;
$newsCache[$topic_id]['title_html'] = htmlspecialchars($title);
}
saveNews();
echo '<p>Edit successful</p>';
}
if (@$_POST['act'] === 'newentry') {
if (!$users->csrfCheck()) die('csrf error');
$topic_id = intval($latestNewsCache[0]) + 1;
$title = $_POST['title'];
$summary = $_POST['summary'];
$pre_summary = $summary;
$summary = str_replace("\r", '', $summary);
$summary = str_replace("\n\n", '</p><p>', $summary);
$summary = str_replace("\n", '<br />', $summary);
$summary = str_replace("\n", '<br />', $summary);
$summary = preg_replace('/\[url=([^\]]+)\]/', '<a href="$1" target="_blank">', $summary);
$summary = str_replace("[/url]", '</a>', $summary);
$summary = str_replace("[b]", '<strong>', $summary);
$summary = str_replace("[/b]", '</strong>', $summary);
$summary = '<p>'.$summary.'</p>';
$time = ''.time();
$newsCache[$topic_id] = array(
'topic_id' => ''.$topic_id,
'title' => $title,
'authorname' => $curuser['username'],
'date' => $time,
'topic_time' => $time,
'summary' => $pre_summary,
'summary_html' => $summary,
'title_html' => htmlspecialchars($title),
);
array_unshift($latestNewsCache, ''.$topic_id);
saveNews();
echo '<p>New post successful</p>';
}
foreach ($latestNewsCache as $i => $topic_id) {
$topic = $newsCache[$topic_id];
?>
<p>
<h1><?php echo $topic['title_html']; ?></h1>
<p>
<button onclick="$('#editform-<?= $topic_id ?>').show(); return false">Edit</button>
</p>
<form id="editform-<?= $topic_id ?>" style="display:none" method="post">
<input type="hidden" name="act" value="editentry" /><input type="hidden" name="topic_id" value="<?= $topic_id ?>" /><?php $users->csrfData(); ?>
<input type="text" name="title" size="80" placeholder="Title" value="<?= htmlspecialchars($topic['title']) ?>" /><br /><br />
<textarea name="summary" cols="80" rows="10" placeholder="Summary"><?= htmlspecialchars(@$topic['summary']) ?></textarea>
<?php if (isset($topic['details'])) { ?>
<textarea name="details" cols="80" rows="10" placeholder="Details"><?= htmlspecialchars(@$topic['details']) ?></textarea>
<?php } else { ?>
<textarea name="details" cols="80" rows="10" placeholder="Details" style="display:none"></textarea><button onclick="$(this).prev().show();$(this).hide();return false">Add "read more" details</button>
<?php } ?>
<br /><button type="submit"><strong>Make Edit</strong></button>
</form>
<?php echo @$topic['summary_html'] ?>
<p>
—<?php echo $topic['authorname']; ?> on <small class="date"><?php echo readableDate($topic['date']); ?></small></small>
</p>
</p>
<?php
}
?>
</div>
<script src="/js/jquery-1.9.1.min.js"></script>
<?php
includeFooter();
?>
| agpl-3.0 |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/utilities/smoke-test-librarian.py | 779 | #! /usr/bin/python -S
#
# Copyright 2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Perform simple librarian operations to verify the current configuration.
"""
import _pythonpath
import sys
from zope.component import getUtility
from lp.services.librarian.interfaces.client import (
ILibrarianClient,
IRestrictedLibrarianClient,
)
from lp.services.librarian.smoketest import do_smoketest
from lp.services.scripts import execute_zcml_for_scripts
if __name__ == '__main__':
execute_zcml_for_scripts()
restricted_client = getUtility(IRestrictedLibrarianClient)
regular_client = getUtility(ILibrarianClient)
sys.exit(do_smoketest(restricted_client, regular_client))
| agpl-3.0 |
amdw/gopoker | poker/testhelpers.go | 6913 | /*
Copyright 2017 Andrew Medworth
This file is part of Gopoker, a set of miscellaneous poker-related functions
written in the Go programming language (http://golang.org).
Gopoker 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.
Gopoker 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 Gopoker. If not, see <http://www.gnu.org/licenses/>.
*/
package poker
import (
"fmt"
"math"
"reflect"
"testing"
)
func TestMakeHand(cards ...string) []Card {
result := make([]Card, len(cards))
for i, c := range cards {
result[i] = C(c)
}
return result
}
var h = TestMakeHand // Helper for tests in this package
func TestMakeHands(hands ...[]Card) [][]Card {
return hands
}
func parseHandClass(handClassStr string) HandClass {
switch handClassStr {
case "StraightFlush":
return StraightFlush
case "FourOfAKind":
return FourOfAKind
case "FullHouse":
return FullHouse
case "Flush":
return Flush
case "Straight":
return Straight
case "ThreeOfAKind":
return ThreeOfAKind
case "TwoPair":
return TwoPair
case "OnePair":
return OnePair
case "HighCard":
return HighCard
default:
panic(fmt.Sprintf("Unknown hand class %v", handClassStr))
}
}
func TestMakeHandLevel(handClassStr string, tieBreakRankStrs ...string) HandLevel {
class := parseHandClass(handClassStr)
tieBreaks := make([]Rank, len(tieBreakRankStrs))
for i, rankStr := range tieBreakRankStrs {
var err error
tieBreaks[i], err = MakeRank(rankStr)
if err != nil {
panic(fmt.Sprintf("Cannot parse rank %v", rankStr))
}
}
return HandLevel{class, tieBreaks}
}
var hl = TestMakeHandLevel // Helper for tests in this package
func TestMakeHandLevels(levels ...HandLevel) []HandLevel {
return levels
}
// Check equality of sets of cards, ignoring ordering (mutates inputs)
func CardsEqual(c1, c2 []Card) bool {
SortCards(c1, false)
SortCards(c2, false)
return reflect.DeepEqual(c1, c2)
}
// Assert that the pack contains exactly one of every card
func TestPackPermutation(pack *Pack, t *testing.T) {
permCheck := make([][]int, 4)
for i := 0; i < 4; i++ {
permCheck[i] = make([]int, 13)
}
for _, c := range pack.Cards {
permCheck[c.Suit][c.Rank]++
}
for s := range permCheck {
for r, count := range permCheck[s] {
if count != 1 {
t.Fatalf("Expected exactly one %v%v in pack after shuffle, found %v", Rank(r).String(), Suit(s).String(), count)
}
}
}
}
func TestAssertPotsWonSanity(winCount int, potsWon float64, description string, t *testing.T) {
if potsWon > float64(winCount) || potsWon < 0 || (winCount > 0 && math.Abs(potsWon) < 1e-6) {
t.Errorf("Illogical pot win total %v for %v (win count %v)", potsWon, description, winCount)
}
}
func TestAssertSimSanity(sim *Simulator, players, simulations int, t *testing.T) {
if sim.Players != players {
t.Errorf("Expected %v players, found %v", players, sim.Players)
}
if sim.HandCount != simulations {
t.Errorf("Expected %v found %v for HandCount", simulations, sim.HandCount)
}
if sim.WinCount < 0 || sim.WinCount > simulations {
t.Errorf("Illogical win count %v", sim.WinCount)
}
TestAssertPotsWonSanity(sim.WinCount, sim.PotsWon, "us", t)
TestAssertPotsWonSanity(sim.BestOpponentWinCount, sim.BestOpponentPotsWon, "best opponent", t)
TestAssertPotsWonSanity(sim.RandomOpponentWinCount, sim.RandomOpponentPotsWon, "random opponent", t)
if sim.PotsWon+sim.BestOpponentPotsWon > float64(simulations) {
t.Errorf("More pots won than there were simulated hands: %v+%v vs %v", sim.PotsWon, sim.BestOpponentPotsWon, simulations)
}
betBreakEven := sim.PotOddsBreakEven()
if betBreakEven < 0 || math.IsInf(betBreakEven, -1) || math.IsNaN(betBreakEven) {
t.Errorf("Illogical pot odds break-even point: %v", betBreakEven)
}
checkCounts := func(counts []int, shouldSumToSims bool, name string) int {
if len(counts) != int(MAX_HANDCLASS) {
t.Errorf("Expected %v %v, found %v", MAX_HANDCLASS, name, len(counts))
}
sum := 0
for i, c := range counts {
if c < 0 || c > simulations {
t.Errorf("Insane value %v at %v of %v", c, i, name)
}
sum += c
}
if sum > simulations {
t.Errorf("Insane sum %v for %v", sum, name)
}
if shouldSumToSims && sum != simulations {
t.Errorf("Expected sum %v for %v, found %v", simulations, name, sum)
}
return sum
}
checkCounts(sim.OurClassCounts, true, "OurClassCounts")
checkCounts(sim.BestOpponentClassCounts, true, "BestOpponentClassCounts")
checkCounts(sim.RandomOpponentClassCounts, true, "RandomOpponentClassCounts")
ourWins := checkCounts(sim.ClassWinCounts, false, "ClassWinCounts")
jointWins := checkCounts(sim.ClassJointWinCounts, false, "ClassJointWinCounts")
bestOppWins := checkCounts(sim.ClassBestOppWinCounts, false, "ClassBestOppWinCounts")
if ourWins != sim.WinCount {
t.Errorf("Class win counts should sum to %v, found %v", sim.WinCount, ourWins)
}
if jointWins != sim.JointWinCount {
t.Errorf("Class joint win counts should sum to %v, found %v", sim.JointWinCount, jointWins)
}
if bestOppWins != sim.BestOpponentWinCount {
t.Errorf("Best opponent win counts should sum to %v, found %v", sim.BestOpponentWinCount, bestOppWins)
}
if ourWins+bestOppWins-sim.JointWinCount != simulations {
t.Errorf("Our wins (%v) and opponent wins (%v) minus joint wins (%v) sum to %v, expected %v", ourWins, bestOppWins, sim.JointWinCount, ourWins+bestOppWins-sim.JointWinCount, simulations)
}
randOppWins := checkCounts(sim.ClassRandOppWinCounts, false, "ClassRandOppWinCounts")
if randOppWins != sim.RandomOpponentWinCount {
t.Errorf("Random opponent wins %v but classes sum to %v", sim.RandomOpponentWinCount, randOppWins)
}
if randOppWins > bestOppWins {
t.Errorf("Random opponent won more than best opponent (%v vs %v)", randOppWins, bestOppWins)
}
for c, l := range sim.ClassBestHands {
if Beats(l, sim.BestHand) {
t.Errorf("Best hand %v of class %v better than overall best %v", l, c, sim.BestHand)
}
}
for c, l := range sim.ClassBestOppHands {
if Beats(l, sim.BestOppHand) {
t.Errorf("Best opponent hand %v of class %v better than overall best %v", l, c, sim.BestOppHand)
}
}
checkTiebreaks := func(tbs []Rank, name string) {
if len(tbs) != 5 {
t.Errorf("Expected 5 tiebreaks for %v, found %v", name, len(tbs))
}
}
// Catches error with best-hand zero value
checkTiebreaks(sim.ClassBestHands[HighCard].Tiebreaks, "high-card best hands")
checkTiebreaks(sim.ClassBestOppHands[HighCard].Tiebreaks, "high-card opponent best hands")
}
| agpl-3.0 |
AegisEmu/AegisEmu | src/arcemu-world/LogonCommHandler.cpp | 13213 | /*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008 <http://www.ArcEmu.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
* 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 "StdAfx.h"
initialiseSingleton(LogonCommHandler);
#ifndef CLUSTERING
LogonCommHandler::LogonCommHandler()
{
idhigh = 1;
next_request = 1;
pings = !Config.MainConfig.GetBoolDefault("LogonServer", "DisablePings", false);
string logon_pass = Config.MainConfig.GetStringDefault("LogonServer", "RemotePassword", "r3m0t3");
// sha1 hash it
Sha1Hash hash;
hash.UpdateData(logon_pass);
hash.Finalize();
memset(sql_passhash,0,20);
memcpy(sql_passhash, hash.GetDigest(), 20);
// cleanup
servers.clear();
realms.clear();
}
LogonCommHandler::~LogonCommHandler()
{
for(set<LogonServer*>::iterator i = servers.begin(); i != servers.end(); ++i)
delete (*i);
for(set<Realm*>::iterator i = realms.begin(); i != realms.end(); ++i)
delete (*i);
}
LogonCommClientSocket * LogonCommHandler::ConnectToLogon(string Address, uint32 Port)
{
LogonCommClientSocket * conn = ConnectTCPSocket<LogonCommClientSocket>(Address.c_str(), Port);
return conn;
}
void LogonCommHandler::RequestAddition(LogonCommClientSocket * Socket)
{
set<Realm*>::iterator itr = realms.begin();
for(; itr != realms.end(); ++itr)
{
WorldPacket data(RCMSG_REGISTER_REALM, 100);
// Add realm to the packet
Realm * realm = *itr;
data << realm->Name;
data << realm->Address;
data << uint8(realm->Icon);
data << uint8(realm->TimeZone);
data << float(realm->Population);
data << uint8(realm->Lock);
Socket->SendPacket(&data,false);
}
}
class LogonCommWatcherThread : public ThreadBase
{
bool running;
#ifdef WIN32
HANDLE hEvent;
#endif
public:
LogonCommWatcherThread()
{
#ifdef WIN32
hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
#endif
running = true;
}
~LogonCommWatcherThread()
{
}
void OnShutdown()
{
running = false;
#ifdef WIN32
SetEvent( hEvent );
#endif
}
bool run()
{
sLogonCommHandler.ConnectAll();
while( running )
{
sLogonCommHandler.UpdateSockets();
#ifdef WIN32
WaitForSingleObject( hEvent, 5000 );
#else
Sleep( 5000 );
#endif
}
return true;
}
};
void LogonCommHandler::Startup()
{
// Try to connect to all logons.
LoadRealmConfiguration();
Log.Notice("LogonCommClient", "Loading forced permission strings...");
QueryResult * result = CharacterDatabase.Query("SELECT * FROM account_forced_permissions");
if( result != NULL )
{
do
{
string acct = result->Fetch()[0].GetString();
string perm = result->Fetch()[1].GetString();
arcemu_TOUPPER(acct);
forced_permissions.insert(make_pair(acct,perm));
} while (result->NextRow());
delete result;
}
ThreadPool.ExecuteTask( new LogonCommWatcherThread() );
}
void LogonCommHandler::ConnectAll()
{
Log.Notice("LogonCommClient", "Attempting to connect to logon server...");
for(set<LogonServer*>::iterator itr = servers.begin(); itr != servers.end(); ++itr)
Connect(*itr);
}
const string* LogonCommHandler::GetForcedPermissions(string& username)
{
ForcedPermissionMap::iterator itr = forced_permissions.find(username);
if(itr == forced_permissions.end())
return NULL;
return &itr->second;
}
void LogonCommHandler::Connect(LogonServer * server)
{
if(sMaster.m_ShutdownEvent == true && sMaster.m_ShutdownTimer <= 120000) // 2minutes
return;
server->RetryTime = (uint32)UNIXTIME + 10;
server->Registered = false;
LogonCommClientSocket * conn = ConnectToLogon(server->Address, server->Port);
logons[server] = conn;
if(conn == 0)
{
Log.Notice("LogonCommClient", "Connection failed. Will try again in 10 seconds.");
return;
}
Log.Notice("LogonCommClient", "Authenticating...");
uint32 tt = (uint32)UNIXTIME + 10;
conn->SendChallenge();
while(!conn->authenticated)
{
if((uint32)UNIXTIME >= tt)
{
Log.Notice("LogonCommClient", "Authentication timed out.");
conn->Disconnect();
logons[server]=NULL;
return;
}
Sleep(50);
}
if(conn->authenticated != 1)
{
Log.Notice("LogonCommClient","Authentication failed.");
logons[server] = 0;
conn->Disconnect();
return;
}
Log.Notice("LogonCommClient","Authentication OK.");
Log.Notice("LogonCommClient", "Logonserver was connected on [%s:%u].", server->Address.c_str(), server->Port );
// Send the initial ping
conn->SendPing();
Log.Notice("LogonCommClient", "Registering Realms...");
conn->_id = server->ID;
RequestAddition(conn);
uint32 st = (uint32)UNIXTIME + 10;
// Wait for register ACK
while(server->Registered == false)
{
// Don't wait more than.. like 10 seconds for a registration
if((uint32)UNIXTIME >= st)
{
Log.Notice("LogonCommClient", "Realm registration timed out.");
logons[server] = 0;
conn->Disconnect();
break;
}
Sleep(50);
}
if(!server->Registered)
return;
// Wait for all realms to register
Sleep(200);
Log.Notice("LogonCommClient", "Logonserver latency is %ums.", conn->latency);
}
void LogonCommHandler::AdditionAck(uint32 ID, uint32 ServID)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
for(; itr != logons.end(); ++itr)
{
if(itr->first->ID == ID)
{
itr->first->ServerID = ServID;
itr->first->Registered = true;
return;
}
}
}
void LogonCommHandler::UpdateSockets()
{
mapLock.Acquire();
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
LogonCommClientSocket * cs;
uint32 t = (uint32)UNIXTIME;
for(; itr != logons.end(); ++itr)
{
cs = itr->second;
if(cs != 0)
{
if(!pings) continue;
if(cs->IsDeleted() || !cs->IsConnected())
{
cs->_id = 0;
itr->second = 0;
continue;
}
if(cs->last_pong < t && ((t - cs->last_pong) > 60))
{
// no pong for 60 seconds -> remove the socket
printf(" >> realm id %u connection dropped due to pong timeout.\n", (unsigned int)itr->first->ID);
cs->_id = 0;
cs->Disconnect();
itr->second = 0;
continue;
}
if( (t - cs->last_ping) > 15 )
{
// send a ping packet.
cs->SendPing();
}
}
else
{
// check retry time
if(t >= itr->first->RetryTime)
{
Connect(itr->first);
}
}
}
mapLock.Release();
}
void LogonCommHandler::ConnectionDropped(uint32 ID)
{
mapLock.Acquire();
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
for(; itr != logons.end(); ++itr)
{
if(itr->first->ID == ID && itr->second != 0)
{
sLog.outColor(TNORMAL, " >> realm id %u connection was dropped unexpectedly. reconnecting next loop.", ID);
sLog.outColor(TNORMAL, "\n");
itr->second = 0;
break;
}
}
mapLock.Release();
}
uint32 LogonCommHandler::ClientConnected(string AccountName, WorldSocket * Socket)
{
uint32 request_id = next_request++;
size_t i = 0;
const char * acct = AccountName.c_str();
sLog.outDebug ( " >> sending request for account information: `%s` (request %u).", AccountName.c_str(), request_id);
// sLog.outColor(TNORMAL, "\n");
// Send request packet to server.
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0)
{
// No valid logonserver is connected.
return (uint32)-1;
}
LogonCommClientSocket * s = itr->second;
if( s == NULL )
return (uint32)-1;
pendingLock.Acquire();
WorldPacket data(RCMSG_REQUEST_SESSION, 100);
data << request_id;
// strip the shitty hash from it
for(; acct[i] != '#' && acct[i] != '\0'; ++i )
data.append( &acct[i], 1 );
data.append( "\0", 1 );
s->SendPacket(&data,false);
pending_logons[request_id] = Socket;
pendingLock.Release();
return request_id;
}
void LogonCommHandler::UnauthedSocketClose(uint32 id)
{
pendingLock.Acquire();
pending_logons.erase(id);
pendingLock.Release();
}
void LogonCommHandler::RemoveUnauthedSocket(uint32 id)
{
pending_logons.erase(id);
}
void LogonCommHandler::LoadRealmConfiguration()
{
LogonServer * ls = new LogonServer;
ls->ID = idhigh++;
ls->Name = Config.RealmConfig.GetStringDefault("LogonServer", "Name", "UnkLogon");
ls->Address = Config.RealmConfig.GetStringDefault("LogonServer", "Address", "127.0.0.1");
ls->Port = Config.RealmConfig.GetIntDefault("LogonServer", "Port", 8093);
servers.insert(ls);
uint32 realmcount = Config.RealmConfig.GetIntDefault("LogonServer", "RealmCount", 1);
if(realmcount == 0)
{
sLog.outColor(TRED, "\n >> no realms found. this server will not be online anywhere!\n");
}
else
{
for(uint32 i = 1; i < realmcount+1; ++i)
{
Realm * realm = new Realm;
realm->Name = Config.RealmConfig.GetStringVA("Name", "SomeRealm", "Realm%u", i);
realm->Address = Config.RealmConfig.GetStringVA("Address", "127.0.0.1:8129", "Realm%u", i);
realm->TimeZone = Config.RealmConfig.GetIntVA("TimeZone", 1, "Realm%u", i);
realm->Population = Config.RealmConfig.GetFloatVA("Population", 0, "Realm%u", i);
realm->Lock = Config.RealmConfig.GetIntVA("Lock", 0, "Realm%u", i);
string rt = Config.RealmConfig.GetStringVA("Icon", "Normal", "Realm%u", i);
uint32 type;
// process realm type
if( stricmp(rt.c_str(), "pvp")==0 )
type = REALMTYPE_PVP;
else if( stricmp(rt.c_str(), "rp")==0 )
type = REALMTYPE_RP;
else if( stricmp(rt.c_str(), "rppvp")==0 )
type = REALMTYPE_RPPVP;
else
type = REALMTYPE_NORMAL;
_realmType = type;
realm->Icon = type;
realms.insert(realm);
}
}
}
void LogonCommHandler::UpdateAccountCount(uint32 account_id, uint8 add)
{
// Send request packet to server.
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
itr->second->UpdateAccountCount(account_id, add);
}
void LogonCommHandler::TestConsoleLogon(string& username, string& password, uint32 requestnum)
{
string newuser = username;
string newpass = password;
string srpstr;
arcemu_TOUPPER(newuser);
arcemu_TOUPPER(newpass);
srpstr = newuser + ":" + newpass;
// Send request packet to server.
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
Sha1Hash hash;
hash.UpdateData(srpstr);
hash.Finalize();
WorldPacket data(RCMSG_TEST_CONSOLE_LOGIN, 100);
data << requestnum;
data << newuser;
data.append(hash.GetDigest(), 20);
itr->second->SendPacket(&data, false);
}
// db funcs
void LogonCommHandler::Account_SetBanned(const char * account, uint32 banned, const char *reason)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 300);
data << uint32(1); // 1 = ban
data << account;
data << banned;
data << reason;
itr->second->SendPacket(&data, false);
}
void LogonCommHandler::Account_SetGM(const char * account, const char * flags)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 50);
data << uint32(2); // 2 = set gm
data << account;
data << flags;
itr->second->SendPacket(&data, false);
}
void LogonCommHandler::Account_SetMute(const char * account, uint32 muted)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 50);
data << uint32(3); // 3 = mute
data << account;
data << muted;
itr->second->SendPacket(&data, false);
}
void LogonCommHandler::IPBan_Add(const char * ip, uint32 duration,const char *reason)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 300);
data << uint32(4); // 4 = ipban add
data << ip;
data << duration;
data << reason;
itr->second->SendPacket(&data, false);
}
void LogonCommHandler::IPBan_Remove(const char * ip)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 50);
data << uint32(5); // 5 = ipban remove
data << ip;
itr->second->SendPacket(&data, false);
}
#endif
| agpl-3.0 |
Hoot215/TheWalls2 | src/me/Hoot215/TheWalls2/TheWalls2PlayerListener.java | 16241 | /*
* TheWalls2: The Walls 2 plugin. Copyright (C) 2012 Andrew Stevanus (Hoot215)
* <hoot893@gmail.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 me.Hoot215.TheWalls2;
import java.util.List;
import java.util.Random;
import me.Hoot215.TheWalls2.util.AutoUpdater;
import me.Hoot215.TheWalls2.util.Teleport;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
public class TheWalls2PlayerListener implements Listener
{
private TheWalls2 plugin;
public TheWalls2PlayerListener(TheWalls2 instance)
{
plugin = instance;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockBreak (BlockBreakEvent event)
{
Player player = event.getPlayer();
TheWalls2GameList gameList = plugin.getGameList();
if (player.getWorld().getName().equals(TheWalls2.worldName))
{
if (gameList == null)
{
if (plugin.getQueue().isInQueue(player.getName()))
{
event.setCancelled(true);
player.sendMessage(ChatColor.RED
+ "You can't do that until the game starts!");
return;
}
}
else if (gameList.isInGame(player.getName()))
{
if (plugin.getLocationData().isPartOfWall(
event.getBlock().getLocation()))
{
event.setCancelled(true);
player
.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
for (Location loc : plugin.getLocationData().getSlots())
{
if (loc.getBlockX() == event.getBlock().getX()
&& loc.getBlockZ() == event.getBlock().getZ())
{
event.setCancelled(true);
player.sendMessage(ChatColor.RED
+ "Don't break the rules!");
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPlace (BlockPlaceEvent event)
{
Player player = event.getPlayer();
TheWalls2GameList gameList = plugin.getGameList();
if (player.getWorld().getName().equals(TheWalls2.worldName))
{
if (gameList == null)
{
if (plugin.getQueue().isInQueue(player.getName()))
{
event.setCancelled(true);
player.sendMessage(ChatColor.RED
+ "You can't do that until the game starts!");
return;
}
}
else if (gameList.isInGame(player.getName()))
{
if (plugin.getLocationData().isPartOfWall(
event.getBlock().getLocation()))
{
event.setCancelled(true);
player
.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
if (event.getBlock().getY() > 93)
{
event.setCancelled(true);
player
.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
for (Location loc : plugin.getLocationData().getSlots())
{
if (loc.getBlockX() == event.getBlock().getX()
&& loc.getBlockZ() == event.getBlock().getZ())
{
event.setCancelled(true);
player.sendMessage(ChatColor.RED
+ "Don't break the rules!");
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract (PlayerInteractEvent event)
{
Player player = event.getPlayer();
if (player.getWorld().getName().equals(TheWalls2.worldName))
{
TheWalls2GameList gameList = plugin.getGameList();
if (gameList == null)
{
if (plugin.getQueue().isInQueue(player.getName()))
{
event.setCancelled(true);
player.sendMessage(ChatColor.RED
+ "You can't do that until the game starts!");
}
}
else
{
if (player.getItemInHand().getType() != Material.COMPASS
|| !gameList.isInGame(player.getName()))
return;
Player randomPlayer = null;
int count = 0;
while (true)
{
List<Player> playerList = player.getWorld().getPlayers();
int playerCount = playerList.size();
int randomInt = new Random().nextInt(playerCount);
randomPlayer = playerList.get(randomInt);
if (randomPlayer != player)
break;
if (count >= 20)
{
player.sendMessage(ChatColor.RED + "Either you are "
+ "extremely unlucky or there is no one else "
+ "playing with you!");
return;
}
count++;
}
player.setCompassTarget(randomPlayer.getLocation());
player.sendMessage(ChatColor.GREEN + "Random player located!");
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityDamageByEntity (EntityDamageByEntityEvent event)
{
if ( ! (event.getEntity() instanceof Player))
return;
Player player = (Player) event.getEntity();
if (player.getWorld().getName().equals(TheWalls2.worldName))
{
if (plugin.getGameList() == null)
{
if (plugin.getQueue().isInQueue(player.getName()))
{
event.setCancelled(true);
}
}
else
{
if ( ! (event.getDamager() instanceof Player))
return;
if ( !plugin.getConfig().getBoolean("general.friendly-fire"))
{
Player attacker = (Player) event.getDamager();
TheWalls2GameTeams teams = plugin.getGameTeams();
if (plugin.getGameList().isInGame(player.getName())
&& plugin.getGameList().isInGame(attacker.getName()))
{
if (teams.compareTeams(player.getName(),
attacker.getName()))
{
event.setCancelled(true);
}
attacker.sendMessage(ChatColor.RED
+ "Friendly fire is disabled!");
}
}
}
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerDeath (PlayerDeathEvent event)
{
Player player = event.getEntity();
String playerName = player.getName();
TheWalls2GameList gameList = plugin.getGameList();
TheWalls2PlayerQueue queue = plugin.getQueue();
TheWalls2RespawnQueue respawnQueue = plugin.getRespawnQueue();
if (gameList == null)
return;
if (gameList.isInGame(playerName))
{
plugin.getServer().broadcastMessage(
ChatColor.YELLOW + playerName + ChatColor.RED
+ " has been defeated in " + "a game of The Walls 2!");
gameList.removeFromGame(playerName);
respawnQueue.addPlayer(playerName,
queue.getLastPlayerLocation(playerName));
plugin.checkIfGameIsOver();
return;
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit (PlayerQuitEvent event)
{
Player player = event.getPlayer();
final String playerName = player.getName();
TheWalls2GameList gameList = plugin.getGameList();
TheWalls2PlayerQueue queue = plugin.getQueue();
if (gameList == null)
{
if (queue.isInQueue(playerName))
{
queue.removePlayer(playerName, true);
return;
}
return;
}
if (gameList.isInGame(playerName))
{
int time = plugin.getConfig().getInt("general.disconnect-timer");
plugin.getServer().broadcastMessage(
ChatColor.YELLOW + playerName + ChatColor.RED
+ " has disconnected! " + "They have "
+ String.valueOf(time)
+ " seconds to reconnect before they quit The Walls 2");
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run ()
{
TheWalls2GameList futureGameList = plugin.getGameList();
if (futureGameList == null)
return;
if (plugin.getServer().getPlayer(playerName) == null)
{
futureGameList.removeFromGame(playerName);
plugin.getServer().broadcastMessage(
ChatColor.YELLOW + playerName + ChatColor.RED
+ " has forfeit The Walls 2");
plugin.checkIfGameIsOver();
}
}
}, time * 20);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn (PlayerRespawnEvent event)
{
Player player = event.getPlayer();
String playerName = player.getName();
TheWalls2RespawnQueue respawnQueue = plugin.getRespawnQueue();
if (respawnQueue.isInRespawnQueue(playerName))
{
event.setRespawnLocation(respawnQueue
.getLastPlayerLocation(playerName));
respawnQueue.removePlayer(playerName);
player.getInventory().setContents(
plugin.getInventory().getInventoryContents(playerName));
player.getInventory().setArmorContents(
plugin.getInventory().getArmourContents(playerName));
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin (PlayerJoinEvent event)
{
Player player = event.getPlayer();
final String playerName = player.getName();
TheWalls2GameList gameList = plugin.getGameList();
TheWalls2PlayerQueue queue = plugin.getQueue();
if (gameList == null)
{
if (player.getWorld().getName().equals(TheWalls2.worldName))
{
if ( !queue.isInQueue(playerName))
{
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run ()
{
Player futurePlayer =
plugin.getServer().getPlayer(playerName);
if (futurePlayer == null)
return;
Location loc =
plugin.getServer()
.getWorld(TheWalls2.fallbackWorldName)
.getSpawnLocation();
Teleport.teleportPlayerToLocation(futurePlayer,
loc);
futurePlayer.sendMessage(ChatColor.AQUA
+ "[TheWalls2] " + ChatColor.GREEN
+ "You have been teleported "
+ "to a fallback world because you "
+ "left while a game was in progress");
}
}, 1L);
}
}
}
else
{
if ( !gameList.isInGame(playerName) && queue.isInQueue(playerName))
{
queue.removePlayer(playerName, true);
player.getInventory().setContents(
plugin.getInventory().getInventoryContents(playerName));
player.getInventory().setArmorContents(
plugin.getInventory().getArmourContents(playerName));
}
}
AutoUpdater autoUpdater = plugin.getAutoUpdater();
synchronized (autoUpdater.getLock())
{
if (player.hasPermission("thewalls2.notify"))
{
if ( !AutoUpdater.getIsUpToDate())
{
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run ()
{
Player player =
plugin.getServer().getPlayer(playerName);
if (player == null)
return;
player.sendMessage(ChatColor.AQUA
+ "[TheWalls2] " + ChatColor.GREEN
+ "An update is available!");
player
.sendMessage(ChatColor.WHITE
+ "http://dev.bukkit.org/server-mods/thewalls2/");
player.sendMessage(ChatColor.RED
+ "If you can't find a newer version, "
+ "check in the comments section for a "
+ "Dropbox link");
}
}, 60L);
}
}
}
}
} | agpl-3.0 |
tcitworld/FaceClone | Model/Post.php | 1541 | <?php
class Post {
private $idpost;
private $idmembre;
private $contenupost;
private $datemessage;
private $database;
private $user;
private $likes;
private $comments;
private $attachment;
function __construct($idpost) {
$this->idpost = $idpost;
$this->database = new Database();
$post = $this->database->getPost($idpost);
$this->idmembre = $post['idmembre'];
$this->user = new User($this->database->getMailForId($this->idmembre)[0]);
$this->contenupost = $post['contenupost'];
$this->datemessage = $post['datemessage'];
$this->attachment = new Attachment($post['attachment']);
/*
Convert id $peopleliking from database to proper User objects
*/
$peopleliking = $this->database->getLikes($this->idpost);
foreach ($peopleliking as $people) {
$this->likes[] = new User($this->database->getMailForId($people['idmembre'])[0]);
}
/*
Convert id $comments from database to proper Comments objects
*/
$comments = $this->database->getComments($this->idpost);
foreach ($comments as $comment) {
$this->comments[] = new Comment($comment);
}
}
public function getUser() {
return $this->user;
}
public function getContenuPost() {
return $this->contenupost;
}
public function getDateMessage() {
return $this->datemessage;
}
public function getid() {
return $this->idpost;
}
public function getLikes() {
return $this->likes;
}
public function getComments() {
return $this->comments;
}
public function getAttachment() {
return $this->attachment;
}
} | agpl-3.0 |
wojons/rethinkdb | test/interface/precise_stats.py | 8282 | #!/usr/bin/env python
# Copyright 2010-2012 RethinkDB, all rights reserved.
# This file tests the `rethinkdb.stats` admin table.
# Here, we run very particular queries and verify that the 'total' stats are exactly
# correct. This includes point reads/writes, range reads/replaces, backfills, and
# sindex construction.
from __future__ import print_function
import sys, os, time, re, multiprocessing, random, pprint
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import driver, scenario_common, utils, vcoptparse, workload_runner
r = utils.import_python_driver()
db_name = 'test'
table_name = 'foo'
server_names = ['grey', 'face']
op = vcoptparse.OptParser()
scenario_common.prepare_option_parser_mode_flags(op)
opts = op.parse(sys.argv)
with driver.Metacluster() as metacluster:
cluster = driver.Cluster(metacluster)
_, command_prefix, serve_options = scenario_common.parse_mode_flags(opts)
print('Spinning up %d processes...' % len(server_names))
servers = [ ]
for i in xrange(len(server_names)):
info = { 'name': server_names[i] }
info['files'] = driver.Files(metacluster, db_path='db-%d' % i,
console_output='create-output-%d' % i,
server_name=info['name'], command_prefix=command_prefix)
info['process'] = driver.Process(cluster, info['files'],
console_output='serve-output-%d' % i,
command_prefix=command_prefix, extra_options=serve_options)
servers.append(info)
for server in servers:
server['process'].wait_until_started_up()
r.connect(servers[0]['process'].host, servers[0]['process'].driver_port).repl()
r.db_create(db_name).run()
r.db(db_name).table_create(table_name).run()
tbl = r.db(db_name).table(table_name)
table_id = tbl.config()['id'].run()
for server in servers:
server['id'] = r.db('rethinkdb').table('server_config') \
.filter(r.row['name'].eq(server['name']))[0]['id'].run()
def get_stats(server):
return r.db('rethinkdb').table('stats').get(['table_server', table_id, server['id']]) \
.do({'reads': r.row['query_engine']['read_docs_total'],
'writes': r.row['query_engine']['written_docs_total']}).run ()
def check_stats_internal(query, reads, writes):
stats = get_stats(servers[0])
delta_reads = stats['reads'] - check_stats_internal.last_reads
delta_writes = stats['writes'] - check_stats_internal.last_writes
if delta_reads != reads:
print('Error in query %s: Expected %d reads but got %d' %
(r.errors.QueryPrinter(query).print_query(), reads, delta_reads))
if delta_writes != writes:
print('Error in query %s: Expected %d writes but got %d' %
(r.errors.QueryPrinter(query).print_query(), writes, delta_writes))
check_stats_internal.last_reads = stats['reads']
check_stats_internal.last_writes = stats['writes']
check_stats_internal.last_reads = 0
check_stats_internal.last_writes = 0
def check_error_stats(query, reads=0, writes=0):
try:
query.run()
print("Failed to error in query (%s)", r.errors.QueryPrinter(query).print_query())
except r.RqlError as e:
pass
check_stats_internal(query, reads, writes)
def check_query_stats(query, reads=0, writes=0):
query.run()
check_stats_internal(query, reads, writes)
def primary_shard(server):
return { 'primary_replica': server['name'], 'replicas': [ server['name'] ] }
# Pin the table to one server
tbl.config().update({'shards': [ primary_shard(servers[0]) ]}).run()
tbl.wait().run()
# Create a secondary index that will be used in some of the inserts
check_query_stats(tbl.index_create('double', r.row['id']), reads=0, writes=0)
check_query_stats(tbl.index_create('value'), reads=0, writes=0)
# batch of writes
check_query_stats(tbl.insert(r.range(100).map(lambda x: {'id': x})), writes=100)
# point operations
check_query_stats(tbl.insert({'id': 100}), reads=0, writes=1)
check_query_stats(tbl.get(100).delete(), reads=0, writes=1)
check_query_stats(tbl.get(50), reads=1, writes=0)
check_query_stats(tbl.get(101).replace({'id': 101}), reads=0, writes=1)
check_query_stats(tbl.get(101).delete(), reads=0, writes=1)
# point writes with changed rows
check_query_stats(tbl.get(50).update({'value': 'dummy'}), reads=0, writes=1)
check_query_stats(tbl.get(50).replace({'id': 50}), reads=0, writes=1)
check_query_stats(tbl.get(50).update(lambda x: {'value': 'dummy'}), reads=0, writes=1)
check_query_stats(tbl.get(50).replace(lambda x: {'id': 50}), reads=0, writes=1)
# point writes with unchanged rows
check_query_stats(tbl.get(50).update({}), reads=0, writes=1)
check_query_stats(tbl.get(50).update(lambda x: {}), reads=0, writes=1)
check_query_stats(tbl.get(50).replace({'id': 50}), reads=0, writes=1)
check_query_stats(tbl.get(50).replace(lambda x: x), reads=0, writes=1)
# range operations
check_query_stats(tbl.between(20, 40), reads=20, writes=0)
# range writes with some changed and some unchanged rows
check_query_stats(tbl.between(20, 40).update(r.branch(r.row['id'].mod(2).eq(1), {}, {'value': 'dummy'})),
reads=20, writes=20)
check_query_stats(tbl.between(20, 40).replace({'id': r.row['id']}), reads=20, writes=20)
# range writes with unchanged rows
check_query_stats(tbl.between(20, 40).update({}), reads=20, writes=20)
check_query_stats(tbl.between(20, 40).replace(lambda x: x), reads=20, writes=20)
# Operations with existence errors should still show up
check_query_stats(tbl.get(101), reads=1, writes=0)
check_query_stats(tbl.get(101).delete(), reads=0, writes=1)
check_query_stats(tbl.get(101).update({}), reads=0, writes=1)
check_query_stats(tbl.get(101).update(lambda x: {}), reads=0, writes=1)
check_query_stats(tbl.get(101).replace(lambda x: x), reads=0, writes=1)
check_error_stats(tbl.insert(0), reads=0, writes=1)
# Add a sindex, make sure that all rows are represented
check_query_stats(r.expr([tbl.index_create('fake', r.row['id']), tbl.index_wait()]), reads=100, writes=100)
backfiller_stats_before = get_stats(servers[0])
backfillee_stats_before = get_stats(servers[1])
# Shard the table into two shards (1 primary replica on each server)
tbl.config().update({'shards': [ primary_shard(servers[0]),
primary_shard(servers[1]) ]}).run()
tbl.wait().run()
# Manually check stats here as the number of reads/writes will be unpredictable
backfiller_stats_after = get_stats(servers[0])
backfillee_stats_after = get_stats(servers[1])
backfiller_reads = backfiller_stats_after['reads'] - backfiller_stats_before['reads']
backfiller_writes = backfiller_stats_after['writes'] - backfiller_stats_before['writes']
backfillee_reads = backfillee_stats_after['reads'] - backfillee_stats_before['reads']
backfillee_writes = backfillee_stats_after['writes'] - backfillee_stats_before['writes']
if backfiller_reads > 60 or backfiller_reads < 40: # Backfiller should transfer roughly half the rows
print("During backfill, on backfiller: Expected between 40 and 60 reads but got %d" % backfiller_reads)
if backfillee_reads != 0: # Backfillee didn't have any rows to read - we only want writes
print("During backfill, on backfillee: Expected 0 reads but got %d" % backfillee_reads)
if backfiller_writes != backfiller_reads: # Backfiller should have deleted the rows it transfered
print("During backfill, on backfiller: Expected %d writes but got %d" % (backfiller_reads, backfiller_writes))
if backfillee_writes != backfiller_reads: # Backfillee should have written the same number of rows transferred
print("During backfill, on backfillee: Expected %d writes but got %d" % (backfiller_reads, backfillee_writes))
cluster.check_and_stop()
print('Done.')
| agpl-3.0 |
nextcloud/spreed | tests/php/Command/Stun/AddTest.php | 3559 | <?php
/**
* @copyright 2018, Denis Mosolov <denismosolov@gmail.com>
*
* @author Denis Mosolov <denismosolov@gmail.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Afferoq General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Talk\Tests\php\Command\Stun;
use OCA\Talk\Command\Stun\Add;
use OCP\IConfig;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Test\TestCase;
class AddTest extends TestCase {
/** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */
private $config;
/** @var Add|\PHPUnit_Framework_MockObject_MockObject */
private $command;
/** @var InputInterface|\PHPUnit_Framework_MockObject_MockObject */
private $input;
/** @var OutputInterface|\PHPUnit_Framework_MockObject_MockObject */
private $output;
public function setUp(): void {
parent::setUp();
$this->config = $this->createMock(IConfig::class);
$this->command = new Add($this->config);
$this->input = $this->createMock(InputInterface::class);
$this->output = $this->createMock(OutputInterface::class);
}
public function testMalformedServerString() {
$this->input->method('getArgument')
->with('server')
->willReturn('stun.test.com');
$this->output->expects($this->once())
->method('writeln')
->with($this->equalTo('<error>Incorrect value. Must be stunserver:port.</error>'));
$this->config->expects($this->never())
->method('setAppValue');
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
public function testAddServerToEmptyList() {
$this->input->method('getArgument')
->with('server')
->willReturn('stun.test.com:443');
$this->config->method('getAppValue')
->with('spreed', 'stun_servers')
->willReturn(json_encode([]));
$this->config->expects($this->once())
->method('setAppValue')
->with(
$this->equalTo('spreed'),
$this->equalTo('stun_servers'),
$this->equalTo(json_encode(['stun.test.com:443']))
);
$this->output->expects($this->once())
->method('writeln')
->with($this->equalTo('<info>Added stun.test.com:443.</info>'));
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
public function testAddServerToNonEmptyList() {
$this->input->method('getArgument')
->with('server')
->willReturn('stun2.test.com:443');
$this->config->method('getAppValue')
->with('spreed', 'stun_servers')
->willReturn(json_encode(['stun1.test.com:443']));
$this->config->expects($this->once())
->method('setAppValue')
->with(
$this->equalTo('spreed'),
$this->equalTo('stun_servers'),
$this->equalTo(json_encode(['stun1.test.com:443', 'stun2.test.com:443']))
);
$this->output->expects($this->once())
->method('writeln')
->with($this->equalTo('<info>Added stun2.test.com:443.</info>'));
$this->invokePrivate($this->command, 'execute', [$this->input, $this->output]);
}
}
| agpl-3.0 |
mrexodia/fabiano-swagger-of-doom | wServer/networking/handlers/GoToQuestRoomHandler.cs | 476 | #region
using System;
using wServer.networking.cliPackets;
#endregion
namespace wServer.networking.handlers
{
internal class GoToQuestRoomHandler : PacketHandlerBase<GoToQuestRoomPacket>
{
public override PacketID ID
{
get { return PacketID.QUEST_ROOM_MSG; }
}
protected override void HandlePacket(Client client, GoToQuestRoomPacket packet)
{
throw new NotImplementedException();
}
}
} | agpl-3.0 |
denkbar/step | step-plans/step-plans-core/src/main/java/step/datapool/DataPoolConfiguration.java | 1433 | /*******************************************************************************
* Copyright (C) 2020, exense GmbH
*
* This file is part of STEP
*
* STEP 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.
*
* STEP 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 STEP. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package step.datapool;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import step.core.dynamicbeans.DynamicValue;
@JsonTypeInfo(use=Id.CLASS,property="_class")
public abstract class DataPoolConfiguration {
private DynamicValue<Boolean> forWrite = new DynamicValue<Boolean>(false);
public DynamicValue<Boolean> getForWrite() {
return forWrite;
}
public void setForWrite(DynamicValue<Boolean> forWrite) {
this.forWrite = forWrite;
}
}
| agpl-3.0 |
openego/eDisGo | edisgo/opf/results/opf_result_class.py | 10874 | import json
import pandas as pd
import logging
from edisgo.tools.preprocess_pypsa_opf_structure import (
preprocess_pypsa_opf_structure,
aggregate_fluct_generators,
)
logger = logging.getLogger("edisgo")
def read_from_json(edisgo_obj, path, mode="mv"):
"""
Read optimization results from json file.
This reads the optimization results directly from a JSON result file
without carrying out the optimization process.
Parameters
-----------
edisgo_obj : :class:`~.EDisGo`
An edisgo object with the same topology that the optimization was run
on.
path : str
Path to the optimization result JSON file.
mode : str
Voltage level, currently only supports "mv"
"""
pypsa_net = edisgo_obj.to_pypsa(
mode=mode, timesteps=edisgo_obj.timeseries.timeindex
)
timehorizon = len(pypsa_net.snapshots)
pypsa_net.name = "ding0_{}_t_{}".format(
edisgo_obj.topology.id, timehorizon
)
preprocess_pypsa_opf_structure(edisgo_obj, pypsa_net, hvmv_trafo=False)
aggregate_fluct_generators(pypsa_net)
edisgo_obj.opf_results.set_solution(path, pypsa_net)
class LineVariables:
def __init__(self):
self.p = None
self.q = None
self.cm = None
class BusVariables:
def __init__(self):
self.w = None
class GeneratorVariables:
def __init__(self):
self.pg = None
self.qg = None
class LoadVariables:
def __init__(self):
self.pd = None
self.qd = None
class StorageVariables:
def __init__(self):
self.ud = None
self.uc = None
self.soc = None
class OPFResults:
def __init__(self):
self.solution_file = None
self.solution_data = None
self.name = None
self.obj = None
self.status = None
self.solution_time = None
self.solver = None
self.lines = None
self.pypsa = None
self.lines_t = LineVariables()
self.buses_t = BusVariables()
self.generators_t = GeneratorVariables()
self.loads_t = LoadVariables()
self.storage_units = None
self.storage_units_t = StorageVariables()
def set_solution(self, solution_name, pypsa_net):
self.read_solution_file(solution_name)
self.set_solution_to_results(pypsa_net)
def read_solution_file(self, solution_name):
with open(solution_name) as json_file:
self.solution_data = json.load(json_file)
self.solution_file = solution_name
def dump_solution_file(self, solution_name=[]):
if not solution_name:
solution_name = self.solution_name
with open(solution_name, "w") as outfile:
json.dump(self.solution_data, outfile)
def set_solution_to_results(self, pypsa_net):
solution_data = self.solution_data
self.name = solution_data["name"]
self.obj = solution_data["obj"]
self.status = solution_data["status"]
self.solution_time = solution_data["sol_time"]
self.solver = solution_data["solver"]
self.pypsa = pypsa_net
# Line Variables
self.set_line_variables(pypsa_net)
# Bus Variables
self.set_bus_variables(pypsa_net)
# Generator Variables
# TODO Adjust for case that generators are fixed and no variables are returned from julia
self.set_gen_variables(pypsa_net)
self.set_load_variables(pypsa_net)
# Storage Variables
self.set_strg_variables(pypsa_net)
def set_line_variables(self, pypsa_net):
solution_data = self.solution_data
# time independent variables: ne: line expansion factor, 1.0 => no expansion
br_statics = pd.Series(
solution_data["branch"]["static"]["ne"], name="nep"
).to_frame()
br_statics.index = br_statics.index.astype(int)
br_statics = br_statics.sort_index()
br_statics.index = pypsa_net.lines.index
self.lines = br_statics
# time dependent variables: cm: squared current magnitude, p: active power flow, q: reactive power flow
ts = pypsa_net.snapshots.sort_values()
cm_t = pd.DataFrame(index=ts, columns=pypsa_net.lines.index)
p_t = pd.DataFrame(index=ts, columns=pypsa_net.lines.index)
q_t = pd.DataFrame(index=ts, columns=pypsa_net.lines.index)
for (t, date_idx) in enumerate(ts):
branch_t = pd.DataFrame(solution_data["branch"]["nw"][str(t + 1)])
branch_t.index = branch_t.index.astype(int)
branch_t = branch_t.sort_index()
branch_t.insert(0, "br_idx", branch_t.index)
branch_t.index = pypsa_net.lines.index
p_t.loc[date_idx] = branch_t.p.T
q_t.loc[date_idx] = branch_t.q.T
cm_t.loc[date_idx] = branch_t.cm.T
self.lines_t.cm = cm_t
self.lines_t.p = p_t
self.lines_t.q = q_t
return
def set_bus_variables(self, pypsa_net):
solution_data = self.solution_data
ts = pypsa_net.snapshots.sort_values()
w_t = pd.DataFrame(index=ts, columns=pypsa_net.buses.index)
for (t, date_idx) in enumerate(ts):
bus_t = pd.DataFrame(solution_data["bus"]["nw"][str(t + 1)])
bus_t.index = bus_t.index.astype(int)
bus_t = bus_t.sort_index()
bus_t.index = pypsa_net.buses.index
w_t.loc[date_idx] = bus_t.w
self.buses_t.w = w_t
return
def set_gen_variables(self, pypsa_net):
# ToDo disaggregate aggregated generators?
gen_solution_data = self.solution_data["gen"]["nw"]
ts = pypsa_net.snapshots.sort_values()
# in case no curtailment requirement was given, all generators are
# made to fixed loads and Slack is the only remaining generator
if len(gen_solution_data["1"]["pg"].keys()) == 1:
try:
# check if generator index in pypsa corresponds to generator
# int
slack = pypsa_net.generators[
pypsa_net.generators.control == "Slack"
].index.values[0]
ind = pypsa_net.generators.index.get_loc(slack) + 1
if not str(ind) in gen_solution_data["1"]["pg"].keys():
logger.warning("Slack indexes do not match.")
# write slack results
pg_t = pd.DataFrame(index=ts, columns=[slack])
qg_t = pd.DataFrame(index=ts, columns=[slack])
for (t, date_idx) in enumerate(ts):
gen_t = pd.DataFrame(gen_solution_data[str(t + 1)])
gen_t.index = [slack]
pg_t.loc[date_idx] = gen_t.pg
qg_t.loc[date_idx] = gen_t.qg
self.generators_t.pg = pg_t
self.generators_t.qg = qg_t
except:
logger.warning(
"Error in writing OPF solutions for slack time " "series."
)
else:
try:
pg_t = pd.DataFrame(
index=ts, columns=pypsa_net.generators.index
)
qg_t = pd.DataFrame(
index=ts, columns=pypsa_net.generators.index
)
for (t, date_idx) in enumerate(ts):
gen_t = pd.DataFrame(gen_solution_data[str(t + 1)])
gen_t.index = gen_t.index.astype(int)
gen_t = gen_t.sort_index()
gen_t.index = pypsa_net.generators.index
pg_t.loc[date_idx] = gen_t.pg
qg_t.loc[date_idx] = gen_t.qg
self.generators_t.pg = pg_t
self.generators_t.qg = qg_t
except:
logger.warning(
"Error in writing OPF solutions for generator time "
"series."
)
def set_load_variables(self, pypsa_net):
load_solution_data = self.solution_data["load"]["nw"]
ts = pypsa_net.snapshots.sort_values()
pd_t = pd.DataFrame(
index=ts,
columns=[int(_) for _ in load_solution_data["1"]["pd"].keys()]
)
qd_t = pd.DataFrame(
index=ts,
columns=[int(_) for _ in load_solution_data["1"]["pd"].keys()]
)
for (t, date_idx) in enumerate(ts):
load_t = pd.DataFrame(load_solution_data[str(t + 1)])
load_t.index = load_t.index.astype(int)
pd_t.loc[date_idx] = load_t.pd
qd_t.loc[date_idx] = load_t.qd
load_buses = self.pypsa.loads.bus.unique()
load_bus_df = pd.DataFrame(
columns=["bus_loc"],
index=[load_buses])
for b in load_buses:
load_bus_df.at[
b, "bus_loc"] = self.pypsa.buses.index.get_loc(b)
load_bus_df = load_bus_df.sort_values(by="bus_loc").reset_index()
load_bus_df.index = load_bus_df.index + 1
pd_t = pd_t.rename(columns=load_bus_df.level_0.to_dict())
qd_t = qd_t.rename(columns=load_bus_df.level_0.to_dict())
self.loads_t.pd = pd_t
self.loads_t.qd = qd_t
def set_strg_variables(self, pypsa_net):
solution_data = self.solution_data
# time independent values
strg_statics = pd.DataFrame.from_dict(
solution_data["storage"]["static"]["emax"], orient="index"
)
if not strg_statics.empty:
strg_statics.columns = ["emax"]
strg_statics.index = strg_statics.index.astype(int)
strg_statics = strg_statics.sort_index()
# Convert one-based storage indices back to string names
idx_names = [
pypsa_net.buses.index[i - 1] for i in strg_statics.index
]
strg_statics.index = pd.Index(idx_names)
self.storage_units = strg_statics
# time dependent values
ts = pypsa_net.snapshots
uc_t = pd.DataFrame(index=ts, columns=strg_statics.index)
ud_t = pd.DataFrame(index=ts, columns=strg_statics.index)
soc_t = pd.DataFrame(index=ts, columns=strg_statics.index)
for (t, date_idx) in enumerate(ts):
strg_t = pd.DataFrame(
solution_data["storage"]["nw"][str(t + 1)]
)
strg_t.index = strg_t.index.astype(int)
strg_t = strg_t.sort_index()
strg_t.index = strg_statics.index
uc_t.loc[date_idx].update(strg_t["uc"])
ud_t.loc[date_idx].update(strg_t["ud"])
soc_t.loc[date_idx].update(strg_t["soc"])
self.storage_units_t.soc = soc_t
self.storage_units_t.uc = uc_t
self.storage_units_t.ud = ud_t
| agpl-3.0 |
InstitutoPascal/campuswebpro | controllers/setup_alumnos.py | 20314 | # coding: utf8
# intente algo como
def index(): return dict(message="hello from setup_alumnos.py")
####### FUNCION DE PRUEBA---INSERT EN TABLA ALUMNOS---######
db1= DAL("postgres://luka:1234@127.0.0.1:5432/practica")
def insert_alumnos():
filas= db1.executesql('SELECT * FROM alumnos', as_dict= True)
for fila in filas:
db.alumnos.insert(alumnoid= fila['alumnoid'],
nombre= fila['alumno'],
codigo= fila['codigo'],
dni= fila['dni'],
sexo= fila['sexo'],
fechanacimiento= fila['fechanacimiento'],
lugarnacimiento= fila['lugarnacimiento'],
estadocivil= fila['estadocivil'],
nacionalidad= fila['nacionalidad'],
direccion= fila['direccion'],
localidad= fila['localidad'],
cp= fila['cp'],
telefonos= fila['telefonos'],
email1= fila['email1'],
email2= fila['email2'],
ingreso= fila['ingreso'],
egreso= fila['egreso'])
return {'filas': filas}
def insert_ciclo():
filas= db1.executesql('SELECT * FROM ciclos', as_dict= True)
for fila in filas:
db.ciclos.insert(cicloid= fila['cicloid'],
nombre= fila['ciclo'],
anio= fila['año'],
detalle= fila['detalle'],
desde= fila['desde'],
hasta= fila['hasta'] )
return {'filas': filas}
def insert_division():
filas= db1.executesql('SELECT * FROM divisiones', as_dict= True)
for fila in filas:
db.divisiones.insert(divisionid= fila['divisionid'],
descripcion= fila['division'],
codigo= fila['codigo'],
cursoid= fila['cursoid'],
cicloid= fila['cicloid'],
numero= fila['numero'],
letra= fila['letra'],
turno= fila['turno'],
anio= fila['año'] )
return {'filas': filas}
def insert_materias():
db.materias.insert(codigo=500, nombre= "ALGEBRA", cursoid=1, catedraid=3)
db.materias.insert(codigo=501, nombre= "ANALISIS MATEMATICO I", cursoid=1, catedraid=3)
return dict()
def insert_catedra():
filas= db1.executesql('SELECT * FROM catedras', as_dict= True)
for fila in filas:
db.catedras.insert(catedraid= fila['catedraid'],
nombre= fila['catedra'],
informe= fila['informe'],
boletin= fila['boletin'],
analitico= fila['analítico'],
espacio= fila['espacio'],
abr= fila['abr'],
calificacion= fila['calificacion'],
horas= fila['horas'],
minutos= fila['minutos'],
nivelid= fila['nivelid'])
return {'filas': filas}
def insert_carrera():
filas= db1.executesql('SELECT * FROM carreras', as_dict= True)
for fila in filas:
db.carreras.insert(carreraid= fila['carreraid'],
nombre= fila['carrera'] )
return {'filas': filas}
def insert_planestudio():
filas= db1.executesql('SELECT * FROM planesestudio', as_dict= True)
for fila in filas:
db.planesestudio.insert(planestudioid= fila['planestudioid'],
descripcion= fila['planestudio'],
aprobadopor= fila['aprobadopor'],
carreraid= fila['carreraid'],
desde= fila['desde'],
hasta= fila['hasta'] )
return {'filas': filas}
def insert_asignaturas():
db.asignaturas.insert(nombre= "SALUD PUBLICA", materiaid=125, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "EST. Y FUNCION DEL CUERPO HUMANO", materiaid=126, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "BIOFISICA Y BIOQUIMICA", materiaid=127, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "MICROBIOLOGIA Y PARASITOLOGIA", materiaid=128, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "FUNDAMENTOS DE NUTRICION", materiaid=129, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "ENFERM. FUND. PRACT. Y TENDENCIAS", materiaid=130, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "ENFERMERIA MATERNO INFANTIL I", materiaid=131, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "FARMOCOLOGIA EN ENFERMERIA", materiaid=132, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "PRACTICA I", materiaid=133, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "INT. A LA INVESTIGACION EN SALUD", materiaid=134, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "EPIDEMIOLOGIA Y ESTADISTICA EN SALUD", materiaid=135, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "INFORMATICA", materiaid=136, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "ENFERMERIA DELADULTO Y EL ANCIANO", materiaid=137, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "DIETETICA EN ENFERMERIA", materiaid=138, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "ENFERMERIA EN SALUD MENTAL", materiaid=139, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "EDI", materiaid=140, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "PRACTICA II", materiaid=141, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "EDUCACION EN SALUD", materiaid=142, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "ORG. Y GESTION SERV. SALUD", materiaid=143, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "INV. Y PLANIF. EN SALUD", materiaid=144, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "INGLES", materiaid=145, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "ENFERM. MATERNO-INF. II", materiaid=146, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "ORG. Y GESTION SERV. DE ENFERM.", materiaid=147, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "ENFERM. EN EMERG. Y CATASTROFES", materiaid=148, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "ASPECTOS ETICOS Y LEGALES DE LA PRAC. PROF", materiaid=149, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "EDI II", materiaid=150, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "PRACTICA III", materiaid=151, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "CONDICIONES Y MEDIO AMBIENTE DEL TRABAJO", materiaid=152, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "SALUD PUBLICA I", materiaid=153, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "BIOLOGIA HUMANA", materiaid=154, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "FUNDAMENTOS DEL CUIDADO", materiaid=155, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "CUIDADOS DE LA SALUD CENTRADOS EN LA COMUNIDAD Y LA FAMILIA", materiaid=156, carreraid=2, planestudioid=4, cicloid=2)
db.asignaturas.insert(nombre= "PRACTICA I", materiaid=157, carreraid=2, planestudioid=4, cicloid=2)
return dict ()
def insert_calendario():
filas= db1.executesql('SELECT * FROM calendario', as_dict= True)
for fila in filas:
db.calendarios.insert(calendarioid= fila['id'],
fecha= fila['fecha'],
feriado= fila['feriado'],
mensaje= fila['mensaje'] )
return {'filas': filas}
def insert_calificacion():
filas= db1.executesql('SELECT * FROM calificaciones', as_dict= True)
for fila in filas:
db.calificaciones.insert(calificacionid= fila['calificacionid'],
descripcion= fila['calificacion'],
condicion= fila['condicion'],
ayuda= fila['ayuda'],
equivalencia= fila['equivalencia'],
previa= fila['previa'] )
return {'filas': filas}
def insert_periodo():
filas= db1.executesql('SELECT * FROM periodos', as_dict= True)
for fila in filas:
print fila
db.periodos.insert(periodoid= fila['periodoid'],
descripcion= fila['periodo'],
nivelid= fila['nivelid'],
cicloid= fila['cicloid'],
mes= fila['mes'],
anio= fila['anio'],
trimestre= fila['trimestre'],
condicion= fila['condicion'],
cuatrimestre= fila['cuatrimestre'],
semestre= fila['semestre'],
orden= fila['orden'],
codigo= fila['codigo'],
inicio= fila['inicio'],
cierre= fila['cierre'],
tipo= fila['tipo'],
dias= fila['dias'],
secuencia= fila['secuencia'],
notaminima= fila['notaminima'] )
return {'filas': filas}
def insert_titulos():
filas= db1.executesql('SELECT * FROM titulos', as_dict= True)
for fila in filas:
db.titulos.insert(tituloid= fila['tituloid'],
nombre= fila['titulo'],
planestudioid= fila['planestudioid'],
carreraid= fila['carreraid'],
cursoid= fila['cursoid'] )
return {'filas': filas}
def insert_nota():
fecha = request.now.date()
db.notas.insert(alumnoid= 25, materiaid=175, periodoid=26, calificacionid=3, nota=7, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=176, periodoid=26, calificacionid=3, nota=6, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=177, periodoid=26, calificacionid=3, nota=8, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=178, periodoid=26, calificacionid=3, nota=7, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=179, periodoid=26, calificacionid=3, nota=9, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=180, periodoid=26, calificacionid=3, nota=6, alta= fecha)
#2DO CUATRI
db.notas.insert(alumnoid= 25, materiaid=175, periodoid=27, calificacionid=3, nota=7, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=176, periodoid=27, calificacionid=3, nota=6, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=177, periodoid=27, calificacionid=3, nota=8, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=178, periodoid=27, calificacionid=3, nota=7, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=179, periodoid=27, calificacionid=3, nota=9, alta= fecha)
db.notas.insert(alumnoid= 25, materiaid=180, periodoid=27, calificacionid=3, nota=6, alta= fecha)
return dict ()
def insert_correlativas():
filas= db1.executesql('SELECT * FROM correlativas', as_dict= True)
for fila in filas:
db.correlativas.insert(correlativaid= fila['correlativaid'],
materiaid1= fila['materiaid1'],
materiaid2= fila['materiaid2'],
planestudioid= fila['planestudioid'] )
return {'filas': filas}
def insert_comision():
db.comisiones.insert(nombre= "SALUD PUBLICA", materiaid=125, divisionid=1, periodoid=22)
db.comisiones.insert(nombre= "EST. Y FUNCION DEL CUERPO HUMANO", materiaid=126, divisionid=1, periodoid=22, personalid=15)
db.comisiones.insert(nombre= "BIOFISICA Y BIOQUIMICA", materiaid=127, divisionid=1, periodoid=22, personalid=15)
db.comisiones.insert(nombre= "MICROBIOLOGIA Y PARASITOLOGIA", materiaid=128, divisionid=1, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "FUNDAMENTOS DE NUTRICION", materiaid=129, divisionid=1, periodoid=22)
db.comisiones.insert(nombre= "ENFERM. FUND. PRACT. Y TENDENCIAS", materiaid=130, divisionid=1, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "ENFERMERIA MATERNO INFANTIL I", materiaid=131, divisionid=1, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "FARMACOLOGIA EN ENFERMERIA", materiaid=132, divisionid=1, periodoid=22, personalid=15)
db.comisiones.insert(nombre= "PRACTICA I", materiaid=133, divisionid=1, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "INT. A LA INVESTIGACION EN SALUD", materiaid=134, divisionid=2, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "EPIDEMIOLOGIA Y ESTADISTICA EN SALUD", materiaid=135, divisionid=2, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "INFORMATICA", materiaid=136, divisionid=2, periodoid=22, personalid=11)
db.comisiones.insert(nombre= "ENFERMERIA DEL ADULTO Y EL ANCIANO", materiaid=137, divisionid=2, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "DIETETICA EN ENFERMERIA", materiaid=138, divisionid=2, periodoid=2)
db.comisiones.insert(nombre= "ENFERMERIA EN SALUD MENTAL", materiaid=139, divisionid=2, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "EDI", materiaid=140, divisionid=2, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "PRACTICA II", materiaid=141, divisionid=2, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "EDUCACION EN SALUD", materiaid=142, divisionid=3, periodoid=22, personalid=26)
db.comisiones.insert(nombre= "ORG. Y GESTION SERV. SALUD", materiaid=143, divisionid=3, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "INV. Y PLANIF. EN SALUD", materiaid=144, divisionid=3, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "INGLES", materiaid=145, divisionid=3, periodoid=22, personalid=9)
db.comisiones.insert(nombre= "ENFERM. MATERNO-INF. II", materiaid=146, divisionid=3, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "ORG. Y GESTION SERV. DE ENFERM.", materiaid=147, divisionid=3, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "ENFERM. EN EMERG. Y CATASTROFES", materiaid=148, divisionid=3, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "ASPECTOS ETICOS Y LEGALES DE LA PRAC. PROF", materiaid=149, divisionid=3, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "EDI II", materiaid=150, divisionid=3, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "PRACTICA III", materiaid=151, divisionid=3, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "CONDICIONES Y MEDIO AMBIENTE DEL TRABAJO", materiaid=152, divisionid=1, periodoid=22, personalid=24)
db.comisiones.insert(nombre= "SALUD PUBLICA I", materiaid=153, divisionid=1, periodoid=22, personalid=27)
db.comisiones.insert(nombre= "BIOLOGIA HUMANA", materiaid=154, divisionid=1, periodoid=22, personalid=15)
db.comisiones.insert(nombre= "FUNDAMENTOS DEL CUIDADO", materiaid=155, divisionid=1, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "CUIDADOS DE LA SALUD CENTRADOS EN LA COMUNIDAD Y LA FAMILIA", materiaid=156, divisionid=1, periodoid=22, personalid=25)
db.comisiones.insert(nombre= "PRACTICA I", materiaid=157, divisionid=1, periodoid=22, personalid=24)
return dict ()
def insert_inscripcioncomision():
filas= db1.executesql('SELECT * FROM inscripcionescomision', as_dict= True)
for fila in filas:
db.inscripcionescomision.insert(inscripcionid= fila['inscripcionid'],
alumnoid= fila['alumnoid'],
comisionid= fila['comisionid'],
alta= fila['alta'],
baja= fila['baja'],
condicion= fila['condicion'] )
return {'filas': filas}
def insert_situaciones():
filas= db1.executesql('SELECT * FROM situaciones', as_dict= True)
for fila in filas:
db.situaciones.insert(situacionid= fila['situacionid'],
detalle= fila['situacion'] )
return {'filas': filas}
def insert_inscripcionexamen():
filas= db1.executesql('SELECT * FROM inscripcionesexamen', as_dict= True)
for fila in filas:
db.inscripcionesexamen.insert(inscripcionid= fila['inscripcionid'],
alumnoid= fila['alumnoid'],
examenid= fila['examenid'],
condicion= fila['condicion'],
alta= fila['alta'],
baja= fila['baja'],
confirmar= fila['confirmar'],
valido= fila['valido'] )
return {'filas': filas}
def insert_inscripciondivision():
filas= db1.executesql('SELECT * FROM inscripcionesdivision', as_dict= True)
for fila in filas:
db.inscripcionesdivision.insert(inscripcionid= fila['inscripcionid'],
alumnoid= fila['alumnoid'],
divisionid= fila['divisionid'],
alta= fila['alta'],
baja= fila['baja'],
condicion= fila['condicion'] )
return {'filas': filas}
def insert_faltas():
filas= db1.executesql('SELECT * FROM faltas', as_dict= True)
for fila in filas:
db.faltas.insert(faltaid= fila['faltaid'],
alumnoid= fila['alumnoid'],
comisionid= fila['comisionid'],
inasistenciaid= fila['inasistenciaid'],
fecha= fila['fecha'],
cantidad= fila['cantidad'],
justificado= fila['justificado'],
detalle= fila['detalle'],
web= fila['web'])
return {'filas': filas}
def insert_sancion():
filas= db1.executesql('SELECT * FROM sanciones', as_dict= True)
for fila in filas:
db.sanciones.insert(sancionid= fila['sancionid'],
alumnoid= fila['alumnoid'],
fecha= fila['fecha'],
cantidad= fila['cantidad'],
tipo= fila['tipo'],
detalle= fila['detalle'],
parte= fila['parte'])
return {'filas': filas}
def insert_secciones():
filas= db1.executesql('SELECT * FROM secciones', as_dict= True)
for fila in filas:
db.secciones.insert(seccionid= fila['seccionid'],
descripcion= fila['seccion'] )
return {'filas': filas}
| agpl-3.0 |
Sparfel/iTop-s-Portal | library/Zend/Form/Element/Xhtml.php | 1125 | <?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_Form
* @subpackage Element
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/** Zend_Form_Element */
//$1 'Zend/Form/Element.php';
/**
* Base element for XHTML elements
*
* @category Zend
* @package Zend_Form
* @subpackage Element
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
abstract class Zend_Form_Element_Xhtml extends Zend_Form_Element
{
}
| agpl-3.0 |
gnosygnu/xowa_android | _400_xowa/src/main/java/gplx/xowa/xtns/pfuncs/exprs/Func_tkn_round.java | 958 | package gplx.xowa.xtns.pfuncs.exprs; import gplx.*; import gplx.xowa.*; import gplx.xowa.xtns.*; import gplx.xowa.xtns.pfuncs.*;
import gplx.xowa.parsers.*;
class Func_tkn_round extends Func_tkn_base {
public Func_tkn_round(String v) {this.Ctor(v);}
@Override public int ArgCount() {return 2;}
@Override public int Precedence() {return 5;}
@Override public boolean Calc_hook(Xop_ctx ctx, Pfunc_expr_shunter shunter, Val_stack val_stack) {
Decimal_adp rhs = val_stack.Pop();
Decimal_adp lhs = val_stack.Pop();
if (rhs.Comp_gt(16)) {
rhs = Decimal_adp_.int_(16);
}
else if (rhs.Comp_lt(-16)) {
rhs = Decimal_adp_.int_(-16);
}
Decimal_adp val = lhs.Round_old(rhs.To_int());
if (val.To_double() == 0) // NOTE: must explicitly check for zero, else "0.0" will be pushed onto stack; EXE: {{#expr: 0 round 1}}; DATE:2013-11-09
val_stack.Push(Decimal_adp_.Zero);
else
val_stack.Push(val);
return true;
}
}
| agpl-3.0 |
edbaskerville/mc3kit | src/mc3kit/types/doublevalue/distributions/ImproperUniformDistribution.java | 1867 | /***
This file is part of mc3kit.
Copyright (C) 2013 Edward B. Baskerville
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 mc3kit.types.doublevalue.distributions;
import mc3kit.*;
import mc3kit.model.Model;
import mc3kit.model.Variable;
import mc3kit.step.univariate.VariableProposer;
import mc3kit.types.doublevalue.DoubleDistribution;
import mc3kit.types.doublevalue.proposers.MHNormalProposer;
public class ImproperUniformDistribution extends DoubleDistribution {
protected ImproperUniformDistribution() {
}
public ImproperUniformDistribution(Model model) {
this(model, null);
}
public ImproperUniformDistribution(Model model, String name) {
super(model, name);
}
@Override
public VariableProposer makeVariableProposer(String varName) {
return new MHNormalProposer(varName);
}
@Override
public boolean valueIsValid(double value) {
return !Double.isNaN(value) && !Double.isInfinite(value);
}
@Override
public double getLogP(Variable var) {
return 0.0;
}
@Override
public void sample(Variable var) throws MC3KitException {
throw new MC3KitException(
"Cannot sample from improper prior. Initialize value during construction.");
}
@Override
public boolean update() {
return false;
}
}
| agpl-3.0 |
mezuro/kalibro_gatekeeper | spec/routing/ranges_routing_spec.rb | 443 | require "rails_helper"
describe RangesController, :type => :routing do
describe "routing" do
it { is_expected.to route(:post, 'ranges/save').
to(controller: :ranges, action: :save) }
it { is_expected.to route(:post, 'ranges/destroy').
to(controller: :ranges, action: :destroy) }
it { is_expected.to route(:post, 'ranges/of').
to(controller: :ranges, action: :of) }
end
end | agpl-3.0 |
guerrerocarlos/fiware-IoTAgent-Cplusplus | tests/e2e_tests/component/iot_manager_api/manager_devices/update/setup.py | 1139 | from lettuce import step, world
from common.functions import Functions
from common.steps import service_with_path_created_precond, device_with_attr_or_cmd_created_precond, update_device_data_manager, check_device_data_updated
functions = Functions()
@step('I try to update the device data of device "([^"]*)" with service "([^"]*)", protocol "([^"]*)" and path "([^"]*)" with the attribute "([^"]*)" and value "([^"]*)"')
def update_wrong_device_data(step, device_name, service_name, protocol, service_path, attribute, value):
world.req = functions.update_device_with_params(attribute, device_name, value, service_name, service_path, True, True, protocol)
assert world.req.status_code != 200, 'ERROR: ' + world.req.text + "El dispositivo {} se ha podido actualizar".format(service_name)
@step('user receives the "([^"]*)" and the "([^"]*)"')
def assert_device_created_failed(step, http_status, error_text):
assert world.req.status_code == int(http_status), "El codigo de respuesta {} es incorrecto".format(world.req.status_code)
assert str(error_text) in world.req.text, 'ERROR: ' + world.req.text | agpl-3.0 |
blckshrk/Weboob | modules/rockradio/backend.py | 3418 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Pierre Mazière
#
# Based on somafm backend
#
# This file is part of weboob.
#
# weboob 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.
#
# weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>.
from weboob.capabilities.radio import ICapRadio, Radio, Stream, Emission
from weboob.capabilities.collection import ICapCollection
from weboob.tools.backend import BaseBackend
from weboob.tools.browser import StandardBrowser
__all__ = ['RockRadioBackend']
class RockRadioBackend(BaseBackend, ICapRadio, ICapCollection):
NAME = 'rockradio'
MAINTAINER = u'Pierre Mazière'
EMAIL = 'pierre.maziere@gmx.com'
VERSION = '0.h'
DESCRIPTION = u'Rock Music Internet Radio'
LICENSE = 'AGPLv3+'
BROWSER = StandardBrowser
ALLINFO = 'http://www.rockradio.com'
# FIXME
#
# MPlayer does not like the pls file sent from this site.
def _parse_current(self, data):
current = data.split(' - ')
if len(current) == 2:
return current
else:
return (u'Unknown', u'Unknown')
def _fetch_radio_list(self):
radios = []
document = self.browser.location(self.ALLINFO)
for channel in document.iter('div'):
if ("shadow"!=channel.get('class')):
continue
url=u''+channel.find('a').get('href')
radio = Radio(url[(url.rfind('/')+1):].replace('.pls',''))
radio.title = u''+channel.getprevious().text
radio.description = u""
current_data = u""
current = Emission(0)
current.artist, current.title = self._parse_current(current_data)
radio.current = current
radio.streams = []
stream_id = 0
stream = Stream(stream_id)
stream.title = radio.title
stream.url = url
radio.streams.append(stream)
radios.append(radio)
return radios
def iter_radios_search(self, pattern):
radios = self._fetch_radio_list()
pattern = pattern.lower()
for radio in radios:
if pattern in radio.title.lower() or pattern in radio.description.lower():
yield radio
def iter_resources(self, objs, split_path):
radios = self._fetch_radio_list()
if Radio in objs:
self._restrict_level(split_path)
for radio in radios:
yield radio
def get_radio(self, radio_id):
radios = self._fetch_radio_list()
for radio in radios:
if radio_id == radio.id:
return radio
def fill_radio(self, radio, fields):
if 'current' in fields:
if not radio.current:
radio.current = Emission(0)
radio.current.artist, radio.current.title = self.get_current(radio.id)
return radio
| agpl-3.0 |
armanbilge/phyloHMC | src/main/scala/group/matsen/phylohmc/Z.scala | 560 | package group.matsen.phylohmc
import spire.algebra.Field
import spire.syntax.field._
case class Z[R : Field, N, G](q: Tree[R, N], p: IndexedSeq[R])(_U: => (R, G), _K: => (R, G)) {
lazy val (u, dU) = _U
lazy val (k, dK) = _K
lazy val H = u + k
def copy(q: Tree[R, N] = this.q, p: IndexedSeq[R] = this.p)(_U: => (R, G) = (u, dU), _K: => (R, G) = (k, dK)): Z[R, N, G] = Z(q, p)(_U, _K)
}
object Z {
def apply[R : Field, N, G](q: Tree[R, N], p: IndexedSeq[R], U: Tree[R, N] => (R, G), K: IndexedSeq[R] => (R, G)): Z[R, N, G] = Z(q, p)(U(q), K(p))
}
| agpl-3.0 |
npcdoom/ZelosOnline | globald/certd/state_certify.cpp | 1916 | /*********************************************************************************
*
* This file is part of ZelosOnline.
*
* ZelosOnline 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.
*
* ZelosOnline 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/>.
*
* Copyright 2013 Rafael Dominguez (npcdoom)
*
*********************************************************************************/
#include "state_certify.h"
#include <net/client/connection.h>
#include <net/opcode/cert_srv.h>
#include "service.h"
namespace clt
{
StateCertify::StateCertify (Service *service, const boost::shared_ptr<IConnection> &conn)
: ConnectionState<IConnection>::ConnectionState(conn),
m_service(service)
{
m_opcode_table[SERVER_CERTIFY_DAEMON] = boost::bind(&clt::StateCertify::OnCertify,this,_1);
}
StateCertify::~StateCertify ()
{
}
void StateCertify::Close ()
{
}
int StateCertify::OnCertify (const IPacket &packet)
{
uint8_t ret = packet.Read<uint8_t>();
if (!packet.EndOfStream())
return MSG_ERROR_SIZE;
if (ret > ANSWER_ERROR)
return MSG_ERROR_ARG;
if (ret == ANSWER_ACCEPT)
{
syslog(LOG_INFO,"Certification Successfull.");
m_service->runServer();
m_connection->stop();
}
else
{
syslog(LOG_INFO,"Certification failed.");
m_service->stop();
}
return MSG_SUCCESS;
}
}
| agpl-3.0 |
Tanaguru/Tanaguru | rules/rgaa3-2016/src/test/java/org/tanaguru/rules/rgaa32016/Rgaa32016Rule120101Test.java | 3380 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2016 Tanaguru.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.rgaa32016;
import org.tanaguru.entity.audit.IndefiniteResult;
import org.tanaguru.entity.audit.ProcessResult;
import org.tanaguru.entity.audit.TestSolution;
import org.tanaguru.entity.subject.Page;
import org.tanaguru.entity.subject.Site;
import org.tanaguru.rules.rgaa32016.test.Rgaa32016RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 12-1-1 of the referential Rgaa 3-2016.
*
* @author jkowalczyk
*/
public class Rgaa32016Rule120101Test extends Rgaa32016RuleImplementationTestCase {
/**
* Default constructor
* @param testName
*/
public Rgaa32016Rule120101Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName("org.tanaguru.rules.rgaa32016.Rgaa32016Rule120101");
}
@Override
protected void setUpWebResourceMap() {
getWebResourceMap().put("Rgaa32016.Test.12.01.01-4NA-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "rgaa32016/Rgaa32016Rule120101/Rgaa32016.Test.12.01.01-3NMI-01.html"));
Site site = getWebResourceFactory().createSite("file:Site-NotTested");
getWebResourceMap().put("Rgaa32016.Test.12.01.01-5NT-01", site);
Page page = getWebResourceFactory().createPage(getTestcasesFilePath() +
"rgaa32016/Rgaa32016Rule120101/Rgaa32016.Test.12.01.01-3NMI-01.html");
site.addChild(page);
getWebResourceMap().put("Rgaa32016.Test.12.01.01-5NT-01-page1",page);
page = getWebResourceFactory().createPage(getTestcasesFilePath() +
"rgaa32016/Rgaa32016Rule120101/Rgaa32016.Test.12.01.01-3NMI-01.html");
site.addChild(page);
getWebResourceMap().put("Rgaa32016.Test.12.01.01-5NT-01-page1",page);
}
@Override
protected void setProcess() {
ProcessResult pr = processPageTest("Rgaa32016.Test.12.01.01-4NA-01");
assertTrue(pr instanceof IndefiniteResult);
assertEquals(getWebResourceMap().get("Rgaa32016.Test.12.01.01-4NA-01"),pr.getSubject());
assertEquals("mock-result", pr.getValue());
process("Rgaa32016.Test.12.01.01-5NT-01");
}
@Override
protected void setConsolidate() {
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("Rgaa32016.Test.12.01.01-4NA-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa32016.Test.12.01.01-5NT-01").getValue());
}
}
| agpl-3.0 |
LYY/code2docx | vendor/baliance.com/gooxml/schema/soo/dml/CT_GvmlTextShapeChoice.go | 2632 | // Copyright 2017 Baliance. All rights reserved.
//
// DO NOT EDIT: generated by gooxml ECMA-376 generator
//
// Use of this source code is governed by the terms of the Affero GNU General
// Public License version 3.0 as published by the Free Software Foundation and
// appearing in the file LICENSE included in the packaging of this file. A
// commercial license can be purchased by contacting sales@baliance.com.
package dml
import (
"encoding/xml"
"log"
)
type CT_GvmlTextShapeChoice struct {
UseSpRect *CT_GvmlUseShapeRectangle
Xfrm *CT_Transform2D
}
func NewCT_GvmlTextShapeChoice() *CT_GvmlTextShapeChoice {
ret := &CT_GvmlTextShapeChoice{}
return ret
}
func (m *CT_GvmlTextShapeChoice) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if m.UseSpRect != nil {
seuseSpRect := xml.StartElement{Name: xml.Name{Local: "a:useSpRect"}}
e.EncodeElement(m.UseSpRect, seuseSpRect)
}
if m.Xfrm != nil {
sexfrm := xml.StartElement{Name: xml.Name{Local: "a:xfrm"}}
e.EncodeElement(m.Xfrm, sexfrm)
}
return nil
}
func (m *CT_GvmlTextShapeChoice) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
// initialize to default
lCT_GvmlTextShapeChoice:
for {
tok, err := d.Token()
if err != nil {
return err
}
switch el := tok.(type) {
case xml.StartElement:
switch el.Name {
case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/main", Local: "useSpRect"}:
m.UseSpRect = NewCT_GvmlUseShapeRectangle()
if err := d.DecodeElement(m.UseSpRect, &el); err != nil {
return err
}
case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/main", Local: "xfrm"}:
m.Xfrm = NewCT_Transform2D()
if err := d.DecodeElement(m.Xfrm, &el); err != nil {
return err
}
default:
log.Printf("skipping unsupported element on CT_GvmlTextShapeChoice %v", el.Name)
if err := d.Skip(); err != nil {
return err
}
}
case xml.EndElement:
break lCT_GvmlTextShapeChoice
case xml.CharData:
}
}
return nil
}
// Validate validates the CT_GvmlTextShapeChoice and its children
func (m *CT_GvmlTextShapeChoice) Validate() error {
return m.ValidateWithPath("CT_GvmlTextShapeChoice")
}
// ValidateWithPath validates the CT_GvmlTextShapeChoice and its children, prefixing error messages with path
func (m *CT_GvmlTextShapeChoice) ValidateWithPath(path string) error {
if m.UseSpRect != nil {
if err := m.UseSpRect.ValidateWithPath(path + "/UseSpRect"); err != nil {
return err
}
}
if m.Xfrm != nil {
if err := m.Xfrm.ValidateWithPath(path + "/Xfrm"); err != nil {
return err
}
}
return nil
}
| agpl-3.0 |
jpmml/jpmml-sparkml | src/main/java/org/jpmml/sparkml/model/DecisionTreeClassificationModelConverter.java | 1592 | /*
* Copyright (c) 2016 Villu Ruusmann
*
* This file is part of JPMML-SparkML
*
* JPMML-SparkML 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.
*
* JPMML-SparkML 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 JPMML-SparkML. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpmml.sparkml.model;
import org.apache.spark.ml.classification.DecisionTreeClassificationModel;
import org.apache.spark.ml.linalg.Vector;
import org.dmg.pmml.tree.TreeModel;
import org.jpmml.converter.Schema;
import org.jpmml.sparkml.ClassificationModelConverter;
public class DecisionTreeClassificationModelConverter extends ClassificationModelConverter<DecisionTreeClassificationModel> implements HasFeatureImportances, HasTreeOptions {
public DecisionTreeClassificationModelConverter(DecisionTreeClassificationModel model){
super(model);
}
@Override
public Vector getFeatureImportances(){
DecisionTreeClassificationModel model = getTransformer();
return model.featureImportances();
}
@Override
public TreeModel encodeModel(Schema schema){
return TreeModelUtil.encodeDecisionTree(this, schema);
}
} | agpl-3.0 |
karlkoorna/Bussiaeg | web/src/i18n.js | 650 | import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './locales/en.json';
import et from './locales/et.json';
import ru from './locales/ru.json';
function genResources(langs) {
const resources = {};
for (const lang of Object.entries(langs)) resources[lang[0]] = { translation: lang[1] };
return resources;
}
i18n.use(initReactI18next).init({
resources: genResources({ en, et, ru }),
load: 'languageOnly',
lng: navigator.languages.filter((language) => [ 'et', 'en', 'ru' ].some((lang) => language.indexOf(lang) > -1))[0].split('-')[0],
fallbackLng: 'et',
interpolation: {
escapeValue: false
}
});
| agpl-3.0 |
Codeminer42/cm42-central | spec/factories/membership_factory.rb | 111 | FactoryBot.define do
factory :membership do |m|
m.association :project
m.association :user
end
end
| agpl-3.0 |
omkelderman/osu-web | resources/lang/uk/beatmapset_watches.php | 1026 | <?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
return [
'index' => [
'description' => 'Тут показуються карти, на оновлення яких ви підписані. Ви будете сповіщені, якщо з\'являться нові пости або оновлення.',
'title_compact' => 'підписки на карти',
'counts' => [
'total' => '',
'unread' => '',
],
'table' => [
'empty' => 'У вас немає відслідковуваних карт.',
'last_update' => '',
'open_issues' => 'Виявлених проблем',
'state' => 'Статус',
'title' => 'Назва',
],
],
'status' => [
'read' => 'Прочитано',
'unread' => 'Не прочитано',
],
];
| agpl-3.0 |
AnkiUniversal/Anki-Universal | AnkiU/Views/TemplateInformationView.xaml.cs | 10063 | /*
Copyright (C) 2016 Anki Universal Team <ankiuniversal@outlook.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/>.
*/
using AnkiU.AnkiCore;
using AnkiU.Models;
using AnkiU.UIUtilities;
using AnkiU.UserControls;
using AnkiU.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace AnkiU.Views
{
public sealed partial class TemplateInformationView : UserControl
{
private bool isSuppressComboxSelectionChangeEvent = false;
private MenuFlyout editMenuFlyout;
private NameEnterFlyout renameFlyout = null;
private NameEnterFlyout addNewFlyout = null;
private IntNumberEnterFlyout respositionFlyout = null;
public event RoutedEventHandler FlipButtonClick;
public event RoutedEventHandler SaveEvent;
public event RoutedEventHandler ComboBoxSelectionChangedEvent;
public event NoticeRoutedHandler AddTemplateEvent;
public event NoticeRoutedHandler FlipCardEvent;
private TemplateInformationViewModel viewModel;
public TemplateInformationViewModel ViewModel
{
get { return viewModel; }
set
{
if (viewModel != null)
viewModel.Templates.CollectionChanged -= TemplatesCollectionChangedHandler;
viewModel = value;
this.DataContext = viewModel.Templates;
viewModel.Templates.CollectionChanged += TemplatesCollectionChangedHandler;
UpdateButtonState();
}
}
private void UpdateButtonState()
{
if (JsonHelper.GetNameNumber(viewModel.CurrentModel,"type") == (int)AnkiCore.ModelType.CLOZE)
{
addTemplateButton.Visibility = Visibility.Collapsed;
deleteButton.Visibility = Visibility.Collapsed;
comboBox.IsEnabled = false;
return;
}
if (viewModel.Templates.Count > 1)
{
deleteButton.IsEnabled = true;
comboBox.IsEnabled = true;
}
else
{
deleteButton.IsEnabled = false;
comboBox.IsEnabled = false;
}
}
public TemplateInformationView()
{
this.InitializeComponent();
}
public void BeginAnimation()
{
NoticeMe.Begin();
}
public void StopAnimation()
{
NoticeMe.Stop();
}
public void SetAnimationOnEdit()
{
NoticeMe.Stop();
UIHelper.SetStoryBoardTarget(BlinkingBlue, editButton.Name);
}
private void TemplatesCollectionChangedHandler(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
UpdateButtonState();
}
private void ComboBoxSelectionChangedHandler(object sender, SelectionChangedEventArgs e)
{
if(!isSuppressComboxSelectionChangeEvent)
ComboBoxSelectionChangedEvent?.Invoke(sender, e);
}
private async void AddButtonClickHandler(object sender, RoutedEventArgs e)
{
var isContinue = await MainPage.WarnFullSyncIfNeeded();
if (!isContinue)
return;
if (addNewFlyout == null)
{
addNewFlyout = new NameEnterFlyout();
addNewFlyout.OkButtonClickEvent += NewTemplateFlyoutOKButtonClickHandler;
}
addNewFlyout.Show(sender as Button, "");
}
public void ChangeSelectedItem(long ord)
{
foreach (var item in comboBox.Items)
{
var model = item as TemplateInformation;
if (model.Ord == ord)
{
comboBox.SelectedItem = item;
break;
}
}
}
private async void NewTemplateFlyoutOKButtonClickHandler(object sender, RoutedEventArgs e)
{
var name = addNewFlyout.NewName;
bool isValid = await CheckNameValid(name);
if (!isValid)
return;
var templateToClone = comboBox.SelectedItem as TemplateInformation;
ViewModel.AddNewTemplate(name, templateToClone.Ord);
comboBox.SelectedItem = viewModel.Templates.Last();
MainPage.UserPrefs.IsFullSyncRequire = true;
SaveEvent?.Invoke(sender, null);
AddTemplateEvent?.Invoke();
}
private async Task<bool> CheckNameValid(string name)
{
return await UIHelper.CheckValidName(name, viewModel.Templates,
"This note type already has a template with the same name. Please enter another name.");
}
private async void DeleteButtonClickHandler(object sender, RoutedEventArgs e)
{
if(viewModel.Templates.Count == 1)
{
await UIHelper.ShowMessageDialog("One note type needs at least one template!");
return;
}
bool isContinue = await MainPage.WarnFullSyncIfNeeded();
if (!isContinue)
return;
var countNote = viewModel.Models.TmplUseCount(viewModel.CurrentModel, comboBox.SelectedIndex);
string message = String.Format(UIConst.WARN_TEMPLATE_DELETE, countNote);
isContinue = await UIHelper.AskUserConfirmation(message);
if (!isContinue)
return;
isSuppressComboxSelectionChangeEvent = true;
var template = comboBox.SelectedItem as TemplateInformation;
uint ord = template.Ord;
viewModel.RemoveTemplate(template.Ord);
if (ord > 0)
comboBox.SelectedItem = viewModel.Templates[(int)ord - 1];
else
comboBox.SelectedItem = viewModel.Templates[0];
ComboBoxSelectionChangedEvent?.Invoke(comboBox, e);
isSuppressComboxSelectionChangeEvent = false;
MainPage.UserPrefs.IsFullSyncRequire = true;
SaveEvent?.Invoke(sender, null);
}
private void RenameMenuFlyoutItemClickHandler(object sender, RoutedEventArgs e)
{
if (renameFlyout == null)
{
renameFlyout = new NameEnterFlyout();
renameFlyout.OkButtonClickEvent += RenameTemplateFlyoutOKButtonClickHandler;
}
renameFlyout.Show(editButton);
}
private async void RenameTemplateFlyoutOKButtonClickHandler(object sender, RoutedEventArgs e)
{
string name = renameFlyout.NewName;
bool isValid = await CheckNameValid(name);
if (!isValid)
{
renameFlyout.Show(editButton);
return;
}
isSuppressComboxSelectionChangeEvent = true;
var template = comboBox.SelectedItem as TemplateInformation;
viewModel.RenameTemplate(name, template.Ord);
ChangeSelectedItem(template.Ord);
isSuppressComboxSelectionChangeEvent = false;
SaveEvent?.Invoke(sender, null);
}
private void EditButtonClickHandler(object sender, RoutedEventArgs e)
{
if (editMenuFlyout == null)
{
editMenuFlyout = Resources["EditMenuFlyout"] as MenuFlyout;
editMenuFlyout.Placement = FlyoutPlacementMode.Bottom;
}
editMenuFlyout.ShowAt(editButton);
}
private void RepositionMenuFlyoutItemClickHandler(object sender, RoutedEventArgs e)
{
if (respositionFlyout == null)
{
respositionFlyout = new IntNumberEnterFlyout();
respositionFlyout.OKButtonClickEvent += ReposOKButtonClickHandler;
}
var maxOrder = viewModel.Templates.Count;
var textToShow = "Enter new position (1..." + maxOrder + ")";
respositionFlyout.Number = 1;
respositionFlyout.Show(editButton, textToShow, maxOrder, 1);
}
private void ReposOKButtonClickHandler(object sender, RoutedEventArgs e)
{
isSuppressComboxSelectionChangeEvent = true;
var currentOrd = (comboBox.SelectedItem as TemplateInformation).Ord;
var newOrd = respositionFlyout.Number - 1;
viewModel.RepositionTemplate(currentOrd, newOrd);
ChangeSelectedItem(newOrd);
isSuppressComboxSelectionChangeEvent = false;
SaveEvent?.Invoke(sender, null);
}
private void FliptMenuFlyoutItemClickHandler(object sender, RoutedEventArgs e)
{
FlipButtonClick?.Invoke(sender, e);
FlipCardEvent?.Invoke();
}
}
}
| agpl-3.0 |
protyposis/Aurio | Aurio/Aurio.Soxr.UnitTest/SoxResamplerTest.cs | 8728 | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Aurio.Soxr.UnitTest {
[TestClass]
public class SoxResamplerTest {
[TestMethod]
public void CreateInstance() {
var r = new SoxResampler(44100, 96000, 2);
Assert.IsNotNull(r);
}
[TestMethod]
public void CreateAndDestroyLotsOfInstancesAndProcess() {
var r = new SoxResampler(44100, 96000, 2);
int count = 1000;
var instances = new SoxResampler[count];
var dataIn = new byte[80000];
var dataOut = new byte[80000];
int readIn = 0, readOut = 0;
for (int i = 0; i < count; i++) {
instances[i] = new SoxResampler(5.0, 1.0, 2, QualityRecipe.SOXR_HQ, QualityFlags.SOXR_VR);
instances[i].Process(dataIn, 0, dataIn.Length, dataOut, 0, dataOut.Length, false, out readIn, out readOut);
}
for (int i = 0; i < count; i++) {
instances[i].Dispose();
}
}
[TestMethod]
[ExpectedException(typeof(SoxrException), "Invalid instantiation parameter didn't raise exception")]
public void CreateInvalidInstance() {
/* A negative input rate is invalid and should return in an error that triggers an exception.
* Other invalid parameters should also trigger an exception, but we do not test them all. This test
* only assures that the error reading works correctly. */
new SoxResampler(-44100, 96000, 2);
}
[TestMethod]
public void CreateVariableRateInstance() {
var r = new SoxResampler(2.0, 1.0, 1, QualityRecipe.SOXR_HQ, QualityFlags.SOXR_VR);
}
[TestMethod]
[ExpectedException(typeof(SoxrException), "Invalid instantiation parameter didn't raise exception")]
public void CreateInvalidVariableRateInstance() {
var r = new SoxResampler(2.0, 1.0, 1, QualityRecipe.SOXR_LQ, QualityFlags.SOXR_VR);
}
[TestMethod]
public void VersionReturnsString() {
var r = new SoxResampler(44100, 96000, 2);
string v = r.Version;
StringAssert.StartsWith(v, "libsoxr-", "invalid version string returned");
Console.WriteLine(v);
}
[TestMethod]
public void EngineReturnsString() {
var r = new SoxResampler(44100, 96000, 2);
string e = r.Engine;
Assert.IsNotNull(e, "no engine string returned");
Console.WriteLine(e);
}
[TestMethod]
public void ClearInternalState() {
var r = new SoxResampler(44100, 96000, 2);
r.Clear();
}
[TestMethod]
public void CheckDelay() {
var r = new SoxResampler(44100, 96000, 2);
// When no samples have been fed to the resampler, there can't be an output delay
Assert.AreEqual(0, r.GetOutputDelay(), "unexpected output delay");
}
[TestMethod]
public void ProcessWithoutResampling() {
var r = new SoxResampler(1.0d, 1.0d, 1);
int inSize = 12;
int outSize = 12;
var sampleDataIn = new byte[inSize];
var sampleDataOut = new byte[outSize];
int inputLengthUsed = 0;
int outputLengthGenerated = 0;
int remainingIn = inSize;
int totalIn = 0, totalOut = 0;
do {
r.Process(sampleDataIn, 0, remainingIn, sampleDataOut, 0, outSize,
remainingIn == 0, out inputLengthUsed, out outputLengthGenerated);
totalIn += inputLengthUsed;
totalOut += outputLengthGenerated;
remainingIn -= inputLengthUsed;
}
while (inputLengthUsed > 0 || outputLengthGenerated > 0);
Assert.AreEqual(inSize, totalIn, "not all data has been read");
Assert.AreEqual(outSize, totalOut, "not all data has been put out");
}
[TestMethod]
public void ProcessHugeBlock() {
var r = new SoxResampler(1.0d, 1.0d, 1);
int inSize = 15360;
int outSize = 15360;
var sampleDataIn = new byte[inSize];
var sampleDataOut = new byte[outSize];
int inputLengthUsed = 0;
int outputLengthGenerated = 0;
int remainingIn = inSize;
int totalIn = 0, totalOut = 0;
do {
r.Process(sampleDataIn, 0, remainingIn, sampleDataOut, 0, outSize,
remainingIn == 0, out inputLengthUsed, out outputLengthGenerated);
totalIn += inputLengthUsed;
totalOut += outputLengthGenerated;
remainingIn -= inputLengthUsed;
}
while (inputLengthUsed > 0 || outputLengthGenerated > 0);
Assert.AreEqual(inSize, totalIn, "not all data has been read");
Assert.AreEqual(outSize, totalOut, "not all data has been put out");
}
[TestMethod]
public void ProcessRateDouble() {
var r = new SoxResampler(48000, 96000, 1);
int inSize = 12;
int outSize = 12;
var sampleDataIn = new byte[inSize];
var sampleDataOut = new byte[outSize];
int inputLengthUsed = 0;
int outputLengthGenerated = 0;
int remainingIn = inSize;
int totalIn = 0, totalOut = 0;
do {
r.Process(sampleDataIn, 0, remainingIn, sampleDataOut, 0, outSize,
remainingIn == 0, out inputLengthUsed, out outputLengthGenerated);
totalIn += inputLengthUsed;
totalOut += outputLengthGenerated;
remainingIn -= inputLengthUsed;
}
while (inputLengthUsed > 0 || outputLengthGenerated > 0);
Assert.AreEqual(inSize, totalIn, "not all data has been read");
Assert.AreEqual(inSize * 2, totalOut, "not all data has been put out");
}
[TestMethod]
public void ProcessRateHalf() {
var r = new SoxResampler(1.0d, 0.5d, 1);
int inSize = 4 * 10;
int outSize = 12;
var sampleDataIn = new byte[inSize];
var sampleDataOut = new byte[outSize];
int inputLengthUsed = 0;
int outputLengthGenerated = 0;
int remainingIn = inSize;
int totalIn = 0, totalOut = 0;
do {
r.Process(sampleDataIn, 0, remainingIn, sampleDataOut, 0, outSize,
remainingIn == 0, out inputLengthUsed, out outputLengthGenerated);
totalIn += inputLengthUsed;
totalOut += outputLengthGenerated;
remainingIn -= inputLengthUsed;
}
while (inputLengthUsed > 0 || outputLengthGenerated > 0);
Assert.AreEqual(inSize, totalIn, "not all data has been read");
Assert.AreEqual(inSize / 2, totalOut, "not all data has been put out");
}
[TestMethod]
[ExpectedException(typeof(SoxrException), "Illegal call didn't raise exception")]
public void IllegalRateChange() {
var r = new SoxResampler(1.0, 1.0, 1);
// This call is illegal because a fixed-rate resampler was instantiated
r.SetRatio(2.0, 0);
}
[TestMethod]
[ExpectedException(typeof(SoxrException), "Invalid rate change didn't raise exception")]
public void InvalidRateChangeAboveMax() {
var r = new SoxResampler(2.0, 1.0, 1, QualityRecipe.SOXR_HQ, QualityFlags.SOXR_VR);
// This ratio is invalid because it is higher than the max ratio specified in the constructor
r.SetRatio(3.0, 0);
}
[TestMethod]
[ExpectedException(typeof(SoxrException), "Invalid rate change didn't raise exception")]
public void InvalidRateChangeNegative() {
var r = new SoxResampler(2.0, 1.0, 1, QualityRecipe.SOXR_HQ, QualityFlags.SOXR_VR);
// A negative ratio is impossible
r.SetRatio(-1.0, 0);
}
[TestMethod]
public void RateChange() {
var r = new SoxResampler(2.0, 1.0, 1, QualityRecipe.SOXR_HQ, QualityFlags.SOXR_VR);
r.SetRatio(1.5, 0);
}
[TestMethod]
public void DisposeTest() {
var r = new SoxResampler(1.0, 1.0, 1);
r.Dispose();
r.Dispose(); // call a second time to check for repeated calls working
}
}
}
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/operator/features/weighting/ForestBasedWeighting.java | 8597 | /**
* 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.operator.features.weighting;
import static com.rapidminer.operator.features.weighting.AbstractWeighting.PARAMETER_NORMALIZE_WEIGHTS;
import static com.rapidminer.operator.learner.tree.AbstractTreeLearner.CRITERIA_NAMES;
import static com.rapidminer.operator.learner.tree.AbstractTreeLearner.CRITERION_GAIN_RATIO;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.rapidminer.example.AttributeWeights;
import com.rapidminer.gui.renderer.RendererService;
import com.rapidminer.operator.Model;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.PortUserError;
import com.rapidminer.operator.learner.meta.MetaModel;
import com.rapidminer.operator.learner.tree.ConfigurableRandomForestModel;
import com.rapidminer.operator.learner.tree.Edge;
import com.rapidminer.operator.learner.tree.RandomForestModel;
import com.rapidminer.operator.learner.tree.Tree;
import com.rapidminer.operator.learner.tree.TreeModel;
import com.rapidminer.operator.learner.tree.criterions.AbstractCriterion;
import com.rapidminer.operator.learner.tree.criterions.Criterion;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.OutputPort;
import com.rapidminer.operator.ports.metadata.CompatibilityLevel;
import com.rapidminer.operator.ports.metadata.ExampleSetMetaData;
import com.rapidminer.operator.ports.metadata.MetaData;
import com.rapidminer.operator.ports.metadata.ModelMetaData;
import com.rapidminer.operator.ports.metadata.SimplePrecondition;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeBoolean;
import com.rapidminer.parameter.ParameterTypeStringCategory;
/**
* This weighting schema will use a given random forest to extract the implicit importance of the
* used attributes. Therefore each node is visited and the benefit created by the respective split
* is aggregated for the attribute the split was performed on. The mean benefit over all nodes in
* all trees is used as importance.
*
* @author Sebastian Land
*/
@SuppressWarnings("deprecation")
public class ForestBasedWeighting extends Operator {
/**
* The parameter name for "Specifies the used criterion for selecting attributes and
* numerical splits."
*/
public static final String PARAMETER_CRITERION = "criterion";
private InputPort forestInput = getInputPorts().createPort("random forest");
private OutputPort weightsOutput = getOutputPorts().createPort("weights");
private OutputPort forestOutput = getOutputPorts().createPort("random forest");
/**
* {@link ModelMetaData} that accepts both {@link RandomForestModel}s and
* {@link ConfigurableRandomForestModel}s.
*
* @author Michael Knopf
* @since 7.0.0
*/
public static class RandomForestModelMetaData extends ModelMetaData {
private static final long serialVersionUID = 1L;
public RandomForestModelMetaData() {
super(ConfigurableRandomForestModel.class, new ExampleSetMetaData());
}
@Override
public boolean isCompatible(MetaData isData, CompatibilityLevel level) {
if (RandomForestModel.class.isAssignableFrom(isData.getObjectClass())) {
return true;
}
return super.isCompatible(isData, level);
}
}
public ForestBasedWeighting(OperatorDescription description) {
super(description);
forestInput.addPrecondition(new SimplePrecondition(forestInput, new RandomForestModelMetaData(), true));
getTransformer().addPassThroughRule(forestInput, forestOutput);
getTransformer().addGenerationRule(weightsOutput, AttributeWeights.class);
}
@Override
public void doWork() throws OperatorException {
// The old and new random forest model implementations are not related (class hierarchy).
// Thus, Port#getData() would fail for one or the other. For this reason, the implementation
// below request the common super-type Model and performs the compatibility check manually.
Model forest = forestInput.getData(Model.class);
if (!(forest instanceof MetaModel)
|| !(forest instanceof ConfigurableRandomForestModel || forest instanceof RandomForestModel)) {
PortUserError error = new PortUserError(forestInput, 156, RendererService.getName(forest.getClass()),
forestInput.getName(), RendererService.getName(ConfigurableRandomForestModel.class));
error.setExpectedType(ConfigurableRandomForestModel.class);
error.setActualType(forest.getClass());
throw error;
}
String[] labelValues = forest.getTrainingHeader().getAttributes().getLabel().getMapping().getValues()
.toArray(new String[0]);
// now start measuring weights
Criterion criterion = AbstractCriterion.createCriterion(this, 0);
HashMap<String, Double> attributeBenefitMap = new HashMap<>();
for (Model model : ((MetaModel) forest).getModels()) {
TreeModel treeModel = (TreeModel) model;
extractWeights(attributeBenefitMap, criterion, treeModel.getRoot(), labelValues);
}
AttributeWeights weights = new AttributeWeights();
int numberOfModels = ((MetaModel) forest).getModels().size();
for (Entry<String, Double> entry : attributeBenefitMap.entrySet()) {
weights.setWeight(entry.getKey(), entry.getValue() / numberOfModels);
}
if (getParameterAsBoolean(PARAMETER_NORMALIZE_WEIGHTS)) {
weights.normalize();
}
weightsOutput.deliver(weights);
forestOutput.deliver(forest);
}
private void extractWeights(HashMap<String, Double> attributeBenefitMap, Criterion criterion, Tree root,
String[] labelValues) {
if (!root.isLeaf()) {
int numberOfChildren = root.getNumberOfChildren();
double[][] weights = new double[numberOfChildren][];
String attributeName = null;
Iterator<Edge> childIterator = root.childIterator();
int i = 0;
while (childIterator.hasNext()) {
Edge edge = childIterator.next();
// retrieve attributeName: On each edge the same
attributeName = edge.getCondition().getAttributeName();
// retrieve weights after split: Weight in child
Map<String, Integer> subtreeCounterMap = edge.getChild().getSubtreeCounterMap();
weights[i] = new double[labelValues.length];
for (int j = 0; j < labelValues.length; j++) {
Integer weight = subtreeCounterMap.get(labelValues[j]);
double weightValue = 0;
if (weight != null) {
weightValue = weight;
}
weights[i][j] = weightValue;
}
i++;
}
// calculate benefit and add to map
double benefit = criterion.getBenefit(weights);
Double knownBenefit = attributeBenefitMap.get(attributeName);
if (knownBenefit != null) {
benefit += knownBenefit;
}
attributeBenefitMap.put(attributeName, benefit);
// recursively descent to children
childIterator = root.childIterator();
while (childIterator.hasNext()) {
Tree child = childIterator.next().getChild();
extractWeights(attributeBenefitMap, criterion, child, labelValues);
}
}
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
ParameterTypeStringCategory type = new ParameterTypeStringCategory(PARAMETER_CRITERION,
"Specifies the used criterion for weighting attributes.", CRITERIA_NAMES,
CRITERIA_NAMES[CRITERION_GAIN_RATIO], false);
type.setExpert(false);
types.add(type);
types.add(new ParameterTypeBoolean(PARAMETER_NORMALIZE_WEIGHTS, "Activates the normalization of all weights.", false,
false));
return types;
}
}
| agpl-3.0 |
USAID-DELIVER-PROJECT/elmis | modules/core/src/main/java/org/openlmis/core/repository/GeographicZoneRepository.java | 4356 | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* 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. For additional information contact info@OpenLMIS.org.
*/
package org.openlmis.core.repository;
import lombok.NoArgsConstructor;
import org.openlmis.core.domain.Facility;
import org.openlmis.core.domain.GeographicLevel;
import org.openlmis.core.domain.GeographicZone;
import org.openlmis.core.domain.Pagination;
import org.openlmis.core.exception.DataException;
import org.openlmis.core.repository.helper.CommaSeparator;
import org.openlmis.core.repository.mapper.GeographicLevelMapper;
import org.openlmis.core.repository.mapper.GeographicZoneMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* GeographicZoneRepository is repository class for GeographicZone related database operations.
*/
@Repository
@NoArgsConstructor
public class GeographicZoneRepository {
private GeographicZoneMapper mapper;
private GeographicLevelMapper geographicLevelMapper;
@Autowired
private CommaSeparator<Facility> facilityCommaSeparator;
@Autowired
public GeographicZoneRepository(GeographicZoneMapper mapper, GeographicLevelMapper geographicLevelMapper) {
this.mapper = mapper;
this.geographicLevelMapper = geographicLevelMapper;
}
public GeographicZone getByCode(String code) {
return mapper.getGeographicZoneByCode(code);
}
public Integer getLowestGeographicLevel() {
return geographicLevelMapper.getLowestGeographicLevel();
}
public List<GeographicZone> getAllGeographicZones() {
return mapper.getAllGeographicZones();
}
public void save(GeographicZone zone) {
try {
if (zone.getId() == null) {
mapper.insert(zone);
return;
}
mapper.update(zone);
} catch (DuplicateKeyException e) {
throw new DataException("error.duplicate.geographic.zone.code");
} catch (DataIntegrityViolationException e) {
throw new DataException("error.incorrect.length");
}
}
public GeographicLevel getGeographicLevelByCode(String code) {
return mapper.getGeographicLevelByCode(code);
}
public GeographicZone getById(Long id) {
return mapper.getWithParentById(id);
}
public List<GeographicZone> searchByParentName(String searchParam, Pagination pagination) {
return mapper.searchByParentName(searchParam, pagination);
}
public List<GeographicZone> searchByName(String searchParam, Pagination pagination) {
return mapper.searchByName(searchParam, pagination);
}
public List<GeographicLevel> getAllGeographicLevels() {
return geographicLevelMapper.getAll();
}
public List<GeographicZone> getAllGeographicZonesAbove(GeographicLevel geographicLevel) {
return mapper.getAllGeographicZonesAbove(geographicLevel);
}
public Integer getTotalParentSearchResultCount(String param) {
return mapper.getTotalParentSearchResultCount(param);
}
public Integer getTotalSearchResultCount(String param) {
return mapper.getTotalSearchResultCount(param);
}
public List<GeographicZone> getGeographicZonesByCodeOrName(String searchParam) {
return mapper.getGeographicZonesByCodeOrName(searchParam);
}
public Integer getGeographicZonesCountBy(String searchParam) {
return mapper.getGeographicZonesCountBy(searchParam);
}
public List<GeographicZone> getDistrictsFor(List<Facility> facilities) {
return mapper.getDistrictsForFacilities(facilityCommaSeparator.commaSeparateIds(facilities));
}
}
| agpl-3.0 |
epforgpl/web-parldata.eu | wp-content/themes/scribe/admin/page-builder/blocks/countdown-block.php | 1606 | <?php
class PG_Countdown_Block extends AQ_Block {
//set and create block
function __construct() {
$block_options = array(
'name' => 'Countdown',
'size' => 'span6',
);
//create the block
parent::__construct('pg_countdown_block', $block_options);
}
function form($instance) {
$defaults = array(
'text' => '',
'wp_autop' => 0
);
$instance = wp_parse_args($instance, $defaults);
extract($instance);
?>
<p class="description">
<label for="<?php echo $this->get_field_id('title') ?>">
Title (optional)
<?php echo aq_field_input('title', $block_id, $title, $size = 'full') ?>
</label>
</p>
<p class="description">
<label for="<?php echo $this->get_field_id('countdown') ?>">
Date (format: 2014/09/24)
<?php echo aq_field_input('countdown', $block_id, $countdown, $size = 'full') ?>
</label>
</p>
<?php
}
function block($instance) {
extract($instance);
?>
<section class="countdown">
<div class="col-sm-12 col-md-12 col-lg-12 text-center">
<h3><?php echo strip_tags($title) ?></h3>
<h4 class="subtitle"></h4>
<h1 id="countdown">42 weeks 01 days <br> 01:57:04</h1>
</section>
<script>
//The Final Countdown for jQuery v2.0.2 (http://hilios.github.io/jQuery.countdown/)
// * Copyright (c) 2013 Edson Hilios
// just change year and date
jQuery(document).ready(function () {
jQuery('#countdown').countdown('<?php echo do_shortcode(htmlspecialchars_decode($countdown)) ?>', function(event) {
jQuery(this).html(event.strftime('%w weeks %d days <br /> %H:%M:%S'));
});
});
</script>
<?php
}
}
| agpl-3.0 |
BlaBlaNet/BlaBlaNet | extend/addon/blablanet/openid/Mod_Openid.php | 6160 | <?php
namespace GeditLab\Module;
require_once('library/openid/openid.php');
require_once('include/auth.php');
class Openid extends \GeditLab\Web\Controller {
function get() {
$noid = get_config('system','disable_openid');
if($noid)
goaway(z_root());
logger('mod_openid ' . print_r($_REQUEST,true), LOGGER_DATA);
if(x($_REQUEST,'openid_mode')) {
$openid = new LightOpenID(z_root());
if($openid->validate()) {
logger('openid: validate');
$authid = normalise_openid($_REQUEST['openid_identity']);
if(! strlen($authid)) {
logger( t('OpenID protocol error. No ID returned.') . EOL);
goaway(z_root());
}
$x = match_openid($authid);
if($x) {
$r = q("select * from channel where channel_id = %d limit 1",
intval($x)
);
if($r) {
$y = q("select * from account where account_id = %d limit 1",
intval($r[0]['channel_account_id'])
);
if($y) {
foreach($y as $record) {
if(($record['account_flags'] == ACCOUNT_OK) || ($record['account_flags'] == ACCOUNT_UNVERIFIED)) {
logger('mod_openid: openid success for ' . $x[0]['channel_name']);
$_SESSION['uid'] = $r[0]['channel_id'];
$_SESSION['account_id'] = $r[0]['channel_account_id'];
$_SESSION['authenticated'] = true;
authenticate_success($record,$r[0],true,true,true,true);
goaway(z_root());
}
}
}
}
}
// Successful OpenID login - but we can't match it to an existing account.
// See if they've got an xchan
$r = q("select * from xconfig left join xchan on xchan_hash = xconfig.xchan where cat = 'system' and k = 'openid' and v = '%s' limit 1",
dbesc($authid)
);
if($r) {
$_SESSION['authenticated'] = 1;
$_SESSION['visitor_id'] = $r[0]['xchan_hash'];
$_SESSION['my_url'] = $r[0]['xchan_url'];
$_SESSION['my_address'] = $r[0]['xchan_addr'];
$arr = array('xchan' => $r[0], 'session' => $_SESSION);
call_hooks('magic_auth_openid_success',$arr);
\App::set_observer($r[0]);
require_once('include/security.php');
\App::set_groups(init_groups_visitor($_SESSION['visitor_id']));
info(sprintf( t('Welcome %s. Remote authentication successful.'),$r[0]['xchan_name']));
logger('mod_openid: remote auth success from ' . $r[0]['xchan_addr']);
if($_SESSION['return_url'])
goaway($_SESSION['return_url']);
goaway(z_root());
}
// no xchan...
// create one.
// We should probably probe the openid url and figure out if they have any kind of
// social presence we might be able to scrape some identifying info from.
$name = $authid;
$url = trim($_REQUEST['openid_identity'],'/');
if(strpos($url,'http') === false)
$url = 'https://' . $url;
$pphoto = z_root() . '/' . get_default_profile_photo();
$parsed = @parse_url($url);
if($parsed) {
$host = $parsed['host'];
}
$attr = $openid->getAttributes();
if(is_array($attr) && count($attr)) {
foreach($attr as $k => $v) {
if($k === 'namePerson/friendly')
$nick = notags(trim($v));
if($k === 'namePerson/first')
$first = notags(trim($v));
if($k === 'namePerson')
$name = notags(trim($v));
if($k === 'contact/email')
$addr = notags(trim($v));
if($k === 'media/image/aspect11')
$photosq = trim($v);
if($k === 'media/image/default')
$photo_other = trim($v);
}
}
if(! $nick) {
if($first)
$nick = $first;
else
$nick = $name;
}
require_once('library/urlify/URLify.php');
$x = strtolower(\URLify::transliterate($nick));
if($nick & $host)
$addr = $nick . '@' . $host;
$network = 'unknown';
if($photosq)
$pphoto = $photosq;
elseif($photo_other)
$pphoto = $photo_other;
$mimetype = guess_image_type($pphoto);
$x = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_mimetype,
xchan_photo_l, xchan_addr, xchan_url, xchan_connurl, xchan_follow, xchan_connpage, xchan_name, xchan_network, xchan_photo_date,
xchan_name_date, xchan_hidden)
values ( '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', 1) ",
dbesc($url),
dbesc(''),
dbesc(''),
dbesc(''),
dbesc($mimetype),
dbesc($pphoto),
dbesc($addr),
dbesc($url),
dbesc(''),
dbesc(''),
dbesc(''),
dbesc($name),
dbesc($network),
dbesc(datetime_convert()),
dbesc(datetime_convert())
);
if($x) {
$r = q("select * from xchan where xchan_hash = '%s' limit 1",
dbesc($url)
);
if($r) {
$photos = import_xchan_photo($pphoto,$url);
if($photos) {
$z = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s',
xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'",
dbesc(datetime_convert()),
dbesc($photos[0]),
dbesc($photos[1]),
dbesc($photos[2]),
dbesc($photos[3]),
dbesc($url)
);
}
set_xconfig($url,'system','openid',$authid);
$_SESSION['authenticated'] = 1;
$_SESSION['visitor_id'] = $r[0]['xchan_hash'];
$_SESSION['my_url'] = $r[0]['xchan_url'];
$_SESSION['my_address'] = $r[0]['xchan_addr'];
$arr = array('xchan' => $r[0], 'session' => $_SESSION);
call_hooks('magic_auth_openid_success',$arr);
\App::set_observer($r[0]);
info(sprintf( t('Welcome %s. Remote authentication successful.'),$r[0]['xchan_name']));
logger('mod_openid: remote auth success from ' . $r[0]['xchan_addr']);
if($_SESSION['return_url'])
goaway($_SESSION['return_url']);
goaway(z_root());
}
}
}
}
notice( t('Login failed.') . EOL);
goaway(z_root());
// NOTREACHED
}
}
| agpl-3.0 |
maandree/tbrpg | src/MediumShield.cc | 3974 | // -*- mode: c++ , coding: utf-8 -*-
/**
* tbrpg – Text based roll playing game
*
* Copyright © 2012, 2013 Mattias Andrée (maandree@kth.se)
*
* 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 "MediumShield.hpp"
/**
* Text based roll playing game
*
* DD2387 Program construction with C++
* Laboration 3
*
* @author Mattias Andrée <maandree@kth.se>
*/
namespace tbrpg
{
/**
* Constructor
*/
MediumShield::MediumShield() : Shield()
{
this->class_inheritance.push_back(70);
this->name = "medium shield";
this->weight = 3150;
this->unit_value = 670;
}
/**
* Copy constructor
*
* @param original The object to clone
*/
MediumShield::MediumShield(const MediumShield& original) : Shield(original)
{
(void) original;
}
/**
* Copy constructor
*
* @param original The object to clone
*/
MediumShield::MediumShield(MediumShield& original) : Shield(original)
{
(void) original;
}
/**
* Move constructor
*
* @param original The object to clone
*/
MediumShield::MediumShield(MediumShield&& original) : Shield(original)
{
(void) original;
}
/**
* Fork the object
*
* @return A fork of the object
*/
Object* MediumShield::fork() const
{
return (Object*)(new MediumShield(*this));
}
/**
* Destructor
*/
MediumShield::~MediumShield()
{
// do nothing
}
/**
* Assignment operator
*
* @param original The reference object
* @return The invoked object
*/
MediumShield& MediumShield::operator =(const MediumShield& original)
{
Shield::__copy__((Shield&)*this, (Shield&)original);
return *this;
}
/**
* Assignment operator
*
* @param original The reference object
* @return The invoked object
*/
MediumShield& MediumShield::operator =(MediumShield& original)
{
Shield::__copy__((Shield&)*this, (Shield&)original);
return *this;
}
/**
* Move operator
*
* @param original The moved object, its resourced will be moved
* @return The invoked object
*/
MediumShield& MediumShield::operator =(MediumShield&& original)
{
std::swap((Shield&)*this, (Shield&)original);
return *this;
}
/**
* Equality evaluator
*
* @param other The other comparand
* @return Whether the instances are equal
*/
bool MediumShield::operator ==(const MediumShield& other) const
{
if ((Shield&)(*this) != (Shield&)other) return false;
return true;
}
/**
* Inequality evaluator
*
* @param other The other comparand
* @return Whether the instances are not equal
*/
bool MediumShield::operator !=(const MediumShield& other) const
{
return (*this == other) == false;
}
/**
* Copy method
*
* @param self The object to modify
* @param original The reference object
*/
void MediumShield::__copy__(MediumShield& self, const MediumShield& original)
{
self = original;
}
/**
* Hash method
*
* @return The object's hash code
*/
size_t MediumShield::hash() const
{
size_t rc = 0;
rc = (rc * 3) ^ ((rc >> (sizeof(size_t) << 2)) * 3);
rc += std::hash<Shield>()(*this);
return rc;
}
}
| agpl-3.0 |
Intermesh/groupoffice-webclient | app/core/directives/form/autoselect-directive.js | 744 | 'use strict';
/**
* @ngdoc directive
* @name GO.Core.goAutoselect
* @element input
*
* @description
* Put autofocus on an input. The standard autofocus attribute doesn't work on
* firefox
*
* @example
<input ng-Model="text" go-autoselect="{expression}" />
*/
angular.module('GO.Core')
.directive('goAutoselect', ['$timeout',function($timeout) {
return {
scope: {
trigger: '@focus',
autoselect: '='
},
link: function(scope, element) {
if(scope.autofocus!==false){
scope.$watch('trigger', function(value) {
$timeout(function() {
element[0].select();
});
});
}
}
};
}]); | agpl-3.0 |
AsherBond/MondocosmOS | mangos/src/game/GameObject.cpp | 69079 | /*
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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
*/
#include "GameObject.h"
#include "QuestDef.h"
#include "ObjectMgr.h"
#include "PoolManager.h"
#include "SpellMgr.h"
#include "Spell.h"
#include "UpdateMask.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "World.h"
#include "Database/DatabaseEnv.h"
#include "LootMgr.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "InstanceData.h"
#include "MapManager.h"
#include "MapPersistentStateMgr.h"
#include "BattleGround.h"
#include "BattleGroundAV.h"
#include "Util.h"
#include "ScriptMgr.h"
#include <G3D/Quat.h>
GameObject::GameObject() : WorldObject(),
m_goInfo(NULL),
m_displayInfo(NULL)
{
m_objectType |= TYPEMASK_GAMEOBJECT;
m_objectTypeId = TYPEID_GAMEOBJECT;
m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_HAS_POSITION | UPDATEFLAG_POSITION | UPDATEFLAG_ROTATION);
m_valuesCount = GAMEOBJECT_END;
m_respawnTime = 0;
m_respawnDelayTime = 25;
m_lootState = GO_NOT_READY;
m_spawnedByDefault = true;
m_useTimes = 0;
m_spellId = 0;
m_cooldownTime = 0;
m_packedRotation = 0;
}
GameObject::~GameObject()
{
}
void GameObject::AddToWorld()
{
///- Register the gameobject for guid lookup
if(!IsInWorld())
GetMap()->GetObjectsStore().insert<GameObject>(GetObjectGuid(), (GameObject*)this);
Object::AddToWorld();
}
void GameObject::RemoveFromWorld()
{
///- Remove the gameobject from the accessor
if(IsInWorld())
{
// Remove GO from owner
if (ObjectGuid owner_guid = GetOwnerGuid())
{
if (Unit* owner = ObjectAccessor::GetUnit(*this,owner_guid))
owner->RemoveGameObject(this,false);
else
{
sLog.outError("Delete %s with SpellId %u LinkedGO %u that lost references to owner %s GO list. Crash possible later.",
GetGuidStr().c_str(), m_spellId, GetGOInfo()->GetLinkedGameObjectEntry(), owner_guid.GetString().c_str());
}
}
GetMap()->GetObjectsStore().erase<GameObject>(GetObjectGuid(), (GameObject*)NULL);
}
Object::RemoveFromWorld();
}
bool GameObject::Create(uint32 guidlow, uint32 name_id, Map *map, uint32 phaseMask, float x, float y, float z, float ang, QuaternionData rotation, uint8 animprogress, GOState go_state)
{
MANGOS_ASSERT(map);
Relocate(x,y,z,ang);
SetMap(map);
SetPhaseMask(phaseMask,false);
if(!IsPositionValid())
{
sLog.outError("Gameobject (GUID: %u Entry: %u ) not created. Suggested coordinates are invalid (X: %f Y: %f)",guidlow,name_id,x,y);
return false;
}
GameObjectInfo const* goinfo = ObjectMgr::GetGameObjectInfo(name_id);
if (!goinfo)
{
sLog.outErrorDb("Gameobject (GUID: %u) not created: Entry %u does not exist in `gameobject_template`. Map: %u (X: %f Y: %f Z: %f) ang: %f",guidlow, name_id, map->GetId(), x, y, z, ang);
return false;
}
Object::_Create(guidlow, goinfo->id, HIGHGUID_GAMEOBJECT);
m_goInfo = goinfo;
if (goinfo->type >= MAX_GAMEOBJECT_TYPE)
{
sLog.outErrorDb("Gameobject (GUID: %u) not created: Entry %u has invalid type %u in `gameobject_template`. It may crash client if created.",guidlow,name_id,goinfo->type);
return false;
}
SetObjectScale(goinfo->size);
SetWorldRotation(rotation.x,rotation.y,rotation.z,rotation.w);
// For most of gameobjects is (0, 0, 0, 1) quaternion, only some transports has not standart rotation
if (const GameObjectDataAddon * addon = sGameObjectDataAddonStorage.LookupEntry<GameObjectDataAddon>(guidlow))
SetTransportPathRotation(addon->path_rotation);
else
SetTransportPathRotation(QuaternionData(0,0,0,1));
SetUInt32Value(GAMEOBJECT_FACTION, goinfo->faction);
SetUInt32Value(GAMEOBJECT_FLAGS, goinfo->flags);
if (goinfo->type == GAMEOBJECT_TYPE_TRANSPORT)
SetFlag(GAMEOBJECT_FLAGS, (GO_FLAG_TRANSPORT | GO_FLAG_NODESPAWN));
SetEntry(goinfo->id);
SetDisplayId(goinfo->displayId);
// GAMEOBJECT_BYTES_1, index at 0, 1, 2 and 3
SetGoState(go_state);
SetGoType(GameobjectTypes(goinfo->type));
SetGoArtKit(0); // unknown what this is
SetGoAnimProgress(animprogress);
//Notify the map's instance data.
//Only works if you create the object in it, not if it is moves to that map.
//Normally non-players do not teleport to other maps.
if (InstanceData* iData = map->GetInstanceData())
iData->OnObjectCreate(this);
return true;
}
void GameObject::Update(uint32 update_diff, uint32 /*p_time*/)
{
if (GetObjectGuid().IsMOTransport())
{
//((Transport*)this)->Update(p_time);
return;
}
switch (m_lootState)
{
case GO_NOT_READY:
{
switch(GetGoType())
{
case GAMEOBJECT_TYPE_TRAP:
{
// Arming Time for GAMEOBJECT_TYPE_TRAP (6)
Unit* owner = GetOwner();
if (owner && ((Player*)owner)->isInCombat())
m_cooldownTime = time(NULL) + GetGOInfo()->trap.startDelay;
m_lootState = GO_READY;
break;
}
case GAMEOBJECT_TYPE_FISHINGNODE:
{
// fishing code (bobber ready)
if (time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME)
{
// splash bobber (bobber ready now)
Unit* caster = GetOwner();
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
SetGoState(GO_STATE_ACTIVE);
// SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
SendForcedObjectUpdate();
SendGameObjectCustomAnim(GetObjectGuid());
}
m_lootState = GO_READY; // can be successfully open with some chance
}
return;
}
default:
m_lootState = GO_READY; // for other GO is same switched without delay to GO_READY
break;
}
// NO BREAK for switch (m_lootState)
}
case GO_READY:
{
if (m_respawnTime > 0) // timer on
{
if (m_respawnTime <= time(NULL)) // timer expired
{
m_respawnTime = 0;
ClearAllUsesData();
switch (GetGoType())
{
case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now
{
Unit* caster = GetOwner();
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
caster->FinishSpell(CURRENT_CHANNELED_SPELL);
WorldPacket data(SMSG_FISH_NOT_HOOKED,0);
((Player*)caster)->GetSession()->SendPacket(&data);
}
// can be deleted
m_lootState = GO_JUST_DEACTIVATED;
return;
}
case GAMEOBJECT_TYPE_DOOR:
case GAMEOBJECT_TYPE_BUTTON:
//we need to open doors if they are closed (add there another condition if this code breaks some usage, but it need to be here for battlegrounds)
if (GetGoState() != GO_STATE_READY)
ResetDoorOrButton();
//flags in AB are type_button and we need to add them here so no break!
default:
if (!m_spawnedByDefault) // despawn timer
{
// can be despawned or destroyed
SetLootState(GO_JUST_DEACTIVATED);
return;
}
// respawn timer
GetMap()->Add(this);
break;
}
}
}
if (isSpawned())
{
// traps can have time and can not have
GameObjectInfo const* goInfo = GetGOInfo();
if (goInfo->type == GAMEOBJECT_TYPE_TRAP)
{
if (m_cooldownTime >= time(NULL))
return;
// traps
Unit* owner = GetOwner();
Unit* ok = NULL; // pointer to appropriate target if found any
bool IsBattleGroundTrap = false;
//FIXME: this is activation radius (in different casting radius that must be selected from spell data)
//TODO: move activated state code (cast itself) to GO_ACTIVATED, in this place only check activating and set state
float radius = float(goInfo->trap.radius);
if (!radius)
{
if (goInfo->trap.cooldown != 3) // cast in other case (at some triggering/linked go/etc explicit call)
return;
else
{
if (m_respawnTime > 0)
break;
// battlegrounds gameobjects has data2 == 0 && data5 == 3
radius = float(goInfo->trap.cooldown);
IsBattleGroundTrap = true;
}
}
// Note: this hack with search required until GO casting not implemented
// search unfriendly creature
if (owner && goInfo->trap.charges > 0) // hunter trap
{
MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, owner, radius);
MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> checker(ok, u_check);
Cell::VisitGridObjects(this,checker, radius);
if (!ok)
Cell::VisitWorldObjects(this,checker, radius);
}
else // environmental trap
{
// environmental damage spells already have around enemies targeting but this not help in case nonexistent GO casting support
// affect only players
Player* p_ok = NULL;
MaNGOS::AnyPlayerInObjectRangeCheck p_check(this, radius);
MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck> checker(p_ok, p_check);
Cell::VisitWorldObjects(this,checker, radius);
ok = p_ok;
}
if (ok)
{
Unit *caster = owner ? owner : ok;
caster->CastSpell(ok, goInfo->trap.spellId, true, NULL, NULL, GetObjectGuid());
// use template cooldown if provided
m_cooldownTime = time(NULL) + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4));
// count charges
if (goInfo->trap.charges > 0)
AddUse();
if (IsBattleGroundTrap && ok->GetTypeId() == TYPEID_PLAYER)
{
//BattleGround gameobjects case
if (((Player*)ok)->InBattleGround())
if (BattleGround *bg = ((Player*)ok)->GetBattleGround())
bg->HandleTriggerBuff(GetObjectGuid());
}
}
}
if (uint32 max_charges = goInfo->GetCharges())
{
if (m_useTimes >= max_charges)
{
m_useTimes = 0;
SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed
}
}
}
break;
}
case GO_ACTIVATED:
{
switch(GetGoType())
{
case GAMEOBJECT_TYPE_DOOR:
case GAMEOBJECT_TYPE_BUTTON:
if (GetGOInfo()->GetAutoCloseTime() && (m_cooldownTime < time(NULL)))
ResetDoorOrButton();
break;
case GAMEOBJECT_TYPE_GOOBER:
if (m_cooldownTime < time(NULL))
{
RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
SetLootState(GO_JUST_DEACTIVATED);
m_cooldownTime = 0;
}
break;
default:
break;
}
break;
}
case GO_JUST_DEACTIVATED:
{
// if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed
if (GetGoType() == GAMEOBJECT_TYPE_GOOBER)
{
uint32 spellId = GetGOInfo()->goober.spellId;
if (spellId)
{
for (GuidsSet::const_iterator itr = m_UniqueUsers.begin(); itr != m_UniqueUsers.end(); ++itr)
{
if (Player* owner = GetMap()->GetPlayer(*itr))
owner->CastSpell(owner, spellId, false, NULL, NULL, GetObjectGuid());
}
ClearAllUsesData();
}
SetGoState(GO_STATE_READY);
//any return here in case battleground traps
}
if (GetOwnerGuid())
{
if (Unit* owner = GetOwner())
owner->RemoveGameObject(this, false);
SetRespawnTime(0);
Delete();
return;
}
// burning flags in some battlegrounds, if you find better condition, just add it
if (GetGOInfo()->IsDespawnAtAction() || GetGoAnimProgress() > 0)
{
SendObjectDeSpawnAnim(GetObjectGuid());
// reset flags
if (GetMap()->Instanceable())
{
// In Instances GO_FLAG_LOCKED or GO_FLAG_NO_INTERACT are not changed
uint32 currentLockOrInteractFlags = GetUInt32Value(GAMEOBJECT_FLAGS) & (GO_FLAG_LOCKED | GO_FLAG_NO_INTERACT);
SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags & ~(GO_FLAG_LOCKED | GO_FLAG_NO_INTERACT) | currentLockOrInteractFlags);
}
else
SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
}
loot.clear();
SetLootState(GO_READY);
if (!m_respawnDelayTime)
return;
// since pool system can fail to roll unspawned object, this one can remain spawned, so must set respawn nevertheless
m_respawnTime = m_spawnedByDefault ? time(NULL) + m_respawnDelayTime : 0;
// if option not set then object will be saved at grid unload
if (sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATELY))
SaveRespawnTime();
// if part of pool, let pool system schedule new spawn instead of just scheduling respawn
if (uint16 poolid = sPoolMgr.IsPartOfAPool<GameObject>(GetGUIDLow()))
sPoolMgr.UpdatePool<GameObject>(*GetMap()->GetPersistentState(), poolid, GetGUIDLow());
// can be not in world at pool despawn
if (IsInWorld())
UpdateObjectVisibility();
break;
}
}
}
void GameObject::Refresh()
{
// not refresh despawned not casted GO (despawned casted GO destroyed in all cases anyway)
if(m_respawnTime > 0 && m_spawnedByDefault)
return;
if(isSpawned())
GetMap()->Add(this);
}
void GameObject::AddUniqueUse(Player* player)
{
AddUse();
if (!m_firstUser)
m_firstUser = player->GetObjectGuid();
m_UniqueUsers.insert(player->GetObjectGuid());
}
void GameObject::Delete()
{
SendObjectDeSpawnAnim(GetObjectGuid());
SetGoState(GO_STATE_READY);
SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
if (uint16 poolid = sPoolMgr.IsPartOfAPool<GameObject>(GetGUIDLow()))
sPoolMgr.UpdatePool<GameObject>(*GetMap()->GetPersistentState(), poolid, GetGUIDLow());
else
AddObjectToRemoveList();
}
void GameObject::getFishLoot(Loot *fishloot, Player* loot_owner)
{
fishloot->clear();
uint32 zone, subzone;
GetZoneAndAreaId(zone,subzone);
// if subzone loot exist use it
if (!fishloot->FillLoot(subzone, LootTemplates_Fishing, loot_owner, true, (subzone != zone)) && subzone != zone)
// else use zone loot (if zone diff. from subzone, must exist in like case)
fishloot->FillLoot(zone, LootTemplates_Fishing, loot_owner, true);
}
void GameObject::SaveToDB()
{
// this should only be used when the gameobject has already been loaded
// preferably after adding to map, because mapid may not be valid otherwise
GameObjectData const *data = sObjectMgr.GetGOData(GetGUIDLow());
if(!data)
{
sLog.outError("GameObject::SaveToDB failed, cannot get gameobject data!");
return;
}
SaveToDB(GetMapId(), data->spawnMask, data->phaseMask);
}
void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
{
const GameObjectInfo *goI = GetGOInfo();
if (!goI)
return;
// update in loaded data (changing data only in this place)
GameObjectData& data = sObjectMgr.NewGOData(GetGUIDLow());
// data->guid = guid don't must be update at save
data.id = GetEntry();
data.mapid = mapid;
data.phaseMask = phaseMask;
data.posX = GetPositionX();
data.posY = GetPositionY();
data.posZ = GetPositionZ();
data.orientation = GetOrientation();
data.rotation.x = m_worldRotation.x;
data.rotation.y = m_worldRotation.y;
data.rotation.z = m_worldRotation.z;
data.rotation.w = m_worldRotation.w;
data.spawntimesecs = m_spawnedByDefault ? (int32)m_respawnDelayTime : -(int32)m_respawnDelayTime;
data.animprogress = GetGoAnimProgress();
data.go_state = GetGoState();
data.spawnMask = spawnMask;
// updated in DB
std::ostringstream ss;
ss << "INSERT INTO gameobject VALUES ( "
<< GetGUIDLow() << ", "
<< GetEntry() << ", "
<< mapid << ", "
<< uint32(spawnMask) << "," // cast to prevent save as symbol
<< uint16(GetPhaseMask()) << "," // prevent out of range error
<< GetPositionX() << ", "
<< GetPositionY() << ", "
<< GetPositionZ() << ", "
<< GetOrientation() << ", "
<< m_worldRotation.x << ", "
<< m_worldRotation.y << ", "
<< m_worldRotation.z << ", "
<< m_worldRotation.w << ", "
<< m_respawnDelayTime << ", "
<< uint32(GetGoAnimProgress()) << ", "
<< uint32(GetGoState()) << ")";
WorldDatabase.BeginTransaction();
WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", GetGUIDLow());
WorldDatabase.PExecuteLog("%s", ss.str().c_str());
WorldDatabase.CommitTransaction();
}
bool GameObject::LoadFromDB(uint32 guid, Map *map)
{
GameObjectData const* data = sObjectMgr.GetGOData(guid);
if( !data )
{
sLog.outErrorDb("Gameobject (GUID: %u) not found in table `gameobject`, can't load. ",guid);
return false;
}
uint32 entry = data->id;
//uint32 map_id = data->mapid; // already used before call
uint32 phaseMask = data->phaseMask;
float x = data->posX;
float y = data->posY;
float z = data->posZ;
float ang = data->orientation;
uint8 animprogress = data->animprogress;
GOState go_state = data->go_state;
if (!Create(guid,entry, map, phaseMask, x, y, z, ang, data->rotation, animprogress, go_state))
return false;
if (!GetGOInfo()->GetDespawnPossibility() && !GetGOInfo()->IsDespawnAtAction() && data->spawntimesecs >= 0)
{
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
m_spawnedByDefault = true;
m_respawnDelayTime = 0;
m_respawnTime = 0;
}
else
{
if(data->spawntimesecs >= 0)
{
m_spawnedByDefault = true;
m_respawnDelayTime = data->spawntimesecs;
m_respawnTime = map->GetPersistentState()->GetGORespawnTime(GetGUIDLow());
// ready to respawn
if (m_respawnTime && m_respawnTime <= time(NULL))
{
m_respawnTime = 0;
map->GetPersistentState()->SaveGORespawnTime(GetGUIDLow(), 0);
}
}
else
{
m_spawnedByDefault = false;
m_respawnDelayTime = -data->spawntimesecs;
m_respawnTime = 0;
}
}
return true;
}
struct GameObjectRespawnDeleteWorker
{
explicit GameObjectRespawnDeleteWorker(uint32 guid) : i_guid(guid) {}
void operator() (MapPersistentState* state)
{
state->SaveGORespawnTime(i_guid, 0);
}
uint32 i_guid;
};
void GameObject::DeleteFromDB()
{
if (!HasStaticDBSpawnData())
{
DEBUG_LOG("Trying to delete not saved gameobject!");
return;
}
GameObjectRespawnDeleteWorker worker(GetGUIDLow());
sMapPersistentStateMgr.DoForAllStatesWithMapId(GetMapId(), worker);
sObjectMgr.DeleteGOData(GetGUIDLow());
WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", GetGUIDLow());
WorldDatabase.PExecuteLog("DELETE FROM game_event_gameobject WHERE guid = '%u'", GetGUIDLow());
WorldDatabase.PExecuteLog("DELETE FROM gameobject_battleground WHERE guid = '%u'", GetGUIDLow());
}
GameObjectInfo const *GameObject::GetGOInfo() const
{
return m_goInfo;
}
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
bool GameObject::HasQuest(uint32 quest_id) const
{
QuestRelationsMapBounds bounds = sObjectMgr.GetGOQuestRelationsMapBounds(GetEntry());
for(QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
if (itr->second == quest_id)
return true;
}
return false;
}
bool GameObject::HasInvolvedQuest(uint32 quest_id) const
{
QuestRelationsMapBounds bounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(GetEntry());
for(QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
if (itr->second == quest_id)
return true;
}
return false;
}
bool GameObject::IsTransport() const
{
// If something is marked as a transport, don't transmit an out of range packet for it.
GameObjectInfo const * gInfo = GetGOInfo();
if(!gInfo) return false;
return gInfo->type == GAMEOBJECT_TYPE_TRANSPORT || gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT;
}
Unit* GameObject::GetOwner() const
{
return ObjectAccessor::GetUnit(*this, GetOwnerGuid());
}
void GameObject::SaveRespawnTime()
{
if(m_respawnTime > time(NULL) && m_spawnedByDefault)
GetMap()->GetPersistentState()->SaveGORespawnTime(GetGUIDLow(), m_respawnTime);
}
bool GameObject::isVisibleForInState(Player const* u, WorldObject const* viewPoint, bool inVisibleList) const
{
// Not in world
if(!IsInWorld() || !u->IsInWorld())
return false;
// invisible at client always
if(!GetGOInfo()->displayId)
return false;
// Transport always visible at this step implementation
if(IsTransport() && IsInMap(u))
return true;
// quick check visibility false cases for non-GM-mode
if(!u->isGameMaster())
{
// despawned and then not visible for non-GM in GM-mode
if(!isSpawned())
return false;
// special invisibility cases
/* TODO: implement trap stealth, take look at spell 2836
if(GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && GetGOInfo()->trap.stealthed && u->IsHostileTo(GetOwner()))
{
if(check stuff here)
return false;
}*/
}
// check distance
return IsWithinDistInMap(viewPoint, GetMap()->GetVisibilityDistance() +
(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), false);
}
void GameObject::Respawn()
{
if(m_spawnedByDefault && m_respawnTime > 0)
{
m_respawnTime = time(NULL);
GetMap()->GetPersistentState()->SaveGORespawnTime(GetGUIDLow(), 0);
}
}
bool GameObject::ActivateToQuest(Player *pTarget) const
{
// if GO is ReqCreatureOrGoN for quest
if (pTarget->HasQuestForGO(GetEntry()))
return true;
if (!sObjectMgr.IsGameObjectForQuests(GetEntry()))
return false;
switch(GetGoType())
{
case GAMEOBJECT_TYPE_QUESTGIVER:
{
// Not fully clear when GO's can activate/deactivate
// For cases where GO has additional (except quest itself),
// these conditions are not sufficient/will fail.
// Never expect flags|4 for these GO's? (NF-note: It doesn't appear it's expected)
QuestRelationsMapBounds bounds = sObjectMgr.GetGOQuestRelationsMapBounds(GetEntry());
for(QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
const Quest *qInfo = sObjectMgr.GetQuestTemplate(itr->second);
if (pTarget->CanTakeQuest(qInfo, false))
return true;
}
bounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(GetEntry());
for(QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
if ((pTarget->GetQuestStatus(itr->second) == QUEST_STATUS_INCOMPLETE || pTarget->GetQuestStatus(itr->second) == QUEST_STATUS_COMPLETE)
&& !pTarget->GetQuestRewardStatus(itr->second))
return true;
}
break;
}
// scan GO chest with loot including quest items
case GAMEOBJECT_TYPE_CHEST:
{
if (pTarget->GetQuestStatus(GetGOInfo()->chest.questId) == QUEST_STATUS_INCOMPLETE)
return true;
if (LootTemplates_Gameobject.HaveQuestLootForPlayer(GetGOInfo()->GetLootId(), pTarget))
{
//look for battlegroundAV for some objects which are only activated after mine gots captured by own team
if (GetEntry() == BG_AV_OBJECTID_MINE_N || GetEntry() == BG_AV_OBJECTID_MINE_S)
if (BattleGround *bg = pTarget->GetBattleGround())
if (bg->GetTypeID() == BATTLEGROUND_AV && !(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(GetEntry(),pTarget->GetTeam())))
return false;
return true;
}
break;
}
case GAMEOBJECT_TYPE_GENERIC:
{
if (pTarget->GetQuestStatus(GetGOInfo()->_generic.questID) == QUEST_STATUS_INCOMPLETE)
return true;
break;
}
case GAMEOBJECT_TYPE_SPELL_FOCUS:
{
if (pTarget->GetQuestStatus(GetGOInfo()->spellFocus.questID) == QUEST_STATUS_INCOMPLETE)
return true;
break;
}
case GAMEOBJECT_TYPE_GOOBER:
{
if (pTarget->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE)
return true;
break;
}
default:
break;
}
return false;
}
void GameObject::SummonLinkedTrapIfAny()
{
uint32 linkedEntry = GetGOInfo()->GetLinkedGameObjectEntry();
if (!linkedEntry)
return;
GameObject* linkedGO = new GameObject;
if (!linkedGO->Create(GetMap()->GenerateLocalLowGuid(HIGHGUID_GAMEOBJECT), linkedEntry, GetMap(),
GetPhaseMask(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()))
{
delete linkedGO;
return;
}
linkedGO->SetRespawnTime(GetRespawnDelay());
linkedGO->SetSpellId(GetSpellId());
if (GetOwnerGuid())
{
linkedGO->SetOwnerGuid(GetOwnerGuid());
linkedGO->SetUInt32Value(GAMEOBJECT_LEVEL, GetUInt32Value(GAMEOBJECT_LEVEL));
}
GetMap()->Add(linkedGO);
}
void GameObject::TriggerLinkedGameObject(Unit* target)
{
uint32 trapEntry = GetGOInfo()->GetLinkedGameObjectEntry();
if (!trapEntry)
return;
GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(trapEntry);
if (!trapInfo || trapInfo->type != GAMEOBJECT_TYPE_TRAP)
return;
SpellEntry const* trapSpell = sSpellStore.LookupEntry(trapInfo->trap.spellId);
// The range to search for linked trap is weird. We set 0.5 as default. Most (all?)
// traps are probably expected to be pretty much at the same location as the used GO,
// so it appears that using range from spell is obsolete.
float range = 0.5f;
if (trapSpell) // checked at load already
range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(trapSpell->rangeIndex));
// search nearest linked GO
GameObject* trapGO = NULL;
{
// search closest with base of used GO, using max range of trap spell as search radius (why? See above)
MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*this, trapEntry, range);
MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(trapGO, go_check);
Cell::VisitGridObjects(this, checker, range);
}
// found correct GO
if (trapGO)
trapGO->Use(target);
}
GameObject* GameObject::LookupFishingHoleAround(float range)
{
GameObject* ok = NULL;
MaNGOS::NearestGameObjectFishingHoleCheck u_check(*this, range);
MaNGOS::GameObjectSearcher<MaNGOS::NearestGameObjectFishingHoleCheck> checker(ok, u_check);
Cell::VisitGridObjects(this,checker, range);
return ok;
}
void GameObject::ResetDoorOrButton()
{
if (m_lootState == GO_READY || m_lootState == GO_JUST_DEACTIVATED)
return;
SwitchDoorOrButton(false);
SetLootState(GO_JUST_DEACTIVATED);
m_cooldownTime = 0;
}
void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = false */)
{
if(m_lootState != GO_READY)
return;
if(!time_to_restore)
time_to_restore = GetGOInfo()->GetAutoCloseTime();
SwitchDoorOrButton(true,alternative);
SetLootState(GO_ACTIVATED);
m_cooldownTime = time(NULL) + time_to_restore;
}
void GameObject::SwitchDoorOrButton(bool activate, bool alternative /* = false */)
{
if(activate)
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
else
RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
if(GetGoState() == GO_STATE_READY) //if closed -> open
SetGoState(alternative ? GO_STATE_ACTIVE_ALTERNATIVE : GO_STATE_ACTIVE);
else //if open -> close
SetGoState(GO_STATE_READY);
}
void GameObject::Use(Unit* user)
{
// by default spell caster is user
Unit* spellCaster = user;
uint32 spellId = 0;
bool triggered = false;
// test only for exist cooldown data (cooldown timer used for door/buttons reset that not have use cooldown)
if (uint32 cooldown = GetGOInfo()->GetCooldown())
{
if (m_cooldownTime > sWorld.GetGameTime())
return;
m_cooldownTime = sWorld.GetGameTime() + cooldown;
}
bool scriptReturnValue = user->GetTypeId() == TYPEID_PLAYER && sScriptMgr.OnGameObjectUse((Player*)user, this);
switch (GetGoType())
{
case GAMEOBJECT_TYPE_DOOR: // 0
{
//doors never really despawn, only reset to default state/flags
UseDoorOrButton();
// activate script
if (!scriptReturnValue)
GetMap()->ScriptsStart(sGameObjectScripts, GetGUIDLow(), spellCaster, this);
return;
}
case GAMEOBJECT_TYPE_BUTTON: // 1
{
//buttons never really despawn, only reset to default state/flags
UseDoorOrButton();
TriggerLinkedGameObject(user);
// activate script
if (!scriptReturnValue)
GetMap()->ScriptsStart(sGameObjectScripts, GetGUIDLow(), spellCaster, this);
return;
}
case GAMEOBJECT_TYPE_QUESTGIVER: // 2
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (!sScriptMgr.OnGossipHello(player, this))
{
player->PrepareGossipMenu(this, GetGOInfo()->questgiver.gossipID);
player->SendPreparedGossip(this);
}
return;
}
case GAMEOBJECT_TYPE_CHEST: // 3
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
TriggerLinkedGameObject(user);
// TODO: possible must be moved to loot release (in different from linked triggering)
if (GetGOInfo()->chest.eventId)
{
DEBUG_LOG("Chest ScriptStart id %u for GO %u", GetGOInfo()->chest.eventId, GetGUIDLow());
if (!sScriptMgr.OnProcessEvent(GetGOInfo()->chest.eventId, user, this, true))
GetMap()->ScriptsStart(sEventScripts, GetGOInfo()->chest.eventId, user, this);
}
return;
}
case GAMEOBJECT_TYPE_GENERIC: // 5
{
if (scriptReturnValue)
return;
// No known way to exclude some - only different approach is to select despawnable GOs by Entry
SetLootState(GO_JUST_DEACTIVATED);
return;
}
case GAMEOBJECT_TYPE_TRAP: // 6
{
// Currently we do not expect trap code below to be Use()
// directly (except from spell effect). Code here will be called by TriggerLinkedGameObject.
if (scriptReturnValue)
return;
// FIXME: when GO casting will be implemented trap must cast spell to target
if (spellId = GetGOInfo()->trap.spellId)
user->CastSpell(user, spellId, true, NULL, NULL, GetObjectGuid());
// TODO: all traps can be activated, also those without spell.
// Some may have have animation and/or are expected to despawn.
// TODO: Improve this when more information is available, currently these traps are known that must send the anim (Onyxia/ Heigan Fissures)
if (GetDisplayId() == 4392 || GetDisplayId() == 4472 || GetDisplayId() == 6785)
SendGameObjectCustomAnim(GetObjectGuid());
return;
}
case GAMEOBJECT_TYPE_CHAIR: // 7 Sitting: Wooden bench, chairs
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
// a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one
// check if the db is sane
if (info->chair.slots > 0)
{
float lowestDist = DEFAULT_VISIBILITY_DISTANCE;
float x_lowest = GetPositionX();
float y_lowest = GetPositionY();
// the object orientation + 1/2 pi
// every slot will be on that straight line
float orthogonalOrientation = GetOrientation() + M_PI_F * 0.5f;
// find nearest slot
for(uint32 i=0; i<info->chair.slots; ++i)
{
// the distance between this slot and the center of the go - imagine a 1D space
float relativeDistance = (info->size*i)-(info->size*(info->chair.slots-1)/2.0f);
float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation);
float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation);
// calculate the distance between the player and this slot
float thisDistance = player->GetDistance2d(x_i, y_i);
/* debug code. It will spawn a npc on each slot to visualize them.
Creature* helper = player->SummonCreature(14496, x_i, y_i, GetPositionZ(), GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 10000);
std::ostringstream output;
output << i << ": thisDist: " << thisDistance;
helper->MonsterSay(output.str().c_str(), LANG_UNIVERSAL);
*/
if (thisDistance <= lowestDist)
{
lowestDist = thisDistance;
x_lowest = x_i;
y_lowest = y_i;
}
}
player->TeleportTo(GetMapId(), x_lowest, y_lowest, GetPositionZ(), GetOrientation(), TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
}
else
{
// fallback, will always work
player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(), TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
}
player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR + info->chair.height);
return;
}
case GAMEOBJECT_TYPE_SPELL_FOCUS: // 8
{
TriggerLinkedGameObject(user);
// some may be activated in addition? Conditions for this? (ex: entry 181616)
return;
}
case GAMEOBJECT_TYPE_GOOBER: // 10
{
GameObjectInfo const* info = GetGOInfo();
TriggerLinkedGameObject(user);
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
SetLootState(GO_ACTIVATED);
// this appear to be ok, however others exist in addition to this that should have custom (ex: 190510, 188692, 187389)
if (info->goober.customAnim)
SendGameObjectCustomAnim(GetObjectGuid());
else
SetGoState(GO_STATE_ACTIVE);
m_cooldownTime = time(NULL) + info->GetAutoCloseTime();
if (user->GetTypeId() == TYPEID_PLAYER)
{
Player* player = (Player*)user;
if (info->goober.pageId) // show page...
{
WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8);
data << ObjectGuid(GetObjectGuid());
player->GetSession()->SendPacket(&data);
}
else if (info->goober.gossipID) // ...or gossip, if page does not exist
{
if (!sScriptMgr.OnGossipHello(player, this))
{
player->PrepareGossipMenu(this, info->goober.gossipID);
player->SendPreparedGossip(this);
}
}
if (info->goober.eventId)
{
DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Goober ScriptStart id %u for GO entry %u (GUID %u).", info->goober.eventId, GetEntry(), GetGUIDLow());
if (!sScriptMgr.OnProcessEvent(info->goober.eventId, player, this, true))
GetMap()->ScriptsStart(sEventScripts, info->goober.eventId, player, this);
}
// possible quest objective for active quests
if (info->goober.questId && sObjectMgr.GetQuestTemplate(info->goober.questId))
{
//Quest require to be active for GO using
if (player->GetQuestStatus(info->goober.questId) != QUEST_STATUS_INCOMPLETE)
break;
}
player->RewardPlayerAndGroupAtCast(this);
}
if (scriptReturnValue)
return;
// cast this spell later if provided
spellId = info->goober.spellId;
// database may contain a dummy spell, so it need replacement by actually existing
switch(spellId)
{
case 34448: spellId = 26566; break;
case 34452: spellId = 26572; break;
case 37639: spellId = 36326; break;
case 45367: spellId = 45371; break;
case 45370: spellId = 45368; break;
}
break;
}
case GAMEOBJECT_TYPE_CAMERA: // 13
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (info->camera.cinematicId)
player->SendCinematicStart(info->camera.cinematicId);
if (info->camera.eventID)
{
if (!sScriptMgr.OnProcessEvent(info->camera.eventID, player, this, true))
GetMap()->ScriptsStart(sEventScripts, info->camera.eventID, player, this);
}
return;
}
case GAMEOBJECT_TYPE_FISHINGNODE: // 17 fishing bobber
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (player->GetObjectGuid() != GetOwnerGuid())
return;
switch (getLootState())
{
case GO_READY: // ready for loot
{
// 1) skill must be >= base_zone_skill
// 2) if skill == base_zone_skill => 5% chance
// 3) chance is linear dependence from (base_zone_skill-skill)
uint32 zone, subzone;
GetZoneAndAreaId(zone, subzone);
int32 zone_skill = sObjectMgr.GetFishingBaseSkillLevel(subzone);
if (!zone_skill)
zone_skill = sObjectMgr.GetFishingBaseSkillLevel(zone);
//provide error, no fishable zone or area should be 0
if (!zone_skill)
sLog.outErrorDb("Fishable areaId %u are not properly defined in `skill_fishing_base_level`.", subzone);
int32 skill = player->GetSkillValue(SKILL_FISHING);
int32 chance = skill - zone_skill + 5;
int32 roll = irand(1, 100);
DEBUG_LOG("Fishing check (skill: %i zone min skill: %i chance %i roll: %i", skill, zone_skill, chance, roll);
// normal chance
bool success = skill >= zone_skill && chance >= roll;
GameObject* fishingHole = NULL;
// overwrite fail in case fishhole if allowed (after 3.3.0)
if (!success)
{
if (!sWorld.getConfig(CONFIG_BOOL_SKILL_FAIL_POSSIBLE_FISHINGPOOL))
{
//TODO: find reasonable value for fishing hole search
fishingHole = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE);
if (fishingHole)
success = true;
}
}
// just search fishhole for success case
else
//TODO: find reasonable value for fishing hole search
fishingHole = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE);
if (success || sWorld.getConfig(CONFIG_BOOL_SKILL_FAIL_GAIN_FISHING))
player->UpdateFishingSkill();
// fish catch or fail and junk allowed (after 3.1.0)
if (success || sWorld.getConfig(CONFIG_BOOL_SKILL_FAIL_LOOT_FISHING))
{
// prevent removing GO at spell cancel
player->RemoveGameObject(this, false);
SetOwnerGuid(player->GetObjectGuid());
if (fishingHole) // will set at success only
{
fishingHole->Use(player);
SetLootState(GO_JUST_DEACTIVATED);
}
else
player->SendLoot(GetObjectGuid(), success ? LOOT_FISHING : LOOT_FISHING_FAIL);
}
else
{
// fish escaped, can be deleted now
SetLootState(GO_JUST_DEACTIVATED);
WorldPacket data(SMSG_FISH_ESCAPED, 0);
player->GetSession()->SendPacket(&data);
}
break;
}
case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update
break;
default:
{
SetLootState(GO_JUST_DEACTIVATED);
WorldPacket data(SMSG_FISH_NOT_HOOKED, 0);
player->GetSession()->SendPacket(&data);
break;
}
}
player->FinishSpell(CURRENT_CHANNELED_SPELL);
return;
}
case GAMEOBJECT_TYPE_SUMMONING_RITUAL: // 18
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
Unit* owner = GetOwner();
GameObjectInfo const* info = GetGOInfo();
if (owner)
{
if (owner->GetTypeId() != TYPEID_PLAYER)
return;
// accept only use by player from same group as owner, excluding owner itself (unique use already added in spell effect)
if (player == (Player*)owner || (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(((Player*)owner))))
return;
// expect owner to already be channeling, so if not...
if (!owner->GetCurrentSpell(CURRENT_CHANNELED_SPELL))
return;
// in case summoning ritual caster is GO creator
spellCaster = owner;
}
else
{
if (m_firstUser && player->GetObjectGuid() != m_firstUser && info->summoningRitual.castersGrouped)
{
if (Group* group = player->GetGroup())
{
if (!group->IsMember(m_firstUser))
return;
}
else
return;
}
spellCaster = player;
}
AddUniqueUse(player);
if (info->summoningRitual.animSpell)
{
player->CastSpell(player, info->summoningRitual.animSpell, true);
// for this case, summoningRitual.spellId is always triggered
triggered = true;
}
// full amount unique participants including original summoner, need more
if (GetUniqueUseCount() < info->summoningRitual.reqParticipants)
return;
// owner is first user for non-wild GO objects, if it offline value already set to current user
if (!GetOwnerGuid())
if (Player* firstUser = GetMap()->GetPlayer(m_firstUser))
spellCaster = firstUser;
spellId = info->summoningRitual.spellId;
if (spellId == 62330) // GO store nonexistent spell, replace by expected
spellId = 61993;
// spell have reagent and mana cost but it not expected use its
// it triggered spell in fact casted at currently channeled GO
triggered = true;
// finish owners spell
if (owner)
owner->FinishSpell(CURRENT_CHANNELED_SPELL);
// can be deleted now, if
if (!info->summoningRitual.ritualPersistent)
SetLootState(GO_JUST_DEACTIVATED);
// reset ritual for this GO
else
ClearAllUsesData();
// go to end function to spell casting
break;
}
case GAMEOBJECT_TYPE_SPELLCASTER: // 22
{
SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED);
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (info->spellcaster.partyOnly)
{
Unit* caster = GetOwner();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
if (user->GetTypeId() != TYPEID_PLAYER || !((Player*)user)->IsInSameRaidWith((Player*)caster))
return;
}
spellId = info->spellcaster.spellId;
AddUse();
break;
}
case GAMEOBJECT_TYPE_MEETINGSTONE: // 23
{
GameObjectInfo const* info = GetGOInfo();
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
Player* targetPlayer = ObjectAccessor::FindPlayer(player->GetSelectionGuid());
// accept only use by player from same group for caster except caster itself
if (!targetPlayer || targetPlayer == player || !targetPlayer->IsInSameGroupWith(player))
return;
//required lvl checks!
uint8 level = player->getLevel();
if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
return;
level = targetPlayer->getLevel();
if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
return;
if (info->id == 194097)
spellId = 61994; // Ritual of Summoning
else
spellId = 59782; // Summoning Stone Effect
break;
}
case GAMEOBJECT_TYPE_FLAGSTAND: // 24
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (player->CanUseBattleGroundObject())
{
// in battleground check
BattleGround* bg = player->GetBattleGround();
if (!bg)
return;
// BG flag click
// AB:
// 15001
// 15002
// 15003
// 15004
// 15005
bg->EventPlayerClickedOnFlag(player, this);
return; //we don't need to delete flag ... it is despawned!
}
break;
}
case GAMEOBJECT_TYPE_FISHINGHOLE: // 25
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
player->SendLoot(GetObjectGuid(), LOOT_FISHINGHOLE);
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT, GetGOInfo()->id);
return;
}
case GAMEOBJECT_TYPE_FLAGDROP: // 26
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (player->CanUseBattleGroundObject())
{
// in battleground check
BattleGround *bg = player->GetBattleGround();
if (!bg)
return;
// BG flag dropped
// WS:
// 179785 - Silverwing Flag
// 179786 - Warsong Flag
// EotS:
// 184142 - Netherstorm Flag
GameObjectInfo const* info = GetGOInfo();
if (info)
{
switch(info->id)
{
case 179785: // Silverwing Flag
// check if it's correct bg
if (bg->GetTypeID() == BATTLEGROUND_WS)
bg->EventPlayerClickedOnFlag(player, this);
break;
case 179786: // Warsong Flag
if (bg->GetTypeID() == BATTLEGROUND_WS)
bg->EventPlayerClickedOnFlag(player, this);
break;
case 184142: // Netherstorm Flag
if (bg->GetTypeID() == BATTLEGROUND_EY)
bg->EventPlayerClickedOnFlag(player, this);
break;
}
}
//this cause to call return, all flags must be deleted here!!
spellId = 0;
Delete();
}
break;
}
case GAMEOBJECT_TYPE_CAPTURE_POINT: // 29
{
// Code here is not even halfway complete, and only added for further development.
// Computer may very well blow up after stealing your bank accounts and wreck your car.
// Use() object at own risk.
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
// Can we expect that only player object are able to trigger a capture point or
// could dummy creatures be involved?
//if (user->GetTypeId() != TYPEID_PLAYER)
//return;
//Player* player = (Player*)user;
// ID1 vs ID2 are possibly related to team. The world states should probably
// control which event to be used. For this to work, we need a far better system for
// sWorldStateMgr (system to store and keep track of states) so that we at all times
// know the state of every part of the world.
// Call every event, which is obviously wrong, but can help in further development. For
// the time being script side can process events and determine which one to use. It
// require of course that some object call go->Use()
if (info->capturePoint.winEventID1)
{
if (!sScriptMgr.OnProcessEvent(info->capturePoint.winEventID1, user, this, true))
GetMap()->ScriptsStart(sEventScripts, info->capturePoint.winEventID1, user, this);
}
if (info->capturePoint.winEventID2)
{
if (!sScriptMgr.OnProcessEvent(info->capturePoint.winEventID2, user, this, true))
GetMap()->ScriptsStart(sEventScripts, info->capturePoint.winEventID2, user, this);
}
if (info->capturePoint.contestedEventID1)
{
if (!sScriptMgr.OnProcessEvent(info->capturePoint.contestedEventID1, user, this, true))
GetMap()->ScriptsStart(sEventScripts, info->capturePoint.contestedEventID1, user, this);
}
if (info->capturePoint.contestedEventID2)
{
if (!sScriptMgr.OnProcessEvent(info->capturePoint.contestedEventID2, user, this, true))
GetMap()->ScriptsStart(sEventScripts, info->capturePoint.contestedEventID2, user, this);
}
if (info->capturePoint.progressEventID1)
{
if (!sScriptMgr.OnProcessEvent(info->capturePoint.progressEventID1, user, this, true))
GetMap()->ScriptsStart(sEventScripts, info->capturePoint.progressEventID1, user, this);
}
if (info->capturePoint.progressEventID2)
{
if (!sScriptMgr.OnProcessEvent(info->capturePoint.progressEventID2, user, this, true))
GetMap()->ScriptsStart(sEventScripts, info->capturePoint.progressEventID2, user, this);
}
if (info->capturePoint.neutralEventID1)
{
if (!sScriptMgr.OnProcessEvent(info->capturePoint.neutralEventID1, user, this, true))
GetMap()->ScriptsStart(sEventScripts, info->capturePoint.neutralEventID1, user, this);
}
if (info->capturePoint.neutralEventID2)
{
if (!sScriptMgr.OnProcessEvent(info->capturePoint.neutralEventID2, user, this, true))
GetMap()->ScriptsStart(sEventScripts, info->capturePoint.neutralEventID2, user, this);
}
// Some has spell, need to process those further.
return;
}
case GAMEOBJECT_TYPE_BARBER_CHAIR: // 32
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
// fallback, will always work
player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
WorldPacket data(SMSG_ENABLE_BARBER_SHOP, 0);
player->GetSession()->SendPacket(&data);
player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR + info->barberChair.chairheight);
return;
}
default:
sLog.outError("GameObject::Use unhandled GameObject type %u (entry %u).", GetGoType(), GetEntry());
return;
}
if (!spellId)
return;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
{
sLog.outError("WORLD: unknown spell id %u at use action for gameobject (Entry: %u GoType: %u )", spellId, GetEntry(), GetGoType());
return;
}
Spell *spell = new Spell(spellCaster, spellInfo, triggered, GetObjectGuid());
// spell target is user of GO
SpellCastTargets targets;
targets.setUnitTarget(user);
spell->prepare(&targets);
}
// overwrite WorldObject function for proper name localization
const char* GameObject::GetNameForLocaleIdx(int32 loc_idx) const
{
if (loc_idx >= 0)
{
GameObjectLocale const *cl = sObjectMgr.GetGameObjectLocale(GetEntry());
if (cl)
{
if (cl->Name.size() > (size_t)loc_idx && !cl->Name[loc_idx].empty())
return cl->Name[loc_idx].c_str();
}
}
return GetName();
}
using G3D::Quat;
struct QuaternionCompressed
{
QuaternionCompressed() : m_raw(0) {}
QuaternionCompressed(int64 val) : m_raw(val) {}
QuaternionCompressed(const Quat& quat) { Set(quat); }
enum{
PACK_COEFF_YZ = 1 << 20,
PACK_COEFF_X = 1 << 21,
};
void Set(const Quat& quat)
{
int8 w_sign = (quat.w >= 0 ? 1 : -1);
int64 X = int32(quat.x * PACK_COEFF_X) * w_sign & ((1 << 22) - 1);
int64 Y = int32(quat.y * PACK_COEFF_YZ) * w_sign & ((1 << 21) - 1);
int64 Z = int32(quat.z * PACK_COEFF_YZ) * w_sign & ((1 << 21) - 1);
m_raw = Z | (Y << 21) | (X << 42);
}
Quat Unpack() const
{
double x = (double)(m_raw >> 42) / (double)PACK_COEFF_X;
double y = (double)(m_raw << 22 >> 43) / (double)PACK_COEFF_YZ;
double z = (double)(m_raw << 43 >> 43) / (double)PACK_COEFF_YZ;
double w = 1 - (x * x + y * y + z * z);
MANGOS_ASSERT(w >= 0);
w = sqrt(w);
return Quat(x,y,z,w);
}
int64 m_raw;
};
void GameObject::SetWorldRotation(float qx, float qy, float qz, float qw)
{
Quat rotation(qx, qy, qz, qw);
// Temporary solution for gameobjects that has no rotation data in DB:
if (qz == 0.f && qw == 0.f)
rotation = Quat::fromAxisAngleRotation(G3D::Vector3::unitZ(), GetOrientation());
rotation.unitize();
m_packedRotation = QuaternionCompressed(rotation).m_raw;
m_worldRotation.x = rotation.x;
m_worldRotation.y = rotation.y;
m_worldRotation.z = rotation.z;
m_worldRotation.w = rotation.w;
}
void GameObject::SetTransportPathRotation(QuaternionData rotation)
{
SetFloatValue(GAMEOBJECT_PARENTROTATION+0, rotation.x);
SetFloatValue(GAMEOBJECT_PARENTROTATION+1, rotation.y);
SetFloatValue(GAMEOBJECT_PARENTROTATION+2, rotation.z);
SetFloatValue(GAMEOBJECT_PARENTROTATION+3, rotation.w);
}
void GameObject::SetWorldRotationAngles(float z_rot, float y_rot, float x_rot)
{
Quat quat( G3D::Matrix3::fromEulerAnglesZYX(z_rot, y_rot, x_rot) );
SetWorldRotation(quat.x, quat.y, quat.z, quat.w);
}
bool GameObject::IsHostileTo(Unit const* unit) const
{
// always non-hostile to GM in GM mode
if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
return false;
// test owner instead if have
if (Unit const* owner = GetOwner())
return owner->IsHostileTo(unit);
if (Unit const* targetOwner = unit->GetCharmerOrOwner())
return IsHostileTo(targetOwner);
// for not set faction case (wild object) use hostile case
if(!GetGOInfo()->faction)
return true;
// faction base cases
FactionTemplateEntry const*tester_faction = sFactionTemplateStore.LookupEntry(GetGOInfo()->faction);
FactionTemplateEntry const*target_faction = unit->getFactionTemplateEntry();
if(!tester_faction || !target_faction)
return false;
// GvP forced reaction and reputation case
if(unit->GetTypeId()==TYPEID_PLAYER)
{
// forced reaction
if(tester_faction->faction)
{
if(ReputationRank const* force = ((Player*)unit)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
return *force <= REP_HOSTILE;
// apply reputation state
FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
return ((Player const*)unit)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
}
}
// common faction based case (GvC,GvP)
return tester_faction->IsHostileTo(*target_faction);
}
bool GameObject::IsFriendlyTo(Unit const* unit) const
{
// always friendly to GM in GM mode
if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
return true;
// test owner instead if have
if (Unit const* owner = GetOwner())
return owner->IsFriendlyTo(unit);
if (Unit const* targetOwner = unit->GetCharmerOrOwner())
return IsFriendlyTo(targetOwner);
// for not set faction case (wild object) use hostile case
if(!GetGOInfo()->faction)
return false;
// faction base cases
FactionTemplateEntry const*tester_faction = sFactionTemplateStore.LookupEntry(GetGOInfo()->faction);
FactionTemplateEntry const*target_faction = unit->getFactionTemplateEntry();
if(!tester_faction || !target_faction)
return false;
// GvP forced reaction and reputation case
if(unit->GetTypeId()==TYPEID_PLAYER)
{
// forced reaction
if(tester_faction->faction)
{
if(ReputationRank const* force =((Player*)unit)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
return *force >= REP_FRIENDLY;
// apply reputation state
if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
if(raw_tester_faction->reputationListID >=0 )
return ((Player const*)unit)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
}
}
// common faction based case (GvC,GvP)
return tester_faction->IsFriendlyTo(*target_faction);
}
void GameObject::SetDisplayId(uint32 modelId)
{
SetUInt32Value(GAMEOBJECT_DISPLAYID, modelId);
m_displayInfo = sGameObjectDisplayInfoStore.LookupEntry(modelId);
}
float GameObject::GetObjectBoundingRadius() const
{
//FIXME:
// 1. This is clearly hack way because GameObjectDisplayInfoEntry have 6 floats related to GO sizes, but better that use DEFAULT_WORLD_OBJECT_SIZE
// 2. In some cases this must be only interactive size, not GO size, current way can affect creature target point auto-selection in strange ways for big underground/virtual GOs
if (m_displayInfo)
return fabs(m_displayInfo->unknown12) * GetObjectScale();
return DEFAULT_WORLD_OBJECT_SIZE;
}
bool GameObject::IsInSkillupList(Player* player) const
{
return m_SkillupSet.find(player->GetObjectGuid()) != m_SkillupSet.end();
}
void GameObject::AddToSkillupList(Player* player)
{
m_SkillupSet.insert(player->GetObjectGuid());
}
struct AddGameObjectToRemoveListInMapsWorker
{
AddGameObjectToRemoveListInMapsWorker(ObjectGuid guid) : i_guid(guid) {}
void operator() (Map* map)
{
if (GameObject* pGameobject = map->GetGameObject(i_guid))
pGameobject->AddObjectToRemoveList();
}
ObjectGuid i_guid;
};
void GameObject::AddToRemoveListInMaps(uint32 db_guid, GameObjectData const* data)
{
AddGameObjectToRemoveListInMapsWorker worker(ObjectGuid(HIGHGUID_GAMEOBJECT, data->id, db_guid));
sMapMgr.DoForAllMapsWithMapId(data->mapid, worker);
}
struct SpawnGameObjectInMapsWorker
{
SpawnGameObjectInMapsWorker(uint32 guid, GameObjectData const* data)
: i_guid(guid), i_data(data) {}
void operator() (Map* map)
{
// Spawn if necessary (loaded grids only)
if (map->IsLoaded(i_data->posX, i_data->posY))
{
GameObject* pGameobject = new GameObject;
//DEBUG_LOG("Spawning gameobject %u", *itr);
if (!pGameobject->LoadFromDB(i_guid, map))
{
delete pGameobject;
}
else
{
if (pGameobject->isSpawnedByDefault())
map->Add(pGameobject);
}
}
}
uint32 i_guid;
GameObjectData const* i_data;
};
void GameObject::SpawnInMaps(uint32 db_guid, GameObjectData const* data)
{
SpawnGameObjectInMapsWorker worker(db_guid, data);
sMapMgr.DoForAllMapsWithMapId(data->mapid, worker);
}
bool GameObject::HasStaticDBSpawnData() const
{
return sObjectMgr.GetGOData(GetGUIDLow()) != NULL;
}
| agpl-3.0 |
helfertool/helfertool | src/registration/migrations/0056_auto_20211106_1621.py | 878 | # Generated by Django 3.2.9 on 2021-11-06 15:21
from django.db import migrations
import helfertool.forms.fields
import registration.models.event
class Migration(migrations.Migration):
dependencies = [
('registration', '0055_event_corona'),
]
operations = [
migrations.AlterField(
model_name='event',
name='logo',
field=helfertool.forms.fields.RestrictedImageField(blank=True, null=True, upload_to=registration.models.event._logo_upload_path, verbose_name='Logo'),
),
migrations.AlterField(
model_name='event',
name='logo_social',
field=helfertool.forms.fields.RestrictedImageField(blank=True, help_text='Best results with 1052 x 548 px.', null=True, upload_to=registration.models.event._logo_upload_path, verbose_name='Logo for Facebook'),
),
]
| agpl-3.0 |
HotChalk/canvas-lms | spec/selenium/grades/speedgrader/speedgrader_teacher_spec.rb | 14888 | require_relative "../../common"
require_relative "../../helpers/speed_grader_common"
require_relative "../../helpers/gradebook2_common"
require_relative "../../helpers/quizzes_common"
require_relative "../../helpers/groups_common"
describe "speed grader" do
include_context "in-process server selenium tests"
include QuizzesCommon
include Gradebook2Common
include SpeedGraderCommon
include GroupsCommon
before(:each) do
stub_kaltura
course_with_teacher_logged_in
@assignment = @course.assignments.create(:name => 'assignment with rubric', :points_possible => 10)
end
context "as a course limited ta" do
before(:each) do
@taenrollment = course_with_ta(:course => @course, :active_all => true)
@taenrollment.limit_privileges_to_course_section = true
@taenrollment.save!
user_logged_in(:user => @ta, :username => "imata@example.com")
@section = @course.course_sections.create!
student_in_course(:active_all => true); @student1 = @student
student_in_course(:active_all => true); @student2 = @student
@enrollment.course_section = @section; @enrollment.save
@assignment.submission_types = "online_upload"
@assignment.save!
@submission1 = @assignment.submit_homework(@student1, :submission_type => "online_text_entry", :body => "hi")
@submission2 = @assignment.submit_homework(@student2, :submission_type => "online_text_entry", :body => "there")
end
it "lists the correct number of students", priority: "2", test_id: 283737 do
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
expect(f("#x_of_x_students_frd")).to include_text("1/1")
expect(ff("#students_selectmenu-menu li").count).to eq 1
end
end
context "alerts" do
it "should alert the teacher before leaving the page if comments are not saved", priority: "1", test_id: 283736 do
student_in_course(active_user: true).user
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
comment_textarea = f("#speedgrader_comment_textarea")
replace_content(comment_textarea, "oh no i forgot to save this comment!")
# navigate away
driver.navigate.refresh
alert_shown = alert_present?
dismiss_alert
expect(alert_shown).to eq(true)
end
end
context "url submissions" do
before do
@assignment.update_attributes! submission_types: 'online_url',
title: "url submission"
student_in_course
@assignment.submit_homework(@student, :submission_type => "online_url", :workflow_state => "submitted", :url => "http://www.instructure.com")
end
it "properly shows and hides student name when name hidden toggled", priority: "2", test_id: 283741 do
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
in_frame 'speedgrader_iframe' do
expect(f('.not_external')).to include_text("instructure")
expect(f('.open_in_a_new_tab')).to include_text("View")
end
end
end
it "does not show students in other sections if visibility is limited", priority: "1", test_id: 283758 do
@enrollment.update_attribute(:limit_privileges_to_course_section, true)
student_submission
student_submission(:username => 'otherstudent@example.com', :section => @course.course_sections.create(:name => "another section"))
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
expect(ff('#students_selectmenu option').size).to eq 1 # just the one student
expect(ff('#section-menu ul li').size).to eq 1 # "Show all sections"
expect(f("#students_selectmenu")).not_to contain_css('#section-menu') # doesn't get inserted into the menu
end
it "displays inactive students" do
@teacher.preferences = { gradebook_settings: { @course.id => { 'show_inactive_enrollments' => 'true' } } }
@teacher.save
student_submission(:username => 'inactivestudent@example.com')
en = @student.student_enrollments.first
en.deactivate
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
expect(ff('#students_selectmenu option').size).to eq 1 # just the one student
expect(f('#enrollment_inactive_notice').text).to eq 'Notice: Inactive Student'
end
it "can grade and comment inactive students" do
skip "Skipped because this spec fails if not run in foreground\n"\
"This is believed to be the issue: https://code.google.com/p/selenium/issues/detail?id=7346"
@teacher.preferences = { gradebook_settings: { @course.id => { 'show_inactive_enrollments' => 'true' } } }
@teacher.save
student_submission(:username => 'inactivestudent@example.com')
en = @student.student_enrollments.first
en.deactivate
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
replace_content f('#grading-box-extended'), "5", tab_out: true
wait_for_ajaximations
@submission.reload
expect(@submission.score).to eq 5
f('#speedgrader_comment_textarea').send_keys('srsly')
f('#add_a_comment button[type="submit"]').click
wait_for_ajaximations
expect(@submission.submission_comments.first.comment).to eq 'srsly'
# doesn't get inserted into the menu
expect(f('#students_selectmenu')).not_to contain_css('#section-menu')
end
it "displays concluded students" do
@teacher.preferences = { gradebook_settings: { @course.id => { 'show_concluded_enrollments' => 'true' } } }
@teacher.save
student_submission(:username => 'inactivestudent@example.com')
en = @student.student_enrollments.first
en.conclude
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
expect(ff('#students_selectmenu option').size).to eq 1 # just the one student
expect(f('#enrollment_concluded_notice').text).to eq 'Notice: Concluded Student'
end
context "multiple enrollments" do
before(:each) do
student_in_course
@course_section = @course.course_sections.create!(:name => "<h1>Other Section</h1>")
@enrollment = @course.enroll_student(@student,
:enrollment_state => "active",
:section => @course_section,
:allow_multiple_enrollments => true)
end
it "does not duplicate students", priority: "1", test_id: 283985 do
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
expect(ff("#students_selectmenu option").length).to eq 1
end
it "filters by section properly", priority: "1", test_id: 283986 do
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
sections = @course.course_sections
section_options_text = f("#section-menu ul")[:textContent] # hidden
expect(section_options_text).to include(@course_section.name)
goto_section(sections[0].id)
expect(ff("#students_selectmenu option").length).to eq 1
goto_section(sections[1].id)
expect(ff("#students_selectmenu option").length).to eq 1
end
end
it "shows the first ungraded student with a submission", priority: "1", test_id: 283987 do
s1, s2, s3 = n_students_in_course(3, course: @course)
s1.update_attribute :name, "A"
s2.update_attribute :name, "B"
s3.update_attribute :name, "C"
@assignment.grade_student s1, score: 10
@assignment.find_or_create_submission(s2).tap { |submission|
submission.student_entered_score = 5
}.save!
@assignment.submit_homework(s3, body: "Homework!?")
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
expect(fj("#students_selectmenu option[value=#{s3.id}]")[:selected]).to be_truthy
end
it "allows the user to change sorting and hide student names", priority: "1", test_id: 283988 do
student_submission(name: 'student@example.com')
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
# sort by submission date
f("#settings_link").click
f('select#eg_sort_by option[value="submitted_at"]').click
expect_new_page_load { fj('.ui-dialog-buttonset .ui-button:visible:last').click }
expect(f('#combo_box_container .ui-selectmenu .ui-selectmenu-item-header')).to include_text @student.name
# hide student names
f("#settings_link").click
f('#hide_student_names').click
expect_new_page_load { fj('.ui-dialog-buttonset .ui-button:visible:last').click }
expect(f('#combo_box_container .ui-selectmenu .ui-selectmenu-item-header')).to include_text "Student 1"
# make sure it works a second time too
f("#settings_link").click
f('select#eg_sort_by option[value="alphabetically"]').click
expect_new_page_load { fj('.ui-dialog-buttonset .ui-button:visible:last').click }
expect(f('#combo_box_container .ui-selectmenu .ui-selectmenu-item-header')).to include_text "Student 1"
# unselect the hide option
f("#settings_link").click
f('#hide_student_names').click
expect_new_page_load { fj('.ui-dialog-buttonset .ui-button:visible:last').click }
expect(f('#combo_box_container .ui-selectmenu .ui-selectmenu-item-header')).to include_text @student.name
end
context "student dropdown" do
before(:each) do
@section0 = @course.course_sections.create!(name: "Section0")
@section1 = @course.course_sections.create!(name: "Section1")
@student0 = User.create!(name: "Test Student 0")
@student1 = User.create!(name: "Test Student 1")
@course.enroll_student(@student0, section: @section0)
@course.enroll_student(@student1, section: @section1)
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
end
it "show all sections menu item is present", priority: "2", test_id: "164207" do
f("#students_selectmenu-button").click
hover(f("#section-menu-link"))
wait_for_ajaximations
expect(f("#section-menu .ui-menu")).to include_text("Show All Sections")
end
it "should list all course sections", priority: "2", test_id: "588914" do
f("#students_selectmenu-button").click
hover(f("#section-menu-link"))
wait_for_ajaximations
expect(f("#section-menu .ui-menu")).to include_text(@section0.name)
expect(f("#section-menu .ui-menu")).to include_text(@section1.name)
end
end
it "includes the student view student for grading", priority: "1", test_id: 283990 do
@course.student_view_student
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
expect(ff("#students_selectmenu option").length).to eq 1
end
it "marks the checkbox of students for graded assignments", priority: "1", test_id: 283992 do
student_submission
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
expect(f("#students_selectmenu-button")).to have_class("not_graded")
f('#grade_container input[type=text]').click
set_value(f('#grade_container input[type=text]'), 1)
f(".ui-selectmenu-icon").click
wait_for_ajaximations
expect(f("#students_selectmenu-button")).to have_class("graded")
end
context "Pass / Fail assignments" do
it "displays correct options in the speedgrader dropdown", priority: "1", test_id: 283996 do
course_with_teacher_logged_in
course_with_student(course: @course, active_all: true)
@assignment = @course.assignments.build
@assignment.grading_type = 'pass_fail'
@assignment.publish
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
select_box_values = ff('#grading-box-extended option').map(&:text)
expect(select_box_values).to eql(["---", "Complete", "Incomplete", "Excused"])
end
end
it 'should let you enter in a float for a quiz question point value', priority: "1", test_id: 369250 do
init_course_with_students
quiz = seed_quiz_with_submission
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{quiz.assignment_id}"
# In the left panel modify the grade to 0.5
driver.switch_to.frame f('#speedgrader_iframe')
points_input = ff('#questions .user_points input')
driver.execute_script("$('#questions .user_points input').focus()")
replace_content(points_input[0], '0')
replace_content(points_input[1], '.5')
replace_content(points_input[2], '0')
f('.update_scores button[type="submit"]').click
wait_for_ajaximations
# Switch to the right panel
# Verify that the grade is .5
driver.switch_to.default_content
expect(f('#grading-box-extended')['value']).to eq('0.5')
expect(f("#students_selectmenu-button")).to_not have_class("not_graded")
expect(f("#students_selectmenu-button")).to have_class("graded")
end
context 'Crocodocable Submissions' do
# set up course and users
let(:test_course) { @course }
let(:student) { user(active_all: true) }
let!(:crocodoc_plugin) { PluginSetting.create! name: "crocodoc", settings: {api_key: "abc123"} }
let!(:enroll_student) do
test_course.enroll_user(student, 'StudentEnrollment', enrollment_state: 'active')
end
# create an assignment with online_upload type submission
let!(:assignment) { test_course.assignments.create!(title: 'Assignment A', submission_types: 'online_text_entry,online_upload') }
# submit to the assignment as a student twice, one with file and other with text
let!(:file_attachment) { attachment_model(:content_type => 'application/pdf', :context => student) }
let!(:submit_with_attachment) do
assignment.submit_homework(
student,
submission_type: 'online_upload',
attachments: [file_attachment]
)
end
it 'should display a flash warning banner when viewed in Firefox', priority: "2", test_id: 571755 do
skip_if_chrome('This test applies to Firefox')
skip_if_ie('This test applies to Firefox')
# sometimes google docs is slow to load, which causes the flash
# message to go away before `get` finishes. we're not testing
# google docs here anyway, so ¯\_(ツ)_/¯
Account.default.disable_service(:google_docs_previews)
Account.default.save
get "/courses/#{test_course.id}/gradebook/speed_grader?assignment_id=#{assignment.id}"
assert_flash_notice_message 'Warning: Crocodoc has limitations when used in Firefox. Comments will not always be saved.'
end
end
end
| agpl-3.0 |
nilcy/yoyo | yoyo-framework/yoyo-framework-standard/src/main/java/yoyo/framework/standard/app/package-info.java | 466 | // ========================================================================
// Copyright (C) YOYO Project Team. All rights reserved.
// GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
// http://www.gnu.org/licenses/agpl-3.0.txt
// ========================================================================
/**
* スタンダードフレームワーク(JavaSE) | アプリケーション
* @author nilcy
*/
package yoyo.framework.standard.app; | agpl-3.0 |
Nivocer/webenq | libraries/Doctrine/Validator/Unsigned.php | 2009 | <?php
/*
* $Id: Unsigned.php,v 1.2 2011/07/12 13:38:58 bart Exp $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
/**
* Doctrine_Validator_Unsigned
*
* @package Doctrine
* @subpackage Validator
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 1.0
* @version $Revision: 1.2 $
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
*/
class Doctrine_Validator_Unsigned extends Doctrine_Validator_Driver
{
/**
* checks if given value is a valid unsigned integer or float
*
* valid values: null, '', 5, '5', 5.9, '5.9'
* invalid values: -5, '-5', 'five', -5.9, '-5.9', '5.5.5'
*
* @param mixed $value
* @return boolean
*/
public function validate($value)
{
if (is_null($value) || $value == '') {
return true;
}
if (preg_match('/[^0-9\-\.]/', $value)) {
return false;
}
if ((double) $value >= 0)
{
return true;
}
return false;
}
} | agpl-3.0 |
be-lb/sdi-clients | view/src/queries/app.ts | 4764 |
/*
* Copyright (C) 2017 Atelier Cartographique <contact@atelier-cartographique.be>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { fromNullable, none, some, Option } from 'fp-ts/lib/Option';
import { left, right, Either } from 'fp-ts/lib/Either';
import { query } from 'sdi/shape';
import { getMessageRecord, IMapInfo, FeatureCollection } from 'sdi/source';
import { SyntheticLayerInfo } from 'sdi/app';
const queries = {
mapReady() {
return query('app/map-ready');
},
getLayout() {
const ll = query('app/layout');
if (ll.length === 0) {
throw (new Error('PoppingEmptyLayoutList'));
}
return ll[ll.length - 1];
},
getLayerData(id: string): Either<string, Option<FeatureCollection>> {
const layers = query('data/layers');
const errors = query('remote/errors');
if (id in layers) {
return right(some<FeatureCollection>(layers[id]));
}
else if (id in errors) {
return left(errors[id]);
}
return right(none);
},
getMap(mid: string) {
const maps = query('data/maps');
return maps.find(m => m.id === mid);
},
getDatasetMetadata(id: string) {
const collection = query('data/datasetMetadata');
if (id in collection) {
return collection[id];
}
return null;
},
getMapInfo() {
const mid = query('app/current-map');
const info = query('data/maps').find(m => m.id === mid);
return (info !== undefined) ? info : null;
},
getLayerInfo(layerId: string): SyntheticLayerInfo {
const mid = query('app/current-map');
const info = query('data/maps').find(m => m.id === mid);
if (info) {
const layers = info.layers;
const layerInfo = layers.find(l => l.id === layerId);
if (layerInfo) {
const metadata = queries.getDatasetMetadata(layerInfo.metadataId);
if (metadata) {
return {
name: getMessageRecord(metadata.resourceTitle),
info: layerInfo,
metadata,
};
}
}
}
return { name: null, info: null, metadata: null };
},
getCurrentMap() {
return query('app/current-map');
},
getCurrentLayer() {
return query('app/current-layer');
},
getCurrentLayerInfo() {
const lid = query('app/current-layer');
if (lid) {
return queries.getLayerInfo(lid);
}
return { name: null, info: null, metadata: null };
},
getCurrentFeature() {
return query('app/current-feature');
},
getCurrentBaseLayerName() {
const mid = query('app/current-map');
const map = query('data/maps').find(m => m.id === mid);
if (map) {
return map.baseLayer;
}
return null;
},
gteBaseLayer(id: string | null) {
const bls = query('data/baselayers');
if (id && id in bls) {
return bls[id];
}
return null;
},
getCurrentBaseLayer() {
const name = queries.getCurrentBaseLayerName();
return queries.gteBaseLayer(name);
},
getBaseLayerServices() {
const names = Object.keys(query('data/baselayers')).map(id => id.split('/')[0]);
return names.reduce<string[]>((acc, name) => {
if (acc.indexOf(name) >= 0) {
return acc;
}
return acc.concat([name]);
}, []);
},
getBaseLayersForService(name: string) {
const collection = query('data/baselayers');
const layers =
Object.keys(collection)
.filter(id => id.split('/')[0] === name);
return layers;
},
};
export default queries;
export const hasPrintTitle =
() => null === query('component/print').customTitle;
export const getPrintTitle =
(info: IMapInfo) =>
fromNullable(query('component/print').customTitle)
.fold(
info.title,
s => s);
| agpl-3.0 |
RoumenGeorgiev/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingFragment.java | 1782 | package info.nightscout.androidaps.plugins.InsulinFastacting;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
/**
* Created by mike on 17.04.2017.
*/
public class InsulinFastactingFragment extends Fragment {
static InsulinFastactingPlugin insulinFastactingPlugin = new InsulinFastactingPlugin();
static public InsulinFastactingPlugin getPlugin() {
return insulinFastactingPlugin;
}
TextView insulinName;
TextView insulinComment;
TextView insulinDia;
ActivityGraph insulinGraph;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.insulin_fragment, container, false);
insulinName = (TextView) view.findViewById(R.id.insulin_name);
insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
updateGUI();
return view;
}
@Override
public void onResume() {
super.onResume();
updateGUI();
}
private void updateGUI() {
insulinName.setText(insulinFastactingPlugin.getFriendlyName());
insulinComment.setText(insulinFastactingPlugin.getComment());
insulinDia.setText(MainApp.sResources.getText(R.string.dia) + " " + new Double(insulinFastactingPlugin.getDia()).toString() + "h");
insulinGraph.show(insulinFastactingPlugin);
}
}
| agpl-3.0 |
bosman/raven.testsuite | Imports/Newtonsoft.Json/Src/Newtonsoft.Json/Linq/JEnumerable.cs | 4111 | #region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.Generic;
#if NET20
using Raven.Imports.Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Raven.Imports.Newtonsoft.Json.Utilities;
using System.Collections;
namespace Raven.Imports.Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a collection of <see cref="JToken"/> objects.
/// </summary>
/// <typeparam name="T">The type of tokenWrapper</typeparam>
public struct JEnumerable<T> : IJEnumerable<T> where T : JToken
{
/// <summary>
/// An empty collection of <see cref="JToken"/> objects.
/// </summary>
public static readonly JEnumerable<T> Empty = new JEnumerable<T>(Enumerable.Empty<T>());
private readonly IEnumerable<T> _enumerable;
/// <summary>
/// Initializes a new instance of the <see cref="JEnumerable{T}"/> struct.
/// </summary>
/// <param name="enumerable">The enumerable.</param>
public JEnumerable(IEnumerable<T> enumerable)
{
ValidationUtils.ArgumentNotNull(enumerable, "enumerable");
_enumerable = enumerable;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
return _enumerable.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Gets the <see cref="IJEnumerable{JToken}"/> with the specified key.
/// </summary>
/// <value></value>
public IJEnumerable<JToken> this[object key]
{
get { return new JEnumerable<JToken>(Extensions.Values<T, JToken>(_enumerable, key)); }
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj is JEnumerable<T>)
return _enumerable.Equals(((JEnumerable<T>)obj)._enumerable);
return false;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return _enumerable.GetHashCode();
}
}
}
| agpl-3.0 |
lmaslag/test | engine/Library/Zend/Json/Server/Smd.php | 11645 | <?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_Json
* @subpackage Server
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @category Zend
* @package Zend_Json
* @subpackage Server
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Json_Server_Smd
{
const ENV_JSONRPC_1 = 'JSON-RPC-1.0';
const ENV_JSONRPC_2 = 'JSON-RPC-2.0';
const SMD_VERSION = '2.0';
/**
* Content type
* @var string
*/
protected $_contentType = 'application/json';
/**
* Content type regex
* @var string
*/
protected $_contentTypeRegex = '#[a-z]+/[a-z][a-z-]+#i';
/**
* Service description
* @var string
*/
protected $_description;
/**
* Generate Dojo-compatible SMD
* @var bool
*/
protected $_dojoCompatible = false;
/**
* Current envelope
* @var string
*/
protected $_envelope = self::ENV_JSONRPC_1;
/**
* Allowed envelope types
* @var array
*/
protected $_envelopeTypes = array(
self::ENV_JSONRPC_1,
self::ENV_JSONRPC_2,
);
/**
* Service id
* @var string
*/
protected $_id;
/**
* Services offerred
* @var array
*/
protected $_services = array();
/**
* Service target
* @var string
*/
protected $_target;
/**
* Global transport
* @var string
*/
protected $_transport = 'POST';
/**
* Allowed transport types
* @var array
*/
protected $_transportTypes = array('POST');
/**
* Set object state via options
*
* @param array $options
* @return Zend_Json_Server_Smd
*/
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
/**
* Set transport
*
* @param string $transport
* @return Zend_Json_Server_Smd
*/
public function setTransport($transport)
{
if (!in_array($transport, $this->_transportTypes)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception(sprintf('Invalid transport "%s" specified', $transport));
}
$this->_transport = $transport;
return $this;
}
/**
* Get transport
*
* @return string
*/
public function getTransport()
{
return $this->_transport;
}
/**
* Set envelope
*
* @param string $envelopeType
* @return Zend_Json_Server_Smd
*/
public function setEnvelope($envelopeType)
{
if (!in_array($envelopeType, $this->_envelopeTypes)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception(sprintf('Invalid envelope type "%s"', $envelopeType));
}
$this->_envelope = $envelopeType;
return $this;
}
/**
* Retrieve envelope
*
* @return string
*/
public function getEnvelope()
{
return $this->_envelope;
}
// Content-Type of response; default to application/json
/**
* Set content type
*
* @param string $type
* @return Zend_Json_Server_Smd
*/
public function setContentType($type)
{
if (!preg_match($this->_contentTypeRegex, $type)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception(sprintf('Invalid content type "%s" specified', $type));
}
$this->_contentType = $type;
return $this;
}
/**
* Retrieve content type
*
* @return string
*/
public function getContentType()
{
return $this->_contentType;
}
/**
* Set service target
*
* @param string $target
* @return Zend_Json_Server_Smd
*/
public function setTarget($target)
{
$this->_target = (string) $target;
return $this;
}
/**
* Retrieve service target
*
* @return string
*/
public function getTarget()
{
return $this->_target;
}
/**
* Set service ID
*
* @param string $Id
* @return Zend_Json_Server_Smd
*/
public function setId($id)
{
$this->_id = (string) $id;
return $this->_id;
}
/**
* Get service id
*
* @return string
*/
public function getId()
{
return $this->_id;
}
/**
* Set service description
*
* @param string $description
* @return Zend_Json_Server_Smd
*/
public function setDescription($description)
{
$this->_description = (string) $description;
return $this->_description;
}
/**
* Get service description
*
* @return string
*/
public function getDescription()
{
return $this->_description;
}
/**
* Indicate whether or not to generate Dojo-compatible SMD
*
* @param bool $flag
* @return Zend_Json_Server_Smd
*/
public function setDojoCompatible($flag)
{
$this->_dojoCompatible = (bool) $flag;
return $this;
}
/**
* Is this a Dojo compatible SMD?
*
* @return bool
*/
public function isDojoCompatible()
{
return $this->_dojoCompatible;
}
/**
* Add Service
*
* @param Zend_Json_Server_Smd_Service|array $service
* @return void
*/
public function addService($service)
{
require_once 'Zend/Json/Server/Smd/Service.php';
if ($service instanceof Zend_Json_Server_Smd_Service) {
$name = $service->getName();
} elseif (is_array($service)) {
$service = new Zend_Json_Server_Smd_Service($service);
$name = $service->getName();
} else {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Invalid service passed to addService()');
}
if (array_key_exists($name, $this->_services)) {
require_once 'Zend/Json/Server/Exception.php';
throw new Zend_Json_Server_Exception('Attempt to register a service already registered detected');
}
$this->_services[$name] = $service;
return $this;
}
/**
* Add many services
*
* @param array $services
* @return Zend_Json_Server_Smd
*/
public function addServices(array $services)
{
foreach ($services as $service) {
$this->addService($service);
}
return $this;
}
/**
* Overwrite existing services with new ones
*
* @param array $services
* @return Zend_Json_Server_Smd
*/
public function setServices(array $services)
{
$this->_services = array();
return $this->addServices($services);
}
/**
* Get service object
*
* @param string $name
* @return false|Zend_Json_Server_Smd_Service
*/
public function getService($name)
{
if (array_key_exists($name, $this->_services)) {
return $this->_services[$name];
}
return false;
}
/**
* Return services
*
* @return array
*/
public function getServices()
{
return $this->_services;
}
/**
* Remove service
*
* @param string $name
* @return boolean
*/
public function removeService($name)
{
if (array_key_exists($name, $this->_services)) {
unset($this->_services[$name]);
return true;
}
return false;
}
/**
* Cast to array
*
* @return array
*/
public function toArray()
{
if ($this->isDojoCompatible()) {
return $this->toDojoArray();
}
$transport = $this->getTransport();
$envelope = $this->getEnvelope();
$contentType = $this->getContentType();
$SMDVersion = self::SMD_VERSION;
$service = compact('transport', 'envelope', 'contentType', 'SMDVersion');
if (null !== ($target = $this->getTarget())) {
$service['target'] = $target;
}
if (null !== ($id = $this->getId())) {
$service['id'] = $id;
}
$services = $this->getServices();
if (!empty($services)) {
$service['services'] = array();
foreach ($services as $name => $svc) {
$svc->setEnvelope($envelope);
$service['services'][$name] = $svc->toArray();
}
$service['methods'] = $service['services'];
}
return $service;
}
/**
* Export to DOJO-compatible SMD array
*
* @return array
*/
public function toDojoArray()
{
$SMDVersion = '.1';
$serviceType = 'JSON-RPC';
$service = compact('SMDVersion', 'serviceType');
$target = $this->getTarget();
$services = $this->getServices();
if (!empty($services)) {
$service['methods'] = array();
foreach ($services as $name => $svc) {
$method = array(
'name' => $name,
'serviceURL' => $target,
);
$params = array();
foreach ($svc->getParams() as $param) {
$paramName = array_key_exists('name', $param) ? $param['name'] : $param['type'];
$params[] = array(
'name' => $paramName,
'type' => $param['type'],
);
}
if (!empty($params)) {
$method['parameters'] = $params;
}
$service['methods'][] = $method;
}
}
return $service;
}
/**
* Cast to JSON
*
* @return string
*/
public function toJson()
{
require_once 'Zend/Json.php';
return Zend_Json::encode($this->toArray());
}
/**
* Cast to string (JSON)
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
}
| agpl-3.0 |
worknenjoy/gitpay | migration/migrations/20181227152503-create-offer.js | 1122 | 'use strict';
module.exports = {
up: function (queryInterface, Sequelize) {
return queryInterface.createTable('Offers', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
type: Sequelize.INTEGER,
references: {
model: 'Users',
key: 'id'
},
allowNull: true
},
taskId: {
type: Sequelize.INTEGER,
references: {
model: 'Tasks',
key: 'id'
},
allowNull: true
},
value: {
type: Sequelize.DECIMAL
},
suggestedDate: {
type: Sequelize.DATE,
allowNull: true,
},
comment: {
type: Sequelize.STRING,
},
learn: {
type: Sequelize.BOOLEAN
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function (queryInterface, Sequelize) {
return queryInterface.dropTable('Offers');
}
};
| agpl-3.0 |
Maslosoft/IlmatarWidgets | src/Renderers/Form/HtmlArea.php | 633 | <?php
/**
* This software package is licensed under AGPL or Commercial license.
*
* @package maslosoft/ilmatar-widgets
* @licence AGPL or Commercial
* @copyright Copyright (c) Piotr Masełkowski <pmaselkowski@gmail.com>
* @copyright Copyright (c) Maslosoft
* @link http://maslosoft.com/ilmatar-widgets/
*/
namespace Maslosoft\Ilmatar\Widgets\Renderers\Form;
/**
* HtmlArea
*
* Use this for multiline rich text input
*
* @author Piotr Maselkowski <pmaselkowski at gmail.com>
*/
class HtmlArea extends HtmlInput
{
public function init()
{
parent::init();
$this->innerOptions['style'] = 'min-height:6em;';
}
}
| agpl-3.0 |
Amos2016GroupOne/amos-ss16-proj1 | tests/unit-tests/SettingsCtrl.tests.js | 11388 | /*
* Projectname: amos-ss16-proj1
*
* Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe1
*
* This file is part of the AMOS Project 2016 @ FAU
* (Friedrich-Alexander University Erlangen-Nürnberg)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
var DBMeter = null;
describe('SettingsCtrl:', function() {
var controller,
LogMock,
settingsMock,
$scope;
// Load the App Module as a mock.
// This will also make all app intern services available per inject()
beforeEach(module('app', function ($provide, $translateProvider) {
//use a custom Loader for angular-translate. Otherwise some test will fail with
//"Error: Unexpected request: GET en-us.json"
//why this has to be done is explained in detail here:
//https://angular-translate.github.io/docs/#/guide/22_unit-testing-with-angular-translate
$provide.factory('customLoader', function ($q) {
return function () {
var deferred = $q.defer();
deferred.resolve({});
return deferred.promise;
};
});
$translateProvider.useLoader('customLoader');
$translateProvider.translations('en-us', {
"LANGUAGE": "language",
"PROMPT_TURN_ON_BLUETOOTH": "BLEaring would like to turn on Bluetooth",
"ONLY_AVAIL_IN_EN_US": "this translation is only available in en-us"
});
$translateProvider.translations('de-de', {
"LANGUAGE": "Sprache",
"PROMPT_TURN_ON_BLUETOOTH": "BLEaring möchte Bluetooth aktivieren"
});
}));
// Disable template caching
beforeEach(module(function($provide, $urlRouterProvider) {
$provide.value('$ionicTemplateCache', function(){} );
$urlRouterProvider.deferIntercept();
}));
// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
beforeEach(inject(function(_$compile_, _$rootScope_, _$timeout_, _$translate_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$compile = _$compile_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
$translate = _$translate_;
}));
// Instantiate the Controller and Mocks
// Using angular-mocks inject() for having all the providers ($...) available!
beforeEach(inject(function($rootScope, $controller) {
DBMeter = MockFactory.createNewDBMeterMock();
settingsMock = MockFactory.createNewSettingsMock();
LogMock = { };
$scope = $rootScope.$new();
controller = $controller('SettingsCtrl',{
'$scope': $scope,
// '$ionicPlatform': - not specified, so it will take the original ionicPlatform
'Log': LogMock,
//'settings': settingsMock
});
}));
// for easy muting:
function muteHelper(mute) {
$scope.settings.mute = mute;
$scope.muteToggle();
}
// for easy volume set:
function setVolume(vol) {
$scope.settings.volume = vol;
$scope.changedVolume();
}
// for easy decibel set:
function setListenDecibel(val) {
$scope.settings.isListeningDecibel = val;
$scope.decibelToggle();
}
function setLanguage(lang) {
$scope.settings.language = lang;
$scope.changeLanguage();
}
function setScanDuration(index) {
$scope.durationSlider.selectedIndex = index;
$scope.scanDurationChanged();
}
describe('Translation', function(){
it('should translate html expression to currently set language', function(){
setLanguage('en-us');
// Compile a piece of HTML containing the translate filter
var element = $compile("<div>{{ 'LANGUAGE' | translate }}</div>")($rootScope);
// fire all the watches, so the scope expression {{ 'LANGUAGE' | translate }} will be evaluated
$rootScope.$digest();
// Check that the compiled element contains the templated content
expect(element.html()).toContain("language");
setLanguage('de-de');
var element = $compile("<div>{{ 'LANGUAGE' | translate }}</div>")($rootScope);
$rootScope.$digest();
expect(element.html()).toContain("Sprache");
});
it('should translate notification text instantly to currently set language', function(){
setLanguage('en-us');
expect($translate.instant('PROMPT_TURN_ON_BLUETOOTH')).toBe('BLEaring would like to turn on Bluetooth');
setLanguage('de-de');
expect($translate.instant('PROMPT_TURN_ON_BLUETOOTH')).toBe('BLEaring möchte Bluetooth aktivieren');
});
it('should translate notifications text asynchronously to currently set language', function(){
setLanguage('en-us');
var translationString;
$translate('PROMPT_TURN_ON_BLUETOOTH').then(function (translation) {
translationString = translation;
});
$rootScope.$digest();
expect(translationString).toBe('BLEaring would like to turn on Bluetooth');
setLanguage('de-de');
$translate('PROMPT_TURN_ON_BLUETOOTH').then(function (translation) {
translationString = translation;
});
$rootScope.$digest();
expect(translationString).toBe('BLEaring möchte Bluetooth aktivieren');
});
it('should translate to english if the translation id is not found', function(){
setLanguage('de-de');
$translate.fallbackLanguage('en-us');
expect($translate.instant('ONLY_AVAIL_IN_EN_US')).toBe('this translation is only available in en-us');
});
it('should change floating direction to right if changing language to ar-sy', function(){
setLanguage('de-de');
setLanguage('ar-sy');
expect($rootScope.default_float).toBe('right');
});
});
describe('Muting', function() {
it('should set volume to 0', function() {
muteHelper(true);
expect($scope.settings.volume).toBe(0);
});
it('should restore volume profile', function() {
$scope.settings.currentVolumeProfile = JSON.stringify($scope.settings.volumeProfiles[1]);
$scope.changeVolumeProfile();
var old = $scope.settings.volume;
muteHelper(true);
expect($scope.settings.mute).toBe(true);
muteHelper(false);
expect($scope.settings.volume).toBe(old);
expect($scope.settings.currentVolumeProfile).toBe(JSON.stringify($scope.settings.volumeProfiles[1]));
});
it('should deselect volume profiles', function() {
muteHelper(false);
$scope.settings.currentVolumeProfile = JSON.stringify($scope.settings.volumeProfiles[1]);
$scope.changeVolumeProfile();
//when muting now no profile should be selected anymore
muteHelper(true);
for(var i = 0; i<$scope.settings.volumeProfiles.length; i++){
JSON.stringify($scope.settings.volumeProfiles[1])
expect($scope.settings.currentVolumeProfile).not.toBe(JSON.stringify($scope.settings.volumeProfiles[i]));
}
});
it('should reselect volume profiles', function() {
muteHelper(false);
$scope.settings.currentVolumeProfile = JSON.stringify($scope.settings.volumeProfiles[1]);
$scope.changeVolumeProfile();
muteHelper(true);
//when unmuting now the profile should be selected again
muteHelper(false);
expect($scope.settings.currentVolumeProfile).toBe(JSON.stringify($scope.settings.volumeProfiles[1]));
});
it('should unmute on volumeChange', function() {
muteHelper(true);
expect($scope.settings.mute).toBe(true);
setVolume(55);
expect($scope.settings.mute).toBe(false);
});
it('should restore volume before on unmute', function() {
setVolume(55);
expect($scope.settings.volume).toBe(55);
muteHelper(true);
expect($scope.settings.mute).toBe(true);
muteHelper(false);
expect($scope.settings.mute).toBe(false);
expect($scope.settings.volume).toBe(55);
});
});
describe('VolumeHardButtons', function() {
it('should unmute', function(){
muteHelper(true);
expect($scope.settings.mute).toBe(true);
$scope.$emit('volumeupbutton');
$timeout.flush();
expect($scope.settings.mute).toBe(false);
muteHelper(true);
expect($scope.settings.mute).toBe(true);
$scope.$emit('volumedownbutton');
$timeout.flush();
expect($scope.settings.mute).toBe(false);
});
it('should change the volume in the right direction', function() {
var old = $scope.settings.volume;
$scope.$emit('volumeupbutton');
$timeout.flush();
expect($scope.settings.volume).toBeGreaterThan(old);
old = $scope.settings.volume;
$scope.$emit('volumedownbutton');
$timeout.flush();
expect($scope.settings.volume).toBeLessThan(old);
});
it('should be capped', function() {
setVolume(0);
$scope.$emit('volumedownbutton');
$timeout.flush();
expect($scope.settings.volume).toBe(0);
setVolume(100);
$scope.$emit('volumeupbutton');
$timeout.flush();
expect($scope.settings.volume).toBe(100);
});
});
describe('Decibel Measurement', function() {
beforeEach(function() {
jasmine.clock().install();
setListenDecibel(true);
});
afterEach(function() {
jasmine.clock().uninstall();
});
it('should start the measurements', function() {
jasmine.clock().tick(101); // wait a bit...
$timeout.flush();
expect($scope.decibel).toBeGreaterThan(0);
expect(typeof $scope.decibel).toEqual('string');
});
it('should run the measurements', function() {
var old = DBMeter.callCounter;
jasmine.clock().tick(101);
$timeout.flush();
expect(DBMeter.callCounter).toBeGreaterThan(old);
});
it('should stop the measurements', function() {
old = DBMeter.callCounter;
setListenDecibel(false);
jasmine.clock().tick(102); // to ensure it has stopped it somehow...
$timeout.flush();
expect(DBMeter.callCounter).toEqual(old);
});
});
describe('Scan Duration', function() {
it('should set the right scan duration value according to the index of the slider', function(){
var index = 0;
setScanDuration(index);
expect($scope.settings.duration).toBe(1);
var index = 12;
setScanDuration(index);
expect($scope.settings.duration).toBe(60);
var index = 4;
setScanDuration(index);
expect($scope.settings.duration).toBe(20);
});
it('should set the right index according to scan duration value the slider shows on app start', function(){
$scope.settings.duration = 1;
$scope.durationSlider.selectedIndex = $scope.durationSlider.getInitialIndex();
expect($scope.durationSlider.selectedIndex).toBe(0);
$scope.settings.duration = 20;
$scope.durationSlider.selectedIndex = $scope.durationSlider.getInitialIndex();
expect($scope.durationSlider.selectedIndex).toBe(4);
$scope.settings.duration = 60;
$scope.durationSlider.selectedIndex = $scope.durationSlider.getInitialIndex();
expect($scope.durationSlider.selectedIndex).toBe(12);
});
});
});
| agpl-3.0 |
protogalaxy/service-device-presence | Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go | 3210 | // Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2014 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto_test
import (
"testing"
pb "./proto3_proto"
"github.com/protogalaxy/service-device-presence/Godeps/_workspace/src/github.com/golang/protobuf/proto"
)
func TestProto3ZeroValues(t *testing.T) {
tests := []struct {
desc string
m proto.Message
}{
{"zero message", &pb.Message{}},
{"empty bytes field", &pb.Message{Data: []byte{}}},
}
for _, test := range tests {
b, err := proto.Marshal(test.m)
if err != nil {
t.Errorf("%s: proto.Marshal: %v", test.desc, err)
continue
}
if len(b) > 0 {
t.Errorf("%s: Encoding is non-empty: %q", test.desc, b)
}
}
}
func TestRoundTripProto3(t *testing.T) {
m := &pb.Message{
Name: "David", // (2 | 1<<3): 0x0a 0x05 "David"
Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01
HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01
Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto"
ResultCount: 47, // (0 | 7<<3): 0x38 0x2f
TrueScotsman: true, // (0 | 8<<3): 0x40 0x01
Score: 8.1, // (5 | 9<<3): 0x4d <8.1>
Key: []uint64{1, 0xdeadbeef},
Nested: &pb.Nested{
Bunny: "Monty",
},
}
t.Logf(" m: %v", m)
b, err := proto.Marshal(m)
if err != nil {
t.Fatalf("proto.Marshal: %v", err)
}
t.Logf(" b: %q", b)
m2 := new(pb.Message)
if err := proto.Unmarshal(b, m2); err != nil {
t.Fatalf("proto.Unmarshal: %v", err)
}
t.Logf("m2: %v", m2)
if !proto.Equal(m, m2) {
t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2)
}
}
| agpl-3.0 |
SourceMod-Store/WebPanel-Core | app/Http/Controllers/WebPanel/Store/VersionsController.php | 9223 | <?php namespace App\Http\Controllers\WebPanel\Store;
//Copyright (c) 2015 "Werner Maisl"
//
//This file is part of the Store Webpanel V2.
//
//The Store Webpanel V2 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/>.
use App\Models\StoreVersion;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Storage;
use Carbon\Carbon;
use Illuminate\Http\Request;
class VersionsController extends Controller
{
/**
* Gives an Overview of the installed module Versions
*
* @return Response
*/
public function index()
{
//If the user us using private plugins
$private_plugins = false;
//Check if the Versions are cached
if(!Storage::exists('/versions/master.json'))
{
$this->do_update();
}
$master_json = Storage::get('/versions/master.json');
$master_array = json_decode($master_json,true);
$master_version = $master_array['format-version'];
//Verify that the master_version is correct
if($master_version != '0.0.3')
{
$versions = array();
return view('templates.' . \Config::get('webpanel.template') . 'webpanel.store.versions.index', compact('versions'))
->with("flash_notification",array("message"=>"Master Version Mismatch", "level"=>"error"));
}
//Get days since the last update
$update_date = Storage::lastModified('/versions/master.json');
$update_date = Carbon::createFromTimestamp($update_date);
$current_date = Carbon::today();
$date_diff = $update_date->diffInDays($current_date);
//Get the installed modules from the db
$plugins = StoreVersion::all();
//dd($plugins);
$plugin_versions = array();
foreach($plugins as $plugin)
{
if(Storage::exists('/versions/'.$plugin->mod_ver_convar.'.json'))
{
//Populate the default fields
$plugin_versions[$plugin->id]["mod_id"] = $plugin->id;
$plugin_versions[$plugin->id]["mod_name"] = $plugin->mod_name;
$plugin_versions[$plugin->id]["mod_description"] = $plugin->mod_description;
$plugin_versions[$plugin->id]["mod_ver_convar"] = $plugin->mod_ver_convar;
$plugin_versions[$plugin->id]["mod_ver_number"] = $plugin->mod_ver_number;
$plugin_versions[$plugin->id]["mod_last_updated"] = $plugin->last_updated;
$plugin_versions[$plugin->id]["server_id"] = $plugin->server_id;
//Get the online data for the plugin
$plugin_data =json_decode(Storage::get('/versions/'.$plugin->mod_ver_convar.'.json'),true);
//Add the online data to the plugin
$plugin_versions[$plugin->id]["name"] = $plugin_data["name"];
$plugin_versions[$plugin->id]["display-name"] = $plugin_data["display-name"];
$plugin_versions[$plugin->id]["description"] = $plugin_data["description"];
$plugin_versions[$plugin->id]["author"] = $plugin_data["author"];
$plugin_versions[$plugin->id]["current-version"] = $plugin_data["current-version"];
$plugin_versions[$plugin->id]["min-store-version"] = $plugin_data["min-store-version"];
$plugin_versions[$plugin->id]["max-store-version"] = $plugin_data["max-store-version"];
$plugin_versions[$plugin->id]["link"] = $plugin_data["link"];
$plugin_versions[$plugin->id]["tags"] = $plugin_data["tags"];
//Check if its up2date
$u2d = $this->check_if_up2date($plugin->mod_ver_number, $plugin_data["current-version"]);
$plugin_versions[$plugin->id]["version"] = $u2d;
}
else
{
$private_plugins = true;
}
}
return view('templates.' . \Config::get('webpanel.template') . 'webpanel.store.versions.index', compact('date_diff','plugin_versions','private_plugins'));
}
/**
* Shows details about the Selected Version
*
* @param StoreVersion $version
*/
public function show($version)
{
dd($version);
}
/**
* Updates the Cached Versions
*/
public function update()
{
$this->do_update();
return redirect()->route('webpanel.store.versions.index');
}
/**
* Perform the Update
*/
private function do_update()
{
//Delete the current files
$files = Storage::allFiles('/versions');
Storage::delete($files);
//Download the main file
$master_version = file_get_contents('https://raw.githubusercontent.com/SourceMod-Store/Module-Versions/master/modules.json');
Storage::put('/versions/master.json',$master_version);
$master_version = json_decode($master_version,true);
//Download additional files
foreach($master_version['modules-links'] as $module=>$version_link)
{
Storage::put('/versions/'.$module.'.json',file_get_contents($version_link));
}
}
/**
* Check if the store plugin is up2date
*/
private function check_if_up2date($plugin_version,$online_version)
{
//Return
/**
* txt_short = Short Message to the User
* txt_long = Long Message
* description = A description of the available update
* code = a return code that describes what happened
* * 0 -> up2date
* * 11 -> major version outofdate
* * 12 -> minor version outofdate
* * 13 -> patchlevel outofdate
* * 91 -> Problem when checking major version
* * 92 -> Problem when checking minor version
* * 93 -> Problem when checking patchlevel
*/
$plg_ver_array = explode(".",$plugin_version);
$onl_ver_array = explode(".",$online_version);
//Compare Major Version, then Minor and then Patchlevel
if($plg_ver_array[0] < $onl_ver_array[0])
{
return array(
"txt_short"=>"Out Of Date",
"txt_long"=>"Major Version is out of date",
"description" => "A Major Release is available",
"code"=>"11",
);
}
elseif($plg_ver_array[0] == $onl_ver_array[0])
{
//Compare Minor Versions
if($plg_ver_array[1] < $onl_ver_array[1])
{
return array(
"txt_short"=>"Out Of Date",
"txt_long"=>"Minor Version is out of date",
"description" => "A feature update is available",
"code"=>"12",
);
}
elseif($plg_ver_array[1] == $onl_ver_array[1])
{
if($plg_ver_array[2] < $onl_ver_array[2])
{
return array(
"txt_short"=>"Out Of Date",
"txt_long"=>"Patchlevel is out of date",
"description" => "A patch is available",
"code"=>"13",
);
}
elseif($plg_ver_array[2] == $onl_ver_array[2])
{
return array(
"txt_short"=>"Up2Date",
"txt_long"=>"The version is up to date",
"description" => "There is no update available",
"code"=>"0",
);
}
else
{
return array(
"txt_short"=>"Error",
"txt_long"=>"Error during version check",
"description" => "There has been an error while checking the patchlevel",
"code"=>"93",
);
}
}
else
{
return array(
"txt_short"=>"Error",
"txt_long"=>"Error during version check",
"description" => "There has been an error while checking minor version",
"code"=>"92",
);
}
}
else
{
return array(
"txt_short"=>"Error",
"txt_long"=>"Error during version check",
"description" => "There has been an error while checking the major version",
"code"=>"91",
);
}
}
}
| agpl-3.0 |
kc5nra/RevTK | apps/core/modules/includes/actions/componentDemo1Component.php | 480 | <?php
/**
* Example component, using one action per file.
*
* @package RevTK
* @author Fabrice Denis
* @see documentation/helpers/partial
*/
class componentDemo1Component extends coreComponent
{
public function execute()
{
$this->component_set_var = 'Error';
if (isset($this->include_component_var)) {
$this->component_set_var = 'Success';
}
$this->component_variables = $this->getVarHolder()->getAll();
return coreView::SUCCESS;
}
} | agpl-3.0 |
gabrys/wikidot | php/db/DB_PageFtsEntryPeer.php | 998 | <?php
/**
* Wikidot - free wiki collaboration software
* Copyright (c) 2008, Wikidot 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.
*
* For more information about licensing visit:
* http://www.wikidot.org/license
*
* @category Wikidot
* @package Wikidot_Db
* @version $Id$
* @copyright Copyright (c) 2008, Wikidot Inc.
* @license http://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License
*/
/**
* Object Model class.
*
*/
class DB_PageFtsEntryPeer extends DB_PageFtsEntryPeerBase {
}
| agpl-3.0 |
vladnicoara/superdesk-client-core | test-server/gunicorn_config.py | 145 |
import os
bind = '0.0.0.0:%s' % os.environ.get('PORT', '5000')
reload = False
workers = 2
timeout = 8
max_requests = 500
loglevel = 'error'
| agpl-3.0 |
jazztpt/edx-platform | lms/djangoapps/teams/static/teams/js/views/edit_team.js | 8758 | ;(function (define) {
'use strict';
define(['backbone',
'underscore',
'gettext',
'js/views/fields',
'teams/js/models/team',
'text!teams/templates/edit-team.underscore'],
function (Backbone, _, gettext, FieldViews, TeamModel, editTeamTemplate) {
return Backbone.View.extend({
maxTeamNameLength: 255,
maxTeamDescriptionLength: 300,
events: {
'click .action-primary': 'createTeam',
'submit form': 'createTeam',
'click .action-cancel': 'goBackToTopic'
},
initialize: function(options) {
this.courseID = options.teamParams.courseID;
this.topicID = options.teamParams.topicID;
this.collection = options.collection;
this.teamsUrl = options.teamParams.teamsUrl;
this.languages = options.teamParams.languages;
this.countries = options.teamParams.countries;
this.primaryButtonTitle = options.primaryButtonTitle || 'Submit';
_.bindAll(this, 'goBackToTopic', 'createTeam');
this.teamModel = new TeamModel({});
this.teamModel.url = this.teamsUrl;
this.teamNameField = new FieldViews.TextFieldView({
model: this.teamModel,
title: gettext('Team Name (Required) *'),
valueAttribute: 'name',
helpMessage: gettext('A name that identifies your team (maximum 255 characters).')
});
this.teamDescriptionField = new FieldViews.TextareaFieldView({
model: this.teamModel,
title: gettext('Team Description (Required) *'),
valueAttribute: 'description',
editable: 'always',
showMessages: false,
helpMessage: gettext('A short description of the team to help other learners understand the goals or direction of the team (maximum 300 characters).')
});
this.teamLanguageField = new FieldViews.DropdownFieldView({
model: this.teamModel,
title: gettext('Language'),
valueAttribute: 'language',
required: false,
showMessages: false,
titleIconName: 'fa-comment-o',
options: this.languages,
helpMessage: gettext('The language that team members primarily use to communicate with each other.')
});
this.teamCountryField = new FieldViews.DropdownFieldView({
model: this.teamModel,
title: gettext('Country'),
valueAttribute: 'country',
required: false,
showMessages: false,
titleIconName: 'fa-globe',
options: this.countries,
helpMessage: gettext('The country that team members primarily identify with.')
});
},
render: function() {
this.$el.html(_.template(editTeamTemplate)({primaryButtonTitle: this.primaryButtonTitle}));
this.set(this.teamNameField, '.team-required-fields');
this.set(this.teamDescriptionField, '.team-required-fields');
this.set(this.teamLanguageField, '.team-optional-fields');
this.set(this.teamCountryField, '.team-optional-fields');
return this;
},
set: function(view, selector) {
var viewEl = view.$el;
if (this.$(selector).has(viewEl).length) {
view.render().setElement(viewEl);
} else {
this.$(selector).append(view.render().$el);
}
},
createTeam: function (event) {
event.preventDefault();
var view = this,
teamLanguage = this.teamLanguageField.fieldValue(),
teamCountry = this.teamCountryField.fieldValue();
var data = {
course_id: this.courseID,
topic_id: this.topicID,
name: this.teamNameField.fieldValue(),
description: this.teamDescriptionField.fieldValue(),
language: _.isNull(teamLanguage) ? '' : teamLanguage,
country: _.isNull(teamCountry) ? '' : teamCountry
};
var validationResult = this.validateTeamData(data);
if (validationResult.status === false) {
this.showMessage(validationResult.message, validationResult.srMessage);
return;
}
this.teamModel.save(data, { wait: true })
.done(function(result) {
Backbone.history.navigate(
'teams/' + view.topicID + '/' + view.teamModel.id,
{trigger: true}
);
})
.fail(function(data) {
var response = JSON.parse(data.responseText);
var message = gettext("An error occurred. Please try again.")
if ('error_message' in response && 'user_message' in response['error_message']){
message = response['error_message']['user_message'];
}
view.showMessage(message, message);
});
},
validateTeamData: function (data) {
var status = true,
message = gettext('Check the highlighted fields below and try again.');
var srMessages = [];
this.teamNameField.unhighlightField();
this.teamDescriptionField.unhighlightField();
if (_.isEmpty(data.name.trim()) ) {
status = false;
this.teamNameField.highlightFieldOnError();
srMessages.push(
gettext('Enter team name.')
);
} else if (data.name.length > this.maxTeamNameLength) {
status = false;
this.teamNameField.highlightFieldOnError();
srMessages.push(
gettext('Team name cannot have more than 255 characters.')
);
}
if (_.isEmpty(data.description.trim()) ) {
status = false;
this.teamDescriptionField.highlightFieldOnError();
srMessages.push(
gettext('Enter team description.')
);
} else if (data.description.length > this.maxTeamDescriptionLength) {
status = false;
this.teamDescriptionField.highlightFieldOnError();
srMessages.push(
gettext('Team description cannot have more than 300 characters.')
);
}
return {
status: status,
message: message,
srMessage: srMessages.join(' ')
};
},
showMessage: function (message, screenReaderMessage) {
this.$('.wrapper-msg').removeClass('is-hidden');
this.$('.msg-content .copy p').text(message);
this.$('.wrapper-msg').focus();
if (screenReaderMessage) {
this.$('.screen-reader-message').text(screenReaderMessage);
}
},
goBackToTopic: function () {
Backbone.history.navigate('topics/' + this.topicID, {trigger: true});
}
});
});
}).call(this, define || RequireJS.define);
| agpl-3.0 |
avikivity/scylla | test/alternator/test_key_conditions.py | 29297 | # -*- coding: utf-8 -*-
# Copyright 2020 ScyllaDB
#
# This file is part of Scylla.
#
# Scylla 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.
#
# Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
# Tests for the KeyConditions parameter of the Query operation.
# KeyConditions is the older version of the newer "KeyConditionExpression"
# syntax. That newer syntax is tested in test_key_conditions.py.
import pytest
from botocore.exceptions import ClientError
from util import random_string, random_bytes, full_query, multiset
# The test_table_{sn,ss,sb}_with_sorted_partition fixtures are the regular
# test_table_{sn,ss,sb} fixture with a partition inserted with many items.
# The table, the partition key, and the items are returned - the items are
# sorted (by column 'c'), so they can be easily used to test various range
# queries. This fixture is useful for writing many small query tests which
# read the same input data without needing to re-insert data for every test,
# so overall the test suite is faster.
@pytest.fixture(scope="session")
def test_table_sn_with_sorted_partition(test_table_sn):
p = random_string()
items = [{'p': p, 'c': i, 'a': random_string()} for i in range(12)]
with test_table_sn.batch_writer() as batch:
for item in items:
batch.put_item(item)
# Add another partition just to make sure that a query of just
# partition p can't just match the entire table and still succeed
batch.put_item({'p': random_string(), 'c': 123, 'a': random_string()})
yield test_table_sn, p, items
@pytest.fixture(scope="session")
def test_table_ss_with_sorted_partition(test_table):
p = random_string()
items = [{'p': p, 'c': str(i).zfill(3), 'a': random_string()} for i in range(12)]
with test_table.batch_writer() as batch:
for item in items:
batch.put_item(item)
batch.put_item({'p': random_string(), 'c': '123', 'a': random_string()})
yield test_table, p, items
@pytest.fixture(scope="session")
def test_table_sb_with_sorted_partition(test_table_sb):
p = random_string()
items = [{'p': p, 'c': bytearray(str(i).zfill(3), 'ascii'), 'a': random_string()} for i in range(12)]
with test_table_sb.batch_writer() as batch:
for item in items:
batch.put_item(item)
batch.put_item({'p': random_string(), 'c': bytearray('123', 'ascii'), 'a': random_string()})
yield test_table_sb, p, items
# A key condition with just a partition key, returning the entire partition
def test_key_conditions_partition(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'}})
# Both items and got_items are already sorted, so simple equality check is enough
assert(got_items == items)
# The "ComparisonOperator" is case sensitive, "EQ" works but "eq" does not:
def test_key_conditions_comparison_operator_case(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
with pytest.raises(ClientError, match='ValidationException.*eq'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'eq'}})
# Only the "EQ" operator is allowed for the partition keys. The operators "LE",
# "LT", "GE", "GT", "BEGINS_WITH" and "BETWEEN" are allowed for the sort key
# (we'll test this below), but NOT for the partition key. Other random strings
# also are not allowed, but with a different error message.
def test_key_conditions_partition_only_eq(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
for op in ['LE', 'LT', 'GE', 'GT', 'BEGINS_WITH']:
with pytest.raises(ClientError, match='ValidationException.*not supported'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': op}})
# 'BETWEEN' also fails the test above, but with a different error (it needs
# two arguments). So let's test it fails also with two arguments:
with pytest.raises(ClientError, match='ValidationException.*not supported'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p, p], 'ComparisonOperator': 'BETWEEN'}})
# An unknown operator, e.g., "DOG", is also not allowed, but with a
# different error message.
with pytest.raises(ClientError, match='ValidationException.*DOG'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p, p], 'ComparisonOperator': 'DOG'}})
# The operators 'NULL', 'NOT_NULL', 'IN', 'CONTAINS', 'NOT_CONTAINS', 'NE'
# exist for ComparisonOperator and are allowed in filters, but not allowed
# in key conditions:
for op in ['IN', 'CONTAINS', 'NOT_CONTAINS', 'NE']:
with pytest.raises(ClientError, match='ValidationException'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': op}})
for op in ['NULL', 'NOT_NULL']:
with pytest.raises(ClientError, match='ValidationException'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [], 'ComparisonOperator': op}})
# The "EQ" operator requires exactly one argument, not more, not less.
def test_key_conditions_partition_one(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
with pytest.raises(ClientError, match='ValidationException.*EQ'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [], 'ComparisonOperator': 'EQ'}})
with pytest.raises(ClientError, match='ValidationException.*EQ'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p, p], 'ComparisonOperator': 'EQ'}})
# A KeyCondition must define the partition key p, it can't be just on the
# sort key c.
def test_key_conditions_partition_missing(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
with pytest.raises(ClientError, match='ValidationException.* miss'):
full_query(table, KeyConditions={
'c' : {'AttributeValueList': [3], 'ComparisonOperator': 'EQ'}})
# The following tests test the various condition operators on the sort key,
# for a *numeric* sort key:
# Test the EQ operator on a numeric sort key:
def test_key_conditions_num_eq(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [3], 'ComparisonOperator': 'EQ'}})
expected_items = [item for item in items if item['c'] == 3]
assert(got_items == expected_items)
# Test the LT operator on a numeric sort key:
def test_key_conditions_num_lt(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [5], 'ComparisonOperator': 'LT'}})
expected_items = [item for item in items if item['c'] < 5]
assert(got_items == expected_items)
# Test the LE operator on a numeric sort key:
def test_key_conditions_num_le(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [5], 'ComparisonOperator': 'LE'}})
expected_items = [item for item in items if item['c'] <= 5]
assert(got_items == expected_items)
# Test the GT operator on a numeric sort key:
def test_key_conditions_num_gt(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [5], 'ComparisonOperator': 'GT'}})
expected_items = [item for item in items if item['c'] > 5]
assert(got_items == expected_items)
# Test the GE operator on a numeric sort key:
def test_key_conditions_num_ge(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [5], 'ComparisonOperator': 'GE'}})
expected_items = [item for item in items if item['c'] >= 5]
assert(got_items == expected_items)
# Test the BETWEEN operator on a numeric sort key:
def test_key_conditions_num_between(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [4, 7], 'ComparisonOperator': 'BETWEEN'}})
expected_items = [item for item in items if item['c'] >= 4 and item['c'] <= 7]
assert(got_items == expected_items)
# The BEGINS_WITH operator does *not* work on a numeric sort key (it only
# works on strings or bytes - we'll check this later):
def test_key_conditions_num_begins(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
with pytest.raises(ClientError, match='ValidationException.*BEGINS_WITH'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [3], 'ComparisonOperator': 'BEGINS_WITH'}})
# The following tests test the various condition operators on the sort key,
# for a *string* sort key:
# Test the EQ operator on a string sort key:
def test_key_conditions_str_eq(test_table_ss_with_sorted_partition):
table, p, items = test_table_ss_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['003'], 'ComparisonOperator': 'EQ'}})
expected_items = [item for item in items if item['c'] == '003']
assert(got_items == expected_items)
# Test the LT operator on a string sort key:
def test_key_conditions_str_lt(test_table_ss_with_sorted_partition):
table, p, items = test_table_ss_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['005'], 'ComparisonOperator': 'LT'}})
expected_items = [item for item in items if item['c'] < '005']
assert(got_items == expected_items)
# Test the LE operator on a string sort key:
def test_key_conditions_str_le(test_table_ss_with_sorted_partition):
table, p, items = test_table_ss_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['005'], 'ComparisonOperator': 'LE'}})
expected_items = [item for item in items if item['c'] <= '005']
assert(got_items == expected_items)
# Test the GT operator on a string sort key:
def test_key_conditions_str_gt(test_table_ss_with_sorted_partition):
table, p, items = test_table_ss_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['005'], 'ComparisonOperator': 'GT'}})
expected_items = [item for item in items if item['c'] > '005']
assert(got_items == expected_items)
# Test the GE operator on a string sort key:
def test_key_conditions_str_ge(test_table_ss_with_sorted_partition):
table, p, items = test_table_ss_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['005'], 'ComparisonOperator': 'GE'}})
expected_items = [item for item in items if item['c'] >= '005']
assert(got_items == expected_items)
# Test the BETWEEN operator on a string sort key:
def test_key_conditions_str_between(test_table_ss_with_sorted_partition):
table, p, items = test_table_ss_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['004', '007'], 'ComparisonOperator': 'BETWEEN'}})
expected_items = [item for item in items if item['c'] >= '004' and item['c'] <= '007']
assert(got_items == expected_items)
# Test the BEGINS_WITH operator on a string sort key:
def test_key_conditions_str_begins_with(test_table_ss_with_sorted_partition):
table, p, items = test_table_ss_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['00'], 'ComparisonOperator': 'BEGINS_WITH'}})
expected_items = [item for item in items if item['c'].startswith('00')]
assert(got_items == expected_items)
# This tests BEGINS_WITH with some more elaborate characters
def test_begins_with_more_str(dynamodb, test_table_ss):
p = random_string()
items = [{'p': p, 'c': sort_key, 'str': 'a'} for sort_key in [u'ÿÿÿ', u'cÿbÿ', u'cÿbÿÿabg'] ]
with test_table_ss.batch_writer() as batch:
for item in items:
batch.put_item(item)
got_items = full_query(test_table_ss, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [u'ÿÿ'], 'ComparisonOperator': 'BEGINS_WITH'}})
assert sorted([d['c'] for d in got_items]) == sorted([d['c'] for d in items if d['c'].startswith(u'ÿÿ')])
got_items = full_query(test_table_ss, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [u'cÿbÿ'], 'ComparisonOperator': 'BEGINS_WITH'}})
assert sorted([d['c'] for d in got_items]) == sorted([d['c'] for d in items if d['c'].startswith(u'cÿbÿ')])
# The following tests test the various condition operators on the sort key,
# for a *bytes* sort key:
# Test the EQ operator on a bytes sort key:
def test_key_conditions_bytes_eq(test_table_sb_with_sorted_partition):
table, p, items = test_table_sb_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray('003', 'ascii')], 'ComparisonOperator': 'EQ'}})
expected_items = [item for item in items if item['c'] == bytearray('003', 'ascii')]
assert(got_items == expected_items)
# Test the LT operator on a bytes sort key:
def test_key_conditions_bytes_lt(test_table_sb_with_sorted_partition):
table, p, items = test_table_sb_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray('005', 'ascii')], 'ComparisonOperator': 'LT'}})
expected_items = [item for item in items if item['c'] < bytearray('005', 'ascii')]
assert(got_items == expected_items)
# Test the LE operator on a bytes sort key:
def test_key_conditions_bytes_le(test_table_sb_with_sorted_partition):
table, p, items = test_table_sb_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray('005', 'ascii')], 'ComparisonOperator': 'LE'}})
expected_items = [item for item in items if item['c'] <= bytearray('005', 'ascii')]
assert(got_items == expected_items)
# Test the GT operator on a bytes sort key:
def test_key_conditions_bytes_gt(test_table_sb_with_sorted_partition):
table, p, items = test_table_sb_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray('005', 'ascii')], 'ComparisonOperator': 'GT'}})
expected_items = [item for item in items if item['c'] > bytearray('005', 'ascii')]
assert(got_items == expected_items)
# Test the GE operator on a bytes sort key:
def test_key_conditions_bytes_ge(test_table_sb_with_sorted_partition):
table, p, items = test_table_sb_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray('005', 'ascii')], 'ComparisonOperator': 'GE'}})
expected_items = [item for item in items if item['c'] >= bytearray('005', 'ascii')]
assert(got_items == expected_items)
# Test the BETWEEN operator on a bytes sort key:
def test_key_conditions_bytes_between(test_table_sb_with_sorted_partition):
table, p, items = test_table_sb_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray('004', 'ascii'), bytearray('007', 'ascii')], 'ComparisonOperator': 'BETWEEN'}})
expected_items = [item for item in items if item['c'] >= bytearray('004', 'ascii') and item['c'] <= bytearray('007', 'ascii')]
assert(got_items == expected_items)
# Test the BEGINS_WITH operator on a bytes sort key:
def test_key_conditions_bytes_begins_with(test_table_sb_with_sorted_partition):
table, p, items = test_table_sb_with_sorted_partition
got_items = full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray('00', 'ascii')], 'ComparisonOperator': 'BEGINS_WITH'}})
expected_items = [item for item in items if item['c'].startswith(bytearray('00', 'ascii'))]
assert(got_items == expected_items)
# Test the special case of the 0xFF character for which we have special handling
def test_key_conditions_bytes_begins_with_ff(dynamodb, test_table_sb):
p = random_string()
items = [{'p': p, 'c': sort_key, 'str': 'a'} for sort_key in [bytearray([1, 2,3]), bytearray([255, 3, 4]), bytearray([255, 255, 255])] ]
with test_table_sb.batch_writer() as batch:
for item in items:
batch.put_item(item)
got_items = full_query(test_table_sb, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray([255])], 'ComparisonOperator': 'BEGINS_WITH'}})
expected_items = [item for item in items if item['c'].startswith(bytearray([255]))]
assert(got_items == expected_items)
# Other ComparisonOperator values besides what we tested above may be supported by
# filters, but *not* by KeyConditions, not even on the sort keys:
def test_key_conditions_sort_unsupported(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
# The operators 'NULL', 'NOT_NULL', 'IN', 'CONTAINS', 'NOT_CONTAINS', 'NE'
# exist for ComparisonOperator and are allowed in filters, but not allowed
# in key conditions:
for op in ['IN', 'CONTAINS', 'NOT_CONTAINS', 'NE']:
with pytest.raises(ClientError, match='ValidationException'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [3], 'ComparisonOperator': op}})
for op in ['NULL', 'NOT_NULL']:
with pytest.raises(ClientError, match='ValidationException'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [], 'ComparisonOperator': op}})
# An unknown operator, e.g., "DOG", is also not allowed.
with pytest.raises(ClientError, match='ValidationException.*DOG'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [p], 'ComparisonOperator': 'DOG'}})
# We cannot have a key condition on a non-key column (not instead of a
# condition on the sort key, and not in addition to it).
def test_key_conditions_non_key(test_table_sn_with_sorted_partition):
table, p, items = test_table_sn_with_sorted_partition
with pytest.raises(ClientError, match='ValidationException'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'a' : {'AttributeValueList': [5], 'ComparisonOperator': 'EQ'}})
with pytest.raises(ClientError, match='ValidationException'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [3], 'ComparisonOperator': 'EQ'},
'a' : {'AttributeValueList': [5], 'ComparisonOperator': 'EQ'}})
# Test for trying to use a KeyCondition with an operand type which doesn't
# match the key type:
def test_key_conditions_wrong_type(test_table_ss_with_sorted_partition):
table, p, items = test_table_ss_with_sorted_partition
with pytest.raises(ClientError, match='ValidationException.* type'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [3], 'ComparisonOperator': 'EQ'}})
with pytest.raises(ClientError, match='ValidationException.* type'):
full_query(table, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [3], 'ComparisonOperator': 'EQ'}})
# Query and KeyConditions work also on a table with just a partition
# key and no sort key, although obviously it isn't very useful (for such
# tables, Query is just an elaborate way to do a GetItem).
def test_key_conditions_hash_only_s(test_table_s):
p = random_string()
item = {'p': p, 'val': 'hello'}
test_table_s.put_item(Item=item)
got_items = full_query(test_table_s, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'}})
assert(got_items == [item])
def test_key_conditions_hash_only_b(test_table_b):
p = random_bytes()
item = {'p': p, 'val': 'hello'}
test_table_b.put_item(Item=item)
got_items = full_query(test_table_b, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'}})
assert(got_items == [item])
# TODO: add a test_table_n fixture, and test this case too.
# Demonstrate that issue #6573 was not a bug for KeyConditions: binary
# strings are ordered as unsigned bytes, i.e., byte 128 comes after 127,
# not as signed bytes.
# Test the five ordering operators: LT, LE, GT, GE, BETWEEN.
def test_key_conditions_unsigned_bytes(test_table_sb):
p = random_string()
items = [{'p': p, 'c': bytearray([i])} for i in range(126,129)]
with test_table_sb.batch_writer() as batch:
for item in items:
batch.put_item(item)
got_items = full_query(test_table_sb, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray([127])], 'ComparisonOperator': 'LT'}})
expected_items = [item for item in items if item['c'] < bytearray([127])]
assert(got_items == expected_items)
got_items = full_query(test_table_sb, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray([127])], 'ComparisonOperator': 'LE'}})
expected_items = [item for item in items if item['c'] <= bytearray([127])]
assert(got_items == expected_items)
got_items = full_query(test_table_sb, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray([127])], 'ComparisonOperator': 'GT'}})
expected_items = [item for item in items if item['c'] > bytearray([127])]
assert(got_items == expected_items)
got_items = full_query(test_table_sb, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray([127])], 'ComparisonOperator': 'GE'}})
expected_items = [item for item in items if item['c'] >= bytearray([127])]
assert(got_items == expected_items)
got_items = full_query(test_table_sb, KeyConditions={
'p' : {'AttributeValueList': [p], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': [bytearray([127]), bytearray([128])], 'ComparisonOperator': 'BETWEEN'}})
expected_items = [item for item in items if item['c'] >= bytearray([127]) and item['c'] <= bytearray([128])]
print(expected_items)
assert(got_items == expected_items)
# The following is an older test we had, and is probably no longer needed.
# It tests one limited use case for KeyConditions. It uses filled_test_table
# (the one we also use in test_scan.py) instead of the fixtures defined in this
# file. It also uses Boto3's paginator instead of our full_query utility.
def test_query_basic_restrictions(dynamodb, filled_test_table):
test_table, items = filled_test_table
paginator = dynamodb.meta.client.get_paginator('query')
# EQ
got_items = []
for page in paginator.paginate(TableName=test_table.name, KeyConditions={
'p' : {'AttributeValueList': ['long'], 'ComparisonOperator': 'EQ'}
}):
got_items += page['Items']
print(got_items)
assert multiset([item for item in items if item['p'] == 'long']) == multiset(got_items)
# LT
got_items = []
for page in paginator.paginate(TableName=test_table.name, KeyConditions={
'p' : {'AttributeValueList': ['long'], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['12'], 'ComparisonOperator': 'LT'}
}):
got_items += page['Items']
print(got_items)
assert multiset([item for item in items if item['p'] == 'long' and item['c'] < '12']) == multiset(got_items)
# LE
got_items = []
for page in paginator.paginate(TableName=test_table.name, KeyConditions={
'p' : {'AttributeValueList': ['long'], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['14'], 'ComparisonOperator': 'LE'}
}):
got_items += page['Items']
print(got_items)
assert multiset([item for item in items if item['p'] == 'long' and item['c'] <= '14']) == multiset(got_items)
# GT
got_items = []
for page in paginator.paginate(TableName=test_table.name, KeyConditions={
'p' : {'AttributeValueList': ['long'], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['15'], 'ComparisonOperator': 'GT'}
}):
got_items += page['Items']
print(got_items)
assert multiset([item for item in items if item['p'] == 'long' and item['c'] > '15']) == multiset(got_items)
# GE
got_items = []
for page in paginator.paginate(TableName=test_table.name, KeyConditions={
'p' : {'AttributeValueList': ['long'], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['14'], 'ComparisonOperator': 'GE'}
}):
got_items += page['Items']
print(got_items)
assert multiset([item for item in items if item['p'] == 'long' and item['c'] >= '14']) == multiset(got_items)
# BETWEEN
got_items = []
for page in paginator.paginate(TableName=test_table.name, KeyConditions={
'p' : {'AttributeValueList': ['long'], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['155', '164'], 'ComparisonOperator': 'BETWEEN'}
}):
got_items += page['Items']
print(got_items)
assert multiset([item for item in items if item['p'] == 'long' and item['c'] >= '155' and item['c'] <= '164']) == multiset(got_items)
# BEGINS_WITH
got_items = []
for page in paginator.paginate(TableName=test_table.name, KeyConditions={
'p' : {'AttributeValueList': ['long'], 'ComparisonOperator': 'EQ'},
'c' : {'AttributeValueList': ['11'], 'ComparisonOperator': 'BEGINS_WITH'}
}):
print([item for item in items if item['p'] == 'long' and item['c'].startswith('11')])
got_items += page['Items']
print(got_items)
assert multiset([item for item in items if item['p'] == 'long' and item['c'].startswith('11')]) == multiset(got_items)
| agpl-3.0 |
harrowio/harrow | api/src/github.com/harrowio/harrow/domain/capability_list.go | 1682 | package domain
import "fmt"
// capabilityList is a helper for constructing lists of capabilities.
type capabilityList []string
func newCapabilityList() *capabilityList {
capabilities := capabilityList([]string{})
return &capabilities
}
func (l *capabilityList) writesFor(thing string) *capabilityList {
*l = append(*l,
"create-"+thing,
"update-"+thing,
"archive-"+thing,
)
return l
}
func (l *capabilityList) reads(things ...string) *capabilityList {
for _, thing := range things {
*l = append(*l, "read-"+thing)
}
return l
}
func (l *capabilityList) creates(things ...string) *capabilityList {
for _, thing := range things {
*l = append(*l, "create-"+thing)
}
return l
}
func (l *capabilityList) updates(things ...string) *capabilityList {
for _, thing := range things {
*l = append(*l, "update-"+thing)
}
return l
}
func (l *capabilityList) archives(things ...string) *capabilityList {
for _, thing := range things {
*l = append(*l, "archive-"+thing)
}
return l
}
func (l *capabilityList) does(action string, things ...string) *capabilityList {
for _, thing := range things {
*l = append(*l, fmt.Sprintf("%s-%s", action, thing))
}
return l
}
func (l *capabilityList) add(capabilities []string) *capabilityList {
set := map[string]bool{}
for _, cap := range *l {
set[cap] = true
}
for _, cap := range capabilities {
set[cap] = true
}
merged := make([]string, 0, len(set))
for cap := range set {
merged = append(merged, cap)
}
result := capabilityList(merged)
return &result
}
func (l *capabilityList) strings() []string {
return *l
}
func (l *capabilityList) Capabilities() []string {
return l.strings()
}
| agpl-3.0 |