repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
mazvv/travelcrm | alembic/versions/9d6e4f7a0f93_alter_db.py | 1001 | """alter db
Revision ID: 9d6e4f7a0f93
Revises: b1eac8a9f577
Create Date: 2016-08-15 20:24:36.483777
"""
# revision identifiers, used by Alembic.
revision = '9d6e4f7a0f93'
down_revision = 'b1eac8a9f577'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('mail',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('resource_id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=32), nullable=False),
sa.Column('html_content', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(['resource_id'], ['resource.id'], name='fk_resource_id_mail', onupdate='cascade', ondelete='restrict'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name', name='unique_idx_name_mail')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('mail')
### end Alembic commands ###
| gpl-3.0 |
manassolanki/erpnext | erpnext/config/erpnext_integrations.py | 678 | from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Payments"),
"icon": "fa fa-star",
"items": [
{
"type": "doctype",
"name": "GoCardless Settings",
"description": _("GoCardless payment gateway settings"),
},
{
"type": "doctype",
"name": "GoCardless Mandate",
"description": _("GoCardless SEPA Mandate"),
}
]
},
{
"label": _("Settings"),
"items": [
{
"type": "doctype",
"name": "Woocommerce Settings"
},
{
"type": "doctype",
"name": "Shopify Settings",
"description": _("Connect Shopify with ERPNext"),
}
]
}
]
| gpl-3.0 |
DSI-Ville-Noumea/sirh-ws | src/main/java/nc/noumea/mairie/web/dto/TitrePosteDto.java | 499 | package nc.noumea.mairie.web.dto;
import nc.noumea.mairie.model.bean.sirh.FichePoste;
public class TitrePosteDto {
private String libTitrePoste;
public TitrePosteDto() {
super();
}
public TitrePosteDto(FichePoste fichePoste) {
this.libTitrePoste = fichePoste.getTitrePoste().getLibTitrePoste();
}
public String getLibTitrePoste() {
return libTitrePoste;
}
public void setLibTitrePoste(String libTitrePoste) {
this.libTitrePoste = libTitrePoste;
}
}
| gpl-3.0 |
imr/Electric8 | com/sun/electric/database/constraint/Layout.java | 15956 | /* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Layout.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.database.constraint;
import com.sun.electric.database.CellBackup;
import com.sun.electric.database.IdMapper;
import com.sun.electric.database.ImmutableArcInst;
import com.sun.electric.database.ImmutableCell;
import com.sun.electric.database.ImmutableExport;
import com.sun.electric.database.ImmutableLibrary;
import com.sun.electric.database.ImmutableNodeInst;
import com.sun.electric.database.Snapshot;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.EDatabase;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.id.CellId;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitivePort;
import com.sun.electric.technology.Technology;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Class to implement the layout-constraint system.
* Handles the fixed-angle and rigid constraints.
* Also propagates these constraints up the hierarchy.
*/
public class Layout extends Constraints {
// private static final Layout layoutConstraint = new Layout();
static final boolean DEBUG = false;
private static boolean doChangesQuietly;
private static Snapshot oldSnapshot;
private static long revisionDate;
private static String userName;
private static Set<Cell> goodSpacingDRCCells, goodAreaDRCCells;
private static Variable goodSpacingDRCDate, goodSpacingDRCBit, goodAreaDRCDate;
/** Shadow Cell info */
private static final ArrayList<LayoutCell> cellInfos = new ArrayList<LayoutCell>();
/** Map which contains temporary rigidity of ArcInsts. */
private static final HashMap<ArcInst, Boolean> tempRigid = new HashMap<ArcInst, Boolean>();
/** key of Variable for last valid DRC date on a Cell. Only spacing rules */
public static final Variable.Key DRC_LAST_GOOD_DATE_SPACING = Variable.newKey("DRC_last_good_drc_date");
/** key of Variable for last valid DRC bit on a Cell. Only spacing rules */
public static final Variable.Key DRC_LAST_GOOD_BIT_SPACING = Variable.newKey("DRC_last_good_drc_bit");
/** Default valud when no bit is found **/
public static final int DRC_LAST_GOOD_BIT_DEFAULT = -1;
/** No need of bit for area since it is only 1 mode */
public static final Variable.Key DRC_LAST_GOOD_DATE_AREA = Variable.newKey("DRC_last_good_drc_area_date");
Layout() {
}
// /**
// * Method to return the current constraint solver.
// * @return the current constraint solver.
// */
// public static Layout getConstraint() { return layoutConstraint; }
/**
* Method to set the subsequent changes to be "quiet".
* Quiet changes are not passed to constraint satisfaction, not recorded for Undo and are not broadcast.
* This method is used to suppress endBatch.
*/
public static void changesQuiet(boolean quiet) {
doChangesQuietly = true;
}
/**
* Method to start a batch of changes.
* @param initialSnapshot snapshot before job changes.
*/
@Override
public void startBatch(Snapshot initialSnapshot) {
// force every cell to remember its current bounds
doChangesQuietly = false;
oldSnapshot = initialSnapshot;
tempRigid.clear();
goodSpacingDRCCells = null;
goodAreaDRCCells = null;
makeLayoutCells();
}
/**
* Method to do hierarchical update on any cells that changed
*/
@Override
public void endBatch(String userName) {
if (DEBUG) {
System.out.println("Temporary rigid:");
for (Map.Entry<ArcInst, Boolean> e : tempRigid.entrySet()) {
System.out.println("\t" + e.getKey() + " --> " + e.getValue());
}
}
Layout.userName = userName;
revisionDate = System.currentTimeMillis();
if (goodSpacingDRCCells != null) {
TextDescriptor td = TextDescriptor.getCellTextDescriptor().withDisplay(false);
goodSpacingDRCDate = Variable.newInstance(DRC_LAST_GOOD_DATE_SPACING, new Long(revisionDate + 1), td); // If cell is changed during this 1 millisecond ???
}
if (goodAreaDRCCells != null) {
TextDescriptor td = TextDescriptor.getCellTextDescriptor().withDisplay(false);
goodAreaDRCDate = Variable.newInstance(DRC_LAST_GOOD_DATE_AREA, new Long(revisionDate + 1), td); // If cell is changed during this 1 millisecond ???
}
if (!doChangesQuietly) {
// Propagate changes and mark changed cells.
for (Iterator<Library> it = Library.getLibraries(); it.hasNext();) {
Library lib = it.next();
for (Iterator<Cell> cIt = lib.getCells(); cIt.hasNext();) {
Cell cell = cIt.next();
assert cell.isLinked();
LayoutCell cellInfo = getCellInfo(cell);
cellInfo.compute();
}
}
}
cellInfos.clear();
tempRigid.clear();
// Set revision dates to modified Cells, update DRC date, update bounds
for (Iterator<Library> it = Library.getLibraries(); it.hasNext();) {
Library lib = it.next();
for (Iterator<Cell> cIt = lib.getCells(); cIt.hasNext();) {
Cell cell = cIt.next();
cell.lowLevelMadeRevision(revisionDate, userName, oldSnapshot.getCellRevision(cell.getId()));
if (goodSpacingDRCCells != null && goodSpacingDRCCells.contains(cell)) {
cell.addVar(goodSpacingDRCDate);
cell.addVar(goodSpacingDRCBit);
}
if (goodAreaDRCCells != null && goodAreaDRCCells.contains(cell)) {
cell.addVar(goodAreaDRCDate);
}
}
}
EDatabase.serverDatabase().backup();
goodSpacingDRCCells = null;
goodAreaDRCCells = null;
oldSnapshot = null;
}
/**
* Method to handle a change to a NodeInst.
* @param ni the NodeInst that was changed.
* @param oD the old contents of the NodeInst.
*/
@Override
public void modifyNodeInst(NodeInst ni, ImmutableNodeInst oD) {
if (doChangesQuietly) {
return;
}
getCellInfo(ni.getParent()).modifyNodeInst(ni, oD);
}
/**
* Method to handle a change to an ArcInst.
* @param ai the ArcInst that changed.
* @param oD the old contents of the ArcInst.
*/
@Override
public void modifyArcInst(ArcInst ai, ImmutableArcInst oD) {
if (doChangesQuietly) {
return;
}
getCellInfo(ai.getParent()).modifyArcInst(ai, oD);
}
/**
* Method to handle a change to an Export.
* @param pp the Export that moved.
* @param oldD the old contents of the Export.
*/
@Override
public void modifyExport(Export pp, ImmutableExport oldD) {
if (doChangesQuietly) {
return;
}
PortInst oldPi = pp.getParent().getPortInst(oldD.originalNodeId, oldD.originalPortId);
if (oldPi == pp.getOriginalPort()) {
return;
}
getCellInfo(pp.getParent()).modifyExport(pp, oldPi);
}
/**
* Method to handle a change to a Cell.
* @param cell the Cell that was changed.
* @param oD the old contents of the Cell.
*/
@Override
public void modifyCell(Cell cell, ImmutableCell oD) {
}
/**
* Method to handle a change to a Library.
* @param lib the Library that was changed.
* @param oldD the old contents of the Library.
*/
@Override
public void modifyLibrary(Library lib, ImmutableLibrary oldD) {
}
/**
* Method to handle the creation of a new ElectricObject.
* @param obj the ElectricObject that was just created.
*/
@Override
public void newObject(ElectricObject obj) {
if (doChangesQuietly) {
return;
}
Cell cell = obj.whichCell();
if (obj == cell) {
newCellInfo(cell, null);
} else if (cell != null) {
getCellInfo(cell).newObject(obj);
}
}
/**
* Method to announce than Ids were renamed.
* @param idMapper mapper from old Ids to new Ids.
*/
@Override
public void renameIds(IdMapper idMapper) {
EDatabase database = EDatabase.serverDatabase();
for (CellId cellId : idMapper.getNewCellIds()) {
newObject(cellId.inDatabase(database));
}
// for (ExportId exportId: idMapper.getNewExportIds())
// newObject(exportId.inDatabase(database));
}
/**
* Method to set temporary rigidity on an ArcInst.
* @param ai the ArcInst to make temporarily rigid/not-rigid.
* @param tempRigid true to make the ArcInst temporarily rigid;
* false to make it temporarily not-rigid.
*/
public static void setTempRigid(ArcInst ai, boolean tempRigid) {
if (DEBUG) {
System.out.println("setTempRigid " + ai + " " + tempRigid);
}
ai.checkChanging();
Layout.tempRigid.put(ai, Boolean.valueOf(tempRigid));
// if (tempRigid)
// {
// if (ai.getChangeClock() == changeClock + 2) return;
// ai.setChangeClock(changeClock + 2);
// } else
// {
// if (ai.getChangeClock() == changeClock + 3) return;
// ai.setChangeClock(changeClock + 3);
// }
}
/**
* Method to remove temporary rigidity on an ArcInst.
* @param ai the ArcInst to remove temporarily rigidity.
*/
public static void removeTempRigid(ArcInst ai) {
ai.checkChanging();
tempRigid.remove(ai);
// if (ai.getChangeClock() != changeClock + 3 && ai.getChangeClock() != changeClock + 2) return;
// ai.setChangeClock(changeClock - 3);
}
/*
* Method to request to set
*/
public static void setGoodDRCCells(Set<Cell> goodDRCCells, Variable.Key key, int activeBits, boolean inMemory) {
assert (!inMemory); // call only if you are storing in disk
if (key == DRC_LAST_GOOD_DATE_SPACING) {
Layout.goodSpacingDRCCells = goodDRCCells;
TextDescriptor td = TextDescriptor.getCellTextDescriptor().withDisplay(false);
goodSpacingDRCBit = Variable.newInstance(DRC_LAST_GOOD_BIT_SPACING, new Integer(activeBits), td);
} else // min area
{
Layout.goodAreaDRCCells = goodDRCCells;
}
}
/**
** Returns rigidity of an ArcInst considering temporary rigidity.
* @param ai ArcInst to test rigidity.
* @return true if the ArcInst is considered rigid in this batch.
*/
static boolean isRigid(ArcInst ai) {
Boolean override = tempRigid.get(ai);
return override != null ? override.booleanValue() : ai.isRigid();
}
private static void makeLayoutCells() {
cellInfos.clear();
for (Iterator<Library> it = Library.getLibraries(); it.hasNext();) {
Library lib = it.next();
for (Iterator<Cell> cIt = lib.getCells(); cIt.hasNext();) {
Cell cell = cIt.next();
newCellInfo(cell, oldSnapshot.getCell(cell.getId()));
}
}
}
/******************** NODE MODIFICATION CODE *************************/
/**
* Method to compute the position of portinst "pi" and
* place the center of the area in the parameters "x" and "y". The position
* is the "old" position, as determined by any changes that may have occured
* to the nodeinst (and any sub-nodes).
*/
static Poly oldPortPosition(PortInst pi) {
NodeInst ni = pi.getNodeInst();
PortProto pp = pi.getPortProto();
// descend to the primitive node
AffineTransform subrot = makeOldRot(ni);
if (subrot == null) {
return null;
}
NodeInst bottomNi = ni;
PortProto bottomPP = pp;
while (bottomNi.isCellInstance()) {
AffineTransform localtran = makeOldTrans(bottomNi);
subrot.concatenate(localtran);
PortInst bottomPi = getOldOriginalPort((Export) bottomPP);
bottomNi = bottomPi.getNodeInst();
bottomPP = bottomPi.getPortProto();
localtran = makeOldRot(bottomNi);
subrot.concatenate(localtran);
}
// if the node hasn't changed, use its current values
ImmutableNodeInst d = Layout.getOldD(bottomNi);
assert d != null;
if (d != bottomNi.getD()) {
// create a fake node with these values
bottomNi = NodeInst.makeDummyInstance(bottomNi.getProto());
bottomNi.lowLevelModify(d);
}
PrimitiveNode np = (PrimitiveNode) bottomNi.getProto();
Technology tech = np.getTechnology();
Poly poly = tech.getShapeOfPort(bottomNi, (PrimitivePort) bottomPP);
poly.transform(subrot);
return (poly);
}
private static AffineTransform makeOldRot(NodeInst ni) {
// if the node has not been modified, just use the current transformation
ImmutableNodeInst d = getOldD(ni);
if (d == null) {
return null;
}
// get the old values
double cX = d.anchor.getX();
double cY = d.anchor.getY();
return d.orient.rotateAbout(cX, cY);
}
private static AffineTransform makeOldTrans(NodeInst ni) {
ImmutableNodeInst d = getOldD(ni);
if (d == null) {
return null;
}
// create the former translation matrix
AffineTransform transform = new AffineTransform();
double cX = d.anchor.getX();
double cY = d.anchor.getY();
transform.translate(cX, cY);
return transform;
}
static PortInst getOldOriginalPort(Export e) {
return getCellInfo(e.getParent()).getOldOriginalPort(e);
}
static ImmutableNodeInst getOldD(NodeInst ni) {
return getCellInfo(ni.getParent()).getOldD(ni);
}
private static void newCellInfo(Cell cell, CellBackup oldBackup) {
int cellIndex = cell.getCellIndex();
while (cellInfos.size() <= cellIndex) {
cellInfos.add(null);
}
// assert cellInfos.get(cellIndex) == null;
cellInfos.set(cellIndex, new LayoutCell(cell, oldBackup));
}
static LayoutCell getCellInfo(Cell cell) {
return cellInfos.get(cell.getCellIndex());
}
}
| gpl-3.0 |
sadiqdon/cycommerce | backend/controllers/StoreController.php | 1585 | <?php
class StoreController extends CrudController
{
public $modelName = 'Store';
public function actionView($id) {
parent::view($id, $this->modelName);
}
public function actionCreate() {
$model = new Store;
parent::create($model, $this->modelName, 'store-form');
}
public function actionUpdate($id) {
$model = $this->loadModel($id, $this->modelName);
parent::update($id, $this->modelName, 'store-form');
}
public function actionDelete($id) {
parent::delete($id, $this->modelName);
}
public function actionBatchDelete() {
parent::batchDelete($this->modelName);
}
public function actionExportSelected() {
$criteriaWith = array();
$exportfield = array(
'id',
'name',
'url',
'ssl',
);
parent::exportSelected($this->modelName, 't.id', $criteriaWith, $exportfield);
}
public function actionExportAll() {
$criteriaWith = array();
$exportfield = array(
'id',
'name',
'url',
'ssl',
);
parent::exportAll($this->modelName, $criteriaWith, $exportfield);
}
public function actionIndex() {
$dorder = '';
$modelName = $this->modelName;
if($modelName::model()->hasAttribute('sort_order'))
$dorder = 't.sort_order ASC';
else if($modelName::model()->hasAttribute('id'))
$dorder = 't.id DESC';
$criteriaWith = $attr = array();
$attr[] = '*';
$sort = array( 'defaultOrder' => $dorder, 'attributes' => $attr);
parent::index($this->modelName, $sort, $criteriaWith);
}
public function actionAdmin() {
$model = new Store('search');
parent::admin($model, $this->modelName);
}
}
| gpl-3.0 |
kenji1322/kramerius | search/src/java/cz/incad/Kramerius/views/virtualcollection/VirtualCollectionServlet.java | 16764 | package cz.incad.Kramerius.views.virtualcollection;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import biz.sourcecode.base64Coder.Base64Coder;
import cz.incad.Kramerius.backend.guice.GuiceServlet;
import cz.incad.kramerius.FedoraAccess;
import cz.incad.kramerius.processes.impl.ProcessStarter;
import cz.incad.kramerius.processes.utils.ProcessUtils;
import cz.incad.kramerius.security.SecurityException;
import cz.incad.kramerius.utils.ApplicationURL;
import cz.incad.kramerius.utils.IOUtils;
import cz.incad.kramerius.utils.conf.KConfiguration;
import cz.incad.kramerius.virtualcollections.CollectionUtils;
import cz.incad.kramerius.virtualcollections.CollectionsManager;
import cz.incad.kramerius.virtualcollections.VirtualCollectionsManager;
import cz.incad.kramerius.virtualcollections.impl.AbstractCollectionManager;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.fedora.api.ObjectProfile;
public class VirtualCollectionServlet extends GuiceServlet {
public static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(VirtualCollectionServlet.class.getName());
@Inject
@Named("securedFedoraAccess")
FedoraAccess fedoraAccess;
@Inject
KConfiguration kConfiguration;
public static final String ACTION_NAME = "action";
@Inject
@Named("fedora")
CollectionsManager collectionManager;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
Actions actionToDo = Actions.CHANGE;
String actionNameParam = req.getParameter(ACTION_NAME);
if (actionNameParam != null) {
actionToDo = Actions.valueOf(actionNameParam);
}
try {
actionToDo.doPerform(this, fedoraAccess, this.collectionManager, req, resp);
} catch (IOException e1) {
LOGGER.log(Level.SEVERE, e1.getMessage(), e1);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e1.toString());
PrintWriter out = resp.getWriter();
out.print(e1.toString());
} catch (SecurityException e1) {
LOGGER.log(Level.INFO, e1.getMessage());
resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
} catch (Exception e1) {
LOGGER.log(Level.SEVERE, e1.getMessage(), e1);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
PrintWriter out = resp.getWriter();
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e1.toString());
out.print(e1.toString());
}
} catch (SecurityException e) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
PostActions actionToDo = PostActions.IMAGES_UPLOAD;
String actionNameParam = req.getParameter(ACTION_NAME);
if (actionNameParam != null) {
actionToDo = PostActions.valueOf(actionNameParam);
}
try {
actionToDo.doPerform(this, fedoraAccess, this.collectionManager, req, resp);
} catch (IOException e1) {
LOGGER.log(Level.SEVERE, e1.getMessage(), e1);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e1.toString());
PrintWriter out = resp.getWriter();
out.print(e1.toString());
} catch (SecurityException e1) {
LOGGER.log(Level.INFO, e1.getMessage());
resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
} catch (Exception e1) {
LOGGER.log(Level.SEVERE, e1.getMessage(), e1);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
PrintWriter out = resp.getWriter();
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e1.toString());
out.print(e1.toString());
}
} catch (SecurityException e) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
protected void writeOutput(HttpServletRequest req, HttpServletResponse resp, String s) throws IOException {
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
out.print(s);
}
protected String[] getLangs() {
String[] langs = kConfiguration.getPropertyList("interface.languages");
return langs;
}
enum PostActions {
/** long text uploading */
LONG_TEXT_UPLOAD {
@Override
void doPerform(VirtualCollectionServlet vc,
FedoraAccess fedoraAccess,
CollectionsManager colMan,
HttpServletRequest req,
HttpServletResponse response) throws Exception, SecurityException {
String collection = req.getParameter("pid");
String language = req.getParameter("lang");
String encodedProfile = req.getParameter("encodedData");
byte[] decoded = Base64Coder.decode(encodedProfile);
CollectionUtils.modifyLangDatastream(collection, language, AbstractCollectionManager.LONG_TEXT_DS_PREFIX+language,new String(decoded, "UTF-8"), fedoraAccess);
}
},
/** image uploads */
IMAGES_UPLOAD {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan,
HttpServletRequest req, HttpServletResponse response) throws Exception, SecurityException {
String collection = req.getParameter("pid");
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream fileItemStream = iterator.next();
String filename = fileItemStream.getName();
if (!fileItemStream.isFormField()) {
InputStream inputStream = fileItemStream.openStream();
String streamName = fileItemStream.getFieldName();
String contentType = fileItemStream.getContentType();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
IOUtils.copyStreams(inputStream, bos);;
LOGGER.info("Creating stream '"+streamName+"' for collection '"+collection+"'");
CollectionUtils.modifyImageDatastream(collection, streamName, contentType, bos.toByteArray(), fedoraAccess);
} else {
throw new IllegalArgumentException("illegal argument! ");
}
}
}
};
abstract void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse response) throws Exception, SecurityException;
}
enum Actions {
/**
* Request to check if pid is in virtual collection
*/
CHECK {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse resp) throws IOException, SecurityException {
String pid = req.getParameter("pid");
String collection = req.getParameter("collection");
resp.setContentType("text/plain");
if (CollectionUtils.isInCollection(pid, collection, fedoraAccess)) {
vc.writeOutput(req, resp, "1");
} else {
vc.writeOutput(req, resp, "0");
}
}
},
/**
* Request to add pid to virtual collection
*/
ADDTOCOLLECTIONS {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse resp) throws IOException, SecurityException {
String pid = req.getParameter("pid");
String base = ProcessUtils.getLrServlet();
if (base == null || pid == null) {
LOGGER.severe("Cannot start long running process");
return;
}
String baseurl = base + "?action=start&def=virtualcollections&out=text";
String[] rcollections = req.getParameterValues("remove");
if (rcollections != null) {
for (String collection : rcollections) {
String token = System.getProperty(ProcessStarter.TOKEN_KEY);
String url = baseurl + "¶ms=remove," + pid + "," + URLEncoder.encode(collection, "UTF-8");
if(token!=null){
url += "&token=" + token;
}
//ProcessUtils.startProcess("virtualcollections", url)
ProcessStarter.httpGet(url);
}
}
String[] collections = req.getParameterValues("add");
if (collections != null) {
for (String collection : collections) {
String token = System.getProperty(ProcessStarter.TOKEN_KEY);
String url = baseurl + "¶ms=add," + pid + "," + collection;
if(token!=null){
url += "&token=" + token;
}
ProcessStarter.httpGet(url);
}
}
String url = base + "?action=start&def=reindex&out=text¶ms=fromKrameriusModel," + pid + "," + pid + "&token=" + System.getProperty(ProcessStarter.TOKEN_KEY);
LOGGER.info("indexer URL:" + url);
try {
ProcessStarter.httpGet(url);
} catch (Exception e) {
LOGGER.severe("Error spawning indexer for " + pid + ":" + e);
}
}
},
/**
* Request to add pid to virtual collection
*/
ADDTOCOLLECTION {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse resp) throws IOException, SecurityException {
String pid = req.getParameter("pid");
String collection = req.getParameter("collection");
CollectionUtils.addToCollection(pid, collection, fedoraAccess);
}
},
/**
* Request to remove pid from virtual collection
*/
REMOVEFROMCOLLECTION {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse resp) throws IOException, SecurityException {
String pid = req.getParameter("pid");
String collection = req.getParameter("collection");
CollectionUtils.removeFromCollection(pid, collection, fedoraAccess);
}
},
/**
* Request to write to response the content of parameter content.
* Used when creating datastream
*/
TEXT {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse resp) throws IOException, SecurityException {
String content = req.getParameter("content");
vc.writeOutput(req, resp, content);
}
},
/**
* Request to create a virtual collection
*/
LABEL {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse resp) throws IOException, SecurityException {
String pid = req.getParameter("pid");
ObjectProfile op = fedoraAccess.getAPIA().getObjectProfile(pid, null);
vc.writeOutput(req, resp, op.getObjLabel());
}
},
/**
* Request to create a virtual collection
*/
CREATE {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse resp) throws IOException, SecurityException, InterruptedException {
boolean canLeave = Boolean.parseBoolean(req.getParameter("canLeave"));
Map<String, String> plainTexts = new HashMap<String, String>();
Enumeration paramNames = req.getParameterNames();
while(paramNames.hasMoreElements()) {
String p = paramNames.nextElement().toString();
if (p.startsWith("text_")) {
String langCode = p.substring("text_".length());
plainTexts.put(langCode, req.getParameter(p));
}
}
String pid = CollectionUtils.create(fedoraAccess, null, canLeave, plainTexts, new CollectionUtils.CollectionManagerWait(colMan));
resp.setContentType("text/plain");
vc.writeOutput(req, resp, pid);
}
},
/**
* Request to delete a virtual collection
*/
DELETE {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse resp) throws Exception, SecurityException {
String pid = req.getParameter("pid");
CollectionUtils.delete(pid, fedoraAccess);
}
},
/**
* Request to change a virtual collection
*/
CHANGE {
@Override
void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse resp) throws IOException, SecurityException {
String[] langs = vc.getLangs();
String pid = req.getParameter("pid");
boolean canLeave = Boolean.parseBoolean(req.getParameter("canLeave"));
CollectionUtils.modify(pid, pid, canLeave, fedoraAccess);
String string = req.getRequestURL().toString();
URL url = new URL(string);
//String k4url = url.getProtocol() + "://" + url.getHost() + ApplicationURL.extractPort(url) + req.getRequestURI();
for (int i = 0; i < langs.length; i++) {
String lang = langs[++i];
String text = req.getParameter("text_" + lang);
if (text != null) {
CollectionUtils.modifyLangDatastream(pid, lang, text, fedoraAccess);
}
}
PrintWriter out = resp.getWriter();
out.print("1");
}
};
abstract void doPerform(VirtualCollectionServlet vc, FedoraAccess fedoraAccess, CollectionsManager colMan, HttpServletRequest req, HttpServletResponse response) throws Exception, SecurityException;
}
}
| gpl-3.0 |
u2g/MoonLake | src/main/java/com/minecraft/moonlake/nbt/NBTTagByte.java | 2265 | /*
* Copyright (C) 2017 The MoonLake Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.minecraft.moonlake.nbt;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* <h1>NBTTagByte</h1>
* NBT 标签字节类型数据
*
* @version 1.0
* @author Month_Light
* @see NBTTagNumber
* @see Byte
*/
public class NBTTagByte extends NBTTagNumber<Byte> {
/**
* NBT 标签字节类型数据构造函数
*/
public NBTTagByte() {
this((byte) 0);
}
/**
* NBT 标签字节类型数据构造函数
*
* @param value 值
*/
public NBTTagByte(byte value) {
this("", value);
}
/**
* NBT 标签字节类型数据构造函数
*
* @param name 特殊名
*/
public NBTTagByte(String name) {
this(name, (byte) 0);
}
/**
* NBT 标签字节类型数据构造函数
*
* @param name 特殊名
* @param value 值
*/
public NBTTagByte(String name, Byte value) {
super(name, value);
}
/**
* 设置此 NBT 标签字节数据的值
*
* @param value 新值
*/
public void set(byte value) {
super.value = value;
}
@Override
public NBTType getType() {
return NBTType.BYTE;
}
@Override
public void read(DataInput input) throws IOException {
super.value = input.readByte();
}
@Override
public void write(DataOutput output) throws IOException {
output.writeByte(value);
}
@Override
public NBTTagByte clone() {
return new NBTTagByte(getName(), value);
}
}
| gpl-3.0 |
CIFASIS/VDiscover | vdiscover/Vulnerabilities.py | 2137 | """
This file is part of VDISCOVER.
VDISCOVER 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.
VDISCOVER 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 VDISCOVER. If not, see <http://www.gnu.org/licenses/>.
Copyright 2014 by G.Grieco
"""
from Event import Call, Crash, Abort, Exit, Signal, Vulnerability
from Analysis import FindModule
def detect_vulnerabilities(preevents, events, process, mm):
r = []
for (i, event) in enumerate(events):
r.append(detect_vulnerability(preevents, event, process, mm))
return filter(lambda e: e is not None, r)
def detect_vulnerability(preevents, event, process, mm):
if isinstance(event, Call):
(name, args) = event.GetTypedName()
if name == "system" or name == "popen":
pass
elif isinstance(event, Abort):
if len(event.bt) > 0 and len(preevents) > 0:
if not (str(preevents[-1]) in ["free", "malloc", "realloc"]):
return None
for (typ, val) in event.bt:
module = FindModule(val, mm)
if module == "[vdso]":
pass
elif "libc-" in module:
assert(0)
return Vulnerability("MemoryCorruption")
else:
return None
elif isinstance(event, Crash):
if str(
event.fp_type[0]) == "DPtr32" and str(
event.eip_type[0]) == "DPtr32":
return Vulnerability("StackCorruption")
for (typ, val) in event.bt:
if str(typ) == "DPtr32":
return Vulnerability("StackCorruption")
elif isinstance(event, Signal):
pass
return None
| gpl-3.0 |
ifes-ci/Trabalhos2016-POO1 | SystemSCPDC-Marlon/SCPDC/src/Views/IFrmExcluirCliente.java | 8325 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Views;
import Crud.CrudCliente;
import Domain.Cliente;
import javax.swing.JOptionPane;
/**
*
* @author thiag
*/
public class IFrmExcluirCliente extends javax.swing.JInternalFrame {
Cliente cliente;
/**
* Creates new form IFrmVisualizarCliente
*/
public IFrmExcluirCliente(Cliente c) {
initComponents();
this.cliente = c;
lbIdCliente.setText(Integer.toString(c.getId()));
lbNomeCliente.setText(c.getNome());
lbCnpjCliente.setText(c.getCnpj());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lbExcluirCliente = new javax.swing.JLabel();
btConfirmarExcluirCliente = new javax.swing.JButton();
btCancelarExcluirCliente = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
lbNome = new javax.swing.JLabel();
lbNomeCliente = new javax.swing.JLabel();
lbID = new javax.swing.JLabel();
lbIdCliente = new javax.swing.JLabel();
lbCNPJ = new javax.swing.JLabel();
lbCnpjCliente = new javax.swing.JLabel();
setTitle("Excluir Cliente");
lbExcluirCliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lbExcluirCliente.setText("Deseja realmente excluir Cliente?");
btConfirmarExcluirCliente.setText("Confirmar");
btConfirmarExcluirCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btConfirmarExcluirClienteActionPerformed(evt);
}
});
btCancelarExcluirCliente.setText("Cancelar");
btCancelarExcluirCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btCancelarExcluirClienteActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setText("Cliente");
lbNome.setText("Nome:");
lbNomeCliente.setText("jLabel2");
lbID.setText("ID:");
lbIdCliente.setText("jLabel3");
lbCNPJ.setText("CNPJ:");
lbCnpjCliente.setText("jLabel3");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(96, 96, 96)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbExcluirCliente)
.addGroup(layout.createSequentialGroup()
.addComponent(lbID)
.addGap(18, 18, 18)
.addComponent(lbIdCliente))))
.addGroup(layout.createSequentialGroup()
.addGap(80, 80, 80)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lbNome)
.addComponent(lbCNPJ))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbCnpjCliente)
.addComponent(lbNomeCliente))))))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(220, Short.MAX_VALUE)
.addComponent(btCancelarExcluirCliente)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btConfirmarExcluirCliente)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbID)
.addComponent(lbIdCliente))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbNome)
.addComponent(lbNomeCliente))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbCnpjCliente)
.addComponent(lbCNPJ))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE)
.addComponent(lbExcluirCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btConfirmarExcluirCliente)
.addComponent(btCancelarExcluirCliente))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btConfirmarExcluirClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConfirmarExcluirClienteActionPerformed
CrudCliente crudCliente = new CrudCliente();
crudCliente.excluirCliente(cliente);
JOptionPane.showMessageDialog(null, "Cliente Excluido!");
this.dispose();
}//GEN-LAST:event_btConfirmarExcluirClienteActionPerformed
private void btCancelarExcluirClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarExcluirClienteActionPerformed
JOptionPane.showMessageDialog(null, "Cancelado!");
this.dispose();
}//GEN-LAST:event_btCancelarExcluirClienteActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btCancelarExcluirCliente;
private javax.swing.JButton btConfirmarExcluirCliente;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel lbCNPJ;
private javax.swing.JLabel lbCnpjCliente;
private javax.swing.JLabel lbExcluirCliente;
private javax.swing.JLabel lbID;
private javax.swing.JLabel lbIdCliente;
private javax.swing.JLabel lbNome;
private javax.swing.JLabel lbNomeCliente;
// End of variables declaration//GEN-END:variables
}
| gpl-3.0 |
Commercial-Group/CG-Theme | wp-content/plugins/divi-booster/core/fixes/065-set-background-color/wp_head_style.php | 247 | <?php
if (!defined('ABSPATH')) { exit(); } // No direct access
list($name, $option) = $this->get_setting_bases(__FILE__); ?>
#main-content, .et_pb_section {
background-color: <?php echo htmlentities(@$option['bgcol']); ?> !important;
} | gpl-3.0 |
doughague/minuit-cpp | include/minuit-cpp/SimplexMinimizer.hh | 1533 | // @(#)root/minuit2:$Id: SimplexMinimizer.h 21530 2007-12-20 11:14:35Z moneta $
// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005
/**********************************************************************
* *
* Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT *
* *
**********************************************************************/
#ifndef MINUITCPP_SimplexMinimizer
#define MINUITCPP_SimplexMinimizer
#include "minuit-cpp/MnConfig.hh"
#include "minuit-cpp/ModularFunctionMinimizer.hh"
#include "minuit-cpp/SimplexBuilder.hh"
#include "minuit-cpp/SimplexSeedGenerator.hh"
#include <vector>
namespace MinuitCpp {
//_____________________________________________________________
/**
Class implementing the required methods for a minimization using Simplex.
API is provided in the upper MinuitCpp::ModularFunctionMinimizer class
*/
class SimplexMinimizer : public ModularFunctionMinimizer {
public:
SimplexMinimizer() : fSeedGenerator(SimplexSeedGenerator()),
fBuilder(SimplexBuilder()) {}
~SimplexMinimizer() {}
const MinimumSeedGenerator& SeedGenerator() const {return fSeedGenerator;}
const MinimumBuilder& Builder() const {return fBuilder;}
private:
SimplexSeedGenerator fSeedGenerator;
SimplexBuilder fBuilder;
};
} // namespace MinuitCpp
#endif // MINUITCPP_SimplexMinimizer
| gpl-3.0 |
LearningLocker/learninglocker | lib/services/auth/tests/utils/testGlobalModel.js | 3038 | import { SITE_ADMIN, ALL } from 'lib/constants/scopes';
import setup from 'lib/services/auth/tests/utils/setup';
import testOrgScopeFilter
from 'lib/services/auth/tests/utils/testOrgScopeFilter';
import testOrgScopeFilterError
from 'lib/services/auth/tests/utils/testOrgScopeFilterError';
import testClientBasicScopeFilter
from 'lib/services/auth/tests/utils/testClientBasicScopeFilter';
import testClientBasicScopeFilterError
from 'lib/services/auth/tests/utils/testClientBasicScopeFilterError';
import testOrgScopeFilterOwnerError
from 'lib/services/auth/tests/utils/testOrgScopeFilterOwnerError';
import testOwnerScopeFilterError
from 'lib/services/auth/tests/utils/testOwnerScopeFilterError';
import testSiteAdminScopeFilter
from 'lib/services/auth/tests/utils/testSiteAdminScopeFilter';
import testAllActions from 'lib/services/auth/tests/utils/testAllActions';
import { TEST_ORG_FILTER } from 'lib/services/auth/tests/utils/constants';
export default ({ modelName, editAllScopes }) => {
describe(`model scope filters ${modelName}`, () => {
setup();
testAllActions(modelName, [SITE_ADMIN], TEST_ORG_FILTER);
testAllActions(modelName, [ALL], TEST_ORG_FILTER);
testAllActions(modelName, editAllScopes, TEST_ORG_FILTER);
// org token tests
testOrgScopeFilter(modelName, 'view', [], TEST_ORG_FILTER);
testOrgScopeFilterError(modelName, 'edit', []);
testOrgScopeFilterError(modelName, 'create', []);
testOrgScopeFilterError(modelName, 'delete', []);
testOrgScopeFilterOwnerError(modelName, 'edit');
testOrgScopeFilterOwnerError(modelName, 'create');
testOrgScopeFilterOwnerError(modelName, 'delete');
testOwnerScopeFilterError(modelName, 'view');
testOwnerScopeFilterError(modelName, 'edit');
testOwnerScopeFilterError(modelName, 'create');
testOwnerScopeFilterError(modelName, 'delete');
// basic client tests
testClientBasicScopeFilter(modelName, 'view', [ALL], TEST_ORG_FILTER);
testClientBasicScopeFilter(modelName, 'view', editAllScopes, TEST_ORG_FILTER);
testClientBasicScopeFilterError(modelName, 'view', []);
testClientBasicScopeFilter(modelName, 'edit', [ALL], TEST_ORG_FILTER);
testClientBasicScopeFilter(modelName, 'edit', editAllScopes, TEST_ORG_FILTER);
testClientBasicScopeFilterError(modelName, 'edit', []);
testClientBasicScopeFilter(modelName, 'create', [ALL], TEST_ORG_FILTER);
testClientBasicScopeFilter(modelName, 'create', editAllScopes, TEST_ORG_FILTER);
testClientBasicScopeFilterError(modelName, 'create', []);
testClientBasicScopeFilter(modelName, 'delete', [ALL], TEST_ORG_FILTER);
testClientBasicScopeFilter(modelName, 'delete', editAllScopes, TEST_ORG_FILTER);
testClientBasicScopeFilterError(modelName, 'delete', []);
// site admin tests
testSiteAdminScopeFilter(modelName, 'view', {});
testSiteAdminScopeFilter(modelName, 'edit', {});
testSiteAdminScopeFilter(modelName, 'create', {});
testSiteAdminScopeFilter(modelName, 'delete', {});
});
};
| gpl-3.0 |
akshaycool/django-rest-serialization-demo | snippets/urls.py | 2005 | # from django.conf.urls import url,include
# from . import views
# from rest_framework.urlpatterns import format_suffix_patterns
# from snippets.views import SnippetViewSet,UserViewSet ,api_root
# from rest_framework import renderers
# from rest_framework.routers import DefaultRouter
# # snippet_list=SnippetViewSet.as_view({
# # 'get':'list',
# # 'post':'create'
# # })
# # snippet_detail=SnippetViewSet.as_view({
# # 'get':'retrieve',
# # 'put':'update',
# # 'patch':'partial_update',
# # 'delete':'destroy'
# # })
# # snippet_highlight=SnippetViewSet.as_view({
# # 'get':'retrieve'
# # },renderers_classes=[renderers.StaticHTMLRenderer])
# # user_list=UserViewSet.as_view({
# # 'get':'list'
# # })
# # user_detail=UserViewSet.as_view({
# # 'get':'retrieve'
# # })
# """ DefaultRouter creates the api root automatically
# And also explicitly setting the api is not needed
# """
# router=DefaultRouter()
# router.register(r'snippets',views.SnippetViewSet)
# router.register(r'users',views.UserViewSet)
# #API endpoints
# # urlpatterns=format_suffix_patterns([
# # #url(r'^$',api_root),
# # url(r'^$',include(router.urls)),
# # url(r'^api-auth/',include('rest_framework.urls',namespace='rest_framework')),
# # # url(r'^snippets/$', snippet_list,name='snippets-list'),
# # # url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail,name='snippet-detail'),
# # # url(r'^snippets/(?P<pk>[0-9]+)/highlight/$',snippet_highlight,name='snippet-highlight'),
# # # url(r'^users/$',user_list,name='user-list'),
# # # url(r'^users/(?P<pk>[0-9]+)/$', user_detail,name='user-detail'),
# # ])
# urlpatterns=[
# url(r'^$',include(router.urls)),
# url(r'^api-auth/',include('rest_framework.urls',namespace='rest_framework')),
# ]
# #urlpatterns=format_suffix_patterns(urlpatterns)
# #Login and Logout views for browsable API
# # urlpatterns+=[
# # url(r'^api-auth/',include('rest_framework.urls',namespace='rest_franework')),
# # ] | gpl-3.0 |
PeterParushev/BoxingParadise | BoxingParadise/App_Start/BundleConfig.cs | 2117 | using System.Web.Optimization;
namespace BoxingParadise
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
}
} | gpl-3.0 |
reBirthLab/gradebook | services/oauth-service/src/main/java/com/rebirthlab/gradebook/auth/controller/UserController.java | 2919 | package com.rebirthlab.gradebook.auth.controller;
import com.rebirthlab.gradebook.auth.model.User;
import com.rebirthlab.gradebook.auth.service.UserDTO;
import com.rebirthlab.gradebook.auth.service.UserService;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.DELETE;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by Anastasiy
*/
@Path("/user")
@Scope("request")
@Produces(MediaType.APPLICATION_JSON)
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@POST
@Path("/register")
@Transactional
public Response createUser(UserDTO user) {
Set<String> userRole = new HashSet<>();
userRole.add("ROLE_USER");
user.setRoles(userRole);
Optional<User> registeredUser = userService.registerUser(user);
if (registeredUser.isPresent()) {
return Response.ok(registeredUser.get()).build();
}
throw new BadRequestException("A user with email " + user.getEmail() + " already exists");
}
@GET
public Response getUser(@Context SecurityContext securityContext) {
Authentication authentication = (Authentication) securityContext.getUserPrincipal();
UserDetails currentUser = (UserDetails) authentication.getPrincipal();
return Response.ok(currentUser).build();
}
@PUT
public Response updateUser(UserDTO userDTO) {
// TODO: Implement user update logic
throw new UnsupportedOperationException("Not implemented yet");
}
@DELETE
public Response deleteUser(@Context HttpServletRequest request,
@QueryParam("email") String email) {
if (!request.isUserInRole("ROLE_ADMIN")) {
throw new ForbiddenException("Insufficient access rights to perform the requested operation");
}
Optional<User> deletedUser = userService.deleteUserByEmail(email);
if (deletedUser.isPresent()) {
return Response.noContent().build();
}
throw new BadRequestException("The user with email " + email + " doesn't exist");
}
}
| gpl-3.0 |
fargalaxy1/geonode-wagtail | geonode/contrib/wagtail_/templatetags/wagtail_tags.py | 508 | from django.conf import settings
from django import template
from geonode.contrib.wagtail_.models import BlogPage
register = template.Library()
# Blog feed for home page
@register.inclusion_tag(
'wagtail_/tags/blog_posts_homepage.html',
takes_context=True
)
def blog_posts_homepage(context, count=2):
blogs = BlogPage.objects.all()
return {
'blogs': blogs,
# required by the pageurl tag that we want to use within this template
'request': context['request'],
}
| gpl-3.0 |
DoubleLabyrinth/FunctionTools | Hash/MDA/MD4.cpp | 4752 | #include "MD4.h"
Hash::MDA::HashResult Hash::MDA::MD4::GetChecksum(const BYTE* srcBytes, UINT64 srcByteLength) {
Hash::MDA::HashResult Ret;
Ret.A = 0x67452301;
Ret.B = 0xEFCDAB89;
Ret.C = 0x98BADCFE;
Ret.D = 0x10325476;
UINT32 AA, BB, CC, DD;
bool Final = false;
BYTE Extra[128] = {0};
UINT64 BitsOfsrcByte = srcByteLength << 3;
UINT64 TimesOfMainCycle = srcByteLength >> 6;
BYTE LeftoversrcByteLength = (BYTE)(srcByteLength & 0x3F);
const UINT32(*Ptr)[16] = (const UINT32(*)[16])srcBytes;
fin:if(Final) {
TimesOfMainCycle = LeftoversrcByteLength >= 56 ? 2 : 1;
Ptr = (const UINT32(*)[16])Extra;
}
for(UINT64 i = 0; i < TimesOfMainCycle; i++) {
AA = Ret.A;
BB = Ret.B;
CC = Ret.C;
DD = Ret.D;
#define UINT32_ROL(X, Y) X << Y | X >> (32 - Y)
#define MD4_F(X, Y, Z) ((X & Y) | (~X & Z))
#define MD4_G(X, Y, Z) ((X & Y) | (X & Z) | (Y & Z))
#define MD4_H(X, Y, Z) (X ^ Y ^ Z)
#define MD4_FF(A, B, C, D, K, s)\
A += MD4_F(B, C, D) + K;\
A = UINT32_ROL(A, s);
#define MD4_GG(A, B, C, D, K, s)\
A += MD4_G(B, C, D) + K + 0x5A827999;\
A = UINT32_ROL(A, s);
#define MD4_HH(A, B, C, D, K, s)\
A += MD4_H(B, C, D) + K + 0x6ED9EBA1;\
A = UINT32_ROL(A, s);
MD4_FF(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][0], 3) //MD4_FF is a MACRO, no need to add ';'
MD4_FF(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][1], 7)
MD4_FF(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][2], 11)
MD4_FF(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][3], 19)
MD4_FF(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][4], 3)
MD4_FF(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][5], 7)
MD4_FF(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][6], 11)
MD4_FF(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][7], 19)
MD4_FF(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][8], 3)
MD4_FF(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][9], 7)
MD4_FF(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][10], 11)
MD4_FF(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][11], 19)
MD4_FF(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][12], 3)
MD4_FF(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][13], 7)
MD4_FF(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][14], 11)
MD4_FF(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][15], 19)
MD4_GG(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][0], 3)
MD4_GG(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][4], 5)
MD4_GG(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][8], 9)
MD4_GG(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][12], 13)
MD4_GG(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][1], 3)
MD4_GG(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][5], 5)
MD4_GG(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][9], 9)
MD4_GG(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][13], 13)
MD4_GG(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][2], 3)
MD4_GG(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][6], 5)
MD4_GG(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][10], 9)
MD4_GG(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][14], 13)
MD4_GG(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][3], 3)
MD4_GG(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][7], 5)
MD4_GG(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][11], 9)
MD4_GG(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][15], 13)
MD4_HH(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][0], 3)
MD4_HH(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][8], 9)
MD4_HH(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][4], 11)
MD4_HH(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][12], 15)
MD4_HH(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][2], 3)
MD4_HH(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][10], 9)
MD4_HH(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][6], 11)
MD4_HH(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][14], 15)
MD4_HH(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][1], 3)
MD4_HH(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][9], 9)
MD4_HH(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][5], 11)
MD4_HH(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][13], 15)
MD4_HH(Ret.A, Ret.B, Ret.C, Ret.D, Ptr[i][3], 3)
MD4_HH(Ret.D, Ret.A, Ret.B, Ret.C, Ptr[i][11], 9)
MD4_HH(Ret.C, Ret.D, Ret.A, Ret.B, Ptr[i][7], 11)
MD4_HH(Ret.B, Ret.C, Ret.D, Ret.A, Ptr[i][15], 15)
#ifdef UINT32_ROL
#undef UINT32_ROL
#endif //#ifdef UINT32_ROL
#undef MD4_F
#undef MD4_G
#undef MD4_H
#undef MD4_FF
#undef MD4_GG
#undef MD4_HH
Ret.A += AA;
Ret.B += BB;
Ret.C += CC;
Ret.D += DD;
}
if(!Final) {
const BYTE(*_Ptr)[64] = (const BYTE (*)[64])srcBytes;
for(BYTE i = LeftoversrcByteLength - 1; i >0; i--) Extra[i] = _Ptr[TimesOfMainCycle][i];
Extra[0] = _Ptr[TimesOfMainCycle][0];
Extra[LeftoversrcByteLength] = 0x80;
*(UINT64*)(Extra + (LeftoversrcByteLength >= 56 ? 120 : 56)) = BitsOfsrcByte;
Final = true;
goto fin;
}
return Ret;
}
| gpl-3.0 |
boraolim/MVCSample40 | 01. Codigo Fuente/Capa de Presentacion/UILWeb/Controllers/system/OperacionController.cs | 498 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace UILWeb
{
[SecurityFilter]
[AjaxSessionExpiredFilter]
[DisableCache]
public class OperacionController : Controller
{
[HttpGet, OutputCache(NoStore = true, Duration = 1)]
[DisableCache]
public ActionResult Index()
{
ViewBag.Message = "Información del módulo de las operaciones críticas en la aplicación web.";
return View();
}
}
}
| gpl-3.0 |
shrkey/ardupilot | libraries/AP_Airspeed/AP_Airspeed.cpp | 11342 | /// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* APM_Airspeed.cpp - airspeed (pitot) driver
*/
#include "AP_Airspeed.h"
#include <AP_ADC/AP_ADC.h>
#include <AP_Common/AP_Common.h>
#include <AP_HAL/AP_HAL.h>
#include <AP_HAL/I2CDevice.h>
#include <AP_Math/AP_Math.h>
#include <GCS_MAVLink/GCS.h>
#include <utility>
extern const AP_HAL::HAL &hal;
// the virtual pin for digital airspeed sensors
#define AP_AIRSPEED_I2C_PIN 65
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
#define ARSPD_DEFAULT_PIN 1
#elif CONFIG_HAL_BOARD == HAL_BOARD_PX4 || CONFIG_HAL_BOARD == HAL_BOARD_VRBRAIN
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <systemlib/airspeed.h>
#include <drivers/drv_airspeed.h>
#include <uORB/topics/differential_pressure.h>
#if defined(CONFIG_ARCH_BOARD_VRBRAIN_V45)
#define ARSPD_DEFAULT_PIN 0
#elif defined(CONFIG_ARCH_BOARD_VRBRAIN_V51)
#define ARSPD_DEFAULT_PIN 0
#elif defined(CONFIG_ARCH_BOARD_VRBRAIN_V52)
#define ARSPD_DEFAULT_PIN 0
#elif defined(CONFIG_ARCH_BOARD_VRUBRAIN_V51)
#define ARSPD_DEFAULT_PIN 0
#elif defined(CONFIG_ARCH_BOARD_VRUBRAIN_V52)
#define ARSPD_DEFAULT_PIN 0
#elif defined(CONFIG_ARCH_BOARD_VRHERO_V10)
#define ARSPD_DEFAULT_PIN 0
#elif defined(CONFIG_ARCH_BOARD_PX4FMU_V1)
#define ARSPD_DEFAULT_PIN 11
#else
#define ARSPD_DEFAULT_PIN 15
#endif
#elif CONFIG_HAL_BOARD == HAL_BOARD_LINUX
#if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_NAVIO2 || CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_NAVIO
#define ARSPD_DEFAULT_PIN 5
#else
#define ARSPD_DEFAULT_PIN AP_AIRSPEED_I2C_PIN
#endif
#if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_DISCO
#define PSI_RANGE_DEFAULT 0.05
#endif
#else
#define ARSPD_DEFAULT_PIN 0
#endif
#ifndef PSI_RANGE_DEFAULT
#define PSI_RANGE_DEFAULT 1.0f
#endif
// table of user settable parameters
const AP_Param::GroupInfo AP_Airspeed::var_info[] = {
// @Param: ENABLE
// @DisplayName: Airspeed enable
// @Description: enable airspeed sensor
// @Values: 0:Disable,1:Enable
AP_GROUPINFO_FLAGS("ENABLE", 0, AP_Airspeed, _enable, 1, AP_PARAM_FLAG_ENABLE),
// @Param: USE
// @DisplayName: Airspeed use
// @Description: use airspeed for flight control
// @Values: 1:Use,0:Don't Use
AP_GROUPINFO("USE", 1, AP_Airspeed, _use, 0),
// @Param: OFFSET
// @DisplayName: Airspeed offset
// @Description: Airspeed calibration offset
// @Increment: 0.1
AP_GROUPINFO("OFFSET", 2, AP_Airspeed, _offset, 0),
// @Param: RATIO
// @DisplayName: Airspeed ratio
// @Description: Airspeed calibration ratio
// @Increment: 0.1
AP_GROUPINFO("RATIO", 3, AP_Airspeed, _ratio, 1.9936f),
// @Param: PIN
// @DisplayName: Airspeed pin
// @Description: The analog pin number that the airspeed sensor is connected to. Set this to 0..9 for the APM2 analog pins. Set to 64 on an APM1 for the dedicated airspeed port on the end of the board. Set to 11 on PX4 for the analog airspeed port. Set to 15 on the Pixhawk for the analog airspeed port. Set to 65 on the PX4 or Pixhawk for an EagleTree or MEAS I2C airspeed sensor.
// @User: Advanced
AP_GROUPINFO("PIN", 4, AP_Airspeed, _pin, ARSPD_DEFAULT_PIN),
// @Param: AUTOCAL
// @DisplayName: Automatic airspeed ratio calibration
// @Description: If this is enabled then the APM will automatically adjust the ARSPD_RATIO during flight, based upon an estimation filter using ground speed and true airspeed. The automatic calibration will save the new ratio to EEPROM every 2 minutes if it changes by more than 5%. This option should be enabled for a calibration flight then disabled again when calibration is complete. Leaving it enabled all the time is not recommended.
// @User: Advanced
AP_GROUPINFO("AUTOCAL", 5, AP_Airspeed, _autocal, 0),
// @Param: TUBE_ORDER
// @DisplayName: Control pitot tube order
// @Description: This parameter allows you to control whether the order in which the tubes are attached to your pitot tube matters. If you set this to 0 then the top connector on the sensor needs to be the dynamic pressure. If set to 1 then the bottom connector needs to be the dynamic pressure. If set to 2 (the default) then the airspeed driver will accept either order. The reason you may wish to specify the order is it will allow your airspeed sensor to detect if the aircraft it receiving excessive pressure on the static port, which would otherwise be seen as a positive airspeed.
// @User: Advanced
AP_GROUPINFO("TUBE_ORDER", 6, AP_Airspeed, _tube_order, 2),
// @Param: SKIP_CAL
// @DisplayName: Skip airspeed calibration on startup
// @Description: This parameter allows you to skip airspeed offset calibration on startup, instead using the offset from the last calibration. This may be desirable if the offset variance between flights for your sensor is low and you want to avoid having to cover the pitot tube on each boot.
// @Values: 0:Disable,1:Enable
// @User: Advanced
AP_GROUPINFO("SKIP_CAL", 7, AP_Airspeed, _skip_cal, 0),
// @Param: PSI_RANGE
// @DisplayName: The PSI range of the device
// @Description: This parameter allows you to to set the PSI (pounds per square inch) range for your sensor. You should not change this unless you examine the datasheet for your device
// @User: Advanced
AP_GROUPINFO("PSI_RANGE", 8, AP_Airspeed, _psi_range, PSI_RANGE_DEFAULT),
// @Param: ARSPD_FBW_MIN
// @DisplayName: Minimum Airspeed
// @Description: This is the minimum airspeed you want to fly at in modes where the autopilot controls the airspeed. This should be set to a value around 20% higher than the level flight stall speed for the airframe. This value is also used in the STALL_PREVENTION code.
// @Units: m/s
// @Range: 5 100
// @Increment: 1
// @User: Standard
AP_GROUPINFO("FBW_MIN", 9, AP_Airspeed, _airspeed_min, 9),
// @Param: ARSPD_FBW_MAX
// @DisplayName: Maximum Airspeed
// @Description: This is the maximum airspeed that you want to allow for your airframe in auto-throttle modes. You should ensure that this value is sufficiently above the ARSPD_MIN value to allow for a sufficient flight envelope to accurately control altitude using airspeed. A value at least 50% above ARSPD_MIN is recommended.
// @Units: m/s
// @Range: 5 100
// @Increment: 1
// @User: Standard
AP_GROUPINFO("FBW_MAX", 10, AP_Airspeed, _airspeed_max, 22),
AP_GROUPEND
};
AP_Airspeed::AP_Airspeed()
: _EAS2TAS(1.0f)
, _calibration()
, analog(_pin, _psi_range)
, digital(_psi_range)
{
AP_Param::setup_object_defaults(this, var_info);
};
/*
this scaling factor converts from the old system where we used a
0 to 4095 raw ADC value for 0-5V to the new system which gets the
voltage in volts directly from the ADC driver
*/
#define SCALING_OLD_CALIBRATION 819 // 4095/5
void AP_Airspeed::init()
{
_last_pressure = 0;
_calibration.init(_ratio);
_last_saved_ratio = _ratio;
_counter = 0;
analog.init();
digital.init();
}
// read the airspeed sensor
float AP_Airspeed::get_pressure(void)
{
if (!_enable) {
return 0;
}
if (_hil_set) {
_healthy = true;
return _hil_pressure;
}
float pressure = 0;
if (_pin == AP_AIRSPEED_I2C_PIN) {
_healthy = digital.get_differential_pressure(pressure);
} else {
_healthy = analog.get_differential_pressure(pressure);
}
return pressure;
}
// get a temperature reading if possible
bool AP_Airspeed::get_temperature(float &temperature)
{
if (!_enable) {
return false;
}
if (_pin == AP_AIRSPEED_I2C_PIN) {
return digital.get_temperature(temperature);
}
return false;
}
// calibrate the airspeed. This must be called at least once before
// the get_airspeed() interface can be used
void AP_Airspeed::calibrate(bool in_startup)
{
if (!_enable) {
return;
}
if (in_startup && _skip_cal) {
return;
}
// discard first reading
get_pressure();
_cal.start_ms = AP_HAL::millis();
_cal.count = 0;
_cal.sum = 0;
_cal.read_count = 0;
}
/*
update async airspeed calibration
*/
void AP_Airspeed::update_calibration(float raw_pressure)
{
// consider calibration complete when we have at least 10 samples
// over at least 1 second
if (AP_HAL::millis() - _cal.start_ms >= 1000 &&
_cal.read_count > 10) {
if (_cal.count == 0) {
GCS_MAVLINK::send_statustext_all(MAV_SEVERITY_INFO, "Airspeed sensor unhealthy");
} else {
GCS_MAVLINK::send_statustext_all(MAV_SEVERITY_INFO, "Airspeed sensor calibrated");
_offset.set_and_save(_cal.sum / _cal.count);
}
_cal.start_ms = 0;
return;
}
if (_healthy) {
_cal.sum += raw_pressure;
_cal.count++;
}
_cal.read_count++;
}
// read the airspeed sensor
void AP_Airspeed::read(void)
{
float airspeed_pressure;
if (!_enable) {
return;
}
float raw_pressure = get_pressure();
if (_cal.start_ms != 0) {
update_calibration(raw_pressure);
}
airspeed_pressure = raw_pressure - _offset;
// remember raw pressure for logging
_corrected_pressure = airspeed_pressure;
/*
we support different pitot tube setups so used can choose if
they want to be able to detect pressure on the static port
*/
switch ((enum pitot_tube_order)_tube_order.get()) {
case PITOT_TUBE_ORDER_NEGATIVE:
airspeed_pressure = -airspeed_pressure;
// no break
case PITOT_TUBE_ORDER_POSITIVE:
if (airspeed_pressure < -32) {
// we're reading more than about -8m/s. The user probably has
// the ports the wrong way around
_healthy = false;
}
break;
case PITOT_TUBE_ORDER_AUTO:
default:
airspeed_pressure = fabsf(airspeed_pressure);
break;
}
airspeed_pressure = MAX(airspeed_pressure, 0);
_last_pressure = airspeed_pressure;
_raw_airspeed = sqrtf(airspeed_pressure * _ratio);
_airspeed = 0.7f * _airspeed + 0.3f * _raw_airspeed;
_last_update_ms = AP_HAL::millis();
}
void AP_Airspeed::setHIL(float airspeed, float diff_pressure, float temperature)
{
_raw_airspeed = airspeed;
_airspeed = airspeed;
_last_pressure = diff_pressure;
_last_update_ms = AP_HAL::millis();
_hil_pressure = diff_pressure;
_hil_set = true;
_healthy = true;
}
| gpl-3.0 |
uocxp/logisim-evolution | src/com/cburch/logisim/std/gates/Gates.java | 2420 | /*******************************************************************************
* This file is part of logisim-evolution.
*
* logisim-evolution 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.
*
* logisim-evolution 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 logisim-evolution. If not, see <http://www.gnu.org/licenses/>.
*
* Original code by Carl Burch (http://www.cburch.com), 2011.
* Subsequent modifications by :
* + Haute École Spécialisée Bernoise
* http://www.bfh.ch
* + Haute École du paysage, d'ingénierie et d'architecture de Genève
* http://hepia.hesge.ch/
* + Haute École d'Ingénierie et de Gestion du Canton de Vaud
* http://www.heig-vd.ch/
* The project is currently maintained by :
* + REDS Institute - HEIG-VD
* Yverdon-les-Bains, Switzerland
* http://reds.heig-vd.ch
*******************************************************************************/
package com.cburch.logisim.std.gates;
import java.util.Arrays;
import java.util.List;
import com.cburch.logisim.tools.AddTool;
import com.cburch.logisim.tools.Library;
import com.cburch.logisim.tools.Tool;
public class Gates extends Library {
private List<Tool> tools = null;
public Gates() {
tools = Arrays.asList(new Tool[] { new AddTool(NotGate.FACTORY),
new AddTool(Buffer.FACTORY), new AddTool(AndGate.FACTORY),
new AddTool(OrGate.FACTORY), new AddTool(NandGate.FACTORY),
new AddTool(NorGate.FACTORY), new AddTool(XorGate.FACTORY),
new AddTool(XnorGate.FACTORY),
new AddTool(OddParityGate.FACTORY),
new AddTool(EvenParityGate.FACTORY),
new AddTool(ControlledBuffer.FACTORY_BUFFER),
new AddTool(ControlledBuffer.FACTORY_INVERTER), });
}
@Override
public String getDisplayName() {
return Strings.get("gatesLibrary");
}
@Override
public String getName() {
return "Gates";
}
@Override
public List<Tool> getTools() {
return tools;
}
}
| gpl-3.0 |
nimbusparis/IngressChase | src/IngressChase/wwwroot/js/shared/mainFactory.js | 540 | (function () {
'use strict';
angular
.module('app')
.factory('mainFactory', mainFactory);
mainFactory.$inject = ['$http'];
function mainFactory($http) {
var service = {
getVersion: getVersion,
getEnvironment: getEnvironment
};
return service;
function getVersion() {
return $http.get("api/Main/GetVersion");
}
function getEnvironment() {
return $http.get("api/Main/GetEnvironment");
}
}
})(); | gpl-3.0 |
kevinnguyeneng/django-uwsgi-nginx | app/naf_autoticket/migrations/0014_auto_20161006_1408.py | 780 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
class Migration(migrations.Migration):
dependencies = [
('naf_autoticket', '0013_auto_20161004_1051'),
]
operations = [
migrations.AddField(
model_name='ackalert',
name='AckDateTime',
field=models.DateTimeField(default=datetime.datetime(2016, 10, 6, 14, 8, 0, 404739)),
preserve_default=False,
),
migrations.AddField(
model_name='ackalert',
name='AckReceiveDateTime',
field=models.DateTimeField(default=datetime.datetime(2016, 10, 6, 14, 8, 30, 71495), auto_now_add=True),
preserve_default=False,
),
]
| gpl-3.0 |
theclanks/zurmo | app/protected/commands/bootstrap.php | 2371 | <?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2012 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU 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 ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207,
* Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com.
********************************************************************************/
// fix for fcgi
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
require_once('roots.php');
chdir(COMMON_ROOT);
$yii = COMMON_ROOT . "/../yii/framework/yii.php";
// Debug is used per instance.
$debug = INSTANCE_ROOT . '/protected/config/debug.php';
//Console configuration file
$config = INSTANCE_ROOT . '/protected/config/console.php';
require_once(COMMON_ROOT . "/version.php");
require_once($debug);
require_once($yii);
require_once(COMMON_ROOT . '/protected/extensions/zurmoinc/framework/components/ConsoleApplication.php');
//Including web application, because in console application, there is a reference to a method here.
require_once(COMMON_ROOT . '/protected/extensions/zurmoinc/framework/components/WebApplication.php');
$app = Yii::createApplication('ConsoleApplication', $config);
$app->run();
?> | gpl-3.0 |
mtaandao/Framework | admin/js/word-count.js | 3059 | ( function() {
function WordCounter( settings ) {
var key,
shortcodes;
if ( settings ) {
for ( key in settings ) {
if ( settings.hasOwnProperty( key ) ) {
this.settings[ key ] = settings[ key ];
}
}
}
shortcodes = this.settings.l10n.shortcodes;
if ( shortcodes && shortcodes.length ) {
this.settings.shortcodesRegExp = new RegExp( '\\[\\/?(?:' + shortcodes.join( '|' ) + ')[^\\]]*?\\]', 'g' );
}
}
WordCounter.prototype.settings = {
HTMLRegExp: /<\/?[a-z][^>]*?>/gi,
HTMLcommentRegExp: /<!--[\s\S]*?-->/g,
spaceRegExp: / | /gi,
HTMLEntityRegExp: /&\S+?;/g,
connectorRegExp: /--|\u2014/g,
removeRegExp: new RegExp( [
'[',
// Basic Latin (extract)
'\u0021-\u0040\u005B-\u0060\u007B-\u007E',
// Latin-1 Supplement (extract)
'\u0080-\u00BF\u00D7\u00F7',
// General Punctuation
// Superscripts and Subscripts
// Currency Symbols
// Combining Diacritical Marks for Symbols
// Letterlike Symbols
// Number Forms
// Arrows
// Mathematical Operators
// Miscellaneous Technical
// Control Pictures
// Optical Character Recognition
// Enclosed Alphanumerics
// Box Drawing
// Block Elements
// Geometric Shapes
// Miscellaneous Symbols
// Dingbats
// Miscellaneous Mathematical Symbols-A
// Supplemental Arrows-A
// Braille Patterns
// Supplemental Arrows-B
// Miscellaneous Mathematical Symbols-B
// Supplemental Mathematical Operators
// Miscellaneous Symbols and Arrows
'\u2000-\u2BFF',
// Supplemental Punctuation
'\u2E00-\u2E7F',
']'
].join( '' ), 'g' ),
astralRegExp: /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
wordsRegExp: /\S\s+/g,
characters_excluding_spacesRegExp: /\S/g,
characters_including_spacesRegExp: /[^\f\n\r\t\v\u00AD\u2028\u2029]/g,
l10n: window.wordCountL10n || {}
};
WordCounter.prototype.count = function( text, type ) {
var count = 0;
type = type || this.settings.l10n.type;
if ( type !== 'characters_excluding_spaces' && type !== 'characters_including_spaces' ) {
type = 'words';
}
if ( text ) {
text = text + '\n';
text = text.replace( this.settings.HTMLRegExp, '\n' );
text = text.replace( this.settings.HTMLcommentRegExp, '' );
if ( this.settings.shortcodesRegExp ) {
text = text.replace( this.settings.shortcodesRegExp, '\n' );
}
text = text.replace( this.settings.spaceRegExp, ' ' );
if ( type === 'words' ) {
text = text.replace( this.settings.HTMLEntityRegExp, '' );
text = text.replace( this.settings.connectorRegExp, ' ' );
text = text.replace( this.settings.removeRegExp, '' );
} else {
text = text.replace( this.settings.HTMLEntityRegExp, 'a' );
text = text.replace( this.settings.astralRegExp, 'a' );
}
text = text.match( this.settings[ type + 'RegExp' ] );
if ( text ) {
count = text.length;
}
}
return count;
};
window.mn = window.mn || {};
window.mn.utils = window.mn.utils || {};
window.mn.utils.WordCounter = WordCounter;
} )();
| gpl-3.0 |
UM-LPM/EARS | src/org/um/feri/ears/problems/unconstrained/FletcherPowell2.java | 6310 | package org.um.feri.ears.problems.unconstrained;
import org.um.feri.ears.problems.Problem;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.Math.*;
public class FletcherPowell2 extends Problem {
public double[][] a;
public double[][] b;
public double[] alpha;
public FletcherPowell2() {
super(2, 0);
lowerLimit = new ArrayList<Double>(Collections.nCopies(numberOfDimensions, -PI));
upperLimit = new ArrayList<Double>(Collections.nCopies(numberOfDimensions, PI));
name = "FletcherPowell2";
a = new double[][]{
{-79, 56, -62, -9, 92, 48, -22, -34, -39, -40, -95, -69, -20, -66, -98, -66, -67, 37, -83, -45},
{91, -9, -18, -59, 99, -45, 88, -14, -29, 26, 71, -65, 19, 45, 88, 18, -11, -81, -10, 42},
{-38, 8, -12, -73, 40, 26, -64, 29, -82, -32, -89, -3, 88, 98, 53, 58, 45, -39, 34, -23},
{-78, -18, -49, 65, 66, -40, 88, -95, -57, 10, -98, -11, -16, -55, 33, 84, 21, -43, 45, 100},
{-1, -43, 93, -18, -76, -68, -42, 22, 46, -14, 69, 27, -12, -26, 57, -13, 0, 1, 56, 17},
{34, -96, 26, -56, -36, -85, -62, 13, 93, 78, -43, 96, 77, 65, -34, -52, 82, 18, -59, -55},
{52, -46, -69, 99, -47, -72, -11, 55, -55, 91, -30, 7, -35, 23, -20, 55, 61, -39, -58, 13},
{81, 47, 35, 55, 67, -13, 33, 14, 83, -42, 8, -45, -44, 12, 100, -9, -33, -11, 21, 14},
{5, -43, -45, 46, 56, -94, -62, 52, 66, 55, -86, -29, -52, -71, -91, -46, 27, -27, 6, 67},
{-50, 66, -47, -75, 89, -16, 82, 6, -85, -62, -30, 31, -7, -75, -26, -24, 46, -95, -71, -57},
{24, 98, -50, 68, -97, -64, -24, 81, -59, -7, 85, -92, 2, 61, 52, -59, -91, 74, -99, -95},
{-30, -63, -32, -90, -35, 44, -64, 57, 27, 87, -70, -39, -18, -89, 99, 40, 14, -58, -5, -42},
{56, 3, 88, 38, -14, -15, 84, -9, 65, -20, -75, -37, 74, 66, -44, 72, 74, 90, -83, -40},
{84, 1, 73, 43, 84, -99, -35, 24, -78, -58, 47, -83, 94, -86, -65, 63, -22, 65, 50, -40},
{-21, -8, -48, 68, -91, 17, -52, -99, -23, 43, -8, -5, -98, -17, -62, -79, 60, -18, 54, 74},
{35, 93, -98, -88, -8, 64, 15, 69, -65, -86, 58, -44, -9, -94, 68, -27, -79, -67, -35, -56},
{-91, 73, 51, 68, 96, 49, 10, -13, -6, -23, 50, -89, 19, -67, 36, -97, 0, 3, 1, 39},
{53, 66, 23, 10, -33, 62, -73, 22, -65, 37, -83, -65, 59, -51, -56, 98, -57, -11, -48, 88},
{83, 48, 67, 27, 91, -33, -90, -34, 39, -36, -68, 17, -7, 14, 11, -10, 96, 98, -32, 56},
{52, -52, -5, 19, -25, 15, -1, -11, 8, -70, -4, -7, -4, -6, 48, 88, 13, -56, 85, -65}
};
b = new double[][]{
{-65, -11, 76, 78, 30, 93, -86, -99, -37, 52, -20, -10, -97, -71, 16, 9, -99, -84, 90, -18, -94},
{59, 67, 49, -45, 52, -33, -34, 29, -39, -80, 22, 7, 3, -19, -15, 7, -83, -4, 84, -60, -4},
{21, -23, -80, 86, 86, -30, 39, -73, -91, 5, 83, -2, -45, -54, -81, -8, 14, 83, 73, 45, 32},
{-91, -75, 20, -64, -15, 17, -89, 36, -49, -2, 56, -6, 76, 56, 2, -68, -59, -70, 48, 2, 24},
{-79, 99, -31, -8, -67, -72, -43, -55, 76, -57, 1, -58, 3, -59, 30, 32, 57, 29, 66, 50, -80},
{-89, -35, -55, 75, 15, -6, -53, -56, -96, 87, -90, -93, 52, -86, -38, -55, -53, 94, 98, 4, -79},
{-76, 45, 74, 12, -12, -69, 2, 71, 75, -60, -50, 23, 0, 6, 44, -82, 37, 91, 84, -15, -63},
{-50, -88, 93, 68, 10, -13, 84, -21, 65, 14, 4, 92, 11, 67, -18, -51, 4, 21, -38, 75, -59},
{-23, -95, 99, 62, -37, 96, 27, 69, -64, -92, -12, 87, 93, -19, -99, -92, -34, -77, 17, -72, 29},
{-5, -57, -30, -6, -96, 75, 25, -6, 96, 77, -35, -10, 82, 82, 97, -39, -65, -8, 34, 72, 65},
{85, -9, -14, 27, -45, 70, 55, 26, -87, -98, -25, -12, 60, -45, -24, -42, -88, -46, -95, 53, 28},
{80, -47, 38, -6, 43, -59, 91, -41, 90, -63, 11, -54, 33, -61, 74, 96, 21, -77, -58, -75, -9},
{-66, -98, -4, 96, -11, 88, -99, 5, 5, 58, -53, 52, -98, -97, 50, 49, 97, -62, 79, -10, -80},
{80, -95, 82, 5, -68, -54, 64, -2, 5, 10, 85, -33, -54, -30, -65, 58, 40, -21, -84, -66, -11},
{94, 85, -31, 37, -25, 60, 55, -13, 48, -23, -50, 84, -71, 54, 47, 18, -67, -30, 5, -46, 53},
{-29, 54, -10, -68, -54, -24, -16, 21, 32, 33, -27, 48, 37, -61, 97, 45, -90, 87, -95, 85, 67},
{76, -11, -48, 38, -7, 86, -55, 51, 26, 8, -96, 99, 69, -84, 41, 78, -53, 4, 29, 38, 16},
{-8, 48, 95, 47, 39, -11, -72, -95, -17, 33, 65, 96, -52, -17, -22, -15, -91, -41, -16, 23, 14},
{92, 87, 63, -63, -80, 96, -62, 71, -58, 17, -89, -35, -96, -79, 7, 46, -74, 88, 93, -44, 52},
{-21, 35, 16, -17, 54, -22, -93, 27, 88, 0, -67, 94, -24, -30, -90, -5, -48, 45, -90, 32, -81},
{-86, 31, -80, -79, -5, 11, -20, 9, 52, -38, 67, 64, -49, 23, -86, 39, -97, 76, 10, 81, 20}
};
alpha = new double[]{
-2.7910,
2.5623,
-1.0429,
0.5097,
-2.8096,
1.1883,
2.0771,
-2.9926,
0.0715,
0.4142,
-2.5010,
1.7731,
1.6473,
0.4934,
2.1038,
-1.9930,
0.3813,
-2.2144,
-2.5572,
2.9449};
}
@Override
public double eval(double[] x) {
double fitness = 0;
double[] A = new double[numberOfDimensions];
double[] B = new double[numberOfDimensions];
for (int i = 0; i < numberOfDimensions; i++) {
A[i] = 0;
B[i] = 0;
for (int j = 0; j < numberOfDimensions; j++) {
A[i] = A[i] + (a[i][j] * sin(alpha[j]) + b[i][j] * cos(alpha[j]));
B[i] = B[i] + (a[i][j] * sin(x[j]) + b[i][j] * cos(x[j]));
}
}
for (int i = 0; i < numberOfDimensions; i++) {
fitness += pow(A[i] - B[i], 2);
}
return fitness;
}
}
| gpl-3.0 |
sethten/MoDesserts | mcp50/temp/src/minecraft/net/minecraft/src/BlockMelon.java | 1189 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.util.Random;
// Referenced classes of package net.minecraft.src:
// Block, Material, Item
public class BlockMelon extends Block
{
protected BlockMelon(int p_i293_1_)
{
super(p_i293_1_, Material.field_4261_w);
field_378_bb = 136;
}
public int func_232_a(int p_232_1_, int p_232_2_)
{
return p_232_1_ != 1 && p_232_1_ != 0 ? 136 : 137;
}
public int func_218_a(int p_218_1_)
{
return p_218_1_ != 1 && p_218_1_ != 0 ? 136 : 137;
}
public int func_240_a(int p_240_1_, Random p_240_2_, int p_240_3_)
{
return Item.field_35421_bg.field_291_aS;
}
public int func_229_a(Random p_229_1_)
{
return 3 + p_229_1_.nextInt(5);
}
public int func_40198_a(int p_40198_1_, Random p_40198_2_)
{
int i = func_229_a(p_40198_2_) + p_40198_2_.nextInt(1 + p_40198_1_);
if(i > 9)
{
i = 9;
}
return i;
}
}
| gpl-3.0 |
anamunlam/ahkacp | dist/www/themes/default/web.php | 11035 | <?php
if(!defined('_WORKDIR_'))
{
header('location:/');
exit(1);
}
$users_->CheckAuth();
$web_ = new \Web;
if($helper_->IsPost($_POST, 'act'))
{
if($_POST['act']=='add')
{
if($helper_->IsPost($_POST, array('domain', 'alias', 'tpl')))
{
if($helper_->IsNotEmpty($_POST, array('domain', 'tpl')))
{
$ret_ = $web_->Add($_POST['domain'], $_POST['alias'], $_POST['tpl']);
if($ret_['status']===true)
{
$msg_ = Helper::Alert('success', $ret_['msg']);
}
else
{
$msg_ = Helper::Alert('warning', $ret_['msg']);
}
}
}
}
if($_POST['act']=='edit')
{
if($helper_->IsPost($_POST, array('domain', 'alias', 'tpl')))
{
if($helper_->IsNotEmpty($_POST, array('domain', 'tpl')))
{
$ret_ = $web_->Edit($_POST['domain'], $_POST['alias'], $_POST['tpl']);
if($ret_['status']===true)
{
$msg_ = Helper::Alert('success', $ret_['msg']);
}
else
{
$msg_ = Helper::Alert('warning', $ret_['msg']);
}
}
}
}
else if($_POST['act']=='delete')
{
if($helper_->IsPost($_POST, array('domain')))
{
if($helper_->IsNotEmpty($_POST, array('domain')))
{
$ret_ = $web_->Delete($_POST['domain']);
if($ret_['status']===true)
{
$msg_ = Helper::Alert('success', $ret_['msg']);
}
else
{
$msg_ = Helper::Alert('warning', $ret_['msg']);
}
}
}
}
}
require_once(_WORKDIR_.DIRECTORY_SEPARATOR.'themes'.DIRECTORY_SEPARATOR.$helper_->GetConf('theme').DIRECTORY_SEPARATOR.'header.php');
require_once(_WORKDIR_.DIRECTORY_SEPARATOR.'themes'.DIRECTORY_SEPARATOR.$helper_->GetConf('theme').DIRECTORY_SEPARATOR.'nav.php');
?>
<div class="brc">
<div class="container">
<div class="row">
<ul class="breadcrumb">
<li class="active">Web</li>
</ul>
</div>
</div>
</div>
<div class="container">
<div id="page">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<?php
if(isset($msg_))
{
echo($msg_);
}
?>
<div class="panel panel-info">
<div class="panel-heading">
<span class="panel-title">Web</span>
<span class="pull-right">
<button class="btn btn-success btn-xs" data-toggle="modal" data-target="#modaladd" title="Add new web"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<?php
$a_web = $web_->Lists();
if($a_web)
{
?>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Domain</th>
<th>Alias</th>
<th colspan="2">Template</th>
</tr>
</thead>
<tbody>
<?php
foreach($a_web as $domain => $val)
{
?>
<tr>
<td><?php echo($domain); ?></td>
<td><?php echo(str_replace(',', ', ', $val['ALIAS'])); ?></td>
<td><?php echo($val['TPL']); ?></td>
<td class="pull-right nowrap">
<button class="btn btn-xs btn-warning web-edit" title="Edit this web" data-domain="<?php echo($domain); ?>" data-alias="<?php echo($val['ALIAS']); ?>" data-tpl="<?php echo($val['TPL']); ?>"><span class="glyphicon glyphicon-pencil"></span></button>
<button class="btn btn-xs btn-danger web-delete" title="Delete web" data-domain="<?php echo($domain); ?>"><span class="glyphicon glyphicon-trash"></span></button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<?php
}
else
{
echo('<div class="panel-body">'.$helper_->Alert('info', 'Nothing found').'</div>');
}
?>
</div>
</div>
</div>
</div>
</div>
<div id="modaladd" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm">
<div class="modal-content norad">
<form method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Web</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="domain">Domain</label>
<input type="text" name="domain" class="form-control" autocomplete="off" placeholder="Domain" />
</div>
<div class="form-group">
<label for="alias">Alias</label>
<textarea class="form-control" name="alias" placeholder="One line per alias"></textarea>
</div>
<div class="form-group">
<label for="tpl">Template</label>
<select name="tpl" class="form-control">
<?php
$tpl_ = $web_->ListTemplate();
foreach($tpl_ as $tpl)
{
?>
<option value="<?php echo($tpl); ?>"><?php echo($tpl); ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-warning">Add</button>
</div>
<input type="hidden" name="act" value="add" />
</form>
</div>
</div>
</div>
<div id="modaledit" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm">
<div class="modal-content norad">
<form method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Web</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="domain">Domain</label>
<input type="text" id="domain" class="form-control" readonly="yes" />
</div>
<div class="form-group">
<label for="alias">Alias</label>
<textarea class="form-control" name="alias" id="alias" placeholder="One line per alias"></textarea>
</div>
<div class="form-group">
<label for="tpl">Template</label>
<select name="tpl" id="tpl" class="form-control">
<?php
$tpl_ = $web_->ListTemplate();
foreach($tpl_ as $tpl)
{
?>
<option value="<?php echo($tpl); ?>"><?php echo($tpl); ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-warning">Add</button>
</div>
<input type="hidden" name="domain" id="domain" />
<input type="hidden" name="act" value="edit" />
</form>
</div>
</div>
</div>
<div id="modaldelete" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm">
<div class="modal-content norad">
<form method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Confirm</h4>
</div>
<div class="modal-body">
Are you sure want to delete web <strong id="domainb"></strong>?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">No</button>
<button type="submit" class="btn btn-warning">Yes</button>
</div>
<input type="hidden" name="domain" id="domain" />
<input type="hidden" name="act" value="delete" />
</form>
</div>
</div>
</div>
<?php
$custom_footer[] = '<script type="text/javascript" src="/themes/'.$helper_->GetConf('theme').'/assets/js/javascript.js"></script>';
require_once(_WORKDIR_.DIRECTORY_SEPARATOR.'themes'.DIRECTORY_SEPARATOR.$helper_->GetConf('theme').DIRECTORY_SEPARATOR.'footer.php'); | gpl-3.0 |
simeonpp/SQL-Db-Back-And-Restore | Source/SQL-Db-Back-And-Restore/Core/SqlDbBackAndRestore.Core/Properties/AssemblyInfo.cs | 1489 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SqlDbBackAndRestore.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SqlDbBackAndRestore.Core")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("SqlDbBackAndRestore.Tests.Core")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dd33cc06-1f49-48d3-b2b0-bc16ae26de19")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| gpl-3.0 |
legalbox/legalbox_php_client_api | API/beans/LetterDeliveryType.php | 1876 | <?php
/*
* This file is part of LegalBox PHP Client API.
*
* Copyright 2013 LegalBox SA <contact@legalbox.com>
*
* LegalBox PHP Client API 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 3 of the License, or
* (at your option) any later version.
*
* LegalBox PHP Client API 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 LegalBox PHP Client API. If not, see <http://www.gnu.org/licenses/lgpl.txt>.
*/
/**
* @author David Keller <david.keller@legalbox.com>
* @author Johann Brocail <johannbrocail@enaco.fr>
*/
namespace API\beans;
use API\connectors\ApplicationClient;
class LetterDeliveryType extends AbstractBeans
{
protected $id;
protected $code;
protected $name;
protected static $letterDeliveryTypes = array();
public static $LRE_CODE = "LRE";
public static $CERTIFIED_LETTER_CODE = "CERTIFIED_LETTER";
public function __construct(ApplicationClient $ApplicationClient, $letterDeliveryTypeId = null)
{
parent::__construct($ApplicationClient);
if($letterDeliveryTypeId)
{
$datas = array(
'letterDeliveryTypeId' => $letterDeliveryTypeId
);
//$this->getApplicationClient()->execute('getLetterDeliveryTypeDetails', $datas);
$this->id = $letterDeliveryTypeId;
}
}
public function getId() {
return $this->id;
}
public function getCode() {
return $this->code;
}
public function getName() {
return $this->name;
}
}
| gpl-3.0 |
hjy846/scrapy-web | crawler/spiders/malimalihome_spider.py | 12547 | # -*- encoding:utf-8 -*-
import scrapy
from crawler.items import ResidenceItem, ResidenceDetailItem, ResidenceImageItem
import sys
import time
import urlparse
import os
from datetime import datetime, timedelta
import json
from scrapy.conf import settings
import logging
import traceback
reload(sys)
sys.setdefaultencoding('utf-8')
class ResidenceSpider(scrapy.Spider):
name = "residence"
#allowed_domains = ['xxx.net']
start_urls = []
def __init__(self, crawl_date = None, region = None, *args, **kwargs):
super(ResidenceSpider, self).__init__(*args, **kwargs)
#处理时间
now = datetime.now()
yesterday = now - timedelta(days=1)
yesterday_str = yesterday.strftime('%Y-%m-%d')
today_str = now.strftime('%Y-%m-%d')
if crawl_date == 'today':
self.crawl_date = today_str
elif crawl_date == 'yesterday':
self.crawl_date = yesterday_str
else:
self.crawl_date = crawl_date if crawl_date else yesterday_str
#help(settings)
settings.set('crawl_date', self.crawl_date)
#settings['crawl_date'] = self.crawl_date
self.now = now.strftime('%Y%m%d_%H%M')
#处理起始爬取url
url = settings['INIT_URL']
#根据地区爬取
self.region = region if region != None else 'all'
self.region_num = self.map_region(self.region)
if self.region_num != None:
url += '®ion1=%s' % self.region_num
self.start_urls.append(url)
#房产列表网页保存路径
self.list_output_path = './output/list/%s/%s/%s/' % (self.crawl_date, self.region, self.now)
self.list_output_path = self.list_output_path.strip('\r')
if not os.path.exists(self.list_output_path):
os.makedirs(self.list_output_path)
#房产详情页面保存路径
self.detail_output_path = './output/detail/%s/%s/%s/' % (self.crawl_date, self.region, self.now)
self.detail_output_path = self.detail_output_path.strip('\r')
if not os.path.exists(self.detail_output_path):
os.makedirs(self.detail_output_path)
#房产图片保存路径
self.image_output_path = './output/image/'
self.image_output_path = self.image_output_path.strip('\r')
if not os.path.exists(self.image_output_path):
os.makedirs(self.image_output_path)
self.go_next = settings['GO_NEXT']
def map_region(self, region):
if region.lower() == 'macau':
return 3
elif region.lower() == 'taipa':
return 1
elif region.lower() == 'coloane':
return 6
return None
def parse1(self, response):
print 'parse' * 100
self.parse_articles_follow_next_page(response)
self.now = int(time.time())
#解释房产列表
def parse_list(self, response):
result = urlparse.urlparse(response.url)
params = urlparse.parse_qs(result.query, True)
filename = 'page_%s' % params['page'][0]
with open(self.list_output_path + filename, 'wb') as f:
f.write(response.body)
for sel in response.xpath('//div[@class="result-list"]'):
try:
info_list = sel.xpath('div[@style="float:right"]/div[@class="result-list-c"]/div[@class="result-list-c-type"]/b/text()').extract()
update_time = info_list[-1].strip()
#if update_time > self.crawl_date:
# pass
if update_time < self.crawl_date:
self.go_next = False
break
item = ResidenceItem()
item['building_name'] = sel.xpath('div[@style="float:right"]/div[@class="result-list-c"]/div[@class="result-list-c-title"]/a/text()').extract()[0]
item['link'] = sel.xpath('div[@style="float:right"]/div[@class="result-list-c"]/div[@class="result-list-c-title"]/a/@href').extract()[0]
item['_id'] = item['link'].split('/')[-1:][0]
item['price'] = sel.xpath('div[@style="float:right"]/div[@class="result-list-r"]/div[@class="result-list-r-price red"]/text()').re('(\d+)')[0]
item['price'] = int(item['price'])
huxing = info_list[0:-1]
record_bed_room = False
for i in huxing:
if int(i) < 10:
if record_bed_room:
item['living_room_num'] = int(i)
else:
item['bed_room_num'] = int(i)
record_bed_room = True
else:
item['size'] = int(i)
item['update_time'] = update_time
item['remark'] = sel.xpath('div[@style="float:right"]/div[@class="result-list-c"]/div[@class="result-list-c-desc"]/text()').extract()
item['remark'] = item['remark'][0] if len(item['remark']) else ''
item['agent_logo'] = sel.xpath('div[@style="float:right"]/div[@class="result-list-r"]/div[@class="result-list-r-logo"]/img/@src').extract()[0]
item['photo_num'] = sel.xpath('div[@class="result-list-l"]/div[@class="list-cover"]/div[@class="total_img"]/text()').extract()
item['photo_num'] = int(item['photo_num'][0].split()[0]) if len(item['photo_num']) else 0
#self.fp.write(json.dumps(dict(item), ensure_ascii = False) + '\n')
#爬取详情页
item['list_insert_time'] = datetime.now()
yield scrapy.Request(item['link'], self.parse_detail)
yield item
except Exception as e:
self.logger.error(repr(e))
print 'error: %s' % repr(e)
print traceback.format_exc()
#next_page = response.xpath('//div[@class="result-list"]/div[@style="float:right"]').extract()
next_page = response.xpath('//div[@class="page result-desc"]/div/div/ul[@class="pagination"]/li/a[@rel="next"]/@href').extract()
if next_page and self.go_next:
url = response.urljoin(next_page[0])
yield scrapy.Request(url, self.parse_list)
def parse(self, response):
#return self.parse_image(response)
#return self.parse_detail(response)
return self.parse_list(response)
def parse_detail(self, response):
#保存文件
filename = '%s.html' % response.url.split('/')[-1:][0]
with open(self.detail_output_path + filename, 'wb') as f:
f.write(response.body)
for sel in response.xpath('//div[@class="module1 left"]'):
try:
item = ResidenceDetailItem()
item['building'] = sel.xpath('div[@class="view-title"]/a/text()').extract()
if len(item['building']):
item['building'] = item['building'][0]
else:
item['building'] = sel.xpath('div[@class="view-title"]/text()').extract()[0].strip().split()[0]
item['location'] = sel.xpath('div[@class="view-address"]/text()').extract()[0]
item['_id'] = sel.xpath('div[@class="view-no"]/b/text()').extract()[0].split('#')[-1:][0]
item['rent'] = sel.xpath('div[@class="view-price"]/div[@class="view-price-div view-price-yellow"]/div/text()').extract()[0].strip('$').strip('-')
#item['property_type'] = sel.xpath('div[@class="view-photo"]/div[@class="photo-small slick-initialized slick-slider"]/div[@class="slick-list draggable"]/div[@class="slick-track"]/div[@class="slick-slide slick-current slick-active"]/div[@class="image-border"]/div/center/img/@src').extract()
info_list_nodes = sel.xpath('div[@class="view-desc"]/div/table/tr')
info_list = []
for x in info_list_nodes:
for y in x.xpath('td'):
info = y.xpath('text()').extract()
if len(info):
info_list.append(info[0])
else:
info_list.append("")
item['property_type'] = info_list[0].strip().strip('-')
item['region'] = info_list[1].strip().strip('-')
item['block'] = info_list[2].strip().strip('-')
item['floor'] = info_list[3].strip().strip('-')
item['room'] = info_list[4].strip().strip('-')
item['layout'] = info_list[5].strip().strip('-')
item['size'] = info_list[6].strip().strip('-').split()
if len(item['size']):
item['size'] = float(item['size'][0])
else: item['size'] = 0
item['net_size'] = info_list[7].strip().strip('-').split()
if len(item['net_size']):
item['net_size'] = float(item['net_size'][0])
else: item['net_size'] = 0
item['price'] = info_list[8].strip().strip('-').strip('$').split('\r\n')[0]
if item['price'] != "":
item['price'] = float(item['price'])
item['price_per_ft2'] = info_list[9].strip().strip('-').strip('$').split(u'\u5143')[0]
if item['price_per_ft2'] != "":
item['price_per_ft2'] = float(item['price_per_ft2'])
item['rental'] = info_list[10].strip().strip('-')
item['rental_per_ft2'] = info_list[11].strip().strip('-')
item['age'] = info_list[12].strip().strip('-').split()
if len(item['age']):
item['age'] = int(item['age'][0])
else:item['age'] = 0
item['lift'] = info_list[13].strip().strip('-')
item['direction'] = info_list[14].strip().strip('-')
item['views'] = info_list[15].strip().strip('-')
item['renovation'] = info_list[16].strip().strip('-')
item['other'] = info_list[17].strip().strip('-')
item['remark'] = info_list[18].strip().strip('-')
item['detail_insert_time'] = datetime.now()
item['image_list'] = sel.xpath('div[@class="view-photo"]/div[@class="photo-big"]/a/@href').extract()
item['agent_name'] = response.xpath('//div[@class="view-agent-desc-contact"]/text()').extract()
if len(item['agent_name']):
item['agent_name'] = item['agent_name'][0].strip()
else: item['agent_name'] = ""
item['agent_contact'] = response.xpath('//span[@class="view-agent-desc-phone result-list-b-phone-shown"]/text()').extract()
if len(item['agent_contact']):
item['agent_contact'] = item['agent_contact'][0].strip()
else: item['agent_contact'] = ""
item['agent_company'] = response.xpath('//div[@class="view-agent-name"]/b/text()').extract()
if len(item['agent_company']):
item['agent_company'] = item['agent_company'][0].strip()
else: item['agent_company'] = ""
item['agent_address'] = response.xpath('//div[@class="view-agent-desc-adr"]/text()').extract()
if len(item['agent_address']):
item['agent_address'] = item['agent_address'][0].strip()
else: item['agent_address'] = ""
yield item
image_item = ResidenceImageItem()
image_item['image_urls'] = item['image_list']
#yield image_item
except Exception as e:
self.logger.error(response.url)
self.logger.error(repr(e))
print response.url
print 'error: %s' % repr(e)
print traceback.format_exc()
def parse_image(self, response):
item = ResidenceImageItem()
item['image_urls'] = ["http://media.xxx.net/images/props/001/216/082/2/570431.jpeg",
"http://media.xxx.net/images/props/001/216/082/1/570432.jpeg"]
yield item
| gpl-3.0 |
Microvellum/Fluid-Designer | win64-vc/2.78/scripts/addons/fd_library/__init__.py | 1917 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
bl_info = {
"name": "Products and Inserts",
"author": "Andrew Peel",
"version": (1, 0, 0),
"blender": (2, 7, 0),
"location": "Tools Shelf",
"description": "This add-on creates a UI to work with the Products and Inserts Library",
"warning": "",
"wiki_url": "",
"category": "Fluid Designer"
}
import bpy
class PANEL_Library_Management(bpy.types.Panel):
bl_space_type = "VIEW_3D"
bl_region_type = "TOOLS"
bl_context = "objectmode"
bl_label = "Products and Inserts"
bl_options = {'DEFAULT_CLOSED'}
bl_category = "Fluid Designer"
@classmethod
def poll(cls, context):
return True
def draw_header(self, context):
layout = self.layout
layout.label('',icon='EXTERNAL_DATA')
def draw(self, context):
layout = self.layout
wm = context.window_manager
wm.cabinetlib.draw_library_items(layout,'PRODUCT')
def register():
bpy.utils.register_class(PANEL_Library_Management)
def unregister():
bpy.utils.unregister_class(PANEL_Library_Management)
if __name__ == "__main__":
register()
| gpl-3.0 |
ivandiazwm/opensupports | client/src/app/admin/panel/tickets/admin-panel-new-tickets.js | 2419 | import React from 'react';
import {connect} from 'react-redux';
import i18n from 'lib-app/i18n';
import AdminDataAction from 'actions/admin-data-actions';
import TicketList from 'app-components/ticket-list';
import Header from 'core-components/header';
import Message from 'core-components/message';
class AdminPanelNewTickets extends React.Component {
static defaultProps = {
page: 1,
userId: 0,
departments: [],
tickets: [],
};
state = {
departmentId: null,
};
componentDidMount() {
this.retrieveNewTickets();
}
render() {
const noDepartments = !this.props.departments.length;
return (
<div className="admin-panel-new-tickets">
<Header title={i18n('NEW_TICKETS')} description={i18n('NEW_TICKETS_DESCRIPTION')} />
{(noDepartments) ? <Message className="admin-panel-new-tickets__department-warning" type="warning">{i18n('NO_DEPARTMENT_ASSIGNED')}</Message> : null}
{(this.props.error) ? <Message type="error">{i18n('ERROR_RETRIEVING_TICKETS')}</Message> : <TicketList {...this.getProps()}/>}
</div>
);
}
getProps() {
return {
userId: this.props.userId,
departments: this.props.departments,
tickets: this.props.tickets,
type: 'secondary',
loading: this.props.loading,
ticketPath: '/admin/panel/tickets/view-ticket/',
page: this.props.page,
pages: this.props.pages,
onPageChange: event => this.retrieveNewTickets(event.target.value),
onDepartmentChange: departmentId => {
this.setState({departmentId});
this.retrieveNewTickets(1, departmentId);
},
};
}
retrieveNewTickets(page = this.props.page, departmentId = this.state.departmentId) {
this.props.dispatch(AdminDataAction.retrieveNewTickets(page, departmentId));
}
}
export default connect((store) => {
return {
userId: store.session.userId,
departments: store.session.userDepartments,
tickets: store.adminData.newTickets,
page: store.adminData.newTicketsPage,
pages: store.adminData.newTicketsPages,
loading: !store.adminData.newTicketsLoaded,
error: store.adminData.newTicketsError
};
})(AdminPanelNewTickets);
| gpl-3.0 |
frostasm/qt-creator | src/plugins/analyzerbase/diagnosticlocation.cpp | 2354 | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "diagnosticlocation.h"
namespace Analyzer {
DiagnosticLocation::DiagnosticLocation() : line(0), column(0)
{
}
DiagnosticLocation::DiagnosticLocation(const QString &filePath, int line, int column)
: filePath(filePath), line(line), column(column)
{
}
bool DiagnosticLocation::isValid() const
{
return !filePath.isEmpty();
}
bool operator==(const DiagnosticLocation &first, const DiagnosticLocation &second)
{
return first.filePath == second.filePath
&& first.line == second.line
&& first.column == second.column;
}
QDebug operator<<(QDebug dbg, const DiagnosticLocation &location)
{
dbg.nospace() << "Location(" << location.filePath << ", "
<< location.line << ", "
<< location.column << ')';
return dbg.space();
}
} // namespace Analyzer
| gpl-3.0 |
luigiecalo/Club | guias/src/java/com/Entidades/Grupo.java | 2799 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.Entidades;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author usuario
*/
@Entity
@Table(name = "grupo")
public class Grupo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idgrupo")
private Long idgrupo;
@Column(name = "nombre")
private String nombre;
@Column(name = "icono")
private String icono;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "grupomodulo")
private List<Modulo> modulos;
public Grupo() {
}
public Grupo(Long idgrupo) {
this.idgrupo = idgrupo;
}
public Long getIgrupo() {
return idgrupo;
}
public void setIgrupo(Long idgrupo) {
this.idgrupo = idgrupo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getIcono() {
return icono;
}
public void setIcono(String icono) {
this.icono = icono;
}
public List<Modulo> getModulos() {
return modulos;
}
public void setModulos(List<Modulo> modulos) {
this.modulos = modulos;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idgrupo != null ? idgrupo.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Grupo)) {
return false;
}
Grupo other = (Grupo) object;
if ((this.idgrupo == null && other.idgrupo != null) || (this.idgrupo != null && !this.idgrupo.equals(other.idgrupo))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.Entidades.Modulo[ idgrupo=" + idgrupo + " ]";
}
}
| gpl-3.0 |
xnau/pardibee | setup_guide.php | 3766 | <div class="text-block">
<?php
$langfile = Participants_Db::$plugin_path . 'languages/setup_guide-' . get_locale() . '.html';
if (file_exists($langfile)) {
$text = file_get_contents($langfile);
echo wpautop($text);
} else {
?>
<h1>Participants Database<br />Quick Setup Guide</h1>
<h2>Initial Setup</h2>
<p>There are several settings that must be set for many of the plugin's functions to work. On this page, I will walk you through getting the plugin set up and running on your site. The first thing you will want to do is have a general idea of how you want the plugin to work, what information you need to gather and store and how your users will see and interact with that information. </p>
<h3>Here is one example of how to set up the plugin.</h3>
<p>Let’s just say you want to have a signup form that gathers a person’s name and email address. When they fill out and submit the form, they will be taken to another page and thanked. An email will be sent to them letting them know they’ve signed up and that they can return to the site to add more information to their record. A private link for this purpose is provided in the email.</p>
<p>Meanwhile, the site admin receives an email notifying them of the signup, and providing them with a direct link to the new record.</p>
<h3>Here’s How We Set That Up</h3>
<ol>
<li>Place the <code>[pdb_signup]</code> shortcode on the page where you want your signup form to appear.</li>
<li>Go to the plugin settings page and click on the “Signup Form” tab.</li>
<li>Set the “Thanks Page” setting to point to the page you want them to go to after they sign up. Place the <code>[pdb_signup_thanks]</code> shortcode on that page somewhere.</li>
<li>When the person who signed up clicks on the link provided them in the email, they will go to a page where they can fill out the rest of the form with information for their record.</li>
<li>Click on the “Record Form” tab and set the “Participant Record Page” setting to point to the page where you want them to go to edit their record. Put the <code>[pdb_record]</code> shortcode on that page. This shortcode won’t show anything unless it is visited with the special private link provided to the user in the receipt email.</li>
</ol>
<h2>Setting Up the List Page and Detail Page</h2>
<p>When someone visits the site, you can show them a list of the people who have signed up. Each name on the list can be clicked to take the user to a detail page showing all the public information in their record. This is how to set that up:</p>
<ol>
<li>Place the <code>[pdb_list]</code> shortcode on the page where you want the list of participants to go.</li>
<li>On the “Manage Database Fields” page you can determine which fields get shown in the list and which column they will be in. This is under the “Display” column and you give each field you want to show a number which determines which column the field will appear in. Zero means it won’t show at all.</li>
<li>On the page where you want the record detail to show, place the <code>[pdb_single]</code> shortcode. This page won’t show anything unless it is visited using a link with the ID of the record to show in it. For example: <pre>/participants/detail?pdb=27</pre></li>
<li>On the plugin settings page, under the “List Display” tab, set the “Single Record Link Field” to the field in the list (like 'first_name') where you want the link to the detail page to go.</li>
<li>Next, set the “Single Record Page” setting to point to the page where you put the <code>[pdb_single]</code> shortcode.</li>
</ol>
<p>Now, go to the “Add Participant” page in the admin and enter a test record. You can now test the plugin functions to see how it all works.</p>
<?php } ?>
</div> | gpl-3.0 |
wangyufu/Python-practice | day2/shopping_cart/shopping_cart.py | 1836 | #!/usr/bin/env python
cart = []
product = [['iphone7', 6500], ['macbook', 12000], ['pythonbook', 66], ['bike', 999], ['coffee', 31]]
# 第二列最长的字符串
two_row = max([len(x[0]) for x in product])
while True:
gongzi = input('salary>: ').strip()
# 判断工资输入的是数字还是其它字符
if gongzi.isdigit():
gongzi = int(gongzi)
break
else:
print("Please enter the correct salary.")
while True:
# 表头和列表的第二列以最长字符串左对齐
print("number", "\t", "product".ljust(two_row), "cost")
for k, v in enumerate(product):
print(k, "\t\t", v[0].ljust(two_row), v[1])
print("Please enter the article number or enter exit.")
xuanzhe = input('>>: ').strip()
if xuanzhe != "":
# 输入负数时isdigit函数用认为‘-’是特殊字符不是输入
if (xuanzhe.startswith('-') and xuanzhe[1:] or xuanzhe).isdigit():
xuanzhe = int(xuanzhe)
if xuanzhe < len(product) and xuanzhe >= 0:
if product[xuanzhe][1] > gongzi:
print('cannot afford this product, need %d' % (product[xuanzhe][1] - gongzi))
else:
gongzi -= product[xuanzhe][1]
print('added %s into your shopping cart , your current balance is %d'\
% (product[xuanzhe][0], gongzi))
cart.append(product[xuanzhe])
else:
print("Please enter the correct article number.")
elif xuanzhe == 'exit':
total_price = 0
for c in cart:
print(c[0], c[1])
total_price += c[1]
print('total_price: ', total_price)
break
else:
print("The input value is empty, please enter again.\n")
| gpl-3.0 |
conejoninja/webwallet | app/scripts/controllers/nav.js | 1473 | /*global angular*/
/**
* Navigation Controller
*
* Manage device and account navigation and account adding.
*
* @see nav.html
*/
angular.module('webwalletApp').controller('NavCtrl', function (
$scope,
$location,
deviceList,
modalOpener,
forgetModalService,
flash) {
'use strict';
$scope.devices = function () {
return deviceList.all();
};
$scope.isActive = function (path) {
return $location.path().match(path);
};
$scope.addingInProgress = false;
$scope.addAccount = function (dev) {
$scope.addingInProgress = true;
dev.addAccount().then(
function (acc) {
$location.path('/device/' + dev.id + '/account/' + acc.id);
$scope.addingInProgress = false;
},
function (err) {
flash.error(err.message || 'Failed to add account.');
}
);
};
$scope.accountLink = function (dev, acc) {
var link = '#/device/' + dev.id + '/account/' + acc.id;
if ($scope.isActive('/receive$')) link += '/receive';
if ($scope.isActive('/send$')) link += '/send';
return link;
};
/**
* When user clicks on trash icon, ask again (to be sure).
*
* @param {TrezorDevice} device Device that was disconnected
*/
$scope.forget = function (device) {
forgetModalService.showRequestedModal($scope, device,deviceList);
}
});
| gpl-3.0 |
LNTakeshi/beatoraja | src/bms/player/beatoraja/audio/GdxSoundDriver.java | 9391 | package bms.player.beatoraja.audio;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.file.*;
import java.util.logging.Logger;
import bms.player.beatoraja.Config;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.files.FileHandleStream;
import com.badlogic.gdx.utils.GdxRuntimeException;
/**
* libGDX Sound(OpenAL)サウンドドライバ
*
* @author exch
*/
public class GdxSoundDriver extends AbstractAudioDriver<Sound> {
private SoundMixer mixer;
private final boolean soundthread = false;
private SoundInstance[] sounds = new SoundInstance[256];
private int soundPos = 0;
public GdxSoundDriver(Config config) {
super(config.getSongResourceGen());
channels = 2;
for (int i = 0; i < sounds.length; i++) {
sounds[i] = new SoundInstance();
}
if(soundthread) {
mixer = new SoundMixer();
mixer.start();
}
}
static final String[] exts = { ".wav", ".ogg", ".mp3", ".flac" };
@Override
protected Sound getKeySound(Path p) {
String path = p.toString();
final int index = path.lastIndexOf('.');
final String name = path.substring(0, index < 0 ? path.length() : index);
final String ext = index < 0 ? "" : path.substring(index, path.length());
if (p.toFile().exists()) {
return getKeySound(name, ext);
}
for (String _ext : exts) {
if (!_ext.equals(ext) && p.resolve(name + _ext).toFile().exists()) {
return getKeySound(name, _ext);
}
}
return null;
}
private Sound getKeySound(String name, String ext) {
switch (ext) {
case ".wav":
case ".flac":
return getKeySound(new PCMHandleStream(name + ext));
case ".ogg":
case ".mp3":
return getKeySound(Gdx.files.internal(name + ext));
}
return null;
}
private Sound getKeySound(FileHandle handle) {
try {
return Gdx.audio.newSound(handle);
} catch (GdxRuntimeException e) {
Logger.getGlobal().warning("音源ファイル読み込み失敗" + e.getMessage());
}
return null;
}
@Override
protected Sound getKeySound(final PCM pcm) {
return Gdx.audio.newSound(new FileHandleStream("tempwav.wav") {
@Override
public InputStream read() {
return new WavFileInputStream(pcm);
}
@Override
public OutputStream write(boolean overwrite) {
return null;
}
});
}
private Object lock = new Object();
@Override
protected void play(Sound pcm, int channel, float volume, float pitch) {
if(soundthread) {
mixer.put(pcm, channel, volume, getGlobalPitch() * pitch);
} else {
synchronized (lock) {
sounds[soundPos].sound = pcm;
sounds[soundPos].id = pcm.play(volume, getGlobalPitch() * pitch, 0);
sounds[soundPos].channel = channel;
soundPos = (soundPos + 1) % sounds.length;
}
}
}
@Override
protected void play(AudioElement<Sound> id, float volume, boolean loop) {
if(soundthread) {
mixer.put(id.audio, volume, loop);
} else {
synchronized (lock) {
if(loop) {
id.id = id.audio.loop(volume);
} else {
id.id = id.audio.play(volume);
}
}
}
}
@Override
protected void setVolume(AudioElement<Sound> id, float volume) {
id.audio.setVolume(id.id, volume);
}
@Override
protected void stop(Sound id) {
if (soundthread) {
mixer.stop(id, 0);
} else {
synchronized (lock) {
id.stop();
}
}
}
@Override
protected void stop(Sound id, int channel) {
if (soundthread) {
mixer.stop(id, channel);
} else {
for (int i = 0; i < sounds.length; i++) {
if (sounds[i].sound == id && sounds[i].channel == channel) {
synchronized (lock) {
sounds[i].sound.stop(sounds[i].id);
sounds[i].sound = null;
}
}
}
}
}
@Override
protected void disposeKeySound(Sound pcm) {
pcm.dispose();
}
class SoundMixer extends Thread {
private Sound[] sound = new Sound[256];
private float[] volume = new float[256];
private float[] pitch = new float[256];
private int[] channels = new int[256];
private long[] ids = new long[256];
private boolean[] loops = new boolean[256];
private int cpos;
private int pos;
public synchronized void put(Sound sound, int channel, float volume, float pitch) {
this.sound[cpos] = sound;
this.volume[cpos] = volume;
this.pitch[cpos] = pitch;
this.channels[cpos] = channel;
this.loops[cpos] = false;
cpos = (cpos + 1) % this.sound.length;
}
public synchronized void put(Sound sound, float volume, boolean loop) {
this.sound[cpos] = sound;
this.volume[cpos] = volume;
this.pitch[cpos] = 0;
this.channels[cpos] = 0;
this.loops[cpos] = loop;
cpos = (cpos + 1) % this.sound.length;
}
public synchronized void stop(Sound snd, int channel) {
for (int i = 0; i < sound.length; i++) {
if (sound[i] == snd && this.channels[i] == channel) {
sound[i].stop(ids[i]);
sound[i] = null;
}
}
}
public void run() {
for(;;) {
if(pos != cpos) {
if(loops[pos]) {
ids[pos] = sound[pos].loop(this.volume[pos], getGlobalPitch() * this.pitch[pos], 0);
} else {
ids[pos] = sound[pos].play(this.volume[pos], getGlobalPitch() * this.pitch[pos], 0);
}
pos = (pos + 1) % this.sound.length;
} else {
try {
sleep(1);
} catch (InterruptedException e) {
}
}
}
}
}
private static class SoundInstance {
public Sound sound;
public long id = -1;
public int channel = -1;
}
private class PCMHandleStream extends FileHandleStream {
private final Path p;
public PCMHandleStream(Path p) {
super("tempwav.wav");
this.p = p;
}
public PCMHandleStream(String path) {
this(Paths.get(path));
}
@Override
public InputStream read() {
try {
return new WavFileInputStream(PCM.load(p,GdxSoundDriver.this));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public OutputStream write(boolean overwrite) {
return null;
}
}
static class WavFileInputStream extends InputStream {
private int pos = 0;
private int mark = 0;
private final byte[] header;
private final PCM pcm;
public WavFileInputStream(PCM pcm) {
header = new byte[44];
final int sampleRate = pcm.sampleRate;
final int channels = pcm.channels;
this.pcm = pcm;
final long totalDataLen = pcm.len * 2 + 36;
final long bitrate = sampleRate * channels * 16;
header[0] = 'R';
header[1] = 'I';
header[2] = 'F';
header[3] = 'F';
header[4] = (byte) (totalDataLen & 0xff);
header[5] = (byte) ((totalDataLen >> 8) & 0xff);
header[6] = (byte) ((totalDataLen >> 16) & 0xff);
header[7] = (byte) ((totalDataLen >> 24) & 0xff);
header[8] = 'W';
header[9] = 'A';
header[10] = 'V';
header[11] = 'E';
header[12] = 'f';
header[13] = 'm';
header[14] = 't';
header[15] = ' ';
header[16] = 16;
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1;
header[21] = 0;
header[22] = (byte) channels;
header[23] = 0;
header[24] = (byte) (sampleRate & 0xff);
header[25] = (byte) ((sampleRate >> 8) & 0xff);
header[26] = (byte) ((sampleRate >> 16) & 0xff);
header[27] = (byte) ((sampleRate >> 24) & 0xff);
header[28] = (byte) ((bitrate / 8) & 0xff);
header[29] = (byte) (((bitrate / 8) >> 8) & 0xff);
header[30] = (byte) (((bitrate / 8) >> 16) & 0xff);
header[31] = (byte) (((bitrate / 8) >> 24) & 0xff);
header[32] = (byte) ((channels * 16) / 8);
header[33] = 0;
header[34] = 16;
header[35] = 0;
header[36] = 'd';
header[37] = 'a';
header[38] = 't';
header[39] = 'a';
header[40] = (byte) ((pcm.len * 2) & 0xff);
header[41] = (byte) (((pcm.len * 2) >> 8) & 0xff);
header[42] = (byte) (((pcm.len * 2) >> 16) & 0xff);
header[43] = (byte) (((pcm.len * 2) >> 24) & 0xff);
}
@Override
public int available() {
return 44 + pcm.len * 2 - pos;
}
@Override
public synchronized void mark(int readlimit) {
mark = pos;
}
@Override
public synchronized void reset() {
pos = mark;
}
@Override
public long skip(long n) {
if (n < 0) {
return 0;
}
if (44 + pcm.len * 2 - pos < n) {
pos = 44 + pcm.len * 2;
return 44 + pcm.len * 2 - pos;
}
pos += n;
return n;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public int read() {
int result = -1;
if (pos < 44) {
result = 0x00ff & header[pos];
pos++;
} else if (pos < 44 + pcm.len * 2) {
if(pcm instanceof ShortPCM) {
short s = ((short[])pcm.sample)[(pos - 44) / 2 + pcm.start];
if (pos % 2 == 0) {
result = (s & 0x00ff);
} else {
result = ((s & 0xff00) >>> 8);
}
} else if(pcm instanceof ShortDirectPCM) {
result = ((ByteBuffer)pcm.sample).get(pos - 44 + pcm.start * 2) & 0xff;
} else if(pcm instanceof FloatPCM) {
short s = (short) (((float[])pcm.sample)[(pos - 44) / 2 + pcm.start] * Short.MAX_VALUE);
if (pos % 2 == 0) {
result = (s & 0x00ff);
} else {
result = ((s & 0xff00) >>> 8);
}
} else if(pcm instanceof BytePCM) {
result = pos % 2 != 0 ? (((byte[])pcm.sample)[(pos - 44) / 2 + pcm.start]) & 0x000000ff : 0;
}
pos++;
}
// System.out.println("read : " + pos + " data : " + result);
return result;
}
}
}
| gpl-3.0 |
vandango/moviematic | MovieMatic/AboutForm.Designer.cs | 6227 | namespace Toenda.MovieMatic {
partial class AboutForm {
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing) {
if(disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent() {
this.lblCopyright = new System.Windows.Forms.Label();
this.lblVersion = new System.Windows.Forms.Label();
this.lblTFLVersion = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.lblInterfaceVersion = new System.Windows.Forms.Label();
this.lblPVersion = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lblCopyright
//
this.lblCopyright.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left ) ) );
this.lblCopyright.AutoSize = true;
this.lblCopyright.ForeColor = System.Drawing.Color.White;
this.lblCopyright.Location = new System.Drawing.Point(12, 122);
this.lblCopyright.Name = "lblCopyright";
this.lblCopyright.Size = new System.Drawing.Size(61, 13);
this.lblCopyright.TabIndex = 2;
this.lblCopyright.Text = "lblCopyright";
this.lblCopyright.Click += new System.EventHandler(this.lblCopyright_Click);
//
// lblVersion
//
this.lblVersion.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left ) ) );
this.lblVersion.AutoSize = true;
this.lblVersion.ForeColor = System.Drawing.Color.White;
this.lblVersion.Location = new System.Drawing.Point(12, 136);
this.lblVersion.Name = "lblVersion";
this.lblVersion.Size = new System.Drawing.Size(52, 13);
this.lblVersion.TabIndex = 3;
this.lblVersion.Text = "lblVersion";
this.lblVersion.Click += new System.EventHandler(this.lblVersion_Click);
//
// lblTFLVersion
//
this.lblTFLVersion.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left ) ) );
this.lblTFLVersion.AutoSize = true;
this.lblTFLVersion.ForeColor = System.Drawing.Color.White;
this.lblTFLVersion.Location = new System.Drawing.Point(12, 165);
this.lblTFLVersion.Name = "lblTFLVersion";
this.lblTFLVersion.Size = new System.Drawing.Size(71, 13);
this.lblTFLVersion.TabIndex = 4;
this.lblTFLVersion.Text = "lblTFLVersion";
this.lblTFLVersion.Click += new System.EventHandler(this.lblTFLVersion_Click);
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.White;
this.panel1.BackgroundImage = global::Toenda.MovieMatic.Properties.Resources.logo;
this.panel1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Location = new System.Drawing.Point(12, 12);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(502, 102);
this.panel1.TabIndex = 0;
this.panel1.Click += new System.EventHandler(this.panel1_Click);
//
// lblInterfaceVersion
//
this.lblInterfaceVersion.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left ) ) );
this.lblInterfaceVersion.AutoSize = true;
this.lblInterfaceVersion.ForeColor = System.Drawing.Color.White;
this.lblInterfaceVersion.Location = new System.Drawing.Point(12, 150);
this.lblInterfaceVersion.Name = "lblInterfaceVersion";
this.lblInterfaceVersion.Size = new System.Drawing.Size(94, 13);
this.lblInterfaceVersion.TabIndex = 5;
this.lblInterfaceVersion.Text = "lblInterfaceVersion";
this.lblInterfaceVersion.Click += new System.EventHandler(this.lblInterfaceVersion_Click);
//
// lblPVersion
//
this.lblPVersion.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left ) ) );
this.lblPVersion.AutoSize = true;
this.lblPVersion.ForeColor = System.Drawing.Color.White;
this.lblPVersion.Location = new System.Drawing.Point(12, 180);
this.lblPVersion.Name = "lblPVersion";
this.lblPVersion.Size = new System.Drawing.Size(59, 13);
this.lblPVersion.TabIndex = 6;
this.lblPVersion.Text = "lblPVersion";
//
// AboutForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.SteelBlue;
this.ClientSize = new System.Drawing.Size(526, 202);
this.Controls.Add(this.lblPVersion);
this.Controls.Add(this.lblInterfaceVersion);
this.Controls.Add(this.lblTFLVersion);
this.Controls.Add(this.lblVersion);
this.Controls.Add(this.lblCopyright);
this.Controls.Add(this.panel1);
this.DoubleBuffered = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "AboutForm";
this.Opacity = 0.95;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "AboutForm";
this.Click += new System.EventHandler(this.AboutForm_Click);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label lblCopyright;
private System.Windows.Forms.Label lblVersion;
private System.Windows.Forms.Label lblTFLVersion;
private System.Windows.Forms.Label lblInterfaceVersion;
private System.Windows.Forms.Label lblPVersion;
}
} | gpl-3.0 |
nil0x42/phpsploit | plugins/file_system/edit/reader.php | 685 | <?php
$mtime = @filemtime($PHPSPLOIT["FILE"]);
// If the file does not exists, the file could be edited for
// creation anyway, so we inform plugin that file does not exists.
if (!@file_exists($PHPSPLOIT['FILE']))
return "NEW_FILE";
// If the path is not a regular file, throw error.
if ((@fileperms($PHPSPLOIT['FILE']) & 0x8000) != 0x8000)
return error("%s: Not a file", $PHPSPLOIT['FILE']);
// Get file contents, or throw error (unreadable file).
if (($data = @file_get_contents($PHPSPLOIT['FILE'])) === False)
return error("%s: Read permission denied", $PHPSPLOIT['FILE']);
// Return the file data (in base64 format)
return array($mtime, base64_encode($data));
?>
| gpl-3.0 |
VB-is-Terrible/Elements | manifest_explicit.py | 3381 | import yaml
import os
class Manifest:
props = ['requires', 'recommends', 'resources', 'css', 'templates',
'provides', 'type']
def __init__(self):
super()
self.requires = None
self.recommends = None
self.resources = None
self.css = None
self.templates = None
self.type = None
self.provides = None
def apply(self, other):
for i in self.props:
if getattr(other, i) is not None:
setattr(self, i, getattr(other, i))
return self
def desugar(self):
result = {}
for i in self.props:
value = getattr(self, i)
if value is None or value == []:
continue
result[i] = value
return result
@staticmethod
def blank():
result = Manifest()
result.requires = []
result.recommends = []
result.resources = []
result.css = []
result.templates = []
result.type = 'module'
result.provides = []
return result
@staticmethod
def sugar(other: dict):
result = Manifest()
for i in Manifest.props:
if i not in other:
continue
setattr(result, i, other[i])
return result
def __repr__(self):
return f'{{requires: {self.requires}, recommends: {self.recommends}, resources: {self.resources}, css: {self.css}, templates: {self.templates}, provides: {self.provides}, type: {self.type}}}'
def read_manifests(dirpath: str):
results = {}
manifest_location = os.path.join(dirpath, 'manifest.yaml')
if not os.path.isfile(manifest_location):
return results
with open(manifest_location) as manifests:
manifest_objs = yaml.load(manifests,
Loader=yaml.loader.BaseLoader)
if manifest_objs is not None:
for key in manifest_objs:
results[key] = Manifest.sugar(
manifest_objs[key])
if '/' in results:
results[''] = results['/']
del results['/']
return results
def read_manifest(dirpath: str, module_name: str):
results = read_manifests(dirpath)
if module_name in results:
return results[module_name]
else:
return Manifest()
def add_explicit_manifests(manifests, dirpath):
explicit = read_manifests(dirpath)
for name in explicit:
if name in manifests:
manifests[name].apply(explicit[name])
else:
manifests[name] = Manifest.blank().apply(explicit[name])
return manifests
def desugar_manifests(manifests):
results = {}
for name in manifests:
results[name] = manifests[name].desugar()
return results
| gpl-3.0 |
yonas/world-population-simulator | src/cpp/main.cpp | 523 | #include <iostream>
#include <fstream>
#include <thread>
#include "world.h"
using namespace std;
// Global world variable, accessed by other classes.
World* world = new World();
int main() {
int initial_world_size = 70;
int total_years = 1000;
// Create the initial conditions.
world->populate(initial_world_size);
// Grow the population, and print the world population to screen every 10 years.
world->age(total_years, 10);
cout << "Total human population: " << world->size() << endl;
}
| gpl-3.0 |
JonSteinn/Kattis-Solutions | src/Bit by Bit/Python 3/bitbybit.py | 873 | from collections import defaultdict
def true(c):
return c == '1'
def false(c):
return c == '0'
def _clear(i, b):
b[i[0]] = '0'
def _set(i, b):
b[i[0]] = '1'
def _or(i, b):
if true(b[i[0]]) or true(b[i[1]]):
b[i[0]] = '1'
elif false(b[i[0]]) and false(b[i[1]]):
b[i[0]] = '0'
else:
del b[i[0]]
def _and(i, b):
if true(b[i[0]]) and true(b[i[1]]):
b[i[0]] = '1'
elif false(b[i[0]]) or false(b[i[1]]):
b[i[0]] = '0'
else:
del b[i[0]]
commands = {"CLEAR": _clear, 'SET': _set, 'OR': _or, 'AND': _and}
while True:
n = int(input())
if n == 0:
break
bits = defaultdict(lambda: '?')
for i in range(n):
s = input().split()
commands[s[0]](list(map(lambda z: int(z), s[1:])), bits)
print("".join([bits[x] for x in reversed(range(32))]))
| gpl-3.0 |
simith/HomeOrAway | app/src/main/java/homeornot/com/au/wifi_homeornot/data/WifiListAdapter.java | 1450 | package homeornot.com.au.wifi_homeornot.data;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import homeornot.com.au.wifi_homeornot.R;
public class WifiListAdapter extends ArrayAdapter<WiFiAp>{
public WifiListAdapter(Context context, int resource, List<WiFiAp> pWiFiApList) {
super(context, 0,pWiFiApList);
}
@Override
public int getCount() {
return super.getCount();
}
@Override
public WiFiAp getItem(int position) {
return super.getItem(position);
}
@Override
public int getPosition(WiFiAp item) {
return super.getPosition(item);
}
@Override
public long getItemId(int position) {
return super.getItemId(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
WiFiAp lWifiAp = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_view, parent, false);
}
// Lookup view for data population
TextView wifiApName = (TextView) convertView.findViewById(R.id.wifiApName);
wifiApName.setText(lWifiAp.getSSID());
// Return the completed view to render on screen
return convertView;
}
} | gpl-3.0 |
renkezuo/util | src/main/java/com/renke/util/db/Obj.java | 474 | package com.renke.util.db;
import com.google.gson.Gson;
public class Obj {
public int total;
public int total1;
public int total2;
public Sub _id;
public static void main(String[] args) {
Gson gs = new Gson();
Obj obj = gs.fromJson("{ \"_id\" : { \"aa\" : NumberLong(918739), \"bb\" : NumberLong(20786) }, \"total1\" : 5, \"total\" : 2, \"total2\" : 2 }", Obj.class);
System.out.println(obj._id.aa);
}
}
class Sub{
public String aa;
public String bb;
} | gpl-3.0 |
cyclestreets/android | libraries/cyclestreets-core/src/main/java/net/cyclestreets/api/Photos.java | 841 | package net.cyclestreets.api;
import org.osmdroid.util.BoundingBox;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Photos implements Iterable<Photo> {
private final List<Photo> photos = new ArrayList<>();
public Photos(List<Photo> photos) {
this.photos.addAll(photos);
}
@Override
public Iterator<Photo> iterator() {
return photos.iterator();
}
/////////////////////////////////////////////////////////////
public static Photos load(final BoundingBox boundingBox) {
return ApiClient.INSTANCE.getPhotos(boundingBox.getLonWest(),
boundingBox.getLatSouth(),
boundingBox.getLonEast(),
boundingBox.getLatNorth());
}
}
| gpl-3.0 |
KineticIsEpic/CadenciiStudio | src/Cadencii/FormVibratoConfig.cs | 22455 | /*
* FormVibratoConfig.cs
* Copyright © 2008-2011 kbinani
*
* This file is part of cadencii.
*
* cadencii is free software; you can redistribute it and/or
* modify it under the terms of the GPLv3 License.
*
* cadencii 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.
*/
#if JAVA
package cadencii;
//INCLUDE-SECTION IMPORT ./ui/java/FormVibratoConfig.java
import java.awt.event.*;
import java.util.*;
import cadencii.*;
import cadencii.apputil.*;
import cadencii.vsq.*;
import cadencii.windows.forms.*;
#else
using System;
using cadencii;
using cadencii.apputil;
using cadencii.vsq;
using cadencii.windows.forms;
using cadencii.java.awt.event_;
using cadencii.java.util;
namespace cadencii
{
using boolean = System.Boolean;
#endif
#if JAVA
public class FormVibratoConfig extends BDialog{
#else
public class FormVibratoConfig : System.Windows.Forms.Form
{
#endif
private VibratoHandle m_vibrato;
private int m_note_length;
/// <summary>
/// コンストラクタ.引数vibrato_handleには,Cloneしたものを渡さなくてよい.
/// </summary>
/// <param name="vibrato_handle"></param>
/// <param name="note_length"></param>
/// <param name="default_vibrato_length"></param>
/// <param name="type"></param>
/// <param name="use_original"></param>
public FormVibratoConfig(
VibratoHandle vibrato_handle,
int note_length,
DefaultVibratoLengthEnum default_vibrato_length,
SynthesizerType type,
boolean use_original )
{
#if JAVA
super();
initialize();
#else
InitializeComponent();
#endif
#if DEBUG
AppManager.debugWriteLine( "FormVibratoConfig.ctor(Vsqhandle,int,DefaultVibratoLength)" );
AppManager.debugWriteLine( " (vibrato_handle==null)=" + (vibrato_handle == null) );
sout.println( " type=" + type );
#endif
if ( use_original ) {
radioUserDefined.Checked = true;
} else {
if ( type == SynthesizerType.VOCALOID1 ) {
radioVocaloid1.Checked = true;
} else {
radioVocaloid2.Checked = true;
}
}
if ( vibrato_handle != null ) {
m_vibrato = (VibratoHandle)vibrato_handle.clone();
}
// 選択肢の状態を更新
updateComboBoxStatus();
// どれを選ぶか?
if( vibrato_handle != null ){
#if DEBUG
sout.println( "FormVibratoConfig#.ctor; vibrato_handle.IconID=" + vibrato_handle.IconID );
#endif
for ( int i = 0; i < comboVibratoType.Items.Count; i++ ) {
VibratoHandle handle = (VibratoHandle)comboVibratoType.Items[i];
#if DEBUG
sout.println( "FormVibratoConfig#.ctor; handle.IconID=" + handle.IconID );
#endif
if ( vibrato_handle.IconID.Equals( handle.IconID ) ) {
comboVibratoType.SelectedIndex = i;
break;
}
}
}
txtVibratoLength.Enabled = (vibrato_handle != null);
if ( vibrato_handle != null ) {
txtVibratoLength.Text = (int)((float)vibrato_handle.getLength() / (float)note_length * 100.0f) + "";
} else {
String s = "";
if ( default_vibrato_length == DefaultVibratoLengthEnum.L100 ) {
s = "100";
} else if ( default_vibrato_length == DefaultVibratoLengthEnum.L50 ) {
s = "50";
} else if ( default_vibrato_length == DefaultVibratoLengthEnum.L66 ) {
s = "66";
} else if ( default_vibrato_length == DefaultVibratoLengthEnum.L75 ) {
s = "75";
}
txtVibratoLength.Text = s;
}
m_note_length = note_length;
registerEventHandlers();
setResources();
applyLanguage();
Util.applyFontRecurse( this, AppManager.editorConfig.getBaseFont() );
}
#region public methods
public void applyLanguage()
{
this.Text = _( "Vibrato property" );
lblVibratoLength.Text = _( "Vibrato length" );
lblVibratoLength.Mnemonic( KeyEvent.VK_L );
lblVibratoType.Text = _( "Vibrato Type" );
lblVibratoType.Mnemonic( KeyEvent.VK_T );
btnOK.Text = _( "OK" );
btnCancel.Text = _( "Cancel" );
groupSelect.Text = _( "Select from" );
}
/// <summary>
/// 編集済みのビブラート設定.既にCloneされているので,改めてCloneしなくて良い
/// </summary>
public VibratoHandle getVibratoHandle()
{
return m_vibrato;
}
#endregion
#region helper methods
private static String _( String id )
{
return Messaging.getMessage( id );
}
/// <summary>
/// ビブラートの選択肢の状態を更新します
/// </summary>
private void updateComboBoxStatus()
{
// 選択位置
int old = comboVibratoType.SelectedIndex;
// 全部削除
comboVibratoType.Items.Clear();
// 「ビブラート無し」を表すアイテムを追加
VibratoHandle empty = new VibratoHandle();
empty.setCaption( "[Non Vibrato]" );
empty.IconID = "$04040000";
comboVibratoType.Items.Add( empty );
// 選択元を元に,選択肢を追加する
if ( radioUserDefined.Checked ) {
// ユーザー定義のを使う場合
int size = AppManager.editorConfig.AutoVibratoCustom.size();
for ( int i = 0; i < size; i++ ) {
VibratoHandle handle = AppManager.editorConfig.AutoVibratoCustom.get( i );
comboVibratoType.Items.Add( handle );
}
} else {
// VOCALOID1/VOCALOID2のシステム定義のを使う場合
SynthesizerType type = radioVocaloid1.Checked ? SynthesizerType.VOCALOID1 : SynthesizerType.VOCALOID2;
for ( Iterator<VibratoHandle> itr = VocaloSysUtil.vibratoConfigIterator( type ); itr.hasNext(); ) {
VibratoHandle vconfig = itr.next();
comboVibratoType.Items.Add( vconfig );
}
}
// 選択位置を戻せるなら戻す
int index = old;
if ( index >= comboVibratoType.Items.Count ) {
index = comboVibratoType.Items.Count - 1;
}
if ( 0 <= index ) {
comboVibratoType.SelectedIndex = index;
}
}
private void registerEventHandlers()
{
btnOK.Click += new EventHandler( btnOK_Click );
btnCancel.Click += new EventHandler( btnCancel_Click );
radioUserDefined.CheckedChanged += new EventHandler( handleRadioCheckedChanged );
comboVibratoType.SelectedIndexChanged += new EventHandler( comboVibratoType_SelectedIndexChanged );
txtVibratoLength.TextChanged += new EventHandler( txtVibratoLength_TextChanged );
}
public void handleRadioCheckedChanged( Object sender, EventArgs e )
{
comboVibratoType.SelectedIndexChanged -= new EventHandler( comboVibratoType_SelectedIndexChanged );
updateComboBoxStatus();
comboVibratoType.SelectedIndexChanged += new EventHandler( comboVibratoType_SelectedIndexChanged );
}
private void setResources()
{
}
#endregion
#region event handlers
public void btnOK_Click( Object sender, EventArgs e )
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
public void comboVibratoType_SelectedIndexChanged( Object sender, EventArgs e )
{
int index = comboVibratoType.SelectedIndex;
#if DEBUG
sout.println( "FormVibratoConfig#comboVibratoType_SelectedIndexChanged; index=" + index );
#endif
if ( index >= 0 ) {
String s = ((VibratoHandle)comboVibratoType.Items[index]).IconID;
#if DEBUG
sout.println( "FormVibratoConfig#comboVibratoType_SelectedIndexChanged; index=" + index + "; iconid=" + s );
#endif
if ( s.Equals( "$04040000" ) ) {
#if DEBUG
sout.println( "FormVibratoConfig#comboVibratoType_SelectedIndexChanged; B; m_vibrato -> null" );
#endif
m_vibrato = null;
txtVibratoLength.Enabled = false;
return;
} else {
txtVibratoLength.Enabled = true;
VibratoHandle src = null;
if ( radioUserDefined.Checked ) {
int size = AppManager.editorConfig.AutoVibratoCustom.Count;
for ( int i = 0; i < size; i++ ) {
VibratoHandle handle = AppManager.editorConfig.AutoVibratoCustom[i];
if ( s == handle.IconID ) {
src = handle;
break;
}
}
} else {
SynthesizerType type = radioVocaloid1.Checked ? SynthesizerType.VOCALOID1 : SynthesizerType.VOCALOID2;
for ( Iterator<VibratoHandle> itr = VocaloSysUtil.vibratoConfigIterator( type ); itr.hasNext(); ) {
VibratoHandle vconfig = itr.next();
if ( s == vconfig.IconID ) {
src = vconfig;
break;
}
}
}
#if DEBUG
sout.println( "FormVibratoConfig#comboVibratoType_SelectedIndexChanged; (src==null)=" + (src == null) );
#endif
if ( src != null ) {
int percent;
try {
percent = int.Parse( txtVibratoLength.Text );
} catch ( Exception ex ) {
return;
}
m_vibrato = (VibratoHandle)src.clone();
m_vibrato.setLength( (int)(m_note_length * percent / 100.0f) );
return;
}
}
}
}
public void txtVibratoLength_TextChanged( Object sender, EventArgs e )
{
#if DEBUG
AppManager.debugWriteLine( "txtVibratoLength_TextChanged" );
AppManager.debugWriteLine( " (m_vibrato==null)=" + (m_vibrato == null) );
#endif
int percent = 0;
try {
percent = int.Parse( txtVibratoLength.Text );
if ( percent < 0 ) {
percent = 0;
} else if ( 100 < percent ) {
percent = 100;
}
} catch ( Exception ex ) {
return;
}
if ( percent == 0 ) {
m_vibrato = null;
#if DEBUG
sout.println( "FormVibratoConfig#txtVibratoLength_TextChanged; A; m_vibrato -> null" );
#endif
txtVibratoLength.Enabled = false;
} else {
if ( m_vibrato != null ) {
int new_length = (int)(m_note_length * percent / 100.0f);
m_vibrato.setLength( new_length );
}
}
}
public void btnCancel_Click( Object sender, EventArgs e )
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
}
#endregion
#if JAVA
#region UI Impl for Java
//INCLUDE-SECTION FIELD ./ui/java/FormVibratoConfig.java
//INCLUDE-SECTION METHOD ./ui/java/FormVibratoConfig.java
#endregion
#else
#region UI Impl for C#
/// <summary>
/// 必要なデザイナ変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
protected override void Dispose( boolean disposing )
{
if ( disposing && (components != null) ) {
components.Dispose();
}
base.Dispose( disposing );
}
#region Windows フォーム デザイナで生成されたコード
/// <summary>
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.lblVibratoLength = new System.Windows.Forms.Label();
this.lblVibratoType = new System.Windows.Forms.Label();
this.txtVibratoLength = new cadencii.NumberTextBox();
this.label3 = new System.Windows.Forms.Label();
this.comboVibratoType = new System.Windows.Forms.ComboBox();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.groupSelect = new System.Windows.Forms.GroupBox();
this.radioUserDefined = new System.Windows.Forms.RadioButton();
this.radioVocaloid2 = new System.Windows.Forms.RadioButton();
this.radioVocaloid1 = new System.Windows.Forms.RadioButton();
this.groupSelect.SuspendLayout();
this.SuspendLayout();
//
// lblVibratoLength
//
this.lblVibratoLength.AutoSize = true;
this.lblVibratoLength.Location = new System.Drawing.Point( 12, 15 );
this.lblVibratoLength.Name = "lblVibratoLength";
this.lblVibratoLength.Size = new System.Drawing.Size( 94, 12 );
this.lblVibratoLength.TabIndex = 0;
this.lblVibratoLength.Text = "Vibrato Length(&L)";
//
// lblVibratoType
//
this.lblVibratoType.AutoSize = true;
this.lblVibratoType.Location = new System.Drawing.Point( 12, 39 );
this.lblVibratoType.Name = "lblVibratoType";
this.lblVibratoType.Size = new System.Drawing.Size( 86, 12 );
this.lblVibratoType.TabIndex = 1;
this.lblVibratoType.Text = "Vibrato Type(&T)";
//
// txtVibratoLength
//
this.txtVibratoLength.Enabled = false;
this.txtVibratoLength.Location = new System.Drawing.Point( 143, 12 );
this.txtVibratoLength.Name = "txtVibratoLength";
this.txtVibratoLength.Size = new System.Drawing.Size( 61, 19 );
this.txtVibratoLength.TabIndex = 2;
this.txtVibratoLength.Type = cadencii.NumberTextBox.ValueType.Integer;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point( 210, 15 );
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size( 49, 12 );
this.label3.TabIndex = 3;
this.label3.Text = "%(0-100)";
//
// comboVibratoType
//
this.comboVibratoType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboVibratoType.FormattingEnabled = true;
this.comboVibratoType.Location = new System.Drawing.Point( 143, 36 );
this.comboVibratoType.Name = "comboVibratoType";
this.comboVibratoType.Size = new System.Drawing.Size( 167, 20 );
this.comboVibratoType.TabIndex = 4;
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point( 240, 129 );
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size( 75, 23 );
this.btnCancel.TabIndex = 7;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Location = new System.Drawing.Point( 159, 129 );
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size( 75, 23 );
this.btnOK.TabIndex = 6;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
//
// groupSelect
//
this.groupSelect.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupSelect.Controls.Add( this.radioUserDefined );
this.groupSelect.Controls.Add( this.radioVocaloid2 );
this.groupSelect.Controls.Add( this.radioVocaloid1 );
this.groupSelect.Location = new System.Drawing.Point( 14, 61 );
this.groupSelect.Name = "groupSelect";
this.groupSelect.Size = new System.Drawing.Size( 301, 55 );
this.groupSelect.TabIndex = 9;
this.groupSelect.TabStop = false;
this.groupSelect.Text = "Select from";
//
// radioUserDefined
//
this.radioUserDefined.AutoSize = true;
this.radioUserDefined.Location = new System.Drawing.Point( 198, 21 );
this.radioUserDefined.Name = "radioUserDefined";
this.radioUserDefined.Size = new System.Drawing.Size( 88, 16 );
this.radioUserDefined.TabIndex = 11;
this.radioUserDefined.TabStop = true;
this.radioUserDefined.Text = "User defined";
this.radioUserDefined.UseVisualStyleBackColor = true;
//
// radioVocaloid2
//
this.radioVocaloid2.AutoSize = true;
this.radioVocaloid2.Checked = true;
this.radioVocaloid2.Location = new System.Drawing.Point( 106, 21 );
this.radioVocaloid2.Name = "radioVocaloid2";
this.radioVocaloid2.Size = new System.Drawing.Size( 86, 16 );
this.radioVocaloid2.TabIndex = 10;
this.radioVocaloid2.TabStop = true;
this.radioVocaloid2.Text = "VOCALOID2";
this.radioVocaloid2.UseVisualStyleBackColor = true;
//
// radioVocaloid1
//
this.radioVocaloid1.AutoSize = true;
this.radioVocaloid1.Location = new System.Drawing.Point( 14, 21 );
this.radioVocaloid1.Name = "radioVocaloid1";
this.radioVocaloid1.Size = new System.Drawing.Size( 86, 16 );
this.radioVocaloid1.TabIndex = 9;
this.radioVocaloid1.TabStop = true;
this.radioVocaloid1.Text = "VOCALOID1";
this.radioVocaloid1.UseVisualStyleBackColor = true;
//
// FormVibratoConfig
//
this.AcceptButton = this.btnOK;
this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 12F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size( 327, 164 );
this.Controls.Add( this.groupSelect );
this.Controls.Add( this.btnOK );
this.Controls.Add( this.btnCancel );
this.Controls.Add( this.comboVibratoType );
this.Controls.Add( this.label3 );
this.Controls.Add( this.txtVibratoLength );
this.Controls.Add( this.lblVibratoType );
this.Controls.Add( this.lblVibratoLength );
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FormVibratoConfig";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Vibrato property";
this.groupSelect.ResumeLayout( false );
this.groupSelect.PerformLayout();
this.ResumeLayout( false );
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblVibratoLength;
private System.Windows.Forms.Label lblVibratoType;
private NumberTextBox txtVibratoLength;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox comboVibratoType;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.GroupBox groupSelect;
private System.Windows.Forms.RadioButton radioVocaloid2;
private System.Windows.Forms.RadioButton radioVocaloid1;
private System.Windows.Forms.RadioButton radioUserDefined;
#endregion
#endif
}
#if !JAVA
}
#endif
| gpl-3.0 |
getconverge/converge-1.x | modules/converge-war/src/main/java/dk/i2m/converge/jsf/beans/administrator/UserConfiguration.java | 13702 | /*
* Copyright (C) 2011 Interactive Media Management
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package dk.i2m.converge.jsf.beans.administrator;
import dk.i2m.converge.core.ConfigurationKey;
import dk.i2m.converge.ejb.facades.SystemFacadeLocal;
import dk.i2m.converge.ejb.services.ConfigurationServiceLocal;
import dk.i2m.jsf.JsfUtils;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.event.ActionEvent;
/**
* Backing bean for {@code /administrator/UserConfiguration.jspx}.
*
* @author Allan Lykke Christensen
*/
public class UserConfiguration {
@EJB private ConfigurationServiceLocal cfgService;
@EJB private SystemFacadeLocal systemFacade;
private String ldapConnectionFactory;
private String ldapProviderUrl;
private String ldapConnectTimeout;
private String ldapReadTimeout;
private String ldapSecurityPrincipal;
private String ldapSecurityCredentials;
private String ldapSecurityAuthentication;
private String ldapBase;
private String ldapGroupUsers;
private String ldapGroupAdministrators;
private String ldapUserMappingUsername;
private String ldapUserMappingFirstName;
private String ldapUserMappingLastName;
private String ldapUserMappingCommonName;
private String ldapUserMappingJobTitle;
private String ldapUserMappingOrganisation;
private String ldapUserMappingMobile;
private String ldapUserMappingPhone;
private String ldapUserMappingEmail;
private String ldapUserMappingLanguage;
private String ldapUserMappingJpegPhoto;
private String ldapGroupMappingName;
private String ldapGroupMappingMemberOf;
@PostConstruct
public void onInit() {
setLdapBase(systemFacade.getProperty(ConfigurationKey.LDAP_BASE));
setLdapConnectTimeout(systemFacade.getProperty(
ConfigurationKey.LDAP_CONNECT_TIMEOUT));
setLdapConnectionFactory(systemFacade.getProperty(
ConfigurationKey.LDAP_CONNECTION_FACTORY));
setLdapGroupAdministrators(systemFacade.getProperty(
ConfigurationKey.LDAP_GROUP_ADMINISTRATORS));
setLdapGroupMappingMemberOf(systemFacade.getProperty(
ConfigurationKey.LDAP_GROUP_MAPPING_MEMBEROF));
setLdapGroupMappingName(systemFacade.getProperty(
ConfigurationKey.LDAP_GROUP_MAPPING_NAME));
setLdapGroupUsers(systemFacade.getProperty(
ConfigurationKey.LDAP_GROUP_USERS));
setLdapProviderUrl(systemFacade.getProperty(
ConfigurationKey.LDAP_PROVIDER_URL));
setLdapReadTimeout(systemFacade.getProperty(
ConfigurationKey.LDAP_READ_TIMEOUT));
setLdapSecurityAuthentication(systemFacade.getProperty(
ConfigurationKey.LDAP_SECURITY_AUTHENTICATION));
setLdapSecurityCredentials(systemFacade.getProperty(
ConfigurationKey.LDAP_SECURITY_CREDENTIALS));
setLdapSecurityPrincipal(systemFacade.getProperty(
ConfigurationKey.LDAP_SECURITY_PRINCIPAL));
setLdapUserMappingCommonName(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_COMMON_NAME));
setLdapUserMappingEmail(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_EMAIL));
setLdapUserMappingFirstName(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_FIRST_NAME));
setLdapUserMappingJobTitle(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_JOB_TITLE));
setLdapUserMappingJpegPhoto(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_JPEG_PHOTO));
setLdapUserMappingLanguage(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_LANGUAGE));
setLdapUserMappingLastName(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_LAST_NAME));
setLdapUserMappingMobile(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_MOBILE));
setLdapUserMappingOrganisation(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_ORGANISATION));
setLdapUserMappingPhone(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_PHONE));
setLdapUserMappingUsername(systemFacade.getProperty(
ConfigurationKey.LDAP_USER_MAPPING_USERNAME));
}
public void onSaveLdapSettings(ActionEvent event) {
cfgService.set(ConfigurationKey.LDAP_BASE, ldapBase);
cfgService.set(ConfigurationKey.LDAP_CONNECT_TIMEOUT, ldapConnectTimeout);
cfgService.set(ConfigurationKey.LDAP_CONNECTION_FACTORY,
ldapConnectionFactory);
cfgService.set(ConfigurationKey.LDAP_GROUP_ADMINISTRATORS,
ldapGroupAdministrators);
cfgService.set(ConfigurationKey.LDAP_GROUP_USERS, ldapGroupUsers);
cfgService.set(ConfigurationKey.LDAP_PROVIDER_URL, ldapProviderUrl);
cfgService.set(ConfigurationKey.LDAP_READ_TIMEOUT, ldapReadTimeout);
cfgService.set(ConfigurationKey.LDAP_SECURITY_AUTHENTICATION,
ldapSecurityAuthentication);
cfgService.set(ConfigurationKey.LDAP_SECURITY_CREDENTIALS,
ldapSecurityCredentials);
cfgService.set(ConfigurationKey.LDAP_SECURITY_PRINCIPAL,
ldapSecurityPrincipal);
JsfUtils.createMessage("frmUserConfiguration",
FacesMessage.SEVERITY_INFO, "i18n",
"administrator_UserConfiguration_LDAP_SETTINGS_SAVED", null);
}
public void onSaveLdapFieldMappings(ActionEvent event) {
cfgService.set(ConfigurationKey.LDAP_GROUP_MAPPING_MEMBEROF,
ldapGroupMappingMemberOf);
cfgService.set(ConfigurationKey.LDAP_GROUP_MAPPING_NAME,
ldapGroupMappingName);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_COMMON_NAME,
ldapUserMappingCommonName);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_EMAIL,
ldapUserMappingEmail);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_FIRST_NAME,
ldapUserMappingFirstName);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_JOB_TITLE,
ldapUserMappingJobTitle);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_JPEG_PHOTO,
ldapUserMappingJpegPhoto);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_LANGUAGE,
ldapUserMappingLanguage);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_LAST_NAME,
ldapUserMappingLastName);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_MOBILE,
ldapUserMappingMobile);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_ORGANISATION,
ldapUserMappingOrganisation);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_PHONE,
ldapUserMappingPhone);
cfgService.set(ConfigurationKey.LDAP_USER_MAPPING_USERNAME,
ldapUserMappingUsername);
JsfUtils.createMessage("frmUserConfiguration",
FacesMessage.SEVERITY_INFO, "i18n",
"administrator_UserConfiguration_LDAP_FIELD_MAPPINGS_SAVED",
null);
}
public String getLdapBase() {
return ldapBase;
}
public void setLdapBase(String ldapBase) {
this.ldapBase = ldapBase;
}
public String getLdapConnectTimeout() {
return ldapConnectTimeout;
}
public void setLdapConnectTimeout(String ldapConnectTimeout) {
this.ldapConnectTimeout = ldapConnectTimeout;
}
public String getLdapConnectionFactory() {
return ldapConnectionFactory;
}
public void setLdapConnectionFactory(String ldapConnectionFactory) {
this.ldapConnectionFactory = ldapConnectionFactory;
}
public String getLdapGroupAdministrators() {
return ldapGroupAdministrators;
}
public void setLdapGroupAdministrators(String ldapGroupAdministrators) {
this.ldapGroupAdministrators = ldapGroupAdministrators;
}
public String getLdapGroupMappingMemberOf() {
return ldapGroupMappingMemberOf;
}
public void setLdapGroupMappingMemberOf(String ldapGroupMappingMemberOf) {
this.ldapGroupMappingMemberOf = ldapGroupMappingMemberOf;
}
public String getLdapGroupMappingName() {
return ldapGroupMappingName;
}
public void setLdapGroupMappingName(String ldapGroupMappingName) {
this.ldapGroupMappingName = ldapGroupMappingName;
}
public String getLdapGroupUsers() {
return ldapGroupUsers;
}
public void setLdapGroupUsers(String ldapGroupUsers) {
this.ldapGroupUsers = ldapGroupUsers;
}
public String getLdapProviderUrl() {
return ldapProviderUrl;
}
public void setLdapProviderUrl(String ldapProviderUrl) {
this.ldapProviderUrl = ldapProviderUrl;
}
public String getLdapReadTimeout() {
return ldapReadTimeout;
}
public void setLdapReadTimeout(String ldapReadTimeout) {
this.ldapReadTimeout = ldapReadTimeout;
}
public String getLdapSecurityAuthentication() {
return ldapSecurityAuthentication;
}
public void setLdapSecurityAuthentication(String ldapSecurityAuthentication) {
this.ldapSecurityAuthentication = ldapSecurityAuthentication;
}
public String getLdapSecurityCredentials() {
return ldapSecurityCredentials;
}
public void setLdapSecurityCredentials(String ldapSecurityCredentials) {
this.ldapSecurityCredentials = ldapSecurityCredentials;
}
public String getLdapSecurityPrincipal() {
return ldapSecurityPrincipal;
}
public void setLdapSecurityPrincipal(String ldapSecurityPrincipal) {
this.ldapSecurityPrincipal = ldapSecurityPrincipal;
}
public String getLdapUserMappingCommonName() {
return ldapUserMappingCommonName;
}
public void setLdapUserMappingCommonName(String ldapUserMappingCommonName) {
this.ldapUserMappingCommonName = ldapUserMappingCommonName;
}
public String getLdapUserMappingEmail() {
return ldapUserMappingEmail;
}
public void setLdapUserMappingEmail(String ldapUserMappingEmail) {
this.ldapUserMappingEmail = ldapUserMappingEmail;
}
public String getLdapUserMappingFirstName() {
return ldapUserMappingFirstName;
}
public void setLdapUserMappingFirstName(String ldapUserMappingFirstName) {
this.ldapUserMappingFirstName = ldapUserMappingFirstName;
}
public String getLdapUserMappingJobTitle() {
return ldapUserMappingJobTitle;
}
public void setLdapUserMappingJobTitle(String ldapUserMappingJobTitle) {
this.ldapUserMappingJobTitle = ldapUserMappingJobTitle;
}
public String getLdapUserMappingJpegPhoto() {
return ldapUserMappingJpegPhoto;
}
public void setLdapUserMappingJpegPhoto(String ldapUserMappingJpegPhoto) {
this.ldapUserMappingJpegPhoto = ldapUserMappingJpegPhoto;
}
public String getLdapUserMappingLanguage() {
return ldapUserMappingLanguage;
}
public void setLdapUserMappingLanguage(String ldapUserMappingLanguage) {
this.ldapUserMappingLanguage = ldapUserMappingLanguage;
}
public String getLdapUserMappingLastName() {
return ldapUserMappingLastName;
}
public void setLdapUserMappingLastName(String ldapUserMappingLastName) {
this.ldapUserMappingLastName = ldapUserMappingLastName;
}
public String getLdapUserMappingMobile() {
return ldapUserMappingMobile;
}
public void setLdapUserMappingMobile(String ldapUserMappingMobile) {
this.ldapUserMappingMobile = ldapUserMappingMobile;
}
public String getLdapUserMappingOrganisation() {
return ldapUserMappingOrganisation;
}
public void setLdapUserMappingOrganisation(
String ldapUserMappingOrganisation) {
this.ldapUserMappingOrganisation = ldapUserMappingOrganisation;
}
public String getLdapUserMappingPhone() {
return ldapUserMappingPhone;
}
public void setLdapUserMappingPhone(String ldapUserMappingPhone) {
this.ldapUserMappingPhone = ldapUserMappingPhone;
}
public String getLdapUserMappingUsername() {
return ldapUserMappingUsername;
}
public void setLdapUserMappingUsername(String ldapUserMappingUsername) {
this.ldapUserMappingUsername = ldapUserMappingUsername;
}
}
| gpl-3.0 |
BoostedColliderAnalysis/BoCA | boca/identification/Id.hh | 2966 | /**
* Copyright (C) 2015-2016 Jan Hajer
*/
#pragma once
#include <string>
#include <vector>
#include "boca/units/ElectronVolt.hh"
/**
* @ingroup Boca
* @brief Boosted Collider %Analysis
*
*/
namespace boca
{
/**
* @brief PDG particle naming conventions
*
*/
enum class Id
{
none = 0,
down = 1, ///< Down Quark
up = 2, ///< Up Quark
strange = 3, ///< Strange Quark
charm = 4, ///< Charm Quark
bottom = 5, ///< Bottom Quark
top = 6, ///< Top Quark
bottom_partner = 7, ///< Bottom Partner Quark
top_partner = 8, ///< Top Partner Quark
electron = 11, ///< %Electron
electron_neutrino = 12,
muon = 13,
muon_neutrino = 14,
tau = 15,
tau_neutrino = 16,
tau_partner = 17,
tau_neutrino_partner = 18,
gluon = 21,
photon = 22,
Z = 23,
W = 24,
higgs = 25, ///< Higgs boson
Z_partner = 32,
Z_partner_2 = 33,
W_partner = 34,
heavy_higgs = 35,
CP_odd_higgs = 36,
charged_higgs = 37,
any = 86,
isr = 87,
marker = 88,
mixed_jet = 90,
cluster = 91,
string = 92,
pi0 = 111,
rho0 = 113,
K0l = 130,
pion = 211,
rho = 213,
eta = 221,
omega = 223,
K0s = 310,
K0 = 311,
K0S = 313,
K = 321,
KS = 323,
etaP = 331,
Dpm = 411,
DS = 413,
DS2 = 415,
D0 = 421,
DS0 = 423,
etac = 441,
B0 = 511,
B0S = 513,
Bpm = 521,
BS = 523,
BS0 = 531,
BsS0 = 533,
ypsilon = 553,
down_down_1 = 1103,
up_down_0 = 2101,
up_down_1 = 2103,
Delta = 1114,
neutron = 2112,
up_up_1 = 2203,
proton = 2212,
Delta_2 = 2224,
CP_violating_higgs = 5000000,
higgs_coupling = 9010221
};
/**
* @brief Name of a particle with given PDG number
*
*/
std::string Name(int id);
/**
* @brief Name of a particle with given Id
*
*/
std::string Name(Id id);
/**
* @brief Stream the name of a particle with given Id
*
*/
std::ostream& operator<<(std::ostream & stream, Id id);
/**
* @brief Mass of particle with given Id
*
*/
Mass MassOf(Id id);
/**
* @brief Groups of PDG particles
*
*/
enum class MultiId
{
quark,
five_quark,
charged_lepton,
neutrino,
neutral_boson, ///< Multi particle containing neutral bosons
bosons ///< Multi particle containing bosons
};
/**
* @brief Names of PDG particle groups
*
*/
std::string Name(MultiId multi_id);
/**
* @brief Stream the name of a particle with given MultiId
*
*/
std::ostream& operator<<(std::ostream & stream, MultiId id);
/**
* @brief Common mass of a multi particle
*
*/
Mass MassOf(MultiId multi_id);
/**
* @brief Vector if PDG particle Ids for a given MultiId
*
*/
std::vector<Id> Resolve(MultiId multi_id);
/**
* @brief Lightest particle of a given MultiID
*
*/
Id Lightest(MultiId multi_id);
/**
* @brief Heaviest particle of a given MultiId
*
*/
Id Heavyest(MultiId multi_id);
}
| gpl-3.0 |
tor4kichi/ReNaming | ReNaming/Models/RenamePattern/ReplaceRegexRenamePattern.cs | 935 | using System;
using System.Runtime.Serialization;
namespace ReNaming.Models
{
/// <summary>
/// 正規表現による置換リネーム動作
/// </summary>
[DataContract]
public class ReplaceRegexRenamePattern : ReplaceRenamePatternBase
{
[IgnoreDataMember]
private RegexReplaceBehavior _RegexReplaceBehavior;
public RegexReplaceBehavior RegexReplaceBehavior
{
get
{
return _RegexReplaceBehavior
?? (_RegexReplaceBehavior = ReplaceBehavior as RegexReplaceBehavior);
}
}
[IgnoreDataMember]
public String RegexString
{
get { return RegexReplaceBehavior.RegexString; }
set { RegexReplaceBehavior.RegexString = value; }
}
public ReplaceRegexRenamePattern()
: base(new RegexReplaceBehavior())
{
}
}
}
| gpl-3.0 |
obarrilero/s2tbx | s2tbx-spot-reader/src/main/java/org/esa/s2tbx/dataio/spot/SpotViewProductReader.java | 12540 | /*
* Copyright (C) 2014-2015 CS-SI (foss-contact@thor.si.c-s.fr)
* Copyright (C) 2014-2015 CS-Romania (office@c-s.ro)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.s2tbx.dataio.spot;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.s2tbx.dataio.VirtualDirEx;
import org.esa.s2tbx.dataio.metadata.XmlMetadata;
import org.esa.s2tbx.dataio.metadata.XmlMetadataParser;
import org.esa.s2tbx.dataio.metadata.XmlMetadataParserFactory;
import org.esa.s2tbx.dataio.readers.BaseProductReaderPlugIn;
import org.esa.s2tbx.dataio.spot.dimap.SpotConstants;
import org.esa.s2tbx.dataio.spot.dimap.SpotDimapMetadata;
import org.esa.s2tbx.dataio.spot.dimap.SpotViewMetadata;
import org.esa.snap.core.dataio.AbstractProductReader;
import org.esa.snap.core.dataio.ProductReaderPlugIn;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.image.ImageManager;
import org.esa.snap.core.util.TreeNode;
import org.geotools.coverage.grid.io.imageio.geotiff.TiePoint;
import org.geotools.referencing.ReferencingFactoryFinder;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.logging.Logger;
/**
* This product reader is intended for reading SPOTView files
* from compressed archive files or from file system.
* This may be not the official format from Spot Image, but is used by DLR and MERIA.
* There seems to be a precision problem with attaching a CrsGeoCoding using EPSG:3035.
*
* @author Cosmin Cara
*/
public class SpotViewProductReader extends AbstractProductReader {
private ImageInputStream imageInputStream;
private SpotViewMetadata metadata;
private SpotDimapMetadata imageMetadata;
private final Logger logger;
private VirtualDirEx zipDir;
private final Object sharedLock;
static {
XmlMetadataParserFactory.registerParser(SpotDimapMetadata.class, new XmlMetadataParser<SpotDimapMetadata>(SpotDimapMetadata.class));
XmlMetadataParserFactory.registerParser(SpotViewMetadata.class, new XmlMetadataParser<SpotViewMetadata>(SpotViewMetadata.class));
}
protected SpotViewProductReader(ProductReaderPlugIn readerPlugIn) {
super(readerPlugIn);
logger = Logger.getLogger(SpotViewProductReader.class.getName());
sharedLock = new Object();
}
@Override
protected Product readProductNodesImpl() throws IOException {
logger.info("Reading product metadata");
zipDir = ((BaseProductReaderPlugIn)getReaderPlugIn()).getInput(getInput());
File metadataFile = zipDir.getFile(SpotConstants.SPOTVIEW_METADATA_FILE);
File imageMetadataFile = zipDir.getFile(SpotConstants.SPOTSCENE_METADATA_FILE);
if (metadataFile != null) {
metadata = XmlMetadata.create(SpotViewMetadata.class, metadataFile);
}
if (imageMetadataFile != null) {
imageMetadata = XmlMetadata.create(SpotDimapMetadata.class, imageMetadataFile);
}
Product product = null;
if (metadata != null) {
String productName = metadata.getProductName().replace(" ", "_").replace("/", "_");
if (imageMetadata != null && imageMetadata.getProductName() != null) {
productName = imageMetadata.getProductName();
}
product = new Product(productName,
SpotConstants.SPOTVIEW_FORMAT_NAMES[0],
metadata.getRasterWidth(),
metadata.getRasterHeight());
product.setProductReader(this);
//product.setFileLocation(metadataFile);
product.setFileLocation(new File(zipDir.getBasePath()));
product.getMetadataRoot().addElement(metadata.getRootElement());
logger.info("Trying to attach tiepoint geocoding");
initTiePointGeoCoding(product);
if (product.getSceneGeoCoding() == null) {
logger.info("Trying to attach geocoding");
initGeoCoding(product);
}
//initGeoCoding(product, zipDir.getFile("geolayer.bil"), metadata.getGeolayerJavaByteOrder());
logger.info("Reading product bands");
initBands(product);
product.setPreferredTileSize(ImageManager.getPreferredTileSize(product));
initialiseInputStream(zipDir.getFile(SpotConstants.SPOTVIEW_RASTER_FILENAME), metadata.getRasterJavaByteOrder());
product.setModified(false);
}
return product;
}
@Override
protected void readBandRasterDataImpl(int sourceOffsetX, int sourceOffsetY, int sourceWidth, int sourceHeight, int sourceStepX, int sourceStepY, Band destBand, int destOffsetX, int destOffsetY, int destWidth, int destHeight, ProductData destBuffer, ProgressMonitor pm) throws IOException {
final int sourceMaxY = sourceOffsetY + sourceHeight - 1;
Product product = destBand.getProduct();
final int elemSize = destBuffer.getElemSize();
final int bandIndex = product.getBandIndex(destBand.getName());
final long lineSizeInBytes = (long)metadata.getRasterWidth() * (long)metadata.getRasterPixelSize();
int numBands = product.getNumBands();
pm.beginTask("Reading band '" + destBand.getName() + "'...", sourceMaxY - sourceOffsetY);
try {
int destPos = 0;
for (int sourceY = sourceOffsetY; sourceY <= sourceMaxY; sourceY += sourceStepY) {
if (pm.isCanceled()) {
break;
}
synchronized (sharedLock) {
long lineStartPos = sourceY * numBands * lineSizeInBytes + bandIndex * lineSizeInBytes;
imageInputStream.seek(lineStartPos + elemSize * sourceOffsetX);
destBuffer.readFrom(destPos, destWidth, imageInputStream);
destPos += destWidth;
}
pm.worked(1);
}
} finally {
pm.done();
}
}
private void initialiseInputStream(File inputFile, ByteOrder rasterByteOrder) {
try {
imageInputStream = ImageIO.createImageInputStream(inputFile);
imageInputStream.setByteOrder(rasterByteOrder);
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
private void initTiePointGeoCoding(Product product) {
TiePoint[] tiePoints = imageMetadata.getTiePoints();
if (tiePoints != null && tiePoints.length == 4) {
float[] latPoints = new float[tiePoints.length];
float[] lonPoints = new float[tiePoints.length];
for (int i = 0; i < tiePoints.length; i++) {
latPoints[(i != 2 ? (i != 3 ? i : 2) : 3)] = (float) tiePoints[i].getValueAt(4);
lonPoints[(i != 2 ? (i != 3 ? i : 2) : 3)] = (float) tiePoints[i].getValueAt(3);
}
TiePointGrid latGrid = createTiePointGrid("latitude", 2, 2, 0, 0, metadata.getRasterWidth(), metadata.getRasterHeight(), latPoints);
product.addTiePointGrid(latGrid);
TiePointGrid lonGrid = createTiePointGrid("longitude", 2, 2, 0, 0, metadata.getRasterWidth(), metadata.getRasterHeight(), lonPoints);
product.addTiePointGrid(lonGrid);
GeoCoding geoCoding = new TiePointGeoCoding(latGrid, lonGrid);
product.setSceneGeoCoding(geoCoding);
}
}
private void initGeoCoding(Product product) {
try {
String projectionCode = metadata.getProjectionCode();
if (projectionCode != null && projectionCode.startsWith("epsg")) {
CRSAuthorityFactory factory = ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", null);
CoordinateReferenceSystem crs = factory.createProjectedCRS(projectionCode);
if (crs != null) {
AffineTransform transformation = new AffineTransform();
transformation.translate(metadata.getRasterGeoRefY(), metadata.getRasterGeoRefX());
transformation.scale(metadata.getRasterGeoRefSizeX(), -metadata.getRasterGeoRefSizeY());
transformation.rotate(-Math.toRadians(imageMetadata.getOrientation()));
// Why do we need to do this??? Because it seems that the coordinates given were somehow
// offset during processing
transformation.translate(-product.getSceneRasterHeight(), -product.getSceneRasterWidth());
Rectangle rectangle = new Rectangle(metadata.getRasterWidth(), metadata.getRasterHeight());
CrsGeoCoding geoCoding = new CrsGeoCoding(crs, rectangle, transformation);
product.setSceneGeoCoding(geoCoding);
}
}
} catch (FactoryException e) {
e.printStackTrace();
} catch (TransformException e) {
e.printStackTrace();
}
}
private void initBands(Product product) {
final int dataType = metadata.getRasterDataType();
final String[] bandNames = metadata.getBandNames();
for (int i = 0; i < bandNames.length; i++) {
final Band band = new Band(bandNames[i], dataType, product.getSceneRasterWidth(), product.getSceneRasterHeight());
band.setSpectralWavelength(imageMetadata.getWavelength(i));
band.setSpectralBandwidth(imageMetadata.getBandwidth(i));
//band.setScalingOffset(imageMetadata.getScalingOffset(i));
//band.setScalingFactor(imageMetadata.getScalingFactor(i));
band.setNoDataValueUsed(true);
band.setNoDataValue(imageMetadata.getNoDataValue());
product.addBand(band);
}
}
@Override
public TreeNode<File> getProductComponents() {
if (zipDir.isCompressed()) {
return super.getProductComponents();
} else {
TreeNode<File> result = super.getProductComponents();
addProductComponentIfNotPresent(metadata.getFileName(), result);
addProductComponentIfNotPresent(metadata.getGeolayerFileName(), result);
//addProductComponentIfNotPresent(metadata.getRasterFileName(), result);
addProductComponentIfNotPresent(SpotConstants.SPOTSCENE_METADATA_FILE, result);//WARN: it should be imageMetadata.getFileName()
for (String name : imageMetadata.getRasterFileNames())
addProductComponentIfNotPresent(name, result);
return result;
}
}
private void addProductComponentIfNotPresent(String componentId, TreeNode<File> currentComponents) {
try {
File componentFile = zipDir.getFile(componentId);
TreeNode<File> resultComponent = null;
for (TreeNode node : currentComponents.getChildren()) {
if (node.getId().toLowerCase().equals(componentId.toLowerCase())) {
//noinspection unchecked
resultComponent = node;
break;
}
}
if (resultComponent == null) {
resultComponent = new TreeNode<File>(componentId, componentFile);
currentComponents.addChild(resultComponent);
}
} catch (IOException ex) {
logger.warning(ex.getMessage());
}
}
@Override
public void close() throws IOException {
if (imageInputStream != null) {
imageInputStream.close();
}
super.close();
}
}
| gpl-3.0 |
pfedick/winmusik | lib/tests/src/id3tagsaver.cpp | 577 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <ppl7.h>
#include <ppl7-audio.h>
#include <gtest/gtest.h>
#include "libwinmusik3.h"
#include "wmlib-tests.h"
#include <map>
#include "wm_id3tagsaver.h"
namespace {
using namespace de::pfp::winmusik;
class ID3TagSaverTest : public ::testing::Test {
protected:
ID3TagSaverTest() {
if (setlocale(LC_ALL,"")==NULL) {
printf ("setlocale fehlgeschlagen\n");
throw std::exception();
}
}
~ID3TagSaverTest()
{
}
};
TEST_F(ID3TagSaverTest, updateNow) {
}
} // EOF namespace
| gpl-3.0 |
atpshxc/shcoyee | catalog/controller/checkout/checkout.php | 67086 | <?php
class ControllerCheckoutCheckout extends Controller {
private $direct_payments= array('cod','cheque','free_checkout','bank_transfer');
public function index() {
if (!$this->customer->isLogged()) {
$this->session->data['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
$this->redirect($this->url->link('account/login', '', 'SSL'));
}
if ((!$this->cart->hasProducts() && (!isset($this->session->data['vouchers']) || !$this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout')) ) {
$this->redirect($this->url->link('checkout/cart'));
}
if(!isset($this->session->data['checkout_token']))
$this->session->data['checkout_token'] = md5(mt_rand());
$this->data['token'] =$this->session->data['checkout_token'];
$this->log->debug('IlexDebug:: Begin Checkout : '.$this->session->data['checkout_token']);
$this->load_language('checkout/checkout');
$this->document->setTitle($this->language->get('heading_title'));
// Minimum quantity validation
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($this->session->data['cart'] as $key => $quantity) {
$product_2 = explode(':', $key);
if ($product_2[0] == $product['product_id']) {
$product_total += $quantity;
}
}
if ($product['minimum'] > $product_total) {
$this->session->data['error'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
$this->redirect($this->url->link('checkout/cart'));
}
}
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_cart'),
'href' => $this->url->link('checkout/cart'),
'separator' => $this->language->get('text_separator')
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('checkout/checkout', '', 'SSL'),
'separator' => $this->language->get('text_separator')
);
$this->data['cart'] = $this->url->link('checkout/cart');
$this->data['logged'] = $this->customer->isLogged();
$this->data['shipping_required'] = $this->cart->hasShipping();
$this->data['has_address']=1;
if($this->customer->getAddressId()){
$this->data['shipping_address']=$this->shipping_address();
$this->data['shipping_methods']=$this->shipping_method();
}else{
$this->data['has_address']=0;
$this->data['shipping_address']=$this->shipping_new_address();
$this->data['shipping_methods']=$this->default_shipping_method();
}
$this->data['payment_methods']=$this->payment_method();
$this->data['card_methods']=$this->card_method();
$this->data['comment']='';
if (isset($this->session->data['comment'])) {
$this->data['comment']=$this->session->data['comment'];
}
$results = $this->model_setting_extension->getExtensions('total');
$this->data['country_id'] = $this->config->get('config_country_id');
// Modules
$this->data['modules'] = array();
if (isset($results)) {
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status') && file_exists(DIR_APPLICATION . 'controller/total/' . $result['code'] . '.php')) {
$this->data['modules'][] = $this->getChild('total/' . $result['code']);
}
}
}
// $this->data['modules'][] = $this->getChild('total/comment');
$this->data['order_confirm']=$this->confirm();
//$this->data['payment'] =$this->payment();
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
$this->load->model('setting/extension');
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $total_data);
$this->data['totals'] = $total_data;
/*zhangbo endit*/
// $ze_total=0;
// $sp_total=0;
// foreach ($total_data as $total)
// {
// if($this->language->get('text_sub_total')==$total['title'])
// $ze_total=$total['value'];
// }
// foreach($products as $product)
// {
// $sp_total+=$product['quantity'];
// }
// if($ze_total>1000 && $sp_total>1)
// {
// $this->redirect($this->url->link('checkout/cart'));
// }
// $ischeckedclassid=0;
// if(isset($this->session->data['ischeckedclassid']))
// {
// $ischeckedclassid=(int)$this->session->data['ischeckedclassid'];
// }
// if($ischeckedclassid>3 || $ischeckedclassid==0)
// {
// $this->redirect($this->url->link('checkout/cart'));
// }
/*zhangbo endit*/
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/checkout.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/checkout.tpl';
} else {
$this->template = 'default/template/checkout/checkout.tpl';
}
$this->children = array(
'common/column_left',
'common/column_right',
'common/content_top',
'common/content_bottom',
'common/footer',
'common/checkout_header'
);
// print_r($this->session);
// exit;
$this->response->setOutput($this->render());
}
public function shipping_address() {
$this->load_language('checkout/checkout');
$this->load->model('account/address');
$this->data['type'] = 'shipping';
if (isset($this->session->data['shipping_address_id'])) {
$this->data['address_id'] = $this->session->data['shipping_address_id'];
$this->log->debug('IlexDebug:: session : '.$this->session->data['shipping_address_id']);
} else {
$this->data['address_id'] = $this->customer->getAddressId();
$this->session->data['shipping_address_id']=$this->data['address_id'];
$this->log->debug('IlexDebug:: default address_id : '.$this->session->data['shipping_address_id']);
}
$this->data['addresses'] = $this->model_account_address->getAddresses();
$this->data['country_id'] = $this->config->get('config_country_id');
$this->load->model('localisation/country');
$this->data['countries'] = $this->model_localisation_country->getCountries();
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/address.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/address.tpl';
} else {
$this->template = 'default/template/checkout/address.tpl';
}
return $this->render();
}
private function shipping_new_address() {
// $this->load_language('checkout/checkout');
//
// $this->load->model('account/address');
//
// $this->data['type'] = 'shipping';
//
// $this->data['country_id'] = $this->config->get('config_country_id');
//
// $this->load->model('localisation/country');
//
// $this->data['countries'] = $this->model_localisation_country->getCountries();
//
// if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/address_new.tpl')) {
// $this->template = $this->config->get('config_template') . '/template/checkout/address_new.tpl';
// } else {
// $this->template = 'default/template/checkout/address_new.tpl';
// }
//
// return $this->render();
return"您还未添加收货地址,请点击“使用新收货地址”添加。";
}
public function shipping_method() {
$this->load_language('checkout/checkout');
$this->load->model('account/address');
if(isset($this->session->data['shipping_address_id']))
{
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
}else{
$shipping_address = $this->model_account_address->getAddress($this->customer->getAddressId());
}
$this->tax->setZone($shipping_address['country_id'], $shipping_address['zone_id']);
if (!isset($this->session->data['shipping_methods'])) {
$quote_data = array();
$this->load->model('setting/extension');
$results = $this->model_setting_extension->getExtensions('shipping');
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('shipping/' . $result['code']);
$quote = $this->{'model_shipping_' . $result['code']}->getQuote($shipping_address);
if ($quote) {
$quote_data[$result['code']] = array(
'title' => $quote['title'],
'quote' => $quote['quote'],
'description' => $quote['description'],
'sort_order' => $quote['sort_order'],
'error' => $quote['error']
);
}
}
}
$sort_order = array();
foreach ($quote_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $quote_data);
$this->session->data['shipping_methods'] = $quote_data;
}
if (isset($this->session->data['shipping_methods']) && !$this->session->data['shipping_methods']) {
$this->data['error_warning'] = sprintf($this->language->get('error_no_shipping'), $this->url->link('information/contact'));
} else {
$this->data['error_warning'] = '';
}
if (isset($this->session->data['shipping_methods'])) {
$this->data['shipping_methods'] = $this->session->data['shipping_methods'];
} else {
$this->data['shipping_methods'] = array();
}
if (isset($this->session->data['shipping_method']['code'])) {
$this->data['shipping_code'] = $this->session->data['shipping_method']['code'];
$this->customer->setShippingMethod($this->session->data['shipping_method']['code']);
} else {
$this->data['shipping_code'] = $this->customer->getShippingMethod();
$shipping = explode('.', $this->data['shipping_code']);
if(isset($shipping[0])&&isset($shipping[1])){
if(isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]]))
$this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];
else
$this->data['shipping_code']='';
}
}
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/shipping.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/shipping.tpl';
} else {
$this->template = 'default/template/checkout/shipping.tpl';
}
return $this->render();
}
public function default_shipping_method() {
$this->load_language('checkout/checkout');
$shipping_address['country_id']=$this->config->get('config_country_id');
$shipping_address['zone_id']=$this->config->get('config_zone_id');
$this->tax->setZone($shipping_address['country_id'], $shipping_address['zone_id']);
$this->tax->setZone($shipping_address['country_id'], $shipping_address['zone_id']);
$quote_data = array();
$this->load->model('setting/extension');
$results = $this->model_setting_extension->getExtensions('shipping');
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('shipping/' . $result['code']);
$quote = $this->{'model_shipping_' . $result['code']}->getQuote($shipping_address);
if ($quote) {
$quote_data[$result['code']] = array(
'title' => $quote['title'],
'quote' => $quote['quote'],
'description' => $quote['description'],
'sort_order' => $quote['sort_order'],
'error' => $quote['error']
);
}
}
}
$sort_order = array();
foreach ($quote_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $quote_data);
$this->session->data['shipping_methods'] = $quote_data;
$this->data['error_warning'] = '';
if (isset($this->session->data['shipping_methods'])) {
$this->data['shipping_methods'] = $this->session->data['shipping_methods'];
} else {
$this->data['shipping_methods'] = array();
}
if (isset($this->session->data['shipping_method']['code'])) {
$this->data['shipping_code'] = $this->session->data['shipping_method']['code'];
$this->customer->setShippingMethod($this->session->data['shipping_method']['code']);
} else {
$this->data['shipping_code'] = $this->customer->getShippingMethod();
}
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/shipping.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/shipping.tpl';
} else {
$this->template = 'default/template/checkout/shipping.tpl';
}
return $this->render();
}
public function payment_method() {
$this->load_language('checkout/checkout');
$this->load->model('account/address');
if(isset($this->session->data['shipping_address_id']))
$this->session->data['payment_address_id']=$this->session->data['shipping_address_id'];
else
$this->session->data['payment_address_id']=$this->customer->getAddressId();
$payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
$this->load->model('setting/extension');
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
}
// Payment Methods
$method_data = array();
$this->load->model('setting/extension');
$results = $this->model_setting_extension->getExtensions('payment');
/*
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('payment/' . $result['code']);
$method = $this->{'model_payment_' . $result['code']}->getMethod($payment_address, $total);
if ($method )
{
if(isset($this->session->data['ischeckedclassid']))
{
if($this->session->data['ischeckedclassid']==1 || $this->session->data['ischeckedclassid']==2)
{
if($result['code']=='easipay')
{
$method_data[$result['code']] = $method;
}
}else
{
if($result['code']!='easipay')
{
$method_data[$result['code']] = $method;
}
}
}
}
}
}
*/
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('payment/' . $result['code']);
$method = $this->{'model_payment_' . $result['code']}->getMethod($payment_address, $total);
if ($method) {
$method_data[$result['code']] = $method;
}
}
}
$sort_order = array();
foreach ($method_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $method_data);
$this->session->data['payment_methods'] = $method_data;
if (isset($this->session->data['payment_methods']) && !$this->session->data['payment_methods']) {
$this->data['error_warning'] = sprintf($this->language->get('error_no_payment'), $this->url->link('information/contact'));
} else {
$this->data['error_warning'] = '';
}
if (isset($this->session->data['payment_methods'])) {
$this->data['payment_methods'] = $this->session->data['payment_methods'];
} else {
$this->data['payment_methods'] = array();
}
if (isset($this->session->data['payment_method']['code'])) {
$this->data['payment_code'] = $this->session->data['payment_method']['code'];
$this->customer->setPaymentMethod($this->data['payment_code']);
$this->log->debug('IlexDebug:: Checkout payment_method 1 '. $this->data['payment_code']);
} else if($this->customer->getPaymentMethod()!=''){
$this->data['payment_code'] = $this->customer->getPaymentMethod();
$this->log->debug('IlexDebug:: Checkout payment_method 2 '. $this->data['payment_code']);
} else{
$this->data['payment_code']=$this->config->get('config_default_payment');
$this->log->debug('IlexDebug:: Checkout payment_method 3 '. $this->data['payment_code']);
}
$this->session->data['payment_method']['code'] = $this->data['payment_code'] ;
if ($this->config->get('config_checkout_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_checkout_id'));
if ($information_info) {
$this->data['text_agree'] = sprintf($this->language->get('text_agree'), $this->url->link('information/information/info', 'information_id=' . $this->config->get('config_checkout_id'), 'SSL'), $information_info['title'], $information_info['title']);
} else {
$this->data['text_agree'] = '';
}
} else {
$this->data['text_agree'] = '';
}
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/payment.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/payment.tpl';
} else {
$this->template = 'default/template/checkout/payment.tpl';
}
return $this->render();
}
public function card_method()
{
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/card.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/card.tpl';
} else {
$this->template = 'default/template/checkout/card.tpl';
}
return $this->render();
}
public function payment() {
if (isset($this->session->data['payment_method'])) {
$this->data['payment_code'] = $this->session->data['payment_method']['code'];
$this->customer->setPaymentMethod($this->data['payment_code']);
$this->log->debug('IlexDebug:: payment comfirm payment_method '. $this->data['payment_code']);
} else if($this->customer->getPaymentMethod()!=''){
$this->data['payment_code'] = $this->customer->getPaymentMethod();
$this->log->debug('IlexDebug:: payment comfirm 2 getPaymentMethod '. $this->data['payment_code']);
} else{
$this->data['payment_code']=$this->config->get('config_default_payment');
$this->log->debug('IlexDebug:: payment comfirm 3 '. $this->data['payment_code']);
}
//echo $this->data['payment_code'];exit;
return $this->getChild('payment/' . $this->data['payment_code']);
/*
$zb_payment_code='easipay';
foreach($this->session->data['payment_methods'] as $paycode=>$pv)
{
$zb_payment_code=$paycode;
$this->data['payment_code']=$zb_payment_code;
$this->data['payment_method']=$pv['title'];
$this->session->data['payment_code']=$zb_payment_code;
$this->session->data['payment_method']=$pv['title'];
}
return $this->getChild('payment/' . $zb_payment_code);
*/
}
public function confirm()
{
//
if ((!$this->cart->hasProducts() && (!isset($this->session->data['vouchers']) || !$this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$json['redirect'] = $this->url->link('checkout/cart');
}
$this->load->model('account/address');
if ($this->cart->hasShipping()) {
$this->load->model('account/address');
if ($this->customer->isLogged()) {
if(isset($this->session->data['shipping_address_id']))
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
else
$shipping_address = $this->model_account_address->getAddress($this->customer->getAddressId());
} else{
$this->redirect($this->url->link('account/login', '', 'SSL'));
}
if (!isset($shipping_address)) {
$json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
}
if (!isset($this->session->data['shipping_method'])) {
$json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
}
} else {
unset($this->session->data['guest']['shipping']);
unset($this->session->data['shipping_address_id']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
}
$json = array();
if (!$json) {
//张博订单拆分 拆单规则
///拆单--------------------------------------------------------
//删除旧订单
// if(isset($this->session->data['zb_orders']))
// {
// foreach($this->session->data['zb_orders'] as $delorderid)
// {
// $this->deleteorder($delorderid);
// }
// }
///拆单--
$this->cart->check_order();
unset( $this->session->data['zb_cart_orderid']);
unset($this->session->data['zb_orders']);
foreach($this->session->data['orders'] as $key=>$ordirinproducts)
{
$this->session->data['zb_cart_orderid']=$key;
// print_r($this->session->data['orders'][$this->session->data['zb_cart_orderid']]);
// exit;
//
// foreach($product_data as $product)
// {
// $sp_total+=$product['quantity'];
// }
// if($ze_total>1000 && $sp_total>1)
// {
// if(isset($this->data['error_warning']))
// {
// if($this->data['error_warning']=='')
// $this->data['error_warning'] = $this->language->get('error_total');
// else
// $this->data['error_warning'] = $this->data['error_warning'].'<br/>'.$this->language->get('error_total');
// }
// else
// $this->data['error_warning'] = $this->language->get('error_total');
//
// }
//张博订单拆分
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
$this->load->model('setting/extension');
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
$this->log->debug('IlexDebug:: get total data '.$value['code']);
}
array_multisort($sort_order, SORT_ASC, $total_data);
$this->language->load('checkout/checkout');
$data = array();
$data["classid"]=$ordirinproducts[0];
$data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
$data['store_id'] = $this->config->get('config_store_id');
$data['store_name'] = $this->config->get('config_name');
if ($data['store_id']) {
$data['store_url'] = $this->config->get('config_url');
} else {
$data['store_url'] = HTTP_SERVER;
}
if ($this->customer->isLogged()) {
$data['customer_id'] = $this->customer->getId();
$data['customer_group_id'] = $this->customer->getCustomerGroupId();
$data['firstname'] = $this->customer->getFirstName();
$data['lastname'] = $this->customer->getLastName();
$data['email'] = $this->customer->getEmail();
$data['telephone'] = $this->customer->getTelephone();
$data['fax'] = $this->customer->getFax();
$this->load->model('account/address');
if(isset($this->session->data['payment_address_id'])){
$payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
}
} elseif (isset($this->session->data['guest'])) {
$data['customer_id'] = 0;
$data['customer_group_id'] = $this->config->get('config_customer_group_id');
$data['firstname'] = $this->session->data['guest']['firstname'];
$data['lastname'] = $this->session->data['guest']['lastname'];
$data['email'] = $this->session->data['guest']['email'];
$data['telephone'] = $this->session->data['guest']['telephone'];
$data['fax'] = $this->session->data['guest']['fax'];
$payment_address = $this->session->data['guest']['payment'];
}
if(isset($payment_address)){
$data['payment_firstname'] = $payment_address['firstname'];
$data['payment_lastname'] = $payment_address['lastname'];
$data['payment_company'] = $payment_address['company'];
$data['payment_address_1'] = $payment_address['address_1'];
$data['payment_address_2'] = $payment_address['address_2'];
$data['payment_city'] = $payment_address['city'];
$data['payment_postcode'] = $payment_address['postcode'];
$data['payment_zone'] = $payment_address['zone'];
$data['payment_zone_id'] = $payment_address['zone_id'];
$data['payment_country'] = $payment_address['country'];
$data['payment_country_id'] = $payment_address['country_id'];
$data['payment_address_format'] = $payment_address['address_format'];
}else{
$data['payment_firstname'] = '';
$data['payment_lastname'] = '';
$data['payment_company'] = '';
$data['payment_address_1'] = '';
$data['payment_address_2'] = '';
$data['payment_city'] = '';
$data['payment_postcode'] = '';
$data['payment_zone'] = '';
$data['payment_zone_id'] = '';
$data['payment_country'] = '';
$data['payment_country_id'] = '';
$data['payment_address_format'] = '';
}
if (isset($this->session->data['payment_method']['title'])) {
$data['payment_method'] = $this->session->data['payment_method']['title'];
} else {
$data['payment_method'] = $this->customer->getPaymentMethodTitle();
}
if ($this->cart->hasShipping()) {
if ($this->customer->isLogged()) {
$this->load->model('account/address');
if(isset($this->session->data['shipping_address_id']))
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
else
$shipping_address = $this->model_account_address->getAddress($this->customer->getAddressId());
} else{
$this->redirect($this->url->link('account/login', '', 'SSL'));
}
$data['shipping_firstname'] = $shipping_address['firstname'];
$data['shipping_lastname'] = $shipping_address['lastname'];
$data['shipping_mobile'] = $shipping_address['mobile'];
$data['shipping_phone'] = $shipping_address['phone'];
$data['shipping_company'] = $shipping_address['company'];
$data['shipping_address_1'] = $shipping_address['address_1'];
$data['shipping_address_2'] = $shipping_address['address_2'];
$data['shipping_city'] = $shipping_address['city'];
$data['shipping_city_id'] = $shipping_address['city_code'];
$data['shipping_postcode'] = $shipping_address['postcode'];
$data['shipping_zone'] = $shipping_address['zone'];
$data['shipping_zone_id'] = $shipping_address['zone_id'];
$data['shipping_country'] = $shipping_address['country'];
$data['shipping_country_id'] = $shipping_address['country_id'];
$data['shipping_address_format'] = $shipping_address['address_format'];
if (isset($this->session->data['shipping_method']['title'])) {
$data['shipping_method'] = $this->session->data['shipping_method']['title'];
} else {
$data['shipping_method'] = $this->customer->getShippingMethodTitle();
}
} else {
$data['shipping_firstname'] = '';
$data['shipping_lastname'] = '';
$data['shipping_mobile'] ='';
$data['shipping_phone'] = '';
$data['shipping_company'] = '';
$data['shipping_address_1'] = '';
$data['shipping_address_2'] = '';
$data['shipping_city'] = '';
$data['shipping_city_id'] = '';
$data['shipping_postcode'] = '';
$data['shipping_zone'] = '';
$data['shipping_zone_id'] = '';
$data['shipping_country'] = '';
$data['shipping_country_id'] = '';
$data['shipping_address_format'] = '';
$data['shipping_method'] = '';
}
if ($this->cart->hasShipping()) {
$this->tax->setZone($shipping_address['country_id'], $shipping_address['zone_id']);
} else {
$this->tax->setZone($payment_address['country_id'], $payment_address['zone_id']);
}
$product_data = array();
$cart_products=$this->cart->getProducts();
foreach ($cart_products as $product)
{
// if(!$product['ischecked'])
// {
// continue;
// }
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$option_data[] = array(
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'option_id' => $option['option_id'],
'option_value_id' => $option['option_value_id'],
'name' => $option['name'],
'value' => $option['option_value'],
'type' => $option['type']
);
} else {
$this->load->library('encryption');
$encryption = new Encryption($this->config->get('config_encryption'));
$option_data[] = array(
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'option_id' => $option['option_id'],
'option_value_id' => $option['option_value_id'],
'name' => $option['name'],
'value' => $encryption->decrypt($option['option_value']),
'type' => $option['type']
);
}
}
$product_data[] = array(
'product_id' => $product['product_id'],
'classid' => $product['classid'],//zhangbo edit ���ӷ���
'href' => $this->url->link('product/product', '&product_id=' . $product['product_id']),
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'download' => $product['download'],
'quantity' => $product['quantity'],
'subtract' => $product['subtract'],
'price' => $product['price'],
'total' => $product['total'],
'tax' => $product['tax_money']
);
}
// Gift Voucher
if (isset($this->session->data['vouchers']) && $this->session->data['vouchers']) {
foreach ($this->session->data['vouchers'] as $voucher) {
$product_data[] = array(
'product_id' => 0,
'classid' => $product['classid'],//zhangbo edit ���ӷ���
'href' => '#',
'name' => $voucher['description'],
'model' => '',
'option' => array(),
'download' => array(),
'quantity' => 1,
'subtract' => false,
'price' => $voucher['amount'],
'total' => $voucher['total'],
'tax' => $product['tax_money']
);
}
}
$data['products'] = $product_data;
$this->data['products'] = $product_data;
$data['totals'] = $total_data;
if(isset($this->session->data['comment'])){
$data['comment'] = $this->session->data['comment'];
}else{
$data['comment'] = '';
}
$data['total'] = $total;
$data['reward'] = $this->cart->getTotalRewardPoints();
if (isset($this->request->cookie['tracking'])) {
$this->load->model('affiliate/affiliate');
$affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);
if ($affiliate_info) {
$data['affiliate_id'] = $affiliate_info['affiliate_id'];
$data['commission'] = ($total / 100) * $affiliate_info['commission'];
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
$data['language_id'] = $this->config->get('config_language_id');
$data['currency_id'] = $this->currency->getId();
$data['currency_code'] = $this->currency->getCode();
$data['currency_value'] = $this->currency->getValue($this->currency->getCode());
$data['ip'] = $this->request->server['REMOTE_ADDR'];
$this->load->model('checkout/order');
if (isset($this->session->data['payment_method'])) {
$this->data['payment_code'] = $this->session->data['payment_method']['code'];
$this->customer->setPaymentMethod($this->data['payment_code']);
$this->log->debug('IlexDebug:: Checkout comfirm payment_method '. $this->data['payment_code']);
} else if($this->customer->getPaymentMethod()!=''){
$this->data['payment_code'] = $this->customer->getPaymentMethod();
$this->log->debug('IlexDebug:: Checkout comfirm 2 getPaymentMethod '. $this->data['payment_code']);
} else{
$this->data['payment_code']=$this->config->get('config_default_payment');
$this->log->debug('IlexDebug:: Checkout comfirm 3 '. $this->data['payment_code']);
}
$data['payment_code']=$this->data['payment_code'];
/////////////////////////////////创建订单////////////////////////////////////////////////////
$orderid= $this->model_checkout_order->create($data);
if(!isset($this->session->data['zb_orders']))
{
$this->session->data['zb_orders']=array($orderid);
}else
{
$this->session->data['zb_orders'][count($this->session->data['zb_orders'])]=$orderid;
}
// if(!isset($this->session->data['order_id']))
// $this->session->data['order_id'] = $this->model_checkout_order->create($data);
// else
// {
// $this->model_checkout_order->modify($data);
// }
// Gift Voucher
if (isset($this->session->data['vouchers']) && is_array($this->session->data['vouchers'])) {
$this->load->model('checkout/voucher');
foreach ($this->session->data['vouchers'] as $voucher) {
$this->model_checkout_voucher->addVoucher($this->session->data['order_id'], $voucher);
}
}
// Gift Voucher
$this->data['vouchers'] = array();
if (isset($this->session->data['vouchers']) && $this->session->data['vouchers']) {
foreach ($this->session->data['vouchers'] as $key => $voucher) {
$this->data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'])
);
}
}
$this->data['totals'] = $total_data;
if (isset($this->session->data['shipping_method']['title'])) {
$this->data['shipping_method'] = $this->session->data['shipping_method']['title'];
} else {
$this->data['shipping_method'] = $this->customer->getShippingMethodTitle();
}
if (isset($this->session->data['payment_method']['title'])) {
$this->data['payment_method'] = $this->session->data['payment_method']['title'];
} else {
$this->data['payment_method']= $this->customer->getPaymentMethodTitle();
}
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/confirm.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/confirm.tpl';
} else {
$this->template = 'default/template/checkout/confirm.tpl';
}
}
unset( $this->session->data['zb_cart_orderid']);
}
return $this->render();
}
public function update() {
if ((!$this->cart->hasProducts() && (!isset($this->session->data['vouchers']) || !$this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$json['redirect'] = $this->url->link('checkout/cart');
}
$this->load->model('account/address');
if ($this->cart->hasShipping()) {
$this->load->model('account/address');
if ($this->customer->isLogged()) {
if(isset($this->session->data['shipping_address_id']))
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
else
$shipping_address = $this->model_account_address->getAddress($this->customer->getAddressId());
} else{
$this->redirect($this->url->link('account/login', '', 'SSL'));
}
if (!isset($shipping_address)) {
$json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
}
if (!isset($this->session->data['shipping_method'])) {
$json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
}
} else {
unset($this->session->data['guest']['shipping']);
unset($this->session->data['shipping_address_id']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
}
$json = array();
if (!$json) {
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
$this->load->model('setting/extension');
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
$this->log->debug('IlexDebug:: get total data '.$value['code']);
}
array_multisort($sort_order, SORT_ASC, $total_data);
$this->language->load('checkout/checkout');
$data = array();
$data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
$data['store_id'] = $this->config->get('config_store_id');
$data['store_name'] = $this->config->get('config_name');
if ($data['store_id']) {
$data['store_url'] = $this->config->get('config_url');
} else {
$data['store_url'] = HTTP_SERVER;
}
if ($this->customer->isLogged()) {
$data['customer_id'] = $this->customer->getId();
$data['customer_group_id'] = $this->customer->getCustomerGroupId();
$data['firstname'] = $this->customer->getFirstName();
$data['lastname'] = $this->customer->getLastName();
$data['email'] = $this->customer->getEmail();
$data['telephone'] = $this->customer->getTelephone();
$data['fax'] = $this->customer->getFax();
$this->load->model('account/address');
if(isset($this->session->data['payment_address_id'])){
$payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
}
} elseif (isset($this->session->data['guest'])) {
$data['customer_id'] = 0;
$data['customer_group_id'] = $this->config->get('config_customer_group_id');
$data['firstname'] = $this->session->data['guest']['firstname'];
$data['lastname'] = $this->session->data['guest']['lastname'];
$data['email'] = $this->session->data['guest']['email'];
$data['telephone'] = $this->session->data['guest']['telephone'];
$data['fax'] = $this->session->data['guest']['fax'];
$payment_address = $this->session->data['guest']['payment'];
}
if(isset($payment_address)){
$data['payment_firstname'] = $payment_address['firstname'];
$data['payment_lastname'] = $payment_address['lastname'];
$data['payment_company'] = $payment_address['company'];
$data['payment_address_1'] = $payment_address['address_1'];
$data['payment_address_2'] = $payment_address['address_2'];
$data['payment_city'] = $payment_address['city'];
$data['payment_postcode'] = $payment_address['postcode'];
$data['payment_zone'] = $payment_address['zone'];
$data['payment_zone_id'] = $payment_address['zone_id'];
$data['payment_country'] = $payment_address['country'];
$data['payment_country_id'] = $payment_address['country_id'];
$data['payment_address_format'] = $payment_address['address_format'];
}else{
$data['payment_firstname'] = '';
$data['payment_lastname'] = '';
$data['payment_company'] = '';
$data['payment_address_1'] = '';
$data['payment_address_2'] = '';
$data['payment_city'] = '';
$data['payment_postcode'] = '';
$data['payment_zone'] = '';
$data['payment_zone_id'] = '';
$data['payment_country'] = '';
$data['payment_country_id'] = '';
$data['payment_address_format'] = '';
}
if (isset($this->session->data['payment_method']['title'])) {
$data['payment_method'] = $this->session->data['payment_method']['title'];
} else {
$data['payment_method'] = $this->customer->getPaymentMethodTitle();
}
if ($this->cart->hasShipping()) {
if ($this->customer->isLogged()) {
$this->load->model('account/address');
if(isset($this->session->data['shipping_address_id']))
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
else
$shipping_address = $this->model_account_address->getAddress($this->customer->getAddressId());
} else{
$this->redirect($this->url->link('account/login', '', 'SSL'));
}
$data['shipping_firstname'] = $shipping_address['firstname'];
$data['shipping_lastname'] = $shipping_address['lastname'];
$data['shipping_mobile'] = $shipping_address['mobile'];
$data['shipping_phone'] = $shipping_address['phone'];
$data['shipping_company'] = $shipping_address['company'];
$data['shipping_address_1'] = $shipping_address['address_1'];
$data['shipping_address_2'] = $shipping_address['address_2'];
$data['shipping_city'] = $shipping_address['city'];
$data['shipping_city_id'] = $shipping_address['city_code'];
$data['shipping_postcode'] = $shipping_address['postcode'];
$data['shipping_zone'] = $shipping_address['zone'];
$data['shipping_zone_id'] = $shipping_address['zone_id'];
$data['shipping_country'] = $shipping_address['country'];
$data['shipping_country_id'] = $shipping_address['country_id'];
$data['shipping_address_format'] = $shipping_address['address_format'];
if (isset($this->session->data['shipping_method']['title'])) {
$data['shipping_method'] = $this->session->data['shipping_method']['title'];
} else {
$data['shipping_method'] = $this->customer->getShippingMethodTitle();
}
} else {
$data['shipping_firstname'] = '';
$data['shipping_lastname'] = '';
$data['shipping_mobile'] ='';
$data['shipping_phone'] = '';
$data['shipping_company'] = '';
$data['shipping_address_1'] = '';
$data['shipping_address_2'] = '';
$data['shipping_city'] = '';
$data['shipping_city_id'] = '';
$data['shipping_postcode'] = '';
$data['shipping_zone'] = '';
$data['shipping_zone_id'] = '';
$data['shipping_country'] = '';
$data['shipping_country_id'] = '';
$data['shipping_address_format'] = '';
$data['shipping_method'] = '';
}
if ($this->cart->hasShipping()) {
$this->tax->setZone($shipping_address['country_id'], $shipping_address['zone_id']);
} else {
$this->tax->setZone($payment_address['country_id'], $payment_address['zone_id']);
}
$product_data = array();
foreach ($this->cart->getProducts() as $product) {
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$option_data[] = array(
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'option_id' => $option['option_id'],
'option_value_id' => $option['option_value_id'],
'name' => $option['name'],
'value' => $option['option_value'],
'type' => $option['type']
);
} else {
$this->load->library('encryption');
$encryption = new Encryption($this->config->get('config_encryption'));
$option_data[] = array(
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'option_id' => $option['option_id'],
'option_value_id' => $option['option_value_id'],
'name' => $option['name'],
'value' => $encryption->decrypt($option['option_value']),
'type' => $option['type']
);
}
}
$product_data[] = array(
'product_id' => $product['product_id'],
'href' => $this->url->link('product/product', '&product_id=' . $product['product_id']),
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'download' => $product['download'],
'quantity' => $product['quantity'],
'subtract' => $product['subtract'],
'price' => $product['price'],
'total' => $product['total'],
'tax' => $product['tax_money']
);
}
// Gift Voucher
if (isset($this->session->data['vouchers']) && $this->session->data['vouchers']) {
foreach ($this->session->data['vouchers'] as $voucher) {
$product_data[] = array(
'product_id' => 0,
'href' => '#',
'name' => $voucher['description'],
'model' => '',
'option' => array(),
'download' => array(),
'quantity' => 1,
'subtract' => false,
'price' => $voucher['amount'],
'total' => $voucher['amount'],
'tax' => $product['tax_money']
);
}
}
$data['products'] = $product_data;
$this->data['products'] = $product_data;
$data['totals'] = $total_data;
if(isset($this->session->data['comment'])){
$data['comment'] = $this->session->data['comment'];
}else{
$data['comment'] = '';
}
$data['total'] = $total;
$data['reward'] = $this->cart->getTotalRewardPoints();
if (isset($this->request->cookie['tracking'])) {
$this->load->model('affiliate/affiliate');
$affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);
if ($affiliate_info) {
$data['affiliate_id'] = $affiliate_info['affiliate_id'];
$data['commission'] = ($total / 100) * $affiliate_info['commission'];
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
$data['language_id'] = $this->config->get('config_language_id');
$data['currency_id'] = $this->currency->getId();
$data['currency_code'] = $this->currency->getCode();
$data['currency_value'] = $this->currency->getValue($this->currency->getCode());
$data['ip'] = $this->request->server['REMOTE_ADDR'];
$this->load->model('checkout/order');
if (isset($this->session->data['payment_method'])) {
$this->data['payment_code'] = $this->session->data['payment_method']['code'];
$this->customer->setPaymentMethod($this->data['payment_code']);
$this->log->debug('IlexDebug:: Checkout comfirm payment_method '. $this->data['payment_code']);
} else if($this->customer->getPaymentMethod()!=''){
$this->data['payment_code'] = $this->customer->getPaymentMethod();
$this->log->debug('IlexDebug:: Checkout comfirm 2 getPaymentMethod '. $this->data['payment_code']);
} else{
$this->data['payment_code']=$this->config->get('config_default_payment');
$this->log->debug('IlexDebug:: Checkout comfirm 3 '. $this->data['payment_code']);
}
$data['payment_code']=$this->data['payment_code'];
if(!isset($this->session->data['order_id']))
$this->session->data['order_id'] = $this->model_checkout_order->create($data);
else
$this->model_checkout_order->modify($data);
// Gift Voucher
if (isset($this->session->data['vouchers']) && is_array($this->session->data['vouchers'])) {
$this->load->model('checkout/voucher');
foreach ($this->session->data['vouchers'] as $voucher) {
$this->model_checkout_voucher->addVoucher($this->session->data['order_id'], $voucher);
}
}
// Gift Voucher
$this->data['vouchers'] = array();
if (isset($this->session->data['vouchers']) && $this->session->data['vouchers']) {
foreach ($this->session->data['vouchers'] as $key => $voucher) {
$this->data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'])
);
}
}
$this->data['totals'] = $total_data;
if (isset($this->session->data['shipping_method']['title'])) {
$this->data['shipping_method'] = $this->session->data['shipping_method']['title'];
} else {
$this->data['shipping_method'] = $this->customer->getShippingMethodTitle();
}
if (isset($this->session->data['payment_method']['title'])) {
$this->data['payment_method'] = $this->session->data['payment_method']['title'];
} else {
$this->data['payment_method']= $this->customer->getPaymentMethodTitle();
}
}
$this->load->library('json');
$this->response->setOutput(Json::encode($json));
}
public function validate() {
// $this->log('asdf');
$this->load_language('checkout/checkout');
if (!$this->customer->isLogged()) {
$this->session->data['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
$this->redirect($this->url->link('account/login', '', 'SSL'));
}
if($this->request->get['token']==''){
return true;
}
unset($this->session->data['card_info']);
$this->session->data['card_info']=array
(
"card_id"=>"",
"customer_id"=>$this->session->data['customer_id'],
"card_name"=> urldecode($this->request->get['xm']),
"card_code"=>$this->request->get['cd'],
"card_type"=>0,
"card_email"=>$this->request->get['em'],
"card_phone"=>$this->request->get['ph']
);
$this->db->query("DELETE FROM " . DB_PREFIX . "card WHERE customer_id = '" .$this->session->data['customer_id'] . "'");
$this->db->query("INSERT INTO " . DB_PREFIX . "card SET customer_id='".$this->session->data['customer_id']."', card_name='".$this->request->get['xm']."', card_code='".$this->request->get['cd']."', card_type=0, card_phone='".$this->request->get['ph']."', card_email='".$this->request->get['em']."'");
//$file = fopen("createcard_log.txt",'a'); fwrite($file,"INSERT INTO " . DB_PREFIX . "card SET customer_id='".$this->session->data['customer_id']."', card_name='".urldecode($this->request->get['xm'])."', card_code='".$this->request->get['cd']."', card_type=0, card_phone='".$this->request->get['ph']."', card_email='".$this->request->get['em']."'"."\n"); fclose($file);
$json = array();
if(!isset($this->session->data['payment_method']))
$json['error']['warning'] = $this->language->get('error_payment');
if($this->cart->hasShipping()){
if(!isset($this->session->data['shipping_method']))
$json['error']['warning'] = $this->language->get('error_shipping');
if(!isset($this->session->data['shipping_address_id']))
$json['error']['warning'] = $this->language->get('error_address');
}
if(!isset($json['error'])){
$this->load->model('checkout/order');
// added comment to order
/*if ($this->request->server['REQUEST_METHOD'] == 'POST') {
$this->model_checkout_order->updateOrderComment($this->session->data['order_id'],$this->request->post['comment']);
}
*/
//TODO update order status to nonpay
if($this->request->get['token']==$this->session->data['checkout_token']){
if(isset($this->session->data['order_id'])){
if(isset($this->session->data['payment_method']['code']))
{
if(!in_array($this->session->data['payment_method']['code'],$this->direct_payments)){
$this->log->debug('IlexDebug:: Checkout Update updateOrderStatus() : order '.$this->session->data['order_id'] .' payment_method '.$this->session->data['payment_method']['code']);
$this->model_checkout_order->updateOrderStatus($this->session->data['order_id'],$this->config->get('config_order_nopay_status_id'));
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['card_methods']);
unset($this->session->data['guest']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
unset($this->session->data['order_id']);
unset($this->session->data['checkout_token']);
}
}
}
}
}
$this->load->library('json');
$this->response->setOutput(Json::encode($json));
}
public function deleteorder($order_id)
{
$this->db->query("DELETE FROM " . DB_PREFIX . "order WHERE order_id = '" .$order_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" .$order_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "order_option WHERE order_id = '" . $order_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "order_download WHERE order_id = '" . $order_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . $order_id . "'");
}
function getchecked_totle()
{
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
$this->load->model('setting/extension');
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
$this->log->debug('IlexDebug:: get total data '.$value['code']);
}
array_multisort($sort_order, SORT_ASC, $total_data);
return $total_data;
}
function getCheckedProducts()
{$taxes = $this->cart->getTaxes();
$product_data = array();
$this->load->model('tool/image');
foreach ($this->cart->getProducts() as $product) {
$option_data = array();
if ($product['image'])
{
$image = $this->model_tool_image->resize($product['image'], $this->config->get('config_image_cart_width'), $this->config->get('config_image_cart_height'));
} else {
$image = '';
}
if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
$total = $this->currency->format($this->tax->calculate($product['total'], $product['tax_class_id'], $this->config->get('config_tax')));
} else {
$total = false;
}
$tax=$this->tax->getRate($product['tax_class_id'])*$product['price']/100;
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$option_data[] = array(
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'option_id' => $option['option_id'],
'option_value_id' => $option['option_value_id'],
'name' => $option['name'],
'value' => $option['option_value'],
'type' => $option['type']
);
} else {
$this->load->library('encryption');
$encryption = new Encryption($this->config->get('config_encryption'));
$option_data[] = array(
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'option_id' => $option['option_id'],
'option_value_id' => $option['option_value_id'],
'name' => $option['name'],
'value' => $encryption->decrypt($option['option_value']),
'type' => $option['type']
);
}
}
$product_data[] = array(
'product_id' => $product['product_id'],
'href' => $this->url->link('product/product', '&product_id=' . $product['product_id']),
'name' => $product['name'],
'thumb' => $image,
'model' => $product['model'],
'option' => $option_data,
'download' => $product['download'],
'quantity' => $product['quantity'],
'subtract' => $product['subtract'],
'price' => $product['price'],
'total' => $total,
'tax' => $tax
);
}
// Gift Voucher
if (isset($this->session->data['vouchers']) && $this->session->data['vouchers']) {
foreach ($this->session->data['vouchers'] as $voucher) {
$product_data[] = array(
'product_id' => 0,
'href' => '#',
'thumb' => $image,
'name' => $voucher['description'],
'model' => '',
'option' => array(),
'download' => array(),
'quantity' => 1,
'subtract' => false,
'price' => $voucher['amount'],
'total' => $voucher['amount'],
'tax' => $product['tax_money']
);
}
}
return $product_data;
}
//身份证合法性验证
function validation_filter_id_card($id_card)
{
if(strlen($id_card) == 18)
{
return idcard_checksum18($id_card);
}
elseif((strlen($id_card) == 15))
{
$id_card = idcard_15to18($id_card);
return idcard_checksum18($id_card);
}
else
{
return false;
}
}
// 计算身份证校验码,根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base)
{
if(strlen($idcard_base) != 17)
{
return false;
}
//加权因子
$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
//校验码对应值
$verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
$checksum = 0;
for ($i = 0; $i < strlen($idcard_base); $i++)
{
$checksum += substr($idcard_base, $i, 1) * $factor[$i];
}
$mod = $checksum % 11;
$verify_number = $verify_number_list[$mod];
return $verify_number;
}
// 将15位身份证升级到18位
function idcard_15to18($idcard){
if (strlen($idcard) != 15){
return false;
}else{
// 如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码
if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false){
$idcard = substr($idcard, 0, 6) . '18'. substr($idcard, 6, 9);
}else{
$idcard = substr($idcard, 0, 6) . '19'. substr($idcard, 6, 9);
}
}
$idcard = $idcard . idcard_verify_number($idcard);
return $idcard;
}
// 18位身份证校验码有效性检查
function idcard_checksum18($idcard){
if (strlen($idcard) != 18){ return false; }
$idcard_base = substr($idcard, 0, 17);
if (idcard_verify_number($idcard_base) != strtoupper(substr($idcard, 17, 1))){
return false;
}else{
return true;
}
}
}
?> | gpl-3.0 |
modsim/CADET-semi-analytic | include/ModelData.hpp | 2488 | // =============================================================================
// CADET-semi-analytic - The semi analytic extension of
// CADET - The Chromatography Analysis and Design Toolkit
//
// Copyright © 2015-2019: Samuel Leweke¹
//
// ¹ Forschungszentrum Juelich GmbH, IBG-1, Juelich, Germany.
//
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the GNU Public License v3.0 (or, at
// your option, any later version) which accompanies this distribution, and
// is available at http://www.gnu.org/licenses/gpl.html
// =============================================================================
#ifndef CASEMA_MODELDATA_HPP_
#define CASEMA_MODELDATA_HPP_
#include <vector>
#include "CadetEnumeration.hpp"
namespace casema
{
enum ChromatographyUnitType : int
{
GeneralRateModel,
LumpedRateModelWithPores,
LumpedRateModelWithoutPores
};
template <typename real_t>
struct ModelData
{
ChromatographyUnitType modelType;
std::size_t nComponents;
std::vector<real_t> initialLiquidConcentration;
std::vector<real_t> initialSolidConcentration;
real_t colDispersion;
real_t colLength;
real_t colPorosity;
real_t totPorosity;
std::vector<real_t> filmDiffusion;
std::vector<real_t> particleDiffusion;
std::vector<real_t> surfaceDiffusion;
real_t parRadius;
real_t parPorosity;
real_t velocity;
bool kineticBinding;
casema::AdsorptionType bindingModel;
std::vector<real_t> linearKA;
std::vector<real_t> linearKD;
std::size_t nInletSections;
std::vector<real_t> sectionTimes;
std::vector<real_t> constCoeff;
std::vector<real_t> linCoeff;
std::vector<real_t> quadCoeff;
std::vector<real_t> cubicCoeff;
bool writeUserTimes;
std::vector<real_t> outletTimes;
inline real_t totalPorosity() const
{
if (totPorosity < 0.0)
return colPorosity + (real_t(1) - colPorosity) * parPorosity;
else
return totPorosity;
}
};
template <typename real_t>
real_t maxSimulationTime(const ModelData<real_t>& model)
{
if (!model.outletTimes.empty())
{
return max(model.outletTimes[model.outletTimes.size() - 1], model.sectionTimes[model.sectionTimes.size() - 1]);
}
return model.sectionTimes[model.sectionTimes.size() - 1];
}
template <typename real_t>
bool inletIsStep(const ModelData<real_t>& model)
{
// Always true for piecewise polynomials
return true;
}
}
#endif
| gpl-3.0 |
succlz123/DoubanBookLog | src/org/succlz123/doubanbooklog/support/xlistview/me/maxwin/view/XListViewHeader.java | 3682 | /**
* @file XListViewHeader.java
* @create Apr 18, 2012 5:22:27 PM
* @author Maxwin
* @description XListView's header
*/
package org.succlz123.doubanbooklog.support.xlistview.me.maxwin.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.succlz123.doubanbooklog.R;
public class XListViewHeader extends LinearLayout {
private LinearLayout mContainer;
private ImageView mArrowImageView;
private ProgressBar mProgressBar;
private TextView mHintTextView;
private int mState = STATE_NORMAL;
private Animation mRotateUpAnim;
private Animation mRotateDownAnim;
private final int ROTATE_ANIM_DURATION = 180;
public final static int STATE_NORMAL = 0;
public final static int STATE_READY = 1;
public final static int STATE_REFRESHING = 2;
public XListViewHeader(Context context) {
super(context);
initView(context);
}
/**
* @param context
* @param attrs
*/
public XListViewHeader(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
private void initView(Context context) {
// 初始情况,设置下拉刷新view高度为0
LayoutParams lp = new LayoutParams(
LayoutParams.FILL_PARENT, 0);
mContainer = (LinearLayout) LayoutInflater.from(context).inflate(
R.layout.xlistview_header, null);
addView(mContainer, lp);
setGravity(Gravity.BOTTOM);
mArrowImageView = (ImageView)findViewById(R.id.xlistview_header_arrow);
mHintTextView = (TextView)findViewById(R.id.xlistview_header_hint_textview);
mProgressBar = (ProgressBar)findViewById(R.id.xlistview_header_progressbar);
mRotateUpAnim = new RotateAnimation(0.0f, -180.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateUpAnim.setFillAfter(true);
mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateDownAnim.setFillAfter(true);
}
public void setState(int state) {
if (state == mState) return ;
if (state == STATE_REFRESHING) { // 显示进度
mArrowImageView.clearAnimation();
mArrowImageView.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
} else { // 显示箭头图片
mArrowImageView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.INVISIBLE);
}
switch(state){
case STATE_NORMAL:
if (mState == STATE_READY) {
mArrowImageView.startAnimation(mRotateDownAnim);
}
if (mState == STATE_REFRESHING) {
mArrowImageView.clearAnimation();
}
mHintTextView.setText(R.string.xlistview_header_hint_normal);
break;
case STATE_READY:
if (mState != STATE_READY) {
mArrowImageView.clearAnimation();
mArrowImageView.startAnimation(mRotateUpAnim);
mHintTextView.setText(R.string.xlistview_header_hint_ready);
}
break;
case STATE_REFRESHING:
mHintTextView.setText(R.string.xlistview_header_hint_loading);
break;
default:
}
mState = state;
}
public void setVisiableHeight(int height) {
if (height < 0)
height = 0;
LayoutParams lp = (LayoutParams) mContainer
.getLayoutParams();
lp.height = height;
mContainer.setLayoutParams(lp);
}
public int getVisiableHeight() {
return mContainer.getLayoutParams().height;
}
}
| gpl-3.0 |
peterpilgrim/javaee7-developer-handbook | ch02/standalone-owb/src/test/java/je7hb/standalone/ExpensiveCreditProcessorTest.java | 1392 | /*******************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013,2014 by Peter Pilgrim, Addiscombe, Surrey, XeNoNiQUe UK
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU GPL v3.0
* which accompanies this distribution, and is available at:
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Developers:
* Peter Pilgrim -- design, development and implementation
* -- Blog: http://www.xenonique.co.uk/blog/
* -- Twitter: @peter_pilgrim
*
* Contributors:
*
*******************************************************************************/
package je7hb.standalone;
import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import static org.junit.Assert.assertNotNull;
/**
* A unit test CreditProcessorTest to verify the operation of CreditProcessorTest
*
* @author Peter Pilgrim
*/
@RunWith(CdiTestRunner.class)
public class ExpensiveCreditProcessorTest {
@Inject @Premium private CreditProcessor agent;
@Test
public void shouldInjectExpensiveCredit() {
assertNotNull(agent);
agent.check("12345678");
System.out.printf("agent=%s\n", agent );
}
}
| gpl-3.0 |
WorldGrower/WorldGrower | test/org/worldgrower/actions/UTestConstructBedAction.java | 3428 | /*******************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package org.worldgrower.actions;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.worldgrower.Args;
import org.worldgrower.Constants;
import org.worldgrower.TestUtils;
import org.worldgrower.World;
import org.worldgrower.WorldImpl;
import org.worldgrower.WorldObject;
import org.worldgrower.attribute.WorldObjectContainer;
import org.worldgrower.generator.BuildingGenerator;
import org.worldgrower.generator.Item;
public class UTestConstructBedAction {
@Test
public void testExecute() {
World world = new WorldImpl(10, 10, null, null);
WorldObject performer = TestUtils.createSkilledWorldObject(2, Constants.INVENTORY, new WorldObjectContainer());
WorldObject target = createWorkbench(world, performer);
Actions.CONSTRUCT_BED_ACTION.execute(performer, target, Args.EMPTY, world);
assertEquals(1, performer.getProperty(Constants.INVENTORY).getQuantityFor(Constants.SLEEP_COMFORT));
}
@Test
public void testIsValidTarget() {
World world = new WorldImpl(10, 10, null, null);
WorldObject performer = TestUtils.createSkilledWorldObject(2, Constants.INVENTORY, new WorldObjectContainer());
WorldObject workbench = createWorkbench(world, performer);
assertEquals(true, Actions.CONSTRUCT_BED_ACTION.isValidTarget(performer, workbench, world));
assertEquals(false, Actions.CONSTRUCT_BED_ACTION.isValidTarget(performer, performer, world));
}
private WorldObject createWorkbench(World world, WorldObject performer) {
int workbenchId = BuildingGenerator.generateWorkbench(0, 0, world, performer);
WorldObject workbench = world.findWorldObjectById(workbenchId);
return workbench;
}
@Test
public void testIsActionPossible() {
World world = new WorldImpl(10, 10, null, null);
WorldObject performer = TestUtils.createSkilledWorldObject(2, Constants.INVENTORY, new WorldObjectContainer());
performer.getProperty(Constants.INVENTORY).addQuantity(Item.WOOD.generate(1f), 20);
WorldObject workbench = createWorkbench(world, performer);
assertEquals(true, Actions.CONSTRUCT_BED_ACTION.isActionPossible(performer, workbench, Args.EMPTY, world));
}
@Test
public void testDistance() {
World world = new WorldImpl(10, 10, null, null);
WorldObject performer = TestUtils.createSkilledWorldObject(2, Constants.INVENTORY, new WorldObjectContainer());
WorldObject workbench = createWorkbench(world, performer);
assertEquals(0, Actions.CONSTRUCT_BED_ACTION.distance(performer, workbench, Args.EMPTY, world));
}
} | gpl-3.0 |
Vifon/ranger | ranger/__init__.py | 1274 | # This file is part of ranger, the console file manager.
# License: GNU GPL version 3, see the file "AUTHORS" for details.
"""A console file manager with VI key bindings.
It provides a minimalistic and nice curses interface with a view on the
directory hierarchy. The secondary task of ranger is to figure out which
program you want to use to open your files with.
"""
from __future__ import (absolute_import, division, print_function)
import os
# Information
__license__ = 'GPL3'
__version__ = '1.9.1'
__author__ = __maintainer__ = 'Roman Zimbelmann'
__email__ = 'hut@hut.pm'
# Constants
RANGERDIR = os.path.dirname(__file__)
TICKS_BEFORE_COLLECTING_GARBAGE = 100
TIME_BEFORE_FILE_BECOMES_GARBAGE = 1200
MAX_RESTORABLE_TABS = 3
MACRO_DELIMITER = '%'
MACRO_DELIMITER_ESC = '%%'
DEFAULT_PAGER = 'less'
USAGE = '%prog [options] [path]'
VERSION = 'ranger-master {0}'.format(__version__)
# These variables are ignored if the corresponding
# XDG environment variable is non-empty and absolute
CACHEDIR = os.path.expanduser('~/.cache/ranger')
CONFDIR = os.path.expanduser('~/.config/ranger')
DATADIR = os.path.expanduser('~/.local/share/ranger')
args = None # pylint: disable=invalid-name
from ranger.core.main import main # NOQA pylint: disable=wrong-import-position
| gpl-3.0 |
mwpowellhtx/Kingdom.Castle.Extensions | src/Kingdom.Web.Http.Castle.Windsor/MicroKernel/Registration/ContainerInstaller.cs | 770 | // ReSharper disable once CheckNamespace
namespace Kingdom.MicroKernel.Registration
{
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
/// <summary>
/// Provides <see cref="IWindsorContainer"/> installer services.
/// </summary>
public class ContainerInstaller : WindsorInstallerBase
{
/// <summary>
/// Installs using the <paramref name="container"/> and <paramref name="store"/>.
/// </summary>
/// <param name="container"></param>
/// <param name="store"></param>
public override void Install(IWindsorContainer container, IConfigurationStore store)
{
RegisterComponent<IWindsorContainer>(container, r => r.Instance(container));
}
}
}
| gpl-3.0 |
esaito/ExemplosDemoiselle | estacionamentov25X/src/test/java/org/demoiselle/estacionamento/business/VagaBCTest.java | 1850 | package org.demoiselle.estacionamento.business;
import static org.junit.Assert.*;
import java.util.*;
import javax.inject.Inject;
import org.demoiselle.estacionamento.business.VagaBC;
import org.demoiselle.estacionamento.domain.Vaga;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import br.gov.frameworkdemoiselle.junit.DemoiselleRunner;
//
//Para executar os testes sem erro de segurança altere no arquivo demoiselle.properties o valor da propriedade frameworkdemoiselle.security.enabled para falso:
//frameworkdemoiselle.security.enabled=false
//
@RunWith(DemoiselleRunner.class)
public class VagaBCTest {
@Inject
private VagaBC vagaBC;
@Before
public void before() {
for (Vaga vaga : vagaBC.findAll()) {
vagaBC.delete(vaga.getId());
}
}
@Test
public void testInsert() {
Vaga vaga = new Vaga(true, "porte", null ,new Date(),new Date(), null);
vagaBC.insert(vaga);
List<Vaga> listOfVaga = vagaBC.findAll();
assertNotNull(listOfVaga);
assertEquals(1, listOfVaga.size());
}
@Test
public void testDelete() {
Vaga vaga = new Vaga(true,"porte",null,new Date(),new Date(),null);
vagaBC.insert(vaga);
List<Vaga> listOfVaga = vagaBC.findAll();
assertNotNull(listOfVaga);
assertEquals(1, listOfVaga.size());
vagaBC.delete(vaga.getId());
listOfVaga = vagaBC.findAll();
assertEquals(0, listOfVaga.size());
}
@Test
public void testUpdate() {
Vaga vaga = new Vaga(true,"porte",null,new Date(),new Date(),null);
vagaBC.insert(vaga);
List<Vaga> listOfVaga = vagaBC.findAll();
Vaga vaga2 = (Vaga)listOfVaga.get(0);
assertNotNull(listOfVaga);
vaga2.setPorte("novo valor");
vagaBC.update(vaga2);
listOfVaga = vagaBC.findAll();
Vaga vaga3 = (Vaga)listOfVaga.get(0);
assertEquals("novo valor", vaga3.getPorte());
}
} | gpl-3.0 |
moderna/ShivaSensorRigging | shiva/SensorRigging/Resources/Scripts/SensorRigging_Function_parseSensors.lua | 1900 | --------------------------------------------------------------------------------
-- Function......... : parseSensors
-- Author........... :
-- Description...... :
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function SensorRigging.parseSensors( sCsv )
--------------------------------------------------------------------------------
local csvLines = table.newInstance()
string.explode( sCsv, csvLines, "\r\n" )
-- local csvHeaderLine = table.getFirst( csvLines )
-- local headers = table.newInstance()
-- string.explode( csvHeaderLine, headers, ";" )
for r = 1, table.getSize( csvLines ) - 1 do
local csvLine = table.getAt( csvLines, r )
local cells = table.newInstance()
string.explode( csvLine, cells, ";" )
local model = table.getAt( cells, 0 )
local joint = table.getAt( cells, 1 )
local id = string.toNumber( table.getAt( cells, 2 ) )
local type = table.getAt( cells, 3 )
local x = string.toNumber( table.getAt( cells, 4 ) )
local y = string.toNumber( table.getAt( cells, 5 ) )
local z = string.toNumber( table.getAt( cells, 6 ) )
local w = string.toNumber( table.getAt( cells, 7 ) )
local h = string.toNumber( table.getAt( cells, 8 ) )
local d = string.toNumber( table.getAt( cells, 9 ) )
local r = string.toNumber( table.getAt( cells, 10 ) )
this.addSensorEntry( model, joint, id, type, x, y, z, w, h, d, r )
end
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
| gpl-3.0 |
organicsmarthome/OSHv2 | osh_core/osh_src/osh/datatypes/registry/globalcontroller/PvCommandExchange.java | 2429 | /*
*************************************************************************************************
* OrganicSmartHome [Version 2.0] is a framework for energy management in intelligent buildings
* Copyright (C) 2014 Florian Allerding (florian.allerding@kit.edu) and Kaibin Bao and
* Ingo Mauser and Till Schuberth
*
*
* This file is part of the OrganicSmartHome.
*
* OrganicSmartHome 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.
*
* OrganicSmartHome 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 OrganicSmartHome.
*
* If not, see <http://www.gnu.org/licenses/>.
*
*************************************************************************************************
*/
package osh.datatypes.registry.globalcontroller;
import java.util.UUID;
import osh.datatypes.registry.CommandExchange;
public class PvCommandExchange extends CommandExchange {
private Boolean newPvSwitchedOn;
private Double reactivePowerTargetValue;
public PvCommandExchange(UUID sender, UUID receiver, long time, Boolean newPvSwitchedOn) {
this(sender, receiver, time, newPvSwitchedOn, null);
}
public PvCommandExchange(UUID sender, UUID receiver, long time, Double reactivePowerTargetValue) {
this(sender, receiver, time, null, reactivePowerTargetValue);
}
public PvCommandExchange(UUID sender, UUID receiver, long timestamp, Boolean newPvSwitchedOn, Double reactivePowerTargetValue) {
super(sender, receiver, timestamp);
this.newPvSwitchedOn = newPvSwitchedOn;
this.reactivePowerTargetValue = reactivePowerTargetValue;
}
public Boolean getNewPvSwitchedOn() {
return newPvSwitchedOn;
}
public void setNewPvSwitchedOn(Boolean newPvSwitchedOn) {
this.newPvSwitchedOn = newPvSwitchedOn;
}
public Double getReactivePowerTargetValue() {
return reactivePowerTargetValue;
}
public void setReactivePowerTargetValue(Double reactivePowerTargetValue) {
this.reactivePowerTargetValue = reactivePowerTargetValue;
}
} | gpl-3.0 |
ldbc/ldbc_snb_datagen | src/main/scala/ldbc/snb/datagen/syntax/SparkSqlSyntax.scala | 850 | package ldbc.snb.datagen.syntax
import org.apache.spark.sql.{Column, ColumnName, DataFrame, Dataset}
import scala.language.implicitConversions
trait SparkSqlSyntax {
@`inline` implicit final def datasetOps[A](a: Dataset[A]) = new DatasetOps(a)
@`inline` implicit final def stringToColumnOps[A](a: StringContext) = new StringToColumnOps(a)
}
final class DatasetOps[A](private val self: Dataset[A]) extends AnyVal {
def |+|(other: Dataset[A]): Dataset[A] = self union other
def select(columns: Seq[Column]): DataFrame = self.select(columns: _*)
def partition(expr: Column): (Dataset[A], Dataset[A]) = {
val df = self.cache()
(df.filter(expr), df.filter(!expr || expr.isNull))
}
}
final class StringToColumnOps(private val sc: StringContext) extends AnyVal {
def $(args: Any*): ColumnName = new ColumnName(sc.s(args: _*))
}
| gpl-3.0 |
aheadley/scorepeon | scorepeon_app/leaderboard/models.py | 3179 | from django.db import models
import trueskill
class Game(models.Model):
name = models.CharField(max_length=255)
mu = models.FloatField(default=trueskill.MU)
sigma = models.FloatField(default=trueskill.SIGMA)
beta = models.FloatField(default=trueskill.BETA)
tau = models.FloatField(default=trueskill.TAU)
draw_probability = models.FloatField(default=trueskill.DRAW_PROBABILITY)
golf_style = models.BooleanField(default=True)
def __str__(self):
return self.name
@property
def env(self):
if self._env is None:
self._env = trueskill.TrueSkill(mu=self.mu, sigma=self.sigma,
beta=self.beta, tau=self.tau, draw_probability=self.draw_probability)
return self._env
@property
def ranking(self):
return sorted(Skill.objects.filter(game=self),
key=lambda ps: self.env.explose(ps.rating), reverse=True)
@property
def players(self):
return [s.player for s in self.skills]
class Player(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Skill(models.Model):
game = models.ForeignKey(Game, related_name='skills')
player = models.ForeignKey(Player, related_name='skills')
mu = models.FloatField()
sigma = models.FloatField()
@property
def rating(self):
if self._rating is None:
self._rating = self.game.env.Rating(mu=self.mu, sigma=self.sigma)
return self._rating
@rating.setter
def rating(self, rating):
self.mu = rating.mu
self.sigma = rating.sigma
self._rating = rating
self.save()
class Match(models.Model):
game = models.ForeignKey(Game, related_name='matches')
timestamp = models.DateTimeField(auto_now_add=True)
recorded = models.BooleanField(default=False)
@property
def players(self):
return [s.player for s in self.scores]
def record_results(self):
if not recorded:
new_ratings = self._get_new_ratings(self._get_current_ratings())
for score, rating in new_ratings.iteritems():
score.skill.rating = rating
self.recorded = True
self.save()
else:
raise RuntimeError('Match result already recorded')
def _get_player_skill(self, player):
return Skill.objects.get(game=self.game, player=player)
#return Skill.objects.get(game_id=self.game.id, player_id=player.id)
def _get_current_ratings(self):
return dict((s, s.skill.rating) for s in self.scores)
def _get_new_ratings(self, original_ratings):
scores = [s.score for s in original_ratings.keys()]
ranking = [scores.index(s) for s in \
sorted(scores, reverse=(not self.game.golf_style))]
new_ratings = self.game.env.rate(original_ratings)
return new_ratings
class Score(models.Model):
match = models.ForeignKey(Match, related_name='scores')
player = models.ForeignKey(Player, related_name='+')
score = models.IntegerField()
@property
def skill(self):
return self.match._get_player_skill(self.player)
| gpl-3.0 |
Tymewalk/EfficientEnigma | modules/util.py | 552 | # util.py
# Various utilities, such as !ping.
import aiohttp, time
async def ping(client, message):
aiosession = aiohttp.ClientSession(loop=client.loop)
start = time.time()
async with aiosession.get('https://discordapp.com'):
duration = time.time() - start
duration = round(duration * 1000)
await message.channel.send("{} :ping_pong: Pong! (**{}ms**)".format(message.author.mention, duration))
aiosession.close()
# Add the commands to the global command table.
def setup_command_table(table):
table["!ping"] = ping | gpl-3.0 |
montimaj/CRYPTSTEG | CryptoSteg/app/src/main/java/edu/sxccal/stegano/utilities/DecodeQR.java | 3030 | package edu.sxccal.stegano.utilities;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import edu.sxccal.stegano.R;
import edu.sxccal.stegano.Stegano;
/**
* This module decodes a QR image
* @author Sayantan Majumdar
*/
public class DecodeQR extends Activity implements View.OnClickListener {
private Button bt;
public static TextView tv;
private final int PICKFILE_RESULT_CODE = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decode_qr);
bt=(Button)findViewById(R.id.edqr);
bt.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("file/*");
try {
startActivityForResult(fileintent,PICKFILE_RESULT_CODE);
}
catch (Exception e) {
Log.create_log(e, getApplicationContext());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK) {
String f = data.getData().getPath();
decodeQR(f);
}
break;
}
}
/**
* Writes decoded message to Decoded.txt
* @param f Input Stegano image
*/
private void decodeQR(String f) {
try {
tv= (TextView)findViewById(R.id.dqr);
tv.setText("");
Bitmap bmp=BitmapFactory.decodeFile(f); //import QR image file
int width = bmp.getWidth(), height = bmp.getHeight();
int[] pixels = new int[width * height];
bmp.getPixels(pixels, 0, width, 0, 0, width, height);
bmp.recycle();
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result qr_result = new QRCodeReader().decode(bitmap);
tv.setText("Successfully Decoded!\n");
tv.append("Decoded file is at:\n");
writeToFile(qr_result.getText().toString());
}
catch(Exception e) {
Log.create_log(e, getApplicationContext());
}
}
/**
* Creates decoded.txt
* @param s Decoded string
* @throws IOException
*/
private void writeToFile(String s) throws IOException {
String dfile= Stegano.filePath+"/Decoded";
File dir=new File(dfile);
if(!dir.exists())
dir.mkdir();
dfile+="/decoded.txt";
File file=new File(dfile);
FileOutputStream fp=new FileOutputStream(file);
fp.write(s.getBytes());
fp.close();
tv.append(dfile);
}
} | gpl-3.0 |
ISRAPIL/FastCorePE | src/pocketmine/event/block/LeavesDecayEvent.php | 422 | <?php
namespace pocketmine\event\block;
use pocketmine\block\Block;
use pocketmine\event\Cancellable;
class LeavesDecayEvent extends BlockEvent implements Cancellable {
public static $handlerList = null;
public function __construct(Block $block) {
parent::__construct($block);
}
/**
* @return EventName
*/
public function getName() {
return "LeavesDecayEvent";
}
}
| gpl-3.0 |
ColacX/slowbro | plugins/Authentication/Saml/Saml.php | 4656 | <?php
/**
File in Authentication plugin package for ver 2.1.4 Booked Scheduler
to implement Single Sign On Capability. Based on code from the
Booked Scheduler Authentication Ldap plugin as well as a SAML
Authentication plugin for Moodle 1.9+.
See http://moodle.org/mod/data/view.php?d=13&rid=2574
This plugin uses the SimpleSAMLPHP version 1.8.2 libraries.
http://simplesamlphp.org/
Booked Scheduler 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.
Booked Scheduler 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 Booked Scheduler. If not, see <http://www.gnu.org/licenses/>.
*/
require_once(ROOT_DIR . 'lib/Application/Authentication/namespace.php');
require_once(ROOT_DIR . 'plugins/Authentication/Saml/namespace.php');
/**
* Provides simpleSAMLphp authentication/synchronization for Booked Scheduler
* @see IAuthorization
*/
class Saml extends Authentication implements IAuthentication
{
/**
* @var IAuthentication
*/
private $authToDecorate;
/**
* @var AdSamlWrapper
*/
private $saml;
/**
* @var SamlOptions
*/
private $options;
/**
* @var IRegistration
*/
private $_registration;
/**
* @var PasswordEncryption
*/
private $_encryption;
/**
* @var SamlUser
*/
private $user;
/**
* @var string
*
*/
private $username;
/**
* @var string
*/
private $password;
public function SetRegistration($registration)
{
$this->_registration = $registration;
}
private function GetRegistration()
{
if ($this->_registration == null)
{
$this->_registration = new Registration();
}
return $this->_registration;
}
public function SetEncryption($passwordEncryption)
{
$this->_encryption = $passwordEncryption;
}
private function GetEncryption()
{
if ($this->_encryption == null)
{
$this->_encryption = new PasswordEncryption();
}
return $this->_encryption;
}
/**
* @param IAuthentication $authentication Authentication class to decorate
* @param ISaml $samlImplementation The actual SAML implementation to work against
* @param SamlOptions $samlOptions Options to use for SAML configuration
*/
public function __construct(IAuthentication $authentication, $samlImplementation = null, $samlOptions = null)
{
$this->authToDecorate = $authentication;
$this->options = $samlOptions;
if ($samlOptions == null)
{
$this->options = new SamlOptions();
}
$this->saml = $samlImplementation;
if ($samlImplementation == null)
{
$this->saml = new AdSamlWrapper($this->options);
}
}
public function Validate($username, $password)
{
$this->saml->Connect();
$isValid = $this->saml->Authenticate();
if ($isValid)
{
$this->user = $this->saml->GetSamlUser();
$userLoaded = $this->SamlUserExists();
if (!$userLoaded)
{
Log::Error('Could not load user details from SinmpleSamlPhpSSO. Check your SSO settings. User: %s',
$username);
}
return $userLoaded;
}
return false;
}
public function Login($username, $loginContext)
{
$this->username = $username;
if ($this->username == null)
{
$this->username = $this->user->GetUserName();
}
if ($this->SamlUserExists())
{
$this->Synchronize($this->username);
}
return $this->authToDecorate->Login($this->username, $loginContext);
}
public function Logout(UserSession $user)
{
$this->authToDecorate->Logout($user);
}
public function AreCredentialsKnown()
{
return true;
}
private function SamlUserExists()
{
return $this->user != null;
}
private function Synchronize($username)
{
$registration = $this->GetRegistration();
$registration->Synchronize(
new AuthenticatedUser(
$username,
$this->user->GetEmail(),
$this->user->GetFirstName(),
$this->user->GetLastName(),
$this->password,
Configuration::Instance()->GetKey(ConfigKeys::LANGUAGE),
Configuration::Instance()->GetDefaultTimezone(),
$this->user->GetPhone(), $this->user->GetInstitution(),
$this->user->GetTitle())
);
}
public function ShowForgotPasswordPrompt()
{
return false;
}
public function ShowPasswordPrompt()
{
return true;
}
public function ShowPersistLoginPrompt()
{
return false;
}
public function ShowUsernamePrompt()
{
return true;
}
}
?> | gpl-3.0 |
maninator/manimediaserver | www/init.php | 1887 | <?php
/**
* Init
*
* @package Wojo Framework
* @author wojoscripts.com
* @copyright 2016
* @version $Id: init.php, v1.00 2016-03-05 10:12:05 gewa Exp $
*/
if (!defined("_WOJO"))
die('Direct access to this location is not allowed.');
$BASEPATH = str_replace("init.php", "", realpath(__FILE__));
define("BASEPATH", $BASEPATH);
// Import Mani config
$MANI_CONFIG = parse_ini_file($BASEPATH."/../config/config.ini");
$MEDIA_TV = array();
if (!empty($MANI_CONFIG['libraries_tv_dirs'])) {
$dirs = explode(',',$MANI_CONFIG['libraries_tv_dirs']);
foreach ($dirs as $dir) {
$MEDIA_TV[] = trim($dir);
}
}
$MEDIA_MOVIE = array();
if (!empty($MANI_CONFIG['libraries_movies_dirs'])) {
$dirs = explode(',',$MANI_CONFIG['libraries_movies_dirs']);
foreach ($dirs as $dir) {
$MEDIA_MOVIE[] = trim($dir);
}
}
$configFile = BASEPATH . "lib/config.ini.php";
if (file_exists($configFile)) {
require_once($configFile);
} else {
header("Location: setup/");
exit;
}
require_once (BASEPATH . "bootstrap.php");
Bootstrap::init();
wError::run();
Filter::run();
Debug::run();
new Lang();
define("ADMIN", BASEPATH . "admin/");
define("FRONT", BASEPATH . "front/");
$dir = (App::Core()->site_dir) ? '/' . App::Core()->site_dir : '';
$url = preg_replace("#/+#", "/", $_SERVER['HTTP_HOST'] . $dir);
$site_url = Url::protocol() . "://" . $url;
define("SITEURL", $site_url);
define("UPLOADURL", SITEURL . '/uploads');
define("UPLOADS", BASEPATH . 'uploads');
define("ADMINURL", SITEURL . '/admin');
define("ADMINVIEW", SITEURL . '/view/admin');
define("ADMINBASE", BASEPATH . 'view/admin');
define("FRONTVIEW", SITEURL . '/view/front');
define("FRONTBASE", BASEPATH . 'view/front');
| gpl-3.0 |
NGSEP/NGSEPcore | src/ngsep/sequencing/RawReadsTrimmer.java | 2447 | package ngsep.sequencing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import ngsep.sequences.DegenerateSequence;
import ngsep.sequences.RawRead;
import ngsep.sequences.io.FastqFileReader;
public class RawReadsTrimmer {
private String adapter = "AGATCG";
private String inputDirectory;
private String outDirectory;
private String sampleNamesFile;
public static void main(String[] args) throws Exception {
RawReadsTrimmer instance = new RawReadsTrimmer();
instance.inputDirectory = args[0];
instance.sampleNamesFile = args[1];
instance.outDirectory = args[2];
instance.adapter = args[3];
instance.run();
}
private void run() throws FileNotFoundException, IOException {
loadFileNames();
}
private void loadFileNames() throws IOException {
try (Scanner scanner = new Scanner(new File(sampleNamesFile))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String [] items = line.split("\t");
try(FastqFileReader reader1 = new FastqFileReader(inputDirectory+File.separator+items[1]);
FastqFileReader reader2 = new FastqFileReader(inputDirectory+File.separator+items[2])) {
trimAdapters(reader1, items[1], reader2, items[2]);
}
}
}
}
private void trimAdapters(FastqFileReader reader1, String file1, FastqFileReader reader2, String file2) throws IOException {
Pattern pattern = Pattern.compile(DegenerateSequence.makeRegularExpression(adapter));
try(OutputStream os1 = new GZIPOutputStream(new FileOutputStream(outDirectory + File.separator+file1));
PrintStream out1 = new PrintStream(os1);
OutputStream os2 = new GZIPOutputStream(new FileOutputStream(outDirectory + File.separator+file2));
PrintStream out2 = new PrintStream(os2)) {
Iterator<RawRead> it1 = reader1.iterator();
Iterator<RawRead> it2 = reader2.iterator();
while(it1.hasNext() && it2.hasNext()) {
RawRead read1 = it1.next();
RawRead read2 = it2.next();
int l1 = read1.getLength();
read1.trimFromSequence(pattern);
if(read1.getLength()!=l1) {
l1 = read1.getLength();
read2.trimToLength(l1);
}
if(l1>=40 ) {
read1.save(out1);
read2.save(out2);
}
}
}
}
}
| gpl-3.0 |
workhorsy/nulldc-linux | nulldc/nullDC/serial_ipc/serial_ipc_client.cpp | 4846 |
#include "types.h"
#include <windows.h>
#include <assert.h>
#include <iostream>
#define sipcver "0.3 -spdma -buffered"
HANDLE readp=NULL;
HANDLE writep=NULL;
#define buff_size (512*1024)
u8 ReadBuff[buff_size];
u32 readind=0;
u32 ReadSz=0;
u32 serial_RxBytes=0;
u32 serial_TxBytes=0;
u32 last_serial_RxBytes=0;
u32 last_serial_TxBytes=0;
u32 last_serial_Rx_tick=0;
u32 last_serial_Tx_tick=0;
void StartGDBSession();
int serial_cmdl(wchar** arg,int cl)
{
if (cl<1)
printf("-serial : too few params.-serial <FILE> must be used\n");
if (writep)
printf("-serial : -serial/-slave allready used ...\n");
wprintf(_T("Serial port to \"%s\" redirection version %s\n"),arg[1],sipcver);
writep = CreateFile(arg[1],GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL ,NULL );
if (writep==INVALID_HANDLE_VALUE)
{
wprintf(_T("Unable to open \"%\".The file must exist \n"),arg[1]);
writep=NULL;
return 0;
}
DCB dcbConfig;
if(GetCommState(writep, &dcbConfig))
{
dcbConfig.BaudRate = 115200;
dcbConfig.ByteSize = 8;
dcbConfig.Parity = NOPARITY;
dcbConfig.StopBits = ONESTOPBIT;
dcbConfig.fBinary = true;
dcbConfig.fParity = true;
}
SetCommState(writep, &dcbConfig);
COMMTIMEOUTS to;
GetCommTimeouts(writep,&to);
to.ReadIntervalTimeout=MAXDWORD;
to.ReadTotalTimeoutConstant=0;
to.ReadTotalTimeoutMultiplier=0;
to.WriteTotalTimeoutConstant=1000000;
to.WriteTotalTimeoutMultiplier=5;
SetCommTimeouts(writep,&to);
readp=writep;
return 1;
}
int slave_cmdl(wchar** arg,int cl)
{
if (cl<2)
printf("-slave : too few params.-slave <piperead> <pipewrite> must be used\n");
//TODO : how to do on 64b compatable code ?
HANDLE laddWrSlave = (HANDLE)(u64)_wtoi(arg[1]);
HANDLE laddRdSlave = (HANDLE)(u64)_wtoi(arg[2]);
if (laddWrSlave ==0 || laddRdSlave==0)
{
printf("Invalid param @ slave, pipe cant be 0/non number\n");
return 0;
}
log("Value of write handle to pipe1: %p\n",laddWrSlave);
log("Value of read handle to pipe2 : %p\n",laddRdSlave);
//this warning can't be fixed can it ?
writep = laddWrSlave;
readp = laddRdSlave;
return 2;
}
void PrintSerialIPUsage(int argc, wchar *argv[])
{
/*
if (argc==1)
{
printf("If you want to use serial port ipc redirection use -slave piperead pipewrite/-serial FILE_NAME \n");
//StartGDBSession();
return;
}
if (argc!=4 && argc!=3)
{
printf("Serial port pipe redirection version %s\n",sipcver);
printf("Wrong number of parameters , expecting nulldc -slave piperead pipewrite/-serial FILE_NAME \n");
printf("redirection disabled");
//StartGDBSession();
return;
}
*/
}
void WriteBlockSerial(u8* blk,u32 size,u8* sum)
{
serial_TxBytes+=size;
*sum=0;
for (u32 i=0;i<size;i++)
*sum^=blk[i];
if (!writep)
{
for (u32 i=0;i<size;i++)
putc(blk[i],stdout);
return;
}
//printf("Write IPC not implemented");
DWORD dwWritten=0;
if (!WriteFile(writep,blk,size,&dwWritten,NULL))
log("IPC error");
if (dwWritten!=size)
log("IPC error");
}
void WriteSerial(u8 data)
{
serial_TxBytes++;
putc(data,stdout);
if (!writep)
return;
//log("Write IPC not implemented");
DWORD dwWritten=0;
if (!WriteFile(writep,&data,1,&dwWritten,NULL))
log("IPC error");
if (dwWritten!=1)
log("IPC error");
}
int pend_temp=0;
bool PendingSerialData()
{
if(!readp)
return false;
if (readind==0)
{
/*pend_temp++;
if ((pend_temp%8)!=0)
return false;*/
/*
if (((i++)%256)==0)
PeekNamedPipe(readp,NULL,NULL,NULL,&tba,NULL);
*/
DWORD tba=0;
//ReadFile(readp, &ReadBuff, 0, &tba, NULL);
if(ReadFile(readp, &ReadBuff, buff_size, &tba, NULL) != 0)
{
if(tba > 0)
{
ReadSz=tba;
readind=tba;
}
}
/*
if (tba!=0)
{
readind=tba;
if (readind>(buff_size)) readind=buff_size;
ReadFile(readp,ReadBuff,readind,&tba,NULL);
ReadSz=tba;
if (readind!=tba)
log("IPC ERROR \n");
}
*/
return tba!=0;
}
else
{
return true;
}
}
s32 ReadSerial()
{
serial_RxBytes++;
if (!readp)
return -1;
//u8 read_data;
//DWORD dwRead;
if (readind<=0)
{
log("IPC error");
return -1;
}
u8 rv= ReadBuff[ReadSz-readind];
readind--;
return rv;
/*
if (!ReadFile(readp,&read_data,1,&dwRead,NULL))
log("IPC error");
if (dwRead!=1)
log("IPC error");
//log("Read IPC not implemented");
return read_data;*/
}
float GetRxSpeed()
{
double tp=((double)timeGetTime()-(double)last_serial_Rx_tick)/1000.0;
float rv=(float)((serial_RxBytes-last_serial_RxBytes)/tp);
last_serial_RxBytes=serial_RxBytes;
last_serial_Rx_tick=timeGetTime();
return rv;
}
float GetTxSpeed()
{
double tp=((double)timeGetTime()-(double)last_serial_Tx_tick)/1000.0;
float rv=(float)((serial_TxBytes-last_serial_TxBytes)/tp);
last_serial_TxBytes=serial_TxBytes;
last_serial_Tx_tick=timeGetTime();
return rv;
} | gpl-3.0 |
cstrouse/chromebrew | packages/apriconv.rb | 1696 | require 'package'
class Apriconv < Package
description 'a portable implementation of the iconv() library'
homepage 'http://apr.apache.org/'
version '1.2.2'
compatibility 'all'
source_url 'https://apache.claz.org/apr/apr-iconv-1.2.2.tar.bz2'
source_sha256 '7d454e0fe32f2385f671000e3b755839d16aabd7291e3947c973c90377c35313'
binary_url ({
aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/apriconv-1.2.2-chromeos-armv7l.tar.xz',
armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/apriconv-1.2.2-chromeos-armv7l.tar.xz',
i686: 'https://dl.bintray.com/chromebrew/chromebrew/apriconv-1.2.2-chromeos-i686.tar.xz',
x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/apriconv-1.2.2-chromeos-x86_64.tar.xz',
})
binary_sha256 ({
aarch64: '6ec314d1d6143a855e59d5a3b76db311e3ba60b980b98be3d639c39e74949fed',
armv7l: '6ec314d1d6143a855e59d5a3b76db311e3ba60b980b98be3d639c39e74949fed',
i686: 'ef8a4e543d11b010edae76ec4ea4d06be68b41a3d4e31bc8764969f2d216d8e5',
x86_64: 'd3abcd64112eb46aef6bb090409471c9fbaf675cd258aff0220d696fed9b6771',
})
depends_on 'apr'
depends_on 'libtool'
def self.build
system "./configure \
--prefix=#{CREW_PREFIX} \
--libdir=#{CREW_LIB_PREFIX} \
--with-apr=#{CREW_PREFIX}"
system "sed -i 's,/usr/local/lib,#{CREW_LIB_PREFIX},g' Makefile"
system "sed -i 's,/usr/local/lib,#{CREW_LIB_PREFIX},g' ccs/Makefile"
system "sed -i 's,/usr/local/lib,#{CREW_LIB_PREFIX},g' ces/Makefile"
system "make"
end
def self.install
system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
system "libtool --mode=finish #{CREW_DEST_LIB_PREFIX}/iconv"
end
end
| gpl-3.0 |
easymodo/qimgv | qimgv/gui/overlays/videocontrolsproxy.cpp | 2385 | #include "videocontrolsproxy.h"
VideoControlsProxyWrapper::VideoControlsProxyWrapper(FloatingWidgetContainer *parent)
: container(parent),
videoControls(nullptr)
{
}
VideoControlsProxyWrapper::~VideoControlsProxyWrapper() {
if(videoControls)
videoControls->deleteLater();
}
void VideoControlsProxyWrapper::init() {
if(videoControls)
return;
videoControls = new VideoControls(container);
connect(videoControls, &VideoControls::seekBackward, this, &VideoControlsProxyWrapper::seekBackward);
connect(videoControls, &VideoControls::seekForward, this, &VideoControlsProxyWrapper::seekForward);
connect(videoControls, &VideoControls::seek, this, &VideoControlsProxyWrapper::seek);
videoControls->setMode(stateBuf.mode);
videoControls->setPlaybackDuration(stateBuf.duration);
videoControls->setPlaybackPosition(stateBuf.position);
videoControls->onPlaybackPaused(stateBuf.paused);
videoControls->onVideoMuted(stateBuf.videoMuted);
}
void VideoControlsProxyWrapper::show() {
init();
videoControls->show();
}
void VideoControlsProxyWrapper::hide() {
if(videoControls)
videoControls->hide();
}
void VideoControlsProxyWrapper::setPlaybackDuration(int _duration) {
if(videoControls) {
videoControls->setPlaybackDuration(_duration);
} else {
stateBuf.duration = _duration;
}
}
void VideoControlsProxyWrapper::setPlaybackPosition(int _position) {
if(videoControls) {
videoControls->setPlaybackPosition(_position);
} else {
stateBuf.position = _position;
}
}
void VideoControlsProxyWrapper::setMode(PlaybackMode _mode) {
if(videoControls) {
videoControls->setMode(_mode);
} else {
stateBuf.mode = _mode;
}
}
void VideoControlsProxyWrapper::onPlaybackPaused(bool _mode) {
if(videoControls) {
videoControls->onPlaybackPaused(_mode);
} else {
stateBuf.paused = _mode;
}
}
void VideoControlsProxyWrapper::onVideoMuted(bool _mode) {
if(videoControls) {
videoControls->onVideoMuted(_mode);
} else {
stateBuf.videoMuted = _mode;
}
}
bool VideoControlsProxyWrapper::underMouse() {
return videoControls ? videoControls->underMouse() : false;
}
bool VideoControlsProxyWrapper::isVisible() {
return videoControls ? videoControls->isVisible() : false;
}
| gpl-3.0 |
jquesnelle/MissionControl | ARDroneSDK3/swig/eARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR.cs | 1801 | //------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.7
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
public enum eARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR {
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_NOERROR = 0,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERROREEPROM,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORMOTORSTALLED,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORPROPELLERSECURITY,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORCOMMLOST,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORRCEMERGENCYSTOP,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORREALTIME,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORMOTORSETTING,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORTEMPERATURE,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORBATTERYVOLTAGE,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORLIPOCELLS,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORMOSFET,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORBOOTLOADER,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_ERRORASSERT,
ARCOMMANDS_ARDRONE3_SETTINGSSTATE_MOTORERRORSTATECHANGED_MOTORERROR_MAX
}
| gpl-3.0 |
Jeewantha/leefy | leefy/leefy-api/src/main/java/com/jeesoft/api/dto/UserRegistrationForm.java | 6324 | /*******************************************************************************
*
* Leefy is a simple social network to narrow the gap between people speaking different
* languages and to aid the language learning process.
* Copyright (C) 2015 Jeewantha Samaraweera
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*******************************************************************************/
package com.jeesoft.api.dto;
import java.io.Serializable;
import java.util.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import com.jeesoft.common.annotation.FieldMatch;
/**
* The Class UserRegistrationForm.
*
* @author Jeewantha Samaraweera
* @since alpha
*/
@FieldMatch.List({
@FieldMatch(first="password", second="confirmPassword", message="The password and confirm password fields must match"),
@FieldMatch(first="email", second="confirmEmail", message="The email fields must match")
})
public class UserRegistrationForm implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The Constant INTEGER_FOURTY. */
private static final int INTEGER_FOURTY = 40;
/** The id. */
private Long id;
/** The name. */
@NotNull
@Size(min = 1, max = INTEGER_FOURTY)
private String username;
/** The password. */
@NotNull
@Size(min=6, max=12, message="The password should be 6 to 12 characters containing any character")
private String password;
/** The confirm password. */
private String confirmPassword;
/** The phone. */
private String phone;
/** The email. */
@Email
private String email;
/** The confirm email. */
private String confirmEmail;
/** The birthday. */
private Date birthday;
/** The country. */
private String country;
/**
* Instantiates a new personal contact.
*/
public UserRegistrationForm() {
}
/**
* Instantiates a new personal contact.
*
* @param username the username
* @param phone the phone
* @param email the email
* @param password the password
* @param birthday the birthday
* @param country the country
*/
public UserRegistrationForm(String username, String phone, String email,
String password, Date birthday, String country) {
super();
this.username = username;
this.phone = phone;
this.email = email;
this.password = password;
this.birthday = birthday;
this.country = country;
}
/**
* Gets the id.
*
* @return the id
*/
public Long getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(Long id) {
this.id = id;
}
/**
* Gets the username.
*
* @return the username
*/
public String getUsername() {
return username;
}
/**
* Sets the username.
*
* @param username the new username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Gets the password.
*
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Sets the password.
*
* @param password the new password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Gets the confirm password.
*
* @return the confirm password
*/
public String getConfirmPassword() {
return confirmPassword;
}
/**
* Sets the confirm password.
*
* @param confirmPassword the new confirm password
*/
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
/**
* Gets the phone.
*
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* Sets the phone.
*
* @param phone the new phone
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* Gets the email.
*
* @return the email
*/
public String getEmail() {
return email;
}
/**
* Sets the email.
*
* @param email the new email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Gets the confirm email.
*
* @return the confirm email
*/
public String getConfirmEmail() {
return confirmEmail;
}
/**
* Sets the confirm email.
*
* @param confirmEmail the new confirm email
*/
public void setConfirmEmail(String confirmEmail) {
this.confirmEmail = confirmEmail;
}
/**
* Gets the birthday.
*
* @return the birthday
*/
public Date getBirthday() {
return birthday;
}
/**
* Sets the birthday.
*
* @param birthday the new birthday
*/
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
/**
* Gets the country.
*
* @return the country
*/
public String getCountry() {
return country;
}
/**
* Sets the country.
*
* @param country the new country
*/
public void setCountry(String country) {
this.country = country;
}
}
| gpl-3.0 |
igorcoding/rsys | src/rsys/exporters/svd_mysql_exporter.cc | 2179 | #include "svd_mysql_exporter.h"
namespace rsys {
namespace exporters {
svd_mysql_config::svd_mysql_config()
: _users_table(""),
_items_table(""),
_features_table("svd_features"),
_pU_table("svd_pU"),
_pI_table("svd_pI"),
_bU_table("svd_bU"),
_bI_table("svd_bI"),
_mu_table("svd_mu") {
}
const std::string& svd_mysql_config::users_table() const { return _users_table; }
const std::string& svd_mysql_config::items_table() const { return _items_table; }
const std::string& svd_mysql_config::features_table() const { return _features_table; }
const std::string& svd_mysql_config::pU_table() const { return _pU_table; }
const std::string& svd_mysql_config::pI_table() const { return _pI_table; }
const std::string& svd_mysql_config::bU_table() const { return _bU_table; }
const std::string& svd_mysql_config::bI_table() const { return _bI_table; }
const std::string& svd_mysql_config::mu_table() const { return _mu_table; }
svd_mysql_config& svd_mysql_config::users_table(const std::string& user_table) { _users_table = user_table; return *this; }
svd_mysql_config& svd_mysql_config::items_table(const std::string& items_table) { _items_table = items_table; return *this; }
svd_mysql_config& svd_mysql_config::features_table(const std::string& features_table) { _features_table = features_table; return *this; }
svd_mysql_config& svd_mysql_config::pU_table(const std::string& pU_table) { _pU_table = pU_table; return *this; }
svd_mysql_config& svd_mysql_config::pI_table(const std::string& pI_table) { _pI_table = pI_table; return *this; }
svd_mysql_config& svd_mysql_config::bU_table(const std::string& bU_table) { _bU_table = bU_table; return *this; }
svd_mysql_config& svd_mysql_config::bI_table(const std::string& bI_table) { _bI_table = bI_table; return *this; }
svd_mysql_config& svd_mysql_config::mu_table(const std::string& mu_table) { _mu_table = mu_table; return *this; }
}
} | gpl-3.0 |
libre/webexploitscan | wes/data/rules/fullscan/10092019-MS-PHP-Antimalware-Scanner-127-malware_signature.php | 1724 | <?php
/**
* WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan
*
* The PHP page that serves all page requests on WebExploitScan installation.
*
* The routines here dispatch control to the appropriate handler, which then
* prints the appropriate page.
*
* All WebExploitScan code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*/
$NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 127';
$TAGCLEAR='if(isset($_(GET|POST|COOKIE|SERVER|REQUEST)[\'[^\']*\'])){(?:system|exec|shell_exec|popen|passthru)($_(GET|POST|COOKIE|SERVER|REQUEST)[\'[^\']*\'].\'2>&1\');}';
$TAGBASE64='aWYoaXNzZXQoJF8oR0VUfFBPU1R8Q09PS0lFfFNFUlZFUnxSRVFVRVNUKVtcJ1teXCddKlwnXSkpeyg/OnN5c3RlbXxleGVjfHNoZWxsX2V4ZWN8cG9wZW58cGFzc3RocnUpKCRfKEdFVHxQT1NUfENPT0tJRXxTRVJWRVJ8UkVRVUVTVClbXCdbXlwnXSpcJ10uXCcyPiYxXCcpO30=';
$TAGHEX='696628697373657428245f284745547c504f53547c434f4f4b49457c5345525645527c52455155455354295b5c275b5e5c275d2a5c275d29297b283f3a73797374656d7c657865637c7368656c6c5f657865637c706f70656e7c70617373746872752928245f284745547c504f53547c434f4f4b49457c5345525645527c52455155455354295b5c275b5e5c275d2a5c275d2e5c27323e26315c27293b7d';
$TAGHEXPHP='';
$TAGURI='if%28isset%28%24_%28GET%7CPOST%7CCOOKIE%7CSERVER%7CREQUEST%29%5B%5C%27%5B%5E%5C%27%5D%2A%5C%27%5D%29%29%7B%28%3F%3Asystem%7Cexec%7Cshell_exec%7Cpopen%7Cpassthru%29%28%24_%28GET%7CPOST%7CCOOKIE%7CSERVER%7CREQUEST%29%5B%5C%27%5B%5E%5C%27%5D%2A%5C%27%5D.%5C%272%3E%261%5C%27%29%3B%7D';
$TAGCLEAR2='';
$TAGBASE642='';
$TAGHEX2='';
$TAGHEXPHP2='';
$TAGURI2='';
$DATEADD='10/09/2019';
$LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 127 ';
$ACTIVED='1';
$VSTATR='malware_signature';
| gpl-3.0 |
ElliotTheRobot/LILACS-mycroft-core | mycroft/skills/LILACS_storage/__init__.py | 1324 | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core 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.
#
# Mycroft Core 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 Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
from mycroft.skills.LILACS_storage.main import main as service
from threading import Thread
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSStorageSkill(MycroftSkill):
def __init__(self):
super(LILACSStorageSkill, self).__init__(name="LILACS_Storage_Skill")
def initialize(self):
timer_thread = Thread(target=self.service)
timer_thread.setDaemon(True)
timer_thread.start()
def service(self):
service()
def create_skill():
return LILACSStorageSkill() | gpl-3.0 |
AegeanApp/Aegean-App-V1-Android | app/src/main/java/com/aegeanapp/george/test_aegean_app/Sitisi.java | 4717 | package com.aegeanapp.george.test_aegean_app;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class Sitisi extends ActionBarActivity {
private Spinner dropdown;
private Spinner dropdown2;
// private Spinner dropdown3;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sitisi);
getSupportActionBar().setTitle("Πρόγραμμα Σίτισης");//setting title in actionBar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);//energopoiisi tou back button
dropdown = (Spinner) findViewById(R.id.list1);
dropdown2 = (Spinner) findViewById(R.id.list2);
// dropdown3 = (Spinner) findViewById(R.id.list3);
//1h lista gia ebdomades
String[] items = new String[]{"1η Εβδομάδα", "2η Εβδομάδα", "3η Εβδομάδα", "4η Εβδομάδα"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
//2h lista gia ebdomades
String[] items2 = new String[]{"Μεσημεριανό", "Βραδινό"};
ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items2);
dropdown2.setAdapter(adapter2);
/* //3h gia imera ths evdomadas
String[] items3 = new String[]{"Δευτέρα", "Τρίτη","Τετάρτη","Πέμπτη","Παρασκευή","Σάββατο","Κυριακή"};
ArrayAdapter<String> adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items3);
dropdown3.setAdapter(adapter3);*/
}
private String val_list1;
private String val_list2;
// private String val_list3;
public void weekOnClick(View v)
{
val_list1 = (String) dropdown.getSelectedItem();
val_list2 = (String) dropdown2.getSelectedItem();
// val_list3 = (String) dropdown3.getSelectedItem();
int week = 0, daytime = 0;
if (val_list2.equals("Βραδινό"))
daytime = 2;
else
daytime = 1;
if (val_list1.equals("1η Εβδομάδα")) {
week = 1;
} else if (val_list1.equals("2η Εβδομάδα")) {
week = 2;
} else if (val_list1.equals("3η Εβδομάδα")) {
week = 3;
} else if (val_list1.equals("4η Εβδομάδα")) {
week = 4;
}
Intent i = new Intent(this, FoodActivity.class);
//Create the bundles
Bundle bundle1 = new Bundle();
Bundle bundle2 = new Bundle();
String weekSt = String.valueOf(week);
String daytimeSt = String.valueOf(daytime);
//Add your data to bundle
bundle1.putString("week", weekSt);
bundle1.putString("daytime", daytimeSt);
//Add the bundle to the intent
i.putExtras(bundle1);
i.putExtras(bundle2);
startActivity(i);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
finish();//na mporei to back button na paei pisw
}
return super.onOptionsItemSelected(item);
}
public void foodVisitHistory(View v)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://studies.aegean.gr/node/216"));
startActivity(browserIntent);
}
public void freeFoodCheck(View v)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://studies.aegean.gr/node/17"));
startActivity(browserIntent);
}
/* public void Dialog(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//exits the application
public void onClick(DialogInterface dialog, int id) {
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}*/
}
| gpl-3.0 |
VladX/Xwing-Engine | src/external/cityhash_constexpr.hpp | 135 | /* Following code was taken from https://github.com/LordJZ/consthash */
namespace external
{
#include "consthash/cityhash64.hxx"
};
| gpl-3.0 |
peterpilgrim/digital-javaee7-public | ch08/xen-force-angularjs/src/main/webapp/app/services/iso-countries.js | 29708 | // A shared ISO countries
angular.module('isoCountries', [])
.factory( 'isoCountries', function ($rootScope) {
var isoCountries = { };
isoCountries.countryToCodeArrayMap = [
{ "country": "United Kingdom - Citizen", "code": "GBR" },
{ "country": "United Kingdom - Dependent territories citizen", "code": "GBD" },
{ "country": "United Kingdom - National (overseas)", "code": "GBN" },
{ "country": "United Kingdom - Overseas citizen", "code": "GBO" },
{ "country": "United Kingdom - Protected Person", "code": "GBP" },
{ "country": "United Kingdom - Subject", "code": "GBS" },
{ "country": "Afghanistan", "code": "AFG" },
{ "country": "Albania", "code": "ALB" },
{ "country": "Algeria", "code": "DZA" },
{ "country": "American Samoa", "code": "ASM" },
{ "country": "Andorra", "code": "AND" },
{ "country": "Angola", "code": "AGO" },
{ "country": "Anguilla", "code": "AIA" },
{ "country": "Antarctica", "code": "ATA" },
{ "country": "Antigua and Barbuda", "code": "ATG" },
{ "country": "Argentina", "code": "ARG" },
{ "country": "Armenia", "code": "ARM" },
{ "country": "Aruba", "code": "ABW" },
{ "country": "Australia", "code": "AUS" },
{ "country": "Austria", "code": "AUT" },
{ "country": "Azerbaijan", "code": "AZE" },
{ "country": "Bahamas", "code": "BHS" },
{ "country": "Bahrain", "code": "BHR" },
{ "country": "Bangladesh", "code": "BGD" },
{ "country": "Barbados", "code": "BRB" },
{ "country": "Belarus", "code": "BLR" },
{ "country": "Belgium", "code": "BEL" },
{ "country": "Belize", "code": "BLZ" },
{ "country": "Benin", "code": "BEN" },
{ "country": "Bermuda", "code": "BMU" },
{ "country": "Bhutan", "code": "BTN" },
{ "country": "Bolivia", "code": "BOL" },
{ "country": "Bosnia and Herzegovina", "code": "BIH" },
{ "country": "Botswana", "code": "BWA" },
{ "country": "Bouvet Island", "code": "BVT" },
{ "country": "Brazil", "code": "BRA" },
{ "country": "British Indian Ocean Territory", "code": "IOT" },
{ "country": "Brunei Darussalam", "code": "BRN" },
{ "country": "Bulgaria", "code": "BGR" },
{ "country": "Burkina Faso", "code": "BFA" },
{ "country": "Burundi", "code": "BDI" },
{ "country": "Cambodia", "code": "KHM" },
{ "country": "Cameroon", "code": "CMR" },
{ "country": "Canada", "code": "CAN" },
{ "country": "Cape Verde", "code": "CPV" },
{ "country": "Cayman Islands", "code": "CYM" },
{ "country": "Central African Republic", "code": "CAF" },
{ "country": "Chad", "code": "TCD" },
{ "country": "Chile", "code": "CHL" },
{ "country": "China", "code": "CHN" },
{ "country": "Christmas Island", "code": "CXR" },
{ "country": "Cocos (Keeling) Islands", "code": "CCK" },
{ "country": "Colombia", "code": "COL" },
{ "country": "Comoros", "code": "COM" },
{ "country": "Congo", "code": "COG" },
{ "country": "Cook Islands", "code": "COK" },
{ "country": "Costa Rica", "code": "CRI" },
{ "country": "Croatia", "code": "HRV" },
{ "country": "Cuba", "code": "CUB" },
{ "country": "Cyprus", "code": "CYP" },
{ "country": "Czech Republic", "code": "CZE" },
{ "country": "Côte d'Ivoire", "code": "CIV" },
{ "country": "Democratic People's Republic of Korea", "code": "PRK" },
{ "country": "Democratic Republic of the Congo", "code": "COD" },
{ "country": "Denmark", "code": "DNK" },
{ "country": "Djibouti", "code": "DJI" },
{ "country": "Dominica", "code": "DMA" },
{ "country": "Dominican Republic", "code": "DOM" },
{ "country": "East Timor", "code": "TMP" },
{ "country": "Ecuador", "code": "ECU" },
{ "country": "Egypt", "code": "EGY" },
{ "country": "El Salvador", "code": "SLV" },
{ "country": "Equatorial Guinea", "code": "GNQ" },
{ "country": "Eritrea", "code": "ERI" },
{ "country": "Estonia", "code": "EST" },
{ "country": "Ethiopia", "code": "ETH" },
{ "country": "Faeroe Islands", "code": "FRO" },
{ "country": "Falkland Islands (Malvinas)", "code": "FLK" },
{ "country": "Fiji", "code": "FJI" },
{ "country": "Finland", "code": "FIN" },
{ "country": "France", "code": "FRA" },
{ "country": "France, Metropolitan", "code": "FXX" },
{ "country": "French Guiana", "code": "GUF" },
{ "country": "French Polynesia", "code": "PYF" },
{ "country": "Gabon", "code": "GAB" },
{ "country": "Gambia", "code": "GMB" },
{ "country": "Georgia", "code": "GEO" },
{ "country": "Germany", "code": "D" },
{ "country": "Ghana", "code": "GHA" },
{ "country": "Gibraltar", "code": "GIB" },
{ "country": "Greece", "code": "GRC" },
{ "country": "Greenland", "code": "GRL" },
{ "country": "Grenada", "code": "GRD" },
{ "country": "Guadeloupe", "code": "GLP" },
{ "country": "Guam", "code": "GUM" },
{ "country": "Guatemala", "code": "GTM" },
{ "country": "Guinea", "code": "GIN" },
{ "country": "Guinea-Bissau", "code": "GNB" },
{ "country": "Guyana", "code": "GUY" },
{ "country": "Haiti", "code": "HTI" },
{ "country": "Heard and McDonald Islands", "code": "HMD" },
{ "country": "Holy See (Vatican City State)", "code": "VAT" },
{ "country": "Honduras", "code": "HND" },
{ "country": "Hong Kong", "code": "HKG" },
{ "country": "Hungary", "code": "HUN" },
{ "country": "Iceland", "code": "ISL" },
{ "country": "India", "code": "IND" },
{ "country": "Indonesia", "code": "IDN" },
{ "country": "Iran, Islamic Republic of", "code": "IRN" },
{ "country": "Iraq", "code": "IRQ" },
{ "country": "Ireland", "code": "IRL" },
{ "country": "Israel", "code": "ISR" },
{ "country": "Italy", "code": "ITA" },
{ "country": "Jamaica", "code": "JAM" },
{ "country": "Japan", "code": "JPN" },
{ "country": "Jordan", "code": "JOR" },
{ "country": "Kazakhstan", "code": "KAZ" },
{ "country": "Kenya", "code": "KEN" },
{ "country": "Kiribati", "code": "KIR" },
{ "country": "Kuwait", "code": "KWT" },
{ "country": "Kyrgyzstan", "code": "KGZ" },
{ "country": "Lao People's Democratic Republic", "code": "LAO" },
{ "country": "Latvia", "code": "LVA" },
{ "country": "Lebanon", "code": "LBN" },
{ "country": "Lesotho", "code": "LSO" },
{ "country": "Liberia", "code": "LBR" },
{ "country": "Libyan Arab Jamahiriya", "code": "LBY" },
{ "country": "Liechtenstein", "code": "LIE" },
{ "country": "Lithuania", "code": "LTU" },
{ "country": "Luxembourg", "code": "LUX" },
{ "country": "Madagascar", "code": "MDG" },
{ "country": "Malawi", "code": "MWI" },
{ "country": "Malaysia", "code": "MYS" },
{ "country": "Maldives", "code": "MDV" },
{ "country": "Mali", "code": "MLI" },
{ "country": "Malta", "code": "MLT" },
{ "country": "Marshall Islands", "code": "MHL" },
{ "country": "Martinique", "code": "MTQ" },
{ "country": "Mauritania", "code": "MRT" },
{ "country": "Mauritius", "code": "MUS" },
{ "country": "Mayotte", "code": "MYT" },
{ "country": "Mexico", "code": "MEX" },
{ "country": "Micronesia, Federated States of", "code": "FSM" },
{ "country": "Monaco", "code": "MCO" },
{ "country": "Mongolia", "code": "MNG" },
{ "country": "Montserrat", "code": "MSR" },
{ "country": "Morocco", "code": "MAR" },
{ "country": "Mozambique", "code": "MOZ" },
{ "country": "Myanmar", "code": "MMR" },
{ "country": "Namibia", "code": "NAM" },
{ "country": "Nauru", "code": "NRU" },
{ "country": "Nepal", "code": "NPL" },
{ "country": "Netherlands Antilles", "code": "ANT" },
{ "country": "Netherlands, Kingdom of the", "code": "NLD" },
{ "country": "Neutral Zone", "code": "NTZ" },
{ "country": "New Caledonia", "code": "NCL" },
{ "country": "New Zealand", "code": "NZL" },
{ "country": "Nicaragua", "code": "NIC" },
{ "country": "Niger", "code": "NER" },
{ "country": "Nigeria", "code": "NGA" },
{ "country": "Niue", "code": "NIU" },
{ "country": "Norfolk Island", "code": "NFK" },
{ "country": "Northern Mariana Islands", "code": "MNP" },
{ "country": "Norway", "code": "NOR" },
{ "country": "Oman", "code": "OMN" },
{ "country": "Pakistan", "code": "PAK" },
{ "country": "Palau", "code": "PLW" },
{ "country": "Panama", "code": "PAN" },
{ "country": "Papua New Guinea", "code": "PNG" },
{ "country": "Paraguay", "code": "PRY" },
{ "country": "Peru", "code": "PER" },
{ "country": "Philippines", "code": "PHL" },
{ "country": "Pitcairn", "code": "PCN" },
{ "country": "Poland", "code": "POL" },
{ "country": "Portugal", "code": "PRT" },
{ "country": "Puerto Rico", "code": "PRI" },
{ "country": "Qatar", "code": "QAT" },
{ "country": "Refugee (non-convention)", "code": "XXC" },
{ "country": "Republic of Korea", "code": "KOR" },
{ "country": "Republic of Moldova", "code": "MDA" },
{ "country": "Romania", "code": "ROM" },
{ "country": "Russian Federation", "code": "RUS" },
{ "country": "Rwanda", "code": "RWA" },
{ "country": "Réunion", "code": "REU" },
{ "country": "Saint Helena", "code": "SHN" },
{ "country": "Saint Kitts and Nevis", "code": "KNA" },
{ "country": "Saint Lucia", "code": "LCA" },
{ "country": "Saint Pierre and Miquelon", "code": "SPM" },
{ "country": "Saint Vincent and the Grenadines", "code": "VCT" },
{ "country": "Samoa", "code": "WSM" },
{ "country": "San Marino", "code": "SMR" },
{ "country": "Sao Tome and Principe", "code": "STP" },
{ "country": "Saudi Arabia", "code": "SAU" },
{ "country": "Senegal", "code": "SEN" },
{ "country": "Seychelles", "code": "SYC" },
{ "country": "Sierra Leone", "code": "SLE" },
{ "country": "Singapore", "code": "SGP" },
{ "country": "Slovakia", "code": "SVK" },
{ "country": "Slovenia", "code": "SVN" },
{ "country": "Solomon Islands", "code": "SLB" },
{ "country": "Somalia", "code": "SOM" },
{ "country": "South Africa", "code": "ZAF" },
{ "country": "South Georgia and the South Sandwich Island", "code": "SGS" },
{ "country": "Spain", "code": "ESP" },
{ "country": "Sri Lanka", "code": "LKA" },
{ "country": "Stateless (per Article 1 of 1954 convention)", "code": "XXA" },
{ "country": "Sudan", "code": "SDN" },
{ "country": "Suriname", "code": "SUR" },
{ "country": "Svalbard and Jan Mayen Islands", "code": "SJM" },
{ "country": "Swaziland", "code": "SWZ" },
{ "country": "Sweden", "code": "SWE" },
{ "country": "Switzerland", "code": "CHE" },
{ "country": "Syrian Arab Republic", "code": "SYR" },
{ "country": "Taiwan Province of China", "code": "TWN" },
{ "country": "Tajikistan", "code": "TJK" },
{ "country": "Thailand", "code": "THA" },
{ "country": "The former Yugoslav Republic of Macedonia", "code": "MKD" },
{ "country": "Togo", "code": "TGO" },
{ "country": "Tokelau", "code": "TKL" },
{ "country": "Tonga", "code": "TON" },
{ "country": "Trinidad and Tobago", "code": "TTO" },
{ "country": "Tunisia", "code": "TUN" },
{ "country": "Turkey", "code": "TUR" },
{ "country": "Turkmenistan", "code": "TKM" },
{ "country": "Turks and Caicos Islands", "code": "TCA" },
{ "country": "Tuvalu", "code": "TUV" },
{ "country": "Uganda", "code": "UGA" },
{ "country": "Ukraine", "code": "UKR" },
{ "country": "United Arab Emirates", "code": "ARE" },
{ "country": "United Republic of Tanzania", "code": "TZA" },
{ "country": "United States of America", "code": "USA" },
{ "country": "United States of America Minor Outlying Islands", "code": "UMI" },
{ "country": "Unspecified / Unknown", "code": "XXX" },
{ "country": "Uruguay", "code": "URY" },
{ "country": "Uzbekistan", "code": "UZB" },
{ "country": "Vanuatu", "code": "VUT" },
{ "country": "Venezuela", "code": "VEN" },
{ "country": "Viet Nam", "code": "VNM" },
{ "country": "Virgin Islands (Great Britian)", "code": "VGB" },
{ "country": "Virgin Islands (United States)", "code": "VIR" },
{ "country": "Wallis and Futuna Islands", "code": "WLF" },
{ "country": "Western Sahara", "code": "ESH" },
{ "country": "Yemen", "code": "YEM" },
{ "country": "Zaire", "code": "ZAR" },
{ "country": "Zambia", "code": "ZMB" },
{ "country": "Zimbabwe", "code": "ZWE" },
{ "country": "amended by 1967 protocol)", "code": "XXB" },
{ "country": "indicates an UN offical)", "code": "UNO" },
{ "country": "specialized agency official", "code": "UNA" },
];
isoCountries.codeToCountryArrayMap = [
{ "code": "ABW", "country": "Aruba" },
{ "code": "AFG", "country": "Afghanistan" },
{ "code": "AGO", "country": "Angola" },
{ "code": "AIA", "country": "Anguilla" },
{ "code": "ALB", "country": "Albania" },
{ "code": "AND", "country": "Andorra" },
{ "code": "ANT", "country": "Netherlands Antilles" },
{ "code": "ARE", "country": "United Arab Emirates" },
{ "code": "ARG", "country": "Argentina" },
{ "code": "ARM", "country": "Armenia" },
{ "code": "ASM", "country": "American Samoa" },
{ "code": "ATA", "country": "Antarctica" },
{ "code": "ATG", "country": "Antigua and Barbuda" },
{ "code": "AUS", "country": "Australia" },
{ "code": "AUT", "country": "Austria" },
{ "code": "AZE", "country": "Azerbaijan" },
{ "code": "BDI", "country": "Burundi" },
{ "code": "BEL", "country": "Belgium" },
{ "code": "BEN", "country": "Benin" },
{ "code": "BFA", "country": "Burkina Faso" },
{ "code": "BGD", "country": "Bangladesh" },
{ "code": "BGR", "country": "Bulgaria" },
{ "code": "BHR", "country": "Bahrain" },
{ "code": "BHS", "country": "Bahamas" },
{ "code": "BIH", "country": "Bosnia and Herzegovina" },
{ "code": "BLR", "country": "Belarus" },
{ "code": "BLZ", "country": "Belize" },
{ "code": "BMU", "country": "Bermuda" },
{ "code": "BOL", "country": "Bolivia" },
{ "code": "BRA", "country": "Brazil" },
{ "code": "BRB", "country": "Barbados" },
{ "code": "BRN", "country": "Brunei Darussalam" },
{ "code": "BTN", "country": "Bhutan" },
{ "code": "BVT", "country": "Bouvet Island" },
{ "code": "BWA", "country": "Botswana" },
{ "code": "CAF", "country": "Central African Republic" },
{ "code": "CAN", "country": "Canada" },
{ "code": "CCK", "country": "Cocos (Keeling) Islands" },
{ "code": "CHE", "country": "Switzerland" },
{ "code": "CHL", "country": "Chile" },
{ "code": "CHN", "country": "China" },
{ "code": "CIV", "country": "Côte d'Ivoire" },
{ "code": "CMR", "country": "Cameroon" },
{ "code": "COD", "country": "Democratic Republic of the Congo" },
{ "code": "COG", "country": "Congo" },
{ "code": "COK", "country": "Cook Islands" },
{ "code": "COL", "country": "Colombia" },
{ "code": "COM", "country": "Comoros" },
{ "code": "CPV", "country": "Cape Verde" },
{ "code": "CRI", "country": "Costa Rica" },
{ "code": "CUB", "country": "Cuba" },
{ "code": "CXR", "country": "Christmas Island" },
{ "code": "CYM", "country": "Cayman Islands" },
{ "code": "CYP", "country": "Cyprus" },
{ "code": "CZE", "country": "Czech Republic" },
{ "code": "D", "country": "Germany" },
{ "code": "DJI", "country": "Djibouti" },
{ "code": "DMA", "country": "Dominica" },
{ "code": "DNK", "country": "Denmark" },
{ "code": "DOM", "country": "Dominican Republic" },
{ "code": "DZA", "country": "Algeria" },
{ "code": "ECU", "country": "Ecuador" },
{ "code": "EGY", "country": "Egypt" },
{ "code": "ERI", "country": "Eritrea" },
{ "code": "ESH", "country": "Western Sahara" },
{ "code": "ESP", "country": "Spain" },
{ "code": "EST", "country": "Estonia" },
{ "code": "ETH", "country": "Ethiopia" },
{ "code": "FIN", "country": "Finland" },
{ "code": "FJI", "country": "Fiji" },
{ "code": "FLK", "country": "Falkland Islands (Malvinas)" },
{ "code": "FRA", "country": "France" },
{ "code": "FRO", "country": "Faeroe Islands" },
{ "code": "FSM", "country": "Micronesia, Federated States of" },
{ "code": "FXX", "country": "France, Metropolitan" },
{ "code": "GAB", "country": "Gabon" },
{ "code": "GBD", "country": "United Kingdom - Dependent territories citizen" },
{ "code": "GBN", "country": "United Kingdom - National (overseas)" },
{ "code": "GBO", "country": "United Kingdom - Overseas citizen" },
{ "code": "GBP", "country": "United Kingdom - Protected Person" },
{ "code": "GBR", "country": "United Kingdom - Citizen" },
{ "code": "GBS", "country": "United Kingdom - Subject" },
{ "code": "GEO", "country": "Georgia" },
{ "code": "GHA", "country": "Ghana" },
{ "code": "GIB", "country": "Gibraltar" },
{ "code": "GIN", "country": "Guinea" },
{ "code": "GLP", "country": "Guadeloupe" },
{ "code": "GMB", "country": "Gambia" },
{ "code": "GNB", "country": "Guinea-Bissau" },
{ "code": "GNQ", "country": "Equatorial Guinea" },
{ "code": "GRC", "country": "Greece" },
{ "code": "GRD", "country": "Grenada" },
{ "code": "GRL", "country": "Greenland" },
{ "code": "GTM", "country": "Guatemala" },
{ "code": "GUF", "country": "French Guiana" },
{ "code": "GUM", "country": "Guam" },
{ "code": "GUY", "country": "Guyana" },
{ "code": "HKG", "country": "Hong Kong" },
{ "code": "HMD", "country": "Heard and McDonald Islands" },
{ "code": "HND", "country": "Honduras" },
{ "code": "HRV", "country": "Croatia" },
{ "code": "HTI", "country": "Haiti" },
{ "code": "HUN", "country": "Hungary" },
{ "code": "IDN", "country": "Indonesia" },
{ "code": "IND", "country": "India" },
{ "code": "IOT", "country": "British Indian Ocean Territory" },
{ "code": "IRL", "country": "Ireland" },
{ "code": "IRN", "country": "Iran, Islamic Republic of" },
{ "code": "IRQ", "country": "Iraq" },
{ "code": "ISL", "country": "Iceland" },
{ "code": "ISR", "country": "Israel" },
{ "code": "ITA", "country": "Italy" },
{ "code": "JAM", "country": "Jamaica" },
{ "code": "JOR", "country": "Jordan" },
{ "code": "JPN", "country": "Japan" },
{ "code": "KAZ", "country": "Kazakhstan" },
{ "code": "KEN", "country": "Kenya" },
{ "code": "KGZ", "country": "Kyrgyzstan" },
{ "code": "KHM", "country": "Cambodia" },
{ "code": "KIR", "country": "Kiribati" },
{ "code": "KNA", "country": "Saint Kitts and Nevis" },
{ "code": "KOR", "country": "Republic of Korea" },
{ "code": "KWT", "country": "Kuwait" },
{ "code": "LAO", "country": "Lao People's Democratic Republic" },
{ "code": "LBN", "country": "Lebanon" },
{ "code": "LBR", "country": "Liberia" },
{ "code": "LBY", "country": "Libyan Arab Jamahiriya" },
{ "code": "LCA", "country": "Saint Lucia" },
{ "code": "LIE", "country": "Liechtenstein" },
{ "code": "LKA", "country": "Sri Lanka" },
{ "code": "LSO", "country": "Lesotho" },
{ "code": "LTU", "country": "Lithuania" },
{ "code": "LUX", "country": "Luxembourg" },
{ "code": "LVA", "country": "Latvia" },
{ "code": "MAR", "country": "Morocco" },
{ "code": "MCO", "country": "Monaco" },
{ "code": "MDA", "country": "Republic of Moldova" },
{ "code": "MDG", "country": "Madagascar" },
{ "code": "MDV", "country": "Maldives" },
{ "code": "MEX", "country": "Mexico" },
{ "code": "MHL", "country": "Marshall Islands" },
{ "code": "MKD", "country": "The former Yugoslav Republic of Macedonia" },
{ "code": "MLI", "country": "Mali" },
{ "code": "MLT", "country": "Malta" },
{ "code": "MMR", "country": "Myanmar" },
{ "code": "MNG", "country": "Mongolia" },
{ "code": "MNP", "country": "Northern Mariana Islands" },
{ "code": "MOZ", "country": "Mozambique" },
{ "code": "MRT", "country": "Mauritania" },
{ "code": "MSR", "country": "Montserrat" },
{ "code": "MTQ", "country": "Martinique" },
{ "code": "MUS", "country": "Mauritius" },
{ "code": "MWI", "country": "Malawi" },
{ "code": "MYS", "country": "Malaysia" },
{ "code": "MYT", "country": "Mayotte" },
{ "code": "NAM", "country": "Namibia" },
{ "code": "NCL", "country": "New Caledonia" },
{ "code": "NER", "country": "Niger" },
{ "code": "NFK", "country": "Norfolk Island" },
{ "code": "NGA", "country": "Nigeria" },
{ "code": "NIC", "country": "Nicaragua" },
{ "code": "NIU", "country": "Niue" },
{ "code": "NLD", "country": "Netherlands, Kingdom of the" },
{ "code": "NOR", "country": "Norway" },
{ "code": "NPL", "country": "Nepal" },
{ "code": "NRU", "country": "Nauru" },
{ "code": "NTZ", "country": "Neutral Zone" },
{ "code": "NZL", "country": "New Zealand" },
{ "code": "OMN", "country": "Oman" },
{ "code": "PAK", "country": "Pakistan" },
{ "code": "PAN", "country": "Panama" },
{ "code": "PCN", "country": "Pitcairn" },
{ "code": "PER", "country": "Peru" },
{ "code": "PHL", "country": "Philippines" },
{ "code": "PLW", "country": "Palau" },
{ "code": "PNG", "country": "Papua New Guinea" },
{ "code": "POL", "country": "Poland" },
{ "code": "PRI", "country": "Puerto Rico" },
{ "code": "PRK", "country": "Democratic People's Republic of Korea" },
{ "code": "PRT", "country": "Portugal" },
{ "code": "PRY", "country": "Paraguay" },
{ "code": "PYF", "country": "French Polynesia" },
{ "code": "QAT", "country": "Qatar" },
{ "code": "REU", "country": "Réunion" },
{ "code": "ROM", "country": "Romania" },
{ "code": "RUS", "country": "Russian Federation" },
{ "code": "RWA", "country": "Rwanda" },
{ "code": "SAU", "country": "Saudi Arabia" },
{ "code": "SDN", "country": "Sudan" },
{ "code": "SEN", "country": "Senegal" },
{ "code": "SGP", "country": "Singapore" },
{ "code": "SGS", "country": "South Georgia and the South Sandwich Island" },
{ "code": "SHN", "country": "Saint Helena" },
{ "code": "SJM", "country": "Svalbard and Jan Mayen Islands" },
{ "code": "SLB", "country": "Solomon Islands" },
{ "code": "SLE", "country": "Sierra Leone" },
{ "code": "SLV", "country": "El Salvador" },
{ "code": "SMR", "country": "San Marino" },
{ "code": "SOM", "country": "Somalia" },
{ "code": "SPM", "country": "Saint Pierre and Miquelon" },
{ "code": "STP", "country": "Sao Tome and Principe" },
{ "code": "SUR", "country": "Suriname" },
{ "code": "SVK", "country": "Slovakia" },
{ "code": "SVN", "country": "Slovenia" },
{ "code": "SWE", "country": "Sweden" },
{ "code": "SWZ", "country": "Swaziland" },
{ "code": "SYC", "country": "Seychelles" },
{ "code": "SYR", "country": "Syrian Arab Republic" },
{ "code": "TCA", "country": "Turks and Caicos Islands" },
{ "code": "TCD", "country": "Chad" },
{ "code": "TGO", "country": "Togo" },
{ "code": "THA", "country": "Thailand" },
{ "code": "TJK", "country": "Tajikistan" },
{ "code": "TKL", "country": "Tokelau" },
{ "code": "TKM", "country": "Turkmenistan" },
{ "code": "TMP", "country": "East Timor" },
{ "code": "TON", "country": "Tonga" },
{ "code": "TTO", "country": "Trinidad and Tobago" },
{ "code": "TUN", "country": "Tunisia" },
{ "code": "TUR", "country": "Turkey" },
{ "code": "TUV", "country": "Tuvalu" },
{ "code": "TWN", "country": "Taiwan Province of China" },
{ "code": "TZA", "country": "United Republic of Tanzania" },
{ "code": "UGA", "country": "Uganda" },
{ "code": "UKR", "country": "Ukraine" },
{ "code": "UMI", "country": "United States of America Minor Outlying Islands" },
{ "code": "UNA", "country": "specialized agency official" },
{ "code": "UNO", "country": "indicates an UN offical)" },
{ "code": "URY", "country": "Uruguay" },
{ "code": "USA", "country": "United States of America" },
{ "code": "UZB", "country": "Uzbekistan" },
{ "code": "VAT", "country": "Holy See (Vatican City State)" },
{ "code": "VCT", "country": "Saint Vincent and the Grenadines" },
{ "code": "VEN", "country": "Venezuela" },
{ "code": "VGB", "country": "Virgin Islands (Great Britian)" },
{ "code": "VIR", "country": "Virgin Islands (United States)" },
{ "code": "VNM", "country": "Viet Nam" },
{ "code": "VUT", "country": "Vanuatu" },
{ "code": "WLF", "country": "Wallis and Futuna Islands" },
{ "code": "WSM", "country": "Samoa" },
{ "code": "XXA", "country": "Stateless (per Article 1 of 1954 convention)" },
{ "code": "XXB", "country": "amended by 1967 protocol)" },
{ "code": "XXC", "country": "Refugee (non-convention)" },
{ "code": "XXX", "country": "Unspecified / Unknown" },
{ "code": "YEM", "country": "Yemen" },
{ "code": "ZAF", "country": "South Africa" },
{ "code": "ZAR", "country": "Zaire" },
{ "code": "ZMB", "country": "Zambia" },
{ "code": "ZWE", "country": "Zimbabwe" },
];
return isoCountries;
});
| gpl-3.0 |
UdaraAlwis/Xamarin-Playground | XFAnimatingTextColorButton/XFAnimatingTextColorButton/XFAnimatingTextColorButton.Windows/Properties/AssemblyInfo.cs | 1104 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XFAnimatingTextColorButton.Windows.Windows")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XFAnimatingTextColorButton.Windows.Windows")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | gpl-3.0 |
HiSPARC/station-software | user/hsmonitor/test/test_HiSPARCEvent.py | 2805 | import sys
sys.path.append("..")
import unittest
import struct
from HiSPARCEvent import HiSPARCEvent
from parse_and_check import parse_and_check_data
from load_message import load_hisparc_message
class TestHiSPARCEvent(unittest.TestCase):
def test_event(self):
event = load_hisparc_message('test_data/Event.txt')
parse_and_check_data(self, event, 1, HiSPARCEvent, 'CIC')
def pack_trace(self, trace):
"""Space efficiently pack 12-bit trace values into 8-bit values
:param trace: list with even number of 12-bit values (0-4095).
:return: struct with 1.5 times the length of trace in bytes.
"""
byte_trace = []
for i in xrange(0, len(trace), 2):
# First byte of the first 12 bits
byte_trace.append((trace[i] >> 4))
# Last 4 bits the first 12 bits and first 4 bits of second 12 bits
byte_trace.append(((trace[i] & 15) << 4) + (trace[i + 1] >> 8))
# Last byte of the second 12 bits
byte_trace.append(trace[i + 1] & 255)
packed_trace = struct.pack('%dB' % (len(trace) / 2 * 3), *byte_trace)
return packed_trace
def test_unpack_trace(self):
"""Test unpacking a trace
Example trace from station 508 event 1432684741282735016 detector 4.
"""
trace = [189, 197, 188, 198, 190, 196, 189, 199, 193, 249, 443,
1098, 1753, 2393, 2709, 3014, 3125, 3243, 3203, 3168,
3022, 2932, 2761, 2621, 2411, 2266, 2083, 1910, 1696,
1489, 1275, 1167, 1053, 968, 855, 783, 680, 654, 604,
595, 531, 509, 464, 457, 415, 409, 370, 380, 356, 354,
326, 343, 319, 324, 304, 305, 286, 299, 286, 306, 289,
314, 305, 314, 300, 300, 276, 284, 272, 286, 266, 265,
248, 253, 242, 257, 249, 251, 237, 247, 235, 248, 237,
248, 237, 247, 239, 245, 237, 253, 235, 250, 241, 239,
226, 230, 218, 236, 218, 231, 214, 225, 209, 219, 215,
227, 217, 224, 222, 260, 242, 241, 225, 226, 210, 226,
221, 228, 216, 226, 210, 217, 205, 218, 213, 222, 209,
214, 198, 211, 207, 216, 203, 218, 206, 232, 224, 229,
220, 230, 221, 235, 225, 229, 222, 235, 225, 229, 212,
227, 216, 230, 220, 220, 206, 207, 192, 200, 197, 215]
packed_trace = self.pack_trace(trace)
unpacked_trace = HiSPARCEvent.unpack_trace(packed_trace)
self.assertEqual(trace, [int(x) for x in unpacked_trace.split(',')
if not x == ''])
self.assertRaises(Exception, HiSPARCEvent.unpack_trace,
packed_trace[:-1])
if __name__ == '__main__':
unittest.main()
| gpl-3.0 |
GFG/dto-marketplace | src/DTOMarketplace/Context/Manager.php | 488 | <?php
namespace GFG\DTOMarketplace\Context;
class Manager extends \GFG\DTOContext\Manager
{
/**
* @param string $contextName
* @param string $dataWrapperName
* @param array $dataWrapperData
* @return mixed
*/
public function build(
$contextName,
$dataWrapperName,
array $dataWrapperData = []
) {
$dataWrapper = new $dataWrapperName($dataWrapperData);
return $this->create($contextName, $dataWrapper);
}
}
| gpl-3.0 |
projectestac/alexandria | html/langpacks/es/gradereport_history.php | 3034 | <?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Strings for component 'gradereport_history', language 'es', version '3.11'.
*
* @package gradereport_history
* @category string
* @copyright 1999 Martin Dougiamas and contributors
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['allgradeitems'] = 'Todos los ítems de calificación';
$string['allgraders'] = 'Todas las calificaciones';
$string['datefrom'] = 'Fecha desde';
$string['datetime'] = 'Fecha y Hora';
$string['dateto'] = 'Fecha hasta';
$string['deleteditemid'] = 'Borrado item con id {$a}';
$string['errajaxsearch'] = 'Error en la búsqueda de usuarios';
$string['eventgradereportviewed'] = 'Informe de historial de notas visto';
$string['excluded'] = 'Excluir de los cálculos';
$string['exportfilename'] = 'Historial de notas';
$string['feedbacktext'] = 'Texto de retroalimentación';
$string['finishselectingusers'] = 'Finalizar selección de usuarios';
$string['foundnusers'] = '{$a} usuarios encontrados';
$string['foundoneuser'] = '1 usuario encontrado';
$string['gradenew'] = 'Calificación revisada';
$string['gradeold'] = 'Calificación original';
$string['grader'] = 'Calificador';
$string['history:view'] = 'Ver el historial de calificaciones';
$string['historyperpage'] = 'Historial de entradas por página';
$string['historyperpage_help'] = 'Este ajuste determina el número de entradas de historial mostradas por página en el informe de historial.';
$string['loadmoreusers'] = 'Cargar más usuarios...';
$string['pluginname'] = 'Historial de calificación';
$string['preferences'] = 'Preferencias del historial de calificaciones';
$string['privacy:metadata'] = 'El Informe de Historia de la calificación solamente muestra datos almacenados en otros sitios.';
$string['revisedonly'] = 'Solamente calificaciones revisadas';
$string['revisedonly_help'] = 'Mostrar solamente calificaciones que han sido revisadas.
Esto quiere decir solamente las entradas las cuales resultan en el cambio de una calificación están listadas.';
$string['selectedusers'] = 'Usuarios Seleccionados';
$string['selectuser'] = 'Seleccionar usuario';
$string['selectusers'] = 'Seleccionar usuarios';
$string['source'] = 'Fuente';
$string['useractivityfeedback'] = '{$a} retroalimentación';
$string['useractivitygrade'] = '{$a} calificación';
| gpl-3.0 |
dac922/octave-pkg-octave | src/main.cc | 1969 | /*
Copyright (C) 2012 John W. Eaton
This file is part of Octave.
Octave 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.
Octave 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 Octave; see the file COPYING. If not, see
<http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "defaults.h"
#include "octave.h"
#include "octave-gui.h"
#include "sysdep.h"
int
main (int argc, char **argv)
{
int retval = 0;
octave_process_command_line (argc, argv);
sysdep_init ();
install_defaults ();
if (octave_starting_gui ())
retval = octave_start_gui (argc, argv);
else
{
octave_initialize_interpreter (argc, argv, 0);
retval = octave_execute_interpreter ();
}
return retval;
}
/*!
@mainpage Source code documentation for GNU Octave
GNU Octave is a high-level language, primarily intended for numerical
computations. It provides a convenient interactive command line
interface for solving linear and nonlinear problems numerically, and
for performing other numerical experiments. It may also be used as a
batch-oriented language for data processing.
GNU Octave is free software. You may redistribute it and/or modify it
under the terms of the <a href="http://www.gnu.org/licenses/">GNU
General Public License</a> as published by the Free Software Foundation.
This is the developer documentation for Octave's own source code. It is
intended to help for hacking Octave. It may also be useful for
understanding the Octave API when writing your own .oct files.
*/
| gpl-3.0 |
mbcxqcw2/heimdall-astro-code-clone | Applications/heimdall.C | 5884 | /***************************************************************************
*
* Copyright (C) 2012 by Ben Barsdell and Andrew Jameson
* Licensed under the Academic Free License version 2.1
*
***************************************************************************/
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <sstream>
#include <fstream>
#include <iomanip>
#include <vector>
#include "hd/parse_command_line.h"
#include "hd/default_params.h"
#include "hd/pipeline.h"
#include "hd/error.h"
// input formats supported
#include "hd/DataSource.h"
#include "hd/SigprocFile.h"
#ifdef HAVE_PSRDADA
#include "hd/PSRDadaRingBuffer.h"
#endif
#include "hd/stopwatch.h"
int main(int argc, char* argv[])
{
hd_params params;
hd_set_default_params(¶ms);
int ok = hd_parse_command_line(argc, argv, ¶ms);
size_t nsamps_gulp = params.nsamps_gulp;
if (ok < 0)
return 1;
DataSource* data_source = 0;
#ifdef HAVE_PSRDADA
if( params.dada_id != 0 ) {
if (params.verbosity)
cerr << "Createing PSRDADA client" << endl;
PSRDadaRingBuffer * d = new PSRDadaRingBuffer(params.dada_id);
// Read from psrdada ring buffer
if( !d || d->get_error() ) {
cerr << "ERROR: Failed to initialise connection to psrdada" << endl;
return -1;
}
if (params.verbosity)
cerr << "Connecting to ring buffer" << endl;
// connect to PSRDADA ring buffer
if (! d->connect())
{
cerr << "ERROR: Failed to connection to psrdada ring buffer" << endl;
return -1;
}
if (params.verbosity)
cerr << "Waiting for next header / data" << endl;
// wait for and then read next PSRDADA header/observation
if (! d->read_header())
{
cerr << "ERROR: Failed to connection to psrdada ring buffer" << endl;
return -1;
}
data_source = (DataSource *) d;
if (!params.override_beam)
params.beam = d->get_beam() - 1;
}
else
{
#endif
// Read from filterbank file
data_source = new SigprocFile(params.sigproc_file);
if( !data_source || data_source->get_error() ) {
cerr << "ERROR: Failed to open data file" << endl;
return -1;
}
#ifdef HAVE_PSRDADA
}
#endif
if (!params.override_beam)
if (data_source->get_beam() > 0)
params.beam = data_source->get_beam() - 1;
else
params.beam = 0;
params.f0 = data_source->get_f0();
params.df = data_source->get_df();
params.dt = data_source->get_tsamp();
if ( params.verbosity > 0)
cout << "processing beam " << (params.beam+1) << endl;
float tsamp = data_source->get_tsamp() / 1000000;
size_t stride = data_source->get_stride();
size_t nbits = data_source->get_nbit();
params.nchans = data_source->get_nchan();
params.utc_start = data_source->get_utc_start();
params.spectra_per_second = data_source->get_spectra_rate();
if ( params.verbosity >= 2)
cout << "allocating filterbank data vector for " << nsamps_gulp << " samples with size " << (nsamps_gulp * stride) << " bytes" << endl;
std::vector<hd_byte> filterbank(nsamps_gulp * stride);
bool stop_requested = false;
// Create the pipeline object
// --------------------------
hd_pipeline pipeline;
hd_error error;
error = hd_create_pipeline(&pipeline, params);
if( error != HD_NO_ERROR ) {
cerr << "ERROR: Pipeline creation failed" << endl;
cerr << " " << hd_get_error_string(error) << endl;
return -1;
}
// --------------------------
if( params.verbosity >= 1 ) {
cout << "Beginning data processing, requesting " << nsamps_gulp << " samples" << endl;
}
// start a timer for the whole pipeline
//Stopwatch pipeline_timer;
size_t total_nsamps = 0;
size_t nsamps_read = data_source->get_data (nsamps_gulp, (char*)&filterbank[0]);
size_t overlap = 0;
while( nsamps_read && !stop_requested ) {
if ( params.verbosity >= 1 ) {
cout << "Executing pipeline on new gulp of " << nsamps_read
<< " samples..." << endl;
}
//pipeline_timer.start();
hd_size nsamps_processed;
error = hd_execute(pipeline, &filterbank[0], nsamps_read+overlap, nbits,
total_nsamps, &nsamps_processed);
if (error == HD_NO_ERROR)
{
if (params.verbosity >= 1)
cout << "Processed " << nsamps_processed << " samples." << endl;
}
else if (error == HD_TOO_MANY_EVENTS)
{
if (params.verbosity >= 1)
cerr << "WARNING: hd_execute produces too many events, some data skipped" << endl;
}
else
{
cerr << "ERROR: Pipeline execution failed" << endl;
cerr << " " << hd_get_error_string(error) << endl;
hd_destroy_pipeline(pipeline);
return -1;
}
//pipeline_timer.stop();
//cout << "pipeline time: " << pipeline_timer.getTime() << " of " << (nsamps_read+overlap) * tsamp << endl;
//pipeline_timer.reset();
total_nsamps += nsamps_processed;
// Now we must 'rewind' to do samples that couldn't be processed
// Note: This assumes nsamps_gulp > 2*overlap
std::copy(&filterbank[nsamps_processed * stride],
&filterbank[(nsamps_read+overlap) * stride],
&filterbank[0]);
overlap += nsamps_read - nsamps_processed;
nsamps_read = data_source->get_data(nsamps_gulp - overlap,
(char*)&filterbank[overlap*stride]);
// at the end of data, never execute the pipeline
if (nsamps_read < nsamps_gulp - overlap)
stop_requested = 1;
}
if( params.verbosity >= 1 ) {
cout << "Successfully processed a total of " << total_nsamps
<< " samples." << endl;
}
if( params.verbosity >= 1 ) {
cout << "Shutting down..." << endl;
}
hd_destroy_pipeline(pipeline);
if( params.verbosity >= 1 ) {
cout << "All done." << endl;
}
}
| gpl-3.0 |
YoloSoftDE/YoloTrack | Source/MVC/Model/StateMachine/Impl/Util/CompatibleImage.cs | 2477 | using System;
using System.Drawing;
namespace YoloTrack.MVC.Model.StateMachine.Impl.Util
{
/// <summary>
/// Ultitily class for providing an native interface from a standard bitmap object to the
/// libraries image class (adapter).
/// </summary>
class CompatibleImage : Cognitec.FRsdk.Image
{
/// <summary>
/// Holds the original bitmap
/// </summary>
private System.Drawing.Bitmap color;
/// <summary>
/// Holds the pointer to the data
/// </summary>
private IntPtr data_ptr_color;
/// <summary>
/// Factory method for creating a Campatible image from standard bitmap
/// </summary>
/// <param name="orginal"></param>
/// <returns></returns>
public static CompatibleImage FromBitmap(Bitmap orginal)
{
CompatibleImage ci = new CompatibleImage()
{
color = new Bitmap(orginal)
};
ci.data_ptr_color = ci.color.LockBits(new Rectangle(0, 0, ci.color.Width, ci.color.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb).Scan0;
return ci;
}
/// <summary>
/// Getter for the raw color stream information
/// </summary>
/// <returns></returns>
public IntPtr colorRepresentation()
{
return data_ptr_color;
}
/// <summary>
/// Unused
/// </summary>
/// <returns></returns>
public IntPtr grayScaleRepresentation()
{
throw new NotImplementedException();
}
/// <summary>
/// Picture is always colorized
/// </summary>
/// <returns></returns>
public bool isColor()
{
return true;
}
/// <summary>
/// Unused
/// </summary>
/// <returns></returns>
public string name()
{
return "";
}
/// <summary>
/// The width of the bitmap
/// </summary>
/// <returns></returns>
public uint width()
{
return (uint)color.Width;
}
/// <summary>
/// The height of the bitmap
/// </summary>
/// <returns></returns>
public uint height()
{
return (uint)color.Height;
}
} // End class
} // End namespace
| gpl-3.0 |
ae-dschorsaanjo/HTCC | dl_json.php | 327 | <?php
header('Content-Type: application/json');
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Disposition: attachment; filename=team.json');
echo $_POST['json'];
exit;
| gpl-3.0 |
hartwigmedical/hmftools | hmf-common/src/main/java/com/hartwig/hmftools/common/serve/classification/EventPreprocessor.java | 196 | package com.hartwig.hmftools.common.serve.classification;
import org.jetbrains.annotations.NotNull;
public interface EventPreprocessor {
@NotNull
String apply(@NotNull String event);
}
| gpl-3.0 |
cbmsc-diti/firecast-comunidade-android | app/src/main/java/br/gov/sc/cbm/e193comunitario/data/FirecastClient.java | 1589 | package br.gov.sc.cbm.e193comunitario.data;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
import br.gov.sc.cbm.e193comunitario.data.events.OccurrencesFailedLoading;
import br.gov.sc.cbm.e193comunitario.data.events.OcurrencesFinishedLoading;
import br.gov.sc.cbm.e193comunitario.domain.Occurrence;
import br.gov.sc.cbm.e193comunitario.domain.OccurrenceRepository;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by bonet on 9/13/16.
*/
public class FirecastClient implements OccurrenceRepository{
private FirecastApi api;
public FirecastClient() {
api = buildApi();
}
public void getOccurrences() {
api.getOccurrences().enqueue(new Callback<List<Occurrence>>() {
@Override
public void onResponse(Call<List<Occurrence>> call, Response<List<Occurrence>> response) {
EventBus.getDefault().post(new OcurrencesFinishedLoading(response.body()));
}
@Override
public void onFailure(Call<List<Occurrence>> call, Throwable t) {
EventBus.getDefault().post(new OccurrencesFailedLoading());
}
});
}
private FirecastApi buildApi() {
return new Retrofit.Builder()
.baseUrl("http://aplicativosweb.cbm.sc.gov.br/e193comunitario/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(FirecastApi.class);
}
}
| gpl-3.0 |
zebraxxl/CIL2Java | StdLibs/corlib/System/Runtime/Remoting/Channels/ClientChannelSinkStack.cs | 4635 | using System.Runtime.InteropServices;
using System.Security;
using System.Runtime.Remoting.Messaging;
using System.IO;
using System;
namespace System.Runtime.Remoting.Channels
{
/// <summary>Holds the stack of client channel sinks that must be invoked during an asynchronous message response decoding.</summary>
[ComVisibleAttribute(true)]
[SecurityCriticalAttribute()]
public class ClientChannelSinkStack : IClientChannelSinkStack
{
public ClientChannelSinkStack()
{
throw new NotImplementedException();
}
/// <summary>Initializes a new instance of the <see cref="T:System.Runtime.Remoting.Channels.ClientChannelSinkStack" /> class with the specified reply sink.</summary><param name="replySink">The <see cref="T:System.Runtime.Remoting.Messaging.IMessageSink" /> that the current stack can use to reply to messages. </param>
public ClientChannelSinkStack(IMessageSink replySink)
{
throw new NotImplementedException();
}
/// <summary>Pushes the specified sink and information that is associated with it onto the sink stack.</summary><param name="sink">The sink to push onto the sink stack. </param><param name="state">Information generated on the request side that is needed on the response side. </param><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet>
[SecurityCriticalAttribute()]
public void Push(IClientChannelSink sink, object state)
{
throw new NotImplementedException();
}
/// <summary>Pops the information that is associated with all the sinks from the sink stack up to and including the specified sink.</summary><returns>Information generated on the request side and associated with the specified sink.</returns><param name="sink">The sink to remove and return from the sink stack. </param><exception cref="T:System.Runtime.Remoting.RemotingException">The current sink stack is empty, or the specified sink was never pushed onto the current stack. </exception><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet>
[SecurityCriticalAttribute()]
public object Pop(IClientChannelSink sink)
{
throw new NotImplementedException();
}
/// <summary>Requests asynchronous processing of a method call on the sinks that are in the current sink stack.</summary><param name="headers">The headers that are retrieved from the server response stream. </param><param name="stream">The stream that is returning from the transport sink. </param><exception cref="T:System.Runtime.Remoting.RemotingException">The current sink stack is empty. </exception><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet>
[SecurityCriticalAttribute()]
public void AsyncProcessResponse(ITransportHeaders headers, Stream stream)
{
throw new NotImplementedException();
}
/// <summary>Dispatches the specified reply message on the reply sink.</summary><param name="msg">The <see cref="T:System.Runtime.Remoting.Messaging.IMessage" /> to dispatch. </param><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet>
[SecurityCriticalAttribute()]
public void DispatchReplyMessage(IMessage msg)
{
throw new NotImplementedException();
}
/// <summary>Dispatches the specified exception on the reply sink.</summary><param name="e">The exception to dispatch to the server. </param><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet>
[SecurityCriticalAttribute()]
public void DispatchException(Exception e)
{
throw new NotImplementedException();
}
}
}
| gpl-3.0 |
RainerGrimm/ModernesCppSource | source/localTime.cpp | 803 | // localTime.cpp
#include "date/tz.h"
#include <iostream>
int main() {
std::cout << std::endl;
using namespace date;
std::cout << "UTC time" << std::endl;
auto utcTime = std::chrono::system_clock::now();
std::cout << " " << utcTime << std::endl;
std::cout << " " << date::floor<std::chrono::seconds>(utcTime) << '\n':
std::cout << std::endl;
std::cout << "Local time" << std::endl;
auto localTime = date::make_zoned(date::current_zone(), utcTime);
std::cout << " " << localTime << std::endl;
std::cout << " " << date::floor<std::chrono::seconds>(localTime.get_local_time())
<< std::endl;
auto offset = localTime.get_info().offset;
std::cout << " UTC offset: " << offset << std::endl;
std::cout << std::endl;
} | gpl-3.0 |
GregoryIwanek/German_study | debug version/guesssentencesection.cpp | 2806 | #include "guesssentencesection.h"
#include <QDebug>
GuessSentenceSection::GuessSentenceSection()
{
}
void GuessSentenceSection::setSceneFromMainWindow(CustomScene *myScene)
{
//sets main scene as a secene to draw on
scene = myScene;
}
void GuessSentenceSection::setGuessSentenceSectionUI()
{
//sets UI of GSSection and basic definitions
scene->clear();
guessSentenceSectionUI = new GuessSentenceSectionUI();
guessSentenceSectionUI->setParent(this);
guessSentenceSectionUI->setSceneFromParent(scene);
guessSentenceSectionUI->buildUI();
}
void GuessSentenceSection::setGuessSentenceSectionLogic()
{
//sets Logic of GSSection and basic definitions
guessSentenceSectionLogic = new GuessSentenceSectionLogic();
guessSentenceSectionLogic->setParent(this);
guessSentenceSectionLogic->setSceneFromParent(scene);
guessSentenceSectionLogic->setSentenceAreaList(guessSentenceSectionUI->getSentenceAreaList());
}
void GuessSentenceSection::keyPressEvent(QKeyEvent *event)
{
//standard key press event, passed to Logic by emitting signal
emit keyPressed(event);
}
void GuessSentenceSection::setConnectionsForSection()
{
//sets all type of connections beetwen Logic and UI in GSSection
connect(this,SIGNAL(keyPressed(QKeyEvent*)),guessSentenceSectionLogic,SLOT(keyPressEvent(QKeyEvent*)));
connect(guessSentenceSectionUI->getMyLineEdit(),SIGNAL(returnPressed()),guessSentenceSectionUI,SLOT(sendLineEditData()));
//UI to Logic
connect(guessSentenceSectionUI,SIGNAL(signalSendLineEditData(QString)),guessSentenceSectionLogic,SLOT(checkIfSentenceIsCorrectInLineEdit(QString)));
connect(guessSentenceSectionUI->getMyButton("buttonClear"),SIGNAL(clicked()),guessSentenceSectionLogic,SLOT(clearSentence()));
connect(guessSentenceSectionUI->getMyButton("buttonCheck"),SIGNAL(clicked()),guessSentenceSectionLogic,SLOT(checkIfSentenceIsCorrect()));
connect(guessSentenceSectionUI->getMyButton("buttonStart"),SIGNAL(clicked()),guessSentenceSectionLogic,SLOT(setNewSentence()));
connect(guessSentenceSectionUI->getMyButton("buttonHint"),SIGNAL(hoverEvent()),guessSentenceSectionUI,SLOT(showHideHint()));
connect(guessSentenceSectionUI->getMyButton("buttonBack"),SIGNAL(clicked()),guessSentenceSectionUI,SLOT(back()));
//Logic to UI
connect(guessSentenceSectionLogic,SIGNAL(sentenceCreated(QString)),guessSentenceSectionUI,SLOT(updateSentenceText(QString)));
connect(guessSentenceSectionLogic,SIGNAL(pointsChanged(int)),guessSentenceSectionUI,SLOT(updatePointsText(int)));
connect(guessSentenceSectionLogic,SIGNAL(resultChanged(bool)),guessSentenceSectionUI,SLOT(updateResultText(bool)));
connect(guessSentenceSectionLogic,SIGNAL(clearUITexts(bool)),guessSentenceSectionUI,SLOT(clearUIText(bool)));
}
| gpl-3.0 |
gurko-va/p2pool-dash-poiuty | p2pool/networks.py | 1999 | from p2pool.bitcoin import networks
from p2pool.util import math
# CHAIN_LENGTH = number of shares back client keeps
# REAL_CHAIN_LENGTH = maximum number of shares back client uses to compute payout
# REAL_CHAIN_LENGTH must always be <= CHAIN_LENGTH
# REAL_CHAIN_LENGTH must be changed in sync with all other clients
# changes can be done by changing one, then the other
nets = dict(
dash=math.Object(
PARENT=networks.nets['dash'],
SHARE_PERIOD=20, # seconds
CHAIN_LENGTH=24*60*60//20, # shares
REAL_CHAIN_LENGTH=24*60*60//20, # shares
TARGET_LOOKBEHIND=100, # shares //with that the pools share diff is adjusting faster, important if huge hashing power comes to the pool
SPREAD=10, # blocks
IDENTIFIER='7242ef345e1bed6b'.decode('hex'),
PREFIX='3b3e1286f446b891'.decode('hex'),
P2P_PORT=8999,
MIN_TARGET=0,
MAX_TARGET=2**256//2**20 - 1,
PERSIST=True,
WORKER_PORT=7903,
BOOTSTRAP_ADDRS='eu.p2pool.pl p2pool.dashninja.pl dash.p2pools.us darkcoin.fr p2pool.crunchpool.com happymining.de'.split(' '),
ANNOUNCE_CHANNEL='#p2pool-drk',
VERSION_CHECK=lambda v: v >= 110011,
),
dash_testnet=math.Object(
PARENT=networks.nets['dash_testnet'],
SHARE_PERIOD=20, # seconds
CHAIN_LENGTH=24*60*60//20, # shares
REAL_CHAIN_LENGTH=24*60*60//20, # shares
TARGET_LOOKBEHIND=100, # shares //with that the pools share diff is adjusting faster, important if huge hashing power comes to the pool
SPREAD=10, # blocks
IDENTIFIER='fa417f64e92d1a3c'.decode('hex'),
PREFIX='e6fc75a2eca9f373'.decode('hex'),
P2P_PORT=18999,
MIN_TARGET=0,
MAX_TARGET=2**256//2**20 - 1,
PERSIST=False,
WORKER_PORT=18998,
BOOTSTRAP_ADDRS=''.split(' '),
ANNOUNCE_CHANNEL='',
VERSION_CHECK=lambda v: True,
),
)
for net_name, net in nets.iteritems():
net.NAME = net_name
| gpl-3.0 |
enricocid/LaunchEnr | Launcher3-O-r12/src/main/java/com/enrico/launcher3/allapps/DefaultAppSearchController.java | 910 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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.
*/
package com.enrico.launcher3.allapps;
/**
* The default search controller.
*/
public class DefaultAppSearchController extends AllAppsSearchBarController {
public DefaultAppSearchAlgorithm onInitializeSearch() {
return new DefaultAppSearchAlgorithm(mApps.getApps());
}
}
| gpl-3.0 |
gamegineer/dev | main/table/org.gamegineer.table.net.impl.tests/src/org/gamegineer/table/internal/net/impl/transport/AbstractServiceTestCase.java | 2875 | /*
* AbstractServiceTestCase.java
* Copyright 2008-2015 Gamegineer contributors and others.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Created on Apr 1, 2011 at 9:27:25 PM.
*/
package org.gamegineer.table.internal.net.impl.transport;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
/**
* A fixture for testing the basic aspects of classes that implement the
* {@link IService} interface.
*/
public abstract class AbstractServiceTestCase
{
// ======================================================================
// Fields
// ======================================================================
/** The service under test in the fixture. */
private Optional<IService> service_;
// ======================================================================
// Constructors
// ======================================================================
/**
* Initializes a new instance of the {@code AbstractServiceTestCase} class.
*/
protected AbstractServiceTestCase()
{
service_ = Optional.empty();
}
// ======================================================================
// Methods
// ======================================================================
/**
* Creates the service to be tested.
*
* @return The service to be tested.
*
* @throws java.lang.Exception
* If an error occurs.
*/
protected abstract IService createService()
throws Exception;
/**
* Gets the service under test in the fixture.
*
* @return The service under test in the fixture.
*/
protected final IService getService()
{
return service_.get();
}
/**
* Sets up the test fixture.
*
* @throws java.lang.Exception
* If an error occurs.
*/
@Before
public void setUp()
throws Exception
{
service_ = Optional.of( createService() );
}
/**
* Placeholder for future interface tests.
*/
@Test
public void testDummy()
{
// do nothing
}
}
| gpl-3.0 |
exaphaser/MK.MobileDevice | MobileDevice/iPhoneXE/OpenMode.cs | 320 | using System;
namespace MK.MobileDevice.XEDevice
{
// Token: 0x0200000A RID: 10
public enum OpenMode
{
// Token: 0x0400003E RID: 62
None,
// Token: 0x0400003F RID: 63
ReadSafe,
// Token: 0x04000040 RID: 64
Read,
// Token: 0x04000041 RID: 65
Write,
// Token: 0x04000042 RID: 66
ReadWrite = 5
}
}
| gpl-3.0 |
espressopp/espressopp | testsuite/pi_water/water.py | 8200 | #!/usr/bin/env python3
#
# Copyright (C) 2013-2017(H)
# Max Planck Institute for Polymer Research
#
# This file is part of ESPResSo++.
#
# ESPResSo++ 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.
#
# ESPResSo++ is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# -*- coding: utf-8 -*-
###########################################################################
# #
# ESPResSo++ Python script for tabulated GROMACS simulation #
# #
###########################################################################
import sys
import time
import espressopp
import mpi4py.MPI as MPI
import logging
import copy
import math
from espressopp import Real3D, Int3D
from espressopp.tools import gromacs
from espressopp.tools import decomp
from espressopp.tools import timers
import pathintegral
def genTabPotentials(tabfilesnb):
potentials = {}
for fg in tabfilesnb:
fe = fg.split(".")[0]+".tab" # name of espressopp file
gromacs.convertTable(fg, fe, sigma, epsilon, c6, c12)
pot = espressopp.interaction.Tabulated(itype=3, filename=fe, cutoff=rc)
t1, t2 = fg[6], fg[8] # type 1, type 2
potentials.update({t1+"_"+t2: pot})
print("created", t1, t2, fe)
return potentials
# This example reads in a gromacs water system (SPC/Fw) treated with reaction field. See the corresponding gromacs grompp.mdp paramter file.
# Output of gromacs energies and esp energies should be the same
# simulation parameters (nvt = False is nve)
steps = 1 #100
check = 1 #steps/10
rc = 0.9 # Verlet list cutoff
skin = 0.14
timestep = 0.0002
# parameters to convert GROMACS tabulated potential file
sigma = 1.0
epsilon = 1.0
c6 = 1.0
c12 = 1.0
# GROMACS setup files
grofile = "conf.gro"
topfile = "topol.top"
# this calls the gromacs parser for processing the top file (and included files) and the conf file
# The variables at the beginning defaults, types, etc... can be found by calling
# gromacs.read(grofile,topfile) without return values. It then prints out the variables to be unpacked
defaults, types, atomtypes, masses, charges, atomtypeparameters, bondtypes, bondtypeparams, angletypes, angletypeparams, exclusions, x, y, z, resname, resid, Lx, Ly, Lz= gromacs.read(grofile,topfile)
######################################################################
## IT SHOULD BE UNNECESSARY TO MAKE MODIFICATIONS BELOW THIS LINE ##
######################################################################
#types, bonds, angles, dihedrals, x, y, z, vx, vy, vz, Lx, Ly, Lz = gromacs.read(grofile,topfile)
num_particles = len(x)
density = num_particles / (Lx * Ly * Lz)
size = (Lx, Ly, Lz)
sys.stdout.write('Setting up simulation ...\n')
system = espressopp.System()
system.rng = espressopp.esutil.RNG()
system.bc = espressopp.bc.OrthorhombicBC(system.rng, size)
system.skin = skin
comm = MPI.COMM_WORLD
nodeGrid = decomp.nodeGrid(comm.size,size,rc,skin)
cellGrid = decomp.cellGrid(size, nodeGrid, rc, skin)
system.storage = espressopp.storage.DomainDecomposition(system, nodeGrid, cellGrid)
# setting up GROMACS interaction stuff
# create a force capped Lennard-Jones interaction that uses a verlet list
verletlist = espressopp.VerletList(system, rc)
#interaction = espressopp.interaction.VerletListLennardJonesGromacs(verletlist)
# add particles to the system and then decompose
props = ['id', 'pos', 'v', 'type', 'mass', 'q']
allParticles = []
for pid in range(num_particles):
part = [pid + 1, Real3D(x[pid], y[pid], z[pid]),
Real3D(0, 0, 0), types[pid], masses[pid], charges[pid]]
allParticles.append(part)
system.storage.addParticles(allParticles, *props)
#system.storage.decompose()
# set up LJ interaction according to the parameters read from the .top file
#ljinteraction=gromacs.setLennardJonesInteractions(system, defaults, atomtypeparameters, verletlist,rc)
########## tabulated nb interactions ############
tabfilesnb = ["table_O_O.xvg", "table_H_O.xvg", "table_H_H.xvg"]
potentials = genTabPotentials(tabfilesnb)
tabulatedinteraction = espressopp.interaction.VerletListTabulated(verletlist)
tabulatedinteraction.setPotential(0, 0, potentials["O_O"])
tabulatedinteraction.setPotential(0, 1, potentials["H_O"])
tabulatedinteraction.setPotential(1, 1, potentials["H_H"])
system.addInteraction(tabulatedinteraction)
# set up angle interactions according to the parameters read from the .top file
angleinteractions=gromacs.setAngleInteractions(system, angletypes, angletypeparams)
# set up bonded interactions according to the parameters read from the .top file
bondedinteractions=gromacs.setBondedInteractions(system, bondtypes, bondtypeparams)
# exlusions, i.e. pairs of atoms not considered for the non-bonded part. Those are defined either by bonds which automatically generate an exclusion. Or by the nregxcl variable
verletlist.exclude(exclusions)
# langevin thermostat
langevin = espressopp.integrator.LangevinThermostat(system)
langevin.gamma = 10
langevin.temperature = 2.4942 # kT in gromacs units
integrator = espressopp.integrator.VelocityVerlet(system)
integrator.addExtension(langevin)
integrator.dt = timestep
print("POT", potentials)
pathintegral.createPathintegralSystem(allParticles, props, types, system, langevin, potentials, P=16)
system.storage.decompose()
num_particles = int(espressopp.analysis.NPart(system).compute())
# print simulation parameters
print('')
print('number of particles =', num_particles)
print('density = %.4f' % (density))
print('rc =', rc)
print('dt =', integrator.dt)
print('skin =', system.skin)
print('steps =', steps)
print('NodeGrid = %s' % (nodeGrid,))
print('CellGrid = %s' % (cellGrid,))
print('')
# analysis
configurations = espressopp.analysis.Configurations(system)
configurations.gather()
temperature = espressopp.analysis.Temperature(system)
pressure = espressopp.analysis.Pressure(system)
pressureTensor = espressopp.analysis.PressureTensor(system)
print("i*timestep,Eb, EAng, ETab, Ek, Etotal T")
fmt='%5.5f %15.8g %15.8g %15.8g %15.8g %15.8f %15.8f\n'
outfile = open("esp.dat", "w")
start_time = time.process_time()
espressopp.tools.psfwrite("system.psf", system)
#espressopp.tools.decomp.tuneSkin(system, integrator)
#espressopp.tools.analyse.info(system, integrator)
espressopp.tools.fastwritexyz("traj.xyz", system, append=False, scale=10)
for i in range(check):
T = temperature.compute()
P = pressure.compute()
Eb = 0
EAng = 0
ETab=0
#for bd in bondedinteractions.values(): Eb+=bd.computeEnergy()
#for ang in angleinteractions.values(): EAng+=ang.computeEnergy()
#ELj= ljinteraction.computeEnergy()
#EQQ= qq_interactions.computeEnergy()
ETab= tabulatedinteraction.computeEnergy()
T = temperature.compute()
Ek = 0.5 * T * (3 * num_particles)
Etotal = Ek+Eb+EAng+ETab
sys.stdout.write(fmt%(i*timestep,Eb, EAng, ETab, Ek, Etotal, T))
outfile.write(fmt%(i*timestep,Eb, EAng, ETab, Ek, Etotal, T))
#espressopp.tools.pdb.pdbfastwrite("traj.pdb", system, append=True)
espressopp.tools.fastwritexyz("traj.xyz", system, append=True, scale=10)
integrator.run(int(steps/check)) # print out every steps/check steps
#espressopp.tools.vmd.imd_positions(system, sock)
# print timings and neighbor list information
end_time = time.process_time()
timers.show(integrator.getTimers(), precision=2)
espressopp.tools.analyse.final_info(system, integrator, verletlist, start_time, end_time)
sys.stdout.write('Integration steps = %d\n' % integrator.step)
sys.stdout.write('CPU time = %.1f\n' % (end_time - start_time))
| gpl-3.0 |
Coheed/Shiny-Portfolio | system/modules/favorites/languages/en/tl_user_fav.php | 3036 | <?php if (!defined('TL_ROOT')) die('You cannot access this file directly!');
/**
* Contao Open Source CMS
* Copyright (C) 2005-2012 Leo Feyer
*
* Formerly known as TYPOlight Open Source CMS.
*
* 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 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
* 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, please visit the Free
* Software Foundation website at <http://www.gnu.org/licenses/>.
*
* PHP version 5
* @copyright Thyon Design 2012
* @author John Brand <http://www.thyon.com>
* @package Language
* @license LGPL
* @filesource
*/
/**
* Miscellaneous
*/
$GLOBALS['TL_LANG']['tl_user_fav']['label'] = array('Label', 'Enter the display label of the favorite.');
$GLOBALS['TL_LANG']['tl_user_fav']['href'] = array('Redirect target', 'Enter the redirect link of the favorite.');
$GLOBALS['TL_LANG']['tl_user_fav']['target'] = array('Open in new window', 'Opens link in a new window.');
$GLOBALS['TL_LANG']['tl_user_fav']['title'] = array('Help text', 'Enter the help description or title pop-up text.');
$GLOBALS['TL_LANG']['tl_user_fav']['icon'] = array('Favorite icon', 'Please select an image to override the default icon.');
$GLOBALS['TL_LANG']['tl_user_fav']['cssClass'] = array('CSS class', 'Here you can enter one or more classes.');
$GLOBALS['TL_LANG']['tl_user_fav']['published'] = array('Publish item', 'Make the favorite item visible.');
/**
* Legends
*/
$GLOBALS['TL_LANG']['tl_user_fav']['title_legend'] = 'Title, redirect and icon';
$GLOBALS['TL_LANG']['tl_user_fav']['expert_legend'] = 'Expert settings';
$GLOBALS['TL_LANG']['tl_user_fav']['publish_legend'] = 'Publish settings';
/**
* Buttons
*/
$GLOBALS['TL_LANG']['tl_user_fav']['new'] = array('Add favorite', 'Add a new favorite');
$GLOBALS['TL_LANG']['tl_user_fav']['show'] = array('Favorite details', 'Show the details of favorite ID %s');
$GLOBALS['TL_LANG']['tl_user_fav']['edit'] = array('Edit favorite', 'Edit favorite ID %s');
$GLOBALS['TL_LANG']['tl_user_fav']['copy'] = array('Duplicate favorite', 'Duplicate favorite ID %s');
$GLOBALS['TL_LANG']['tl_user_fav']['cut'] = array('Move favorite', 'Move favorite ID %s');
$GLOBALS['TL_LANG']['tl_user_fav']['delete'] = array('Delete favorite', 'Delete favorite ID %s');
$GLOBALS['TL_LANG']['tl_user_fav']['editheader'] = array('Edit user profile', 'Edit the user profile');
$GLOBALS['TL_LANG']['tl_user_fav']['toggle'] = array('Publish/unpublish favorite', 'Publish/unpublish favorite ID %s');
?> | gpl-3.0 |