repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Hilfe/decidim | decidim-core/lib/decidim/has_scope.rb | 635 | # frozen_string_literal: true
require "active_support/concern"
module Decidim
# A concern with the features needed when you want a model to have a scope.
module HasScope
extend ActiveSupport::Concern
included do
belongs_to :scope,
foreign_key: "decidim_scope_id",
class_name: "Decidim::Scope",
optional: true
validate :scope_belongs_to_organization
private
def scope_belongs_to_organization
return if !scope || !feature
errors.add(:scope, :invalid) unless feature.scopes.where(id: scope.id).exists?
end
end
end
end
| agpl-3.0 |
epu-ntua/FITMAN-SeMa | coma-engine/src/main/java/de/wdilab/coma/insert/relationships/RDFAlignmentParser.java | 26954 | /*
* COMA 3.0 Community Edition
*
* 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 de.wdilab.coma.insert.relationships;
import java.util.ArrayList;
import java.util.Enumeration;
import java.net.URI;
import org.semanticweb.owl.align.Alignment;
import org.semanticweb.owl.align.AlignmentException;
import org.semanticweb.owl.align.Cell;
import de.wdilab.coma.center.Manager;
import de.wdilab.coma.insert.InsertParser;
import de.wdilab.coma.repository.DataAccess;
import de.wdilab.coma.repository.DataImport;
import de.wdilab.coma.repository.Repository;
import de.wdilab.coma.structure.Element;
import de.wdilab.coma.structure.Graph;
import de.wdilab.coma.structure.MatchResult;
import de.wdilab.coma.structure.MatchResultArray;
import de.wdilab.coma.structure.Source;
import de.wdilab.coma.structure.SourceRelationship;
import fr.inrialpes.exmo.align.parser.AlignmentParser;
/**
* This class imports a rdf alignment that contains the location of the
* source and target model and for * for each correspondence
* between them unique identifier of the two elements.
*
* @author Hong Hai Do, Sabine Massmann
*/
public class RDFAlignmentParser {
// public static int onlySourceInstances = 0;
// public static int onlyTargetInstances = 0;
// public static int bothInstances = 0, bothInstancesIntended=0;
// public static int noInstances = 0;
Manager manager = null;
DataImport importer=null;
// if false return match result otherwise insert directly into database
boolean dbInsert = false;
int mappingId = -1;
public RDFAlignmentParser(Manager manager, boolean dbInsert){
this.manager=manager;
if (manager!=null){
importer = manager.getImporter();
}
this.dbInsert = dbInsert;
}
public MatchResult loadOWLAlignmentFile(String alignFile) {
return loadOWLAlignmentFile(alignFile,(String) null, (String)null, (String)null);
}
public MatchResult loadOWLAlignmentFile(String alignFile, String resultName, String srcURI, String trgURI){
// ArrayList<ArrayList<String>> pairs1 = new ArrayList<ArrayList<String>>();
Alignment alignment =null;
try {
AlignmentParser alignParser = new AlignmentParser(0);
if (!alignFile.startsWith("file:") && alignFile.indexOf(":")==1){
alignFile = "file:/"+alignFile;
}
alignFile = alignFile.replace("\\", "/");
// alignFile = alignFile.replaceFirst("file:/", "").replace(" ", "%20");
alignment = alignParser.parse(alignFile.replace(" ", "%20"));
System.gc();
} catch (Exception e) {
System.out.println("loadOWLAlignmentFile(): Error parsing file "
+ e.getMessage());
}
if (alignment == null) {
System.out.println("loadOWLAlignmentFile(): Error parsing file " + alignFile);
return null;
}
int srcId = Source.UNDEF, trgId = Source.UNDEF;
if (srcURI!=null){
srcId = getSourceWithProvider(srcURI);
}
if (trgURI!=null){
trgId = getSourceWithProvider(trgURI);
}
try {
if (srcURI==null){
URI uri = alignment.getOntology1URI();
if (uri!=null){
srcURI = uri.toString();
} else {
System.out.println("loadOWLAlignmentFile(): Error no source uri " );
return null;
}
srcId = getSourceWithURI(srcURI);
}
if (trgURI==null){
URI uri = alignment.getOntology2URI();
if (uri!=null){
trgURI = uri.toString();
} else {
System.out.println("loadOWLAlignmentFile(): Error no target uri " );
return null;
}
trgId = getSourceWithURI(trgURI);
}
} catch (AlignmentException e1) {
// e1.printStackTrace();
System.out.println("loadOWLAlignmentFile(): Error getting URI for ontology " + e1.getCause());
}
if (srcId==Source.UNDEF || trgId==Source.UNDEF){
return null;
}
if (dbInsert){
return loadOWLAlignmentDBInsert(resultName, alignFile, srcId, trgId, alignment);
}
return loadOWLAlignmentMemory(resultName, alignFile, srcId, trgId, alignment);
}
int getSourceWithURI(String uri){
if (uri == null) {
return Source.UNDEF;
}
DataAccess accessor = manager.getAccessor();
ArrayList<Integer> sources = accessor.getSourceIdsWithUrl(uri.toString());
if (sources==null){
System.out.println("loadOWLAlignmentFile(): Error getting source with the uri " + uri);
return Source.UNDEF;
} else if (sources.size()==1){
return sources.get(0);
} else {
System.out.println("loadOWLAlignmentFile(): Error getting source with the uri " + uri);
}
return Source.UNDEF;
}
MatchResult loadOWLAlignmentDBInsert(String resultName, String alignFile, int srcId, int trgId, Alignment alignment){
if (resultName==null){
resultName = InsertParser.createSourceName(alignFile);
}
String date = new java.util.Date().toString();
mappingId = importer.insertSourceRel(srcId,trgId,
SourceRelationship.REL_MATCHRESULT, resultName, null,
alignFile, Graph.PREP_DEFAULT_ONTOLOGY, date);
importer.updateSourceRel(mappingId, Repository.STATUS_IMPORT_STARTED);
Enumeration<Cell> cells = alignment.getElements();
int count =0;
try {
while (cells.hasMoreElements()) {
Cell cell = cells.nextElement();
String srcAcc = cell.getObject1AsURI().toString();
String trgAcc = cell.getObject2AsURI().toString();
float simValue = (float) cell.getStrength();
String relation = cell.getRelation().getRelation();
// dbInsert - srcAcc and trgAcc are the accessions
int oSrcId = importer.getObjectIdNotKind(srcId, srcAcc, Element.KIND_ELEMPATH);
if (oSrcId<0){
oSrcId = importer.getObjectIdEndingNotKind(srcId, srcAcc, Element.KIND_ELEMPATH);
}
if (oSrcId<0){
// not valid id
continue;
}
int oTrgId = importer.getObjectIdNotKind(trgId, trgAcc, Element.KIND_ELEMPATH);
if (oTrgId<0){
oTrgId = importer.getObjectIdEndingNotKind(trgId, trgAcc, Element.KIND_ELEMPATH);
}
if (oTrgId<0){
// not valid id
continue;
}
if (simValue==0){
// bugfix: zero doesn't make sense - treated like no correspondence
simValue=(float) 1;
}
importer.insertObjectRel(mappingId, oSrcId, oTrgId, simValue, relation);
count++;
}
} catch (AlignmentException e) {
System.err.println("RDFAlignmentParser.loadOWLAlignmentDBInsert AlignmentException "
+ e.getLocalizedMessage());
}
System.out.println("cells\t" + count);
importer.updateSourceRel(mappingId, Repository.STATUS_IMPORT_DONE);
// return null because direct import into database
return null;
}
public int getMappingId(){
return mappingId;
}
int getSourceWithProvider(String uri){
if (uri == null) {
return Source.UNDEF;
}
DataAccess accessor = manager.getAccessor();
ArrayList<Integer> sources = accessor.getSourceIdsWithProvider(uri.toString());
if (sources==null){
System.out.println("loadOWLAlignmentFile(): Error getting source with the uri " + uri);
return Source.UNDEF;
} else if (sources.size()==1){
return sources.get(0);
} else {
System.out.println("loadOWLAlignmentFile(): Error getting source with the uri " + uri);
}
return Source.UNDEF;
}
MatchResult loadOWLAlignmentMemory(String resultName, String alignFile, int srcId, int trgId, Alignment alignment){
Graph srcGraph=manager.loadGraph(srcId);
Graph trgGraph=manager.loadGraph(trgId);
return loadOWLAlignmentMemory(resultName, alignFile, srcGraph, trgGraph, alignment);
}
MatchResult loadOWLAlignmentFile(String resultName, String alignFile, Graph srcGraph, Graph trgGraph){
Alignment alignment =null;
try {
AlignmentParser alignParser = null;
alignParser = new AlignmentParser(0);
if (!alignFile.startsWith("file:") && alignFile.indexOf(":")==1){
alignFile = "file:/"+alignFile;
}
alignFile = alignFile.replace("\\", "/");
// alignFile = alignFile.replaceFirst("file:/", "").replace(" ", "%20");
alignment = alignParser.parse(alignFile.replace(" ", "%20"));
System.gc();
} catch (Exception e) {
System.out.println("loadOWLAlignmentFile(): Error parsing file "
+ e.getMessage());
}
if (alignment == null) {
System.out.println("loadOWLAlignmentFile(): Error parsing file " + alignFile);
return null;
}
if (dbInsert){
return loadOWLAlignmentDBInsert(resultName, alignFile, srcGraph.getSource().getId(), trgGraph.getSource().getId(), alignment);
}
return loadOWLAlignmentMemory(resultName, alignFile, srcGraph, trgGraph, alignment);
}
MatchResult loadOWLAlignmentMemory(String resultName, String alignFile, Graph srcGraph, Graph trgGraph, Alignment alignment){
if (resultName==null){
resultName = InsertParser.createSourceName(alignFile);
}
// srcGraph = srcGraph.getGraph(graphState);
// trgGraph = trgGraph.getGraph(graphState);
MatchResultArray result = new MatchResultArray(srcGraph.getAllNodes(), trgGraph.getAllNodes());
result.setName(resultName);
Enumeration<Cell> cells = alignment.getElements();
int count =0;
try {
while (cells.hasMoreElements()) {
Cell cell = cells.nextElement();
String srcAcc = cell.getObject1AsURI().toString();
String trgAcc = cell.getObject2AsURI().toString();
float sim = (float) cell.getStrength();
// String relation = cell.getRelation().getRelation(); // not used
// srcAcc and trgAcc are the accessions
ArrayList srcObjects = srcGraph.getElementsWithAccession(srcAcc);
// expecting exactly one element
if (srcObjects==null){
// not valid accession
System.out.println("loadOWLAlignmentMemory() Error not found accessioon in source: " + srcAcc);
continue;
}
ArrayList trgObjects = trgGraph.getElementsWithAccession(trgAcc);
if (trgObjects==null){
// not valid accession
System.out.println("loadOWLAlignmentMemory() Error not found accessioon in target: " + trgAcc);
continue;
}
if (srcObjects.size()>1){
System.out.println("loadOWLAlignmentMemory() Error found several elements with the accessioon in source: " + srcAcc);
}
if (trgObjects.size()>1){
System.out.println("loadOWLAlignmentMemory() Error found several elements with the accessioon in target: " + trgAcc);
}
if (sim==0){
// bugfix: zero doesn't make sense - treated like no correspondence
sim=(float) 1;
}
for (Object srcObject : srcObjects) {
for (Object trgObject : trgObjects) {
if (result.getSimilarity(srcObject, trgObject)>0){
System.out.println("Duplicate information");
} else {
result.append(srcObject, trgObject, sim);
count++;
}
}
}
if (count%100==0){
System.out.println("count: " + count);
if (result!=null){
System.out.println(count+"\t" + result.getMatchCount());
}
}
}
result.getMatchCount();
System.out.println(count);
} catch (AlignmentException e) {
System.err.println("RDFAlignmentParser.loadOWLAlignmentMemory AlignmentException "
+ e.getLocalizedMessage());
}
System.out.println("cells\t" + count);
// return result because no direct import into database
return result;
}
// public MatchResult loadOWLAlignmentFile(String alignFile,String resultName,
// String endString1, String endString2) {
// return loadOWLAlignmentFile(alignFile, resultName, endString1, endString2,
//// SchemaGraph.GRAPH_STATE_LOADED);
// Graph.PREP_DEFAULT_ONTOLOGY);
//// SchemaGraph.GRAPH_STATE_SIMPLIFIED);
// }
// public MatchResult loadOWLAlignmentFile(String alignFile, String resultName,
// String endString1, String endString2, int graphState) {
// TODO directly insert result into database if true
// Alignment alignment =null;
// try {
// AlignmentParser alignParser = null;
// alignParser = new AlignmentParser(0);
// Hashtable hash = new Hashtable();
// System.gc();
//// alignFile = alignFile.replaceFirst("file:/", "").replace(" ", "%20");
//// alignment = alignParser.parse(alignFile.replace(" ", "%20"), hash);
// alignment = alignParser.parse(alignFile.replace(" ", "%20"), hash);
// } catch (Exception e) {
// System.out.println("loadOWLAlignmentFile(): Error parsing file "
// + e.getMessage());
// }
// if (alignment == null) {
// System.out.println("loadOWLAlignmentFile(): Error parsing file "
// + alignFile);
// return null;
// }
//
// DataAccess accessor = manager.getAccessor();
//
// OWLOntology ont1 = (OWLOntology) alignment.getOntology1();
// OWLOntology ont2 = (OWLOntology) alignment.getOntology2();
// String oUri1 = null, oUri2 = null;
// try {
// oUri1 = ont1.getPhysicalURI().toString();
// oUri2 = ont2.getPhysicalURI().toString();
// } catch (Exception e) {
// System.out.println("loadOWLAlignmentFile(): Error getting URI "
// + e.getMessage());
// }
// if (oUri1 == null) {
// System.out
// .println("loadOWLAlignmentFile(): Error getting URI from source ontology "
// + ont1);
// return null;
// } else if (oUri2 == null) {
// System.out
// .println("loadOWLAlignmentFile(): Error getting URI from target ontology"
// + ont2);
// return null;
// }
//
// // System.out.println("URI1: " + oUri1);
// // System.out.println("URI2: " + oUri2);
// Source source1 = null, source2 = null;
// ArrayList<Source> sources = null;
// if (endString1 != null && endString1.length() > 0)
// sources = accessor.getSourcesWithUrl(endString1);
// else
// sources = accessor.getSourcesWithUrl(oUri1);
// if (!(sources == null || sources.isEmpty()))
// source1 = sources.get(0);
// if (source1==null){
// try {
// OWLClassImpl classI = (OWLClassImpl) ont1.getClasses().iterator().next();
// oUri1 = classI.getURI().toString();
// if (oUri1.contains("#")){
// oUri1 = oUri1.substring(0, oUri1.indexOf("#"));
// }
// } catch (Exception e) {
// System.out.println("loadOWLAlignmentFile(): Error getting URI "
// + e.getMessage());
// }
// if (endString1 != null && endString1.length() > 0)
// sources = accessor.getSourcesWithUrl(endString1);
// else
// sources = accessor.getSourcesWithUrl(oUri1);
// if (sources != null && !sources.isEmpty())
// source1 = sources.get(0);
// }
// if (endString2 != null && endString2.length() > 0)
// sources = accessor.getSourcesWithUrl(endString2);
// else
// sources = accessor.getSourcesWithUrl(oUri2);
// if (sources != null && !sources.isEmpty())
// source2 = sources.get(0);
// if (source2==null){
// try {
// OWLClassImpl classI = (OWLClassImpl) ont2.getClasses().iterator().next();
// oUri2 = classI.getURI().toString();
// if (oUri2.contains("#")){
// oUri2 = oUri2.substring(0, oUri2.indexOf("#"));
// }
// } catch (Exception e) {
// System.out.println("loadOWLAlignmentFile(): Error getting URI "
// + e.getMessage());
// }
// if (endString2 != null && endString2.length() > 0)
// sources = accessor.getSourcesWithUrl(endString2);
// else
// sources = accessor.getSourcesWithUrl(oUri2);
// if (!(sources == null || sources.isEmpty()))
// source2 = sources.get(0);
// }
//
// if (source1 == null) {
// System.out
// .println("loadOWLAlignmentFile(): No source with such URI "
// + oUri1);
// return null;
// } else if (source2 == null) {
// System.out
// .println("loadOWLAlignmentFile(): No target with such URI "
// + oUri2);
// return null;
// }
// Graph ontGraph1 = manager.loadGraph(source1, true, true, true);
// Graph ontGraph2 = manager.loadGraph(source2, true, true, true);
// // because at the moment - only loaded and resolved are supported
// ontGraph1 = ontGraph1.getGraph(graphState);
// ontGraph2 = ontGraph2.getGraph(graphState);
// DataImport importer = manager.getImporter();
//
// if (resultName==null){
// resultName = InsertParser.createSourceName(alignFile);
// }
// String date = new java.util.Date().toString();
// int mappingId = importer.insertSourceRel(source1.getId(), source2.getId(),
// SourceRelationship.REL_MATCHRESULT, resultName, null,
// alignFile, Graph.PREP_DEFAULT_ONTOLOGY, date);
//
//// if (false) {
//// // for statistics
//// // count overlapping names and datatypes
//// ArrayList simpleTypes1 = ontGraph1.getAllSimpleTypes();
//// ArrayList complexTypes1 = ontGraph1.getAllComplexTypes();
//// ArrayList simpleTypes2 = ontGraph2.getAllSimpleTypes();
//// ArrayList complexTypes2 = ontGraph1.getAllComplexTypes();
////
//// ArrayList<String> names1 = new ArrayList<String>();
//// ArrayList<String> names2 = new ArrayList<String>();
////
//// for (Iterator iter = simpleTypes1.iterator(); iter.hasNext();) {
//// Element element = (Element) iter.next();
//// if (element != null && element.getLabel() != null) {
//// names1.add(element.getLabel());
//// }
//// }
//// for (Iterator iter = complexTypes1.iterator(); iter.hasNext();) {
//// Element element = (Element) iter.next();
//// if (element != null && element.getLabel() != null) {
//// names1.add(element.getLabel());
//// }
//// }
////
//// for (Iterator iter = simpleTypes2.iterator(); iter.hasNext();) {
//// Element element = (Element) iter.next();
//// if (element != null && element.getLabel() != null) {
//// names2.add(element.getLabel());
//// }
//// }
//// for (Iterator iter = complexTypes2.iterator(); iter.hasNext();) {
//// Element element = (Element) iter.next();
//// if (element != null && element.getLabel() != null) {
//// names2.add(element.getLabel());
//// }
//// }
//// ArrayList<String> help = (ArrayList<String>) names1.clone();
//// help.removeAll(names2);
//// int diff = names1.size() - help.size();
//// System.out.println("count overlapping names types2 in types1: "
//// + diff);
////
//// help = (ArrayList<String>) names2.clone();
//// help.removeAll(names1);
//// diff = names2.size() - help.size();
//// System.out.println("count overlapping names types1 in types2: "
//// + diff);
////
//// Iterator iterator = ontGraph1.getElementIterator();
//// names1 = new ArrayList<String>();
//// while (iterator.hasNext()) {
//// Element element = (Element) iterator.next();
//// names1.add(element.getLabel());
//// }
//// iterator = ontGraph2.getElementIterator();
//// names2 = new ArrayList<String>();
//// while (iterator.hasNext()) {
//// Element element = (Element) iterator.next();
//// names2.add(element.getLabel());
//// }
//// help = (ArrayList<String>) names1.clone();
//// help.removeAll(names2);
//// diff = names1.size() - help.size();
//// System.out.println("count overlapping names names2 in names1: "
//// + diff);
////
//// help = (ArrayList<String>) names2.clone();
//// help.removeAll(names1);
//// diff = names2.size() - help.size();
//// System.out.println("count overlapping names names1 in names2: "
//// + diff);
//// }
//// ontGraph1 = ontGraph1.getGraph(SchemaGraph.GRAPH_STATE_SIMPLIFIED);
//// ontGraph2 = ontGraph2.getGraph(SchemaGraph.GRAPH_STATE_SIMPLIFIED);
//// if (ontGraph1==null || ontGraph2==null){
//// System.out.println("loadOWLAlignmentFile(): Transformation to SIMPLIFIED failed, therefore use REDUCED");
//// ontGraph1 = ontGraph1.getGraph(SchemaGraph.GRAPH_STATE_REDUCED);
//// ontGraph2 = ontGraph2.getGraph(SchemaGraph.GRAPH_STATE_REDUCED);
//// }
//
//// System.out.println(ontGraph2.getSource().getName());
//// ontGraph2.printGraphInfo();
// // ontGraph2.printSchemaInfo();
// if (ontGraph1 == null) {
// System.out
// .println("loadOWLAlignmentFile(): No graph loaded for source "
// + source1);
// return null;
// } else if (ontGraph2 == null) {
// System.out
// .println("loadOWLAlignmentFile(): No graph loaded for target "
// + source2);
// return null;
// }
//// countExpectedElementsWithInstances(alignment, ontGraph1, ontGraph2);
// Enumeration<Cell> cells = alignment.getElements();
// MatchResult matchResult = null;
// if (!dbInsert) {
// matchResult = new MatchResultArray();
// }
// int count =0;
// while (cells.hasMoreElements()) {
// Cell cell = cells.nextElement();
// count++;
// OWLNamedObject o1 = (OWLNamedObject) cell.getObject1();
// OWLNamedObject o2 = (OWLNamedObject) cell.getObject2();
// // String sem = cell.getSemantics();
// double sim = cell.getStrength();
//
// URI uri1 = null, uri2 = null;
// try {
// uri1 = o1.getURI();
// uri2 = o2.getURI();
// } catch (Exception e) {
// System.out
// .println("loadOWLAlignmentFile(): Error getting object URI "
// + e.getMessage());
// }
// if (uri1 == null || uri2 == null) {
// System.out
// .println("loadOWLAlignmentFile(): Error getting URI from objects");
// continue;
// }
//
//// String namespace1 = OWLParser.getNamespace(uri1.toString());
//// String name1 = OWLParser.getName(uri1);
//// String namespace2 = OWLParser.getNamespace(uri2.toString());
//// String name2 = OWLParser.getName(uri2);
//
//// ArrayList vertices1 = ontGraph1.getVerticesWithQualifiedName(name1, namespace1);
//// ArrayList vertices1 = ontGraph1.getElementsWithAccession(namespace1+"#"+name1);
// ArrayList vertices1 = ontGraph1.getElementsWithAccession(uri1.toString());
//// ArrayList vertices2 = ontGraph2.getVerticesWithQualifiedName(name2, namespace2);
//// ArrayList vertices2 = ontGraph2.getElementsWithAccession(namespace2+"#"+name2);
// ArrayList vertices2 = ontGraph2.getElementsWithAccession(uri2.toString());
// if (vertices1 == null) {
// System.out
// .println("loadOWLAlignmentFile(): No source nodes with URI "
// + uri1);
// continue;
// } else if (vertices2 == null) {
// System.out
// .println("loadOWLAlignmentFile(): No target nodes with URI "
// + uri2);
// continue;
// }
//
// for (int i = 0; i < vertices1.size(); i++) {
// Element vertex1 = (Element) vertices1.get(i);
// for (int j = 0; j < vertices2.size(); j++) {
// Element vertex2 = (Element) vertices2.get(j);
// // int before = matchResult.getMatchCount();
////
// if (dbInsert) {
// importer.insertObjectRel(mappingId, vertex1.getId(),
// vertex2.getId(), (float) sim,null);
// } else {
// matchResult.append(vertex1, vertex2, (float) sim);
// }
// // int after = matchResult.getMatchCount();
// // if (before==after){
// // System.out.print("\t MatchCount " +
// // matchResult.getMatchCount());
// // System.out.println(vertex1 + " - " + vertex2 + " : " +
// // sim);
// // matchResult.append(vertex1, vertex2, (float)1.0);
// // }
// }
// }
// }
// System.out.println("count: " + count);
// System.out.println("LOADED " + alignFile + ": " + alignment.nbCells()
//// + " and " + matchResult.getMatchCount()
// );
// if (dbInsert) {
// importer.updateSourceRel(mappingId, Repository.STATUS_IMPORT_DONE);
// return null;
// }
// matchResult.setGraphs(ontGraph1, ontGraph2);
// return matchResult;
// }
//
// static public void loadOWLAlignmentFile(String alignFile) {
// Alignment alignment =null;
// try {
// AlignmentParser alignParser = null;
// alignParser = new AlignmentParser(0);
// Hashtable hash = new Hashtable();
// System.gc();
//// alignFile = alignFile.replaceFirst("file:/", "").replace(" ", "%20");
//// alignment = alignParser.parse(alignFile.replace(" ", "%20"), hash);
// alignment = alignParser.parse(alignFile.replace(" ", "%20"), hash);
// System.gc();
// } catch (Exception e) {
// System.out.println("loadOWLAlignmentFile(): Error parsing file "
// + e.getMessage());
// }
// if (alignment == null) {
// System.out.println("loadOWLAlignmentFile(): Error parsing file "
// + alignFile);
// } else {
// Enumeration<Cell> cells = alignment.getElements();
// int count =0;
// while (cells.hasMoreElements()) {
// Cell cell = cells.nextElement();
// count++;
// }
// System.out.println("cells\t" + count);
// }
//
// }
//
//
//// private void countExpectedElementsWithInstances(Alignment alignment,
//// Graph sourceGraph, Graph targetGraph) {
//// Enumeration<Cell> cells = (Enumeration<Cell>) alignment.getElements();
//// Set<Element> sourceVertices = sourceGraph.vertexSet();
//// Set<Element> targetVertices = targetGraph.vertexSet();
//// bothInstancesIntended = 0;
//// cellLoop: while (cells.hasMoreElements()) {
//// Cell cell = cells.nextElement();
//// OWLNamedObjectImpl namedObject1 = (OWLNamedObjectImpl) cell
//// .getObject1();
//// OWLNamedObjectImpl namedObject2 = (OWLNamedObjectImpl) cell
//// .getObject2();
////
//// for (Element sourceElement : sourceVertices) {
//// if (sourceElement.getNamespace() == null)
//// continue;
//// String sourceUri = sourceElement.getNamespace();
//// if (!(sourceElement.getNamespace().equals(sourceElement
//// .getAccession())))
//// sourceUri += "#" + sourceElement.getAccession();
////
//// if (sourceUri.equals(namedObject1.getURI().toString())) {
//// for (VertexImpl targetVetex : targetVertices) {
//// Element targetElement = (Element) targetVetex
//// .getObject();
//// if (targetElement.getNamespace() == null)
//// continue;
//// String targetUri = targetElement.getNamespace();
//// if (!(targetElement.getNamespace().equals(targetElement
//// .getAccession())))
//// targetUri += "#" + targetElement.getAccession();
////
//// if (targetUri.equals(namedObject2.getURI().toString())) {
//// // Element in refalign
//// if (sourceElement.hasDirectInstancesSimple() || sourceElement.hasDirectInstancesComplex()
//// || sourceElement.getIdentifiers().size() > 0){
//// if (targetElement.hasDirectInstancesSimple() || targetElement.hasDirectInstancesComplex()
//// || targetElement.getIdentifiers()
//// .size() > 0){
//// bothInstances++;
//// bothInstancesIntended++;
//// } else{
//// onlySourceInstances++;
//// }
//// }
//// else if (targetElement.hasDirectInstancesSimple() || targetElement.hasDirectInstancesComplex()
//// || targetElement.getIdentifiers().size() > 0)
//// onlyTargetInstances++;
//// else
//// noInstances++;
//// continue cellLoop;
//// }
//// }
//// }
//// }
//// }
//// }
}
| agpl-3.0 |
SeedScientific/polio | source_data/migrations/0065_auto__del_unique_sourceregion_region_string__add_unique_sourceregion_r.py | 73358 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'SourceRegion', fields ['region_string']
try:
db.delete_unique(u'source_data_sourceregion', ['region_string'])
except Exception:
pass
# Adding unique constraint on 'SourceRegion', fields ['region_string', 'document']
db.create_unique(u'source_data_sourceregion', ['region_string', 'document_id'])
def backwards(self, orm):
# Removing unique constraint on 'SourceRegion', fields ['region_string', 'document']
db.delete_unique(u'source_data_sourceregion', ['region_string', 'document_id'])
# Adding unique constraint on 'SourceRegion', fields ['region_string']
db.create_unique(u'source_data_sourceregion', ['region_string'])
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'datapoints.campaign': {
'Meta': {'ordering': "('-start_date',)", 'unique_together': "(('office', 'start_date'),)", 'object_name': 'Campaign', 'db_table': "'campaign'"},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'end_date': ('django.db.models.fields.DateField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'office': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['datapoints.Office']"}),
'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "'get_full_name'"}),
'start_date': ('django.db.models.fields.DateField', [], {})
},
u'datapoints.indicator': {
'Meta': {'ordering': "('name',)", 'object_name': 'Indicator', 'db_table': "'indicator'"},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_reported': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'short_name': ('django.db.models.fields.CharField', [], {'max_length': '55'}),
'slug': ('autoslug.fields.AutoSlugField', [], {'unique': 'True', 'max_length': '255', 'populate_from': "'name'", 'unique_with': '()'})
},
u'datapoints.office': {
'Meta': {'object_name': 'Office', 'db_table': "'office'"},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '55'})
},
u'datapoints.region': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('source', 'source_guid'),)", 'object_name': 'Region', 'db_table': "'region'"},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_high_risk': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '55'}),
'office': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['datapoints.Office']"}),
'parent_region': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['datapoints.Region']"}),
'region_code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'}),
'region_type': ('django.db.models.fields.CharField', [], {'max_length': '55'}),
'shape_file_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '55', 'populate_from': "'name'"}),
'source': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['datapoints.Source']"}),
'source_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'datapoints.source': {
'Meta': {'object_name': 'Source', 'db_table': "'source'"},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'source_description': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'source_name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '55'})
},
'source_data.activityreport': {
'Meta': {'object_name': 'ActivityReport'},
'activity': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cd_attendance': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cd_hh_pending_issues': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cd_iec': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cd_local_leadership_present': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cd_num_hh_affected': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cd_num_vaccinated': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cd_pro_opv_cd': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cd_resolved': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cm_attendance': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cm_iec': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cm_num_caregiver_issues': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cm_num_husband_issues': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cm_num_positive': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cm_num_vaccinated': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cm_vcm_present': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cm_vcm_sett': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'daterecorded': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'endtime': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_appropriate_location': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_clinician1': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_clinician2': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_crowdcontroller': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_nc_location': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_num_measles': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_num_opv': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_num_patients': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_num_penta': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_opvvaccinator': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_recorder_opv': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_recorder_ri': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_separatetally': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_stockout': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_team_allowances': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_townannouncer': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ipds_community_leader_present': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ipds_issue_reported': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ipds_issue_resolved': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ipds_num_children': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ipds_num_hh': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ipds_other_issue': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ipds_team': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ipds_team_allowances': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'lga': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'names': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_accuracy': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_altitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_latitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_longitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'start_time': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'state': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ward': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'source_data.campaignmap': {
'Meta': {'object_name': 'CampaignMap'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mapped_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'master_campaign': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['datapoints.Campaign']"}),
'source_campaign': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['source_data.SourceCampaign']", 'unique': 'True'})
},
'source_data.clustersupervisor': {
'Meta': {'object_name': 'ClusterSupervisor'},
'coord_rfp_meeting': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'coord_smwg_meetings': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'coord_vcm_meeting': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'daterecorded': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'end_time': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'fund_transparency': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hrop_activities_conducted': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hrop_activities_planned': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hrop_endorsed': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hrop_implementation': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hrop_socialdata': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hrop_special_pop': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hrop_workplan_aligned': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'instruction': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'lga': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'num_lgac': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ri_supervision': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'start_time': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'state': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'supervisee_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'supervision_location_accuracy': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'supervision_location_altitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'supervision_location_latitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'supervision_location_longitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'supervisor_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'supervisor_title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcm_birthtracking': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcm_data': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcm_supervision': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'source_data.document': {
'Meta': {'unique_together': "(('docfile', 'doc_text'),)", 'object_name': 'Document'},
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'doc_text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'docfile': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True'}),
'guid': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_processed': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
u'source_data.etljob': {
'Meta': {'object_name': 'EtlJob'},
'date_attempted': ('django.db.models.fields.DateTimeField', [], {}),
'date_completed': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'error_msg': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'guid': ('django.db.models.fields.CharField', [], {'max_length': '40', 'primary_key': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'success_msg': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'task_name': ('django.db.models.fields.CharField', [], {'max_length': '55'})
},
u'source_data.headeroverride': {
'Meta': {'object_name': 'HeaderOverride'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'header_string': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'source_data.healthcamp': {
'Meta': {'object_name': 'HealthCamp'},
'agencyname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'appropriate_location': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'clinician1': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'clinician2': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'crowdcontroller': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'daterecorded': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'endtime': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'formhub_uuid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_photo': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hc_stockout': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'lga': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'megaphone': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'names': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'nc_location': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'num_measles': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'num_opv': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'num_patients': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'num_penta': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'opvvaccinator': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'recorder_opv': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'recorder_ri': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'region': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'separatetally': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_accuracy': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_altitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_latitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_longitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'start_time': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'townannouncer': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'userid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'ward': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'source_data.indicatormap': {
'Meta': {'object_name': 'IndicatorMap'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mapped_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'master_indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['datapoints.Indicator']"}),
'source_indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['source_data.SourceIndicator']", 'unique': 'True'})
},
'source_data.knowthepeople': {
'Meta': {'object_name': 'KnowThePeople'},
'brothers': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'citiesvisited': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'dob': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'nameofpax': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'prefferedcity': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'sisters': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'state_country': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.paxlistreporttraining': {
'Meta': {'object_name': 'PaxListReportTraining'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'emailaddr': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'nameofparticipant': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'state': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'timestamp': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.phoneinventory': {
'Meta': {'object_name': 'PhoneInventory'},
'asset_number': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'colour_phone': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'lga': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'state': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'telephone_no': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.practicevcmbirthrecord': {
'Meta': {'object_name': 'PracticeVCMBirthRecord'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'dateofreport': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'datereport': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'dob': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'householdnumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'nameofchild': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementcode': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'simserial': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcm0dose': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcmnamecattended': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcmrilink': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.practicevcmsettcoordinates': {
'Meta': {'object_name': 'PracticeVCMSettCoordinates'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'daterecorded': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementcode': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_accuracy': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_altitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_latitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_longitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'simserial': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcmname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcmphone': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.practicevcmsummary': {
'Meta': {'object_name': 'PracticeVCMSummary'},
'census12_59mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'census12_59mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'census2_11mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'census2_11mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'censusnewbornsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'censusnewbornsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'date_implement': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'dateofreport': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_agedoutf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_agedoutm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childdiedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childdiedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childsickf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childsickm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_familymovedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_familymovedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_farmf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_farmm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_hhnotvisitedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_hhnotvisitedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_marketf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_marketm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noconsentf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noconsentm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nofeltneedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nofeltneedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nogovtservicesf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nogovtservicesm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noplusesf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noplusesm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noreasonf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noreasonm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_otherprotectionf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_otherprotectionm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_playgroundf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_playgroundm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poldiffsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poldiffsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliohascuref': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliohascurem': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliouncommonf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliouncommonm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_relbeliefsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_relbeliefsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_schoolf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_schoolm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_securityf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_securitym': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_sideeffectsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_sideeffectsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_soceventf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_soceventm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_toomanyroundsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_toomanyroundsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_unhappywteamf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_unhappywteamm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_afpcase': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_cmamreferral': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_fic': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_mslscase': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_newborn': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_otherdisease': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_pregnantmother': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_rireferral': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_vcmattendedncer': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_zerodose': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'msd_grp_choice': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementcode': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'simserial': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'spec_grp_choice': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax12_59mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax12_59mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax2_11mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax2_11mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vaxnewbornsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vaxnewbornsm': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.processstatus': {
'Meta': {'object_name': 'ProcessStatus'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'status_description': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'status_text': ('django.db.models.fields.CharField', [], {'max_length': '25'})
},
u'source_data.regionmap': {
'Meta': {'object_name': 'RegionMap'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mapped_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'master_region': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['datapoints.Region']"}),
'source_region': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['source_data.SourceRegion']", 'unique': 'True'})
},
u'source_data.sourcecampaign': {
'Meta': {'object_name': 'SourceCampaign'},
'campaign_string': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'document': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['source_data.Document']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'source_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.sourcedatapoint': {
'Meta': {'unique_together': "(('source', 'source_guid', 'indicator_string'),)", 'object_name': 'SourceDataPoint'},
'campaign_string': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'cell_value': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'document': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['source_data.Document']"}),
'error_msg': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'guid': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'indicator_string': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'region_string': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'row_number': ('django.db.models.fields.IntegerField', [], {}),
'source': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['datapoints.Source']"}),
'source_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"})
},
u'source_data.sourceindicator': {
'Meta': {'object_name': 'SourceIndicator'},
'document': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['source_data.Document']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'indicator_string': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'source_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'source_data.sourceregion': {
'Meta': {'unique_together': "(('region_string', 'document'),)", 'object_name': 'SourceRegion'},
'country': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'document': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['source_data.Document']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lat': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'lon': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'parent_code': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'parent_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'region_code': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'region_string': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'region_type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'source_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.vcmbirthrecord': {
'Meta': {'object_name': 'VCMBirthRecord'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'dateofreport': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'datereport': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'dob': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'householdnumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'nameofchild': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementcode': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'simserial': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcm0dose': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcmnamecattended': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcmrilink': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.vcmsettlement': {
'Meta': {'object_name': 'VCMSettlement'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'daterecorded': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementcode': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_accuracy': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_altitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_latitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementgps_longitude': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'simserial': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcmname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vcmphone': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.vcmsummary': {
'Meta': {'object_name': 'VCMSummary'},
'census12_59mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'census12_59mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'census2_11mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'census2_11mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'censusnewbornsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'censusnewbornsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'date_implement': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'dateofreport': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_agedoutf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_agedoutm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childdiedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childdiedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childsickf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childsickm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_familymovedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_familymovedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_farmf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_farmm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_hhnotvisitedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_hhnotvisitedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_marketf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_marketm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noconsentf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noconsentm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nofeltneedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nofeltneedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nogovtservicesf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nogovtservicesm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noplusesf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noplusesm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noreasonf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noreasonm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_otherprotectionf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_otherprotectionm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_playgroundf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_playgroundm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poldiffsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poldiffsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliohascuref': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliohascurem': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliouncommonf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliouncommonm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_relbeliefsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_relbeliefsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_schoolf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_schoolm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_securityf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_securitym': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_sideeffectsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_sideeffectsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_soceventf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_soceventm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_toomanyroundsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_toomanyroundsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_unhappywteamf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_unhappywteamm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_afpcase': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_cmamreferral': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_fic': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_mslscase': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_newborn': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_otherdisease': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_pregnantmother': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_rireferral': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_vcmattendedncer': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_zerodose': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'msd_grp_choice': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementcode': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'simserial': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'spec_grp_choice': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax12_59mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax12_59mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax2_11mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax2_11mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vaxnewbornsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vaxnewbornsm': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.vcmsummarynew': {
'Meta': {'object_name': 'VCMSummaryNew'},
'census12_59mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'census12_59mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'census2_11mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'census2_11mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'censusnewbornsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'censusnewbornsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'date_implement': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'dateofreport': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_msd1': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_msd2': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_vax1': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_vax2': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_vax3': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_vax4': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_vax5': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_vax6': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_vax7': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_vax8': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_vax9': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_display_msd3': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_agedoutf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_agedoutm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childdiedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childdiedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childsickf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_childsickm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_familymovedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_familymovedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_farmf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_farmm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_hhnotvisitedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_hhnotvisitedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_marketf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_marketm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noconsentf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noconsentm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nofeltneedf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nofeltneedm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nogovtservicesf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_nogovtservicesm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noplusesf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_noplusesm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_otherprotectionf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_otherprotectionm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_playgroundf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_playgroundm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poldiffsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poldiffsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliohascuref': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliohascurem': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliouncommonf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_poliouncommonm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_relbeliefsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_relbeliefsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_schoolf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_schoolm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_securityf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_securitym': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_sideeffectsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_sideeffectsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_soceventf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_soceventm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_toomanyroundsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_toomanyroundsm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_unhappywteamf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_msd_unhappywteamm': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_msd_chd_tot_missed_check': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_afpcase': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_cmamreferral': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_fic': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_mslscase': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_newborn': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_otherdisease': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_pregnantmother': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_rireferral': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_vcmattendedncer': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'group_spec_events_spec_zerodose': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'settlementcode': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'simserial': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'spec_grp_choice': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'tot_12_59months': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'tot_2_11months': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'tot_census': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'tot_missed': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'tot_newborns': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'tot_vax': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'tot_vax12_59mo': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'tot_vax2_11mo': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'tot_vaxnewborn': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax12_59mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax12_59mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax2_11mof': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vax2_11mom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vaxnewbornsf': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'vaxnewbornsm': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'source_data.vwsregister': {
'Meta': {'object_name': 'VWSRegister'},
'acceptphoneresponsibility': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 11, 27, 0, 0)'}),
'datephonecollected': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'fname_vws': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'lname_vws': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'meta_instanceid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'personal_phone': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'process_status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['source_data.ProcessStatus']"}),
'request_guid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'simserial': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'submissiondate': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'wardcode': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['source_data']
| agpl-3.0 |
UCL-INGI/Informatique-1-additional | M2Q9/student/Exercice9Vide.java | 943 | /**
* Copyright (c) 2016 Ludovic Taffin
* 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 student;
public class Exercice9Stu {
/*
* @pre : -
* @post : Donne la saison de l'année
*
*/
public static int sais(int jour, int mois){
String saison;
@ @q1@@
return saison;
}
}
| agpl-3.0 |
OpusVL/odoo | addons/web_kanban/static/src/js/kanban.js | 58441 | openerp.web_kanban = function (instance) {
var _t = instance.web._t,
_lt = instance.web._lt;
var QWeb = instance.web.qweb;
instance.web.views.add('kanban', 'instance.web_kanban.KanbanView');
instance.web_kanban.KanbanView = instance.web.View.extend({
template: "KanbanView",
display_name: _lt('Kanban'),
default_nr_columns: 1,
view_type: "kanban",
quick_create_class: "instance.web_kanban.QuickCreate",
number_of_color_schemes: 10,
init: function (parent, dataset, view_id, options) {
this._super(parent, dataset, view_id, options);
var self = this;
_.defaults(this.options, {
"quick_creatable": true,
"creatable": true,
"create_text": undefined,
"read_only_mode": false,
"confirm_on_delete": true,
});
this.fields_view = {};
this.fields_keys = [];
this.group_by = null;
this.group_by_field = {};
this.grouped_by_m2o = false;
this.many2manys = [];
this.state = {
groups : {},
records : {}
};
this.groups = [];
this.aggregates = {};
this.group_operators = ['avg', 'max', 'min', 'sum', 'count'];
this.qweb = new QWeb2.Engine();
this.qweb.debug = instance.session.debug;
this.qweb.default_dict = _.clone(QWeb.default_dict);
this.has_been_loaded = $.Deferred();
this.search_domain = this.search_context = this.search_group_by = null;
this.currently_dragging = {};
this.limit = options.limit || 40;
this.add_group_mutex = new $.Mutex();
if (!this.options.$buttons || !this.options.$buttons.length) {
this.options.$buttons = false;
}
},
view_loading: function(r) {
return this.load_kanban(r);
},
start: function() {
var self = this;
this._super.apply(this, arguments);
this.$el.on('click', '.oe_kanban_dummy_cell', function() {
if (self.$buttons) {
self.$buttons.find('.oe_kanban_add_column').openerpBounce();
}
});
},
destroy: function() {
this._super.apply(this, arguments);
$('html').off('click.kanban');
},
load_kanban: function(data) {
this.fields_view = data;
// use default order if defined in xml description
var default_order = this.fields_view.arch.attrs.default_order,
unsorted = !this.dataset._sort.length;
if (unsorted && default_order) {
this.dataset.set_sort(default_order.split(','));
}
this.$el.addClass(this.fields_view.arch.attrs['class']);
this.$buttons = $(QWeb.render("KanbanView.buttons", {'widget': this}));
if (this.options.$buttons) {
this.$buttons.appendTo(this.options.$buttons);
} else {
this.$('.oe_kanban_buttons').replaceWith(this.$buttons);
}
this.$buttons
.on('click', 'button.oe_kanban_button_new', this.do_add_record)
.on('click', '.oe_kanban_add_column', this.do_add_group);
this.$groups = this.$el.find('.oe_kanban_groups tr');
this.fields_keys = _.keys(this.fields_view.fields);
this.add_qweb_template();
this.has_been_loaded.resolve();
this.trigger('kanban_view_loaded', data);
return $.when();
},
_is_quick_create_enabled: function() {
if (!this.options.quick_creatable || !this.is_action_enabled('create'))
return false;
if (this.fields_view.arch.attrs.quick_create !== undefined)
return JSON.parse(this.fields_view.arch.attrs.quick_create);
return !! this.group_by;
},
is_action_enabled: function(action) {
if (action === 'create' && !this.options.creatable)
return false;
return this._super(action);
},
/* add_qweb_template
* select the nodes into the xml and send to extract_aggregates the nodes with TagName="field"
*/
add_qweb_template: function() {
for (var i=0, ii=this.fields_view.arch.children.length; i < ii; i++) {
var child = this.fields_view.arch.children[i];
if (child.tag === "templates") {
this.transform_qweb_template(child);
this.qweb.add_template(instance.web.json_node_to_xml(child));
break;
} else if (child.tag === 'field') {
this.extract_aggregates(child);
}
}
},
/* extract_aggregates
* extract the agggregates from the nodes (TagName="field")
*/
extract_aggregates: function(node) {
for (var j = 0, jj = this.group_operators.length; j < jj; j++) {
if (node.attrs[this.group_operators[j]]) {
this.aggregates[node.attrs.name] = node.attrs[this.group_operators[j]];
break;
}
}
},
transform_qweb_template: function(node) {
var qweb_add_if = function(node, condition) {
if (node.attrs[QWeb.prefix + '-if']) {
condition = _.str.sprintf("(%s) and (%s)", node.attrs[QWeb.prefix + '-if'], condition);
}
node.attrs[QWeb.prefix + '-if'] = condition;
};
// Process modifiers
if (node.tag && node.attrs.modifiers) {
var modifiers = JSON.parse(node.attrs.modifiers || '{}');
if (modifiers.invisible) {
qweb_add_if(node, _.str.sprintf("!kanban_compute_domain(%s)", JSON.stringify(modifiers.invisible)));
}
}
switch (node.tag) {
case 'field':
var ftype = this.fields_view.fields[node.attrs.name].type;
ftype = node.attrs.widget ? node.attrs.widget : ftype;
if (ftype === 'many2many') {
if (_.indexOf(this.many2manys, node.attrs.name) < 0) {
this.many2manys.push(node.attrs.name);
}
node.tag = 'div';
node.attrs['class'] = (node.attrs['class'] || '') + ' oe_form_field oe_tags';
} else if (instance.web_kanban.fields_registry.contains(ftype)) {
// do nothing, the kanban record will handle it
} else {
node.tag = QWeb.prefix;
node.attrs[QWeb.prefix + '-esc'] = 'record.' + node.attrs['name'] + '.value';
}
break;
case 'button':
case 'a':
var type = node.attrs.type || '';
if (_.indexOf('action,object,edit,open,delete,url'.split(','), type) !== -1) {
_.each(node.attrs, function(v, k) {
if (_.indexOf('icon,type,name,args,string,context,states,kanban_states'.split(','), k) != -1) {
node.attrs['data-' + k] = v;
delete(node.attrs[k]);
}
});
if (node.attrs['data-string']) {
node.attrs.title = node.attrs['data-string'];
}
if (node.attrs['data-icon']) {
node.children = [{
tag: 'img',
attrs: {
src: instance.session.prefix + '/web/static/src/img/icons/' + node.attrs['data-icon'] + '.png',
width: '16',
height: '16'
}
}];
}
if (node.tag == 'a' && node.attrs['data-type'] != "url") {
node.attrs.href = '#';
} else {
node.attrs.type = 'button';
}
node.attrs['class'] = (node.attrs['class'] || '') + ' oe_kanban_action oe_kanban_action_' + node.tag;
}
break;
}
if (node.children) {
for (var i = 0, ii = node.children.length; i < ii; i++) {
this.transform_qweb_template(node.children[i]);
}
}
},
do_add_record: function() {
this.dataset.index = null;
this.do_switch_view('form');
},
do_add_group: function() {
var self = this;
self.do_action({
name: _t("Add column"),
res_model: self.group_by_field.relation,
views: [[false, 'form']],
type: 'ir.actions.act_window',
target: "new",
context: self.dataset.get_context(),
flags: {
action_buttons: true,
}
});
var am = instance.webclient.action_manager;
var form = am.dialog_widget.views.form.controller;
form.on("on_button_cancel", am.dialog, am.dialog.close);
form.on('record_created', self, function(r) {
(new instance.web.DataSet(self, self.group_by_field.relation)).name_get([r]).done(function(new_record) {
am.dialog.close();
var domain = self.dataset.domain.slice(0);
domain.push([self.group_by, '=', new_record[0][0]]);
var dataset = new instance.web.DataSetSearch(self, self.dataset.model, self.dataset.get_context(), domain);
var datagroup = {
get: function(key) {
return this[key];
},
value: new_record[0],
length: 0,
aggregates: {},
};
var new_group = new instance.web_kanban.KanbanGroup(self, [], datagroup, dataset);
self.do_add_groups([new_group]).done(function() {
$(window).scrollTo(self.groups.slice(-1)[0].$el, { axis: 'x' });
});
});
});
},
do_search: function(domain, context, group_by) {
var self = this;
this.search_domain = domain;
this.search_context = context;
this.search_group_by = group_by;
return $.when(this.has_been_loaded).then(function() {
self.group_by = group_by.length ? group_by[0] : self.fields_view.arch.attrs.default_group_by;
self.group_by_field = self.fields_view.fields[self.group_by] || {};
self.grouped_by_m2o = (self.group_by_field.type === 'many2one');
self.$buttons.find('.oe_alternative').toggle(self.grouped_by_m2o);
self.$el.toggleClass('oe_kanban_grouped_by_m2o', self.grouped_by_m2o);
var grouping_fields = self.group_by ? [self.group_by].concat(_.keys(self.aggregates)) : undefined;
if (!_.isEmpty(grouping_fields)) {
// ensure group_by fields are read.
self.fields_keys = _.unique(self.fields_keys.concat(grouping_fields));
}
var grouping = new instance.web.Model(self.dataset.model, context, domain).query(self.fields_keys).group_by(grouping_fields);
return self.alive($.when(grouping)).then(function(groups) {
self.remove_no_result();
if (groups) {
return self.do_process_groups(groups);
} else {
return self.do_process_dataset();
}
});
});
},
do_process_groups: function(groups) {
var self = this;
// Check in the arch the fields to fetch on the stage to get tooltips data.
// Fetching data is done in batch for all stages, to avoid doing multiple
// calls. The first naive implementation of group_by_tooltip made a call
// for each displayed stage and was quite limited.
// Data for the group tooltip (group_by_tooltip) and to display stage-related
// legends for kanban state management (states_legend) are fetched in
// one call.
var group_by_fields_to_read = [];
var recurse = function(node) {
if (node.tag === "field" && node.attrs && node.attrs.options) {
var options = instance.web.py_eval(node.attrs.options);
var states_fields_to_read = _.map(
options && options.states_legend || {},
function (value, key, list) { return value; });
var tooltip_fields_to_read = _.map(
options && options.group_by_tooltip || {},
function (value, key, list) { return key; });
group_by_fields_to_read = _.union(
group_by_fields_to_read,
states_fields_to_read,
tooltip_fields_to_read);
}
_.each(node.children, function(child) {
recurse(child);
});
};
recurse(this.fields_view.arch);
var group_ids = _.without(_.map(groups, function (elem) { return elem.attributes.value[0]}), undefined);
if (this.grouped_by_m2o && group_ids.length && group_by_fields_to_read.length) {
var group_data = new instance.web.DataSet(
this,
this.group_by_field.relation).read_ids(group_ids, _.union(['display_name'], group_by_fields_to_read));
}
else { var group_data = $.Deferred().resolve({}); }
this.$el.find('table:first').show();
this.$el.removeClass('oe_kanban_ungrouped').addClass('oe_kanban_grouped');
return $.when(group_data).then(function (results) {
_.each(results, function (group_by_data) {
var group = _.find(groups, function (elem) {return elem.attributes.value[0] == group_by_data.id});
if (group) {
group.values = group_by_data;
}
});
}).done( function () {return self.add_group_mutex.exec(function() {
self.do_clear_groups();
self.dataset.ids = [];
if (!groups.length) {
self.no_result();
return $.when();
}
self.nb_records = 0;
var groups_array = [];
return $.when.apply(null, _.map(groups, function (group, index) {
var def = $.when([]);
var dataset = new instance.web.DataSetSearch(self, self.dataset.model,
new instance.web.CompoundContext(self.dataset.get_context(), group.model.context()), group.model.domain());
if (self.dataset._sort) {
dataset.set_sort(self.dataset._sort);
}
if (group.attributes.length >= 1) {
def = dataset.read_slice(self.fields_keys.concat(['__last_update']), { 'limit': self.limit });
}
return def.then(function(records) {
self.nb_records += records.length;
self.dataset.ids.push.apply(self.dataset.ids, dataset.ids);
groups_array[index] = new instance.web_kanban.KanbanGroup(self, records, group, dataset);
});
})).then(function () {
if(!self.nb_records) {
self.no_result();
}
if (self.dataset.index >= self.nb_records){
self.dataset.index = self.dataset.size() ? 0 : null;
}
return self.do_add_groups(groups_array).done(function() {
self.trigger('kanban_groups_processed');
});
});
})});
},
do_process_dataset: function() {
var self = this;
this.$el.find('table:first').show();
this.$el.removeClass('oe_kanban_grouped').addClass('oe_kanban_ungrouped');
var def = $.Deferred();
this.add_group_mutex.exec(function() {
self.do_clear_groups();
self.dataset.read_slice(self.fields_keys.concat(['__last_update']), { 'limit': self.limit }).done(function(records) {
var kgroup = new instance.web_kanban.KanbanGroup(self, records, null, self.dataset);
if (!_.isEmpty(self.dataset.ids) && (self.dataset.index === null || self.dataset.index >= self.dataset.ids.length)) {
self.dataset.index = 0;
} else if (_.isEmpty(self.dataset.ids)){
self.dataset.index = null;
}
self.do_add_groups([kgroup]).done(function() {
if (_.isEmpty(records)) {
self.no_result();
}
self.trigger('kanban_dataset_processed');
def.resolve();
});
}).done(null, function() {
def.reject();
});
});
return def;
},
do_reload: function() {
this.do_search(this.search_domain, this.search_context, this.search_group_by);
},
do_clear_groups: function() {
var groups = this.groups.slice(0);
this.groups = [];
_.each(groups, function(group) {
group.destroy();
});
},
do_add_groups: function(groups) {
var self = this;
var $parent = this.$el.parent();
this.$el.detach();
_.each(groups, function(group) {
self.groups[group.undefined_title ? 'unshift' : 'push'](group);
});
var $last_td = self.$el.find('.oe_kanban_groups_headers td:last');
var groups_started = _.map(this.groups, function(group) {
if (!group.is_started) {
group.on("add_record", self, function () {
self.remove_no_result();
});
return group.insertBefore($last_td);
}
});
return $.when.apply(null, groups_started).done(function () {
self.on_groups_started();
self.$el.appendTo($parent);
_.each(self.groups, function(group) {
group.compute_cards_auto_height();
});
});
},
on_groups_started: function() {
var self = this;
if (this.group_by || this.fields_keys.indexOf("sequence") !== -1) {
// Kanban cards drag'n'drop
var prev_widget, is_folded, record, $columns;
if (this.group_by) {
$columns = this.$el.find('.oe_kanban_column .oe_kanban_column_cards, .oe_kanban_column .oe_kanban_folded_column_cards');
} else {
$columns = this.$el.find('.oe_kanban_column_cards');
}
$columns.sortable({
handle : '.oe_kanban_draghandle',
start: function(event, ui) {
self.currently_dragging.index = ui.item.parent().children('.oe_kanban_record').index(ui.item);
self.currently_dragging.group = prev_widget = ui.item.parents('.oe_kanban_column:first').data('widget');
ui.item.find('*').on('click.prevent', function(ev) {
return false;
});
record = ui.item.data('widget');
record.$el.bind('mouseup',function(ev,ui){
if (is_folded) {
record.$el.hide();
}
record.$el.unbind('mouseup');
})
ui.placeholder.height(ui.item.height());
},
over: function(event, ui) {
var parent = $(event.target).parent();
prev_widget.highlight(false);
is_folded = parent.hasClass('oe_kanban_group_folded');
if (is_folded) {
var widget = parent.data('widget');
widget.highlight(true);
prev_widget = widget;
}
},
revert: 150,
stop: function(event, ui) {
prev_widget.highlight(false);
var old_index = self.currently_dragging.index;
var new_index = ui.item.parent().children('.oe_kanban_record').index(ui.item);
var old_group = self.currently_dragging.group;
var new_group = ui.item.parents('.oe_kanban_column:first').data('widget');
if (!(old_group.title === new_group.title && old_group.value === new_group.value && old_index == new_index)) {
self.on_record_moved(record, old_group, old_index, new_group, new_index);
}
setTimeout(function() {
// A bit hacky but could not find a better solution for Firefox (problem not present in chrome)
// http://stackoverflow.com/questions/274843/preventing-javascript-click-event-with-scriptaculous-drag-and-drop
ui.item.find('*').off('click.prevent');
}, 0);
},
scroll: false
});
// Keep connectWith out of the sortable initialization for performance sake:
// http://www.planbox.com/blog/development/coding/jquery-ui-sortable-slow-to-bind.html
$columns.sortable({ connectWith: $columns });
// Kanban groups drag'n'drop
var start_index;
if (this.grouped_by_m2o) {
this.$('.oe_kanban_groups_headers').sortable({
items: '.oe_kanban_group_header',
helper: 'clone',
axis: 'x',
opacity: 0.5,
scroll: false,
start: function(event, ui) {
start_index = ui.item.index();
self.$('.oe_kanban_record, .oe_kanban_quick_create').css({ visibility: 'hidden' });
},
stop: function(event, ui) {
var stop_index = ui.item.index();
if (start_index !== stop_index) {
var $start_column = self.$('.oe_kanban_groups_records .oe_kanban_column').eq(start_index);
var $stop_column = self.$('.oe_kanban_groups_records .oe_kanban_column').eq(stop_index);
var method = (start_index > stop_index) ? 'insertBefore' : 'insertAfter';
$start_column[method]($stop_column);
var tmp_group = self.groups.splice(start_index, 1)[0];
self.groups.splice(stop_index, 0, tmp_group);
var new_sequence = _.pluck(self.groups, 'value');
(new instance.web.DataSet(self, self.group_by_field.relation)).resequence(new_sequence).done(function(r) {
if (r === false) {
console.error("Kanban: could not resequence model '%s'. Probably no 'sequence' field.", self.group_by_field.relation);
}
});
}
self.$('.oe_kanban_record, .oe_kanban_quick_create').css({ visibility: 'visible' });
}
});
}
} else {
this.$el.find('.oe_kanban_draghandle').removeClass('oe_kanban_draghandle');
}
this.postprocess_m2m_tags();
},
on_record_moved : function(record, old_group, old_index, new_group, new_index) {
var self = this;
record.$el.find('[title]').tooltip('destroy');
$(old_group.$el).add(new_group.$el).find('.oe_kanban_aggregates, .oe_kanban_group_length').hide();
if (old_group === new_group) {
new_group.records.splice(old_index, 1);
new_group.records.splice(new_index, 0, record);
new_group.do_save_sequences();
} else {
old_group.records.splice(old_index, 1);
new_group.records.splice(new_index, 0, record);
record.group = new_group;
var data = {};
data[this.group_by] = new_group.value;
this.dataset.write(record.id, data, {}).done(function() {
record.do_reload();
new_group.do_save_sequences();
if (new_group.state.folded) {
new_group.do_action_toggle_fold();
record.prependTo(new_group.$records.find('.oe_kanban_column_cards'));
}
}).fail(function(error, evt) {
evt.preventDefault();
alert(_t("An error has occured while moving the record to this group: ") + error.data.message);
self.do_reload(); // TODO: use draggable + sortable in order to cancel the dragging when the rcp fails
});
}
},
do_show: function() {
if (this.options.$buttons) {
this.$buttons.show();
}
this.do_push_state({});
return this._super();
},
do_hide: function () {
if (this.$buttons) {
this.$buttons.hide();
}
return this._super();
},
open_record: function(id, editable) {
if (this.dataset.select_id(id)) {
this.do_switch_view('form', null, { mode: editable ? "edit" : undefined });
} else {
this.do_warn("Kanban: could not find id#" + id);
}
},
no_result: function() {
var self = this;
if (this.groups.group_by
|| !this.options.action
|| (!this.options.action.help && !this.options.action.get_empty_list_help)) {
return;
}
this.$el.css("position", "relative");
$(QWeb.render('KanbanView.nocontent', { content : this.options.action.get_empty_list_help || this.options.action.help})).insertBefore(this.$('table:first'));
this.$el.find('.oe_view_nocontent').click(function() {
self.$buttons.openerpBounce();
});
},
remove_no_result: function() {
this.$el.css("position", "");
this.$el.find('.oe_view_nocontent').remove();
},
/*
* postprocessing of fields type many2many
* make the rpc request for all ids/model and insert value inside .oe_tags fields
*/
postprocess_m2m_tags: function() {
var self = this;
if (!this.many2manys.length) {
return;
}
var relations = {};
this.groups.forEach(function(group) {
group.records.forEach(function(record) {
self.many2manys.forEach(function(name) {
var field = record.record[name];
var $el = record.$('.oe_form_field.oe_tags[name=' + name + ']').empty();
if (!relations[field.relation]) {
relations[field.relation] = { ids: [], elements: {}};
}
var rel = relations[field.relation];
field.raw_value.forEach(function(id) {
rel.ids.push(id);
if (!rel.elements[id]) {
rel.elements[id] = [];
}
rel.elements[id].push($el[0]);
});
});
});
});
_.each(relations, function(rel, rel_name) {
var dataset = new instance.web.DataSetSearch(self, rel_name, self.dataset.get_context());
dataset.name_get(_.uniq(rel.ids)).done(function(result) {
result.forEach(function(nameget) {
$(rel.elements[nameget[0]]).append('<span class="oe_tag">' + _.str.escapeHTML(nameget[1]) + '</span>');
});
});
});
}
});
function get_class(name) {
return new instance.web.Registry({'tmp' : name}).get_object("tmp");
}
instance.web_kanban.KanbanGroup = instance.web.Widget.extend({
template: 'KanbanView.group_header',
init: function (parent, records, group, dataset) {
var self = this;
this._super(parent);
this.$has_been_started = $.Deferred();
this.view = parent;
this.group = group;
this.dataset = dataset;
this.dataset_offset = 0;
this.aggregates = {};
this.value = this.title = this.values = null;
if (this.group) {
this.values = group.values;
this.value = group.get('value');
this.title = group.get('value');
if (this.value instanceof Array) {
this.title = this.value[1];
this.value = this.value[0];
}
var field = this.view.group_by_field;
if (!_.isEmpty(field)) {
try {
this.title = instance.web.format_value(group.get('value'), field, false);
} catch(e) {}
}
_.each(this.view.aggregates, function(value, key) {
self.aggregates[value] = instance.web.format_value(group.get('aggregates')[key], {type: 'float'});
});
}
if (this.title === false) {
this.title = _t('Undefined');
this.undefined_title = true;
}
var key = this.view.group_by + '-' + this.value;
if (!this.view.state.groups[key]) {
this.view.state.groups[key] = {
folded: group ? group.get('folded') : false
};
}
this.state = this.view.state.groups[key];
this.$records = null;
this.records = [];
this.$has_been_started.done(function() {
self.do_add_records(records);
});
},
start: function() {
var self = this,
def = this._super();
if (! self.view.group_by) {
self.$el.addClass("oe_kanban_no_group");
self.quick = new (get_class(self.view.quick_create_class))(this, self.dataset, {}, false)
.on('added', self, self.proxy('quick_created'));
self.quick.replace($(".oe_kanban_no_group_qc_placeholder"));
}
this.$records = $(QWeb.render('KanbanView.group_records_container', { widget : this}));
this.$records.insertBefore(this.view.$el.find('.oe_kanban_groups_records td:last'));
this.$el.on('click', '.oe_kanban_group_dropdown li a', function(ev) {
var fn = 'do_action_' + $(ev.target).data().action;
if (typeof(self[fn]) === 'function') {
self[fn]($(ev.target));
}
});
this.$el.find('.oe_kanban_add').click(function () {
if (self.view.quick) {
self.view.quick.trigger('close');
}
if (self.quick) {
return false;
}
self.view.$el.find('.oe_view_nocontent').hide();
var ctx = {};
ctx['default_' + self.view.group_by] = self.value;
self.quick = new (get_class(self.view.quick_create_class))(this, self.dataset, ctx, true)
.on('added', self, self.proxy('quick_created'))
.on('close', self, function() {
self.view.$el.find('.oe_view_nocontent').show();
this.quick.destroy();
delete self.view.quick;
delete this.quick;
});
self.quick.appendTo($(".oe_kanban_group_list_header", self.$records));
self.quick.focus();
self.view.quick = self.quick;
});
// Add bounce effect on image '+' of kanban header when click on empty space of kanban grouped column.
this.$records.on('click', '.oe_kanban_show_more', this.do_show_more);
if (this.state.folded) {
this.do_toggle_fold();
}
this.$el.data('widget', this);
this.$records.data('widget', this);
this.$has_been_started.resolve();
var add_btn = this.$el.find('.oe_kanban_add');
add_btn.tooltip({delay: { show: 500, hide:1000 }});
this.$records.find(".oe_kanban_column_cards").click(function (ev) {
if (ev.target == ev.currentTarget) {
if (!self.state.folded) {
add_btn.openerpBounce();
}
}
});
this.is_started = true;
this.fetch_tooltip();
return def;
},
/*
* Form the tooltip, based on optional group_by_tooltip on the grouping field.
* This function goes through the arch of the view, finding the declaration
* of the field used to group. If group_by_tooltip is defined, use the previously
* computed values of the group to form the tooltip. */
fetch_tooltip: function() {
var self = this;
if (! this.group)
return;
var options = null;
var recurse = function(node) {
if (node.tag === "field" && node.attrs.name == self.view.group_by) {
options = instance.web.py_eval(node.attrs.options || '{}');
return;
}
_.each(node.children, function(child) {
recurse(child);
});
};
recurse(this.view.fields_view.arch);
if (options && options.group_by_tooltip) {
this.tooltip = _.union(
[this.title],
_.map(
options.group_by_tooltip,
function (key, value, list) { return self.values && self.values[value] || ''; })
).join('\n\n');
this.$(".oe_kanban_group_title_text").attr("title", this.tooltip || this.title || "");
}
},
compute_cards_auto_height: function() {
// oe_kanban_no_auto_height is an empty class used to disable this feature
if (!this.view.group_by) {
var min_height = 0;
var els = [];
_.each(this.records, function(r) {
var $e = r.$el.children(':first:not(.oe_kanban_no_auto_height)').css('min-height', 0);
if ($e.length) {
els.push($e[0]);
min_height = Math.max(min_height, $e.outerHeight());
}
});
$(els).css('min-height', min_height);
}
},
destroy: function() {
this._super();
if (this.$records) {
this.$records.remove();
}
},
do_show_more: function(evt) {
var self = this;
var ids = self.view.dataset.ids.splice(0);
return this.dataset.read_slice(this.view.fields_keys.concat(['__last_update']), {
'limit': self.view.limit,
'offset': self.dataset_offset += self.view.limit
}).then(function(records) {
self.view.dataset.ids = ids.concat(self.dataset.ids);
self.do_add_records(records);
self.compute_cards_auto_height();
self.view.postprocess_m2m_tags();
return records;
});
},
do_add_records: function(records, prepend) {
var self = this;
var $list_header = this.$records.find('.oe_kanban_group_list_header');
var $show_more = this.$records.find('.oe_kanban_show_more');
var $cards = this.$records.find('.oe_kanban_column_cards');
_.each(records, function(record) {
var rec = new instance.web_kanban.KanbanRecord(self, record);
if (!prepend) {
rec.appendTo($cards);
self.records.push(rec);
} else {
rec.prependTo($cards);
self.records.unshift(rec);
}
});
if ($show_more.length) {
var size = this.dataset.size();
$show_more.toggle(this.records.length < size).find('.oe_kanban_remaining').text(size - this.records.length);
}
},
remove_record: function(id, remove_from_dataset) {
for (var i = 0; i < this.records.length; i++) {
if (this.records[i]['id'] === id) {
this.records.splice(i, 1);
i--;
}
}
},
do_toggle_fold: function(compute_width) {
this.$el.add(this.$records).toggleClass('oe_kanban_group_folded');
this.state.folded = this.$el.is('.oe_kanban_group_folded');
this.$("ul.oe_kanban_group_dropdown li a[data-action=toggle_fold]").text((this.state.folded) ? _t("Unfold") : _t("Fold"));
},
do_action_toggle_fold: function() {
this.do_toggle_fold();
},
do_action_edit: function() {
var self = this;
self.do_action({
res_id: this.value,
name: _t("Edit column"),
res_model: self.view.group_by_field.relation,
views: [[false, 'form']],
type: 'ir.actions.act_window',
target: "new",
flags: {
action_buttons: true,
}
});
var am = instance.webclient.action_manager;
var form = am.dialog_widget.views.form.controller;
form.on("on_button_cancel", am.dialog, function() { return am.dialog.$dialog_box.modal('hide'); });
form.on('record_saved', self, function() {
am.dialog.$dialog_box.modal('hide');
self.view.do_reload();
});
},
do_action_delete: function() {
var self = this;
if (confirm(_t("Are you sure to remove this column ?"))) {
(new instance.web.DataSet(self, self.view.group_by_field.relation)).unlink([self.value]).done(function(r) {
self.view.do_reload();
});
}
},
do_save_sequences: function() {
var self = this;
if (_.indexOf(this.view.fields_keys, 'sequence') > -1) {
var new_sequence = _.pluck(this.records, 'id');
self.view.dataset.resequence(new_sequence);
}
},
/**
* Handles a newly created record
*
* @param {id} id of the newly created record
*/
quick_created: function (record) {
var id = record, self = this;
self.view.remove_no_result();
self.trigger("add_record");
this.dataset.read_ids([id], this.view.fields_keys)
.done(function (records) {
self.view.dataset.ids.push(id);
self.do_add_records(records, true);
});
},
highlight: function(show){
if(show){
this.$el.addClass('oe_kanban_column_higlight');
this.$records.addClass('oe_kanban_column_higlight');
}else{
this.$el.removeClass('oe_kanban_column_higlight');
this.$records.removeClass('oe_kanban_column_higlight');
}
}
});
instance.web_kanban.KanbanRecord = instance.web.Widget.extend({
template: 'KanbanView.record',
init: function (parent, record) {
this._super(parent);
this.group = parent;
this.view = parent.view;
this.id = null;
this.set_record(record);
if (!this.view.state.records[this.id]) {
this.view.state.records[this.id] = {
folded: false
};
}
this.state = this.view.state.records[this.id];
this.fields = {};
},
set_record: function(record) {
var self = this;
this.id = record.id;
this.values = {};
_.each(record, function(v, k) {
self.values[k] = {
value: v
};
});
this.record = this.transform_record(record);
},
start: function() {
var self = this;
this._super();
this.init_content();
},
init_content: function() {
var self = this;
self.sub_widgets = [];
this.$("[data-field_id]").each(function() {
self.add_widget($(this));
});
this.$el.data('widget', this);
this.bind_events();
},
transform_record: function(record) {
var self = this,
new_record = {};
_.each(record, function(value, name) {
var r = _.clone(self.view.fields_view.fields[name] || {});
if ((r.type === 'date' || r.type === 'datetime') && value) {
r.raw_value = instance.web.auto_str_to_date(value);
} else {
r.raw_value = value;
}
r.value = instance.web.format_value(value, r);
new_record[name] = r;
});
return new_record;
},
renderElement: function() {
this.qweb_context = {
instance: instance,
record: this.record,
widget: this,
read_only_mode: this.view.options.read_only_mode,
};
for (var p in this) {
if (_.str.startsWith(p, 'kanban_')) {
this.qweb_context[p] = _.bind(this[p], this);
}
}
var $el = instance.web.qweb.render(this.template, {
'widget': this,
'content': this.view.qweb.render('kanban-box', this.qweb_context)
});
this.replaceElement($el);
this.replace_fields();
},
replace_fields: function() {
var self = this;
this.$("field").each(function() {
var $field = $(this);
var $nfield = $("<span></span");
var id = _.uniqueId("kanbanfield");
self.fields[id] = $field;
$nfield.attr("data-field_id", id);
$field.replaceWith($nfield);
});
},
add_widget: function($node) {
var $orig = this.fields[$node.data("field_id")];
var field = this.record[$orig.attr("name")];
var type = field.type;
type = $orig.attr("widget") ? $orig.attr("widget") : type;
var obj = instance.web_kanban.fields_registry.get_object(type);
var widget = new obj(this, field, $orig);
this.sub_widgets.push(widget);
widget.replace($node);
},
bind_events: function() {
var self = this;
this.setup_color_picker();
this.$el.find('[title]').each(function(){
$(this).tooltip({
delay: { show: 500, hide: 0},
title: function() {
var template = $(this).attr('tooltip');
if (!self.view.qweb.has_template(template)) {
return false;
}
return self.view.qweb.render(template, self.qweb_context);
},
});
});
// If no draghandle is found, make the whole card as draghandle (provided one can edit)
if (!this.$el.find('.oe_kanban_draghandle').length) {
this.$el.children(':first')
.toggleClass('oe_kanban_draghandle', this.view.is_action_enabled('edit'));
}
this.$el.find('.oe_kanban_action').click(function(ev) {
ev.preventDefault();
var $action = $(this),
type = $action.data('type') || 'button',
method = 'do_action_' + (type === 'action' ? 'object' : type);
if ((type === 'edit' || type === 'delete') && ! self.view.is_action_enabled(type)) {
self.view.open_record(self.id, true);
} else if (_.str.startsWith(type, 'switch_')) {
self.view.do_switch_view(type.substr(7));
} else if (typeof self[method] === 'function') {
self[method]($action);
} else {
self.do_warn("Kanban: no action for type : " + type);
}
});
if (this.$el.find('.oe_kanban_global_click,.oe_kanban_global_click_edit').length) {
this.$el.on('click', function(ev) {
if (!ev.isTrigger && !$._data(ev.target, 'events')) {
var trigger = true;
var elem = ev.target;
var ischild = true;
var children = [];
while (elem) {
var events = $._data(elem, 'events');
if (elem == ev.currentTarget) {
ischild = false;
}
if (ischild) {
children.push(elem);
if (events && events.click) {
// do not trigger global click if one child has a click event registered
trigger = false;
}
}
if (trigger && events && events.click) {
_.each(events.click, function(click_event) {
if (click_event.selector) {
// For each parent of original target, check if a
// delegated click is bound to any previously found children
_.each(children, function(child) {
if ($(child).is(click_event.selector)) {
trigger = false;
}
});
}
});
}
elem = elem.parentElement;
}
if (trigger) {
self.on_card_clicked(ev);
}
}
});
}
},
/* actions when user click on the block with a specific class
* open on normal view : oe_kanban_global_click
* open on form/edit view : oe_kanban_global_click_edit
*/
on_card_clicked: function(ev) {
if (this.$el.find('.oe_kanban_global_click').size() > 0 && this.$el.find('.oe_kanban_global_click').data('routing')) {
instance.web.redirect(this.$el.find('.oe_kanban_global_click').data('routing') + "/" + this.id);
}
else if (this.$el.find('.oe_kanban_global_click_edit').size()>0)
this.do_action_edit();
else
this.do_action_open();
},
setup_color_picker: function() {
var self = this;
var $el = this.$el.find('ul.oe_kanban_colorpicker');
if ($el.length) {
$el.html(QWeb.render('KanbanColorPicker', {
widget: this
}));
$el.on('click', 'a', function(ev) {
ev.preventDefault();
var color_field = $(this).parents('.oe_kanban_colorpicker').first().data('field') || 'color';
var data = {};
data[color_field] = $(this).data('color');
self.view.dataset.write(self.id, data, {}).done(function() {
self.record[color_field] = $(this).data('color');
self.do_reload();
});
});
}
},
do_action_delete: function($action) {
var self = this;
function do_it() {
return $.when(self.view.dataset.unlink([self.id])).done(function() {
self.group.remove_record(self.id);
self.destroy();
});
}
if (this.view.options.confirm_on_delete) {
if (confirm(_t("Are you sure you want to delete this record ?"))) {
return do_it();
}
} else
return do_it();
},
do_action_edit: function($action) {
this.view.open_record(this.id, true);
},
do_action_open: function($action) {
this.view.open_record(this.id);
},
do_action_object: function ($action) {
var button_attrs = $action.data();
this.view.do_execute_action(button_attrs, this.view.dataset, this.id, this.do_reload);
},
do_action_url: function($action) {
return instance.web.redirect($action.attr("href"));
},
do_reload: function() {
var self = this;
this.view.dataset.read_ids([this.id], this.view.fields_keys.concat(['__last_update'])).done(function(records) {
_.each(self.sub_widgets, function(el) {
el.destroy();
});
self.sub_widgets = [];
if (records.length) {
self.set_record(records[0]);
self.renderElement();
self.init_content();
self.group.compute_cards_auto_height();
self.view.postprocess_m2m_tags();
} else {
self.destroy();
}
});
},
kanban_getcolor: function(variable) {
var index = 0;
switch (typeof(variable)) {
case 'string':
for (var i=0, ii=variable.length; i<ii; i++) {
index += variable.charCodeAt(i);
}
break;
case 'number':
index = Math.round(variable);
break;
default:
return '';
}
var color = (index % this.view.number_of_color_schemes);
return color;
},
kanban_color: function(variable) {
var color = this.kanban_getcolor(variable);
return color === '' ? '' : 'oe_kanban_color_' + color;
},
kanban_image: function(model, field, id, cache, options) {
options = options || {};
var url;
if (this.record[field] && this.record[field].value && !instance.web.form.is_bin_size(this.record[field].value)) {
url = 'data:image/png;base64,' + this.record[field].value;
} else if (this.record[field] && ! this.record[field].value) {
url = "/web/static/src/img/placeholder.png";
} else {
id = JSON.stringify(id);
if (options.preview_image)
field = options.preview_image;
url = this.session.url('/web/binary/image', {model: model, field: field, id: id});
if (cache !== undefined) {
// Set the cache duration in seconds.
url += '&cache=' + parseInt(cache, 10);
}
}
return url;
},
kanban_text_ellipsis: function(s, size) {
size = size || 160;
if (!s) {
return '';
} else if (s.length <= size) {
return s;
} else {
return s.substr(0, size) + '...';
}
},
kanban_compute_domain: function(domain) {
return instance.web.form.compute_domain(domain, this.values);
}
});
/**
* Quick creation view.
*
* Triggers a single event "added" with a single parameter "name", which is the
* name entered by the user
*
* @class
* @type {*}
*/
instance.web_kanban.QuickCreate = instance.web.Widget.extend({
template: 'KanbanView.quick_create',
/**
* close_btn: If true, the widget will display a "Close" button able to trigger
* a "close" event.
*/
init: function(parent, dataset, context, buttons) {
this._super(parent);
this._dataset = dataset;
this._buttons = buttons || false;
this._context = context || {};
},
start: function () {
var self = this;
self.$input = this.$el.find('input');
self.$input.keyup(function(event){
if(event.keyCode == 13){
self.quick_add();
}
});
$(".oe_kanban_quick_create").focusout(function (e) {
var val = self.$el.find('input').val();
if (/^\s*$/.test(val)) { self.trigger('close'); }
e.stopImmediatePropagation();
});
$(".oe_kanban_quick_create_add", this.$el).click(function () {
self.quick_add();
self.focus();
});
$(".oe_kanban_quick_create_close", this.$el).click(function (ev) {
ev.preventDefault();
self.trigger('close');
});
self.$input.keyup(function(e) {
if (e.keyCode == 27 && self._buttons) {
self.trigger('close');
}
});
},
focus: function() {
this.$el.find('input').focus();
},
/**
* Handles user event from nested quick creation view
*/
quick_add: function () {
var self = this;
var val = this.$input.val();
if (/^\s*$/.test(val)) { this.$el.remove(); return; }
this._dataset.call(
'name_create', [val, new instance.web.CompoundContext(
this._dataset.get_context(), this._context)])
.then(function(record) {
self.$input.val("");
self.trigger('added', record[0]);
}, function(error, event) {
event.preventDefault();
return self.slow_create();
});
},
slow_create: function() {
var self = this;
var pop = new instance.web.form.SelectCreatePopup(this);
pop.select_element(
self._dataset.model,
{
title: _t("Create: ") + (this.string || this.name),
initial_view: "form",
disable_multiple_selection: true
},
[],
{"default_name": self.$input.val()}
);
pop.on("elements_selected", self, function(element_ids) {
self.$input.val("");
self.trigger('added', element_ids[0]);
});
}
});
/**
* Interface to be implemented by kanban fields.
*
*/
instance.web_kanban.FieldInterface = {
/**
Constructor.
- parent: The widget's parent.
- field: A dictionary giving details about the field, including the current field's value in the
raw_value field.
- $node: The field <field> tag as it appears in the view, encapsulated in a jQuery object.
*/
init: function(parent, field, $node) {},
};
/**
* Abstract class for classes implementing FieldInterface.
*
* Properties:
* - value: useful property to hold the value of the field. By default, the constructor
* sets value property.
*
*/
instance.web_kanban.AbstractField = instance.web.Widget.extend(instance.web_kanban.FieldInterface, {
/**
Constructor that saves the field and $node parameters and sets the "value" property.
*/
init: function(parent, field, $node) {
this._super(parent);
this.field = field;
this.$node = $node;
this.options = instance.web.py_eval(this.$node.attr("options") || '{}');
this.set("value", field.raw_value);
},
});
instance.web_kanban.Priority = instance.web_kanban.AbstractField.extend({
init: function(parent, field, $node) {
this._super.apply(this, arguments);
this.name = $node.attr('name')
this.parent = parent;
},
prepare_priority: function() {
var self = this;
var selection = this.field.selection || [];
var init_value = selection && selection[0][0] || 0;
var data = _.map(selection.slice(1), function(element, index) {
var value = {
'value': element[0],
'name': element[1],
'click_value': element[0],
}
if (index == 0 && self.get('value') == element[0]) {
value['click_value'] = init_value;
}
return value;
});
return data;
},
renderElement: function() {
var self = this;
this.record_id = self.parent.id;
this.priorities = self.prepare_priority();
this.$el = $(QWeb.render("Priority", {'widget': this}));
this.$el.find('li').click(self.do_action.bind(self));
},
do_action: function(e) {
var self = this;
var li = $(e.target).closest( "li" );
if (li.length) {
var value = {};
value[self.name] = String(li.data('value'));
return self.parent.view.dataset._model.call('write', [[self.record_id], value, self.parent.view.dataset.get_context()]).done(self.reload_record.bind(self.parent));
}
},
reload_record: function() {
this.do_reload();
},
});
instance.web_kanban.KanbanSelection = instance.web_kanban.AbstractField.extend({
init: function(parent, field, $node) {
this._super.apply(this, arguments);
this.name = $node.attr('name')
this.parent = parent;
},
prepare_dropdown_selection: function() {
var self = this;
var data = [];
_.map(this.field.selection || [], function(res) {
var value = {
'name': res[0],
'tooltip': res[1],
'state_name': res[1],
}
var leg_opt = self.options && self.options.states_legend || null;
if (leg_opt && leg_opt[res[0]] && self.parent.group.values && self.parent.group.values[leg_opt[res[0]]]) {
value['state_name'] = self.parent.group.values[leg_opt[res[0]]];
}
if (res[0] == 'normal') { value['state_class'] = 'oe_kanban_status'; }
else if (res[0] == 'done') { value['state_class'] = 'oe_kanban_status oe_kanban_status_green'; }
else { value['state_class'] = 'oe_kanban_status oe_kanban_status_red'; }
data.push(value);
});
return data;
},
renderElement: function() {
var self = this;
this.record_id = self.parent.id;
this.states = self.prepare_dropdown_selection();;
this.$el = $(QWeb.render("KanbanSelection", {'widget': self}));
this.$el.find('li').click(self.do_action.bind(self));
},
do_action: function(e) {
var self = this;
var li = $(e.target).closest( "li" );
if (li.length) {
var value = {};
value[self.name] = String(li.data('value'));
return self.parent.view.dataset._model.call('write', [[self.record_id], value, self.parent.view.dataset.get_context()]).done(self.reload_record.bind(self.parent));
}
},
reload_record: function() {
this.do_reload();
},
});
instance.web_kanban.fields_registry = new instance.web.Registry({});
instance.web_kanban.fields_registry.add('priority','instance.web_kanban.Priority');
instance.web_kanban.fields_registry.add('kanban_state_selection','instance.web_kanban.KanbanSelection');
};
// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
| agpl-3.0 |
enviroCar/enviroCar-server | core/src/main/java/org/envirocar/server/core/guice/CoreModule.java | 3305 | /*
* Copyright (C) 2013-2021 The enviroCar project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.envirocar.server.core.guice;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import org.envirocar.server.core.CarSimilarityService;
import org.envirocar.server.core.CarSimilarityServiceImpl;
import org.envirocar.server.core.ConfirmationLinkFactory;
import org.envirocar.server.core.CountService;
import org.envirocar.server.core.CountServiceImpl;
import org.envirocar.server.core.DataService;
import org.envirocar.server.core.DataServiceImpl;
import org.envirocar.server.core.FriendService;
import org.envirocar.server.core.FriendServiceImpl;
import org.envirocar.server.core.GroupService;
import org.envirocar.server.core.GroupServiceImpl;
import org.envirocar.server.core.StatisticsService;
import org.envirocar.server.core.StatisticsServiceImpl;
import org.envirocar.server.core.TermsRepositoryImpl;
import org.envirocar.server.core.TermsRepository;
import org.envirocar.server.core.UserService;
import org.envirocar.server.core.UserServiceImpl;
import org.envirocar.server.core.UserStatisticService;
import org.envirocar.server.core.UserStatisticServiceImpl;
import org.envirocar.server.core.activities.ActivityListener;
import org.envirocar.server.core.util.BCryptPasswordEncoder;
import org.envirocar.server.core.util.GeodesicGeometryOperations;
import org.envirocar.server.core.util.GeometryOperations;
import org.envirocar.server.core.util.PasswordEncoder;
import org.joda.time.DateTimeZone;
/**
* TODO JavaDoc
*
* @author Christian Autermann <autermann@uni-muenster.de>
* @author Arne de Wall
*/
public class CoreModule extends AbstractModule {
@Override
protected void configure() {
bind(DataService.class).to(DataServiceImpl.class);
bind(UserService.class).to(UserServiceImpl.class);
bind(FriendService.class).to(FriendServiceImpl.class);
bind(GroupService.class).to(GroupServiceImpl.class);
bind(StatisticsService.class).to(StatisticsServiceImpl.class);
bind(UserStatisticService.class).to(UserStatisticServiceImpl.class);
bind(ActivityListener.class).asEagerSingleton();
bind(PasswordEncoder.class).to(BCryptPasswordEncoder.class);
bind(GeometryOperations.class).to(GeodesicGeometryOperations.class);
bind(CarSimilarityService.class).to(CarSimilarityServiceImpl.class);
bind(CountService.class).to(CountServiceImpl.class);
DateTimeZone.setDefault(DateTimeZone.UTC);
requireBinding(ConfirmationLinkFactory.class);
bind(TermsRepository.class).to(TermsRepositoryImpl.class).in(Scopes.SINGLETON);
}
}
| agpl-3.0 |
epeios-q37/epeios | apps/esketch/frontend/Dalvik/jni/ui_ssn_frm.cpp | 2347 | /*
'ui_ssn_frm.cpp' by Claude SIMON (http://q37.info/contact/).
This file is part of 'eSketch' software.
'eSketch' 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.
'eSketch' 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 'eSketch'. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ui_ssn_frm.h"
#include "ui.h"
#include "sktinf.h"
#include "trunk.h"
using namespace ui_ssn_frm;
void ui_ssn_frm::backend_type_event_handler__::DVKEVTOnItemSelected(
JNIEnv * Env,
jobject Activity,
jobject View,
bso::uint__ Id )
{
bso::integer_buffer__ Buffer;
LogD( bso::Convert( Id, Buffer ) );
switch ( Id ) {
case 0:
dalvik::Hide( Trunk().UI.SessionForm.Widget.PredefinedBackend.Token(), Env, Activity );
dalvik::Hide( Trunk().UI.SessionForm.Widget.DaemonBackendLocation.Token(), Env, Activity );
break;
case 1:
dalvik::Show( Trunk().UI.SessionForm.Widget.PredefinedBackend.Token(), Env, Activity );
dalvik::Hide( Trunk().UI.SessionForm.Widget.DaemonBackendLocation.Token(), Env, Activity );
break;
case 2:
dalvik::Hide( Trunk().UI.SessionForm.Widget.PredefinedBackend.Token(), Env, Activity );
dalvik::Show( Trunk().UI.SessionForm.Widget.DaemonBackendLocation.Token(), Env, Activity );
break;
case 3:
dalvik::Hide( Trunk().UI.SessionForm.Widget.PredefinedBackend.Token(), Env, Activity );
dalvik::Hide( Trunk().UI.SessionForm.Widget.DaemonBackendLocation.Token(), Env, Activity );
break;
default:
qRGnr();
break;
}
}
void ui_ssn_frm::backend_type_event_handler__::DVKEVTOnNothingSelected(
JNIEnv * Env,
jobject Activity,
jobject View )
{
LogD( "Nothing selected !" );
}
void ui_ssn_frm::session_form__::Show(
JNIEnv *Env,
jobject Activity )
{
LOC
dvkbse::SetContentView( Token(), Activity, Env );
LOC
dvkfev::Install( EventHandler.BackendType, Widget.BackendType.Token(), Activity, Env );
LOC
}
| agpl-3.0 |
axelor/axelor-business-suite | axelor-sale/src/main/java/com/axelor/apps/sale/web/ConfiguratorCreatorController.java | 3717 | /*
* Axelor Business Solutions
*
* Copyright (C) 2020 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.apps.sale.web;
import com.axelor.apps.sale.db.ConfiguratorCreator;
import com.axelor.apps.sale.db.repo.ConfiguratorCreatorRepository;
import com.axelor.apps.sale.service.configurator.ConfiguratorCreatorImportService;
import com.axelor.apps.sale.service.configurator.ConfiguratorCreatorService;
import com.axelor.auth.AuthUtils;
import com.axelor.auth.db.User;
import com.axelor.exception.service.TraceBackService;
import com.axelor.inject.Beans;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import com.google.inject.Singleton;
import java.lang.invoke.MethodHandles;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class ConfiguratorCreatorController {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
/**
* Called from the configurator creator form on formula changes
*
* @param request
* @param response
*/
public void updateAndActivate(ActionRequest request, ActionResponse response) {
ConfiguratorCreator creator = request.getContext().asType(ConfiguratorCreator.class);
ConfiguratorCreatorService configuratorCreatorService =
Beans.get(ConfiguratorCreatorService.class);
creator = Beans.get(ConfiguratorCreatorRepository.class).find(creator.getId());
configuratorCreatorService.updateAttributes(creator);
configuratorCreatorService.updateIndicators(creator);
configuratorCreatorService.activate(creator);
response.setSignal("refresh-app", true);
}
/**
* Called from the configurator creator form on new
*
* @param request
* @param response
*/
public void configure(ActionRequest request, ActionResponse response) {
ConfiguratorCreator creator = request.getContext().asType(ConfiguratorCreator.class);
ConfiguratorCreatorService configuratorCreatorService =
Beans.get(ConfiguratorCreatorService.class);
creator = Beans.get(ConfiguratorCreatorRepository.class).find(creator.getId());
User currentUser = AuthUtils.getUser();
configuratorCreatorService.authorizeUser(creator, currentUser);
try {
configuratorCreatorService.addRequiredFormulas(creator);
} catch (Exception e) {
TraceBackService.trace(e);
response.setError(e.getMessage());
}
response.setReload(true);
}
/**
* Called from configurator creator grid view, on clicking import button. Call {@link
* ConfiguratorCreatorService#importConfiguratorCreators(String)}.
*
* @param request
* @param response
*/
public void importConfiguratorCreators(ActionRequest request, ActionResponse response) {
try {
String pathDiff = (String) ((Map) request.getContext().get("dataFile")).get("filePath");
String importLog =
Beans.get(ConfiguratorCreatorImportService.class).importConfiguratorCreators(pathDiff);
response.setValue("importLog", importLog);
} catch (Exception e) {
TraceBackService.trace(e);
}
}
}
| agpl-3.0 |
lasko2112/legend-of-hondo | MMOCoreORB/bin/scripts/object/weapon/ranged/pistol/pistol_cdef_corsec.lua | 5072 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_weapon_ranged_pistol_pistol_cdef_corsec = object_weapon_ranged_pistol_shared_pistol_cdef_corsec:new {
playerRaces = { "object/creature/player/bothan_male.iff",
"object/creature/player/bothan_female.iff",
"object/creature/player/human_male.iff",
"object/creature/player/human_female.iff",
"object/creature/player/ithorian_male.iff",
"object/creature/player/ithorian_female.iff",
"object/creature/player/moncal_male.iff",
"object/creature/player/moncal_female.iff",
"object/creature/player/rodian_male.iff",
"object/creature/player/rodian_female.iff",
"object/creature/player/sullustan_male.iff",
"object/creature/player/sullustan_female.iff",
"object/creature/player/trandoshan_male.iff",
"object/creature/player/trandoshan_female.iff",
"object/creature/player/twilek_male.iff",
"object/creature/player/twilek_female.iff",
"object/creature/player/wookiee_male.iff",
"object/creature/player/wookiee_female.iff",
"object/creature/player/zabrak_male.iff",
"object/creature/player/zabrak_female.iff" },
-- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK,
-- HEAVYLIGHTNINGBEAMATTACK, HEAVYPARTICLEBEAMATTACK, HEAVYROCKETLAUNCHERATTACK, HEAVYLAUNCHERATTACK
attackType = RANGEDATTACK,
-- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, FORCE, LIGHTSABER
damageType = ENERGY,
-- NONE, LIGHT, MEDIUM, HEAVY
armorPiercing = NONE,
-- combat_rangedspecialize_bactarifle, combat_rangedspecialize_rifle, combat_rangedspecialize_pistol, combat_rangedspecialize_heavy, combat_rangedspecialize_carbine
-- combat_meleespecialize_unarmed, combat_meleespecialize_twohand, combat_meleespecialize_polearm, combat_meleespecialize_onehand, combat_general,
-- combat_meleespecialize_twohandlightsaber, combat_meleespecialize_polearmlightsaber, combat_meleespecialize_onehandlightsaber
xpType = "combat_rangedspecialize_pistol",
-- See http://www.ocdsoft.com/files/certifications.xls
certificationsRequired = { "cert_pistol_cdef" },
-- See http://www.ocdsoft.com/files/accuracy.xls
creatureAccuracyModifiers = { "pistol_accuracy" },
creatureAimModifiers = { "pistol_aim", "aim" },
-- See http://www.ocdsoft.com/files/defense.xls
defenderDefenseModifiers = { "ranged_defense" },
-- Leave as "dodge" for now, may have additions later
defenderSecondaryDefenseModifiers = { "dodge" },
-- See http://www.ocdsoft.com/files/speed.xls
speedModifiers = { "pistol_speed" },
-- Leave blank for now
damageModifiers = { },
-- The values below are the default values. To be used for blue frog objects primarily
healthAttackCost = 10,
actionAttackCost = 22,
mindAttackCost = 10,
forceCost = 0,
pointBlankAccuracy = 0,
pointBlankRange = 0,
idealRange = 15,
idealAccuracy = 15,
maxRange = 45,
maxRangeAccuracy = 5,
minDamage = 17,
maxDamage = 35,
attackSpeed = 4.6,
woundsRatio = 4,
}
ObjectTemplates:addTemplate(object_weapon_ranged_pistol_pistol_cdef_corsec, "object/weapon/ranged/pistol/pistol_cdef_corsec.iff")
| agpl-3.0 |
digilys/digilys | spec/models/group_spec.rb | 8664 | require 'spec_helper'
describe Group do
context "factory" do
subject { build(:group) }
it { should be_valid }
context "invalid" do
subject { build(:invalid_group) }
it { should_not be_valid }
end
end
context "accessible attributes" do
it { should allow_mass_assignment_of(:name) }
it { should allow_mass_assignment_of(:parent_id) }
it { should allow_mass_assignment_of(:instance) }
it { should allow_mass_assignment_of(:instance_id) }
end
context "validation" do
it { should validate_presence_of(:name) }
it { should validate_presence_of(:instance) }
it { should ensure_inclusion_of(:status).in_array(%w(open closed)) }
context ".must_belong_to_parent_instance" do
let(:parent) { create(:group, instance: create(:instance)) }
subject { build(:group, parent: parent) }
it { should allow_value(parent.instance).for(:instance) }
it { should_not allow_value(create(:instance)).for(:instance) }
context "without parent" do
let(:parent) { nil }
it { should allow_value(create(:instance)).for(:instance) }
end
end
end
context "#with_parents" do
let(:parent1) { create(:group, name: "parent1") }
let(:parent2) { create(:group, name: "parent2", parent: parent1) }
let(:parent3) { create(:group, name: "parent3", parent: parent2) }
let(:group) { create(:group, name: "subject", parent: parent3) }
it "does nothing for 0 or less parents" do
expect(Group.with_parents(0).where(id: group.id)).to eq [group]
end
it "makes parents queryable" do
expect(Group.with_parents(2).where(
"parent_1.name" => "parent3",
"parent_2.name" => "parent2"
)).to eq [group]
end
it "joins only n parents" do
expect {
Group.with_parents(1).where(
"parent_2.name" => "parent2"
).all
}.to raise_error(ActiveRecord::StatementInvalid)
end
end
context "#top_level" do
let!(:top_level) { create_list(:group, 3) }
let!(:second_level) { create_list(:group, 3, parent: top_level.first) }
let!(:third_level) { create_list(:group, 3, parent: second_level.second) }
it "only matches groups without parents" do
expect(Group.top_level.all).to match_array(top_level)
end
end
context ".add_students" do
let(:parent1) { create(:group) }
let(:parent2) { create(:group, parent: parent1) }
let(:group) { create(:group, parent: parent2) }
let(:students) { create_list(:student, 2) }
it "adds students to the group" do
group.add_students(students)
expect(group.students).to match_array(students)
end
it "adds the students to the group's parents as well" do
group.add_students(students)
expect(parent1.students(true)).to match_array(students)
expect(parent2.students(true)).to match_array(students)
end
it "handles a single student" do
group.add_students(students.last)
expect(group.students).to eq [students.last]
end
it "does not touch already added students" do
group.add_students(students.first)
group.add_students(students.last)
expect(group.students).to match_array(students)
end
it "handles a string with comma separated student ids" do
group.add_students("#{students.first.id}, #{students.last.id}")
expect(group.students).to match_array(students)
end
it "handles an empty string" do
group.add_students("")
expect(group.students).to be_blank
end
it "does not add duplicates" do
group.add_students(students)
group.add_students(students)
parent1.add_students(students)
parent1.add_students(students)
expect(group.students(true)).to match_array(students)
expect(parent1.students(true)).to match_array(students)
end
it "does not add students from other instances" do
group.add_students(create_list(:student, 2, instance: create(:instance)))
expect(group.students(true)).to be_empty
end
context "automatic participation" do
let!(:parent1_suite) { create(:suite) }
let!(:parent1_participant) { create(:participant, suite: parent1_suite, student: students.first, group: parent1) }
let!(:group_suite) { create(:suite) }
let!(:group_participant) { create(:participant, suite: group_suite, student: students.first, group: group) }
let!(:inactive_suite) { create(:suite, status: :closed) }
let!(:inactive_participant) { create(:participant, suite: inactive_suite, student: students.first, group: group) }
it "adds the users as participants to any active suites the group or the parents, are associated with" do
group.add_students(students.last)
expect(parent1_suite.participants.where(student_id: students.last.id)).to have(1).items
expect(group_suite.participants.where(student_id: students.last.id)).to have(1).items
expect(inactive_suite.participants.where(student_id: students.last.id)).to be_blank
end
end
end
context ".remove_students" do
let(:parent1) { create(:group) }
let(:parent2) { create(:group, parent: parent1) }
let(:group) { create(:group, parent: parent2) }
let(:students) { create_list(:student, 2) }
before(:each) { group.add_students(students) } # Added to parents as well, see specs for .add_students
it "removes students from the group" do
group.remove_students(students)
expect(group.students).to be_blank
end
it "removes the students from the group's parents as well" do
group.remove_students(students)
expect(parent1.students(true)).to be_blank
expect(parent2.students(true)).to be_blank
end
it "removes the students from the group's children as well" do
parent1.remove_students(students)
expect(parent2.students(true)).to be_blank
expect(group.students(true)).to be_blank
end
it "handles a single student" do
group.remove_students(students.first)
expect(group.students).to eq [students.second]
end
it "handles an array of student ids" do
group.remove_students(students.collect(&:id).collect(&:to_s))
expect(group.students).to be_blank
end
context "automatic departicipation" do
let!(:parent1_suite) { create(:suite) }
let!(:parent1_participant) { create(:participant, suite: parent1_suite, student: students.first, group: parent1) }
let!(:parent2_suite) { create(:suite) }
let!(:parent2_participant) { create(:participant, suite: parent2_suite, student: students.first, group: parent2) }
let!(:group_suite) { create(:suite) }
let!(:group_participant) { create(:participant, suite: group_suite, student: students.first, group: group) }
let!(:inactive_suite) { create(:suite, status: :closed) }
let!(:inactive_participant) { create(:participant, suite: inactive_suite, student: students.first, group: group) }
it "removes the users as participants from any active suites the group hierarchy is associated with" do
parent2.remove_students(students.first)
expect(parent1_suite.participants.where(student_id: students.first.id)).to be_blank
expect(parent2_suite.participants.where(student_id: students.first.id)).to be_blank
expect(group_suite.participants.where(student_id: students.first.id)).to be_blank
expect(inactive_suite.participants.where(student_id: students.first.id)).to have(1).items
end
end
end
context ".add_users" do
let(:group) { create(:group) }
let(:users) { create_list(:user, 3) }
it "adds users from a comma separated list of user ids" do
group.add_users(users.collect(&:id).join(","))
expect(group.users(true)).to match_array(users)
end
it "handles an empty string" do
group.add_users("")
expect(group.users(true)).to be_blank
end
it "does not add duplicates" do
group.users << users.first
group.add_users("#{users.first.id},#{users.first.id}")
expect(group.users(true)).to eq [users.first]
end
end
context ".remove_users" do
let(:group) { create(:group) }
let(:users) { create_list(:user, 3) }
before(:each) { group.users = users }
it "removes users from an array of user ids" do
group.remove_users(users.collect(&:id))
expect(group.users(true)).to be_blank
end
it "handles an empty array" do
group.remove_users([])
expect(group.users(true)).to match_array(users)
end
end
end
| agpl-3.0 |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/piexif/_common.py | 1612 | import struct
def split_into_segments(data):
"""Slices JPEG meta data into a list from JPEG binary data.
"""
if data[0:2] != b"\xff\xd8":
raise ValueError("Given data isn't JPEG.")
head = 2
segments = [b"\xff\xd8"]
while 1:
if data[head: head + 2] == b"\xff\xda":
segments.append(data[head:])
break
else:
length = struct.unpack(">H", data[head + 2: head + 4])[0]
endPoint = head + length + 2
seg = data[head: endPoint]
segments.append(seg)
head = endPoint
if (head >= len(data)):
raise ValueError("Wrong JPEG data.")
return segments
def get_app1(segments):
"""Returns Exif from JPEG meta data list
"""
for seg in segments:
if seg[0:2] == b"\xff\xe1":
return seg
return None
def merge_segments(segments, exif=b""):
"""Merges Exif with APP0 and APP1 manipulations.
"""
if segments[1][0:2] == b"\xff\xe0" and segments[2][0:2] == b"\xff\xe1":
if exif:
segments[2] = exif
segments.pop(1)
elif exif is None:
segments.pop(2)
else:
segments.pop(1)
elif segments[1][0:2] == b"\xff\xe0":
if exif:
segments[1] = exif
elif segments[1][0:2] == b"\xff\xe1":
if exif:
segments[1] = exif
elif exif is None:
segments.pop(1)
else:
if exif:
segments.insert(1, exif)
return b"".join(segments)
| agpl-3.0 |
crb02005/SuperGreatDataLayer | application/application.php | 345 | <?php namespace application;
require_once(dirname(__FILE__) .'/../dataLayer/database.connection.php');
abstract class Application{
var $_context;
function __construct(){
$this->setDatabaseConnections();
}
abstract protected function setDatabaseConnections();
public function getConnections(){
return $this->_context;
}
}
?>
| agpl-3.0 |
rfhk/tks-custom | project_view_adjust_tks/models/project_project.py | 258 | # -*- coding: utf-8 -*-
# Copyright 2017 Quartile Limited
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import models
class ProjectProject(models.Model):
_inherit = 'project.project'
_order = "date, sequence, name, id"
| agpl-3.0 |
fomalsd/unitystation | UnityProject/Assets/Mirror/Runtime/NetworkWriter.cs | 17666 | using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using UnityEngine;
namespace Mirror
{
/// <summary>Helper class that weaver populates with all writer types.</summary>
// Note that c# creates a different static variable for each type
// -> Weaver.ReaderWriterProcessor.InitializeReaderAndWriters() populates it
public static class Writer<T>
{
public static Action<NetworkWriter, T> write;
}
/// <summary>Network Writer for most simple types like floats, ints, buffers, structs, etc. Use NetworkWriterPool.GetReader() to avoid allocations.</summary>
public class NetworkWriter
{
public const int MaxStringLength = 1024 * 32;
// create writer immediately with it's own buffer so no one can mess with it and so that we can resize it.
// note: BinaryWriter allocates too much, so we only use a MemoryStream
// => 1500 bytes by default because on average, most packets will be <= MTU
byte[] buffer = new byte[1500];
/// <summary>Next position to write to the buffer</summary>
public int Position;
/// <summary>Reset both the position and length of the stream</summary>
// Leaves the capacity the same so that we can reuse this writer without
// extra allocations
public void Reset()
{
Position = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void EnsureCapacity(int value)
{
if (buffer.Length < value)
{
int capacity = Math.Max(value, buffer.Length * 2);
Array.Resize(ref buffer, capacity);
}
}
/// <summary>Copies buffer until 'Position' to a new array.</summary>
public byte[] ToArray()
{
byte[] data = new byte[Position];
Array.ConstrainedCopy(buffer, 0, data, 0, Position);
return data;
}
/// <summary>Returns allocation-free ArraySegment until 'Position'.</summary>
public ArraySegment<byte> ToArraySegment()
{
return new ArraySegment<byte>(buffer, 0, Position);
}
public void WriteByte(byte value)
{
EnsureCapacity(Position + 1);
buffer[Position++] = value;
}
// for byte arrays with consistent size, where the reader knows how many to read
// (like a packet opcode that's always the same)
public void WriteBytes(byte[] buffer, int offset, int count)
{
EnsureCapacity(Position + count);
Array.ConstrainedCopy(buffer, offset, this.buffer, Position, count);
Position += count;
}
/// <summary>Writes any type that mirror supports. Uses weaver populated Writer(T).write.</summary>
public void Write<T>(T value)
{
Action<NetworkWriter, T> writeDelegate = Writer<T>.write;
if (writeDelegate == null)
{
Debug.LogError($"No writer found for {typeof(T)}. Use a type supported by Mirror or define a custom writer");
}
else
{
writeDelegate(this, value);
}
}
}
// Mirror's Weaver automatically detects all NetworkWriter function types,
// but they do all need to be extensions.
public static class NetworkWriterExtensions
{
// cache encoding instead of creating it with BinaryWriter each time
// 1000 readers before: 1MB GC, 30ms
// 1000 readers after: 0.8MB GC, 18ms
static readonly UTF8Encoding encoding = new UTF8Encoding(false, true);
static readonly byte[] stringBuffer = new byte[NetworkWriter.MaxStringLength];
public static void WriteByte(this NetworkWriter writer, byte value) => writer.WriteByte(value);
public static void WriteSByte(this NetworkWriter writer, sbyte value) => writer.WriteByte((byte)value);
public static void WriteChar(this NetworkWriter writer, char value) => writer.WriteUShort(value);
// Deprecated 2021-05-18
[Obsolete("We've cleaned up the API. Use WriteBool instead.")]
public static void WriteBoolean(this NetworkWriter writer, bool value) => writer.WriteBool(value);
public static void WriteBool(this NetworkWriter writer, bool value) => writer.WriteByte((byte)(value ? 1 : 0));
// Deprecated 2021-05-18
[Obsolete("We've cleaned up the API. Use WriteUShort instead.")]
public static void WriteUInt16(this NetworkWriter writer, ushort value) => writer.WriteUShort(value);
public static void WriteUShort(this NetworkWriter writer, ushort value)
{
writer.WriteByte((byte)value);
writer.WriteByte((byte)(value >> 8));
}
// Deprecated 2021-05-18
[Obsolete("We've cleaned up the API. Use WriteShort instead.")]
public static void WriteInt16(this NetworkWriter writer, short value) => writer.WriteShort(value);
public static void WriteShort(this NetworkWriter writer, short value) => writer.WriteUShort((ushort)value);
// Deprecated 2021-05-18
[Obsolete("We've cleaned up the API. Use WriteUInt instead.")]
public static void WriteUInt32(this NetworkWriter writer, uint value) => writer.WriteUInt(value);
public static void WriteUInt(this NetworkWriter writer, uint value)
{
writer.WriteByte((byte)value);
writer.WriteByte((byte)(value >> 8));
writer.WriteByte((byte)(value >> 16));
writer.WriteByte((byte)(value >> 24));
}
// Deprecated 2021-05-18
[Obsolete("We've cleaned up the API. Use WriteInt instead.")]
public static void WriteInt32(this NetworkWriter writer, int value) => writer.WriteInt(value);
public static void WriteInt(this NetworkWriter writer, int value) => writer.WriteUInt((uint)value);
// Deprecated 2021-05-18
[Obsolete("We've cleaned up the API. Use WriteULong instead.")]
public static void WriteUInt64(this NetworkWriter writer, ulong value) => writer.WriteULong(value);
public static void WriteULong(this NetworkWriter writer, ulong value)
{
writer.WriteByte((byte)value);
writer.WriteByte((byte)(value >> 8));
writer.WriteByte((byte)(value >> 16));
writer.WriteByte((byte)(value >> 24));
writer.WriteByte((byte)(value >> 32));
writer.WriteByte((byte)(value >> 40));
writer.WriteByte((byte)(value >> 48));
writer.WriteByte((byte)(value >> 56));
}
// Deprecated 2021-05-18
[Obsolete("We've cleaned up the API. Use WriteLong instead.")]
public static void WriteInt64(this NetworkWriter writer, long value) => writer.WriteLong(value);
public static void WriteLong(this NetworkWriter writer, long value) => writer.WriteULong((ulong)value);
// Deprecated 2021-05-18
[Obsolete("We've cleaned up the API. Use WriteFloat instead.")]
public static void WriteSingle(this NetworkWriter writer, float value) => writer.WriteFloat(value);
public static void WriteFloat(this NetworkWriter writer, float value)
{
UIntFloat converter = new UIntFloat
{
floatValue = value
};
writer.WriteUInt(converter.intValue);
}
public static void WriteDouble(this NetworkWriter writer, double value)
{
UIntDouble converter = new UIntDouble
{
doubleValue = value
};
writer.WriteULong(converter.longValue);
}
public static void WriteDecimal(this NetworkWriter writer, decimal value)
{
// the only way to read it without allocations is to both read and
// write it with the FloatConverter (which is not binary compatible
// to writer.Write(decimal), hence why we use it here too)
UIntDecimal converter = new UIntDecimal
{
decimalValue = value
};
writer.WriteULong(converter.longValue1);
writer.WriteULong(converter.longValue2);
}
public static void WriteString(this NetworkWriter writer, string value)
{
// write 0 for null support, increment real size by 1
// (note: original HLAPI would write "" for null strings, but if a
// string is null on the server then it should also be null
// on the client)
if (value == null)
{
writer.WriteUShort(0);
return;
}
// write string with same method as NetworkReader
// convert to byte[]
int size = 0;
try
{
size = encoding.GetBytes(value, 0, value.Length, stringBuffer, 0);
}
catch (ArgumentException exception)
{
Debug.LogError("Caught ArguementException in Mirror::NetworkWriter.WriteString() " +
exception.Message);
return;
}
// check if within max size
if (size >= NetworkWriter.MaxStringLength)
{
throw new IndexOutOfRangeException("NetworkWriter.Write(string) too long: " + size + ". Limit: " + NetworkWriter.MaxStringLength);
}
// write size and bytes
writer.WriteUShort(checked((ushort)(size + 1)));
writer.WriteBytes(stringBuffer, 0, size);
}
// for byte arrays with dynamic size, where the reader doesn't know how many will come
// (like an inventory with different items etc.)
public static void WriteBytesAndSize(this NetworkWriter writer, byte[] buffer, int offset, int count)
{
// null is supported because [SyncVar]s might be structs with null byte[] arrays
// write 0 for null array, increment normal size by 1 to save bandwidth
// (using size=-1 for null would limit max size to 32kb instead of 64kb)
if (buffer == null)
{
writer.WriteUInt(0u);
return;
}
writer.WriteUInt(checked((uint)count) + 1u);
writer.WriteBytes(buffer, offset, count);
}
// Weaver needs a write function with just one byte[] parameter
// (we don't name it .Write(byte[]) because it's really a WriteBytesAndSize since we write size / null info too)
public static void WriteBytesAndSize(this NetworkWriter writer, byte[] buffer)
{
// buffer might be null, so we can't use .Length in that case
writer.WriteBytesAndSize(buffer, 0, buffer != null ? buffer.Length : 0);
}
public static void WriteBytesAndSizeSegment(this NetworkWriter writer, ArraySegment<byte> buffer)
{
writer.WriteBytesAndSize(buffer.Array, buffer.Offset, buffer.Count);
}
public static void WriteVector2(this NetworkWriter writer, Vector2 value)
{
writer.WriteFloat(value.x);
writer.WriteFloat(value.y);
}
public static void WriteVector3(this NetworkWriter writer, Vector3 value)
{
writer.WriteFloat(value.x);
writer.WriteFloat(value.y);
writer.WriteFloat(value.z);
}
public static void WriteVector4(this NetworkWriter writer, Vector4 value)
{
writer.WriteFloat(value.x);
writer.WriteFloat(value.y);
writer.WriteFloat(value.z);
writer.WriteFloat(value.w);
}
public static void WriteVector2Int(this NetworkWriter writer, Vector2Int value)
{
writer.WriteInt(value.x);
writer.WriteInt(value.y);
}
public static void WriteVector3Int(this NetworkWriter writer, Vector3Int value)
{
writer.WriteInt(value.x);
writer.WriteInt(value.y);
writer.WriteInt(value.z);
}
public static void WriteColor(this NetworkWriter writer, Color value)
{
writer.WriteFloat(value.r);
writer.WriteFloat(value.g);
writer.WriteFloat(value.b);
writer.WriteFloat(value.a);
}
public static void WriteColor32(this NetworkWriter writer, Color32 value)
{
writer.WriteByte(value.r);
writer.WriteByte(value.g);
writer.WriteByte(value.b);
writer.WriteByte(value.a);
}
public static void WriteQuaternion(this NetworkWriter writer, Quaternion value)
{
writer.WriteFloat(value.x);
writer.WriteFloat(value.y);
writer.WriteFloat(value.z);
writer.WriteFloat(value.w);
}
public static void WriteRect(this NetworkWriter writer, Rect value)
{
writer.WriteFloat(value.xMin);
writer.WriteFloat(value.yMin);
writer.WriteFloat(value.width);
writer.WriteFloat(value.height);
}
public static void WritePlane(this NetworkWriter writer, Plane value)
{
writer.WriteVector3(value.normal);
writer.WriteFloat(value.distance);
}
public static void WriteRay(this NetworkWriter writer, Ray value)
{
writer.WriteVector3(value.origin);
writer.WriteVector3(value.direction);
}
public static void WriteMatrix4x4(this NetworkWriter writer, Matrix4x4 value)
{
writer.WriteFloat(value.m00);
writer.WriteFloat(value.m01);
writer.WriteFloat(value.m02);
writer.WriteFloat(value.m03);
writer.WriteFloat(value.m10);
writer.WriteFloat(value.m11);
writer.WriteFloat(value.m12);
writer.WriteFloat(value.m13);
writer.WriteFloat(value.m20);
writer.WriteFloat(value.m21);
writer.WriteFloat(value.m22);
writer.WriteFloat(value.m23);
writer.WriteFloat(value.m30);
writer.WriteFloat(value.m31);
writer.WriteFloat(value.m32);
writer.WriteFloat(value.m33);
}
public static void WriteGuid(this NetworkWriter writer, Guid value)
{
byte[] data = value.ToByteArray();
writer.WriteBytes(data, 0, data.Length);
}
public static void WriteNetworkIdentity(this NetworkWriter writer, NetworkIdentity value)
{
if (value == null)
{
writer.WriteUInt(0);
return;
}
writer.WriteUInt(value.netId);
}
public static void WriteNetworkBehaviour(this NetworkWriter writer, NetworkBehaviour value)
{
if (value == null)
{
writer.WriteUInt(0);
return;
}
writer.WriteUInt(value.netId);
writer.WriteByte((byte)value.ComponentIndex);
}
public static void WriteTransform(this NetworkWriter writer, Transform value)
{
if (value == null)
{
writer.WriteUInt(0);
return;
}
NetworkIdentity identity = value.GetComponent<NetworkIdentity>();
if (identity != null)
{
writer.WriteUInt(identity.netId);
}
else
{
Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity");
writer.WriteUInt(0);
}
}
public static void WriteGameObject(this NetworkWriter writer, GameObject value)
{
if (value == null)
{
writer.WriteUInt(0);
return;
}
NetworkIdentity identity = value.GetComponent<NetworkIdentity>();
if (identity != null)
{
writer.WriteUInt(identity.netId);
}
else
{
Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity");
writer.WriteUInt(0);
}
}
public static void WriteUri(this NetworkWriter writer, Uri uri)
{
writer.WriteString(uri?.ToString());
}
public static void WriteList<T>(this NetworkWriter writer, List<T> list)
{
if (list is null)
{
writer.WriteInt(-1);
return;
}
writer.WriteInt(list.Count);
for (int i = 0; i < list.Count; i++)
writer.Write(list[i]);
}
public static void WriteArray<T>(this NetworkWriter writer, T[] array)
{
if (array is null)
{
writer.WriteInt(-1);
return;
}
writer.WriteInt(array.Length);
for (int i = 0; i < array.Length; i++)
writer.Write(array[i]);
}
public static void WriteArraySegment<T>(this NetworkWriter writer, ArraySegment<T> segment)
{
int length = segment.Count;
writer.WriteInt(length);
for (int i = 0; i < length; i++)
{
writer.Write(segment.Array[segment.Offset + i]);
}
}
}
}
| agpl-3.0 |
zvini/website | www/scripts/expire-unused-users.php | 685 | #!/usr/bin/php
<?php
chdir(__DIR__);
include_once '../../lib/cli.php';
include_once '../../lib/defaults.php';
include_once '../fns/mysqli_query_object.php';
include_once '../lib/mysqli.php';
$microtime = microtime(true);
$insert_time = time() - 7 * 24 * 60 * 60;
$sql = 'select * from users where num_signins = 0'
." and insert_time < $insert_time limit 10";
$users = mysqli_query_object($mysqli, $sql);
if ($users) {
include_once '../fns/Users/Account/Close/close.php';
foreach ($users as $user) {
Users\Account\Close\close($mysqli, $user);
}
}
$elapsedSeconds = number_format(microtime(true) - $microtime, 3);
echo "Done in $elapsedSeconds seconds.\n";
| agpl-3.0 |
codegram/decidim | decidim-meetings/spec/commands/admin/update_agenda_spec.rb | 2890 | # frozen_string_literal: true
require "spec_helper"
module Decidim::Meetings
describe Admin::UpdateAgenda do
subject { described_class.new(form, agenda) }
let(:agenda_item_child) { create(:agenda_item, :with_parent) }
let(:agenda_item) { agenda_item_child.parent }
let(:agenda) { agenda_item.agenda }
let(:meeting) { agenda.meeting }
let(:organization) { meeting.component.organization }
let(:current_user) { create(:user, :admin, :confirmed, organization: organization) }
let(:deleted) { false }
let(:attributes) do
{
id: agenda.id,
title: { en: "new title" },
visible: true,
agenda_items: [
{
id: agenda_item.id,
title: { en: "new item title" },
description: { en: "new item description" },
position: agenda_item.position,
duration: agenda_item.duration,
parent_id: agenda_item.parent_id,
deleted: false,
agenda_item_children: [
{
id: agenda_item_child.id,
title: { en: "new title child 1" },
description: { en: "new description child 1" },
position: agenda_item_child.position,
duration: agenda_item_child.duration,
parent_id: agenda_item.parent_id,
deleted: deleted
}
]
}
]
}
end
let(:form) do
Admin::MeetingAgendaForm.from_params(
attributes
).with_context(
meeting: meeting,
current_user: current_user,
current_organization: organization
)
end
context "when the form is not valid" do
before do
expect(form).to receive(:valid?).and_return(false)
end
it "is not valid" do
expect { subject.call }.to broadcast(:invalid)
end
end
context "when everything is ok" do
before do
subject.call
end
it "updates the meeting agenda and agenda items" do
expect(translated(agenda.reload.title)).to eq("new title")
expect(translated(agenda_item.reload.title)).to eq("new item title")
expect(translated(agenda_item_child.reload.title)).to eq("new title child 1")
end
context "and an agenda item is removed" do
let(:deleted) { true }
it "removes the agenda item" do
expect(agenda.reload.agenda_items.count).to eq(1)
end
end
it "traces the action", versioning: true do
expect(Decidim.traceability)
.to receive(:update!)
.with(Agenda, current_user, kind_of(Hash))
.and_call_original
expect { subject.call }.to change(Decidim::ActionLog, :count)
action_log = Decidim::ActionLog.last
expect(action_log.version).to be_present
end
end
end
end
| agpl-3.0 |
automenta/java_dann | src/syncleus/dann/learn/bayesian/bif/BIFDefinition.java | 2684 | /*
* Encog(tm) Core v3.2 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2013 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package syncleus.dann.learn.bayesian.bif;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import syncleus.dann.data.file.csv.CSVFormat;
/**
* Holds a BIF definition.
*/
public class BIFDefinition {
private String forDefinition;
private final List<String> givenDefinitions = new ArrayList<>();
private double[] table;
/**
* @return the forDefinition
*/
public String getForDefinition() {
return forDefinition;
}
/**
* @param forDefinition the forDefinition to set
*/
public void setForDefinition(final String forDefinition) {
this.forDefinition = forDefinition;
}
/**
* @return the probability
*/
public double[] getTable() {
return table;
}
/**
* @param s the probability to set
*/
public void setTable(final String s) {
// parse a space separated list of numbers
final StringTokenizer tok = new StringTokenizer(s);
final List<Double> list = new ArrayList<>();
while (tok.hasMoreTokens()) {
final String str = tok.nextToken();
// support both radix formats
if (str.indexOf(',') != -1) {
list.add(CSVFormat.DECIMAL_COMMA.parse(str));
} else {
list.add(CSVFormat.DECIMAL_POINT.parse(str));
}
}
// now copy to regular array
this.table = new double[list.size()];
for (int i = 0; i < this.table.length; i++) {
this.table[i] = list.get(i);
}
}
/**
* @return the givenDefinitions
*/
public List<String> getGivenDefinitions() {
return givenDefinitions;
}
public void addGiven(final String s) {
this.givenDefinitions.add(s);
}
}
| agpl-3.0 |
CanonicalLtd/subiquity | subiquity/common/tests/test_serialization.py | 5604 | # Copyright 2021 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License 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 attr
import random
import string
import typing
import unittest
from subiquity.common.serialize import Serializer
@attr.s(auto_attribs=True)
class Data:
field1: str
field2: int
@staticmethod
def make_random():
return Data(
random.choice(string.ascii_letters),
random.randint(0, 1000))
@attr.s(auto_attribs=True)
class Container:
data: Data
data_list: typing.List[Data]
@staticmethod
def make_random():
return Container(
data=Data.make_random(),
data_list=[Data.make_random()
for i in range(random.randint(10, 20))])
class CommonSerializerTests:
simple_examples = [
(int, 1),
(str, "v"),
(list, [1]),
(dict, {"2": 3}),
(type(None), None),
]
def assertSerializesTo(self, annotation, value, expected):
self.assertEqual(
self.serializer.serialize(annotation, value), expected)
def assertDeserializesTo(self, annotation, value, expected):
self.assertEqual(
self.serializer.deserialize(annotation, value), expected)
def assertRoundtrips(self, annotation, value):
serialized = self.serializer.to_json(annotation, value)
self.assertEqual(
self.serializer.from_json(annotation, serialized), value)
def assertSerialization(self, annotation, value, expected):
self.assertSerializesTo(annotation, value, expected)
self.assertDeserializesTo(annotation, expected, value)
def test_roundtrip_scalars(self):
for typ, val in self.simple_examples:
self.assertRoundtrips(typ, val)
def test_roundtrip_optional(self):
self.assertRoundtrips(typing.Optional[int], None)
self.assertRoundtrips(typing.Optional[int], 1)
def test_roundtrip_list(self):
self.assertRoundtrips(typing.List[str], ["a"])
self.assertRoundtrips(typing.List[int], [23])
def test_roundtrip_attr(self):
self.assertRoundtrips(Data, Data.make_random())
self.assertRoundtrips(Container, Container.make_random())
def test_scalars(self):
for typ, val in self.simple_examples:
self.assertSerialization(typ, val, val)
def test_non_string_key_dict(self):
self.assertRaises(
Exception, self.serializer.serialize, dict, {1: 2})
def test_roundtrip_dict(self):
ann = typing.Dict[int, str]
self.assertRoundtrips(ann, {1: "2"})
def test_roundtrip_dict_strkey(self):
ann = typing.Dict[str, int]
self.assertRoundtrips(ann, {"a": 2})
def test_serialize_dict(self):
self.assertSerialization(typing.Dict[int, str], {1: "a"}, [[1, "a"]])
def test_serialize_dict_strkeys(self):
self.assertSerialization(typing.Dict[str, str], {"a": "b"}, {"a": "b"})
def test_rountrip_union(self):
ann = typing.Union[Data, Container]
self.assertRoundtrips(ann, Data.make_random())
self.assertRoundtrips(ann, Container.make_random())
class TestSerializer(CommonSerializerTests, unittest.TestCase):
serializer = Serializer()
def test_serialize_attr(self):
data = Data.make_random()
expected = {'field1': data.field1, 'field2': data.field2}
self.assertSerialization(Data, data, expected)
def test_serialize_container(self):
data1 = Data.make_random()
data2 = Data.make_random()
container = Container(data1, [data2])
expected = {
'data': {'field1': data1.field1, 'field2': data1.field2},
'data_list': [
{'field1': data2.field1, 'field2': data2.field2},
],
}
self.assertSerialization(Container, container, expected)
def test_serialize_union(self):
data = Data.make_random()
expected = {
'$type': 'Data',
'field1': data.field1,
'field2': data.field2,
}
self.assertSerialization(typing.Union[Data, Container], data, expected)
class TestCompactSerializer(CommonSerializerTests, unittest.TestCase):
serializer = Serializer(compact=True)
def test_serialize_attr(self):
data = Data.make_random()
expected = [data.field1, data.field2]
self.assertSerialization(Data, data, expected)
def test_serialize_container(self):
data1 = Data.make_random()
data2 = Data.make_random()
container = Container(data1, [data2])
expected = [
[data1.field1, data1.field2],
[[data2.field1, data2.field2]],
]
self.assertSerialization(Container, container, expected)
def test_serialize_union(self):
data = Data.make_random()
expected = ['Data', data.field1, data.field2]
self.assertSerialization(typing.Union[Data, Container], data, expected)
| agpl-3.0 |
avikivity/scylla | cdc/generation.hh | 7957 | /*
* Copyright (C) 2019 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 General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
/* This module contains classes and functions used to manage CDC generations:
* sets of CDC stream identifiers used by the cluster to choose partition keys for CDC log writes.
* Each CDC generation begins operating at a specific time point, called the generation's timestamp
* (`cdc_streams_timpestamp` or `streams_timestamp` in the code).
* The generation is used by all nodes in the cluster to pick CDC streams until superseded by a new generation.
*
* Functions from this module are used by the node joining procedure to introduce new CDC generations to the cluster
* (which is necessary due to new tokens being inserted into the token ring), or during rolling upgrade
* if CDC is enabled for the first time.
*/
#pragma once
#include <vector>
#include <unordered_set>
#include <seastar/util/noncopyable_function.hh>
#include "database_fwd.hh"
#include "db_clock.hh"
#include "dht/token.hh"
namespace seastar {
class abort_source;
} // namespace seastar
namespace db {
class config;
class system_distributed_keyspace;
} // namespace db
namespace gms {
class inet_address;
class gossiper;
} // namespace gms
namespace locator {
class token_metadata;
} // namespace locator
namespace cdc {
class stream_id final {
bytes _value;
public:
static constexpr uint8_t version_1 = 1;
stream_id() = default;
stream_id(bytes);
bool is_set() const;
bool operator==(const stream_id&) const;
bool operator!=(const stream_id&) const;
bool operator<(const stream_id&) const;
uint8_t version() const;
size_t index() const;
const bytes& to_bytes() const;
dht::token token() const;
partition_key to_partition_key(const schema& log_schema) const;
static int64_t token_from_bytes(bytes_view);
private:
friend class topology_description_generator;
stream_id(dht::token, size_t);
};
/* Describes a mapping of tokens to CDC streams in a token range.
*
* The range ends with `token_range_end`. A vector of `token_range_description`s defines the ranges entirely
* (the end of the `i`th range is the beginning of the `i+1 % size()`th range). Ranges are left-opened, right-closed.
*
* Tokens in the range ending with `token_range_end` are mapped to streams in the `streams` vector as follows:
* token `T` is mapped to `streams[j]` if and only if the used partitioner maps `T` to the `j`th shard,
* assuming that the partitioner is configured for `streams.size()` shards and (partitioner's) `sharding_ignore_msb`
* equals to the given `sharding_ignore_msb`.
*/
struct token_range_description {
dht::token token_range_end;
std::vector<stream_id> streams;
uint8_t sharding_ignore_msb;
bool operator==(const token_range_description&) const;
};
/* Describes a mapping of tokens to CDC streams in a whole token ring.
*
* Division of the ring to token ranges is defined in terms of `token_range_end`s
* in the `_entries` vector. See the comment above `token_range_description` for explanation.
*/
class topology_description {
std::vector<token_range_description> _entries;
public:
topology_description(std::vector<token_range_description> entries);
bool operator==(const topology_description&) const;
const std::vector<token_range_description>& entries() const;
};
/**
* The set of streams for a single topology version/generation
* I.e. the stream ids at a given time.
*/
class streams_version {
std::vector<stream_id> _streams;
db_clock::time_point _timestamp;
std::optional<db_clock::time_point> _expired;
public:
streams_version(std::vector<stream_id> streams, db_clock::time_point ts, std::optional<db_clock::time_point> expired)
: _streams(std::move(streams))
, _timestamp(ts)
, _expired(std::move(expired))
{}
const db_clock::time_point& timestamp() const {
return _timestamp;
}
const std::optional<db_clock::time_point>& expired() const {
return _expired;
}
const std::vector<stream_id>& streams() const {
return _streams;
}
};
/* Should be called when we're restarting and we noticed that we didn't save any streams timestamp in our local tables,
* which means that we're probably upgrading from a non-CDC/old CDC version (another reason could be
* that there's a bug, or the user messed with our local tables).
*
* It checks whether we should be the node to propose the first generation of CDC streams.
* The chosen condition is arbitrary, it only tries to make sure that no two nodes propose a generation of streams
* when upgrading, and nothing bad happens if they for some reason do (it's mostly an optimization).
*/
bool should_propose_first_generation(const gms::inet_address& me, const gms::gossiper&);
/*
* Read this node's streams generation timestamp stored in the LOCAL table.
* Assumes that the node has successfully bootstrapped, and we're not upgrading from a non-CDC version,
* so the timestamp is present.
*/
future<db_clock::time_point> get_local_streams_timestamp();
/* Generate a new set of CDC streams and insert it into the distributed cdc_generation_descriptions table.
* Returns the timestamp of this new generation.
*
* Should be called when starting the node for the first time (i.e., joining the ring).
*
* Assumes that the system_distributed keyspace is initialized.
*
* The caller of this function is expected to insert this timestamp into the gossiper as fast as possible,
* so that other nodes learn about the generation before their clocks cross the timestmap
* (not guaranteed in the current implementation, but expected to be the common case;
* we assume that `ring_delay` is enough for other nodes to learn about the new generation).
*/
db_clock::time_point make_new_cdc_generation(
const db::config& cfg,
const std::unordered_set<dht::token>& bootstrap_tokens,
const locator::token_metadata& tm,
const gms::gossiper& g,
db::system_distributed_keyspace& sys_dist_ks,
std::chrono::milliseconds ring_delay,
bool for_testing);
/* Retrieves CDC streams generation timestamp from the given endpoint's application state (broadcasted through gossip).
* We might be during a rolling upgrade, so the timestamp might not be there (if the other node didn't upgrade yet),
* but if the cluster already supports CDC, then every newly joining node will propose a new CDC generation,
* which means it will gossip the generation's timestamp.
*/
std::optional<db_clock::time_point> get_streams_timestamp_for(const gms::inet_address& endpoint, const gms::gossiper&);
/* Inform CDC users about a generation of streams (identified by the given timestamp)
* by inserting it into the cdc_streams table.
*
* Assumes that the cdc_generation_descriptions table contains this generation.
*
* Returning from this function does not mean that the table update was successful: the function
* might run an asynchronous task in the background.
*
* Run inside seastar::async context.
*/
void update_streams_description(
db_clock::time_point,
shared_ptr<db::system_distributed_keyspace>,
noncopyable_function<unsigned()> get_num_token_owners,
abort_source&);
} // namespace cdc
| agpl-3.0 |
moshpirit/qvitter | QvitterPlugin.php | 30481 | <?php
/* · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · ·
· ·
· ·
· Q V I T T E R ·
· ·
· http://github.com/hannesmannerheim/qvitter ·
· ·
· ·
· <o) ·
· /_//// ·
· (____/ ·
· (o< ·
· o> \\\\_\ ·
· \\) \____) ·
· ·
· ·
· ·
· Qvitter 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 three of the License or (at ·
· your option) any later version. ·
· ·
· Qvitter is distributed in hope that it will be useful but WITHOUT ANY ·
· WARRANTY; without even the implied warranty of MERCHANTABILTY 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 Qvitter. If not, see <http://www.gnu.org/licenses/>. ·
· ·
· Contact h@nnesmannerhe.im if you have any questions. ·
· ·
· · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · */
const QVITTERDIR = __DIR__;
class QvitterPlugin extends Plugin {
public function settings($setting)
{
/* · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · ·
· ·
· S E T T I N G S ·
· ·
· · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · */
// THESE SETTINGS CAN BE OVERRIDDEN IN CONFIG.PHP
// e.g. $config['site']['qvitter']['enabledbydefault'] = 'false';
// ENABLED BY DEFAULT (true/false)
$settings['enabledbydefault'] = true;
// DEFAULT BACKGROUND COLOR
$settings['defaultbackgroundcolor'] = '#f4f4f4';
// DEFAULT BACKGROUND IMAGE
$settings['sitebackground'] = 'img/vagnsmossen.jpg';
// DEFAULT FAVICON
$settings['favicon'] = 'img/favicon.ico?v=4';
// DEFAULT LINK COLOR
$settings['defaultlinkcolor'] = '#0084B4';
// ENABLE WELCOME TEXT
$settings['enablewelcometext'] = true;
// TIME BETWEEN POLLING
$settings['timebetweenpolling'] = 5000; // ms
// URL SHORTENER
$settings['urlshortenerapiurl'] = 'http://qttr.at/yourls-api.php';
$settings['urlshortenersignature'] = 'b6afeec983';
// CUSTOM TERMS OF USE
$settings['customtermsofuse'] = false;
// IP ADDRESSES BLOCKED FROM REGISTRATION
$settings['blocked_ips'] = array();
/* · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · ·
· ·
· (o> >o) ·
· \\\\_\ /_//// .
· \____) (____/ ·
· ·
· · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · */
// config.php settings override the settings in this file
$configphpsettings = common_config('site','qvitter') ?: array();
foreach($configphpsettings as $configphpsetting=>$value) {
$settings[$configphpsetting] = $value;
}
if(isset($settings[$setting])) {
return $settings[$setting];
}
else {
return false;
}
}
// make sure we have a notifications table
function onCheckSchema()
{
$schema = Schema::get();
$schema->ensureTable('qvitternotification', QvitterNotification::schemaDef());
return true;
}
// route/reroute urls
public function onRouterInitialized($m)
{
$m->connect('api/qvitter/favs_and_repeats/:notice_id.json',
array('action' => 'ApiFavsAndRepeats'),
array('notice_id' => '[0-9]+'));
$m->connect('api/statuses/public_and_external_timeline.:format',
array('action' => 'ApiTimelinePublicAndExternal',
'format' => '(xml|json|rss|atom|as)'));
$m->connect('api/qvitter/update_link_color.json',
array('action' => 'apiqvitterupdatelinkcolor'));
$m->connect('api/qvitter/update_background_color.json',
array('action' => 'apiqvitterupdatebackgroundcolor'));
$m->connect('api/qvitter/checklogin.json',
array('action' => 'apiqvitterchecklogin'));
$m->connect('api/qvitter/allfollowing/:id.json',
array('action' => 'apiqvitterallfollowing',
'id' => Nickname::INPUT_FMT));
$m->connect('api/qvitter/update_cover_photo.json',
array('action' => 'ApiUpdateCoverPhoto'));
$m->connect('api/qvitter/update_background_image.json',
array('action' => 'ApiUpdateBackgroundImage'));
$m->connect('api/qvitter/update_avatar.json',
array('action' => 'ApiUpdateAvatar'));
$m->connect('api/qvitter/upload_image.json',
array('action' => 'ApiUploadImage'));
$m->connect('api/qvitter/external_user_show.json',
array('action' => 'ApiExternalUserShow'));
$m->connect('api/qvitter/toggle_qvitter.json',
array('action' => 'ApiToggleQvitter'));
$m->connect('api/qvitter/statuses/notifications.json',
array('action' => 'apiqvitternotifications'));
$m->connect(':nickname/notifications',
array('action' => 'qvitter',
'nickname' => Nickname::INPUT_FMT));
$m->connect('settings/qvitter',
array('action' => 'qvittersettings'));
$m->connect('panel/qvitter',
array('action' => 'qvitteradminsettings'));
common_config_append('admin', 'panels', 'qvitteradm');
$m->connect('main/qlogin',
array('action' => 'qvitterlogin'));
// check if we should reroute UI to qvitter
$logged_in_user = common_current_user();
$qvitter_enabled_by_user = false;
$qvitter_disabled_by_user = false;
if($logged_in_user) {
try {
$qvitter_enabled_by_user = Profile_prefs::getData($logged_in_user->getProfile(), 'qvitter', 'enable_qvitter');
} catch (NoResultException $e) {
$qvitter_enabled_by_user = false;
}
try {
$qvitter_disabled_by_user = Profile_prefs::getData($logged_in_user->getProfile(), 'qvitter', 'disable_qvitter');
} catch (NoResultException $e) {
$qvitter_disabled_by_user = false;
}
}
if((self::settings('enabledbydefault') && !$logged_in_user) ||
(self::settings('enabledbydefault') && !$qvitter_disabled_by_user) ||
(!self::settings('enabledbydefault') && $qvitter_enabled_by_user)) {
$m->connect('', array('action' => 'qvitter'));
$m->connect('main/all', array('action' => 'qvitter'));
$m->connect('search/notice', array('action' => 'qvitter'));
URLMapperOverwrite::overwrite_variable($m, ':nickname',
array('action' => 'showstream'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, ':nickname/',
array('action' => 'showstream'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, ':nickname/all',
array('action' => 'all'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, ':nickname/subscriptions',
array('action' => 'subscriptions'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, ':nickname/subscribers',
array('action' => 'subscribers'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, ':nickname/groups',
array('action' => 'usergroups'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, ':nickname/replies',
array('action' => 'replies'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, ':nickname/favorites',
array('action' => 'showfavorites'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, 'group/:nickname',
array('action' => 'showgroup'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, 'group/:nickname/members',
array('action' => 'groupmembers'),
array('nickname' => Nickname::DISPLAY_FMT),
'qvitter');
$m->connect('group/:nickname/admins',
array('action' => 'qvitter'),
array('nickname' => Nickname::DISPLAY_FMT));
URLMapperOverwrite::overwrite_variable($m, 'tag/:tag',
array('action' => 'showstream'),
array('tag' => Router::REGEX_TAG),
'qvitter');
URLMapperOverwrite::overwrite_variable($m, 'notice/:notice',
array('action' => 'shownotice'),
array('notice' => '[0-9]+'),
'qvitter');
}
// if qvitter is opt-out, disable the default register page (if we don't have a valid invitation code)
if(isset($_POST['code'])) {
$valid_code = Invitation::getKV('code', $_POST['code']);
}
if(self::settings('enabledbydefault') && empty($valid_code)) {
$m->connect('main/register',
array('action' => 'qvitter'));
}
}
/**
* Add script to default ui, to be able to toggle Qvitter with one click
*
* @return boolean hook return
*/
function onEndShowScripts($action){
if (common_logged_in()) {
$user = common_current_user();
$profile = $user->getProfile();
$qvitter_enabled='false';
// if qvitter is enabled by default but _not_ disabled by the user,
if(QvitterPlugin::settings('enabledbydefault')) {
$disabled = Profile_prefs::getConfigData($profile, 'qvitter', 'disable_qvitter');
if($disabled == 0) {
$qvitter_enabled='true';
}
}
// if qvitter is disabled by default and _enabled_ by the user,
else {
$enabled = Profile_prefs::getConfigData($profile, 'qvitter', 'enable_qvitter');
if($enabled == 1) {
$qvitter_enabled='true';
}
}
$action->inlineScript(' var toggleQvitterAPIURL = \''.common_path('', true).'api/qvitter/toggle_qvitter.json\';
var toggleText = \'New '.str_replace("'","\'",common_config('site','name')).'\';
var qvitterEnabled = '.$qvitter_enabled.';
var qvitterAllLink = \''.common_local_url('all', array('nickname' => $user->nickname)).'\';
');
$action->script($this->path('js/toggleqvitter.js').'?changed='.date('YmdHis',filemtime(QVITTERDIR.'/js/toggleqvitter.js')));
}
}
/**
* User colors in default UI too, if theme is neo-quitter
*
* @return boolean hook return
*/
function onEndShowStylesheets($action) {
$theme = common_config('site','theme');
if (common_logged_in() && substr($theme,0,11) == 'neo-quitter') {
$user = common_current_user();
$profile = $user->getProfile();
$backgroundcolor = Profile_prefs::getConfigData($profile, 'theme', 'backgroundcolor');
if(!$backgroundcolor) {
$backgroundcolor = substr(QvitterPlugin::settings('defaultbackgroundcolor'),1);
}
$linkcolor = Profile_prefs::getConfigData($profile, 'theme', 'linkcolor');
if(!$linkcolor) {
$linkcolor = substr(QvitterPlugin::settings('defaultlinkcolor'),1);
}
$ligthen_elements = '';
if($this->darkness($backgroundcolor)<0.5) {
$ligthen_elements = "
#nav_profile a:before,
#nav_timeline_replies a:before,
#nav_timeline_personal a:before,
#nav_local_default li:first-child ul.nav li:nth-child(4) a:before,
#nav_timeline_favorites a:before,
#nav_timeline_public a:before,
#nav_groups a:before,
#nav_recent-tags a:before,
#nav_timeline_favorited a:before,
#nav_directory a:before,
#nav_lists a:before,
#site_nav_local_views h3,
#content h1,
#aside_primary h2,
#gnusocial-version p,
#page_notice,
#pagination .nav_next a {
color:rgba(255,255,255,0.4);
}
.nav li.current a:before,
.entity_actions a {
color: rgba(255,255,255, 0.6) !important;
}
#aside_primary,
.entity_edit a:before,
.entity_remote_subscribe:before,
#export_data a:before,
.peopletags_edit_button:before,
.form_group_join:before,
.form_group_leave:before,
.form_group_delete:before,
#site_nav_object li.current a,
#pagination .nav_next a:hover,
#content .guide {
color: rgba(255,255,255, 0.6);
}
#site_nav_local_views a,
#site_nav_object a,
#aside_primary a:not(.invite_button) {
color: rgba(255,255,255, 0.7);
}
#site_nav_local_views li.current a,
.entity_edit a:hover:before,
.entity_remote_subscribe:hover:before,
.peopletags_edit_button:hover:before,
.form_group_join:hover:before,
.form_group_leave:hover:before,
.form_group_delete:hover:before {
color: rgba(255,255,255, 0.8);
}
#site_nav_local_views li.current a {
background-position: -3px 1px;
}
#site_nav_local_views li a:hover {
background-position:-3px -24px;
}
#gnusocial-version,
#pagination .nav_next a {
border-color: rgba(255,255,255, 0.3);
}
#pagination .nav_next a:hover {
border-color: rgba(255,255,255, 0.5);
}
#site_nav_object li.current a {
background-position: -3px 2px;
}
#site_nav_object li a:hover {
background-position: -3px -23px;
}
";
}
$action->style("
body {
background-color:#".$backgroundcolor.";
}
a,
a:hover,
a:active,
#site_nav_global_primary a:hover,
.threaded-replies .notice-faves:before,
.threaded-replies .notice-repeats:before,
.notice-reply-comments > a:before,
#content .notices > .notice > .entry-metadata .conversation {
color:#".$linkcolor.";
}
#site_nav_global_primary a:hover {
border-color:#".$linkcolor.";
}
address {
background-color:#".$linkcolor.";
}
".$ligthen_elements);
}
}
/**
* Menu item for Qvitter
*
* @param Action $action action being executed
*
* @return boolean hook return
*/
function onEndAccountSettingsNav($action)
{
$action_name = $action->trimmed('action');
$action->menuItem(common_local_url('qvittersettings'),
// TRANS: Poll plugin menu item on user settings page.
_m('MENU', 'Qvitter'),
// TRANS: Poll plugin tooltip for user settings menu item.
_m('Enable/Disable Qvitter UI'),
$action_name === 'qvittersettings');
return true;
}
/**
* Menu item for admin panel
*
* @param Action $action action being executed
*
* @return boolean hook return
*/
function onEndAdminPanelNav($action)
{
$action_name = $action->trimmed('action');
$action->out->menuItem(common_local_url('qvitteradminsettings'),
// TRANS: Poll plugin menu item on user settings page.
_m('MENU', 'Qvitter'),
// TRANS: Poll plugin tooltip for user settings menu item.
_m('Qvitter Sidebar Notice'),
$action_name === 'qvitteradminsettings');
return true;
}
/**
* Add stuff to notices in API responses
*
* @param Action $action action being executed
*
* @return boolean hook return
*/
function onNoticeSimpleStatusArray($notice, &$twitter_status, $scoped)
{
// groups
$notice_groups = $notice->getGroups();
$group_addressees = false;
foreach($notice_groups as $g) {
$group_addressees = array('nickname'=>$g->nickname,'url'=>$g->mainpage);
}
$twitter_status['statusnet_in_groups'] = $group_addressees;
// include the repeat-id, which we need when unrepeating later
if(array_key_exists('repeated', $twitter_status) && $twitter_status['repeated'] === true) {
$repeated = Notice::pkeyGet(array('profile_id' => $scoped->id,
'repeat_of' => $notice->id));
$twitter_status['repeated_id'] = $repeated->id;
}
// thumb urls
// find all thumbs
$attachments = $notice->attachments();
$attachment_url_to_id = array();
if (!empty($attachments)) {
foreach ($attachments as $attachment) {
try {
$enclosure_o = $attachment->getEnclosure();
$thumb = $attachment->getThumbnail();
$attachment_url_to_id[$enclosure_o->url]['id'] = $attachment->id;
$attachment_url_to_id[$enclosure_o->url]['thumb_url'] = $thumb->getUrl();
} catch (ServerException $e) {
$thumb = File_thumbnail::getKV('file_id', $attachment->id);
if ($thumb instanceof File_thumbnail) {
$attachment_url_to_id[$enclosure_o->url]['id'] = $attachment->id;
$attachment_url_to_id[$enclosure_o->url]['thumb_url'] = $thumb->getUrl();
}
}
}
}
// add thumbs to $twitter_status
if (!empty($twitter_status['attachments'])) {
foreach ($twitter_status['attachments'] as &$attachment) {
if (!empty($attachment_url_to_id[$attachment['url']])) {
$attachment['id'] = $attachment_url_to_id[$attachment['url']]['id'];
// if the attachment is other than image, and we have a thumb (e.g. videos),
// we include the default thumbnail url
if(substr($attachment['mimetype'],0,5) != 'image') {
$attachment['thumb_url'] = $attachment_url_to_id[$attachment['url']]['thumb_url'];
}
}
}
}
// reply-to profile url
$twitter_status['in_reply_to_profileurl'] = null;
if ($notice->reply_to) {
$reply = Notice::getKV(intval($notice->reply_to));
if ($reply) {
$replier_profile = $reply->getProfile();
$twitter_status['in_reply_to_profileurl'] = $replier_profile->profileurl;
}
}
// some more metadata about notice
if($notice->is_local == '1') {
$twitter_status['is_local'] = true;
}
else {
$twitter_status['is_local'] = false;
$twitter_status['external_url'] = $notice->getUrl(true);
}
if($notice->object_type == 'activity') {
$twitter_status['is_activity'] = true;
}
else {
$twitter_status['is_activity'] = false;
}
return true;
}
/**
* Cover photo in API response, also follows_you, etc
*
* @return boolean hook return
*/
function onTwitterUserArray($profile, &$twitter_user, $scoped)
{
$twitter_user['cover_photo'] = Profile_prefs::getConfigData($profile, 'qvitter', 'cover_photo');
$twitter_user['background_image'] = Profile_prefs::getConfigData($profile, 'qvitter', 'background_image');
// follows me?
if ($scoped) {
$twitter_user['follows_you'] = $profile->isSubscribed($scoped);
}
// local user?
$twitter_user['is_local'] = $profile->isLocal();
return true;
}
/**
* Insert into notification table
*/
function insertNotification($to_profile_id, $from_profile_id, $ntype, $notice_id=false)
{
// never notify myself
if($to_profile_id != $from_profile_id) {
// insert
$notif = new QvitterNotification();
$notif->to_profile_id = $to_profile_id;
$notif->from_profile_id = $from_profile_id;
$notif->ntype = $ntype;
$notif->notice_id = $notice_id;
$notif->created = common_sql_now();
if (!$notif->insert()) {
common_log_db_error($notif, 'INSERT', __FILE__);
return false;
}
}
return true;
}
/**
* Insert likes in notification table
*/
public function onEndFavorNotice($profile, $notice)
{
// don't notify people favoriting their own notices
if($notice->profile_id != $profile->id) {
$this->insertNotification($notice->profile_id, $profile->id, 'like', $notice->id);
}
}
/**
* Remove likes in notification table on dislike
*/
public function onEndDisfavorNotice($profile, $notice)
{
$notif = new QvitterNotification();
$notif->from_profile_id = $profile->id;
$notif->notice_id = $notice->id;
$notif->ntype = 'like';
$notif->delete();
return true;
}
/**
* Insert notifications for replies, mentions and repeats
*
* @return boolean hook flag
*/
function onStartNoticeDistribute($notice) {
// don't add notifications for activity type notices
if($notice->object_type == 'activity') {
return true;
}
// repeats
if ($notice->isRepeat()) {
$repeated_notice = Notice::getKV('id', $notice->repeat_of);
if ($repeated_notice instanceof Notice) {
$this->insertNotification($repeated_notice->profile_id, $notice->profile_id, 'repeat', $repeated_notice->id);
}
}
// replies and mentions (no notifications for these if this is a repeat)
else {
$reply_notification_to = false;
// check for reply to insert in notifications
if($notice->reply_to) {
$replyparent = $notice->getParent();
$replyauthor = $replyparent->getProfile();
if ($replyauthor instanceof Profile && !empty($notice->id)) {
$reply_notification_to = $replyauthor->id;
$this->insertNotification($replyauthor->id, $notice->profile_id, 'reply', $notice->id);
}
}
// check for mentions to insert in notifications
$mentions = common_find_mentions($notice->content, $notice);
$sender = Profile::getKV($notice->profile_id);
foreach ($mentions as $mention) {
foreach ($mention['mentioned'] as $mentioned) {
// Not from blocked profile
$mentioned_user = User::getKV('id', $mentioned->id);
if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
continue;
}
// only notify if mentioned user is not already notified for reply
if($reply_notification_to != $mentioned->id && !empty($notice->id)) {
$this->insertNotification($mentioned->id, $notice->profile_id, 'mention', $notice->id);
}
}
}
}
return true;
}
/**
* Delete any notifications tied to deleted notices and un-repeats
*
* @return boolean hook flag
*/
public function onNoticeDeleteRelated($notice)
{
$notif = new QvitterNotification();
// unrepeats
if ($notice->isRepeat()) {
$repeated_notice = Notice::getKV('id', $notice->repeat_of);
$notif->notice_id = $repeated_notice->id;
$notif->from_profile_id = $notice->profile_id;
}
// notices
else {
$notif->notice_id = $notice->id;
}
$notif->delete();
return true;
}
/**
* Add notification on subscription, remove on unsubscribe
*
* @return boolean hook flag
*/
public function onEndSubscribe($subscriber, $other)
{
if(Subscription::exists($subscriber, $other)) {
$this->insertNotification($other->id, $subscriber->id, 'follow', 1);
}
return true;
}
public function onEndUnsubscribe($subscriber, $other)
{
if(!Subscription::exists($subscriber, $other)) {
$notif = new QvitterNotification();
$notif->to_profile_id = $other->id;
$notif->from_profile_id = $subscriber->id;
$notif->ntype = 'follow';
$notif->delete();
}
return true;
}
/**
* Replace GNU Social's default FAQ with Qvitter's
*
* @return boolean hook flag
*/
public function onEndLoadDoc($title, &$output)
{
if($title == 'faq') {
$faq = file_get_contents(QVITTERDIR.'/doc/en/faq.html');
$faq = str_replace('{instance-name}',common_config('site','name'),$faq);
$faq = str_replace('{instance-url}',common_config('site','server'),$faq);
$faq = str_replace('{instance-url-with-protocol}',common_path('', true),$faq);
if (common_logged_in()) {
$user = common_current_user();
$faq = str_replace('{nickname}',$user->nickname,$faq);
}
$output = $faq;
}
return true;
}
/**
* Add menu items to top header in Classic
*
* @return boolean hook flag
*/
public function onStartPrimaryNav($action)
{
$action->menuItem(common_local_url('doc', array('title' => 'faq')),
// TRANS: Menu item in primary navigation panel.
_m('MENU','FAQ'),
// TRANS: Menu item title in primary navigation panel.
_('Frequently asked questions'),
false,
'top_nav_doc_faq');
return true;
}
/**
* No registration for blocked ips
*
* @return boolean hook flag
*/
public function onStartUserRegister($profile)
{
if(is_array(self::settings("blocked_ips"))) {
if(in_array($_SERVER['REMOTE_ADDR'], self::settings("blocked_ips"))) {
return false;
}
}
return true;
}
/**
* Add unread notification count to all API responses
*
* @return boolean hook flag
*/
public function onEndSetApiUser($user) {
if (!$user instanceof User) {
return true;
}
$user_id = $user->id;
$notification = new QvitterNotification();
$notification->selectAdd();
$notification->selectAdd('ntype');
$notification->selectAdd('count(id) as count');
$notification->whereAdd("(to_profile_id = '".$user_id."')");
$notification->groupBy('ntype');
$notification->whereAdd("(is_seen = '0')");
$notification->whereAdd("(notice_id IS NOT NULL)"); // sometimes notice_id is NULL, those notifications are corrupt and should be discarded
$notification->find();
$new_notifications = array();
while ($notification->fetch()) {
$new_notifications[$notification->ntype] = $notification->count;
}
header('Qvitter-Notifications: '.json_encode($new_notifications));
return true;
}
function onPluginVersion(&$versions)
{
$versions[] = array('name' => 'Qvitter',
'version' => '4',
'author' => 'Hannes Mannerheim',
'homepage' => 'https://github.com/hannesmannerheim/qvitter',
'rawdescription' => _m('User interface'));
return true;
}
function darkness($hex) {
$r = hexdec($hex[0].$hex[1]);
$g = hexdec($hex[2].$hex[3]);
$b = hexdec($hex[4].$hex[5]);
return (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
}
}
/**
* Overwrites variables in URL-mapping
*
*/
class URLMapperOverwrite extends URLMapper
{
function overwrite_variable($m, $path, $args, $paramPatterns, $newaction)
{
$m->connect($path, array('action' => $newaction), $paramPatterns);
$regex = URLMapper::makeRegex($path, $paramPatterns);
foreach($m->variables as $n=>$v)
if($v[1] == $regex)
$m->variables[$n][0]['action'] = $newaction;
}
}
?>
| agpl-3.0 |
tailuge/chess-o-tron | generate/gulpfile.js | 1027 | var source = require('vinyl-source-stream');
var gulp = require('gulp');
var gutil = require('gulp-util');
var watchify = require('watchify');
var browserify = require('browserify');
var sources = ['./src/main.js'];
var destination = '../public/compiled/';
var onError = function(error) {
gutil.log(gutil.colors.red(error.message));
};
var standalone = 'Trainer';
gulp.task('dev', function() {
return browserify('./src/main.js', {
standalone: standalone
}).bundle()
.on('error', onError)
.pipe(source('app-util.js'))
.pipe(gulp.dest(destination));
});
gulp.task('watch', function() {
var opts = watchify.args;
opts.debug = true;
opts.standalone = standalone;
var bundleStream = watchify(browserify(sources, opts))
.on('update', rebundle)
.on('log', gutil.log);
function rebundle() {
return bundleStream.bundle()
.on('error', onError)
.pipe(source('app-util.js'))
.pipe(gulp.dest(destination));
}
return rebundle();
});
gulp.task('default', ['watch']);
| agpl-3.0 |
frankban/charmstore | internal/blobstore/swift.go | 3116 | // Copyright 2017 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package blobstore // import "gopkg.in/juju/charmstore.v5-unstable/internal/blobstore"
import (
"fmt"
"io"
"strconv"
"github.com/juju/loggo"
"gopkg.in/errgo.v1"
"gopkg.in/goose.v2/client"
"gopkg.in/goose.v2/errors"
"gopkg.in/goose.v2/identity"
"gopkg.in/goose.v2/swift"
)
type swiftBackend struct {
client *swift.Client
container string
}
// NewSwiftBackend returns a backend which uses OpenStack's Swift for
// its operations with the given credentials and auth mode. It stores
// all the data objects in the container with the given name.
func NewSwiftBackend(cred *identity.Credentials, authmode identity.AuthMode, container string) Backend {
c := client.NewClient(cred,
authmode,
gooseLogger{},
)
c.SetRequiredServiceTypes([]string{"object-store"})
return &swiftBackend{
client: swift.New(c),
container: container,
}
}
func (s *swiftBackend) Get(name string) (r ReadSeekCloser, size int64, err error) {
// Use infinite read-ahead here as the goose implementation of
// byte range handling seems to differ from swift's.
r2, headers, err := s.client.OpenObject(s.container, name, -1)
if err != nil {
if errors.IsNotFound(err) {
return nil, 0, errgo.WithCausef(nil, ErrNotFound, "")
}
return nil, 0, errgo.Mask(err)
}
lengthstr := headers.Get("Content-Length")
size, err = strconv.ParseInt(lengthstr, 10, 64)
return swiftBackendReader{r2.(ReadSeekCloser)}, size, err
}
func (s *swiftBackend) Put(name string, r io.Reader, size int64, hash string) error {
h := NewHash()
r2 := io.TeeReader(r, h)
err := s.client.PutReader(s.container, name, r2, size)
if err != nil {
// TODO: investigate if PutReader can return err but the object still be
// written. Should there be cleanup here?
return errgo.Mask(err)
}
if hash != fmt.Sprintf("%x", h.Sum(nil)) {
err := s.client.DeleteObject(s.container, name)
if err != nil {
logger.Errorf("could not delete object from container after a hash mismatch was detected: %v", err)
}
return errgo.New("hash mismatch")
}
return nil
}
func (s *swiftBackend) Remove(name string) error {
err := s.client.DeleteObject(s.container, name)
if err != nil && errors.IsNotFound(err) {
return errgo.WithCausef(nil, ErrNotFound, "")
}
return errgo.Mask(err)
}
// swiftBackendReader translates not-found errors as
// produced by Swift into not-found errors as expected
// by the Backend.Get interface contract.
type swiftBackendReader struct {
ReadSeekCloser
}
func (r swiftBackendReader) Read(buf []byte) (int, error) {
n, err := r.ReadSeekCloser.Read(buf)
if err == nil || err == io.EOF {
return n, err
}
if errors.IsNotFound(err) {
return n, errgo.WithCausef(nil, ErrNotFound, "")
}
return n, errgo.Mask(err)
}
// gooseLogger implements the logger interface required
// by goose, using the loggo logger to do the actual
// logging.
// TODO: Patch goose to use loggo directly.
type gooseLogger struct{}
func (gooseLogger) Printf(f string, a ...interface{}) {
logger.LogCallf(2, loggo.DEBUG, f, a...)
}
| agpl-3.0 |
acontes/scheduling | src/common/org/ow2/proactive/utils/appenders/FileAppender.java | 3820 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* 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, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.utils.appenders;
import java.io.IOException;
import java.util.Enumeration;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.spi.LoggingEvent;
/**
*
* An appender that redirects logging events to different files
* depending on "filename" property in log4j context.
*
* Is used to put server logs for tasks and jobs into files with
* different names.
*
*/
public class FileAppender extends WriterAppender {
// property from log4j configuration
public static final String FILES_LOCATION = "FilesLocation";
public static final String FILE_NAME = "filename";
protected String filesLocation;
public FileAppender() {
setLayout(new PatternLayout("[%d{ISO8601} %-5p] %m%n"));
// trying to get a layout from log4j configuration
Enumeration<?> en = Logger.getRootLogger().getAllAppenders();
if (en != null && en.hasMoreElements()) {
Appender app = (Appender) en.nextElement();
if (app != null && app.getLayout() != null) {
Logger.getRootLogger().info("Retrieved layout from log4j configuration");
setLayout(app.getLayout());
}
}
}
@Override
public void append(LoggingEvent event) {
Object value = MDC.getContext().get(FILE_NAME);
if (value != null) {
append(value.toString(), event);
}
}
public void append(String fileName, LoggingEvent event) {
if (filesLocation != null) {
fileName = filesLocation + fileName;
}
try {
org.apache.log4j.FileAppender appender = new org.apache.log4j.FileAppender(getLayout(), fileName,
true);
appender.append(event);
appender.close();
} catch (IOException e) {
Logger.getRootLogger().error(e.getMessage(), e);
e.printStackTrace();
}
}
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
return true;
}
public String getFilesLocation() {
return filesLocation;
}
public void setFilesLocation(String filesLocation) {
this.filesLocation = filesLocation;
}
}
| agpl-3.0 |
xdite/Airesis | db/seeds/122_airesis_seed.rb | 13240 | #encoding: utf-8
Comune.create(:description => "Altivole", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 6122)
Comune.create(:description => "Arcade", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3440)
Comune.create(:description => "Asolo", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7605)
Comune.create(:description => "Borso Del Grappa", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4935)
Comune.create(:description => "Breda Di Piave", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 6348)
Comune.create(:description => "Caerano Di San Marco", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7027)
Comune.create(:description => "Cappella Maggiore", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4412)
Comune.create(:description => "Carbonera", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9804)
Comune.create(:description => "Casale Sul Sile", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9461)
Comune.create(:description => "Casier", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 8935)
Comune.create(:description => "Castelcucco", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 1871)
Comune.create(:description => "Castelfranco Veneto", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 31486)
Comune.create(:description => "Castello Di Godego", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 6347)
Comune.create(:description => "Cavaso Del Tomba", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 2675)
Comune.create(:description => "Cessalto", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3134)
Comune.create(:description => "Chiarano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3114)
Comune.create(:description => "Cimadolmo", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3327)
Comune.create(:description => "Cison Di Valmarino", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 2553)
Comune.create(:description => "Colle Umberto", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4572)
Comune.create(:description => "Conegliano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 35100)
Comune.create(:description => "Cordignano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 6374)
Comune.create(:description => "Cornuda", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 5730)
Comune.create(:description => "Crespano Del Grappa", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4328)
Comune.create(:description => "Crocetta Del Montello", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 5709)
Comune.create(:description => "Farra Di Soligo", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7892)
Comune.create(:description => "Follina", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3646)
Comune.create(:description => "Fontanelle", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 5471)
Comune.create(:description => "Fonte", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 5479)
Comune.create(:description => "Fregona", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 2927)
Comune.create(:description => "Gaiarine", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 6161)
Comune.create(:description => "Giavera Del Montello", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4318)
Comune.create(:description => "Gorgo Al Monticano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3977)
Comune.create(:description => "Istrana", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7763)
Comune.create(:description => "Loria", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7764)
Comune.create(:description => "Mareno Di Piave", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7870)
Comune.create(:description => "Maser", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4846)
Comune.create(:description => "Maserada Sul Piave", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7575)
Comune.create(:description => "Meduna Di Livenza", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 2702)
Comune.create(:description => "Miane", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3416)
Comune.create(:description => "Mogliano Veneto", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 26322)
Comune.create(:description => "Monastier Di Treviso", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3554)
Comune.create(:description => "Monfumo", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 1428)
Comune.create(:description => "Montebelluna", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 27539)
Comune.create(:description => "Morgano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3754)
Comune.create(:description => "Moriago Della Battaglia", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 2627)
Comune.create(:description => "Motta Di Livenza", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9657)
Comune.create(:description => "Nervesa Della Battaglia", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 6653)
Comune.create(:description => "Oderzo", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 17316)
Comune.create(:description => "Ormelle", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4087)
Comune.create(:description => "Orsago", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3598)
Comune.create(:description => "Paderno Del Grappa", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 2002)
Comune.create(:description => "Paese", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 18407)
Comune.create(:description => "Pederobba", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7061)
Comune.create(:description => "Pieve Di Soligo", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 10673)
Comune.create(:description => "Ponte Di Piave", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7128)
Comune.create(:description => "Ponzano Veneto", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9783)
Comune.create(:description => "Possagno", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 2029)
Comune.create(:description => "Povegliano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4109)
Comune.create(:description => "Preganziol", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 14706)
Comune.create(:description => "Quinto Di Treviso", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9288)
Comune.create(:description => "Refrontolo", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 1805)
Comune.create(:description => "Resana", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7491)
Comune.create(:description => "Revine Lago", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 2119)
Comune.create(:description => "Riese Pio X", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9627)
Comune.create(:description => "Roncade", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 11911)
Comune.create(:description => "Salgareda", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 5574)
Comune.create(:description => "San Biagio Di Callalta", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 11439)
Comune.create(:description => "San Fior", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 6153)
Comune.create(:description => "San Pietro Di Feletto", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4890)
Comune.create(:description => "San Polo Di Piave", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4536)
Comune.create(:description => "San Vendemiano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 8776)
Comune.create(:description => "San Zenone Degli Ezzelini", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 6506)
Comune.create(:description => "Santa Lucia Di Piave", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 7226)
Comune.create(:description => "Sarmede", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3004)
Comune.create(:description => "Segusino", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 1980)
Comune.create(:description => "Sernaglia Della Battaglia", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 5799)
Comune.create(:description => "Silea", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9114)
Comune.create(:description => "Spresiano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9251)
Comune.create(:description => "Susegana", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 10754)
Comune.create(:description => "Tarzo", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4537)
Comune.create(:description => "Trevignano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9074)
Comune.create(:description => "Treviso", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 80144)
Comune.create(:description => "Valdobbiadene", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 10624)
Comune.create(:description => "Vazzola", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 6405)
Comune.create(:description => "Vedelago", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 13826)
Comune.create(:description => "Vidor", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 3405)
Comune.create(:description => "Villorba", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 16921)
Comune.create(:description => "Vittorio Veneto", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 29184)
Comune.create(:description => "Volpago Del Montello", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 9084)
Comune.create(:description => "Zenson Di Piave", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 1694)
Comune.create(:description => "Zero Branco", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 8581)
Comune.create(:description => "Codogne'", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 5068)
Comune.create(:description => "Godega Di Sant'Urbano", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 5954)
Comune.create(:description => "Mansue'", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 4132)
Comune.create(:description => "Portobuffole'", :provincia_id => 69, :regione_id => 17, stato_id: 1, continente_id: 1 , :population => 739)
| agpl-3.0 |
florianprobst/vms | src/Model/Entity/Flangetype.php | 679 | <?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* Flangetype Entity
*
* @property int $id
* @property string $bezeichnung
*
* @property \App\Model\Entity\Valf[] $valves
*/
class Flangetype extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $_accessible = [
'*' => true,
'id' => false
];
}
| agpl-3.0 |
lasko2112/legend-of-hondo | MMOCoreORB/bin/scripts/mobile/quest/corellia/corran_horn.lua | 796 | corran_horn = Creature:new {
objectName = "@npc_name:human_base_male",
customName = "Corran Horn",
socialGroup = "townsperson",
faction = "townsperson",
level = 100,
chanceHit = 1,
damageMin = 645,
damageMax = 1000,
baseXp = 9429,
baseHAM = 24000,
baseHAMmax = 30000,
armor = 0,
resists = {0,0,0,0,0,0,0,0,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = PACK,
optionsBitmask = 136,
diet = HERBIVORE,
templates = {"object/mobile/dressed_corran_horn.iff"},
lootGroups = {},
weapons = {},
conversationTemplate = "corran_horn_mission_giver_convotemplate",
attacks = {
}
}
CreatureTemplates:addCreatureTemplate(corran_horn, "corran_horn") | agpl-3.0 |
andreas-p/nextcloud-server | apps/files_sharing/lib/Scanner.php | 2458 | <?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Vincent Petry <pvince81@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Sharing;
use OC\Files\ObjectStore\NoopScanner;
/**
* Scanner for SharedStorage
*/
class Scanner extends \OC\Files\Cache\Scanner {
/**
* @var \OCA\Files_Sharing\SharedStorage $storage
*/
protected $storage;
private $sourceScanner;
/**
* Returns metadata from the shared storage, but
* with permissions from the source storage.
*
* @param string $path path of the file for which to retrieve metadata
*
* @return array an array of metadata of the file
*/
public function getData($path) {
$data = parent::getData($path);
if ($data === null) {
return null;
}
$internalPath = $this->storage->getUnjailedPath($path);
$data['permissions'] = $this->storage->getSourceStorage()->getPermissions($internalPath);
return $data;
}
private function getSourceScanner() {
if ($this->sourceScanner) {
return $this->sourceScanner;
}
if ($this->storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
/** @var \OC\Files\Storage\Storage $storage */
list($storage) = $this->storage->resolvePath('');
$this->sourceScanner = $storage->getScanner();
return $this->sourceScanner;
} else {
return null;
}
}
public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true, $data = null) {
$sourceScanner = $this->getSourceScanner();
if ($sourceScanner instanceof NoopScanner) {
return [];
} else {
return parent::scanFile($file, $reuseExisting, $parentId, $cacheData, $lock);
}
}
}
| agpl-3.0 |
ProtocolSupport/ProtocolSupport | src/protocolsupport/protocol/packet/middle/impl/serverbound/play/v_4_5_6_7_8/AbstractMoveLook.java | 1137 | package protocolsupport.protocol.packet.middle.impl.serverbound.play.v_4_5_6_7_8;
import protocolsupport.protocol.packet.middle.base.serverbound.ServerBoundMiddlePacket;
import protocolsupport.protocol.packet.middle.base.serverbound.play.MiddleMoveLook;
import protocolsupport.protocol.packet.middle.base.serverbound.play.MiddleTeleportAccept;
import protocolsupport.protocol.storage.netcache.MovementCache;
public abstract class AbstractMoveLook extends ServerBoundMiddlePacket {
protected AbstractMoveLook(IMiddlePacketInit init) {
super(init);
}
protected final MovementCache movementCache = cache.getMovementCache();
protected double x;
protected double y;
protected double z;
protected float yaw;
protected float pitch;
protected boolean onGround;
@Override
protected void write() {
int teleportId = movementCache.tryTeleportConfirm(x, y, z);
if (teleportId == -1) {
io.writeServerbound(MiddleMoveLook.create(x, y, z, yaw, pitch, onGround));
} else {
io.writeServerbound(MiddleTeleportAccept.create(teleportId));
io.writeServerbound(MiddleMoveLook.create(x, y, z, yaw, pitch, onGround));
}
}
}
| agpl-3.0 |
andreicristianpetcu/cotam | config/application.rb | 982 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Cotam
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
| agpl-3.0 |
printedheart/opennars | nars_lab_x/nars_scala/src/main/scala/nars/gui/TermWindow.scala | 1962 | package nars.gui
import java.awt._
import java.awt.event._
import nars.logic.entity.Concept
import nars.storage.Memory
//remove if not needed
import scala.collection.JavaConversions._
/**
* Window accept a Term, then display the content of the corresponding Concept
*/
class TermWindow(var memory: Memory) extends NarsFrame("Term Window") with ActionListener {
/**
Display label
*/
private var termLabel: Label = new Label("Term:", Label.RIGHT)
/**
Input field for term name
*/
private var termField: TextField = new TextField("")
/**
Control buttons
*/
private var playButton: Button = new Button("Show")
private var hideButton: Button = new Button("Hide")
// super("Term Window")
setBackground(NarsFrame.SINGLE_WINDOW_COLOR)
val gridbag = new GridBagLayout()
val c = new GridBagConstraints()
setLayout(gridbag)
c.ipadx = 3
c.ipady = 3
c.insets = new Insets(5, 5, 5, 5)
c.fill = GridBagConstraints.BOTH
c.gridwidth = 1
c.weightx = 0.0
c.weighty = 0.0
termLabel.setBackground(NarsFrame.SINGLE_WINDOW_COLOR)
gridbag.setConstraints(termLabel, c)
add(termLabel)
c.weightx = 1.0
gridbag.setConstraints(termField, c)
add(termField)
c.weightx = 0.0
playButton.addActionListener(this)
gridbag.setConstraints(playButton, c)
add(playButton)
hideButton.addActionListener(this)
gridbag.setConstraints(hideButton, c)
add(hideButton)
setBounds(400, 0, 400, 100)
/**
* Handling button click
* @param e The ActionEvent
*/
def actionPerformed(e: ActionEvent) {
val b = e.getSource.asInstanceOf[Button]
if (b == playButton) {
val concept = memory.nameToConcept(termField.getText.trim())
if (concept != null) {
concept.startPlay(true)
}
} else if (b == hideButton) {
close()
}
}
private def close() {
setVisible(false)
}
override def windowClosing(arg0: WindowEvent) {
close()
}
}
| agpl-3.0 |
papyrussolution/OpenPapyrus | Src/OSF/icu/tools/multi/proj/icu4jscan/src/com/ibm/icu/dev/scan/CapNode.java | 359 | // © 2017 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/* Copyright (C) 2008-2012 IBM Corporation and Others. All Rights Reserved. */
package com.ibm.icu.dev.scan;
import java.io.PrintWriter;
public interface CapNode extends Comparable {
void write(PrintWriter pw, int i);
String getName();
}
| agpl-3.0 |
denkbar/djigger | client-ui/src/main/java/io/djigger/ui/SessionListener.java | 1141 | /*******************************************************************************
* (C) Copyright 2016 Jérôme Comte and Dorian Cransac
*
* This file is part of djigger
*
* djigger 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.
*
* djigger 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 djigger. If not, see <http://www.gnu.org/licenses/>.
*
*******************************************************************************/
package io.djigger.ui;
import io.djigger.agent.InstrumentationError;
public interface SessionListener {
public void subscriptionChange();
public void instrumentationError(InstrumentationError error);
}
| agpl-3.0 |
dshatrov/momentvideo | moment-rtmp/moment-rtmp/rtmpt_service.cpp | 32725 | /* Copyright (C) 2011-2014 Dmitry Shatrov - All Rights Reserved
e-mail: info@momentvideo.org
Unauthorized copying of this file or any part of its contents,
via any medium is strictly prohibited.
Proprietary and confidential.
*/
#include <moment-rtmp/rtmpt_service.h>
//#warning There's' some problem with session lifetime (results in hangs on mutex unlock).
// TODO Current RTMPT implementation is not secure enough.
// Hint: Don't put commas after *HEADERS macros when using them.
#define RTMPT_SERVICE__HEADERS_DATE \
Byte date_buf [unixtimeToString_BufSize]; \
Size const date_len = unixtimeToString (Memory::forObject (date_buf), getUnixtime());
#define RTMPT_SERVICE__COMMON_HEADERS(keepalive) \
"Server: Moment/1.0\r\n" \
"Date: ", ConstMemory (date_buf, date_len), "\r\n" \
"Connection: ", (keepalive) ? "Keep-Alive" : "Close", "\r\n" \
"Cache-Control: no-cache\r\n"
#define RTMPT_SERVICE__OK_HEADERS(keepalive) \
"HTTP/1.", ((keepalive) ? "1" : "1"), " 200 OK\r\n" \
RTMPT_SERVICE__COMMON_HEADERS(keepalive)
#define RTMPT_SERVICE__FCS_OK_HEADERS(keepalive) \
RTMPT_SERVICE__OK_HEADERS(keepalive) \
"Content-Type: application/x-fcs\r\n" \
#define RTMPT_SERVICE__404_HEADERS(keepalive) \
"HTTP/1.", (keepalive) ? "1" : "1", " 404 Not found\r\n" \
RTMPT_SERVICE__COMMON_HEADERS(keepalive) \
"Content-Type: text/plain\r\n" \
"Content-Length: 0\r\n"
#define RTMPT_SERVICE__400_HEADERS(keepalive) \
"HTTP/1.", (keepalive) ? "1" : "1", " 400 Bad Request\r\n" \
RTMPT_SERVICE__COMMON_HEADERS(keepalive) \
"Content-Type: text/plain\r\n" \
"Content-Length: 0\r\n"
using namespace M;
namespace Moment {
static LogGroup libMary_logGroup_rtmpt ("rtmpt", LogLevel::I);
RtmpConnection::Backend const RtmptService::rtmp_conn_backend = {
rtmpClosed
};
mt_async void
RtmptService::RtmptSender::sendMessage (SenderMessageEntry * const mt_nonnull msg_entry,
bool const do_flush)
{
mutex.lock ();
sendMessage_locked (msg_entry, do_flush);
mutex.unlock ();
}
mt_async void
RtmptService::RtmptSender::sendMessage (SenderMessageEntry * const mt_nonnull msg_entry,
bool const do_flush,
SenderStateCallback * const /* sender_state_cb */,
void * const /* sender_state_cb_data */)
{
mutex.lock ();
sendMessage_locked (msg_entry, do_flush);
// TODO Implement queue limits and sender states.
mutex.unlock ();
}
mt_mutex (mutex) void
RtmptService::RtmptSender::sendMessage_locked (SenderMessageEntry * const mt_nonnull msg_entry,
bool const do_flush)
{
nonflushed_msg_list.append (msg_entry);
nonflushed_data_len += msg_entry->getTotalMsgLen();
if (do_flush)
doFlush ();
}
mt_mutex (mutex) void
RtmptService::RtmptSender::doFlush ()
{
pending_msg_list.stealAppend (nonflushed_msg_list.getFirst(), nonflushed_msg_list.getLast());
pending_data_len += nonflushed_data_len;
nonflushed_msg_list.clear();
nonflushed_data_len = 0;
}
mt_async void
RtmptService::RtmptSender::flush ()
{
mutex.lock ();
doFlush ();
mutex.unlock ();
}
mt_mutex (mutex) void
RtmptService::RtmptSender::flush_locked ()
{
doFlush ();
}
mt_async void
RtmptService::RtmptSender::closeAfterFlush ()
{
mutex.lock ();
close_after_flush = true;
mutex.unlock ();
}
mt_async void
RtmptService::RtmptSender::close ()
{
closeAfterFlush ();
}
mt_mutex (mutex) bool
RtmptService::RtmptSender::isClosed_locked ()
{
return false;
}
mt_mutex (mutex) SenderState
RtmptService::RtmptSender::getSenderState_locked ()
{
//#warning RTMPT sender state is always ConnectionReady. Queue limits MUST be implemented (that's critical for VOD).
return SenderState::ConnectionReady;
}
mt_mutex (mutex) void
RtmptService::RtmptSender::sendPendingData (Sender * const mt_nonnull sender)
{
SenderMessageEntry_MessageList::iter iter (pending_msg_list);
while (!pending_msg_list.iter_done (iter)) {
SenderMessageEntry * const msg_entry = pending_msg_list.iter_next (iter);
sender->sendMessage (msg_entry, false /* do_flush */);
}
pending_msg_list.clear ();
pending_data_len = 0;
}
RtmptService::RtmptSender::RtmptSender (EmbedContainer * const embed_container)
: Sender (embed_container),
nonflushed_data_len (0),
pending_data_len (0),
close_after_flush (false)
{
}
mt_async
RtmptService::RtmptSender::~RtmptSender ()
{
mutex.lock ();
{
SenderMessageEntry_MessageList::iter iter (nonflushed_msg_list);
while (!nonflushed_msg_list.iter_done (iter)) {
SenderMessageEntry * const msg_entry = nonflushed_msg_list.iter_next (iter);
msg_entry->release ();
}
}
{
SenderMessageEntry_MessageList::iter iter (pending_msg_list);
while (!pending_msg_list.iter_done (iter)) {
SenderMessageEntry * const msg_entry = pending_msg_list.iter_next (iter);
msg_entry->release ();
}
}
mutex.unlock ();
}
RtmptService::RtmptSession::~RtmptSession ()
{
Ref<RtmptService> const rtmpt_service = weak_rtmpt_service.getRef ();
rtmpt_service->num_session_objects.dec ();
}
RtmptService::RtmptConnection::~RtmptConnection ()
{
Ref<RtmptService> const rtmpt_service = weak_rtmpt_service.getRef ();
rtmpt_service->num_connection_objects.dec ();
}
void
RtmptService::sessionKeepaliveTimerTick (void * const _session)
{
RtmptSession * const session = static_cast <RtmptSession*> (_session);
Ref<RtmptService> const self = session->weak_rtmpt_service.getRef ();
if (!self)
return;
self->mutex.lock ();
if (!session->valid) {
self->mutex.unlock ();
return;
}
Time const cur_time = getTime();
if (cur_time >= session->last_msg_time &&
cur_time - session->last_msg_time > self->session_keepalive_timeout)
{
logD (rtmpt, _func, "RTMPT session timeout");
mt_unlocks (mutex) self->destroyRtmptSession (session, true /* close_rtmp_conn */);
} else {
self->mutex.unlock ();
}
}
void
RtmptService::connKeepaliveTimerTick (void * const _rtmpt_conn)
{
RtmptConnection * const rtmpt_conn = static_cast <RtmptConnection*> (_rtmpt_conn);
Ref<RtmptService> const self = rtmpt_conn->weak_rtmpt_service.getRef ();
if (!self)
return;
self->mutex.lock ();
if (!rtmpt_conn->valid) {
self->mutex.unlock ();
return;
}
Time const cur_time = getTime();
if (cur_time >= rtmpt_conn->last_msg_time &&
cur_time - rtmpt_conn->last_msg_time > self->conn_keepalive_timeout)
{
logD (rtmpt, _func, "RTMPT connection timeout");
mt_unlocks (mutex) self->doConnectionClosed (rtmpt_conn);
} else {
self->mutex.unlock ();
}
}
mt_unlocks (mutex) void
RtmptService::destroyRtmptSession (RtmptSession * const mt_nonnull session,
bool const close_rtmp_conn)
{
if (!session->valid) {
mutex.unlock ();
return;
}
session->valid = false;
if (session->session_keepalive_timer) {
server_ctx->getMainThreadContext()->getTimers()->deleteTimer (session->session_keepalive_timer);
session->session_keepalive_timer = NULL;
}
Ref<RtmptSession> tmp_session = session;
if (!session->session_map_entry.isNull()) {
session_map.remove (session->session_map_entry);
--num_valid_sessions;
}
mutex.unlock ();
if (close_rtmp_conn) {
tmp_session->rtmp_conn->close_noBackendCb ();
tmp_session = NULL; // last unref
}
}
mt_mutex (mutex) void
RtmptService::destroyRtmptConnection (RtmptConnection * const mt_nonnull rtmpt_conn)
{
if (!rtmpt_conn->valid) {
return;
}
rtmpt_conn->valid = false;
--num_valid_connections;
logI (rtmpt, _func, "closed, rtmpt_conn 0x", fmt_hex, (UintPtr) rtmpt_conn);
Ref<ServerThreadContext> const thread_ctx = rtmpt_conn->weak_thread_ctx.getRef ();
if (thread_ctx) {
if (rtmpt_conn->conn_keepalive_timer) {
thread_ctx->getTimers()->deleteTimer (rtmpt_conn->conn_keepalive_timer);
rtmpt_conn->conn_keepalive_timer = NULL;
}
if (rtmpt_conn->pollable_key) {
thread_ctx->getPollGroup()->removePollable (rtmpt_conn->pollable_key);
rtmpt_conn->pollable_key = NULL;
}
}
conn_list.remove (rtmpt_conn);
rtmpt_conn->unref ();
}
mt_unlocks (mutex) void
RtmptService::doConnectionClosed (RtmptConnection * const mt_nonnull rtmpt_conn)
{
destroyRtmptConnection (rtmpt_conn);
mutex.unlock ();
#if 0
// Too early to close the connection. It is still in use.
// In particular, it is very likely that processInput() is yet to be called
// for this connection.
rtmpt_conn->conn->close ();
#endif
}
mt_async void
RtmptService::rtmpClosed (DisconnectReason const disconnect_reason,
void * const _session)
{
RtmptSession * const session = static_cast <RtmptSession*> (_session);
Ref<RtmptService> const self = session->weak_rtmpt_service.getRef ();
if (!self)
return;
self->mutex.lock ();
mt_unlocks (mutex) self->destroyRtmptSession (session, false /* close_rtmp_conn */);
}
void
RtmptService::sendDataInReply (Sender * const mt_nonnull conn_sender,
RtmptSession * const mt_nonnull session)
{
session->rtmpt_sender->mutex.lock ();
RTMPT_SERVICE__HEADERS_DATE
conn_sender->send (
page_pool,
false /* do_flush */,
RTMPT_SERVICE__FCS_OK_HEADERS(!no_keepalive_conns)
"Content-Length: ", 1 /* idle interval */ + session->rtmpt_sender->pending_data_len, "\r\n"
"\r\n",
// TODO Variable idle intervals.
"\x09");
session->rtmpt_sender->sendPendingData (conn_sender);
conn_sender->flush ();
if (session->rtmpt_sender->close_after_flush)
session->closed = true;
session->rtmpt_sender->mutex.unlock ();
#if 0
// We're not destroying the session immediately, since more requests may arrive
// from the client for this session. The session is expected to time out eventually.
// If close after flush has been requested for session->rtmpt_sender, then
// virtual RTMP connection should be closed, hence we're destroying the session.
if (destroy_session) {
mutex.lock ();
mt_unlocks (mutex) destroyRtmptSession (session, true /* close_rtmp_conn */);
}
#endif
}
void
RtmptService::doOpen (Sender * const mt_nonnull conn_sender,
IpAddress const client_addr)
{
Ref<RtmptSession> const session = grab (new (std::nothrow) RtmptSession (NULL /* embed_conatiner */));
num_session_objects.inc ();
session->session_info.creation_unixtime = getUnixtime();
session->valid = true;
session->closed = false;
session->weak_rtmpt_service = this;
session->last_msg_time = getTime();
// TODO Do not allow more than one external IP address for a single session.
// ^^^ Maybe configurable, disallowed by default.
session->session_info.last_client_addr = client_addr;
session->session_id = session_id_counter;
++session_id_counter;
session->rtmp_conn->init (NULL /* dump_stream */,
server_ctx->getMainThreadContext()->getTimers(),
page_pool,
0 /* send_delay_millisec */,
rtmp_ping_timeout_millisec,
false /* momentrtmp_proto */);
session->rtmp_conn->setBackend (
CbDesc<RtmpConnection::Backend> (&rtmp_conn_backend, session, session));
session->rtmp_conn->setSender (session->rtmpt_sender);
{
Result res = Result::Failure;
bool const call_res =
frontend.call_ret (&res, frontend->clientConnected,
/*(*/ session->rtmp_conn.ptr(), client_addr /*)*/);
if (!call_res || !res) {
session->rtmp_conn->close_noBackendCb ();
RTMPT_SERVICE__HEADERS_DATE
conn_sender->send (
page_pool,
true /* do_flush */,
RTMPT_SERVICE__404_HEADERS(!no_keepalive_conns)
"\r\n");
return;
}
}
mutex.lock ();
// The session might have been invalidated by rtmpClose().
if (!session->valid) {
mutex.unlock ();
RTMPT_SERVICE__HEADERS_DATE
conn_sender->send (
page_pool,
true /* do_flush */,
RTMPT_SERVICE__404_HEADERS(!no_keepalive_conns)
"\r\n");
return;
}
session->session_map_entry = session_map.add (session);
++num_valid_sessions;
{
// Checking for session timeout at least each 10 seconds.
Time const timeout = (session_keepalive_timeout >= 10 ? 10 : session_keepalive_timeout);
session->session_keepalive_timer =
server_ctx->getMainThreadContext()->getTimers()->addTimer (
CbDesc<Timers::TimerCallback> (sessionKeepaliveTimerTick,
session,
session /* coderef_container */),
timeout,
true /* periodical */,
false /* auto_delete */);
}
mutex.unlock ();
RTMPT_SERVICE__HEADERS_DATE
conn_sender->send (
page_pool,
true /* do_flush */,
RTMPT_SERVICE__FCS_OK_HEADERS(!no_keepalive_conns)
"Content-Length: ", toString (Memory(), session->session_id) + 1 /* for \n */, "\r\n"
"\r\n",
session->session_id,
"\n");
}
Ref<RtmptService::RtmptSession>
RtmptService::doSend (Sender * const mt_nonnull conn_sender,
Uint32 const session_id,
RtmptConnection * const rtmpt_conn)
{
mutex.lock ();
SessionMap::Entry const session_entry = session_map.lookup (session_id);
Ref<RtmptSession> session;
if (!session_entry.isNull()) {
session = session_entry.getData();
if (session->closed)
logD_ (_func, "Session closed: ", session_id);
} else {
logD_ (_func, "Session not found: ", session_id);
}
if (session_entry.isNull()
|| session->closed)
{
mutex.unlock ();
RTMPT_SERVICE__HEADERS_DATE
conn_sender->send (
page_pool,
true /* do_flush */,
RTMPT_SERVICE__404_HEADERS(!no_keepalive_conns)
"\r\n");
return NULL;
}
{
Time const cur_time = getTime();
session->last_msg_time = cur_time;
if (rtmpt_conn)
rtmpt_conn->last_msg_time = cur_time;
}
mutex.unlock ();
sendDataInReply (conn_sender, session);
return session;
}
void
RtmptService::doClose (Sender * const mt_nonnull conn_sender,
Uint32 const session_id)
{
mutex.lock ();
SessionMap::Entry const session_entry = session_map.lookup (session_id);
if (session_entry.isNull()) {
mutex.unlock ();
logD_ (_func, "Session not found: ", session_id);
RTMPT_SERVICE__HEADERS_DATE
conn_sender->send (
page_pool,
true /* do_flush */,
RTMPT_SERVICE__404_HEADERS(!no_keepalive_conns)
"\r\n");
return;
}
Ref<RtmptSession> const session = session_entry.getData();
mt_unlocks (mutex) destroyRtmptSession (session, true /* close_rtmp_conn */);
RTMPT_SERVICE__HEADERS_DATE
conn_sender->send (
page_pool,
true /* do_flush */,
RTMPT_SERVICE__OK_HEADERS(!no_keepalive_conns)
"Content-Type: text/plain\r\n"
"Content-Length: 0\r\n"
"\r\n");
}
Ref<RtmptService::RtmptSession>
RtmptService::doHttpRequest (HttpRequest * const mt_nonnull req,
Sender * const mt_nonnull conn_sender,
RtmptConnection * const rtmpt_conn)
{
logD (rtmpt, _func, req->getRequestLine());
ConstMemory const command = req->getPath (0);
if (equal (command, "send")) {
Uint32 const session_id = strToUlong (req->getPath (1));
return doSend (conn_sender, session_id, rtmpt_conn);
} else
if (equal (command, "idle")) {
Uint32 const session_id = strToUlong (req->getPath (1));
doSend (conn_sender, session_id, rtmpt_conn);
} else
if (equal (command, "open")) {
doOpen (conn_sender, req->getClientAddress());
} else
if (equal (command, "close")) {
Uint32 const session_id = strToUlong (req->getPath (1));
doClose (conn_sender, session_id);
} else {
if (!equal (command, "fcs"))
logW_ (_func, "uknown command: ", command);
RTMPT_SERVICE__HEADERS_DATE
conn_sender->send (
page_pool,
true /* do_flush */,
RTMPT_SERVICE__400_HEADERS (!no_keepalive_conns)
"\r\n");
}
return NULL;
}
HttpServer::Frontend const RtmptService::http_frontend = {
NULL /* rawData */,
httpRequest,
httpMessageBody,
httpClosed
};
mt_async void
RtmptService::httpRequest (HttpRequest * const mt_nonnull req,
bool * const mt_nonnull /* ret_block_input */,
void * const _rtmpt_conn)
{
RtmptConnection * const rtmpt_conn = static_cast <RtmptConnection*> (_rtmpt_conn);
Ref<RtmptService> const self = rtmpt_conn->weak_rtmpt_service.getRef ();
if (!self)
return;
rtmpt_conn->cur_req_session = NULL;
Ref<RtmptSession> const session = self->doHttpRequest (req, rtmpt_conn->conn_sender, rtmpt_conn);
if (session && req->hasBody())
rtmpt_conn->cur_req_session = session;
if (!req->getKeepalive() || self->no_keepalive_conns)
rtmpt_conn->conn_sender->closeAfterFlush ();
}
mt_async void
RtmptService::httpMessageBody (HttpRequest * const mt_nonnull /* req */,
Memory const mem,
bool const /* end_of_request */,
Size * const mt_nonnull ret_accepted,
bool * const mt_nonnull /* ret_block_input */,
void * const _rtmpt_conn)
{
RtmptConnection * const rtmpt_conn = static_cast <RtmptConnection*> (_rtmpt_conn);
Ref<RtmptService> const self = rtmpt_conn->weak_rtmpt_service.getRef ();
if (!self)
return;
RtmptSession * const session = rtmpt_conn->cur_req_session;
if (!session) {
*ret_accepted = mem.len();
return;
}
// 'cur_req_session' is not null, which means that we're processing
// message body of a "/send" request.
// Note that we don't check 'cur_req_session->valid' here because
// that would require an extra mutex lock. Calling rtmp_conn.doProcessInput()
// for an invalid session should be harmless.
Size accepted;
Receiver::ProcessInputResult res;
{
session->rtmp_input_mutex.lock ();
res = session->rtmp_conn->doProcessInput (mem, &accepted);
session->rtmp_input_mutex.unlock ();
}
if (res == Receiver::ProcessInputResult::Error) {
logE_ (_func, "failed to parse RTMP data: ", toString (res));
self->mutex.lock ();
mt_unlocks (mutex) self->destroyRtmptSession (session, true /* close_rtmp_conn */);
rtmpt_conn->cur_req_session = NULL;
*ret_accepted = mem.len();
} else {
// RtmpConnection::doProcessInput() never returns InputBlocked.
assert (res != Receiver::ProcessInputResult::InputBlocked);
*ret_accepted = accepted;
}
}
mt_async void
RtmptService::httpClosed (HttpRequest * const /* req */,
Exception * const exc_,
void * const _rtmpt_conn)
{
if (exc_)
logE_ (_func, "exception: ", exc_->toString());
RtmptConnection * const rtmpt_conn = static_cast <RtmptConnection*> (_rtmpt_conn);
Ref<RtmptService> const self = rtmpt_conn->weak_rtmpt_service.getRef ();
if (!self)
return;
self->mutex.lock ();
mt_unlocks (mutex) self->doConnectionClosed (rtmpt_conn);
}
HttpService::HttpHandler const RtmptService::http_handler = {
service_httpRequest,
service_httpMessageBody
};
Result
RtmptService::service_httpRequest (HttpRequest * const mt_nonnull req,
HttpService::HttpConnectionInfo * const mt_nonnull /* conn_info */,
IpAddress const /* local_addr */,
Sender * const mt_nonnull conn_sender,
Memory const /* msg_body */,
void ** const mt_nonnull ret_msg_data,
void * const _self)
{
RtmptService * const self = static_cast <RtmptService*> (_self);
Ref<RtmptSession> session = self->doHttpRequest (req, conn_sender, NULL /* rtmpt_conn */);
if (session && req->hasBody()) {
*ret_msg_data = session;
session.setNoUnref ((RtmptSession*) NULL);
}
if (!req->getKeepalive() || self->no_keepalive_conns)
conn_sender->closeAfterFlush ();
return Result::Success;
}
// Almost identical to httpMessaggeBody()
Result
RtmptService::service_httpMessageBody (HttpRequest * const mt_nonnull /* req */,
HttpService::HttpConnectionInfo * const mt_nonnull /* conn_info */,
Sender * const mt_nonnull /* conn_sender */,
Memory const mem,
bool const end_of_request,
Size * const mt_nonnull ret_accepted,
void * const _session,
void * const _self)
{
RtmptService * const self = static_cast <RtmptService*> (_self);
RtmptSession * const session = static_cast <RtmptSession*> (_session);
if (!session) {
*ret_accepted = mem.len();
return Result::Success;
}
// 'cur_req_session' is not null, which means that we're processing
// message body of a "/send" request.
// Note that we don't check 'cur_req_session->valid' here because
// that would require an extra mutex lock. Calling rtmp_conn.doProcessInput()
// for an invalid session should be harmless.
Size accepted;
Receiver::ProcessInputResult res;
{
session->rtmp_input_mutex.lock ();
res = session->rtmp_conn->doProcessInput (mem, &accepted);
session->rtmp_input_mutex.unlock ();
}
if (res == Receiver::ProcessInputResult::Error) {
logE_ (_func, "failed to parse RTMP data: ", toString (res));
self->mutex.lock ();
mt_unlocks (mutex) self->destroyRtmptSession (session, true /* close_rtmp_conn */);
*ret_accepted = mem.len();
} else {
// RtmpConnection::doProcessInput() never returns InputBlocked.
assert (res != Receiver::ProcessInputResult::InputBlocked);
*ret_accepted = accepted;
}
if (end_of_request) {
if (*ret_accepted != mem.len()) {
logW_ (_func, "RTMPT request contains an incomplete RTMP message");
self->mutex.lock ();
mt_unlocks (mutex) self->destroyRtmptSession (session, true /* close_rtmp_conn */);
session->unref ();
return Result::Failure;
}
session->unref ();
}
return Result::Success;
}
bool
RtmptService::acceptOneConnection ()
{
Ref<RtmptConnection> const rtmpt_conn = grab (new (std::nothrow) RtmptConnection (NULL /* embed_conatiner */));
num_connection_objects.inc ();
rtmpt_conn->connection_info.creation_unixtime = getUnixtime();
rtmpt_conn->valid = true;
rtmpt_conn->weak_rtmpt_service = this;
rtmpt_conn->last_msg_time = getTime();
rtmpt_conn->cur_req_session = NULL;
Ref<ServerThreadContext> const thread_ctx = server_ctx->selectThreadContext ();
rtmpt_conn->weak_thread_ctx = thread_ctx;
IpAddress client_addr;
{
TcpServer::AcceptResult const res = tcp_server->accept (rtmpt_conn->tcp_conn, &client_addr);
if (res == TcpServer::AcceptResult::Error) {
logE_ (_func, exc->toString());
return false;
}
if (res == TcpServer::AcceptResult::NotAccepted)
return false;
assert (res == TcpServer::AcceptResult::Accepted);
}
rtmpt_conn->connection_info.client_addr = client_addr;
rtmpt_conn->conn_sender->init (thread_ctx->getDeferredProcessor());
rtmpt_conn->conn_sender->setConnection (rtmpt_conn->tcp_conn);
rtmpt_conn->conn_receiver->init (rtmpt_conn->tcp_conn, thread_ctx->getDeferredProcessor());
rtmpt_conn->http_server->init (CbDesc<HttpServer::Frontend> (&http_frontend, rtmpt_conn, rtmpt_conn),
rtmpt_conn->conn_receiver,
rtmpt_conn->conn_sender,
thread_ctx->getDeferredProcessor(),
page_pool,
client_addr);
logI (rtmpt, _func, "accepted rtmpt_conn 0x", fmt_hex, (UintPtr) rtmpt_conn.ptr(), ", client_addr ", client_addr);
mutex.lock ();
rtmpt_conn->pollable_key =
thread_ctx->getPollGroup()->addPollable (rtmpt_conn->tcp_conn->getPollable());
if (!rtmpt_conn->pollable_key) {
mutex.unlock ();
logE_ (_func, "PollGroup::addPollable() failed: ", exc->toString ());
return true;
}
if (conn_keepalive_timeout > 0) {
rtmpt_conn->conn_keepalive_timer =
thread_ctx->getTimers()->addTimer_microseconds (
CbDesc<Timers::TimerCallback> (
connKeepaliveTimerTick, rtmpt_conn, rtmpt_conn),
conn_keepalive_timeout,
true /* periodical */,
false /* auto_delete */);
}
conn_list.append (rtmpt_conn);
rtmpt_conn->ref ();
++num_valid_connections;
mutex.unlock ();
rtmpt_conn->conn_receiver->start ();
return true;
}
TcpServer::Frontend const RtmptService::tcp_server_frontend = {
accepted
};
void
RtmptService::accepted (void * const _self)
{
RtmptService * const self = static_cast <RtmptService*> (_self);
for (;;) {
if (!self->acceptOneConnection ())
break;
}
}
void
RtmptService::attachToHttpService (HttpService * const http_service,
// TODO Use path? Does it work with RTMPT?
ConstMemory const /* path */)
{
ConstMemory const paths [] = { ConstMemory ("send"),
ConstMemory ("idle"),
ConstMemory ("open"),
ConstMemory ("close"),
ConstMemory ("fcs") };
Size const num_paths = sizeof (paths) / sizeof (ConstMemory);
for (unsigned i = 0; i < num_paths; ++i) {
http_service->addHttpHandler (
CbDesc<HttpService::HttpHandler> (&http_handler, this, this),
paths [i],
false /* preassembly */,
0 /* preassembly_limit */,
false /* parse_body_params */);
}
}
mt_throws Result
RtmptService::bind (IpAddress const addr)
{
if (!tcp_server->bind (addr)) {
logE_ (_func, "tcp_server.bind() failed: ", exc->toString());
return Result::Failure;
}
return Result::Success;
}
mt_throws Result
RtmptService::start ()
{
if (!tcp_server->listen ()) {
logE_ (_func, "tcp_server.listen() failed: ", exc->toString());
return Result::Failure;
}
mutex.lock ();
assert (!server_pollable_key);
server_pollable_key =
server_ctx->getMainThreadContext()->getPollGroup()->addPollable (tcp_server->getPollable());
if (!server_pollable_key) {
mutex.unlock ();
logE_ (_func, "addPollable() failed: ", exc->toString());
return Result::Failure;
}
mutex.unlock ();
if (!tcp_server->start ()) {
logF_ (_func, "tcp_server.start() failed: ", exc->toString());
mutex.lock ();
server_ctx->getMainThreadContext()->getPollGroup()->removePollable (server_pollable_key);
server_pollable_key = NULL;
mutex.unlock ();
return Result::Failure;
}
return Result::Success;
}
mt_mutex (mutex) void
RtmptService::updateRtmptSessionsInfo ()
{
Time const cur_unixtime = getUnixtime();
Time const cur_time = getTime();
SessionMap::data_iterator iter (session_map);
while (!iter.done()) {
RtmptSession * const session = iter.next ();
session->session_info.last_req_unixtime = cur_unixtime - (cur_time - session->last_msg_time);
}
}
mt_mutex (mutex) RtmptService::RtmptSessionInfoIterator
RtmptService::getRtmptSessionsInfo_locked (RtmptSessionsInfo * const ret_info)
{
if (ret_info) {
ret_info->num_session_objects = num_session_objects.get ();
ret_info->num_valid_sessions = num_valid_sessions;
}
updateRtmptSessionsInfo ();
return RtmptSessionInfoIterator (*this);
}
mt_mutex (mutex) void
RtmptService::updateRtmptConnectionsInfo ()
{
Time const cur_unixtime = getUnixtime();
Time const cur_time = getTime();
ConnectionList::iterator iter (conn_list);
while (!iter.done()) {
RtmptConnection * const rtmpt_conn = iter.next ();
rtmpt_conn->connection_info.last_req_unixtime = cur_unixtime - (cur_time - rtmpt_conn->last_msg_time);
}
}
mt_mutex (mutex) RtmptService::RtmptConnectionInfoIterator
RtmptService::getRtmptConnectionsInfo_locked (RtmptConnectionsInfo * const ret_info)
{
if (ret_info) {
ret_info->num_connection_objects = num_connection_objects.get ();
ret_info->num_valid_connections = num_valid_connections;
}
updateRtmptConnectionsInfo ();
return RtmptConnectionInfoIterator (*this);
}
mt_const Result
RtmptService::init (ServerContext * const mt_nonnull server_ctx,
PagePool * const mt_nonnull page_pool,
bool const enable_standalone_tcp_server,
Time const rtmp_ping_timeout_millisec,
Time const session_keepalive_timeout,
Time const conn_keepalive_timeout,
bool const no_keepalive_conns)
{
this->frontend = frontend;
this->server_ctx = server_ctx;
this->page_pool = page_pool;
this->rtmp_ping_timeout_millisec = rtmp_ping_timeout_millisec;
this->session_keepalive_timeout = session_keepalive_timeout;
this->conn_keepalive_timeout = conn_keepalive_timeout;
this->no_keepalive_conns = no_keepalive_conns;
if (enable_standalone_tcp_server) {
tcp_server->init (CbDesc<TcpServer::Frontend> (&tcp_server_frontend, this, this),
server_ctx->getMainThreadContext()->getDeferredProcessor(),
server_ctx->getMainThreadContext()->getTimers());
if (!tcp_server->open ())
return Result::Failure;
}
return Result::Success;
}
RtmptService::RtmptService (EmbedContainer * const embed_container)
: Object (embed_container),
rtmp_ping_timeout_millisec (5 * 60 * 1000),
session_keepalive_timeout (60),
conn_keepalive_timeout (60),
no_keepalive_conns (false),
tcp_server (this /* embed_container */),
session_id_counter (1),
num_valid_sessions (0),
num_valid_connections (0)
{
}
RtmptService::~RtmptService ()
{
mutex.lock ();
if (server_pollable_key) {
server_ctx->getMainThreadContext()->getPollGroup()->removePollable (server_pollable_key);
server_pollable_key = NULL;
}
{
SessionMap::Iterator iter (session_map);
while (!iter.done ()) {
Ref<RtmptSession> const session = iter.next().getData();
mt_unlocks (mutex) destroyRtmptSession (session, true /* close_rtmp_conn */);
mutex.lock ();
}
}
{
ConnectionList::iter iter (conn_list);
while (!conn_list.iter_done (iter)) {
RtmptConnection * const rtmpt_conn = conn_list.iter_next (iter);
destroyRtmptConnection (rtmpt_conn);
}
}
mutex.unlock ();
}
}
| agpl-3.0 |
jochenmanz/plentymarkets-shopware-connector | Connector/ServiceBus/QueryFactory/QueryFactoryInterface.php | 965 | <?php
namespace PlentyConnector\Connector\ServiceBus\QueryFactory;
use PlentyConnector\Connector\ServiceBus\Query\QueryInterface;
use PlentyConnector\Connector\ServiceBus\QueryFactory\Exception\MissingQueryException;
use PlentyConnector\Connector\ServiceBus\QueryFactory\Exception\MissingQueryGeneratorException;
use PlentyConnector\Connector\ServiceBus\QueryGenerator\QueryGeneratorInterface;
/**
* Class QueryFactoryInterface.
*/
interface QueryFactoryInterface
{
/**
* @param QueryGeneratorInterface $generator
*/
public function addGenerator(QueryGeneratorInterface $generator);
/**
* @param string $adapterName
* @param string $objectType
* @param string $queryType
* @param mixed $payload
*
* @throws MissingQueryGeneratorException
* @throws MissingQueryException
*
* @return QueryInterface
*/
public function create($adapterName, $objectType, $queryType, $payload = null);
}
| agpl-3.0 |
patcon/ConsiderIt | lib/gems/reflect/app/assets/javascripts/reflect.study.js | 8810 | /* Copyright (c) 2010 Travis Kriplean (http://www.cs.washington.edu/homes/travis/)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* DOM manipulations for the Reflect research surveys. Basically drop in
* a short survey when the user takes specific actions (like adding bullet).
*
* See server/api/ApiReflectStudyAction for high level about research study.
*/
/////////////////////
//enclosure
if ( typeof Reflect == 'undefined' ) {
Reflect = {};
// ///////////////////
}
var $j = jQuery.noConflict();
Reflect.study = {
load_surveys : function () {
var bullets = [],
user = Reflect.utils.get_logged_in_user();
$j( '.bullet' ).each( function () {
var bullet = $j( this ).data( 'bullet' );
if ( bullet.id
&& (bullet.user == user || bullet.comment.user == user) )
{
bullets.push( bullet.id );
}
} );
Reflect.api.server.get_survey_bullets( {
bullets : JSON.stringify( bullets )
}, function ( data ) {
// for each candidate bullet NOT in data, lay down
// appropriate survey
for ( var i in data['bullets'] ){
var bullet = $j( '#bullet-' + data['bullets'][i] )
.data( 'bullet' );
Reflect.study.new_bullet_survey(
bullet, bullet.comment, bullet.$elem );
}
for ( var i in data['responses'] ){
var bullet = $j( '#bullet-' + data['responses'][i] )
.data( 'bullet' );
Reflect.study.new_bullet_reaction_survey(
bullet, bullet.comment, bullet.$elem );
}
} );
},
_bullet_survey_base : function ( comment, bullet, title, checkbox_name,
checkboxes, survey_id, element )
{
if ( Reflect.data[comment.id][bullet.id]
&& Reflect.data[comment.id][bullet.id].survey_responses ) {
return;
}
fields = '';
for ( var i in checkboxes) {
var box = checkboxes[i];
if ( box == 'other' ) {
fields += '<input type="checkbox" name="'
+ checkbox_name + '-' + bullet.id + '" id="other-' + bullet.id
+ '" value="' + i
+ '" class="other survey_check" /><label for="other-' + bullet.id
+ '">other</label> <input type="text" class="other_text" name="other_text" /><br>';
} else {
fields += '<input type="checkbox" name="' + checkbox_name + '-'
+ bullet.id + '" id="' + box + '-' + bullet.id
+ '" value="' + i + '" class="survey_check" />'
+ '<label for="' + box + '-' + bullet.id + '">' + box
+ '</label><br>';
}
}
// TODO: move this to html template
var prompt = $j( ''
+ '<div class="survey_prompt">'
+ ' <div class="survey_intro">'
+ ' <ul>'
+ ' <li class="survey_label"><span>'
+ title
+ '</span></li>'
+ ' <li class="cancel_survey"><button class="skip"><img title="Skip this survey" src="'
+ Reflect.api.server.media_dir
+ '/cancel_black.png" ></button></li>'
+ ' <li style="clear:both"></li>'
+ ' </ul>'
+ ' </div>'
+ ' <div class="survey_detail">'
+ ' <p class="validateTips">Check all that apply. Your response will not be shown to others.</p>'
+ ' <form>' + ' <fieldset>' + fields + '</fieldset>'
+ '<button class="done" type="button">Done</button>'
+ '<button class="skip" type="button">Skip</button>'
+ ' </form>' + ' </div>' + '</div>' );
prompt.find( '.survey_detail' ).hide();
prompt.find( '.done' ).attr( 'disabled', true );
prompt.find( 'input' ).click( function () {
prompt.find( '.done' )
.attr( 'disabled', prompt.find( 'input:checked' ).length == 0 );
} );
function open () {
$j( this ).parents( '.survey_prompt' ).find( '.survey_detail' )
.slideDown();
$j( this ).unbind( 'click' );
$j( this ).click( close );
}
function close () {
$j( this ).parents( '.survey_prompt' ).find( '.survey_detail' )
.slideUp();
$j( this ).unbind( 'click' );
$j( this ).click( open );
}
prompt.find( '.survey_label' ).click( open );
prompt.find( '.done' ).click( function () {
prompt.find( ':checkbox:checked' ).each( function () {
var response_id = $j( this ).val();
if ( $j( this ).hasClass( 'other' ) ) {
var text = prompt.find( 'input:text' ).val();
} else {
var text = '';
}
var params = {
bullet_id : bullet.id,
comment_id : comment.id,
text : text,
survey_id : survey_id,
response_id : response_id,
bullet_rev : bullet.rev
};
var vals = {
params : params,
success : function ( data ) {
},
error : function ( data ) {
}
};
Reflect.api.server.post_survey_bullets( vals );
} );
prompt.fadeTo( "slow", 0.01, function () { // fade
prompt.slideUp( "slow", function () { // slide up
prompt.remove(); // then remove from the DOM
} );
} );
} );
prompt.find( '.skip' ).click( function () {
var response_id = $j( this ).val();
if ( $j( this ).attr( 'id' ) == 'other' ) {
var text = prompt.find( 'input:text' ).val();
} else {
var text = '';
}
var params = {
bullet_id : bullet.id,
bullet_rev : bullet.rev,
comment_id : comment.id,
text : text,
survey_id : survey_id,
response_id : -1
};
var vals = {
params : params,
success : function ( data ) {
},
error : function ( data ) {
}
};
Reflect.api.server.post_survey_bullets( vals );
prompt.fadeTo( "slow", 0.01, function () { // fade
prompt.slideUp( "slow", function () { // slide up
prompt.remove(); // then remove from the DOM
} );
} );
} );
prompt.hide();
element.append( prompt );
prompt.fadeIn( 'slow' );
},
new_bullet_survey : function ( bullet, comment, element ) {
var commenter = comment.user_short,
checkboxes = [
'make sure other people will see the point',
'teach ' + comment.user_short + ' something',
'show other readers that you understand',
'show ' + comment.user_short + ' that you understand',
'help you understand the comment better', 'other' ],
title = 'Why did you add this summary?',
checkbox_name = 'point_reaction',
survey_id = 1;
Reflect.study._bullet_survey_base(
comment, bullet, title, checkbox_name,
checkboxes, survey_id, element );
},
new_bullet_reaction_survey : function ( bullet, comment, element ) {
var checkboxes = [
'It shows that people are listening to what I say',
'It shows that I need to clarify what I meant',
bullet.user + ' did not understand, though my point is clear',
bullet.user + '’s phrasing makes my point clear',
'It shows me a different way of phrasing my point',
'Thanks, ' + bullet.user,
'It makes it easier for others to hear my point',
'It makes it easier for others to understand my point',
'other' ],
title = 'How do you feel about this summary?',
checkbox_name = 'adding_point',
survey_id = 2;
Reflect.study._bullet_survey_base(
comment, bullet, title, checkbox_name,
checkboxes, survey_id, element );
},
post_mousehover : function (entity_type, entity_id){
Reflect.api.server.post_mousehover(
{
entity_type: entity_type,
entity_id: entity_id,
success: function(data){
},
error: function(data){
}
});
},
post_bullet_mousehover : function ( event ) {
try {
var id = $j(event.target).parents('.bullet').attr('id').substring(7);
Reflect.study.post_mousehover(2, id);
} catch (e) {
}
},
post_comment_mousehover : function ( event ) {
var id = $j(event.target).parents('.comment').attr('id').substring(8);
Reflect.study.post_mousehover(1, id);
},
post_blog_mousehover : function ( event ) {
var id = $j(event.target).parents('.blogpost_body').attr('id').substring(9);
Reflect.study.post_mousehover(0, id);
},
instrument_bullet : function( element ) {
var config = {
over: Reflect.study.post_bullet_mousehover, // function = onMouseOver callback (REQUIRED)
timeout: 500, // number = milliseconds delay before onMouseOut
out: function(){}, // function = onMouseOut callback (REQUIRED)
interval: 1000
};
$j(element).find('.bullet_main_wrapper').hoverIntent( config );
},
instrument_mousehovers : function ( ) {
var config = {
over: Reflect.study.post_bullet_mousehover, // function = onMouseOver callback (REQUIRED)
timeout: 500, // number = milliseconds delay before onMouseOut
out: function(){}, // function = onMouseOut callback (REQUIRED)
interval: 1000
};
$j(".bullet_main_wrapper").hoverIntent( config );
config.over = Reflect.study.post_comment_mousehover;
$j(".rf_comment_text_wrapper").hoverIntent( config );
config.over = Reflect.study.post_blog_mousehover;
$j(".blogpost_body").hoverIntent( config );
}
};
| agpl-3.0 |
Khudzlin/Doomtown-Reloaded-OCTGN | o8g/Scripts/customscripts.py | 16387 | # Python Scripts for the Star Wards LCG definition for OCTGN
# Copyright (C) 2013 Konstantine Thoukydides
# This python script is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this script. If not, see <http://www.gnu.org/licenses/>.
###==================================================File Contents==================================================###
# This file contains the autoscripting for cards with specialized effects. So called 'CustomScripts'
# * UseCustomAbility() is used among other scripts, and it just one custom ability among other normal core commands
# * CustomScipt() is a completely specialized effect, that is usually so unique, that it's not worth updating my core commands to facilitate it for just one card.
# Remote Functions are custom functions coming from specific cards which usually affect other players and are called via remoteCall()
###=================================================================================================================###
def UseCustomAbility(Autoscript, announceText, card, targetCards = None, notification = None, n = 0):
mute()
debugNotify(">>> UseCustomAbility() with Autoscript: {}".format(Autoscript)) #Debug
if card.name == "Mara Jade":
remoteCall(card.controller,'MaraJade',[card])
announceString = ''
else: announceString = announceText
debugNotify("<<< UseCustomAbility() with announceString: {}".format(announceString)) #Debug
return announceString
def CustomScript(card, action = 'PLAY'): # Scripts that are complex and fairly unique to specific cards, not worth making a whole generic function for them.
debugNotify(">>> CustomScript() with action: {}".format(action)) #Debug
mute()
discardPile = me.piles['Discard Pile']
deck = me.piles['Deck']
bootHill = me.piles['Boot Hill']
if card.name == "Bottom Dealin'" and action == 'PLAY':
debugNotify("Bottom Dealin' Script")
drawHandPlayers = []
for c in table:
if c.controller != me and c.controller not in drawHandPlayers and c.highlight == DrawHandColor: drawHandPlayers.append(c.controller)
if len(drawHandPlayers) == 1: targetPL = drawHandPlayers[0]
elif len(drawHandPlayers) == 0:
whisper(":::ERRROR::: No valid player found to bottom deal. Aborting!")
return 'ABORT'
else:
choice = SingleChoice("Please choose which of your opponents you're bottom dealin'.", [pl.name for pl in drawHandPlayers])
if choice == None: return 'ABORT'
targetPL = drawHandPlayers[choice]
remoteCall(targetPL,'clearDrawHandonTable',[])
drawhandMany(me.Deck, 5, True,scripted = True)
resultTXT = revealHand(me.piles['Draw Hand'], type = 'shootout', event = None, silent = True)
notify("{}'s new hand rank is {}".format(targetPL,resultTXT))
elif card.name == "Coachwhip!" and action == 'PLAY':
debugNotify("Coachwhip Script")
targetDude = [c for c in table if c.targetedBy and c.targetedBy == me and c.controller != me and c.Type == 'Dude']
if not len(targetDude): notify(":> No target selected. Cheating player has to select one of their dudes to boot or ace")
else:
if getGlobalVariable('Shootout') == 'True':
aceTarget(targetCards = targetDude[1:], silent = True)
notify(":> {} is caught cheating in a shootout while {} has a legal hand and the Coachwhip forces them to ace {}".format(targetDude[0].controller,me,targetDude[0]))
else:
remoteCall(targetDude[0].controller,'boot',[targetDude[0]])
notify(":> {} is caught cheating in lowball while {} has a legal hand and the Coachwhip forces them to boot {}".format(targetDude[0].controller,me,targetDude[0]))
elif card.name == "Elander Boldman" and action == 'USE':
if getGlobalVariable('Shootout') != 'True':
whisper(":::ERROR::: {} can only use his shootout ability during shootouts".format(card))
return 'ABORT'
foundDude = False
hostCards = eval(getGlobalVariable('Host Cards'))
for c in table:
attachedWG = [Card(att_id) for att_id in hostCards if hostCards[att_id] == c._id and re.search(r'Weapon',Card(att_id).Keywords) and re.search(r'Gadget',Card(att_id).Keywords)]
if c.targetedBy and c.targetedBy == me and c.Type == 'Dude' and c.controller == me and len(attachedWG): # If we've targeted a dude with a weapon gadget...
rank,suit = pull(silent = True)
notify("{} attempts to optimize {} and pulls a {} {}.".format(card,attachedWG[0],rank, suit))
if suit == 'Clubs':
notify(":> Oops! The {} explodes. {} is discarded".format(attachedWG[0],c))
if confirm("You pulled a club! Go ahead and discard {}?".format(c.name)): discard(c,silent = True)
else:
attachedWG[0].markers[mdict['BulletShootoutPlus']] += 3
notify(":> The tweaks done on {} give it +3 bullet bonus for this shootout".format(attachedWG[0],c))
foundDude = True
break
if not foundDude:
whisper(":::ERROR::: No dude targeted. Aborting!")
return 'ABORT'
elif card.name == "Jarrett Blake" and action == 'USE':
if getGlobalVariable('Shootout') != 'True':
whisper(":::ERROR::: {} can only use his shootout ability during shootouts".format(card))
return 'ABORT'
hostCards = eval(getGlobalVariable('Host Cards'))
if not len([Card(att_id) for att_id in hostCards if hostCards[att_id] == card._id and re.search(r'Horse',Card(att_id).Keywords)]):
whisper(":::ERROR::: {} can only use his shootout ability while they have a horse attached".format(card))
return 'ABORT'
foundDude = False
for c in table:
if c.targetedBy and c.targetedBy == me and c.Type == 'Dude' and c.controller == me and (c.highlight == AttackColor or c.highlight == DefendColor): # If we've targeted a dude in a shootout
x,y = c.position
Jx,Jy = card.position
c.moveToTable(Jx,Jy)
card.moveToTable(x,y)
orgAttachments(card)
orgAttachments(c)
participateDude(card)
leavePosse(c)
foundDude = True
notify("{} switches places with {}".format(card,c))
break
if not foundDude:
whisper(":::ERROR::: No dude targeted. Aborting!")
return 'ABORT'
elif card.name == "Morgan Cattle Co." and action == 'USE':
targetDeed = findTarget('DemiAutoTargeted-atDeed-fromHand-choose1')
if not len(targetDeed):
whisper(":::ERROR::: You have no deeds in your hand to attempt to build")
return 'ABORT'
targetDude = findTarget('DemiAutoTargeted-atDude-isUnbooted-hasProperty{Influence}gt0-choose1')
if not len(targetDude):
whisper(":::ERROR::: You have no available dudes in play to build that deed")
return 'ABORT'
reduction = compileCardStat(targetDude[0], 'Influence')
playcard(targetDeed[0],costReduction = reduction)
x,y = targetDeed[0].position
boot(targetDude[0],forced = 'boot')
targetDude[0].moveToTable(x + cardDistance(), y)
orgAttachments(targetDude[0])
notify("{} uses {} and boots {} to build {}, reducing its cost by {}.".format(me,card,targetDude[0],targetDeed[0],reduction))
elif card.name == "The Union Casino" and action == 'USE':
targetDude = findTarget('Targeted-atDude-isUnbooted')
if not len(targetDude):
whisper(":::ERROR::: You need to target an unbooted dudes at this deed to use this ability")
return 'ABORT'
boot(targetDude[0],silent = True)
myBet = askInteger("How much ghost rock do you want to bet on the Union Casino?",4)
if payCost(myBet, loud) == 'ABORT': return 'ABORT'
if myBet <= 3: notify(":> {} felt the need to burn some money by wasting {} Ghost Rock on Union Casino. Nothing else happens".format(me,myBet))
else:
notify(":> {} boots {} and uses {}'s ability to bet {}".format(me,targetDude[0],card,myBet))
for player in getActivePlayers():
if player != me or len(getActivePlayers()) == 1: remoteCall(player,'UnionCasino',[card,myBet,targetDude[0],'others bet'])
elif card.name == "This is a Holdup!" and action == 'PLAY':
targetDeed = findTarget('Targeted-atDeed')
if not len(targetDeed):
whisper(":::ERROR::: You need to target a deed with production to steal from first. Aborting.")
return 'ABORT'
deed = targetDeed[0]
if deed.controller.GhostRock == 0:
whisper(":::ERROR::: {} has no money in their bank to steal. Aborting")
return 'ABORT'
deedProd = compileCardStat(deed, stat = 'Production')
if deedProd == 0:
whisper(":::ERROR::: {} has no production to steal. Aborting")
return 'ABORT'
targetDude = findTarget('Targeted-atDude-isUnbooted')
if not len(targetDude):
whisper(":::ERROR::: You need to target an unbooted dudes at this deed to use this ability. Aborting.")
return 'ABORT'
boot(targetDude[0],silent = True, forced = 'boot')
if deedProd > deed.controller.GhostRock:
notify(":> {} doesn't have the full {} ghost rock to steal, so {} is taking the {} possible.".format(deed.controller,deedProd,card,deed.controller.GhostRock))
me.GhostRock += deed.controller.GhostRock # We cannot steal more money than the target player has.
targetDude[0].markers[mdict['Bounty']] += deed.controller.GhostRock
deed.controller.GhostRock = 0
else:
notify(":> {} is holding up {} and taking {} ghost rock from {}.".format(targetDude[0],deed,deedProd,deed.controller))
me.GhostRock += deedProd # We cannot steal more money than the target player has.
deed.controller.GhostRock -= deedProd
targetDude[0].markers[mdict['Bounty']] += deedProd
elif card.name == "Unprepared" and action == 'PLAY':
targetDude = findTarget('DemiAutoTargeted-atDude-isParticipating-targetOpponents-choose1')
if not len(targetDude):
whisper(":::ERROR::: You need to target an dude in this shootout. Aborting.")
return 'ABORT'
boot(targetDude[0],silent = True, forced = 'boot')
TokensX('Put1Unprepared', '', targetDude[0])
dudeGoods = findTarget('AutoTargeted-atGoods_or_Spells-onAttachment', card = targetDude[0])
for attachment in dudeGoods:
boot(attachment,silent = True, forced = 'boot')
TokensX('Put1Unprepared', '', attachment)
targetDude[0].markers[mdict['BulletShootoutMinus']] += 1
notify("{} has been caught with their pants down.".format(targetDude[0]))
else: notify("{} uses {}'s ability".format(me,card)) # Just a catch-all.
return 'OK'
def markerEffects(Time = 'Start'):
debugNotify(">>> markerEffects() at time: {}".format(Time)) #Debug
cardList = [c for c in table if c.markers]
for card in cardList:
for marker in card.markers:
if (Time == 'Sundown'
and (re.search(r'Bad Company',marker[0])
or re.search(r'High Noon',marker[0])
or re.search(r'Hiding in the Shadows',marker[0])
or re.search(r'Rumors',marker[0]))):
TokensX('Remove999'+marker[0], marker[0] + ':', card)
notify("--> {} removes the {} resident effect from {}".format(me,marker[0],card))
if Time == 'Sundown' and re.search(r'Come Git Some',marker[0]) and card.controller == me and card.owner == me: # This is the Sloane outfit ability
if card.markers[mdict['PermControl']]:
choice = SingleChoice("Do you want to take one Ghost Rock per player?", ['No, {} is not in the Town Square anymore.'.format(card.name),'Yes! Take 1 GR per player.'])
else: choice = SingleChoice("Do you want to take one Ghost Rock per player, or put a permanent control point on this dude?'.", ['None of the above. {} is not in the Town Square anymore.'.format(card.name),'Take 1 GR per player.','Put 1 permanent CP on {}.'.format(card.name)])
if not choice: # If the choice is 0 or None (i.e. closed the selection window) the dude is assumed to be out of the Town Square
notify("{}'s {} didn't manage to hold the Town Square. They gain nothing this turn".format(me,card,len(getActivePlayers()) - 1))
elif choice == 1: # If the choice is 0 or None (i.e. closed the selection window, we give them money)
me.GhostRock += len(getActivePlayers()) - 1
notify("{}'s {} and shakes down the citizens of Gomorra for {} Ghost Rock".format(me,card,len(getActivePlayers()) - 1))
else:
notify("{}'s {} puts the fear of the gun to the town, giving them one permanent control point".format(me,card))
card.markers[mdict['PermControl']] += 1
card.markers[marker] = 0
if (Time == 'ShootoutEnd'
and (re.search(r'Sun In Yer Eyes',marker[0])
or re.search(r'Unprepared',marker[0])
or re.search(r'Shootout',marker[0]))):
TokensX('Remove999'+marker[0], marker[0] + ':', card)
notify("--> {} removes the {} resident effect from {}".format(me,marker[0],card))
#------------------------------------------------------------------------------
# Remote Functions
#------------------------------------------------------------------------------
def UnionCasino(card,mainBet,targetDude, function = 'others bet'):
mute()
if function == 'others bet' and len(getActivePlayers()) > 1:
minBet = mainBet - 3
if minBet < 0: minBet = 0
myBet = askInteger("{} has started the Union Casino pool with {}. You need {} to check. Bet how much?".format(card.controller,mainBet,minBet),0)
if payCost(myBet, loud) == 'ABORT': myBet = 0
if myBet == 0: TokensX('Put1Union Casino Zero Bet:{}'.format(me.name), '', card)
else: TokensX('Put{}Union Casino Bet:{}'.format(myBet,me.name), '', card)
remoteCall(card.controller,'UnionCasino',[card,mainBet,targetDude,'resolve'])
else:
#confirm('b')
betPlayers = 1
for player in getActivePlayers():
if player != me and findMarker(card, ':{}'.format(player.name)): betPlayers += 1
if betPlayers == len(getActivePlayers()): # We compare to see if the controller won only after all players have finished betting.
highBet = 0
highBetter = None
#confirm('a')
for player in getActivePlayers():
if player != me:
zeroMarker = findMarker(card, 'Union Casino Zero Bet:{}'.format(player.name))
if zeroMarker:
card.markers[zeroMarker] = 0
continue
else:
currBet = findMarker(card, ':{}'.format(player.name))
if highBet < card.markers[currBet]:
highBet = card.markers[currBet]
card.markers[currBet] = 0
highBetter = player
if mainBet >= (highBet + 4) or not highBetter:
targetDude.markers[mdict['PermControl']] += 1
notify(":> {} outbid all other players by {} and thus {} gains a permanent control point".format(me,mainBet - highBet,targetDude))
else: notify(":> {} checked the bet by raising {} to {}'s {}".format(me,highBet,card.controller,mainBet))
| agpl-3.0 |
Comunitea/CMNT_004_15 | project-addons/custom_account/models/account_payment.py | 2864 | # Copyright 2019 Omar Castiñeira, Comunitea Servicios Tecnológicos S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields, api
class PaymentLine(models.Model):
_inherit = 'account.payment.line'
is_refund = fields.Boolean(compute='_get_is_refund')
not_change_date = fields.Boolean("Not change date")
@api.multi
def write(self, vals):
if 'not_change_date' not in vals and vals.get('date'):
for line in self:
if line.not_change_date:
del vals['date']
break
return super().write(vals)
@api.multi
def _get_is_refund(self):
for line in self:
line.is_refund = line.amount_currency < 0 and True or False
class AccountAccount(models.Model):
_inherit = 'account.account'
not_payment_followup = fields.\
Boolean("Don't show on supplier payment follow-ups")
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends('invoice_ids', 'currency_id', 'payment_date')
def _get_current_exchange_rate(self):
for payment in self:
if payment.invoice_ids and payment.journal_id and \
payment.invoice_ids[0].currency_id != \
payment.journal_id.company_id.currency_id:
payment.current_exchange_rate = payment.journal_id.company_id.\
currency_id.with_context(date=self.payment_date).\
_get_conversion_rate(payment.journal_id.
company_id.currency_id,
payment.invoice_ids[0].currency_id)
else:
payment.current_exchange_rate = 1.0
current_exchange_rate = fields.Float("Exchange rate computed",
compute="_get_current_exchange_rate",
digits=(16, 6), readonly=True,
help="Currency rate used to convert "
"to company currency")
force_exchange_rate = fields.Float("Force exchange rate", digits=(16, 6))
@api.multi
def post(self):
for rec in self:
ctx = self.env.context.copy()
if rec.invoice_ids and \
all([x.currency_id == rec.invoice_ids[0].currency_id
for x in rec.invoice_ids]):
invoice_currency = rec.invoice_ids[0].currency_id
if invoice_currency != \
rec.invoice_ids[0].company_id.currency_id and \
rec.force_exchange_rate:
ctx['force_from_rate'] = rec.force_exchange_rate
super(AccountPayment, rec.with_context(ctx)).post()
return True
| agpl-3.0 |
acontes/scheduling | src/resource-manager/src/org/ow2/proactive/resourcemanager/exception/RMException.java | 2466 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* 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, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.resourcemanager.exception;
import org.ow2.proactive.resourcemanager.RMFactory;
import org.ow2.proactive.resourcemanager.frontend.RMConnection;
/**
* Exceptions Generated by the RM
*
* @see RMConnection
* @see RMFactory
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*
*/
public class RMException extends Exception {
/**
* Attaches a message to the Exception
* @param message message attached
*/
public RMException(String message) {
super(message);
}
/**
* Empty constructor
*/
public RMException() {
super();
}
/**
* Attaches a message and a cause to the Exception
* @param message message attached
* @param cause the cause
*/
public RMException(String message, Throwable cause) {
super(message, cause);
}
/**
* Attaches a cause to the Exception
* @param cause the cause
*/
public RMException(Throwable cause) {
super(cause);
}
}
| agpl-3.0 |
maco/growstuff | spec/controllers/account_types_controller_spec.rb | 800 | ## DEPRECATION NOTICE: Do not add new tests to this file!
##
## View and controller tests are deprecated in the Growstuff project.
## We no longer write new view and controller tests, but instead write
## feature tests (in spec/features) using Capybara (https://github.com/jnicklas/capybara).
## These test the full stack, behaving as a browser, and require less complicated setup
## to run. Please feel free to delete old view/controller tests as they are reimplemented
## in feature tests.
##
## If you submit a pull request containing new view or controller tests, it will not be
## merged.
require 'rails_helper'
describe AccountTypesController do
# This automatically creates a "Free" account type
login_member(:admin_member)
def valid_attributes
{ "name" => "MyString" }
end
end
| agpl-3.0 |
utilitydriverepo/udms-pi-master | Modules/admin/admin_controller.php | 11185 | <?php
/*
All Emoncms code is released under the GNU Affero General Public License.
See COPYRIGHT.txt and LICENSE.txt.
---------------------------------------------------------------------
Emoncms - open source energy visualisation
Part of the OpenEnergyMonitor project:
http://openenergymonitor.org
*/
// no direct access
defined('EMONCMS_EXEC') or die('Restricted access');
function admin_controller()
{
global $mysqli,$session,$route,$updatelogin,$allow_emonpi_admin, $log_filename, $log_enabled, $redis;
$result = "<br><div class='alert-error' style='top:0px; left:0px; width:100%; height:100%; text-align:center; padding-top:100px; padding-bottom:100px; border-radius:4px;'><h4>"._('Admin re-authentication required')."</h4></div>";
// Allow for special admin session if updatelogin property is set to true in settings.php
// Its important to use this with care and set updatelogin to false or remove from settings
// after the update is complete.
if ($updatelogin || $session['admin']) {
if ($route->format == 'html') {
if ($route->action == 'view') $result = view("Modules/admin/admin_main_view.php", array());
else if ($route->action == 'db')
{
$applychanges = get('apply');
if (!$applychanges) $applychanges = false;
else $applychanges = true;
require_once "Lib/dbschemasetup.php";
$updates = array();
$updates[] = array(
'title'=>"Database schema",
'description'=>"",
'operations'=>db_schema_setup($mysqli,load_db_schema(),$applychanges)
);
$result = view("Modules/admin/update_view.php", array('applychanges'=>$applychanges, 'updates'=>$updates));
}
else if ($route->action == 'users' && $session['write'])
{
$result = view("Modules/admin/userlist_view.php", array());
}
else if ($route->action == 'setuser' && $session['write'])
{
$_SESSION['userid'] = intval(get('id'));
header("Location: ../user/view");
}
else if ($route->action == 'downloadlog')
{
if ($log_enabled) {
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($log_filename) . "\"");
header("Pragma: no-cache");
header("Expires: 0");
flush();
if (file_exists($log_filename)) {
readfile($log_filename);
}
else
{
echo($log_filename . " does not exist!");
}
exit;
}
}
else if ($route->action == 'getlog')
{
$route->format = "text";
if ($log_enabled) {
ob_start();
// PHP replacement for tail starts here
// full path to text file
define("TEXT_FILE", $log_filename);
// number of lines to read from the end of file
define("LINES_COUNT", 25);
function read_file($file, $lines) {
//global $fsize;
$handle = fopen($file, "r");
$linecounter = $lines;
$pos = -2;
$beginning = false;
$text = array();
while ($linecounter > 0) {
$t = " ";
while ($t != "\n") {
if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true;
break;
}
$t = fgetc($handle);
$pos --;
}
$linecounter --;
if ($beginning) {
rewind($handle);
}
$text[$lines-$linecounter-1] = fgets($handle);
if ($beginning) break;
}
fclose ($handle);
return array_reverse($text);
}
$fsize = round(filesize(TEXT_FILE)/1024/1024,2);
$lines = read_file(TEXT_FILE, LINES_COUNT);
foreach ($lines as $line) {
echo $line;
} //End PHP replacement for Tail
$result = trim(ob_get_clean());
} else {
$result = "Log is disabled.";
}
}
else if ($allow_emonpi_admin && $route->action == 'emonpi') {
//put $update_logfile here so it can be referenced in other if statements
//before it was only accesable in the update subaction
//placed some other variables here as well so they are grouped
//together for the emonpi action even though they might not be used
//in the subaction
$update_logfile = "/home/pi/data/emonpiupdate.log";
$backup_logfile = "/home/pi/data/emonpibackup.log";
$update_flag = "/tmp/emoncms-flag-update";
$backup_flag = "/tmp/emonpibackup";
$update_script = "/home/pi/emonpi/service-runner-update.sh";
$backup_file = "/home/pi/data/backup.tar.gz";
if ($route->subaction == 'update' && $session['write'] && $session['admin']) {
$route->format = "text";
// Get update argument e.g. 'emonpi' or 'rfm69pi'
$argument="";
if (isset($_POST['argument'])) {
$argument = $_POST['argument'];
}
$fh = @fopen($update_flag,"w");
if (!$fh) {
$result = "ERROR: Can't write the flag $update_flag.";
} else {
fwrite($fh,"$update_script $argument>$update_logfile");
$result = "Update flag set";
}
@fclose($fh);
}
if ($route->subaction == 'getupdatelog' && $session['admin']) {
$route->format = "text";
ob_start();
passthru("cat " . $update_logfile);
$result = trim(ob_get_clean());
}
if ($route->subaction == 'downloadupdatelog' && $session['admin'])
{
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($update_logfile) . "\"");
header("Pragma: no-cache");
header("Expires: 0");
flush();
if (file_exists($update_logfile))
{
ob_start();
readfile($update_logfile);
echo(trim(ob_get_clean()));
}
else
{
echo($update_logfile . " does not exist!");
}
exit;
}
if ($route->subaction == 'backup' && $session['write'] && $session['admin']) {
$route->format = "text";
$fh = @fopen($backup_flag,"w");
if (!$fh) $result = "ERROR: Can't write the flag $backup_flag.";
else $result = "Update flag file $backup_flag created. Update will start on next cron call in " . (60 - (time() % 60)) . "s...";
@fclose($fh);
}
if ($route->subaction == 'getbackuplog' && $session['admin']) {
$route->format = "text";
ob_start();
passthru("cat " . $backup_logfile);
$result = trim(ob_get_clean());
}
if ($route->subaction == 'downloadbackuplog' && $session['admin'])
{
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($backup_logfile) . "\"");
header("Pragma: no-cache");
header("Expires: 0");
flush();
if (file_exists($backup_logfile)) {
ob_start();
readfile($backup_logfile);
echo(trim(ob_get_clean()));
}
else
{
echo($backup_logfile . " does not exist!");
}
exit;
}
if ($route->subaction == "downloadbackup" && $session['write'] && $session['admin']) {
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=\"" . basename($backup_file) . "\"");
header("Pragma: no-cache");
header("Expires: 0");
readfile($backup_file);
exit;
}
if ($route->subaction == 'fs' && $session['admin'])
{
if (isset($_POST['argument'])) {
$argument = $_POST['argument'];
}
if ($argument == 'ro'){
$result = passthru('rpi-ro');
}
if ($argument == 'rw'){
$result = passthru('rpi-rw');
}
}
}
}
else if ($route->format == 'json')
{
if ($route->action == 'redisflush' && $session['write'])
{
$redis->flushDB();
$result = array('used'=>$redis->info()['used_memory_human'], 'dbsize'=>$redis->dbSize());
}
else if ($route->action == 'userlist' && $session['write'])
{
$data = array();
$result = $mysqli->query("SELECT id,username,email FROM users");
while ($row = $result->fetch_object()) $data[] = $row;
$result = $data;
}
}
}
return array('content'=>$result);
}
| agpl-3.0 |
objective-solutions/taskboard | application/src/test/java/objective/taskboard/it/RefreshToast.java | 1158 | package objective.taskboard.it;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class RefreshToast extends AbstractUiFragment {
private By issueToast = By.id("toastIssueUpdated");
private By showOnlyUpdatedOrDismiss = By.id("showOnlyUpdatedOrDismiss");
private By closeIssueUpdated = By.id("closeIssueUpdated");
public RefreshToast(WebDriver webDriver) {
super(webDriver);
}
public RefreshToast assertVisible() {
waitVisibilityOfElement(issueToast);
return this;
}
public RefreshToast showOnlyUpdated() {
waitUntilElementIsVisibleExistsWithText(showOnlyUpdatedOrDismiss, "SHOW ONLY UPDATED");
waitForClick(showOnlyUpdatedOrDismiss);
return this;
}
public RefreshToast dismiss() {
waitUntilElementIsVisibleExistsWithText(showOnlyUpdatedOrDismiss, "DISMISS");
waitForClick(showOnlyUpdatedOrDismiss);
return this;
}
public void assertNotVisible() {
waitInvisibilityOfElement(issueToast);
}
public void close() {
waitForClick(closeIssueUpdated);
assertNotVisible();
}
} | agpl-3.0 |
giovanisp/Airesis | app/controllers/area_participations_controller.rb | 1107 | class AreaParticipationsController < ApplicationController
layout 'groups'
before_filter :load_group
before_filter :authenticate_user!
authorize_resource :group
load_and_authorize_resource :group_area, through: :group
before_filter :load_area_participation, only: :destroy
load_and_authorize_resource through: :group_area
def create
# part = @group_area.area_participations.new
# part.user_id = params[:user_id]
# TODO: check if the user can be added to the area
@area_participation.area_role_id = @group_area.area_role_id
if @area_participation.save
flash[:notice] = t('info.area_participation.create')
else
flash[:error] = t('error.area_participation.create')
end
end
def destroy
@area_participation.destroy
flash[:notice] = t('info.area_participation.destroy')
end
protected
def load_area_participation
@area_participation = @group_area.area_participations.find_by(user_id: area_participation_params[:user_id])
end
def area_participation_params
params.require(:area_participation).permit(:user_id)
end
end
| agpl-3.0 |
iwatendo/skybeje | src/Contents/Sender/GetAudioBlobSender.ts | 253 | import Sender from "../../Base/Container/Sender";
/**
*
*/
export default class GetAudioBlobSender extends Sender {
public static ID = "GetAudioBlob";
constructor() {
super(GetAudioBlobSender.ID);
}
public mid: string;
}
| agpl-3.0 |
WebDataConsulting/billing | src/java/com/sapienter/jbilling/server/user/permisson/db/RoleDAS.java | 1691 | /*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling 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.
jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>.
This source was modified by Web Data Technologies LLP (www.webdatatechnologies.in) since 15 Nov 2015.
You may download the latest source from webdataconsulting.github.io.
*/
package com.sapienter.jbilling.server.user.permisson.db;
import org.hibernate.criterion.Restrictions;
import org.hibernate.Criteria;
import com.sapienter.jbilling.server.util.db.AbstractDAS;
public class RoleDAS extends AbstractDAS<RoleDTO> {
public RoleDTO findByRoleTypeIdAndCompanyId(Integer roleTypeId, Integer companyId) {
Criteria criteria =getSession().createCriteria(getPersistentClass())
.add(Restrictions.eq("roleTypeId", roleTypeId));
if (null != companyId) {
criteria.add(Restrictions.eq("company.id", companyId));
} else {
criteria.add(Restrictions.isNull("company"));
}
return findFirst(criteria);
}
}
| agpl-3.0 |
printedheart/opennars | nars_lab/src/main/java/automenta/spacegraph/ui/TextButton.java | 800 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package automenta.spacegraph.ui;
import automenta.spacegraph.math.linalg.Vec4f;
import automenta.spacegraph.shape.TextRect;
import com.jogamp.opengl.GL2;
/**
*
* @author me
*/
public class TextButton extends Button {
private String text;
private TextRect tr;
private Vec4f textColor = new Vec4f(0, 0, 0, 1f);
public TextButton(String label) {
super();
setText(label);
}
public void setText(String newText) {
this.text = newText;
tr = new TextRect(text);
tr.setTextColor(textColor);
}
@Override
protected void drawFront(GL2 gl) {
super.drawFront(gl);
tr.draw(gl);
}
}
| agpl-3.0 |
zqian/gradecraft-development | spec/factories/challenge_factory.rb | 93 | FactoryGirl.define do
factory :challenge do
course
name "shoot the moon"
end
end
| agpl-3.0 |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/code/model/tests/test_branchmergequeuecollection.py | 8470 | # Copyright 2009-2012 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests for branch merge queue collections."""
__metaclass__ = type
from zope.component import getUtility
from zope.security.proxy import removeSecurityProxy
from lp.app.enums import InformationType
from lp.app.interfaces.launchpad import ILaunchpadCelebrities
from lp.code.interfaces.branchmergequeuecollection import (
IAllBranchMergeQueues,
IBranchMergeQueueCollection,
)
from lp.code.interfaces.codehosting import LAUNCHPAD_SERVICES
from lp.code.model.branchmergequeue import BranchMergeQueue
from lp.code.model.branchmergequeuecollection import (
GenericBranchMergeQueueCollection,
)
from lp.services.database.interfaces import IMasterStore
from lp.testing import TestCaseWithFactory
from lp.testing.layers import DatabaseFunctionalLayer
class TestGenericBranchMergeQueueCollection(TestCaseWithFactory):
layer = DatabaseFunctionalLayer
def setUp(self):
TestCaseWithFactory.setUp(self)
self.store = IMasterStore(BranchMergeQueue)
def test_provides_branchmergequeuecollection(self):
# `GenericBranchMergeQueueCollection`
# provides the `IBranchMergeQueueCollection` interface.
self.assertProvides(
GenericBranchMergeQueueCollection(self.store),
IBranchMergeQueueCollection)
def test_getMergeQueues_no_filter_no_queues(self):
# If no filter is specified, then the collection is of all branches
# merge queues. By default, there are no branch merge queues.
collection = GenericBranchMergeQueueCollection(self.store)
self.assertEqual([], list(collection.getMergeQueues()))
def test_getMergeQueues_no_filter(self):
# If no filter is specified, then the collection is of all branch
# merge queues.
collection = GenericBranchMergeQueueCollection(self.store)
queue = self.factory.makeBranchMergeQueue()
self.assertEqual([queue], list(collection.getMergeQueues()))
def test_count(self):
# The 'count' property of a collection is the number of elements in
# the collection.
collection = GenericBranchMergeQueueCollection(self.store)
self.assertEqual(0, collection.count())
for i in range(3):
self.factory.makeBranchMergeQueue()
self.assertEqual(3, collection.count())
def test_count_respects_filter(self):
# If a collection is a subset of all possible queues, then the count
# will be the size of that subset. That is, 'count' respects any
# filters that are applied.
person = self.factory.makePerson()
self.factory.makeBranchMergeQueue(owner=person)
self.factory.makeAnyBranch()
collection = GenericBranchMergeQueueCollection(
self.store, [BranchMergeQueue.owner == person])
self.assertEqual(1, collection.count())
class TestBranchMergeQueueCollectionFilters(TestCaseWithFactory):
layer = DatabaseFunctionalLayer
def setUp(self):
TestCaseWithFactory.setUp(self)
self.all_queues = getUtility(IAllBranchMergeQueues)
def test_count_respects_visibleByUser_filter(self):
# IBranchMergeQueueCollection.count() returns the number of queues
# that getMergeQueues() yields, even when the visibleByUser filter is
# applied.
branch = self.factory.makeAnyBranch(
information_type=InformationType.USERDATA)
naked_branch = removeSecurityProxy(branch)
self.factory.makeBranchMergeQueue(branches=[naked_branch])
branch2 = self.factory.makeAnyBranch(
information_type=InformationType.USERDATA)
naked_branch2 = removeSecurityProxy(branch2)
self.factory.makeBranchMergeQueue(branches=[naked_branch2])
collection = self.all_queues.visibleByUser(naked_branch.owner)
self.assertEqual(1, len(collection.getMergeQueues()))
self.assertEqual(1, collection.count())
def test_ownedBy(self):
# 'ownedBy' returns a new collection restricted to queues owned by
# the given person.
queue = self.factory.makeBranchMergeQueue()
self.factory.makeBranchMergeQueue()
collection = self.all_queues.ownedBy(queue.owner)
self.assertEqual([queue], collection.getMergeQueues())
class TestGenericBranchMergeQueueCollectionVisibleFilter(TestCaseWithFactory):
layer = DatabaseFunctionalLayer
def setUp(self):
TestCaseWithFactory.setUp(self)
public_branch = self.factory.makeAnyBranch(name='public')
self.queue_with_public_branch = self.factory.makeBranchMergeQueue(
branches=[removeSecurityProxy(public_branch)])
private_branch1 = self.factory.makeAnyBranch(
name='private1', information_type=InformationType.USERDATA)
naked_private_branch1 = removeSecurityProxy(private_branch1)
self.private_branch1_owner = naked_private_branch1.owner
self.queue1_with_private_branch = self.factory.makeBranchMergeQueue(
branches=[naked_private_branch1])
private_branch2 = self.factory.makeAnyBranch(
name='private2', information_type=InformationType.USERDATA)
self.queue2_with_private_branch = self.factory.makeBranchMergeQueue(
branches=[removeSecurityProxy(private_branch2)])
self.all_queues = getUtility(IAllBranchMergeQueues)
def test_all_queues(self):
# Without the visibleByUser filter, all queues are in the
# collection.
self.assertEqual(
sorted([self.queue_with_public_branch,
self.queue1_with_private_branch,
self.queue2_with_private_branch]),
sorted(self.all_queues.getMergeQueues()))
def test_anonymous_sees_only_public(self):
# Anonymous users can see only queues with public branches.
queues = self.all_queues.visibleByUser(None)
self.assertEqual([self.queue_with_public_branch],
list(queues.getMergeQueues()))
def test_random_person_sees_only_public(self):
# Logged in users with no special permissions can see only queues with
# public branches.
person = self.factory.makePerson()
queues = self.all_queues.visibleByUser(person)
self.assertEqual([self.queue_with_public_branch],
list(queues.getMergeQueues()))
def test_owner_sees_own_branches(self):
# Users can always see the queues with branches that they own, as well
# as queues with public branches.
queues = self.all_queues.visibleByUser(self.private_branch1_owner)
self.assertEqual(
sorted([self.queue_with_public_branch,
self.queue1_with_private_branch]),
sorted(queues.getMergeQueues()))
def test_owner_member_sees_own_queues(self):
# Members of teams that own queues can see queues owned by those
# teams, as well as public branches.
team_owner = self.factory.makePerson()
team = self.factory.makeTeam(team_owner)
private_branch = self.factory.makeAnyBranch(
owner=team, name='team',
information_type=InformationType.USERDATA)
queue_with_private_branch = self.factory.makeBranchMergeQueue(
branches=[removeSecurityProxy(private_branch)])
queues = self.all_queues.visibleByUser(team_owner)
self.assertEqual(
sorted([self.queue_with_public_branch,
queue_with_private_branch]),
sorted(queues.getMergeQueues()))
def test_launchpad_services_sees_all(self):
# The LAUNCHPAD_SERVICES special user sees *everything*.
queues = self.all_queues.visibleByUser(LAUNCHPAD_SERVICES)
self.assertEqual(
sorted(self.all_queues.getMergeQueues()),
sorted(queues.getMergeQueues()))
def test_admins_see_all(self):
# Launchpad administrators see *everything*.
admin = self.factory.makePerson()
admin_team = removeSecurityProxy(
getUtility(ILaunchpadCelebrities).admin)
admin_team.addMember(admin, admin_team.teamowner)
queues = self.all_queues.visibleByUser(admin)
self.assertEqual(
sorted(self.all_queues.getMergeQueues()),
sorted(queues.getMergeQueues()))
| agpl-3.0 |
KillBait/PrimordialCrops | src/main/java/killbait/PrimordialCrops/Compat/WAILA/WailaCompatibility.java | 2844 | package killbait.PrimordialCrops.Compat.WAILA;
import killbait.PrimordialCrops.Blocks.CropBlocks;
import killbait.PrimordialCrops.Blocks.CropBlocksSpecial;
import mcp.mobius.waila.api.IWailaConfigHandler;
import mcp.mobius.waila.api.IWailaDataAccessor;
import mcp.mobius.waila.api.IWailaDataProvider;
import mcp.mobius.waila.api.IWailaRegistrar;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import java.util.List;
/**
* Created by Jon on 04/10/2016.
*/
public class WailaCompatibility implements IWailaDataProvider {
public static final WailaCompatibility INSTANCE = new WailaCompatibility();
private static boolean registered;
private static boolean loaded;
private WailaCompatibility() {
}
public static void load(IWailaRegistrar registrar) {
System.out.println("WailaCompatibility.load");
if (!registered) {
throw new RuntimeException("Please register this handler using the provided method.");
}
if (!loaded) {
registrar.registerHeadProvider(INSTANCE, CropBlocks.class);
registrar.registerBodyProvider(INSTANCE, CropBlocks.class);
registrar.registerTailProvider(INSTANCE, CropBlocks.class);
registrar.registerHeadProvider(INSTANCE, CropBlocksSpecial.class);
registrar.registerBodyProvider(INSTANCE, CropBlocksSpecial.class);
registrar.registerTailProvider(INSTANCE, CropBlocksSpecial.class);
loaded = true;
}
}
public static void register() {
if (registered)
return;
registered = true;
FMLInterModComms.sendMessage("Waila", "register", "killbait.PrimordialCrops.Compat.WAILA.WailaCompatibility.load");
}
@Override
public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) {
return tag;
}
@Override
public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) {
return null;
}
@Override
public List<String> getWailaHead(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Override
public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
Block block = accessor.getBlock();
if (block instanceof WailaInfoProvider) {
return ((WailaInfoProvider) block).getWailaBody(itemStack, currenttip, accessor, config);
}
return currenttip;
}
@Override
public List<String> getWailaTail(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
}
| agpl-3.0 |
kriberg/stationspinner | stationspinner/corporation/migrations/0035_auto_20160102_1948.py | 1212 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('corporation', '0034_auto_20160102_1808'),
]
operations = [
migrations.AddField(
model_name='outpostservice',
name='stationID',
field=models.BigIntegerField(default=0),
preserve_default=False,
),
migrations.AlterField(
model_name='outpost',
name='ownerID',
field=models.BigIntegerField(),
),
migrations.AlterField(
model_name='outpost',
name='standingOwnerID',
field=models.BigIntegerField(),
),
migrations.AlterField(
model_name='outpost',
name='stationID',
field=models.BigIntegerField(serialize=False, primary_key=True),
),
migrations.AlterUniqueTogether(
name='outpostservice',
unique_together=set([('stationID', 'serviceName', 'owner')]),
),
migrations.RemoveField(
model_name='outpostservice',
name='outpost',
),
]
| agpl-3.0 |
Metatavu/kunta-api-spec | jaxrs-spec-generated/src/main/java/fi/metatavu/kuntaapi/server/rest/model/AccessibilityContactInfo.java | 2522 | package fi.metatavu.kuntaapi.server.rest.model;
import io.swagger.annotations.ApiModel;
/**
* Accessibility contact info
**/
import io.swagger.annotations.*;
import java.util.Objects;
@ApiModel(description = "Accessibility contact info")
public class AccessibilityContactInfo implements java.io.Serializable {
private String phone = null;
private String email = null;
private String url = null;
/**
* Phone
**/
public AccessibilityContactInfo phone(String phone) {
this.phone = phone;
return this;
}
@ApiModelProperty(example = "null", value = "Phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
/**
* Email
**/
public AccessibilityContactInfo email(String email) {
this.email = email;
return this;
}
@ApiModelProperty(example = "null", value = "Email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
/**
* Url
**/
public AccessibilityContactInfo url(String url) {
this.url = url;
return this;
}
@ApiModelProperty(example = "null", value = "Url")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AccessibilityContactInfo accessibilityContactInfo = (AccessibilityContactInfo) o;
return Objects.equals(phone, accessibilityContactInfo.phone) &&
Objects.equals(email, accessibilityContactInfo.email) &&
Objects.equals(url, accessibilityContactInfo.url);
}
@Override
public int hashCode() {
return Objects.hash(phone, email, url);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AccessibilityContactInfo {\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" url: ").append(toIndentedString(url)).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 |
edewaele/petiteReine | api.php | 11619 | <?php
require 'conf.php';
try {
$PDO = new PDO( 'pgsql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD );
} catch ( Exception $e ) {
die("Unable to connect database");
}
function getZoneFilter($zoneParam = "")
{
if(isset($zoneParam) and $zoneParam != "")
{
$result = " AND zone_id IN (";
foreach(explode(",",$zoneParam) as $numParam => $zoneId)
{
if($numParam == 0)
{
$result .= "'$zoneId'";
}
else
{
$result .= ",'$zoneId'";
}
}
return $result . ") ";
}
else
{
return " AND zone_id IN (SELECT zone_id FROM pv_zones WHERE visible_default = 1) ";
}
}
function calculateStats($PDO,$LABELS,$filterClause,$geom = "")
{
global $PARKING_LABEL;
$stats = "";
$parkingCats = array();
foreach($LABELS['stats.byType'] as $key=>$value)
{
$parkingCats[$key] = 0;
}
$numberParkings = $parkingCats;
$capacityParkings = $parkingCats;
$numberParkingsTotal = 0;
$capacityParkingsTotal = 0;
if($geom != "")
{
// if a geometry is provided, the area within the polygon
$sqlArea = "select st_area(st_transform(st_geomfromgeojson(:geojson),:proj)) as area";
$queryArea = $PDO->prepare($sqlArea);
$queryArea->execute(array(":proj"=>DIST_PROJ,":geojson"=>json_encode($_REQUEST["geom"]["geometry"])));
if($rs = $queryArea->fetch())
{
$areaInSqrKm = $rs["area"] / 1000 / 1000;
$stats .= sprintf($LABELS['stats.area'],number_format($areaInSqrKm,2,DEC_POINT,THOUSAND_SEP));
}
$sqlStats = "select parking_type,count(*) as n,sum(capacity) as c from pv_parkings where st_contains(st_geomfromgeojson(:geojson),the_geom) ".$filterClause.getZoneFilter($_REQUEST["zones"])." group by parking_type";
$queryStats = $PDO->prepare($sqlStats);
$queryStats->execute(array(":geojson"=>json_encode($_REQUEST["geom"]["geometry"])));
}
else
{
// otherwise, the global statistics are calculated
$queryStats = $PDO->query("select parking_type,count(*) as n,sum(capacity) as c from pv_parkings where 1=1 ".$filterClause.getZoneFilter(isset($_REQUEST["zones"])?$_REQUEST["zones"]:"")." group by parking_type");
}
// counting parkings and total capacity by type
while($rs = $queryStats->fetch())
{
if($rs["parking_type"] == "")
{
$numberParkings["unknown"] += $rs["n"];
$capacityParkings["unknown"] += $rs["c"];
}
else if(isset($PARKING_LABEL[$rs["parking_type"]]))
{
$numberParkings[$rs["parking_type"]] += $rs["n"];
$capacityParkings[$rs["parking_type"]] += $rs["c"];
}
else
{
$numberParkings["other"] += $rs["n"];
$capacityParkings["other"] += $rs["c"];
}
$numberParkingsTotal += $rs["n"];
$capacityParkingsTotal += $rs["c"];
}
if($numberParkingsTotal > 0)
{
// total number of parkings
$stats .= sprintf($LABELS['stats.total'],$capacityParkingsTotal,$numberParkingsTotal);
$stats .= "<ul>";
// number of parkings (and capacity) by type
foreach($LABELS['stats.byType'] as $type => $label)
{
if($numberParkings[$type])
{
$stats .= "<li>".sprintf($label,$capacityParkings[$type],$numberParkings[$type])."</li>";
}
}
$stats .= "</ul>";
}
else
$stats = $LABELS["stats.noData"];
return $stats;
}
// Get a list of bicycle parkings, that is suitable for display
// get = list => display all parking except private ones
// get = private => display only private parkings
if(isset($_REQUEST["get"]))
{
// List of all bicycle parkings
// Generates a GeoJSON document with labels for in-app display
if($_REQUEST["get"] == "list" or $_REQUEST["get"] == "private")
{
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
$filterClause = "";
if($_REQUEST["get"] == "private")
$filterClause = " AND access='private'";
else if($_REQUEST["get"] == "list")
$filterClause = " AND access <> 'private'";
if(isset($_REQUEST["zones"]))
$filterClause .= getZoneFilter($_REQUEST["zones"]);
else
$filterClause .= getZoneFilter();
$sqlParkings = "SELECT obj_id as id,capacity,covered,parking_type as type,access,ST_AsGeoJSON(public.ST_Transform((the_geom),4326)) AS geojson,operator FROM pv_parkings where 1=1 ".$filterClause;
$queryParkings = $PDO->query($sqlParkings);
while($rs = $queryParkings->fetch())
{
$properties = array("capacity"=>$rs["capacity"]);
$obj_label = "";
// Parking type label
if($rs["type"] == "")
$obj_label .= $PARKING_LABEL["empty"];
else if(isset($PARKING_LABEL[$rs["type"]]))
$obj_label .= $PARKING_LABEL[$rs["type"]];
else
$obj_label .= $PARKING_LABEL["other"];
$obj_label .= ", ";
// Capacity
if($rs["capacity"] > 0)
$obj_label .= sprintf($LABELS["map.parking.capacity"],$rs["capacity"]);
else
$obj_label .= $LABELS["map.parking.noCapacity"];
// is the parking covered
if(isset($COVERED_LABEL[$rs["covered"]]))
$obj_label .= ", ".$COVERED_LABEL[$rs["covered"]];
// access informations
if(isset($rs["operator"]) && $rs["operator"] != "")
{
$accessLabel = $LABELS['map.parking.accessLabelWithOpr'];
if($rs["access"] == "")
$obj_label .= " ".$accessLabel["empty"];
else if(isset($accessLabel[$rs["access"]]))
$obj_label .= " ".sprintf($accessLabel[$rs["access"]],$rs["operator"]);
else
$obj_label .= " ".$accessLabel["other"];
}
else
{
$accessLabel = $LABELS['map.parking.accessLabel'];
if($rs["access"] == "")
$obj_label .= " ".$accessLabel["empty"];
else if(isset($accessLabel[$rs["access"]]))
$obj_label .= " ".$accessLabel[$rs["access"]];
else
$obj_label .= " ".$accessLabel["other"];
}
$properties["popup"] = $obj_label;
$feature = array(
'type' => 'Feature',
'geometry' => json_decode($rs['geojson'], true),
'properties' => $properties
);
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
}
/*
Ask the the server for the distance beetween a point and the closest parking
*/
else if($_REQUEST["get"] == "distance" && isset($_REQUEST["lon"]) && isset($_REQUEST["lat"]))
{
$result = array("distance"=>0);
$geomString = "POINT(".$_REQUEST["lon"]." ".$_REQUEST["lat"].")";
$sqlDistance = "select min(st_distance(st_transform(the_geom,:proj), st_transform(st_geomfromtext(:point,4326),:proj2))) as distance from pv_parkings where access <> 'private'";
$queryDistance = $PDO->prepare($sqlDistance);
$queryDistance->execute(array(":proj"=>DIST_PROJ,":proj2"=>DIST_PROJ,":point"=>$geomString));
if($rs = $queryDistance->fetch())
{
$result = array("distance"=>sprintf($LABELS["map.distanceToolLabel"],floor($rs["distance"])));
}
header('Content-type: application/json');
echo json_encode($result, JSON_NUMERIC_CHECK);
}
/* Calculate the numbers of parkings (with capacity) per bicycle_parking key
- by default, in the whole area
- restricted to a given area, with a "geom" parameter (must be a GeoJSON feature)
*/
else if($_REQUEST["get"] == "stats")
{
$result = array();
$result["content"] = '<div class="private">'.calculateStats($PDO,$LABELS,"",$_REQUEST["geom"]).'</div>';
$result["content"] .= '<div class="noPrivate">'.calculateStats($PDO,$LABELS," and access <> 'private' ",$_REQUEST["geom"]).'</div>';
header('Content-type: application/json');
echo json_encode($result, JSON_NUMERIC_CHECK);
}
else if($_REQUEST["get"] == "badObj")
{
// put every answer in the KML response
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
/* There is warning about data quality when :
- there is no capacity (and it is not in private access, it is often impossible to determine the capacity in such a case)
- the type is unknown
- there is another bicycle parking with equal coordinates */
$sqlBadParkings = "SELECT obj_id,capacity,parking_type as type,ST_AsGeoJSON(public.ST_Transform((the_geom),4326),6) AS geojson,(select count(*) from pv_parkings SR where P.the_geom = SR.the_geom and P.obj_id <> SR.obj_id) as doubloons FROM pv_parkings P where (capacity = 0 and access<>'private' or parking_type = '' or exists(select * from pv_parkings SR where P.the_geom = SR.the_geom and P.obj_id <> SR.obj_id)) ".getZoneFilter(isset($_REQUEST["zones"])?$_REQUEST["zones"]:"");
$queryBadParkings = $PDO->query($sqlBadParkings);
while($rs = $queryBadParkings->fetch())
{
$label = "";
if($rs["type"] == "")
{
$label .= $LABELS["map.bad.noType"];
}
if($rs["capacity"] == 0)
{
$label .= $LABELS["map.bad.noCapacity"];
}
if($rs["doubloons"] > 0)
{
$label .= $LABELS["map.bad.doubloon"];
}
if(EDIT_JOSM)
{
$label .= '<br><a href="http://localhost:8111/load_object?objects='.$rs["obj_id"].'" target="hiddenIframe">'.$LABELS["map.bad.edit"].'</a>';
}
$feature = array(
'type' => 'Feature',
'geometry' => json_decode($rs["geojson"], true),
'properties' => array("label"=>$label)
);
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
}
/*
This request for the area surrouning the bicycle parkings
*/
else if($_REQUEST["get"] == "surroundingArea")
{
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
$sqlBadParkings = "SELECT distance,ST_AsGeoJSON(public.ST_Transform(geom,4326),5) AS geojson FROM pv_parking_dist_zones where 1=1 ".getZoneFilter(isset($_REQUEST["zones"])?$_REQUEST["zones"]:"")." order by distance DESC";
$queryBadParkings = $PDO->query($sqlBadParkings);
while($rs = $queryBadParkings->fetch())
{
// Retrieve the fill colour associated with the threshold
$colour = "";
foreach($DISTANCE_LEVELS as $distElt)
{
if($distElt["dist"] == $rs["distance"])
{
$colour = $distElt["colour"];
}
}
$feature = array(
'type' => 'Feature',
'geometry' => json_decode($rs["geojson"], true),
'properties' => array("style"=>array(
"color"=>$colour,
"stroke"=>false,
"fillOpacity"=>0.3))
);
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
}
else if($_REQUEST["get"] == "boundaries")
{
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
$sqlBadParkings = "SELECT ST_AsGeoJSON(public.ST_Transform(geom,4326),5) AS geojson FROM pv_zones where active = 1 ".getZoneFilter(isset($_REQUEST["zones"])?$_REQUEST["zones"]:"");
$queryBadParkings = $PDO->query($sqlBadParkings);
while($rs = $queryBadParkings->fetch())
{
$feature = array(
'type' => 'Feature',
'geometry' => json_decode($rs["geojson"], true),
'properties' => array("style"=>array(
"color"=>'#555',
"stroke"=>true,
"weight"=>2,
"fill"=>false,
"opacity"=>1))
);
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
}
else if($_REQUEST["get"] == "zones")
{
// put every answer in the KML response
$result = array();
$sqlZones = "SELECT P.zone_id,label,visible_default,sum(capacity) as spaces FROM pv_zones Z, pv_parkings P WHERE active = 1 and access <> 'private' AND P.zone_id = Z.zone_id GROUP BY P.zone_id,label,visible_default ORDER BY label";
$queryZones = $PDO->query($sqlZones);
while($rs = $queryZones->fetch(PDO::FETCH_ASSOC))
{
array_push($result, $rs);
}
header('Content-type: application/json');
echo json_encode($result, JSON_NUMERIC_CHECK);
}
}
?> | agpl-3.0 |
iamy/fx | modules/dp_bkrv/language/en_us.lang.php | 3867 | <?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".
*/
$mod_strings = array (
'LBL_ASSIGNED_TO_ID' => 'Assigned User Id',
'LBL_ASSIGNED_TO_NAME' => 'Assigned to',
'LBL_SECURITYGROUPS' => 'Security Groups',
'LBL_SECURITYGROUPS_SUBPANEL_TITLE' => 'Security Groups',
'LBL_ID' => 'ID',
'LBL_DATE_ENTERED' => 'Date Created',
'LBL_DATE_MODIFIED' => 'Date Modified',
'LBL_MODIFIED' => 'Modified By',
'LBL_MODIFIED_ID' => 'Modified By Id',
'LBL_MODIFIED_NAME' => 'Modified By Name',
'LBL_CREATED' => 'Created By',
'LBL_CREATED_ID' => 'Created By Id',
'LBL_DESCRIPTION' => 'Description',
'LBL_DELETED' => 'Deleted',
'LBL_NAME' => 'Name',
'LBL_CREATED_USER' => 'Created by User',
'LBL_MODIFIED_USER' => 'Modified by User',
'LBL_LIST_NAME' => 'Name',
'LBL_EDIT_BUTTON' => 'Edit',
'LBL_REMOVE' => 'Remove',
'LBL_LIST_FORM_TITLE' => 'Банковские реквизиты List',
'LBL_MODULE_NAME' => 'Банковские реквизиты',
'LBL_MODULE_TITLE' => 'Банковские реквизиты',
'LBL_HOMEPAGE_TITLE' => 'My Банковские реквизиты',
'LNK_NEW_RECORD' => 'Create Банковские реквизиты',
'LNK_LIST' => 'View Банковские реквизиты',
'LNK_IMPORT_DP_BKRV' => 'Импорт Банковские реквизиты',
'LBL_SEARCH_FORM_TITLE' => ' Банковские реквизиты',
'LBL_HISTORY_SUBPANEL_TITLE' => 'View History',
'LBL_ACTIVITIES_SUBPANEL_TITLE' => 'Activities',
'LBL_DP_BKRV_SUBPANEL_TITLE' => 'Банковские реквизиты',
'LBL_NEW_FORM_TITLE' => 'New Банковские реквизиты',
'LBL_RSCH' => 'Расчётный счёт',
'LBL_KRCH' => 'Корреспондентский счет',
'LBL_BIK_BANK' => 'БИК банка',
'LBL_INN_BANK' => 'ИНН банка',
); | agpl-3.0 |
lasko2112/legend-of-hondo | MMOCoreORB/bin/scripts/mobile/naboo/gungan_mercenary.lua | 1054 | gungan_mercenary = Creature:new {
objectName = "@mob/creature_names:gungan_mercenary",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "gungan",
faction = "gungan",
level = 14,
chanceHit = 0.3,
damageMin = 150,
damageMax = 160,
baseXp = 831,
baseHAM = 2000,
baseHAMmax = 2400,
armor = 0,
resists = {0,0,0,0,15,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {"object/mobile/gungan_male.iff"},
lootGroups = {
{
groups = {
{group = "junk", chance = 4000000},
{group = "gungan_common", chance = 2000000},
{group = "tailor_components", chance = 2000000},
{group = "loot_kit_parts", chance = 2000000}
}
}
},
weapons = {"rebel_weapons_medium"},
conversationTemplate = "",
attacks = merge(brawlermid,marksmanmid)
}
CreatureTemplates:addCreatureTemplate(gungan_mercenary, "gungan_mercenary")
| agpl-3.0 |
colares/touke-flow | Packages/Application/TYPO3.Surf/Classes/TYPO3/Surf/Domain/Model/Application.php | 5709 | <?php
namespace TYPO3\Surf\Domain\Model;
/* *
* This script belongs to the TYPO3 Flow package "TYPO3.Surf". *
* *
* */
use TYPO3\Surf\Exception\InvalidConfigurationException;
/**
* A generic application without any tasks
*
*/
class Application {
/**
* The name
* @var string
*/
protected $name;
/**
* The nodes for this application
* @var array
*/
protected $nodes = array();
/**
* The deployment path for this application on a node
* @var string
*/
protected $deploymentPath;
/**
* The options
* @var array
*/
protected $options = array();
/**
* Constructor
*
* @param string $name
*/
public function __construct($name) {
$this->name = $name;
}
/**
* Register tasks for this application
*
* This is a template method that should be overriden by specific applications to define
* new task or to add tasks to the workflow.
*
* Example:
*
* $workflow->addTask('typo3.surf:createdirectories', 'initialize', $this);
*
* @param \TYPO3\Surf\Domain\Model\Workflow $workflow
* @param \TYPO3\Surf\Domain\Model\Deployment $deployment
* @return void
*/
public function registerTasks(Workflow $workflow, Deployment $deployment) {}
/**
* Get the application name
*
* @return string
*/
public function getName() {
return $this->name;
}
/**
* Sets the application name
*
* @param string $name
* @return \TYPO3\Surf\Domain\Model\Application The current instance for chaining
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get the nodes where this application should be deployed
*
* @return array The application nodes
*/
public function getNodes() {
return $this->nodes;
}
/**
* Set the nodes where this application should be deployed
*
* @param array $nodes The application nodes
* @return \TYPO3\Surf\Domain\Model\Application The current instance for chaining
*/
public function setNodes(array $nodes) {
$this->nodes = $nodes;
return $this;
}
/**
* Add a node where this application should be deployed
*
* @param \TYPO3\Surf\Domain\Model\Node $node The node to add
* @return \TYPO3\Surf\Domain\Model\Application The current instance for chaining
*/
public function addNode(Node $node) {
$this->nodes[$node->getName()] = $node;
return $this;
}
/**
* Return TRUE if the given node is registered for this application
*
* @param Node $node The node to test
* @return boolean TRUE if the node is registered for this application
*/
public function hasNode(Node $node) {
return isset($this->nodes[$node->getName()]);
}
/**
* Get the deployment path for this application
*
* This is the path for an application pointing to the root of the Surf deployment:
*
* [deploymentPath]
* |-- releases
* |-- cache
* |-- shared
*
* @return string The deployment path
* @throws \TYPO3\Surf\Exception\InvalidConfigurationException If no deployment path was set
*/
public function getDeploymentPath() {
/*
* FIXME Move check somewhere else
*
if ($this->deploymentPath === NULL) {
throw new InvalidConfigurationException(sprintf('No deployment path has been defined for application %s.', $this->name), 1312220645);
}
*/
return $this->deploymentPath;
}
/**
* Get the path for shared resources for this application
*
* This path defaults to a directory "shared" below the deployment path.
*
* @return string The shared resources path
*/
public function getSharedPath() {
return $this->getDeploymentPath() . '/shared';
}
/**
* Sets the deployment path
*
* @param string $deploymentPath The deployment path
* @return \TYPO3\Surf\Domain\Model\Application The current instance for chaining
*/
public function setDeploymentPath($deploymentPath) {
$this->deploymentPath = rtrim($deploymentPath, '/');
return $this;
}
/**
* Get all options defined on this application instance
*
* The options will include the deploymentPath and sharedPath for
* unified option handling.
*
* @return array An array of options indexed by option key
*/
public function getOptions() {
return array_merge($this->options, array(
'deploymentPath' => $this->getDeploymentPath(),
'sharedPath' => $this->getSharedPath()
));
}
/**
* Get an option defined on this application instance
*
* @param string $key
* @return mixed
*/
public function getOption($key) {
switch ($key) {
case 'deploymentPath':
return $this->deploymentPath;
case 'sharedPath':
return $this->getSharedPath();
default:
return $this->options[$key];
}
}
/**
* Test if an option was set for this application
*
* @param string $key The option key
* @return boolean TRUE If the option was set
*/
public function hasOption($key) {
return array_key_exists($key, $this->options);
}
/**
* Sets all options for this application instance
*
* @param array $options The options to set indexed by option key
* @return \TYPO3\Surf\Domain\Model\Application The current instance for chaining
*/
public function setOptions($options) {
$this->options = $options;
return $this;
}
/**
* Set an option for this application instance
*
* @param string $key The option key
* @param mixed $value The option value
* @return \TYPO3\Surf\Domain\Model\Application The current instance for chaining
*/
public function setOption($key, $value) {
$this->options[$key] = $value;
return $this;
}
}
?> | agpl-3.0 |
kittiu/sale-workflow | sale_order_invoicing_finished_task/__manifest__.py | 777 | # -*- coding: utf-8 -*-
# Copyright 2017 Sergio Teruel <sergio.teruel@tecnativa.com>
# Copyright 2017 Carlos Dauden <carlos.dauden@tecnativa.com>
# Copyright 2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Sale Order Invoicing Finished Task",
"summary": "Control invoice order lines if his task has been finished",
"version": "10.0.1.0.3",
"category": "Sales",
"website": "https://github.com/OCA/sale-workflow",
"author": "Tecnativa, "
"Camptocamp, "
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": [
"sale_timesheet",
],
"data": [
"views/product_view.xml",
"views/project_view.xml",
],
}
| agpl-3.0 |
AydinSakar/sql-layer | src/main/java/com/foundationdb/sql/optimizer/rule/range/RangeEndpoint.java | 9388 | /**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* 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.foundationdb.sql.optimizer.rule.range;
import com.foundationdb.sql.optimizer.plan.ConstantExpression;
public abstract class RangeEndpoint implements Comparable<RangeEndpoint> {
public abstract boolean isUpperWild();
public abstract ConstantExpression getValueExpression();
public abstract Object getValue();
public abstract boolean isInclusive();
public abstract String describeValue();
@Override
public int compareTo(RangeEndpoint o) {
ComparisonResult comparison = compareEndpoints(this, o);
switch (comparison) {
case LT:
case LT_BARELY:
return -1;
case GT:
case GT_BARELY:
return 1;
case EQ:
return 0;
case INVALID:
default:
throw new IllegalComparisonException(this.getValue(), o.getValue());
}
}
public ComparisonResult comparePreciselyTo(RangeEndpoint other) {
return compareEndpoints(this, other);
}
public static ValueEndpoint inclusive(ConstantExpression value) {
return new ValueEndpoint(value, true);
}
public static ValueEndpoint exclusive(ConstantExpression value) {
return new ValueEndpoint(value, false);
}
public static RangeEndpoint of(ConstantExpression value, boolean inclusive) {
return new ValueEndpoint(value, inclusive);
}
private RangeEndpoint() {}
/**
* Returns whether the two endpoints are LT, GT or EQ to each other.
* @param point1 the first point
* @param point2 the second point
* @return LT if point1 is less than point2; GT if point1 is greater than point2; EQ if point1 is greater than
* point2; and INVALID if the two points can't be compared
*/
private static ComparisonResult compareEndpoints(RangeEndpoint point1, RangeEndpoint point2)
{
if (point1.equals(point2))
return ComparisonResult.EQ;
// At this point we know they're not both upper wild. If either one is, we know the answer.
if (point1.isUpperWild())
return ComparisonResult.GT;
if (point2.isUpperWild())
return ComparisonResult.LT;
// neither is wild
ComparisonResult comparison = compareObjects(point1.getValue(), point2.getValue());
if (comparison == ComparisonResult.EQ && (point1.isInclusive() != point2.isInclusive())) {
if (point1.isInclusive())
return ComparisonResult.LT_BARELY;
assert point2.isInclusive() : point2;
return ComparisonResult.GT_BARELY;
}
return comparison;
}
@SuppressWarnings("unchecked") // We know that oneT and twoT are both Comparables of the same class.
private static ComparisonResult compareObjects(Object one, Object two) {
// if both are null, they're equal. Otherwise, at most one can be null; if either is null, we know the
// answer. Otherwise, we know neither is null, and we can test their values (after checking the classes)
if (one == two)
return ComparisonResult.EQ;
if (one == null)
return ComparisonResult.LT;
if (two == null)
return ComparisonResult.GT;
int compareResult;
if (one.getClass().equals(two.getClass())) {
if (!(one instanceof Comparable))
return ComparisonResult.INVALID;
Comparable oneT = (Comparable) one;
Comparable twoT = (Comparable) two;
compareResult = (oneT).compareTo(twoT);
}
else if (((one.getClass() == Byte.class) || (one.getClass() == Short.class) ||
(one.getClass() == Integer.class) || (one.getClass() == Long.class)) &&
((two.getClass() == Byte.class) || (two.getClass() == Short.class) ||
(two.getClass() == Integer.class) || (two.getClass() == Long.class))) {
Number oneT = (Number) one;
Number twoT = (Number) two;
// TODO: JDK 7 this is in Long.
compareResult = com.google.common.primitives.Longs.compare(oneT.longValue(),
twoT.longValue());
}
else
return ComparisonResult.INVALID;
if (compareResult < 0)
return ComparisonResult.LT;
else if (compareResult > 0)
return ComparisonResult.GT;
else
return ComparisonResult.EQ;
}
public static final RangeEndpoint UPPER_WILD = new Wild();
public static final RangeEndpoint NULL_EXCLUSIVE = exclusive(ConstantExpression.typedNull(null, null, null));
public static final RangeEndpoint NULL_INCLUSIVE = inclusive(NULL_EXCLUSIVE.getValueExpression());
private static class Wild extends RangeEndpoint {
@Override
public boolean isUpperWild() {
return true;
}
@Override
public Object getValue() {
throw new UnsupportedOperationException();
}
@Override
public ConstantExpression getValueExpression() {
return null;
}
@Override
public boolean isInclusive() {
return false;
}
@Override
public String toString() {
return "(*)";
}
@Override
public String describeValue() {
return "*";
}
}
private static class ValueEndpoint extends RangeEndpoint {
@Override
public ConstantExpression getValueExpression() {
return valueExpression;
}
@Override
public Object getValue() {
return valueExpression.getValue();
}
@Override
public boolean isInclusive() {
return inclusive;
}
@Override
public boolean isUpperWild() {
return false;
}
@Override
public String toString() {
return valueExpression + (inclusive ? " inclusive" : " exclusive");
}
@Override
public String describeValue() {
Object value = getValue();
return value == null ? "NULL" : value.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ValueEndpoint that = (ValueEndpoint) o;
return inclusive == that.inclusive && !(valueExpression != null ? !valueExpression.equals(that.valueExpression) : that.valueExpression != null);
}
@Override
public int hashCode() {
int result = valueExpression != null ? valueExpression.hashCode() : 0;
result = 31 * result + (inclusive ? 1 : 0);
return result;
}
private ValueEndpoint(ConstantExpression valueExpression, boolean inclusive) {
this.valueExpression = valueExpression;
this.inclusive = inclusive;
}
private ConstantExpression valueExpression;
private boolean inclusive;
}
static class IllegalComparisonException extends RuntimeException {
private IllegalComparisonException(Object one, Object two) {
super(String.format("couldn't sort objects <%s> and <%s>",
one,
two
));
}
}
enum RangePointComparison {
MIN() {
@Override
protected Object select(Object one, Object two, ComparisonResult comparison) {
return comparison == ComparisonResult.LT ? one : two;
}
},
MAX() {
@Override
protected Object select(Object one, Object two, ComparisonResult comparison) {
return comparison == ComparisonResult.GT ? one : two;
}
}
;
protected abstract Object select(Object one, Object two, ComparisonResult comparison);
public Object get(Object one, Object two) {
ComparisonResult comparisonResult = compareObjects(one, two);
switch (comparisonResult) {
case EQ:
return one;
case LT_BARELY:
case LT:
case GT_BARELY:
case GT:
return select(one, two, comparisonResult.normalize());
case INVALID:
return null;
default:
throw new AssertionError(comparisonResult.name());
}
}
public static final Object INVALID_COMPARISON = new Object();
}
}
| agpl-3.0 |
yonkon/nedvig | custom/modules/Cosib_postsale/metadata/dashletviewdefs.php | 1513 | <?php
$dashletData['Cosib_postsaleDashlet']['searchFields'] = array (
'cosib_postshr_client_name' =>
array (
'default' => '',
),
'cosib_postshr_object_name' =>
array (
'default' => '',
),
'assigned_user_name' =>
array (
'default' => '',
),
'description' =>
array (
'default' => '',
),
'date_entered' =>
array (
'default' => '',
),
);
$dashletData['Cosib_postsaleDashlet']['columns'] = array (
'cosib_postshr_client_name' =>
array (
'type' => 'relate',
'link' => 'cosib_postsle_sphr_client',
'label' => 'LBL_COSIB_POSTSALE_SPHR_CLIENT_FROM_SPHR_CLIENT_TITLE',
'width' => '10%',
'default' => true,
),
'cosib_postshr_object_name' =>
array (
'type' => 'relate',
'link' => 'cosib_postsle_sphr_object',
'label' => 'LBL_COSIB_POSTSALE_SPHR_OBJECT_FROM_SPHR_OBJECT_TITLE',
'width' => '10%',
'default' => true,
),
'assigned_user_name' =>
array (
'width' => '8%',
'label' => 'LBL_LIST_ASSIGNED_USER',
'name' => 'assigned_user_name',
'default' => true,
),
'date_entered' =>
array (
'width' => '15%',
'label' => 'LBL_DATE_ENTERED',
'default' => true,
'name' => 'date_entered',
),
'date_modified' =>
array (
'width' => '15%',
'label' => 'LBL_DATE_MODIFIED',
'name' => 'date_modified',
'default' => false,
),
'created_by' =>
array (
'width' => '8%',
'label' => 'LBL_CREATED',
'name' => 'created_by',
'default' => false,
),
);
| agpl-3.0 |
dhosa/yamcs | yamcs-xtce/src/main/java/org/yamcs/xtce/AlarmRanges.java | 3618 | package org.yamcs.xtce;
import java.io.Serializable;
/**
* Contains five ranges: Watch, Warning, Distress, Critical, and Severe each in increasing severity.
* Normally, only the Warning and Critical ranges are used and the color yellow is associated with Warning
* and the color red is associated with Critical. The ranges given are valid for numbers lower than the
* min and higher than the max values. These ranges should not overlap, but if they do, assume the most
* severe range is to be applied. All ranges are optional and it is quite allowed for there to be only one
* end of the range. Range values are in calibrated engineering units.
* @author nm
*
*/
public class AlarmRanges implements Serializable {
private static final long serialVersionUID = 200706052351L;
FloatRange watchRange=null;
FloatRange warningRange=null;
FloatRange distressRange=null;
FloatRange criticalRange=null;
FloatRange severeRange=null;
public void addWatchRange(FloatRange range) {
if(this.watchRange == null) {
this.watchRange = range;
} else {
this.watchRange = this.watchRange.intersectWith(range);
}
}
public void addWarningRange(FloatRange range) {
if(this.warningRange == null) {
this.warningRange = range;
} else {
this.warningRange = this.warningRange.intersectWith(range);
}
}
public void addDistressRange(FloatRange range) {
if(this.distressRange == null) {
this.distressRange = range;
} else {
this.distressRange = this.distressRange.intersectWith(range);
}
}
public void addCriticalRange(FloatRange range) {
if(this.criticalRange == null) {
this.criticalRange = range;
} else {
this.criticalRange = this.criticalRange.intersectWith(range);
}
}
public void addSevereRange(FloatRange range) {
if(this.severeRange == null) {
this.severeRange = range;
} else {
this.severeRange = this.severeRange.intersectWith(range);
}
}
public void addRange(FloatRange range, AlarmLevels level) {
switch(level) {
case watch:
addWatchRange(range);
break;
case warning:
addWarningRange(range);
break;
case distress:
addDistressRange(range);
break;
case critical:
addCriticalRange(range);
break;
case severe:
addSevereRange(range);
break;
default:
throw new RuntimeException("Level '"+level+"' not allowed for alarm ranges");
}
}
public FloatRange getWatchRange() {
return watchRange;
}
public FloatRange getWarningRange() {
return warningRange;
}
public FloatRange getDistressRange() {
return distressRange;
}
public FloatRange getCriticalRange() {
return criticalRange;
}
public FloatRange getSevereRange() {
return severeRange;
}
public void setWarningRange(FloatRange warningRange) {
this.warningRange=warningRange;
}
@Override
public String toString() {
return ((watchRange!=null)?"watchRange"+watchRange:"")+
((warningRange!=null)?"warningRange"+warningRange:"")+
((distressRange!=null)?"distressRange"+distressRange:"")+
((criticalRange!=null)?"criticalRange"+criticalRange:"")+
((severeRange!=null)?" severeRange"+severeRange:"");
}
}
| agpl-3.0 |
Rhetos/Rhetos | CommonConcepts/Plugins/Rhetos.Dsl.DefaultConcepts/DataStructure/Writing/OnSaveValidateInfo.cs | 2367 | /*
Copyright (C) 2014 Omega software d.o.o.
This file is part of Rhetos.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rhetos.Dsl;
using System.ComponentModel.Composition;
namespace Rhetos.Dsl.DefaultConcepts
{
/// <summary>
/// Implement a custom data validation. If possible, use InvalidData instead, for standard data validations, or RowPermissions for user permissions.
/// </summary>
[Export(typeof(IConceptInfo))]
[ConceptKeyword("OnSaveValidate")]
public class OnSaveValidateInfo : IConceptInfo
{
[ConceptKey]
public SaveMethodInfo SaveMethod { get; set; }
/// <summary>
/// Name of this business rule, unique among this entity's validations.
/// </summary>
[ConceptKey]
public string RuleName { get; set; }
/// <summary>
/// Available variables in this context:
/// _executionContext,
/// checkUserPermissions (whether the Save command is called directly by client through a web API)
/// inserted (array of new items),
/// updated (array of new items).
/// If LoadOldItems concept is used, there are also available:
/// updatedOld (array of old items),
/// deletedOld (array of old items).
/// Throw Rhetos.UserException("message to the user") if the Save command should be canceled and all changes rolled back.
/// See WritableOrmDataStructureCodeGenerator.OnSaveTag2 for more info.
/// </summary>
public string CsCodeSnippet { get; set; }
}
}
| agpl-3.0 |
dmitr25/demobbed-viewer | js/nuEventsData/nuMu/loadEvent12092022698.js | 9933 | demobbed.resetEvent();
demobbed.event().id(12092022698);
demobbed.event().date(1333258910000);
demobbed.event().hitsTT()[0] = [
new HitTT(10000, 28.16, -504.58, 69.8),
new HitTT(10001, 36.08, -504.58, 25.5),
new HitTT(10002, 25.58, -491.18, 8.97),
new HitTT(10003, 33.5, -491.18, 24.15),
new HitTT(10004, 30.86, -491.18, 7.21),
new HitTT(10005, 28.22, -491.18, 21.24),
new HitTT(10006, 25.32, -477.78, 9.48),
new HitTT(10007, 30.6, -477.78, 7.69),
new HitTT(10008, 33.45, -464.38, 12.54),
new HitTT(10009, 30.81, -464.38, 3.84),
new HitTT(10010, 22.89, -464.38, 8.63),
new HitTT(10011, 33.32, -450.98, 26.98),
new HitTT(10012, 22.76, -450.98, 21.32),
new HitTT(10013, 19.97, -437.58, 7.82),
new HitTT(10014, 33.17, -437.58, 11.2),
new HitTT(10015, 36.25, -424.18, 19.42),
new HitTT(10016, 17.77, -424.18, 16.24),
new HitTT(10017, 17.33, -410.78, 20.39),
new HitTT(10018, 10.17, -397.38, 15.26),
new HitTT(10019, 15.45, -397.38, 2.2),
new HitTT(10020, 15.27, -383.98, 14.45),
new HitTT(10021, 11.94, -370.58, 12.57),
new HitTT(10022, -50.8, 161.59, 8.16),
new HitTT(10023, -50.89, 174.99, 3.28),
new HitTT(10024, -53.66, 188.39, 22.4),
new HitTT(10025, -54.22, 201.79, 40.18),
new HitTT(10026, -56.82, 215.19, 12.97),
new HitTT(10027, -59.53, 228.59, 15.54),
new HitTT(10028, -56.89, 228.59, 9.67),
new HitTT(10029, -59.29, 241.99, 53.05),
new HitTT(10030, -59.26, 255.39, 8.04),
new HitTT(10031, -64.46, 268.79, 7.48),
new HitTT(10032, -61.82, 268.79, 12.82),
new HitTT(10033, -64.96, 282.19, 13.24),
new HitTT(10034, -64.77, 295.59, 9.11),
new HitTT(10035, -64.84, 308.99, 3.97),
new HitTT(10036, -67.19, 322.39, 10.45),
new HitTT(10037, -67.33, 335.79, 2.03),
new HitTT(10038, -69.81, 362.59, 23.3),
new HitTT(10039, -70.36, 375.99, 16),
new HitTT(10040, -70.09, 389.39, 11.11),
new HitTT(10041, -70.12, 402.79, 20.55),
new HitTT(10042, -72.78, 416.19, 12.49),
new HitTT(10043, -72.63, 429.59, 27.66),
new HitTT(10044, -72.3, 442.99, 6.6),
new HitTT(10045, -74.98, 456.39, 5.88),
new HitTT(10046, -74.97, 469.79, 12.47),
new HitTT(10047, -75.12, 483.19, 13.45),
new HitTT(10048, -75.17, 496.59, 17.3),
new HitTT(10049, -78.39, 509.99, 14.52),
new HitTT(10050, -80.53, 523.39, 64.04)
];
demobbed.event().hitsTT()[1] = [
new HitTT(11000, -84.8, -506.04, 13.59),
new HitTT(11001, -95.36, -506.04, 23.78),
new HitTT(11002, -92.72, -506.04, 5.44),
new HitTT(11003, -87.44, -506.04, 37.61),
new HitTT(11004, -89.56, -492.64, 15.61),
new HitTT(11005, -94.84, -492.64, 9.55),
new HitTT(11006, -81.64, -492.64, 4.63),
new HitTT(11007, -92.65, -479.24, 4.31),
new HitTT(11008, -87.37, -479.24, 13.2),
new HitTT(11009, -81.96, -465.84, 18.85),
new HitTT(11010, -92.52, -465.84, 15.85),
new HitTT(11011, -93.01, -452.44, 29.54),
new HitTT(11012, -79.81, -452.44, 15.47),
new HitTT(11013, -74.14, -439.04, 21.34),
new HitTT(11014, -92.62, -439.04, 20.2),
new HitTT(11015, -69.11, -425.64, 7.66),
new HitTT(11016, -92.87, -425.64, 23.28),
new HitTT(11017, -92.9, -412.24, 4.24),
new HitTT(11018, -92.33, -398.84, 15.7),
new HitTT(11019, -92.15, -385.44, 32.35),
new HitTT(11020, -90.66, -372.04, 17.82),
new HitTT(11021, -74.31, 173.53, 19.14),
new HitTT(11022, -74.24, 186.93, 19.77),
new HitTT(11023, -72.35, 200.33, 25.53),
new HitTT(11024, -71.63, 213.73, 15.36),
new HitTT(11025, -71.77, 227.13, 17.14),
new HitTT(11026, -71.53, 240.53, 23.53),
new HitTT(11027, -71.64, 253.93, 15.35),
new HitTT(11028, -71.59, 267.33, 15.37),
new HitTT(11029, -68.94, 280.73, 7.29),
new HitTT(11030, -68.81, 294.13, 12.18),
new HitTT(11031, -68.91, 307.53, 23.55),
new HitTT(11032, -69.09, 320.93, 10.12),
new HitTT(11033, -69.39, 334.33, 23.2),
new HitTT(11034, -66.75, 334.33, 13.19),
new HitTT(11035, -69.3, 347.73, 18.93),
new HitTT(11036, -69.21, 361.13, 15.43),
new HitTT(11037, -66.74, 374.53, 6.81),
new HitTT(11038, -66.26, 387.93, 14.53),
new HitTT(11039, -66.27, 401.33, 12.25),
new HitTT(11040, -66.48, 414.73, 9.52),
new HitTT(11041, -66.33, 428.13, 24.14),
new HitTT(11042, -63.63, 441.53, 28.41),
new HitTT(11043, -63.78, 454.93, 10.56),
new HitTT(11044, -63.62, 468.33, 9.92),
new HitTT(11045, -63.87, 481.73, 22.9),
new HitTT(11046, -63.82, 495.13, 12.55),
new HitTT(11047, -61.34, 508.53, 37.99),
new HitTT(11048, -61.67, 521.93, 6.73)
];
demobbed.event().hitsRPC()[0] = [
new HitRPC(20000, 1.9, -261.48, 7.8),
new HitRPC(20001, -0.7, -247.48, 2.6),
new HitRPC(20002, -0.7, -240.48, 2.6),
new HitRPC(20003, -3.3, -219.48, 2.6),
new HitRPC(20004, -5.9, -212.48, 2.6),
new HitRPC(20005, -5.9, -205.48, 2.6),
new HitRPC(20006, -5.9, -198.48, 2.6),
new HitRPC(20007, -7.2, -191.48, 5.2),
new HitRPC(20008, -26.7, -60.18, 2.6),
new HitRPC(20009, -26.7, -53.18, 2.6),
new HitRPC(20010, -29.3, -46.18, 2.6),
new HitRPC(20011, -29.3, -39.18, 2.6),
new HitRPC(20012, -30.6, -32.18, 5.2),
new HitRPC(20013, -30.6, -25.18, 10.4),
new HitRPC(20014, -38.4, -18.18, 15.6),
new HitRPC(20015, -31.9, -11.18, 2.6),
new HitRPC(20016, -26.7, -11.18, 2.6),
new HitRPC(20017, -34.5, -4.18, 7.8),
new HitRPC(20018, -34.5, 2.82, 7.8),
new HitRPC(20019, -34.5, 9.82, 2.6),
new HitRPC(20020, -91.5, 672.71, 2.6),
new HitRPC(20021, -92.8, 679.71, 5.2),
new HitRPC(20022, -92.8, 686.71, 5.2),
new HitRPC(20023, -94.1, 693.71, 2.6),
new HitRPC(20024, -96.7, 707.71, 2.6),
new HitRPC(20025, -96.7, 714.71, 2.6),
new HitRPC(20026, -98, 721.71, 5.2),
new HitRPC(20027, -99.3, 728.71, 2.6),
new HitRPC(20028, -99.3, 735.71, 2.6),
new HitRPC(20029, -100.6, 742.71, 5.2),
new HitRPC(20030, -120.1, 874.01, 2.6),
new HitRPC(20031, -122.7, 881.01, 2.6),
new HitRPC(20032, -122.7, 888.01, 2.6),
new HitRPC(20033, -124, 895.01, 5.2),
new HitRPC(20034, -125.3, 902.01, 2.6),
new HitRPC(20035, -125.3, 909.01, 7.8),
new HitRPC(20036, -125.3, 916.01, 2.6),
new HitRPC(20037, -125.3, 923.01, 2.6),
new HitRPC(20038, -126.6, 930.01, 5.2),
new HitRPC(20039, -127.9, 937.01, 2.6),
new HitRPC(20040, -127.9, 944.01, 2.6)
];
demobbed.event().hitsRPC()[1] = [
new HitRPC(21000, -89.2, -261.48, 3.5),
new HitRPC(21001, -89.2, -247.48, 3.5),
new HitRPC(21002, -89.2, -240.48, 3.5),
new HitRPC(21003, -89.2, -233.48, 3.5),
new HitRPC(21004, -89.2, -219.48, 3.5),
new HitRPC(21005, -85.7, -205.48, 3.5),
new HitRPC(21006, -85.7, -198.48, 3.5),
new HitRPC(21007, -85.7, -191.48, 3.5),
new HitRPC(21008, -80.45, -60.18, 7),
new HitRPC(21009, -80.45, -53.18, 7),
new HitRPC(21010, -80.45, -46.18, 7),
new HitRPC(21011, -80.45, -39.18, 7),
new HitRPC(21012, -80.45, -32.18, 7),
new HitRPC(21013, -99.7, -25.18, 3.5),
new HitRPC(21014, -83.95, -25.18, 14),
new HitRPC(21015, -80.45, -18.18, 35),
new HitRPC(21016, -82.2, -11.18, 10.5),
new HitRPC(21017, -80.45, -4.18, 7),
new HitRPC(21018, -80.45, 2.82, 7),
new HitRPC(21019, -78.7, 9.82, 3.5),
new HitRPC(21020, -65.2, 672.71, 3.5),
new HitRPC(21021, -65.2, 679.71, 3.5),
new HitRPC(21022, -65.2, 686.71, 3.5),
new HitRPC(21023, -68.7, 707.71, 3.5),
new HitRPC(21024, -68.7, 714.71, 3.5),
new HitRPC(21025, -68.7, 721.71, 3.5),
new HitRPC(21026, -68.7, 728.71, 3.5),
new HitRPC(21027, -68.7, 735.71, 3.5),
new HitRPC(21028, -68.7, 742.71, 3.5),
new HitRPC(21029, -79.2, 909.01, 3.5),
new HitRPC(21030, -79.2, 916.01, 3.5),
new HitRPC(21031, -82.7, 937.01, 3.5),
new HitRPC(21032, -82.7, 944.01, 3.5)
];
demobbed.event().hitsDT()[0] = [
new HitDT(30000, 11.51, -359.64, 0.47),
new HitDT(30001, 9.41, -356, 1.76),
new HitDT(30002, 10.41, -348.3, 0.46),
new HitDT(30003, 2.37, -289.45, 1.55),
new HitDT(30004, 4.47, -285.81, 1.07),
new HitDT(30005, 3.37, -281.75, 0.58),
new HitDT(30006, 1.27, -278.11, 1.41),
new HitDT(30007, -10.55, -178.56, 0.72),
new HitDT(30008, 380.05, -178.44, 1.82),
new HitDT(30009, 428.35, -174.79, 1.82),
new HitDT(30010, -9.56, -170.86, 1.59),
new HitDT(30011, 381.05, -170.74, 0.01),
new HitDT(30012, -11.66, -167.22, 0.43),
new HitDT(30013, -21.93, -84.65, 1.75),
new HitDT(30014, -24.03, -81.01, 0.49),
new HitDT(30015, -25.13, -76.95, 0.56),
new HitDT(30016, 23.17, -73.3, 1.41),
new HitDT(30017, -35.86, 22.99, 1.49),
new HitDT(30018, -37.96, 26.63, 0.58),
new HitDT(30019, -39.06, 30.69, 1.08),
new HitDT(30020, -36.96, 34.33, 1.48),
new HitDT(30021, -45.64, 124.06, 1.57),
new HitDT(30022, -47.74, 127.7, 0.41),
new HitDT(30023, -48.84, 131.76, 0.49),
new HitDT(30024, -50.94, 135.4, 1.39),
new HitDT(30025, -46.74, 135.4, 1.58),
new HitDT(30026, -84.61, 574.16, 0.83),
new HitDT(30027, -82.51, 577.8, 1.77),
new HitDT(30028, -83.61, 581.86, 1.09),
new HitDT(30029, -85.71, 585.5, 0.93),
new HitDT(30030, -89.96, 644.28, 0.57),
new HitDT(30031, -92.05, 647.92, 1.75),
new HitDT(30032, -88.95, 651.97, 1.8),
new HitDT(30033, -91.05, 655.62, 0.51),
new HitDT(30034, -103, 755.49, 0.6),
new HitDT(30035, -105.1, 759.13, 1.34),
new HitDT(30036, -106.2, 763.19, 1.77),
new HitDT(30037, -104.1, 766.83, 1.06),
new HitDT(30038, -118.09, 849.52, 0.6),
new HitDT(30039, -120.18, 853.16, 1.82),
new HitDT(30040, -119.18, 860.86, 0.63),
new HitDT(30041, -129.81, 960.5, 0.53),
new HitDT(30042, -130.91, 964.56, 1.02),
new HitDT(30043, -128.81, 968.2, 1.47),
new HitDT(30044, -134.3, 1058.12, 0.65),
new HitDT(30045, -136.4, 1061.76, 1.61),
new HitDT(30046, -133.3, 1065.82, 1.79),
new HitDT(30047, -135.39, 1069.46, 0.56)
];
demobbed.event().verticesECC([new Vertex([10070.7, 29676.7, 45177], [27.526, -94.4533, -511.974])]);
demobbed.event().tracksECC([
new TrackECC(0, 1, [10063.7, 29679.4, 45258], [-0.0882, 0.0351]),
new TrackECC(1, 2, [10077.3, 29692, 45258], [0.0828, 0.1888])
]);
demobbed.mgrDrawED().onEventChange();
demobbed.mgrDrawECC().onEventChange();
| agpl-3.0 |
veronikaslc/phenotips | components/patient-data/rest/src/main/java/org/phenotips/data/rest/DateTimeAdapter.java | 1661 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
*/
package org.phenotips.data.rest;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
/**
* Uses JodaTime's DateTime for representing dates in REST resources instead of JAXB's default,
* {@code XMLGregorianCalendar}.
*
* @version $Id$
* @since 1.2RC1
*/
public class DateTimeAdapter extends XmlAdapter<String, DateTime>
{
private static final DateTimeFormatter ISO_DATETIME_FORMATTER = ISODateTimeFormat.dateTime().withZone(
DateTimeZone.UTC);
@Override
public DateTime unmarshal(String v) throws Exception
{
return DateTime.parse(v);
}
@Override
public String marshal(DateTime v) throws Exception
{
return ISO_DATETIME_FORMATTER.print(v);
}
}
| agpl-3.0 |
KillBait/PrimordialCrops | src/main/java/killbait/PrimordialCrops/WorldGen/MagicalWorldGen.java | 1849 | package killbait.PrimordialCrops.WorldGen;
import killbait.PrimordialCrops.Config.PrimordialConfig;
import killbait.PrimordialCrops.Registry.ModBlocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkGenerator;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenMinable;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraftforge.fml.common.IWorldGenerator;
import java.util.Random;
public class MagicalWorldGen implements IWorldGenerator {
private WorldGenerator MinicioOre;
public MagicalWorldGen() {
this.MinicioOre = new WorldGenMinable(ModBlocks.MinicioOre.getDefaultState(), 7);
}
private void runGenerator(WorldGenerator generator, World world, Random rand, int chunk_X, int chunk_Z, int chancesToSpawn, int minHeight, int maxHeight) {
if (minHeight < 0 || maxHeight > 256 || minHeight > maxHeight)
throw new IllegalArgumentException("Illegal Height Arguments for WorldGenerator");
int heightDiff = maxHeight - minHeight + 1;
for (int i = 0; i < chancesToSpawn; i++) {
int x = chunk_X * 16 + rand.nextInt(16);
int y = minHeight + rand.nextInt(heightDiff);
int z = chunk_Z * 16 + rand.nextInt(16);
generator.generate(world, rand, new BlockPos(x, y, z));
}
}
@Override
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator,
IChunkProvider chunkProvider) {
switch (world.provider.getDimension()) {
case -1: //Nether
break;
case 1: //End
break;
default:
if (PrimordialConfig.enableOreSpawn) {
this.runGenerator(this.MinicioOre, world, random, chunkX, chunkZ, PrimordialConfig.oreSpawnChance, PrimordialConfig.oreSpawnMinZ, PrimordialConfig.oreSpawnMaxZ);
}
break;
}
}
}
| agpl-3.0 |
npcdoom/eSRO | EPL/src/packet_login.cpp | 1374 | /*********************************************************************************
*
* This file is part of eSRO.
*
* eSRO 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.
*
* eSRO 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 "packet_login.hpp"
#include "opcodes_shard_server.hpp"
#include <packet.hpp>
namespace srv_pkt
{
void WriteLoginShard (const boost::shared_ptr<OPacket> &pkt)
{
pkt->WriteOpcode(SERVER_SHARD_LOGIN);
pkt->Write<uint8_t>(ANSWER_ACCEPT);
}
void WriteLoginShard (const boost::shared_ptr<OPacket> &pkt, const LOGIN_ERROR error)
{
pkt->WriteOpcode(SERVER_SHARD_LOGIN);
pkt->Write<uint8_t>(ANSWER_ERROR);
pkt->Write<uint8_t>(error);
}
}
| agpl-3.0 |
Treeptik/cloudunit | cu-core/src/main/java/fr/treeptik/cloudunit/dto/SourceUnit.java | 1743 | /*
* LICENCE : CloudUnit is available under the GNU Affero General Public License : https://gnu.org/licenses/agpl.html
* but CloudUnit is licensed too under a standard commercial license.
* Please contact our sales team if you would like to discuss the specifics of our Enterprise license.
* If you are not sure whether the AGPL is right for you,
* you can always test our software under the AGPL and inspect the source code before you contact us
* about purchasing a commercial license.
*
* LEGAL TERMS : "CloudUnit" is a registered trademark of Treeptik and can't be used to endorse
* or promote products derived from this project without prior written permission from Treeptik.
* Products or services derived from this software may not be called "CloudUnit"
* nor may "Treeptik" or similar confusing terms appear in their names without prior written permission.
* For any questions, contact us : contact@treeptik.fr
*/
package fr.treeptik.cloudunit.dto;
/**
* Created by nicolas on 25/06/15.
*/
public class SourceUnit {
private String name;
public SourceUnit(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SourceUnit that = (SourceUnit) o;
return !(name != null ? !name.equals(that.name) : that.name != null);
}
@Override
public String toString() {
return "SourceUnit{" +
"name='" + name + '\'' +
'}';
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
}
| agpl-3.0 |
PDI-DGS-Protolab/WebGLExperiments | js/cubicvr/scene.js | 1393 |
(function (CubicVR, undefined){
"use strict";
function webGLStart (gl, canvas) {
var CubicVR = window.CubicVR;
var scene = new CubicVR.Scene({
light : {
name : "light",
type : "point",
position : [1.0, 1.5, -2.0]
},
camera : {
name : "camera",
width : canvas.width,
height : canvas.height,
position : [1,1,1],
lookat : [0,0,0],
fov : 60.0
},
sceneObject : {
name : "cube",
position : [0.0, 0.0, 0.0],
mesh : {
primitive : {
type : "box",
size : 1.0,
uvmapper : {
projectionMode : "cubic",
scale : [1,1,1]
}
},
compile : true
}
},
skybox : new CubicVR.SkyBox({ texture : '../assets/textures/skybox.jpg' })
});
CubicVR.addResizeable(scene.camera);
CubicVR.MainLoop(function(timer, gl) {
scene.render();
});
}
CubicVR.start('auto', webGLStart);
})( CubicVR );
| agpl-3.0 |
Fantu/Unrealrpg | pagine/home.php | 5085 | <?php
if((empty($int_security)) OR ($int_security!=$game_se_code)){
header("Location: ../index.php?error=16");
exit();
}
if(isset($_POST['registra'])){
$errore="";
$server=(int)$_POST['server'];
if(isset($game_server[$server])){$db->Setdb($server);}else{$errore.=$lang['reg_error1'];}
$username=htmlspecialchars($_POST['username'],ENT_QUOTES);
if(!$_POST['username'])
$errore.=$lang['reg_error2'];
if(strlen($username)<3 OR strlen($username)>20)
$errore.=$lang['reg_error3'];
if(!$_POST['password'])
$errore.=$lang['reg_error4'];
if(strlen($_POST['password'])<6 OR strlen($_POST['password'])>20)
$errore.=$lang['reg_error5'];
if(!$_POST['email'])
$errore.=$lang['reg_error6'];
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/",$_POST['email']))
$errore.=$lang['reg_error7'];
if(empty($errore)){
if($_POST['password']!=$_POST['password2'])
$errore.=$lang['reg_error13'];
if($_POST['email']!=$_POST['email2'])
$errore.=$lang['reg_error15'];
$a=$db->QuerySelect("SELECT maxutenti AS Max, utenti AS Ut FROM config WHERE id='".$server."'");
$a2=$db->QuerySelect("SELECT COUNT(*) AS Us1 FROM utenti WHERE username='".$username."'");
if($a2['Us1']>0)
$errore.=$lang['reg_error8'];
if($a['Ut']>=$a['Max'])
$errore.=$lang['reg_error9'];
}
if($errore){
$outputreg="<span>".$lang['outputerrori']."</span><br /><span>".$errore."</span><br /><br />";}
else{
$ip=$_SERVER['REMOTE_ADDR'];
$password=htmlspecialchars($_POST['password'],ENT_QUOTES);
$pass=md5($password);
$cod=md5($username);
$refer=0;
$refertime=0;
if($_COOKIE['urbgrefer']){
$refer=htmlspecialchars($_COOKIE['urbgrefer'],ENT_QUOTES);
$refertime=$adesso+172800;
}
$newsletter=(int)$_POST['newsletter'];
if($newsletter!=0 AND $newsletter!=1)
$newsletter=1;
$ue=$db->QuerySelect("SELECT COUNT(userid) AS n FROM cacheuserid WHERE data<'".($adesso-5184000)."'");
if($ue['n']>0){
$ue=$db->QuerySelect("SELECT userid FROM cacheuserid WHERE data<'".($adesso-5184000)."' LIMIT 1");
$db->QueryMod("INSERT INTO utenti (userid,username,password,codice,email,dataiscrizione,ipreg,ultimazione,refer,refertime,ultimologin,mailnews) VALUES ('".$ue['userid']."','".$username."','".$pass."','".$cod."','".$_POST['email']."','".$adesso."','".$ip."','".$adesso."','".$refer."','".$refertime."','".$adesso."','".$newsletter."')");
$db->QueryMod("DELETE FROM cacheuserid WHERE userid='".$ue['userid']."'");
}else{//fine se si prende userid reciclato
$db->QueryMod("INSERT INTO utenti (username,password,codice,email,dataiscrizione,ipreg,ultimazione,refer,refertime,ultimologin,mailnews) VALUES ('".$username."','".$pass."','".$cod."','".$_POST['email']."','".$adesso."','".$ip."','".$adesso."','".$refer."','".$refertime."','".$adesso."','".$newsletter."')");
}//se non si prende userid reciclato
$messaggio=sprintf($lang['testo_mail_conferma'],$username,$game_name,$game_link,$server,$cod,$game_server[$server]);
$email=new Email(1,$_POST['email'],$lang['Conferma_account'].$game_name,$messaggio);
$outputreg=$lang['account_creato_ok'];
}
}//fine registrazione
if(isset($_POST['attivazione'])){
$errore="";
$server=(int)$_POST['serveratt'];
if(isset($game_server[$server])){$db->Setdb($server);}else{$errore.=$lang['reg_error1'];}
if(!$_POST['usernameatt'] AND !$_POST['codice'])
$errore.=$lang['reg_error10'];
if(empty($errore)){
if(!$_POST['codice']){
$username=htmlspecialchars($_POST['usernameatt'],ENT_QUOTES);
$a=$db->QuerySelect("SELECT COUNT(*) AS U FROM utenti WHERE username='".$username."'");
if($a['U']==0){$errore.=$lang['reg_error11'];
}else{
$a=$db->QuerySelect("SELECT conferma FROM utenti WHERE username='".$username."'");
if($a['conferma']==1)
$errore.=$lang['reg_error14'];
}
$step=1;
}else{
$codice=htmlspecialchars($_POST['codice'],ENT_QUOTES);
$a=$db->QuerySelect("SELECT COUNT(*) AS C FROM utenti WHERE codice='".$codice."'");
if($a['C']==0)
$errore.=$lang['reg_error12'];
$step=2;
}
}//se nn ci sono errori precedenti
if($errore){
$outputreg="<span>".$lang['outputerrori']."</span><br /><span>".$errore."</span><br /><br />";}
else{
if($step==1){
$user=$db->QuerySelect("SELECT username,email,codice FROM utenti WHERE username='".$username."'");
$messaggio=sprintf($lang['testo_mail_codice_conferma'],$game_name,$user['codice'],$user['username']);
$email=new Email(0,$user['email'],$lang['Conferma_account'].$game_name,$messaggio);
$outputreg=$lang['codice_spedito'];
}else{
$link=$game_link."/conferma.php?t=".$server."&cod=".$codice;
echo "<script language=\"javascript\">window.location.href='".$link."'</script>";
exit();
}
}
}//fine attivazione
require('game/template/est_pagina_home.php');
?> | agpl-3.0 |
XeryusTC/rotd | functional_tests/test_error_pages.py | 2295 | # -*- coding: utf-8 -*-
# ROTD suggest a recipe to cook for dinner, changing the recipe every day.
# Copyright © 2015 Xeryus Stokkel
# ROTD 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.
# ROTD 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 General Public License
# along with ROTD. If not, see <http://www.gnu.org/licenses/>.
from .base import FunctionalTestCase
class ErrorPagesTests(FunctionalTestCase):
def test_403_page_setup(self):
# Alice is a visitor who encounters a page she isn't supposed to
# visit
self.browser.get(self.server_url + '/403/')
# She sees a 403 error in the browser's title
self.assertIn('403', self.browser.title)
# She also sees a 403 error on the page, along with a text message
body = self.browser.find_element_by_tag_name('body')
self.assertIn('403', body.text)
self.assertIn('toegang', body.text.lower())
self.assertIn('verboden', body.text.lower())
def test_404_page_setup(self):
# Alice is a visitor who encounters a non-existing page
self.browser.get(self.server_url + '/404/')
# She sees a 404 error in the browser's title
self.assertIn('404', self.browser.title)
# She also sees a 404 error on the page, along with some text
body = self.browser.find_element_by_tag_name('body')
self.assertIn('404', body.text)
self.assertIn('niet gevonden', body.text.lower())
def test_500_page_setup(self):
# Alice visits a page which broke the server for some reason
self.browser.get(self.server_url + '/500/')
# She sees a 500 error in the browser's title
self.assertIn('500', self.browser.title)
# She also sees a 500 error on the page
body = self.browser.find_element_by_tag_name('body')
self.assertIn('500', body.text)
| agpl-3.0 |
doubtfire-lms/doubtfire-api | db/schema.rb | 20495 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2022_01_10_052033) do
create_table "activity_types", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "name", null: false
t.string "abbreviation", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["abbreviation"], name: "index_activity_types_on_abbreviation", unique: true
t.index ["name"], name: "index_activity_types_on_name", unique: true
end
create_table "auth_tokens", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.datetime "auth_token_expiry", null: false
t.bigint "user_id"
t.string "authentication_token", null: false
t.index ["user_id"], name: "index_auth_tokens_on_user_id"
end
create_table "breaks", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.datetime "start_date", null: false
t.integer "number_of_weeks", null: false
t.bigint "teaching_period_id"
t.index ["teaching_period_id"], name: "index_breaks_on_teaching_period_id"
end
create_table "campuses", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "name", null: false
t.integer "mode", null: false
t.string "abbreviation", null: false
t.boolean "active", null: false
t.index ["abbreviation"], name: "index_campuses_on_abbreviation", unique: true
t.index ["active"], name: "index_campuses_on_active"
t.index ["name"], name: "index_campuses_on_name", unique: true
end
create_table "comments_read_receipts", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "task_comment_id", null: false
t.bigint "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["task_comment_id", "user_id"], name: "index_comments_read_receipts_on_task_comment_id_and_user_id", unique: true
t.index ["task_comment_id"], name: "index_comments_read_receipts_on_task_comment_id"
t.index ["user_id"], name: "index_comments_read_receipts_on_user_id"
end
create_table "group_memberships", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "group_id"
t.bigint "project_id"
t.boolean "active", default: true
t.datetime "created_at"
t.datetime "updated_at"
t.index ["group_id"], name: "index_group_memberships_on_group_id"
t.index ["project_id"], name: "index_group_memberships_on_project_id"
end
create_table "group_sets", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "unit_id"
t.string "name"
t.boolean "allow_students_to_create_groups", default: true
t.boolean "allow_students_to_manage_groups", default: true
t.boolean "keep_groups_in_same_class", default: false
t.datetime "created_at"
t.datetime "updated_at"
t.integer "capacity"
t.boolean "locked", default: false, null: false
t.index ["unit_id"], name: "index_group_sets_on_unit_id"
end
create_table "group_submissions", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "group_id"
t.string "notes"
t.bigint "submitted_by_project_id"
t.datetime "created_at"
t.datetime "updated_at"
t.bigint "task_definition_id"
t.index ["group_id"], name: "index_group_submissions_on_group_id"
t.index ["submitted_by_project_id"], name: "index_group_submissions_on_submitted_by_project_id"
t.index ["task_definition_id"], name: "index_group_submissions_on_task_definition_id"
end
create_table "groups", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "group_set_id"
t.bigint "tutorial_id"
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "capacity_adjustment", default: 0, null: false
t.boolean "locked", default: false, null: false
t.index ["group_set_id"], name: "index_groups_on_group_set_id"
t.index ["tutorial_id"], name: "index_groups_on_tutorial_id"
end
create_table "learning_outcome_task_links", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.text "description"
t.integer "rating"
t.bigint "task_definition_id"
t.bigint "task_id"
t.bigint "learning_outcome_id"
t.datetime "created_at"
t.datetime "updated_at"
t.index ["learning_outcome_id"], name: "learning_outcome_task_links_lo_index"
t.index ["task_definition_id"], name: "index_learning_outcome_task_links_on_task_definition_id"
t.index ["task_id"], name: "index_learning_outcome_task_links_on_task_id"
end
create_table "learning_outcomes", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "unit_id"
t.integer "ilo_number"
t.string "name"
t.string "description", limit: 4096
t.string "abbreviation"
t.index ["unit_id"], name: "index_learning_outcomes_on_unit_id"
end
create_table "logins", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.datetime "timestamp"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_logins_on_user_id"
end
create_table "overseer_assessments", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "task_id", null: false
t.string "submission_timestamp", null: false
t.string "result_task_status"
t.integer "status", default: 0, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["task_id", "submission_timestamp"], name: "index_overseer_assessments_on_task_id_and_submission_timestamp", unique: true
t.index ["task_id"], name: "index_overseer_assessments_on_task_id"
end
create_table "overseer_images", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "name", null: false
t.string "tag", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "plagiarism_match_links", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "task_id"
t.bigint "other_task_id"
t.integer "pct"
t.datetime "created_at"
t.datetime "updated_at"
t.string "plagiarism_report_url"
t.boolean "dismissed", default: false
t.index ["other_task_id"], name: "index_plagiarism_match_links_on_other_task_id"
t.index ["task_id"], name: "index_plagiarism_match_links_on_task_id"
end
create_table "projects", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "unit_id"
t.string "project_role"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "started"
t.string "progress"
t.string "status"
t.string "task_stats"
t.boolean "enrolled", default: true
t.integer "target_grade", default: 0
t.boolean "compile_portfolio", default: false
t.date "portfolio_production_date"
t.integer "max_pct_similar", default: 0
t.bigint "user_id"
t.integer "grade", default: 0
t.string "grade_rationale", limit: 4096
t.bigint "campus_id"
t.integer "submitted_grade"
t.boolean "uses_draft_learning_summary", default: false, null: false
t.index ["campus_id"], name: "index_projects_on_campus_id"
t.index ["enrolled"], name: "index_projects_on_enrolled"
t.index ["unit_id"], name: "index_projects_on_unit_id"
t.index ["user_id"], name: "index_projects_on_user_id"
end
create_table "roles", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "task_comments", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "task_id", null: false
t.bigint "user_id", null: false
t.string "comment", limit: 4096
t.datetime "created_at", null: false
t.bigint "recipient_id"
t.string "content_type"
t.string "attachment_extension"
t.string "type"
t.datetime "time_discussion_started"
t.datetime "time_discussion_completed"
t.integer "number_of_prompts"
t.datetime "date_extension_assessed"
t.boolean "extension_granted"
t.bigint "assessor_id"
t.bigint "task_status_id"
t.integer "extension_weeks"
t.string "extension_response"
t.bigint "reply_to_id"
t.bigint "overseer_assessment_id"
t.index ["assessor_id"], name: "index_task_comments_on_assessor_id"
t.index ["overseer_assessment_id"], name: "index_task_comments_on_overseer_assessment_id"
t.index ["recipient_id"], name: "fk_rails_1dbb49165b"
t.index ["reply_to_id"], name: "index_task_comments_on_reply_to_id"
t.index ["task_id"], name: "index_task_comments_on_task_id"
t.index ["task_status_id"], name: "index_task_comments_on_task_status_id"
t.index ["user_id"], name: "index_task_comments_on_user_id"
end
create_table "task_definitions", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "unit_id"
t.string "name"
t.string "description", limit: 4096
t.decimal "weighting", precision: 10
t.datetime "target_date", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "abbreviation"
t.string "upload_requirements", limit: 4096
t.integer "target_grade", default: 0
t.boolean "restrict_status_updates", default: false
t.string "plagiarism_checks", limit: 4096
t.string "plagiarism_report_url"
t.boolean "plagiarism_updated", default: false
t.integer "plagiarism_warn_pct", default: 50
t.bigint "group_set_id"
t.datetime "due_date"
t.datetime "start_date", null: false
t.boolean "is_graded", default: false
t.integer "max_quality_pts", default: 0
t.bigint "tutorial_stream_id"
t.boolean "assessment_enabled", default: false
t.bigint "overseer_image_id"
t.index ["group_set_id"], name: "index_task_definitions_on_group_set_id"
t.index ["overseer_image_id"], name: "index_task_definitions_on_overseer_image_id"
t.index ["tutorial_stream_id"], name: "index_task_definitions_on_tutorial_stream_id"
t.index ["unit_id"], name: "index_task_definitions_on_unit_id"
end
create_table "task_engagements", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.datetime "engagement_time"
t.string "engagement"
t.bigint "task_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["task_id"], name: "index_task_engagements_on_task_id"
end
create_table "task_pins", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "task_id", null: false
t.bigint "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["task_id", "user_id"], name: "index_task_pins_on_task_id_and_user_id", unique: true
t.index ["task_id"], name: "index_task_pins_on_task_id"
t.index ["user_id"], name: "fk_rails_915df186ed"
end
create_table "task_statuses", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "name"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "task_submissions", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.datetime "submission_time"
t.datetime "assessment_time"
t.string "outcome"
t.bigint "task_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "assessor_id"
t.index ["assessor_id"], name: "index_task_submissions_on_assessor_id"
t.index ["task_id"], name: "index_task_submissions_on_task_id"
end
create_table "tasks", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "task_definition_id"
t.bigint "project_id"
t.bigint "task_status_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.date "completion_date"
t.string "portfolio_evidence"
t.boolean "include_in_portfolio", default: true
t.datetime "file_uploaded_at"
t.integer "max_pct_similar", default: 0
t.bigint "group_submission_id"
t.integer "contribution_pct", default: 100
t.integer "times_assessed", default: 0
t.datetime "submission_date"
t.datetime "assessment_date"
t.integer "grade"
t.integer "contribution_pts", default: 3
t.integer "quality_pts", default: -1
t.integer "extensions", default: 0, null: false
t.index ["group_submission_id"], name: "index_tasks_on_group_submission_id"
t.index ["project_id", "task_definition_id"], name: "tasks_uniq_proj_task_def", unique: true
t.index ["project_id"], name: "index_tasks_on_project_id"
t.index ["task_definition_id"], name: "index_tasks_on_task_definition_id"
t.index ["task_status_id"], name: "index_tasks_on_task_status_id"
end
create_table "teaching_periods", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "period", null: false
t.datetime "start_date", null: false
t.datetime "end_date", null: false
t.integer "year", null: false
t.datetime "active_until", null: false
t.index ["period", "year"], name: "index_teaching_periods_on_period_and_year", unique: true
end
create_table "tutorial_enrolments", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "project_id", null: false
t.bigint "tutorial_id", null: false
t.index ["project_id"], name: "index_tutorial_enrolments_on_project_id"
t.index ["tutorial_id", "project_id"], name: "index_tutorial_enrolments_on_tutorial_id_and_project_id", unique: true
t.index ["tutorial_id"], name: "index_tutorial_enrolments_on_tutorial_id"
end
create_table "tutorial_streams", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "name", null: false
t.string "abbreviation", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "activity_type_id", null: false
t.bigint "unit_id", null: false
t.index ["abbreviation", "unit_id"], name: "index_tutorial_streams_on_abbreviation_and_unit_id", unique: true
t.index ["abbreviation"], name: "index_tutorial_streams_on_abbreviation"
t.index ["activity_type_id"], name: "fk_rails_14ef80da76"
t.index ["name", "unit_id"], name: "index_tutorial_streams_on_name_and_unit_id", unique: true
t.index ["unit_id"], name: "index_tutorial_streams_on_unit_id"
end
create_table "tutorials", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "unit_id"
t.string "meeting_day"
t.string "meeting_time"
t.string "meeting_location"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "code"
t.bigint "unit_role_id"
t.string "abbreviation"
t.integer "capacity", default: -1
t.bigint "campus_id"
t.bigint "tutorial_stream_id"
t.index ["campus_id"], name: "index_tutorials_on_campus_id"
t.index ["tutorial_stream_id"], name: "index_tutorials_on_tutorial_stream_id"
t.index ["unit_id"], name: "index_tutorials_on_unit_id"
t.index ["unit_role_id"], name: "index_tutorials_on_unit_role_id"
end
create_table "unit_roles", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "user_id"
t.bigint "tutorial_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "role_id"
t.bigint "unit_id"
t.index ["role_id"], name: "index_unit_roles_on_role_id"
t.index ["tutorial_id"], name: "index_unit_roles_on_tutorial_id"
t.index ["unit_id"], name: "index_unit_roles_on_unit_id"
t.index ["user_id"], name: "index_unit_roles_on_user_id"
end
create_table "units", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "name"
t.string "description", limit: 4096
t.datetime "start_date"
t.datetime "end_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "code"
t.boolean "active", default: true
t.datetime "last_plagarism_scan"
t.bigint "teaching_period_id"
t.bigint "main_convenor_id"
t.boolean "auto_apply_extension_before_deadline", default: true, null: false
t.boolean "send_notifications", default: true, null: false
t.boolean "enable_sync_timetable", default: true, null: false
t.boolean "enable_sync_enrolments", default: true, null: false
t.bigint "draft_task_definition_id"
t.boolean "allow_student_extension_requests", default: true, null: false
t.integer "extension_weeks_on_resubmit_request", default: 1, null: false
t.boolean "allow_student_change_tutorial", default: true, null: false
t.boolean "assessment_enabled", default: true
t.bigint "overseer_image_id"
t.index ["draft_task_definition_id"], name: "index_units_on_draft_task_definition_id"
t.index ["main_convenor_id"], name: "index_units_on_main_convenor_id"
t.index ["overseer_image_id"], name: "index_units_on_overseer_image_id"
t.index ["teaching_period_id"], name: "index_units_on_teaching_period_id"
end
create_table "users", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name"
t.string "last_name"
t.string "username"
t.string "nickname"
t.string "unlock_token"
t.bigint "role_id", default: 0
t.boolean "receive_task_notifications", default: true
t.boolean "receive_feedback_notifications", default: true
t.boolean "receive_portfolio_notifications", default: true
t.boolean "opt_in_to_research"
t.boolean "has_run_first_time_setup", default: false
t.string "login_id"
t.string "student_id"
t.index ["login_id"], name: "index_users_on_login_id", unique: true
t.index ["role_id"], name: "index_users_on_role_id"
end
create_table "webcal_unit_exclusions", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.bigint "webcal_id", null: false
t.bigint "unit_id", null: false
t.index ["unit_id", "webcal_id"], name: "index_webcal_unit_exclusions_on_unit_id_and_webcal_id", unique: true
t.index ["unit_id"], name: "index_webcal_unit_exclusions_on_unit_id"
t.index ["webcal_id"], name: "fk_rails_d5fab02cb7"
end
create_table "webcals", charset: "utf8mb3", collation: "utf8mb3_unicode_ci", force: :cascade do |t|
t.string "guid", limit: 36, null: false
t.boolean "include_start_dates", default: false, null: false
t.bigint "user_id"
t.integer "reminder_time"
t.string "reminder_unit"
t.index ["guid"], name: "index_webcals_on_guid", unique: true
t.index ["user_id"], name: "index_webcals_on_user_id", unique: true
end
end
| agpl-3.0 |
Br3nda/statusnet-debian | classes/Oauth_application.php | 4686 | <?php
/**
* Table Definition for oauth_application
*/
require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
class Oauth_application extends Memcached_DataObject
{
###START_AUTOCODE
/* the code below is auto generated do not remove the above tag */
public $__table = 'oauth_application'; // table name
public $id; // int(4) primary_key not_null
public $owner; // int(4) not_null
public $consumer_key; // varchar(255) not_null
public $name; // varchar(255) not_null
public $description; // varchar(255)
public $icon; // varchar(255) not_null
public $source_url; // varchar(255)
public $organization; // varchar(255)
public $homepage; // varchar(255)
public $callback_url; // varchar(255) not_null
public $type; // tinyint(1)
public $access_type; // tinyint(1)
public $created; // datetime not_null
public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
/* Static get */
function staticGet($k,$v=NULL) {
return Memcached_DataObject::staticGet('Oauth_application',$k,$v);
}
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
// Bit flags
public static $readAccess = 1;
public static $writeAccess = 2;
public static $browser = 1;
public static $desktop = 2;
function getConsumer()
{
return Consumer::staticGet('consumer_key', $this->consumer_key);
}
static function maxDesc()
{
$desclimit = common_config('application', 'desclimit');
// null => use global limit (distinct from 0!)
if (is_null($desclimit)) {
$desclimit = common_config('site', 'textlimit');
}
return $desclimit;
}
static function descriptionTooLong($desc)
{
$desclimit = self::maxDesc();
return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
}
function setAccessFlags($read, $write)
{
if ($read) {
$this->access_type |= self::$readAccess;
} else {
$this->access_type &= ~self::$readAccess;
}
if ($write) {
$this->access_type |= self::$writeAccess;
} else {
$this->access_type &= ~self::$writeAccess;
}
}
function setOriginal($filename)
{
$imagefile = new ImageFile($this->id, Avatar::path($filename));
// XXX: Do we want to have a bunch of different size icons? homepage, stream, mini?
// or just one and control size via CSS? --Zach
$orig = clone($this);
$this->icon = Avatar::url($filename);
common_debug(common_log_objstring($this));
return $this->update($orig);
}
static function getByConsumerKey($key)
{
if (empty($key)) {
return null;
}
$app = new Oauth_application();
$app->consumer_key = $key;
$app->limit(1);
$result = $app->find(true);
return empty($result) ? null : $app;
}
/**
* Handle an image upload
*
* Does all the magic for handling an image upload, and crops the
* image by default.
*
* @return void
*/
function uploadLogo()
{
if ($_FILES['app_icon']['error'] ==
UPLOAD_ERR_OK) {
try {
$imagefile = ImageFile::fromUpload('app_icon');
} catch (Exception $e) {
common_debug("damn that sucks");
$this->showForm($e->getMessage());
return;
}
$filename = Avatar::filename($this->id,
image_type_to_extension($imagefile->type),
null,
'oauth-app-icon-'.common_timestamp());
$filepath = Avatar::path($filename);
move_uploaded_file($imagefile->filepath, $filepath);
$this->setOriginal($filename);
}
}
function delete()
{
$this->_deleteAppUsers();
$consumer = $this->getConsumer();
$consumer->delete();
parent::delete();
}
function _deleteAppUsers()
{
$oauser = new Oauth_application_user();
$oauser->application_id = $this->id;
$oauser->delete();
}
}
| agpl-3.0 |
irontec/Mintzatu | library/Mintzatu/Model/Raw/Checks.php | 8201 | <?php
/**
* Application Models
*
* @package Mintzatu_Model_Raw
* @subpackage Model
* @author <Lander Ontoria Gardeazabal>
* @copyright Irontec - Internet y Sistemas sobre GNU/Linux
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
*
*
* @package Mintzatu_Model
* @subpackage Model
* @author <Lander Ontoria Gardeazabal>
*/
class Mintzatu_Model_Raw_Checks extends Mintzatu_Model_Raw_ModelAbstract
{
/**
* Database var type mediumint(8) unsigned
*
* @var int
*/
protected $_IdCheck;
/**
* Database var type mediumint(8) unsigned
*
* @var int
*/
protected $_IdErabiltzaile;
/**
* Database var type mediumint(8) unsigned
*
* @var int
*/
protected $_IdLekua;
/**
* Database var type text
*
* @var text
*/
protected $_Iruzkina;
/**
* Database var type timestamp
*
* @var string
*/
protected $_Noiz;
/**
* Database var type enum('web','app')
*
* @var string
*/
protected $_Nondik;
/**
* Parent relation checks_ibfk_2
*
* @var Mintzatu_Model_Lekuak
*/
protected $_Lekuak;
/**
* Parent relation checks_ibfk_3
*
* @var Mintzatu_Model_Erabiltzaileak
*/
protected $_Erabiltzaileak;
/**
* Sets up column and relationship lists
*/
public function __construct()
{
parent::init();
$this->setColumnsList(array(
'id_check'=>'IdCheck',
'id_erabiltzaile'=>'IdErabiltzaile',
'id_lekua'=>'IdLekua',
'iruzkina'=>'Iruzkina',
'noiz'=>'Noiz',
'nondik'=>'Nondik',
));
$this->setMultiLangColumnsList(array(
));
$this->setAvailableLangs(array('check','erabiltzaile','lekua'));
$this->setParentList(array(
'ChecksIbfk2'=> array(
'property' => 'Lekuak',
'table_name' => 'Lekuak',
),
'ChecksIbfk3'=> array(
'property' => 'Erabiltzaileak',
'table_name' => 'Erabiltzaileak',
),
));
$this->setDependentList(array(
));
parent::__construct();
}
/**
* Sets column id_check
*
* @param int $data
* @return Mintzatu_Model_Checks
*/
public function setIdCheck($data)
{
$this->_IdCheck = $data;
return $this;
}
/**
* Gets column id_check
*
* @return int
*/
public function getIdCheck()
{
return $this->_IdCheck;
}
/**
* Sets column id_erabiltzaile
*
* @param int $data
* @return Mintzatu_Model_Checks
*/
public function setIdErabiltzaile($data)
{
$this->_IdErabiltzaile = $data;
return $this;
}
/**
* Gets column id_erabiltzaile
*
* @return int
*/
public function getIdErabiltzaile()
{
return $this->_IdErabiltzaile;
}
/**
* Sets column id_lekua
*
* @param int $data
* @return Mintzatu_Model_Checks
*/
public function setIdLekua($data)
{
$this->_IdLekua = $data;
return $this;
}
/**
* Gets column id_lekua
*
* @return int
*/
public function getIdLekua()
{
return $this->_IdLekua;
}
/**
* Sets column iruzkina
*
* @param text $data
* @return Mintzatu_Model_Checks
*/
public function setIruzkina($data)
{
$this->_Iruzkina = $data;
return $this;
}
/**
* Gets column iruzkina
*
* @return text
*/
public function getIruzkina()
{
return $this->_Iruzkina;
}
/**
* Sets column noiz
*
* @param string $data
* @return Mintzatu_Model_Checks
*/
public function setNoiz($data)
{
$this->_Noiz = $data;
return $this;
}
/**
* Gets column noiz
*
* @return string
*/
public function getNoiz()
{
return $this->_Noiz;
}
/**
* Sets column nondik
*
* @param string $data
* @return Mintzatu_Model_Checks
*/
public function setNondik($data)
{
$this->_Nondik = $data;
return $this;
}
/**
* Gets column nondik
*
* @return string
*/
public function getNondik()
{
return $this->_Nondik;
}
/**
* Sets parent relation IdLekua
*
* @param Mintzatu_Model_Lekuak $data
* @return Mintzatu_Model_Checks
*/
public function setLekuak(Mintzatu_Model_Lekuak $data)
{
$this->_Lekuak = $data;
$primary_key = $data->getPrimaryKey();
if (is_array($primary_key)) {
$primary_key = $primary_key['id_lekua'];
}
$this->setIdLekua($primary_key);
return $this;
}
/**
* Gets parent IdLekua
*
* @param boolean $load Load the object if it is not already
* @return Mintzatu_Model_Lekuak
*/
public function getLekuak($load = true)
{
if ($this->_Lekuak === null && $load) {
$this->getMapper()->loadRelated('ChecksIbfk2', $this);
}
return $this->_Lekuak;
}
/**
* Sets parent relation IdErabiltzaile
*
* @param Mintzatu_Model_Erabiltzaileak $data
* @return Mintzatu_Model_Checks
*/
public function setErabiltzaileak(Mintzatu_Model_Erabiltzaileak $data)
{
$this->_Erabiltzaileak = $data;
$primary_key = $data->getPrimaryKey();
if (is_array($primary_key)) {
$primary_key = $primary_key['id_erabiltzaile'];
}
$this->setIdErabiltzaile($primary_key);
return $this;
}
/**
* Gets parent IdErabiltzaile
*
* @param boolean $load Load the object if it is not already
* @return Mintzatu_Model_Erabiltzaileak
*/
public function getErabiltzaileak($load = true)
{
if ($this->_Erabiltzaileak === null && $load) {
$this->getMapper()->loadRelated('ChecksIbfk3', $this);
}
return $this->_Erabiltzaileak;
}
/**
* Returns the mapper class for this model
*
* @return \Mappers\Sql\Checks
*/
public function getMapper()
{
if ($this->_mapper === null) {
\Zend_Loader_Autoloader::getInstance()->suppressNotFoundWarnings(true);
if (class_exists('\Mappers\Sql\Checks')) {
$this->setMapper(new \Mappers\Sql\Checks);
} else if (class_exists('\Mappers\Soap\Checks')) {
$this->setMapper(new \Mappers\Soap\Checks);
} else {
Throw new \Exception("Not a valid mapper class found");
}
\Zend_Loader_Autoloader::getInstance()->suppressNotFoundWarnings(false);
}
return $this->_mapper;
}
/**
* Returns the validator class for this model
*
* @return null | Mintzatu_Model_Validator_Checks
*/
public function getValidator()
{
if ($this->_validator === null) {
if (class_exists('Mintzatu_Validator_Checks')) {
$this->setValidator(new Mintzatu_Validator_Checks);
}
}
return $this->_validator;
}
/**
* Deletes current row by deleting the row that matches the primary key
*
* @see \Mappers\Sql\Checks::delete
* @return int|boolean Number of rows deleted or boolean if doing soft delete
*/
public function deleteRowByPrimaryKey()
{
if ($this->getIdCheck() === null) {
throw new Exception('Primary Key does not contain a value');
}
return $this->getMapper()
->getDbTable()
->delete('id_check = ' .
$this->getMapper()
->getDbTable()
->getAdapter()
->quote($this->getIdCheck()));
}
}
| agpl-3.0 |
SarahVictoria/IOConnection | Case 12/simple/main.cpp | 2516 |
#include <cstdio>
#include <cstdlib>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pthread.h>
void sleep_sec(int seconds){
usleep(seconds * 1000000);
}
int setupSocket(const char * address, const char * port, int socketType){
int returnSocket = 0;
struct addrinfo hints, *servinfo;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo(address, port, &hints, &servinfo);
returnSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if (socketType == 1){ // Server
int yes = 1;
setsockopt(returnSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
bind(returnSocket, servinfo->ai_addr, servinfo->ai_addrlen);
listen(returnSocket, 5);
}
if (socketType == 2){ // Client
connect(returnSocket, servinfo->ai_addr, servinfo->ai_addrlen);
}
// Cleanup
free(servinfo);
return returnSocket;
}
static void * clientThread(void * data){
struct addrinfo aiStruct;
int socket_client = setupSocket("127.0.0.1", "5000", 2);
char buffer[1024] = {0};
int bufferLength = 0;
int bytes = 0;
int count = 0;
while(*(bool*)data){
sprintf(buffer,"count:%d",count++);
bytes = send(socket_client, buffer, 1023, 0);
sleep_sec(1);
}
close(socket_client);
}
static void * serverThread(void * data){
int socket_server = setupSocket(NULL, "5000", 1);
int socket_listen = -1;
struct sockaddr_storage connector;
socklen_t sin_size;
char buffer[1024] = {0};
int bufferLength = 0;
do{
sin_size = sizeof(connector);
socket_listen = accept(socket_server, (struct sockaddr *)&connector, &sin_size);
}while(socket_listen == -1);
int bytes = 0;
while(*(bool*)data){
bytes = recv(socket_listen, buffer, 1023, 0);
if (bytes != -1){
buffer[bytes] = '\0';
printf("Received: %s\n", buffer);
bytes = -1;
}
}
close(socket_listen);
close(socket_server);
return NULL;
}
int main(int argc, char** argv){
pthread_t server;
pthread_t client;
bool clientRun = true;
bool serverRun = true;
pthread_create(&server, NULL, serverThread, (void*)&serverRun);
pthread_create(&client, NULL, clientThread, (void*)&clientRun);
srand(time(NULL));
sleep_sec((rand()%5)*2+5);
clientRun = false;
serverRun = false;
return 0;
}
| agpl-3.0 |
prefeiturasp/SME-SGP | Src/MSTech.GestaoEscolar.DAL/ACA_TipoJustificativaExclusaoAulasDAO.cs | 6120 | /*
Classe gerada automaticamente pelo MSTech Code Creator
*/
namespace MSTech.GestaoEscolar.DAL
{
using Data.Common;
using Entities;
using MSTech.GestaoEscolar.DAL.Abstracts;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
/// <summary>
/// Description: .
/// </summary>
public class ACA_TipoJustificativaExclusaoAulasDAO : Abstract_ACA_TipoJustificativaExclusaoAulasDAO
{
/// <summary>
/// Retorna todos os tipos de justificativas para exclusão de aulas não excluídos logicamente
/// </summary>
/// <param name="paginado">Indica se o datatable será paginado ou não</param>
/// <param name="currentPage">Página atual do grid</param>
/// <param name="pageSize">Total de registros por página do grid</param>
/// <param name="situacao"></param>
/// <param name="totalRecords">Total de registros retornado na busca</param>
public DataTable SelectBy_Pesquisa
(
bool paginado
, int currentPage
, int pageSize
, int situacao
, out int totalRecords
)
{
QuerySelectStoredProcedure qs = new QuerySelectStoredProcedure("NEW_ACA_TipoJustificativaExclusaoAulas_SelectBy_Pesquisa", _Banco);
try
{
Param = qs.NewParameter();
Param.DbType = DbType.Int32;
Param.ParameterName = "@tje_situacao";
Param.Size = 1;
if (situacao > 0)
Param.Value = situacao;
else
Param.Value = DBNull.Value;
qs.Parameters.Add(Param);
if (paginado)
totalRecords = qs.Execute(currentPage, pageSize);
else
{
qs.Execute();
totalRecords = qs.Return.Rows.Count;
}
return qs.Return;
}
catch
{
throw;
}
finally
{
qs.Parameters.Clear();
}
}
/// <summary>
/// Verifica se já existe um tipo de justificativa para exclusão de aulas cadastrado com o mesmo nome
/// </summary>
/// <param name="tje_id">ID do tipo de justificativa para exclusão de aulas</param>
/// <param name="tje_nome">Nome do tipo de justificativa para exclusão de aulas</param>
public bool SelectBy_Nome
(
int tje_id
, string tje_nome
)
{
QuerySelectStoredProcedure qs = new QuerySelectStoredProcedure("NEW_ACA_TipoJustificativaExclusaoAulas_SelectBy_Nome", _Banco);
try
{
#region PARAMETROS
Param = qs.NewParameter();
Param.DbType = DbType.Int32;
Param.ParameterName = "@tje_id";
Param.Size = 4;
if (tje_id > 0)
Param.Value = tje_id;
else
Param.Value = DBNull.Value;
qs.Parameters.Add(Param);
Param = qs.NewParameter();
Param.DbType = DbType.AnsiString;
Param.ParameterName = "@tje_nome";
Param.Size = 100;
Param.Value = tje_nome;
qs.Parameters.Add(Param);
#endregion
qs.Execute();
return (qs.Return.Rows.Count > 0);
}
catch
{
throw;
}
finally
{
qs.Parameters.Clear();
}
}
/// <summary>
/// Retorna os tipos de justificativas para exclusão de aulas ativos.
/// </summary>
/// <returns></returns>
public List<ACA_TipoJustificativaExclusaoAulas> SelectAtivos()
{
QuerySelectStoredProcedure qs = new QuerySelectStoredProcedure("NEW_ACA_TipoJustificativaExclusaoAulas_SelectBy_PesquisaAtivos", _Banco);
try
{
qs.Execute();
return qs.Return.Rows.Count > 0 ?
qs.Return.Rows.Cast<DataRow>().Select(dr => DataRowToEntity(dr, new ACA_TipoJustificativaExclusaoAulas())).ToList() :
new List<ACA_TipoJustificativaExclusaoAulas>();
}
finally
{
qs.Parameters.Clear();
}
}
#region Métodos Sobrescritos
/// <summary>
/// Override do método ParamInserir
/// </summary>
protected override void ParamInserir(QuerySelectStoredProcedure qs, ACA_TipoJustificativaExclusaoAulas entity)
{
base.ParamInserir(qs, entity);
qs.Parameters["@tje_dataCriacao"].Value = DateTime.Now;
qs.Parameters["@tje_dataAlteracao"].Value = DateTime.Now;
}
/// <summary>
/// Override do método ParamAlterar
/// </summary>
protected override void ParamAlterar(QueryStoredProcedure qs, ACA_TipoJustificativaExclusaoAulas entity)
{
base.ParamAlterar(qs, entity);
qs.Parameters.RemoveAt("@tje_dataCriacao");
qs.Parameters["@tje_dataAlteracao"].Value = DateTime.Now;
}
/// <summary>
/// Override do método Alterar
/// </summary>
protected override bool Alterar(ACA_TipoJustificativaExclusaoAulas entity)
{
__STP_UPDATE = "NEW_ACA_TipoJustificativaExclusaoAulas_UPDATE";
return base.Alterar(entity);
}
/// <summary>
/// Override do método Delete
/// </summary>
public override bool Delete(ACA_TipoJustificativaExclusaoAulas entity)
{
__STP_DELETE = "NEW_ACA_TipoJustificativaExclusaoAulas_UPDATE_Situacao";
return base.Delete(entity);
}
#endregion
}
} | agpl-3.0 |
jerolba/torodb | engine/packaging-utils/src/main/java/com/torodb/packaging/config/model/protocol/mongo/Ssl.java | 3892 | /*
* ToroDB
* Copyright © 2014 8Kdata Technology (www.8kdata.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.torodb.packaging.config.model.protocol.mongo;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.torodb.packaging.config.annotation.Description;
import javax.validation.constraints.NotNull;
@JsonPropertyOrder({"enabled", "allowInvalidHostnames", "FIPSMode", "CAFile", "trustStoreFile",
"trustStorePassword", "keyStoreFile", "keyStorePassword", "keyPassword"})
public class Ssl {
@Description("config.mongo.replication.ssl.enabled")
@NotNull
@JsonProperty(required = true)
private Boolean enabled = false;
@Description("config.mongo.replication.ssl.allowInvalidHostnames")
@NotNull
@JsonProperty(required = true)
private Boolean allowInvalidHostnames = false;
@Description("config.mongo.replication.ssl.fipsMode")
@NotNull
@JsonProperty(required = true)
private Boolean fipsMode = false;
@Description("config.mongo.replication.ssl.caFile")
@JsonProperty(required = true)
private String caFile;
@Description("config.mongo.replication.ssl.trustStoreFile")
@JsonProperty(required = true)
private String trustStoreFile;
@Description("config.mongo.replication.ssl.trustStorePassword")
@JsonProperty(required = true)
private String trustStorePassword;
@Description("config.mongo.replication.ssl.keyStoreFile")
@JsonProperty(required = true)
private String keyStoreFile;
@Description("config.mongo.replication.ssl.keyStorePassword")
@JsonProperty(required = true)
private String keyStorePassword;
@Description("config.mongo.replication.ssl.keyPassword")
@JsonProperty(required = true)
private String keyPassword;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getAllowInvalidHostnames() {
return allowInvalidHostnames;
}
public void setAllowInvalidHostnames(Boolean allowInvalidHostnames) {
this.allowInvalidHostnames = allowInvalidHostnames;
}
public Boolean getFipsMode() {
return fipsMode;
}
public void setFipsMode(Boolean fipsMode) {
this.fipsMode = fipsMode;
}
public String getCaFile() {
return caFile;
}
public void setCaFile(String cAFile) {
caFile = cAFile;
}
public String getTrustStoreFile() {
return trustStoreFile;
}
public void setTrustStoreFile(String trustStoreFile) {
this.trustStoreFile = trustStoreFile;
}
public String getTrustStorePassword() {
return trustStorePassword;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public String getKeyStoreFile() {
return keyStoreFile;
}
public void setKeyStoreFile(String keyStoreFile) {
this.keyStoreFile = keyStoreFile;
}
public String getKeyStorePassword() {
return keyStorePassword;
}
public void setKeyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
public String getKeyPassword() {
return keyPassword;
}
public void setKeyPassword(String keyPassword) {
this.keyPassword = keyPassword;
}
}
| agpl-3.0 |
Tisawesomeness/Minecord | src/main/java/com/tisawesomeness/minecord/debug/DebugOption.java | 559 | package com.tisawesomeness.minecord.debug;
import lombok.NonNull;
/**
* Provides debug information to the {@code &debug} command.
*/
public interface DebugOption {
/**
* @return The name of this debug option, used for user input
*/
@NonNull String getName();
/**
* Gets useful debug information this object is responsible for.
* @param extra A possibly-empty string, used to select sub-options
* @return The debug information formatted as a multiline string
*/
@NonNull String debug(@NonNull String extra);
}
| agpl-3.0 |
afshinnj/php-mvc | vendor/framework/core/Uri.php | 271 | <?php
class Uri {
public static function segment($segment) {
$url = preg_replace(Configs::get('invalidUrlChars'), '', $_GET['r']);
$seg = explode('/', $url);
if (isset($seg[$segment])) {
return $seg[$segment];
}
}
}
| agpl-3.0 |
interjection/infinity-next | app/Http/Routes/API.php | 3039 | <?php
/**
* Content API
*/
Route::group(['as' => 'site', 'namespace' => "Content",], function () {
// boardlist get
Route::get('board-details.json', 'BoardlistController@getDetails');
// boardlist search
Route::post('board-details.json', 'BoardlistController@getDetails');
// overboard update
Route::get('overboard.json', 'MultiboardController@getOverboard');
});
/**
* Multiboard API
*/
Route::group(['prefix' => '*', 'as' => 'overboard', 'namespace' => "Content",], function () {
Route::get('{boards}/catalog.json', ['uses' => 'MultiboardController@getOverboardCatalogWithBoards',]);
Route::get('{worksafe}/catalog.json', ['uses' => 'MultiboardController@getOverboardCatalogWithWorksafe',]);
Route::get('{worksafe}/{boards}/catalog.json', ['uses' => 'MultiboardController@getOverboardCatalog',]);
Route::get('catalog.json', ['uses' => 'MultiboardController@getOverboardCatalog',]);
Route::get('{boards}.json', ['uses' => 'MultiboardController@getOverboardWithBoards',]);
Route::get('{worksafe}.json', ['uses' => 'MultiboardController@getOverboardWithWorksafe',]);
Route::get('{worksafe}/{boards}.json', ['uses' => 'MultiboardController@getOverboard',]);
Route::get('.json', ['uses' => 'MultiboardController@getOverboard',]);
});
/**
* Board API
*/
Route::group(['as' => 'board.', 'prefix' => '{board}', 'namespace' => "Board",], function () {
// Gets the first page of a board.
Route::any('index.json', ['as' => 'index', 'uses' => 'BoardController@getIndex']);
// Gets index pages for the board.
Route::get('page/{id}.json', ['as' => 'page', 'uses' => 'BoardController@getIndex']);
// Gets all visible OPs on a board.
Route::any('catalog.json', ['as' => 'catalog', 'uses' => 'BoardController@getCatalog']);
// Gets all visible OPs on a board.
Route::any('config.json', ['as' => 'config', 'uses' => 'BoardController@getConfig']);
// Put new thread
Route::put('thread.json', ['as' => 'thread.put', 'uses' => 'BoardController@putThread']);
// Put reply to thread.
Route::put('thread/{post_id}.json', ['as' => 'thread.reply', 'uses' => 'BoardController@putThread']);
// Get single thread.
Route::get('thread/{post_id}.json', ['as' => 'thread', 'uses' => 'BoardController@getThread']);
// Get single post.
Route::get('post/{post_id}.json', ['as' => 'post', 'uses' => 'BoardController@getPost']);
});
/*
| Legacy API Routes (JSON)
*/
if (env('LEGACY_ROUTES', false)) {
Route::group(['namespace' => "Legacy",], function () {
// Gets the first page of a board.
Route::any('{board}/index.json', 'BoardController@getIndex');
// Gets index pages for the board.
Route::get('{board}/{id}.json', 'BoardController@getIndex');
// Gets all visible OPs on a board.
Route::any('{board}/threads.json', 'BoardController@getThreads');
// Get single thread.
Route::get('{board}/res/{post_id}.json', 'BoardController@getThread');
});
}
| agpl-3.0 |
dzc34/Asqatasun | rules/rules-rgaa3.2016/src/main/java/org/asqatasun/rules/rgaa32016/Rgaa32016Rule010608.java | 3652 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa32016;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.ruleimplementation.AbstractMarkerPageRuleImplementation;
import org.asqatasun.rules.elementchecker.element.ElementPresenceChecker;
import org.asqatasun.rules.elementselector.ImageElementSelector;
import static org.asqatasun.rules.keystore.CssLikeQueryStore.CANVAS_NOT_IN_LINK_CSS_LIKE_QUERY;
import static org.asqatasun.rules.keystore.HtmlElementStore.TEXT_ELEMENT2;
import static org.asqatasun.rules.keystore.MarkerStore.DECORATIVE_IMAGE_MARKER;
import static org.asqatasun.rules.keystore.MarkerStore.INFORMATIVE_IMAGE_MARKER;
import static org.asqatasun.rules.keystore.RemarkMessageStore.CHECK_DETAILED_DESC_DEFINITION_OF_INFORMATIVE_IMG_MSG;
import static org.asqatasun.rules.keystore.RemarkMessageStore.CHECK_NATURE_OF_IMAGE_AND_DETAILED_DESC_AVAILABILITY_MSG;
/**
* Implementation of the rule 1.6.8 of the referential RGAA 3.2016
*
* For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.2016/01.Images/Rule-1-6-8.html">the rule 1.6.8 design page.</a>
* @see <a href="http://references.modernisation.gouv.fr/rgaa-accessibilite/2016/criteres.html#test-1-6-8">1.6.8 rule specification</a>
*/
public class Rgaa32016Rule010608 extends AbstractMarkerPageRuleImplementation {
/**
* Default constructor
*/
public Rgaa32016Rule010608 () {
super(
new ImageElementSelector(CANVAS_NOT_IN_LINK_CSS_LIKE_QUERY),
// the informative images are part of the scope
INFORMATIVE_IMAGE_MARKER,
// the decorative images are not part of the scope
DECORATIVE_IMAGE_MARKER,
// checker for elements identified by marker
new ElementPresenceChecker(
// solution when at least one element is found
new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_DETAILED_DESC_DEFINITION_OF_INFORMATIVE_IMG_MSG),
// solution when no element is found
new ImmutablePair(TestSolution.NOT_APPLICABLE,""),
// evidence elements
TEXT_ELEMENT2),
// checker for elements not identified by marker
new ElementPresenceChecker(
// solution when at least one element is found
new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_NATURE_OF_IMAGE_AND_DETAILED_DESC_AVAILABILITY_MSG),
// solution when no element is found
new ImmutablePair(TestSolution.NOT_APPLICABLE,""),
// evidence elements
TEXT_ELEMENT2)
);
}
}
| agpl-3.0 |
corecode/rcsparse | setup.py | 210 | #!/usr/bin/env python
from distutils.core import setup, Extension
setup(
name = "rcsparse",
version = "0.1",
ext_modules = [
Extension("rcsparse", ["py-rcsparse.c", "rcsparse.c"])
]
)
| agpl-3.0 |
malikov/platform-android | ushahidi/src/test/java/com/ushahidi/android/domain/usecase/form/ListFormUsecaseTest.java | 3191 | /*
* Copyright (c) 2015 Ushahidi 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 in the file LICENSE-AGPL. If not, see
* https://www.gnu.org/licenses/agpl-3.0.html
*/
package com.ushahidi.android.domain.usecase.form;
import com.addhen.android.raiburari.domain.executor.PostExecutionThread;
import com.addhen.android.raiburari.domain.executor.ThreadExecutor;
import com.ushahidi.android.BuildConfig;
import com.ushahidi.android.DefaultConfig;
import com.ushahidi.android.domain.entity.From;
import com.ushahidi.android.domain.repository.FormRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Tests {@link ListFormUsecase}
*
* @author Ushahidi Team <team@ushahidi.com>
*/
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = DefaultConfig.EMULATE_SDK, constants = BuildConfig.class)
public class ListFormUsecaseTest {
@Mock
private FormRepository mMockFormJsonRepository;
@Mock
private ThreadExecutor mMockThreadExecutor;
@Mock
private PostExecutionThread mMockPostExecutionThread;
private ListFormUsecase mListFormUsecase;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mListFormUsecase = new ListFormUsecase(mMockFormJsonRepository, mMockThreadExecutor,
mMockPostExecutionThread);
}
@Test
public void shouldSuccessfullyFetchFromOnline() {
mListFormUsecase.setListForm(1l, From.ONLINE);
mListFormUsecase.buildUseCaseObservable();
verify(mMockFormJsonRepository).getForms(1l, From.ONLINE);
verifyNoMoreInteractions(mMockFormJsonRepository);
verifyNoMoreInteractions(mMockPostExecutionThread);
verifyNoMoreInteractions(mMockThreadExecutor);
}
@Test
public void shouldThrowRuntimeException() {
assertThat(mListFormUsecase).isNotNull();
mListFormUsecase.setListForm(null, null);
try {
mListFormUsecase.execute(null);
assert_().fail("Should have thrown RuntimeException");
} catch (RuntimeException e) {
assertThat(e).hasMessage(
"Deployment id and from cannot be null. You must call setListForm(...)");
}
}
}
| agpl-3.0 |
kaltura/KalturaGeneratedAPIClientsCsharp | KalturaClient/Enums/UserEntryOrderBy.cs | 1858 | // ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2021 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
namespace Kaltura.Enums
{
public sealed class UserEntryOrderBy : StringEnum
{
public static readonly UserEntryOrderBy CREATED_AT_ASC = new UserEntryOrderBy("+createdAt");
public static readonly UserEntryOrderBy UPDATED_AT_ASC = new UserEntryOrderBy("+updatedAt");
public static readonly UserEntryOrderBy CREATED_AT_DESC = new UserEntryOrderBy("-createdAt");
public static readonly UserEntryOrderBy UPDATED_AT_DESC = new UserEntryOrderBy("-updatedAt");
private UserEntryOrderBy(string name) : base(name) { }
}
}
| agpl-3.0 |
VeryTastyTomato/passhport | passhportd/app/models_mod/usergroup/__init__.py | 5736 | # -*-coding:Utf-8 -*-
# Compatibility 2.7-3.4
from __future__ import absolute_import
from __future__ import unicode_literals
from app import db
# Table to handle the self-referencing many-to-many relationship
# for the Usergroup class:
# First column holds the containers, the second the subusergroups.
group_of_group = db.Table(
"group_of_group",
db.Column(
"container_id",
db.Integer,
db.ForeignKey("usergroup.id"),
primary_key=True),
db.Column(
"subgroup_id",
db.Integer,
db.ForeignKey("usergroup.id"),
primary_key=True))
class Usergroup(db.Model):
"""Usergroup defines a group of users
(can contain some usergroups too)
"""
__tablename__ = "usergroup"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(256), index=True, unique=True)
comment = db.Column(db.String(500), index=True, unique=False)
# Relations
members = db.relationship("User", secondary="group_user")
gmembers = db.relationship(
"Usergroup",
secondary=group_of_group,
primaryjoin=id == group_of_group.c.container_id,
secondaryjoin=id == group_of_group.c.subgroup_id,
backref="containedin")
def __repr__(self):
"""Return main data of the usergroup as a string"""
output = []
output.append("Name: {}".format(self.name))
output.append("Comment: {}".format(self.comment))
output.append("User list: " + " ".join(self.username_list()))
output.append("Usergroup list: " + " ".join(self.usergroupname_list()))
output.append("All users: " + " ".join(self.all_username_list()))
output.append("All usergroups: " + \
" ".join(self.all_usergroupname_list()))
return "\n".join(output)
def show_name(self):
"""Return a string containing the usergroup's name"""
return self.name
# User management
def is_member(self, user):
"""Return true if the given user is a member of the usergroup,
false otherwise
"""
return user in self.members
def adduser(self, user):
"""Add a user to the relation table"""
if not self.is_member(user):
self.members.append(user)
return self
def rmuser(self, user):
"""Remove a user from the relation table"""
if self.is_member(user):
self.members.remove(user)
return self
def username_in_usergroup(self, username):
"""Return true if the given username belongs to a member
of the usergroup
"""
for user in self.members:
if user.show_name() == username:
return True
return False
def username_list(self):
"""Return usernames which belong to users in the usergroup"""
usernames = []
for user in self.members:
usernames.append(user.show_name())
return usernames
def all_username_list(self, parsed_usergroups = []):
"""Return all usernames which belong to users
in the usergroup and subusergroups
"""
usernames = self.username_list()
# Recursive on groups:
# we list all usernames but we never parse a group twice
# to avoid cirular issues.
for usergroup in self.gmembers:
if usergroup not in parsed_usergroups:
parsed_usergroups.append(usergroup)
for username in usergroup.all_username_list(parsed_usergroups):
if username not in usernames:
usernames.append(username)
return usernames
# Usergroup management
def is_gmember(self, usergroup):
"""Return true if the given usergroup is a member
of the usergroup, false otherwise
"""
return usergroup in self.gmembers
def addusergroup(self, usergroup):
"""Add a usergroup to the relation table"""
if not self.is_gmember(usergroup):
self.gmembers.append(usergroup)
return self
def rmusergroup(self, usergroup):
"""Remove a usergroup from the relation table"""
if self.is_gmember(usergroup):
self.gmembers.remove(usergroup)
return self
def subusergroupname_in_usergroup(self, subusergroupname):
"""Return true if the given subusergroupname belongs to a member
of the usergroup, false otherwise
"""
for subusergroup in self.gmembers:
if subusergroup.show_name() == subusergroupname:
return True
return False
def usergroupname_list(self):
"""Return usergroupnames which belong to subusergroups
in the usergroup
"""
usergroupnames = []
for usergroup in self.gmembers:
usergroupnames.append(usergroup.show_name())
return usergroupnames
def all_usergroupname_list(self, parsed_usergroups = []):
"""Return all usergroupnames which belong to subusergroups
in the usergroup
"""
usergroupnames = self.usergroupname_list() # ["G1","G2"]
# Recursive on usergroups:
# we list all usergroups but we never parse a group twice
# to avoid cirular issues.
for subusergroup in self.gmembers:
if subusergroup not in parsed_usergroups:
parsed_usergroups.append(subusergroup) # [G1,G2]
for subsubusergroupname in subusergroup.all_usergroupname_list(parsed_usergroups):
if subsubusergroupname not in usergroupnames:
usergroupnames.append(subsubusergroupname)
return usergroupnames
| agpl-3.0 |
SmartInfrastructures/xipi | portlets/bro4xipi-portlet/docroot/WEB-INF/src/eu/xipi/bro4xipi/Bro4xipi.java | 17329 |
/*******************************************************************************
* Copyright (C) 2013, University of Patras, Greece*
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package eu.xipi.bro4xipi;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import eu.xipi.bro4xipi.brokermodel.BrokerJpaController;
import eu.xipi.bro4xipi.resourceadvisor.AdvicedOffer;
import eu.xipi.bro4xipi.resourceadvisor.OfferedPlan;
import eu.xipi.bro4xipi.resourceadvisor.ResourceAdvisor;
import eu.xipi.bro4xipi.transformation.XiPiBroker;
import gr.upatras.ece.nam.broker.Broker;
import gr.upatras.ece.nam.broker.model.availabilitycontract.Availability;
import gr.upatras.ece.nam.broker.model.availabilitycontract.Cost;
import gr.upatras.ece.nam.broker.model.availabilitycontract.ResourceServiceContract;
import gr.upatras.ece.nam.broker.model.federationscenarios.ServiceRequest;
import gr.upatras.ece.nam.broker.model.providersite.DomainManager;
import gr.upatras.ece.nam.broker.model.providersite.Site;
import gr.upatras.ece.nam.broker.model.resources.OfferedResource;
import gr.upatras.ece.nam.broker.model.services.OfferedService;
import gr.upatras.ece.nam.broker.model.users.Account;
import gr.upatras.ece.nam.broker.model.users.ResourcesProvider;
/**
*
* the main class of the portlet
* @author ctranoris
*
*/
public class Bro4xipi extends GenericPortlet {
// @BeanReference(name = "eu.xipi.bro4xipi.brokermodel.BrokerJpaController")
protected enum portletViewstatusEnum {PVDEFINITION, PVPLANS, PVSELECTEDPLAN};
protected portletViewstatusEnum portletViewstatus = portletViewstatusEnum.PVDEFINITION;
private BrokerJpaController brokerJpaCtrl;
protected String editJSP;
protected String viewJSP;
protected String viewPlansJSP;
protected String viewSelectedPlanJSP;
protected String startsessionobjPage;
private static final transient Log logger = LogFactory
.getLog(Bro4xipi.class.getName());
private static EntityManagerFactory emf;
private static EntityManager entityManager;
private Broker broker;
public BrokerJpaController getBrokerJpaCtrl() {
return brokerJpaCtrl;
}
public void setBrokerJpaCtrl(BrokerJpaController brokerJpaCtrl) {
this.brokerJpaCtrl = brokerJpaCtrl;
}
public void setup() {
logger.info("Calling setup");
eu.xipi.bro4xipi.brokermodel.BrokerJpaController b = new BrokerJpaController();
this.brokerJpaCtrl = b;
Bro4xipi.emf = PersistenceManager.getInstance().getEntityManagerFactory();
Bro4xipi.entityManager = emf.createEntityManager();
}
/* (non-Javadoc)
* @see javax.portlet.GenericPortlet#init()
*/
public void init() throws PortletException {
logger.info("in init");
editJSP = getInitParameter("edit-jsp");
viewJSP = getInitParameter("view-jsp");
viewPlansJSP = getInitParameter("viewPlans-jsp");
viewSelectedPlanJSP = getInitParameter("viewSelectedPlan-jsp");
startsessionobjPage = getInitParameter("startsessionobj-jsp");
if (brokerJpaCtrl != null)
logger.info("Init Bro4xipi GenericPortlet brokerJpaCtrl="
+ brokerJpaCtrl.toString());
else
logger.info("Init Bro4xipi GenericPortlet brokerJpaCtrl=NULL!");
setup();
if (brokerJpaCtrl != null) {
logger.info("Init Bro4xipi GenericPortlet brokerJpaCtrl="
+ brokerJpaCtrl.toString());
brokerJpaCtrl.setEntityManager(entityManager);
entityManager.getTransaction().begin();
broker = brokerJpaCtrl.getFirstBroker();
entityManager.getTransaction().commit();
if (broker != null) {
logger.info("brokerJpaCtrl.getFirstBroker()="
+ broker.getName());
} else {
logger.info("brokerJpaCtrl.getFirstBroker()= NULL!");
}
} else
logger.info("Init Bro4xipi GenericPortlet brokerJpaCtrl=NULL!");
}
/* (non-Javadoc)
* @see javax.portlet.GenericPortlet#doEdit(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
public void doEdit(RenderRequest renderRequest,
RenderResponse renderResponse) throws IOException, PortletException {
renderResponse.setContentType("text/html");
PortletURL addNameURL = renderResponse.createActionURL();
addNameURL.setParameter("addName", "addName");
renderRequest.setAttribute("addNameURL", addNameURL.toString());
include(editJSP, renderRequest, renderResponse);
}
/* (non-Javadoc)
* @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
public void doView(RenderRequest renderRequest,
RenderResponse renderResponse) throws IOException, PortletException {
logger.info("in doView..");
PortletPreferences prefs = renderRequest.getPreferences();
//Try to get the session object
XiPiScenarioRequest sr = (XiPiScenarioRequest) renderRequest.getPortletSession().getAttribute("JSPxipiScenarioRequest" );
if (sr == null) { //session obj bean not yet created
logger.info("===> IN doView: (sr == null) ");
include(startsessionobjPage , renderRequest, renderResponse); //in here the session bean is created!
//this should be after include!
sr = (XiPiScenarioRequest) renderRequest.getPortletSession().getAttribute("JSPxipiScenarioRequest" );
logger.info("===>XiPiScenarioRequest sr just created sr="+sr.toString());
sr.setScenarioName("myNewExperiment");
sr.setBroker(broker);
renderRequest.getPortletSession().setAttribute("JSPxipiScenarioRequest", sr );
}else{
//the session object already exists
logger.info("===> IN doView: (XiPiScenarioRequest sr != null) !!!! sr="+sr.toString());
sr.setBroker(broker);
}
if (portletViewstatus == portletViewstatusEnum.PVDEFINITION)
include(viewJSP, renderRequest, renderResponse);
else if (portletViewstatus == portletViewstatusEnum.PVPLANS)
include(viewPlansJSP, renderRequest, renderResponse);
else if (portletViewstatus == portletViewstatusEnum.PVSELECTEDPLAN)
include(viewSelectedPlanJSP, renderRequest, renderResponse);
}
/* (non-Javadoc)
* @see javax.portlet.GenericPortlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
*/
public void processAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
//uncomment to view more debug info for passed parameters between pages
// logger.debug("==> in processAction");
// Enumeration<String> pns = actionRequest.getParameterNames();
// while (pns.hasMoreElements())
// logger.debug("==> in processAction pns.nextElement() ="+pns.nextElement());
//
// Enumeration<String> atns = actionRequest.getAttributeNames();
// while (atns.hasMoreElements())
// logger.debug("==> in processAction atns.nextElement() ="+atns.nextElement());
//
// Enumeration<String> propns = actionRequest.getPropertyNames();
// while (propns.hasMoreElements())
// logger.debug("==> in processAction getPropertyNames.nextElement() ="+propns.nextElement());
String mvcPath = actionRequest.getParameter("mvcPath");
//works like a statemachine according to which page we wish to view
if (mvcPath!=null){
if (mvcPath.equals("startTransformation"))
startTransformation( actionRequest, actionResponse);
else if (mvcPath.equals("addScenarioAction"))
addScenarioAction( actionRequest, actionResponse);
else if (mvcPath.equals("backToAddScenarioURL"))
startScenarioAction( actionRequest, actionResponse);
else if (mvcPath.equals("viewSelectedPlanAction"))
viewSelectedPlanAction( actionRequest, actionResponse);
else if (mvcPath.equals("backToViewPlansAction"))
viewPlansAction( actionRequest, actionResponse);
}
}
/**
*
* It will display the page with the selected plan
* @param actionRequest
* @param actionResponse
* @throws IOException
* @throws PortletException
*/
public void viewSelectedPlanAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
String selectedPlanId = actionRequest.getParameter("planid");
logger.info("==> in viewSelectedPlanAction selectedPlanId="+selectedPlanId);
portletViewstatus = portletViewstatusEnum.PVSELECTEDPLAN ;
XiPiScenarioRequest sr =(XiPiScenarioRequest) actionRequest.getPortletSession().getAttribute("JSPxipiScenarioRequest");
sr.setSelectedPlanId(Integer.parseInt(selectedPlanId));
actionResponse.setPortletMode(PortletMode.VIEW);
}
/**
* It will display the page with Offered plans
* @param actionRequest
* @param actionResponse
* @throws IOException
* @throws PortletException
*/
public void viewPlansAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
logger.info("==> in viewPlansAction");
portletViewstatus = portletViewstatusEnum.PVPLANS;
actionResponse.setPortletMode(PortletMode.VIEW);
}
/**
* It will display the main view page of a scenario
*
* @param actionRequest
* @param actionResponse
* @throws IOException
* @throws PortletException
*/
public void addScenarioAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
logger.info("==> in addScenarioAction");
portletViewstatus = portletViewstatusEnum.PVPLANS;
Enumeration<String> pns = actionRequest.getPortletSession().getAttributeNames();
while (pns.hasMoreElements()){
String s = pns.nextElement();
logger.info("==> in addScenarioAction getAttributeNames.nextElement() ="+s);
Object obj = actionRequest.getPortletSession().getAttribute(s);
logger.info("==> in addScenarioAction, obj="+obj.toString());
if (obj instanceof XiPiScenarioRequest){
XiPiScenarioRequest sr =(XiPiScenarioRequest) obj;
logger.info("==> in addScenarioAction, srname="+sr.getScenario().getName() );
if (sr.getBroker() == null)
sr.setBroker(broker);
}
}
XiPiScenarioRequest sr =(XiPiScenarioRequest) actionRequest.getPortletSession().getAttribute("JSPxipiScenarioRequest");
if (sr!=null){
sr.setBroker(broker);
logger.info("Setting broker to XiPiScenarioRequest = "+broker.toString());
String inputScenarioName = actionRequest.getParameter("inputScenarioName");
sr.setScenarioName(inputScenarioName);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm z");
Date startDate;
try {
startDate = df.parse(actionRequest.getParameter("startDate"));
sr.setStartDate( startDate);
Date endDate = df.parse(actionRequest.getParameter("endDate"));
sr.setEndDate( endDate );
for (Iterator< ServiceRequest > iterator = sr.getScenario().getServicesRequest().getServiceRequestList().iterator(); iterator.hasNext();) {
ServiceRequest servReq = (ServiceRequest) iterator.next();
if (servReq instanceof ServiceRequest) {
ServiceRequest serviceRequest = (ServiceRequest) servReq;
logger.info("serviceRequest.getName()="+ serviceRequest.getName() );
}
}
logger.debug("Starting ResourceAdvisor");
//logger.info("Contracts=" + brokerJpaCtrl.countServiceContracts() );
ResourceAdvisor ra = new ResourceAdvisor( broker, sr.getScenario(), brokerJpaCtrl );
ra.CalculateOffers();
Vector<OfferedPlan> offeredPlans = ra.getOfferedPlans();
for (OfferedPlan offeredPlan : offeredPlans) {
logger.info("========= "+offeredPlan.getProposedScenario().getName()+" #"+offeredPlan.getPlanID() +" =========");
Vector<AdvicedOffer> offer = offeredPlan.getAdvicedOffers();
for (AdvicedOffer advicedOffer : offer) {
logger.info( advicedOffer.getFullOfferedResourceIDRevert() );
}
}
sr.setOfferedPlans(offeredPlans);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("==> in addScenarioAction, XiPiScenarioRequest sr= ="+ sr.getScenario().getName() );
}else{
logger.info("==> in addScenarioAction, XiPiScenarioRequest sr= NULL !");
}
actionResponse.setPortletMode(PortletMode.VIEW);
}
/**
*
* used to return back to scenario view
* @param actionRequest
* @param actionResponse
* @throws IOException
* @throws PortletException
*/
public void startScenarioAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
logger.info("==> in startScenarioAction");
portletViewstatus = portletViewstatusEnum.PVDEFINITION;
actionResponse.setPortletMode(PortletMode.VIEW);
}
/**
*
* only called from edit mode to start manually the transformation
* This process takes time (about 10-15 minutes)
* @param actionRequest
* @param actionResponse
* @throws IOException
* @throws PortletException
*/
public void startTransformation(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
logger.info("In startTransformation");
broker = brokerJpaCtrl.getFirstBroker();
while (broker != null){ //delete all brokers found if any...normally should be only one
logger.info("Delete found brokers");
entityManager.getTransaction().begin();
brokerJpaCtrl.delete(broker);
entityManager.getTransaction().commit();
broker = brokerJpaCtrl.getFirstBroker();
}
logger.info("Starting transofrmation");
XiPiBroker xipibroker = new XiPiBroker();
//xipibroker.setMakeOnlyOneTaxonomy(true); //used to test a smalled transformation
String endpointUrl = "http://www.xipi.eu/InfinityServices-portlet/json";
xipibroker.setEndPointUrl(endpointUrl);
xipibroker.setURLAPI_getTechnicalComponents(endpointUrl
+ "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=getTechnicalComponents");
xipibroker.setURLAPI_getInfrastructuresById(endpointUrl
+ "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=getInfrastructuresById&serviceParameters=[id]&id=");
xipibroker.setURLAPI_searchInfrastructures(endpointUrl
+ "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=searchInfrastructures&serviceParameters=[text,country,component]&text=_$TEXTSEARCH_&country=_$COUNTRYID_&component=_$COMPONENTID_");
xipibroker.setURLAPI_getComponentDetail(endpointUrl
+ "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=getComponentDetail&serviceParameters=[idInfra,idComponent]&idInfra=_$INFRAID_&idComponent=_$COMPONENTID_");
xipibroker.setURLAPI_getValue4Field( endpointUrl
+ "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=getValue4Field");
//xipibroker.setMakeOnlyOneTaxonomy(true);
xipibroker.startTransformation(true);
Broker bro = xipibroker.getBroker();
// Broker bro = createTestBroker();
if (bro!=null){
logger.info("Transformation finished. Broker is ="+bro.getName());
entityManager.getTransaction().begin();
brokerJpaCtrl.addBroker(bro);
entityManager.getTransaction().commit();
logger.info("Broker and all data saved succesfully");
broker = brokerJpaCtrl.getFirstBroker();
logger.info("Broker getFirstBroker");
}
else
logger.info("Transformation finished. Broker is = NULL" );
}
protected void include(String path, RenderRequest renderRequest,
RenderResponse renderResponse) throws IOException, PortletException {
PortletRequestDispatcher portletRequestDispatcher = getPortletContext()
.getRequestDispatcher(path);
if (portletRequestDispatcher == null) {
logger.error(path + " is not a valid include");
} else {
portletRequestDispatcher.include(renderRequest, renderResponse);
}
}
}
| agpl-3.0 |
tudarmstadt-lt/newsleak-frontend | app/controllers/NetworkController.scala | 12557 | /*
* Copyright (C) 2016 Language Technology Group and Interactive Graphics Systems Group, Technische Universität Darmstadt, Germany
*
* 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 controllers
import javax.inject.Inject
import models.KeyTerm.keyTermFormat
import models.services.{ EntityService, KeywordNetworkService, NetworkService }
import models.{ Facets, Network, NodeBucket, Relationship }
import play.api.libs.json.{ JsObject, Json, JsValue }
import play.api.mvc.{ Action, AnyContent, Controller, Request }
import util.DateUtils
import util.SessionUtils.currentDataset
import scala.collection.JavaConverters._
import scala.collection.JavaConversions._
/**
* Provides network related actions.
*
* @param entityService the service for entity backend operations.
* @param networkService the service for network backend operations.
* @param dateUtils common helper for date and time operations.
*/
class NetworkController @Inject() (
entityService: EntityService,
networkService: NetworkService,
keywordNetworkService: KeywordNetworkService,
dateUtils: DateUtils
) extends Controller {
private val numberOfNeighbors = 200
/**
* Accumulates the number of entities that fall in a certain entity type and co-occur with the given entity.
*
* @param fullText match documents that contain the given expression in the document body.
* @param generic a map linking from document metadata keys to a list of instances for this metadata.
* @param entities a list of entity ids that should occur in the document.
* @param timeRange a string representing a time range for the document creation date.
* @param timeExprRange a string representing a time range for the document time expression.
* @param nodeId the entity id.
* @return mapping from unique entity types to the number of neighbors of that type.
*/
def getNeighborCounts(
fullText: List[String],
generic: Map[String, List[String]],
entities: List[Long],
timeRange: String,
timeExprRange: String,
nodeId: Long
) = Action { implicit request =>
val (from, to) = dateUtils.parseTimeRange(timeRange)
val (timeExprFrom, timeExprTo) = dateUtils.parseTimeRange(timeExprRange)
val facets = Facets(fullText, generic, entities, List(), from, to, timeExprFrom, timeExprTo)
val res = networkService.getNeighborCountsPerType(facets, nodeId)(currentDataset)
val counts = res.map { case (t, c) => Json.obj("type" -> t, "count" -> c) }
Ok(Json.toJson(counts)).as("application/json")
}
/**
* Returns important terms representing the relationship between both nodes based on the underlying document content.
*
* @param fullText match documents that contain the given expression in the document body.
* @param generic a map linking from document metadata keys to a list of instances for this metadata.
* @param entities a list of entity ids that should occur in the document.
* @param timeRange a string representing a time range for the document creation date.
* @param timeExprRange a string representing a time range for the document time expression.
* @param first the first adjacent node of the edge.
* @param second the second adjacent node of the edge.
* @param numberOfTerms the number of keywords to fetch.
* @return a list of [[models.KeyTerm]] representing important terms for the given relationship.
*/
def getEdgeKeywords(
fullText: List[String],
generic: Map[String, List[String]],
entities: List[Long],
timeRange: String,
timeExprRange: String,
first: Long,
second: Long,
numberOfTerms: Int
) = Action { implicit request =>
val (from, to) = dateUtils.parseTimeRange(timeRange)
val (timeExprFrom, timeExprTo) = dateUtils.parseTimeRange(timeExprRange)
val facets = Facets(fullText, generic, entities, List(), from, to, timeExprFrom, timeExprTo)
val terms = networkService.getEdgeKeywords(facets, first, second, numberOfTerms)(currentDataset)
Ok(Json.toJson(terms)).as("application/json")
}
/**
* Returns a co-occurrence network matching the given search query.
*
* @param fullText match documents that contain the given expression in the document body.
* @param generic a map linking from document metadata keys to a list of instances for this metadata.
* @param entities a list of entity ids that should occur in the document.
* @param timeRange a string representing a time range for the document creation date.
* @param timeExprRange a string representing a time range for the document time expression.
* @param nodeFraction a map linking from entity types to the number of nodes to request for each type.
* @return a network consisting of the nodes and relationships of the created co-occurrence network.
*/
def induceSubgraph(
fullText: List[String],
generic: Map[String, List[String]],
entities: List[Long],
keywords: List[String],
timeRange: String,
timeExprRange: String,
nodeFraction: Map[String, String]
) = Action { implicit request =>
val (from, to) = dateUtils.parseTimeRange(timeRange)
val (timeExprFrom, timeExprTo) = dateUtils.parseTimeRange(timeExprRange)
val facets = Facets(fullText, generic, entities, keywords, from, to, timeExprFrom, timeExprTo)
val sizes = nodeFraction.mapValues(_.toInt)
val blacklistedIds = entityService.getBlacklisted()(currentDataset).map(_.id)
val Network(nodes, relations) = networkService.createNetwork(facets, sizes, blacklistedIds)(currentDataset)
if (nodes.isEmpty) {
Ok(Json.obj("entities" -> List[JsObject](), "relations" -> List[JsObject]())).as("application/json")
} else {
val graphEntities = nodesToJson(nodes)
// Ignore relations that connect blacklisted nodes
val graphRelations = relations.filterNot { case Relationship(source, target, _) => blacklistedIds.contains(source) && blacklistedIds.contains(target) }
Ok(Json.obj("entities" -> graphEntities, "relations" -> graphRelations)).as("application/json")
}
}
/**
* Adds new nodes to the current network matching the given search query.
*
* @param fullText match documents that contain the given expression in the document body.
* @param generic a map linking from document metadata keys to a list of instances for this metadata.
* @param entities a list of entity ids that should occur in the document.
* @param timeRange a string representing a time range for the document creation date.
* @param timeExprRange a string representing a time range for the document time expression.
* @param currentNetwork the entity ids of the current network.
* @param nodes new entities to be added to the network.
* @return a network consisting of the nodes and relationships of the created co-occurrence network.
*/
def addNodes(
fullText: List[String],
generic: Map[String, List[String]],
entities: List[Long],
timeRange: String,
timeExprRange: String,
currentNetwork: List[Long],
nodes: List[Long]
) = Action { implicit request =>
val (from, to) = dateUtils.parseTimeRange(timeRange)
val (timeExprFrom, timeExprTo) = dateUtils.parseTimeRange(timeExprRange)
val facets = Facets(fullText, generic, entities, List(), from, to, timeExprFrom, timeExprTo)
val Network(buckets, relations) = networkService.induceNetwork(facets, currentNetwork, nodes)(currentDataset)
Ok(Json.obj("entities" -> nodesToJson(buckets), "relations" -> relations)).as("application/json")
}
// TODO: Use json writer and reader to minimize parameter in a case class Facets
/**
* Returns entities co-occurring with the given entity matching the search query.
*
* @param fullText match documents that contain the given expression in the document body.
* @param generic a map linking from document metadata keys to a list of instances for this metadata.
* @param entities a list of entity ids that should occur in the document.
* @param timeRange a string representing a time range for the document creation date.
* @param timeExprRange a string representing a time range for the document time expression.
* @param currentNetwork the entity ids of the current network.
* @param focalNode the entity id.
* @return co-occurring entities with the given entity.
*/
def getNeighbors(
fullText: List[String],
generic: Map[String, List[String]],
entities: List[Long],
timeRange: String,
timeExprRange: String,
currentNetwork: List[Long],
focalNode: Long
) = Action { implicit request =>
// TODO Duplicated code to parse facets
val (from, to) = dateUtils.parseTimeRange(timeRange)
val (timeExprFrom, timeExprTo) = dateUtils.parseTimeRange(timeExprRange)
val facets = Facets(fullText, generic, entities, List(), from, to, timeExprFrom, timeExprTo)
// TODO: we don't need to add the blacklist as exclude when we use getById.contains
val blacklistedIds = entityService.getBlacklisted()(currentDataset).map(_.id)
val nodes = networkService.getNeighbors(facets, focalNode, numberOfNeighbors, blacklistedIds ++ currentNetwork)(currentDataset)
val neighbors = nodesToJson(nodes)
Ok(Json.toJson(neighbors)).as("application/json")
}
private def nodesToJson(nodes: List[NodeBucket])(implicit request: Request[AnyContent]): List[JsObject] = {
val ids = nodes.map(_.id)
val nodeIdToEntity = entityService.getByIds(ids)(currentDataset).map(e => e.id -> e).toMap
val typesToId = entityService.getTypes()(currentDataset)
nodes.collect {
// Only add node if it is not blacklisted
case NodeBucket(id, count) if nodeIdToEntity.contains(id) =>
val node = nodeIdToEntity(id)
Json.obj(
"id" -> id,
"label" -> node.name,
"count" -> count,
"type" -> node.entityType.toString,
"group" -> typesToId(node.entityType)
)
}
}
/** Marks the entities associated with the given ids as blacklisted. */
def blacklistEntitiesById(ids: List[Long]) = Action { implicit request =>
Ok(Json.obj("result" -> entityService.blacklist(ids)(currentDataset))).as("application/json")
}
/**
* Merges multiple nodes in a given focal node.
*
* @param focalId the central entity id.
* @param duplicates entity ids referring to similar textual mentions of the focal id.
*/
def mergeEntitiesById(focalId: Long, duplicates: List[Long]) = Action { implicit request =>
entityService.merge(focalId, duplicates)(currentDataset)
Ok("success").as("Text")
}
/** Changes the name of the entity corresponding to the given entity id. */
def changeEntityNameById(id: Long, newName: String) = Action { implicit request =>
Ok(Json.obj("result" -> entityService.changeName(id, newName)(currentDataset))).as("application/json")
}
/** Changes the name of the entity corresponding to the given entity id. */
def highlightKeysByEnt(entName: String) = Action { implicit request =>
val keywords = networkService.getHighlights(entName)(currentDataset)
var res = Array[JsValue]()
var i = 0
val l = keywords.length
while (i < l) {
val kwd = keywords(i).asInstanceOf[List[_]].get(0).toString //keywords.get(i)("kwd")
val term = keywords(i).asInstanceOf[List[_]].get(1).toString //keywords.get(i)("tfq")
res = res :+ Json.obj("Keyword" -> kwd, "TermFrequency" -> term)
i += 1
}
Ok(Json.obj("keys" -> res)).as("application/json")
//Ok(Json.obj("result" -> entityService.changeName(id, newName)(currentDataset))).as("application/json")
}
/** Changes the type of the entity corresponding to the given entity id. */
def changeEntityTypeById(id: Long, newType: String) = Action { implicit request =>
Ok(Json.obj("result" -> entityService.changeType(id, newType)(currentDataset))).as("application/json")
}
}
| agpl-3.0 |
bosman/raven.testsuite | RavenClientWrappers/Raven.TestSuite.ClientWrapper.v2_5_2750/SyncAdvancedSessionOperationWrapper.cs | 3995 | namespace Raven.TestSuite.ClientWrapper.v2_5_2750
{
using Raven.TestSuite.Common.WrapperInterfaces;
using Raven.Client;
using Raven.TestSuite.Common.Abstractions.Json.Linq;
using Raven.Json.Linq;
using Raven.Imports.Newtonsoft.Json;
using Raven.TestSuite.Common.Abstractions.Data;
public class SyncAdvancedSessionOperationWrapper : ISyncAdvancedSessionOperationWrapper
{
private readonly ISyncAdvancedSessionOperation syncAdvancedSessionOperation;
internal SyncAdvancedSessionOperationWrapper(ISyncAdvancedSessionOperation syncAdvancedSessionOperation)
{
this.syncAdvancedSessionOperation = syncAdvancedSessionOperation;
}
public IEagerSessionOperationsWrapper Eagerly
{
get { return new EagerSessionOperationsWrapper(this.syncAdvancedSessionOperation.Eagerly); }
}
public ILazySessionOperationsWrapper Lazily
{
get { return new LazySessionOperationsWrapper(this.syncAdvancedSessionOperation.Lazily); }
}
public T[] LoadStartingWith<T>(string keyPrefix, string matches = null, int start = 0, int pageSize = 25, string exclude = null)
{
return this.syncAdvancedSessionOperation.LoadStartingWith<T>(keyPrefix, matches, start, pageSize, exclude);
}
public string GetDocumentUrl(object entity)
{
return this.syncAdvancedSessionOperation.GetDocumentUrl(entity);
}
public string GetDocumentId(object entity)
{
return this.syncAdvancedSessionOperation.GetDocumentId(entity);
}
public bool HasChanges
{
get { return this.syncAdvancedSessionOperation.HasChanges; }
}
public int MaxNumberOfRequestsPerSession
{
get { return this.syncAdvancedSessionOperation.MaxNumberOfRequestsPerSession; }
set { this.syncAdvancedSessionOperation.MaxNumberOfRequestsPerSession = value; }
}
public int NumberOfRequests
{
get { return this.syncAdvancedSessionOperation.NumberOfRequests; }
}
public string StoreIdentifier
{
get { return this.syncAdvancedSessionOperation.StoreIdentifier; }
}
public void Refresh<T>(T entity)
{
this.syncAdvancedSessionOperation.Refresh<T>(entity);
}
public bool UseOptimisticConcurrency
{
get { return this.syncAdvancedSessionOperation.UseOptimisticConcurrency; }
set { this.syncAdvancedSessionOperation.UseOptimisticConcurrency = value; }
}
public void Clear()
{
this.syncAdvancedSessionOperation.Clear();
}
public void Evict<T>(T entity)
{
this.syncAdvancedSessionOperation.Evict<T>(entity);
}
public EtagWrapper GetEtagFor<T>(T instance)
{
return new EtagWrapper(this.syncAdvancedSessionOperation.GetEtagFor<T>(instance).ToString());
}
public RavenJObjectWrapper GetMetadataFor<T>(T instance)
{
return RavenJObjectWrapper.Parse(this.syncAdvancedSessionOperation.GetMetadataFor<T>(instance).ToString());
}
public void SetMetadataValueFor<T>(T instance, string key, string value)
{
this.syncAdvancedSessionOperation.GetMetadataFor<T>(instance)[key] = value;
}
public bool HasChanged(object entity)
{
return this.syncAdvancedSessionOperation.HasChanged(entity);
}
public bool IsLoaded(string id)
{
return this.syncAdvancedSessionOperation.IsLoaded(id);
}
public void MarkReadOnly(object entity)
{
this.syncAdvancedSessionOperation.MarkReadOnly(entity);
}
}
}
| agpl-3.0 |
Muhannes/diaspora | spec/javascripts/app/views/header_view_spec.js | 2333 | describe("app.views.Header", function() {
beforeEach(function() {
this.userAttrs = {name: "alice", avatar: {small: "http://avatar.com/photo.jpg"}, guid: "foo" };
loginAs(this.userAttrs);
spec.loadFixture("aspects_index");
gon.appConfig = {settings: {podname: "MyPod"}};
this.view = new app.views.Header().render();
});
describe("render", function(){
context("notifications badge", function(){
it("displays a count when the current user has a notification", function(){
loginAs(_.extend(this.userAttrs, {notifications_count : 1}));
this.view.render();
expect(this.view.$(".notifications-link .badge").hasClass("hidden")).toBe(false);
expect(this.view.$(".notifications-link .badge").text()).toContain("1");
});
it("does not display a count when the current user has a notification", function(){
loginAs(_.extend(this.userAttrs, {notifications_count : 0}));
this.view.render();
expect(this.view.$(".notifications-link .badge").hasClass("hidden")).toBe(true);
});
});
context("conversations badge", function(){
it("displays a count when the current user has a notification", function(){
loginAs(_.extend(this.userAttrs, {unread_messages_count : 1}));
this.view.render();
expect(this.view.$("#conversations-link .badge").hasClass("hidden")).toBe(false);
expect(this.view.$("#conversations-link .badge").text()).toContain("1");
});
it("does not display a count when the current user has a notification", function(){
loginAs(_.extend(this.userAttrs, {unread_messages_count : 0}));
this.view.render();
expect(this.view.$("#conversations-link .badge").hasClass("hidden")).toBe(true);
});
});
context("admin link", function(){
it("displays if the current user is an admin", function(){
loginAs(_.extend(this.userAttrs, {admin : true}));
this.view.render();
expect(this.view.$("#user_menu").html()).toContain("/admins");
});
it("does not display if the current user is not an admin", function(){
loginAs(_.extend(this.userAttrs, {admin : false}));
this.view.render();
expect(this.view.$("#user_menu").html()).not.toContain("/admins");
});
});
});
});
| agpl-3.0 |
Minds/engine | Controllers/api/v2/admin/features.php | 1257 | <?php
/**
* features
*
* @author edgebal
*/
namespace Minds\Controllers\api\v2\admin;
use Exception;
use Minds\Api\Factory;
use Minds\Core\Features\Manager;
use Minds\Core\Session;
use Minds\Entities\User;
use Minds\Interfaces;
use Minds\Core\Di\Di;
class features implements Interfaces\Api, Interfaces\ApiAdminPam
{
/**
* @inheritDoc
*/
public function get($pages)
{
$for = null;
if (isset($_GET['for'])) {
try {
$for = new User(strtolower($_GET['for']));
if (!$for || !$for->guid) {
$for = null;
}
} catch (Exception $e) {
$for = null;
}
}
/** @var Manager $manager */
$manager = Di::_()->get('Features\Manager');
return Factory::response(
$manager->breakdown($for)
);
}
/**
* @inheritDoc
*/
public function post($pages)
{
return Factory::response([]);
}
/**
* @inheritDoc
*/
public function put($pages)
{
return Factory::response([]);
}
/**
* @inheritDoc
*/
public function delete($pages)
{
return Factory::response([]);
}
}
| agpl-3.0 |
ROIV/ViorCoin-ElectrumServer | src/networks.py | 1141 | # Main network and testnet3 definitions
params = {
'bitcoin_main': {
'pubkey_address': 0,
'script_address': 5,
'genesis_hash': '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
},
'bitcoin_test': {
'pubkey_address': 111,
'script_address': 196,
'genesis_hash': '000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943'
},
'litecoin_main': {
'pubkey_address': 48,
'script_address': 5,
'genesis_hash': '12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2'
},
'litecoin_test': {
'pubkey_address': 111,
'script_address': 196,
'genesis_hash': 'f5ae71e26c74beacc88382716aced69cddf3dffff24f384e1808905e0188f68f'
},
'viorcoin_main': {
'pubkey_address': 70,
'script_address': 125,
'genesis_hash': '0000074a757ce334e850ff46a695b96d4dc44ccdd0f6860f5c34c49ef9005dcc'
},
'viorcoin_test': {
'pubkey_address': 132,
'script_address': 196,
'genesis_hash': '0000074a757ce334e850ff46a695b96d4dc44ccdd0f6860f5c34c49ef9005dcc'
}
}
| agpl-3.0 |
exomiser/Exomiser | exomiser-core/src/main/java/org/monarchinitiative/exomiser/core/genome/dao/SvDaoBoundaryCalculator.java | 4468 | /*
* The Exomiser - A tool to annotate and prioritize genomic variants
*
* Copyright (c) 2016-2021 Queen Mary University of London.
* Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.monarchinitiative.exomiser.core.genome.dao;
import org.monarchinitiative.svart.GenomicRegion;
import java.util.Objects;
// /**
// * Returns a value to be added/subtracted to a ChromosomalRegion's start and end positions such that another region
// * whose start and end positions fall within these boundaries will have the required minimum coverage provided in the
// * method. For example the region 10-20 with a 0.85 overlap would have a margin value of 1 to be added/subtracted to
// * the start and end - i.e. anywhere between 10+/-1 and 20+/-1 will satisfy the 85% overlap requirement. Return values
// * are rounded to the nearest integer.
// *
// * @param region The {@link GenomicRegion} for which the boundaries are to be calculated
// * @param minCoverage The minimum required overlap for other regions
// * @return The modifier, to the nearest whole number, to be added and subtracted from the start and end of the input
// * region
// */
public class SvDaoBoundaryCalculator {
private final GenomicRegion genomicRegion;
private final double minSimilarity;
private final int innerBoundsOffset;
private final int outerBoundsOffset;
public SvDaoBoundaryCalculator(GenomicRegion genomicRegion, double minSimilarity) {
this.genomicRegion = genomicRegion;
this.minSimilarity = minSimilarity;
int length = genomicRegion.length();
this.innerBoundsOffset = innerBoundsOffset(length, minSimilarity);
this.outerBoundsOffset = outerBoundsOffset(length, minSimilarity);
}
private int outerBoundsOffset(int length, double minSimilarity) {
// (100 / 0.70) - 100
return Math.max(1, (int) Math.round((length / minSimilarity) - length));
}
private int innerBoundsOffset(int length, double minSimilarity) {
// 100 * (1 - 0.70)
return Math.max(1, (int) Math.round(length * (1 - minSimilarity)));
}
public GenomicRegion genomicRegion() {
return genomicRegion;
}
public double minSimilarity() {
return minSimilarity;
}
public int innerBoundsOffset() {
return innerBoundsOffset;
}
public int outerBoundsOffset() {
return outerBoundsOffset;
}
public int startMin() {
return Math.max(1, genomicRegion.startPosition().minPos() - outerBoundsOffset);
}
public int startMax() {
return genomicRegion.startPosition().maxPos() + innerBoundsOffset;
}
public int endMin() {
return genomicRegion.endPosition().minPos() - innerBoundsOffset;
}
public int endMax() {
return Math.min(genomicRegion.contig().length(), genomicRegion.endPosition().maxPos() + outerBoundsOffset);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SvDaoBoundaryCalculator that = (SvDaoBoundaryCalculator) o;
return Double.compare(that.minSimilarity, minSimilarity) == 0 && genomicRegion.equals(that.genomicRegion);
}
@Override
public int hashCode() {
return Objects.hash(genomicRegion, minSimilarity);
}
@Override
public String toString() {
return "SvDaoBoundaryCalculator{" +
"genomicRegion=" + genomicRegion +
", minSimilarity=" + minSimilarity +
", innerBoundsOffset=" + innerBoundsOffset +
", outerBoundsOffset=" + outerBoundsOffset +
'}';
}
}
| agpl-3.0 |
k10r/shopware | engine/Shopware/Bundle/ESIndexingBundle/Commands/BacklogSyncCommand.php | 2704 | <?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\ESIndexingBundle\Commands;
use Shopware\Bundle\ESIndexingBundle\Struct\Backlog;
use Shopware\Commands\ShopwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @category Shopware
*
* @copyright Copyright (c) shopware AG (http://www.shopware.de)
*/
class BacklogSyncCommand extends ShopwareCommand
{
/**
* @var int
*/
private $batchSize;
/**
* @param int $batchSize
*/
public function __construct($batchSize = 500)
{
$this->batchSize = (int) $batchSize;
parent::__construct(null);
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('sw:es:backlog:sync')
->setDescription('Synchronize events from the backlog to the live index.')
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$reader = $this->container->get('shopware_elastic_search.backlog_reader');
$backlogs = $reader->read($reader->getLastBacklogId(), $this->batchSize);
if (empty($backlogs)) {
return;
}
/** @var $last Backlog */
$last = $backlogs[count($backlogs) - 1];
$reader->setLastBacklogId($last->getId());
$shops = $this->container->get('shopware_elastic_search.identifier_selector')->getShops();
foreach ($shops as $shop) {
$index = $this->container->get('shopware_elastic_search.index_factory')->createShopIndex($shop, '');
$this->container->get('shopware_elastic_search.backlog_processor')
->process($index, $backlogs);
}
}
}
| agpl-3.0 |
protolambda/blocktopograph | app/src/main/java/com/protolambda/blocktopograph/map/renderer/SlimeChunkRenderer.java | 5492 | package com.protolambda.blocktopograph.map.renderer;
import android.graphics.Bitmap;
import com.protolambda.blocktopograph.chunk.ChunkManager;
import com.protolambda.blocktopograph.chunk.Version;
import com.protolambda.blocktopograph.map.Dimension;
import com.protolambda.blocktopograph.util.MTwister;
public class SlimeChunkRenderer implements MapRenderer {
/**
* Render a single chunk to provided bitmap (bm)
* @param cm ChunkManager, provides chunks, which provide chunk-data
* @param bm Bitmap to render to
* @param dimension Mapped dimension
* @param chunkX X chunk coordinate (x-block coord / Chunk.WIDTH)
* @param chunkZ Z chunk coordinate (z-block coord / Chunk.LENGTH)
* @param bX begin block X coordinate, relative to chunk edge
* @param bZ begin block Z coordinate, relative to chunk edge
* @param eX end block X coordinate, relative to chunk edge
* @param eZ end block Z coordinate, relative to chunk edge
* @param pX texture X pixel coord to start rendering to
* @param pY texture Y pixel coord to start rendering to
* @param pW width (X) of one block in pixels
* @param pL length (Z) of one block in pixels
* @return bm is returned back
*
* @throws Version.VersionException when the version of the chunk is unsupported.
*/
public Bitmap renderToBitmap(ChunkManager cm, Bitmap bm, Dimension dimension, int chunkX, int chunkZ, int bX, int bZ, int eX, int eZ, int pX, int pY, int pW, int pL) throws Version.VersionException {
int x, z, i, j, tX, tY;
MapType.OVERWORLD_SATELLITE.renderer.renderToBitmap(cm, bm, dimension, chunkX, chunkZ, bX, bZ, eX, eZ, pX, pY, pW, pL);
boolean isSlimeChunk = isSlimeChunk(chunkX, chunkZ);
int color, r, g, b, avg;
//make slimeChunks much more green
for (z = bZ, tY = pY ; z < eZ; z++, tY += pL) {
for (x = bX, tX = pX; x < eX; x++, tX += pW) {
color = bm.getPixel(tX, tY);
r = (color >> 16) & 0xff;
g = (color >> 8) & 0xff;
b = color & 0xff;
avg = (r + g + b) / 3;
if(isSlimeChunk){
r = b = avg;
g = (g + 0xff) >> 1;
} else {
r = g = b = avg;
}
color = (color & 0xFF000000) | (r << 16) | (g << 8) | b;
for(i = 0; i < pL; i++){
for(j = 0; j < pW; j++){
bm.setPixel(tX + j, tY + i, color);
}
}
}
}
return bm;
}
// See: https://gist.github.com/protolambda/00b85bf34a75fd8176342b1ad28bfccc
public static boolean isSlimeChunk(int cX, int cZ){
//
// MCPE slime-chunk checker
// From Minecraft: Pocket Edition 0.15.0 (0.15.0.50_V870150050)
// Reverse engineered by @protolambda and @jocopa3
//
// NOTE:
// - The world-seed doesn't seem to be incorporated into the randomness, which is very odd.
// This means that every world has its slime-chunks in the exact same chunks!
// This is not officially confirmed yet.
// - Reverse engineering this code cost a lot of time,
// please add CREDITS when you are copying this.
// Copy the following into your program source:
// MCPE slime-chunk checker; reverse engineered by @protolambda and @jocopa3
//
// chunkX/Z are the chunk-coordinates, used in the DB keys etc.
// Unsigned int32, using 64 bit longs to work-around the sign issue.
long chunkX_uint = cX & 0xffffffffL;
long chunkZ_uint = cZ & 0xffffffffL;
// Combine X and Z into a 32 bit int (again, long to work around sign issue)
long seed = (chunkX_uint * 0x1f1f1f1fL) ^ chunkZ_uint;
// The random function MCPE uses, not the same as MCPC!
// This is a Mersenne Twister; MT19937 by Takuji Nishimura and Makoto Matsumoto.
// Java adaption source: http://dybfin.wustl.edu/teaching/compufinj/MTwister.java
MTwister random = new MTwister();
random.init_genrand(seed);
// The output of the random function, first operand of the asm umull instruction
long n = random.genrand_int32();
// The other operand, magic bit number that keeps characteristics
// In binary: 1100 1100 1100 1100 1100 1100 1100 1101
long m = 0xcccccccdL;
// umull (unsigned long multiplication)
// Stores the result of multiplying two int32 integers in two registers (lo and hi).
// Java workaround: store the result in a 64 bit long, instead of two 32 bit registers.
long product = n * m;
// The umull instruction puts the result in a lo and a hi register, the lo one is not used.
long hi = (product >> 32) & 0xffffffffL;
// Make room for 3 bits, preparation for decrease of randomness by a factor 10.
long hi_shift3 = (hi >> 0x3) & 0xffffffffL;
// Multiply with 10 (3 bits)
// ---> effect: the 3 bit randomness decrease expresses a 1 in a 10 chance.
long res = (((hi_shift3 + (hi_shift3 * 0x4)) & 0xffffffffL) * 0x2) & 0xffffffffL;
// Final check: is the input equal to 10 times less random, but comparable, output.
// Every chunk has a 1 in 10 chance to be a slime-chunk.
return n == res;
}
} | agpl-3.0 |
sikamedia/metaverse | include/metaverse/explorer/commands/mnemonic-encode.hpp | 6229 | /**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BX_MNEMONIC_ENCODE_HPP
#define BX_MNEMONIC_ENCODE_HPP
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <metaverse/bitcoin.hpp>
#include <metaverse/explorer/command.hpp>
#include <metaverse/explorer/define.hpp>
#include <metaverse/explorer/generated.hpp>
#include <metaverse/explorer/config/address.hpp>
#include <metaverse/explorer/config/algorithm.hpp>
#include <metaverse/explorer/config/btc.hpp>
#include <metaverse/explorer/config/byte.hpp>
#include <metaverse/explorer/config/cert_key.hpp>
#include <metaverse/explorer/config/ec_private.hpp>
#include <metaverse/explorer/config/encoding.hpp>
#include <metaverse/explorer/config/endorsement.hpp>
#include <metaverse/explorer/config/hashtype.hpp>
#include <metaverse/explorer/config/hd_key.hpp>
#include <metaverse/explorer/config/header.hpp>
#include <metaverse/explorer/config/input.hpp>
#include <metaverse/explorer/config/language.hpp>
#include <metaverse/explorer/config/output.hpp>
#include <metaverse/explorer/config/raw.hpp>
#include <metaverse/explorer/config/script.hpp>
#include <metaverse/explorer/config/signature.hpp>
#include <metaverse/explorer/config/transaction.hpp>
#include <metaverse/explorer/config/wrapper.hpp>
#include <metaverse/explorer/utility.hpp>
/********* GENERATED SOURCE CODE, DO NOT EDIT EXCEPT EXPERIMENTALLY **********/
namespace libbitcoin {
namespace explorer {
namespace commands {
/**
* Various localizable strings.
*/
#define BX_MNEMONIC_ENCODE_OBSOLETE \
"Electrum style key functions are obsolete. Use mnemonic-new (BIP39) command instead."
/**
* Class to implement the mnemonic-encode command.
*/
class BCX_API mnemonic_encode
: public command
{
public:
/**
* The symbolic (not localizable) command name, lower case.
*/
static const char* symbol()
{
return "mnemonic-encode";
}
/**
* The symbolic (not localizable) former command name, lower case.
*/
static const char* formerly()
{
return "mnemonic";
}
/**
* The member symbolic (not localizable) command name, lower case.
*/
virtual const char* name()
{
return mnemonic_encode::symbol();
}
/**
* The localizable command category name, upper case.
*/
virtual const char* category()
{
return "ELECTRUM";
}
/**
* The localizable command description.
*/
virtual const char* description()
{
return "Convert an Electrum mnemonic to its seed.";
}
/**
* Declare whether the command has been obsoleted.
* @return True if the command is obsolete
*/
virtual bool obsolete()
{
return true;
}
/**
* Load program argument definitions.
* A value of -1 indicates that the number of instances is unlimited.
* @return The loaded program argument definitions.
*/
virtual arguments_metadata& load_arguments()
{
return get_argument_metadata();
}
/**
* Load parameter fallbacks from file or input as appropriate.
* @param[in] input The input stream for loading the parameters.
* @param[in] The loaded variables.
*/
virtual void load_fallbacks(std::istream& input,
po::variables_map& variables)
{
}
/**
* Load program option definitions.
* BUGBUG: see boost bug/fix: svn.boost.org/trac/boost/ticket/8009
* @return The loaded program option definitions.
*/
virtual options_metadata& load_options()
{
using namespace po;
options_description& options = get_option_metadata();
options.add_options()
(
BX_HELP_VARIABLE ",h",
value<bool>()->zero_tokens(),
"Get a description and instructions for this command."
)
(
BX_CONFIG_VARIABLE ",c",
value<boost::filesystem::path>(),
"The path to the configuration settings file."
);
return options;
}
/**
* Set variable defaults from configuration variable values.
* @param[in] variables The loaded variables.
*/
virtual void set_defaults_from_config(po::variables_map& variables)
{
}
/**
* Invoke the command.
* @param[out] output The input stream for the command execution.
* @param[out] error The input stream for the command execution.
* @return The appropriate console return code { -1, 0, 1 }.
*/
virtual console_result invoke(std::ostream& output,
std::ostream& cerr);
/* Properties */
private:
/**
* Command line argument bound variables.
* Uses cross-compiler safe constructor-based zeroize.
* Zeroize for unit test consistency with program_options initialization.
*/
struct argument
{
argument()
{
}
} argument_;
/**
* Command line option bound variables.
* Uses cross-compiler safe constructor-based zeroize.
* Zeroize for unit test consistency with program_options initialization.
*/
struct option
{
option()
{
}
} option_;
};
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
#endif
| agpl-3.0 |
be-cloud-be/horizon-addons | partner-contact/partner_financial_risk/__openerp__.py | 705 | # -*- coding: utf-8 -*-
# © 2016 Carlos Dauden <carlos.dauden@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Partner Financial Risk',
'summary': 'Manage partner risk',
'version': '9.0.1.0.0',
'category': 'Sales Management',
'license': 'AGPL-3',
'author': 'Tecnativa, Odoo Community Association (OCA)',
'website': 'https://www.tecnativa.com',
'depends': ['account'],
'data': [
'data/partner_financial_risk_data.xml',
'views/res_config_view.xml',
'views/res_partner_view.xml',
'views/account_invoice_view.xml',
'wizard/partner_risk_exceeded_view.xml',
],
'installable': True,
}
| agpl-3.0 |
grafana/grafana | public/app/features/variables/state/types.ts | 1380 | import { VariableType } from '@grafana/data';
import { VariableModel } from '../types';
export interface VariablesState extends Record<string, VariableModel> {}
export const initialVariablesState: VariablesState = {};
export const getInstanceState = <Model extends VariableModel = VariableModel>(state: VariablesState, id: string) => {
return state[id] as Model;
};
export interface VariableIdentifier {
type: VariableType;
id: string;
}
export interface VariablePayload<T extends any = undefined> extends VariableIdentifier {
data: T;
}
export interface AddVariable<T extends VariableModel = VariableModel> {
global: boolean; // part of dashboard or global
index: number; // the order in variables list
model: T;
}
export const toVariableIdentifier = (variable: VariableModel): VariableIdentifier => {
return { type: variable.type, id: variable.id };
};
export function toVariablePayload<T extends any = undefined>(
identifier: VariableIdentifier,
data?: T
): VariablePayload<T>;
// eslint-disable-next-line
export function toVariablePayload<T extends any = undefined>(model: VariableModel, data?: T): VariablePayload<T>;
// eslint-disable-next-line
export function toVariablePayload<T extends any = undefined>(
obj: VariableIdentifier | VariableModel,
data?: T
): VariablePayload<T> {
return { type: obj.type, id: obj.id, data: data as T };
}
| agpl-3.0 |
ambimorph/recluse | recluse/vocabulary_cutter.py | 1342 | # 2012 L. Amber Wilcox-O'Hearn
import sys, bisect
class VocabularyCutter():
"""
Takes a file of unigram counts and returns a file of the top n
most frequent words.
If there are fewer than n words, it returns them all.
"""
def __init__(self, infile_obj, outfile_obj):
self.infile_obj = infile_obj
self.outfile_obj = outfile_obj
def cut_vocabulary(self, n=None, min_frequency=None):
frequencies = []
for line in self.infile_obj:
tokens = line.split()
assert len(tokens) == 2, line
bisect.insort( frequencies, (int(tokens[1]), tokens[0]) )
if min_frequency is not None:
frequencies = [x for x in frequencies if x[0] >= min_frequency]
if n is None:
n = len(frequencies)
else:
n = min(n, len(frequencies))
for i in range(n):
self.outfile_obj.write(frequencies[-1-i][1])
self.outfile_obj.write('\n')
if __name__ == '__main__':
infile_obj = sys.stdin
outfile_obj = sys.stdout
vc = VocabularyCutter(infile_obj, outfile_obj)
try:
n = int(sys.argv[1])
except ValueError:
n = None
try:
min_freq = int(sys.argv[2])
except ValueError:
min_freq = None
vc.cut_vocabulary(n=n, min_frequency=min_freq)
| agpl-3.0 |
timble/openpolice-platform | application/manager/component/police/view/zones/templates/default_sidebar.html.php | 660 | <?
/**
* Belgian Police Web Platform - Police Component
*
* @copyright Copyright (C) 2012 - 2017 Timble CVBA. (http://www.timble.net)
* @license GNU AGPLv3 <https://www.gnu.org/licenses/agpl.html>
* @link https://github.com/timble/openpolice-platform
*/
?>
<h3><?= translate('Provinces')?></h3>
<?= import('com:streets.view.provinces.list.html', array('provinces' => object('com:streets.model.provinces')->sort('title')->getRowset())); ?>
<h3><?= translate('Districts')?></h3>
<?= import('com:streets.view.districts.list.html', array('districts' => object('com:streets.model.districts')->province($state->province)->sort('title')->getRowset())); ?>
| agpl-3.0 |
NoetherEmmy/intransigentms | src/net/sf/odinms/net/channel/ChannelWorldInterfaceImpl.java | 24506 | package net.sf.odinms.net.channel;
import net.sf.odinms.client.*;
import net.sf.odinms.client.BuddyList.BuddyAddResult;
import net.sf.odinms.client.BuddyList.BuddyOperation;
import net.sf.odinms.database.DatabaseConnection;
import net.sf.odinms.net.ByteArrayMaplePacket;
import net.sf.odinms.net.MaplePacket;
import net.sf.odinms.net.channel.remote.ChannelWorldInterface;
import net.sf.odinms.net.world.*;
import net.sf.odinms.net.world.guild.MapleGuildSummary;
import net.sf.odinms.net.world.remote.CheaterData;
import net.sf.odinms.server.ShutdownServer;
import net.sf.odinms.server.TimerManager;
import net.sf.odinms.tools.CollectionUtil;
import net.sf.odinms.tools.MaplePacketCreator;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
public class ChannelWorldInterfaceImpl extends UnicastRemoteObject implements ChannelWorldInterface {
private static final long serialVersionUID = 7815256899088644192L;
private ChannelServer server;
public ChannelWorldInterfaceImpl() throws RemoteException {
super(0, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory());
}
public ChannelWorldInterfaceImpl(final ChannelServer server) throws RemoteException {
super(0, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory());
this.server = server;
}
public void setChannelId(final int id) throws RemoteException {
server.setChannel(id);
}
public int getChannelId() throws RemoteException {
return server.getChannel();
}
public String getIP() throws RemoteException {
return server.getIP();
}
public void broadcastMessage(final String sender, final byte[] message) throws RemoteException {
final MaplePacket packet = new ByteArrayMaplePacket(message);
server.broadcastPacket(packet);
}
public void whisper(final String sender, final String target, final int channel, final String message) throws RemoteException {
if (isConnected(target)) {
server.getPlayerStorage().getCharacterByName(target).getClient().getSession().write(
MaplePacketCreator.getWhisper(sender, channel, message)
);
}
}
public boolean isConnected(final String charName) throws RemoteException {
return server.getPlayerStorage().getCharacterByName(charName) != null;
}
public MapleCharacter getPlayer(final String charName) throws RemoteException {
return server.getPlayerStorage().getCharacterByName(charName);
}
public void shutdown(final int time) throws RemoteException {
server.broadcastPacket(
MaplePacketCreator.serverNotice(
0,
"The world will be shut down in " +
(time / 60000) +
" minutes, please log off safely"
)
);
TimerManager.getInstance().schedule(new ShutdownServer(server.getChannel()), time);
}
public int getConnected() throws RemoteException {
return server.getConnectedClients();
}
@Override
public void loggedOff(final String name, final int characterId, final int channel, final int[] buddies) throws RemoteException {
updateBuddies(characterId, channel, buddies, true);
}
@Override
public void loggedOn(final String name, final int characterId, final int channel, final int[] buddies) throws RemoteException {
updateBuddies(characterId, channel, buddies, false);
}
private void updateBuddies(final int characterId, final int channel, final int[] buddies, final boolean offline) {
final IPlayerStorage playerStorage = server.getPlayerStorage();
for (final int buddy : buddies) {
final MapleCharacter chr = playerStorage.getCharacterById(buddy);
if (chr != null) {
final BuddylistEntry ble = chr.getBuddylist().get(characterId);
if (ble != null && ble.isVisible()) {
final int mcChannel;
if (offline) {
ble.setChannel(-1);
mcChannel = -1;
} else {
ble.setChannel(channel);
mcChannel = channel - 1;
}
chr.getBuddylist().put(ble);
chr.getClient()
.getSession()
.write(MaplePacketCreator.updateBuddyChannel(ble.getCharacterId(), mcChannel));
}
}
}
}
@Override
public void updateParty(final MapleParty party,
final PartyOperation operation,
final MaplePartyCharacter target) throws RemoteException {
for (final MaplePartyCharacter partychar : party.getMembers()) {
if (partychar.getChannel() == server.getChannel()) {
final MapleCharacter chr = server.getPlayerStorage().getCharacterByName(partychar.getName());
if (chr != null) {
if (operation == PartyOperation.DISBAND) {
chr.setParty(null);
} else {
chr.setParty(party);
}
chr.getClient()
.getSession()
.write(
MaplePacketCreator.updateParty(
chr.getClient().getChannel(),
party,
operation,
target
)
);
}
}
}
switch (operation) {
case LEAVE:
case EXPEL:
if (target.getChannel() == server.getChannel()) {
final MapleCharacter chr = server.getPlayerStorage().getCharacterByName(target.getName());
if (chr != null) {
chr.getClient()
.getSession()
.write(
MaplePacketCreator.updateParty(
chr.getClient().getChannel(),
party,
operation,
target
)
);
chr.setParty(null);
}
}
}
}
@Override
public void partyChat(final MapleParty party, final String chattext, final String namefrom) throws RemoteException {
for (final MaplePartyCharacter partychar : party.getMembers()) {
if (partychar.getChannel() == server.getChannel() && !(partychar.getName().equals(namefrom))) {
final MapleCharacter chr = server.getPlayerStorage().getCharacterByName(partychar.getName());
if (chr != null) {
chr.getClient().getSession().write(MaplePacketCreator.multiChat(namefrom, chattext, 1));
}
}
}
}
public boolean isAvailable() throws RemoteException {
return true;
}
public int getLocation(final String name) throws RemoteException {
final MapleCharacter chr = server.getPlayerStorage().getCharacterByName(name);
if (chr != null) {
return server.getPlayerStorage().getCharacterByName(name).getMapId();
}
return -1;
}
public List<CheaterData> getCheaters() throws RemoteException {
final List<CheaterData> cheaters = new ArrayList<>();
final List<MapleCharacter> allplayers = new ArrayList<>(server.getPlayerStorage().getAllCharacters());
/*Collections.sort(allplayers, new Comparator<MapleCharacter>() {
@Override
public int compare(MapleCharacter o1, MapleCharacter o2) {
int thisVal = o1.getCheatTracker().getPoints();
int anotherVal = o2.getCheatTracker().getPoints();
return (thisVal<anotherVal ? 1 : (thisVal==anotherVal ? 0 : -1));
}
});*/
for (int x = allplayers.size() - 1; x >= 0; x--) {
final MapleCharacter cheater = allplayers.get(x);
if (cheater.getCheatTracker().getPoints() > 0) {
cheaters.add(
new CheaterData(
cheater.getCheatTracker().getPoints(),
MapleCharacterUtil.makeMapleReadable(cheater.getName()) +
" (" +
cheater.getCheatTracker().getPoints() +
") " +
cheater.getCheatTracker().getSummary()
)
);
}
}
Collections.sort(cheaters);
return CollectionUtil.copyFirst(cheaters, 10);
}
@Override
public BuddyAddResult requestBuddyAdd(final String addName, final int channelFrom, final int cidFrom, final String nameFrom) {
final MapleCharacter addChar = server.getPlayerStorage().getCharacterByName(addName);
if (addChar != null) {
final BuddyList buddylist = addChar.getBuddylist();
if (buddylist.isFull()) {
return BuddyAddResult.BUDDYLIST_FULL;
}
if (!buddylist.contains(cidFrom)) {
buddylist.addBuddyRequest(addChar.getClient(), cidFrom, nameFrom, channelFrom);
} else {
if (buddylist.containsVisible(cidFrom)) {
return BuddyAddResult.ALREADY_ON_LIST;
}
}
}
return BuddyAddResult.OK;
}
@Override
public boolean isConnected(final int characterId) throws RemoteException {
return server.getPlayerStorage().getCharacterById(characterId) != null;
}
@Override
public void buddyChanged(final int cid, final int cidFrom, final String name, final int channel, final BuddyOperation operation) {
final MapleCharacter addChar = server.getPlayerStorage().getCharacterById(cid);
if (addChar != null) {
final BuddyList buddylist = addChar.getBuddylist();
switch (operation) {
case ADDED:
if (buddylist.contains(cidFrom)) {
buddylist.put(new BuddylistEntry(name, cidFrom, channel, true));
addChar
.getClient()
.getSession()
.write(
MaplePacketCreator.updateBuddyChannel(cidFrom, channel - 1)
);
}
break;
case DELETED:
if (buddylist.contains(cidFrom)) {
buddylist.put(new BuddylistEntry(name, cidFrom, -1, buddylist.get(cidFrom).isVisible()));
addChar.getClient().getSession().write(MaplePacketCreator.updateBuddyChannel(cidFrom, -1));
}
break;
}
}
}
@Override
public void buddyChat(final int[] recipientCharacterIds,
final int cidFrom,
final String nameFrom,
final String chattext) throws RemoteException {
final IPlayerStorage playerStorage = server.getPlayerStorage();
for (final int characterId : recipientCharacterIds) {
final MapleCharacter chr = playerStorage.getCharacterById(characterId);
if (chr != null) {
if (chr.getBuddylist().containsVisible(cidFrom)) {
chr.getClient().getSession().write(MaplePacketCreator.multiChat(nameFrom, chattext, 0));
}
}
}
}
@Override
public int[] multiBuddyFind(final int charIdFrom, final int[] characterIds) throws RemoteException {
final List<Integer> ret = new ArrayList<>(characterIds.length);
final IPlayerStorage playerStorage = server.getPlayerStorage();
for (final int characterId : characterIds) {
final MapleCharacter chr = playerStorage.getCharacterById(characterId);
if (chr != null) {
if (chr.getBuddylist().containsVisible(charIdFrom)) {
ret.add(characterId);
}
}
}
final int[] retArr = new int[ret.size()];
int pos = 0;
for (final Integer i : ret) {
retArr[pos++] = i;
}
return retArr;
}
@Override
public void sendPacket(final List<Integer> targetIds, final MaplePacket packet, final int exception) throws RemoteException {
MapleCharacter c;
for (final int i : targetIds) {
if (i == exception) {
continue;
}
c = server.getPlayerStorage().getCharacterById(i);
if (c != null) {
c.getClient().getSession().write(packet);
}
}
}
@Override
public void setGuildAndRank(final List<Integer> cids, final int guildid, final int rank,
final int exception) throws RemoteException {
for (final int cid : cids) {
if (cid != exception) {
setGuildAndRank(cid, guildid, rank);
}
}
}
@Override
public void setGuildAndRank(final int cid, final int guildid, final int rank) throws RemoteException {
final MapleCharacter mc = server.getPlayerStorage().getCharacterById(cid);
if (mc == null) {
//System.out.println("ERROR: cannot find player in given channel");
return;
}
final boolean bDifferentGuild;
if (guildid == -1 && rank == -1) {
bDifferentGuild = true;
} else {
bDifferentGuild = guildid != mc.getGuildId();
mc.setGuildId(guildid);
mc.setGuildRank(rank);
mc.saveGuildStatus();
}
if (bDifferentGuild) {
mc.getMap().broadcastMessage(mc, MaplePacketCreator.removePlayerFromMap(cid), false);
mc.getMap().broadcastMessage(mc, MaplePacketCreator.spawnPlayerMapobject(mc), false);
final MaplePet[] pets = mc.getPets();
for (int i = 0; i < 3; ++i) {
if (pets[i] != null) {
mc.getMap().broadcastMessage(mc, MaplePacketCreator.showPet(mc, pets[i], false, false), false);
} else {
break;
}
}
}
}
@Override
public void setOfflineGuildStatus(final int guildid, final byte guildrank, final int cid) throws RemoteException {
//final Logger log = LoggerFactory.getLogger(this.getClass());
try {
final Connection con = DatabaseConnection.getConnection();
final PreparedStatement ps =
con.prepareStatement(
"UPDATE characters SET guildid = ?, guildrank = ? WHERE id = ?"
);
ps.setInt(1, guildid);
ps.setInt(2, guildrank);
ps.setInt(3, cid);
ps.execute();
ps.close();
} catch (final SQLException sqle) {
System.err.println("SQLException: " + sqle.getLocalizedMessage());
}
}
@Override
public void reloadGuildCharacters() throws RemoteException {
for (final MapleCharacter mc : server.getPlayerStorage().getAllCharacters()) {
if (mc.getGuildId() > 0) {
// Multiple world ops, but this method is ONLY used
// in !clearguilds gm command, so it shouldn't be a problem
server.getWorldInterface().setGuildMemberOnline(mc.getMGC(), true, server.getChannel());
server.getWorldInterface().memberLevelJobUpdate(mc.getMGC());
}
}
ChannelServer.getInstance(this.getChannelId()).reloadGuildSummary();
}
@Override
public void changeEmblem(final int gid, final List<Integer> affectedPlayers, final MapleGuildSummary mgs) throws RemoteException {
ChannelServer.getInstance(this.getChannelId()).updateGuildSummary(gid, mgs);
sendPacket(
affectedPlayers,
MaplePacketCreator.guildEmblemChange(
gid,
mgs.getLogoBG(),
mgs.getLogoBGColor(),
mgs.getLogo(),
mgs.getLogoColor()
),
-1
);
setGuildAndRank(affectedPlayers, -1, -1, -1); // Respawn player
}
public void messengerInvite(final String sender,
final int messengerid,
final String target,
final int fromchannel) throws RemoteException {
if (isConnected(target)) {
final MapleMessenger messenger = server.getPlayerStorage().getCharacterByName(target).getMessenger();
if (messenger == null) {
server
.getPlayerStorage()
.getCharacterByName(target)
.getClient()
.getSession()
.write(
MaplePacketCreator.messengerInvite(
sender,
messengerid
)
);
final MapleCharacter from =
ChannelServer.getInstance(fromchannel).getPlayerStorage().getCharacterByName(sender);
from.getClient().getSession().write(MaplePacketCreator.messengerNote(target, 4, 1));
} else {
final MapleCharacter from =
ChannelServer.getInstance(fromchannel).getPlayerStorage().getCharacterByName(sender);
from
.getClient()
.getSession()
.write(
MaplePacketCreator.messengerChat(
sender +
" : " +
target +
" is already using Maple Messenger."
)
);
}
}
}
public void addMessengerPlayer(final MapleMessenger messenger,
final String namefrom,
final int fromchannel,
final int position) throws RemoteException {
for (final MapleMessengerCharacter messengerchar : messenger.getMembers()) {
if (messengerchar.getChannel() == server.getChannel() && !(messengerchar.getName().equals(namefrom))) {
final MapleCharacter chr = server.getPlayerStorage().getCharacterByName(messengerchar.getName());
if (chr != null) {
final MapleCharacter from =
ChannelServer.getInstance(fromchannel).getPlayerStorage().getCharacterByName(namefrom);
chr.getClient()
.getSession()
.write(
MaplePacketCreator.addMessengerPlayer(
namefrom,
from,
position,
fromchannel - 1
)
);
from
.getClient()
.getSession()
.write(
MaplePacketCreator.addMessengerPlayer(
chr.getName(),
chr,
messengerchar.getPosition(),
messengerchar.getChannel() - 1
)
);
}
} else if (
messengerchar.getChannel() == server.getChannel() &&
messengerchar.getName().equals(namefrom)
) {
final MapleCharacter chr = server.getPlayerStorage().getCharacterByName(messengerchar.getName());
if (chr != null) {
chr.getClient().getSession().write(MaplePacketCreator.joinMessenger(messengerchar.getPosition()));
}
}
}
}
public void removeMessengerPlayer(final MapleMessenger messenger, final int position) throws RemoteException {
for (final MapleMessengerCharacter messengerchar : messenger.getMembers()) {
if (messengerchar.getChannel() == server.getChannel()) {
final MapleCharacter chr = server.getPlayerStorage().getCharacterByName(messengerchar.getName());
if (chr != null) {
chr.getClient().getSession().write(MaplePacketCreator.removeMessengerPlayer(position));
}
}
}
}
public void messengerChat(final MapleMessenger messenger, final String chattext, final String namefrom) throws RemoteException {
for (final MapleMessengerCharacter messengerchar : messenger.getMembers()) {
if (messengerchar.getChannel() == server.getChannel() && !(messengerchar.getName().equals(namefrom))) {
final MapleCharacter chr = server.getPlayerStorage().getCharacterByName(messengerchar.getName());
if (chr != null) {
chr.getClient().getSession().write(MaplePacketCreator.messengerChat(chattext));
}
}
}
}
public void declineChat(final String target, final String namefrom) throws RemoteException {
if (isConnected(target)) {
final MapleMessenger messenger = server.getPlayerStorage().getCharacterByName(target).getMessenger();
if (messenger != null) {
server.getPlayerStorage().getCharacterByName(target).getClient().getSession().write(
MaplePacketCreator.messengerNote(namefrom, 5, 0));
}
}
}
public void updateMessenger(final MapleMessenger messenger,
final String namefrom,
final int position,
final int fromchannel) throws RemoteException {
for (final MapleMessengerCharacter messengerchar : messenger.getMembers()) {
if (messengerchar.getChannel() == server.getChannel() && !(messengerchar.getName().equals(namefrom))) {
final MapleCharacter chr = server.getPlayerStorage().getCharacterByName(messengerchar.getName());
if (chr != null) {
final MapleCharacter from =
ChannelServer.getInstance(fromchannel).getPlayerStorage().getCharacterByName(namefrom);
chr.getClient()
.getSession()
.write(
MaplePacketCreator.updateMessengerPlayer(
namefrom,
from,
position,
fromchannel - 1
)
);
}
}
}
}
public void broadcastGMMessage(final String sender, final byte[] message) throws RemoteException {
final MaplePacket packet = new ByteArrayMaplePacket(message);
server.broadcastGMPacket(packet);
}
public void broadcastSMega(final String sender, final byte[] message) throws RemoteException {
final MaplePacket packet = new ByteArrayMaplePacket(message);
server.broadcastSMega(packet);
}
public void broadcastToClan(final byte[] message, final int clan) throws RemoteException {
final MaplePacket packet = new ByteArrayMaplePacket(message);
server.broadcastToClan(packet, clan);
}
public int onlineClanMembers(final int clan) {
return server.onlineClanMembers(clan);
}
}
| agpl-3.0 |
adaxi/freeciv-web | freeciv-web/src/main/webapp/3d-models/Dragoons.js | 3310 | {
"metadata" :
{
"formatVersion" : 3.1,
"sourceFile" : "Dragoons.obj",
"generatedBy" : "OBJConverter",
"vertices" : 4089,
"faces" : 3858,
"normals" : 3697,
"uvs" : 0,
"materials" : 12
},
"materials": [ {
"DbgColor" : 15658734,
"DbgIndex" : 0,
"DbgName" : "None",
"colorDiffuse" : [0.8, 0.8, 0.8],
"colorSpecular" : [0.8, 0.8, 0.8],
"illumination" : 2,
"opacity" : 1.0,
"specularCoef" : 0.0
},
{
"DbgColor" : 15597568,
"DbgIndex" : 1,
"DbgName" : "Material",
"colorDiffuse" : [0.137866, 0.070109, 0.020319],
"colorSpecular" : [0.159237, 0.126169, 0.015383],
"illumination" : 2,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 60928,
"DbgIndex" : 2,
"DbgName" : "shirt",
"colorDiffuse" : [0.336271, 0.008448, 0.0],
"colorSpecular" : [0.0, 0.0, 0.0],
"illumination" : 1,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 238,
"DbgIndex" : 3,
"DbgName" : "hat_cover",
"colorDiffuse" : [0.64, 0.463547, 0.118838],
"colorSpecular" : [0.5, 0.5, 0.5],
"illumination" : 2,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 15658496,
"DbgIndex" : 4,
"DbgName" : "horse_cover",
"colorDiffuse" : [0.041358, 0.115292, 0.213403],
"colorSpecular" : [0.5, 0.5, 0.5],
"illumination" : 2,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 61166,
"DbgIndex" : 5,
"DbgName" : "jacket",
"colorDiffuse" : [0.005244, 0.020314, 0.0],
"colorSpecular" : [0.0, 0.0, 0.0],
"illumination" : 1,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 15597806,
"DbgIndex" : 6,
"DbgName" : "hat",
"colorDiffuse" : [0.0, 0.0, 0.0],
"colorSpecular" : [0.0, 0.0, 0.0],
"illumination" : 1,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 14968288,
"DbgIndex" : 7,
"DbgName" : "leather",
"colorDiffuse" : [0.064007, 0.037171, 0.017811],
"colorSpecular" : [0.035088, 0.035088, 0.035088],
"illumination" : 2,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 7078673,
"DbgIndex" : 8,
"DbgName" : "horse_body",
"colorDiffuse" : [0.061666, 0.057343, 0.048823],
"colorSpecular" : [0.0, 0.0, 0.0],
"illumination" : 1,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 1458591,
"DbgIndex" : 9,
"DbgName" : "hoof",
"colorDiffuse" : [0.021767, 0.008416, 0.0],
"colorSpecular" : [0.0, 0.0, 0.0],
"illumination" : 1,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 11353132,
"DbgIndex" : 10,
"DbgName" : "tail",
"colorDiffuse" : [0.430572, 0.430572, 0.430572],
"colorSpecular" : [0.0, 0.0, 0.0],
"illumination" : 1,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
},
{
"DbgColor" : 499914,
"DbgIndex" : 11,
"DbgName" : "boot",
"colorDiffuse" : [0.006874, 0.006874, 0.006874],
"colorSpecular" : [0.210526, 0.210526, 0.210526],
"illumination" : 2,
"opacity" : 1.0,
"opticalDensity" : 1.0,
"specularCoef" : 96.078431
}],
"buffers": "Dragoons.bin"
}
| agpl-3.0 |
jzinedine/CMDBuild | shark/commons/src/main/java/org/cmdbuild/workflow/xpdl/XpdlActivity.java | 7229 | package org.cmdbuild.workflow.xpdl;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.cmdbuild.workflow.xpdl.XpdlDocument.ScriptLanguage;
import org.enhydra.jxpdl.XPDLConstants;
import org.enhydra.jxpdl.elements.Activity;
import org.enhydra.jxpdl.elements.ExtendedAttribute;
import org.enhydra.jxpdl.elements.ExtendedAttributes;
import org.enhydra.jxpdl.elements.ImplementationTypes;
import org.enhydra.jxpdl.elements.Performer;
import org.enhydra.jxpdl.elements.SubFlow;
import org.enhydra.jxpdl.elements.TSScript;
import org.enhydra.jxpdl.elements.TaskApplication;
import org.enhydra.jxpdl.elements.TaskTypes;
import org.enhydra.jxpdl.elements.Transition;
public class XpdlActivity implements XpdlExtendedAttributesHolder {
final XpdlDocument doc;
final XpdlProcess process;
final Activity inner;
private final XpdlExtendedAttributes extendedAttributes;
XpdlActivity(final XpdlProcess process, final Activity activity) {
Validate.notNull(process);
Validate.notNull(activity);
this.doc = process.getDocument();
this.process = process;
this.inner = activity;
this.extendedAttributes = new XpdlActivityExtendedAttributes(this);
}
public XpdlProcess getProcess() {
return process;
}
public XpdlDocument getDocument() {
return doc;
}
public String getId() {
return inner.getId();
}
public String getName() {
return inner.getName();
}
public String getDescription() {
return inner.getDescription();
}
public boolean isManualType() {
return inner.getActivityType() == XPDLConstants.ACTIVITY_TYPE_NO;
}
public void setBlockType(final XpdlActivitySet activitySet) {
if (activitySet != null) {
inner.getActivityTypes().setBlockActivity();
inner.getActivityTypes().getBlockActivity().setActivitySetId(activitySet.inner.getId());
}
}
public boolean isBlockType() {
return inner.getActivityType() == XPDLConstants.ACTIVITY_TYPE_BLOCK;
}
public XpdlActivitySet getBlockActivitySet() {
if (isBlockType()) {
final String blockId = inner.getActivityTypes().getBlockActivity().getActivitySetId();
return process.findActivitySet(blockId);
} else {
return null;
}
}
public void setStartEventType() {
doc.turnReadWrite();
inner.getActivityTypes().setEvent();
inner.getActivityTypes().getEvent().getEventTypes().setStartEvent();
}
public boolean isStartEventType() {
return inner.getActivityType() == XPDLConstants.ACTIVITY_TYPE_EVENT_START;
}
public void setEndEventType() {
doc.turnReadWrite();
inner.getActivityTypes().setEvent();
inner.getActivityTypes().getEvent().getEventTypes().setEndEvent();
}
public boolean isEndEventType() {
return inner.getActivityType() == XPDLConstants.ACTIVITY_TYPE_EVENT_END;
}
public boolean isScriptingType() {
return inner.getActivityType() == XPDLConstants.ACTIVITY_TYPE_TASK_SCRIPT;
}
public ScriptLanguage getScriptLanguage() {
final TSScript tsScript = getScript();
final String mimeType = tsScript.getScriptType();
return ScriptLanguage.of(mimeType);
}
public String getScriptExpression() {
final TSScript tsScript = getScript();
final String script = tsScript.toValue();
return script;
}
public void setScriptingType(final ScriptLanguage language, final String expression) {
doc.turnReadWrite();
final TSScript tsScript = getScript();
tsScript.setScriptType(language.getMimeType());
tsScript.setValue(expression);
}
private TSScript getScript() {
final TaskTypes taskTypes = getTaskTypes();
taskTypes.setTaskScript();
final TSScript tsScript = taskTypes.getTaskScript().getScript();
return tsScript;
}
public void setSubProcess(final XpdlProcess subprocess) {
doc.turnReadWrite();
final ImplementationTypes implementationTypes = inner.getActivityTypes().getImplementation()
.getImplementationTypes();
implementationTypes.setSubFlow();
final SubFlow subflow = implementationTypes.getSubFlow();
subflow.setId(subprocess.getId());
}
/**
* Sets the only performer for this activity. We are not interested in more
* than one performer.
*
* @param name
* of the first and only performer
*/
public void setPerformer(final String performerName) {
doc.turnReadWrite();
final Performer performer = (Performer) inner.getPerformers().generateNewElement();
performer.setValue(performerName);
inner.getPerformers().clear();
inner.getPerformers().add(performer);
}
/**
* List<CMActivityVariableToProcess> Returns the first performer for this
* activity.
*
* @return name of the first performer
*/
public String getFirstPerformer() {
if (inner.getPerformers().isEmpty()) {
return null;
} else {
final Performer p = (Performer) inner.getPerformers().get(0);
return p.toValue();
}
}
@Override
public void addExtendedAttribute(final String key, final String value) {
extendedAttributes.addExtendedAttribute(key, value);
}
@Override
public String getFirstExtendedAttributeValue(final String key) {
return extendedAttributes.getFirstExtendedAttributeValue(key);
}
public XpdlExtendedAttribute getFirstExtendedAttribute(final String key) {
final ExtendedAttribute xa = extendedAttributes.getFirstExtendedAttribute(key);
return XpdlExtendedAttribute.newInstance(xa);
}
public List<XpdlExtendedAttribute> getExtendedAttributes() {
final List<XpdlExtendedAttribute> xxas = new ArrayList<XpdlExtendedAttribute>();
final ExtendedAttributes xattrs = inner.getExtendedAttributes();
if (xattrs != null) {
for (int i = 0; i < xattrs.size(); ++i) {
final ExtendedAttribute xa = (ExtendedAttribute) xattrs.get(i);
final XpdlExtendedAttribute xxa = XpdlExtendedAttribute.newInstance(xa);
if (xxa != null) {
xxas.add(xxa);
}
}
}
return xxas;
}
public boolean hasExtendedAttributeIgnoreCase(final String key) {
if (key == null) {
return false;
}
final ExtendedAttributes xattrs = inner.getExtendedAttributes();
if (xattrs != null) {
for (int i = 0; i < xattrs.size(); ++i) {
final ExtendedAttribute xa = (ExtendedAttribute) xattrs.get(i);
if (key.equalsIgnoreCase(xa.getName())) {
return true;
}
}
}
return false;
}
public boolean isTaskApplication() {
return inner.getActivityType() == XPDLConstants.ACTIVITY_TYPE_TASK_APPLICATION;
}
public void setTaskApplication(final String applicationId) {
final TaskTypes taskTypes = getTaskTypes();
taskTypes.setTaskApplication();
final TaskApplication taskApplication = taskTypes.getTaskApplication();
taskApplication.setId(applicationId);
}
private TaskTypes getTaskTypes() {
final ImplementationTypes implementationTypes = inner.getActivityTypes().getImplementation()
.getImplementationTypes();
implementationTypes.setTask();
final TaskTypes taskTypes = implementationTypes.getTask().getTaskTypes();
return taskTypes;
}
public List<XpdlTransition> getOutgoingTransitions() {
doc.turnReadOnly();
final List<XpdlTransition> outgoing = new ArrayList<XpdlTransition>();
for (final Object o : inner.getOutgoingTransitions()) {
final Transition transition = (Transition) o;
outgoing.add(new XpdlTransition(process, transition));
}
return outgoing;
}
} | agpl-3.0 |
ONLYOFFICE/core | ASCOfficeXlsFile2/source/XlsXlsxConverter/ConvertShapes/FormulaShape.cpp | 5053 | /*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#pragma once
#include "FormulaShape.h"
LONG NSCustomShapesConvert::CFormula::CalculateFormula(NSCustomShapesConvert::CFormulasManager* pManager)
{
if ((0 > m_lIndex) || (m_lIndex >= pManager->m_arResults.size()))
return 0;
if (0xFFFFFFFF != pManager->m_arResults[m_lIndex])
{
return pManager->m_arResults[m_lIndex];
}
LONG lResult = 0;
LONG lGuidesCount = pManager->m_arFormulas.size();
LONG lAdjCount = pManager->m_pAdjustments->size();
LONG a1 = m_lParam1;
if (ptFormula == m_eType1)
{
a1 = (m_lParam1 >= lGuidesCount) ? 0 : pManager->m_arFormulas[m_lParam1].CalculateFormula(pManager);
}
else if (ptAdjust == m_eType1)
{
a1 = (m_lParam1 >= lAdjCount) ? 0 : (*(pManager->m_pAdjustments))[m_lParam1];
}
LONG b1 = m_lParam2;
if (ptFormula == m_eType2)
{
b1 = (m_lParam2 >= lGuidesCount) ? 0 : pManager->m_arFormulas[m_lParam2].CalculateFormula(pManager);
}
else if (ptAdjust == m_eType2)
{
b1 = (m_lParam2 >= lAdjCount) ? 0 : (*(pManager->m_pAdjustments))[m_lParam2];
}
LONG c1 = m_lParam3;
if (ptFormula == m_eType3)
{
c1 = (m_lParam3 >= lGuidesCount) ? 0 : pManager->m_arFormulas[m_lParam3].CalculateFormula(pManager);
}
else if (ptAdjust == m_eType3)
{
c1 = (m_lParam3 >= lAdjCount) ? 0 : (*(pManager->m_pAdjustments))[m_lParam3];
}
double a = (double)a1;
double b = (double)b1;
double c = (double)c1;
double dRes = 0.0;
try
{
// теперь нужно просто посчитать
switch (m_eFormulaType)
{
case ftSum: { dRes = a + b - c; break; }
case ftProduct: {
if (0 == c)
c = 1;
dRes = a * b / c;
break;
}
case ftMid: { dRes = (a + b) / 2.0; break; }
case ftAbsolute: { dRes = abs(a); break; }
case ftMin: { dRes = (std::min)(a, b); break; }
case ftMax: { dRes = (std::max)(a, b); break; }
case ftIf: { dRes = (a > 0) ? b : c; break; }
case ftSqrt: { dRes = sqrt(a); break; }
case ftMod: { dRes = sqrt(a*a + b*b + c*c); break; }
case ftSin: {
//dRes = a * sin(b);
//dRes = a * sin(b / pow2_16);
dRes = a * sin(M_PI * b / (pow2_16 * 180));
break;
}
case ftCos: {
//dRes = a * cos(b);
//dRes = a * cos(b / pow2_16);
dRes = a * cos(M_PI * b / (pow2_16 * 180));
break;
}
case ftTan: {
//dRes = a * tan(b);
dRes = a * tan(M_PI * b / (pow2_16 * 180));
break;
}
case ftAtan2: {
dRes = 180 * pow2_16 * atan2(b,a) / M_PI;
break;
}
case ftSinatan2: { dRes = a * sin(atan2(c,b)); break; }
case ftCosatan2: { dRes = a * cos(atan2(c,b)); break; }
case ftSumangle: {
//dRes = a + b - c;
dRes = a + b * pow2_16 - c * pow2_16;
/*while (23592960 < dRes)
{
dRes -= 23592960;
}
while (-23592960 > dRes)
{
dRes += 23592960;
}*/
break;
}
case ftEllipse: {
if (0 == b)
b = 1;
dRes = c * sqrt(1-(a*a/(b*b)));
break;
}
case ftVal: { dRes = a; break; }
default: break;
};
}
catch (...)
{
dRes = 0;
}
lResult = (LONG)dRes;
pManager->m_arResults[m_lIndex] = lResult;
return lResult;
}
| agpl-3.0 |
gangadharkadam/sher | erpnext/selling/doctype/sales_order/sales_order.py | 14276 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import frappe.utils
from frappe.utils import cstr, flt, getdate, comma_and
from frappe import _
from frappe.model.mapper import get_mapped_doc
from erpnext.controllers.selling_controller import SellingController
form_grid_templates = {
"sales_order_details": "templates/form_grid/item_grid.html"
}
class SalesOrder(SellingController):
tname = 'Sales Order Item'
fname = 'sales_order_details'
person_tname = 'Target Detail'
partner_tname = 'Partner Target Detail'
territory_tname = 'Territory Target Detail'
def validate_mandatory(self):
# validate transaction date v/s delivery date
if self.delivery_date:
if getdate(self.transaction_date) > getdate(self.delivery_date):
frappe.throw(_("Expected Delivery Date cannot be before Sales Order Date"))
def validate_po(self):
# validate p.o date v/s delivery date
if self.po_date and self.delivery_date and getdate(self.po_date) > getdate(self.delivery_date):
frappe.throw(_("Expected Delivery Date cannot be before Purchase Order Date"))
if self.po_no and self.customer:
so = frappe.db.sql("select name from `tabSales Order` \
where ifnull(po_no, '') = %s and name != %s and docstatus < 2\
and customer = %s", (self.po_no, self.name, self.customer))
if so and so[0][0]:
frappe.msgprint(_("Warning: Sales Order {0} already exists against same Purchase Order number").format(so[0][0]))
def validate_for_items(self):
check_list, flag = [], 0
chk_dupl_itm = []
for d in self.get('sales_order_details'):
e = [d.item_code, d.description, d.warehouse, d.prevdoc_docname or '']
f = [d.item_code, d.description]
if frappe.db.get_value("Item", d.item_code, "is_stock_item") == 'Yes':
if not d.warehouse:
frappe.throw(_("Reserved warehouse required for stock item {0}").format(d.item_code))
if e in check_list:
frappe.throw(_("Item {0} has been entered twice").format(d.item_code))
else:
check_list.append(e)
else:
if f in chk_dupl_itm:
frappe.throw(_("Item {0} has been entered twice").format(d.item_code))
else:
chk_dupl_itm.append(f)
# used for production plan
d.transaction_date = self.transaction_date
tot_avail_qty = frappe.db.sql("select projected_qty from `tabBin` \
where item_code = %s and warehouse = %s", (d.item_code,d.warehouse))
d.projected_qty = tot_avail_qty and flt(tot_avail_qty[0][0]) or 0
def validate_sales_mntc_quotation(self):
for d in self.get('sales_order_details'):
if d.prevdoc_docname:
res = frappe.db.sql("select name from `tabQuotation` where name=%s and order_type = %s", (d.prevdoc_docname, self.order_type))
if not res:
frappe.msgprint(_("Quotation {0} not of type {1}").format(d.prevdoc_docname, self.order_type))
def validate_order_type(self):
super(SalesOrder, self).validate_order_type()
def validate_delivery_date(self):
if self.order_type == 'Sales' and not self.delivery_date:
frappe.throw(_("Please enter 'Expected Delivery Date'"))
self.validate_sales_mntc_quotation()
def validate_proj_cust(self):
if self.project_name and self.customer_name:
res = frappe.db.sql("""select name from `tabProject` where name = %s
and (customer = %s or ifnull(customer,'')='')""",
(self.project_name, self.customer))
if not res:
frappe.throw(_("Customer {0} does not belong to project {1}").format(self.customer, self.project_name))
def validate(self):
super(SalesOrder, self).validate()
self.validate_order_type()
self.validate_delivery_date()
self.validate_mandatory()
self.validate_proj_cust()
self.validate_po()
self.validate_uom_is_integer("stock_uom", "qty")
self.validate_for_items()
self.validate_warehouse()
from erpnext.stock.doctype.packed_item.packed_item import make_packing_list
make_packing_list(self,'sales_order_details')
self.validate_with_previous_doc()
if not self.status:
self.status = "Draft"
from erpnext.utilities import validate_status
validate_status(self.status, ["Draft", "Submitted", "Stopped",
"Cancelled"])
if not self.billing_status: self.billing_status = 'Not Billed'
if not self.delivery_status: self.delivery_status = 'Not Delivered'
def validate_warehouse(self):
from erpnext.stock.utils import validate_warehouse_company
warehouses = list(set([d.warehouse for d in
self.get(self.fname) if d.warehouse]))
for w in warehouses:
validate_warehouse_company(w, self.company)
def validate_with_previous_doc(self):
super(SalesOrder, self).validate_with_previous_doc(self.tname, {
"Quotation": {
"ref_dn_field": "prevdoc_docname",
"compare_fields": [["company", "="], ["currency", "="]]
}
})
def update_enquiry_status(self, prevdoc, flag):
enq = frappe.db.sql("select t2.prevdoc_docname from `tabQuotation` t1, `tabQuotation Item` t2 where t2.parent = t1.name and t1.name=%s", prevdoc)
if enq:
frappe.db.sql("update `tabOpportunity` set status = %s where name=%s",(flag,enq[0][0]))
def update_prevdoc_status(self, flag):
for quotation in list(set([d.prevdoc_docname for d in self.get(self.fname)])):
if quotation:
doc = frappe.get_doc("Quotation", quotation)
if doc.docstatus==2:
frappe.throw(_("Quotation {0} is cancelled").format(quotation))
doc.set_status(update=True)
def on_submit(self):
super(SalesOrder, self).on_submit()
self.update_stock_ledger(update_stock = 1)
self.check_credit(self.grand_total)
frappe.get_doc('Authorization Control').validate_approving_authority(self.doctype, self.grand_total, self)
self.update_prevdoc_status('submit')
frappe.db.set(self, 'status', 'Submitted')
def on_cancel(self):
# Cannot cancel stopped SO
if self.status == 'Stopped':
frappe.throw(_("Stopped order cannot be cancelled. Unstop to cancel."))
self.check_nextdoc_docstatus()
self.update_stock_ledger(update_stock = -1)
self.update_prevdoc_status('cancel')
frappe.db.set(self, 'status', 'Cancelled')
def check_nextdoc_docstatus(self):
# Checks Delivery Note
submit_dn = frappe.db.sql_list("""select t1.name from `tabDelivery Note` t1,`tabDelivery Note Item` t2
where t1.name = t2.parent and t2.against_sales_order = %s and t1.docstatus = 1""", self.name)
if submit_dn:
frappe.throw(_("Delivery Notes {0} must be cancelled before cancelling this Sales Order").format(comma_and(submit_dn)))
# Checks Sales Invoice
submit_rv = frappe.db.sql_list("""select t1.name
from `tabSales Invoice` t1,`tabSales Invoice Item` t2
where t1.name = t2.parent and t2.sales_order = %s and t1.docstatus = 1""",
self.name)
if submit_rv:
frappe.throw(_("Sales Invoice {0} must be cancelled before cancelling this Sales Order").format(comma_and(submit_rv)))
#check maintenance schedule
submit_ms = frappe.db.sql_list("""select t1.name from `tabMaintenance Schedule` t1,
`tabMaintenance Schedule Item` t2
where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1""", self.name)
if submit_ms:
frappe.throw(_("Maintenance Schedule {0} must be cancelled before cancelling this Sales Order").format(comma_and(submit_ms)))
# check maintenance visit
submit_mv = frappe.db.sql_list("""select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2
where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1""",self.name)
if submit_mv:
frappe.throw(_("Maintenance Visit {0} must be cancelled before cancelling this Sales Order").format(comma_and(submit_mv)))
# check production order
pro_order = frappe.db.sql_list("""select name from `tabProduction Order`
where sales_order = %s and docstatus = 1""", self.name)
if pro_order:
frappe.throw(_("Production Order {0} must be cancelled before cancelling this Sales Order").format(comma_and(pro_order)))
def check_modified_date(self):
mod_db = frappe.db.get_value("Sales Order", self.name, "modified")
date_diff = frappe.db.sql("select TIMEDIFF('%s', '%s')" %
( mod_db, cstr(self.modified)))
if date_diff and date_diff[0][0]:
frappe.throw(_("{0} {1} has been modified. Please refresh.").format(self.doctype, self.name))
def stop_sales_order(self):
self.check_modified_date()
self.update_stock_ledger(-1)
frappe.db.set(self, 'status', 'Stopped')
frappe.msgprint(_("{0} {1} status is Stopped").format(self.doctype, self.name))
def unstop_sales_order(self):
self.check_modified_date()
self.update_stock_ledger(1)
frappe.db.set(self, 'status', 'Submitted')
frappe.msgprint(_("{0} {1} status is Unstopped").format(self.doctype, self.name))
def update_stock_ledger(self, update_stock):
from erpnext.stock.utils import update_bin
for d in self.get_item_list():
if frappe.db.get_value("Item", d['item_code'], "is_stock_item") == "Yes":
args = {
"item_code": d['item_code'],
"warehouse": d['reserved_warehouse'],
"reserved_qty": flt(update_stock) * flt(d['reserved_qty']),
"posting_date": self.transaction_date,
"voucher_type": self.doctype,
"voucher_no": self.name,
"is_amended": self.amended_from and 'Yes' or 'No'
}
update_bin(args)
def on_update(self):
pass
def get_portal_page(self):
return "order" if self.docstatus==1 else None
@frappe.whitelist()
def make_material_request(source_name, target_doc=None):
def postprocess(source, doc):
doc.material_request_type = "Purchase"
doc = get_mapped_doc("Sales Order", source_name, {
"Sales Order": {
"doctype": "Material Request",
"validation": {
"docstatus": ["=", 1]
}
},
"Sales Order Item": {
"doctype": "Material Request Item",
"field_map": {
"parent": "sales_order_no",
"stock_uom": "uom"
}
}
}, target_doc, postprocess)
return doc
@frappe.whitelist()
def make_delivery_note(source_name, target_doc=None):
def set_missing_values(source, target):
target.ignore_pricing_rule = 1
target.run_method("set_missing_values")
target.run_method("calculate_taxes_and_totals")
def update_item(source, target, source_parent):
target.base_amount = (flt(source.qty) - flt(source.delivered_qty)) * flt(source.base_rate)
target.amount = (flt(source.qty) - flt(source.delivered_qty)) * flt(source.rate)
target.qty = flt(source.qty) - flt(source.delivered_qty)
target_doc = get_mapped_doc("Sales Order", source_name, {
"Sales Order": {
"doctype": "Delivery Note",
"validation": {
"docstatus": ["=", 1]
}
},
"Sales Order Item": {
"doctype": "Delivery Note Item",
"field_map": {
"rate": "rate",
"name": "prevdoc_detail_docname",
"parent": "against_sales_order",
},
"postprocess": update_item,
"condition": lambda doc: doc.delivered_qty < doc.qty
},
"Sales Taxes and Charges": {
"doctype": "Sales Taxes and Charges",
"add_if_empty": True
},
"Sales Team": {
"doctype": "Sales Team",
"add_if_empty": True
}
}, target_doc, set_missing_values)
return target_doc
@frappe.whitelist()
def make_sales_invoice(source_name, target_doc=None):
def postprocess(source, target):
set_missing_values(source, target)
#Get the advance paid Journal Vouchers in Sales Invoice Advance
target.get_advances()
def set_missing_values(source, target):
target.is_pos = 0
target.ignore_pricing_rule = 1
target.run_method("set_missing_values")
target.run_method("calculate_taxes_and_totals")
def update_item(source, target, source_parent):
target.amount = flt(source.amount) - flt(source.billed_amt)
target.base_amount = target.amount * flt(source_parent.conversion_rate)
target.qty = source.rate and target.amount / flt(source.rate) or source.qty
doclist = get_mapped_doc("Sales Order", source_name, {
"Sales Order": {
"doctype": "Sales Invoice",
"validation": {
"docstatus": ["=", 1]
}
},
"Sales Order Item": {
"doctype": "Sales Invoice Item",
"field_map": {
"name": "so_detail",
"parent": "sales_order",
},
"postprocess": update_item,
"condition": lambda doc: doc.base_amount==0 or doc.billed_amt < doc.amount
},
"Sales Taxes and Charges": {
"doctype": "Sales Taxes and Charges",
"add_if_empty": True
},
"Sales Team": {
"doctype": "Sales Team",
"add_if_empty": True
}
}, target_doc, postprocess)
def set_advance_vouchers(source, target):
advance_voucher_list = []
advance_voucher = frappe.db.sql("""
select
t1.name as voucher_no, t1.posting_date, t1.remark, t2.account,
t2.name as voucher_detail_no, {amount_query} as payment_amount, t2.is_advance
from
`tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
""")
return doclist
@frappe.whitelist()
def make_maintenance_schedule(source_name, target_doc=None):
maint_schedule = frappe.db.sql("""select t1.name
from `tabMaintenance Schedule` t1, `tabMaintenance Schedule Item` t2
where t2.parent=t1.name and t2.prevdoc_docname=%s and t1.docstatus=1""", source_name)
if not maint_schedule:
doclist = get_mapped_doc("Sales Order", source_name, {
"Sales Order": {
"doctype": "Maintenance Schedule",
"field_map": {
"name": "sales_order_no"
},
"validation": {
"docstatus": ["=", 1]
}
},
"Sales Order Item": {
"doctype": "Maintenance Schedule Item",
"field_map": {
"parent": "prevdoc_docname"
},
"add_if_empty": True
}
}, target_doc)
return doclist
@frappe.whitelist()
def make_maintenance_visit(source_name, target_doc=None):
visit = frappe.db.sql("""select t1.name
from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2
where t2.parent=t1.name and t2.prevdoc_docname=%s
and t1.docstatus=1 and t1.completion_status='Fully Completed'""", source_name)
if not visit:
doclist = get_mapped_doc("Sales Order", source_name, {
"Sales Order": {
"doctype": "Maintenance Visit",
"field_map": {
"name": "sales_order_no"
},
"validation": {
"docstatus": ["=", 1]
}
},
"Sales Order Item": {
"doctype": "Maintenance Visit Purpose",
"field_map": {
"parent": "prevdoc_docname",
"parenttype": "prevdoc_doctype"
},
"add_if_empty": True
}
}, target_doc)
return doclist
| agpl-3.0 |